Skip to content

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

Merged
anshss merged 8 commits into
mainfrom
analyzer-depth
Aug 4, 2026
Merged

anshss merged 8 commits into
mainfrom
analyzer-depth

Conversation

@anshss

@anshss anshss commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

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 prune and expire real 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

  • The MCP schema tax is measured per server. FULL_SCHEMA_TAX_TOKENS = 25_000 is 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.
  • The agent-config surface is ingested. New agent_config_files table (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.
  • prune and expire can write. Both go through the same diff-then-approve step compress already uses, with every removed fragment committed to an on-device quarantine before the source file is touched, and a restore that re-anchors or refuses rather than corrupting.
  • A plugin lane for 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 fix-prose guard had three independent escapes and was green over a ~330-character advisory paragraph.

The dollar figure was linear in an unmeasured constant

core/optimize/analyzers/deadweight.py carried FULL_SCHEMA_TAX_TOKENS = 25_000 and 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's MCP_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_window and from there into past_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.py measures each server directly: start it, send initialize and tools/list and nothing else, serialize the tool array the way it is injected (namespaced mcp__<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:

  • Read-only. Exactly two requests are ever sent. No tools/call, no resources/read, no prompts/get.
  • Bounded and terminated. One wall-clock budget covers spawn, handshake and listing; stdin closes, the process is signalled, then killed. Reads happen on a daemon thread, because readline blocks 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.
  • Never a fabricated answer. A server that will not start, does not answer, or answers something unparseable produces tokens = None and 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 reports unsupported — 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 reports skipped and prices nothing.

Before / after on real data

Measured against a real, locally-installed stdio MCP server:

old flat constant measured
@playwright/mcp (24 tools) 25,000 tok/call 4,267 tok/call
deferred listing 400 tok 628 tok

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 — so past_overspend_usd was None before and is None after. What changed there is that the tax-table row which previously read $0.65 for 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: deadweight re-read ~/.claude.json and every project's .mcp.json / .claude/settings*.json, core/summarize/candidates re-globbed the prompt-file catalog, and prompt_bloat globbed 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.py makes the walk the population step and the table the thing analyzers read:

  • One catalog expander, used by both consumers, so "the catalog is the source of truth for which paths count" is enforced by there being one expander rather than by two modules agreeing to behave. The catalog itself is passed in from each consumer's own reference, so a test that isolates the catalog keeps isolating it.
  • Per record: kind, scope, root, slot, absolute path, size, token count, content hash, last seen. Drift is visible as a hash change under a stable id, which is the question a consumer actually has.
  • Reads are scoped by the pass's own timestamp. A persistent store holds every root ever scanned, so an unfiltered read would price a repo the current window never touched.
  • The default store is in-memory, so every direct caller and unit test gets exactly today's behaviour with nothing persisted; the registered analyzers pass a DuckDB-backed one.

missing_expected_tables/ensure_expected_tables cover the new table too — this repo has renumbered migrations before, and a recorded-but-unlanded CREATE TABLE is the failure mode that motivated that self-heal.

prune and expire are performable and revertible

core/summarize/route.py named 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 derivation backup uses, 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 — 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, 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. expire selects 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-run shape 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: description surface 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:

  • 1,299 SKILL.md files installed under ~/.claude/plugins.
  • 15 of them actually resident — the other 1,284 belong to plugins switched off in enabledPlugins or installed at project scope.
  • Pricing installed-ness would have overstated the population by 87x.

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 pluginUsage entry 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: superpowers costs 546 tok/call resident, while everything-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.py reported 23/23 passes while cost_proposals._summarize_to_proposals hardcoded a ~330-character multi-sentence advisory paragraph that never routed through fixes.fix_text(). It took three independent escapes, all silent:

  1. advise_text was 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.
  2. The constant-name check matched ADVICE; the variable was named advise. ADVISE vs ADVICE, one letter, and the substring test returned False forever.
  3. The length floor was borrowed from 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 an AugAssign, which the guard never inspected at all, so a rule appended to a grounded sentence was invisible however long it ran.

What changed

  • Name guessing is gone. The guard now traces what actually flows into a fix slot — keyword arguments, dict values, assignments, transitively — so a name can be spelled anything and still be caught. Constant names match only by being a slot, compared exactly.
  • The floor is decoupled and paired. MIN_GUARD_STATIC_RUN is the guard's own single-run floor; MIN_GUARD_STATIC_TOTAL + MIN_GUARD_SENTENCES is 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.
  • summarize and deadweight finally 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_slot reproduces the exact shape and fails on the pre-fix guard; there are also regression tests for the short-fragment escape, the AugAssign escape, and a deliberately oddly-named carrier.

A behaviour change in prompt_bloat, called out because it is not a pure rewire

The old _catalog_global_files called is_file() on the catalog's raw global paths, and those paths include literal globs such as ~/.claude/rules/**/*.md. A glob string never satisfies is_file(), so prompt_bloat's global provenance index silently never contained the user's global rules tree. The shared catalog_global_paths expands 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 a FixRecord would 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/delivery owns that kind; route.py still 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 to tmp_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/ and mypy 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

anshss and others added 2 commits August 4, 2026 17:07
…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]>
@anshss
anshss requested a review from anilmurty as a code owner August 4, 2026 12:06
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds agent-config ingestion, per-server MCP schema measurement, plugin deadweight pricing, and reversible prune/expire operations.

  • Persists instruction, hook, MCP, and plugin configuration for analyzer consumption.
  • Measures MCP schema and deferred-listing token costs instead of applying a flat constant.
  • Adds quarantine-backed prune, expire, and restore CLI workflows.
  • Strengthens the fix-prose catalog guard and adds plugin reporting.

Confidence Score: 4/5

The PR is not yet safe to merge because duplicate prune selections can delete unrelated content, and the previously reported plugin-residency, MCP-measurement, and markup-rendering failures remain.

Repeating one unique --section appends the same source range twice, after which the second splice operates on shortened text and removes following content without tripping the aggregate-length gate. Project-scoped plugin residency still lacks analyzed-root matching, same-named MCP declarations still share one canonical measurement, and plugin identifiers still enter Rich markup unescaped.

Files Needing Attention: tokenjam/core/summarize/prune.py, tokenjam/core/agent_config.py, tokenjam/core/optimize/analyzers/deadweight.py, tokenjam/cli/cmd_optimize.py

Important Files Changed

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]
Loading
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

Comment thread tokenjam/core/summarize/prune.py Resolved
Comment thread tokenjam/core/agent_config.py Resolved
Comment thread tokenjam/cli/cmd_optimize.py Resolved
anshss and others added 6 commits August 4, 2026 17:44
…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]>
Comment on lines +205 to +217
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',
))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 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.

Suggested change
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.

@anshss
anshss merged commit ff7bf8e into main Aug 4, 2026
6 checks passed
@anilmurty
anilmurty deleted the analyzer-depth branch September 18, 2026 21:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant