Skip to content

Fix #1067: shrink session-start-hook.sh's release-tree budget - #1069

Merged
fdaviddpt merged 3 commits into
mainfrom
fix-1067-hook-script-budget
Oct 31, 2026
Merged

fdaviddpt merged 3 commits into
mainfrom
fix-1067-hook-script-budget

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

Closes #1067

Problem

The built scripts/session-start-hook.sh was 122,830 bytes against the 122,880-byte HOOK_SCRIPT_MAX_BYTES cap -- 50 bytes of headroom -- blocking #1064 (404 bytes over, blocked on this one) and #1056 (fewer forks under concurrent Windows session starts, which will also need room in the same file).

Fix

Extracts three rarely-taken groups of logic out of scripts/session-start-hook.sh into a new file, scripts/capture-gap-check.sh, invoked as a separate process (synchronously when REMEMBER_DEFER=0, backgrounded with &disown otherwise) rather than sourced -- mirroring the existing precedent at scripts/consolidation-launch.sh (#1006):

  • previous-session recovery (_find_previous_transcript, session_was_saved)
  • slug/case-divergence bookkeeping (_remember_write_slug_record, _remember_write_slug_index, _remember_write_case_divergence)
  • capture-gap detection (capture_was_seen, _remember_prune_keep_newest, and the whole former body of _remember_deferred_phase)

Compiled session-start-hook.sh now has ~21.25 KiB of headroom (101,129 bytes against the 122,880-byte cap), restoring the stated 4 KiB floor several times over so both #1064 and #1056 should fit.

Out of scope (left for those issues)

Testing

  • RED: python3 -m pytest tests/test_strip_shell_comments_900.py::test_this_repository_session_start_hook_has_4kib_headroom -q --no-cov failed against pre-fix HEAD ("only 50 bytes under... below the 4 KiB headroom floor").
  • GREEN: same test plus the release-tree check test, 2 passed, after the fix.
  • Targeted run across all files touched or coupled to the moved code: 414 passed.
  • Broader behavioral SessionStart set: 293 passed, 9 skipped (platform-gated).
  • Did not run the full pytest suite locally -- CI (ubuntu/macos/windows-latest x Python 3.9-3.12) is the full-matrix gate.

Review

Two independent reviewers (Explore, oss:auditor) returned NO FINDINGS. Changelog fragment and jit-context doc headroom figures verified against a live compile_hooks.py --repo . run (21,751 bytes).

🤖 Generated with Claude Code

[AI-generated]

fdaviddpt and others added 3 commits October 31, 2026 21:57
Move previous-session recovery, slug/case-divergence bookkeeping and
capture-gap detection out of session-start-hook.sh into a new
scripts/capture-gap-check.sh, invoked (not sourced) the same way
scripts/consolidation-launch.sh already was for #1006. Compiled
session-start-hook.sh had only 50 bytes of headroom under its 120 KiB
release-tree budget, blocking #1064 and #1056; it now has over 21 KiB.

Behaviour is unchanged: the moved code still runs inline
(REMEMBER_DEFER=0) or backgrounded, exactly as session-start-hook.sh
ran it before. Updates the several tests that extracted the moved
functions' text directly out of session-start-hook.sh to read from the
new file instead, adds a test pinning the 4 KiB headroom floor, and
updates the hook-script-size-budget jit-context doc's stale figure.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…n, add parity test

Three findings from PR #1069's review:

1. tests/test_case_rewrite_equivalence_898.py pinned a line that moved
   into scripts/capture-gap-check.sh along with capture_was_seen but
   still named scripts/session-start-hook.sh as its site -- would have
   failed on every OS once that leg ran, not just Windows.

2. capture-gap-check.sh re-ran resolve-paths.sh -> detect-tools.sh ->
   bootstrap-dirs.sh in full inside its own freshly forked process,
   redoing work its own parent (session-start-hook.sh) had already done
   and exported moments earlier -- landing directly on #1056 (fewer forks
   under concurrent Windows session starts). Fixed with a fast path that
   trusts PROJECT_DIR/PIPELINE_DIR/REMEMBER_DIR when already present and
   exported, falling back to the full chain otherwise (every direct/
   standalone test invocation). The fast path also needed its own copies
   of resolve-paths.sh's _remember_forward_slash[_into] -- functions are
   never inherited across exec() the way exported variables are, and the
   first attempt at this fix omitted them, which
   tests/test_case_divergence_298.py caught (every external store
   misreported "not-applicable"). This is a bounded fix, not #1056's own
   scope: log.sh's own smaller config_into/log merge still runs inside
   capture-gap-check.sh regardless, needed for log()/config_into().

3. tests/test_entrypoint_sniff_bookkeeping_message_803.py's own
   _function_body search tries session-start-hook.sh before
   capture-gap-check.sh, so every existing test exercised only the
   SESSION-START-HOOK.SH copy of the duplicated _stdin_json_string_into,
   never the one that actually runs at SessionStart time. Added a direct
   parity test asserting the two copies stay byte-identical.

Also fixes two timing-sensitive tests the review flagged as newly racy:
the deferred phase is now a genuinely separate process (capture-gap-
check.sh), slower to start than the pre-#1067 in-process function call,
so a "must appear" assertion reading an on-disk effect the instant the
parent hook returns can race the still-running backgrounded child.
Polls or runs inline (REMEMBER_DEFER=0) instead, matching this suite's
own established convention for the difference between a "must appear"
and a "must not appear" check.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
PR #1069's "hook tests (compiled)" leg (ubuntu + windows) was red on the new
_stdin_json_string_into parity test added in 23ed821. That leg runs
session-start-hook.sh through compile_hooks.py's compile step first, which
strips its whole-line comments (one of the four HOOK_SCRIPT_NAMES scripts
the release build inlines); capture-gap-check.sh is never compiled and
keeps its comments verbatim on every leg. A straight string comparison of
the two copies therefore diverges on a comment-only line in compiled mode,
while every plain pytest leg (which reads both files as source) stays
green.

Fixed the test, not the code: strip whole-line comments from both copies
before comparing, delegating to compile_hooks.py's own
strip_whole_line_comments rather than a second hand-written filter that
could drift from what the build actually does. Added a positive control
(test_stdin_json_string_into_copies_stripping_still_catches_real_divergence)
proving the stripping does not swallow a real functional divergence on a
non-comment line.

Reproduced directly: ran compile_hooks.py --apply against a scratch copy
of the tree and confirmed the raw comparison goes false (red, matching
CI) while the comment-stripped comparison stays true (green).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@fdaviddpt
fdaviddpt merged commit 4dd52ff into main Oct 31, 2026
19 checks passed
@fdaviddpt
fdaviddpt deleted the fix-1067-hook-script-budget branch October 31, 2026 22:54
fdaviddpt added a commit that referenced this pull request Nov 1, 2026
…and stop stacking deferred phases on resume (#1086)

* Fix #1079, #1060: stop re-bootstrapping config on every SessionStart 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]>

* Self-review follow-up on #1079/#1060: clean up the deferred-phase PID 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]>

* Fix #1086 review (#1079, #1060): append EXIT traps instead of replacing, 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]>

* Step 1 (#1079, #1060): make the Windows CI env-cache and resume-stacking 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]>

* Fix #1086 CI: digits-only case lint, scanner case-statement, and two 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]>

* Fix #1086 CI: diagnostics-only bash -x capture must not itself crash 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]>

* Fix #1086 CI: a bash-3.2-only quote-collapse bug leaked log.sh's merged-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]>

* Fix #1086 CI docs: correct two speculative comments CI has since disproven

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]>

* Fix #1079, #1060 CI: env handoff beats the cache file; test the real 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]>

* Fix #1086 CI diagnostics: widen the env_cache trace to the full 31 lines

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]>

* Fix #1086 CI: windows-latest env-cache warm-run precondition failure 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]>

* Fix #1086 CI: poll for the deferred-phase PID marker's removal instead 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]>

* Fix #1086 review round: confirm and harden 4 findings on #1079/#1060

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]>

* Fix #1086 CI: triage the new win32 blanket-skip module in docs/windows-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>

* Fix #1086 CI: widen the new end-to-end deferred-phase test delay for Windows runner overhead

Co-Authored-By: Max <noreply>

---------

Co-authored-by: Claude Sonnet 5 <[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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

session-start-hook.sh is at its 120 KiB release-tree budget: shrink it before more SessionStart fixes can land

1 participant