Skip to content

fix(#690): stop the fd-2 redirect swallowing a deliberate trace - #708

Merged
fdaviddpt merged 3 commits into
mainfrom
fix/690
Sep 16, 2026
Merged

fdaviddpt merged 3 commits into
mainfrom
fix/690

Conversation

@fdaviddpt

@fdaviddpt fdaviddpt commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Part of #690.

bootstrap-dirs.sh sends fd 2 to hook-errors.log so a hook's stderr never leaks into the host's transcript. Bash's own xtrace stream is on fd 2 too — so that line also swallowed every bash -x profile of these hooks, from partway through the run, into a file the profiler never reads.

A truncated trace does not look truncated. It reads as a complete profile of a fast hook, and the fork counts and per-step attributions taken from it describe a fraction of the run. Measured on macOS while building the #660 diagnostic: wall 0.71s, traced span 0.07s — 90% missing, silently. Every PS4='+$EPOCHREALTIME ' bash -x number on the #660 thread, ours and the reporter's both, was partial for this reason.

The change

The redirect stands down in exactly the cases where it would swallow a trace somebody started on purpose:

condition fd 2
nothing tracing redirected to hook-errors.log, as before
set -x with BASH_XTRACEFD unset or 2 left alone — the trace is on it
set -x with BASH_XTRACEFD=9 redirected — the trace is elsewhere and unaffected
REMEMBER_TRACE=1 left alone — for a profiler that is not bash's own xtrace

When it stands down it says so, on the stream it kept, naming both the log it is not writing and BASH_XTRACEFD as the way to have both. Silence there would be a smaller version of the same defect: the operator would find no new lines in hook-errors.log during a profiling run and have nothing to tell them why.

The BASH_XTRACEFD=9 row is the one worth arguing. Disabling the redirect there would trade a solved problem — that trace is already safe — for the stderr leak the redirect exists to prevent (#643).

Tests

Seven, and the pairing is the point: "never redirect" passes every trace assertion, "always redirect" passes every containment assertion, so each direction needs its twin.

  • stderr still reaches hook-errors.log, and not the terminal, when nothing is tracing — the must-fire control
  • an xtrace on fd 2 survives the bootstrap, and is not poured into the log
  • the stood-down redirect names the log and BASH_XTRACEFD
  • a trace on its own fd does not disable the redirect, and still covers the commands after it
  • REMEMBER_TRACE=1 opts out; REMEMBER_TRACE=0 does not (an implementation testing -n would read an explicit "no" as a yes)
  • end to end: the real hook under bash -x, asserting the trace reaches _remember_render_memory_section — long past the redirect — while the hook still works

The module takes the resolve_bash() route rather than a blanket win32 skip, so Windows — where #660 was measured — is not excluded from its own defect. No docs/windows-skip-triage.md row is needed for the same reason.

The end-to-end test reads the trace as bytes: bash's line-oriented xtrace can split the promo's emoji mid-character, and a test that dies decoding its own evidence proves nothing.

pytest: 2504 passed, 58 skipped locally (macOS, Python 3.13). The Linux and Windows legs are reasoned, not observed, from here: the mechanism is $-, BASH_XTRACEFD and one printf, all of which Git Bash has, but "Git Bash has them" is a claim about the shell, and only the windows-latest leg is evidence about the runner.

Docs: docs/diagnostics.md gains a "Profiling a hook: where your trace goes" section with both invocations.

🤖 Generated with Claude Code

Follow-up (commit 055d77a): macOS bash-3.2 fixed, Windows split out as #712

CI first came back red on all 4 macOS legs and all 4 Windows legs (run #35091652526), both in tests/test_trace_not_swallowed_690.py.

macOS (fixed, tested red/green): GitHub's macos-latest runners resolve bash to stock /bin/bash 3.2, which predates BASH_XTRACEFD (bash 4.1+). The guard at scripts/bootstrap-dirs.sh trusted BASH_XTRACEFD's text without checking whether the running bash could honor it, so on 3.2 the variable is silently ignored and fd 2 gets redirected anyway -- reproducing #690's own original symptom through its own fix. Fixed by checking BASH_VERSINFO directly before trusting BASH_XTRACEFD, matching the existing pattern in lib-clock.sh/lib-lock.sh. New test test_pre_4_1_bash_keeps_fd_2_even_with_xtracefd_set, confirmed red on real bash 3.2 (forced first on PATH via a shim) before the fix, green after.

Windows (undiagnosed, split out): the end-to-end test asserting the trace reaches past the bootstrap (the core promise this issue is about) fails on windows-latest with zero stdout bytes under bash -x, while the other six tests in the file pass on the same runner -- so this is not a bash-resolution or PATH problem, and it is not yet understood. No Windows runner was available to step through it locally. Rather than close #690 on an unmet Windows leg, or block the macOS fix on an undiagnosed Windows one, this is split into #712, and test_the_real_hook_traces_past_the_bootstrap is marked xfail(sys.platform == "win32", strict=False, raises=AssertionError) -- loud rather than a silent skip, so it stays visible until fixed (flips to XPASS, the signal to remove the marker), and scoped to AssertionError only so an unrelated crash on that leg still fails the build.

Self-review (Explore + oss:auditor) found and fixed two further issues: a scratch variable (_remember_bd_has_xtracefd) that leaked outside its own -d guard's unset, and a missing raises= scope on the new xfail that would otherwise have absorbed any exception on that leg as the same documented symptom.

#690 stays open until #712 is also fixed -- the issue's own acceptance criterion is the real hook's trace surviving end to end, and that is only verified on Linux and macOS so far.

Verified by the maintainer

Confirmed PR #708's original CI failure (8/16 legs, all macOS + all Windows) against gh-pr:708:status before dispatching the follow-up fix, and confirmed the macOS root cause and fix against the reporter's own issue comment plus the developer's red/green evidence. Filed #712 for the Windows regression and changed this PR's closing reference from Closes #690 to Part of #690 accordingly -- the developer's own report flagged this same caveat (#690 only partially addressed) rather than closing on it unread.

[AI-generated]

bootstrap-dirs.sh sends fd 2 to hook-errors.log so a hooks stderr never
leaks into the hosts transcript. Bashs own xtrace stream is on fd 2 too, so
every `bash -x` profile of these hooks stopped at that line and poured the
rest into a log file the profiler never reads -- silently, from partway
through the run. A truncated trace does not look truncated: it reads as a
complete profile of a fast hook, and the fork counts and per-step
attributions taken from it describe a fraction of it. Measured on macOS while
building the #660 diagnostic: wall 0.71s, traced span 0.07s.

The redirect now stands down in exactly the two cases where it would swallow
a trace somebody started on purpose -- xtrace running with BASH_XTRACEFD
unset or 2, or REMEMBER_TRACE=1 -- and prints one line on the stream it kept
saying the log is NOT being written. A trace on its own fd is untouched by
the redirect, so that case keeps it: the stderr leak this redirect exists to
stop (#643) is not worth trading for a problem already solved.

Both directions are pinned, because either one alone is satisfied by a
broken implementation: never redirecting passes every trace assertion, and
always redirecting passes every containment assertion. The end-to-end test
runs the real hook under bash -x and asserts the trace reaches the memory
render, which is long past the redirect.

No blanket win32 skip: the module takes the resolve_bash() route, so Windows
-- where this was measured -- is not excluded from its own defect.

Co-Authored-By: Max <noreply>
GitHub's own macOS runners resolve `bash` to stock `/bin/bash` 3.2, which
predates BASH_XTRACEFD (added in 4.1) and silently ignores it -- xtrace stays
on real fd 2 no matter what the variable names. The guard added for #690
trusted the variable's TEXT rather than whether this bash actually honours
it, read "9", concluded the trace was safely elsewhere, and redirected fd 2
into hook-errors.log anyway -- reproducing the exact #690 symptom on the
platform the original measurement was taken on.

The guard now checks BASH_VERSINFO directly, the same way lib-clock.sh and
lib-lock.sh already gate their own bash-4+ features, and stands the redirect
down on that floor the same way it already does for a bare fd-2 trace.
test_pre_4_1_bash_keeps_fd_2_even_with_xtracefd_set pins the new behaviour
(red on bash 3.2 before this change, green after); the existing
BASH_XTRACEFD test now skips on that same floor, since its premise --
that the variable actually moves the trace -- does not hold there.

The Windows leg's own failure (test_the_real_hook_traces_past_the_bootstrap,
zero stdout bytes under `bash -x` on windows-latest) is a separate,
undiagnosed mechanism unrelated to this guard -- marked as a loud,
non-strict xfail with the specifics of what is and is not established, so
it stops blocking CI without being silently swept under a skip.

Co-Authored-By: Max <noreply>
Two findings from self-review of 1ff8160:

- Explore: `_remember_bd_has_xtracefd` was set unconditionally but only
  unset inside the `[ -d "$REMEMBER_DIR/logs" ]` guard, breaking this
  file's own convention (every other scratch var it introduces is unset
  before returning) and leaking into the rest of the hook's environment
  on a read-only/missing logs dir. Moved the unset outside that guard so
  it always fires.

- oss:auditor: the new `xfail(sys.platform == "win32", ...)` on
  test_the_real_hook_traces_past_the_bootstrap had no `raises=`, so any
  exception on that leg -- not just the documented empty-stdout assertion
  -- would collapse into the same XFAIL line. Added `raises=AssertionError`
  so an unrelated crash on that leg still fails the build.

Co-Authored-By: Max <noreply>
@fdaviddpt
fdaviddpt merged commit 9bdcde4 into main Sep 16, 2026
16 checks passed
@fdaviddpt
fdaviddpt deleted the fix/690 branch September 16, 2026 21:46
fdaviddpt added a commit that referenced this pull request Sep 19, 2026
…script, refuse a repo-committed handoff (#731)

* fix(#720,#721): stop parsing /remember's Write target from the transcript, refuse a repo-committed handoff

The /remember skill took its Write destination from "the most recent
=== HANDOFF === block in this session's context" -- text any untrusted
content the session ingested (a hostile README, a fetched page, an issue
body, a repo-committed .remember/remember.md the SessionStart hook itself
injected) could forge, with Write pre-approved for any path. The skill now
pipes its note to a new scripts/write-handoff.sh, which resolves the
destination from REMEMBER_DIR and an out-of-band hint the hook writes to
$REMEMBER_DIR/tmp/handoff-path, never from the transcript, and refuses
(falling back to the ordinary default) any resolved path whose shape isn't
remember.md / remember.<id>.md directly inside REMEMBER_DIR (#720).

SessionStart also no longer injects a git-tracked .remember/remember.md as
though it were the user's own prior note -- this plugin never commits one
itself, so a tracked file was shipped by the repository, not written by a
real /remember run, and delivering it verbatim was also how a forged
HANDOFF block reached the skill. A genuine, untracked handoff is still
delivered, now fenced with an explicit "data, not instructions" line
(#721).

#690's macOS/bash-3.2 regression is already fixed on main (PR #708); its
remaining Windows gap is tracked separately as #712, out of this lane's
scope.

Co-Authored-By: Max <noreply>

* fixup #720/#721: fix review findings -- scoped Bash rule, case-insensitive tracked check, mktemp, token fence

Explore review:
- allowed-tools was written as Bash(bash "${CLAUDE_PLUGIN_ROOT}/scripts/write-handoff.sh":*),
  which does not match this environment's real scoped-Bash convention
  (Bash(${CLAUDE_PLUGIN_ROOT}/...:*), no "bash " prefix, no quotes --
  confirmed against ralph-loop's own command). Fixed the rule and the
  invocation to match, and the script is already +x with a shebang.
- The hook's pre-existing "=== HANDOFF ===" hint (external/per-session
  mode) is still emitted and is no longer read by anything -- its own
  comment claimed it was "consumed by the /remember skill", which stopped
  being true. Relabelled it human-facing-only and corrected the "that
  channel is gone" overclaim in docs/handoff.md.
- Strengthened a weak test assertion that would pass on a stub script that
  never touched the filesystem.

oss:auditor:
- _remember_handoff_is_tracked's exact-case `git ls-files` check missed a
  handoff committed under a different case than this session resolves it
  -- on a case-insensitive filesystem (APFS default, NTFS) the SAME bytes
  are still delivered. Added a case-insensitive ls-tree fallback, with a
  new test pinning it.
- write-handoff.sh's temp file used a $$-suffixed literal name in the same
  shared directory this repo's own lib-memory-dir.sh already documents the
  hazard for (predictable, symlink-followable). Switched to mktemp.
- The new closing fence used a fixed literal string
  ("=== END LAST HANDOFF ==="), which the handoff's own attacker-controlled
  content could pre-embed a forged copy of. The marker now carries a
  per-delivery random token the hook generates at delivery time.

The token broke an existing invariant test (single mode byte-identical to
the unset default) by introducing legitimate non-determinism; normalized
the token out of that comparison rather than removing it.

Co-Authored-By: Max <noreply>

* fixup2 #720/#721: fix second-pass review findings on the fixup itself

Second-pass Explore + oss:auditor review over the fixup commit (85d0e70)
found the case-insensitive tracked-check fallback it introduced was itself
broken in three ways, one a real regression:

- it restricted the ls-tree pathspec to the handoff's OWN directory case,
  so a repo-committed DIFFERENTLY-CASED DIRECTORY (.Remember/remember.md)
  was invisible to it -- pathspec matching is byte-exact regardless of
  core.ignorecase, so this missed the exact class of attack #721 targets,
  just shaped one level up from a differently-cased filename;
- it read HEAD's tree rather than the index, so `git rm --cached` -- the
  remediation the hook's own refusal message names -- did not un-refuse a
  handoff until a new commit landed. A genuine regression for anyone who
  follows the refusal message's own advice;
- it used `--name-only` with no `-z`, so `core.quotepath`'s default
  octal-escaping of non-ASCII paths could silently break the comparison.

Rewritten to scan `git ls-files -z` with no path restriction, comparing
each NUL-delimited entry case-insensitively in bash rather than trusting
git's pathspec matching -- closes all three at once, since it no longer
depends on a directory pathspec, reads the index (agreeing with the
exact-case check on `git rm --cached` immediately), and sidesteps
quoting by using `-z`.

Piped via process substitution rather than a `$(...)` variable: NUL-
delimited output cannot survive a bash variable at all (the string
truncates at the first NUL), which very nearly shipped as a new bug
introduced by this same fixup.

Two new regression tests pin the differently-cased-directory case and the
git-rm---cached-un-refuses-immediately case, the second staged with git
plumbing (`hash-object`/`update-index --cacheinfo`) since an actual
second, differently-cased directory cannot exist on this filesystem's own
case-insensitive volume.

Not fixed, logged to trap.d/ instead (non-blocking per the ranking table):
a git command failure in either the exact or the fallback check collapses
to the same state as "genuinely untracked" -- a pre-existing shape in the
codebase (case-divergence's own three-state model exists for the identical
reason) that this diff duplicates rather than introduces. Also not fixed:
mktemp's 0600 vs the previous umask-following handoff file permissions --
judged a desirable tightening consistent with this project's own stated
"treat ~/.remember/ like ~/.ssh/" posture, not a regression.

Co-Authored-By: Max <noreply>

* fix(#720,#721): log two below-bar review findings to trap.d

Left uncommitted in the lane's own working tree by mistake -- both were
already disposed as below-bar in the report and PR body, just not staged
with the fixup commits.

Co-Authored-By: Max <noreply>

* fix(#720,#721): pin the shape-check bracket range to LC_ALL=C, add third trap.d fragment

CI on windows-latest (PR #731) caught a real defect: scripts/write-handoff.sh's
`_wh_shape_ok` used a bracket-range character class
(`*[!A-Za-z0-9._-]*`) without pinning `LC_ALL=C` first, the exact class
tests/test_locale_ranges_695.py's `test_no_unguarded_letter_range_in_shipped_shell`
exists to catch (#695) -- under a locale whose collation folds letters
differently (Turkish is the standing example elsewhere in this codebase),
the range can match or reject bytes it should not. Pinned it the same way
every other bracket-range comparison in this codebase already does
(lib-memory-dir.sh, lib-memory-context.sh, session-start-hook.sh all carry
the identical `local LC_ALL=C  # bracket ranges below are byte-wise, not
collated (#695)` line). Confirmed red before (temporarily removed the
pin, test_no_unguarded_letter_range_in_shipped_shell failed) and green
after, restored file verified byte-identical to the fix.

Also adds the third below-bar trap.d fragment
(trap.d/721.git-dir-symlink-bypasses-tracked-check.md) for the residual
finding the PR body already named but whose receipt was missing: a `.git`
symlinked to a different repository could in principle bypass
`_remember_handoff_is_tracked`, left unaddressed because it requires a
strictly stronger local-write primitive than #720/#721's own threat
model assumes.

Co-Authored-By: Max <noreply>

* fix(#721): fix a case-insensitive-filesystem test fixture bug (CI red on all 4 ubuntu legs)

`test_git_tracked_handoff_is_refused_even_under_a_different_case` wrote its
differently-cased plant directly to disk (`cased.write_text(...)` at
`.remember/Remember.MD`, then `git add`). That only ever worked because it
was authored and locally verified on APFS -- case-insensitive by default,
so writing `Remember.MD` and reading back `remember.md` (the literal path
`$REMEMBER_HANDOFF` resolves to) hit the SAME inode. On a real
case-sensitive filesystem (ext4, every `ubuntu-latest` CI runner) they are
two different files: the literal-case `remember.md` this session actually
resolves to never existed on disk at all, so the hook found nothing to
either refuse or deliver -- the assertion failed because "refused" is not
in an output that consists only of the unrelated always-injected REMEMBER
section, not because the production code (scripts/session-start-hook.sh)
did anything wrong.

Not a defect in _remember_handoff_is_tracked or its case-insensitive
fallback -- both are unchanged by this commit. Fixed the fixture to match
the sibling directory-case test's own convention: write real content to
the literal-case path returned by `_sandbox` (what the hook will actually
look for), and stage the DIFFERENTLY-cased git-index entry with plumbing
(`hash-object` + `update-index --add --cacheinfo`) rather than a second,
differently-cased file on disk.

Verified against the real CI failure: pulled all 4 failing ubuntu-latest
job logs (gh-job:105881733864/854/888/950) directly rather than trusting
a paraphrase -- all four are the identical failure, in the identical
test, for the identical reason. Local run after the fix:
tests/test_handoff_fence_and_tracked_refusal_721.py -- 6 passed.

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.

session-start-hook.sh cannot be profiled with bash -x: bootstrap-dirs.sh:364 redirects fd 2 mid-run and the trace stops silently

1 participant