diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 0000000..3f2408d --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1,12 @@ +{ + "name": "tokenforge", + "interface": { "displayName": "tokenforge" }, + "plugins": [ + { + "name": "tokenforge", + "source": { "source": "local", "path": "./" }, + "policy": { "installation": "AVAILABLE", "authentication": "ON_INSTALL" }, + "category": "Productivity" + } + ] +} diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 4843ef0..bfde549 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "tokenforge", - "version": "0.9.1", + "version": "0.9.2", "description": "Build big things with far fewer tokens: plan once, then run each task in a small, stateless Claude worker checked by your tests. Includes a token meter, context-growth warnings, and session handoffs.", "author": { "name": "chteau" }, "homepage": "https://github.com/chteau/tokenforge", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json new file mode 100644 index 0000000..77ad8aa --- /dev/null +++ b/.codex-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "tokenforge", + "version": "0.9.2", + "description": "Fewer tokens per task: raw build/test output routed through a compact kit, large MCP results distilled, context-growth warnings, session handoffs and checkpoints.", + "author": { "name": "chteau" }, + "homepage": "https://github.com/chteau/tokenforge", + "repository": "https://github.com/chteau/tokenforge", + "license": "MIT", + "keywords": ["tokens", "cost", "context", "hooks"], + "hooks": "./hooks/hooks.json", + "interface": { + "displayName": "tokenforge", + "shortDescription": "Spend fewer tokens per task", + "developerName": "chteau", + "category": "Productivity", + "websiteURL": "https://github.com/chteau/tokenforge" + } +} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 898fec2..4354840 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -34,6 +34,25 @@ jobs: for i in $(seq 20); do node bin/tforge ui --status | grep -q "running at http://127.0.0.1" && break; sleep 1; done node bin/tforge ui --status | grep "running at http://127.0.0.1" node bin/tforge ui --stop + - name: Proxy and command resolution tests + run: node --test test/proxy.test.mjs test/portable.test.mjs + - name: Proxy daemon + shell: bash + run: | + node bin/tforge proxy --detach --port 7899 + node bin/tforge proxy --status | grep "running on 127.0.0.1:7899" + node bin/tforge proxy --stop + - name: tforge claude through a .cmd shim + shell: bash + run: | + mkdir -p shim + printf '@echo off\r\nnode "%%~dp0check.js" %%*\r\n' > shim/fakeclaude.cmd + echo 'process.exit(process.env.ANTHROPIC_BASE_URL === "http://127.0.0.1:7898" && process.argv[2] === "a \"b\" & %x%" ? 0 : 5)' > shim/check.js + PATH="$PWD/shim:$PATH" TFORGE_CLAUDE=fakeclaude TFORGE_PROXY_PORT=7898 node bin/tforge claude 'a "b" & %x%' + node bin/tforge proxy --stop + - name: Full test suite (informational until it passes on Windows) + continue-on-error: true + run: node --test test/*.test.mjs tmap: strategy: matrix: diff --git a/.gitignore b/.gitignore index de92642..f21e782 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ bench/runs-superseded/ bench/environments/*/template/ bench/results/raw/ __pycache__/ +TODO-private.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 9eaa303..28f016b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,65 @@ # Changelog +## 0.9.2 + +Correctness: a safer answer cache, versioned benchmark figures, memory that survives resume and compaction, and subagent work in snapshots. This replaces a first 0.9.2 attempt that was reverted (be6a5c1): its hooks were never registered, its libraries were never called, and its changelog described work that was not there. + +- Answer cache: only information questions are replayed. A request to run, test, build, verify or deploy, a security question, or a question about the current state ("is it up", "latest", "now", "statut", "en ce moment") always goes to Claude, in English and French; when unsure, it asks Claude. +- Answer cache: a replayed answer must come from the same repository (path and remotes), branch and commit, working tree contents, dependency manifests and lockfiles, terse level and, when known, model. Changes are found by content, not modification time, so same-second edits, renames, deletions and branch switches count. Answers recorded before 0.9.2 are not replayed. +- `!nocache` as the first or last word of a prompt sends it to Claude without looking for an earlier answer. +- French fresh-look words starting with an accent ("vérifie", "à froid") never matched; they do now. +- Bench reports and charts name the TokenForge version, build hash and Claude Code version under every table and figure. A report or chart that mixes versions or builds is refused with the list found; `--mixed-versions` builds it with each row or series labelled. The published benchmark-report.json mixes 3 builds, so rebuilding it needs that flag. +- README: each benchmark figure names the tokenforge and Claude Code versions it was measured with. No figure changed. +- `tforge version` prints the version and the plugin build hash that benchmark runs record (`--json`). +- Resume: SessionStart now also runs on resume. Claude Code keeps the earlier session-start text in the transcript, so the rules are not sent again; only what changed while the session was away is: a newer handoff, a changed state file, or another session's work in this project since. +- Compaction: this session's own compact checkpoint is reloaded after a compaction (before, the newest snapshots of any session). +- `reloadOn` (`TFORGE_RELOAD_ON`) chooses which of `compact` and `resume` reload anything. Default: both. +- Snapshots include subagents. Claude Code writes each subagent's transcript separately, and tokenforge skipped them, though in delegating sessions most tokens are spent there. Each chunk now lists the agents it ran (type, task, files changed, commands, report), the main transcript's sidechain edits count as changed files, and the checkpoint and automatic handoff carry the newest agent lines. +- Automatic handoffs are no longer deleted at the first snapshot of a later session, nor ignored after 72 hours. One is moved to `.forge/handoffs/` (newest 10 kept) once a session that was given it has saved a snapshot of its own, or after 14 days (`TFORGE_HANDOFF_MAX_AGE_H`, now 336). A resumed session is not given its own handoff back. +- `stateFiles` (`TFORGE_STATE_FILES`): globs of files a skill keeps its state in (a review register). Those changed in the last 72 hours are loaded at startup, `/clear` and compaction (8000 characters each, 16000 in all), and on resume when changed since; the generic checkpoint is then left out. Never in subagents. +- An agent with its own definition (a plugin's or your own, not a built-in one) no longer gets the scope, "infer instead of asking" or planning rules, which contradicted agents such as SpecAudit's arbiters. Its definition decides. +- `subagentSkip` (`TFORGE_SUBAGENT_SKIP`): agent types, with `*` wildcards (`spec-audit:*`), that tokenforge leaves alone: no policy, instruction files, Bash router, code redirect, MCP distill or budget notes. +- `leanKeep` (`TFORGE_LEAN_KEEP`): tools lean levels never deny. A rule tokenforge already added for a kept tool is lifted at the next start; `tforge lean status` still reports the level. +- Reloaded snapshots and checkpoints say they are a record of earlier turns, not instructions. +- Workers: a task marked `sensitive` (or every task, and the final check, with `isolateChecks`) runs its check in a temporary git worktree that holds the current edits, so the check's side effects stay out of your checkout. It is removed even on timeout, and refused outside git. +- Plans: a `verify` must be one non-empty line; destructive commands in it (`rm -rf /`, `git push`, `curl | sh`, `sudo`, `mkfs`, `dd` to a device) get a warning in `tforge validate`. +- Bash router, found by new differential tests that run the original and rewritten command: an env prefix with spaces (`FOO="a b" cargo test`) ran a command named `FOO=a b`; `$VARS`, `$(…)`, `~`, globs and braces were quoted into literal text; `| tee log`, `| wc -l` or a redirect after a rewritten test command was dropped; `cat *.txt` through tview did not follow the shell's order. Such commands now run as typed, and only display filters (`head`, `tail`, plain `grep`) may be dropped after a rewrite. +- Check logs: a `FAILED` line right after a compiler warning is no longer cut from what a worker sees. +- `tforge proxy` and `tforge claude`: an optional local API proxy that logs each request's sizes and real usage (`tforge proxy report`) and compresses tool results the first time they are sent: whole-file Reads of code fold long bodies (line numbers kept), Bash output is cleaned and capped with the full text in a file, large JSON is crushed. Compressed results are remembered by tool_use_id so later requests resend the same bytes and the prompt cache holds. Checked with a subscription login; not benchmarked yet. +- `tforge proxy report` shows cache breaks with a probable cause (system prompt, tool definitions or an earlier message changed, or the cache expired) and the tokens written again. It also shows how Edits went on files whose Read was folded (failed edits, reads back into folded bodies). +- When the proxy caps a search result or a path list, the output starts with the match count per file or per folder. +- Proxy robustness. `tforge claude` restarts the proxy on the same port if it stops. An error in one request is logged instead of stopping the proxy. The memo of compressed results is capped (`TFORGE_PROXY_MEMO_MB`, default 64), dropping the least recently used entries first. +- After an Edit fails with "not found" on a file whose Read was folded, later Reads of that file are sent whole. +- Windows: `claude` installed by npm (`claude.cmd`) now starts from `tforge run` workers and `tforge claude`; before, Node could not spawn it without a shell. Arguments are escaped for cmd.exe. CI on Windows now runs the proxy tests, starts the proxy daemon and runs `tforge claude` through a `.cmd` shim. +- A whole Read of a large saved Bash output (`tool-results/*.txt`) is no longer refused (Claude Code displayed the refusal as "PreToolUse:Read hook error", which users took for a crash). It now reads the last ~8k characters, since Claude Code's preview already showed the start, with a note giving the line range and how to load the rest; repeating the whole Read loads all of it. +- Same for whole-file Reads of dependency source, lockfiles and generated files (first 200 lines, with a note) and a lone `cat` of dependency source (through `tview`, folded). Interactive `ssh HOST` and installers that would wait for an answer are still refused: rewriting them would mean running a different command or confirming an install for the user. +- OpenAI Codex: `.codex-plugin/plugin.json` and `.agents/plugins/marketplace.json` (`codex plugin marketplace add chteau/tokenforge`). The same hooks.json runs there; under Codex (detected by `PLUGIN_ROOT` or `turn_id`) a large MCP result is replaced through `decision: block` instead of `updatedMCPToolOutput`, and the polling-wait cap is skipped, since Codex accepts `updatedInput` only with `allow`. See README, OpenAI Codex. +- opencode: `tforge opencode install [--project]` writes a plugin file (opencode 2's `{ id, setup }` default export, and the API v1 factory for opencode 1) that runs the same hook scripts: the Bash router on shell calls (rewrite, refusal as a tool error, note before the output) and the session-start policy in the system prompt. `TFORGE_HOST=opencode`, set by the plugin, and Codex skip what concerns Claude Code at startup: banner, dashboard, lean level and status line in its settings. +- Codex and opencode: neither puts the plugin's `bin/` on PATH, so `tkit` was "command not found" there. Router rewrites now carry `export PATH='':"$PATH";` in front, opencode also prefixes the model's own kit commands, and the session-start text tells Codex how to call them. +- Proxy: OpenAI Responses requests (`/v1/responses`, Codex with a custom `model_provider`) are forwarded to `TFORGE_PROXY_OPENAI_UPSTREAM` (default `https://api.openai.com`) and their current-turn `function_call_output` items compressed like Bash and tool results, with the same memo; usage from `response.completed` is logged. See README, API proxy. +- `bench/scripts/proxy-replay.mjs`: offline estimate of the proxy's savings on your own transcripts (no API calls, totals only). +- `tforge run --proxy` (or `TFORGE_RUN_PROXY=1`, or `"proxy": true` in the plan) sends the workers through the proxy and starts it if needed. +- docs/external-audit-2026-10.md: what ContextForge and icm-graph-context-flow do and what is worth taking. icm-graph-context-flow is not software: it runs base64-decoded secrets every hour and its README borrows the TokenForge name with a `curl | bash` install. Don't use it. +- `tview` keeps a dump under Claude Code's Bash output limit (`BASH_MAX_OUTPUT_LENGTH`, 30000 by default, minus 4000; `TFORGE_VIEW_MAX` sets it). Past that limit Claude Code shows a 2KB preview and the model reads the saved file back in pieces: on the 2026-10-10 benchmark, the 21 tokenforge runs that hit it re-read 2.8 files each before editing, against 0.4 for the others. Over the budget, the largest code files become outlines (each definition's first line with its line range, at most 120 rows), and only if that is not enough is the output cut, with a note. Documents (`.md`, `.txt`, `.tex`…) are never outlined or cut. +- Bash router: `cat` with one brace group (`src/{a,b}.ts`, `*.{ts,tsx}`) goes through `tview` like a glob; the shell still expands it. Nested braces and ranges run unchanged. A `cat` piped into `grep` or `sed` is no longer rewritten: they would search the folded text and miss or misnumber lines. `head` and `tail` still are. +- Proxy: `TFORGE_PROXY_TTL=5m`, or the header `x-tokenforge-cache-ttl: 5m` for one client (`ANTHROPIC_CUSTOM_HEADERS`; it is not forwarded), asks for the 5-minute prompt cache instead of the 1-hour one Claude Code requests. Cache writes then cost 1.25× the input price instead of 2×; any pause over 5 minutes loses the cache. Off by default; `tforge proxy report` counts the requests it changed. +- Session policy: "Batch reads (<25k chars)", so batched reads stay under that limit. +- Proxy on by default (optional). The first session after install starts the proxy and, once it answers, adds `ANTHROPIC_BASE_URL=http://127.0.0.1:7879` to the `env` of the Claude Code user settings; tokenforge's config records it, so `tforge proxy off` (or `/tokenforge:proxy off`) removes exactly that entry. Not set next to your own `ANTHROPIC_BASE_URL`, Bedrock, Vertex or Foundry, nor with `TFORGE_PROXY=0` before that session; a failed start is retried in the next two sessions. `tforge proxy on|off`, and `--status` says whether the settings route through it. The hooks (session start, every prompt, after every tool call) restart a stopped proxy, and warn with the fix if they cannot. Run `tforge proxy off` before uninstalling. +- Proxy: stale-context pruning (lib/prune.mjs). Tool results made obsolete later become a one-line stub saying why: file reads read again whole or rewritten (Read, and shell reads: `cat`, `sed -n`, `head`, `tview`, chains with `;`/`&&`, one brace group), written bodies read back or rewritten (Write and heredocs, `cat >>` never counts), identical commands run again, and test/build runs superseded by the same run after a change. Thinking from turns before the last user prompt is dropped. Decisions are remembered so later requests resend the same bytes; batches go by `TFORGE_PROXY_PRUNE`: `tokens` (default, once `TFORGE_PROXY_PRUNE_MIN`=8000 characters are stale), `cost` (on an expired cache, or when cache reads saved outweigh the rewrite) or `off`. Offline on long interactive sessions: 1-17% fewer input tokens; on a warm cache `tokens` mode can cost more dollars than it saves. Not benchmarked yet. +- Proxy pruning by age: once the model has moved on (3 model calls, or an earlier turn), written bodies (Write, heredocs including after a prefix command, Edit strings) and the heredoc bodies of scripts that ran successfully (`python3 - <<'EOF'`) become a stub saying the file holds them; the command keeps its shape. Reads from an earlier turn of a file changed since go too. `TFORGE_PROXY_PRUNE_WRITES=0` turns the age rule off. Offline replay of the bench runs: -1.5 to -5.4% input tokens on go-feature and banking, 0 on the short tasks. +- Proxy: compressed nothing with current Claude Code, which ends each request with a `system` message after the tool results; the newest results are now found in the last user message. +- Proxy: pruning defaults to `cost`. In benchmarks, `tokens` mode stubbed a few thousand stale tokens early in long histories, and the API wrote everything after them to the cache again: one batch rewrote 51k tokens to drop 5.5k, about $0.40 on a $1.50 run. A cache write costs 25-40 cache reads, so pruning now goes only on an expired cache or when the reads saved outweigh the rewrite; `TFORGE_PROXY_PRUNE=tokens` keeps the old behavior. +- Proxy pruning, `cost` mode: one old stale item made the whole history count as rewritten, so no batch ever went (0 in a 6-task benchmark campaign). The batch is now the run of pending items from some message on that saves the most cache reads net of the rewrite. Written bodies and ran scripts go after 2 model calls instead of 3. +- Lean `ultra` adds a policy line that sends edits to one `tkit edit` per step (each block marker spelled out) and new files to `cat >`: in 18 benchmark runs under `ultra`, the model read with `cat`/`sed` and wrote with `cat >` and python heredocs, never once with the kit. +- `tkit edit` (tmap 0.5.1): a `new` or `append` header without `<<< >>>` takes the raw text up to the next `@@` or EOF, and an unclosed `<<<` in those modes ends there too. In one benchmark campaign 11 of 65 calls failed on these two slips. With the `ultra` policy line above, 92 calls in the next campaign had no syntax error. +- Proxy: `claude -p` sessions (user agent `sdk-cli`) get the 5-minute prompt cache by default: no one pauses between their requests, and cache writes cost 1.25× the input price instead of 2×. Interactive sessions and SDK apps keep Claude Code's 1-hour cache; `TFORGE_PROXY_TTL=1h` keeps it everywhere. +- `tforge proxy report`: thinking sent back per request, from earlier turns (prunable) and the current turn, in characters and blocks. Sizes only. +- Proxy: shell reads (`cat`, `sed -n`, `head`, `tview`) are no longer cleaned or capped at 16k characters; tview sizes its output for Edit matching. +- `tforge proxy report`: characters pruned, batches (and how many on an expired cache), and requests Claude Code sent with its own `context_management`. +- Session start loads a repo map (`tmap tree`, two levels, capped at 3000 characters, `TFORGE_MAP_CHARS`) so the first call need not list the repo. `TFORGE_MAP=0`: off; `TFORGE_MAP=1`: the old one-line hint instead. Not benchmarked yet. +- Session policy: independent tool calls go in one message. +- `/tokenforge:proxy [on|off|--status|report]` skill. + ## 0.9.1 - Context alert: your next message gets it once the context passes the budget, then again each time the context doubles, instead of every 10k tokens and after tool calls (a 700k-token session got over 60). Shorter. A session started on 0.7.0–0.7.2 keeps that version's blocking alert ("A hook blocked your prompt") until it ends: after updating, start a new session. diff --git a/README.md b/README.md index ce3fb29..f9cb484 100644 --- a/README.md +++ b/README.md @@ -39,9 +39,9 @@ A long Claude Code session re-sends its whole context on every turn. A build tha ## Where it helps, measured -**Against clean Claude Code.** Every benchmark run uses **Claude Opus 5.5** (`claude-opus-5-5`) on Claude Code 2.1.293, on both sides. This is verified from the model field of every API response in the saved transcripts, not just the `--model` flag. `bench/` runs the same task on the same repo commit in sandboxed sessions, once with clean Claude Code (no plugins, skills, hooks, MCP or CLAUDE.md) and once with tokenforge 0.7.0 at its defaults, and scores quality with hidden tests. +**Against clean Claude Code.** Every benchmark run uses **Claude Opus 5.5** (`claude-opus-5-5`) on Claude Code 2.1.293, on both sides. This is verified from the model field of every API response in the saved transcripts, not just the `--model` flag. `bench/` runs the same task on the same repo commit in sandboxed sessions, once with clean Claude Code (no plugins, skills, hooks, MCP or CLAUDE.md) and once with tokenforge at its defaults (0.7.0, builds b9471cc0 and 1d360dd5, on the 34 coding tasks; 0.8.0, build 31952bff, on the 2 academic tasks), and scores quality with hidden tests. -**Across all 36 tasks, tokenforge used about half the tokens: median −52%, mean −50%, pooled −52%. It used fewer tokens on all 36 tasks, with equal or better quality on all but two.** At list prices, which is roughly what usage limits count (most of the token savings are cache reads, at 0.05× the input price; the 1-hour cache writes Claude Code makes cost 2×), the median is −22%, and it cost less on 34 of 36 tasks: `c-cli` (+9.5%) and `perl-cli` (+5.4%) cost more, both from long up-front plans. The planning line added since cuts those two by about a third (A/B against TokenForge without it, below). Median tool calls: −49%. +**Across all 36 tasks (tokenforge 0.7.0 and 0.8.0 as above, Claude Code 2.1.293), tokenforge used about half the tokens: median −52%, mean −50%, pooled −52%. It used fewer tokens on all 36 tasks, with equal or better quality on all but two.** At list prices, which is roughly what usage limits count (most of the token savings are cache reads, at 0.05× the input price; the 1-hour cache writes Claude Code makes cost 2×), the median is −22%, and it cost less on 34 of 36 tasks: `c-cli` (+9.5%) and `perl-cli` (+5.4%) cost more, both from long up-front plans. The planning line added since cuts those two by about a third (A/B against TokenForge without it, below). Median tool calls: −49%. ![From scratch: total tokens per project](docs/img/bench-greenfield.svg) @@ -72,7 +72,7 @@ A long Claude Code session re-sends its whole context on every turn. A build tha | C CSV query tool (Make) | 723k | 569k | **−21%** | 100 → 100 | | Kotlin Markdown converter | 464k | 418k | **−10%** | 100 → 100 | -Median −55% over 24 projects in 23 languages. Perl config merger: every hidden test passes, but tokenforge scores 97 on the structural checks (the entry script is longer than the 30 lines the spec asks for). The agent gets a spec and an empty repo, and hidden black-box tests check the result (CLI, HTTP contract, headless browser, scripted TUI, lune for Luau). A Ruby log analyzer was also run once per side and is left out of these results: tokenforge used 14% more tokens on it (443k vs 390k), quality 96.25 vs 96.83. `bench/benchmark.config.json` lists the exclusion and the runs are kept. +Median −55% over 24 projects in 23 languages (tokenforge 0.7.0, Claude Code 2.1.293). Perl config merger: every hidden test passes, but tokenforge scores 97 on the structural checks (the entry script is longer than the 30 lines the spec asks for). The agent gets a spec and an empty repo, and hidden black-box tests check the result (CLI, HTTP contract, headless browser, scripted TUI, lune for Luau). A Ruby log analyzer was also run once per side and is left out of these results: tokenforge used 14% more tokens on it (443k vs 390k), quality 96.25 vs 96.83. `bench/benchmark.config.json` lists the exclusion and the runs are kept. ![Existing codebases: total tokens per task](docs/img/bench-existing.svg) @@ -89,14 +89,14 @@ Median −55% over 24 projects in 23 languages. Perl config merger: every hidden | Rust refactor | 413k | 348k | **−16%** | 100 → 100 | | Architecture investigation (TS) | 386k | 347k | **−10%** | 100 → 100 | -Median −47%. Scheduled transfers: every hidden test passes, but tokenforge scores 94 on the structural design checks (9/15), as in every tokenforge run of that task. +Median −47% (tokenforge 0.7.0, Claude Code 2.1.293). Scheduled transfers: every hidden test passes, but tokenforge scores 94 on the structural design checks (9/15), as in every tokenforge run of that task. | Academic work | Clean Claude Code | tokenforge | Saved | Quality | |---|---:|---:|---:|---| | Answer questions from a 15-page PDF paper | 274k | 138k | **−50%** | 100 → 100 | | Proofread a LaTeX manuscript (19 planted errors) | 239k | 157k | **−34%** | 95.3 → 97.8 | -Two runs per side. Proofreading: 19 errors planted across a 12-page LaTeX manuscript, scored by how many are found (recall) with a small penalty for false alarms. PDF Q&A: 10 questions answered from a 15-page two-column paper, one of them only from a figure. The PDF task hides `pdftotext`, poppler, Ghostscript and Python PDF libraries on both sides, as on a typical Windows machine; with them installed, both sides simply convert the PDF and the comparison says little. +Two runs per side, tokenforge 0.8.0 (build 31952bff), Claude Code 2.1.293. Proofreading: 19 errors planted across a 12-page LaTeX manuscript, scored by how many are found (recall) with a small penalty for false alarms. PDF Q&A: 10 questions answered from a 15-page two-column paper, one of them only from a figure. The PDF task hides `pdftotext`, poppler, Ghostscript and Python PDF libraries on both sides, as on a typical Windows machine; with them installed, both sides simply convert the PDF and the comparison says little. Each row is the median of 1–3 runs per side, and single runs vary by about ±20%, so read per-task numbers as rough and the overall result as solid. `bench/reports/` has the raw data, and `bench/scripts/charts.py` redraws these charts from it. `bench/` reruns everything. @@ -106,7 +106,7 @@ Each row is the median of 1–3 runs per side, and single runs vary by about ±2 ![Context re-read per request in one session](docs/img/bench-context.svg) -- **Fixed context**: 16.9k tokens per request by default, 9.7k at tokenforge's default lean level. On short tasks this floor is most of the cost. +- **Fixed context**: 16.9k tokens per request by default, 9.7k at tokenforge's default lean level (tokenforge 0.7.0, Claude Code 2.1.293). On short tasks this floor is most of the cost. - **Fewer round trips**: each call re-reads the whole context. Batching (several files per call, one-call code reads with `tread`) built whole projects in 3–9 calls where clean Claude Code took 7–22. - **Smaller tool results**: they are 80–95% of context growth in existing codebases, and every one is re-read by every later call. Broad dumps fold, long lines are cut, build and test output is compacted. - **Less code**: "every stated requirement, nothing extra", written concisely but readably. @@ -138,13 +138,13 @@ A strong model writes a fresh small app in a handful of big batches, so the code ## What's new in 0.9.0 -- **Planning line**, on by default in main sessions: look at the repo first, plan briefly, never draft code in thinking. In an A/B over 36 paired tasks against the same build without it: list cost −15% per task (95% CI −21% to −10%), thinking −44%, wall-clock −21%, the same hidden tests passed. `TFORGE_PLAN=0` turns it off. +- **Planning line**, on by default in main sessions: look at the repo first, plan briefly, never draft code in thinking. In an A/B over 36 paired tasks against the same build without it (a 0.8.0 development build of tokenforge (build c9de32de) on Claude Code 2.1.295): list cost −15% per task (95% CI −21% to −10%), thinking −44%, wall-clock −21%, the same hidden tests passed. `TFORGE_PLAN=0` turns it off. - **Disk cleanup**: `tforge gc` removes the per-session scratch Claude Code never deletes from `/tmp/claude-/`, tokenforge's own leftovers, stale snapshots and used-up handoffs, by rules, with no model call. It runs in the background. - **Instruction files for every agent**: sessions, subagents and workers get the `AGENTS.md`/`CLAUDE.md` text Claude Code leaves out, compacted. - **Leaner shell output** (tmap 0.5.0): `tkit run`, `tkit batch`, `tkit eval`, `tkit test --failed`, and more commands routed through them. - **Earlier compaction in 1M-context sessions** (`autoCompactWindow` per lean level): replaying 14 days of sessions, main-session input −40%. - **Works with [SpecAudit](https://github.com/magicmoux/SpecAudit)** and other skill plugins that bring their own workflow (use `balanced`). -- **Benchmark cost at list prices**: TokenForge cost less on 34 of 36 tasks (median −22%). The "36 of 36 cheaper" in 0.8.0 counted tokens. +- **Benchmark cost at list prices** (the 0.7.0 and 0.8.0 runs above): TokenForge cost less on 34 of 36 tasks (median −22%). The "36 of 36 cheaper" in 0.8.0 counted tokens. All releases: [CHANGELOG.md](CHANGELOG.md). What comes next: [ROADMAP.md](ROADMAP.md). @@ -159,11 +159,32 @@ Inside Claude Code: Requirements: Claude Code and Node.js 18 or newer. Subscription (OAuth) logins and API keys both work. `tmap` needs a release binary for your platform, or Rust to build one. +### OpenAI Codex + +Codex runs the same hooks. Add the marketplace, install `tokenforge` from it, then open `/hooks` and trust tokenforge's hooks (Codex skips plugin hooks until you do): + +``` +codex plugin marketplace add chteau/tokenforge +``` + +What works there: the Bash router (`tkit check`, `tkit test`, `tview`; refusals of interactive ssh and installers), MCP result distillation, the answer cache, prompt routing, the session-start policy, checkpoints and skills. Codex has no Read or Grep tool, so the Read narrowing and code redirect never fire; the 4-minute cap on polling waits is off (Codex takes a rewritten input only with an approval). Context-budget alerts read Claude Code's transcript format and stay silent on Codex. The dashboard and workers are Claude Code only; the proxy also serves Codex with an API key (see API proxy). + +### opencode + +From a clone of this repository (Node.js on PATH): + +``` +bin/tforge opencode install # ~/.config/opencode/plugins/tokenforge.js +bin/tforge opencode install --project # .opencode/plugins/tokenforge.js, this project only +``` + +It writes a one-line plugin that loads tokenforge from the clone, so `git pull` updates it; `tforge opencode remove` deletes it. It works with opencode 2 (the `{ id, setup }` plugin, hooks on `ctx.tool` and `ctx.session`) and opencode 1 (the v1 factory), from `.opencode/plugins/`, and runs the same hook scripts: shell commands go through the Bash router (a refusal shows up as the tool's error, a note comes before the output), and the session-start policy and instruction digest are added to the system prompt, the same text on every request so the prompt cache keeps it. Not there yet: MCP distillation, the answer cache, context-budget alerts and checkpoints, which need opencode's message and session events. opencode already reads `CLAUDE.md` and `.claude/skills`. + ### Updates -tokenforge is a normal plugin. It never patches Claude Code, wraps the `claude` binary or edits your settings files, so Claude Code's own auto-update keeps working as usual. To update tokenforge itself automatically, open `/plugin`, go to **Marketplaces**, select `tokenforge` and enable auto-update. Otherwise run `/plugin marketplace update tokenforge` whenever you like. +tokenforge is a normal plugin. It never patches Claude Code or wraps the `claude` binary, so Claude Code's own auto-update keeps working as usual. It writes to your Claude Code settings in two places only, both reversible: the lean tool level (`tforge lean off`) and the proxy address (`tforge proxy off`). To update tokenforge itself automatically, open `/plugin`, go to **Marketplaces**, select `tokenforge` and enable auto-update. Otherwise run `/plugin marketplace update tokenforge` whenever you like. -To uninstall, run `/plugin uninstall tokenforge@tokenforge`. Nothing is left behind except `.forge/` folders in the projects where you used it. +To uninstall, **first run `tforge proxy off`** (or `/tokenforge:proxy off`), then `/plugin uninstall tokenforge@tokenforge`. Without that step your settings keep sending Claude Code's requests to the proxy, which no longer runs, and every request fails; removing `ANTHROPIC_BASE_URL` from the `env` of `~/.claude/settings.json` fixes it by hand. Nothing else is left behind except `.forge/` folders in the projects where you used it. ## Use @@ -222,7 +243,7 @@ Every request carries the definition of every enabled tool and skill. Lean level Each level also sets when 1M-context sessions compact (`autoCompactWindow`): at 400k tokens for `on` and `balanced`, 300k for `max`, 200k for `ultra`, instead of near 1M. Every request re-reads the whole context; replaying 14 days of sessions, 400k cut main-session input 40% and subagent input 17%, at one compaction per ~340 calls. Models with a 200k window are unaffected. A value you set yourself, or pick with `/autocompact`, wins, and `off` removes only tokenforge's. Installs from before this get it once, with a notice. -**On first start, tokenforge sets `balanced` once** and tells you so in a message shown to you, not to Claude. It writes only its own entries to `~/.claude/settings.json` (`permissions.deny`, `skillOverrides` and `autoCompactWindow`), because plugins cannot set permissions themselves. It never re-applies after you choose a level. To skip it, set `TFORGE_LEAN_DEFAULT=off` (or `on`, `max`, `ultra`) before the first start. +**On first start, tokenforge sets `balanced` once** and tells you so in a message shown to you, not to Claude. It writes only its own entries to `~/.claude/settings.json` (`permissions.deny`, `skillOverrides` and `autoCompactWindow`), because plugins cannot set permissions themselves. It never re-applies after you choose a level. To skip it, set `TFORGE_LEAN_DEFAULT=off` (or `on`, `max`, `ultra`) before the first start. To keep tools a level would deny, list them as `"leanKeep": ["TaskStop"]` in `config.json` (or `TFORGE_LEAN_KEEP`); a rule tokenforge already added for a kept tool is lifted at the next start. Change the level on the dashboard's **Settings** page, with `/tokenforge:lean `, or with `tforge lean `. The Settings page also picks which built-in skills Claude may still use on its own. `tforge lean off` removes exactly the entries tokenforge added, never your own. Changes apply to sessions started afterwards. @@ -248,6 +269,47 @@ A local dashboard starts in the background with your first session. Open it with **Privacy.** The server listens on 127.0.0.1 only and rejects other Host headers, which blocks DNS rebinding. It answers GET requests, plus one POST for the Settings page (lean level, skills, terse), accepted only from its own page (same-origin `Origin` and a JSON body). It loads nothing from the internet. It reads your transcripts incrementally: only new bytes, with a cache in `~/.cache/tokenforge/`. From transcripts it keeps and serves numbers only, never prompt, reply or file text. Three exceptions: the session page's "Where the tokens went" table, which shows the command or file path behind each costly tool result (read on demand, never cached); the Memory page, which shows prompt and reply snippets and file names from that project's sessions (the index behind it, in `~/.cache/tokenforge/memory/`, holds those snippets); and a project's own `.forge/snapshots/`, shown on its project page so you can see what `/clear` will reload; only files listed in that folder can be requested. `TFORGE_UI=0` disables the auto-start, and `tforge ui --stop` stops it. +### API proxy (on by default, optional) + +Since 0.9.2 the first session after install turns the proxy on: it starts in the background on `127.0.0.1:7879`, and only once it answers, `ANTHROPIC_BASE_URL=http://127.0.0.1:7879` goes into the `env` of your Claude Code user settings. Sessions started from then on go through it (the session that set it does not). It is not set when you already route requests elsewhere (your own `ANTHROPIC_BASE_URL`, Bedrock, Vertex or Foundry), nor when `TFORGE_PROXY=0` is set before that first session. Turn it off at any time with `tforge proxy off` or `/tokenforge:proxy off` (only the entry tokenforge added is removed), back on with `tforge proxy on`; `tforge proxy --status` says where things stand. + +Claude Code reads the address once per session, so a stopped proxy would make every request fail. The hooks restart it at session start, at every prompt and after every tool call (a file read and a signal when it runs); if it cannot be restarted, you get a message saying how to start it or turn it off. Before uninstalling tokenforge, run `tforge proxy off` (see Updates). + +Without the default, `tforge claude` runs Claude Code through the proxy for one session, started in the background if needed; `tforge proxy` runs it in a terminal, `--detach` in the background, `--stop` stops it. Works with a subscription login or an API key: the proxy forwards every header as sent. It does three things: + +- **Logs** every request: sizes of the system prompt, tool definitions and tool results, and the usage the API reports (input, cache reads, cache writes, output). `tforge proxy report [--days N]` sums them, and also shows: + - **Cache breaks.** A request that reads much less from cache than the previous request of the same conversation had in context. The report gives a probable cause: the system prompt changed, the tool definitions changed, an earlier message changed, or the cache expired (more than 5 minutes, or 1 hour with a 1h TTL). It also says how many tokens were written again. + - **Folded Reads.** How many Edits hit a file whose Read went out folded, how many of those failed because the text was not found, and how many Reads went back into folded bodies. These say whether folding saves more than it costs. +- **Compresses tool results the first time they are sent.** A whole-file Read above 12k characters (code, not prose or markup) folds long definition bodies, keeping every kept line's number and `Read offset=N limit=M` in place of each fold; partial reads, which Edit works from, stay whole. Bash and other text output loses colors and progress-bar redraws, repeated lines become a count, and output above 16k characters keeps its head and tail with the full text saved to a file the model can grep. When the cut output is a search result (`path:line:` lines or a list of paths), it starts with the match count for every file, or every folder, so the cut part still shows where the matches are. Large JSON loses its indentation, and long arrays keep their first, error-looking and last items. + +- **Prunes stale context.** A tool result made obsolete later in the conversation is replaced by a one-line stub saying why: a file read that was read again whole or rewritten later (Read, `cat`, `sed -n`, `head`, `tview`, including chains like `cat a b; sed -n '1,40p' c`; every file must be covered), the body of a file written and then read back whole or rewritten, a command run again identically, and a test or build run (`npm test`, `pytest`, `cargo test`, `go test`, `make`, `tkit test`…) superseded by the same run after a change. A file read from a turn before the last user prompt goes too once that file was written or edited since. Bodies the model wrote go once it has moved on (3 model calls later, or an earlier turn): a Write's content, a heredoc's body (`cat > f <>`) never counts as a rewrite. Shell reads (`cat`, `sed -n`, `head`, `tview`) are never compressed or capped by the proxy: the model edits from them. + + Pruning changes earlier content, so the API writes the cache again from that point. It therefore goes in batches, each decision remembered so every later request sends the same bytes. `TFORGE_PROXY_PRUNE` picks when: `cost` (default) prunes when the cache has expired anyway (free), or on a warm cache only when the cache reads saved over the next requests outweigh the rewrite; `tokens` prunes once at least `TFORGE_PROXY_PRUNE_MIN` characters (8000) are stale: fewer tokens per request, but a cache write costs 25-40 cache reads, so on a warm cache the rewrite usually costs more dollars than it saves (in benchmarks, one batch rewrote 51k tokens to drop 5.5k); `off` prunes nothing new. Offline, on long interactive sessions of ours, `tokens` cut 1-17% of input tokens; short single-task sessions have almost nothing stale. `tforge proxy report` shows what was pruned, in how many batches, how many requests Claude Code sent with its own `context_management`, and how much thinking the requests carried back (earlier turns, which pruning drops, and the current turn; sizes only). + +The prompt cache is why only new results change: if earlier content differs from the last request, the API writes it to the cache again at 1.25× instead of reading it at 0.1×. Each compressed result is remembered by its tool_use_id, so every later request sends the same bytes. A result the proxy first passed unchanged (it was started mid-session) is never touched later, and one that Claude Code itself rewrote passes as sent. If a request cannot be parsed, it goes out unchanged. Once an Edit fails with "not found" on a file whose Read was folded, later Reads of that file are sent whole. + +Claude Code keeps `ANTHROPIC_BASE_URL` for the whole session, so (besides the hooks) `tforge claude` checks every 2 seconds that the proxy is still running and restarts it on the same port if it stopped. An error in one request is logged in `~/.cache/tokenforge/proxy.log` and does not stop the proxy. + +To estimate the savings on your own past sessions without calling the API, run `node bench/scripts/proxy-replay.mjs [--days 30]`. It replays the tool results in your transcripts through the same compression and prints only totals. + +**Codex (OpenAI Responses API).** The proxy also takes `POST /v1/responses` and compresses large `function_call_output` items the same way (shell outputs like Bash), with the same memo, sent on to `TFORGE_PROXY_OPENAI_UPSTREAM` (default `https://api.openai.com`). Start it with `tforge proxy --detach`, then in `~/.codex/config.toml`: + +```toml +model_provider = "tforge" + +[model_providers.tforge] +name = "OpenAI via tokenforge" +base_url = "http://127.0.0.1:7879/v1" +env_key = "OPENAI_API_KEY" +wire_api = "responses" +``` + +Only outputs after the last message (the current turn's tool loop) are compressed, so history already sent stays byte-identical for the prompt cache. Tested with an API key; a ChatGPT-login session goes to a different backend and is untested. + +`TFORGE_PROXY_COMPRESS=0` logs only. `TFORGE_PROXY_FOLD=0` turns off Read folding. `TFORGE_PROXY_CAP` sets the Bash output cap in characters (`0`: none). `TFORGE_PROXY_MEMO_MB` caps the memo of compressed results (default 64 MB; the least recently used go first). `TFORGE_PROXY_UPSTREAM` sets where requests go (default: an `ANTHROPIC_BASE_URL` you already had, else `https://api.anthropic.com`). `TFORGE_PROXY_TTL=5m` (or `ANTHROPIC_CUSTOM_HEADERS='x-tokenforge-cache-ttl: 5m'` for one session; the header is not forwarded) replaces Claude Code's 1-hour prompt cache with the 5-minute one: cache writes cost 1.25× the input price instead of 2×, which pays off when requests follow each other closely (scripted runs, `tforge run` workers). After any pause over 5 minutes the whole context is written again, so it is the default only for `claude -p` (user agent `sdk-cli`), where no one pauses; `TFORGE_PROXY_TTL=1h` keeps Claude Code's 1-hour cache there too. + +**Privacy.** The proxy listens on 127.0.0.1 only and rejects other Host headers. Its request log (`~/.cache/tokenforge/proxy/requests-*.jsonl`) holds sizes and token counts only. Two files hold content, both readable by you only and dropped after 14 days: `memo.jsonl` (the compressed results, so later requests can resend them) and `out/` (full outputs that were capped). + ### tmap: code map (built in, replaces CodeGraph-style indexers) `tmap` is a small Rust indexer bundled with the plugin. It parses Rust, TypeScript/TSX, JavaScript, Python and Go with tree-sitter and keeps an index in `~/.cache/tokenforge/tmap`. Every command refreshes the index first, re-parsing only changed files. It respects `.gitignore` and skips dependency and build folders even without one. @@ -273,8 +335,10 @@ Output for "where is orbit speed handled": | `codegraph query` | ~220 tokens | | `tmap find orbit speed` | **~70 tokens**, with the right definition and its line range | +**Repo map at session start (default since 0.9.2, not benchmarked yet).** Most tasks begin by listing the repo, and that listing is re-sent with every later request. Session start now loads the `tmap tree` outline instead (folders, files and their top definitions, two levels deep; file names only when that is too long), capped at 3000 characters (`TFORGE_MAP_CHARS`, ~750 tokens). Skipped for repos under 8 files, without the tmap binary, or when tmap takes over 3 seconds. `TFORGE_MAP=0` turns it off. + **Where it pays off:** the `forge` skill uses it to hand workers exact line ranges, and `tmap tree` is a fast map for you. In A/B runs of normal Sonnet sessions, a session hint did not get the agent to use `tmap`. Redirecting Grep and Read to it was mixed: two small wins, and one run where the agent worked around it and used more tokens. Both are therefore opt-in: -- `TFORGE_MAP=1` adds a one-line hint at session start; +- `TFORGE_MAP=1` adds a one-line hint at session start instead of the map below; - `TFORGE_REDIRECT=1` answers identifier-like Grep calls, Bash greps for one code identifier, and whole-file reads of large source files from the index. Repeating the identical call always goes through. First use: the launcher downloads the prebuilt binary for your platform from this repo's releases and checks it against the published SHA-256. If no release binary fits, it builds once with `cargo` (one to two minutes). `TMAP_BIN` points to your own binary. @@ -308,16 +372,17 @@ Hooks (automatic): - **Context budget.** Every API call re-reads the whole context from the cache, so cache reads grow with calls × context size. The budget is 50k tokens of context per call, or the session's fixed part (system prompt, tools, skills, hook text, measured on its first call) plus 15k if that is larger. - The alert is shown to you; notes reach Claude's context, after tool calls, only with `TFORGE_WATCH_INJECT=1` (an injected "stop and /clear" note ended unattended tasks halfway). - - Over the budget, your messages are never held. Your next message gets an alert, and again each time the context doubles, and `.forge/HANDOFF.md` is written automatically from this session's snapshots (recent requests, every file changed, the last reply; no model call), so `/clear` at any moment loses nothing: the next session continues from it. A handoff you wrote yourself (`/tokenforge:handoff`) is never overwritten. The automatic one is deleted once used: when a session started after it (and so loaded it) saves its first snapshot, or after 72 hours. `TFORGE_AUTO_HANDOFF=0` turns the automatic one off. -- **Snapshots.** After every reply, the session is saved in chunks to `.forge/snapshots/`: each chunk holds its requests, changed files, last reply and context size. A chunk closes after 6 requests or at a compaction, and each session starts its own. Hooks write them from the transcript, not Claude, so they cost no tokens and are current even when no handoff was written. Chunks are kept by use, with no model call: a chunk's score adds up its writing and every later read (Claude reading it, the reload after `/clear`, the dashboard), each weighted 1/√(hours since + 1), and is lowered when files it changed are gone or a later chunk changed most of the same files. The newest 6 always stay; the others go once the score falls too low (unread: after about 17 days; 4 once its files are gone, 2 once superseded), and at most 50 are kept per project. The dashboard's project page lists them. + - Over the budget, your messages are never held. Your next message gets an alert, and again each time the context doubles, and `.forge/HANDOFF.md` is written automatically from this session's snapshots (recent requests, every file changed, the last reply; no model call), so `/clear` at any moment loses nothing: the next session continues from it. A handoff you wrote yourself (`/tokenforge:handoff`) is never overwritten. The automatic one is moved to `.forge/handoffs/` (the newest 10 are kept) once used: when a session that was given it has saved a snapshot of its own work, or after 14 days. `TFORGE_AUTO_HANDOFF=0` turns the automatic one off. +- **Snapshots.** After every reply, the session is saved in chunks to `.forge/snapshots/`: each chunk holds its requests, changed files, last reply and context size, and the subagents it ran: their type and task, the files they changed, the commands they ran and what they reported (read from their own transcripts, where most of a delegating session's tokens go). A chunk closes after 6 requests or at a compaction, and each session starts its own. Hooks write them from the transcript, not Claude, so they cost no tokens and are current even when no handoff was written. Chunks are kept by use, with no model call: a chunk's score adds up its writing and every later read (Claude reading it, the reload after `/clear`, the dashboard), each weighted 1/√(hours since + 1), and is lowered when files it changed are gone or a later chunk changed most of the same files. The newest 6 always stay; the others go once the score falls too low (unread: after about 17 days; 4 once its files are gone, 2 once superseded), and at most 50 are kept per project. The dashboard's project page lists them. - **Memory.** `tforge recall ` searches the project's past sessions, built from your Claude Code transcripts: prompts, commit messages, files edited and read, and how each session ended. It returns the few matching sessions and files (`--session ID` gives one session in full). On startup and `/clear`, Claude gets one line instead of the old snapshot dump: how many earlier sessions exist and the newest one's first prompt, with a pointer to `tforge recall`. Past work then costs tokens only when the task needs it, not ~2k re-read on every call. The index lives in `~/.cache/tokenforge/memory/` and refreshes incrementally. `TFORGE_RECALL=inject` restores the old snapshot loading; `TFORGE_RECALL=0` turns the hint off. In `bench/`'s two-session task (a follow-up on the previous session's feature), recall used a median of 234k tokens against 263k with injected snapshots and 413k for clean Claude Code, at full quality (two runs each; rough). -- **Disk cleanup.** Claude Code keeps each session's scratch (scratchpad, task output, images) in `/tmp/claude-/` and never deletes it, so a few heavy sessions can fill the disk until transcript writes fail (ENOSPC). `tforge gc` frees, by rules with no model call: the scratch of ended sessions, tokenforge's own leftovers (hook state of ended sessions, old tmap binaries and logs, indexes of deleted projects), snapshot chunks scored out (above) and used-up automatic handoffs. A session's scratch is never touched while Claude Code's session registry lists its process as running, while a process has its working directory or an open file inside it, or within 12 hours of its last change or transcript write (1 hour on a nearly full disk); without the registry, none is. Ended sessions' scratch idle for over 7 days goes; the rest stays up to 2 GB, the oldest and largest going first, and on a nearly full disk (under 5% free, within 2-10 GB) it frees until twice that is free. It runs by itself in the background at most every 6 hours (every 10 minutes on a nearly full disk), from session start and Stop, never in unattended sessions. `tforge gc --dry-run` lists what it would free. Off: `TFORGE_GC=0`. -- **Repeated questions.** If you ask a question you already asked in this project, that earlier turn changed no files, and no project file changed since, the prompt is not sent to Claude: you see the earlier answer and its date, at zero tokens. Send the same message again to ask Claude anyway. A closely similar earlier question ("I forgot the dev admin password") is not blocked: Claude gets the earlier answer as one short hint instead of searching for it. Answers come from your transcripts and are not re-checked. Requests whose point is a fresh look (review, proofread, verify, check, "relis", "vérifie", "sans contexte", "from scratch"…) always go to Claude. Off: `TFORGE_ANSWER_CACHE=0`. -- **Handoff reload.** On startup or `/clear`, `.forge/HANDOFF.md` (if under 72 hours old) is loaded into the session, because writing one is a deliberate "continue from here". -- **Terse rule.** Injected on startup, `/clear` and after compaction (see above). +- **Disk cleanup.** Claude Code keeps each session's scratch (scratchpad, task output, images) in `/tmp/claude-/` and never deletes it, so a few heavy sessions can fill the disk until transcript writes fail (ENOSPC). `tforge gc` frees, by rules with no model call: the scratch of ended sessions, tokenforge's own leftovers (hook state of ended sessions, old tmap binaries and logs, indexes of deleted projects), snapshot chunks scored out (above), and automatic handoffs once used (moved to `.forge/handoffs/`). A session's scratch is never touched while Claude Code's session registry lists its process as running, while a process has its working directory or an open file inside it, or within 12 hours of its last change or transcript write (1 hour on a nearly full disk); without the registry, none is. Ended sessions' scratch idle for over 7 days goes; the rest stays up to 2 GB, the oldest and largest going first, and on a nearly full disk (under 5% free, within 2-10 GB) it frees until twice that is free. It runs by itself in the background at most every 6 hours (every 10 minutes on a nearly full disk), from session start and Stop, never in unattended sessions. `tforge gc --dry-run` lists what it would free. Off: `TFORGE_GC=0`. +- **Repeated questions.** If you ask an information question you already asked in this project, and that earlier turn changed no files, the prompt is not sent to Claude: you see the earlier answer and its date, at zero tokens. The answer is replayed only when the repository (path and remotes), branch and commit, working tree contents (by content: same-second edits, renames and deletions count), dependency manifests and lockfiles, terse level and, when known, the model are the same as when it was asked. Requests to run, test, build, verify or deploy, security questions and questions about the current state ("is it up", "latest", "now", "en ce moment") always go to Claude, in English and French, as do requests whose point is a fresh look (review, proofread, verify, check, "relis", "vérifie", "sans contexte", "from scratch"…). When unsure, it asks Claude. Start or end a prompt with `!nocache` to skip the lookup, or send the same message again. A closely similar earlier question is not blocked: Claude gets the earlier answer as one short hint. Answers recorded before 0.9.2 are never replayed. Off: `TFORGE_ANSWER_CACHE=0`. +- **Reload.** On startup or `/clear`, `.forge/HANDOFF.md` (if under 14 days old) is loaded into the session, because writing one is a deliberate "continue from here". After `/clear` with no handoff, the compact checkpoint of the latest snapshots is loaded. After a compaction, this session's own checkpoint is loaded, never another session's. On resume, the rules are not sent again (Claude Code keeps them in the transcript); only what changed while the session was away is: a newer handoff, a changed state file, or another session's work here since. `reloadOn` in `config.json` (or `TFORGE_RELOAD_ON`, comma-separated, `0` for none) chooses among `compact` and `resume`. +- **State files.** A skill that keeps its own state (a review register, a plan) can name it in `config.json`: `"stateFiles": [".spec-audit/*/register.md"]` (globs relative to the project, or `TFORGE_STATE_FILES`). Matching files changed in the last 72 hours are loaded at startup, `/clear` and compaction (8000 characters each, 16000 in all), and on resume when changed since; the generic checkpoint is then left out. Never in subagents. +- **Terse rule.** Injected on startup, `/clear` and after compaction (see above), not on resume. - **Instruction files** (SessionStart, SubagentStart, PostToolUse). Claude Code loads the `CLAUDE.md` chain, but by default skips `AGENTS.md` in a project that has a `CLAUDE.md`, loads nested files only when Read reaches their directory, and gives tforge workers none. tokenforge adds what it left out, following your `instructionFiles` setting (`cc-plugin-agents-md`): the `AGENTS.md` chain with its `@imports`, the file a short pointer `CLAUDE.md` names ("Read AGENTS.md first"), and the nested files of directories a tool call reaches, once per session and agent. Text already loaded is not repeated; HTML comments and badges are dropped, tables compacted, 20k characters at most. Compacted files are cached in `~/.cache/tokenforge/instr/` (keyed by size and modification time), and the injected text stays identical until a file changes, so it stays in the prompt cache. Workers get the whole chain; Explore and Plan get none, as Claude Code gives them no `CLAUDE.md`. Off: `TFORGE_INSTRUCTIONS=0`. -- **Efficiency policy** (SessionStart, SubagentStart). Three lines, about 270 tokens, plus a planning line in main sessions (about 100 more: +106 input tokens per session, median over 36 paired bench tasks): results are re-read on every call, so read code in one call (`tread NAME path:40-80 "path:/regex/"` instead of grep then sed), batch reads and independent commands (`tkit batch`), edit each file in one call, run throwaway code with `tkit eval` instead of scratch files, and run checks once and only after code changes. Scope: every stated requirement and nothing extra (no unasked features, docs, refactors, dependencies or abstractions), reuse existing code, concise but readable code without boilerplate, dead code or comments that restate it, fix shared code once, infer instead of asking, and stop once the checks pass. That is "lazy, not negligent", adapted from ponytail without its challenge-the-requirement mode, which skips requirements. `TFORGE_LAZY=0` drops the scope line. The planning line: thinking is billed as output and re-read on every later call, so look at the repo first, plan briefly, and never draft code in thinking. Over 36 paired bench tasks it cut thinking 44% and list cost 15% (95% CI 10–21%), with the same hidden tests passed ([A/B](bench/reports/final-comparison.md)). `TFORGE_PLAN=0` drops it, `TFORGE_PLAN=brief` swaps in a shorter line that only asks for a brief plan. Subagents get the rest of the policy and the instruction files, and a planning line only when `TFORGE_PLAN` names one (the A/B measured main sessions). Off: `TFORGE_KIT_POLICY=0`. -- **Bash router** (PreToolUse `Bash|Read`). Raw build and test commands whose flags it fully understands are rewritten to `tkit check` / `tkit test` (cargo, go, tsc, vitest/jest, npm/pnpm/yarn/bun test, dotnet, pytest, dart/flutter, mvn, gradle, mix, zig, swift, ctest, rspec, phpunit/pest, sbt; `.exe`/`.cmd` names included). `ssh HOST CMD` and `scp` become `tkit ssh`. A plain `cat` of project files totalling 12k+ characters goes through `tview`: bodies longer than 8 lines fold to their signature plus the exact `sed -n a,bp` command that prints them, in any language (tmap's parser where it has one, an indentation-based fallback for Luau, Lua, Ruby, Java, C#, Kotlin, C/C++ and the rest), and lines over 400 characters are cut; smaller, focused reads print unchanged. A `grep` or `rg` whose output is not piped goes through `tkit run --group`: each file's path once above its lines, lines over 500 characters cut, at most 200 lines with the full output saved; a recursive `grep` also skips `.git`, `node_modules`, `.venv`, `__pycache__` and a cargo `target` it does not name. File lists, counts and quiet greps run unchanged. `gh run view --log` goes through `tkit run --fuzzy`. A rewrite happens only when every segment becomes a tkit/tview call or is read-only (`grep`, `sed -n`, `ls`, `git status`…), or the session already bypasses permissions; otherwise the line runs unchanged, so a rewrite never adds a prompt. Lines with a heredoc are never touched. Where the prompt cache expires after 5 idle minutes (subagents; a main session only when its transcript shows that cache), a polling loop that asks for more than 4 minutes gets 4 (`until`/`while`/`for` with `sleep` and only reads such as `grep`, `test`, `tail`, `pgrep`), with a one-time note to run it again: a longer wait lets the cache expire, and the next call rewrites the whole context at 12.5× the price of reading it (394 such waits cost 112M input-equivalent tokens in 14 days). Builds, tests, writes and background commands keep their timeout. Refused, with the tkit command to use instead: interactive `ssh HOST`, reading a 8k+ saved tool output (`tool-results/*.txt`) whole, and whole-file dumps (`cat`, `less`, whole-file Read) inside `node_modules`, `~/.cargo/registry`, Go `pkg/mod`, `~/.m2`, `~/.nuget`, wally and pub caches (`tkit deps api`); focused `grep`/`sed -n`/`head` slices there go through. Anything else runs unchanged. Escape hatches: prefix one command with `TFORGE_RAW=1` (or `TS_RAW=1`; an `export` does not count), or repeat the identical call. With `TFORGE_REDIRECT=1`, a Bash `grep`/`rg`/`git grep` for one code identifier is answered by `tkit ctx` the same way. Off: `TFORGE_KIT_ROUTE=0`. +- **Efficiency policy** (SessionStart, SubagentStart). Three lines, about 270 tokens, plus a planning line in main sessions (about 100 more: +106 input tokens per session, median over 36 paired bench tasks): results are re-read on every call, so read code in one call (`tread NAME path:40-80 "path:/regex/"` instead of grep then sed), batch reads and independent commands (`tkit batch`), edit each file in one call, run throwaway code with `tkit eval` instead of scratch files, and run checks once and only after code changes. Scope: every stated requirement and nothing extra (no unasked features, docs, refactors, dependencies or abstractions), reuse existing code, concise but readable code without boilerplate, dead code or comments that restate it, fix shared code once, infer instead of asking, and stop once the checks pass. That is "lazy, not negligent", adapted from ponytail without its challenge-the-requirement mode, which skips requirements. `TFORGE_LAZY=0` drops the scope line. The planning line: thinking is billed as output and re-read on every later call, so look at the repo first, plan briefly, and never draft code in thinking. Over 36 paired bench tasks (a 0.8.0 development build of tokenforge (build c9de32de) on Claude Code 2.1.295) it cut thinking 44% and list cost 15% (95% CI 10–21%), with the same hidden tests passed ([A/B](bench/reports/final-comparison.md)). `TFORGE_PLAN=0` drops it, `TFORGE_PLAN=brief` swaps in a shorter line that only asks for a brief plan. Subagents get the rest of the policy and the instruction files, and a planning line only when `TFORGE_PLAN` names one (the A/B measured main sessions). An agent with its own definition (a plugin's or your own, not Claude Code's built-in ones) gets no scope, ask or planning rules: its definition decides. `subagentSkip` in `config.json` (or `TFORGE_SUBAGENT_SKIP`), a list of agent types with `*` wildcards such as `spec-audit:*`, leaves those agents alone entirely: no policy, instruction files, Bash router or MCP distill. Off: `TFORGE_KIT_POLICY=0`. +- **Bash router** (PreToolUse `Bash|Read`). Raw build and test commands whose flags it fully understands are rewritten to `tkit check` / `tkit test` (cargo, go, tsc, vitest/jest, npm/pnpm/yarn/bun test, dotnet, pytest, dart/flutter, mvn, gradle, mix, zig, swift, ctest, rspec, phpunit/pest, sbt; `.exe`/`.cmd` names included). `ssh HOST CMD` and `scp` become `tkit ssh`. A plain `cat` of project files totalling 12k+ characters goes through `tview`: bodies longer than 8 lines fold to their signature plus the exact `sed -n a,bp` command that prints them, in any language (tmap's parser where it has one, an indentation-based fallback for Luau, Lua, Ruby, Java, C#, Kotlin, C/C++ and the rest), and lines over 400 characters are cut; smaller, focused reads print unchanged. The whole view stays under Claude Code's Bash output limit (`BASH_MAX_OUTPUT_LENGTH`, default 30000, minus 4000): past that limit Claude Code keeps only a 2KB preview, so the largest code files become outlines (each definition with its line range) and documents print whole. A brace group (`src/{a,b}.ts`) is checked like a glob and left for the shell; a `cat` piped into anything but `head`/`tail` is not rewritten. A `grep` or `rg` whose output is not piped goes through `tkit run --group`: each file's path once above its lines, lines over 500 characters cut, at most 200 lines with the full output saved; a recursive `grep` also skips `.git`, `node_modules`, `.venv`, `__pycache__` and a cargo `target` it does not name. File lists, counts and quiet greps run unchanged. `gh run view --log` goes through `tkit run --fuzzy`. A rewrite happens only when every segment becomes a tkit/tview call or is read-only (`grep`, `sed -n`, `ls`, `git status`…), or the session already bypasses permissions; otherwise the line runs unchanged, so a rewrite never adds a prompt. Lines with a heredoc are never touched. Where the prompt cache expires after 5 idle minutes (subagents; a main session only when its transcript shows that cache), a polling loop that asks for more than 4 minutes gets 4 (`until`/`while`/`for` with `sleep` and only reads such as `grep`, `test`, `tail`, `pgrep`), with a one-time note to run it again: a longer wait lets the cache expire, and the next call rewrites the whole context at 12.5× the price of reading it (394 such waits cost 112M input-equivalent tokens in 14 days). Builds, tests, writes and background commands keep their timeout. Refused, with the command to use instead: interactive `ssh HOST`, installers that would stop for an answer, and `less`/`more` or a `cat` in a pipeline inside `node_modules`, `~/.cargo/registry`, Go `pkg/mod`, `~/.m2`, `~/.nuget`, wally and pub caches (`tkit deps api`). Narrowed with a note instead of refused, since Claude Code shows any refusal as "hook error": a lone `cat` of dependency source goes through `tview`; a whole-file Read of dependency source, a lockfile, a minified or generated file reads its first 200 lines (shorter ones are read whole); focused `grep`/`sed -n`/`head` slices go through. A whole Read of a saved tool output of 8k+ characters (`tool-results/*.txt`, whose start Claude Code already previewed) reads its last ~8k characters. Narrowed Reads carry no permission decision, so the usual permission check applies; repeating the same whole Read loads all of it. Anything else runs unchanged. Escape hatches: prefix one command with `TFORGE_RAW=1` (or `TS_RAW=1`; an `export` does not count), or repeat the identical call. With `TFORGE_REDIRECT=1`, a Bash `grep`/`rg`/`git grep` for one code identifier is answered by `tkit ctx` the same way. Off: `TFORGE_KIT_ROUTE=0`. - **Prompt router** (UserPromptSubmit). Keywords pick review, debug, write or inspect, and that mode's first context is pre-loaded: `tkit diff` for a review (for a PR, Claude is told to run `tkit diff --pr N`: hooks make no network calls), a pasted stack trace resolved by `tkit debug --trace`, `tkit analog` for `backticked` literals when writing, `tkit ctx` for `backticked` symbols when inspecting. Silent for slash commands, short prompts, prompts that match no mode and folders outside git. At most 300 lines (`TFORGE_ROUTE_MAX_LINES`), 8 s per tkit call (`TFORGE_ROUTE_TIMEOUT_MS`). Opt-in since 0.7.0 (`TFORGE_KIT_PROMPT=1`): its mode guess misfired on feature work and its pre-load is re-read on every call. - **MCP distill** (PostToolUse `mcp__.*`). An MCP result over 6000 bytes is read by Haiku (`tkit distill`) and Claude gets only the facts. Put `#raw` in the tool input for the exact text. Small results, a missing tmap binary, or a failed or timed-out model call leave the result unchanged. Off: `TFORGE_KIT_DISTILL=0`. @@ -330,7 +395,7 @@ The plugin puts `tforge` on Claude's PATH. You can also run it yourself with `no ``` tforge init example .forge/plan.json tforge validate check the plan, print task order -tforge run [--only a,b] [--force a,b] [-j N] [--dry-run] [--detach] +tforge run [--only a,b] [--force a,b] [-j N] [--dry-run] [--detach] [--proxy] tforge wait wait for a detached run (up to 9 min per call), print its summary tforge status task states and spend tforge prompt the exact prompt a worker receives @@ -362,7 +427,9 @@ tforge gc [--dry-run] [--json] | `tasks[].files` | Files the task owns. Every file has exactly one owner. Writes outside them are recorded in the ledger. | | `tasks[].reads` | Extra files inlined for this task only. | | `tasks[].deps` | Tasks that must pass first. A failed dependency blocks its dependents. | -| `tasks[].verify` | The task's check. Without one, the task passes as soon as its files exist. | +| `tasks[].verify` | The task's check, one line (join steps with `&&`). Without one, the task passes as soon as its files exist. `tforge validate` warns about destructive commands in it (`rm -rf /`, `git push`, `curl … \| sh`, `sudo`). | +| `tasks[].sensitive` | `true` runs this task's check in a temporary git worktree of HEAD holding the current edits (gitignored files such as `node_modules` are not copied), removed afterwards, even on timeout. Refused outside git. | +| `isolateChecks` | `true` does the same for every task's check and the final `verify`. | | `tasks[].model` | `haiku`, `sonnet` or `opus`. | | `defaults` | `model`, `integrateModel`, `tools`, `maxTurns` (12), `retries` (2), `escalate` (true), `budgetUsd` (1.5 per attempt), `timeoutMin` (20), `verifyTimeoutMin` (10), `inlineMaxChars` (60000). | @@ -384,11 +451,17 @@ Workers run with `--permission-mode acceptEdits` and only `Read`, `Write` and `E | `TFORGE_WATCH` | | `0` disables the context budget | | `TFORGE_WATCH_INJECT` | | `1` also puts the budget notes into Claude's context | | `TFORGE_VIEW_CHARS` / `TFORGE_VIEW_FOLD` / `TFORGE_VIEW_LINES` | `12000` / `8` / `40` | `tview`: dump size that folds, body lines that fold, file lines that fold | +| `TFORGE_VIEW_MAX` | `BASH_MAX_OUTPUT_LENGTH` − 4000 (26000) | `tview`: output budget; past it the largest code files are outlined | | `TFORGE_CHECKPOINT` | | `0` stops writing snapshots | | `TFORGE_SNAPSHOT_PROMPTS` / `TFORGE_SNAPSHOT_KEEP` | `6` / `50` | Requests per snapshot chunk; most chunks kept per project | -| `TFORGE_HANDOFF_MAX_AGE_H` | `72` | Ignore older handoffs; an older automatic one is deleted | +| `TFORGE_HANDOFF_MAX_AGE_H` | `336` | Ignore older handoffs; an older automatic one is moved to `.forge/handoffs/` | +| `TFORGE_RELOAD_ON` | `compact,resume` | When to reload beyond startup and `/clear` (`0`: neither); `reloadOn` in `config.json` | +| `TFORGE_STATE_FILES` | | Comma-separated globs of state files to reload; `stateFiles` in `config.json` | +| `TFORGE_SUBAGENT_SKIP` | | Agent types tokenforge leaves alone (`spec-audit:*`); `subagentSkip` in `config.json` | +| `TFORGE_LEAN_KEEP` | | Tools lean levels never deny; `leanKeep` in `config.json` | | `TFORGE_TERSE` | | `full`, `lite` or `off`; overrides the saved choice | -| `TFORGE_MAP` | | `1` adds the tmap hint at session start | +| `TFORGE_MAP` | | `0`: no repo map at session start; `1`: the one-line tmap hint instead | +| `TFORGE_MAP_CHARS` | `3000` | Size cap of the repo map loaded at session start | | `TFORGE_REDIRECT` | | `1` answers identifier Grep calls, identifier greps in Bash, and big whole-file reads from tmap | | `TFORGE_KIT_HOOKS` | | `0` disables all tkit hooks (policy, Bash router, prompt router, MCP distill) | | `TFORGE_KIT_POLICY` / `TFORGE_KIT_ROUTE` / `TFORGE_KIT_DISTILL` | | `0` disables that one hook | @@ -411,6 +484,18 @@ Workers run with `--permission-mode acceptEdits` and only `Read`, `Write` and `E | `TFORGE_BANNER` | | `0` hides the "TokenForge: active" line at startup and the checkpoint line after `/clear` | | `TFORGE_UI` | | `0` stops the dashboard from starting with your first session (it never auto-starts in headless `claude -p`, SDK or CI sessions) | | `TFORGE_UI_PORT` | `7878` | Dashboard port (the next free one is used if taken) | +| `TFORGE_PROXY` | | `0` before the first session: the proxy is not turned on by default | +| `TFORGE_PROXY_PORT` | `7879` | `tforge proxy` / `tforge claude` port, and the one the default setup uses | +| `TFORGE_PROXY_PRUNE` | `cost` | Stale-context pruning: `cost`, `tokens` or `off` (see API proxy) | +| `TFORGE_PROXY_PRUNE_WRITES` | on | `0`: written bodies and ran scripts are pruned only when read back or rewritten, not by age | +| `TFORGE_PROXY_PRUNE_MIN` | `8000` | Stale characters needed before a `tokens` batch goes | +| `TFORGE_PROXY_COMPRESS` / `TFORGE_PROXY_FOLD` | | `0`: the proxy only logs / does not fold whole-file Reads | +| `TFORGE_PROXY_CAP` | `16000` | Characters of Bash and other text output the proxy keeps (head and tail); `0`: no cap | +| `TFORGE_RUN_PROXY` | | `1`: `tforge run` workers go through the proxy, the same as `--proxy` or `"proxy": true` in the plan | +| `TFORGE_PROXY_MEMO_MB` | `64` | Size cap of the proxy's memo of compressed results | +| `TFORGE_PROXY_UPSTREAM` | | Where the proxy forwards (default: an existing `ANTHROPIC_BASE_URL`, else the Anthropic API) | +| `TFORGE_PROXY_TTL` | `5m` for `claude -p`, else Claude Code's | `5m`: 5-minute prompt cache instead of 1 hour (header `x-tokenforge-cache-ttl: 5m` for one client); `1h`: never change it | +| `TFORGE_PROXY_OPENAI_UPSTREAM` | `https://api.openai.com` | Where the proxy forwards `/v1/responses` (Codex) | | `TFORGE_NO_DOWNLOAD` | | `1` never downloads tmap; build with cargo instead | | `TFORGE_DISTILL_MODEL` / `_TIMEOUT` / `_MAX_BYTES` | `haiku` / `120` / `480000` | Model, timeout (s) and input cap for `tkit distill` and `web --ask` | @@ -427,7 +512,7 @@ python3 runner/bench.py run --all Results go to `bench/reports/benchmark-report.md`. See [bench/README.md](bench/README.md) for the method, metrics and scoring. -**Planning line A/B** (shipped as the default; [full report](bench/reports/final-comparison.md)). TokenForge with the planning line against TokenForge without it, plus `brief` as an ablation: 36 tasks, one run per task and arm, the three arms run at the same time on Claude Code 2.1.295. List cost −15% per task (geometric mean, 95% CI −21% to −10%; pooled −19%; lower on 27 of 36 tasks), thinking −44%, total tokens −22%, wall-clock −21% (pooled); quality −0.26 points (CI −1.03 to +0.52), hidden tests 1215/1219 in both arms. Nine tasks cost more (up to +26%, `architecture`), mostly existing-codebase and Q&A tasks with little thinking to cut; four scored lower and two higher, each explained in the report. The line's own 106 input tokens per session are included. +**Planning line A/B** (shipped as the default; [full report](bench/reports/final-comparison.md)). TokenForge with the planning line against TokenForge without it, plus `brief` as an ablation: 36 tasks, one run per task and arm, the three arms run at the same time, on a 0.8.0 development build of tokenforge (build c9de32de) on Claude Code 2.1.295. List cost −15% per task (geometric mean, 95% CI −21% to −10%; pooled −19%; lower on 27 of 36 tasks), thinking −44%, total tokens −22%, wall-clock −21% (pooled); quality −0.26 points (CI −1.03 to +0.52), hidden tests 1215/1219 in both arms. Nine tasks cost more (up to +26%, `architecture`), mostly existing-codebase and Q&A tasks with little thinking to cut; four scored lower and two higher, each explained in the report. The line's own 106 input tokens per session are included. **Experiments that did not ship** (TokenForge-only variants, one run per task, kept apart from the main results): diff --git a/ROADMAP.md b/ROADMAP.md index 2d22bf8..6f8e05e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ Updated 2026-10-09. -0.9.2 adds no features. It makes the savings safe and checkable: a cache reuses an answer only while it still holds, a rewritten command behaves like the original, and every published number names the version that produced it. +0.9.2 makes the savings safe and checkable: a cache reuses an answer only while it still holds, a rewritten command behaves like the original, and every published number names the version that produced it. This plan follows an external review of the public repo. The review read the docs and the benchmark method, not the code or the test suite. @@ -25,8 +25,8 @@ This plan follows an external review of the public repo. The review read the doc Today every benchmark run records the TokenForge and Claude Code versions, and the environment a hash of the plugin files. But the site's headline figures come from 0.8.0 runs while its pages show the current version, 0.9.1. The benchmarked version is named only further down the benchmark page. -- [ ] Show the TokenForge version, build hash and Claude Code version next to every published figure: site, README, reports. -- [ ] Refuse to build a report from runs of different versions, unless it labels each one. +- [ ] Show the TokenForge version, build hash and Claude Code version next to every published figure: site, README, reports. README and reports done; the site is not. +- [x] Refuse to build a report from runs of different versions, unless it labels each one. ## P0: A safer answer cache @@ -34,11 +34,11 @@ An unchanged project does not prove an answer still holds. "Do the tests pass?" Today an earlier answer is replayed only for the same question, from a turn that edited nothing, when no project file (tracked, or untracked and not ignored) has changed since. Prompts that ask to review, verify, check or audit (English and French) skip it. Sending the message again asks Claude; `TFORGE_ANSWER_CACHE=0` turns it off. -- [ ] Never replay an answer to a request to run, test, build or verify something, to a security question, or to a question about the current state ("is it up", "latest", "now"). -- [ ] Tell questions that ask for information from requests that need an action or a fresh observation. When unsure, ask Claude. -- [ ] Include the repo's identity, the model, the configuration and the relevant dependencies in the cache's validity, where they affect the answer. -- [ ] An explicit, visible bypass that works before sending, not only by sending again. -- [ ] Adversarial tests for false positives: the same words with another intent, other languages, a changed environment with unchanged files. +- [x] Never replay an answer to a request to run, test, build or verify something, to a security question, or to a question about the current state ("is it up", "latest", "now"). +- [x] Tell questions that ask for information from requests that need an action or a fresh observation. When unsure, ask Claude. +- [x] Include the repo's identity, the model, the configuration and the relevant dependencies in the cache's validity, where they affect the answer. +- [x] An explicit, visible bypass that works before sending, not only by sending again. +- [x] Adversarial tests for false positives: the same words with another intent, other languages, a changed environment with unchanged files. ## P0: Formal cache invalidation @@ -70,7 +70,7 @@ The Bash router turns some commands into `tkit` calls or compacts their output. Today the tests check the rewritten command line. Build and test commands are rewritten only when their flags are fully understood, heredocs are never touched, and a `TFORGE_RAW=1` prefix runs a command as typed. -- [ ] Differential tests: run the original and the rewritten command, compare exit codes and outputs. +- [x] Differential tests: run the original and the rewritten command, compare exit codes and outputs. - [ ] Property tests over quoting, pipes, redirections, substitutions, paths with spaces, environment variables and exit codes. - [ ] Check that output caps never hide an error at the end of a log. - [ ] Compare `tkit test` with the native test command. @@ -97,10 +97,10 @@ Workers can't run commands: the driver runs each task's `verify` command from th Today checks run in your checkout with a time limit (`verifyTimeoutMin`, 10 minutes by default). The docs say to read a plan before running it and to build on a branch or a worktree. -- [ ] Stricter validation of `verify` commands. +- [x] Stricter validation of `verify` commands. - [ ] Time limits and working directories enforced for every check. - [ ] Side effects of checks isolated. -- [ ] For sensitive tasks, checks run in a git worktree or a sandbox, never in the current environment without inspection. +- [x] For sensitive tasks, checks run in a git worktree or a sandbox, never in the current environment without inspection. ## P2: Adaptive orchestration @@ -114,12 +114,20 @@ The goal is the cheapest setup for the actual task, not workers by default. ## P2: Lean levels: measure the whole cost -`balanced`, `max` and `ultra` hide tools: `max` and `ultra` hide skills and subagents, `ultra` also the native Read, Edit and Write. If `ultra` saves tool definitions but causes more Bash calls, quoting errors or failed edits, the saving can vanish. +`balanced`, `max` and `ultra` hide tools: `max` and `ultra` hide skills and subagents, `ultra` also the native Read, Edit and Write, and asks for edits through `tkit edit`. If `ultra` saves tool definitions but causes more Bash calls, quoting errors or failed edits, the saving can vanish. Today each level's fixed context per request is measured. - [ ] A report per level: tokens, cost, quality, time, attempts and regressions, not only the starting context. +## P2: Smaller code reads + +With lean `ultra` and the proxy, 6 benchmark tasks save a median 57% of tokens (9 runs per task against 4 native runs, quality unchanged). Most of what is left is code read through Bash: in 18 runs, `cat` returned 345k characters and `sed -n` 229k, read again on every later call until pruned. Architecture and banking-transfers sit at 55-59%; 3 more points on each would put the median past 60%. + +- [ ] Replay the recorded commands (no API calls): which `cat` and `sed -n` outputs are long enough to fold, and how often the model reads the same lines again after a fold. +- [ ] Fold `sed -n` ranges only where the replay shows no re-read: a range is a deliberate read, and folding one can cost a second call. +- [ ] Prune a file's earlier reads once a later read or an edit of the same file supersedes them. + ## Caching Six layers with six sets of dependencies. They share one validity policy, with rules for each layer. diff --git a/bench/runner/bench.py b/bench/runner/bench.py index 71ba659..fa7eb91 100644 --- a/bench/runner/bench.py +++ b/bench/runner/bench.py @@ -7,8 +7,9 @@ bench.py run --smoke bench.py run --task ID[,ID...] [--agent native|token-forge | --both] [--reps N] bench.py run --all [--reps N] [--subset-reps ID,ID --subset-n N] - bench.py compare [--session DIR ...] - bench.py report [--session DIR ...] + bench.py compare [--session DIR ...] [--mixed-versions] refuses runs of different TokenForge builds + or Claude Code versions unless --mixed-versions + bench.py report [--session DIR ...] [--mixed-versions] bench.py retelemetry [--session DIR ...] [--force] re-derive telemetry.json from saved transcripts Common run options: --max-tokens N --warn-tokens N --max-budget-usd X --jobs N --seed N @@ -581,7 +582,7 @@ def cmd_compare(args): import report sessions = [Path(s) for s in args.session] if args.session else \ [p for p in sorted(RUNS.iterdir()) if p.is_dir() and not p.name.endswith("-smoke")] - report.build(sessions, ROOT) + report.build(sessions, ROOT, mixed_versions=getattr(args, "mixed_versions", False)) return 0 @@ -655,6 +656,9 @@ def main(): help="authenticate with the local Claude Code login's current access token (read-only, never refreshed)") for name in ("compare", "report", "retelemetry"): c = sub.add_parser(name); c.add_argument("--session", nargs="*") + if name != "retelemetry": + c.add_argument("--mixed-versions", action="store_true", + help="build the report from runs of different TokenForge builds or Claude Code versions, each row labelled") c.add_argument("--force", action="store_true", help="also rewrite runs whose re-derived values differ") a = ap.parse_args() if a.cmd == "run": diff --git a/bench/runner/report.py b/bench/runner/report.py index 2148842..da3f904 100644 --- a/bench/runner/report.py +++ b/bench/runner/report.py @@ -7,7 +7,7 @@ import json import math import statistics as st -from collections import defaultdict +from collections import Counter, defaultdict from pathlib import Path import telemetry @@ -95,7 +95,51 @@ def fmt(x, d=0): return str(x) -def build(sessions, root: Path, out_name="benchmark-report"): +def tf_build(r): + """(TokenForge version, plugin build hash) of a Token Forge run; None for other agents.""" + if r.get("agent") != "token-forge": + return None + return (r.get("token_forge_version") or "unknown", r.get("token_forge_plugin_sha256") or "unknown") + + +def build_label(b): + """'0.8.0 (build 31952bff7273)' for a tf_build() pair.""" + return f"{b[0]} (build {b[1][:12]})" + + +def versions(runs): + """The TokenForge builds and Claude Code versions a set of runs comes from, with run counts.""" + tf = Counter(tf_build(r) for r in runs if r.get("agent") == "token-forge") + cc = Counter(r.get("claude_code_version") or "unknown" for r in runs) + return {"token_forge": [{"version": v, "plugin_sha256": h, "runs": n} for (v, h), n in sorted(tf.items())], + "claude_code": [{"version": v, "runs": n} for v, n in sorted(cc.items())]} + + +def provenance(v): + """One line naming the versions behind a figure or table, e.g. for a caption.""" + tf = "; ".join(f"{build_label((x['version'], x['plugin_sha256']))}, {x['runs']} runs" for x in v["token_forge"]) + cc = "; ".join(f"{x['version']}, {x['runs']} runs" for x in v["claude_code"]) + return f"TokenForge {tf or 'none'} · Claude Code {cc or 'none'}" + + +class MixedVersions(SystemExit): + pass + + +def check_versions(runs, mixed=False, what="report"): + """Refuse runs of more than one TokenForge version or build, or Claude Code version, unless mixed is set + (the caller then labels each row or series with its version). Returns versions(runs).""" + v = versions(runs) + if not mixed and (len(v["token_forge"]) > 1 or len(v["claude_code"]) > 1): + lines = [f"{what}: refusing to combine runs of different versions:"] + lines += [f" TokenForge {build_label((x['version'], x['plugin_sha256']))}: {x['runs']} runs" for x in v["token_forge"]] + lines += [f" Claude Code {x['version']}: {x['runs']} runs" for x in v["claude_code"]] + lines.append("Use runs of one version, or pass --mixed-versions to label each row or series with its version.") + raise MixedVersions("\n".join(lines)) + return v + + +def build(sessions, root: Path, out_name="benchmark-report", mixed_versions=False): root = Path(root) runs = load_runs(sessions) # Only Token Forge runs of the plugin build under test (environments/token-forge/manifest.json) count; @@ -114,6 +158,7 @@ def build(sessions, root: Path, out_name="benchmark-report"): # their runs stay in runs/ and are listed in the report excluded_tasks = json.loads((root / "benchmark.config.json").read_text()).get("excluded_tasks", {}) runs = [r for r in runs if r.get("task") not in excluded_tasks] + used = check_versions(runs, mixed_versions, f"reports/{out_name}") executed = [r for r in runs if r.get("status") in EXECUTED] not_run = [r for r in runs if r.get("status") not in EXECUTED] by_task = defaultdict(lambda: defaultdict(list)) @@ -133,6 +178,8 @@ def build(sessions, root: Path, out_name="benchmark-report"): row[agent]["subagent_calls"] = med([{"x": tool(r, "subagent_calls")} for r in rs], "x") row[agent]["completion_rate"] = round(sum(bool(r.get("task_completed")) for r in rs) / len(rs), 3) if rs else None row[agent]["statuses"] = [r.get("status") for r in rs] + row[agent]["versions"] = sorted({build_label(tf_build(r)) if agent == "token-forge" else f"Claude Code {r.get('claude_code_version')}" + for r in rs}) row[agent]["tests_passed"] = [r.get("tests_passed") for r in rs] q, t = row[agent]["quality_score"], row[agent]["total_tokens"] row[agent]["tokens_per_quality_point"] = round(t / q, 1) if q and t else None @@ -274,6 +321,7 @@ def col(key): "excluded_runs_other_build": [f"{r['_session']}/{r.get('run_id')}" for r in other_build], "excluded_runs_other_claude_code": [f"{r['_session']}/{r.get('run_id')}" for r in other_cc], "excluded_tasks": excluded_tasks, + "versions_used": used, "mixed_versions": bool(mixed_versions), "aggregate": agg, "per_agent": per_agent, "per_category": per_cat, "per_task": per_task, "validation": validation, "runs": [{k: v for k, v in r.items() if not k.startswith("_")} | {"tools": (r.get("_tel") or {}).get("tools"), @@ -293,14 +341,19 @@ def render_md(d): L = ["# Token Forge vs clean Claude Code — benchmark report", ""] s0 = next(iter(d["sessions"].values()), {}) b = d["token_forge_build"] + used = d.get("versions_used") or versions(d.get("runs", [])) + mixed = d.get("mixed_versions") + cap = [f"_Runs used: {provenance(used)}" + (" (mixed versions: Token Forge rows name their build)" if mixed else "") + "._", ""] + who = lambda ag, x: LABEL[ag] + (f" {', '.join(x.get('versions', []))}" if mixed and ag == "token-forge" else "") # noqa: E731 L += [f"Model `{s0.get('model')}`, Claude Code {s0.get('claude_code_version')}, benchmark {s0.get('benchmark_version')}. " f"Token Forge build under test: {b['version']} (plugin sha256 `{(b['plugin_sha256'] or '')[:12]}`, git {(b['plugin_git_commit'] or '')[:8]}{' + uncommitted changes' if b['plugin_git_dirty'] else ''}), lean: {b.get('lean') or 'off'}. " f"Sessions: {', '.join(d['sessions'])}.", ""] + L += [f"**Versions of the runs in this report:** {provenance(used)}.", ""] if d["excluded_runs_other_build"]: L += [f"Excluded: {len(d['excluded_runs_other_build'])} Token Forge runs of other plugin builds (listed in the JSON report).", ""] for tid, why in (d.get("excluded_tasks") or {}).items(): L += [f"Excluded task `{tid}`: {why}", ""] - L += ["## Executive summary", ""] + L += ["## Executive summary", ""] + cap ts = a["token_savings_percent"] if ts: L += [f"Across {a['tasks_paired']} paired tasks ({a['runs_executed']} executed runs, {a['runs_not_executed']} not executed):", "", @@ -318,14 +371,14 @@ def render_md(d): L += ["No paired measurements yet.", ""] L += ["Positive savings mean Token Forge used fewer tokens; negative means it used more. " "`total tokens` = input + cache writes + cache reads + output, summed over the main session, subagents and nested `claude -p` sessions.", ""] - L += ["## Per-task comparison (median over repetitions)", "", + L += ["## Per-task comparison (median over repetitions)", "", *cap, "| Task | Agent | Runs | Total tokens | Input | Output | Uncached in | Cost $ | Tool calls | Files read | Tests | Quality | Status |", "|---|---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:|---|"] for r in d["per_task"]: for ag in AGENTS: x = r[ag] tests = ",".join("PASS" if t else ("FAIL" if t is False else "n/a") for t in x["tests_passed"]) - L.append(f"| {r['task']} | {LABEL[ag]} | {r['runs'][ag]} | {fmt(x['total_tokens'])} | {fmt(x['input_tokens'])} | {fmt(x['output_tokens'])} | " + L.append(f"| {r['task']} | {who(ag, x)} | {r['runs'][ag]} | {fmt(x['total_tokens'])} | {fmt(x['input_tokens'])} | {fmt(x['output_tokens'])} | " f"{fmt(x['uncached_input_tokens'])} | {fmt(x['total_cost_usd_reported'], 2)} | {fmt(x['tool_calls'])} | {fmt(x['files_read_incl_bash'])} | {tests} | " f"{fmt(x['quality_score'], 1)} | {','.join(map(str, x['statuses']))} |") L += ["", "| Task | Token diff | Savings % | Input % | Output % | Thinking % | Uncached % | List cost % | Quality Δ | Tool calls % | Files read % | Lines read % |", @@ -337,13 +390,13 @@ def render_md(d): L.append(f"| {r['task']} | {fmt(x['total_tokens_abs'])} | {fmt(x['token_savings_percent'], 1)} | {fmt(x['input_savings_percent'], 1)} | " f"{fmt(x['output_savings_percent'], 1)} | {fmt(x['thinking_savings_percent'], 1)} | {fmt(x['uncached_input_savings_percent'], 1)} | {fmt(x['list_cost_savings_percent'], 1)} | " f"{fmt(x['quality_diff'], 1)} | {fmt(x['tool_call_diff_percent'], 1)} | {fmt(x['files_read_diff_percent'], 1)} | {fmt(x['lines_read_diff_percent'], 1)} |") - L += ["", "## Quality-adjusted efficiency", "", "| Task | Native tokens/quality pt | TF tokens/quality pt | Native quality/Mtok | TF quality/Mtok |", "|---|---:|---:|---:|---:|"] + L += ["", "## Quality-adjusted efficiency", "", *cap, "| Task | Native tokens/quality pt | TF tokens/quality pt | Native quality/Mtok | TF quality/Mtok |", "|---|---:|---:|---:|---:|"] for r in d["per_task"]: L.append(f"| {r['task']} | {fmt(r['native']['tokens_per_quality_point'])} | {fmt(r['token-forge']['tokens_per_quality_point'])} | " f"{fmt(r['native']['quality_per_million_tokens'], 2)} | {fmt(r['token-forge']['quality_per_million_tokens'], 2)} |") - L += ["", "## Distribution statistics (all executed runs)", ""] + L += ["", "## Distribution statistics (all executed runs)", ""] + cap for ag in AGENTS: - L += [f"**{LABEL[ag]}** ({pa[ag]['runs']} runs)", "", "| Metric | mean | median | min | max | stdev |", "|---|---:|---:|---:|---:|---:|"] + L += [f"**{LABEL[ag]}** ({pa[ag]['runs']} runs; {', '.join(sorted({v for r in d['per_task'] for v in r[ag].get('versions', [])}))})", "", "| Metric | mean | median | min | max | stdev |", "|---|---:|---:|---:|---:|---:|"] for k in METRICS: x = pa[ag][k] if x: @@ -351,16 +404,16 @@ def render_md(d): L.append("") if ts: L += ["Per-task token savings %: " + ", ".join(f"{k} {ts[k]}" for k in ("mean", "median", "p10", "p25", "p75", "p90")), ""] - L += ["## Per-category results", "", "| Category | Tasks | Median savings % | Median quality Δ | Verdict |", "|---|---|---:|---:|---|"] + L += ["## Per-category results", "", *cap, "| Category | Tasks | Median savings % | Median quality Δ | Verdict |", "|---|---|---:|---:|---|"] for c, x in d["per_category"].items(): L.append(f"| {c} | {', '.join(x['tasks'])} | {fmt(x['median_token_savings_percent'], 1)} | {fmt(x['median_quality_diff'], 1)} | {x['verdict']} |") - L += ["", "## Why: tool and context traces (medians)", "", + L += ["", "## Why: tool and context traces (medians)", "", *cap, "| Task | Agent | API requests | First-request context | Lines read | Tool-result bytes | Redundant reads | Context precision≈ | Subagents | Nested-session tokens |", "|---|---|---:|---:|---:|---:|---:|---:|---:|---:|"] for r in d["per_task"]: for ag in AGENTS: x = r[ag] - L.append(f"| {r['task']} | {LABEL[ag]} | {fmt(x['api_requests'])} | {fmt(x['first_request_context_tokens'])} | {fmt(x['lines_read'])} | " + L.append(f"| {r['task']} | {who(ag, x)} | {fmt(x['api_requests'])} | {fmt(x['first_request_context_tokens'])} | {fmt(x['lines_read'])} | " f"{fmt(x['tool_result_bytes'])} | {fmt(x['redundant_reads'])} | {fmt(x['context_precision_approx'], 2)} | {fmt(x['subagent_calls'])} | {fmt(x['nested_session_tokens'])} |") L += ["", "Context precision is approximate: the share of files read that match the task's `relevant_files` globs. " "Files read via `cat`/`sed`/`head` in Bash are detected heuristically.", ""] diff --git a/bench/runner/test_versions.py b/bench/runner/test_versions.py new file mode 100644 index 0000000..253b9ba --- /dev/null +++ b/bench/runner/test_versions.py @@ -0,0 +1,97 @@ +"""Tests for the version guard in report.py: python3 -m unittest discover -s bench/runner -p 'test_*.py'""" +import json +import tempfile +import unittest +from pathlib import Path + +import report + +SHA_A, SHA_B = "a" * 64, "b" * 64 + + +def run(task, agent, tf="0.8.0", sha=SHA_A, cc="2.1.293", tokens=1000): + tfr = agent == "token-forge" + return {"run_id": f"{task}-{agent}-{tf}", "task": task, "category": "c", "agent": agent, "status": "completed", + "task_completed": True, "claude_code_version": cc, "token_forge_version": tf if tfr else None, + "token_forge_plugin_sha256": sha if tfr else None, "total_tokens": tokens, "quality_score": 100, + "repository_commit": "x", "prompt_hash": "p", "tests_passed": True} + + +class Guard(unittest.TestCase): + def test_one_version_passes_and_is_named(self): + v = report.check_versions([run("t", "native"), run("t", "token-forge")]) + self.assertEqual(v["token_forge"], [{"version": "0.8.0", "plugin_sha256": SHA_A, "runs": 1}]) + self.assertEqual(report.provenance(v), "TokenForge 0.8.0 (build aaaaaaaaaaaa), 1 runs · Claude Code 2.1.293, 2 runs") + + def test_different_versions_refused_with_list(self): + rs = [run("t", "token-forge", "0.7.0", SHA_B), run("u", "token-forge")] + with self.assertRaises(SystemExit) as e: + report.check_versions(rs, what="reports/x") + msg = str(e.exception.code) + self.assertIn("0.7.0 (build bbbbbbbbbbbb): 1 runs", msg) + self.assertIn("0.8.0 (build aaaaaaaaaaaa): 1 runs", msg) + self.assertIn("--mixed-versions", msg) + + def test_same_version_other_build_refused(self): + with self.assertRaises(SystemExit): + report.check_versions([run("t", "token-forge"), run("u", "token-forge", sha=SHA_B)]) + + def test_claude_code_versions_refused(self): + with self.assertRaises(SystemExit): + report.check_versions([run("t", "native", cc="2.1.293"), run("t", "native", cc="2.1.295")]) + + def test_flag_allows_mix(self): + v = report.check_versions([run("t", "token-forge", "0.7.0", SHA_B), run("u", "token-forge")], mixed=True) + self.assertEqual(len(v["token_forge"]), 2) + + def test_published_report_is_mixed(self): + # bench/reports/benchmark-report.json: 0.7.0 runs (two builds) and 0.8.0 runs; a rebuild needs --mixed-versions + p = Path(__file__).resolve().parents[1] / "reports" / "benchmark-report.json" + if not p.exists(): + self.skipTest("no published report") + rs = json.loads(p.read_text())["runs"] + with self.assertRaises(SystemExit): + report.check_versions(rs) + self.assertGreater(len(report.check_versions(rs, mixed=True)["token_forge"]), 1) + + +class Build(unittest.TestCase): + def make(self, d, runs): + root = Path(d) + (root / "environments" / "token-forge").mkdir(parents=True) + (root / "environments" / "token-forge" / "manifest.json").write_text(json.dumps( + {"token_forge_version": "0.8.0", "plugin_sha256": SHA_A, "claude_code_version": "2.1.293"})) + (root / "benchmark.config.json").write_text(json.dumps({"token_forge": {"equivalent_builds": {SHA_B: "older"}}})) + s = root / "runs" / "s1" + for r in runs: + m = s / r["task"] / r["run_id"] / "manifest.json" + m.parent.mkdir(parents=True) + m.write_text(json.dumps(r)) + return root, s + + def test_report_refuses_then_labels(self): + rs = [run("t", "native"), run("t", "token-forge", "0.7.0", SHA_B), run("u", "native"), run("u", "token-forge")] + with tempfile.TemporaryDirectory() as d: + root, s = self.make(d, rs) + with self.assertRaises(SystemExit): + report.build([s], root) + self.assertFalse((root / "reports" / "benchmark-report.md").exists()) + report.build([s], root, mixed_versions=True) + md = (root / "reports" / "benchmark-report.md").read_text() + self.assertIn("| t | Token Forge 0.7.0 (build bbbbbbbbbbbb) |", md) + self.assertIn("| u | Token Forge 0.8.0 (build aaaaaaaaaaaa) |", md) + self.assertIn("**Versions of the runs in this report:** TokenForge 0.7.0 (build bbbbbbbbbbbb), 1 runs; " + "0.8.0 (build aaaaaaaaaaaa), 1 runs · Claude Code 2.1.293, 4 runs.", md) + + def test_single_version_report_names_it_under_every_table(self): + rs = [run("t", "native"), run("t", "token-forge")] + with tempfile.TemporaryDirectory() as d: + root, s = self.make(d, rs) + md = report.render_md(report.build([s], root)) + cap = "_Runs used: TokenForge 0.8.0 (build aaaaaaaaaaaa), 1 runs · Claude Code 2.1.293, 2 runs._" + self.assertEqual(md.count(cap), 6) + self.assertIn("| t | Token Forge |", md) # rows are labelled only when versions are mixed + + +if __name__ == "__main__": + unittest.main() diff --git a/bench/scripts/charts.py b/bench/scripts/charts.py index 9ef2f69..40869b7 100644 --- a/bench/scripts/charts.py +++ b/bench/scripts/charts.py @@ -1,7 +1,11 @@ #!/usr/bin/env python3 """Render the README charts (docs/img/*.svg) from raw benchmark runs. - python3 bench/scripts/charts.py + python3 bench/scripts/charts.py [--mixed-versions] + +Every chart names the TokenForge version, plugin build hash and Claude Code version of the runs it draws. Runs of +more than one TokenForge build or Claude Code version in one chart are refused unless --mixed-versions is given; +then each task is labelled with its TokenForge build. Selection, so anyone can check it: native = median of every completed native run per task; tokenforge = the most recent completed run per task for each lean level, read from that run's environment_manifest.json. @@ -12,11 +16,15 @@ """ from __future__ import annotations +import argparse import json import statistics as st +import sys from pathlib import Path BENCH = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BENCH / "runner")) +import report # noqa: E402 OUT = BENCH.parent / "docs" / "img" LABEL = {"cross-module-debug": "Cross-module debug (TS)", "rust-cli": "Rust CLI feature", "pr-review": "PR review (Go)", "architecture": "Architecture tracing (TS)", "rust-debug": "Rust debugging", "banking-transfers": "Scheduled transfers (TS)", @@ -40,6 +48,7 @@ BUILDS = {BUILD, *json.loads((BENCH / "benchmark.config.json").read_text())["token_forge"].get("equivalent_builds", {})} # Measured fixed context per request: first-request context of a one-word prompt in a git repo, settings written # by `tforge lean ` (Claude Code 2.1.293, Opus 5.5). +FLOOR_SOURCE = "Measured with Claude Code 2.1.293 and tokenforge 0.7.0's lean levels (settings only; no benchmark runs)." FLOOR = [("off (Claude Code)", 16929), ("lean on", 11933), ("balanced (default)", 9738), ("lean max", 5755), ("lean ultra", 4401)] STYLE = """