How trs integrates with each supported AI coding agent. Use this doc when
adding a new agent, debugging a broken integration, or reviewing why a
specific quirk exists.
Last validated: 2026-04-19 against trs v0.5.7.
trs output-saver installs output-reduction rules into each agent’s
global config. Orthogonal to the input-side hook/plugin/rules install
matrix below. Six distinct target paths across three mechanisms:
| Agent | Mechanism | Path |
|---|---|---|
| Claude Code | standalone file + @import |
~/.claude/trs-output-saver.md + line in ~/.claude/CLAUDE.md |
| Gemini CLI | standalone file + @import |
~/.gemini/trs-output-saver.md + line in ~/.gemini/GEMINI.md |
| Cursor | local plugin, always-apply rule | ~/.cursor/plugins/local/trs/ |
| Codex | inline with sentinels | ~/.codex/AGENTS.md |
| Windsurf | inline with sentinels | ~/.codeium/windsurf/memories/global_rules.md |
| OpenCode | inline with sentinels | ~/.config/opencode/AGENTS.md |
| Kilo Code | inline with sentinels | ~/.config/kilo/AGENTS.md |
| Factory Droid | inline with sentinels | ~/.factory/AGENTS.md |
| Antigravity IDE | @import (shared with Gemini), ~/.gemini/trs.md + line in ~/.gemini/GEMINI.md (output-saver); hooks live separately, see below |
|
Antigravity CLI (agy) |
@import (shared with Gemini), ~/.gemini/trs.md + line in ~/.gemini/GEMINI.md (output-saver); hooks live separately, see below |
|
| Grok Build | inline with sentinels | $GROK_HOME/AGENTS.md (default ~/.grok/AGENTS.md) |
| Kiro | steering file with inclusion: always |
~/.kiro/steering/trs.md |
| OpenClaw | inline with sentinels | ~/.openclaw/workspace/SOUL.md |
Grok Build was confirmed on grok 1.0.70: a needle in ~/.grok/AGENTS.md
reached a headless session. Kiro and OpenClaw follow each agent’s docs. No real
binary has confirmed they load, so treat them as unverified until one does.
Inline installs use the sentinels
<!-- trs:output-saver:start v1 --> / <!-- trs:output-saver:end -->
so a second run replaces the block between them without touching the
surrounding user content.
AGENTS.md convention: Codex, OpenCode, Kilo, and Droid all auto-load
the AGENTS.md convention (Droid is a signatory of the AGENTS.md
consortium, see https://factory.ai/news/agents-md). That’s why those
four converge on the same install mechanism.
Plugin-level hook note: OpenCode’s plugin API has no prompt-layer
hook (tool.execute.* only). Kilo exposes
experimental.chat.system.transform and Droid exposes SessionStart /
UserPromptSubmit, both could inject rules dynamically. For a static
rules block the AGENTS.md file is simpler and less likely to break
across agent updates.
Agents fall into three architectural buckets. Pick the right bucket BEFORE writing a template, the install mechanism, test strategy, and failure modes differ.
| Type | How it works | Agents | File written |
|---|---|---|---|
| Hook (JSON event) | Agent fires a PreToolUse-style event, hands us the command on stdin, applies our rewrite response | Claude Code, Gemini CLI, Cursor, Factory Droid, Codex (codex-cli ≥ 0.134), Antigravity IDE, Antigravity CLI | settings.json / hooks.json |
| Plugin (TypeScript) | Agent auto-discovers .ts plugin files at startup and mutates tool args in-process |
OpenCode, Kilo Code | plugins/trs.ts |
| Rules file | No programmatic interception. Agent reads a rules/instructions file and VOLUNTARILY prefixes trs |
Windsurf, Codex (fallback on older builds) | AGENTS.md / .windsurfrules |
Hook and plugin are deterministic (binary: fires or not). Rules-based is probabilistic, depends on the agent choosing to follow the guidance.
All three hook agents send tool_input.command on stdin but expect different
output shapes. src/rewrite.rs::HookEvent dispatches on the
hook_event_name field of the stdin JSON:
hook_event_name |
Client | Output envelope |
|---|---|---|
PreToolUse (capital P) |
Claude Code | hookSpecificOutput.updatedInput.command |
BeforeTool |
Gemini CLI | hookSpecificOutput.tool_input.command + top-level decision |
preToolUse (lowercase p) |
Cursor | top-level updated_input.command (no permission) |
| missing / unknown | fallback | Claude format |
Claude’s PreToolUse and Cursor’s preToolUse differ ONLY by case. If you
change the match order or add a case-insensitive comparison, you will break
one of them silently.
Factory Droid uses Claude’s Shape verbatim, hook_event_name: "PreToolUse".
TRS_AGENT)Added in v0.5.8. When the rewriter or a plugin template emits a
rewritten command, it prefixes it with TRS_AGENT=<label> so the
downstream trs <cmd> execution can attribute the run.
| Agent | Detection | Label |
|---|---|---|
| Claude Code | hook_event_name: PreToolUse |
claude |
| Gemini CLI | hook_event_name: BeforeTool |
gemini |
| Cursor | hook_event_name: preToolUse |
cursor |
| OpenCode | plugin template bakes the label | opencode |
| Kilo Code | separate plugin template bakes the label | kilo |
| Factory Droid | same wire format as Claude | claude (indistinguishable from Claude) |
| Antigravity IDE / CLI | rules-only as of v0.6.6 (why) | (untagged) |
| Codex | PreToolUse hook command carries TRS_AGENT=codex (codex-cli ≥ 0.134) |
codex (rules-only fallback: (untagged)) |
| Windsurf | rules-only, no programmatic signal | (untagged) |
The shell treats leading VAR=value as a per-command env override
and strips it before executing the downstream program, so the tag
is transparent to git/cargo/etc. Read via std::env::var("TRS_AGENT")
at log time in tracker::log_execution. View results with
trs stats --by-agent.
Droid limitation: Droid’s envelope is identical to Claude’s at
the wire-format layer. We can’t distinguish them without a separate
signal (install-time flag, marker in the hook content, etc.). Both
show up as claude in attribution today.
| Type | Hook |
| Config | ~/.claude/settings.json (global) or hooks/hooks.json (project) |
| Event | PreToolUse with matcher: "Bash" |
| Template | CLAUDE_HOOKS |
| Test prompt | hook-based |
Canonical client: we treat its format as the default. One quirk, permissions:
Claude Code matches permissions.allow/ask/deny against the command after
the hook rewrote it (checked on a real Claude Code with a rewriting hook), and a
hook permissionDecision: "allow" overrides them. A blanket allow therefore
ran git push even with deny: Bash(git push:*), and a plain rewrite made a
user’s allow: Bash(git status:*) stop matching trs git status. So for the
claude label, src/rewrite_permissions.rs reads the user’s rules and applies
them to the original command (every &&/||/;/| part):
| Original command | Hook does |
|---|---|
matches a deny or ask rule |
no rewrite, Claude handles the original |
every part matches an allow rule or is read-only (ls, cat, git status, …) |
rewrite and allow |
| anything else | rewrite, no decision: Claude’s own prompt applies |
| a settings file exists but cannot be parsed | no rewrite (fail closed) |
Sources: ~/.claude (or CLAUDE_CONFIG_DIR), managed settings, and
.claude/settings{,.local}.json from the cwd upwards. A project’s allow counts
only when ~/.claude.json marks the folder trusted (Claude ignores it
otherwise); its deny/ask always count. Rules passed with --settings are
invisible to the hook. The other agents each have their own gate, see
Permissions per agent.
| Type | Hook |
| Config | ~/.gemini/settings.json |
| Event | BeforeTool with matcher: ".*" |
| Tool name | run_shell_command |
| Template | GEMINI_HOOKS |
| Docs | https://geminicli.com/docs/hooks/reference/ |
Quirk: emits a different output envelope than Claude. Early installs
copied Claude’s shape and silently failed, hook fired, exit 0, command not
rewritten. Fixed in a662c9d by dispatching on hook_event_name.
Hallucination caveat: Gemini’s chat mode sometimes fabricates plausible
command output when shell is unavailable. If the reported trs --version
shows a version that doesn’t exist (e.g. v0.14.13), Gemini is inventing,
validate via trs stats --history from a real terminal.
| Type | Hook |
| Config | ~/.cursor/hooks.json |
| Event | preToolUse with matcher: "Shell" |
| Tool name | Shell |
| Template | CURSOR_HOOKS |
| Docs | https://cursor.com/docs/hooks |
Quirks:
beforeShellExecution (Cursor’s other shell-ish hook) only supports
allow/deny, no rewrite. DO NOT register there. preToolUse is the one
with updated_input support. Fixed in fb4bafb.preToolUse for every tool (Shell, Read, Write, MCP, Task).
Without matcher: "Shell", the hook ran for hundreds of Read-tool polling
calls per session, wasted ~4ms subprocess each. Fixed in e797d8a."Shell" is the Shell tool’s exact
name; "shell" doesn’t match.| Type | Hook |
| Config | ~/.factory/settings.json |
| Event | PreToolUse with matcher: ".*" |
| Tool name | Execute (NOT Bash) |
| Template | DROID_HOOKS |
Quirk: Droid’s shell tool is called Execute, not Bash. Initial
installs copied Claude’s template with matcher: "Bash" → hook registered
but never matched. Fixed in af5b783 by widening the matcher to ".*".
Our trs rewrite internally filters non-shell input, so the wider matcher
is safe.
Output envelope is identical to Claude Code.
| Type | Plugin (TypeScript) |
| Config | ~/.config/opencode/plugins/trs.ts (global) or .opencode/plugins/trs.ts (project) |
| Hook key 1.x | "tool.execute.before" (string literal, not before_tool_call) |
| Hook key 2.x | ctx.tool.hook("execute.before") and ctx.shell.hook("create.before") |
| Tool name check | 1.x input.tool === "bash", 2.x input.tool === "shell" |
| Mutation | 1.x output.args.command = viaTrs(cmd), 2.x input.input = { ...input.input, command: viaTrs(cmd) } |
| Template | OPENCODE_PLUGIN (one default export serves both) |
| Docs | https://opencode.ai/docs/plugins/ |
Quirks:
opencode.json
needed.export default { id, setup }.
The named-export form 1.x accepted fails with “Plugin must export a default
definition with an id and an effect or setup function” and the plugin
never runs, so nothing is routed through trs. 1.x (checked on 1.19.3) reads
server from the same default export, so the template defines both.
trs doctor flags a plugin file without export default.viaTrs pipes the command into
trs rewrite (plain-text mode) and uses its answer, so pipes, redirects,
$(...) and bypass prefixes behave as for the hook agents (a blind
trs ${cmd} made ls | wc -l read compressed text). It fails open: no
trs on PATH, a timeout or an error keeps the original command. When the
bare name does not resolve, the plugin tries the usual install locations
(~/.local/bin, ~/.cargo/bin, ~/.trs/bin, /opt/homebrew/bin,
/usr/local/bin) once per load and passes the one it found as TRS_BIN,
so the rewritten command calls that binary too. This covers GUI launches
whose PATH lacks the install dir. Kilo, Pi,
OpenClaw and Hermes use the same helper; tests/cli_plugin_templates.rs
runs it. trs doctor flags a plugin written before this.shell.create.before fires for every shell, including the
user’s own !cmd; the tool hook is the only one that sees the agent’s.before_tool_call hook with ctx.tool / ctx.input;
that API is outdated. The current API is "tool.execute.before" with
(input, output) arguments. Fixed in b3d783f.~/.config/opencode/plugins/, NOT ~/.opencode/plugins/.
The ~/.opencode/ directory exists for unrelated reasons (bun workspace).| Type | Plugin (TypeScript) |
| Config | ~/.config/kilo/plugins/trs.ts (global) or .kilo/plugins/trs.ts (project) |
| Template | KILO_PLUGIN (1.x plugin API, named export) |
Kilo mirrors OpenCode 1.x’s plugin architecture. Same tool.execute.before
hook, same auto-discovery. Our install spec treats it as an OpenCode 1.x
clone and ships its own named-export template (KILO_PLUGIN); revisit it if
Kilo moves to the 2.x plugin API.
| Type | Hook (codex-cli ≥ 0.134) with rules-file fallback |
| Config | ~/.codex/hooks.json (PreToolUse, matcher "Bash") + ~/.codex/AGENTS.md |
| Event | PreToolUse; reply via hookSpecificOutput.updatedInput.command with permissionDecision: "allow" |
| Hook command | trs rewrite --caller codex |
| Template | CODEX_AGENTS_SECTION (rules block) |
| Version gate | REWRITE_HOOK_MIN_VERSION = Some((0,134,0)) in src/codex.rs |
Version-gated. Codex CLI implements programmatic command rewriting
via the PreToolUse hook’s hookSpecificOutput.updatedInput.command
field starting in codex-cli ≥ 0.134 (PR openai/codex#20527, merged
2026-05-12; verified end-to-end on 0.136.0). On a qualifying build,
trs init codex --global merges a real PreToolUse hook into
~/.codex/hooks.json (preserving the user’s other hooks; idempotent).
Approve it once via Codex’s /hooks prompt and commands are rewritten
automatically, no trs prefix needed.
Rules-only fallback. On older codex builds (or when the hook isn’t
trusted), trs falls back to the ~/.codex/AGENTS.md block instructing
Codex to prefix trs. Prefixing is always safe: trs never
double-wraps a command already starting with trs.
Caveat. codex exec dispatches PreToolUse too (verified on 0.166),
but only once the hook is trusted ([hooks.state] in config.toml, or
--dangerously-bypass-hook-trust); an untrusted hook silently does not run.
Validate with the hook-based test prompt on ≥ 0.134, or the rules-based
test prompt on the fallback (see docs/agent-test-prompts.md section
below).
| Type | Rules file (was programmatic hook, reverted in v0.6.6) |
| Config (shared) | ~/.gemini/GEMINI.md (sentinel-wrapped rules block) |
| Template | ANTIGRAVITY_RULES_SECTION |
| Tool name | n/a, no programmatic interception |
v0.6.6 revert. Antigravity (IDE + CLI/agy) is rules-only.
Empirical testing against agy v1.0.1 showed user-defined entries in
~/.gemini/antigravity-{cli,ide}/hooks.json load as subagents
(via invoke_subagent), not as tool-call wrappers. Bash invocations
go through Step_RunCommand and bypass the user-visible PreToolHook
pipeline entirely. The full investigation lives at
docs/development/antigravity-hooks-research.md.
Update (agy 1.4.12). “Rules-only” is stale for the CLI: it now has its own
hooks.json with decision/overwrite replies. trs does not use it yet
(TASK_TODO P3); until then the rules file stays the integration.
Detection:
app_exists("Antigravity") ∨ ~/.gemini/antigravity-ide/
exists ∨ legacy ~/.antigravity/.in_path("agy") ∨ ~/.gemini/antigravity-cli/ exists.Attribution: (untagged) in trs stats --by-agent. The hook
never fires programmatically, so there is no TRS_AGENT signal to
attach. Manual prefixes (trs git status typed by the agent or
user) also land in (untagged). Same posture as Codex/Windsurf.
Migration cleanup. trs init and trs uninstall both sweep:
~/.gemini/antigravity-{cli,ide}/hooks.json~/.gemini/settings.json.agent/rules/antigravity-trs-rules.md per-project fileRe-enable plan. When Google ships user-configurable PreToolHook
for Bash, restoring the programmatic integration is a mechanical
revert of branch fix/antigravity-rules-only-revert. See the
research doc
for the exact checklist.
Quirks:
~/.zshenv;
this could surface as command not found: trs if ~/.local/bin
was only added to .zshrc. install.sh recommends ~/.zshenv for
zsh users (fixed in 6f84f62, plus an explicit warning added in
v0.6.6 for users who already have .local/bin in .zshrc only).
Antigravity 2.0 inherits this constraint.| Type | Rules file |
| Config | .windsurfrules (project root) |
| Template | WINDSURF_RULES |
Windsurf Cascade has no pre-execution hook: rules-based voluntary adoption only (like Codex’s fallback on older builds).
| Type | Output-saver only; the hook never rewrites for Grok, on purpose |
| Config | $GROK_HOME/AGENTS.md (default ~/.grok/AGENTS.md) |
Grok has a Claude-shaped PreToolUse hook in ~/.grok/hooks/*.json, and a
rewrite does apply, but on grok 1.0.70 trs must not install one:
--deny 'Bash(git status:*)'
and the real hook, git status ran through trs. A rule on the original never
fired, and --deny flags are invisible to a hook, so a gate cannot cover them.git status
was blocked as “unknown trs prefix”, with the output-saver block installed.
Without the hook the same command runs, because it is on the read-only list.[compat.claude] hooks defaults to true, so Grok also runs the trs hook installed
for Claude Code. Before #215 that hook omitted description, Grok’s schema refused
the rewrite, and every rewritable command failed. After #215 the rewrite applied
and deny rules stopped firing. So rewrite_gate.rs has a grok row that tells it
apart by tool_name (run_terminal_command) and never rewrites; with it the deny
rule fires again. Unchecked: a Cursor hook reaching Grok through [compat.cursor],
since an explicit --caller skips the tool-name lookup.
Most agents match their permission rules against the command after the
rewrite, so git push becomes TRS_AGENT=x trs git push and a user’s
deny: git push or allow: git status stops matching. A hook allow can also
skip the rules entirely. Each agent therefore has a gate
(src/rewrite_gate.rs, one src/rewrite_perm_<agent>.rs per host) that reads
the user’s rules and applies them to the original command. Outcomes:
Skip (no rewrite, the agent handles the original), Allow (rewrite and
approve), Defer (rewrite, no decision, the agent’s own prompt applies). Every
gate fails closed: an unreadable or unknown rule file means Skip, and a
project’s allow counts only when the folder is trusted (deny/ask always count).
| Agent | Rules read | Gate result | Unverified |
|---|---|---|---|
| Claude Code | settings{,.local}.json, managed |
Skip / Allow / Defer | --settings rules invisible |
| Codex | $CODEX_HOME/rules/*.rules, trusted .codex/rules |
Skip on any matching rule, else Allow (Codex needs the allow for updatedInput) |
managed requirements.toml, --ignore-rules |
| Factory Droid | commandAllowlist/Denylist/Blocklist in ~/.factory, project settings, the managed settings.json and the cached org settings |
Skip on deny/block, Allow if all parts listed, Defer only in auto-high, else Skip; permissionRules (version 1): ask/block skip, allow approves (a project’s allow is ignored); FACTORY_RUNTIME_SETTINGS_PATH overlay read |
--settings flag overlays |
| Gemini CLI | settings.json, policies/*.toml, trusted project settings |
never Allow (Gemini ignores a hook allow); Skip on deny/ask, narrow tools.allowed, or read-only commands |
system settings, admin policies, -y |
| Devin CLI | ~/.config/devin/config.json, .devin/config{,.local}.json |
Skip on deny/ask, Allow if all parts match Exec(...), else Defer |
org rules, dangerous mode, trust |
| Cursor | Shell(...) deny rules in $CURSOR_CONFIG_DIR or ~/.cursor/cli-config.json, and a project’s .cursor/cli.json (read, not verified live) |
Skip on deny, else rewrite with no decision (a hook allow never approves nor beats a deny) |
ask rules (no effect seen) |
| Copilot CLI / VS Code | none readable | no allow is sent; --deny-tool flags and VS Code auto-approve settings are invisible |
flags |
| OpenCode 2.x | permission.bash via ctx.permission.assert |
plugin asks about the original segments (trs rewrite --json, rewrite and segments in one spawn) before rewriting |
1.x config shape |
| Kilo / OpenCode 1.x | client.config.get() |
rewrite only if no ask/deny rule for bash |
|
| Pi | none (no permission engine) | rewrite lives only in the bash spawnHook; never mutate event.input so user gates see the original |
|
| Antigravity | n/a | rules file only; agy 1.4.12 has its own hooks.json with decision/overwrite, unused by trs |
Notes:
git status, ls) are skipped, because
Gemini auto-allows them (the list reuses Claude’s; Gemini’s own safe set is unverified) and the rewrite would add a prompt. tools.exclude
and confirmationRequired do not narrow in 0.63; only TOML policies express
a narrow deny or ask.riskLevel (counts as high), so
outside auto-high an unlisted command is not rewritten. Verified live on Droid 1.2.0: the denylist
is matched on the rewritten text and a hook allow skips it; the blocklist is
not skipped; the allowlist is matched on the original; a project’s legacy
lists count without folder trust.FOO=1 cmd and trs cmd do not match a ["cmd"] rule, hence the
gate. A malformed .rules file stops Codex from starting at all.assert call with all segments as resources, so a
deny on any segment denies the command and the user sees a single prompt. A
permission.evaluate hook turns the follow-up ask into allow for calls
already approved.allow overrides --deny-tool, even for rules that
match the rewritten text, so trs no longer sends it.Estoy validando el hook de trs en este entorno. Ejecuta los comandos
abajo usando tu tool de shell. Pega outputs literales.
CRITICO: Si no tienes acceso a shell, di "no tengo shell" en lugar de
inventar. Si ejecutas algo, no parafrasees, copy-paste literal.
1. `trs --version`
2. `git status`
3. `trs stats --history 2>&1 | tail -5`
Despues responde en 1 frase:
- Que tool usaste para ejecutar los comandos
- Que sabes de trs por tu contexto actual
Pass criteria:
git status returns the compact branch\nuntracked (N):\n ?? file
format, NOT the native On branch X\nYour branch is up to date\n...trs stats --history shows a new entry with a timestamp matching the
test moment, ground truth, use this instead of trusting the agent’s
reported output.Tu archivo de instrucciones (AGENTS.md / .windsurfrules /
.agent/rules/) debe mencionar `trs`. Haz estos 3 tests sin inventar:
1. AWARENESS: Antes de ejecutar nada: ¿que sabes de trs por tu
contexto actual? Una frase.
2. TOOL CHECK: Ejecuta `trs --version` y pega el output literal.
3. VOLUNTARY USE: Necesito ver el estado del repositorio git,
minimizando consumo de tokens. NO ejecutes todavia. ESCRIBE el
comando que usarias y explica por que.
Pass criteria:
trs 0.5.Xtrs git status voluntarily (not git status raw)If a hook/plugin is installed but commands pass through unchanged, use a debug wrapper instead of trusting the agent’s self-report:
# 1. Create a logging wrapper
cat > /tmp/trs-hook-debug.sh <<'EOF'
#!/bin/bash
LOG=/tmp/trs-hook-debug.log
TS=$(date '+%H:%M:%S')
INPUT=$(cat)
echo "[$TS] >>> STDIN: $INPUT" >> $LOG
OUTPUT=$(echo "$INPUT" | /path/to/trs rewrite)
echo "[$TS] <<< STDOUT: $OUTPUT" >> $LOG
echo "$OUTPUT"
EOF
chmod +x /tmp/trs-hook-debug.sh
# 2. Point the agent's hook at the wrapper (back up first)
# cp ~/.xyz/settings.json ~/.xyz/settings.json.bak
# edit the config to replace `trs rewrite` with `/tmp/trs-hook-debug.sh`
# 3. Reproduce the failure in the agent (full quit + restart first)
# 4. Inspect
cat /tmp/trs-hook-debug.log
The log tells you:
updated_input or
equivalent? If only allow/deny, it can’t be a hook integration.hook_event_name, tool_name, or a
header field the agent includes in its stdin payload.src/init_templates.rs. Don’t copy
another agent’s template verbatim, the matcher field and tool name
must match THIS agent’s conventions.src/rewrite.rs::HookEvent::parse if the
output envelope differs from existing clients.src/init.rs::spec() with correct
global_dir (often .config/<agent>/<subdir>).The hook wraps a command by manipulating its text. That is only sound when
the string really is one flat command, so rewrite_decide::is_simple_command
bails out on everything else. Each rule below exists because the alternative
was observed in the field, and every one of them failed silently or fatally,
never loudly:
| Shape | What wrapping did |
|---|---|
| newline (multi-line script) | Two statements collapsed into one: V=abc + printf "$V" became V=abc trs printf "$V", where the shell expands $V before the command-scoped assignment applies. Non-exported values vanished; exported ones survived, which made it look intermittent. |
heredoc (<<) |
The body is data, not commands, yet ` && ` inside it was substituted, so the injected text landed in the written file. In one report it reached main and corrupted a security test whose grep then read compressed output. |
| quoted operators | git commit -m "fix a && b" had its message rewritten; grep -r "foo && bar" had its pattern rewritten, so the search silently looked for something else and returned “not found”. |
array literal (arr=(…)) |
The env-prefix split walks by whitespace and landed inside the parens, inserting a phantom element: [uno][trs][dos]. No error, no exit code, corrupt data that downstream loops iterate over. |
compound keywords, ( ), { }, f() {} |
trs for f in … makes the shell read for as a program and do as a syntax error: the command dies outright. |
; sequences |
Independent commands, same problem as newlines. |
assignment heading a && chain |
S=x && rm -rf $S/* became S=x trs && ...: S went to trs’s environment, $S expanded empty and the shell ran rm -rf /* (2026-11-29, fixed in 0.10.5). |
Behind the shape gate, src/rewrite_guard.rs holds three rules (why: the
2026-11-29 incident):
trs X cannot run like the shell runs X. Builtins
that set shell state (read, declare, export, cd, eval,
: ${S:=x}, printf -v, umask, pushd, bare exec, !, [[, …):
trs runs X as a child process, so read S would set S in trs and leave
it empty in the shell, the same failure as the incident. echo, type and
which: a child cannot see aliases or functions. Programs named like a trs
subcommand (diff, tail, read, init, …): trs diff a b is trs’s own
diff, which runs a. A bare redirect (exec 2>/dev/null). And programs
that need a terminal (vim, less, top, ssh, a bare python3 or
psql): under trs their output is a pipe.rm, mv, cp, chmod, kill,
sudo, find -delete, git clean, git reset --hard, rsync --delete,
…), also behind timeout, env or nix develop -c. They print next to
nothing, so wrapping saves nothing, and no rewrite bug can land on them.
This list cannot be complete; it is a second line, not the lock.TRS_AGENT=
tags, must be the original with only trs inserted at the head of a
segment (after env words or a known wrapper) and tags at the head. Words are
compared quote-aware, so a change inside quotes counts. The lock also
refuses anything the two lists above refuse. Any other difference drops the
rewrite and the command runs as written.rewrite_guard_tests.rs runs each rewrite, and the agent-tagged command the
agent really gets, next to its original under sh -u (and zsh -f when
present) and compares output, status and the files left behind.
Besides those rules and the shape gate, a short prefix list (cat, head)
skips commands not worth wrapping. A shape that looks exempt may simply
be unparseable: check the gate, the rules and the prefixes before concluding.
Escape hatch for anything the gate lets through: TRS_SKIP=1 <cmd>. It does
not work in front of shell keywords or (/{, an env prefix there is
itself a syntax error; wrap those as TRS_SKIP=1 sh -c "…".
src/init.rs: install orchestration, merge_json_hook (safe merging),
install_rules (for rules-file tools)src/init_templates.rs: all templatessrc/rewrite.rs: hook command rewriter, HookEvent dispatchdocs/install.sh: .zshenv targeting for zsh subshells