Skip to content

feat(autoresearch): expand Claude RTK rewriting for chains, guarded find, and rg#3773

Open
MattPua wants to merge 7 commits into
mainfrom
posthog-code/autoresearch-rtk-bash-optimizations
Open

feat(autoresearch): expand Claude RTK rewriting for chains, guarded find, and rg#3773
MattPua wants to merge 7 commits into
mainfrom
posthog-code/autoresearch-rtk-bash-optimizations

Conversation

@MattPua

@MattPua MattPua commented Jul 23, 2026

Copy link
Copy Markdown
Member

Purpose

This PR reduces Claude agent context usage by routing more eligible Bash commands through RTK. It does not change RTK's compression algorithm. It fixes which commands safely reach it:

  • Rewrite eligible segments inside && and ; chains instead of skipping the whole chain
  • Route safe rg commands through native RTK
  • Keep unsupported find predicates and unsafe shell shapes raw
  • Preserve shell behavior, exit codes, and the facts agents need

Codex receives matching developer guidance, but has no deterministic command-rewrite hook. The measured savings below apply only to Claude sessions.

Important

Production-weighted upper estimate: 13.6% less Bash output than main.

Across the measurable 30-day production sample, that is approximately 1.58 MB less output, or 396k estimated command-output tokens.

This weights observed production output bytes by command shape. Actual savings may be lower because a chain can contain both eligible and ineligible segments.

What changes

  • Rewrite eligible top-level segments inside && and ; chains
  • Route rg through native RTK only when a real executable exists
  • Keep output modes that RTK cannot preserve raw
  • Allowlist the find predicates RTK supports
  • Fail safe for multiline input, substitutions, unbalanced syntax, pipes, and redirects
  • Mirror the policy in Codex guidance as a best-effort hint
  • Add a benchmark against the real policy on main and a live context-fidelity E2E

Before and after

1. Large rg searches: 86.4% less output

rg -n '^import' packages/core/src
main This PR Difference
Output lines 1,474 204 1,270 fewer
Output bytes 142,172 19,400 122,772 fewer
Exact totals available No summary 1,474 matches in 511 files Preserved

On main: all 1,474 repetitive matches enter the conversation

packages/core/src/agent-chat/agentChat.module.ts:1:import { ContainerModule } from "inversify";
packages/core/src/agent-chat/agentChat.module.ts:2:import { AgentChatService } from "./agentChatService";
packages/core/src/agent-chat/agentChat.module.ts:3:import { AGENT_CHAT_SERVICE } from "./identifiers";
... 1,471 more lines sent to the model

With this PR: one exact summary plus 200 representative matches enter the conversation

1474 matches in 511 files:

packages/core/src/agent-chat/agentChat.module.ts:1:import { ContainerModule } from "inversify";
packages/core/src/agent-chat/agentChat.module.ts:2:import { AgentChatService } from "./agentChatService";
... remaining repetitive matches omitted

Important

The agent keeps the exact answer, 1,474 matches across 511 files, while 86.4% of the output is removed from context.

2. Batched commands: compression now works inside chains

git status --short && git branch --show-current && git log --oneline --decorate -20 && git diff --stat && git diff

On main: the presence of && disables RTK for the entire line

git status --short && git branch --show-current && git log ... && git diff --stat && git diff
└──────────────────────── all five commands return raw output ────────────────────────────────┘

Result: 9,975 bytes / 188 lines

With this PR: every eligible segment is compressed independently

rtk git status --short && rtk git branch --show-current && rtk git log ... && rtk git diff --stat && rtk git diff
└──────────────────────── all five commands reach RTK ────────────────────────────────────────────┘

Result: 9,128 bytes / 168 lines

Important

This small worktree saves 8.5%. The same change unlocks compression for the 28.9% of production Bash calls containing &&, with larger savings when their output is larger.

Command order, output facts, exit codes, and && short-circuit behavior remain unchanged.

3. Unsupported find: error becomes complete results

find packages/agent -name '*.test.ts' -not -path '*/node_modules/*'

On main: RTK receives syntax it does not support

$ rtk find packages/agent -name '*.test.ts' -not -path '*/node_modules/*'
rtk: rtk find does not support compound predicates or actions (e.g. -not, -exec). Use `find` directly.
exit 1 · 0 of 102 files returned

With this PR: the unsupported shape stays raw

$ find packages/agent -name '*.test.ts' -not -path '*/node_modules/*'
packages/agent/src/acp-helpers.test.ts
packages/agent/src/acp-limits.test.ts
... all remaining files returned
exit 0 · 102 of 102 files returned

Important

The result changes from an error with no data to all 102 requested files, avoiding a failed turn and retry.

Results

Production-calibrated estimate

The measurable 30-day Bash-span sample contains 7,745 calls and 11.7 MB of actual output. Unlike the larger command-frequency analysis below, this sample includes output payloads and can be weighted by bytes.

Candidate behavior Share of production Bash-output bytes Fixture reduction Estimated total reduction
Native rg 0.71% 86.4% 0.61 points
Likely eligible single-line chains 23.65% 54.8% 12.95 points
Combined directional estimate up to 13.6%

Applied to the sample's 11.7 MB of Bash output:

  • Native rg: approximately 72 KB removed
  • Eligible chains: approximately 1.51 MB removed
  • Combined: approximately 1.58 MB, or 396k estimated tokens using bytes divided by four

Warning

This is not an observed production saving. It applies fidelity-validated fixture compression rates to production output-byte shares. It is best treated as an upper estimate until a production shadow evaluation or post-rollout measurement can compare actual output before and after rewriting.

Safety

  • Preserve chain ordering and && short-circuit behavior
  • Leave multiline input, substitutions, unbalanced syntax, pipes, and redirects untouched
  • Keep unsafe rg output modes raw
  • Run rg through RTK only when RTK can execute a real rg binary
  • Keep unsupported find predicates raw instead of replacing results with an RTK error
  • Fidelity-gate benchmark rows on exit status, output presence, and exact expected facts

How did you test this?

  • 117/117 scoped RTK unit tests passed
  • Deterministic benchmark:
    • Candidate fidelity failures: 0
    • Main-policy fidelity failure: unsupported find -not
  • Five authenticated, four-turn live Claude gateway runs:
    • RTK engagement: 5/5
    • Compressed grep file and line: 5/5
    • Compressed 4,800-match total: 5/5
    • Compressed chained Git state: 5/5
    • Full suite: 4/5
  • The single live failure was the intentionally raw find case. Claude counted 0 instead of 9 once; RTK did not rewrite that command.

Automatic notifications

  • Publish to changelog?
  • Alert Sales and Marketing teams?

Created with PostHog Code

Rewrite eligible segments inside top-level &&/; chains, guard rtk find behind an allowlist of supported primaries with a pipefail pipe fallback for pure file-list shapes, and route rg through native rtk rg when it is a real PATH executable (pipe fallback when it is a shell function). Adds scripts/rtk-bench.mjs, a deterministic benchmark applying the real hook policy.

Generated-By: PostHog Code
Task-Id: 5330cf5e-2ca2-4f33-82e9-173dd4a01af6
@trunk-io

trunk-io Bot commented Jul 23, 2026

Copy link
Copy Markdown

Merging to main in this repository is managed by Trunk.

  • To merge this pull request, check the box to the left or comment /trunk merge below.

After your PR is submitted to the merge queue, this comment will be automatically updated with its status. If the PR fails, failure details will also be posted here

@github-actions

github-actions Bot commented Jul 23, 2026

Copy link
Copy Markdown

React Doctor found no issues in the changed files. 🎉

Reviewed by React Doctor for commit 19b645d.

MattPua added 4 commits July 23, 2026 15:59
The Codex adapter has no command-rewrite channel, so its instruction-level guidance must track the hook policy: advertise the find predicate allowlist (rtk hard-fails on -not/-exec/! shapes), allow prefixing eligible segments of && chains, and advertise rg only when it is a real PATH executable, since rtk rg execs rg and fails where rg is only a shell function.

Generated-By: PostHog Code
Task-Id: 5330cf5e-2ca2-4f33-82e9-173dd4a01af6
Proves RTK compression preserves the information the agent needs, end to end: three sequential turns in one session against a seeded ~130-file repo must recover an exact file+line from compressed grep output, an exact file count through the find -not pipe fallback, and per-file git state from a compressed && chain — asserted as JSON side effects against seeded ground truth, never prose. RTK_DB_PATH isolates rtk telemetry so rtk gain must report tracked commands with positive savings, making a silently disabled hook fail instead of passing vacuously.

Generated-By: PostHog Code
Task-Id: 5330cf5e-2ca2-4f33-82e9-173dd4a01af6
…rolled bench, executable PATH check

Review found the pipe fallbacks silently truncate large result sets (10 files per dir with +N markers), the bench had no main-policy control and could count erroring rewrites as savings, PATH detection accepted non-executable files, and the e2e sailed under rtk's truncation cap.

Drops both pipe fallbacks: rtk-unsupported finds now run raw (they are used when the complete matched set matters) and rg routes only through native rtk rg when a real executable is on PATH, which matches the long-shipped grep proxy's caps and reports uncapped totals. findOnPath requires the execute bit. The bench now runs main's policy as a control arm via git show, captures exit status and stderr, and fidelity-gates every row (exit parity, output presence, per-row facts) — candidate-only failures fail the run, baseline-only failures are flagged as fixed. The e2e gains a fourth turn recovering an exact match total past rtk's 200-result cap, where only the uncapped summary header carries the truth.

Generated-By: PostHog Code
Task-Id: 5330cf5e-2ca2-4f33-82e9-173dd4a01af6
… bench facts, rg flag normalization

Review found the segment splitter treats ; and && inside heredoc bodies and $(...) substitutions as separators, rewriting text that is document content or programmatically consumed output; the bench fidelity facts accepted any numeric summary; and rtk intercepts rg -h/--help/-V itself, changing command meaning.

The splitter now refuses multiline input entirely and tracks paren depth, failing safe on unbalanced parens (case arms included). The rg guard normalizes clustered short flags and =-attached long forms and blocks help/version, mirrored into the Codex guidance. Bench facts are now exact values derived from raw output (match totals for anchored patterns, per-file git status facts, full passthrough line presence for under-cap rg), stderr counts toward token cost, temp paths are per-run private dirs with an upfront shim probe, and the baseline ref falls back to origin/main. Also strips shell escapes in find token guards and guards e2e cleanup against partial setup.

Generated-By: PostHog Code
Task-Id: 5330cf5e-2ca2-4f33-82e9-173dd4a01af6
@MattPua MattPua changed the title feat(autoresearch): extend RTK bash rewrite to chains, guarded find, and rg feat(autoresearch): expand Claude RTK rewriting for chains, guarded find, and rg Jul 23, 2026
MattPua added 2 commits July 23, 2026 17:57
Generated-By: PostHog Code
Task-Id: b24a0c15-8e64-4fd4-a9eb-b8528f3bb9f4
Generated-By: PostHog Code
Task-Id: b24a0c15-8e64-4fd4-a9eb-b8528f3bb9f4
@MattPua
MattPua marked this pull request as ready for review July 23, 2026 22:13
@greptile-apps

greptile-apps Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "chore(agent): clarify RTK benchmark scop..." | Re-trigger Greptile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant