Repository navigation
Conversation
…t O(session length) `wc -l < "$TRANSCRIPT"` used to read the whole transcript on every tool call, so the hook got slower every turn of a long session. This stores a (byte offset, line count) sidecar keyed by the transcript's own basename and reads only the bytes appended since the last call via `tail -c +OFFSET`, whose own leading byte doubles as a validator against a shrunk or rewritten transcript -- a shorter read, or a first byte that is not the expected newline, falls back to a full recount. A half-written last line (no trailing newline yet) is never counted and never advances the offset. The cooldown check that decides whether a save can fire at all now runs BEFORE this scan rather than after it, so a tool call inside the post-save cooldown window skips the scan entirely -- a fork avoided here on an affected Windows 11 25H2 build (#1011) is a kernel Token object that never leaks, not merely latency saved. Which saves fire, and at what threshold, is unchanged. Measured on macOS bash 3.2.57, the shared fast-path fixture (tests/test_post_tool_fast_path_350.py) with cooldown active: before 5 spawns (head, ls, wc, mv, date), after 4 (head, ls, mv, date) -- wc is gone entirely. Without cooldown, below the save threshold: before 4 (head, ls, wc, mv), after 4 (head, ls, tail, mv) -- same fork count, now O(delta) instead of O(session length). tests/spawn_counting.py's shared COUNTED list gains `tail`, which it did not carry before this change -- a tail-based fix would otherwise have passed every existing fork-count assertion while the harness itself stayed blind to the fork it claims to measure. tests/test_post_tool_incremental_scan_913.py pins the new mechanism and its named edge cases: incremental reads only the appended bytes, the save decision is unchanged across several incremental calls, a half-written last line is not counted until complete, a shrunk transcript falls back to a full recount, a rewritten transcript (same offset, different content) falls back too, and cooldown skips the scan entirely. tests/test_locale_ranges_695.py's ALLOWLIST is re-pinned to the shifted SESSION_ID bracket-range checks and gains one entry for the new sidecar key's own sanitiser (same ASCII-only charset, same reason). Co-Authored-By: Claude Sonnet 5 <[email protected]>
A self-review spawn found that a write interrupted between OFFSET and LINES (OOM, disk full, a kill mid-printf) can leave a syntactically valid OFFSET -- a real prior scan position, so the newline-validation in _pt_scan_lines passes -- paired with a missing/empty LINES field. The per-field validation defaulted only the missing field to 0, silently pairing a real byte offset with a wrong line count, undercounting every line that existed before it. Both fields are now invalidated together on any parse failure, forcing the same full recount an absent sidecar already gets. tests/test_post_tool_incremental_scan_913.py gains a regression test that reproduces the exact partial-write shape (a real OFFSET, a truncated LINES field) and asserts the sidecar recovers the true count rather than reporting zero. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…allback (non-blocking) Self-review's oss:auditor spawn found that `_pt_scan_lines`'s fallback-to-full-recount branch cannot distinguish a genuine shrink/rewrite from a transient `tail` read failure, because the command substitution's exit status is masked by the trailing `printf` needed to preserve a trailing newline through `$()`. Ranked non-blocking and self-healing (next call recounts fully); left for the curator. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…allowlist, document the Windows skip Rebasing fix/913 onto main (after #1010/#1012's Windows detach watchdog and rc=137 double-save guard) surfaced a real regression on CI that neither the targeted local run nor lane_setup's guard sweep could see: tests/test_hot_path_cost_pin_330.py's own #353/#395 sidecar-trust pins failed on every leg, because the #913 cooldown-before-scan reorder had nested the WHOLE #353 "last saved position" lookup (and the DELTA it feeds) inside the same `if IN_COOLDOWN=false` block that gates the new incremental scan -- not just the scan itself. Since test_hot_path_cost_pin_330.py's own fixture always leaves a recent save-cooldown marker set, IN_COOLDOWN was always true in that fixture, so the #353 branch (and its own regression tests) never ran at all under it. Fixed by scoping the `if [ "$IN_COOLDOWN" = false ]` wrapper to just the scan (through the SCAN_SIDECAR write) again, restoring the #353 lookup and the final DELTA assignment to run unconditionally as they did before #913 ever touched this file. The sidecar's own upper-bound sanity check now skips itself (rather than comparing against a never-computed CURRENT_LINES of 0) when the scan was skipped, via one added `[ "$IN_COOLDOWN" = false ] &&`. #913's own win (incremental, not whole-transcript, line counting) and the cooldown-skips-the-scan behaviour (#1011's own motivation) are both still intact; only the accidental, broader skip is undone. Re-pinned tests/test_locale_ranges_695.py's ALLOWLIST line numbers for the two shifted ASCII-only basename-sanitiser ranges (860->868, 955->970). Documented the new tests/test_post_tool_incremental_scan_913.py's win32 blanket-skip in docs/windows-skip-triage.md (not-convertible: same bash-hook-subprocess shape as test_post_tool_fast_path_350.py, plus a spawn-counting assertion measured only against macOS system bash) -- CI's own tests/test_windows_skip_triage_497.py was failing on every leg for its absence. Re-measured tests/test_post_tool_fast_path_350.py's own FAST_PATH_SPAWN_MEASURED: already stale at 6 before this PR (an earlier, separate #913 PR had removed the slug/cygpath fork this constant's comment still described, without updating the number); corrected to the measured 5. Closes #913. Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
Review note (non-blocking): |
…ames its test A Windows pytest leg was cancelled twice by the job-level timeout-minutes: 30 (PR #1013 job 114288023016, PR #1020 job 114358206393), and a job cancelled by its own timeout writes NO log at all, so we could not tell which test hung or whether it was the runner or our code (#1002's real wscript.exe tests have already hung 40+ minutes once). - pyproject.toml: faulthandler_timeout = 900 under [tool.pytest.ini_options] (built into pytest, no new dependency). Dumps every thread's traceback, naming the hung test, once any single test runs longer than 900s. Sized with ~30x margin over the slowest single test observed on a recent green windows-latest run (30.14s, run 38091996750 job 114330142530), and below the new step timeout so the dump lands in a kept log. - .github/workflows/tests.yml: a step-level timeout-minutes: 25 on both "Run tests" and "Run the full suite against the compiled hooks" -- below the job's 30-minute one, so a hang fails the STEP and the job still completes with its log (including the faulthandler dump) rather than being cancelled with no log at all. - A trailing, Windows-only, if: always() step on both jobs that lists any surviving wscript.exe/bash.exe/conhost.exe/powershell.exe processes with PID/PPID/command line, so a leaked child is visible. Not hypothetical: the same green run above still had to force-terminate a leaked bash and a leaked wscript process at job teardown. PROVEN on PR #1022 (same branch, run 38103924282, before this commit): a temporary faulthandler_timeout=5 plus a throwaway test sleeping 8s produced a log on BOTH a Windows leg (pytest (windows-latest, 3.10), job 114365322297, lines 703-708: "Timeout (0:00:05)!" naming tests/test_proof_1014_faulthandler.py::test_proof_sleep_past_faulthandler_timeout with its full traceback) and a Linux leg (pytest (ubuntu-latest, 3.10), job 114365322191, lines 1072-1079: same dump, same test). The throwaway test and the lowered value are removed/restored in this commit; the real values above are what ships. No user-visible behavior changes -- CI-only -- so no changelog fragment; PR labeled no-changelog instead. faulthandler_timeout is independent of --cov (coverage collection is unaffected) and of pytest-xdist (confirmed via repo-wide grep: this repo has no xdist configured, and the setting is per-worker/per-process either way if that changes). Co-Authored-By: Max <noreply>
…ames its test A Windows pytest leg was cancelled twice by the job-level timeout-minutes: 30 (PR #1013 job 114288023016, PR #1020 job 114358206393), and a job cancelled by its own timeout writes NO log at all, so we could not tell which test hung or whether it was the runner or our code (#1002's real wscript.exe tests have already hung 40+ minutes once). - pyproject.toml: faulthandler_timeout = 900 under [tool.pytest.ini_options] (built into pytest, no new dependency). Dumps every thread's traceback, naming the hung test, once any single test runs longer than 900s. Sized with ~30x margin over the slowest single test observed on a recent green windows-latest run (30.14s, run 38091996750 job 114330142530), and below the new step timeout so the dump lands in a kept log. - .github/workflows/tests.yml: a step-level timeout-minutes: 25 on both "Run tests" and "Run the full suite against the compiled hooks" -- below the job's 30-minute one, so a hang fails the STEP and the job still completes with its log (including the faulthandler dump) rather than being cancelled with no log at all. - A trailing, Windows-only, if: always() step on both jobs that lists any surviving wscript.exe/bash.exe/conhost.exe/powershell.exe processes with PID/PPID/command line, so a leaked child is visible. Not hypothetical: the same green run above still had to force-terminate a leaked bash and a leaked wscript process at job teardown. PROVEN on PR #1022 (same branch, run 38103924282, before this commit): a temporary faulthandler_timeout=5 plus a throwaway test sleeping 8s produced a log on BOTH a Windows leg (pytest (windows-latest, 3.10), job 114365322297, lines 703-708: "Timeout (0:00:05)!" naming tests/test_proof_1014_faulthandler.py::test_proof_sleep_past_faulthandler_timeout with its full traceback) and a Linux leg (pytest (ubuntu-latest, 3.10), job 114365322191, lines 1072-1079: same dump, same test). The throwaway test and the lowered value are removed/restored in this commit; the real values above are what ships. No user-visible behavior changes -- CI-only -- so no changelog fragment; PR labeled no-changelog instead. faulthandler_timeout is independent of --cov (coverage collection is unaffected) and of pytest-xdist (confirmed via repo-wide grep: this repo has no xdist configured, and the setting is per-worker/per-process either way if that changes). Co-Authored-By: Max <noreply>
…ames its test A Windows pytest leg was cancelled twice by the job-level timeout-minutes: 30 (PR #1013 job 114288023016, PR #1020 job 114358206393), and a job cancelled by its own timeout writes NO log at all, so we could not tell which test hung or whether it was the runner or our code (#1002's real wscript.exe tests have already hung 40+ minutes once). - pyproject.toml: faulthandler_timeout = 900 under [tool.pytest.ini_options] (built into pytest, no new dependency). Dumps every thread's traceback, naming the hung test, once any single test runs longer than 900s. Sized with ~30x margin over the slowest single test observed on a recent green windows-latest run (30.14s, run 38091996750 job 114330142530), and below the new step timeout so the dump lands in a kept log. - .github/workflows/tests.yml: a step-level timeout-minutes: 25 on both "Run tests" and "Run the full suite against the compiled hooks" -- below the job's 30-minute one, so a hang fails the STEP and the job still completes with its log (including the faulthandler dump) rather than being cancelled with no log at all. - A trailing, Windows-only, if: always() step on both jobs that lists any surviving wscript.exe/bash.exe/conhost.exe/powershell.exe processes with PID/PPID/command line, so a leaked child is visible. Not hypothetical: the same green run above still had to force-terminate a leaked bash and a leaked wscript process at job teardown. PROVEN on PR #1022 (same branch, run 38103924282, before this commit): a temporary faulthandler_timeout=5 plus a throwaway test sleeping 8s produced a log on BOTH a Windows leg (pytest (windows-latest, 3.10), job 114365322297, lines 703-708: "Timeout (0:00:05)!" naming tests/test_proof_1014_faulthandler.py::test_proof_sleep_past_faulthandler_timeout with its full traceback) and a Linux leg (pytest (ubuntu-latest, 3.10), job 114365322191, lines 1072-1079: same dump, same test). The throwaway test and the lowered value are removed/restored in this commit; the real values above are what ships. No user-visible behavior changes -- CI-only -- so no changelog fragment; PR labeled no-changelog instead. faulthandler_timeout is independent of --cov (coverage collection is unaffected) and of pytest-xdist (confirmed via repo-wide grep: this repo has no xdist configured, and the setting is per-worker/per-process either way if that changes). Co-Authored-By: Max <noreply>
…ok.sh call (#1031) * Follow-up investigation for #1029: the ~67-process whole-hook total is cold-start-only, not a per-call cost #1011/#1028's own CI measurement (strace -f -e trace=clone,clone3,fork,vfork, whole-hook total for post-tool-hook.sh's no-save path, minimum of 9 runs) is 67 on HEAD, down from v0.43.0's 69 and v0.42.4's 68 -- but still on the order of several dozen processes for one no-save PostToolUse call, per #1029. Traced to the test's own fixture: tests/test_post_tool_total_processes_1011.py creates a brand-new tmp_path (HOME, PROJECT, REMEMBER_DIR, TMPDIR all freshly created) for every one of the n repeated runs, so every measured run takes the slow/cold path -- _remember_env_cache_load misses, so resolve-paths.sh, detect-tools.sh, bootstrap-dirs.sh and log.sh all get sourced, pulling in lib-memory-dir.sh's worktree-detection forks, _config_load's jq read, and several mktemp+mv atomic cache publishes. On the warm path -- any call after the first in a real session, the common case once a project has run once -- _remember_env_cache_load succeeds and none of those four files are sourced at all; the only forks left are _pt_scan_lines's own tail+wc pair, which the code's own comment directly above the wc call already documents as unavoidable without reintroducing #1017's quadratic bash-expansion regression. No source change lands in this commit: every candidate #1029 named (bootstrap-dirs.sh's directory creation, the mktemp+mv atomic-write pattern, the jq config read, _pt_scan_lines's two forks) traced to either already-gated cold-path-only work (#230/#666), work inside the byte-pinned lib-memory-dir.sh (tests/test_case_divergence_298.py forbids touching it), or a fork already proven, in-repo, unavoidable without a worse regression. Forcing a cut here would mean either reaching into the pinned file or reintroducing one of #1013/#1017/#1021's own fixed regressions, neither of which is a safe trade for a performance-only, non-blocking issue. tests/test_post_tool_total_processes_1011.py now asserts an absolute budget (69 -- the measured 67 plus 2 of slack) for both the below-threshold and cooldown paths, in addition to the existing relative tag-comparisons, so a real future reduction or regression on this cold path is still caught even on a CI leg where neither tagged comparison tree can be materialized (no network reaching origin). Adds a changelog fragment documenting the corrected attribution with the CI-measured totals. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Fix #1029: port the fork-free stdin-field extractor to post-tool-hook.sh, removing three unconditional subshell forks per call Self-review (Explore + oss:auditor review of commit 3116fcf) found a real, low-risk cut this round's investigation missed: _stdin_json_string in scripts/post-tool-hook.sh was called through X=$(...) command substitution at three sites (REMEMBER_HOOK_CWD, STDIN_SESSION_ID, STDIN_TRANSCRIPT_PATH), all above the _REMEMBER_FAST if/else, so all three ran unconditionally on EVERY invocation of this hook -- cold-start and warm path alike -- each forking a subshell even though the function itself is pure parameter expansion with no external exec at all. session-start-hook.sh already carries a fork-free twin of this exact extractor, _stdin_json_string_into (#665, part of #660), written into VARNAME via printf -v instead of printed through a subshell. Ports that same function (renamed in place, same matching algorithm: same first-occurrence scan, same #344 nested-key gap, same #829 double-backslash collapse) into post-tool-hook.sh and switches all three call sites to it. No behaviour change: tests/test_hook_cwd_end_to_end_411.py, tests/test_codex_stdin_session_id_468.py and tests/test_session_end_hook_345.py, which all exercise this extraction end-to-end, pass unchanged, along with 47 other post-tool-hook.sh tests run locally (test_post_tool_* family, test_hot_path_cost_pin_330, test_pt_scan_lines_wall_clock_1017, test_post_tool_fast_path_350) and tests/test_release_branch_check_900.py's byte-budget pin. tests/test_locale_ranges_695.py's five post-tool-hook.sh line pins shift by +4 for the lines this change adds above them. Tightens tests/test_post_tool_total_processes_1011.py's new absolute-budget assertions (added in 3116fcf) from <69 to <67 -- strictly below #1028's own prior total, reflecting this cut -- for both the below-threshold and cooldown paths; the exact new total is reasoned, not re-measured locally (this file's own strace gate needs Linux, unavailable here), and this pull request's own CI run will confirm it. Updates the changelog fragment and this file's own module docstring to describe the fix landed rather than "no further cut was found." Co-Authored-By: Claude Sonnet 5 <[email protected]> * Fix #447 tests: follow post-tool-hook.sh's extractor rename to _stdin_json_string_into 00f26b7 ported the fork-free printf-v extractor into post-tool-hook.sh, renaming _stdin_json_string to _stdin_json_string_into there (same shape as session-start-hook.sh's own #665/#660 port). The #447 characterization tests still looked for the old name by string match, so all 7 post-tool/* parametrized cases failed collection-time assertions on every CI leg ("_stdin_json_string not found in scripts/post-tool-hook.sh"), not a behaviour regression. Confirmed the new extractor keeps the same first-occurrence scan, the same documented nested-before/after gap, and the same #829 double-backslash collapse by reading its body directly (post-tool-hook.sh:212-230): identical mechanism to _stdin_json_string, just printf -v into a named variable instead of printed and captured via command substitution. No product fix needed -- only the test's CASES table, which already supported the "_into" calling convention via session-start-hook.sh's own rows in the same table. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Fix #829's post-tool EXTRACTORS row to match the same extractor rename The previous commit fixed test_stdin_extractor_top_level_wins_447.py's own CASES table but missed this file's separate EXTRACTORS table, which also names post-tool-hook.sh's extractor by the old "_stdin_json_string" / keyed=True / into=False shape. CI's first re-run surfaced the gap directly: test_windows_cwd_is_decoded[post-tool], test_unc_prefix_decodes_pairwise[post-tool] and test_posix_cwd_is_unchanged[post-tool] all failed the same "_stdin_json_string not found in scripts/post-tool-hook.sh" assertion. Same fix as before: the function is now _stdin_json_string_into (printf -v, no subshell), so this row flips to into=True, matching session-start-hook.sh's own "session-start/into" row in the same table. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Fix #1029 review: _sjsi_-prefix every local in the ported extractor printf -v resolves against the innermost local, so the port left a latent collision: a future call site passing a VARNAME of value, dq, rest, raw, field or prefix would write the function own local, not the caller. session-start-hook.sh copy already prefixes every local for this reason. Same line count, so the locale-range pins do not move. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
…ames its test (#1022) * PROOF (temporary) for #1014: lower faulthandler_timeout to prove the dump fires Temporary commit to capture CI evidence that pytest's faulthandler_timeout names a hung test and dumps its traceback. Will be removed before the final PR: this lowers faulthandler_timeout to 5s and adds a throwaway test that sleeps 8s so the dump fires on a real CI run (windows + linux). Co-Authored-By: Max <noreply> * Fix #1014: faulthandler_timeout + step timeout so a hung pytest leg names its test A Windows pytest leg was cancelled twice by the job-level timeout-minutes: 30 (PR #1013 job 114288023016, PR #1020 job 114358206393), and a job cancelled by its own timeout writes NO log at all, so we could not tell which test hung or whether it was the runner or our code (#1002's real wscript.exe tests have already hung 40+ minutes once). - pyproject.toml: faulthandler_timeout = 900 under [tool.pytest.ini_options] (built into pytest, no new dependency). Dumps every thread's traceback, naming the hung test, once any single test runs longer than 900s. Sized with ~30x margin over the slowest single test observed on a recent green windows-latest run (30.14s, run 38091996750 job 114330142530), and below the new step timeout so the dump lands in a kept log. - .github/workflows/tests.yml: a step-level timeout-minutes: 25 on both "Run tests" and "Run the full suite against the compiled hooks" -- below the job's 30-minute one, so a hang fails the STEP and the job still completes with its log (including the faulthandler dump) rather than being cancelled with no log at all. - A trailing, Windows-only, if: always() step on both jobs that lists any surviving wscript.exe/bash.exe/conhost.exe/powershell.exe processes with PID/PPID/command line, so a leaked child is visible. Not hypothetical: the same green run above still had to force-terminate a leaked bash and a leaked wscript process at job teardown. PROVEN on PR #1022 (same branch, run 38103924282, before this commit): a temporary faulthandler_timeout=5 plus a throwaway test sleeping 8s produced a log on BOTH a Windows leg (pytest (windows-latest, 3.10), job 114365322297, lines 703-708: "Timeout (0:00:05)!" naming tests/test_proof_1014_faulthandler.py::test_proof_sleep_past_faulthandler_timeout with its full traceback) and a Linux leg (pytest (ubuntu-latest, 3.10), job 114365322191, lines 1072-1079: same dump, same test). The throwaway test and the lowered value are removed/restored in this commit; the real values above are what ships. No user-visible behavior changes -- CI-only -- so no changelog fragment; PR labeled no-changelog instead. faulthandler_timeout is independent of --cov (coverage collection is unaffected) and of pytest-xdist (confirmed via repo-wide grep: this repo has no xdist configured, and the setting is per-worker/per-process either way if that changes). Co-Authored-By: Max <noreply> * PROOF (temporary) for #1014 round 2: faulthandler_exit_on_timeout kills a genuine hang This PR's own CI (run 38122057767, job 114418645594, pytest windows-latest/3.9) ran the "Run tests" step ~33.6 min past its own 25min timeout and still ended `cancelled` with no log at all -- the exact failure #1014 set out to fix, on this PR's own branch. Neither the step's nor the job's timeout-minutes visibly stopped it. Temporarily lowers faulthandler_timeout to 20s and adds a test that sleeps forever (never returns on its own) to prove faulthandler_exit_on_timeout kills the pytest PROCESS itself well inside that bound, converting a hang into a failed step with a traceback in a kept log -- rather than depending on a runner-level kill already observed not to fire. Removed in the finalizing commit on this branch; the real values ship there. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Tee pytest output + upload as artifact; clean up v0.42.3 wscript test orphans (#1014) Belt-and-braces alongside faulthandler_exit_on_timeout: the "Run tests" and "Run the full suite against the compiled hooks" steps now tee pytest's output to a file and upload it with actions/upload-artifact under `if: always()`, so a failed or timed-out step still leaves the log behind even if the step's own captured output is somehow lost. Does not cover a job-level `cancelled` -- GitHub Actions skips steps entirely in that case -- which is exactly why the process-level kill is the primary fix. Also fixes the orphan processes a green leg of this PR's own CI already surfaced (run 38122057767, job 114418645663): the OLD v0.42.3 shape test_windows_real_wscript_v0_42_3_1002.py drives backgrounds wscript.exe with a trailing `&` and disowns it by design (reproducing the shipped trap-B silent skip), so nothing in that shape or this test module ever waited on or killed what it launched -- the job's own teardown had to force-terminate a leftover bash.exe/wscript.exe pair at the end of the whole run. Adds an autouse fixture that force-terminates, after every test in the module, any wscript.exe/bash.exe/conhost.exe whose command line mentions that test's own tmp_path. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Finalize #1014: real values + changelog, after round-2 proof narrowed the Linux-only claim The round-2 proof (run 38122057767, job 114445674357) showed the faulthandler traceback naming the stuck test IS kept in the log on Linux, followed by the step's own 25-minute timeout error -- i.e. the step timeout is what keeps the log, not faulthandler_exit_on_timeout: pytest was not observed to exit on its own before the step timeout fired. Windows was not proven. - Removes tests/test_proof_1014_round2_exit_on_timeout.py (the deliberately hanging proof test) and restores faulthandler_timeout to its real value (900s). - Drops faulthandler_exit_on_timeout: unproven by the round-2 evidence, so this repo does not rely on it. - Updates the workflow comments that had claimed faulthandler_exit_on_timeout does the killing, to instead say what is actually proven: the step timeout keeps the log, proven on Linux only. - Adds the changelog.d/1014.fixed.md fragment this PR was missing. Co-Authored-By: Claude Sonnet 5 <[email protected]> * Add changelog fragment for #1014 Co-Authored-By: Claude Sonnet 5 <[email protected]> --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
Closes #913.
Post-tool-hook.sh ran wc -l on the whole transcript on every tool call -- O(whole transcript size), growing with every turn of a session. This replaces that with a (byte offset, line count) sidecar keyed by the transcript's sanitized basename (not SESSION_ID, deliberately, to avoid moving SESSION_ID's own computation earlier). Each call reads only the bytes appended since the last offset via tail -c +OFFSET; the read's own leading byte doubles as a validator against a shrunk/rewritten transcript, falling back to a full recount on mismatch (also what offset=0 / first call of a session naturally gets -- no separate cold branch). A half-written last line (no trailing newline) is never counted and never advances the offset.
Separately, the existing save-cooldown check (which already independently blocks a save regardless of delta) now runs BEFORE this scan, so a cooldown-active call skips the whole scan. This follows the spirit of #1011's report of a Windows kernel bug that leaks a Token object per forked console process until reboot -- one fewer fork under cooldown is one fewer leaked Token, not just saved latency. #1011 itself (its doctor WARN and docs suggestion) is intentionally NOT implemented here; mentioned only as motivation for this ordering. A separate lane should pick up #1011's own ask.
Measured on real /bin/bash 3.2.57 (not the Homebrew bash 5.3 that otherwise resolves as plain bash in this dev environment):
tests/spawn_counting.py gained tail in its shared COUNTED list -- it did not track tail forks before, so a tail-based fix would otherwise have passed every existing fork-count assertion with the harness blind to the very fork it claims to measure.
New test file tests/test_post_tool_incremental_scan_913.py (7 tests): incremental read of only appended bytes with a positive control, save-decision unchanged across incremental calls (threshold boundary), half-written last line not counted until complete, shrunk-transcript fallback to full recount, rewritten-transcript-same-offset fallback, partial-sidecar-write rejected as a pair not per-field (the self-review fix's own regression test), and cooldown-active skips the scan entirely with a positive control (ls present, tail/wc absent).
tests/test_locale_ranges_695.py's ALLOWLIST was re-pinned for shifted SESSION_ID bracket-range line numbers, plus one new entry for the new sidecar key's own ASCII-only basename sanitizer (same charset and reasoning as the existing SESSION_ID check).
FAST_PATH_SPAWN_MEASURED in tests/test_post_tool_fast_path_350.py was already stale before this diff touched the file -- its comment and value (6) described a spawn list that still included sed for the slug fork, which an earlier, separate #913 PR had already removed without re-measuring this constant. Measured in this environment at 5, not 6; fixed here (the constant is read into FAST_PATH_SPAWN_BUDGET, an upper bound with slack, so this is honesty rather than a required correctness fix, but keeping it accurate is what keeps #913's own acceptance measurement honest).
Rebased onto main after #1010/#1012 landed (the Windows detach watchdog and the rc=137 double-save guard). The rebase was conflict-free -- the two changes sit in disjoint regions of post-tool-hook.sh (the #913 scan/cooldown-reorder block above the _pt_scan_lines work, #1012's watchdog/PID_FILE wiring around the detach call near the bottom) -- confirmed afterward with a diff against origin/main: the only post-tool-hook.sh hunks are the ones this PR's own commits introduce, and #1012's _remember_is_windows/_remember_detach_windows wiring and its rc=137 PID_FILE guard are untouched, byte-identical to main. tests/test_locale_ranges_695.py's ALLOWLIST line numbers were already correct for the rebased tree (all 5 locale-range tests pass). Checked the release-tree hook-script budget (.github/scripts/check_release_tree.py's HOOK_SCRIPT_MAX_BYTES = 120 * 1024 = 122880 bytes): post-tool-hook.sh is 72451 bytes after this change, well under; check_release_tree.py on a tree built from this branch's HEAD reports OK (only pre-existing REVIEW advisories unrelated to this diff).
Re-ran the targeted set after the rebase: tests/test_post_tool_incremental_scan_913.py, tests/test_windows_hidden_detach_1002.py, tests/test_post_tool_fast_path_350.py, tests/test_post_tool_hook_spawns.py, tests/test_locale_ranges_695.py and tests/test_scanner_shapes_source_898.py -- 471 passed, 0 failed.
UPDATE after the first CI round: 4 legs failed (ubuntu-latest 3.9/3.11, windows-latest 3.10/3.12). All four shared one failure -- tests/test_windows_skip_triage_497.py, because the new tests/test_post_tool_incremental_scan_913.py's own win32 blanket-skip was never added to docs/windows-skip-triage.md; fixed by adding it there (not-convertible). The two ubuntu legs additionally failed tests/test_hot_path_cost_pin_330.py's own #353/#395 sidecar-trust pins -- a real regression the rebase surfaced, not a platform artifact: the #913 cooldown-before-scan reorder had nested the WHOLE #353 last-saved-position lookup (not just the new scan) inside the same cooldown-gated block, and that pin's own fixture always leaves a cooldown marker set, so the #353 branch never ran under it at all. Fixed by scoping the cooldown gate to just the scan again (through the sidecar write), restoring the #353 lookup and the final DELTA assignment to run unconditionally as before #913 touched this file, and short-circuiting the sidecar's own upper-bound check on IN_COOLDOWN so it skips itself rather than comparing against a never-computed CURRENT_LINES of 0. #913's own win (incremental, not whole-transcript, counting) and the cooldown-skips-the-scan behaviour (#1011's own motivation) are both unchanged; only the accidental extra skip is undone. Re-pinned tests/test_locale_ranges_695.py's two shifted ALLOWLIST line numbers (860->868, 955->970) for the comment lines this fix added above them. Re-ran the full targeted set plus tests/test_hot_path_cost_pin_330.py and tests/test_windows_skip_triage_497.py after this round: 485 passed, 0 failed. Re-checked the release-tree hook-script budget against the new HEAD: post-tool-hook.sh is 73814 bytes, still well under the 122880 budget.
A non-blocking, self-healing finding from this PR's own self-review round (tail's exit status is not checked in the scan's fallback path, masking a transient read failure as a shrink/rewrite) was logged to trap.d/913.tail-exit-status-not-checked-in-scan-fallback.md rather than fixed here, per the repo's own rule that a non-blocking, self-healing, trap-eligible finding ships behind a trap fragment instead of blocking the PR.
[AI-generated]