rungate 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +29 -0
  36. package/lib/bash-write-guard.ts +373 -0
  37. package/lib/branch-cleanup.ts +279 -7
  38. package/lib/config-trackable.ts +9 -0
  39. package/lib/distribution-currency.ts +55 -5
  40. package/lib/failure-intake.ts +7 -1
  41. package/lib/gate-enforcement.ts +222 -28
  42. package/lib/gate-names.ts +72 -0
  43. package/lib/gate-result-protection.ts +427 -0
  44. package/lib/intake-sources.ts +380 -0
  45. package/lib/late-env-spawn.ts +331 -0
  46. package/lib/launch-base.ts +128 -5
  47. package/lib/paths.ts +96 -3
  48. package/lib/phase2-decomposition.ts +1 -1
  49. package/lib/published-artifact.ts +162 -18
  50. package/lib/sc-id-cross-tree.ts +84 -8
  51. package/lib/scaffold/ai-review-findings.ts +7 -1
  52. package/lib/scaffold/ai-review-step.ts +861 -116
  53. package/lib/scaffold/defaults.ts +82 -1
  54. package/lib/scaffold/steps.ts +436 -44
  55. package/lib/security-verdict.ts +1 -1
  56. package/lib/shell-path-interpolation.ts +594 -0
  57. package/lib/text-dependents.ts +875 -0
  58. package/lib/workflow-security.ts +29 -0
  59. package/lib/workflow-taint.ts +732 -0
  60. package/lib/worktree-cleanup.ts +65 -38
  61. package/lib/worktree-repo.ts +32 -2
  62. package/package.json +3 -1
  63. package/scripts/check-installed-hook-currency.ts +825 -0
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env bun
2
+ import { parseHookInput } from './lib/parseStdin';
3
+ /**
4
+ * ActionVerificationGate.hook.ts - Post-Deploy Verification Reminder (PostToolUse/Bash)
5
+ *
6
+ * Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
7
+ *
8
+ * PURPOSE:
9
+ * After state-changing bash commands (deploy, publish, push) that succeed,
10
+ * injects a verification reminder into the conversation so the agent reads
11
+ * actual system state before reporting done.
12
+ *
13
+ * ROOT CAUSE ADDRESSED:
14
+ * Agents report "done" without re-reading actual state after deploy/push.
15
+ *
16
+ * TRIGGER: PostToolUse (matcher: Bash)
17
+ *
18
+ * INPUT:
19
+ * - stdin: JSON with session_id, tool_name, tool_input.command, tool_response.output
20
+ *
21
+ * OUTPUT:
22
+ * - stdout: JSON message when a state-changing command succeeded
23
+ * - stderr: Status messages
24
+ * - exit(0): Always (non-blocking — never interrupts session)
25
+ *
26
+ * SIDE EFFECTS:
27
+ * - None (read-only pattern matching)
28
+ *
29
+ * PORTABILITY (#713): no file I/O and no PAI-owned path. The only import is
30
+ * `./lib/parseStdin`, which is byte-identical in both trees. Functions the
31
+ * same on a consumer repo that has never heard of PAI.
32
+ */
33
+
34
+ // State-changing command patterns — case-insensitive match against command string
35
+ const STATE_CHANGING_PATTERNS: RegExp[] = [
36
+ /make\s+rebuild/i,
37
+ /make\s+build/i,
38
+ /docker\s+push/i,
39
+ /podman\s+push/i,
40
+ /gh\s+release/i,
41
+ /git\s+push/i,
42
+ /npm\s+publish/i,
43
+ /bun\s+publish/i,
44
+ ];
45
+
46
+ function isStateChangingCommand(command: string): boolean {
47
+ return STATE_CHANGING_PATTERNS.some(pattern => pattern.test(command));
48
+ }
49
+
50
+ function commandAppearedToSucceed(output: string): boolean {
51
+ // Only suppress on clear error indicators in the output.
52
+ // Absence of error = likely success (exit code 0 path)
53
+ return !/error/i.test(output);
54
+ }
55
+
56
+ async function main() {
57
+ const payload = await parseHookInput();
58
+ if (!payload) process.exit(0);
59
+
60
+ const command: string = payload?.tool_input?.command ?? '';
61
+
62
+ // `tool_response` is EITHER a string or an object carrying `output`. The
63
+ // `.pai` copy read `.output` unconditionally, which is `undefined` on the
64
+ // string form — so a command whose response came back as a bare string was
65
+ // read as empty, counted as "no error", and always got the reminder. That
66
+ // copy lives outside any tsconfig and never had to typecheck; this one does.
67
+ const response = payload?.tool_response;
68
+ const output: string = typeof response === 'string' ? response : (response?.output ?? '');
69
+
70
+ if (!command) {
71
+ process.exit(0);
72
+ }
73
+
74
+ if (!isStateChangingCommand(command)) {
75
+ process.exit(0);
76
+ }
77
+
78
+ if (!commandAppearedToSucceed(output)) {
79
+ // Command failed — no point reminding to verify a broken deploy
80
+ console.error('[ActionVerificationGate] Command appears to have failed, skipping reminder');
81
+ process.exit(0);
82
+ }
83
+
84
+ console.error(`[ActionVerificationGate] State-changing command detected: ${command.slice(0, 60)}`);
85
+
86
+ // Output the verification reminder to stdout — Claude Code reads this back into context
87
+ const reminder = {
88
+ message:
89
+ "VERIFY BEFORE REPORTING: A state-changing command just ran. Read actual system state before claiming success — check the deploy is live, the release is visible, the image is pushed. Do NOT say 'done' without evidence.",
90
+ };
91
+
92
+ process.stdout.write(JSON.stringify(reminder) + '\n');
93
+ process.exit(0);
94
+ }
95
+
96
+ main();
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * AgentBriefGuard — PreToolUse on Agent (SC-367, SC-370)
4
+ * Validates briefs use templates + bypassPermissions. Delegates to lib/agent-brief-validation.ts
5
+ */
6
+ import { BASE_DIR, WORK_DIR } from './lib/paths';
7
+ import { parseHookInput } from './lib/parseStdin';
8
+ import { logBriefSignal, validateAgentBrief } from '../lib/agent-brief-validation';
9
+
10
+ async function main() {
11
+ const input = await parseHookInput();
12
+ if (!input) process.exit(0);
13
+ try {
14
+ if (input.tool_name !== 'Agent') process.exit(0);
15
+ const result = validateAgentBrief(input, WORK_DIR, BASE_DIR);
16
+ for (const event of result.signalEvents) {
17
+ logBriefSignal(BASE_DIR, event);
18
+ }
19
+ if (result.action === 'exit') process.exit(0);
20
+ if (result.action === 'block') {
21
+ console.log(JSON.stringify({ decision: 'block', reason: result.blockReason }));
22
+ console.error(`[AgentBriefGuard] BLOCKED ${result.agent?.label || 'agent'}`);
23
+ process.exit(0);
24
+ }
25
+ if (result.outputs.length > 0) {
26
+ console.log(['<system-reminder>', ...result.outputs, '</system-reminder>'].join('\n'));
27
+ }
28
+ console.error(
29
+ `[AgentBriefGuard] ${result.agent?.label} spawn validated — sizing: ${result.sizing || 'unknown'}`
30
+ );
31
+ process.exit(0);
32
+ } catch (err) {
33
+ console.error(`[AgentBriefGuard] Error: ${err}`);
34
+ process.exit(0);
35
+ }
36
+ }
37
+
38
+ main();
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * AgentVerdictCapture.hook.ts — SubagentStop hook
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * Parses agent output for structured verdict blocks.
9
+ * Writes verdict, testedSha, testedPaths, spawned to workflow-state.json.
10
+ * Auto-appends blockers to verifyBlockers[].
11
+ * Runs transcript audit and writes compliance results.
12
+ *
13
+ * Issue: #439, #544 (extracted findActiveWorkflow + extractVerdict to lib/)
14
+ */
15
+
16
+ import { writeFileSync } from 'fs';
17
+ import { join } from 'path';
18
+ import { parseHookInput } from './lib/parseStdin';
19
+ import { detectAgent } from './lib/agentDetection';
20
+ import { runAgentAudit, populateBehavioralCache } from '../lib/agent-audit';
21
+ import { findActiveWorkflow, extractVerdict } from '../lib/verdict-capture';
22
+
23
+ const WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
24
+
25
+ function identifyRole(toolInput: any): string | null {
26
+ const detected = detectAgent(toolInput);
27
+ if (detected) return detected.key;
28
+ const name = (toolInput.name || '').toLowerCase();
29
+ if (name.startsWith('quinn')) return 'quinn';
30
+ if (name.startsWith('marcus')) return 'marcus';
31
+ if (name.startsWith('rook')) return 'rook';
32
+ return null;
33
+ }
34
+
35
+ async function main() {
36
+ const payload = await parseHookInput();
37
+ if (!payload) process.exit(0);
38
+
39
+ const toolInput = payload.tool_input || {};
40
+ const role = identifyRole(toolInput);
41
+ if (!role) process.exit(0);
42
+
43
+ const wf = findActiveWorkflow(WORK_DIR);
44
+ if (!wf) process.exit(0);
45
+
46
+ const resp = payload.tool_response;
47
+ const respText = typeof resp === 'string' ? resp : (resp?.output || JSON.stringify(resp) || '');
48
+ const verdict = extractVerdict(respText);
49
+ const state = wf.data;
50
+
51
+ if (!state.agents) state.agents = {};
52
+ if (!state.agents[role]) state.agents[role] = {};
53
+ state.agents[role].spawned = true;
54
+
55
+ if (verdict) {
56
+ state.agents[role].verdict = verdict.verdict || verdict.result || null;
57
+ if (verdict.testedSha) state.agents[role].testedSha = verdict.testedSha;
58
+ if (verdict.testedPaths) state.agents[role].testedPaths = verdict.testedPaths;
59
+
60
+ if (verdict.blockers && Array.isArray(verdict.blockers)) {
61
+ if (!state.verifyBlockers) state.verifyBlockers = [];
62
+ for (const b of verdict.blockers) {
63
+ const id = b.id || `${role}-blocker-${state.verifyBlockers.length + 1}`;
64
+ if (!state.verifyBlockers.some((vb: any) => vb.id === id)) {
65
+ state.verifyBlockers.push({ id, description: b.description || b.detail || String(b), quinnReverified: false });
66
+ }
67
+ }
68
+ }
69
+ } else {
70
+ state.agents[role].verdict = null;
71
+ }
72
+
73
+ const auditResult = runAgentAudit(payload.transcript_path, role);
74
+ if (auditResult) {
75
+ if (!state.audits) state.audits = {};
76
+ state.audits[role] = auditResult;
77
+
78
+ const projectRoot = process.env.RUNGATE_PROJECT_ROOT || join(WORK_DIR, '..');
79
+ populateBehavioralCache(auditResult as any, projectRoot);
80
+ }
81
+
82
+ state.updatedTs = new Date().toISOString();
83
+ writeFileSync(wf.path, JSON.stringify(state, null, 2));
84
+ process.exit(0);
85
+ }
86
+
87
+ main();
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * AutoVerifyGate.hook.ts — PostToolUse on Agent
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * When Marcus/Quinn/Rook agent returns:
9
+ * 1. Find active workflow-state.json in BUILD/VERIFY phase
10
+ * 2. Write agents.<key>.verdict based on response content
11
+ * 3. For Marcus: emit system-reminder to run verify gate
12
+ * 4. For Quinn/Rook: record verdict only
13
+ */
14
+
15
+ import { writeFileSync, renameSync } from 'fs';
16
+ import { join } from 'path';
17
+ import { parseHookInput, detectAgent, findWorkflowState, extractIssueNumber, WORK_DIR, HARNESS_ROOT } from './lib/utils';
18
+
19
+ function atomicWrite(path: string, data: string) {
20
+ const tmp = `${path}.${process.pid}.tmp`;
21
+ writeFileSync(tmp, data, 'utf-8');
22
+ renameSync(tmp, path);
23
+ }
24
+
25
+ const NEGATIVE_PATTERNS = [
26
+ /\b(no|zero|0)\s+(error|fail)/i,
27
+ /\bfixed\s+the\s+(error|fail|bug|issue)/i,
28
+ /\bpreviously\s+failed.*now\s+pass/i,
29
+ /\b0\s+error/i, /\berror.*resolved/i, /\bno\s+failures/i,
30
+ /\bfail(ure)?s?\s*:\s*0\b/i, /\berrors?\s*:\s*0\b/i,
31
+ ];
32
+
33
+ async function main() {
34
+ const payload = await parseHookInput();
35
+ if (!payload || payload.tool_name !== 'Agent') process.exit(0);
36
+
37
+ const toolInput = payload.tool_input || {};
38
+ const agent = detectAgent(toolInput);
39
+ if (!agent) process.exit(0);
40
+
41
+ const { key } = agent;
42
+ const expectedPhase = key === 'marcus' ? 'BUILD' : 'VERIFY';
43
+ const issueNum = extractIssueNumber(toolInput.prompt || '');
44
+ const wf = findWorkflowState(issueNum, [expectedPhase]);
45
+ if (!wf) { console.error('[auto-verify] No active workflow — skipping'); process.exit(0); }
46
+
47
+ if (wf.data.phase !== expectedPhase) {
48
+ console.error(`[auto-verify] Phase is ${wf.data.phase}, not ${expectedPhase} — skipping`);
49
+ process.exit(0);
50
+ }
51
+
52
+ const resp = payload.tool_response;
53
+ const respContent = typeof resp === 'string' ? resp : (resp?.content || resp?.output || '');
54
+ const hasNeg = NEGATIVE_PATTERNS.some(p => p.test(respContent));
55
+ const respLower = respContent.toLowerCase();
56
+ const verdict = hasNeg ? 'PASS'
57
+ : (respLower.includes('error') || respLower.includes('failed')) ? 'FAIL'
58
+ : 'PASS';
59
+
60
+ const state = wf.data;
61
+ state.agents = state.agents || {};
62
+ state.agents[key] = { verdict, completedTs: new Date().toISOString() };
63
+ state.updatedTs = new Date().toISOString();
64
+
65
+ const sfPath = join(WORK_DIR, wf.slug, 'workflow-state.json');
66
+ try { atomicWrite(sfPath, JSON.stringify(state, null, 2)); } catch {
67
+ console.error('[auto-verify] Failed to write workflow-state.json');
68
+ process.exit(0);
69
+ }
70
+
71
+ console.error(`[auto-verify] ${key} verdict: ${verdict}`);
72
+ if (key === 'marcus') {
73
+ console.log(`\n<system-reminder>AUTO-VERIFY TRIGGERED: Run this command NOW:\nbun run ${HARNESS_ROOT}/gates/run-gate.ts --gate verify --slug ${wf.slug}\nDo NOT skip — auto-verify detected Marcus completion.</system-reminder>`);
74
+ } else {
75
+ console.log(`\n<system-reminder>${key} verdict recorded: ${verdict}. No gate trigger — ${key} runs are part of verification.</system-reminder>`);
76
+ }
77
+ }
78
+
79
+ main();
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * BashToolGuard.hook.ts -- PreToolUse on Bash
4
+ * SC-457, SC-370
5
+ *
6
+ * Tier 3 mechanical enforcement for COMP-7.
7
+ * Blocks cat/head/tail used for file reading via Bash — including piped usage.
8
+ * Agents must use the Read tool instead.
9
+ *
10
+ * ROOT CAUSE (#45): BashToolGuard hook registered at project level in
11
+ * .claude/settings.json does not fire for worktree subagents because Claude Code
12
+ * only inherits user-level hooks (~/.claude/settings.json) for isolated agents.
13
+ * The project-level .claude/ directory is gitignored and not copied to worktrees.
14
+ * Additionally, permissions.deny glob patterns (e.g. "Bash(cat *)") miss piped
15
+ * cat/head/tail usage like "grep foo | head -20".
16
+ *
17
+ * Fix: This hook is registered in BOTH user-level (~/.claude/settings.json) and
18
+ * project-level (.claude/settings.json) settings. The regex patterns below block
19
+ * direct, semicolon-chained, &&-chained, AND piped cat/head/tail patterns.
20
+ * permissions.deny entries are retained as defense-in-depth for direct invocations.
21
+ *
22
+ * SCOPE: User-level registration means this hook fires for EVERY Claude Code
23
+ * session on the machine, including non-harness projects and bundled skills that
24
+ * legitimately pipe through head/tail. COMP-7 is a harness compliance directive
25
+ * (lib/compliance-report.ts) graded against Marcus/Quinn/Rook transcripts — it is
26
+ * only meaningful inside a rungate-harnessed project. `isHarnessProject()` walks
27
+ * up from cwd looking for either harness marker. This keeps enforcement for
28
+ * rungate, its worktree subagents, AND consumer projects (DDB, POV) while going
29
+ * silent everywhere else. Scoping lives here, not in the registration:
30
+ * project-level hooks do not reach worktree subagents, so user-level
31
+ * registration is required.
32
+ *
33
+ * The walk itself moved to `lib/harness-project.ts` (#992), which needed the
34
+ * same question for a second hook. Nothing about the behaviour changed; a
35
+ * second inline copy would have been two deciders for one question.
36
+ */
37
+
38
+ import { parseHookInput } from './lib/utils';
39
+ import { detectBashFileRead } from '../lib/bash-file-read';
40
+ import { isHarnessProject } from '../lib/harness-project';
41
+
42
+ async function main() {
43
+ const input = await parseHookInput();
44
+ if (!input) process.exit(0);
45
+
46
+ if (input.tool_name !== 'Bash') process.exit(0);
47
+
48
+ if (!isHarnessProject(process.cwd())) process.exit(0);
49
+
50
+ const cmd = (input.tool_input?.command as string) || '';
51
+
52
+ // Blocks cat/head/tail reading a FILE in any position — direct,
53
+ // ;-chained, &&-chained, or piped. Pure stdin filters (cmd | head -80)
54
+ // are allowed: they read stdin, not a file, and Read cannot replace them.
55
+ const offending = detectBashFileRead(cmd);
56
+ if (offending) {
57
+ console.log(JSON.stringify({
58
+ decision: 'block',
59
+ reason: `COMP-7: Use the Read tool instead of cat/head/tail via Bash.\nOffending segment: ${offending}\nExample: Read({ file_path: "/path/to/file", offset: 0, limit: 50 })`,
60
+ }));
61
+ return;
62
+ }
63
+ }
64
+
65
+ main();
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * BashWriteGuard.hook.ts — PreToolUse on Bash
4
+ *
5
+ * Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
6
+ *
7
+ * TRIGGER: PreToolUse (matcher: Bash)
8
+ *
9
+ * Blocks Bash writes to the gate artifacts — `workflow-state.json`,
10
+ * `.gate-salt`, `witnesses/` — and to hook sources, plus `chmod`/`chflags`
11
+ * on a hook file and `security` access to the gate-salt Keychain entry.
12
+ *
13
+ * THE DECISION LIVES IN `lib/bash-write-guard.ts` (#1120), which is where
14
+ * the reasoning and the measurements are. It was extracted for the same
15
+ * reason #1137 extracted `lib/gate-result-protection.ts`: a decision that
16
+ * only exists inside a subprocess cannot be swept over a corpus, and this
17
+ * one was wrong in two directions at once until 5,060 real commands were
18
+ * run through it.
19
+ *
20
+ * PORTABILITY (#713): every protected artifact is a rungate gate artifact,
21
+ * both imports are rungate-owned and in `package.json` `files[]`. No
22
+ * PAI-owned path is read.
23
+ *
24
+ * Issues: hornjason/pai-config#473, tuned there in
25
+ * hornjason/pai-config#474 — a DIFFERENT repository from this one, whose
26
+ * own #473/#474 are `lib/scaffold/steps.ts` bugs. Reworked in #1120.
27
+ */
28
+
29
+ import { parseHookInput } from './lib/parseStdin';
30
+ import { decideBashWrite } from '../lib/bash-write-guard';
31
+
32
+ async function main() {
33
+ const input = await parseHookInput();
34
+ if (!input) process.exit(0);
35
+
36
+ const cmd: string = input.tool_input?.command || '';
37
+ if (!cmd) process.exit(0);
38
+
39
+ let decision;
40
+ try {
41
+ decision = decideBashWrite(cmd);
42
+ } catch (e) {
43
+ // A guard that crashes must not thereby allow the thing it guards
44
+ // (#1137). Scoped to a command that already names a protected artifact,
45
+ // so a bug here refuses a narrow class rather than bricking the session.
46
+ const touches = ['workflow-state.json', '.gate-salt', '/witnesses/', '.hook.ts', '.hook.sh'];
47
+ if (!touches.some(t => cmd.includes(t))) process.exit(0);
48
+ decision = {
49
+ blocked: true,
50
+ reason: `Refused: BashWriteGuard could not evaluate this command (${String(e)}).`,
51
+ };
52
+ }
53
+
54
+ if (decision.blocked) {
55
+ console.log(JSON.stringify({ decision: 'block', reason: decision.reason }));
56
+ }
57
+ process.exit(0);
58
+ }
59
+
60
+ main().catch(() => process.exit(0));
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * CommitEnforcement.hook.ts — PostToolUse on Agent
4
+ *
5
+ * SC-304 (AGENTS-MD-TEMPLATE-SPEC): CommitEnforcement contains [code, agent]
6
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
7
+ *
8
+ * TRIGGER: PostToolUse (matcher: Agent)
9
+ *
10
+ * Detects two conditions in code agent worktrees after agent completion:
11
+ * 1. UI file changes — writes quinn-required tripwire for quinn-on-ui-change gate
12
+ * 2. Uncommitted changes — writes agent-uncommitted tripwire signal
13
+ *
14
+ * Broadened from Marcus-only to all code agents (marcus, quinn, rook, serena,
15
+ * aditi) — true of NOTHING until #1000, because the config that detection
16
+ * reads was in no commit; see `hooks/lib/agentDetection.ts`.
17
+ *
18
+ * The worktree it acts on comes out of an agent-authored reply, so it must
19
+ * be a REGISTERED worktree of this harness's own repo and git runs ISOLATED
20
+ * — `lib/agent-worktree.ts`, `lib/git-isolation.ts` (#1001).
21
+ *
22
+ * Issue: #361, #343, #1000, #1001
23
+ */
24
+
25
+ import { execFileSync } from 'child_process'
26
+ import { existsSync, mkdirSync } from 'fs'
27
+ import { join } from 'path'
28
+ import { findWorkflowForIssue, extractIssueNumber } from './lib/findWorkflow'
29
+ import { agentWorktreeSubject } from '../lib/agent-worktree'
30
+ import { gitIsolatedArgs, gitIsolatedEnv } from '../lib/git-isolation'
31
+ import { WORK_DIR, SIGNAL_DIR } from './lib/paths'
32
+ import { parseHookInput } from './lib/parseStdin';
33
+ import { detectAgentOrRecord } from './lib/agentDetection'
34
+
35
+ async function main() {
36
+ const payload = await parseHookInput()
37
+ if (!payload) process.exit(0)
38
+
39
+ if (payload?.tool_name !== 'Agent') process.exit(0)
40
+
41
+ const toolInput = payload.tool_input || {}
42
+
43
+ // `OrRecord`: an unreadable config leaves evidence, not a silent null (#1000).
44
+ const agent = detectAgentOrRecord(toolInput, 'CommitEnforcement', { cwd: (payload as { cwd?: string }).cwd })
45
+
46
+ if (!agent) process.exit(0) // Not a known agent, or config unreadable (recorded) — skip
47
+
48
+ if (toolInput.isolation !== 'worktree') process.exit(0)
49
+
50
+ const resp = payload.tool_response
51
+ // `tool_response.content` is declared `unknown` — the payload is whatever the
52
+ // tool emitted. Only a string is regex-able; anything else means no path here.
53
+ const respContent = typeof resp === 'string' ? resp : resp?.content
54
+ const respText = typeof respContent === 'string' ? respContent : ''
55
+
56
+ // A registered worktree of this harness's OWN repo, or nothing (#1001).
57
+ // A named-but-unregistered candidate is a TERMINAL refusal in there — the
58
+ // fall-through to the scan is what made the previous fix misattribute.
59
+ const worktreePath = agentWorktreeSubject(respText, 'CommitEnforcement', { agent: agent.key })
60
+ if (!worktreePath) process.exit(0)
61
+
62
+ // Resolve slug early — needed by both UI detection and uncommitted-changes tripwire
63
+ const issueNum = extractIssueNumber(toolInput.prompt || '')
64
+ const wf = findWorkflowForIssue(issueNum)
65
+ const slug = wf?.slug || issueNum || 'unknown'
66
+
67
+ // ── UI file detection (runs independently of uncommitted check) ──
68
+ const uiExtensions = /\.(tsx|jsx|css|scss|html|svg|less)$/i
69
+ let uiFiles: string[] = []
70
+ try {
71
+ // ARGV, never a shell string (#971 SC-4), and ISOLATED: argv does
72
+ // nothing about config keys git EXECUTES (#1001, lib/git-isolation.ts).
73
+ const diffOutput = execFileSync('git', gitIsolatedArgs(['-C', worktreePath, 'diff', '--name-only', 'main']), {
74
+ encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], env: gitIsolatedEnv(),
75
+ }).trim()
76
+ if (diffOutput) uiFiles = diffOutput.split('\n').filter(f => uiExtensions.test(f))
77
+ } catch {}
78
+
79
+ if (uiFiles.length > 0) {
80
+ const uiSignalName = `quinn-required-${agent.key}-${slug.replace(/\//g, '-')}`
81
+ const uiSignalPath = join(SIGNAL_DIR, uiSignalName)
82
+ if (!existsSync(SIGNAL_DIR)) mkdirSync(SIGNAL_DIR, { recursive: true })
83
+ await Bun.write(uiSignalPath, JSON.stringify({
84
+ detected: new Date().toISOString(),
85
+ worktreePath,
86
+ uiFiles,
87
+ uiFileCount: uiFiles.length,
88
+ issue: issueNum || null,
89
+ slug,
90
+ agent: agent.key,
91
+ }, null, 2))
92
+ console.error(`[commit-enforcement] ${uiFiles.length} UI files changed by ${agent.key} — quinn-required signal written`)
93
+ }
94
+
95
+ // ── Uncommitted-changes detection ──
96
+ let uncommittedStatus = ''
97
+ try {
98
+ uncommittedStatus = execFileSync('git', gitIsolatedArgs(['-C', worktreePath, 'status', '--porcelain']), {
99
+ timeout: 5000, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], env: gitIsolatedEnv(),
100
+ }).trim()
101
+ } catch {
102
+ process.exit(0)
103
+ }
104
+
105
+ if (!uncommittedStatus) process.exit(0)
106
+
107
+ const uncommittedFiles = uncommittedStatus.split('\n').filter(l => l.trim()).length
108
+
109
+ if (!existsSync(SIGNAL_DIR)) mkdirSync(SIGNAL_DIR, { recursive: true })
110
+
111
+ const signalName = `agent-uncommitted-${agent.key}-${slug.replace(/\//g, '-')}`
112
+ const signalPath = join(SIGNAL_DIR, signalName)
113
+ const signal = {
114
+ detected: new Date().toISOString(),
115
+ worktreePath,
116
+ uncommittedFiles,
117
+ uncommittedStatus,
118
+ issue: issueNum || null,
119
+ slug,
120
+ agent: agent.key,
121
+ }
122
+
123
+ await Bun.write(signalPath, JSON.stringify(signal, null, 2))
124
+ console.error(`[commit-enforcement] ${uncommittedFiles} uncommitted files by ${agent.key} in ${worktreePath}`)
125
+ console.log(`\n<system-reminder>${agent.name} UNCOMMITTED CHANGES: ${agent.name} left ${uncommittedFiles} uncommitted file(s) in worktree ${worktreePath}. Review and commit before proceeding. Signal written to ${signalPath}.</system-reminder>`)
126
+
127
+ process.exit(0)
128
+ }
129
+
130
+ main()