Skip to content

fix(summarize): fence the source from the rewrite instruction, and close the vacuous structure gate - #685

Merged
anshss merged 6 commits into
mainfrom
summarize-fence
Aug 4, 2026
Merged

anshss merged 6 commits into
mainfrom
summarize-fence

Conversation

@anshss

@anshss anshss commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

The problem

The summarize analyzer compresses oversized instruction files. Its input is therefore, by
definition, text addressed to an AI — and on the claude -p delivery path the rewrite contract and
the source were concatenated into a single stdin blob:

prompt = f"{system_rules}\n\n{wrapped_prompt}"
subprocess.run(["claude", "-p"], input=prompt, ...)

So the file competed with the instruction to rewrite it, and on a large imperative file the file
won: claude -p read the source as a live prompt and answered it, returning a chat greeting
and dropping every protected block. This scales the wrong way — the bigger and more imperative the
file, the more likely the hijack, and those are exactly the files where the saving is largest.

The severe part is the gate. wrap.is_structure_ok was
not (missing or duplicated or extra or reordered or malformed), and all five sets are computed
against the <tj-keep> protected-block list. On a file with no protected blocks — a plain-prose
CLAUDE.md of pure rules, no fences, no tables, which is the most common kind — every set is empty,
so "no failures" meant "nothing was looked at" and any output at all passed. The hijack was only
caught in the observed case because that file happened to have blocks to drop. On a block-free file
the greeting would have been staged over the user's CLAUDE.md and credited with a token saving.

Confirmed by running the old predicate against the exact input:

protected blocks: 0
integrity: {'missing': [], 'duplicated': [], 'extra': [], 'reordered': False, 'malformed': False}
OLD gate verdict on the hijack greeting : True
NEW gate verdict on the hijack greeting : False

What changed

1. claude -p is invoked properly. The contract goes on --system-prompt; stdin carries the
source and nothing else. Also --safe-mode — without it a rewrite of one instruction file runs in a
session with the user's other instruction files (CLAUDE.md, hooks, skills, plugins, MCP) loaded as
live directives, able to steer the rewrite and billed to a call meant to concern one file. And
--tools "": this call transforms text and has no business holding Edit/Write, which is a shorter
route to a destroyed instruction file than the hijack. Plus --no-session-persistence (tj's own
calls shouldn't enter the transcript corpus tj later reads as evidence) and --name (which also
suppresses the CLI's separate title-generation call, one that re-sent the whole source file for a
label nobody reads).

Deliberately not --bare, despite it being the obvious flag: it also stops the CLI reading
OAuth/keychain credentials, and this path exists precisely for the subscription user who has no API
key — --via api is the one that needs a key. --safe-mode achieves the same context isolation
with auth left alone.

Verified against the installed CLI by capturing the request it actually puts on the wire: the
system prompt and stdin land on the request's system and messages[0] and are never re-joined,
and --tools "" really does send an empty tool list (without it: Bash, Edit, Read).

2. Nonce envelope. The source travels inside a per-call <tj-source nonce="…"> envelope on
both delivery paths, with the contract stating that everything inside is data to rewrite and never
an instruction to obey, answer, or act on. The nonce is per-call and unguessable: the tag name is
published in this repo's own source, so a fixed delimiter could be forged or closed early by the
very text it fences.

3. The gate fails closed, and it reuses the existing mechanism. The model must echo the envelope
back, exactly as it already must echo <tj-keep> markers — so there is something to verify on
every file, including block-free prose, and a hijacked greeting fails for free. is_structure_ok
now requires an affirmative signal (an echoed envelope, or at least one protected block) rather than
treating "nothing to verify" as a pass. A length band against the prose budget catches the model
that complies with the format and then says nothing (a refusal, an apology, a one-line answer). The
band is one-sided by design: a rewrite that under-compresses is a quality question the diff
already surfaces, not evidence the model stopped rewriting.

4. The ceiling is understood. The channel split raises the bar but is not a security boundary —
a model can still follow instructions arriving in the user turn. Part 3 is what actually catches a
hijack when it lands, and it is not weakened on the strength of part 1.

The manual, HTTP and MCP check paths accept the nonce too. All three keep it optional so existing
callers work, and none can pass vacuously any more — without a nonce the gate falls back to
requiring at least one protected block.

Tests

tests/unit/test_summarize_prompt_fence.py is new and deterministic — no model call, runs in normal
CI. It pins the live hole (zero-block fixture + chat greeting ⇒ refused, est_tokens_saved None,
nothing staged, attempt still recorded), the vacuous pass, the forged-envelope case, the length
band, and that a genuine block-free rewrite still stages. A guard test asserts the fixture really
has zero protected blocks, so the others cannot pass vacuously themselves.

tests/unit/test_summarize_delivery.py pins the argv _via_claude builds — rules absent from
stdin, --safe-mode present, --bare absent, empty tool list, source enveloped — and that the
nonce differs between calls.

The live end-to-end check (a file of pure instructions is rewritten, not answered) needs a real
model, so it is skipped unless TJ_LIVE_SUMMARIZE_TEST=1.

Existing fakes returned a bare stub outside the envelope, which is a fake of a hijacked model;
they now model a compliant one via a shared tests/summarize_fakes.py, so happy-path tests keep
testing the happy path rather than silently testing the gate.

tests/unit -k summarize          361 passed, 10 skipped
tests/integration -k summarize    55 passed
tests/ -k mcp                    100 passed
ruff + mypy                      clean

…op the gate passing vacuously

The rewriter is asked to compress instruction files, so its input is by definition
text addressed to an AI. On the claude -p path the contract and the source were
concatenated into one stdin blob, and on a large imperative file the file won: the
model read it as a live prompt and answered it, returning a chat greeting.

- claude -p now takes the contract on --system-prompt and the source on stdin.
  Verified against the CLI on the wire: they land on the request's `system` and
  `messages[0]` and are never re-joined. Also --safe-mode (a rewrite of one
  instruction file must not inherit the user's other ones as live directives),
  --tools "" (this call transforms text; Edit/Write is a shorter route to a
  destroyed file than a hijack), --no-session-persistence and --name. Not --bare:
  it stops the CLI reading OAuth, and this path exists for the user with no API key.
- The source travels inside a per-call nonce envelope, on both delivery paths, with
  the contract stating that everything inside is data to rewrite and never an
  instruction to follow. The nonce is per-call so the source cannot forge or close
  its own envelope.
- The gate now fails closed. Its checks are all computed against the <tj-keep>
  list, so on a file with no protected blocks -- plain prose, pure rules, no
  fences -- every set was empty and "no failures" meant "nothing was looked at",
  accepting any output at all and crediting it with a saving. It now requires an
  echoed envelope or at least one block, plus a length band against the word
  budget for a response that complies with the format and says nothing.

The manual, API and MCP check paths take the nonce too; all remain optional so an
existing caller keeps working, and none can pass vacuously.

Co-Authored-By: Claude <[email protected]>
@anshss
anshss requested a review from anilmurty as a code owner August 4, 2026 07:54
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR separates the Claude rewrite contract from source input, wraps source text in a per-call nonce envelope, and makes structural verification fail closed.

  • Adds an envelope echo requirement for block-free instruction files.
  • Adds a minimum rewrite-length check to reject enveloped refusals and greetings.
  • Isolates local Claude invocations from ambient instructions and tools.
  • Plumbs the nonce through automated, CLI, HTTP, and MCP workflows.

Confidence Score: 4/5

The PR is not yet safe to merge because manual CLI, HTTP, and MCP checks can still stage a correctly enveloped non-rewrite without applying the new length gate.

The automated delivery path forwards the target prose budget and rejects degenerate output, but all three manual prep/check workflows expose that budget during preparation and then omit it during checking, leaving the previously reported refusal-staging path reachable.

Files Needing Attention: tokenjam/core/summarize/session.py, tokenjam/cli/cmd_summarize.py, tokenjam/api/routes/summarize_run.py, tokenjam/mcp/server.py

Important Files Changed

Filename Overview
tokenjam/core/summarize/session.py Adds nonce and rewrite-length validation, but the length gate remains optional and is not reached by the manual check surfaces.
tokenjam/core/summarize/wrap.py Adds nonce-envelope creation, extraction, integrity reporting, and affirmative fail-closed structural verification.
tokenjam/core/summarize/delivery.py Separates system rules from stdin, isolates the Claude invocation, and forwards both nonce and length budget on the automated path.
tokenjam/cli/cmd_summarize.py Carries the nonce through manual checking but still omits the available target prose budget.
tokenjam/api/routes/summarize_run.py Extends the HTTP check contract with the nonce but not the target prose budget.
tokenjam/mcp/server.py Extends MCP prep/check guidance and nonce plumbing while leaving the length budget disconnected.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  Prep[prepare source] --> Envelope[Add nonce envelope]
  Envelope --> Deliver[Deliver rewrite request]
  Deliver --> Check[Verify envelope and protected blocks]
  Check --> Length{Rewrite meets length floor?}
  Length -->|Yes| Stage[Stage candidate]
  Length -->|No| Refuse[Refuse candidate]
Loading

Reviews (3): Last reviewed commit: "docs(rules): state the inverted-twin fai..." | Re-trigger Greptile

Comment thread tokenjam/core/summarize/session.py Resolved
anshss and others added 5 commits August 4, 2026 13:27
…y on an empty set

Promotes the durable lesson from the summarize structure gate. The predicate
"no blocks missing, duplicated, extra or reordered" is trivially true when
there are no blocks, so the gate reported "intact" having verified nothing,
and that pass was indistinguishable from a real one.

Stated as a rule rather than a finding: mechanism and do/don't in full, no
counts, no dates, no incident narrative, thresholds named as constants rather
than values. Appended at the end; nothing renumbered.

Also drops the literal count from the section header, which the new entry would
otherwise have made wrong. A count in an always-on doc rots by construction.

Co-Authored-By: Claude <[email protected]>
Rule 42 was written twice in parallel: once here and once, independently, in
.claude/rules/optimize-analyzers.md. Two different texts under one number is
worse than either alone, since the numbers are load-bearing and cited from
source and tests.

The rules/ version is the one kept. It is the placement this file's own header
prescribes (only a subset is always-on; the rest live in .claude/rules/ with
their numbers intact), it sits beside the analyzer it describes, and it carries
the cross-reference to the sibling filter-format rule.

Reverts this file to its prior state exactly, including the header wording,
so nothing unrequested rides along.

Co-Authored-By: Claude <[email protected]>
@anshss
anshss merged commit abf4b87 into main Aug 4, 2026
6 checks passed
@anilmurty
anilmurty deleted the summarize-fence branch September 18, 2026 21:03
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