Skip to content

Fix #1046, #1047, #1052: cross-store recovery, quadratic stdin extraction, dropped summarizer spans - #1084

Merged
fdaviddpt merged 11 commits into
mainfrom
fix/1046-1047-1052
Nov 1, 2026
Merged

fdaviddpt merged 11 commits into
mainfrom
fix/1046-1047-1052

Conversation

@fdaviddpt

@fdaviddpt fdaviddpt commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

#1046 -- cross-store recovery

Closes #1046

Recovery (scripts/capture-gap-check.sh) now declines to force-save a candidate transcript unless _remember_recovery_prev_id_vouched() confirms it under THIS store's own roster, checking the same two evidence sources capture_was_seen() checks (the per-session capture-alive.d marker and the legacy single-slot file), with the id sanitized the same way capture_was_seen() sanitizes its own. The guard sits at the recovery call site only, not inside _find_previous_transcript itself: that function's PREV_ID/PREV_JSONL result is shared with the #200 capture-gap check, and gating resolution itself would make a genuine capture gap indistinguishable from a foreign store's session. A first attempt that gated inside _find_previous_transcript (matching the issue's own suggested diff literally) broke the existing capture-gap test suite and was reverted.

This narrows recovery's own original use case (rescuing a session with no evidence anywhere at all, the #200/#270 scenario) -- that trade-off is accepted by the issue's own design and is documented in changelog.d/1046.fixed.md. One side effect: the capture-gap notice's "is being recovered" wording is now unreachable -- that wording is effectively dead code after this change -- left in place rather than removed, since removing it is a separate decision.

Review round 2 fix: a chat-only session (no tool calls at all, so post-tool-hook.sh's capture-alive.d marker was never written) that died without a clean SessionEnd was no longer rescuable under the guard above -- new data loss this PR would otherwise have introduced. Fixed: SessionStart now writes its own cheap "started under this store" marker (plain redirect, no fork) and recovery's vouching check accepts either marker. The #200 "never captured" notice also now rewords itself when recovery's own log says the session "may belong to a different store," instead of flatly claiming nothing was captured.

Not fully closed by this PR: the issue's own body also raises a second, separate root cause -- a pinned store cannot be configured, because _LIB_MEMORY_DIR_LOADED=1's early return in lib-memory-dir.sh:41 prevents Pass 2 from ever building REMEMBER_CONFIG, and REMEMBER_CONFIG itself is unusable because bootstrap-dirs.sh moves it under $REMEMBER_DIR/tmp/ and the exit trap deletes it. This needs real design work on how config layering should interact with a pinned REMEMBER_DIR and is out of scope here. Maintainer: please keep #1046 open for that half, or file it separately, rather than treating this PR as closing it in full.

#1047 -- quadratic stdin extraction

Closes #1047

Supersedes PR #1049 (external contributor CNSeniorious000, branch fix/1047). Review round 1 bounded only _stdin_json_string_into's own match input to 4096 bytes, leaving HOOK_STDIN's own read-loop accumulation at scripts/session-start-hook.sh:132 (HOOK_STDIN="$HOOK_STDIN$_line") still quadratic and unbounded -- measured at 3.3MB/2,500 lines = 68.8s on bash 3.2, 23.6s on bash 5.3, and the existing tests only exercised the extracted function directly, missing this entirely.

Review round 2 adopts PR #1049's own approach: HOOK_STDIN is now capped at a 32KiB ceiling during accumulation (stop appending past the cap, rather than building the full string and truncating after), matching the existing before_session_start/after_session_start listener-publish block's own 32KiB cap (#266) so that contract keeps its byte-for-byte promise at or under the cap. Credited with a Co-authored-by: CNSeniorious000 <[email protected]> trailer on the commit that carries the parts taken from #1049. A new end-to-end test drives a real 1MB/2,500-line payload through the actual hook script (not just the extracted function): red at 8.51s pre-fix, green at 1.08s post-fix.

local LC_ALL=C was added to _stdin_json_string_into after review, because without it the byte-count and slice in this function count/slice by CHARACTER under a UTF-8 locale, loosening the bound up to 4x for multi-byte content -- and the same fix was applied to capture-gap-check.sh's own separate copy of the function, restoring byte-parity between the two copies (a parity test added this round is red before, green after). The top-level read loop itself needed an explicit LC_ALL save/restore around its own byte-counting, since it is not inside a function and can't use local. A fail-closed check was also added before the closing-quote strip, because a value whose opening quote survived the 4096-byte bound but whose closing quote did not previously returned SUCCESS with the unterminated truncated tail as the value -- a corrupted-but-non-empty result rather than the documented "missed" degradation every other case in this file produces.

Accepted tradeoff, now documented in code comments: the publish-block's old "holds it complete" promise for payloads above 32KiB is now genuinely unreachable -- real, but unavoidable without reintroducing the quadratic join. Payloads at or under 32KiB keep the existing complete-and-exact contract; payloads above it are capped, not held complete, same as #1049's own approach.

Out of scope, per the issue's own comment thread: the three sibling hooks sharing the same ${var#*pattern} operator (post-tool-hook.sh, session-end-hook.sh, user-prompt-hook.sh) -- a PostToolUse payload can legitimately carry a large tool result, so a blanket window there needs its own measurement, not a drive-by.

#1052 -- dropped summarizer spans (ask 1 of 2)

Refs #1052 (not Closes -- see below)

scripts/doctor.sh gets a new "Dropped summarizer spans" section counting [validate] REJECTED / [haiku] REJECTED lines across every daily log present, warning with the count and the most recent line. A reject gate firing is a SUCCESSFUL summarizer call that drops a span of real work -- invisible to #870's own tmp/last-summary-failure counter, which is only written on a hard call failure, never on a gate rejecting a successful reply's content.

Review round 2 fix: the WARN message no longer claims the dropped span itself is "kept, not lost" -- keep_rejected_text only saves the refusal text, not the span, and by the time it runs the position has already moved past that span; rejected-*.md keeps only 20 files, shared with [ndc]. The message now says only what's actually true. Also fixed a doctor.sh escaped-quote convention violation (now uses printf -v _dq '\042' like sibling warnings in the same file).

Only ask 1 of the issue's two asks is addressed, and save-session.sh is genuinely unchanged -- spans described by the issue are still dropped in the way #1052 describes. This PR therefore references #1052 rather than closing it. Ask 2 -- salvaging a header refusal with a usable body, not advancing the position past a refused span's summary, or changing save-session.sh's prompt wording -- is a separate, more judgment-heavy change left for its own issue/PR.

Review

Two rounds of review (general-purpose Explore + oss:auditor each round, plus a maintainer/scheduler CI-confirmed pass). Round 1 fixes: a legacy-slot evidence-source gap in the roster check, an id-sanitization gap, the LC_ALL byte/char-count gap, and the straddling-boundary fail-closed gap. Round 2 fixes (this CI-driven pass): the HOOK_STDIN quadratic join (#1047), the chat-only-session rescue regression and #200 notice wording (#1046), the doctor.sh message accuracy and quote convention (#1052), two tests switched to use resolve_bash() instead of a bare "bash" string, and docs/windows-skip-triage.md updated for the two win32-skipping test files this PR adds.

One finding left as-is both rounds: doctor.sh's unreadable-log pattern folds to a zero count the same way every pre-existing section in that file already does -- pre-existing across the whole file, not introduced by this diff, ranked non-blocking by review.

Closes #1046, Closes #1047, Refs #1052.

🤖 Generated with Claude Code

[AI-generated]

fdaviddpt and others added 2 commits November 1, 2026 00:40
…tion, dropped summarizer spans

#1046: SessionStart recovery no longer force-saves another store's live
session when several terminals pin different REMEMBER_DIRs at the same
project directory. Recovery now declines to force-save a candidate with no
marker under this store's own tmp/capture-alive.d roster -- gated at the
recovery call site only, not inside _find_previous_transcript, so the #200
capture-gap check (which shares that function's result and depends on the
same "no marker present" signal for a different purpose) stays unaffected.

#1047: session-start-hook.sh's field extractor bounded the raw payload it
matches against to 4096 bytes, eliminating the O(n^2) `${var#*pattern}`
blowup a multi-megabyte stdin payload (e.g. a whole transcript piped in)
triggered -- measured 16.8s before the fix on a 150KB payload with the
target field at the end, same shape as the issue's own 21-hour hang.
HOOK_STDIN's own full accumulation is untouched, so the before_session_start/
after_session_start listener-publish contract (#266) is unaffected.

#1052 (ask 1 only): /remember:doctor now counts [validate]/[haiku] REJECTED
lines across the daily logs present and WARNs -- a reject gate firing is a
successful summarizer call that drops a span of real work, invisible to
#870's own failure-marker counter since the call succeeded. Ask 2 (salvaging
a header refusal with a usable body, or changing the prompt wording) is left
for its own issue/PR.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Explore and oss:auditor findings against 5a9998b, disposed as follows:

- #1046 recovery guard checked only one of capture_was_seen()'s three
  evidence sources (the capture-alive.d marker), missing the legacy
  single-slot file kept specifically for the upgrade-transition false
  positive capture_was_seen() already documents. Fixed: a new
  _remember_recovery_prev_id_vouched() checks both applicable sources
  (the third is excluded by construction, since recovery only reaches
  this guard when PREV_WAS_SAVED is already "no").
- Same function also sanitizes the session id before using it as a path
  component, matching capture_was_seen()'s own id allowlist -- defense in
  depth; empirically the dotglob-off default already makes a `.`/`..`
  id unreachable through _find_previous_transcript's own glob, confirmed
  by trying to reproduce it end to end, so this is tested directly
  against the function rather than through a (non-reproducing) hook
  fixture.
- #1046's functional narrowing of recovery (it can no longer rescue a
  session with literally no evidence anywhere, the original #200/#270
  no-marker case) is real and was under-documented -- changelog.d/1046
  now states it explicitly as the accepted trade-off the issue itself
  asked for, rather than leaving it to a test-file comment.
- #1047's _stdin_json_string_into gained two self-review fixes: LC_ALL=C
  (the 4096 bound was character-counted under a UTF-8 locale, not
  byte-counted, loosening the margin against the quadratic match), and a
  fail-closed check when a value's opening quote survives the bound but
  its closing quote does not -- previously returned success with a
  corrupted truncated value instead of the documented "missed" result.

Both reviewers' doctor.sh findings (unreadable-log-folds-into-zero,
pre-existing across every sibling section in that file) are left as-is
per their own non-blocking ranking.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ue, notice rewording, doctor.sh quote convention

#1047: the HOOK_STDIN accumulation loop in session-start-hook.sh was still
quadratic and unbounded (3.3 MB/2,500 lines measured at 68.8s on bash 3.2,
23.6s on bash 5.3) -- the earlier round only bounded _stdin_json_string_into's
own matched input. Now caps accumulation at a 32 KiB ceiling DURING the read
loop itself, matching the before_session_start/after_session_start listener-
publish block's own existing cap so every payload at or under it still
arrives byte-for-byte. Adopts the approach from external PR #1049
(CNSeniorious000/Muspi Merol); credited via Co-authored-by below. This
supersedes #1049 (its 4KB/4KB split-join approach would silently truncate a
legitimate 8-32KB payload before the listener-publish block ever saw it).
New end-to-end test drives the real hook with a 1MB transcript-shaped
payload. The capture-gap-check.sh copy of _stdin_json_string_into gets the
same LC_ALL=C, 4096-byte bound and fail-closed check, keeping the two copies
identical (pinned by test_entrypoint_sniff_bookkeeping_message_803.py's
parity test).

#1046: SessionStart now writes its own cheap "started under this store"
capture-alive.d marker (plain redirect, no fork) so a chat-only session (no
tool call, so post-tool-hook.sh's own marker never lands) is still rescuable
by recovery on its next startup -- new data loss the roster guard itself
introduced, not present before it. The pre-existing #200 "never captured"
notice is reworded when recovery's own log already says a candidate may
belong to a different store, rather than contradicting it with the flat
"not captured" wording. tests/test_jq_fallback_arg_667.py's fixture now
plants a roster marker for its PREV session, matching what a real previous
session's own SessionStart would have written. test_roster_skip_1046.py's
two direct subprocess calls use resolve_bash() rather than a bare "bash"
literal; docs/windows-skip-triage.md gains rows for it and for
test_doctor_dropped_summarizer_spans_1052.py.

#1052: doctor.sh's new "Dropped summarizer spans" WARN no longer claims the
dropped span itself is "kept, not lost" -- keep_rejected_text only saves the
model's own refusal text, never the span, and save-session.sh is unchanged
by this PR, so the span stays genuinely dropped. The escaped double-quote
in that WARN's message now uses this file's own printf -v _dq octal-042
convention instead of a backslash escape. Note for the maintainer: #1052
should stay OPEN after this merges (change "Closes #1052" to "Refs #1052"
in the PR body) -- save-session.sh's own position-advance-past-a-refused-
span behavior is unchanged, so the issue is not fully closed by this round.

Co-authored-by: CNSeniorious000 <[email protected]>
fdaviddpt and others added 8 commits November 1, 2026 01:56
…oop under UTF-8 locales

Explore + oss:auditor review of commit 32682fb both flagged the same gap
independently: the new HOOK_STDIN read loop counts and slices by CHARACTER
under any UTF-8 locale (the common CI default), the exact defect class
_stdin_json_string_into's own comment already names -- but that function's
`local LC_ALL=C` fix is unavailable here since this block is top-level
script code, not a function. A multi-byte-heavy payload could therefore
grow HOOK_STDIN up to ~4x past the documented 32 KiB byte ceiling before
the loop's own character-count check tripped. The quadratic growth this
whole round exists to bound stays bounded either way (it is a looser
ceiling, not an unbounded one), but the ceiling itself was not the number
the comments and changelog claimed.

Fixed by saving/restoring LC_ALL explicitly around the loop (bash has no
`local` outside a function, so a bare assignment would otherwise leak into
this hook's own later user-facing output). New test
(test_the_cap_is_a_byte_cap_not_a_character_cap_under_utf8) drives a
payload built from a 4-byte UTF-8 character under an explicit UTF-8
locale and asserts the cap holds in bytes, not characters.

Explore's other finding (the hooks.d/ publish FILE's own "holds it,
complete" promise is now unreachable above the 32 KiB cap, not merely
truncated-with-warning) is a real, unavoidable consequence of killing the
quadratic join at the source -- there is no cost-free alternative without
reintroducing the hang this round exists to fix. Left as a documented
tradeoff (the updated comment block already states it honestly); noted for
the maintainer in the handback rather than changed further here.

oss:auditor's other finding (doctor.sh's grep -c folds "zero matches" and
"grep itself failed" into the same WARN-does-not-fire outcome) is
pre-existing across the whole file and was already identified and left
as-is in this PR's own first review round (see PR #1084's own description:
"doctor.sh's unreadable-log pattern folds to a zero count the same way
every pre-existing section in that file already does -- pre-existing
across the whole file, not introduced by this diff, ranked non-blocking by
the auditor itself"). Not re-fixed here for the same reason.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… in the new #1047 test

tests/test_hook_stdin_chunked_read_1040.py's _read_site() located
session-start-hook.sh's stdin block by the literal text `HOOK_STDIN=""`
immediately followed by `if [ ! -t 0 ]; then` on the next line -- this
round's 32KiB-cap rewrite (and the LC_ALL save/restore added for the
byte-vs-character self-review fix) inserted code between those two lines,
so the locator's text.index() raised before any assertion ran, failing 4
session-start parametrized cases on the "hook tests (compiled) / windows-
latest" CI leg. Considered switching session-start-hook.sh onto the shared
_remember_read_stdin_into (scripts/lib-stdin.sh) the other three hooks
already use, per the review's own suggestion -- not done: that helper's own
accumulation (both its chunked and line-loop-fallback paths) is equally
unbounded, so moving session-start-hook.sh onto it without ALSO capping
lib-stdin.sh itself would not fully close #1047 on bash < 4.1 (the exact
case the issue's own worst numbers were measured against), and capping
lib-stdin.sh is a larger change touching three other hooks -- out of scope
for a CI-fix commit. Fixed the locator instead: it now starts at
_REMEMBER_HOOK_STDIN_CAP=32768 (the real start of the block, needed because
that constant is now referenced inside the loop) and ends at the stable
`unset _hook_stdin_lc_all_was_set ...` line that closes the whole block,
rather than the first `fi` reached -- the block now contains three `fi`
lines of its own. The #1040 field-parity assertions this test exists for
are unchanged; all previously-passing cases still pass, and the bug the
locator failure was masking (whatever it would have caught) was never
triggered in this run either way, since LINE_LOOP_MAX_PAYLOAD (16 KiB)
already keeps every payload these session-start cases exercise well under
the new 32 KiB cap.

Did not confirm whether the SAME locator bug also fails on non-compiled,
non-Windows legs (it should, being a pure text-match issue independent of
platform or compilation) -- only the one CI leg named in the report was
investigated; the fix is leg-independent, so it should resolve on every
leg this affects, not only the one that was reported.

tests/test_session_start_stdin_cap_1047.py's new UTF-8-byte-cap test fed a
multi-byte payload through subprocess.run with text=True and no explicit
encoding, which on Windows decodes/encodes via the platform's preferred
codepage (cp1252) rather than UTF-8 -- raising UnicodeEncodeError on the
`input=` argument before the subprocess even started, since cp1252 cannot
represent the payload's own 4-byte UTF-8 character at all. Fixed by pinning
encoding="utf-8" explicitly on that one subprocess.run call.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…rge-redo

# Conflicts:
#	tests/test_locale_ranges_695.py
Three tests failed in CI against the #1046/#1047/#1052 branch, all in
test fixtures/assertions that predate or were invalidated by round 2's
new SessionStart roster marker -- not bugs in the guard itself.

tests/test_recovery_transcript_leak_407.py's _startup_project fixture
gives PREV five real tool_use lines in its transcript but never plants
the capture-alive.d/PREV marker those tool calls would themselves have
produced under post-tool-hook.sh (pre-existing since #206, unrelated to
this PR). #1046's recovery guard reads that exact marker to tell "ran
under this store" from "may belong to a different store sharing this
project's transcript directory" -- so the fixture's omission is not a
realistic "never captured" case, it is a hole the guard correctly
declines on. Planted the marker in the fixture instead of weakening the
guard; this also fixes test_detached_spawn_fd_hygiene_648.py's
test_session_start_recovery_spawn, which imports the same fixture.
tests/test_roster_skip_1046.py's own test_a_chat_only_previous_session_is_still_rescued
already pins the marker staying in capture-alive.d (not moved
elsewhere), so this is the fixture-side fix, not a guard change.

tests/test_session_start_promo_spawn_budget_660.py's
test_capture_seen_prune_is_gated_on_the_threshold asserted an
under-threshold capture-alive.d directory is left with exactly its 2
seeded entries. Round 2 (already shipped on this branch) has
session-start-hook.sh write its own cheap roster marker for every
SessionStart's own session id into that same directory,
unconditionally -- intentional, so a chat-only session still earns
roster evidence. That legitimately adds one entry regardless of the
prune threshold, so the assertion now checks the 2 seeded entries
survive unpruned, plus exactly the new run's own SESSION marker.

Reran the full targeted set plus test_roster_skip_1046,
test_jq_fallback_arg_667, test_locale_ranges_695, test_capture_gap_notice,
test_session_start_prev_session_270, test_previous_transcript_no_sort_691
and the release-tree/branch suites: 557 passed, 1 skipped (case-insensitive
filesystem).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ne cost

CI self-review after pushing the #1046 guard-fixture fix: every Windows
leg (3.9-3.12) failed test_session_start_stdin_cap_1047.py's
test_a_1mb_transcript_sized_stdin_does_not_hang_the_real_hook with a
subprocess.TimeoutExpired at the 30s budget -- consistently, across
every Windows job including the compiled-hooks leg, while every
Ubuntu/macOS leg stayed well under it.

The #1047 round-3 fix correctly caps HOOK_STDIN's own growth at 32KiB
during accumulation, closing the quadratic string-concat cost. But the
`while IFS= read -r -t 1 _line` loop around it kept iterating once per
line for the REST of an oversized payload even after the cap was hit,
with nothing left to do once HOOK_STDIN is already capped. That is
O(lines) of pure per-`read`-call overhead, not O(bytes) -- cheap enough
on Linux/macOS bash to go unnoticed, but Windows runners (git-bash/MSYS
syscall overhead per shell builtin call) paid enough per iteration that
2,500 lines alone pushed this test past its budget.

Fixed by breaking out of the line loop the instant the cap is hit and
draining whatever is left of stdin with a single bulk `cat <&0
>/dev/null`, copying bytes without ever growing a string or forking a
process per line. HOOK_STDIN's own contract (byte-identical up to the
32KiB cap) is unchanged; only the work done AFTER the cap is reached is
removed.

tests/test_locale_ranges_695.py's hardcoded allowlist entry for
scripts/session-start-hook.sh's CURRENT_SESSION_ID bracket range
(line 380) updated to its new line (399) -- this diff inserts 15 lines
above it.

Verified locally (fast on this platform by construction -- the bug is
Windows-specific) plus the full #1046/#1047 targeted set, the release-
tree/branch byte-budget suites, and test_locale_ranges_695: 565 passed,
1 skipped (case-insensitive filesystem, pre-existing).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
- #1052: doctor's dropped-summarizer-spans check now matches #1085's
  renamed [summarizer] tag (was validate|haiku only), confirmed [ndc]
  REJECTED is retried rather than dropped and left out of the count.
- #1047: the post-cap stdin drain now runs detached, so a writer holding
  its end of stdin open past the cap can no longer hang the hook.
- #1046: SessionStart's own roster marker moved out of capture-alive.d
  into its own tmp/session-started.d/, so the #200 capture-gap check can
  no longer read a chat-only session's own marker as proof PostToolUse
  ran; only the recovery guard accepts either folder. Added a one-time
  upgrade grace (tmp/roster-epoch) so a pre-existing unmarked session from
  before this landed is still rescued once, not silently abandoned.
- Reworded the #1046 changelog fragment in plain language and corrected
  its claim that the #200 check is unaffected.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
3.16s observed on windows-latest against the 3.0s bound, from process
spawn overhead alone -- the fix (backgrounded drain) was correctly in
place. Widened to 5s, matching this file's other must-fire test.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…de-off

The writer now holds stdin for 15 s against a 5 s bound, so a later widening for a
slow runner cannot reach the hold and stop catching a blocking drain. The changelog
now says plainly that the one-time grace can still save one other window's
conversation into the wrong store per store, once, after the update.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@fdaviddpt
fdaviddpt merged commit 735e65c into main Nov 1, 2026
19 checks passed
@fdaviddpt
fdaviddpt deleted the fix/1046-1047-1052 branch November 1, 2026 04:42
fdaviddpt added a commit that referenced this pull request Nov 1, 2026
Recompute tests/test_locale_ranges_695.py's session-start-hook.sh
allowlist line from the merged file (421, not 307 or 411 from either
parent).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
fdaviddpt added a commit that referenced this pull request Nov 1, 2026
… first pass missed

Seven findings from the scheduler's own review of 5345c9e, all addressed
with TDD (red before fix, positive control after):

1. HIGH: capture-gap-check.sh's fast path (inherited PROJECT_DIR/
   PIPELINE_DIR/REMEMBER_DIR, #1069/#1079) never re-sources
   lib-memory-dir.sh, so it could only see REMEMBER_DIR_UNSAFE if the
   parent exported it -- and lib-memory-dir.sh's own REMEMBER_DIR_UNSAFE=1
   was a plain assignment, never exported. Now exported, and all three of
   this file's own mkdir sites (session-slug, case-divergence,
   REMEMBER_STORE_ROOT/tmp) gate on the inherited flag.

   Evidence for the main-regression question: origin/main (no #1064 at
   all) has ZERO occurrences of REMEMBER_DIR_UNSAFE in lib-memory-dir.sh --
   gap 1 was never fixed there; #1067/#1086 added capture-gap-check.sh's
   own new mkdir sites onto that same pre-existing, still-open gap, not a
   regression of a working #902 guard.

2. HIGH: session-start-hook.sh:457's tmp/session-started.d mkdir (added by
   #1084/#1086, after this issue's own 806/1200/1630 gating pass) was never
   covered. Gated; new full-SessionStart-run test added (not just
   bootstrap-dirs.sh in isolation).

3. MEDIUM: changelog.d/920.fixed.md's "every memory-folder save site is now
   covered" overclaimed before round 2 landed the above; reworded to "every
   ... site this issue found", now true.

4. MEDIUM: doctor.sh's REMEMBER_DIR line printed OK unconditionally even
   when REMEMBER_DIR_UNSAFE=1 -- the refusal's only other trace is a
   stderr-only FATAL line Claude Code hides for exit-0 hooks, and
   user-prompt-hook.sh/capture-gap-check.sh both discard. Now FAILs (human
   report) and reports remember_dir_unsafe:true/false (--json, always
   present, never an absent key).

5. LOW: log.sh's _remember_log_dir_unsafe is never called at runtime any
   more -- documented as deliberately retained (not dead code to delete),
   since test_remember_dir_guard_920_sync.py extracts and runs it as the
   "log" arm of the three-way consistency check.

6. LOW: lib-memory-dir.sh's UNC regex accepted a third backslash
   (`[\\][\\]?*`) where post-tool-hook.sh/log.sh's copies refuse it
   (`[\\][\\][^\\]*`) -- brought in line with the stricter copies; new
   sync-test case pins it.

7. LOW: session-end-hook.sh's WARNING said "could not create ...
   /logs/autonomous" for both an unsafe-dir refusal and an ordinary mkdir
   failure. Split into two distinct messages.

Every fix's test was confirmed red against the unfixed code and green
against the fix, including the two-item hazard my own first session-start
test initially missed vacuously (see that test's own docstring: an
absolute-but-newline-bearing REMEMBER_DIR resolves outside cwd, so
"nothing leaked under cwd" alone passes even with the gate fully reverted
-- caught by re-deriving against "would this test pass if the code did
nothing", fixed by asserting against the actual unsafe path instead).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
fdaviddpt added a commit that referenced this pull request Nov 1, 2026
* Fix #920: close three gaps in #902's REMEMBER_DIR safety guard

Centralise the unsafe-dir check in lib-memory-dir.sh (new REMEMBER_DIR_UNSAFE
flag) and gate every mkdir -p "$REMEMBER_DIR/..." site that was not already
covered by #902's own guard -- bootstrap-dirs.sh, three more sites in
post-tool-hook.sh, session-start-hook.sh (x3), session-end-hook.sh and
write-handoff.sh. Fix log()'s own write-to-sink path so a FATAL logged while
the sink is active (an append to /dev/null that always succeeds) reaches
stderr instead of vanishing silently. Teach both guard predicates
(_remember_dir_is_unsafe, _remember_log_dir_unsafe) to accept a UNC-rooted
value as absolute rather than misclassifying it as unsafe.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Fix #920 self-review: dedupe FATAL line, fix stale comments, pin guard sync

Explore review (against commit c15e4f3) found a real regression: lib-memory-dir.sh's
new unsafe-dir echo and log.sh's own pre-existing one both fired on every tool call
once REMEMBER_DIR went unsafe, doubling hook-errors.log noise. log.sh now reads the
already-exported REMEMBER_DIR_UNSAFE flag instead of recomputing and re-announcing it.

Also fixes a self-contradictory comment ("above" vs "further down this file" about
the same call site) and a fictional intermediate line-number claim in the scanner
allowlist's own history comment. Adds a pin that lib-memory-dir.sh's and
post-tool-hook.sh's necessarily-duplicated _remember_dir_is_unsafe copies (the
latter exists because post-tool-hook.sh's fast path never sources lib-memory-dir.sh)
stay byte-identical, so a future edit to one that forgets the other fails loudly.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Fix #920 CI: rename duplicate top-level function, compact the new guard block

CI's test_compile_hooks_900.py failed on ubuntu-latest/3.9: the #900 compiled-
hook build inlines every sourced file's top level into one script, and
lib-memory-dir.sh's new _remember_dir_is_unsafe collided under the SAME name
with post-tool-hook.sh's own pre-existing (#902) copy once both land in the
same compiled text. Renamed lib-memory-dir.sh's copy to
_remember_lmd_dir_is_unsafe and updated tests/test_remember_dir_guard_920_sync.py
to compare the three predicates' LOGIC (not their names) across lib-memory-dir.sh,
post-tool-hook.sh and log.sh.

Also compacted the new block's if/else/fi into a single && guard, trimming
compiled bytes toward session-start-hook.sh's 120 KiB release budget (further
addressed in the next commit).

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Fix #920 CI: shrink the new guard predicate to fit session-start-hook.sh's byte budget

check_release_tree.py failed on the compiled session-start-hook.sh (123352 bytes,
over the 120 KiB release budget) -- that hook was already within 37 bytes of the
budget before this fix (per #1002's own comment), and lib-memory-dir.sh's new
_remember_lmd_dir_is_unsafe block alone added 472 bytes to every hook that sources
it (unconditionally, at top level, regardless of whether that hook's own code
reads REMEMBER_DIR_UNSAFE -- tree-shaking only drops unused FUNCTIONS, not
top-level code that runs to set the flag).

Rewrote the predicate to the smallest form that still preserves byte-wise
(#695) LC_ALL=C matching: two `[[ ]]` tests with early returns instead of a
nested `{ } || [[ ]]` combined with a separate if/else/echo block, and a
single bracket class `*[$'\n\r']*` for the embedded-control-character case
instead of two separate `$'...'` glob tests. Also widens the UNC acceptance
from "two backslashes then one non-backslash character" to "two backslashes
then any one character", which incidentally narrows (but does not close) the
auditor's below-bar bare-backslash finding.

Updated tests/test_remember_dir_guard_920_sync.py to assert BEHAVIOURAL
agreement across all three predicates (a table of REMEMBER_DIR values, run
through each predicate, compared) rather than textual body equality -- the
compact rewrite legitimately reads differently from the other two copies
while classifying every case the same way, so a body-text diff is no longer
the right invariant.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Fix #920 CI: merge the guard predicate and flag-setter, drop the unneeded export

Further shrinks the new lib-memory-dir.sh block toward session-start-hook.sh's
120 KiB compiled-hook budget. Merges the separate predicate function and the
if/echo block that called it into one function that sets REMEMBER_DIR_UNSAFE
directly (default unsafe=1, cleared to 0 only on a recognised absolute/UNC
shape, same as before). Drops `export REMEMBER_DIR_UNSAFE`: nothing reads this
variable across a process boundary -- every script that checks it has already
sourced lib-memory-dir.sh itself and computed its own copy in its own process,
so export was pure overhead paid by every hook that sources this file.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* Fix #920: rewrite changelog fragment in plain language for non-technical users

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Fix #920 CI: sanction lib-memory-dir.sh's new unsafe-dir predicate in the byte-pin guard

test_the_per_tool_call_path_is_not_touched (#298/#299) byte-pins
lib-memory-dir.sh against origin/main; the new _remember_lmd_set_dir_unsafe
block is a deliberate addition this guard had no allowance for yet. Red
before: 1 failed, 21 passed in tests/test_case_divergence_298.py. Green
after: 26 passed (that file plus test_sanctioned_divergence_state_440.py).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Fix #920 CI: pass REMEMBER_DIR probe values through env, not argv, on Windows

windows-latest's four pytest legs plus the compiled-hook leg failed two
tests in TestUncPathIsSafe (test_remember_dir_guard_920.py) and the
cross-predicate consistency test (test_remember_dir_guard_920_sync.py):
both guard predicates reported a value carrying an embedded newline as
SAFE on windows-latest only, never on ubuntu/macos, and only for the two
CASES entries containing a raw newline byte -- every newline-free case
agreed across all three predicates on every platform.

The guard predicates themselves are unchanged, correct POSIX shell. The
break is in how the test harness got the probe value into the child bash
process: a bare (list2cmdline leaves it unquoted -- no space/tab/quote to
force quoting) argv element carrying a raw newline does not reliably
survive to the child's own argv on Windows, since a win32 command line is
a single string CreateProcess hands the child, which re-tokenizes it
itself. An environment variable's value is not re-tokenized the same way,
so both helpers now pass the probe value via env instead of argv.

Reasoned, not observed: no Windows host available locally to reproduce
the original failure or re-run the fix directly. Verified instead that
the change does not regress the 22 tests in these two files plus
test_remember_dir_guard_902.py on macOS (all still pass), and that the
mechanism change is the minimal one that explains an argv-only, platform-
only, newline-only failure pattern.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Fix #920 review round 2: close remaining REMEMBER_DIR-unsafe gaps the first pass missed

Seven findings from the scheduler's own review of 5345c9e, all addressed
with TDD (red before fix, positive control after):

1. HIGH: capture-gap-check.sh's fast path (inherited PROJECT_DIR/
   PIPELINE_DIR/REMEMBER_DIR, #1069/#1079) never re-sources
   lib-memory-dir.sh, so it could only see REMEMBER_DIR_UNSAFE if the
   parent exported it -- and lib-memory-dir.sh's own REMEMBER_DIR_UNSAFE=1
   was a plain assignment, never exported. Now exported, and all three of
   this file's own mkdir sites (session-slug, case-divergence,
   REMEMBER_STORE_ROOT/tmp) gate on the inherited flag.

   Evidence for the main-regression question: origin/main (no #1064 at
   all) has ZERO occurrences of REMEMBER_DIR_UNSAFE in lib-memory-dir.sh --
   gap 1 was never fixed there; #1067/#1086 added capture-gap-check.sh's
   own new mkdir sites onto that same pre-existing, still-open gap, not a
   regression of a working #902 guard.

2. HIGH: session-start-hook.sh:457's tmp/session-started.d mkdir (added by
   #1084/#1086, after this issue's own 806/1200/1630 gating pass) was never
   covered. Gated; new full-SessionStart-run test added (not just
   bootstrap-dirs.sh in isolation).

3. MEDIUM: changelog.d/920.fixed.md's "every memory-folder save site is now
   covered" overclaimed before round 2 landed the above; reworded to "every
   ... site this issue found", now true.

4. MEDIUM: doctor.sh's REMEMBER_DIR line printed OK unconditionally even
   when REMEMBER_DIR_UNSAFE=1 -- the refusal's only other trace is a
   stderr-only FATAL line Claude Code hides for exit-0 hooks, and
   user-prompt-hook.sh/capture-gap-check.sh both discard. Now FAILs (human
   report) and reports remember_dir_unsafe:true/false (--json, always
   present, never an absent key).

5. LOW: log.sh's _remember_log_dir_unsafe is never called at runtime any
   more -- documented as deliberately retained (not dead code to delete),
   since test_remember_dir_guard_920_sync.py extracts and runs it as the
   "log" arm of the three-way consistency check.

6. LOW: lib-memory-dir.sh's UNC regex accepted a third backslash
   (`[\\][\\]?*`) where post-tool-hook.sh/log.sh's copies refuse it
   (`[\\][\\][^\\]*`) -- brought in line with the stricter copies; new
   sync-test case pins it.

7. LOW: session-end-hook.sh's WARNING said "could not create ...
   /logs/autonomous" for both an unsafe-dir refusal and an ordinary mkdir
   failure. Split into two distinct messages.

Every fix's test was confirmed red against the unfixed code and green
against the fix, including the two-item hazard my own first session-start
test initially missed vacuously (see that test's own docstring: an
absolute-but-newline-bearing REMEMBER_DIR resolves outside cwd, so
"nothing leaked under cwd" alone passes even with the gate fully reverted
-- caught by re-deriving against "would this test pass if the code did
nothing", fixed by asserting against the actual unsafe path instead).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Fix #920 CI: triage the new doctor.sh win32-blanket-skip module

tests/test_windows_skip_triage_497.py (#497) requires every module with a
module-level `pytestmark = pytest.mark.skipif(sys.platform == "win32", ...)`
to have a row in docs/windows-skip-triage.md -- the new
tests/test_doctor_unsafe_dir_visibility_920.py carries the same
bash-subprocess skip reason as its sibling doctor.sh modules and had none.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
fdaviddpt added a commit that referenced this pull request Nov 1, 2026
…1092)

* Fix #1052: retry a rejected span before giving up on it

A reject gate ([validate] REJECTED or [summarizer] REJECTED) is a
successful summarizer call that discards real work. Until now
save-session.sh advanced the saved position past that span
unconditionally, so a span the model refused once was never
summarized -- gone for good on the first refusal.

Add record_rejected_span(), the same bounded-retry shape
record_summary_failure() already uses for a hard call failure, with
its own separate marker/threshold (thresholds.max_rejected_retries,
default 3): a rejected span is now retried next run, and only after N
consecutive rejections of the same span does the position finally
advance -- with the raw, unsummarized span text (not just the model's
refusal) parked at tmp/dropped-span-*.md so nothing is silently lost.

Updates doctor.sh's #1084 "Dropped summarizer spans" message to
describe what now happens instead of claiming the span is still gone
for good. Pairs every "must not fire" rejection test with the
"must fire"/positive-control pair required by this repo's own
CLAUDE.md (an accepted summary still advances; 0 retries forever,
matching max_summary_failures' own convention).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Address self-review findings on #1052's rejected-span retry fix

Explore and oss:auditor review of 103c35e found six real issues:

- A comment directly above the validate-REJECTED branch still claimed
  "the position still advances", contradicting the bounded retry it
  introduces three lines below.
- doctor.sh's WARN headline said "span(s) dropped by a reject gate"
  while counting every REJECTED log line, including ones that are
  retried and never actually dropped. Reworded to "rejection(s) hit a
  reject gate" (and the OK line to match), with the pinned tests in
  tests/test_doctor_dropped_summarizer_spans_1052.py updated to the
  same wording.
- docs/configuration.md documented max_summary_failures but not its
  new sibling max_rejected_retries. Added the missing row.
- REJECTED_MARKER was never cleared on a successful resolution path,
  unlike FAILURE_MARKER (cleared on SKIP and on a successful append).
  Added the same clears so a stale rejection count cannot survive past
  the span it belonged to.
- test_success_clears_the_rejected_count asserted only that the
  position advances, not that the marker file was actually removed --
  it would have passed even with the bug above present. Strengthened
  to assert the marker file's absence.
- tests/test_marker_write_fifo_653.py's static completeness guard
  (_MARKERS) was not extended to cover the new REJECTED_MARKER write
  site, so a future unguarded write to it would go unnoticed by the
  test that exists specifically to catch that.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

* Fix #1052 final review: key the rejection counter on span start, park on final flush, cap and clamp

The rejection counter keyed its span-id on $POSITION (the transcript's
current end), which grows on every save of a live session -- the counter
never saw the same span twice, the count reset to 1 forever, and a
persistently refused span blocked every later span from being saved too.
Keyed on $SKIP_LINES (the span's actual start) instead, which does not
move across retries of the same span; applied the identical fix to
record_summary_failure's own span-id for the same reason.

A rejection on the session's final --force flush had no later save to
retry it, so it was simply lost rather than parked -- now parked
immediately when $FORCE is set. dropped-span-*.md files are capped to the
newest 20, the same retention rejected-*.md already has. 0
("retry forever") for thresholds.max_rejected_retries is clamped to the
default with a log line, since it could otherwise stall saving for the
rest of a session. doctor.sh now reports how many spans are currently
parked and where, and the give-up message also reaches hook-errors.log.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant