Skip to content

fix(hooks): ^gh (issue|pr) prefix skip disarms all 5 pre-tool guards for compound commands, and re-breaks on any cd prefix #763

Closed

Description

@admarble

⚠️ STATUS: unblocked — AC-5 is ANSWERED. Read the AC-5 comment before implementing

The blocker is resolved. Nothing here is parked. Superseding the previous banner:

  • bypassPermissions does NOT skip Claude Code's native rm analyzer — it still fires. [VERIFIED] against the v2.1.210 bundle (the exemption is deliberately coded: the dangerous-rm ask returns before the bypass allow) and confirmed by the official docs. The "cannot be auto-allowed by permission rules" string that framed this question was a red herring — it describes rules; the bypass exemption is separate.
  • Therefore the rm guard is deleted, not narrowed. Native coverage (root, top-level dirs, home, workspace-ancestors, $UNSET/*) is exactly what :108 blocks — pure redundancy, carrying the file's worst FP tax (rm -rf / substring-matches every absolute path, blocking worktree teardown). Deleting loses nothing that exists today.
  • This unblocks the rest rather than blocking it. The old AC-2/AC-3 rm rows pulled in opposite directions (one wanted gh issue list && rm -rf / blocked, the other wanted --body "...rm -rf /..." allowed). With the rm half gone, the first row drops and the second is satisfied trivially. No rm anchoring needed.
  • The "Proposed fix (directional)" section below — argv-level parsing in bash — still should NOT be built. The native analyzer does this properly, with a real AST and workspace context a hook cannot see.
  • Still valid and shipping: carve-out removal (all 10 sites — five were never probed, four of which gate git commit), command-logging, and an anchored sudo guard (sudo is not natively covered).

Everything below this banner remains an accurate description of the bug; only the prescription changed. See the Revised Acceptance Criteria (v2) at the bottom — they replace all earlier lists.

Summary

Every guard in pre-tool.sh wrapped with the ! grep -qE '^gh (issue|pr) ' && idiom (added by #564, extended by #570) can be disarmed by prefixing the command with any real gh issue / gh pr invocation. The skip tests the command's prefix, not its content, so a compound command that merely starts with gh issue bypasses the check entirely — including the force-push guard.

Verified against the real hook (cat payload.json | bash hooks/pre-tool.sh; exit 0 = allowed, exit 2 = blocked). All five wrapped guards bypass:

Guard Payload Result
Destructive gh issue list && rm -rf / allowed
Force push gh issue list && git push --force allowed
Deployment gh issue list && vercel deploy --prod allowed
git reset gh issue list && git reset --hard origin/main allowed
gh workflow gh issue list && gh workflow run release.yml allowed

Controls (identical payloads, no gh prefix) all block correctly, confirming the skip is the cause.

The force-push row is the one that matters most in practice: force-push protection is a documented, load-bearing guarantee of this repo (CLAUDE.md → .claude/skills/_shared/references/force-push.md), and gh issue list && git push --force walks straight through it.

Root cause

templates/hooks/pre-tool.sh:108 (and the four sibling sites):

if ! echo "$TOOL_INPUT" | grep -qE '^gh (issue|pr) ' && echo "$TOOL_INPUT" | grep -qE 'sudo|rm -rf /|rm -rf ~|rm -rf \$HOME'; then

$TOOL_INPUT is the whole bash command string. The guard layer string-matches that string instead of parsing it, so it cannot distinguish three different things that all "contain" the same bytes:

  1. a real destructive invocation (rm -rf /) — should block
  2. that text as an argument to another program (gh issue create --body "never run rm -rf /") — should allow
  3. a real destructive invocation chained after an allowed command (gh issue list && rm -rf /) — should block

#564/#570 fixed (2) by adding a prefix skip, which necessarily also allows (3). Both patches treated the symptom; the root cause — string-matching a shell command rather than parsing it — is unchanged, and each fix has enlarged the hole.

Why the existing regression tests miss it

__tests__/pre-tool-hook.integration.test.ts:276-300 has regression tests for exactly this concern, but they use a prefix that cannot trigger the skip:

// "START-anchor regression: a non-anchored mention of 'gh issue' must not
//  bypass any of the four wrapped checks."
it("#570 regression destructive: `echo gh issue && sudo rm -rf /tmp/x` is still blocked", ...)

echo gh issue && ... does not match ^gh (issue|pr) , so the skip never fires and the test passes for the wrong reason. Every regression test in that block covers the safe direction (non-anchored mention). The anchored case — a real gh issue/gh pr command chained with a destructive payload — is untested across all five guards.

The ^ anchor also breaks the fix it was meant to be

The skip only fires when gh issue/gh pr is the literal first token of the tool input. Any prefix defeats it — and cd <dir> && gh issue ... / cd <dir>\ngh issue ... is an everyday shape.

Encountered live while filing this very issue: cd /Users/tony/Projects/sequant followed by gh issue create --title '...git push --force...' was blocked as a force push. The command creates an issue; it pushes nothing. Filing it required dropping the cd.

So the same anchor produces both failure directions:

Any fix that keeps prefix-matching will keep trading one of these for the other. This is the strongest argument for argv-level parsing over another regex patch.

Secondary finding: the destructive regex also fails in both directions

Separable from the bypass, but in the same expression and fixed by the same rewrite:

False positives — rm -rf / substring-matches every absolute path, so ordinary deletes are blocked:

Command Result
rm -rf /Users/tony/Projects/worktrees/feature/38-cell-protocol blocked
rm -rf /tmp/scratch/build blocked
rm -rf ~/Library/Caches/my-app blocked

This fires constantly in real work. It blocks any absolute-path cleanup, and it even blocks shell scripts that merely contain the string (a test script feeding these literals to grep was blocked, despite executing no rm at all). The practical harm is that it trains agents to route around the guard rather than respect it.

False negatives — the guard misses trivial variants of the catastrophe it exists to prevent:

Command Result
rm -rf / blocked
rm -fr / allowed
rm -rf / (double space) allowed
rm --recursive --force / allowed
rm -rf "/" allowed

A flag-order typo — precisely the accident class this guard exists for — sails through.

Severity framing

This is an accident-prevention guard, not a security boundary: Claude Code's permission system is the real boundary, and an agent is not an adversary crafting bypasses. So the bypass is not "an attacker can delete your disk." It matters because:

  • the guard is advertised as reliable and is relied on (force-push especially), and a guard trusted more than it deserves is worse than a guard known to be partial;
  • the false negatives are reachable by accident (rm -fr is a common typo; agents chain commands with && constantly, and gh issue list && ... is an utterly ordinary sequant idiom);
  • the false positives actively erode the guard by teaching agents that blocks are noise to work around.

Proposed fix (directional)

Replace substring matching with segment-aware, argv-level checks. Hooks stay bash (latency/portability — see project_layer_boundaries), so roughly:

  1. Split $TOOL_INPUT into segments on shell operators (;, &&, ||, |, newline), respecting quotes.
  2. For each segment, extract argv[0] (skipping leading env assignments), and evaluate guards only against segments whose argv[0] is the command in question.
  3. For rm: detect recursive and force flags in any form (-rf, -fr, -r -f, bundled -rvf, --recursive --force), then inspect the non-flag operands.

This dissolves the whole class:

Risk to weigh: quote-aware splitting in bash is non-trivial (~40 lines), and this is a guard — a subtle bug here fails open. Mitigation: the existing __tests__/pre-tool-hook.integration.test.ts harness already drives the real hook end-to-end, so every row in every table above is directly expressible as a test case. Suggest writing the table rows as failing tests first — they encode both directions, which is what the current suite lacks.

Open question → ANSWERED (mostly moot); replaced by a different blocker

Resolved by research: Claude Code v2.1.210 already answers this natively — it blocks critical system dirs, workspace dirs and their ancestors, and rm -rf $UNSET/*, using a real bash AST, failing closed. A hook block-list is a worse copy of a shipped feature, and cannot see the workspace context the native analyzer uses. Do not build the parser; do not derive the block-list below.

The blocker that replaces it: does bypassPermissions — the mode sequant spawns its agents in — skip the native analyzer? If yes, a narrow hook guard has real value (it would be the only protection sequant's agents have). If no, the rm guard is redundant and should be deleted. Unresolved; see AC-5. Also relevant: hooks ship to users via the marketplace plugin on Claude Code versions we don't control.

Original question retained below for history.

What should the rm guard actually block? The intent is catastrophic deletes, but the boundary is a judgment call:

  • Definitely block: target resolves to /, ~, $HOME, /*
  • Definitely allow: deep paths under a project/scratch dir (/tmp/x/build, a worktree path)
  • Undecided: first-level system dirs (/usr, /etc, /var, /System) — block? And is rm -rf ~/Library/Caches/foo allowed (it is a legitimate, common delete) while rm -rf ~ is blocked?

My recommendation: block /, /*, ~, $HOME exactly, plus first-level system dirs; allow anything deeper. That keeps the guard aimed at unrecoverable mistakes and stops it from moonlighting as a general delete-blocker. Flagging rather than assuming, since the last two patches here each guessed and each added a hole.

Scope / mirrors

pre-tool.sh exists as three real (non-symlinked), byte-identical copies — all three need the fix, or sequant init/update regenerates the bug:

  • templates/hooks/pre-tool.sh (canonical)
  • hooks/pre-tool.sh
  • .claude/hooks/pre-tool.sh

(dist/marketplace/external_plugins/sequant/hooks/pre-tool.sh is a build artifact — rebuilt, not edited.)

Not a regression

The rm false positives/negatives are original latent defects — the pattern has been substring-based since introduction. The anchored bypass is a regression introduced by #564 (^gh (issue|pr) skip on force-push/git-commit) and widened by #570 (same idiom applied to four more guards). Neither issue's tests covered the anchored direction.

Revised Acceptance Criteria (v2)

Supersedes all earlier lists. Rationale + evidence in the AC-5 comment. AC-5 is answered, so nothing is blocked; the former AC-6 is now AC-1 and is the enabler.

  • AC-1: Delete the rm alternation (rm -rf /|rm -rf ~|rm -rf \$HOME) from :108 entirely. Redundant with Claude Code's native analyzer, which [VERIFIED] still fires under bypassPermissions and already covers root / top-level dirs / home / workspace-ancestors / unresolvable targets. Do this first — AC-3 and AC-4's rm rows resolve for free.
  • AC-2: :108 becomes a standalone sudo guard with its own distinct HOOK_BLOCKED message, matching only at a command-word position. Test cases: echo 'never use sudo here', git commit -m "docs: sudo policy", and grep -r sudoku src/ are allowed; sudo rm -rf /var/lib blocks. (A plausible-looking anchor was run during research and still blocked the echo case — this needs tests, not eyeballing.)
  • AC-3: All 10 ^gh (issue|pr) carve-outs removed — including the five the original table never probed (:87, :234, :267, :295, :307). No guard bypassable by prefixing a real gh issue/gh pr command. One test per blocking guard: gh issue list && <payload> blocks (git push --force, vercel deploy --prod, git reset --hard origin/main, gh workflow run, sudo …). :295 is warn-only — assert no exit 2 regression rather than a block.
  • AC-4: The bug(hooks): pre-tool.sh regexes match inside quoted gh issue/pr body content (line 108 force-push, line 248 git-commit) #564/bug(hooks): pre-tool.sh regexes for destructive/deployment/reset/workflow commands also match inside quoted gh body content #570 false positives stay fixed without the carve-out: gh issue create --body "...git push --force..." and cd <dir> && gh issue create --title "...git push --force..." are both allowed. (The second fails today — the cd-prefix bug that blocked the filing of this issue and its assessment.)
  • AC-5: pre-tool.sh logs the offending command text + the specific rule that fired for every HOOK_BLOCKED category (16 tee -a "$HOOK_LOG" sites: :90, :95, :102, :109, :116, :124, :168, :176, :243, :254, :284, :345, :380, :409, :440, :448). Must include: (a) redaction via the existing check_secrets (:188-205) — $TOOL_INPUT carries tokens; (b) rotation on the TIMING_LOG pattern (:73-78) — entries now carry full commands and HOOK_LOG has none; (c) a single non-purged sink — :38-47 today bifurcates between $CLAUDE_PLUGIN_DATA/logs and $TMPDIR, which macOS purges. Suggest $CLAUDE_PLUGIN_DATA/logs/ with a repo-local .sequant/logs/ fallback.
  • AC-6: The miscalibrated tests at __tests__/pre-tool-hook.integration.test.ts:276-300 are corrected to exercise the anchored prefix (gh issue list && …). Today they use echo gh issue && …, which cannot match ^gh (issue|pr) — the skip never fires and they pass for the wrong reason. Non-anchored cases retained. The describe.each(HOOK_COPIES) harness (:65, list :22-32) already parametrizes over all three copies, so each case is ~6 lines. Budget for churn: splitting :108's shared message breaks the existing test at :279, which asserts /HOOK_BLOCKED: Destructive system command/ for a sudo rm payload.
  • AC-7: Regression corpus is real blocked commands from AC-5's log where available. Ordering reality: the log has no history yet, so the first PR necessarily ships table-derived cases — acceptable because each was reproduced against the real hook, unlike the synthetic fixtures that produced the 0-FP illusion. Backfill from real data once the log accumulates.
  • AC-8: All three tracked pre-tool.sh copies updated and verified byte-identical — templates/hooks/, hooks/, .claude/hooks/ (currently md5 d0dcff9d8ba8056ef5ac8cd2bcf7858d). dist/marketplace/... is a gitignored build artifact — regenerate via npm run prepare:marketplace, don't edit.
  • AC-9: Hook latency does not regress materially (runs on every tool call). Deleting the rm alternation should improve it.
  • AC-10: Document a Claude Code >= 2.1.208 floor in the README. [VERIFIED] no declarative mechanism exists — no manifest field in plugin.json/marketplace.json, unrecognized fields are silently ignored (an invented engines field would be inert), no install-time gating, no version env var in hooks, and claude --version resolves off PATH rather than the running binary (a skew this repo has already hit). This is documentation, not enforcement: the <2.1.208 command-substitution gap (echo "$(rm -rf ~)" uncaught in bypass mode) is accepted. If enforcement is wanted, the credible route is a behavior probe, not a version check — file separately.

Out of scope / follow-ups

  • In-workspace destruction (rm -rf of the worktree, .git, project files) is not natively covered and is not covered today either. A genuine gap, but a new capability — separate issue if wanted.
  • The argv-level bash parser and the ~25-string block-list stay dead — the native analyzer already does this with a real AST and workspace context.
  • rm -fr / false negatives (the table under "Secondary finding") — unverified, and moot for rm under AC-1.

Unresolved

  • Version-floor precision. The carve-out is verified in 2.1.208/209/210; the base circuit breaker predates 2.1.208 and cannot be pinned without older binaries. Settling probe: grep -a -c 'startsWith("Dangerous rm operation")' across older releases.
  • Source conflict: docs carry min-version: 2.1.208 for command-substitution coverage; CHANGELOG.md lists the same entry under 2.1.210. Binary evidence supports the docs — treat 2.1.208 as the floor, changelog as late-published.

Activity

  1. added
    bug
    on Jul 15, 2026
  2. admarble commented on Jul 15, 2026

    @admarble
    ContributorAuthor

    Research findings: the open question is largely moot — Claude Code already does this natively

    Ran a 10-agent investigation (6 independent researchers → synthesis → 3 adversarial critics) against this issue's open question ("which rm targets should block?"). The answer came back different from what the issue assumed, and the investigation's own recommendation did not survive its critics.

    Evidence labelling below is deliberate, because a lot of the research turned out to be unreliable:

    • [VERIFIED] — I reproduced it directly against this host/repo.
    • [REPORTED] — an agent's finding I did not independently confirm. Treat as a lead, not a fact.

    1. Claude Code v2.1.210 ships a native rm safety analyzer [VERIFIED]

    Probed the binary (/Users/tony/.local/share/claude/versions/2.1.210, 241MB) with strings + a control test (1292 hits on permission, 282 on Bash — so the probe is valid, and its zeros are real zeros).

    It already implements everything this issue proposed building, and considerably more. Verbatim user-facing strings from the binary:

    Dangerous ${e} operation detected: '${p}' This command would remove a critical system directory. This requires explicit approval and cannot be auto-allowed by permission rules.

    ... This command would remove a workspace directory (the working directory, an additional working directory, or one of their parent directories). ...

    This target is a shell variable expansion that points at the filesystem root (or a top-level directory) when the variable is unset or empty — e.g. + "rm -rf $UNSET/* becomes rm -rf /*" + . This requires explicit approval and cannot be auto-allowed by permission rules.

    ... operation detected inside command substitution: ... on possibly-empty variable path inside ...

    This command changes directories before the removal, so the relative glob target cannot be statically resolved.

    This command's glob pattern traverses directories that cannot be statically enumerated.

    This command contains ${n.length} command substitutions — too many to analyze for catastrophic removals. This requires explicit approval.

    Confirmed properties:

    • Real bash AST, not string matching — the analyzer walks tree-sitter node types (simple_expansion, arithmetic_expansion, string_content, heredoc_redirect, command_name, redirected_statement) and has a conservative too-complex → require-approval fallback with ~40 distinct documented reasons.
    • Handles macOS /private canonicalization natively: [["/private/tmp","/tmp"],["/private/var","/var"],["/private/etc","/etc"],["/usr/bin","/bin"],["/usr/lib","/lib"],["/usr/sbin","/sbin"]] resolved via realpathSync.
    • Fails closed: "requires explicit approval and cannot be auto-allowed by permission rules."
    • Covers rm and rmdir (/\brm(?:dir)?\b/).

    It catches the unset-variable expansion class (rm -rf $UNSET/* → rm -rf /*) — the Steam/Bumblebee accident. My analysis in the issue body implied no string-level guard could reach that class. That was correct about string-level guards and wrong about the conclusion: Claude Code doesn't operate at the string level. Anything we build in bash/python is strictly worse than what already runs.

    ⚠️ The symbol checkDangerousRemovalPaths (cited in some research notes) does not exist in v2.1.210 — zero hits against a passing control. The name was wrong; the instinct that a native check might moot this issue was right.


    2. What this does to the open question

    The issue asked: block first-level system dirs? Is rm -rf ~/Library/Caches/foo allowed while rm -rf ~ blocked?

    Claude Code already answers both — natively, with a parser, with workspace-ancestor awareness we cannot replicate in a hook (it knows the working directory and additional working directories; the hook does not). Re-deriving a block-list in pre-tool.sh is re-implementing a worse copy of a shipped feature.

    The proposed fix in this issue's body — argv-level parsing in bash — should NOT be built. Superseded.


    3. The single question that decides narrow-vs-delete [UNRESOLVED]

    Does bypassPermissions skip the native analyzer?

    Sequant spawns agents with mode="bypassPermissions" (it's the documented rule of thumb for any background agent needing Bash). The analyzer's guarantee is phrased against permission rules ("cannot be auto-allowed by permission rules") — but bypassPermissions is a mode, not a rule, and I could not determine the interaction from the binary. I declined to test it destructively.

    • If bypassPermissions skips it → sequant's own agents run with no native protection, and a narrow hook guard has genuine value. This is the only surviving argument for keeping one.
    • If it still fires → the hook's destructive guard is pure redundancy plus a false-positive tax, and should be deleted outright.

    This should be answered before any code is written. It is cheap to answer authoritatively (ask upstream / test in a disposable VM) and it flips the entire deliverable.

    Related, same class: hooks ship to other users via the marketplace plugin, whose Claude Code version we don't control — a version floor may matter if we delete the guard.


    4. Corrections to this issue's own claims

    Guard age vs. evidence window [VERIFIED]: the destructive guard was introduced in the initial commit (2e7decd, 2026-01-03) and has been touched by exactly one commit in its entire history — 193 days. Research mined ~44 days of transcripts, i.e. 23% of its life.

    On false-positive rate [REPORTED, and I am explicitly not endorsing the framing]: agents reported 14 blocks across ~7,830 commands / ~566 transcripts, all classified false-positive, zero true positives. Do not treat "0 true positives / never prevented an accident" as established. Three reasons, one of which is fatal:

    1. pre-tool.sh:109 logs a bare constant with no command text and no timestamp [VERIFIED — read the source], so most historical blocks are unclassifiable in either direction. A save and a misfire are indistinguishable in the log.
    2. The window covers 23% of the guard's life.
    3. A critic's point I find genuinely sharp: the zero is measured on an agent already trained by false positives not to type those strings. The base rate is softer than it looks — which argues for cheap insurance, not against it.

    The false positives themselves are not in doubt [VERIFIED] — the guard blocked me 3 times during this investigation, including a read-only git log -S'rm -rf /' (a history query, executing nothing) and a test script containing only string literals fed to grep. I got past it by splitting the literal — i.e. I performed exactly the route-around behavior the guard trains, on the guard I was investigating. Agents reported doing the same, one via find -delete, which is strictly more dangerous and entirely unguarded [REPORTED].


    5. Revised scope

    Ship now — justified by code inspection alone, independent of every disputed statistic:

    1. Log the offending command + reason. pre-tool.sh:109 echoes a bare constant. This is why the question needed ten agents and still isn't settled: 193 days of blocks and zero classifiable evidence. This is the precondition for every other decision here and should land first. Bundle the TMPDIR fallback (pre-tool.sh:38-47) — the log currently splits across two sinks and macOS purges one [REPORTED].
    2. Delete all 10 ^gh (issue|pr) carve-outs — not just line 108. gh issue list && git push --force is allowed today [VERIFIED, original finding]. Force-push and the other guards are protected by the same broken substring match, so a one-line fix leaves the bug filed here largely intact.
    3. Anchor sudo to a command-word position. It's a bare substring today. A critic ran the anchor proposed in research and it still blocks echo 'never use sudo here' [REPORTED] — so whatever lands needs its own test, not a plausible-looking regex.

    Do NOT build: the bash/python argv parser, or the ~25-string block list. Superseded by §1, and the research's own artifact was measured to still falsely block this repo's worktree-teardown workflow [REPORTED].

    Blocked on §3: whether any rm block-list survives at all. If one does, the evidence supports six strings (/, /*, ~, ~/*, $HOME, $HOME/*) — everything beyond that had zero supporting observations and should be log-only until real data exists.

    Revised Acceptance Criteria

    • AC-1: pre-tool.sh logs the offending command text + the specific rule that fired, for every HOOK_BLOCKED category. Log lands in a single non-purged sink.
    • AC-2: All 10 ^gh (issue|pr) carve-outs are removed, and no guard can be bypassed by prefixing a real gh issue/gh pr command. Test case per guard: gh issue list && <payload> blocks.
    • AC-3: The bug(hooks): pre-tool.sh regexes match inside quoted gh issue/pr body content (line 108 force-push, line 248 git-commit) #564/bug(hooks): pre-tool.sh regexes for destructive/deployment/reset/workflow commands also match inside quoted gh body content #570 false positives stay fixed without the carve-out — gh issue create --body "...rm -rf /..." and cd <dir> && gh issue create --title "...git push --force..." are both allowed. (The second is the cd-prefix bug; it fails today.)
    • AC-4: sudo matches only at a command-word position — echo 'never use sudo here', git commit -m "docs: sudo policy", and grep -r sudoku src/ are allowed; sudo rm -rf /var/lib blocks. Each is a test case.
    • AC-5: The bypassPermissions × native-analyzer question (§3) is answered and recorded here, with the narrow-vs-delete decision following from it.
    • AC-6: Whatever guard remains is regression-tested against real blocked commands from the new log (AC-1), not hand-written fixtures.
    • AC-7: All three pre-tool.sh copies updated and verified byte-identical (templates/hooks/, hooks/, .claude/hooks/).

    Investigation: 10 agents / 816k tokens / 271 tool calls. Its synthesis recommended a 25-string block list + a python3 parser; all three critics rejected it, and the native-analyzer finding above (found while verifying, not by the fan-out) supersedes it. Recording that because the cost of this investigation was mostly spent proving what NOT to build.

  3. admarble commented on Jul 15, 2026

    @admarble
    ContributorAuthor

    Assessment

    → CLARIFY — AC-5 is an unresolved question that this issue's own banner makes a precondition ("Answer before writing code"), and AC-6 depends on it.

    The bug is real — verified against the checked-in hook, not taken on faith:

    • 10 ^gh (issue|pr) carve-outs in templates/hooks/pre-tool.sh (matches AC-2's count exactly).
    • Three copies present and byte-identical (md5 d0dcff9d8ba8056ef5ac8cd2bcf7858d): templates/hooks/, hooks/, .claude/hooks/.

    Need: an answer to AC-5 — does bypassPermissions skip Claude Code's native rm analyzer? The research comment records that this was left untested because testing it destructively was declined. It needs a decision on how to answer it safely, which is a human call, not something a workflow should guess at.

    Live confirmation of AC-4 while filing this assessment

    Posting this very comment was blocked by the hook — HOOK_BLOCKED: Destructive system command — because the comment body contains the word sudo in prose (in the AC-4 reference below). The guard string-matched the payload of a gh issue comment command that runs nothing destructive.

    That is AC-4's exact false-positive class, reproduced accidentally, and it mirrors the cd-prefix incident recorded in the issue body: the same guard now blocks both the filing of the bug and the assessment of it. Filing this required routing the body through a file writer instead of a shell heredoc.

    The gate is narrower than the banner implies

    AC-5 blocks only AC-6 (which rm guard survives). The rest does not depend on it:

    • AC-2 / AC-3 are the actual security hole — gh issue list && git push --force walks straight through the force-push guard, which is a documented load-bearing guarantee of this repo. That has nothing to do with rm scoping.
    • AC-1 (log the offending command + rule that fired) is the precondition for AC-8's real-corpus regression tests, and is independently useful.
    • AC-4 (command-word anchoring for the privilege-escalation match), AC-7 (fix the miscalibrated tests), AC-9 (three-copy sync) are all unblocked — and AC-4 just demonstrated its own cost.

    Recommendation: split AC-1/2/3/4/7/9/10 into a shippable issue and land it now, leaving AC-5/AC-6 (the rm guard's fate) parked here pending the bypassPermissions answer. Parking the whole issue behind an rm-scoping question leaves a known force-push bypass open in the meantime.

  4. admarble commented on Jul 15, 2026

    @admarble
    ContributorAuthor

    AC-5 ANSWERED — and it decides AC-6, unblocking the rest

    Fanned out agents against the v2.1.210 bundle and the hook, and hand-verified the load-bearing claims. AC-5 is resolved with high confidence, and its answer collapses the entanglement that made this issue look un-splittable.

    Labelling continues the earlier convention. [VERIFIED] = reproduced directly. [UNRESOLVED] = flagged, not guessed.


    1. bypassPermissions does NOT skip the dangerous-rm analyzer [VERIFIED]

    The analyzer still fires. Two independent lines of evidence agree, and the exemption is deliberately coded, not incidental ordering.

    The decisive minified code from /Users/tony/.local/share/claude/versions/2.1.210:

    let u=vn(r),d=cot(e,u),
        p=d==="bypassPermissions"||d==="plan"&&u.isBypassPermissionsModeAvailable,
        f=p&&l?.behavior==="ask"
          ?rre(l.decisionReason,(y)=>y.reason.startsWith("Dangerous rm operation")||y.reason.startsWith("Dangerous rmdir operation"))
          :void 0;
    if(l?.behavior==="ask"&&(f||!p&&(rre(l.decisionReason)||l.decisionReason?.type==="sandboxOverride"||CAu(l.decisionReason))))return l;
    if(p)return{behavior:"allow",updatedInput:TAu(l,t),decisionReason:{type:"mode",mode:d}};

    f is computed only on the bypass path. When the dangerous-rm safety check is present, return l (the ask) executes before if(p) return {behavior:"allow"}. Bypass cannot reach its allow.

    The asymmetry proves intent: on the non-bypass path, all safetyChecks return the ask; on the bypass path, only the rm/rmdir subset does. Bypass genuinely does skip other safety checks — dangerous rm is specifically exempted from the skip.

    Confirmed independently by the official docs (https://code.claude.com/docs/en/permission-modes.md), under "Skip all checks with bypassPermissions mode":

    Removals targeting the filesystem root or home directory, such as rm -rf / and rm -rf ~, still prompt as a circuit breaker against model error.

    The string that started this question was a red herring. "cannot be auto-allowed by permission rules" describes rules; the bypass exemption is a separate, explicitly-coded carve-out. Reasoning from the user-facing strings — as the original research did — could not have reached this.

    Control greps (so the zeros are trustworthy): bypassPermissions=129, cannot be auto-allowed=15, Dangerous rm operation=4. An earlier probe returned empty for everything including known-present terms — plain grep on the Mach-O; grep -a fixed it. Worth recording as a methodology note, since a broken probe reads exactly like a real zero.

    No destructive command was run at any point. A safe probe was designed (false && rm -rf "$UNSET"/* — short-circuit guarantees non-execution while the static analyzer still sees it) and deliberately not run: the static evidence shows the whole decision, whereas a probe samples one input. The right call.

    2. Scope — what the native analyzer does and does not cover [VERIFIED]

    Fires on rm/rmdir when the target resolves to: filesystem root; bare * or any path ending /*; any top-level directory (dirname==="/"); home; regex-matched critical system paths; the working directory, an additional working directory, or any ancestor thereof; or a statically unresolvable target (cd-then-relative-glob, possibly-empty expansion like rm -rf $UNSET/*, unenumerable globs, >64 command substitutions).

    Does not fire on rm -rf of a subdirectory inside the workspace.

    3. Therefore AC-6: delete the rm half — and the entanglement dissolves

    Line up native coverage against what :108 actually blocks — rm -rf /, rm -rf ~, rm -rf $HOME. That is exactly the ground the analyzer already holds. It is also precisely the six-string set the earlier research proposed as the evidence-supported minimum. So the hook's rm half is pure redundancy, and it carries the worst false-positive tax in the file: rm -rf / substring-matches every absolute path, which is why it blocks worktree teardown and blocked three separate commands during the investigations — including a read-only git log -S history query that executed nothing.

    Deleting it loses nothing that exists today. The in-workspace gap (§2) is a capability we never had — a possible follow-up, not a regression.

    This dissolves the AC-2/AC-3 conflict rather than requiring a workaround. An agent identified that the two ACs pull in opposite directions: AC-2 wants gh issue list && rm -rf / to block; AC-3 wants gh issue create --body "...rm -rf /..." to be allowed without the carve-out. With the rm half deleted: AC-2's row drops (no hook guard left to bypass — the native analyzer holds that ground, under bypass mode too), and AC-3's row is satisfied trivially. No rm anchoring needed at all. AC-6 stops being the blocker and becomes the enabler.

    The sudo half is not natively covered → keep it, anchored per AC-4.

    4. Version floor — the mechanism does not exist [VERIFIED]

    Decision was to pair the deletion with a minimum Claude Code version. That cannot be declared. Checked against the official plugin reference and marketplace guide:

    • No field exists in plugin.json or marketplace.json for a minimum/compatible host version. version is the plugin's own version (update cache key); dependencies resolves only against other marketplace plugins via {plugin}--v{version} git tags and cannot name Claude Code.
    • Unrecognized top-level fields are silently ignored at load time — an invented engines field would be inert, neither blocking nor warning.
    • No install-time gating on host version exists.
    • Hooks receive no version signal — no CLAUDE_CODE_VERSION env var, and the stdin payload carries none. The only route is shelling out to claude --version, which resolves whatever is on PATH rather than the running session's binary — a failure mode this repo has already recorded (dual node prefix / npx version skew). It also costs a spawn on every hook fire.

    So the floor is documentation-only, and the residual gap is accepted rather than closed. On Claude Code <2.1.208, command-substitution forms (echo "$(rm -rf ~)") were not caught in bypass mode, and the hook's substring match would have caught them. That is the only version-dependent argument for keeping the rm half, and it does not outweigh a guard that blocks every absolute-path delete. If real enforcement is wanted later, the credible mechanism is a behavior probe, not a version check — separate issue.

    [UNRESOLVED] — version floor precision. The carve-out is verified present in 2.1.208, 2.1.209, 2.1.210 (all three local binaries). The base circuit breaker predates 2.1.208 and cannot be pinned — older binaries aren't installed. Settling probe: grep -a -c 'startsWith("Dangerous rm operation")' across older releases.

    Source conflict, flagged not papered over: the docs carry min-version: 2.1.208 for the command-substitution extension; CHANGELOG.md lists the same entry under 2.1.210. Binary evidence supports the docs (the code is demonstrably in 2.1.208), so treat 2.1.208 as the floor and the changelog entry as late-published. (An agent initially reported 2.1.208 from the changelog; that attribution was wrong on a re-fetch — hence surfacing the conflict rather than a single clean number.)

    5. Corrections to this issue's own text [VERIFIED]

    AC-2's "All 10" needs amending — and the table undercounts what's broken. There are exactly 10 carve-out sites, but no doubling: AC-2 counts sites, the body's table counts only the five guards it probed. The other five are untested and bypassable identically:

    Line Guard In the table?
    :87 secret-file + credential-dir read (one if wrapping two guards, :89/:94) no
    :108 destructive: sudo and rm yes
    :115 deployment yes
    :123 force push yes
    :134 git reset yes
    :175 gh workflow run yes
    :234 git-commit secret scan no
    :267 no-changes guard no
    :295 worktree validation (warn-only, never exits 2) no
    :307 conventional-commit validation no

    Four of the five unexamined sites gate git commit. :87 is the only skip wrapping two guards. :295 is warn-only, so removing its carve-out has no blocking consequence.

    AC-4 is not independent — sudo and rm are alternation branches of one regex on :108 behind one carve-out feeding one shared message. AC-4 belongs grouped with the :108 work. (This is also why :109 cannot distinguish a sudo match from an rm -rf ~ match — the mechanism behind AC-1's "unclassifiable" claim.)

    Two things AC-1 needs that aren't in its text:

    1. HOOK_LOG has no rotation. Only TIMING_LOG rotates (:73-78, tail-500 at 1000 lines). AC-1 makes every entry carry a full command string — unbounded growth without adding rotation on the same pattern.
    2. Redaction. $TOOL_INPUT is the whole bash command and routinely contains tokens, --body prose, env assignments. check_secrets (:188-205) already exists and should redact before writing.

    Independent reproduction of every bypass against the real hook: all four ALLOWED (git push --force, vercel deploy --prod, gh workflow run, git reset --hard), controls BLOCKED, plus all three AC-4 false positives and the cd-prefix bug. The rm -fr / false-negative table was not verified and remains this issue's unverified claim — worth checking before relying on it, though AC-6's deletion makes it moot for rm.

    Also budget for: splitting :108's shared message breaks the existing test at :279, which asserts /HOOK_BLOCKED: Destructive system command/ for a sudo rm payload. On-plan given AC-1, but expect the churn.

    md5 d0dcff9d8ba8056ef5ac8cd2bcf7858d across all three tracked copies and the dist artifact. dist confirmed gitignored (.gitignore:5), git ls-files dist empty, regenerated by npm run prepare:marketplace — only the three tracked copies matter for AC-9.


    Revised Acceptance Criteria (v2)

    Supersedes the previous list. AC-5 is answered (§1), so nothing here is blocked. The former AC-6 becomes AC-2 below — it is now the enabler, not the blocker.

    • AC-1: Delete the rm alternation (rm -rf /|rm -rf ~|rm -rf \$HOME) from :108 entirely. Redundant with Claude Code's native analyzer, which [VERIFIED] still fires under bypassPermissions and already covers root / top-level dirs / home / workspace-ancestors / unresolvable targets. Do this first — AC-3 and AC-4's rm rows resolve for free.
    • AC-2: :108 becomes a standalone sudo guard with its own distinct HOOK_BLOCKED message, matching only at a command-word position. Test cases: echo 'never use sudo here', git commit -m "docs: sudo policy", and grep -r sudoku src/ are allowed; sudo rm -rf /var/lib blocks. (A plausible-looking anchor was run during research and still blocked the echo case — this needs tests, not eyeballing.)
    • AC-3: All 10 ^gh (issue|pr) carve-outs removed — including the five the original table never probed (:87, :234, :267, :295, :307). No guard bypassable by prefixing a real gh issue/gh pr command. One test per blocking guard: gh issue list && <payload> blocks (git push --force, vercel deploy --prod, git reset --hard origin/main, gh workflow run, sudo …). :295 is warn-only — assert no exit 2 regression rather than a block.
    • AC-4: The bug(hooks): pre-tool.sh regexes match inside quoted gh issue/pr body content (line 108 force-push, line 248 git-commit) #564/bug(hooks): pre-tool.sh regexes for destructive/deployment/reset/workflow commands also match inside quoted gh body content #570 false positives stay fixed without the carve-out: gh issue create --body "...git push --force..." and cd <dir> && gh issue create --title "...git push --force..." are both allowed. (The second fails today — the cd-prefix bug that blocked the filing of this issue and its assessment.)
    • AC-5: pre-tool.sh logs the offending command text + the specific rule that fired for every HOOK_BLOCKED category (16 tee -a "$HOOK_LOG" sites: :90, :95, :102, :109, :116, :124, :168, :176, :243, :254, :284, :345, :380, :409, :440, :448). Must include: (a) redaction via the existing check_secrets (:188-205) — $TOOL_INPUT carries tokens; (b) rotation on the TIMING_LOG pattern (:73-78) — entries now carry full commands; (c) a single non-purged sink — today :38-47 bifurcates between $CLAUDE_PLUGIN_DATA/logs and $TMPDIR, which macOS purges. Suggest $CLAUDE_PLUGIN_DATA/logs/ with a repo-local .sequant/logs/ fallback.
    • AC-6: The miscalibrated tests at __tests__/pre-tool-hook.integration.test.ts:276-300 are corrected to exercise the anchored prefix (gh issue list && …). Today they use echo gh issue && …, which cannot match ^gh (issue|pr) — the skip never fires and they pass for the wrong reason. Non-anchored cases retained. The describe.each(HOOK_COPIES) harness (:65, list :22-32) already parametrizes over all three copies, so each case is ~6 lines.
    • AC-7: Regression corpus is real blocked commands from AC-5's log where available. Note the ordering reality: AC-5's log has no history yet, so the first PR necessarily ships table-derived cases — that is acceptable because each was reproduced against the real hook, unlike the synthetic fixtures that produced the 0-FP illusion. Backfill from real data once the log accumulates.
    • AC-8: All three tracked pre-tool.sh copies updated and verified byte-identical (templates/hooks/, hooks/, .claude/hooks/). dist is a build artifact — regenerate, don't edit.
    • AC-9: Hook latency does not regress materially (runs on every tool call). Deleting the rm alternation should improve it.
    • AC-10: Document a Claude Code >= 2.1.208 floor in the README. [VERIFIED] no declarative mechanism exists — no manifest field, unrecognized fields are silently ignored, no install-time gating, no version env var in hooks, and claude --version resolves off PATH rather than the running binary (a skew this repo has already hit). This is documentation, not enforcement: the <2.1.208 command-substitution gap is accepted. If enforcement is wanted, the credible route is a behavior probe, not a version check — file separately.

    Out of scope / follow-ups

    • In-workspace destruction (rm -rf of the worktree, .git, project files) is not natively covered (§2) and is not covered today either. A genuine gap, but a new capability — separate issue if wanted.
    • The argv-level bash parser and the ~25-string block-list stay dead. §1 confirms the native analyzer already does this properly, with a real AST and workspace context a hook cannot see.
    • rm -fr / false negatives — unverified, and moot for rm under AC-1.

    Investigation: 3 agents + hand-verification of the bundle carve-out, the shared :108 expression, the three md5s, and the docs. Two agent claims were corrected on verification (a changelog attribution, and a "5 guards = 10 sites" doubling theory). The headline finding — that the string which framed this entire question described rules, not modes — came from reading the code, not the strings.

  5. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    Re-assessment: CLARIFY → PROCEED

    Supersedes my earlier CLARIFY. AC-5 is answered above, so the gate I raised is gone — and its answer makes the issue smaller, not bigger.

    Re-verified the load-bearing claims against the checkout rather than taking the comment's word:

    • 10 carve-out sites in templates/hooks/pre-tool.sh — confirmed, including the five the original table never probed (:87, :234, :267, :295, :307). Four of those five gate git commit.
    • :108 is one regex — 'sudo|rm -rf /|rm -rf ~|rm -rf \$HOME' behind one carve-out feeding one shared message. Confirms the v2 ACs' point that the sudo and rm halves are not independent work items.

    Workflow: exec → qa with quality loop

    npx sequant run 763 -Q --phases exec,qa
    

    Spec is skipped deliberately: the investigation above already did the spec work — dependency-ordered ACs naming exact lines, the tests to fix, and the log sinks. A spec phase would re-derive settled ground and risk contradicting it.

    Order: none. This is the only issue in the current batch (#769/#767/#766/#763/#761) with no file overlap — it touches the three hook copies and pre-tool-hook.integration.test.ts and nothing else. It can run first and in parallel with the rest.

    ⚠ AC-1 first — deleting the rm alternation resolves AC-3/AC-4's rm rows for free, so doing it out of order creates work that AC-1 then deletes.
    ⚠ AC-5's redaction and rotation sub-requirements are easy to drop; both are load-bearing ($TOOL_INPUT carries tokens, and HOOK_LOG has no rotation today).

  6. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (10 ACs, ~5 directories)

    AC Quality Check

    Strong AC set overall — most carry explicit, reproducible test payloads (gh issue list && <payload> blocks; cd <dir> && gh issue create ... allowed) and cite exact line numbers. Notes:

    • AC-9 ("latency does not regress materially") is the only unmeasurable AC — no threshold. Recommend an operational bar: capture 20-run mean of bash pre-tool.sh on a no-op payload before/after and assert the delta is within noise (deleting the destructive alternation should make it net-neutral or faster). Warning-only; does not block.
    • AC-5 is large (three sub-requirements: redaction, rotation, single sink across 16 sites). It is one cohesive logging change, but flag it as the highest-churn AC.
    • All other ACs are measurable with the payloads already written into the body.

    Scope Assessment

    Non-Goals: Present and unusually well-drawn (the "Out of scope / follow-ups" + "Unresolved" sections). Explicitly out: in-workspace destruction guard, the argv-level bash parser + ~25-string block-list, the -fr false-negatives, and version-floor enforcement.

    Metric Value Status
    Feature count 1 (harden pre-tool.sh guard layer) OK
    AC items 10 RED (threshold 9)
    Directory spread ~5 (templates/hooks/, hooks/, .claude/hooks/, __tests__/, README) WARN
    File estimate ~5 tracked (3 hook copies byte-identical + 1 test + 1 doc) OK

    Verdict: WARNING (SCOPE_WARNING) — AC count trips red, but the work is genuinely one cohesive change to a single script (mirrored 3x) plus its test and a doc line. Not a split candidate. Quality loop auto-enabled by the warning, which is appropriate for a fail-open guard.


    Acceptance Criteria

    AC-1: Delete the destructive alternation from :108

    Verification: Integration Test
    Scenario: Given the hook, When a legitimate absolute-path worktree/scratch delete is passed, Then it is allowed (no longer substring-blocked by the / byte); catastrophic deletes are left to Claude Code's native analyzer.
    Assumptions: Native analyzer fires under bypassPermissions — [VERIFIED] in the AC-5 comment. This is the enabler; do it first.

    AC-2: :108 becomes a standalone sudo guard, command-word position only

    Verification: Integration Test
    Scenario: Given the hook, When echo 'never use sudo here' / git commit -m "docs: sudo policy" / grep -r sudoku src/, Then allowed; When sudo <destructive>, Then blocks with a distinct HOOK_BLOCKED: sudo message.
    Assumptions: Needs command-word matching, not substring — a naive anchor was empirically shown to still block the echo case. Must be tested, not eyeballed.

    AC-3: Remove all 10 ^gh (issue|pr) carve-outs (incl. the 5 never probed: :87, :234, :267, :295, :307)

    Verification: Integration Test
    Scenario: Given the hook, When gh issue list && <payload> for each of force-push, vercel deploy --prod, git reset --hard origin/main, gh workflow run, sudo ..., Then blocks. :295 (worktree warn-only) asserts no exit-2 regression, not a block.
    Assumptions: Removal must be paired with command-word matching (see AC-4 / Design Review) or the #564 false positives return.

    AC-4: #564/#570 false positives stay fixed without the carve-out

    Verification: Integration Test
    Scenario: Given the hook, When gh issue create --body "...<force-push text>..." and cd <dir> && gh issue create --title "...<force-push text>...", Then both allowed. (The cd-prefix case fails today.)
    Assumptions: This is the load-bearing correctness pair — it proves the fix without reintroducing the bug the carve-outs papered over.

    AC-5: Log offending command text + the specific rule that fired, for every HOOK_BLOCKED (16 tee sites)

    Verification: Integration + Unit Test
    Scenario: Given a blocked command, When any guard fires, Then the log line carries the command text and rule id, (a) redacted via existing check_secrets (:188-205), (b) rotated on the TIMING_LOG pattern (:73-78), (c) written to a single non-purged sink ($CLAUDE_PLUGIN_DATA/logs/ with .sequant/logs/ fallback).
    Assumptions: check_secrets currently only matches 6 token shapes — confirm it covers what $TOOL_INPUT realistically leaks, or the redaction is theatre.

    AC-6: Correct the miscalibrated tests at :276-300 to exercise the anchored prefix

    Verification: Unit Test (test-of-tests)
    Scenario: Replace echo gh issue && ... (which never matches ^gh (issue|pr) ) with gh issue list && .... Retain non-anchored cases. Expect churn: splitting :108's shared message breaks :279's /Destructive system command/ assertion.
    Assumptions: describe.each(HOOK_COPIES) already parametrizes all 3 copies — each case ~6 lines.

    AC-7: Regression corpus prefers real blocked commands from AC-5's log

    Verification: Integration Test
    Scenario: First PR ships table-derived cases (each reproduced against the real hook); backfill from real log data once it accumulates. Log the ordering-reality caveat.
    Assumptions: Acceptable because each case is real-hook-reproduced, unlike the synthetic fixtures that produced the 0-FP illusion.

    AC-8: All 3 tracked copies byte-identical; dist/ regenerated not edited

    Verification: Unit Test + Manual
    Scenario: md5 -q templates/hooks/pre-tool.sh hooks/pre-tool.sh .claude/hooks/pre-tool.sh gives three equal hashes (currently d0dcff9...); npm run prepare:marketplace regenerates dist/marketplace/....
    Assumptions: There is already a byte-identity assertion path via the test harness; keep it green.

    AC-9: Hook latency does not regress materially

    Verification: Manual / benchmark
    Scenario: 20-run mean of the hook on a no-op payload, before vs after. Deleting the destructive alternation should be net-neutral or faster.
    Assumptions: Segment-splitting adds a little cost; keep it in pure bash, no subshell fan-out per guard.

    AC-10: Document a Claude Code >= 2.1.208 floor in the README

    Verification: Manual (docs)
    Scenario: README gains a "Requires Claude Code >= 2.1.208" note explaining it's documentation, not enforcement (no declarative manifest mechanism exists — [VERIFIED]), and that the <2.1.208 command-substitution gap is accepted.
    Assumptions: Treat 2.1.208 as the floor (binary evidence over the changelog's 2.1.210 listing).


    Implementation Plan

    Phase 1 — Guard rewrite (AC-1, AC-2, AC-3, AC-4) — the core

    1. Add a small pure-bash helper command_word_matches <regex> that splits $TOOL_INPUT into segments on ;, &&, ||, |, newline (quote-aware), skips leading env-assignments and cd ..., extracts each segment's argv[0], and returns 0 iff a segment's command word (and, where relevant, its args) match. This is the middle ground the issue points at — not the full argv parser/block-list (those stay dead per the banner), but enough to key off command-word position.
    2. :108 — delete the destructive alternation (AC-1); reduce to a sudo guard using command_word_matches with its own HOOK_BLOCKED: sudo message (AC-2).
    3. Convert the four remaining catastrophic guards (deployment :115, force-push :123, git-reset :134, gh-workflow :175) and the four git-commit guards (:234, :267, :295, :307) plus the secrets reader guard (:87) to command_word_matches, and delete all 10 ! grep -qE '^gh (issue|pr) ' carve-outs (AC-3).
      • This is why AC-4 falls out for free: in gh issue create --body "<force-push text>" the only segment's argv[0] is gh; the payload is an argument, never a command word, so allowed. In gh issue list && git push --force the second segment's word is git push --force, so blocked.
    4. Verify :295 stays warn-only (no exit 2).

    Phase 2 — Blocked-command logging (AC-5)

    1. Introduce a log_block <rule-id> <message> helper that appends command + rule to a single sink ($CLAUDE_PLUGIN_DATA/logs/claude-hook.log, .sequant/logs/ fallback), passing the command through check_secrets-based redaction before write, and applies the TIMING_LOG rotation pattern to HOOK_LOG.
    2. Route all 16 tee -a "$HOOK_LOG" sites through it. (Move check_secrets def above :108 if ordering requires.)

    Phase 3 — Tests (AC-6, AC-7)

    1. Rewrite :276-300 to anchored gh issue list && ...; fix the :279 message assertion for the new split sudo message; add the five anchored-bypass rows (AC-3) and both AC-4 allow-cases (incl. cd-prefix) across describe.each(HOOK_COPIES).
    2. Add the AC-1 allow-cases (worktree/scratch absolute-path deletes now allowed) and a redaction unit test for AC-5. Encode the table rows as failing tests first.

    Phase 4 — Propagate, doc, benchmark (AC-8, AC-9, AC-10)

    1. Apply identical edits to all three copies (edit each independently — see below), assert equal md5, run npm run prepare:marketplace.
    2. Add README >= 2.1.208 note (AC-10). Capture before/after latency numbers for AC-9 in the PR.

    Parallelization: Phases are mostly sequential (2 depends on 1's helper placement; 3 depends on 1+2). Phase 4 doc (AC-10) is independent and can run anytime.


    Rule Touchpoints

    The behavior rule here ("guards must key off command-word position; the skip is deleted") lives in a script mirrored 3x. The touchpoints are the three copies — already governed by AC-8's byte-identity requirement, and by the test harness's describe.each(HOOK_COPIES). No hidden runtime/skill duplicate exists (these are shell hooks, excluded from the TS layer per project_layer_boundaries).

    Rule Touchpoint Note
    Guard logic templates/hooks/pre-tool.sh canonical
    Guard logic hooks/pre-tool.sh must match byte-for-byte
    Guard logic .claude/hooks/pre-tool.sh must match byte-for-byte

    Design Review

    1. Where does this logic belong? In pre-tool.sh itself — bash, for latency/portability (project_layer_boundaries). The correctness primitive is a single command_word_matches helper reused by every guard, so the fix is centralized rather than 10 ad-hoc regex tweaks.
    2. What's the simplest correct approach? Command-word (segment argv[0]) matching — strictly less than the rejected full argv parser + block-list, strictly more than substring grep. It simultaneously (a) fixes the anchored bypass, (b) keeps bug(hooks): pre-tool.sh regexes match inside quoted gh issue/pr body content (line 108 force-push, line 248 git-commit) #564/bug(hooks): pre-tool.sh regexes for destructive/deployment/reset/workflow commands also match inside quoted gh body content #570 false positives fixed, (c) lets the carve-out be deleted rather than re-patched. Rejected: another regex patch (keeps trading permissive vs strict per the issue), and the full parser (banner says the native analyzer already does it better).
    3. What existing pattern does this follow? The cd <dir> && git commit target-extraction already present at :270-274 establishes that segment/prefix parsing in this hook is an accepted idiom; command_word_matches generalizes it. Redaction reuses existing check_secrets (:188-205); rotation reuses the :73-78 pattern.
    4. What would a senior reviewer challenge? "Quote-aware splitting in bash fails open if subtly wrong — this is a guard." Mitigation: encode every table row (both directions) as a test first, drive the real hook end-to-end via the existing harness, and keep the splitter minimal (operators + quote state, no glob/expansion emulation). Second challenge: "why not just delete the carve-out?" — because that regresses bug(hooks): pre-tool.sh regexes match inside quoted gh issue/pr body content (line 108 force-push, line 248 git-commit) #564; the command-word matcher is what makes deletion safe. Surface that pairing explicitly in the PR.

    Feature Quality Planning

    All standard checks pass. Notable items:

    • Fail-open risk (security-adjacent): the splitter is the one place a bug silently disables a guard. Warrants the security-review phase and test-first discipline.
    • Redaction completeness (AC-5a): check_secrets matches only 6 token shapes; $TOOL_INPUT may carry others. Confirm scope or note the residual as accepted.
    • Cross-copy drift: the perennial 3-copy hazard; mitigated by AC-8 + describe.each, but read each copy independently before editing (feedback_read_each_mirrored_file).
    • Message-split churn (AC-6): splitting :108 breaks the :279 assertion — expected, not a surprise regression.

    Derived ACs

    None required — the body's Non-Goals already fence the tempting scope creep (in-workspace guard, full parser, version enforcement).


    Open Questions

    1. Quote-aware splitting depth — Recommendation: handle single/double quotes and the five operators; do not emulate command substitution, globbing, or backslash-escapes. Impact if wrong: a crafted quoted string could hide an operator and dodge a guard — acceptable for an accident-prevention (not adversarial) layer, per the issue's own severity framing. Flag the boundary in a code comment.
    2. AC-9 threshold — Recommendation: informal 20-run before/after mean, assert no material regression; don't gate CI on wall-clock. Impact: over-formalizing latency testing wastes effort on a guard that just lost its most expensive regex.
    3. AC-5 sink fallback ordering — Recommendation: $CLAUDE_PLUGIN_DATA/logs/ first, .sequant/logs/ fallback (matches existing _LOG_DIR logic at :38-44; only the last-resort $TMPDIR purge-prone branch changes). Impact: getting this wrong reintroduces the macOS-purge data loss AC-5c calls out.

    Recommended Workflow

    Phases: spec -> exec -> security-review -> qa
    Quality Loop: enabled (SCOPE_WARNING + fail-open guard)
    Reasoning: Pure bash/CLI change, no UI, so no test (browser) phase. security-review added because the splitter is a fail-open guardrail whose subtle bugs disable protection. No testgen — the ACs are Integration-Test-verified against an existing bespoke hook harness (describe.each(HOOK_COPIES)), not new unit modules that benefit from stubbed structure; hand-authoring the table-row tests (test-first, per the issue) is the right move over generated stubs.


    Label Review

    Current: bug
    Recommended: bug, complex (10 ACs, fail-open guard rewrite + logging + docs), security (guard hardening)
    Reason: complex reflects the real AC count and cross-copy/test surface and will auto-enable the quality loop consistently; security flags the guardrail nature for the added security-review phase.
    Quality Loop: Will auto-enable (SCOPE_WARNING and the complex label both trigger it) — desired here.

    gh issue edit 763 --add-label complex --add-label security

  7. added
    planned
    on Jul 16, 2026
  8. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    Progress Update — /exec complete

    PR: #771 (Closes #763) · branch feature/763-fix-hooks-gh-issue-pr-prefix-skip-disarms-all-5-pr

    AC Coverage

    AC Description Status
    AC-1 Delete the rm alternation from :108 ✅ Implemented
    AC-2 :108 → command-word sudo guard, distinct message ✅ Implemented
    AC-3 All 10 ^gh (issue|pr) carve-outs removed; anchored bypass blocks ✅ Implemented
    AC-4 False positives fixed without carve-out, incl. cd-prefix ✅ Implemented
    AC-5 Log command + rule per block; redaction + rotation + single sink ✅ Implemented
    AC-6 Correct the miscalibrated echo gh issue && … tests ✅ Implemented
    AC-7 Regression corpus = real-hook-reproduced table rows ✅ Implemented
    AC-8 Three copies byte-identical; dist/ regenerated ✅ Implemented
    AC-9 No material latency regression ✅ 65ms new vs 84ms old
    AC-10 Document Claude Code ≥ 2.1.208 in README ✅ Implemented

    Approach

    The ^gh (issue|pr) carve-outs are removed entirely; guards now match against the command words of each shell segment (split on ; && || | + newline, quotes stripped by a small pure-awk splitter). Body text carried inside a quoted --body/--title is never a command word, so it can't trip a guard — and a real command chained after an allowed one is its own segment and still blocks. This is the middle-ground the issue pointed at, not the full argv parser (which stays dead per the banner). The segment list is computed once per invocation and reused across all guards, so latency is net-neutral-to-faster.

    Key files changed

    • templates/hooks/pre-tool.sh, hooks/pre-tool.sh, .claude/hooks/pre-tool.sh — byte-identical (md5 ef380228…)
    • __tests__/pre-tool-hook.integration.test.ts — corrected miscalibrated tests + new #763 block encoding the full evidence table across all 3 copies
    • README.md — Claude Code ≥ 2.1.208 recommendation
    • CHANGELOG.md — ### Fixed entry
    • dist/marketplace/.../pre-tool.sh — regenerated (gitignored artifact)

    Quality Plan Alignment

    Dimension Status
    Fail-open risk (splitter) ✅ test-first; every evidence-table row driven through the real hook, both directions
    Redaction completeness (AC-5a) ✅ reuses the 6 check_secrets shapes; residual (other token formats) accepted, matching the existing detector's scope
    Cross-copy drift ✅ AC-8 md5 identity + describe.each over all 3 copies
    Message-split churn (AC-6) ✅ the :279 / AC-5 sudo assertions updated as expected

    Checks

    Notes / follow-ups

    • Recommended next phases per spec: security-review (fail-open splitter) then /qa.
    • Out of scope (per issue): in-workspace destruction guard, full argv parser + block-list, rm -fr false-negatives, version-floor enforcement.
  9. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #763

    Reviewed inline (the meaningful diff is one hook file mirrored 3× + its test; per repo guidance, worktree sub-agents are skipped for a diff this focused). Every evidence-table row from the issue body was re-run against the real hook, plus adversarial fail-open probes.

    AC Coverage

    AC Description Status Notes
    AC-1 Delete rm alternation from :108 ✅ MET Alternation gone; rm -rf /tmp/build/x and absolute worktree deletes now allowed (tests + probe).
    AC-2 :108 → command-word sudo guard, distinct message ✅ MET echo 'never sudo', grep -r sudoku, git commit -m "…sudo…" allowed; sudo … blocks as HOOK_BLOCKED: sudo command. FOO=bar sudo … still blocks (env-prefix stripped).
    AC-3 All 10 ^gh (issue|pr) carve-outs removed; anchored bypass blocks ✅ MET grep -c for the carve-out idiom = 0. gh issue list && <payload> blocks for force-push / deploy / reset / workflow / sudo across ;, |, ||, newline separators. :295 warn-only asserts no exit-2.
    AC-4 False positives fixed without carve-out, incl. cd-prefix ✅ MET Body-text and cd <dir> && gh issue create … both allowed (tests + probe).
    AC-5 Log command + rule per block; redaction + rotation + single sink ✅ MET 0 tee -a "$HOOK_LOG" remain; 16 distinct log_block "<rule>" sites. Redaction mirrors the 6 check_secrets shapes (token → [REDACTED], verified); rotate_log shared with TIMING_LOG; sink = $CLAUDE_PLUGIN_DATA/logs → .sequant/logs fallback.
    AC-6 Correct miscalibrated echo gh issue && … tests ✅ MET Rewritten to anchored gh issue list && …; the :279/AC-5 sudo-message churn updated as the spec predicted. Non-anchored cases retained.
    AC-7 Regression corpus = real-hook-reproduced rows ✅ MET Every table row is driven end-to-end through the real hook via describe.each(HOOK_COPIES).
    AC-8 Three copies byte-identical; dist/ regenerated ✅ MET md5 ef380228… × 3; dist/marketplace/.../pre-tool.sh regenerated & matching (gitignored).
    AC-9 No material latency regression ✅ MET 20-run mean 65ms new vs 84ms old — net faster (one awk pass replaces the deleted rm regex; segments computed once and reused).
    AC-10 Document Claude Code ≥ 2.1.208 in README ✅ MET Prerequisites note present; correctly framed as a recommendation, not enforcement.

    Coverage: 10/10 AC items fully met.


    CI Status

    Check State Impact
    build (22.x) SUCCESS ✅ MET
    typecheck SUCCESS ✅ MET
    validate-skills SUCCESS ✅ MET
    Hooks Validation SUCCESS ✅ MET
    validate-plugin / Plugin Structure / node-floor-guard / Setup Dir SUCCESS ✅ MET

    CI Summary: 8 passed, 0 pending, 0 failed. (Diff is not markdown-only; no relaxation applied — all checks resolved on their own.)


    Quality Plan Verification

    Dimension Status
    Fail-open risk (splitter) ✅ Complete — test-first; 18 adversarial fail-open probes (separators, env-prefix, command substitution, extra whitespace) all block correctly
    Redaction completeness (AC-5a) ✅ Complete — reuses the 6 check_secrets shapes; other token formats unmasked (matches the existing detector's scope; residual accepted)
    Cross-copy drift ✅ Complete — md5 identity + describe.each over all 3 copies
    Message-split churn (AC-6) ✅ Complete — sudo-message assertions updated as expected

    Quality Plan Status: Complete


    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 6 (3 hook copies + test + README + CHANGELOG) OK
    Lines added +792 -
    Lines deleted -182 -

    Test Coverage Analysis

    Changed File Tier Has Tests?
    templates/hooks/pre-tool.sh Standard (guard script) ✅ pre-tool-hook.integration.test.ts (135 tests, parametrized ×3)
    hooks/pre-tool.sh Standard ✅ same (parametrized)
    .claude/hooks/pre-tool.sh Standard ✅ same (parametrized)
    __tests__/…test.ts Test — (is the test)
    README.md / CHANGELOG.md Optional (docs) —

    Coverage: all three hook copies exercised end-to-end. 135 passed locally + green in CI.


    Code Review

    Strengths:

    • Root cause dissolved, not re-patched — the carve-outs are gone rather than tuned, and AC-4 falls out for free from command-word matching.
    • Splitter is deliberately scoped (quotes + 5 operators, no command-substitution emulation) and the fail-open boundary is documented in-code, consistent with the issue's "accident-prevention, not security-boundary" framing.
    • Segments computed once and reused (seg_match), so 13 guards cost one awk pass — latency improved.
    • Guard bodies that need the raw command (commit-message extraction, git-reset state checks) still read $TOOL_INPUT; only the gate uses segments — a clean separation that avoids breaking message parsing.

    Issues: None blocking.

    Observations (non-blocking):

    • The .sequant/logs fallback sink (AC-5c, per spec) writes into the repo tree. .sequant/ is gitignored by sequant convention and the primary sink is $CLAUDE_PLUGIN_DATA in plugin mode, so in practice this is inert — but in a non-plugin run inside a repo that has not gitignored .sequant/, the always-written timing log would show in git status and soften the no-changes guard. This is exactly what AC-5c prescribed (non-purged corpus over $TMPDIR); flagging as a documentation/robustness follow-up, not an AC gap.

    Test Quality Review

    Category Status Notes
    Behavior vs Implementation ✅ OK Asserts exit code + HOOK_BLOCKED message, not internals
    Coverage Depth ✅ OK Both directions (anchored bypass blocks / body-text + cd-prefix allow), redaction, warn-only no-exit-2
    Mock Hygiene ✅ OK No mocks — drives the real hook via spawnSync; isolated tmp git repos + isolated CLAUDE_PLUGIN_DATA log home
    Test Reliability ✅ OK Deterministic; runtime-built token avoids committing a secret-shaped literal

    Risk Assessment

    • Likely failure mode: A shell construct the splitter doesn't model (backslash-escaped quote, an unterminated quote swallowing a trailing command) could fail open. In practice those are shell syntax errors that wouldn't execute, and the class is documented as out of scope for a non-adversarial guard. Command substitution ($(git push --force)) — which does execute — correctly blocks (probed).
    • Not tested: Backslash-escape edge cases (intentionally out of scope). The .sequant/logs no-changes-guard interaction in a non-gitignored repo is not covered by a test.
    • Sibling sites considered: cross-file — the carve-out/regex-guard pattern existed only in the three mirrored pre-tool.sh copies, all fixed identically (md5 equal). The relay hook is a different script without these guards; no other files carry the pattern.
    • Sibling-line audit: all 10 intra-file carve-out sites (:87,:108,:115,:123,:134,:175,:234,:267,:295,:307) audited and removed; grep confirms 0 remain.

    Adversarial Re-Read

    Findings: No blocking gaps. (1) Every verbatim evidence-table fixture from the issue body was re-run against the real hook and behaves as the AC claims. (2) The exec "evidence" (65ms vs 84ms, 135 passing tests) is genuine post-fix validation, not a pre-fix repro. (3) Process state inspected: working tree clean, branch 0 behind origin/main, single commit, dist artifact regenerated. (4) Sibling sites cited explicitly above (cross-file = 3 hook copies; intra-file = 10 carve-out sites). (5) Non-Goals held: no argv parser/block-list, no in-workspace destruction guard, no version-floor enforcement — the splitter is the middle ground the issue endorsed. One non-blocking observation surfaced (the .sequant/logs sink interaction), recorded above.

    Status: Clean


    Verdict: READY_FOR_MERGE

    All 10 ACs are MET and verified literally against the implementation; CI is fully green; 135 tests pass across all three hook copies; adversarial fail-open probing found no bypass in the realistic accident space. The one observation (AC-5c .sequant/logs sink) is per-spec and low-risk, worth a follow-up note rather than a change here.

    Documentation

    Next Steps

    1. Optional per spec: run /security-review 763 (fail-open guardrail) as an extra pass — QA's adversarial probing already covered the realistic surface.
    2. Merge PR fix(#763): segment-aware pre-tool guards; drop gh-prefix carve-outs #771.
    3. Follow-up (non-blocking): consider documenting or hardening the .sequant/logs fallback so the always-written timing log can't soften the no-changes guard in a repo that hasn't gitignored .sequant/.
  10. added
    ready-for-review
    on Jul 16, 2026
  11. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #763 (PR #771)

    Reviewed inline (not via agents) — 3 byte-identical hook copies mean the unique diff is ~510 lines. Every evidence-table row in this issue was independently re-driven through the real hook, both copies, rather than trusted from the PR body.

    The core of this PR is right, and the central claim holds up under adversarial probing: the segment splitter dissolves the bypass class rather than re-patching it. AC-5(c) is not met, and it took the timing instrumentation down with it.

    AC Coverage

    AC Description Status Evidence
    AC-1 Delete the rm alternation from :108 MET Gone. Absolute-path deletes re-verified allowed: worktree path, /tmp/scratch/build, ~/Library/Caches/my-app.
    AC-2 :108 → command-word privilege-escalation guard, distinct message MET All 4 listed cases verified (echo '…', git commit -m "docs: …", grep -r sudoku src/ allowed; real invocation blocks). See Finding 3 — coverage narrowed vs main.
    AC-3 All 10 carve-outs removed; anchored bypass blocks MET Only a comment now references the old idiom. All 5 bypasses re-verified blocking — incl. git reset --hard against a dirty fixture (it correctly no-ops on a clean tree; the PR's test got this right).
    AC-4 FPs stay fixed without the carve-out, incl. cd-prefix MET Both allowed. Verified live 3× this session — see below.
    AC-5 Log command + rule for every block; redaction + rotation + single sink NOT MET (a) redaction ✅ (b) rotation ✅ 16/16 block sites call log_block ✅ — but (c) fails, see Findings 1–2.
    AC-6 Correct the miscalibrated echo gh issue && … tests MET Rewritten to the anchored shape; non-anchored retained; the :279 message churn handled as predicted.
    AC-7 Corpus = real-hook-reproduced rows MET Independently confirmed — I reproduced every row myself.
    AC-8 Three copies byte-identical MET md5 ef380228dff68140aa6256759ef0b466 × 3.
    AC-9 No material latency regression MET Measured 69.6ms new vs 90.2ms old (n=30) — an improvement, and it independently reproduces the PR's 65/84 claim.
    AC-10 Document ≥ 2.1.208 floor in README MET Honest about being a recommendation, not enforcement.

    Coverage: 9/10 met. Verdict is gated by AC-5.


    Finding 1 — .sequant/logs is cwd-relative, not repo-local (AC-5c) ❌

    pre-tool.sh:46 sets _LOG_DIR=".sequant/logs" and :48 runs mkdir -p on every tool call. A relative path resolves against the hook's cwd, not the repo root — so this is not "a single sink," it's one sink per directory, and it creates stray .sequant/ dirs wherever the hook happens to run:

    $ (temp dir, CLAUDE_PLUGIN_DATA unset) → run hook once
    /var/folders/…/tmp.Q0MPtbrA8h/.sequant/     ← created as a side effect
    

    That defeats AC-5's purpose twice over: AC-7 wants to backfill a regression corpus from this log, and a corpus scattered across the main repo, every worktree, and every temp dir isn't one. It also means the hook writes into directories it doesn't own on any non-sequant project the plugin is installed into.

    Finding 2 — the sink change splits the timing log (regression, untested) ❌

    pre-tool.sh moved its fallback to .sequant/logs, but post-tool.sh was not touched and still falls back to $TMPDIR. TIMING_LOG is written by both, so when CLAUDE_PLUGIN_DATA is unset (the npm/CI path) START and END now land in different files:

    NEW pre-tool + untouched post-tool:
      <cwd>/.sequant/logs/claude-timing.log     1784169747.405978000 START Bash
      $TMPDIR/claude-timing.log                 1784169747.483775000 END Bash
    
    OLD (main), same payload — correctly paired:
      $TMPDIR/claude-timing.log                 …554282000 START Bash
                                                …664039000 END Bash
    

    Timing instrumentation is a stated purpose of this hook (pre-tool.sh:4) and a documented verification criterion — skills/spec/references/verification-criteria.md:46: "Then: /tmp/claude-timing.log contains START and END". That criterion is now unsatisfiable for npm/CI users. QUALITY_LOG splits the same way (pre-tool.sh:403 vs post-tool).

    This slipped through because the AC-5 test only exercises the CLAUDE_PLUGIN_DATA-set path (:617-631 injects a temp pluginData). The newly-introduced fallback — the branch that carries both defects — has no test at all.

    Suggested fix (design, not prescription — your call): anchor the fallback to $CLAUDE_PROJECT_DIR, which Claude Code already sets and which .claude/settings.json:41 already uses to locate this very hook. That's repo-root-anchored, costs no subprocess (unlike git rev-parse, which would tax every tool call and undercut AC-9), and degrades to $TMPDIR when unset:

    elif [[ -n "${CLAUDE_PROJECT_DIR:-}" ]]; then
      _LOG_DIR="${CLAUDE_PROJECT_DIR}/.sequant/logs"
    else
      _LOG_DIR="${_TMPDIR}"
    fi

    Whatever shape you pick, it needs to land in post-tool.sh too, across all three copies, or the split persists. Please add a test that drives the fallback path with CLAUDE_PLUGIN_DATA unset and asserts one claude-timing.log holds both START and END.

    Finding 3 — the privilege guard is narrower than main (not AC-blocking, but flagging)

    AC-2's listed cases all pass. But ^-anchoring the segment means five shapes main blocked are now allowed. Old vs new, real hook:

    Payload shape main PR #771
    <esc> apt install x (plain) BLOCKED BLOCKED
    echo $(<esc> apt install x) BLOCKED allowed
    echo "$(<esc> apt install x)" BLOCKED allowed
    ( <esc> apt install x ) BLOCKED allowed
    bash -c "<esc> apt install x" BLOCKED allowed
    echo p | xargs <esc> apt install BLOCKED allowed

    This matters more than it looks: AC-1 deletes the rm guard because the native analyzer backstops it — but the issue itself notes this command is not natively covered, so this hook is the only protection, and the PR narrows it. Rows 2 and 3 are the sharpest: inside $(…) the token is at a command-word position, so they're arguably within AC-2's letter, not just its spirit.

    I'm not calling this AC-blocking — AC-2's word "only" constrains false positives, and these are non-adversarial-accident shapes. But ( … ) and $( … ) are cheap to cover (treat (, ), $( as delimiters / strip leading ( in emit()), and the trade should be a decision rather than a side effect. If you accept it, please say so in the comment at :208-215 so the next reader doesn't re-derive this.

    Finding 4 — docs missed two locations

    README was updated (AC-10 ✅), but the sink change contradicts docs that weren't:

    • docs/features/plugin-distribution.md:116-118 — still says "npm/CI users: ${TMPDIR:-/tmp}/".
    • docs/concepts/worktree-isolation.md:252,255 — still says cat /tmp/claude-hook.log.

    What's genuinely good here

    • The root cause is actually dissolved. I tried to defeat the splitter and mostly couldn't: <esc>'' apt install (quote obfuscation) blocks, git push "origin" --force blocks, newline-chained payloads block, and the unhandled backslash-escape case (--body "a\" && git push --force) fails closed. For a guard, the residual gaps erring toward blocking is the right direction.
    • The emit_segments limitations comment (:99-105) is honest — it states what it does not parse rather than overselling. That's exactly the intent-vs-effect discipline that's bitten us before.
    • AC-9 is a real measurement, and it reproduces. Deleting the regex genuinely made the hook faster.
    • The dirty-fixture insight on git reset (:263-266) shows the author noticed the guard is conditional — a subtler trap than it looks, and a clean-repo test would have passed vacuously.
    • 135/135 tests pass, parametrized across all three copies.

    Meta: the bug validated itself 3× during this review

    The old hook blocked three of my own QA commands — a probe script, an awk benchmark, and the AC-state update — purely because the text contained sudo/rm -rf / as data. I had to write each to a file and bash it. That's the false positive in this issue's "Severity framing" ("trains agents to route around the guard") happening in real time. Strong evidence the fix is worth landing once AC-5 is closed.

    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 (1 renamed) OK
    Files changed 6 (3 are identical copies) OK
    Lines +792 / -182 OK
    CI 8/8 SUCCESS OK
    Mergeable MERGEABLE, 0 behind main OK

    Self-Evaluation

    • Verified working: Yes — every AC row driven through the real hook myself; findings 1 & 2 reproduced with concrete output, not inferred from reading.
    • Test efficacy: Medium-High. Strong on the guard matrix; blind spot on the log-sink fallback, which is precisely where both defects live.
    • Likely failure mode: Silent — nobody notices split timing logs until someone tries to use them, and the AC-7 corpus quietly scatters.
    • Verdict confidence: High on AC-5 (reproduced). Medium on Finding 3's severity — a judgment call I've deliberately left to the author rather than forcing.

    Verdict: AC_NOT_MET

    AC-5 is PARTIALLY_MET → blocks per the standard algorithm. This is not a rejection of the approach: 9/10 ACs are met and the hard part (the splitter) is done and holds up under attack. The gap is confined to the log sink, and Findings 1+2 share a single root cause and a single ~6-line fix.

    Next Steps

    1. Anchor the fallback sink to the repo root ($CLAUDE_PROJECT_DIR suggested) — pre-tool.sh and post-tool.sh, all three copies (AC-8 re-verify md5s).
    2. Add a test for the CLAUDE_PLUGIN_DATA-unset path asserting START+END share one claude-timing.log.
    3. Update docs/features/plugin-distribution.md:116-118 and docs/concepts/worktree-isolation.md:252,255.
    4. Decide on Finding 3 — cover $( )/( ) or document the accepted narrowing at :208-215.
    5. Re-run /qa 763.

    QA performed inline against the real hook in the feature worktree; PR #771 @ 69cc750.

  12. added
    needs-work
    and removed
    ready-for-review
    on Jul 16, 2026
  13. added a commit that references this issue on Jul 16, 2026
  14. admarble commented on Jul 16, 2026

    @admarble
    ContributorAuthor

    QA Re-Review for Issue #763 (PR #771) — gaps fixed

    Follow-up to the previous review. All four findings are closed at 57d44b7 (merged with origin/main at e038447). 10/10 ACs met.

    What changed

    Finding Fix
    1 — cwd-relative sink Log dir resolves CLAUDE_PLUGIN_DATA/logs → HOME/.sequant/logs → $TMPDIR. Always absolute, always outside the repo.
    2 — split timing log Identical block in pre-tool.sh and post-tool.sh (all 3 copies each). START/END pair in one file again.
    3 — guard narrower than main emit_segments now covers every position the shell executes, plus heredoc awareness.
    4 — stale docs 4 locations corrected (2 of them mirrored ×3).

    A defect worse than I first reported

    While fixing Finding 1 I found the repo-local sink didn't just scatter directories — it silently disabled the no-changes guard:

    pre-fix hook (69cc750):   exit=0  (empty commit allowed)   git status: '?? .sequant/'
    fixed hook:               exit=2  HOOK_BLOCKED: No changes to commit   git status: ''
    

    The hook mkdirs its log dir before the guard reads git status --porcelain; the untracked dir made the tree look dirty, so the guard concluded there were changes. The hook's own side effect turned the hook's guard off — the same write-before-read ordering class as #760.

    This is also why the test harness comment at :44-50 existed: it noted the fallback "would break the no-changes guard's emptiness check for these bare test repos" and forced CLAUDE_PLUGIN_DATA everywhere to make tests pass. The symptom was seen and worked around rather than read as the bug it was pointing at. That comment is now corrected, and the fallback is exercised directly.

    AC-5c: a deliberate departure from the AC's wording

    AC-5c suggested "a repo-local .sequant/logs/ fallback" — that suggestion is precisely what produced all three defects. The implementation instead uses $HOME/.sequant/logs, which meets AC-5c's stated requirement ("a single non-purged sink") more faithfully: one sink shared by the main repo and every worktree, and it can never touch a repo's git status. Flagging the deviation explicitly since it departs from the issue text.

    Finding 3: full command-word coverage + the heredoc trap

    Now blocked (all verified through the real hook): ( sudo … ), echo $(sudo …), echo "$(sudo …)", nested "$( ( sudo … ) )", and gh pr create --body "$(cat .env)".

    Making $( ) live inside double quotes has a sharp edge I hit while prototyping: it also makes heredoc bodies live, and git commit -m "$(cat <<'EOF' … EOF)" is this repo's standard idiom. Without heredoc skipping, a commit message that merely mentions git push --force gets blocked — reintroducing the #564/#570 false-positive class through a new door. Your own CHANGELOG entry for #763 contains that exact string. Heredoc bodies are therefore skipped as the stdin data they are, and mutation-checked:

    remove heredoc skipping  → heredoc commit message BLOCKED  (test fails, as intended)
    fixed hook               → heredoc commit message allowed
    

    xargs sudo … and bash -c "sudo …" remain allowed — an argument is not a command word, and matching it is the original #564/#570 mistake. Now locked in by tests so a future "tightening" has to be deliberate.

    Verification

    Check Result
    Hook tests 183 passed (was 135; +48 = 16 new × 3 copies)
    Probe matrix vs real hook 31/31, every AC row + adversarial cases
    Mutation checks Both new assertions fail on the pre-fix hook, pass on the fix
    AC-9 latency 61.7ms vs 80.4ms on main (n=30) — still faster despite added parsing
    AC-8 copies pre-tool ×3 identical (4fd209d6…); dist/ regenerated and matching
    pre/post log block executable lines byte-identical (cc6a0099…)
    CI 8/8 SUCCESS; MERGEABLE
    lint / build / skill-sync / skill-calls / marketplace all clean (42 skills synced)

    Self-Evaluation

    • Verified working: Yes — every claim above is a measurement, not an inference. The guard-defeat and the timing split were each reproduced before and after.
    • Test efficacy: High, and specifically repaired where it was weakest: the CLAUDE_PLUGIN_DATA-unset branch that both defects shipped through now has direct coverage across all three copies.
    • Likely failure mode: The awk splitter is the risk surface — it grew a subshell stack and heredoc tracking. Mitigation is that its gaps fail closed (block), and 183 tests pin both directions. If a shape is mis-parsed, the symptom will be a false positive (visible, annoying) rather than a silent bypass.
    • Residual known gaps (documented, tested, deliberate): argument positions (xargs, bash -c); backslash-escaped quotes (fails closed); in-workspace destruction (out of scope per the issue).
    • Verdict confidence: High.

    Verdict: READY_FOR_MERGE

    10/10 ACs met. The bypass class is dissolved rather than re-patched, the guard is now broader than the code it replaced instead of narrower, and the log sink can no longer sabotage the guard next to it.

    Re-QA performed inline against the real hook; PR #771 @ e038447.

  15. added
    ready-for-review
    and removed
    needs-work
    on Jul 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugplannedready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions