Skip to content

test(hooks): golden-corpus verdict snapshot for pre-tool.sh — every command form ever guarded, replayed on each change, verdict changes reviewed #1094

Closed

Description

@admarble

Blocked by: #1093 Tier: mechanical Doc: guard plan 2026-09-18 (16-bug classification; research: differential testing, Csmith/EMI)

Why

pre-tool.sh is a ~1,600-line bash/awk parser and the repo's hottest regression chain: #763 (segment-aware guards) broke forms #981 fixed, and #981's strip_comments broke the -F - heredoc subject that #1064 fixed. Each fix was tested against the forms its author thought of. Nothing replays the forms previous fixes protected.

A golden corpus makes the parser's whole observed input space a fixture: every command form, with the verdict the hook gives it today. A change that flips any verdict fails the test until the snapshot is updated in the same PR, so the flip is visible in review instead of discovered in the field.

Change

  1. __tests__/fixtures/hook-corpus.jsonl: one line per case { "command": "...", "tool": "Bash", "exit": 0|2, "block": "<HOOK_BLOCKED reason or null>", "source": "#763|#981|#1064|logs|manual" }. Seed from every command string in __tests__/pre-tool-hook.integration.test.ts (114 runHook( sites), plus commands harvested from two machine-local sources: the hook's own log ~/.sequant/logs/claude-hook.log (<ts> BLOCKED [<rule>] <redacted command> lines — 603 on the planning host, already redacted, verdict known) and the Bash tool_use blocks in the Claude Code transcripts ~/.claude/projects/<project-slug>/*.jsonl (5,519 distinct commands on the planning host; verdict obtained by replaying through the hook). .sequant/logs/run-*.json is not a source: Phase 0 found zero command strings in 93 files (lab notes §3). De-duplicated, secrets scrubbed, source set to hook-log or transcript. The harvest is a maintainer-host step; the committed corpus is what CI and --diff read.
  2. __tests__/hook-corpus.integration.test.ts: runs each case through all three hook copies and asserts exit and block reason match the snapshot.
  3. scripts/hook-corpus.ts --harvest [--transcripts <dir>] [--hook-log <file>]: appends new distinct commands from the two sources above with their current verdicts; --diff <ref> runs the corpus through the hook at <ref> and at HEAD and prints only the verdict changes.
  4. The exec skill's checklist for any pre-tool.sh change: run --diff origin/main and list each changed verdict in the PR body under Hook verdicts changed:.

Release-graph plan — guard-2026-09 (2026-09-20)

Graph: guard-2026-09 Tier: mechanical Wave: 3
May touch: __tests__/fixtures/hook-corpus.jsonl, __tests__/hook-corpus.integration.test.ts, scripts/hook-corpus.ts, scripts/hook-corpus.test.ts, exec SKILL.md ×3, CHANGELOG.md; read-only on the three pre-tool.sh copies

The npm run build && npm test AC is verified by the runner from a clean shell after the PR opens (PLAN I-1); the agent runs only the test files its ACs name. Mutation markers use failedTest starting with the test file path (I-4). Fixture first: commit the corpus and the snapshot test before the --diff tooling. The harvest runs on the maintainer host (the sources are local); the PR body states which sources were read and the redaction pass. Skill edits: I-3 applies (byte-identical mirrors, no relay word).

Acceptance criteria

Not in scope

Fuzzing the hook with generated commands; that is the parser property-test issue.

Activity

  1. added
    enhancement
    on Sep 19, 2026
  2. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Runner context — guard-2026-09 wave 3 launch, 2026-09-20. Base: origin/main at 138d12ac (waves 1 and 2 merged: #1093 settle-against-base script + red-main rule + CI job test, #1069 merge-not-rebase, #1087, #1097, plus all of wave 1). These rules override the exec AND qa skills' defaults for this run:

    • No full npm test in the worktree — this applies to the qa phase too. Under concurrent phase agents that one call exceeds the 30-minute no-progress wall and the phase is killed (three wave-1 phases died this way). Verify each AC by its own command; run only the test files the ACs name. The runner runs the full suite once per PR from a clean shell and records it on the PR.
    • A named test file red before your change: the suite is now hermetic (bug(test): suite isn't hermetic against the SEQUANT_* env phases inject — exec sees red tests it didn't cause and opens no PR #1086), so a red file is real. Name the issue number and the base-vs-head result in the PR body.
    • Mutation marker (gate-test ACs): <!-- SEQUANT_MUTATION: {"ac":"AC-N","mutation":"<what you deleted>","failedTest":"<test file path> > <describe> > <case>"} --> in the PR body. failedTest MUST start with the test file path. Run parseMutationMarkers on your body before opening the PR. Commit before mutating.
    • 30-minute no-progress wall per phase. Commit a WIP checkpoint before any long command; every command foreground, with timeout.
    • Commits: single-line git commit -m "...", no Co-Authored-By. Push the branch and open the PR yourself (one wave-1 exec forgot). Never rebase or force-push after pushing. One AC per line in the PR body, ids AC-N only.
    • Stop at the PR. Do not merge.

    Issue-specific: Fixture first: commit the corpus and the snapshot test before the --diff tooling. Harvest sources on this host: ~/.sequant/logs/claude-hook.log records only BLOCKED commands (<epoch> BLOCKED [<rule>] <command>), so the bulk of the corpus comes from Claude Code transcripts under ~/.claude/projects/-Users-tony-Projects-sequant/*.jsonl (Bash tool_use inputs, .message.content[].input.command). Redact before writing (AC-4). Only this issue edits the exec SKILL.md mirrors this wave; npm run lint:skill-sync must report 0 diverged and no SKILL.md may contain the word relay. Any gate test in scripts/ must call a production function (tautology detector). The three pre-tool.sh copies are read-only.

  3. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (6 ACs, 5 directories)

    AC Quality Check

    • AC-1 (grep spacing): the greps match "source": "#1064" (space after the colon). JSON.stringify emits "source":"#1064", so the writer needs a custom serializer (, and : separators) or the counts return 0. AC-1 also uses hook-log while the schema line says logs. Use hook-log and transcript everywhere.
    • AC-1 (hook-log ≥ 50) is not reachable on this host. ~/.sequant/logs/claude-hook.log has 641 lines but only 39 distinct single-line Bash commands (env-dump 14, no-changes 8, commit-format 6, background-task 6, force-push 2, staged-secret 1, sensitive-file 1, git-reset-hard 1). The other 71 BLOCKED lines are JSON payloads for non-Bash tools (worktree-boundary, random tmp paths, and the replay needs SEQUANT_WORKTREE). Multi-line commands are split across log lines. Needs an owner decision (Q1).
    • AC-4 says "a run log", but the issue itself says run logs hold no commands. The real inputs are the hook log and transcripts. Read it as: a harvested transcript/hook-log command containing a ghp_ token or Authorization: header.
    • AC-2, AC-3, AC-5 and AC-6 are measurable as written.

    Scope Assessment

    Non-Goals: ✅ "Not in scope: fuzzing with generated commands".

    Metric Value Status
    Feature count 1 (corpus + gate + tooling) ✅
    AC items 6 ✅
    Directory spread 5 (__tests__, scripts, 3 skill dirs, CHANGELOG) ⚠️ (the three skill dirs are byte-identical mirrors)

    Verdict: ⚠️ SCOPE_WARNING (directory count only; the mirrors are one logical edit).


    Acceptance Criteria

    AC-1: ≥150 distinct commands, all #763/#981/#1064 forms, ≥5 #1064, ≥50 hook-log

    Verification: Integration Test (the wc/grep -c commands in the issue)
    Scenario: Given the committed corpus → When the AC-1 commands run → Then counts meet the thresholds
    Assumptions: the hook-log threshold is corrected per Q1; serializer spacing matches the greps.

    AC-2: snapshot test green on all three hook copies, red on any verdict change

    Verification: Integration Test + mutation check
    Scenario: Given the corpus → When hooks/, .claude/hooks/ and templates/hooks/ each replay every case → Then exit and block reason match. Given heredoc_first_line(raw, start) → (s, start) (line 1316) in one copy → Then the -F - cases fail by name.
    Assumptions: cases are it.each per copy, titled <source> <command prefix>, so the failure names the cases. The gate-test marker uses failedTest = __tests__/hook-corpus.integration.test.ts > <describe> > <case> and is recorded in the PR body.

    AC-3: --diff origin/main on an unchanged hook prints 0 verdict changes, exit 0

    Verification: Integration Test (CLI run)
    Scenario: Given no hook change → When npx tsx scripts/hook-corpus.ts --diff origin/main runs → Then 0 verdict changes, exit 0
    Assumptions: origin/main resolves in the runner's clone. It vacuously passes on an unchanged hook, so add a derived check (see Derived ACs).

    AC-4: harvest redacts secrets

    Verification: Unit Test (npx vitest run scripts/hook-corpus.test.ts -t "redacts")
    Scenario: Given a candidate command with ghp_… or Authorization: Bearer … → When it passes through the production redactor → Then the value becomes <redacted>
    Assumptions: the test calls the exported production function (tautology detector). The hook's own redact_secrets covers too few shapes (ghp/xoxb/AIza…) for transcripts: 102 of 5,626 distinct transcript commands match a broader token/key pattern.

    AC-5: exec skill names the --diff step in all three copies

    Verification: Manual Test (grep -c "hook-corpus.ts --diff" → 1 each)
    Scenario: Given the three exec SKILL.md files → When grepped → Then exactly 1 match each, and lint:skill-sync reports 0 diverged with no relay anywhere.

    AC-6: npm run build && npm test green

    Verification: Integration Test, run by the runner from a clean shell after the PR opens. Per the runner comment, the agent runs only the named test files.


    Implementation Plan

    Fixture first: commit the corpus and the snapshot test before any --diff tooling.

    Phase 1: Corpus and snapshot test (AC-1, AC-2)

    1. Export the replay core from scripts/hook-corpus.ts: replayCase(hookDir, case, state) and serializeCase. The test imports it.
      • It builds an isolated tmp git repo, sets HOME and CLAUDE_PLUGIN_DATA to tmp, and deletes SEQUANT_* and CLAUDE_HOOKS_DISABLED, like cleanEnv().
      • Verdicts depend on git state (no-changes, staged-secret, reset-hard, branch), so the fixture pins one state: a benign staged file on main.
      • The git init sets commit.gpgsign=false and identity via git config, before any commit.
    2. Seed from the existing suite by temporarily instrumenting runHook to dump {command, cwd-state, code} while the suite runs. Do not commit the instrumentation. Regex-parsing 114 call sites misses the commands built through makeStagedRepo and template variables. Tag source by describe block (fix(hooks): ^gh (issue|pr) prefix skip disarms all 5 pre-tool guards for compound commands, and re-breaks on any cd prefix #763, fix(hooks): commit-message validator extracts from the whole command, so an earlier quoted string or unrelated heredoc blocks a valid conventional commit #981, bug(hooks): commit validator strips # from a git commit -F - heredoc subject, blocking every type(#N): message sent via stdin #1064, else manual).
    3. Harvest the hook log (39 distinct commands) and the transcripts only from ~/.claude/projects/-Users-tony-Projects-sequant/*.jsonl. The slug-prefix siblings are bench runs and other projects.
      • The repo is PUBLIC, so scrub /Users/tony, emails and tokens too, not only secrets.
      • Drop commands over 2,000 chars. Truncating would change the verdict.
      • Cap the committed corpus (Q2).
    4. Write __tests__/hook-corpus.integration.test.ts as describe.each(HOOK_COPIES) + it.each(cases). The .integration. name puts it in the 30s project.

    Phase 2: Tooling (AC-3, AC-4)

    1. scripts/hook-corpus.ts: CLI --harvest [--transcripts <dir>] [--hook-log <file>] (append-only, sorted, deterministic) and --diff <ref>.
      • --diff must extract the whole hooks/ dir at <ref>, not pre-tool.sh alone. The hook sources the sibling parallel-marker.sh (line 139), and a single-file extract would silently change verdicts.
      • It replays with the hooks/ copy at both <ref> and HEAD.
    2. scripts/hook-corpus.test.ts stays pure and in-process: redaction, dedupe, serializer spacing, diff formatting. It is in the 5s unit project, and vitest.config.ts is not in "May touch", so nothing there may spawn bash or build repos.

    Phase 3: Skill and changelog (AC-5)

    1. Add one step to exec §3c (Shell Script Checks), applied byte-identically to .claude/skills/exec, skills/exec and templates/skills/exec. When pre-tool.sh changes, run npx tsx scripts/hook-corpus.ts --diff origin/main and list each changed verdict under Hook verdicts changed:. Use the phrase exactly once per file. Then run lint:skill-sync and lint:skill-gates. Add a CHANGELOG entry.

    Design Review

    1. Where does this belong? Replay logic lives in scripts/hook-corpus.ts, exported. The test and the CLI share it, so the --diff verdicts and the CI verdicts cannot drift.
    2. Simplest correct approach: one pinned git state and a JSONL snapshot. Rejected: per-case setup scripts (a fixture DSL) and regex-extracting cases from the test source.
    3. Existing pattern: HOOK_COPIES describe.each parity in pre-tool-hook.integration.test.ts, and settle-against-base (real git, integration project).
    4. Senior reviewer would ask: "Why not just add tests to the existing file?" Because the corpus is a machine-harvested snapshot that updates in the same PR as a verdict flip, not hand-written intent. The existing tests stay as the intent record.

    Feature Quality Planning

    • Runtime: a replay is about 80ms. 5,626 transcript commands × 3 copies is about 22 minutes, too slow for CI. So the committed corpus must be capped (Q2). Target ≤ ~400 cases, about 100s for three copies.
    • Non-determinism: anything time- or lock-dependent (checkout lock, 24h TTL) must not appear in the corpus. If a case flips between two runs, it is excluded at harvest by replaying twice.
    • Sibling scan: --diff runs one copy (hooks/). The other two are covered by the parity test, so a copy that drifts is caught by AC-2, not AC-3.

    Derived ACs

    Source Derived AC Priority
    Error handling AC-7: --diff against a ref containing the #1064 mutation prints ≥1 verdict change naming the -F - cases and exits non-zero (or prints the count). Otherwise AC-3 passes vacuously. High
    Security AC-8: no corpus line contains /Users/, an email, or a token-shaped string (test over the committed file). High

    Open Questions

    1. AC-1 hook-log ≥ 50 vs 39 available (Q1) — Recommendation: lower it to ≥ 30, or count normalized non-Bash payloads. Impact if unchanged: AC-1 fails on a true corpus, or gets padded with invented commands, which the AC forbids. Per project practice, rewrite the AC line and run with force; a comment alone won't re-open exec.
    2. Corpus size cap (Q2) — Recommendation: all seeds, all hook-log commands, every transcript command with a non-zero verdict, plus a stratified exit-0 sample (guard-relevant tokens: git commit|push|reset, gh, env, sudo, heredocs), ≤ ~400 total. Impact: CI time vs coverage.
    3. State field — Recommendation: optional state (staged default, clean) so the existing cleanRepo cases keep their verdicts. The issue's schema has no such field. Impact: without it, ~10 seeds replay against the wrong state.
    4. Existing worktree for test(hooks): golden-corpus verdict snapshot for pre-tool.sh — every command form ever guarded, replayed on each change, verdict changes reviewed #1094 is already at 138d12ac, clean. The exec phase should reuse it.

    Recommended Workflow

    Phases: spec → testgen → exec → qa
    Quality Loop: enabled (SCOPE_WARNING)
    Reasoning: AC-2 and AC-4 declare vitest evidence (unit/integration), so testgen stubs first; the plan is fixture-first anyway. Skip test (no UI). No security-review phase, but AC-4/AC-8 need a hand check on the scrubbed corpus, because the repo is public. If the runner follows its wave rules, exec runs only the named test files.


    Label Review

    Current: enhancement
    Recommended: enhancement, planned
    Reason: feature work, plan posted
    Quality Loop: auto-enabled by SCOPE_WARNING

  4. added
    planned
    on Sep 20, 2026
  5. added a commit that references this issue on Sep 20, 2026
  6. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Runner edit to AC-1 (2026-09-20). The qa phase measured the hook-log ≥ 50 floor as unreachable: the host's hook log holds 42 distinct eligible blocked commands, and the log records only the first line of multi-line commands, so a naive re-harvest adds heredoc fragments that replay as allowed. Two changes: (1) extractHookLogCommands now skips fragments (heredoc openers, trailing operators, unbalanced quotes/parens), gate-tested, matching its own doc comment; GUARD_RELEVANT anchors per line. (2) AC-1's per-source floor is now ≥ 30 whole real blocks (spec Open Question 1); the corpus holds 39. No secrets in the added lines (scanned). Recorded as D-22 in the plan.

  7. added a commit that references this issue on Sep 20, 2026
  8. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    Runner edit to AC-1, second pass (2026-09-20). The qa phase showed 26 of the 39 re-harvested hook-log cases were pinned as allow although the log recorded a block: the replay harness cannot reproduce background-task, orchestrator-env or state-dependent guards. Pinning the wrong side would make the snapshot lie, so the harvester now keeps only reproduced blocks (86ee3e8b), drops rule-mismatched first lines, and redacts session links, foreign project paths and --repo names; the corpus holds 13 hook-log cases, all blocks. AC-1's per-source floor is now ≥ 10 reproduced blocks with zero allow-pinned hook-log cases. The unreproducible 29 are the coverage gap tracked in #1129.

  9. admarble commented on Sep 20, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 0/1 met

    Gaps:

    • AC-1's zero-allow-pinned-hook-log invariant is not gated by any test, so a future harvest regression that re-pins an unreproduced block as allow would leave CI green
    • The harvest orchestration (dedup, replay-twice flake exclusion, hook-log allow-drop, maxAllow slice, ordering) is untested and unexecuted against real sources
    • Redaction-test fixtures hardcode the maintainer's real username, GitHub handle, private project name and a real session id, which the corpus leak gate does not cover
    • A no-op --harvest invocation rewrites the committed corpus fixture instead of short-circuiting on zero additions

    Suggestions:

    • --harvest with no --transcripts/--hook-log still rewrites the corpus file unconditionally (main() → writeCorpus). Harmless today, but a no-op invocation touching a committed fixture is a footgun; guard on added.length > 0.
    • Seven exports (GUARD_RELEVANT, MAX_COMMAND_LENGTH, CORPUS_PATH, caseKey, writeCorpus, diffVerdicts, extractHooksAt) are never imported outside the module. Not dead — all are called internally — just over-exported.
  10. added 2 commits that reference this issue on Sep 21, 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

    enhancementplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions