Skip to content

Fix #1079, #1060: stop re-bootstrapping config on every SessionStart and stop stacking deferred phases on resume - #1086

Merged
fdaviddpt merged 17 commits into
mainfrom
fix/1079
Nov 1, 2026
Merged

fdaviddpt merged 17 commits into
mainfrom
fix/1079

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

What this fixes

Closes #1079: capture-gap-check.sh's fast path (inherited PROJECT_DIR/PIPELINE_DIR/REMEMBER_DIR, extracted by #1069) unconditionally re-sourced log.sh on every SessionStart, redoing lib-memory-dir.sh's whole three-layer config merge (2-6 extra spawns measured on macOS by the issue reporter) and leaking a mktemp'd merged-config file into shared OS tmp (a #362-style leak), because the fast path never sourced bootstrap-dirs.sh.

capture-gap-check.sh now loads the env cache session-start-hook.sh already publishes (scripts/lib-env-cache.sh), via a new REMEMBER_RECOVERY_ENABLED field alongside the pre-existing REMEMBER_SAVE_COOLDOWN/REMEMBER_DELTA_THRESHOLD scalars post-tool-hook.sh's own fast path already replays, falling back to the full merge only on a cache miss/stale cache, with a lazy log() stub for the handful of rare remaining call sites that still need log.sh's real definitions. session-start-hook.sh resolves REMEMBER_RECOVERY_ENABLED via config_into (free -- it already sources log.sh for its own reasons) before publishing the cache.

REMEMBER_RECOVERY_ENABLED is deliberately NOT required for the cache to be considered valid in lib-env-cache.sh's load/publish (unlike the two cooldown scalars, which ARE required), because post-tool-hook.sh and user-prompt-hook.sh also call _remember_env_cache_publish but never resolve .features.recovery, and requiring it would have silently refused every one of their publishes (caught mid-lane: an initial version made it required and broke tests/test_prompt_hook_spawns.py and tests/test_post_tool_hook_spawns.py).

Also fixed within #1079: a stale comment in capture-gap-check.sh claiming the log.sh merge was "needed regardless ... without further work" (now corrected); tests/test_capture_gap_notice.py's dedupe test raced the deferred phase's second write (only waited for the capture-gap-notice file, not the capture-gap-reported marker that follows a few lines later) -- now waits for both; tests/test_locale_ranges_695.py's allowlist entry for session-start-hook.sh's own CURRENT_SESSION_ID sanitizer had to be re-pointed from line 297 to 307 after inserted lines shifted it (a pure line-number drift, not a new finding).

Closes #1060: an Agent SDK host firing SessionStart with source=resume on every resumed turn (not once per session) could stack the backgrounded "deferred phase" (capture-gap-check.sh) indefinitely -- the external reporter measured 42 concurrent processes and host load 275.

session-start-hook.sh now writes a stale-safe per-session PID marker at REMEMBER_DIR/tmp/deferred-<session id>.pid before backgrounding the deferred phase; a new guard function _remember_deferred_already_running (bash builtins only -- [ -f ], $(<file), kill -0 -- no new fork, satisfying the #1056 MSYS fork-cost constraint) skips a second launch when that marker names a still-alive PID, and a dead PID is treated as stale (the launch proceeds and overwrites the marker). The marker is removed by capture-gap-check.sh's own EXIT trap when it still names its own PID, so a session that already resumed-and-relaunched is never affected by the OLDER process's cleanup.

Did NOT implement the features.on_resume config key the issue suggested as one of three alternatives -- judged the PID guard sufficient and simpler.

Self-review round (two independent reviewer spawns against 9d5bd08)

An Explore-based reviewer and oss:auditor each reviewed the committed diff independently. Three findings were fixed directly in a follow-up commit (b565aad): a stale changelog claim about which test file gained coverage was corrected; REMEMBER_DIR/tmp/deferred-<session id>.pid now gets an EXIT-trap cleanup (closing a #362-style leak in the new marker file itself, with a new regression test); and a minor comment-count inaccuracy in the log() stub was corrected.

One finding is being surfaced here rather than fixed, because the right fix is a design decision that trades against the #1056 no-new-fork constraint on this hot path, not a one-line patch: two SessionStarts for the SAME session id landing close enough together can both read "no live deferred phase" before either writes its own PID -- a TOCTOU race in the new guard with no lock. It is documented directly in the guard's own comment block in scripts/session-start-hook.sh, cross-referencing scripts/lib-lock.sh's own _lock_try_steal, which carries the identical limitation and documents it as "an accepted, general limitation rather than a fix." The realistic "fires every resumed turn" pattern #1060 describes has real elapsed time between calls (serial per-turn resumes), unlike this narrow race window, so the guard as shipped is believed sufficient for the reported problem.

Tests

Red/green observed directly (not delegated) for all three fixes via git stash of the relevant files against the pre-fix commit, then restoring: tests/test_capture_gap_check_env_cache_1079.py (new, 4 tests), tests/test_resume_deferred_stacking_1060.py (new, 5 tests after the self-review round), and the tests/test_capture_gap_notice.py dedupe race fix (full 20-test file passed; not a red/green pair since it is a test-harness timing fix).

Final combined targeted run across 21 files: 111+ passed, 40 skipped (Windows-only legs, expected on macOS). Did not run the repository's full pytest suite locally -- CI (13 legs, 3 OSes, 4 interpreters) is the matrix gate.

Release-tree budget verified via .github/scripts/compile_hooks.py --apply: compiled session-start-hook.sh is 101995 bytes, under the 122880-byte cap, and actually smaller than the pre-fix 102047 bytes.

Known risk for the maintainer

Another in-flight lane (PR #1084, branch fix/1046-1047-1052) also edits scripts/session-start-hook.sh (~16 lines) and tests/test_capture_gap_notice.py. This PR's own edits to session-start-hook.sh sit in different regions of the file (~lines 258-266 and ~469-512+), so a rebase should be straightforward, but it has not been tested against #1084 since that PR is not yet merged.

🤖 Generated with Claude Code

[AI-generated]

fdaviddpt and others added 17 commits November 1, 2026 01:28
…and stop stacking deferred phases on resume

capture-gap-check.sh's fast path unconditionally re-sourced log.sh, redoing
lib-memory-dir.sh's whole three-layer config merge (2-6 extra spawns measured
on macOS) and leaving its mktemp'd merged-config file in shared OS tmp (a
#362-style leak) on every single SessionStart. It now loads the env cache
session-start-hook.sh already publishes (a new REMEMBER_RECOVERY_ENABLED
field) instead, falling back to the full merge only on a cache miss, with a
lazy log() for the one remaining rare call site. Also strengthens the
#1069-era fast-path spawn test (it only checked resolve-paths.sh, not the
merge) and fixes a race in the capture-gap dedupe test that only waited for
the notice, not the reported marker.

Separately: an Agent SDK host firing SessionStart with source=resume on
every resumed turn could stack its backgrounded deferred phase indefinitely
(one reporter measured 42 processes, host load 275). A second start for a
session whose deferred phase is still alive now skips rather than relaunches,
via a stale-safe per-session PID marker; a dead marker is treated as stale
and replaced.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… marker, document two known tradeoffs, fix prose

- Adjacent finding: the per-session PID marker (REMEMBER_DIR/tmp/deferred-<id>.pid) the #1060 guard relies on was never removed on a normal finish, leaking one small file per session id forever -- the same leak class #1079 fixes elsewhere in this change. capture-gap-check.sh now removes its own marker under an EXIT trap, only when the file still names its own PID (so a session that already resumed and relaunched is never affected by the older process's cleanup).
- Documents two tradeoffs a reviewer flagged as real but not worth a code change here: the deferred-phase guard is check-then-act, not atomic (two SessionStarts landing within the same narrow window for the SAME session id can both launch), and its kill -0 staleness check cannot tell a dead PID from one the OS has since reassigned -- scripts/lib-lock.sh already accepts the identical PID-recycling limitation for its own lock primitive, and the new guard's comment now cross-references it instead of leaving the tradeoff undocumented.
- Corrects two inaccurate comments: the lazy log() stub's comment claimed exactly one remaining call site when there are several, and the changelog fragment implied tests/test_session_start_spawn_reduction_679.py was edited to cover the merge-spawn gap, when that coverage is entirely in the new tests/test_capture_gap_check_env_cache_1079.py and the 679 file was not touched.
- Fixes two of the new #1060 tests that became vacuous once the cleanup above landed: both polled for the PID file to persist, which it now deliberately does not do on completion. Both now poll for the deferred phase's own durable session-slug record instead.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ng, avoid a read-budget regression, bound PID-marker staleness

Five findings from a code review of PR #1086, plus two CI failures reported
after the review (Windows env-cache miss investigated but not resolved;
Linux read-budget regression fixed):

1. HIGH: capture-gap-check.sh's `trap _remember_cleanup_deferred_pid_file
   EXIT` replaced whatever EXIT trap log.sh's config merge had already
   installed to remove its own merged-config tmpfile, leaking that tmpfile
   on every cache-miss/slow-path exit. Now appends to any existing trap,
   the same idiom bootstrap-dirs.sh and lib-memory-dir.sh already use --
   including the quote-unescape step bootstrap-dirs.sh's own comment
   explains and my first attempt omitted, which TDD caught as a shell
   syntax error in the exit trap itself.

2. LOW: tests/spawn_counting.py's COUNTED list never recorded mktemp, so
   no test built on it could ever see a leaked merge tmpfile. Added, and a
   new test (test_cache_miss_path_leaves_no_new_merged_config_tmpfile_in_shared_tmp)
   covers the slow/cache-miss path the existing warm-path test cannot reach.

3. LOW: session-start-hook.sh and capture-gap-check.sh both read a PID
   marker with `$(<file)`, which forks a subshell for the substitution
   regardless of what is inside it (measured: 2000 calls 0.63s vs 0.045s
   with `read -r ... < file` on bash 3.2) despite a comment claiming no
   fork. Switched both sites to `read -r`, and fixed the comment.

4. LOW: the deferred-phase PID marker had no age bound, so a stale marker
   whose PID got reused (aggressive on Windows) would make `kill -0`
   succeed forever and silently skip recovery for that session indefinitely.
   Bounded by REMEMBER_DEFERRED_PID_MAX_AGE (default 900s), the same
   two-probe `stat` shape lib-lock.sh's own `_lock_dir_age` already uses.
   New test pairs a live-but-unrelated PID with an aged marker.

5. LOW: README.md's #1060 bullet was inserted between a parent bullet and
   its indented sub-bullet, breaking that nesting. Reordered.

CI (scheduler-reported, after the review): the Linux 3.9 leg tripped
test_hot_path_cost_pin_330.py's SIDECAR_READ_BUILTIN_BUDGET by one read,
because REMEMBER_RECOVERY_ENABLED was published as its own line in the
env-cache file -- a line every reader pays a `read` builtin for, including
post-tool-hook.sh and user-prompt-hook.sh, neither of which need the field.
Piggy-backed its value onto the existing REMEMBER_PROMPT_STAMP line instead
(colon-delimited; that field's own values never contain a colon), so no new
line exists to read.

The Windows leg (env cache publishing no file at all after a warm run, on
both the no-config and with-config parametrizations) was investigated but
not resolved: I could not reproduce it without a Windows host, and ruled
out several hypotheses (mixed path separators defeating the
is-standard-merge glob check; REMEMBER_SAVE_COOLDOWN/REMEMBER_DELTA_THRESHOLD
being unset) without finding the actual cause. Left for a maintainer with
Windows CI access to chase with xtrace.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ing test failures self-diagnosing

On windows-latest, tests/test_capture_gap_check_env_cache_1079.py (the
precondition at ~L198: no remember-env-*/remember-config-cache-v2-* cache
file is published in systmp after a warm SessionStart run) and
tests/test_resume_deferred_stacking_1060.py::test_a_resume_for_a_session_whose_deferred_phase_is_still_alive_does_not_relaunch_it
fail on CI, where no Windows host is available locally to reproduce. Add
diagnostics -- TMPDIR/TMP/TEMP/SYS_TMPDIR as the hook saw them, directory
listings of systmp and .remember/tmp, the publish-side and load-side cache
key/path lib-env-cache.sh computes, a bash -x re-run trimmed to the
env_cache or deferred/kill lines, and the PID file contents vs the Popen
pid for the resume test -- to each failing assertion, so the next CI round
names the mechanism instead of only the symptom. Diagnostics live in the
test files only, never in the shipped scripts.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Resolved tests/test_locale_ranges_695.py: session-start-hook.sh line 307 from this branch,
write-handoff.sh line 97 from main (#1081); both match the merged files and the test passes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…Windows-only test failures

Linux lint/scanner legs:
- session-start-hook.sh:530 now reads `10#$_now - 10#$_mtime` (both sides of the
  digits-only `case`-guarded subtraction need the radix prefix, not just one).
- lib-env-cache.sh's one remaining `case "$_stamp" in *:*) ... ;; *) ... ;; esac`
  (the directory's own scanner mis-parses `case`) is rewritten as the `[ ]`
  parameter-expansion idiom the rest of this file already uses.

Windows-only pytest legs (reasoned fixes, built from the CI diagnostics in the two
test files -- no Windows host was available to single-step either one):
- test_resume_deferred_stacking_1060.py: `_remember_deferred_already_running`'s
  `kill -0` liveness check is suspected to false-negative on a PID the test
  harness spawned directly (not forked from the hook's own MSYS/Git-Bash
  process tree), which would explain the observed symptom -- a still-alive
  deferred phase's PID marker vanishing entirely within one second, consistent
  with the guard wrongly treating it as dead, relaunching, and then cleaning up
  the new child's own marker on its own quick exit. Added `/proc/$pid`
  existence as an extra "alive" signal tried before `kill -0`, which never
  regresses a host with no `/proc` (macOS) since it falls through unchanged.
- test_capture_gap_check_env_cache_1079.py: several variants showed
  `_remember_env_cache_publish` writing nothing at all even though every
  precondition held and a sibling mktemp in the same process (log.sh's own
  #668 flatten cache) succeeded moments earlier -- consistent with a
  transient Windows filesystem hiccup. Added a short, bounded retry around
  the cache file's `mktemp`, which costs nothing on the ordinary first-try-
  succeeds path.

Local evidence: tests/test_arith_base_lint_332.py and
tests/test_scanner_shapes_source_898.py / test_strip_shell_comments_900.py now
pass against the committed tree (both read the built tree from HEAD, not the
working tree). The two Windows-only fixes are reasoned from CI's own
diagnostics and could not be reproduced or single-stepped locally (no Windows
host available); the existing tests in both files are the red/green pair, to
be confirmed by the next CI run.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…on non-UTF-8 bytes

macos-latest CI (all four Python legs, pre-existing on commit 123395c -- not
introduced by the previous commit here) consistently crashed with
`UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbf in position 5397`
inside `_env_cache_diag`'s `bash -x` re-run of session-start-hook.sh,
`subprocess.run(..., text=True)`'s strict decode choking on a byte the host's
own locale/filesystem put into the trace. Since the diagnostic text is built
inside the assert's own message argument, Python only evaluates it once the
underlying assertion has already failed -- so this crash was masking the
actual (and still unseen) assertion failure in
test_cache_miss_path_leaves_no_new_merged_config_tmpfile_in_shared_tmp, on
every macOS leg, every run.

Fixed by switching both `bash -x` diagnostic captures (the env-cache test's
own, and the resume-stacking test's sibling `_resume_diag`) to bytes mode
plus `tests/_bash_runner.decode_bash_output`, the same tolerant decode this
repo's own bash-subprocess tests already use for exactly this reason
(`test_is_uint_helper_898.py`, `test_git_reconcile_drive_letter_934.py`,
`test_case_rewrite_equivalence_898.py`). Diagnostics-only code must never
itself be why a test fails.

This does not yet say what the underlying assertion's real message is --
only that it can no longer be hidden behind a crash. The next CI run will
show it.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ed-config tmpfile on the cache-miss path

Root-caused with the now-unmasked assertion from the previous commit:
capture-gap-check.sh's SLOW/cache-miss path left a NEW
`remember-config-XXXXXX` tmpfile behind in shared tmp on every exit --
log.sh's own merge-cleanup `rm -f '...'` never actually ran.

Reproduced locally (no CI round-trip needed): the parameter-expansion
collapse (`${var//PATTERN/REPLACEMENT}`) that undoes `trap -p`'s own
escaping of an embedded single quote, so this file's EXIT-trap append can
re-embed the existing (log.sh-installed) trap body without producing
unbalanced quoting, gives a DIFFERENT result on Apple's shipped /bin/bash
(3.2.57, what macos-latest CI's `shutil.which("bash")` resolves to) than
on bash 4+: identical pattern, identical input, bash 3.2 leaves a stray
backslash in the output where bash 4+ collapses to a bare quote. That
corrupted the reinstalled trap just enough that its `rm -f` fragment
failed silently at exit instead of removing the file, confirmed directly
with /bin/bash side by side with homebrew bash on the same macOS box.

Fixed by replacing the pattern-replacement collapse with a prefix/suffix
removal loop -- bash builtins both versions agree on, verified to produce
the identical (correct) result on both bash 3.2 and bash 5 for the same
input. This trap-install code only runs once per cache-miss invocation of
the already-expensive slow merge path, so one more loop iteration costs
nothing on the hot (cache-hit) path this whole fix exists to protect.

Red/green observed directly against the real bash 3.2 binary (not just
the Homebrew one normally first on PATH locally), by forcing PATH so
shutil.which("bash") resolves /bin/bash:
  red:   1 failed  (test_cache_miss_path_leaves_no_new_merged_config_tmpfile_in_shared_tmp,
                    scripts/capture-gap-check.sh stashed back to its pre-fix form)
  green: 1 passed  (same test, same forced PATH, fix restored)

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

The /proc-based PID liveness check (scripts/session-start-hook.sh) and the
mktemp retry (scripts/lib-env-cache.sh) were both reasoned guesses at the
#1060/#1079 Windows-only test failures, written up front as "reasoned, not
confirmed." The next CI round, with both in place, showed the IDENTICAL
failures on windows-latest -- same assertions, same diagnostic shape -- so
neither guess was the fix. Rewriting both comments to say so plainly,
rather than leave a causal story in shipped code that CI has since
contradicted. Both checks are kept (harmless, zero-cost on the paths that
never hit them) but are no longer claimed as fixes for anything.

The two Windows-only tests remain red; their real mechanism is still
unknown without a real Windows host to single-step them.

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

#1079: capture-gap-check.sh's fast path loaded REMEMBER_RECOVERY_ENABLED
from the env-cache FILE session-start-hook.sh publishes, and windows-latest
CI showed that publish/load round trip through shared tmp is unreliable --
the file was sometimes not yet visible to the child, falling the fast path
through to the full config merge on every run. Real fix: capture-gap-check.sh
is only ever reached as a forked/backgrounded child of session-start-hook.sh's
own process, which already exports REMEMBER_RECOVERY_ENABLED before forking --
check for that inherited value first and skip the cache file (and its
publish-vs-load race) entirely on the path that always has it. The cache file
stays as the fallback for a direct/standalone invocation (every test fixture
here, and post-tool-hook.sh/user-prompt-hook.sh's own fast paths, which are
launched by the host directly and have nothing to inherit).
tests/test_capture_gap_check_env_cache_1079.py now models the real contract
by setting REMEMBER_RECOVERY_ENABLED directly in the child's environment
instead of relying on the published file.

#1060: test_a_resume_for_a_session_whose_deferred_phase_is_still_alive_does_not_relaunch_it
failed on windows-latest because its stand-in "live deferred phase" was
started with a plain subprocess.Popen(["sleep", "60"]), handing the guard a
native Windows PID -- a real deferred phase is always backgrounded with `&`
from inside an MSYS/Git-Bash process, so its $! is an MSYS-space pid, which
is what the guard's own `kill -0` (run inside the same MSYS bash) actually
resolves. Fixed by starting the stand-in process through the resolved bash's
own `& echo $!` instead. This also makes a disproven, speculative /proc/$pid
liveness probe in session-start-hook.sh's own _remember_pid_is_alive provably
unnecessary dead code (its own comment already said CI had disproven it as a
fix) -- removed; plain `kill -0` was correct all along.

Updated changelog.d/1079.fixed.md and changelog.d/1060.fixed.md to describe
the actual root causes and fixes rather than the earlier, disproven theories.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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]>
The env_cache-filtered view of the warm-path bash -x re-run was empty
(0 of 31 lines) on windows-latest, which tells us the hook took an
early silent exit well before line 387's unconditional
_remember_env_cache_publish call, but not which guard fired. Print the
whole trace when the filtered view is empty and the trace itself is
short, so the actual early-exit line is visible in the next CI run
instead of an empty list.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…was the test's own invocation shape, not a product bug

Root cause, confirmed with the widened bash -x trace from the
previous commit (windows-latest job #124755597099): the warm run's
`bash -x` re-run carried only 42 total lines and 0 naming env_cache --
the hook exited silently at `source "$_HOOK_DIR/resolve-paths.sh" ||
exit 0` (scripts/session-start-hook.sh:335), because `_HOOK_DIR` had
resolved to the repo root instead of `.../scripts`:

    + source D:/a/claude-remember/claude-remember/resolve-paths.sh
    D:\a\claude-remember\claude-remember\scripts\session-start-hook.sh:
      line 335: D:/a/claude-remember/claude-remember/resolve-paths.sh:
      No such file or directory
    + exit 0

session-start-hook.sh derives its own directory with
`_HOOK_DIR="${BASH_SOURCE[0]%/*}"`, falling back to `$(pwd)` only when
that expansion finds no `/` to split on (a bare filename, by its own
comment). The real hook invocation (hooks/hooks.json's own command
string, `bash "${CLAUDE_PLUGIN_ROOT}/scripts/session-start-hook.sh"`)
guarantees at least one literal `/` around `/scripts/` regardless of
what CLAUDE_PLUGIN_ROOT itself looks like, so `_HOOK_DIR` always
resolves correctly for a real Windows user. The test instead invoked
bash with `str(SESSION_START)` -- a pathlib Path stringified on
Windows, which is a PURE-backslash path with ZERO forward slashes
anywhere -- a shape the real hook command can never produce. That
pure-backslash BASH_SOURCE[0] hits the "no slash" fallback, `pwd`
answers the repo root (where pytest's subprocess is launched from,
not .../scripts), and the hook exits silently one directory too
shallow, long before the env cache publish this test is probing for.

Confirmed directly, independent of pytest and of Windows itself (pure
bash string-expansion, same on any platform): `_HOOK_DIR="${S%/*}"` on
`"D:\a\...\scripts\session-start-hook.sh"` (no `/` at all) falls back
to pwd; on `"D:\a\...\claude-remember/scripts/session-start-hook.sh"`
(one literal `/`, matching the hooks.json shape) it resolves to
`.../scripts` correctly.

This repo's own convention already encodes the fix:
tests/_bash_runner.py's run_bash_file() passes `path.as_posix()`, not
`str(path)`, for exactly this reason. This test's two subprocess.run
calls that invoke SESSION_START directly were the one place in this
file that still used str() -- switched both to .as_posix(), matching
the real hook invocation's forward-slash shape and the repo's own
established pattern. No product code changed: the early exit cannot
fire for a real Windows user, so nothing in scripts/session-start-hook.sh
needed changing.

536 targeted tests still pass locally (macOS, bash 5.2 and 3.2).
This fix cannot be verified red/green locally (the bug is Windows-only
and macOS str(Path) already yields forward slashes) -- CI is the
verification.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…d of asserting once

tests/test_resume_deferred_stacking_1060.py's own cleanup test
(test_the_deferred_phases_own_pid_file_is_removed_when_it_finishes)
asserted `not pid_file.exists()` immediately after polling for
session-slug to appear. The PID marker is removed by an EXIT trap in
scripts/capture-gap-check.sh, which fires AFTER the script's main
body -- including the session-slug write this test polls for -- so
there is a real window between "session-slug exists" (main body) and
"the EXIT trap has actually run and removed the PID file" (process
teardown). Observed failing on windows-latest CI (job #124762032746,
pytest 3.11): slug_record existed but pid_file still did, well within
a process that does finish shortly after.

Poll with the same bounded wait the slug_record check above already
uses, rather than asserting once right after a different file's
precondition. Not a product bug: scripts/capture-gap-check.sh's own
cleanup is unconditional and untouched here.

5/5 tests in this file still pass locally (macOS).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1. Add a real end-to-end test (test_resume_deferred_stacking_1060.py) that
   drives session-start-hook.sh's own marker write with a slow, real
   backgrounded deferred phase instead of a test-seeded PID file -- proven
   red by deleting that write, green with it restored.

2. capture-gap-check.sh's recovery force-save no longer runs detached
   (`& disown`): this file is already the backgrounded deferred phase, so
   waiting on the save inline keeps session-start-hook.sh's per-session PID
   marker alive for its whole duration, closing the race that let rapid
   resumes stack forced saves for the same unsaved previous session.
   SessionStart's own foreground latency is unaffected. New test:
   test_recovery_save_stacking_1086.py.

3. Fix a stale comment (the trap-install block does not run "once per
   cache miss", it runs on every invocation with a session id) and skip the
   one-fork `$(trap -p EXIT)` preserve dance when log.sh's merge never ran
   in this process, since there is then no prior trap to preserve.

4. lib-env-cache.sh never carried REMEMBER_STORE_ROOT, so
   _remember_write_slug_index silently no-opped for external {slug} stores
   on a direct/standalone capture-gap-check.sh invocation. Piggy-backed as
   a `<len>:` prefix on the existing REMEMBER_DIR cache line (no new line,
   per the #330/#395 hot-path read-budget rule), since REMEMBER_STORE_ROOT
   is always a strict prefix of REMEMBER_DIR by construction. New test:
   test_capture_gap_check_store_root_cache_1086.py.

Targeted suite green (546 passed) including a full re-run with PATH forced
to /bin/bash 3.2.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…s-skip-triage.md\n\ntest_recovery_save_stacking_1086.py was missing from the table test_windows_skip_triage_497.py enforces, failing all 15 non-Windows CI legs on the pull request this test shipped in. Same reason string and verdict shape as its sibling test_recovery_transcript_leak_407.py, whose fixture helpers it reuses directly.\n\nCo-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

Co-Authored-By: Max <noreply>
…Windows runner overhead

Co-Authored-By: Max <noreply>
@fdaviddpt
fdaviddpt merged commit e0379ca into main Nov 1, 2026
19 checks passed
@fdaviddpt
fdaviddpt deleted the fix/1079 branch November 1, 2026 07:38
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]>
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