claude-code-token-optimization-by-tool-call 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +359 -2
- package/SPEC.md +230 -0
- package/bin/hook.mjs +20 -0
- package/bin/mcp.mjs +100 -0
- package/bin/run.mjs +79 -0
- package/package.json +58 -4
- package/src/clean.mjs +92 -0
- package/src/exec.mjs +241 -0
- package/src/extract.mjs +319 -0
- package/src/format.mjs +232 -0
- package/src/hook.mjs +321 -0
- package/src/index.mjs +5 -0
- package/src/parsers/docker.mjs +37 -0
- package/src/parsers/eslint.mjs +61 -0
- package/src/parsers/generic.mjs +71 -0
- package/src/parsers/git.mjs +47 -0
- package/src/parsers/go.mjs +53 -0
- package/src/parsers/index.mjs +36 -0
- package/src/parsers/jest-vitest.mjs +95 -0
- package/src/parsers/nextjs-build.mjs +32 -0
- package/src/parsers/npm-pnpm.mjs +25 -0
- package/src/parsers/playwright.mjs +56 -0
- package/src/parsers/prettier.mjs +36 -0
- package/src/parsers/python.mjs +69 -0
- package/src/parsers/rust.mjs +53 -0
- package/src/parsers/tap.mjs +83 -0
- package/src/parsers/tsc.mjs +55 -0
- package/src/parsers/util.mjs +52 -0
- package/src/warnings.mjs +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ibrahim-bayer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,360 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Claude Code token optimization: keep shell output out of the context window
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**run-tool** cuts the tokens AI coding agents spend reading shell output. It is a zero-dependency Node.js command runner that ships as a **Claude Code hook**, an **MCP server** and a CLI.
|
|
4
|
+
|
|
5
|
+
- **Success:** a passing test, build, install, lint or `git push` returns one line instead of hundreds.
|
|
6
|
+
- **Failure:** a failing one returns a **deterministic error extract**: the failing tests, compiler errors and stack frames that matter, with `L<a>-L<b>` line references into the full log on disk. It uses no LLM summary, so there is no extra model call and no invented error text.
|
|
7
|
+
|
|
8
|
+
> Built by [IB Group](https://ibgroup.dev) while developing [LeanCart](https://leancart.global), and used there in day-to-day agent-driven development.
|
|
9
|
+
|
|
10
|
+
**Keywords:** Claude Code, Claude Code hooks, PreToolUse hook, MCP server, token optimization, context window, context engineering, AI coding agent, LLM cost reduction, test output summarizer, error extraction, jest, vitest, tsc, eslint, pytest, cargo, go test.
|
|
11
|
+
|
|
12
|
+
## Why
|
|
13
|
+
|
|
14
|
+
- **Tool output is paid for many times.** A coding agent re-reads its whole context on every API call. So 8,000 tokens of passing-lint output, printed once, is paid for again on each of the next dozens of calls.
|
|
15
|
+
- **How much it is:** in 14 days of real agent sessions on a large TypeScript monorepo (the LeanCart codebase), Bash output took about **27% of all input tokens**.
|
|
16
|
+
- **Executors are the target, reads are not.** Reads (`cat`, `grep`, `git diff`) are the agent's work and must stay untouched. Executors (tests, builds, installs, lint, typecheck, git writes) mostly need one fact: did it pass? When they fail, the agent needs the failure, not the 400 lines of logger noise around it.
|
|
17
|
+
|
|
18
|
+
## Quick start
|
|
19
|
+
|
|
20
|
+
Requires Node.js >= 20. There are no dependencies and nothing to build.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install -g claude-code-token-optimization-by-tool-call # run-tool, run-tool-hook, run-tool-mcp on PATH
|
|
24
|
+
npm install claude-code-token-optimization-by-tool-call # as a library (see Library)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Or from source: `git clone https://github.com/ibrahim-bayer/claude-code-token-optimization-by-tool-call.git && cd claude-code-token-optimization-by-tool-call && node --test test/`.
|
|
28
|
+
|
|
29
|
+
**Claude Code hook (recommended).** The hook rewrites the agent's own Bash calls, so you need no new tool and no prompt changes. Add this to `~/.claude/settings.json` or the project's `.claude/settings.json`:
|
|
30
|
+
|
|
31
|
+
```json
|
|
32
|
+
{
|
|
33
|
+
"hooks": {
|
|
34
|
+
"PreToolUse": [
|
|
35
|
+
{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "run-tool-hook" }] }
|
|
36
|
+
]
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**MCP server** (any MCP-capable agent):
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
claude mcp add run-tool -- run-tool-mcp
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**CLI:**
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
run-tool -- npm test
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## What the agent sees (illustrative)
|
|
54
|
+
|
|
55
|
+
```
|
|
56
|
+
$ npm test # 71 passing tests, 400 lines of logger output
|
|
57
|
+
0 (exit 0; 412 lines of output hidden by run-tool; log=/home/me/.cache/run-tool/logs/…-npm-test.log)
|
|
58
|
+
|
|
59
|
+
$ npx tsc --noEmit # short failure: the whole output, nothing added
|
|
60
|
+
exit=2
|
|
61
|
+
src/shipping.ts(26,7): error TS2322: Type 'string' is not assignable to type 'number'.
|
|
62
|
+
|
|
63
|
+
$ npx jest # long failure: the failing tests, not the noise
|
|
64
|
+
exit=1 profile=jest-vitest lines=1243 log=/home/me/.cache/run-tool/logs/…-npx-jest.log
|
|
65
|
+
L212-L230:
|
|
66
|
+
● Cart › merging a guest cart sums the quantities of shared items
|
|
67
|
+
- Expected - 1
|
|
68
|
+
+ Received + 1
|
|
69
|
+
…
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Measured results
|
|
73
|
+
|
|
74
|
+
The results are reported in full, including the parts that did not go our way.
|
|
75
|
+
|
|
76
|
+
**Live commands, output not piped** (a NestJS service, the way an agent runs them when it does not filter output itself):
|
|
77
|
+
|
|
78
|
+
| | Plain Bash | run-tool |
|
|
79
|
+
|---|---|---|
|
|
80
|
+
| 7 successful commands (install, build, tsc, eslint, jest, nest, node --test) | 17,791 tokens | 0 tokens |
|
|
81
|
+
| 7 failing commands | 16,935 tokens | 3,188 tokens (−81%) |
|
|
82
|
+
|
|
83
|
+
- **Long failures** shrink the most: eslint 8,571 → 361 tokens, jest 7,075 → 1,600.
|
|
84
|
+
- **Short failures** come back whole, at the same size as plain Bash.
|
|
85
|
+
|
|
86
|
+
**A/B test with real Claude Code sessions.** The task was "make CI green and commit" on a TypeScript project, run three times with the hook and three times without, using Sonnet 5.5. Every run solved the task, checked independently.
|
|
87
|
+
|
|
88
|
+
| | Input tokens per session | Turns | Bash output chars |
|
|
89
|
+
|---|---|---|---|
|
|
90
|
+
| without hook | 527k / 467k / 409k (mean 468k) | 10 | 32.4k |
|
|
91
|
+
| with hook | 390k / 385k / 377k (mean 384k) | 8 | 27.8k (−14%) |
|
|
92
|
+
|
|
93
|
+
- **The test is noisy.** A control arm whose hook wrapped nothing also came out 12% below the baseline. With 3 runs per arm, the session-level difference is within noise. The direct effect is the −14% in Bash output.
|
|
94
|
+
- **Modern agents already filter their own output** (`npm test 2>&1 | tail -80`). For those agents the savings are modest. For agents and projects that don't filter, the savings are large.
|
|
95
|
+
- **A bare `0` confuses an agent that did not ask for it.** It re-ran installs looking for the "missing" output, and one session needed 18 turns. That is why hook mode prints one explanatory line on success.
|
|
96
|
+
|
|
97
|
+
**Replay over 14 days of LeanCart agent sessions** (1,916 executor calls; this codebase's own tooling already compacts output):
|
|
98
|
+
|
|
99
|
+
- Turning successes into a single line saves **0.04%–1.45% of all input tokens**. The range depends on how often the agent later needs the hidden output.
|
|
100
|
+
- The failure extract kept **100% of the identifiers** the agent cited next for short failures, and **86%** for long ones. The misses are mostly CSS classes that coincide with the agent's own new code.
|
|
101
|
+
|
|
102
|
+
## Use it for / don't use it for
|
|
103
|
+
|
|
104
|
+
| Use it | Don't use it |
|
|
105
|
+
|---|---|
|
|
106
|
+
| commands where only pass/fail matters: tests, builds, installs, lint, typecheck, formatters, `git commit/push/fetch/rebase/worktree`, deploys, migrations | reading files or searching code (`cat`, `grep`, `sed`, `head`, `git diff/log/show`) |
|
|
107
|
+
| | commands whose stdout is the data you need (`curl` GET bodies, `kubectl get`, `ls`, `jq`) |
|
|
108
|
+
|
|
109
|
+
## CLI
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
node bin/run.mjs [--show-warning] [--cwd DIR] [--timeout SEC] [--budget CHARS] [--large-output BYTES] -- <command string>
|
|
113
|
+
node bin/run.mjs --last # print the path of the latest log
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
- The command runs as `bash -o pipefail -c <command>`, with stdout and stderr merged in arrival order.
|
|
117
|
+
- The CLI exits with the command's exit code.
|
|
118
|
+
- The default timeout is 600 s. On timeout:
|
|
119
|
+
- The whole process group gets SIGTERM, then SIGKILL 5 s later.
|
|
120
|
+
- The exit code is 124 and the header ends in ` timeout`.
|
|
121
|
+
- A command killed by a signal exits with 128 + signo.
|
|
122
|
+
|
|
123
|
+
Success:
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
$ node bin/run.mjs -- npm test
|
|
127
|
+
0
|
|
128
|
+
$ node bin/run.mjs --show-warning -- npm run build
|
|
129
|
+
0
|
|
130
|
+
warnings: 7 (2 unique) log=/home/me/.cache/run-tool/logs/20261205T101500-4242-npm-run-build.log
|
|
131
|
+
L12: (node:4242) DeprecationWarning: punycode is deprecated
|
|
132
|
+
6× L40,L41,L77,…: src/a.ts:N:N warning Unexpected any @typescript-eslint/no-explicit-any
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Failure (long output):
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
exit=1 profile=jest-vitest lines=412 log=/home/me/.cache/run-tool/logs/20261205T101533-4250-pnpm-test.log
|
|
139
|
+
L203-L221:
|
|
140
|
+
FAIL src/cart.test.ts > cart > applies discount
|
|
141
|
+
AssertionError: expected 90 to be 81
|
|
142
|
+
❯ src/cart.test.ts:42:19
|
|
143
|
+
...
|
|
144
|
+
|
|
145
|
+
L398-L412:
|
|
146
|
+
Test Files 1 failed | 12 passed (13)
|
|
147
|
+
Tests 1 failed | 140 passed (141)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
To read more of the log, ask for a line range (`sed -n '180,230p' <log>`) rather than the whole file.
|
|
151
|
+
|
|
152
|
+
### Large output warning
|
|
153
|
+
|
|
154
|
+
When the cleaned output is bigger than 100 KB, the result gets one more line, on success and on failure:
|
|
155
|
+
|
|
156
|
+
```
|
|
157
|
+
$ node bin/run.mjs -- pnpm test
|
|
158
|
+
0
|
|
159
|
+
warning: large output: 412 KB, 8210 lines (over 100 KB; ~118k tokens to read whole). Read line ranges of the log, and consider a quieter command (e.g. --silent, a dot reporter). log=/home/me/.cache/run-tool/logs/…-pnpm-test.log
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
- **Why 100 KB:** a log that size costs ~30k tokens or more to read whole, and Claude Code's Bash tool keeps only ~30k chars of a result. The warning tells the reader to read ranges, and tells the user the command is noisy.
|
|
163
|
+
- **Where it goes:** on success, under the `0` line (with the log path, unless that line already names it). On failure, right under the header. On failure it counts toward the budget; with a very small budget it shortens to `warning: large output: 412 KB (~118k tokens)`, or is left out.
|
|
164
|
+
- **Threshold:** `--large-output BYTES`, the `RUN_TOOL_LARGE_OUTPUT_BYTES` env var, or the MCP argument `largeOutputBytes`. `0` turns it off. The exit code never changes.
|
|
165
|
+
|
|
166
|
+
## MCP server
|
|
167
|
+
|
|
168
|
+
`bin/mcp.mjs` is a stdio MCP server (JSON-RPC 2.0, one message per line, protocol `2025-06-18`), written by hand with no SDK. It exposes one tool, `run`:
|
|
169
|
+
|
|
170
|
+
| Argument | Type | Required | Default |
|
|
171
|
+
|---|---|---|---|
|
|
172
|
+
| `command` | string | yes | |
|
|
173
|
+
| `cwd` | string | no | |
|
|
174
|
+
| `showWarning` | boolean | no | `false` |
|
|
175
|
+
| `timeoutSec` | number | no | `600` |
|
|
176
|
+
| `largeOutputBytes` | number | no | `100000` (`0` = off) |
|
|
177
|
+
|
|
178
|
+
It returns `{content:[{type:"text", text}], isError: exit !== 0}`.
|
|
179
|
+
|
|
180
|
+
Registration example (documentation only; nothing in this repo changes your config):
|
|
181
|
+
|
|
182
|
+
```json
|
|
183
|
+
{
|
|
184
|
+
"mcpServers": {
|
|
185
|
+
"run-tool": {
|
|
186
|
+
"command": "node",
|
|
187
|
+
"args": ["/absolute/path/to/run-tool/bin/mcp.mjs"],
|
|
188
|
+
"env": { "RUN_TOOL_LOG_DIR": "/absolute/path/to/logs" }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
With Claude Code: `claude mcp add run-tool -- node /absolute/path/to/run-tool/bin/mcp.mjs`.
|
|
195
|
+
|
|
196
|
+
## Claude Code hook
|
|
197
|
+
|
|
198
|
+
`bin/hook.mjs` is a `PreToolUse` hook. It rewrites the agent's own Bash calls, so the agent needs no new tool and no instructions.
|
|
199
|
+
|
|
200
|
+
```json
|
|
201
|
+
{
|
|
202
|
+
"hooks": {
|
|
203
|
+
"PreToolUse": [
|
|
204
|
+
{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "node /path/to/run-tool/bin/hook.mjs" }] }
|
|
205
|
+
]
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
### What it wraps
|
|
211
|
+
|
|
212
|
+
- **Pipelines are wrapped one at a time.** In `cd app && npm ci && npm test 2>&1 | tail -40; git log -1`, only `npm ci` and `npm test 2>&1 | tail -40` go through run. The `cd` and the `git log` stay in the outer shell.
|
|
213
|
+
- **A wrapped pipeline:** it starts with an executor (test runner, build, install, lint, typecheck, formatter, git write, docker build, …), and every later stage is a filter (`tail`, `grep`, `head`, …). Under run's pipefail, the executor's exit code decides the result.
|
|
214
|
+
- **Never wrapped:** reads (`cat`, `grep`, `git diff`), unknown programs (`node script.js`, `curl`), and `run_in_background`.
|
|
215
|
+
- **The whole command is left alone** when it has:
|
|
216
|
+
- a `&`;
|
|
217
|
+
- a heredoc;
|
|
218
|
+
- control flow (`for`, `if`, subshells);
|
|
219
|
+
- shell state (`X=…;`, `export`, `source`).
|
|
220
|
+
|
|
221
|
+
A wrapped pipeline runs in a new bash and could not see them.
|
|
222
|
+
- **Output on success:** the hook passes `--explain-success`, so a success prints one line: `0 (exit 0; N lines of output hidden by run-tool; log=…)`. With a bare `0`, an agent that never asked for run took the `0` as the command's own output. It went looking for the real output: it re-ran installs and inspected the package-manager binary.
|
|
223
|
+
- **Timeout:** the Bash tool's `timeout` (default 120 s) becomes `--timeout` minus 5 s, so run kills its process group before the Bash tool gives up. When one command has several wrapped pipelines, each gets that limit on its own. So a long first pipeline can still leave the Bash tool's limit to cut off a later one.
|
|
224
|
+
|
|
225
|
+
### Permissions
|
|
226
|
+
|
|
227
|
+
Claude Code checks permissions against the **rewritten** command (`node …/run.mjs -- '…'`), so your `Bash(npm test:*)` rules no longer match it. The hook therefore works like this:
|
|
228
|
+
|
|
229
|
+
| Mode | What the hook does |
|
|
230
|
+
|---|---|
|
|
231
|
+
| `bypassPermissions` | wraps, and returns no permission decision |
|
|
232
|
+
| `plan` | does nothing |
|
|
233
|
+
| any other mode | wraps only when your settings files allow every stage of the whole command (`cd` and the filters after a wrapped executor need no rule) and no `ask` or `deny` rule matches; it then returns `allow`, otherwise it leaves the command alone |
|
|
234
|
+
|
|
235
|
+
- **What the hook reads:** the managed settings, the user settings, and the project's `settings.json` and `settings.local.json`. Rules given only with `--allowedTools` on the command line are invisible to it.
|
|
236
|
+
- **Switches:**
|
|
237
|
+
- `RUN_TOOL_HOOK=off` disables the hook.
|
|
238
|
+
- `RUN_TOOL_HOOK=always` wraps without a permission decision. Use it only where your permission setup already allows the rewritten command.
|
|
239
|
+
- `RUN_TOOL_HOOK_EXTRA=<regex>` marks more commands as executors, e.g. `^\./scripts/ci\.sh`.
|
|
240
|
+
|
|
241
|
+
## Library
|
|
242
|
+
|
|
243
|
+
Other tools import the same pieces instead of keeping their own ANSI regex or tail logic:
|
|
244
|
+
|
|
245
|
+
```js
|
|
246
|
+
import { clean, tailLines, headLines, extract, largeOutput, run } from 'claude-code-token-optimization-by-tool-call';
|
|
247
|
+
|
|
248
|
+
const text = clean(rawCiLog); // ANSI, CI markers, \r redraws, control chars
|
|
249
|
+
const last120 = tailLines(text, 120); // the last 120 lines
|
|
250
|
+
const shown = headLines(lines, 60, (k) => `… ${k} more lines in the log`);
|
|
251
|
+
const big = largeOutput(text); // null, or { bytes, lines, tokens, threshold }
|
|
252
|
+
const summary = extract(text, { exitCode: 1, logPath });
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
| Export | What it does |
|
|
256
|
+
|---|---|
|
|
257
|
+
| `clean(text)` | strip ANSI and CI markers, resolve `\r`, drop control chars; lines stay 1:1 |
|
|
258
|
+
| `stripAnsi`, `stripCiMarkers`, `resolveCR`, `toLines`, `cutLine` | the steps of `clean`, and line splitting |
|
|
259
|
+
| `tailLines(textOrLines, n)` | the last `n` lines |
|
|
260
|
+
| `headLines(lines, max, more?)` | at most `max` lines, the last one saying how many were left out |
|
|
261
|
+
| `extract(text, opts)` | the run result text (`0`, or the failure extract) |
|
|
262
|
+
| `outputSize(text)`, `largeOutput(text, threshold?)`, `largeOutputLine`, `largeOutputThreshold(env)` | the large-output check |
|
|
263
|
+
| `run(command, opts)` | spawn, time out, write the cleaned log; returns `{ exitCode, timedOut, logPath, text, lines }` |
|
|
264
|
+
| `hookDecision(event, opts)` | the hook's decision, for a host with its own hook runner |
|
|
265
|
+
|
|
266
|
+
## Logs
|
|
267
|
+
|
|
268
|
+
- **Location:** `$RUN_TOOL_LOG_DIR`, or `~/.cache/run-tool/logs/` when that is unset.
|
|
269
|
+
- **File name:** `<YYYYMMDDTHHMMSS>-<pid>-<slug>.log`, where the slug comes from the first 40 chars of the command.
|
|
270
|
+
- **`last`:** a file in the same directory that holds the latest log path.
|
|
271
|
+
- **Contents:** the *cleaned* output. ANSI escapes and GitLab CI `section_start`/`section_end` markers are stripped, and `\r` progress redraws are resolved. Lines are never collapsed or cut, so line N of the file is exactly what the extract calls `L<N>`.
|
|
272
|
+
- **Cap:** when the cleaned output exceeds 20 MB, the log keeps the first 2 MB and the last 18 MB, with one marker line in between: `[run-tool: log capped, N lines (B bytes) omitted here; line numbers below are shifted]`.
|
|
273
|
+
- **Line numbers after the marker shift:** `L<N>` still matches line N of the *file*, but no longer matches the command's original line N.
|
|
274
|
+
- The extract is computed from the capped text, so its references stay consistent with the file.
|
|
275
|
+
- **Retention**, on every run:
|
|
276
|
+
1. Delete logs older than 7 days.
|
|
277
|
+
2. Then delete the oldest logs until the directory is at most 200 MB.
|
|
278
|
+
|
|
279
|
+
## Output format
|
|
280
|
+
|
|
281
|
+
The header is always the first line on failure:
|
|
282
|
+
|
|
283
|
+
```
|
|
284
|
+
exit=<code> profile=<parser|generic|short> lines=<total log lines> log=<path>[ timeout]
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
A short failure (whole output returned) has the header `exit=<code>[ timeout]` only: the log path would add ~100 chars to most failures and tell the reader nothing new. A long failure keeps the absolute log path, since file-read tools do not expand `~`.
|
|
288
|
+
|
|
289
|
+
- **Short body:** 60 lines or fewer and within the budget. The text comes back whole, with consecutive duplicates collapsed to `line (×N)`.
|
|
290
|
+
- **Long body:** `L<a>-L<b>:` blocks in log order, separated by blank lines. The budget is 6000 chars by default; the header does not count toward it. The body is filled in this order:
|
|
291
|
+
1. **The tail:** the last 15 non-empty lines, at most 1500 chars. It is always included.
|
|
292
|
+
2. **Parser blocks** from the winning parser, ordered by priority (summary lines and final tracebacks rank higher), then earliest first. When another parser wins, npm/pnpm blocks are added next.
|
|
293
|
+
3. **Generic error-regex hits** that are not already covered.
|
|
294
|
+
4. **Context fill** (an extension; see below).
|
|
295
|
+
5. If anything was dropped: `… +K more blocks (L…, L…) — see log`.
|
|
296
|
+
|
|
297
|
+
Shaping inside the blocks:
|
|
298
|
+
|
|
299
|
+
- A message repeated across blocks is shown once as `(×N, also L…)`.
|
|
300
|
+
- Stack traces keep at most 3 project frames; the rest become `(+N frames)`.
|
|
301
|
+
- Runs of git `hint:` lines fold to 2.
|
|
302
|
+
- Lines over 400 chars are cut to `…(+N chars)`.
|
|
303
|
+
|
|
304
|
+
## Parsers
|
|
305
|
+
|
|
306
|
+
Each parser in `src/parsers/` exports `{name, detect(lines), blocks(lines)}`. The one with the highest `detect` score of at least 0.5 wins.
|
|
307
|
+
|
|
308
|
+
- Detection reads the output only.
|
|
309
|
+
- The command matters only as a tie-break between scores within 0.05 of each other, through each parser's `hint` regex.
|
|
310
|
+
|
|
311
|
+
The parsers are tap, jest-vitest, playwright, tsc, eslint, nextjs-build, python, go, rust, npm-pnpm, docker, git, prettier and generic.
|
|
312
|
+
|
|
313
|
+
## Design decisions beyond the spec
|
|
314
|
+
|
|
315
|
+
- **Context fill.** If budget remains after the parser and generic blocks, two more steps run:
|
|
316
|
+
1. Add the head of the output: the first 10 non-empty lines, at most 1000 chars.
|
|
317
|
+
2. Add whole gaps between the selected blocks, smallest first.
|
|
318
|
+
|
|
319
|
+
Context never includes warning lines, or lines the winning parser marks as noise, such as eslint warning rows or git hints. On the dev corpus this step lifts long-bucket recall from 0.86 to 0.96, because agents often cite identifiers from lines near an error that no rule marks as one.
|
|
320
|
+
- **Light normalisation for cross-block dedupe.** Only volatile numbers are masked: hex ids, timestamps, `line:col`, durations, and decimals of 3+ digits. Messages that differ by a count or an index stay distinct.
|
|
321
|
+
- **Tail lines are pinned.** Cross-block dedupe never removes a tail line, so the summary is always visible.
|
|
322
|
+
- **Long-line cut only when rendering.** The log keeps full lines, so that `L` references and `sed -n` reads return the real text.
|
|
323
|
+
- **Frame folding without project frames.** When a trace has no project frames, its first frame is kept so the throw site stays visible.
|
|
324
|
+
- **The `prettier` parser** is extra: `[warn] file` lists and `[error]` blocks are common, and generic handles them poorly.
|
|
325
|
+
- **Library frames** follow the spec's list, plus `<frozen …>` and `/usr/lib/python`.
|
|
326
|
+
- `node:child_process` and similar `node:` modules outside `node:internal` count as project frames.
|
|
327
|
+
|
|
328
|
+
## Development
|
|
329
|
+
|
|
330
|
+
```
|
|
331
|
+
node --test test/ # unit, fixture, exec, mcp and cli tests
|
|
332
|
+
node scripts/replay.mjs # recall/budget metrics over fixtures/corpus-dev.jsonl (gitignored)
|
|
333
|
+
node scripts/replay.mjs --show <id> # print one record's extract
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
The test fixtures in `test/fixtures/` are synthetic. A line `@@NOISE n template@@` expands to n generated lines (see `test/helpers.mjs`).
|
|
337
|
+
|
|
338
|
+
## Changes after independent review
|
|
339
|
+
|
|
340
|
+
Found by testing on a held-out transcript half and live commands, not by the builder's own tests:
|
|
341
|
+
|
|
342
|
+
- **Markup dumps fold.** Testing Library `<body>` dumps (8+ markup lines) collapse to their first 2 lines plus `(+N lines of markup, La-Lb; rendered: "text" #testid …)`. The tags and classes are dropped; rendered text nodes and `data-testid` values are kept, because that is what a reader uses from a dump.
|
|
343
|
+
- **eslint context fill.** Warning-only files no longer come back through the context fill: they used to fill a 6000-char budget with 120 file headers. eslint rows have their column padding squeezed. Code frames keep their spacing, so carets still point at the right column.
|
|
344
|
+
- **`showWarning` on failure.** It now also applies on failure. The warnings section takes up to 25% of the budget.
|
|
345
|
+
- **Binary output.** Output containing a NUL byte, or with more than 10% U+FFFD, renders as `[binary output: N chars, not shown; see log]`.
|
|
346
|
+
- **Missing `--cwd`.** It reports `cwd does not exist: <dir>` instead of `spawn bash ENOENT`.
|
|
347
|
+
|
|
348
|
+
## About
|
|
349
|
+
|
|
350
|
+
run-tool was built by **[IB Group](https://ibgroup.dev)**, the team behind **[LeanCart](https://leancart.global)**.
|
|
351
|
+
|
|
352
|
+
- **LeanCart:** a multi-tenant e-commerce SaaS platform built for zero-developer store management.
|
|
353
|
+
- **How LeanCart is developed:** largely with AI coding agents. That workflow made token cost and context-window size a daily engineering concern, and this tool came out of it.
|
|
354
|
+
- **How it was built:** the tool itself was built by a coding agent from [SPEC.md](SPEC.md). It was then reviewed, measured on held-out agent sessions and hardened by hand.
|
|
355
|
+
|
|
356
|
+
Want to build a product with AI-assisted engineering, or to run an e-commerce store without a developer team? Visit [ibgroup.dev](https://ibgroup.dev) and [leancart.global](https://leancart.global).
|
|
357
|
+
|
|
358
|
+
## License
|
|
359
|
+
|
|
360
|
+
[MIT](LICENSE) © ibrahim-bayer
|
package/SPEC.md
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# run-tool — specification
|
|
2
|
+
|
|
3
|
+
This is the contract the tool was built from: a coding agent (`claude -p`, non-interactive) implemented it, then the result was reviewed, tested on held-out data and fixed by hand (see README § Changes after independent review).
|
|
4
|
+
|
|
5
|
+
A command runner for coding agents that keeps command output out of the model's context.
|
|
6
|
+
Success returns `0`. Failure returns a deterministic extract of the error, never a model summary.
|
|
7
|
+
The full output always goes to a log file on disk, and the extract points into it by line number.
|
|
8
|
+
|
|
9
|
+
It is a general tool: it must work for any project and language, not just one repo.
|
|
10
|
+
|
|
11
|
+
## Why (measured, so you know what matters)
|
|
12
|
+
|
|
13
|
+
Over 14 days of real agent sessions, Bash output took about 27% of all input tokens.
|
|
14
|
+
|
|
15
|
+
- Reads (`cat`, `grep`, `sed`, `git diff`) make up 18% of that. Their output IS the work, so this tool must never be used for them.
|
|
16
|
+
- Executor commands (test, build, install, lint, typecheck, git write, deploy, curl) are the target.
|
|
17
|
+
- Failed executor outputs are usually short (median about 25 lines). Long ones are where extraction matters.
|
|
18
|
+
- A naive error regex finds nothing in 55% of failures. It also produces false positives, such as a React "hydration error" warning on stderr while the real failure is the summary line at the end.
|
|
19
|
+
- The summary line ("Tests 2 failed | 11 passed") is almost always among the last lines.
|
|
20
|
+
|
|
21
|
+
## Hard constraints
|
|
22
|
+
|
|
23
|
+
- Node >= 20, ESM (`.mjs`), **zero npm dependencies**, nothing installed from the network.
|
|
24
|
+
- Tests use `node --test`; run them with `node --test test/`.
|
|
25
|
+
- Work only inside the repository. Do not read or write anything outside it, except temp dirs your tests create under `os.tmpdir()`.
|
|
26
|
+
- `fixtures/corpus-dev.jsonl` holds real agent-session data and is not published. It is gitignored: never commit it, and never copy its contents into committed test fixtures verbatim (write synthetic fixtures modelled on what you see).
|
|
27
|
+
- Commit your work in small commits.
|
|
28
|
+
|
|
29
|
+
## Layout
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
bin/run.mjs CLI
|
|
33
|
+
bin/mcp.mjs MCP stdio server exposing one tool: run
|
|
34
|
+
src/exec.mjs spawn, merge streams, timeout, log file, retention
|
|
35
|
+
src/clean.mjs ANSI strip, \r resolution, long-line cut
|
|
36
|
+
src/extract.mjs extract(text, opts) -> string (pure, no I/O)
|
|
37
|
+
src/warnings.mjs extractWarnings(text, opts) -> string (pure, no I/O)
|
|
38
|
+
src/parsers/<name>.mjs one file per output format
|
|
39
|
+
src/format.mjs block rendering, dedupe, stack-frame folding, budget
|
|
40
|
+
scripts/replay.mjs replay fixtures/corpus-dev.jsonl and print the metrics below
|
|
41
|
+
test/ node:test files + synthetic fixtures
|
|
42
|
+
README.md usage, MCP registration example (documentation only)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Execution contract (src/exec.mjs)
|
|
46
|
+
|
|
47
|
+
- Run `bash -o pipefail -c <command>` with `stdin` ignored, `cwd` = option or `process.cwd()`, and the env inherited.
|
|
48
|
+
- Merge stdout and stderr into **one stream, in arrival order**.
|
|
49
|
+
- Use a new process group (`detached: true`). On timeout send SIGTERM to the group, then SIGKILL after 5 s. A timeout reports exit code **124** with the flag `timeout`. Any other death by signal reports exit `128 + signo`.
|
|
50
|
+
- Write the log as the **cleaned** text (see clean.mjs) to `$RUN_TOOL_LOG_DIR`, or `~/.cache/run-tool/logs/` when that is unset.
|
|
51
|
+
- File name: `<YYYYMMDDTHHMMSS>-<pid>-<slug of first 40 chars of command>.log`.
|
|
52
|
+
- Line N of the log file must equal line N that the extract refers to as `L<N>`. Test this with real files.
|
|
53
|
+
- Log cap: when cleaned output exceeds 20 MB, keep the first 2 MB and the last 18 MB with one marker line in between. Document that line numbers after the marker shift.
|
|
54
|
+
- Retention, run on every invocation: delete logs older than 7 days, then delete the oldest until the directory is at most 200 MB.
|
|
55
|
+
- Write `last` (a text file containing the latest log path) in the log dir. `run --last` prints it.
|
|
56
|
+
|
|
57
|
+
## Clean contract (src/clean.mjs)
|
|
58
|
+
|
|
59
|
+
- Strip ANSI/VT escape sequences (CSI, OSC, and single-char escapes).
|
|
60
|
+
- For each line, keep only the text after the last bare `\r` (progress bars). `\r\n` is a normal newline.
|
|
61
|
+
- Do not collapse duplicates here: the log must keep 1:1 lines.
|
|
62
|
+
|
|
63
|
+
## Output contract
|
|
64
|
+
|
|
65
|
+
### Success (exit 0)
|
|
66
|
+
|
|
67
|
+
- When `showWarning` is false: exactly `0`. Nothing else, not even the log path. The CLI prints `0\n`.
|
|
68
|
+
- When `showWarning` is true and there are no warnings: exactly `0`.
|
|
69
|
+
- When `showWarning` is true and there are warnings:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
0
|
|
73
|
+
warnings: <N> (<U> unique) log=<path>
|
|
74
|
+
L12: <line>
|
|
75
|
+
3× L40,L77,L91: <normalised line>
|
|
76
|
+
… +<K> more unique warnings
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
- Warning detection: lines matching `\bwarn(ing)?\b`, `WARN`, `deprecat`, and `⚠`, case-insensitive.
|
|
80
|
+
- Exclude lines like `0 warnings`, and `--warning` flags echoed in commands.
|
|
81
|
+
- Group by a normalised form: digits become `N`, hex runs of 6 or more characters become `H`, and line:col pairs become `N:N`.
|
|
82
|
+
- Cap the warnings section at the budget.
|
|
83
|
+
|
|
84
|
+
### Failure (exit != 0)
|
|
85
|
+
|
|
86
|
+
Header line, always first:
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
exit=<code> profile=<parser name|generic|short> lines=<total log lines> log=<path>[ timeout]
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
A short failure (whole output returned) has the header `exit=<code>[ timeout]` only: the log path would add ~100 chars to most failures and tell the reader nothing new. A long failure keeps the absolute log path, since file-read tools do not expand `~`.
|
|
93
|
+
|
|
94
|
+
Then one of two bodies.
|
|
95
|
+
|
|
96
|
+
1. **Short**: the cleaned text has 60 lines or fewer AND is within the budget. Return it whole, after consecutive-duplicate collapse. This is `profile=short`, with no `L` prefixes. An empty output is fine: the header alone.
|
|
97
|
+
2. **Long**: return blocks in log order.
|
|
98
|
+
|
|
99
|
+
```
|
|
100
|
+
L<a>-L<b>:
|
|
101
|
+
<lines>
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Blocks are separated by one blank line. When something was dropped, the last line reads:
|
|
105
|
+
|
|
106
|
+
```
|
|
107
|
+
… +<K> more blocks (<first few L-ranges>) — see log
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### Budget and priority (long body)
|
|
111
|
+
|
|
112
|
+
- `budgetChars` defaults to 6000 (about 1500 tokens). The body must never exceed it; the header is not counted. Test this as a property over all fixtures.
|
|
113
|
+
- Fill in this order:
|
|
114
|
+
1. **Reserve the tail**: the last 15 non-empty lines of the output, about 1500 chars at most. This is always included.
|
|
115
|
+
2. **Parser blocks**, earliest first: the root cause is usually the first error. Stop adding when the budget is spent.
|
|
116
|
+
3. **Generic hits**, only if no parser matched, or if budget remains and the generic hits are not already covered.
|
|
117
|
+
- Overlapping or adjacent blocks merge.
|
|
118
|
+
|
|
119
|
+
### Shaping inside blocks (src/format.mjs)
|
|
120
|
+
|
|
121
|
+
- **Consecutive identical lines**: `<line> (×N)`.
|
|
122
|
+
- **Repeated messages across blocks**: when the same normalised message appears more than once, show it once with `(×N, also L…)`.
|
|
123
|
+
- **Stack frames**:
|
|
124
|
+
- Folding: keep at most 3 project frames per trace, and replace the rest with ` (+N frames)`.
|
|
125
|
+
- Node frames are lines matching `^\s+at `. Python frames are `File "...", line N` lines plus the line after each.
|
|
126
|
+
- A frame is a library frame when it contains `node_modules`, `node:internal`, `internal/`, `site-packages`, or `<anonymous>`. Library frames are dropped first.
|
|
127
|
+
- **Long lines**: a line over 400 chars is cut to 400 and followed by `…(+N chars)`.
|
|
128
|
+
|
|
129
|
+
## Parsers (src/parsers/)
|
|
130
|
+
|
|
131
|
+
Each parser exports `{ name, detect(lines): number (0..1 confidence), blocks(lines): [{start, end, priority}] }`, where `start` and `end` are 0-based inclusive.
|
|
132
|
+
|
|
133
|
+
- The parser with the highest `detect` score of at least 0.5 wins.
|
|
134
|
+
- Detect from the **output content**, never from the command name. The command is only a tie-break hint.
|
|
135
|
+
- More than one format can appear in one output, for example pnpm wrapping vitest. Let the winner run first, then add the `npm/pnpm` blocks.
|
|
136
|
+
|
|
137
|
+
Required parsers:
|
|
138
|
+
|
|
139
|
+
| name | detect signals | blocks |
|
|
140
|
+
|---|---|---|
|
|
141
|
+
| tap | `TAP version`, `^\s*not ok \d+` | each `not ok` line plus its indented YAML up to `...`, and the `# fail N` / `# pass` summary |
|
|
142
|
+
| jest-vitest | `FAIL `, `●`, `×`/`✗`, `Test Files`, `Tests:` | each failing test block (from the `●`/`FAIL`/`×` line to the next test header or a blank-blank), and the summary lines |
|
|
143
|
+
| playwright | `✘`, `\d+ failed` with `[chromium]`, `Error: expect(` | each failed test block plus the summary |
|
|
144
|
+
| tsc | `\(\d+,\d+\): error TS\d+` or `:\d+:\d+ - error TS\d+` | each error line plus its continuation lines (indented, or the code frame with `~~~`) |
|
|
145
|
+
| eslint | file header line, then `^\s+\d+:\d+\s+error` | error lines with their file header; skip `warning` rows on failure |
|
|
146
|
+
| nextjs-build | `Failed to compile`, `Type error:`, `Build error occurred` | from the marker to the next blank-blank, or 25 lines |
|
|
147
|
+
| python | `Traceback (most recent call last)`, `^\w+Error:`, pytest `FAILED`, `=+ FAILURES =+` | the last traceback block, the pytest failure sections, and the summary line |
|
|
148
|
+
| go | `--- FAIL`, `^FAIL\t`, `panic:` | each `--- FAIL` block, and the panic plus first goroutine frames |
|
|
149
|
+
| rust | `error\[E\d+\]`, `^error:`, `test result: FAILED` | from each `error[..]`/`error:` to the blank line, `failures:` sections |
|
|
150
|
+
| npm-pnpm | `npm ERR!`, `ERR_PNPM_`, ` ELIFECYCLE`, `ERR! code` | those lines plus the 3 lines before each, deduped |
|
|
151
|
+
| docker | `ERROR [`, `------`, `failed to solve` | each `------`-fenced block, and the `ERROR:` lines |
|
|
152
|
+
| git | `^fatal:`, `^error:`, `CONFLICT`, `! \[rejected\]`, `hint:` | those lines (`hint:` lines folded to 2) |
|
|
153
|
+
| generic | always 0.1 | an error regex hit with context −2/+5, merged |
|
|
154
|
+
|
|
155
|
+
The generic regex must include: `\berror\b`, `ERR!`, `\bfatal\b`, `\bpanic\b`, `Exception`, `Traceback`, `\bFAIL(ED)?\b`, `✕✗✘×`, `AssertionError`, `^not ok\b`, `Cannot find`, `No such file`, `command not found`, `Permission denied`, `ENOENT`, `EACCES`, `ECONNREFUSED`, `timed out`, `exit(ed)? (with )?code [1-9]`.
|
|
156
|
+
|
|
157
|
+
The negative list (a line matching it is never a hit) includes: `\b0 errors?\b`, `\bno errors?\b`, `warning`, `deprecat`, `hydration`, `--error`, `errorCode`/`ErrorCode` identifiers in source-looking lines, and `error\.(ts|js|tsx)` file names in listings.
|
|
158
|
+
|
|
159
|
+
## CLI (bin/run.mjs)
|
|
160
|
+
|
|
161
|
+
```
|
|
162
|
+
run [--show-warning] [--cwd DIR] [--timeout SEC] [--budget CHARS] -- <command string>
|
|
163
|
+
run --last
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
- The process exit code equals the command's exit code. The extract goes to stdout.
|
|
167
|
+
- The default timeout is 600 s.
|
|
168
|
+
|
|
169
|
+
## MCP server (bin/mcp.mjs)
|
|
170
|
+
|
|
171
|
+
- Use stdio, JSON-RPC 2.0 with one JSON message per line, and protocolVersion `2025-06-18`. Implement it by hand: no SDK.
|
|
172
|
+
- Handle `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call`. Unknown methods return error `-32601`.
|
|
173
|
+
- Tool `run`, inputSchema:
|
|
174
|
+
- `command` (string, required)
|
|
175
|
+
- `cwd` (string)
|
|
176
|
+
- `showWarning` (boolean, default false)
|
|
177
|
+
- `timeoutSec` (number, default 600)
|
|
178
|
+
- Result: `{content:[{type:"text", text}], isError: exit !== 0}`.
|
|
179
|
+
- The tool description must tell the model when to use it and when not to (keep it short):
|
|
180
|
+
- **Use** it for commands where only pass/fail matters: tests, builds, installs, lint, typecheck, formatters, git commit/push/fetch/rebase/worktree, deploys, migrations.
|
|
181
|
+
- **Do not use** it to read files or search code (`cat`, `grep`, `sed`, `head`, `git diff/log/show`), or when the command's stdout is the data you need (`curl` GET bodies, `kubectl get`, `ls`, `jq`). Use the normal shell for those.
|
|
182
|
+
- On failure it returns an extract with `L` line ranges. Read more of the log by line range (`sed -n 'A,Bp' <log>`), never the whole log.
|
|
183
|
+
|
|
184
|
+
## Tests (must pass)
|
|
185
|
+
|
|
186
|
+
- **exec**:
|
|
187
|
+
- `false | cat` gives exit 1 (pipefail).
|
|
188
|
+
- Stderr is captured, and interleaved with stdout in order (`echo a; echo b >&2; echo c`).
|
|
189
|
+
- Timeout gives exit 124 with the `timeout` flag, and leaves no orphan child (`sleep 100 & wait`).
|
|
190
|
+
- A signal gives 128+n.
|
|
191
|
+
- Log retention by age and size works (use a temp log dir).
|
|
192
|
+
- The log line numbers match the `L` refs.
|
|
193
|
+
- **clean**: ANSI is stripped, progress bars resolve via `\r`, and `\r\n` is preserved.
|
|
194
|
+
- **extract**:
|
|
195
|
+
- One synthetic fixture per parser, asserting that the key error lines are present and the noise lines absent.
|
|
196
|
+
- The budget property holds over every fixture and over `fixtures/corpus-dev.jsonl` failures.
|
|
197
|
+
- The short path returns the text whole.
|
|
198
|
+
- The tail is always present.
|
|
199
|
+
- The vitest-with-hydration-warning case returns the failing test and the summary, not the warning.
|
|
200
|
+
- **warnings**: grouping and counts.
|
|
201
|
+
- **mcp**: spawn `bin/mcp.mjs`, then send initialize, tools/list, and tools/call (one success, one failure) and assert the results.
|
|
202
|
+
|
|
203
|
+
## Replay metric (scripts/replay.mjs) — acceptance
|
|
204
|
+
|
|
205
|
+
For every **failure** record (`exit != 0`) in `fixtures/corpus-dev.jsonl`, where each line is `{id, cls, command, exit, output, next}`:
|
|
206
|
+
|
|
207
|
+
1. Run `extract(output, {exitCode: exit, command, logPath: "/tmp/x.log"})`. Records come from transcripts, so treat `output` as already cleaned.
|
|
208
|
+
2. **Cited identifiers**:
|
|
209
|
+
- Collect every token in `output` matching `/[A-Za-z_@][\w@.\/:-]*\w/g` with length >= 6, or `/\bTS\d{4}\b/`.
|
|
210
|
+
- A token is cited when it also appears as a substring of `next` (the agent's next messages).
|
|
211
|
+
- Exclude tokens that appear in `command`, and tokens found in more than 2% of all corpus outputs (a stop list, computed over the corpus).
|
|
212
|
+
3. **recall** = the share of cited identifiers that also appear in the extract. Count it micro-averaged over identifiers.
|
|
213
|
+
4. Report the following, split into two buckets: `short` (60 lines or fewer, passthrough) and `long` (more than 60):
|
|
214
|
+
- record count
|
|
215
|
+
- number of records with at least one cited identifier
|
|
216
|
+
- micro recall
|
|
217
|
+
- the 10 worst records by recall, with id and missing tokens
|
|
218
|
+
- average chars in vs out
|
|
219
|
+
- the max out/budget ratio
|
|
220
|
+
|
|
221
|
+
Acceptance: `long` recall >= 0.95, the budget is never exceeded, and every test passes. When recall misses, improve the parsers or the generic rules. Do not special-case corpus ids or strings.
|
|
222
|
+
|
|
223
|
+
## Done
|
|
224
|
+
|
|
225
|
+
- Every test passes.
|
|
226
|
+
- `node scripts/replay.mjs` meets acceptance.
|
|
227
|
+
- README written.
|
|
228
|
+
- Work committed.
|
|
229
|
+
|
|
230
|
+
Print a final summary: the files written, the test count, and the replay numbers.
|
package/bin/hook.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Claude Code PreToolUse hook (matcher: Bash). Reads the hook event on stdin;
|
|
3
|
+
// prints a command rewrite for executor commands, nothing otherwise.
|
|
4
|
+
// Any error leaves the command untouched: a broken hook must not block work.
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { decide } from '../src/hook.mjs';
|
|
8
|
+
|
|
9
|
+
const runPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'run.mjs');
|
|
10
|
+
let s = '';
|
|
11
|
+
process.stdin.on('data', (d) => (s += d));
|
|
12
|
+
process.stdin.on('end', () => {
|
|
13
|
+
try {
|
|
14
|
+
const out = decide(JSON.parse(s), { runPath });
|
|
15
|
+
if (out) process.stdout.write(JSON.stringify(out));
|
|
16
|
+
} catch (e) {
|
|
17
|
+
process.stderr.write(`run-tool hook: ${e.message}\n`);
|
|
18
|
+
}
|
|
19
|
+
process.exit(0);
|
|
20
|
+
});
|