Repository navigation
Measure the MCP schema tax per server, ingest the agent-config surface, make prune/expire performable, and close the fix-prose guard's escapes - #689
Conversation
…ma tax per server, close three fix-prose guard escapes Three analyzers each walked the filesystem themselves at analysis time to answer "what config does this user have", and nothing about it was stored. `core/agent_config` makes the walk a population step and a DuckDB table (migration 22) the thing analyzers read: instruction files from the existing prompt-file catalog, agent files, hooks, and MCP server declarations, each with its size, token count, content hash and last-seen time. That table is what makes the second change affordable. `FULL_SCHEMA_TAX_TOKENS = 25_000` was an assumption charged flat to EVERY configured server on every call, while the only in-repo source for "~25K" describes the tax for ALL of a session's attached servers COMBINED — so the headline dollar figure was linear in an unmeasured constant and multiplied by the server count. Each server is now measured directly (`core/optimize/mcp_probe`): start it, send `initialize` and `tools/list` and nothing else, serialize the schemas as they are injected, count that, cache the answer against the server's launch spec. A server that cannot be measured contributes nothing to any priced figure and says so on its own row; there is no default left to fall back to. The fix-prose guard read green over a ~330-character advisory paragraph because three independent escapes held at once: the slot it was assigned to was not listed, the constant-name check looked for ADVICE while the variable was named advise, and the length floor was borrowed from a constant answering a different question. Name guessing is replaced by tracing what actually reaches a fix slot, the floor is paired with a sentence-count detector for prose stitched around interpolated evidence, `core/summarize/` joins the scanned roots, and `summarize` and `deadweight` finally have catalog records. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ine, plus a priced plugin lane route.py named six verdicts and only compress could reach a write, which left the two largest unrealised recoveries in the tool as advisory prose. The reason was defensible — compression is reversible in principle and deletion is not — but the answer is to make deletion recoverable, not to refuse to act. core/summarize/quarantine holds every removed fragment verbatim under tj's own storage root. It is written, fsync'd and read back from disk BEFORE the source file changes, and a failed or unverifiable write raises before anything is touched, so there is no path that removes content without a committed way back. Restore never trusts a stale line number: placement is by matching the text that surrounded the cut, required to be unambiguous, and it refuses with the entry id when it cannot. Silent corruption of an instruction file is the worse failure — it ships, and the agent follows it. prune acts only on sections the user names, because which rules earn their place is the one question route.py's shape measurement explicitly cannot answer. expire acts on dated entries past a cutoff, which is arithmetic. Both keep the diff-then-approve step compress already uses; quarantine is the net under that gate, not a replacement for it. The plugin lane prices what an enabled plugin costs every session. Two gates decide whether it costs anything and neither is visible on disk: measured against a real machine, 15 of 1,299 installed SKILL.md files were resident, so pricing installed-ness overstates by 87x. Only the name+description listing is counted — a skill body arrives on invocation, and on the same machine bodies outweigh listings by ~4,900x, so counting them is a different number about a different thing. Plugin files stay out of the summarize catalog and a test pins that: they are third-party files under a versioned cache path, and the next plugin update reverts any edit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
| Filename | Overview |
|---|---|
| tokenjam/core/summarize/prune.py | Adds quarantine-backed prune and expiry planning, but repeated selection of one unique heading can still delete unrelated following content. |
| tokenjam/core/agent_config.py | Adds persistent agent-config scanning and measurement caching; project-scoped plugin residency remains disconnected from analyzed session roots. |
| tokenjam/core/optimize/analyzers/deadweight.py | Replaces the flat MCP tax and adds plugin pricing, while same-named declarations with distinct specifications still share one canonical measurement. |
| tokenjam/core/optimize/mcp_probe.py | Adds bounded read-only MCP initialization and tool-schema measurement with cache support. |
| tokenjam/cli/cmd_optimize.py | Renders plugin deadweight details, but plugin identifiers remain unescaped in Rich markup. |
| tokenjam/core/summarize/quarantine.py | Adds durable fragment quarantine and anchor-based restoration for destructive summarize operations. |
| tokenjam/core/db.py | Adds the agent-config table migration and schema self-healing coverage. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart LR
FS[Agent configuration files] --> Ingest[agent_config ingestion]
Ingest --> DB[(agent_config_files)]
DB --> Deadweight[Deadweight analyzer]
Deadweight --> Probe[MCP schema probe]
Probe --> Report[Measured MCP and plugin costs]
Source[Instruction file] --> Plan[Prune or expire plan]
Plan --> Quarantine[Persist removed fragments]
Quarantine --> Apply[Rewrite source]
Quarantine --> Restore[Anchor-based restore]
Prompt To Fix All With AI
### Issue 1
tokenjam/core/summarize/prune.py:205-217
**Duplicate selections corrupt pruning**
When the same unique heading is supplied more than once, each occurrence appends the same source range to `chosen`. The second splice then applies the original offsets to already-shortened text, deleting an equally sized portion of the following content without failing the aggregate-length gate.
```suggestion
seen_titles: set[str] = set()
for title in titles:
title_key = title.strip().lower()
if title_key in seen_titles:
continue
seen_titles.add(title_key)
matches = by_title.get(title_key, [])
if not matches:
missing.append(title)
continue
if len(matches) > 1:
ambiguous.append((title, len(matches)))
continue
section = matches[0]
chosen.append(_fragment(
source_text, section,
reason or f'section "{section.title}" selected for pruning',
))
```
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Reviews (5): Last reviewed commit: "Merge branch 'main' into analyzer-depth" | Re-trigger Greptile
…and record the plugin-residency gates as a Critical Rule Three references to the deleted schema-tax constants survived the measurement change. The one in the block comment stays — it is a deliberate note about what changed and why the old figure was wrong — but the module docstring and `_session_usage_from_records` were still describing the deferred lane and the tax/usage distinction in terms of symbols that no longer exist. A docstring citing a removed symbol sends the next reader looking for something that is not there, which is the same defect class this branch set out to close: documentation asserting more than the code supports. Both now name `SchemaMeasurement.tokens` / `.deferred_tokens` and the fields they surface on the finding, all verified to exist by import rather than by eye. The new Critical Rule records the durable half of the plugin lane: installed is not resident, both gates live in config rather than on the filesystem, and only the listing surface is resident. Deliberately carries no measurement — the counts move with the user's corpus, and a number in always-on context becomes a future lie that later sessions plan around. It points at the two settings keys instead and says to derive current figures from them. Appended at the end of the list at the next number above the highest in use across CLAUDE.md and .claude/rules/; nothing renumbered. The header's rule count went with it, for the same always-on-context reason, replaced by the append convention itself. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…our guard escapes, and an undisclosed floor Thirteen findings from an independent review. The load-bearing ones: DB WRITES. `config_id` is content-derived and therefore deterministic, so two analyzer passes ingesting the same server wrote the same primary key. Forced, that produced 141 exceptions in 240 attempts in two flavours — `Duplicate key` from the DELETE-then-INSERT window and `Conflict on tuple deletion!` — and they propagated out through `deadweight.run` into `build_report`, losing every other analyzer's findings. Three things together, because none alone is sufficient: the backend's write lock when reachable (a lock private to one backend instance cannot serialize two), a single conflict-tolerant `INSERT OR REPLACE` with bounded retry, and an in-memory mirror so persistence failing is never the analysis failing. The cost of losing a race is one re-measurement. DISPATCH. The analyzer loop was bare, so one failure destroyed twelve other analyzers' findings. Isolated now — but a swallowed analyzer is recorded on the report and rendered, because one that vanishes silently reads as "found nothing", a positive claim the run has no evidence for. TWO DATA-LOSS WINDOWS IN PRUNE. An editor landing during the quarantine writes had its work destroyed three ways: overwritten in the file, absent from the quarantine, and absent from the backup, which recorded the plan's text rather than a fresh read — so `undo` restored a state the file was never in. The re-check now sits immediately before the write and the backup takes what was just read. Separately, duplicate section headings collapsed in a dict, so pruning `Notes` removed the second and left the first while reporting the whole title pruned, with the survivor invisible in `declined` because that list filtered by title. Ambiguity is refused now, the same way a typo already was. THE GUARD. Four escapes remained and are reproduced in tests: one catalog call whitelisted unlimited adjacent prose, and `Call` nodes were never traced, so a helper, a `.format()` template and a `join()` all passed unread. The root list is gone entirely — every module under `tokenjam/` is walked, because a hand-maintained root list is how every one of these gaps arose. The ratchet is keyed on a fingerprint per text rather than a count, so swapping one uncatalogued text for another no longer passes. THE PROBE now defaults OFF. The protocol surface is read-only, but starting a process is not nothing and the pass is reachable from tj's own MCP tool, so the first exposure should be a choice rather than a discovery. Children get their own process group and an atexit sweep so a killed parent cannot orphan them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| for title in titles: | ||
| matches = by_title.get(title.strip().lower(), []) | ||
| if not matches: | ||
| missing.append(title) | ||
| continue | ||
| if len(matches) > 1: | ||
| ambiguous.append((title, len(matches))) | ||
| continue | ||
| section = matches[0] | ||
| chosen.append(_fragment( | ||
| source_text, section, | ||
| reason or f'section "{section.title}" selected for pruning', | ||
| )) |
There was a problem hiding this comment.
Duplicate selections corrupt pruning
When the same unique heading is supplied more than once, each occurrence appends the same source range to chosen. The second splice then applies the original offsets to already-shortened text, deleting an equally sized portion of the following content without failing the aggregate-length gate.
| for title in titles: | |
| matches = by_title.get(title.strip().lower(), []) | |
| if not matches: | |
| missing.append(title) | |
| continue | |
| if len(matches) > 1: | |
| ambiguous.append((title, len(matches))) | |
| continue | |
| section = matches[0] | |
| chosen.append(_fragment( | |
| source_text, section, | |
| reason or f'section "{section.title}" selected for pruning', | |
| )) | |
| seen_titles: set[str] = set() | |
| for title in titles: | |
| title_key = title.strip().lower() | |
| if title_key in seen_titles: | |
| continue | |
| seen_titles.add(title_key) | |
| matches = by_title.get(title_key, []) | |
| if not matches: | |
| missing.append(title) | |
| continue | |
| if len(matches) > 1: | |
| ambiguous.append((title, len(matches))) | |
| continue | |
| section = matches[0] | |
| chosen.append(_fragment( | |
| source_text, section, | |
| reason or f'section "{section.title}" selected for pruning', | |
| )) |
Knowledge Base Used: Session Analysis and Export
Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/summarize/prune.py
Line: 205-217
Comment:
**Duplicate selections corrupt pruning**
When the same unique heading is supplied more than once, each occurrence appends the same source range to `chosen`. The second splice then applies the original offsets to already-shortened text, deleting an equally sized portion of the following content without failing the aggregate-length gate.
```suggestion
seen_titles: set[str] = set()
for title in titles:
title_key = title.strip().lower()
if title_key in seen_titles:
continue
seen_titles.add(title_key)
matches = by_title.get(title_key, [])
if not matches:
missing.append(title)
continue
if len(matches) > 1:
ambiguous.append((title, len(matches)))
continue
section = matches[0]
chosen.append(_fragment(
source_text, section,
reason or f'section "{section.title}" selected for pruning',
))
```
**Knowledge Base Used:** [Session Analysis and Export](https://app.greptile.com/metabldr/-/custom-context/knowledge-base/metabuilder-labs/tokenjam/-/docs/session-analysis-export.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
The headline dollar figure this product renders for MCP dead weight was linear in a constant nobody had measured, and multiplied by however many servers the user happened to have configured. This measures it, stores the config surface it needs to do that affordably, gives
pruneandexpirereal write paths behind an on-device quarantine, prices the plugin lane for the first time, and closes three independent escapes in the guard that was supposed to stop analyzer prose drifting outside the catalog.Summary
FULL_SCHEMA_TAX_TOKENS = 25_000is gone. Each configured server is started, asked for its tools, and the schemas serialized exactly as they are injected are counted. A server that cannot be measured contributes nothing to any priced figure and says so on its own row.agent_config_filestable (migration 22) holding instruction files, agent files, hooks, MCP server declarations and plugins — presence, size, token count, content hash, last seen. Three analyzers now read that instead of each re-walking the filesystem at analysis time.pruneandexpirecan write. Both go through the same diff-then-approve stepcompressalready uses, with every removed fragment committed to an on-device quarantine before the source file is touched, and arestorethat re-anchors or refuses rather than corrupting.deadweight. An enabled plugin's skill listing is resident in every session before anything is invoked; that is now priced, behind both gates that decide whether a plugin loads at all.The dollar figure was linear in an unmeasured constant
core/optimize/analyzers/deadweight.pycarriedFULL_SCHEMA_TAX_TOKENS = 25_000and charged it flat to every individual server, on every call, regardless of how many tools that server exposed. Its own docstring conceded two things: the number was never measured here or anywhere in the repo, and the only in-repo source for "~25K" (core/context_diagnostic.py'sMCP_INJECTION_PARK_NOTE) describes the tax for all of a session's attached servers combined.So a per-server loop ran over an all-servers-combined figure. It flowed into
usd_windowand from there intopast_overspend_usd, the field every surface renders — which made the headline number linear in an unmeasured constant and proportional to the server count. A user with six servers was shown roughly six times the tax the cited source described for their whole session.What replaced it
core/optimize/mcp_probe.pymeasures each server directly: start it, sendinitializeandtools/listand nothing else, serialize the tool array the way it is injected (namespacedmcp__<server>__<tool>name, description, input schema), and count that. The deferred/ToolSearch lane comes off the same response — name and description per tool, no input schema — so both lanes are measured rather than one measured and one assumed.Three properties are load-bearing and each has a test:
tools/call, noresources/read, noprompts/get.readlineblocks and a deadline checked between blocking reads is not a deadline — a test that starts a process sleeping for a minute is what surfaced that, and it is pinned.tokens = Noneand a status saying which. There is no default to fall back to, because a default is the defect being removed. An unmeasured server is excluded from every priced figure, its row says why, and the finding carries a coverage note stating every total is a floor.A remote (
http/sse) server is deliberately not probed: there is nothing local to start, and measuring one would mean issuing an authenticated third-party request as a side effect of an analysis run. It reportsunsupported— an honest gap rather than a guess.Measuring means starting a server, so the result is cached on the server's ingested record against its launch spec hash: an unchanged server is measured once, changing its command or args invalidates it, and a failed probe is retried after a grace period rather than believed forever. Gated by
[optimize] measure_mcp_schemas(default on) and only ever taken on the out-of-band analyzer pass. Turning it off does not restore the old assumption — it reportsskippedand prices nothing.Before / after on real data
Measured against a real, locally-installed stdio MCP server:
@playwright/mcp(24 tools)The old constant overstated that one server by 5.9x, and understated its deferred listing by 1.6x. Both errors were invisible because both numbers were rendered exactly the way a measured number would be.
On the machine this was developed against, the honest end-to-end delta is no dollar movement: one MCP server is configured, it is
http-transport, and it sits below the dead-weight session bar — sopast_overspend_usdwasNonebefore and isNoneafter. What changed there is that the tax-table row which previously read$0.65for that server is now correctly absent, with the reason stated, instead of being an assumption rendered as a measurement.The analyzers now read ingested config instead of re-walking the filesystem
Three analyzers each answered "what config does this user have" by walking the filesystem themselves, at analysis time, with three different enumerations:
deadweightre-read~/.claude.jsonand every project's.mcp.json/.claude/settings*.json,core/summarize/candidatesre-globbed the prompt-file catalog, andprompt_bloatglobbed the same catalog a second time through its own near-identical helper (which had quietly dropped the recursive-glob handling the other one needed). Nothing about any of it was stored.core/agent_config.pymakes the walk the population step and the table the thing analyzers read:missing_expected_tables/ensure_expected_tablescover the new table too — this repo has renumbered migrations before, and a recorded-but-unlandedCREATE TABLEis the failure mode that motivated that self-heal.pruneandexpireare performable and revertiblecore/summarize/route.pynamed six verdicts and exactly one of them (compress) could reach a write; the module said outright that nothing there writes or prunes. On a real corpus most oversized always-resident instruction files are long because rules accumulated or a dated log was never drained — and for those the tool emitted advisory prose and stopped.The answer is not to refuse to act. It is to make deletion recoverable:
core/summarize/quarantine.py— under tj's own storage root (<storage parent>/summary/quarantine, the same derivationbackupuses, no second config knob). Every removed fragment is written and fsync'd, then read back from disk, before the source file changes. A failed or unverifiable quarantine write raises, and it raises before the source is touched. There is no path through the apply that removes content without a committed way back.core/summarize/prune.py—pruneacts only on sections the user names, because which rules earn their place is the one questionroute.py's shape measurement explicitly cannot answer, and a heuristic guessing at it would be this product asserting more than its data supports on the one surface where being wrong deletes something.expireselects dated log entries older than a cutoff, which is arithmetic rather than judgement, and never touches an undated section.tj summarize prune/expire/quarantine list/quarantine show/restore— the same--go/--dry-runshape every other write-affecting summarize subcommand uses.The human gate is unchanged. Both plan, render the exact lines and the reason, and write nothing until
--go. Quarantine is the net under that gate, not a replacement for it. Nothing auto-applies.Restore never trusts a line number. The recorded content hash distinguishes "unchanged since we cut it" from "edited since"; placement is by matching the text that surrounded the cut, tried strongest-first and required to be unambiguous. When it cannot be placed, it refuses and names the entry so the user can read the fragment and paste it back. Silent corruption of an instruction file is the worse failure by a distance — it is silent, it ships, and the agent follows it. Anchors are measured against the result rather than the original, because a fragment's neighbour in the original is often another fragment removed in the same apply; that is what makes a multi-fragment restore work at all.
route.py's module docstring and the advisory prose that said the tool "only performs the last" of the four routes are updated to match what the code now does.The plugin lane
An enabled plugin injects the
name: descriptionsurface of every one of its skills into every session before anything is invoked. Nothing measured it.Two gates, neither visible on the filesystem. Verified independently against a real machine while building this:
SKILL.mdfiles installed under~/.claude/plugins.enabledPluginsor installed at project scope.Bodies are never counted. A skill's body arrives on invocation; its listing line is resident. On the same machine the two differ by ~4,900x (2,403 chars of listing against 11.8M chars of bodies). Counting bodies is not a conservative overestimate — it is a different number about a different thing. There is a test whose fixture bodies are ~370x their listing lines, so a leak fails by two orders of magnitude rather than a rounding error.
Every installed plugin gets a row, including the ones that cost nothing: "disabled, so free" and "we never looked" must not be the same absence, and the disabled rows are exactly what someone deciding whether to enable something needs. A plugin with no recorded
pluginUsageentry is never flagged — only a recorded zero is evidence of disuse.Honest framing: this is not a big number today. On the machine measured, the two enabled plugins are worth ~$26.50 across a 30-day window and neither is dead (both are heavily used), so the lane flags nothing. Its value is making one enable/disable decision visible and priced before it is taken:
superpowerscosts 546 tok/call resident, whileeverything-claude-code— installed and currently switched off — would cost 19,765 tok/call, 36x more, the moment someone flipped it on.Explicitly not built: plugin files are not summarize candidates and must never become them. They are third-party files under a versioned cache path the user did not author, and the next plugin update reverts any edit — a "shorten this file" fix would appear to succeed and then silently regress. Two tests pin it: the catalog carries no plugin path, and a scan whose root contains a plugin tree does not pick it up.
The fix-prose guard was green over uncatalogued prose
tests/unit/test_no_fix_prose_outside_the_catalog.pyreported 23/23 passes whilecost_proposals._summarize_to_proposalshardcoded a ~330-character multi-sentence advisory paragraph that never routed throughfixes.fix_text(). It took three independent escapes, all silent:advise_textwas not in_FIX_SLOTS. A guard scoped by slot name sees nothing outside the slots it lists, and a missing slot is indistinguishable from a clean one.ADVICE; the variable was namedadvise. ADVISE vs ADVICE, one letter, and the substring test returned False forever.MIN_FIX_CHARS, which answers a different question — is a catalogued text long enough to be an instruction. Prose written as short interpolated fragments was automatically exempt however much of it there was.A fourth, found while fixing these:
fix += "..."is anAugAssign, which the guard never inspected at all, so a rule appended to a grounded sentence was invisible however long it ran.What changed
MIN_GUARD_STATIC_RUNis the guard's own single-run floor;MIN_GUARD_STATIC_TOTAL+MIN_GUARD_SENTENCESis a second detector for prose stitched around interpolated evidence. Length alone genuinely cannot separate the two cases — the grounded MCP-removal sentence's longest literal run and the shortest rule fragment are the same size — so the second detector asks a different question: grounding is one sentence about one row, a policy runs to several.core/summarize/joins the scanned roots, walked as a tree so a module added there tomorrow is covered without anyone extending a list.summarizeanddeadweightfinally have catalog records (plus one for the plugin lane). Neither had any, which is sharper than it sounds:lint_catalog()can only report on what is catalogued, so it was structurally incapable of saying anything about two analyzers' user-facing prose while returning a clean bill of health.test_the_guard_catches_prose_assigned_to_an_advise_slotreproduces the exact shape and fails on the pre-fix guard; there are also regression tests for the short-fragment escape, theAugAssignescape, and a deliberately oddly-named carrier.A behaviour change in
prompt_bloat, called out because it is not a pure rewireThe old
_catalog_global_filescalledis_file()on the catalog's raw global paths, and those paths include literal globs such as~/.claude/rules/**/*.md. A glob string never satisfiesis_file(), so prompt_bloat's global provenance index silently never contained the user's global rules tree. The sharedcatalog_global_pathsexpands globs properly, so those files are now included and a user who has global rules will get different prompt-provenance classifications than before.That is a latent bug being fixed rather than a regression, but it is a behaviour change, and the rest of the ingestion rewire genuinely is behaviour-preserving — so it would have been wrong to leave it filed under that claim. It affects only users with files matching a globbed catalog global path.
What's NOT in this PR
The remaining uncatalogued advisory texts (56, across 5 modules). Closing the escapes made them visible for the first time — they were always there, the guard simply could not read them. Migrating them changes what a dozen cards say and interacts with the catalog's duplicate lint, so it belongs in its own review. They are held by a ratchet, not an allowlist, and it is keyed on a fingerprint of each text rather than on a count: a count-based pin passes when one uncatalogued text is swapped for a different one, which is exactly the drift a ratchet exists to stop. Adding one fails, editing one fails, and removing one fails until its line comes out of the recorded set. It can only be driven to empty.
core/summarize/route.py's 12 entries are a deliberate deferral rather than an oversight: that file's advisory prose is verbatim quotation of Anthropic's published guidance (which aFixRecordwould subject to lints written for text we author) and diagnosis of a measured prose shape rather than an instruction. Both may belong in the catalog eventually; neither is a mechanical move.Escalating a route to a hook. A hook is a different artifact with a different lifecycle and
core/rulewrite/deliveryowns that kind;route.pystill names it and does not build it.Multi-file MCP removal. The claim is still aggregated across every file declaring a server while the apply edits one; the card discloses the gap, as before.
Tests / Verification
New:
tests/unit/test_agent_config.py(13),tests/unit/test_mcp_probe.py(12, one spawning a real stdio MCP server written totmp_path),tests/unit/test_summarize_prune_quarantine.py(23),tests/unit/test_deadweight_plugins.py(11). Extended:tests/unit/test_deadweight.py,tests/unit/test_no_fix_prose_outside_the_catalog.py,tests/integration/test_summarize_cli.py.ruff check tokenjam/andmypy tokenjam/clean. Unit + integration suites green locally.Live verification ran against the real environment (Critical Rule 31: an isolated harness understates silently rather than erroring), with storage held off
~/.tj— the real state directory was diffed before and after and is unchanged.🤖 Generated with Claude Code