Binary: trs |
Language: Rust | Status: Active development |
@dpeluche/trs)cd X && git Y chains, done in v0.5.5| [ ] Homebrew tap (low priority, npm + curl | sh covers 99% of users) |
trs self-update command, re-download latest binary from GitHub Releases
Done: Shipped as trs upgrade (v0.5.8).parse/aws.rs).mvn, ./mvnw): real fixtures from Maven 3.9, a multi-module reactor and Spring Boot testsgradle, ./gradlew): failed-test messages read from the JUnit XML reportgh run view: done (v0.5.13): extracts title, conclusion, job counts, annotations, URLgh issue view: shares the gh pr view parser (labeled Issue), drops the empty header fields, and reads --comments (PR or issue) as one @author (role, state) line plus body per comment. 5% to 27% fewer bytes on real views; the body is the rest.Check the Cursor output-saver plugin inside a running Cursor (installed by trs output-saver): after Developer: Reload Window, Customize → Rules should list trs-output-saver as Always, and an agent asked to name its rules should mention trs. Built from Cursor’s docs and a staff reply, not yet seen live
trs git status --json after an external command printed compact text on short outputs: the size guard and the never-worse guard now step aside for an explicit –json/–csv/–tsv/–agent[-] Add a flag-ownership entry in child_owns_format_flag (classifier_args.rs) whenever a parser-backed tool turns out to define --json/--raw/--stats/--csv itself
Not doing: A standing rule, not a task: keep it in mind when adding a parser.
execute_and_parse: /usr/bin/git push, git -C dir push and /bin/sh -c now take the same paths as the bare formstrs <cmd> | head panicked with “Broken pipe” and exited 101; it now exits 141 silently like any tool whose reader left
git diff full (not just –stat), reformat unified diff headers
Done: Hunk parser shipped (#224, #231, #295).find with long paths: audit shows ~48% reduction where the first path arg eats the display width. Parser could basename-collapse logged paths the way stats --history now does.
Done: Grouped by directory with basenames (#132).cargo fmt --check diff output: only 32% compression on failures. The unified diff block has a lot of repeat whitespace we could collapse.
Done: Diff blocks folded to “N files (k diffs)” (#78).xcodebuild: the 13.9% came from April-July runs, when trs logged exactly half the bytes of every build. Since 2026-09, 22 of the 26 real runs in the history cut 90% or more (the rest are -version and other tiny runs), and a real IdeaBooks simulator build on 2026-11-22 went from 159,642 bytes to 55 (build: ok, ** BUILD SUCCEEDED **), with no error or warning dropped. The one warning: line in it is appintentsmetadataprocessor’s “Metadata extraction skipped”, which Xcode does not count either. No code change.uv run: no gap, checked 2026-11-28. uv run pytest already saves
87-99%, uv run ruff is routed to the lint parser and its real runs are tiny,
and uv run python -c (7% of uv run calls) prints arbitrary script output,
so it stays passthrough.awk / sed, 0-3% compression. Decision: these print arbitrary user data; compressing would risk corrupting what the agent asked for. Leave as passthrough; TRS_SKIP=1 is the escape hatch.
Not doing: Decision recorded: passthrough.tsc in v0.5.10timeout and bash -c (fixed in #308: stderr_owner unwraps the same wrappers as classify_command; follow-up: strip_wrappers in rewrite_permissions does not unwrap timeout on Windows, so the two still differ there): timeout 300 cargo build does not merge stderr; stderr_owner covers runners only.grep on one file with key:value lines: only on trs parse grep fed from a pipe (grep v kv.txt | trs parse grep reports total: 3 files). trs grep knows the file from argv and prints it right (re-checked 2026-11-28).--json on unread test output: test runners keep the empty parsed shape on purpose; decide whether that contract changes.Source: the 11 repos tagged trs in spark (spark tag list trs, all pulled 2026-11-03), the
TokenEconomizer paper (arXiv 2610.22732) and one gist on Claude Code background cost. Every figure
from those projects is their own claim, unverified. Items marked “verified” were reproduced here.
Do not name those projects in commits, docs or the changelog when shipping these (say “a similar tool”).
ls -la /usr | wc -l gives 12, trs ls -la /usr | wc -l gives 10. The OpenCode, Kilo, Hermes and the other plugin templates in src/init_templates_plugins.rs (lines 23, 39, 59, 83, 114, 149) prepend trs to every command and skip only trs , cd and TRS_AGENT=. The Claude path honours the #162 invariant (pipes, redirects and captures are never rewritten, rewrite_decide.rs); the plugins do not. Preferred fix: the plugin asks trs rewrite for the decision so the rule lives in one place; test: every template against trs rewrite on a list of pipes, redirects, $(...), backticks and && chains. Fixed: every script plugin now asks trs rewrite; tests/cli_plugin_templates.rs, trs doctor flags old copies.permissionDecision: "allow" (verified emitted for rm -rf, git push origin main, git branch -D, kubectl delete pod; src/rewrite.rs:233, also Gemini decision and Cursor permission). Two similar tools fixed the same thing as a security bug: auto-approve only when the user already has an explicit allow rule, otherwise rewrite and leave the prompt to the agent. FIRST verify in real Claude Code how a hook allow orders against ask/deny rules and whether updatedInput works without a decision. Codex needs allow (src/codex.rs), keep it there. Medium risk: a prompt may appear where the user had none. Fixed for Claude Code (src/rewrite_permissions.rs): checked on a real Claude Code that rules match the REWRITTEN command and a hook allow overrides deny/ask. Per-agent gates done for Codex, Droid, Gemini, Devin, Cursor, OpenCode 2.x, Kilo/1.x, Pi (see agent-integrations.md “Permissions per agent”); Copilot no longer gets an allow. Unverified: Droid live run (auth), Cursor (no binary), VS Code Copilot terminal auto-approve, Codex managed requirements.toml, Gemini system/admin policies, Devin org rules and dangerous mode, OpenCode 1.x config shape. Optional (P3): drive Antigravity agy 1.4.12’s own hooks.json (decision/overwrite) instead of the rules file.git rewrite when cwd is under <repo>/.claude/worktrees/* (confirmed with trs rewrite): Claude’s worktree guard rejects trs git ... as “cannot be shown not to be git”. Two similar tools shipped the same fix. Land in rewrite_decide.rs. Fixed in rewrite.rs (git_in_claude_worktree).-h / --help passthrough audit: a similar tool returned its own usage at exit 0 for grep -h and the agent read it as matches. No tests for trs grep -h, trs ls -h, trs tree -h. Land in classifier_args.rs. Fixed: classifier_args::is_help_request gates the classifier and the hook; -h stays an option for ls, grep, du, df, free, sort, tree.# comment are rewritten (echo a # x && git status becomes ... trs git status). Harmless at run time, but rewrite and deny matching should ignore commented-out text. Fixed in rewrite_decide.rs (comment_start).src/passthrough_cut.rs).src/anchor_guard.rs, points at the saved raw output instead of falling back): when a cut is 90% or more and fewer than 70% of the anchors survive (paths, file:line, hashes, error lines; extraction exists in docs/development/benchmarks/truth.py), fall back to the original or add the tee path. Targets the git show --stat row (91% cut, 67% anchors). Gate by size to limit latency.trs stats (failed and oversized runs are left out, ok field in the history; recall: ptr field plus a line counting shell reads of tee/*.log, src/pointer_recall.rs; reads through an agent’s own file tool are not visible): leave rows above ~30,000 chars out of the headline (the agent never saw the rest of them), leave failed runs out of the percentages (the known “100% saved” defect), and add a recall rate (a later read of a [trs] full output: path). Also check that stats, --by-agent, the reports and the site claims share one computation.AGENTS.md / CLAUDE.md block injection: a similar tool lost a 16 KB file to two concurrent init runs. trs has no lock or temp-file rename in the init path (init_install*.rs). Refuse to write if text outside the block would be lost.tests/cli_compression_ratchet.rs; the HashMap in find fixed): determinism sweep (every parser fixture twice, identical bytes; check HashMap use in types/fs.rs), compression ratchet (per-fixture ratio and handler in a JSON baseline, fail on a drop over 2 points or a routing change, tests/cli_compression_ratchet.rs), and must_preserve literals on the failure fixtures.router/handlers/common.rs) may overstate percentages by ~25% against a calibrated divisor. Measure the divisor or label the figures “est.”.docs/support/other-token-savers.md describes one tool as “Node-based compressor, global npm package”, which is wrong.trs rewrite [--caller x], no shell syntax; tests/cli_hook_windows_shells.rs runs codex, droid, vscode and devin-cli commands under cmd.exe and PowerShell on windows-latest, passing): check the Codex/Copilot hook commands run under PowerShell as well as cmd.exe (a similar tool had “hook exited with code 1” there).AgentPolicy table (rewrite_gate.rs: label, TRS_AGENT source, gate) instead of editing the label, gate and TRS_AGENT lookups per agent; the response shape stays per envelope (HookEvent), not per agent. A hook without --caller on Claude’s envelope is identified by its tool_name (row .tool(..): Bash, Execute, exec): an old Droid/Devin hook gets its own label and gate, an unknown tool is rewritten but never approved.trs rewrite --json returns rewrite and segments in one spawn (2.x spawned twice); async spawn instead of spawnSync (hooks there are already async); the config read is cached 2 s per plugin instance. Pi and OpenClaw stay on sync spawnSync (their hook signatures are not verified async).cfg!(test) branches in the gates are one rewrite_rules::reads_host_config(). Injecting roots everywhere would make the in-crate hook tests read the developer’s own config, so the integration tests (real binary, temp HOME) are the injection point.trs doctor checks the OpenClaw and Hermes plugins (stale copy, and installed but not enabled in openclaw.json / config.yaml); messages name the plugin.--settings flag overlay is invisible to the hook (the env overlay is read now).ask Shell rules had no effect on 2026.10.22; project .cursor/cli.json is read but not verified live; Shell(cmd args) is an exact match in Cursor, the gate over-matches by prefix (fails safe).isKnownSafeCommand (gemini-cli 0.63 bundle): cat cd cut echo expr false grep head id ls nl paste pwd rev seq stat tail tr true uname uniq wc which whoami numfmt tac, sed -n, and git status|log|diff|show|branch (read-only forms, no -c), all inside the workspace. Not verified that this set drives the approval prompt (headless run failed on OAuth), so read_only is unchanged: a broader trs list only loses a compression, git branch is the one case where trs rewrites something Gemini would not have asked about.docs/features/output-saver.md has no control arm (A/B run 2026-11-04 on sonnet, N=5 x 8 prompts: block -237 tokens vs no instruction, -20 vs “Answer concisely.” with a CI spanning zero; doc rewritten from the data. Marker counts were ~0 in every arm, so the preamble/em-dash rules had nothing to remove on this model). Three projects that measured reply-style rules found small or zero gains over a plain “be concise” instruction on current models, and output is a small share of the bill. Build an offline A/B (no block, “Answer concisely.”, the trs block; N>=5; isolated claude -p with the block copied into the project file because --setting-sources project hides the global one; count markers such as preamble, closing filler, em dash) plus fidelity cases (negations, numbers, destructive-action wording). Then rewrite the claim from the data and add the caveat that per-request billing sees no benefit.~/.claude/trs.md 3,392 bytes ~850, bytes/4 estimates); doc fixed with the cache economics, size pinned by a test.truth.py (offline half done: a buried-needle probe scores the anchors found only in the middle half of the raw output, flag BLIND; the model-in-the-loop half goes with the A/B): bury an answer in the compressed output and ask for it, so a saving that blinds the model is discarded.src/rerun_rate.rs, shown by trs stats) (from the TokenEconomizer paper, which found fixed output compression raised cost in 12 of 30 cells): in history.jsonl, how often the same command is rerun right after a compressed output. Also repeated failing commands per repo, for stats or doctor. Local data only, no new hook.src/passthrough_cut.rs: unique UUID, hash or URL lines are kept after the error lines, same budget): keep lines with a rare token (UUID, hash, URL, id) when it cuts, so the agent does not rerun a narrower query. Cap it so id-dense logs still compress.audit-docs (src/audit_docs_volatile.rs: only stamps that get rewritten, not every date): flag dates, “Updated:” and “As of YYYY-MM” in CLAUDE.md / AGENTS.md, they break the prompt-cache prefix (src/audit_docs_detect.rs).docs/development/output-cost-findings.md; a line joins the block only with a test it passes).docs/development/benchmarks/transcript_output.py; on this machine the transcripts start after the install, so it has no before data): output tokens per reply before vs after install, with a confidence interval, labelled “estimated” (docs/features/output-saver.md admits stats cannot measure the output side)..trs/filters/*.toml with only skip, keep, on_empty, max_lines, strip_ansi and inline fixture tests, loaded only from trust-approved project dirs and never from the repo-level config for anything that changes behaviour. The generic tier saves only 2-16% today. Large. Local history is against it: without the aws and strings outliers, the largest low-saving families are curl (2.4% of all output, one-off payloads) and git and grep, which a project filter would not help, across 218 families. These outputs vary too much for fixed rules to cover more than a small share. Reopen when a real internal tool needs one.[hooks] pipe_status, src/rewrite_pipe_status.rs, opt-in): pipefail for the last statement only, for build and test tools piped into tail or grep; output stays byte-exact. 14.6% of 99,937 agent Bash calls pipe a check, 42 of them guarded the status, and about 3.5% of all calls qualify. | head (20% of piped checks) stays out: SIGPIPE would report a false failure.pre_tool in hooks.toml) and Trae (PreToolUse RunCommand, omit the decision): done with defer gates and tested on payload shapes; unverified on real binaries.$GROK_HOME/AGENTS.md), Kiro (~/.kiro/steering/trs.md, inclusion: always) and OpenClaw (~/.openclaw/workspace/SOUL.md): written and tested on files; Grok loading is confirmed on 1.0.70, Kiro and OpenClaw stay unverified. No Grok hook: it would bypass deny rules (docs/development/agent-integrations.md).test result lines whose counts differ on purpose. It would also fold data rows that differ only in numbers. Reopen only with data showing large repeated logs.trs read aggressive mode: not building it. trs read ran 2 times in 88,918 runs, and the rewrite never reaches it.PostToolUse output compression (agents’ own Read/Grep/Web tools) where the agent allows output replacement (about 8 of 20 agents in a similar tool’s matrix). Different product direction; keep as a note.
docs/development/output-cost-findings.md).Source: two approaches outside per-command compression (context rendered as
images, token-oriented formats), read 2026-11-21; what each claims and what trs
takes is in
benchmarks/README.md.
Order: measure first, then build only what the numbers support.
count_tokens endpoint (needs an API key and network,
so never in the runtime; trs stays offline). Compare compact, --json, --tsv
and the grouped-path variant per command. Today the benchmarks count with
o200k_base and trs stats with bytes/4; neither bills a Claude session.
Joins the bytes/4 items in Phase 2.9 P2 and 2.10.trs stats instead of
one bytes/4. Fall back to 4 when a class has too few samples or the fit is
out of range (a wrong ratio inflates the claim; a missing one changes nothing).trs grep / trs search print the full path on every
match (src/router/handlers/common.rs:445:12:...); also git status,
git diff --stat and compiler errors. A heading per file, as rg --heading
prints it, loses nothing. trs find already groups per directory. No aliases
or chained relative paths: the agent must rebuild the exact path to call Read.
Measure the saving per command first.trs json and trs read
of .json files (both read to understand a file, not by scripts). Nested data
stays minified JSON, where a table loses. Never in --json..000 milliseconds. Never
round a value or turn a timestamp into “2h ago”: that changes a fact.Not doing:
claude-opus-5-5, claude-sonnet-5-5) misread exact IDs, and they do
it with confidence.--json: scripts read it, and YAML costs more
tokens than minified JSON.Source: the public issue trackers of similar tools and adjacent projects (open and recently closed issues). Every claim below was verified against trs source before filing.
git status footer contains() drops real files. Fixed: file
entries parse before the prose/footer skip, so a file named like a footer
survives in both porcelain and long formats. Regression tests in
test_parser_git_status.rs.git diff strips \r: fixed by flagging raw \r in the input
with a (note: carriage returns in diff; …) line on text formats.reruns field
on TestSummary, parsed from the N rerun summary token and surfaced in
compact/agent/JSON output. jest/vitest verified 2026-11-21 with real runs
(jest@30 retryTimes, vitest@3 retry): neither emits any retry signal in
default/verbose/json output, so there is nothing to preserve at parse level;
the bugs seen in a similar tool were playwright/nextest, which DO print
retry markers. The playwright parser (Phase 2) and a future nextest parser
must keep retried≠passed.~/.local/bin, ~/.cargo/bin,
~/.trs/bin, /opt/homebrew/bin, /usr/local/bin when bare trs is not
on PATH, once per plugin load, and pass the binary they found as TRS_BIN
so the rewritten command calls it too (a bare trs in the rewrite would
fail in that same shell). JSON shell-command hooks embed the absolute
current_exe path at trs init time when it is a known install channel
(upgrade::detect_install_method, plus /usr/local/bin and linuxbrew);
dev target/ builds and unusual locations keep bare trs.ls -F/-p/-i/-s fixtures. Verified against real macOS
output. -F/-p classify markers are now authoritative (an extensionless
file with no marker is a file, @→symlink, *→file); plain ls keeps the
extensionless→dir heuristic since short output cannot distinguish. -i/-s
keep their numeric columns glued to names (lossless) with the same
heuristic typing; documented limitation.nix develop -c rm,
timeout 5 rm): reports in similar tools confirm the class is active.
strip_wrappers now unwraps timeout [opts] DURATION cmd (GNU semantics,
skipped on Windows where timeout is a different builtin) and
the runners nix develop|shell -c, mise exec -- and direnv exec DIR,
with the classifier’s own argv grammar (classifier_args), including one
layer of outer quotes. Still open: env, nice, bash -c/sh -c, xargs, find -exec hide
the inner program the same way.pre_tool_call ignores
in-place args mutation. Verify trs’s mutation surface live before
claiming support (integration already pending validation).conflicts_with, untrusted-tap formula).
Not doing: Duplicate of the Phase 1 Homebrew item.rg -l/grep -l/--files-with-matches → has_unread → raw passthrough.
The path list is the payload for the next command; compressing it breaks
the next step. Leave raw.git merge-base/rev-parse/describe: tiny outputs, generic fallback.no tests found with is_empty; pin
one fixture for exit-code preservation.-- bug in a rewrite hook: N/A, the command arrives on stdin.transcript_output.py
already measures output tokens for the output-saver; extend the same
harness to rewrite on/off before widening savings claims.trs ingest signals from repo-packing toolsignore crate (same engine as ripgrep) with .gitignore, .ignore,
global gitignore and .git/info/exclude all enabled, so the ignore-file
bug classes reported for those tools do not apply. Two real gaps found and fixed
instead: get_changed_files now passes -c core.quotepath=false (non-ASCII
paths came back C-quoted and never matched rel_path, silently dropping
them from ingest --changed), and config.exclude is still a substring
match (documented limitation, revisit only with a real case).unread list (“incomplete: N paths could not be read”). UTF-16 and other
NUL-bearing encodings still classify as binary; transcoding them needs an
encoding dependency, deferred.Found 2026-10-21 while auditing trs stats --by-agent: Exegol’s digest.ts calls
trs digest, which does not exist (it ran the system digest and failed), and its
tests wrote 3,276 runs into the real ~/.trs history in a month.
trs ingest --print --budget 32k <path> instead of trs digest; run its tests with a temp TRS_HOME. (Text sent to its dev.)
Done: Done on the trs side: trs ingest --print --budget 32k prints the digest. The rest is Exegol work.trs stats --by-agent --json --days N (#305; --by-command --json fixed too, each prints its own rows), and a trs doctor / trs init --all --global action.
Done: Fixed the trs side in #305: trs stats --by-agent --json now carries a by_agent array. The doctor/init action is Exegol work.docs/index.html, README.md, README.es.md) once the two items above ship; drop its last sentence if the savings view is not out yet.trs stats: a failed command with empty output counts as 100% saved; leave failed runs out of the percentages.
Done: Done in #209: counts_toward_totals leaves failed runs out (same as the Phase 2.9 P1 item). --history still shows the raw saved_pct.~/.trs history) through trs rewrite: list what the lock rejects and wrapped programs that are not on PATH (functions, aliases). added: 2026-11-30trs run X (diff, tail) to get their compression back; the lock must accept that one form. added: 2026-11-30added: 2026-11-30env, nice, xargs as exec wrappers so nice cargo build is wrapped again. added: 2026-11-30Context: v0.5.6 fixed all 9 supported agents end-to-end.
See docs/development/agent-integrations.md for the per-agent reference.
router/handlers/common.rs: shipped in v0.5.10. Extracted ANSI/emoji/control-char utilities to router/handlers/ansi.rs (168 LOC). common.rs down to 466 LOC.src/rewrite.rs). Current linear scan of ~20 starts_with checks. A first-char dispatch table would shave more than the has_shell_op byte-scan did on the non-operator path. Hot path, measurable.router/handlers/parse/extra_download.rs (463 LOC). Mixes two concepts: HTTP protocol tracer (curl -v / curl -I) and body-content compressor. Not a hard violation yet, but a clean split would be extra_download.rs (protocol) + http_body.rs (body / JSON / base64). Revisit if file crosses 500 LOC..zshenv check in install.sh. If ~/.local/bin is in the user’s interactive PATH but NOT in ~/.zshenv, IDE subshells will still fail. JSON hook commands now embed the absolute trs path at init time (Phase 2.10), which covers the hook path; this item remains for manual trs use and plugin agents.
Done: Shipped (#50, #64): zshenv_has_path in docs/install.sh.HookEvent::Unknown variant. Today unknown hook_event_name values default to Claude format. Silent misroute if a 4th client ships its own envelope.
Done: Shipped (#77): an unknown event fails open.cd, export, heredocs), so wrapping would break cwd/env persistence. On what could be wrapped, the transforms safe for any output shape save 3.4% (scripts) and 1.7% (pipelines): about 0.5% of all bytes. Agents already filter their own pipes (| tail, | grep). Revisit only if a measured case shows cmd | tail -N cutting failures that a trs parser would have kept.Research: plain-text hook protocols. Some clients may pipe the command directly (no JSON envelope). run_rewrite handles this via fallback, but no real client uses it yet.
trs ... for the user to type (doctor_checks.rs has 9, upgrade.rs 8, init_show.rs 4). #158 shipped a trs report that answered “Command not found”, so a printed command is a promise that can be broken silently. v0.8.2 pins 2 of the 37, and only the subcommand path: the suggestions elsewhere carry flags (--all --global --force, --budget, --coverage --json) that the walk would not catch. doctor::Check::hint already funnels 9 of them through one field, which is the seam a shared resolver should use. Sized as its own cycle because fixing whatever it finds is the real work.No end-to-end test for the install tails. trs init <tool> shipped without the hint in v0.8.2 and only a manual run caught it; the paths are --all, single-tool, --dry-run, unknown-tool, and upgrade-child. Pinning them means a test that installs into a temp $HOME, and no test in the repo overrides $HOME today. windows-latest is a blocking job, so this needs to be written cross-platform on purpose rather than bolted on.
git log bodies? trs keeps every commit body whole: 17-22% cut with 100% of anchors kept. Similar tools cut 77-98% by keeping each body’s first lines plus [+N lines omitted], and they keep 12-47% of anchors. Measured on this repo, where commit bodies are unusually long. The tradeoff is a product call, not a bug.
Done: Decided and shipped (#167): condense_body keeps the opening lines plus [+N lines: git show <hash>].unwrap(), 13.9K tokens) got worse, because trs already does something extra there. Look into why before changing it.
Done: Shipped (#167). Re-measured 2026-11-28: dropping the matches: header (it repeats the total: line) saves about 1% and breaks 12 tests that pin it; not worth it. Grouping by directory is the Phase 2.11 “Repeated paths” item.git diff drops context lines. Measured, not changed: keeping 1 context line per change costs 7.6 points of savings (23.7% to 16.1%) and raises anchors kept by 1.3 points (58.7% to 60.0%); the anchors lost are mostly the index abc..def hashes and the duplicated diff --git a/ b/ paths that the file summary replaces on purpose. See docs/development/benchmarks/README.md.docker ps drops container IDs. Measured, not changed: a 12-character ID costs 6-8 tokens per row (79 to 95 tokens for two containers, +20%), container names are unique and work in every docker command, and --json keeps the ID. Revisit if an agent is seen needing to match an ID from another output.
Evaluate: fold near-identical lines beyond timestamps (spacing, symbols, accents, numbers). Measured 2026-09-25 on 49,532 real Bash results (46 MB), consecutive lines equal after each normalization: exact 177 KB (done), + whitespace +30 KB, + symbols +4 KB, + accents/case +1 KB, + digits +647 KB, timestamps only +30 KB (done: (xN, until <time>)). Not done because the matches were mostly code, where they destroy content: whitespace joins ` } with } (indentation), digits join 152- } with 153-}` (line numbers). Revisit only if the fold can tell code from logs (e.g. only lines with a log level or timestamp prefix), and fold digits only inside known volatile fields (durations, PIDs, request ids) with first and last value kept.
~/.copilot/hooks/*.json, sends the VS Code-compatible PreToolUse payload and honors updatedInput. Attributed as copilot-cli via COPILOT_CLI=1. Found through a user who saw no savings: the doctor reported the hook as configured while it had never fired, so trs doctor now names the configured agents and warns when no run has come through a hook.PreToolUse + hookSpecificOutput.updatedInput +
permissionDecision, exactly what trs rewrite already emits. Paths:
user ~/.copilot/hooks/*.json, workspace .github/hooks/*.json; VS Code
ALSO reads ~/.claude/settings.json + project .claude/settings.json, so
users with trs init claude --global get de-facto coverage today
(attributed as claude). Matchers are parsed but IGNORED (hook fires on
every tool), safe: trs no-ops without tool_input.command (pinned by
test_hook_response_missing_command_returns_none). Tool input is
camelCase but the shell field is command (unaffected).
TO SHIP trs init vscode: AiTool variant + VSCODE_HOOKS template with
TRS_AGENT=vscode trs rewrite (own attribution), detection (code binary /
~/.vscode / Copilot ext dir), uninstall paths, docs row.
BLOCKER before shipping: validate interactively in VS Code (like Codex
0.134) that run_in_terminal rewrites apply and updatedInput doesn’t
drop sibling fields (isBackground/explanation, merge vs replace is
undocumented).
SHIPPED: validated live 2026-06-09 (updatedInput applies cleanly to
run_in_terminal); trs init vscode + TRS_AGENT=vscode attribution landed.config.ts, slashCommands, contextProviders). Worth a focused research pass like we did for Kilo/OpenCode/Droid.trs init vscode-copilot / trs init continue entries or a single trs init vscode.
Done: Decided: one trs init vscode, with vscode-copilot as an alias (src/ai_tool.rs).trs init
openclaw, plugin at ~/.openclaw/plugins/trs/ + config enable in
~/.openclaw/openclaw.json). Plugin SDK (TypeScript):
before_tool_call hook rewrites tool params (prepend trs to the exec
command, idempotency guard like OpenCode), and resolve_exec_env injects
TRS_AGENT=openclaw into the exec environment, the cleanest cross-platform
attribution surface in the catalog. Entry file via
definePluginEntry({ id, register(api) { api.on(...) } }). TO RESOLVE at
implementation: exact install path (workspace vs managed plugin dirs;
install also supported via npm/local dir) and whether config registration
in plugins.entries.<id> is needed. Validate live before shipping
(install OpenClaw, confirm rewrite + attribution).trs init hermes, plugin at
~/.hermes/plugins/trs-rewrite/ + plugins.enabled patch in
~/.hermes/config.yaml, HERMES_HOME honored). Python
plugin at ~/.hermes/plugins/<name>/ (__init__.py + plugin.yaml
manifest listing pre_tool_call), registered via register(ctx) →
ctx.register_hook("pre_tool_call", fn); mutate args when
tool_name == "terminal", fail open otherwise. May require a config.yaml
merge (a similar tool’s Hermes integration does; reference cloned under
_repos_2_learn).
Validate live before shipping.trs init devin-cli, hook merged under the hooks
key of ~/.config/devin/config.json global / .devin/config.json project,
matcher exec, command trs rewrite --caller devin-cli; preserves existing
config; aliases devin-terminal / dcli). Distinct product from Devin
Desktop (rules-only). updatedInput live-validation pending: docs confirm
decision/permissionDecision+additionalContext but not
hookSpecificOutput.updatedInput; shipped optimistically (2026-07 research),
harmless no-op if ignored. Dedicated install needed because Devin’s
.claude/settings.json fallback uses matcher Bash, which never matches
Devin’s exec tool.t3code (pingdotgg): evaluated; not applicable for a trs init entry. t3code is a web-GUI wrapper that orchestrates other agent CLIs (Codex, Claude, Cursor, OpenCode), not an agent itself. It doesn’t run shell or expose its own hook surface. trs attaches transitively at the backend-agent layer (all four already supported), so trs init <backend> covers it. Attribution shows the backend agent, not “t3code”. Open validation: confirm the hook fires through t3code’s Codex app-server (JSON-RPC stdio) path, as we validated interactive Codex.
Claude Code agent_summary background cost (gist, 2026-11-03): evaluated, not for trs. Claims (author’s own, from OpenTelemetry, unverified) that Claude Code sends each background agent’s transcript to a model every ~30 s for a 3-5 word status, about 16% of spend. Not shell output, so trs cannot reduce it, and the fix patches the client runtime (a Bun --preload that disables timers), which may conflict with the service terms and breaks silently on updates. Takeaway for the docs only: part of an agent’s bill sits outside what trs touches, so keep the savings claims scoped to shell output. The video that pointed to it was not analysed.
Context-compression layer (Python+Rust): compresses tool outputs / logs / files / RAG before the LLM, 60-95% fewer tokens. Broader scope than trs (we do terminal-command output via hooks; they do all content via library/proxy/MCP). Ideas worth a look, not adoption:
TRS_AGENT= prefix: a similar tool stabilizes prefixes for provider KV-cache hits. Verify our attribution prefix doesn’t bust prefix-caching; if it does, move attribution off the command prefix.experimental.chat.system.transform): plugin hook that mutates the assembled system prompt. experimental. prefix means API churn risk; useful for dynamic injection in a future feature.SessionStart / UserPromptSubmit): per-session and per-turn context injection points.Devin, dual target .devin/rules/trs.md (frontmatter trigger: always_on) + legacy .windsurfrules, aliases devin/devin-desktop/windsurf/cascade.preToolUse + updated_input). beforeShellExecution is allow/deny only, so no migration. No change needed.run tool that returns compacted output. OPEN QUESTION (do not build until answered): is it actually valuable, given the user must register the MCP server + grant directory access in the desktop app? Weigh friction vs token savings before any implementation. Framework reference: ECC’s capability-surface-selection guide: “Avoid MCP when the job is a one-shot local command” (trs is exactly that for CLI agents → CLI+hooks stays primary); MCP is justified ONLY to reach MCP-only clients (desktop GUI apps), so the whole question reduces to “is reaching desktop-GUI users worth the long-lived-server overhead?”README.md, README.es.md, docs/index.html, and docs/support/agents.md. Proposed fix: HTML comments pointing at docs/support/agents.md as canonical; checklist in CONTRIBUTING.md; optional CI diff check.docs/development/codebase-digest.md should stay committed or move to a CI-generated release artifact.Rule added to the injected output-saver block in #143, then applied to the
tool itself. The convention now lives in CONTRIBUTING.md § Writing. What
shipped (#143, #144, #145) is in completed/2608.md.
docs/development/codebase-digest.md after the next
release. It is trs ingest output, so it picks the cleanup up on its own;
the ~192 dashes left in it today come from source comments.Not swept, on purpose: docs/roadmap/completed/*.md and CHANGELOG.md are
dated records of a past state, and rewriting a log falsifies it. Table cells
holding — for “no value” are a glyph, not prose.
Checked every claim in the docs against the code rather than reading for
typos. What was corrected is in
completed/2608.md. Still open:
Resolved in the follow-up (#149):
Still open:
kubectl (not building it, see Phase 2.5). Deliberately not written blind: there is no
cluster reachable here, so every shape would have been guessed. kubectl
get is tabular and should fold like the others once real output exists.command_registry_tests.rs (508).
The source files are under it since #309 and #311: commands.rs 692 to
469 (four variants wrap #[derive(Args)] structs in commands_args.rs,
CLI unchanged), command_registry.rs 527 to 370 (the verbatim rules moved
to command_verbatim.rs, re-exported).Four reviewers went over v0.7.5..HEAD. All of it is done and recorded in
completed/2608.md, including the four items first
filed as deferred. Nothing left open from that pass.
--stats reports the parser’s byte count even when the exec path
discarded it. Root-caused: classifier_exec.rs has its own never-worse
guard (parsed.len() < stdout_ref.len()), and when it falls back to raw,
the parser has already printed its CommandStats. Those go to stderr via
eprintln!, so they escape parse_out::capture and reach the user showing
what the parser would have emitted. Measured: reports 139 bytes, emits 93.
Scope is narrower than it looks, and worth stating exactly: the tracker is
correct (log_execution receives out_bytes, which the fallback sets to
the raw length), so trs stats and every savings number are accurate. Only
the per-invocation --stats diagnostic is wrong, and only in the fallback
case. Confirmed --stats does NOT change the compression decision.
The fix is not a one-liner: the exec layer would have to suppress the parser’s stats and print its own, but it does not know the parser’s reducer name. Deferred on that basis, not on risk appetite.
trs du / trs pgrep fall back to raw on very small inputs. Same
exec guard, and here it is arguably right: for a 6-row du the compressed
form is genuinely longer (+4 bytes a row) and the agent sees every row
either way. Confirmed working from ~100 rows up (du -ah src, 251 rows,
sorts correctly). Listed so nobody re-reports it as a parser bug.-c detector matches any token starting with - and ending in
c (fixed in #307: one is_shell_command_flag helper, shared by the
verbatim check and the Droid matcher), so bash --norc -c 'sort x' consumes --norc as the flag and misses
the inner sort. Pre-existing, and it now applies on the hook path too.captures_output’s = guard tests for a space, not any whitespace,
so a tab-separated line like cargo\tbuild\t--release=x now returns None
where it used to be wrapped. Reachable only with tabs as argument
separators, which agents do not emit.Both found while upgrading to v0.8.0 on a real machine.
install.ps1 has no redirect fallback yet. Same fix as the shell
installer, not written: there is no PowerShell on this machine to test it,
and the property that holds the final redirect URI differs between Windows
PowerShell 5.1 and PowerShell 7. Guessing in the Windows install path is
not worth the four lines it saves.Audited the emitted artifact, not the templates, after noticing that a prompt fragment is only as good as the context it lands in.
trs audit-docs, which scans a project root and cannot see
~/.codex/AGENTS.md at all. A trs doctor check is the right home.
Done: Done (#157): trs doctor reports a pre-sentinel block.install_rules still has the non-refreshing early return. Its two
templates carry no sentinels, so there is nothing to refresh until they get
some. Correcting my earlier note: I claimed those targets are “files trs
creates whole”, which is wrong, line 305 appends to an existing file
preserving user prose. I could not get install to take that branch on a
pre-existing .windsurfrules (file unchanged, no marker written), so the
append path and the whole-file delete in delete_rules_file may or may not
meet. Needs a reproduction before anyone acts on it.Not a finding: four of the five inline targets (opencode, kilo, droid,
devin) are files trs creates whole, so there is no foreign content to
concatenate against. Only ~/.codex/AGENTS.md mixes trs blocks with the
user’s own rules, which is why it was the one that broke.
bash -c "cd x && awk '{print}' f.py") still
reaches generic compression: is_verbatim_invocation reads the first token
of the script only. Covering it means splitting the script on &&/;/|
and treating the whole thing as verbatim if any segment is, which is a
bigger change than the bug warranted. Field data says the direct forms are
what actually run (awk 34, iconv 10, cut, column, xxd).docs/features/stats.md § Summary shows a trs savings: block in a
shape the binary no longer prints. The real header is trs Token Savings
followed by Period: / Total commands: rows.
Done: Fixed: the section shows trs Token Savings (#201).memory/ is tracked in the repo (4 files, including MEMORY.md). It
reads like agent working notes, it names a competing tool by name, and it
duplicates state that lives outside the repo. Decide whether it belongs
here at all.Decoupling pass: “the project doesn’t need more surface, it needs less internal coupling and better quality measurement.” Command knowledge was spread across classifier / rewrite_decide / classifier_exec / stats_coverage.
src/command_registry.rs is now the single
source of truth for per-command facts (aliases, rewrite/known flags,
keep_ratio, stderr policy). keep_ratio / combine_stderr / is_rewrite_command /
is_known_binary all read from it. Behavior-preserving, golden-tested.ExecutionPipeline (#311). execute_and_parse only
spawns and dispatches; the stages (stderr merge, generic, parse, pick,
passthrough) are Pipeline methods in exec_pipeline.rs, and every exit
ends in Pipeline::done (track + footer). classifier_exec.rs 431 to 73.tests/quality_harness.rs: runs fixtures
through their parsers (15 cases) and asserts signal preservation (error
codes, failing-file basenames, failure marker) + reports per-case
compression. Adding a case = one table row. First runs found and fixed 6
real bugs: all-runners “no tests found” destroying unrecognized output;
bun is_empty/success ignoring summary counts; bun FAIL-recap header
dropped; vitest ❯ suites/tests unparsed + summary swallowed by the
failure-details accumulator; cargo-test dropping panic location/message;
build dropping rustc --> file:line locations.[commands.cargo-test] max_failures = 20,
preserve_backtraces = true. Build on the existing Limits/Hooks config and
the new registry. Granularity on top of the base config.trs diff <cmd>: shipped in v0.6.12 (src/diff.rs). Raw vs compact
header (bytes/tokens), the compact output, and the lines dropped/collapsed;
--json too. Follow-up idea: feed the dropped-line analysis into a quality
harness (shares benchmark’s raw-vs-compact capture).check_config_dir /
check_history_writable depend on a writable real $HOME (via
tracker::home_dir()); a test must not depend on the real home. Inject a temp
HOME / path so the suite is hermetic.
Done: Done (#180): trs_dir honors TRS_HOME; .cargo/config.toml sets it for tests.added: 2026-06-02, keep reusable files under
~500 LOC. DONE in v0.6.12: init.rs 711 → 303 (AiTool registry moved to
src/ai_tool.rs). Re-checked 2026-11-28: every file listed then is under 500
now; commands.rs was split in #309, still over is command_registry.rs (527). Plus the
ExecutionPipeline extraction below. Note: the v0.6.x doc-comments were
reviewed and kept, they explain WHY (gotchas/decisions), not paraphrase.Field finding (May 2026), re-checked 2026-08-29 against a live install. Most of this shipped without the section being updated, and one item sat here describing a bug we then rediscovered the hard way three months later.
trs doctor reports
trs rewrite hook active (codex-cli 0.147.0).updatedInput
(src/init_templates.rs, src/init.rs, docs/features/init.md), but current
official Codex docs say PreToolUse does accept updatedInput.command with
permissionDecision: "allow" (https://developers.openai.com/codex/hooks).
Today Codex relies on rules/manual-prefix, not a real hook.
Done: The hook shipped; the gate is in src/codex.rs.doctor: warn when modern Codex exists without a trs rewrite hook.
Currently doctor only flags legacy orphan entries; it doesn’t notice a modern
Codex that could use a hook but has none.uninstall: don’t delete valid Codex hooks. scrub_legacy_codex_hook
keeps user entries in the same event, with a test pinning it.trs (Token-Reducing Shell)
while the codex prose writes it with backticks, so a second copy got
appended, 2189 bytes on every session. Worth remembering that the backlog
knew and the section title said “stale”, so nobody read it.trs install path for the ChatGPT desktop app (no
shell-hook contract). Don’t promise “ChatGPT” support except via Codex / Codex
CLI. Audit any docs that imply otherwise.
Done: Audited 2026-11-28: no ChatGPT install claim left in the README, docs or src.Not every competitor competes at the same layer.
gain/discover/session, config, tee recovery, very close to trs core,
https://www.rtk-ai.app/docs/) and chop (Claude/Gemini/Codex, 50+ filters,
.chop.yml, SQLite tracking, and chop diff <cmd>, https://getchop.run/).trs ingest competes with Repomix (MCP, local/remote pack, grep/read,
Tree-sitter compression, secret scanning, https://repomix.com/guide/mcp-server),
not with shell-output compression.trs ingest is already well-differentiated (--changed, --since-last,
--fresh, --deps, --symbols, budget-aware packing, HEAD-keyed local cache).
Improvements to make:
trs ingest --grep <pattern> over saved digests.--audit-loss mode: compare full vs signatures (full-vs-compact for
ingest; mirrors the trs diff idea at repo scale).trs ingest is incremental, not just a repo packer.
Done: README and docs/features/ingest.md say it.Design study + rationale in INGEST_RESEARCH.md (temp doc, gitignored). Key
learning from studying DeusData/codebase-memory-mcp (arXiv:2603.27277):
symbol-level dead code needs AST/LSP (they hand-wrote ~15k LOC of per-language
type resolution); but the highest-value pieces run on the import graph we
already build, no new deps.
Shipped this cycle (PR #109/#111, draft):
ingest captures pub(crate)/pub(super) symbols (was dropping ~500).trs ingest --html: self-contained visual report: KPIs, LOC-by-module
bars (expandable to files), force-directed module dependency graph
(click-to-pin), oversized files, assets/binaries. --max-loc N.Next, copy from codebase-memory-mcp (all on the existing graph, zero AST):
classify_layer
(store.c:4485): label each module entry / api / core / leaf / internal
from fan-in/fan-out, with an auto reason (“high fan-in: 42 in, 3 out”). Add
fan-in hotspots and optional Louvain clustering (natural subsystems).
Plus an “About” block (README H1 + first para, manifest description,
//!/docstring module purpose). Surface in BOTH the md digest and --html.main/lib/exports first; fail-safe
(query error ⇒ non-dead). Label clearly as module-level.cargo/knip/vulture and surface
their result, or just print a one-liner pointing the user there.SIMILAR_TO list.import_map 0.95 → same_module 0.90 → unique_name 0.75 → …) to improve graph
fidelity for multi-language repos.trs stats --graph: ASCII bar chart (30-day view)trs upgrade --check and the hint in --version; no passive notice, by design.--porcelain for more parseable output)standalone_file(), directly counters the specific false belief that drove the v0.5.15 field-test failure (“compression podría ocultar detalle que necesito”). New wording: “the compression is purely presentational: repetition and noise collapsed; signal preserved. There is no detail in raw output that the compressed form hides from you.” Still no mention of TRS_SKIP=1 or trs raw by name; regression test still passes. See docs/roadmap/completed/2605.md § Defensive-line iteration for the option-A vs B vs C decision.standalone_file() no longer mentions trs raw or TRS_SKIP=1 to Claude / Gemini / Cursor. Supersedes the v0.5.14 strengthening attempt; agents kept reaching for the escape hatch defensively, so visibility itself was the problem. README headline + docs/llms.txt “Configuration” link also demoted. Mechanism still works for humans via trs --help. Regression test guards against re-adding bypass mentions to the template.tracker::log_bypass records TRS_SKIP= observations from the JSON hook path. stats --by-agent adds a BYPASS column (count + rate); stats --json exposes top-level bypass_count. Lets the user measure whether the prompt-level intervention is reducing bypass per agent.append_history_entry private helper to dedupe I/O between log_execution and log_bypass.CODEX_AGENTS_SECTION imperative prefix, replaced soft “prefer prefixing” with explicit “you must prefix every shell command with trs” since Codex has no pre-execution hook; soft language was getting interpreted as optional and yielding 0% savings. Also refreshed Gemini hook format to the current matcher+nested-hooks shape."Tars - TRS CLI" to "Token-Reducing Shell, terminal output compression for AI coding agents".docs/roadmap/completed/2605.md for full session log + decisions.src/my-module/foo.rs:10:content no longer parsed as path="src/my". New algorithm: prefer :N: (match lines) in first pass, fall back to -N- (context lines) only if no colon-separated lineno found.cargo build/check, make/cmake, gcc/g++/clang, go build, swift build, xcodebuild now merge stderr into parser input; errors and warnings were previously lost (only cargo clippy had this). cargo test is explicitly excluded.standalone_file() with strong trs raw guidance, bold DO NOT, explicit “No prefix needed” line, routine commands listed. Next trs upgrade distributes the corrected version to all installed agent configs.benchmark.sh always cds to project root regardless of invocation path; timed_run now distinguishes real timeout (exit 124) from command error (exit N), tests 6/9/10 no longer falsely show (timeout).gh pr diff → GitDiff parser (~90% reduction)gh pr checks: new parser: pass/fail/pending summary, only non-passing checks with durationgh run view: new parser: title, conclusion, job counts, up to 3 annotations, URLnpm/pnpm/bun run format / format:check → Lint parsernpm/pnpm/bun run lint:strict, lint:fix, etc. → Lint parser (starts_with("lint"))poetry run pytest → Test parser; poetry run ruff/mypy/pylint/black/flake8/isort → Lint parsergit pull / git fetch: new GitPull parser: strips remote progress noise, keeps branch updates and diff-stat (~85% reduction)trs stats --by-command: aggregates history by normalized command family, ranked by tokens saveddocs/llms.txt: LLM agent discovery file following llms.txt specinit_collision: detects rtk hook format (rtk v0.37.2+ Windows binary hook)extra_services.rs (672 LOC) → gh_pr.rs + gh_run.rsgit grep → Grep parser (was falling through to generic compression)npm run / pnpm run / bun run: route by script name: build* → Build, test* → Test, lint/type-check → Lintnpx @biomejs/biome: package-name form now routes to Lint (short name biome already worked)trs.md, replaces trs-output-saver.md; includes input-rewrite section + output-saver rules; migration removes legacy file on next installtrs init --global writes trs.md alongside hooks.json for Claude Code and Gemini CLI@RTK.md from ~/.claude/CLAUDE.md (no longer needed, trs covers everything)cat, head, sed -n X,Yp, filter_minimal applied before subprocess spawn (10–35% savings)git show: git stash show -p, stash pop, stash apply, routed to GitDiff parser (~90% reduction)gh pr view: new GhPrView parser: title, state, author, url, labels, 3-line body preview (~45% reduction)tsc linter parser: file(line,col): error TS6133: message format, grouped by file (~80% reduction); dispatched via npx tsc, pnpm dlx tscgit push/pull/fetch: remote: progress lines stripped on success (~85% vs previous 34–41%)classifier_exec (now dispatched to exec_pipeline), skips parser if keep_ratio > 0.90, falls through to generic compressioncommon.rs (671 LOC) → ansi.rs (168 LOC) + common.rs (466 LOC); all callers unchanged via re-exportgrep-matcher, grep-regex, grep-searcherinject_file_path free function refactored → ParseCommands::with_file() method; classifier.rs from 519 → 471 LOCtrs output-saver: installs compact anti-preamble / result-first rules block into each agent’s global config (8/9 agents)trs init: detects competing hooks, --replace / --force / default-abort flowcontains_credential)output_has_failure_signal)cd X && git Y (v0.5.5)@dpeluche/trs)