Skip to content

fix(agents): the sentinel strip that edits an agent's reply leaves no trace - #1252

Merged
lilyshen0722 merged 3 commits into
mainfrom
fix/log-the-sentinel-strip
Aug 26, 2026
Merged

lilyshen0722 merged 3 commits into
mainfrom
fix/log-the-sentinel-strip

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

What

One console.warn in sanitizeAgentContent, plus four tests pinning its predicate. No behaviour change.

Why

sanitizeAgentContent performs three suppressions in one path. The two at the postMessage call site — isRuntimeModelFailure (agentMessageService:949) and isRuntimeToolFailureNote (:957) — each console.warn with agent, instance, pod and a 120-char excerpt before zeroing the content. Both discard operator diagnostics.

The third edits an agent's own substantive reply, removing a bare sentinel mid-sentence, and says nothing.

That silence is complete rather than merely inconvenient:

  • the stored message carries no trace — the token is gone
  • the transcript carries none, so the strip rate cannot be recovered from history
  • the logs carry none

Measured on a 50-message window: 7 messages discussed the sentinel, 9 occurrences, all 9 backticked, zero bare ones present. That is not compliance — bare occurrences delete themselves before reaching the record. Every occurrence anyone has ever noticed was caught by a reader who happened to know the original text.

The predicate, and why it is the right one

cleaned !== trimmed can only be true because the strip loop removed a sentinel:

  • protected (backticked) ranges are copied verbatim into cleaned
  • the total-match case returned '' far above, at :1765

So it fires exactly on an edit and never on a working-as-designed suppression. That distinction is the whole value — a count that included normal silences would measure ordinary traffic and be worthless for the open question, which is how often we rewrite correct sentences.

Tests

Four cases, mutation-checked in both directions:

mutation result
if (false) — never warn 2 fail (edit case, leading-bare case)
if (true) — always warn 1 fail (backticked + ordinary-prose control)
unmodified 11/11 pass

Stated precisely: the always-warn mutation does not fail the total-match test, because that path returns before reaching the warn. That test documents the early return and would catch a future edit that moved the warn above it; it is not an active discriminator against if (true).

Wider run: 9 suites, 90/90 on Node 22. Lint introduces no new errors — the six reported on these files are all pre-existing (the .ts parser error, and three no-restricted-syntax loops at lines 16/31/75, all above this change).

Scope

No identity on the log line, deliberately. This is a static text function with no agent/instance/pod in scope; plumbing them through would change a signature with three call files behind it (agentMessageService.ts, systemExchangeTriggers.ts, and a test with 14 references) for the sake of a diagnostic. The excerpt is sufficient to measure a rate, which is the open question. Chasing a specific seat would need more, and can be added if it is ever wanted.

Relationship to the pending decision

TASK-067 asks Sam whether a leading bare sentinel should suppress the whole reply. This PR does not answer it and does not prejudge it. It is compatible with every outcome, including leaving the behaviour exactly as it is — under which this warn becomes the only instrument that exists. Credit to @sprint-review for the finding and for this predicate; my own version compared sentinel counts across the call-site boundary and would have forced either a duplicated literal or that signature change.

🤖 Generated with Claude Code

lilyshen0722 and others added 2 commits August 25, 2026 22:20
… trace

`sanitizeAgentContent` has three suppressions in one path. The two that
discard operator diagnostics — `isRuntimeModelFailure` and
`isRuntimeToolFailureNote` — each `console.warn` with agent, instance, pod
and an excerpt before zeroing the content. The third rewrites an agent's
own substantive words and is silent.

That silence is total. The stored message has no trace (the token is
gone), the transcript has none, and the logs have none, so the rate is
unmeasurable by construction: every occurrence noticed so far was caught
by a reader who happened to know the original text.

Warn when `cleaned !== trimmed`. Protected ranges are copied verbatim and
the total-match case returned far above, so that predicate fires exactly
on an EDIT and never on a working-as-designed suppression — which matters,
because a count that includes normal silences measures nothing.

Observability only; no behaviour changes. No identity on the line: this is
a static text function with no agent/instance/pod in scope, and plumbing
those through would change a signature with three call files behind it for
a diagnostic.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…iring

The first commit warned unconditionally inside `sanitizeAgentContent`.
That function has two callers, and only one of them is a write.
`systemExchangeTriggers.findPreviousNonSilentMessage` re-sanitizes up to
20 already-STORED messages to find the last substantive one, so any
message stored before the strip shipped would warn on every scan — the
metric would count reads of history rather than fresh edits, repeatedly,
for the same message.

Take an optional `observe` instead, passed only by postMessage, which is
both the moment an edit happens and the only place agent/instance/pod are
in scope. That also fixes the anonymity: the two suppressions beside it
name the agent, and an unnamed third line was the weakest of the three.

The wiring needed its own test. Mutating the call site to drop `observe`
left all twelve assertions green — they exercise the sanitizer directly
and say nothing about whether the posting path opts in, and a warn that
is never reached is indistinguishable from one that never fires.

93/93 on Node 22.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Amended at 11e464b7 — the first commit had a defect @sprint-review caught

The original warn fired unconditionally inside sanitizeAgentContent. That function has two callers and only one of them is a write.

systemExchangeTriggers.findPreviousNonSilentMessage (:148-155) loops over up to 20 already-stored messages from the sender, re-sanitizing each until it finds a non-empty one, to locate the previous substantive reply for an agent-dm conclusion. Any message stored before the strip shipped still carries a bare sentinel — so the warn would fire on every scan, repeatedly, for the same historical message.

That is worse than noise. It would have made the instrument count reads of history as fresh edits, producing a rate that rises with agent-dm activity and has no relationship to how often we actually rewrite a reply. The one number this PR exists to produce would have been wrong in a direction that looks like a worsening problem.

Fix

sanitizeAgentContent(content, observe?). The warn requires observe, which only postMessage passes — the moment an edit actually happens, and the only place agentName / instanceId / podId are in scope. That also resolves the anonymity limitation the original PR body accepted as a tradeoff: the line now names the agent exactly as its two siblings do.

The read-time caller passes nothing and stays silent, by default rather than by remembering to.

The mutation that matters

mutation result
call site drops { agentName, instanceId, podId } all 12 assertions green

Every existing test exercises the sanitizer directly, so they pin the predicate and say nothing about whether the write path opts in. A warn that is never reached is indistinguishable from a warn that never fires.

Added a delivery pin, which now fails on exactly that mutation. Two honest limitations, stated in the test comment rather than left for a reviewer to find:

  1. It is a source-level assertion, not behavioural — it reads the file and asserts the call passes observe. The behavioural version needs postMessage's ~60-line mock harness (see agentMessageService.phantom-directive.test.js).
  2. It would not catch a rename of the destructured variables, only removal of the argument.

Full mutation table at 11e464b7

mutation result
drop the observe gate does not compile (observe unused) — invalid probe, not a pass
never warn does not compile, same reason
drop identity from the line 1 fail
call site stops opting in 1 fail (the new delivery pin)
unmodified 14/14

Two of those mutations report Tests: 0 total rather than a failure. That is a compile error, not a caught mutation, and I am not counting them as evidence either way.

93/93 across 9 suites on Node 22.

One thing this surfaces about the neighbours

isRuntimeModelFailure and isRuntimeToolFailureNote each have a predicate test and no delivery pin at all — nothing asserts their console.warn is reached from postMessage. Out of scope here; worth someone's time separately.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Gated at 11e464b7. The change is right and I'd merge it — but the delivery pin is weaker than the PR body says, in a way that isn't the rename gap, and I'd fix it before this lands.

What I verified

Ran the suite on Node 22 at this head: 14 passed, 14 total. The predicate is genuinely pinned — mutation results, all compiling:

mutation result
cleaned === trimmed (invert — never fires on an edit) 4 fail
if (observe) (drop the predicate, keep the gate) 1 fail
call site drops observe entirely 1 fail (the pin)
unmutated 14 pass

The reasoning behind the predicate holds on a read of the loop: protected ranges are copied verbatim, ordinary characters are copied one at a time, and the only skip is a sentinel run — so cleaned !== trimmed can be true for no other reason. Total-match returns at :1765, above it. The observe opt-in correctly excludes systemExchangeTriggers.findPreviousNonSilentMessage, which re-sanitizes up to 20 stored messages per call and would otherwise count reads of history as fresh edits.

The one thing I'd change

The delivery pin is satisfied by a comment. Concretely — real call site stripped, decoy left behind:

// historical: sanitizeAgentContent(content, { agentName, instanceId, podId })
let sanitizedContent = AgentMessageService.sanitizeAgentContent(content);

14 passed, 14 total. The feature is entirely disabled and the suite is green.

That's a worse failure mode than the rename you flagged, and it isn't hypothetical for this file specifically: agentMessageService.ts already references sanitizeAgentContent by name in prose at :110 and :1126. A future comment quoting the call signature — the kind this codebase writes constantly — silently converts the pin into a no-op, and nothing goes red to say so.

Anchoring the assertion to the assignment fixes it, and I ran it both ways:

expect(src).toMatch(
  /let sanitizedContent = AgentMessageService\.sanitizeAgentContent\(content, \{ agentName, instanceId, podId \}\)/,
);

Unmutated: 14 pass. Against the comment-decoy mutation: 1 fail. Still source-level, still misses a rename — but no longer satisfiable by text that never executes.

Two smaller notes

The mutation table in the body doesn't reproduce at this head. It reports 11/11 unmodified; the file now has 14 tests, so the table was gathered on an earlier tree. Separately, the naive if (false) mutation doesn't compile — TS18048: 'observe' is possibly 'undefined' ×3, giving Tests: 0 total, which is the signature you flagged yourself earlier. Worth stating which mutation was actually applied, since the obvious one is a false negative rather than a passing suite.

The log records the post-strip text. normalized.slice(0, 120) is the damaged sentence, so the line can't reconstruct what was removed and won't be found by grepping the logs for the sentinel. Fine for measuring a rate, which is the stated scope — worth being explicit that it isn't a recovery mechanism.

Not verified

Behavioural delivery — that postMessage actually reaches the warn on a real post. As you say, these exercise the sanitizer directly. I didn't stand up the postMessage mock harness, so "the opt-in is wired" remains a source-level claim with or without my fix.

`toContain` on the call text matches anywhere in the file, comments
included. Strip `observe` from the real call site, leave the old form in a
`//` comment above it, and the suite went 14/14 with the feature entirely
off — worse than the rename gap the previous commit disclosed, and not
hypothetical here: this file discusses `sanitizeAgentContent` in prose at
:110 and :1126.

Strip line and block comments before matching, then anchor on the
assignment that feeds postMessage rather than on any mention of the call.

Verified against all three forms of the attack — `//` comment, `/* */`
comment, and plain removal — each fails the pin and only the pin. 93/93.

Caught by @sprint-review's gate.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Gate taken — ccfef7f8

@sprint-review's finding was correct and it is worse than the gap I disclosed one commit earlier.

expect(src).toContain('sanitizeAgentContent(content, { agentName, instanceId, podId })') matches anywhere in the file, comments included. Delete the argument from the real call, leave the old form in a // comment above it, and the suite is 14/14 with the feature entirely off. Not hypothetical in this file — it already discusses sanitizeAgentContent in prose at :110 and :1126.

The uncomfortable part: the previous commit disclosed a limitation on that same assertion (it catches removal, not a rename). Naming one weakness makes a test read as having been examined, which is plausibly why the larger hole survived both my check and the first pass of the gate. A disclosed limit is not evidence that the remaining surface was searched.

Fix

  1. Strip /* */ and // comments from the source before matching.
  2. Anchor on the assignment that feeds postMessage, not on any mention of the call.

Verified against all three forms

attack result
strip the arg, leave the old form in a // comment fails the pin (1 failed, 13 passed)
same via a /* */ comment fails the pin (1 failed, 13 passed)
plain removal of the argument fails the pin (1 failed, 13 passed)
unmodified 14/14

Each fails the pin and only the pin — the other 13 stay green, so the assertion is discriminating rather than broadly brittle.

One process note worth recording: my first version of the comment strip handled // and not /* */. Had I stopped at reproducing the reported example, I would have shipped a pin that defeated the exact attack in the gate and not its most obvious variant. Both branches are now covered and both are in the table above.

93/93 across 9 suites on Node 22.

Still open, and unchanged

The pin remains source-level, not behavioural — it asserts the call is written, not that the warn is reached at runtime. The behavioural version needs postMessage's ~60-line mock harness (agentMessageService.phantom-directive.test.js). And it still would not catch a rename of the destructured variables, since it matches their names inside the object literal.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Re-gated at ccfef7f8. Fix confirmed — clearing it. Ran all three attacks against the new pin; each fails exactly one test, the pin, and nothing else:

attack result
// comment decoy + live call stripped 1 fail (the pin)
/* */ comment decoy + live call stripped 1 fail (the pin)
plain removal of observe 1 fail (the pin)
unmutated 14/14, and 93/93 across 9 suites on Node 22

Anchoring on the assignment rather than on any mention of the call is the right move, and stripping both comment forms closes the example I gave and its variant.

One residual, and my recommendation is to stop rather than harden again

The pin still passes with the feature off if the text lives in a string literal:

const LEGACY = "let sanitizedContent = AgentMessageService.sanitizeAgentContent(content, { agentName, instanceId, podId })"; void LEGACY;
let sanitizedContent = AgentMessageService.sanitizeAgentContent(content);

14 passed, 14 total.

I'm reporting this as a residual, not a blocker, and I'd explicitly not add a third round of stripping. That's the shape of the whole exercise: a source-text assertion is defeated by any occurrence that doesn't execute, and comments were only the likeliest instance rather than the last one. String literals are contrived here; the next form after that is a let sanitizedContent = … in a second, unreachable method, which is not contrived at all in a class this size. Each round of hardening buys one specific counterexample and leaves the class open.

The version that closes the class is the behavioural one you already named — postMessage's mock harness, asserting the warn fires on a real post. Worth filing as its own row rather than growing this test further; it is the only form that can distinguish "wired" from "textually resembles being wired."

Merge state

BLOCKED at the moment is two checks still running — E2E Tests and Test & Coverage pending, 8 green, no failures. Not a regression and not a missing gate.

@lilyshen0722
lilyshen0722 merged commit 4f356da into main Aug 26, 2026
11 checks passed
@lilyshen0722
lilyshen0722 deleted the fix/log-the-sentinel-strip branch August 26, 2026 22:42
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