Skip to content

fix(apply): keep a stashed tool output's last newline (#752) - #753

Merged
amiddavid merged 1 commit into
mainfrom
fix/expand-trailing-newline
Oct 27, 2026
Merged

amiddavid merged 1 commit into
mainfrom
fix/expand-trailing-newline

Conversation

@amiddavid

@amiddavid amiddavid commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

fix(expand): a stashed tool output came back without its last newline

Summary

Written by GLM (rits/zai-org/glm-5-3) through Claude Code.

The sweep now stashes a tool output byte for byte, last newline included.
GET /expand gives back exactly what the request held. Closes #752.

What we found

The v0.6.2 release check removed 15 cat outputs through the cold sweep.
expand returned each one byte short: the file's own last \n was missing.

  • Claude Code appends a <system-reminder> block after a tool output.
  • normalize splits that block off before the components run.
  • The split also took the whitespace between the output and the block.
  • The body left over is what every offloader stashes and expand returns.
  • So the stash lost the output's final newline. The reminder itself stayed on
    the wire, after the marker.

Only reminder-carrying outputs were hit. Plain trailing \n, \n\n and
\r\n were already exact. The trim sat in splitTrailingReminders, the one
place every stashing offload passes through — sweep, summarizer, extract,
searchfold, mask — so one fix covers them all.

What changed

  • apply/reminder.go: the whitespace before a trailing reminder run stays
    in the body. The stash holds the output proper: everything before the run,
    including its last newline. The run itself still goes to the tail, and the
    request still carries it after the marker.
  • apply/reminder.go + apply/apply.go: slot.writeTail rebuilds the wire
    text. An unchanged output is byte-identical as before. A rewritten
    output gets the original separator back before the reminder, so the wire
    bytes are exactly what they were before this change — the reminder still
    follows a rewrite on its own line.
  • apply/sweep_stash_newline_test.go (new): the fix(expand): a removed tool output came back without its last newline #752 contract, end to end.
    The sweep drops four outputs ending in \n, \n\n, \r\n and a reminder
    run; every stash must resolve to the exact tool_result text minus the
    reminder, and the reminder case must still end with its block on the wire.
  • apply/reminder_internal_test.go: the split table now pins the boundary —
    whitespace before the run is body, whitespace after it is tail.

Data dependence: no change. The split moves bytes between body and tail,
both already stored; the stash gains the output's own trailing bytes. Test
text is synthetic.

One-time upgrade effect: the marker id of a reminder-carrying output
changes (hashKey hashes the stashed body, now one newline richer), so a
replayed pre-upgrade drop rebuilds different bytes. One cache-bust per
affected thread, self-healing. Content keys do not change — ContentKey
collapses whitespace — so frozen decisions and replay still match.

How it was tested

Every run on the eval box (glm752 = this branch, glm752-main = clean
origin/main at 245982d7):

# Copy Run Result
1 glm752 go test ./apply/ -run 'TestSplitTrailingReminders|TestTheSweepStashKeeps|TestTrailingReminder' Split table and new test passed; 4 TestTrailingReminder* failed — rewrites glued the reminder to the marker. Caught before merge, fixed by writeTail.
2 glm752 same, after the writeTail fix PASS (all)
3 glm752-main same tests, copied in FAIL, as required: the reminder case expands 2567 bytes, want 2568 — the last \n gone. The \n/\n\n/\r\n cases pass on main (guards). TestSplitTrailingReminders fails on the 5 updated boundary cases.
4 glm752 go vet ./apply/ clean
5 glm752 gofmt -l apply/ no output
6 glm752 go test -race -count=1 ./apply/... (detached) PASS

The box's two known-environment failures (TestInstallRefuses…,
TestInstallReports…, cmd package) are not in ./apply/... and were not run.

Closes #752

🤖 Generated with Claude Code

The v0.6.2 release check removed 15 cat outputs through the cold sweep, and
expand returned each one byte short: the file's own last newline was gone.

Why: Claude Code appends a <system-reminder> block after a tool output, and
normalize split the block off together with the whitespace between it and the
output. The body left over is what every offloader stashes and expand gives
back, so the stash lost the output's final newline. Only reminder-carrying
outputs were hit; plain trailing newlines were already exact. The trim sat in
splitTrailingReminders, the one split every stashing offload passes through,
so this covers sweep, summarizer, extract, searchfold and mask alike.

The whitespace before a trailing reminder run is output, not packaging, so it
now stays in the body and the stash holds the output proper, byte for byte.
The reminder run still goes to the tail and the request still carries it
after the marker. slot.writeTail rebuilds the wire text: an unchanged output
is byte-identical as before, and a rewritten one gets the original separator
back before the reminder, so the wire bytes are exactly what they were.

One-time upgrade effect: the content key of a reminder-carrying output
changes, so offload decisions frozen before the upgrade miss once and
re-freeze. One cache-bust per affected thread, self-healing.

Written by GLM (rits/zai-org/glm-5-3) through Claude Code.

Assisted-By: GLM
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 34cd085e1fdc approve

Verdict: approve

Findings

None.

Non-blocking

  • Commit message, "One-time upgrade effect" — the named mechanism is wrong. The message says
    "the content key of a reminder-carrying output changes". ContentKey
    (internal/extract/extract.go:137) collapses whitespace (wsRe) and trims the ends, so
    ContentKey("out") == ContentKey("out\n\n"). Content keys do NOT change across this fix, and
    frozen decisions keyed by them still match. What does change: the marker id (hashKey is a raw
    sha256, cmdfilter.go:361) and the descriptor's line and token counts. So a replay of a
    pre-upgrade drop rebuilds different bytes — the one cache bust the message promises — and
    NoteSweepExpand (extract_sweep_apply.go:404) stops attributing expands of those drops to the
    sweep, because the record keeps the old Marker. The stated outcome (one bust, self-healing) is
    right; the mechanism named is not. A one-line correction on the PR would help the next reader.
  • writeTail has no direct unit test. Its three branches (empty tail, unchanged, rewrite) are
    covered only end to end, by the new sweep test and the older reminder tests. The internal test
    file next to it tests splitTrailingReminders case by case. A table test of writeTail would
    pin the rebuild contract the same way.
  • The stash now holds all whitespace before the reminder run, not only the output's own last
    newline.
    When a client adds its own separator newline beyond the output's, expand returns
    that byte too. The bytes are contiguous, so no rule can tell them apart. The chosen boundary
    ("everything before the run is output") is the only deterministic one, and the test documents
    it. One byte rich is harmless where one byte short was the bug.

What I checked

  • Read the full diff (apply/apply.go, apply/reminder.go, apply/reminder_internal_test.go,
    apply/sweep_stash_newline_test.go) and the code around every change.
  • Traced splitTrailingReminders by hand over every case in the unit test, including two-block
    runs, whitespace-only bodies, quoted tags, and the byte cap. The loop sets cut at the open
    tag, so the whitespace before the run stays in the body, and body+tail == text still holds.
  • Proved the wire bytes do not change. Old writeback: rewrite + tail, where the tail carried the
    separator. New: rewrite + trailingWhitespace(body) + tail — the same run, so the same bytes.
    The unchanged branch (cur == body → cur + tail == preText) is exact in both.
  • Proved the stash boundary moved and nothing else. applySweepDrop and sweepDrop
    (extract_sweep_drop.go:105) stash content, the split body, so the stash now ends with the
    output's own newline. commitRefresh on replay re-stashes the same bytes under the same key.
  • Checked the change detection at apply.go:859 and writeBackToolText at apply.go:1949: both call
    writeTail, both compare against preText. A component that trims the body's trailing
    whitespace still counts as unchanged, because writeTail re-adds the separator.
  • Checked the other users of the split body for assumptions that the text is right-trimmed:
    contentClass (head sniff), format (trims before the JSON check), recordCount (trims),
    ContentKey (whitespace-insensitive), carriesRealMarker (substring). None break.
  • Checked that ContentKey stability keeps the sweep's replay matching (replayDrops matches by
    content key) and that kept-verbatim is content-key keyed, so expands stay honored.
  • Read the new test line by line: the asker reply shape matches the sweep's own fixtures
    (extract_sweep_batch_test.go:192), the marker regex matches expand.Marker's format, and the
    wantOutput values pin the exact stash contract, reminder excluded.
  • Read the older reminder tests (tool_reminder_test.go) against the new split: all assertions are
    shape-based (suffix, count) and hold under the new boundary.
  • Did not run tests or builds. Live tests are not approved for this review, and Go is not
    installed on this machine.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.311 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 34cd085e1fdc approve

Verdict: approve

Findings

None. I could not construct a wrong-byte, data-loss, or broken fail-open path from this change.

Non-blocking

  • apply/reminder.go:94 — cut == 0 is now redundant. strings.TrimSpace(text[:cut]) == "" already covers cut == 0 (an empty prefix trims to empty). Harmless; it just restates the old guard.
  • Dedup loses the "mixed reminder" case. hashKey in dedup is byte-exact. Two runs of one command, where only the second carries a trailing reminder, now hash differently: the separator stays in the body, so the bodies differ by that whitespace. Before #752 the split trimmed the separator, so both bodies matched and dedup fired. The result is a missed saving only. Dedup declines, which is fail-safe. The common case is unaffected: a client that appends the reminder appends it to every output, so both bodies carry the same separator (apply/tool_reminder_test.go:57 pins this and still holds).
  • The new e2e test does not by itself pin the separator on the rewrite path. apply/sweep_stash_newline_test.go:161 asserts only HasSuffix(got, suffix) for the reminder case. If writeTail dropped the separator and glued the reminder onto the marker, this test would still pass. The separator is pinned elsewhere: apply/tool_reminder_test.go:74 asserts HasSuffix(dup, r2) where r2 includes its own \n\n separator. Coverage exists, but it lives in the older file.

What I checked

  • splitTrailingReminders, every case in apply/reminder_internal_test.go traced by hand. The invariant body+tail == text holds on every return path. The new "blank space and reminders only" guard is equivalent to the old trimmed cut == 0 guard, because TrimRight(x) == "" iff TrimSpace(x) == "".
  • slot.writeTail, both branches. Unchanged path: cur == body returns body + tail == preText, byte-exact. Rewrite path: cur + trailingWhitespace(body) + tail reproduces the pre-#752 wire bytes (cur + old tail, where the old tail began with the same separator). trailingWhitespace is rune-safe: ASCII whitespace bytes never occur inside UTF-8 continuations.
  • Both call sites updated and no other consumer of tail remains: apply/apply.go:859 (equal-count writeback) and apply/apply.go:1949 (writeBackToolText, the count-change rebuild path). grep over the repo finds no other .tail reconstruction.
  • Slot construction (apply/apply.go:1647-1653): preText holds the whole original and tail its suffix, so preText[:len(preText)-len(tail)] is always the split's body. Slots are per-request and never mutated.
  • The stash boundary, end to end. The offloaders stash schema.MessageText of the normalized tool message, which is the body. The body now keeps the output's trailing newline, so expand.Resolve returns it. The reminder stays out of the stash and stays in the request after the marker, as the new test asserts.
  • The new test's use of the sweep ping API: SweepPingSubstitute / SweepPingWait / SweepPingResult field names and semantics against components/offload/extract_sweep_ping.go; the dropAsker reply shape against internal/extract/adjudicate.go (Verdict fields, [N] inventory labels, the drop-requires-needed_by:"none" contract) and against the sweep's own fixtures in extract_sweep_batch_test.go:193. The test would have failed on the pre-#752 split (the stash was one byte short), so it is a real regression test.
  • Downstream components that read the body. reformat and extract trim before JSON detection (components/reformat/format.go:144, internal/extract/prompt.go:555), so the separator now in the body does not block them. sweepDescriptor counts the separator's newline, but drop and replay compute from the same body, so the descriptor stays stable and true.
  • Cross-version effects. extract.ContentKey collapses whitespace, so drop-record replay and frozen decisions still hit after the boundary moves. commitRefresh re-stashes the payload under the recomputed key, so a replayed marker never dangles. The one-time cost is a changed marker hash in replayed bytes, which matches the commit message's "one cache-bust per affected thread, self-healing".
  • Existing reminder tests traced against the new split: TestTrailingReminderDoesNotBlockDedup, TestTrailingReminderDoesNotBlockFormat, TestTrailingReminderInTextArray, TestTrailingReminderUnchangedIsByteIdentical, TestTrailingReminderSurvivesCountChange all hold under the new boundary (the ccReminder fixture's \n\n separator moves from tail to body, and every assertion still follows).

Live tests were not run (not approved); all verification above is by reading and hand-tracing the code.

@amiddavid

Copy link
Copy Markdown
Collaborator Author

Correction to the commit message and PR body (thanks, reviewer 2):

The "one-time upgrade effect" paragraph names the wrong mechanism.

  • Content keys do not change. ContentKey collapses whitespace and trims
    the ends, so a reminder-carrying output hashes the same before and after
    this fix. Frozen decisions and drop-record replay still match.
  • What changes: the marker id (hashKey is a raw sha256 of the stashed
    body, which now ends one newline richer) and the descriptor's line and
    token counts.
  • Effect: a replayed pre-upgrade drop rebuilds different marker bytes, so
    the affected thread takes one cache bust. Drop records keep their old
    Marker, so expands of those drops stop being attributed to the sweep.

The stated outcome (one bust, self-healing) stands. The named cause did not.

@amiddavid
amiddavid merged commit f234587 into main Oct 27, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

fix(expand): a removed tool output came back without its last newline

1 participant