Skip to content

Generalise the #344 top-level-wins extractor pin across source, cwd and session_id - #493

Merged
fdaviddpt merged 2 commits into
mainfrom
fix/447
Sep 1, 2026
Merged

fdaviddpt merged 2 commits into
mainfrom
fix/447

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

Closes #447.

What

#344/#379 pinned _stdin_json_string's first-occurrence scanning ("first "KEY" occurrence wins, not first top-level occurrence") only for source, which #344 bounded to a five-literal whitelist. Since #444 the same extractor (and its cwd-hardcoded twin _stdin_cwd in user-prompt-hook.sh) also resolves cwd on all four hooks and session_id on three of them, neither of which carries that whitelist -- cwd in particular feeds REMEMBER_HOOK_CWD/PROJECT_DIR, the root every write is relative to.

Adds tests/test_stdin_extractor_top_level_wins_447.py: a unit-level characterization test that extracts each extractor function's body verbatim out of the four live script files (never hand-copied) and drives it directly with synthetic payloads, asserting the same two-test shape #379 established -- nested-after-top-level still wins, nested-before-top-level is pinned as today's documented gap -- for every (hook, key) pair the extractor actually reads. No script file changed and no JSON parser introduced, per #340/#344's standing decision that a hook which must survive a broken install is the wrong place to acquire one.

Review

Two spawned reviews against the committed diff: a correctness reviewer (NO FINDINGS -- independently re-derived the function extraction against the live scripts, reproduced the red/green mutation test, cross-checked coverage against every call site) and an audit pass that found one real issue: the new test file copied the blanket skipif(sys.platform == "win32") shape that PR #432 explicitly retired elsewhere in this suite, which reports the windows-latest CI leg green while silently skipping every test on it. Fixed in a follow-up commit by switching to tests/_bash_runner.py's resolve_bash() (Git-Bash discovery), matching test_hook_cwd_leak_417.py and test_transcript_path_leak_424.py.

Testing

pytest tests/test_stdin_extractor_top_level_wins_447.py -q --no-cov -> 17 passed. Red evidence: a temporary mutation of _stdin_cwd (reverted immediately, never committed) to always return a fixed string produced 2 failures with clear diffs, confirming the assertions have real bite. python3 .oss/assemble_changelog.py --check passes with the new 447.added.md fragment listed.

…source, cwd and session_id (#447)

The #344/#379 pin only ever covered `source`, which #344 had bounded to a
five-literal whitelist. Since #444 the same first-occurrence
`_stdin_json_string`/`_stdin_cwd` extractor also resolves `cwd` (feeding
REMEMBER_HOOK_CWD/PROJECT_DIR) and `session_id` on session-start,
session-end and post-tool hooks -- none of which carry that whitelist.
Adds the same two-test shape (nested-after wins, nested-before is the
documented gap) for every (hook, key) pair the extractor actually reads,
run directly against the extracted function bodies rather than through a
full hook invocation. No JSON parser introduced and no extractor changed,
per #340/#344's standing decision.

Co-Authored-By: Max <noreply>
#432)

The reviewer's audit flagged that the new test file copied the blanket
`skipif(sys.platform == "win32")` shape #432 explicitly fixed in
test_hook_cwd_leak_417.py and test_transcript_path_leak_424.py -- that
pattern makes the windows-latest CI leg collect and skip every test while
reporting the leg green, indistinguishable from a genuine pass. Switches
to tests/_bash_runner.py's resolve_bash() (Git-Bash discovery), the same
fix those two files already carry, so the 17 new tests actually run under
Git Bash on Windows CI instead of being silently skipped for the whole
platform.

Co-Authored-By: Max <noreply>
@fdaviddpt
fdaviddpt merged commit a1af82b into main Sep 1, 2026
13 checks passed
@fdaviddpt
fdaviddpt deleted the fix/447 branch September 1, 2026 21:34
fdaviddpt added a commit that referenced this pull request Sep 3, 2026
… nested-cwd reachability research (#494) (#514)

* fix(hooks): #511 fewer warm-path subshells, #504 env-cache key parity, #494 nested-cwd research

#511 -- user-prompt-hook.sh's warm path still paid a subshell fork for the
cwd extraction and the clock read even where nothing inside them shells out
to an external process. Both now write into a variable directly
(`_stdin_cwd_into`, `_remember_date_into`) instead of being captured
through `$( ... )`. `_stdin_cwd` itself is left untouched, byte for byte,
because tests/test_stdin_extractor_top_level_wins_447.py extracts and calls
it verbatim by name. Reasoned, not observed: no Windows box available to
this lane to measure actual milliseconds saved.

#504 -- user-prompt-hook.sh's fast-path env-cache lookup keys on
CLAUDE_PROJECT_DIR before resolve-paths.sh has normalized a Windows drive
path; session-start-hook.sh's publish keys on it after. On a platform where
normalization actually rewrites the string the two hooks could derive
different cache keys for the same project, so the fast path would never
hit what the slow path had just published. lib-env-cache.sh now normalizes
the key the same way resolve-paths.sh does, scoped to the same
`case "$OSTYPE" in msys|cygwin)` guard so it stays a no-op fork-wise on
every other platform.

#494 -- researched whether any of Claude Code's, Codex's or Gemini CLI's
hook payload schemas can nest a same-named `cwd` key ahead of the
top-level one, the open half of #447/#493. Source-verified for Codex,
docs-observed for the other two: no. `cwd` is always top-level and the
only nested object a hook payload carries is always declared after it, so
even a hypothetical third-party MCP tool naming a parameter `cwd` would
still land in the safe "nested-after" case. Documented in the extractor's
own header comment across all four hooks; the #447 test stays a
characterization against a synthetic payload rather than becoming a hard
assertion, since a host is free to reorder its own schema.

Tests: tests/test_env_cache_key_windows_normalize_504.py (red before the
normalize fix -- raw and normalized Windows spellings keyed different cache
files; green after, with a positive control that a genuinely different
project still keys differently) and tests/test_fast_path_subshells_511.py
(parity between the print-and-capture and set-a-variable extractors, plus
that the `$(_stdin_cwd ...)` / `$(_remember_date ...)` call sites are
actually gone from the hot path). All targeted suites green locally
(pytest tests/ -k "prompt or env_cache or stdin or hook_cwd or
windows_native or clock or session_start or post_tool or codex_stdin" --
276 passed, 3 skipped for unrelated platform reasons). Full test_command
left for CI per this repo's own CLAUDE.md.

Co-Authored-By: Max <noreply>

* fix: self-review findings on #504/#511 (subshell fork, skip gate)

Spawned Explore + oss:auditor against the previous commit. Both returned
real findings, fixed here rather than argued down.

Explore (3 findings, one already covered by design, two applied):
- #504's own fix (`_remember_env_cache_normalize`) was called as
  `_key="$(_remember_env_cache_normalize "$_key")"` -- a `$( )` command
  substitution, which forks a subshell for the substitution itself
  regardless of the function body, on the SAME fast path #511 (this same
  lane) exists to stop forking. Renamed to
  `_remember_env_cache_normalize_into` and switched to `printf -v`, the
  same technique already used for `_stdin_cwd_into`/`_remember_date_into`.
- The file's header comment ("every check below is a bash builtin") was
  left stale by that same bug; now states the one real exception (`tr` on
  a matched Windows drive letter, msys/cygwin only) explicitly.
- A dead `assert ... or True` in the new parity test
  (test_remember_date_into_matches_remember_date_builtin_path) is removed;
  the retry block immediately below it already implements the real check.

oss:auditor (1 finding):
- tests/test_fast_path_subshells_511.py's module-level
  `pytestmark = pytest.mark.skipif(BASH is None, ...)` skipped two
  pure-source-text regression guards
  (test_stdin_cwd_is_no_longer_captured_through_a_subshell and its
  sibling) that read the script file and grep it -- no subprocess, no bash
  needed. If resolve_bash() ever returns None on a leg, those two checks
  -- the ones the previous commit message leans on hardest -- would go
  dark silently. Split into a per-test `_needs_bash` marker applied only
  to the three tests that actually invoke bash via subprocess. Verified
  with a positive control: monkeypatching resolve_bash() to return None
  shows the two static checks still run and pass (2 passed, 7 skipped),
  where before this fix the whole module would have skipped (9 skipped).

Tree snapshot taken before spawning both reviewers and compared after:
the only diffs are these two files, matching exactly the fixes applied
here -- neither spawn (both told explicitly not to edit, Explore has Bash
but no Edit/Write) mutated anything.

Targeted suite still green: pytest tests/ -k "prompt or env_cache or
stdin or hook_cwd or windows_native or clock or session_start or
post_tool or codex_stdin" -- 276 passed, 3 skipped for unrelated platform
reasons. assemble_changelog.py --check passes; shellcheck --severity=warning
on the touched files shows no new findings.

Co-Authored-By: Max <noreply>

* fix: two Windows-only subprocess hazards in PR #514's new bash-harness tests (job #100829698217)\n\n#504's test file hardcoded the literal string "bash" instead of this suite's established resolve_bash() (tests/_bash_runner.py, #432) -- on windows-latest, bare "bash" commonly resolves to the WSL launcher stub rather than Git Bash, which prints a UTF-16 nag and exits nonzero when no WSL distro is installed, exactly matching the corrupted-looking tail in the job log's CompletedProcess repr.\n\n#511's parity test passed a raw JSON string containing embedded double quotes as a Windows argv positional. subprocess.run's no-shell argv list is re-flattened by Python's own list2cmdline (MSVCRT quoting rules) before CreateProcess hands it to bash.exe, and MSYS's own argv re-parsing does not agree with that quoting on a string containing literal '"' characters -- the quotes can be stripped before $1 reaches the function under test, so `"cwd"` no longer appears in $1 and both the old and new extractor report a miss (matching the observed OLD_RC=1/NEW_RC=1 on every case whose raw JSON contains a quote). Routed through an environment variable instead, which Windows passes as an already-decoded block with no command-line re-quoting step.\n\nBoth REASONED, not OBSERVED -- no Windows box available to confirm either mechanism directly; the fixes remove the hazard in the harness itself; the functions under test (_stdin_cwd, _stdin_cwd_into, _remember_env_cache_normalize_into) are unchanged.\n\nVerified: 276 passed, 3 skipped locally (macOS) on the same targeted -k run the lane's own report used; no behavior change to product code, so no red-then-green cycle applies here -- the bug was in the test harness' own subprocess plumbing, not in an assertion.

Co-Authored-By: Max <noreply>
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.

The first-match stdin extractor now feeds cwd on all four hooks, and #344's top-level-wins pin only ever covered source

1 participant