diff --git a/docs/decisions/records/process/hook-resolves-inputs-from-repo-root.md b/docs/decisions/records/process/hook-resolves-inputs-from-repo-root.md index 30419bb5e..3cb2b8951 100644 --- a/docs/decisions/records/process/hook-resolves-inputs-from-repo-root.md +++ b/docs/decisions/records/process/hook-resolves-inputs-from-repo-root.md @@ -7,7 +7,7 @@ supersedes: none superseded-by: none rule: 'A hook resolves every path whose CONTENT it sources, executes, or consults to decide, from `$repo_root` — derived from the hook''s own `${BASH_SOURCE[0]}` — and never from `$CLAUDE_PROJECT_DIR` or any other environment variable. There is NO telemetry exemption, and the attempt to write one is instructive: the first draft of this record exempted `ETV_HOOK_FIRE_LIB` on the grounds that "a wrong log destination is not a wrong verdict", and cold review refuted it by execution — that path is `. `-SOURCED, so whatever it names runs as CODE inside the hook before stdin is read and before `decide` exists; a file there that prints an `allow` decision and exits 0 grants the merge having bypassed every check in the file. A path''s PURPOSE does not bound its authority; how the hook consumes it does. THE SAME TEST DRAWS THE OTHER BOUNDARY, and it is not optional: a path the hook consumes as its SUBJECT — the tree it is asked to JUDGE — is caller-supplied by design, and binding it to `$repo_root` would break the guard, since the hook lives in one tree and must judge whichever worktree is being acted in. Two live cases, both deliberate: `pretooluse-bom-guard.sh` takes the committed tree from the command''s `cd`, then the payload `cwd`, then `${CLAUDE_PROJECT_DIR:-$PWD}` as a last-resort default; and `decisions-guard.sh` `cd`s to `git rev-parse --show-toplevel` and EXECUTES that tree''s `scripts/decisions_validate.py`, whose exit code is the hook''s decision — the stronger case, since it is code and not data, and it is admissible for the same reason: a pre-commit validator must validate the tree being committed, and under husky, its only launcher, git sets the cwd to that tree so the two roots agree anyway. The distinction is not first-two-sources-versus-third and not data-versus-code: it is WHOSE QUESTION the path answers. Ban the variable in the assignment naming the AUTHORITY — the code that decides — never every mention of it in a hook. The failure that matters is not an attacker — the same variable already names the hook binary in `.claude/settings.json`, so a hostile value has chosen which hook runs and the gate is moot before any inner path is read — it is LAUNCHER DIVERGENCE, and it is reachable: husky invokes the prepush hooks as `./.claude/hooks/…`, a relative path wholly independent of `$CLAUDE_PROJECT_DIR`, so the two roots genuinely disagree there. A wrong path holding a plausible file returns a confident answer about another tree; a missing path only asks, so the silent direction is the dangerous one. Two halves of one comparison must never come from two roots.' signals: 'env var as a security input · `$CLAUDE_PROJECT_DIR` vs `$repo_root` · `${BASH_SOURCE[0]}` self-location · sourced file is code not configuration · which checkout''s code decided this · launcher divergence · husky relative path vs harness env · a wrong path returns a confident answer, a missing one asks · both halves of a comparison from one root · paths: `.claude/hooks/pretooluse-merge-consent.sh`, `scripts/hook-fire-log.sh`, `scripts/check-review-verdict.sh`, `scripts/check-required-contexts.sh` · issues: #858, #891, #787, #629' -mechanics: 'No linter can spot "this path should have come from `$repo_root`". Enforcement is review plus a behavioural test per site: point `$CLAUDE_PROJECT_DIR` at a decoy tree whose copy of the resolved file returns the OPPOSITE decision, and assert the outcome is unchanged. That test needs a NEGATIVE CONTROL or it proves nothing — the passing outcome is also what an inert decoy produces — so run the same decoy again with the hook COPIED INTO it, making the decoy genuinely `$repo_root`, and assert the decision DOES flip. Since #891 that test is PARAMETRIZED OVER THE DERIVED HOOK POPULATION in `test_hook_fire_log.py` — `test_CLAUDE_PROJECT_DIR_cannot_choose_the_SOURCED_sink` beside `test_the_sink_decoy_IS_sourced_when_it_genuinely_is_the_repo_root` — so a hook added tomorrow arrives covered rather than needing someone to remember it, and the static arm of `instrumentation_faults` refuses the env-var form at review time, with `test_an_ENV_VAR_resolved_sink_path_is_DETECTED` as its mutation proof. Two worked single-site pairs live in `test_merge_consent_required_check.py`: `test_CLAUDE_PROJECT_DIR_cannot_choose_which_verdict_classifier_runs` and `test_the_SOURCED_fire_log_library_cannot_be_chosen_by_CLAUDE_PROJECT_DIR`, each beside its `..._IS_honoured/sourced_when_it_genuinely_is_the_repo_root` control.' +mechanics: 'No linter can spot "this path should have come from `$repo_root`". Enforcement is review plus a behavioural test per site: point `$CLAUDE_PROJECT_DIR` at a decoy tree whose copy of the resolved file returns the OPPOSITE decision, and assert the outcome is unchanged. That test needs a NEGATIVE CONTROL or it proves nothing — the passing outcome is also what an inert decoy produces — so run the same decoy again with the hook COPIED INTO it, making the decoy genuinely `$repo_root`, and assert the decision DOES flip. Since #891 that test is PARAMETRIZED OVER THE DERIVED HOOK POPULATION in `test_hook_fire_log.py` — `test_CLAUDE_PROJECT_DIR_cannot_choose_the_SOURCED_sink` beside `test_the_sink_decoy_IS_sourced_when_it_genuinely_is_the_repo_root`, and the husky RELATIVE launch as its own pair, since that construct resolves through the CWD — so a hook added tomorrow arrives covered rather than needing someone to remember it. The STATIC half is not a pattern over the line but BYTE-IDENTITY of the preamble''s two lines (a lexical rule was tried and withdrawn; see the body), proved by `test_a_LATER_reassignment_the_regex_cannot_see_is_DETECTED` for the shape only it catches, with `test_an_ENV_VAR_resolved_sink_path_is_DETECTED` and `test_the_NEXT_env_var_to_be_invented_is_DETECTED` pinning the diagnostic arms, each asserting its OWN arm''s phrase because the byte-identity message echoes the offending line and would otherwise satisfy them by itself. The sink''s own root resolution additionally requires the root to OWN it, proved by `test_the_report_REFUSES_a_root_that_does_not_OWN_this_sink`. Two worked single-site pairs live in `test_merge_consent_required_check.py`: `test_CLAUDE_PROJECT_DIR_cannot_choose_which_verdict_classifier_runs` and `test_the_SOURCED_fire_log_library_cannot_be_chosen_by_CLAUDE_PROJECT_DIR`, each beside its `..._IS_honoured/sourced_when_it_genuinely_is_the_repo_root` control.' --- `.claude/hooks/pretooluse-merge-consent.sh` resolved three decision-bearing paths from two different diff --git a/docs/decisions/records/testing/mutation-claims-are-executed.md b/docs/decisions/records/testing/mutation-claims-are-executed.md index 67e6eba52..9dd38e566 100644 --- a/docs/decisions/records/testing/mutation-claims-are-executed.md +++ b/docs/decisions/records/testing/mutation-claims-are-executed.md @@ -45,7 +45,7 @@ finer mutations settled which guards actually admit clause-level proof: all but including `pin_population_faults`, where disarming the against-the-registry comparison alone reddens the proof because a job that loses its `container:` block leaves the two derived sets equal. One does not. -`instrumentation_faults` accumulates from independent arms and a stripped hook trips three of +`instrumentation_faults` accumulates from independent arms and a stripped hook trips several of them at once, so disarming any single arm leaves the proof test green — measured, by running `if not _SOURCES_SINK.search(text):` → `if False:` and watching it pass. That surviving mutation is carried as data and re-run on every suite: if it ever starts reddening, the guard has become diff --git a/docs/guard-inventory.md b/docs/guard-inventory.md index c348a2397..37b95011c 100644 --- a/docs/guard-inventory.md +++ b/docs/guard-inventory.md @@ -373,8 +373,8 @@ Two things that column still does not say. It does not say the declared clause i guard hangs on — for three rows (measured 2026-08-22) the redness arrives through the proof test's own "this clause has moved, RETARGET it" assertion rather than through changed behaviour, which catches the recorded proof going stale but not much else. And one row is graded `DETECTOR` rather than `CLAUSE` in the -manifest: `instrumentation_faults` accumulates from independent arms and a stripped hook trips three -at once, so no single-arm disarm reddens its proof. That finer mutation is carried as data and +manifest: `instrumentation_faults` accumulates from independent arms and a stripped hook trips +several at once, so no single-arm disarm reddens its proof. That finer mutation is carried as data and re-run every suite, and must keep surviving — if it starts reddening, the guard has become clause-provable and the entry is regraded. diff --git a/scripts/hook-fire-log.sh b/scripts/hook-fire-log.sh index cc51e8e25..7b23a366e 100755 --- a/scripts/hook-fire-log.sh +++ b/scripts/hook-fire-log.sh @@ -454,9 +454,16 @@ etv_hook_fire_end() { # Read side: the report # --------------------------------------------------------------------------------------------- -# The hook population, DERIVED from the filesystem, never listed -# (`testing.guard-derives-population-from-source`). A hook added tomorrow appears in the report as +# The hook population, DERIVED rather than listed. A hook added tomorrow appears in the report as # NEVER-FIRED the moment it exists, rather than being invisible because nobody updated an array. +# +# A FILESYSTEM WALK, and that is the carve-out rather than the rule. +# `testing.guard-derives-population-from-source` requires the GIT INDEX for a guard's file +# population and allows a walk only with its reason written down, so: this is the REPORT, not a +# gate — it describes what is on disk in the tree it was run from, and an untracked scratch hook +# that really does fire is a row a reader wants to see. The guard over these same hooks +# (`test_hook_fire_log.py`) uses `git ls-files`, and the two populations are deliberately not the +# same one. etv_hook_fire_population() { local root="${1:-}" f [ -d "$root/.claude/hooks" ] || return 0 @@ -486,11 +493,13 @@ etv_hook_fire_repo_root() { self="${BASH_SOURCE[0]}" root="$( cd -- "$(dirname -- "$self")/.." >/dev/null 2>&1 && pwd )" || return 0 # AND THE ROOT MUST OWN THIS FILE. Self-location alone answers "two directories up from wherever - # I am", which is this repo only when this file sits in it. A copy or symlink somewhere whose - # grandparent happens to hold a `.claude/hooks` — `~/bin/hook-fire-log.sh` beside `~/.claude/hooks` - # exists on a real machine here — otherwise roots at `$HOME` and prints a confident table about - # another tree's hooks. Requiring the root's own sink to BE this file makes that case return - # nothing, which `etv_hook_fire_report` already refuses with exit 2 rather than an empty table. + # I am", which is this repo only when this file sits in it. A copy or symlink whose grandparent + # happens to hold a `.claude/hooks` otherwise roots there and prints a confident table about + # another tree's hooks. The shape is ordinary — `$HOME` holds a `.claude/hooks` on any machine + # running Claude Code, so anything dropped in a `$HOME//` roots at `$HOME` — and it is the + # SILENT direction, since the wrong answer is a plausible one. Requiring the root's own sink to BE + # this file makes that case return nothing, which `etv_hook_fire_report` refuses with exit 2. + # Proven by `test_the_report_REFUSES_a_root_that_does_not_OWN_this_sink`, for a copy and a symlink. [ "$root/scripts/hook-fire-log.sh" -ef "$self" ] || return 0 printf '%s' "$root" } @@ -525,6 +534,14 @@ etv_hook_fire_report() { # ANTI-VACUITY. A report over an empty population would print a clean table of nothing and read # as "all hooks accounted for" — the exact failure this file exists to end. + # + # THE TWO REASONS ARE REPORTED SEPARATELY. An empty `$root` means the ownership check above + # declined to name a checkout, not that a checkout was searched and found bare; saying "no hooks + # under /.claude/hooks" for that case is a refusal stating a finding it never made. + if [ -z "$root" ]; then + printf 'hook-fire-log: could not establish which checkout this sink belongs to (%s is not the `scripts/hook-fire-log.sh` of the tree two levels above it) — refusing to report rather than describing some other tree.\n' "${BASH_SOURCE[0]}" >&2 + return 2 + fi local pop pop=$(etv_hook_fire_population "$root") if [ -z "$pop" ]; then diff --git a/scripts/tests/mutation_manifest.py b/scripts/tests/mutation_manifest.py index e08c89dd5..708127986 100644 --- a/scripts/tests/mutation_manifest.py +++ b/scripts/tests/mutation_manifest.py @@ -270,9 +270,11 @@ MUTATIONS: tuple[Mutation, ...] = ( granularity=DETECTOR, expect="left the check GREEN. The check is not load-bearing", why="NO CLAUSE-LEVEL MUTATION REDDENS THIS ONE, and that is a finding rather than a shortcut. " - "`instrumentation_faults` accumulates from independent arms and a stripped hook trips three " - "of them at once (no sink source, no ETV_HOOK_FIRE_LIB assignment, no begin call), so " - "disarming any single arm leaves the other two answering and the proof test stays green. The " + "`instrumentation_faults` accumulates from independent arms and a stripped hook trips SEVERAL " + "of them at once (no sink source, a preamble that is not the canonical two lines, no " + "ETV_HOOK_FIRE_LIB assignment, no begin call), so disarming any single arm leaves the rest " + "answering and the proof test stays green. No count is pinned here: it moved once already " + "when an arm was added, and the argument needs `more than one`, not a number. The " "whole detector is therefore the smallest mutation this proof can witness — and the surviving " "single-arm mutation below is re-run every time so that claim is checked, not recited.", survived_clause=" if not _SOURCES_SINK.search(text):", diff --git a/scripts/tests/test_hook_fire_log.py b/scripts/tests/test_hook_fire_log.py index 3564592ec..a210b7291 100644 --- a/scripts/tests/test_hook_fire_log.py +++ b/scripts/tests/test_hook_fire_log.py @@ -148,7 +148,10 @@ def instrumentation_faults(text: str, name: str) -> list[str]: # variable in prose. Every other line mentioning it must be one of the two canonical lines, in # order. A heredoc carrying the token would fault; no hook has one, and refusing is the safe # direction — this arm's errors are refusals, never acceptances. - mentions = [line for line in text.splitlines() if "ETV_HOOK_FIRE_LIB" in line and not line.lstrip().startswith("#")] + # `split("\n")`, not `splitlines()`: the latter also breaks on \x0b, \x0c, \x1c-\x1e, \x85 and the + # Unicode separators, none of which ends a line for the shell. Every divergence lands in the + # refusal direction, so this is exactness rather than a live defect. + mentions = [line for line in text.split("\n") if "ETV_HOOK_FIRE_LIB" in line and not line.lstrip().startswith("#")] if mentions != [CANONICAL_SINK_ASSIGNMENT, CANONICAL_SINK_SOURCE]: faults.append( f"{name}: the sink preamble is not the canonical two lines. Every hook carries them " @@ -156,9 +159,15 @@ def instrumentation_faults(text: str, name: str) -> list[str]: f"trailing comment, a rewritten expansion — is a divergence, not a variant. got={mentions}" ) - # The arms below no longer decide anything: byte-identity above already refuses everything they - # catch. They survive to say WHY a line is wrong, because "not byte-identical" is a true but - # useless message for the failure that actually recurs. + # THE FOUR `libs` ARMS BELOW — and only those — no longer decide anything: byte-identity above + # already refuses every line they catch. They survive to say WHY a line is wrong, because "not + # byte-identical" is a true but useless message for the failure that actually recurs. + # + # Scoped deliberately. The sentence used to read over everything below it, which is a + # coverage-boundary claim that MIS-SORTS: the `ETV_HOOK_FIRE_DISABLE` arm and the begin + # name/mode/stdin-order arms are NOT subsumed — a hook carrying both canonical lines plus + # `ETV_HOOK_FIRE_DISABLE=1` trips exactly one fault, and it is not byte-identity's. A reader + # trusting the unscoped sentence would delete a live detector. libs = re.findall(r"^ETV_HOOK_FIRE_LIB=(.*)$", text, re.M) if not libs: faults.append(f"{name}: no ETV_HOOK_FIRE_LIB assignment") @@ -564,9 +573,11 @@ def test_the_HUSKY_RELATIVE_launch_DOES_source_its_own_trees_sink(hook, sandbox, """NEGATIVE CONTROL for the test above, in the same construct. Its sibling asserts an ABSENCE under a relative launch, and a relative launch has an extra way to - produce one: resolve to nothing at all. So the same relative spelling is run against a tree that - IS the decoy — hook copied in, cwd set to it — where the marker MUST appear. That separates "the - variable was ignored" from "the self-location silently resolved nowhere". + produce one: resolve to nothing at all. So the same relative spelling is run against a pushed + tree whose OWN sink is the announcing one, where the marker MUST appear. That separates "the + variable was ignored" from "the self-location silently resolved nowhere". The two arms differ in + exactly one thing — which sink the pushed tree holds — and `$CLAUDE_PROJECT_DIR` names the + unrelated decoy in both. """ pushed = _pushed_tree(tmp_path, hook, DECOY_SINK_BODY) decoy = _sink_decoy(tmp_path) @@ -601,9 +612,13 @@ def test_an_ENV_VAR_resolved_sink_path_is_DETECTED(): ) mutated = text.replace(current, predecessor) faults = instrumentation_faults(mutated, hook.stem) - assert any("CLAUDE_PROJECT_DIR" in f for f in faults), ( - f"restoring the env-var-first sink path in {hook.name} left the check GREEN, so nothing " - f"stops it being reintroduced one hook at a time. faults={faults}" + # THE ARM'S OWN PHRASE, never the variable name. The byte-identity fault echoes the + # offending line verbatim, so a substring assertion on `CLAUDE_PROJECT_DIR` is satisfied by + # the ECHO — measured by cold review: deleting the dedicated arm entirely left this test + # green. Asserting that a MESSAGE mentions the defect is not asserting the DETECTOR ran. + assert any("resolves the SOURCED sink from" in f for f in faults), ( + f"restoring the env-var-first sink path in {hook.name} did not trip the arm that names " + f"it, so nothing stops it being reintroduced one hook at a time. faults={faults}" ) @@ -661,7 +676,8 @@ def test_the_NEXT_env_var_to_be_invented_is_DETECTED(hook): text = hook.read_text() assert current in text, f"{hook.name} no longer carries the line this mutation replaces" faults = instrumentation_faults(text.replace(current, successor), hook.stem) - assert any("besides" in f for f in faults), ( + # Its own phrase too, for the reason given in the sibling proof above. + assert any("expands" in f and "besides" in f for f in faults), ( f"a sink path steered by a NEW environment variable passed clean on {hook.name}. The arm is " f"a containment test, not a resolution test, and the ban is worth only the one name in it. " f"faults={faults}" @@ -1306,6 +1322,52 @@ def test_the_report_names_hooks_that_NEVER_fired(sandbox): assert zero_rows, "no never-fired rows shown despite only one hook appearing in the log" +def test_the_report_REFUSES_a_root_that_does_not_OWN_this_sink(tmp_path, sandbox): + """THE PROOF for the ownership clause in `etv_hook_fire_repo_root` (ersatztv#891). + + Self-location answers "two directories above wherever I am", which is this repo only when this + file sits in it. A copy or symlink whose grandparent HAPPENS to hold a `.claude/hooks` otherwise + roots there and prints a confident table about another tree — the wrong-root case the sink's own + comment claims is enforced rather than hoped for. It was shipped unexecuted: cold review measured + that replacing the clause with `:` left this whole file green, because the sibling test below + copies the sink into `/scripts/`, where the root DOES own it. + + Both spellings, because they reach the check differently: a plain copy, and a SYMLINK (whose + `-ef` comparison resolves through the link and must still say "not mine"). + """ + _root, env = sandbox + for label, place in (("copy", "copy"), ("symlink", "symlink")): + fake = tmp_path / f"fake-{label}" + (fake / "bin").mkdir(parents=True) + # A root that WOULD look plausible: it really does hold hooks, just not this sink's. + (fake / ".claude" / "hooks").mkdir(parents=True) + (fake / ".claude" / "hooks" / "someone-elses-hook.sh").write_text("#!/bin/sh\nexit 0\n") + target = fake / "bin" / "hook-fire-log.sh" + if place == "copy": + shutil.copy2(SINK, target) + else: + target.symlink_to(SINK) + + runenv = dict(env) + runenv.pop("CLAUDE_PROJECT_DIR", None) + p = subprocess.run( + ["bash", str(target), "report", "--all", "--dir", str(tmp_path / "nolog")], + capture_output=True, + cwd=str(tmp_path), + env=runenv, + timeout=60, + ) + assert p.returncode == 2, ( + f"the {label} reported from a root it does not belong to (exit {p.returncode}). A wrong " + f"root must refuse, not describe another tree. stdout={p.stdout.decode()!r}" + ) + assert b"could not establish which checkout" in p.stderr, ( + f"the {label} refused for some other reason, so the ownership clause is not what " + f"stopped it: {p.stderr.decode()[:300]!r}" + ) + assert b"someone-elses-hook" not in p.stdout, "it listed the other tree's hooks" + + def test_the_report_REFUSES_an_empty_population(tmp_path, sandbox): """Anti-vacuity on the read side. A report over zero hooks would print a tidy empty table and read as 'all hooks accounted for' — the shape of #751's 6-second green.