Skip to content

bug(hooks): pre-tool.sh No-Changes Guard only recognizes single-line 'cd path && git commit', silently blocking real multi-line commits #963

Closed

Description

@admarble

Summary

.claude/hooks/pre-tool.sh's "No-Changes Guard" (line ~780-801, templates/hooks/pre-tool.sh and mirrors) extracts the target directory of a git commit by regex-matching TOOL_INPUT for a literal single-line cd /path && git commit (or ;-separated) pattern:

TARGET_DIR=""
if echo "$TOOL_INPUT" | grep -qE '^cd [^;&|]+'; then
  TARGET_DIR=$(echo "$TOOL_INPUT" | grep -oE '^cd [^;&|]+' | head -1 | sed 's/^cd //' | tr -d ' ')
fi

if [[ -n "$TARGET_DIR" && -d "$TARGET_DIR" ]]; then
  CHANGES=$(cd "$TARGET_DIR" && git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
else
  CHANGES=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
fi

When a phase agent's commit command spans multiple lines — a common shape when composing a shell block with earlier variable setup:

WT="/path/to/worktree"
cd "$WT"
git commit -m "..."

— the ^cd [^;&|]+ regex only matches the first line of TOOL_INPUT, so it never sees the cd on line 2, TARGET_DIR stays empty, and the guard falls through to git status --porcelain in the hook's own process cwd (not the worktree the agent is actually operating in). If that cwd has zero changes, the guard fires:

HOOK_BLOCKED: No changes to commit. Stage files with 'git add' first.

— even though real, staged changes exist in the target worktree.

Impact

Any phase agent that writes a multi-line cd $VAR; ...; git commit sequence silently loses its commit under this guard, with real implementation work stranded uncommitted in the worktree. Reproduced live during a sequant run exec phase in a downstream project: a complete, tested implementation (timeout/recycle fix + new test file, 41/41 tests passing) never got committed because of this guard, reported by the CLI as exec left 21 file(s) uncommitted and made no commits.

Repro

From a repo with an existing worktree:

WT="$(git worktree list --porcelain | grep worktree | sed -n 2p | cut -d' ' -f2)"
cd "$WT"
git commit --allow-empty -m "test"

Blocked by the guard. Collapsing to a single line:

cd "$WT" && git commit --allow-empty -m "test"

Succeeds.

Related, but distinct from #763

#763 fixed a different pre-tool.sh guard family — the ^gh (issue|pr) prefix-skip bypass/false-positive on the five destructive-command guards (templates/hooks/pre-tool.sh:108 and siblings). This is the No-Changes Guard's separate TARGET_DIR extraction for git commit, a different code path that #763's fix did not touch — confirmed still present with the single-line-only regex after #763 merged.

Suggested fix

Either:

  • Scan all lines of TOOL_INPUT for the last cd <path> occurrence (not just line 1), or
  • Use the tool call's actual cwd field from the hook payload if available, instead of parsing it out of the command string, or
  • Check git status --porcelain in every directory a cd in the input touches, rather than assuming a single-line command shape.

Discovery context

Found while dogfooding #960's /loop fix against real downstream projects (admarble/ad-motion). Originally mis-filed there as ad-motion#229 before confirming the guard code is byte-identical to sequant-io/sequant's own current template — this is a sequant hook-template bug, not project-local drift.

Activity

  1. added
    bug
    on Aug 24, 2026
  2. admarble commented on Aug 24, 2026

    @admarble
    ContributorAuthor

    Spec Analysis (Plan)

    Complexity: Standard (5 derived ACs, 2 directories)

    Diagnosis correction (empirically verified)

    The guard's grep -E '^cd ' is line-based, so "only matches the first line" is not the actual mechanism — a multi-line command with a literal unquoted cd /path on any line extracts fine. Verified by running the extraction logic (templates/hooks/pre-tool.sh:787-797) against six input shapes. The real failure modes:

    1. Variable targets — cd "$WT" extracts the literal string "$WT", which fails the -d test, silently falling into the fallback. This is the shape that stranded the ad-motion commit.
    2. Quoted literal targets — cd "/path" keeps its quotes after extraction (tr -d ' ' doesn't strip them), fails -d, falls into the fallback.
    3. Wrong fallback directory — the fallback runs git status --porcelain in the hook process's own cwd, not the command's shell cwd. The payload's cwd field is already parsed as HOOK_CWD (pre-tool.sh:29,39) and already used correctly by the feat(locks): per-issue locks give no mutual exclusion on the shared working tree — checkout-scoped protection #901 checkout-lock guard (_CO_CWD="${HOOK_CWD:-$PWD}", line 554) — the No-Changes Guard predates that and never adopted it.
    4. First-cd-wins — head -1 picks the first cd line; a command that cds twice checks the wrong directory.

    Note: the issue's Repro section uses --allow-empty, which line 784 exempts from this guard entirely — that repro as written cannot trip this code path. The Impact section's incident shape (WT=... / cd "$WT" / git commit -m ..., no --allow-empty) is the real repro and reproduces via failure mode 1 + 3.

    Acceptance Criteria

    • AC-1: Multi-line commit commands whose cd target is a resolvable literal path (quoted or unquoted) run the no-changes check in that directory, using the last cd line when several are present. Evidence: integration test in __tests__/pre-tool-hook.integration.test.ts.
    • AC-2: When the extracted cd target is statically unresolvable (contains $, `, or $() or does not exist as a directory, the guard fails open (allows the command) instead of checking a different directory — git commit itself already rejects truly-empty commits. Evidence: integration test using the incident's verbatim WT=.../cd "$WT"/git commit shape with staged changes in the worktree and a clean hook cwd.
    • AC-3: When no cd appears in the command, the fallback checks git -C "${HOOK_CWD:-$PWD}" status --porcelain (the payload's cwd), not the hook process's cwd. Evidence: integration test that varies payload cwd and process cwd independently (a test that sets them together cannot catch this — the feat(locks): per-issue locks give no mutual exclusion on the shared working tree — checkout-scoped protection #901 lesson).
    • AC-4: Existing behavior preserved: single-line cd /path && git commit still resolves the target, a genuinely change-free git commit is still blocked with HOOK_BLOCKED: No changes to commit, and --amend/--allow-empty still bypass. Evidence: existing suite stays green + regression assertions.
    • AC-5: All three checked-in hook mirrors (templates/hooks/, hooks/, .claude/hooks/) receive the identical fix; new tests parametrize over all three like the existing suite. Evidence: suite's 3-copy parametrization.

    Implementation Plan

    Phase 1 — extraction helper (all 3 pre-tool.sh mirrors)

    1. Add a resolve_cd_target() helper near seg_match: scan raw $TOOL_INPUT (not $SEGMENTS — emit_segments drops double-quoted regions, so cd "$WT" becomes cd in segments), take the last line matching ^[[:space:]]*cd[[:space:]]+, strip a trailing [;&|].* tail, strip surrounding single/double quotes.
    2. Rework the No-Changes Guard (lines ~785-797): if a cd was found and the resolved target is a directory → git -C <target> status; if a cd was found but the target is unresolvable/nonexistent → skip the guard (fail open); if no cd → git -C "${HOOK_CWD:-$PWD}" status.

    Phase 2 — tests
    3. Extend __tests__/pre-tool-hook.integration.test.ts with the four new cases (AC-1/2/3 shapes + first-vs-last cd), parametrized over the 3 mirrors, with the incident shape as a verbatim fixture.
    4. Mutation-verify: run the new tests against the unfixed guard (revert the hook edit) and confirm they fail, then restore; record the Mutation-verified: marker in the PR body per repo policy.

    Fail-open rationale: this guard is UX (clearer message, saved roundtrip), not safety — git natively refuses empty commits with "nothing to commit". A false block strands finished work uncommitted (the incident); a false pass costs one harmless git error message. When in doubt, don't block.

    Rejected alternative: resolving shell variables in cd targets — reimplements the shell, disproportionate; fail-open covers those shapes safely.

    Sibling site (user decision needed)

    The #901 checkout-lock guard (pre-tool.sh:556-558) has the same first-line, quote-retaining cd extraction (_CO_CD). Lower severity — its fallback is already HOOK_CWD — but same root-cause pattern in the same file. Option A (recommended): have it call the new resolve_cd_target() helper in this PR (trivially co-located, strictly reduces duplication). Option B: scope out, file follow-up. Not silently widening scope — say which.

    Open Questions

    1. Sibling-site scope (above) — Recommendation: Option A. Impact if deferred: the checkout guard mis-resolves quoted/variable cd targets, degrading to HOOK_CWD (mostly harmless, occasionally checks the wrong repo's lock).
    2. Non-jq fallback path — the grep-based TOOL_INPUT extraction (line 42) truncates at the first escaped quote in multi-line JSON, so on jq-less machines the guard sees a partial command. Recommendation: out of scope (pre-existing, jq is effectively always present); note only.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: bug label, shell-only fix with an existing integration harness; testgen skipped per bug-label rule (tests extend an existing suite rather than needing new stubs).

  3. added
    planned
    on Aug 24, 2026
  4. admarble commented on Aug 24, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #963
    Status: NEEDS_VERIFICATION (all AC met; one CI check still completing)

    Summary

    pre-tool.sh's No-Changes Guard silently checked the wrong directory when a commit command's cd target was quoted or a shell variable, stranding real staged commits behind a false "no changes to commit" block. New resolve_cd_target() scans the raw multi-line command for the last cd line, resolves static-literal targets (quoted or unquoted), and fails open on anything dynamic or nonexistent — applied to both the No-Changes Guard and the sibling #901 checkout-lock guard, identically across all 3 hook mirrors.

    Root-cause correction: the issue's own theory ("only matches single-line commands") didn't hold up under testing — the guard's grep '^cd ' already matches per-line. The real bugs were quote-retention and a wrong fallback directory (hook process cwd instead of the command's actual cwd).

    AC Coverage

    • AC-1: MET — resolvable multi-line cd target (quoted/unquoted), last-of-several wins
    • AC-2: MET — unresolvable target fails open instead of checking the wrong directory
    • AC-3: MET — no-cd fallback uses the payload's cwd, not the hook process's own
    • AC-4: MET — all pre-existing behavior preserved (195 tests unchanged)
    • AC-5: MET — identical across all 3 hook mirrors, tests parametrized

    5/5 AC met.

    Progress Table

    Phase Iterations Status
    Spec 1/1 Complete
    Exec 1/1 Complete
    Test Skipped No ui/frontend/admin label
    QA 1/2 Complete — NEEDS_VERIFICATION

    Quality Metrics

    • Tests: 222/222 in the touched suite (195 pre-existing + 27 new across 3 mirrors), 89/89 in sibling checkout-lock suites
    • Build: clean · Lint: clean
    • Mutation-verified: reverted the fix, 18/21 new test cases failed as expected, restored — markers recorded in the PR body
    • Security scan: 0 critical/warning — no injection vector, fails open on dynamic input

    Risk Assessment

    • Likely failure mode: none identified in review — the only way resolve_cd_target() can misbehave is failing open on a target it could have resolved, which is the safe direction.
    • Not tested: nothing in scope; full existing suite plus new coverage all green.

    Known, unrelated gap

    npm test's full run surfaces 3 failures in scripts/qa/tautology-detector-cli.test.ts — an advisory-only CI job (#955) whose static heuristic doesn't recognize spawnSync-based shell-script testing as "calling a production function." It flags all 74 it() blocks in the touched test file, including ~62 pre-existing ones from earlier issues (#564/#570/#763/#899/#901), unrelated to this fix. Confirmed by running the detector directly and by confirming the same tests pass cleanly on main (nothing to flag there). Not a merge gate.

    PR: #966 — #966


    Left open for human review — build (22.x) CI check was still in progress at QA time; all other checks (typecheck, hooks validation, plugin validation, skill validation, tautology-advisory) pass. Re-check gh pr checks 966 before merging.

  5. admarble commented on Aug 24, 2026

    @admarble
    ContributorAuthor

    CI verification complete

    build (22.x) finished after the prior QA pass — all 9 CI checks now pass. PR #966 is MERGEABLE, merge state CLEAN.

    Verdict: READY_FOR_MERGE

    All 5 AC met, full test suite green, mutation-verified, security scan clean, no remaining blockers. Ready for human review and merge.

  6. added a commit that references this issue on Aug 25, 2026
  7. admarble commented on Aug 25, 2026

    @admarble
    ContributorAuthor

    Gap fixes pushed (commit 7dd2710)

    All three residual gaps documented at QA time are now fixed on PR #966:

    1. Backslash hardening — resolve_cd_target() fails open on backslash-bearing cd targets (a \ could escape a $/backtick past the literal-string check). 3 new tests using a real directory literally named foo\bar.
    2. jq-less truncation — the fallback TOOL_INPUT extraction no longer truncates at the first embedded \"; escape-aware sed capture + single-scan awk unescaper. 12 new tests behind a filtered-PATH symlink farm making jq genuinely unavailable, with a HOOK_LOG assertion that distinguishes full extraction from the old truncation.
    3. Tautology-detector false positives — two detector defects fixed (collectBuildOutputVars missed type-annotated declarations; describe.each callback params had no link to their table's hooks/*.sh literals). 74/74 falsely-flagged blocks → 4 advisory stragglers that need call-site argument-value tracking (structurally larger change, left as follow-up). The 3 previously-failing tautology-detector-cli.test.ts tests now pass.

    Verification: implemented by two sub-agents on disjoint files, then independently verified — diffs reviewed, probes re-run, mutation spot-check (backslash rejection removed → exactly the 3 gap-A tests failed → restored), full suite 5673 passed / 0 failed, build + lint clean, all 3 hook mirrors md5-identical.

    Verdict pending only the new commit's CI run; will confirm READY_FOR_MERGE when it reports.

  8. admarble commented on Aug 25, 2026

    @admarble
    ContributorAuthor

    CI green on gap-fix head

    All 9 checks pass on a7e512f4 (gap fixes + merge of origin/main resolving the #964 CHANGELOG conflict). PR #966 is MERGEABLE / CLEAN.

    Verdict: READY_FOR_MERGE

  9. added a commit that references this issue on Aug 25, 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

    bugplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions