rungate 0.7.0 → 0.8.1

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 (108) hide show
  1. package/gates/.gate-salt +1 -0
  2. package/gates/SCHEMA-GUIDE.md +485 -0
  3. package/gates/ac-quality.test.ts +106 -0
  4. package/gates/adversarial.test.ts +283 -0
  5. package/gates/brief-assembler.test.ts +487 -0
  6. package/gates/brief-assembler.ts +448 -0
  7. package/gates/bunfig.toml +2 -0
  8. package/gates/chain.test.ts +91 -0
  9. package/gates/e2e-smoke.test.ts +234 -0
  10. package/gates/error-classifier.test.ts +250 -0
  11. package/gates/error-classifier.ts +99 -0
  12. package/gates/gate-executor.ts +3071 -0
  13. package/gates/orchestrator.test.ts +968 -0
  14. package/gates/orchestrator.ts +827 -0
  15. package/gates/preload.ts +89 -0
  16. package/gates/prompts/ac-adversary.md +20 -0
  17. package/gates/prompts/evidence-validator.md +22 -0
  18. package/gates/prompts/prove-reproducer.md +53 -0
  19. package/gates/prompts.sha256 +3 -0
  20. package/gates/prove.test.ts +164 -0
  21. package/gates/rook-state.test.ts +108 -0
  22. package/gates/run-attribution.ts +290 -0
  23. package/gates/run-gate.ts +163 -0
  24. package/gates/schema-parity.test.ts +378 -0
  25. package/gates/schema.ts +1209 -0
  26. package/gates/self-heal.test.ts +511 -0
  27. package/gates/self-heal.ts +125 -0
  28. package/gates/ship-orchestrator.test.ts +399 -0
  29. package/gates/ship-orchestrator.ts +384 -0
  30. package/gates/spec-compliance-probe.ts +159 -0
  31. package/gates/test-fixtures/broken-no-environments.json +110 -0
  32. package/gates/test-fixtures/consumer-directory-layout.json +90 -0
  33. package/gates/test-fixtures/valid-standard.json +91 -0
  34. package/gates/test-utils.ts +43 -0
  35. package/gates/typecheck-gate.ts +111 -0
  36. package/gates/witness.ts +349 -0
  37. package/gates/workflow.test.ts +2018 -0
  38. package/hooks/ActionVerificationGate.hook.ts +96 -0
  39. package/hooks/AgentBriefGuard.hook.ts +38 -0
  40. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  41. package/hooks/AutoVerifyGate.hook.ts +79 -0
  42. package/hooks/BashToolGuard.hook.ts +65 -0
  43. package/hooks/BashWriteGuard.hook.ts +60 -0
  44. package/hooks/CommitEnforcement.hook.ts +130 -0
  45. package/hooks/DocHygiene.hook.ts +148 -0
  46. package/hooks/GateEnforcement.hook.ts +58 -0
  47. package/hooks/GateResultProtection.hook.ts +95 -0
  48. package/hooks/HarnessAFKGate.hook.ts +85 -0
  49. package/hooks/HookCurrency.hook.ts +99 -0
  50. package/hooks/IssueCloseGuard.hook.ts +149 -0
  51. package/hooks/MergeGuard.hook.ts +58 -0
  52. package/hooks/PostCompact.hook.ts +60 -0
  53. package/hooks/ProjectStateSync.hook.ts +103 -0
  54. package/hooks/SkillGuard.hook.ts +69 -0
  55. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  56. package/hooks/SpecSCGuard.hook.ts +123 -0
  57. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  58. package/hooks/TaskCompleted.hook.ts +51 -0
  59. package/hooks/TeamInit.hook.ts +85 -0
  60. package/hooks/TestSuiteGuard.hook.ts +70 -0
  61. package/hooks/TestSuiteRelease.hook.ts +85 -0
  62. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  63. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  64. package/hooks/WorkflowStateGuard.hook.ts +64 -0
  65. package/hooks/lib/agent-config.json +9 -0
  66. package/hooks/lib/agentDetection.ts +201 -0
  67. package/hooks/lib/comment-template.ts +86 -0
  68. package/hooks/lib/findWorkflow.ts +101 -0
  69. package/hooks/lib/parseStdin.ts +37 -0
  70. package/hooks/lib/paths.ts +111 -0
  71. package/hooks/lib/utils.ts +338 -0
  72. package/lib/affected-tests.ts +29 -0
  73. package/lib/bash-write-guard.ts +627 -0
  74. package/lib/branch-cleanup.ts +279 -7
  75. package/lib/config-trackable.ts +9 -0
  76. package/lib/distribution-currency.ts +55 -5
  77. package/lib/failure-intake.ts +7 -1
  78. package/lib/gate-enforcement.ts +360 -38
  79. package/lib/gate-names.ts +72 -0
  80. package/lib/gate-result-protection.ts +437 -0
  81. package/lib/generators/code-map.ts +55 -4
  82. package/lib/generators/types.ts +27 -1
  83. package/lib/intake-sources.ts +380 -0
  84. package/lib/js-top-level-code.ts +20 -2
  85. package/lib/junit-checks.ts +239 -1
  86. package/lib/late-env-spawn.ts +331 -0
  87. package/lib/launch-base.ts +128 -5
  88. package/lib/package-closure.ts +114 -0
  89. package/lib/paths.ts +96 -3
  90. package/lib/phase2-decomposition.ts +1 -1
  91. package/lib/published-artifact.ts +162 -18
  92. package/lib/sc-id-cross-tree.ts +84 -8
  93. package/lib/scaffold/ai-review-findings.ts +149 -4
  94. package/lib/scaffold/ai-review-step.ts +1006 -132
  95. package/lib/scaffold/defaults.ts +82 -1
  96. package/lib/scaffold/steps.ts +642 -54
  97. package/lib/scanner.ts +4 -2
  98. package/lib/security-verdict.ts +1 -1
  99. package/lib/shell-path-interpolation.ts +594 -0
  100. package/lib/text-dependents.ts +875 -0
  101. package/lib/transcript-checker.ts +6 -0
  102. package/lib/workflow-security.ts +29 -0
  103. package/lib/workflow-taint.ts +732 -0
  104. package/lib/worktree-cleanup.ts +65 -38
  105. package/lib/worktree-repo.ts +32 -2
  106. package/package.json +4 -1
  107. package/scripts/check-installed-hook-currency.ts +825 -0
  108. package/scripts/generate-code-map.ts +13 -8
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TeamInit.hook.ts — Ensure team directory exists for current session (SessionStart)
4
+ *
5
+ * Governing SCs: SC-370 (traceability), SC-371 (thin trigger, under 150 lines)
6
+ *
7
+ * PURPOSE:
8
+ * Creates <claude-config-dir>/teams/session-{id}/config.json when missing.
9
+ * Fixes typed agent spawns failing after context compaction with
10
+ * "team file not found".
11
+ *
12
+ * TRIGGER: SessionStart
13
+ *
14
+ * INPUT:
15
+ * - env: CLAUDE_CODE_SESSION_ID (full UUID, first 8 chars used)
16
+ *
17
+ * OUTPUT:
18
+ * - stdout: None (never)
19
+ * - stderr: Minimal status (dir created / already exists)
20
+ * - exit(0): Always
21
+ *
22
+ * SIDE EFFECTS:
23
+ * - Creates: <claude-config-dir>/teams/session-{id}/config.json (if missing)
24
+ *
25
+ * ERROR HANDLING:
26
+ * - CLAUDE_CODE_SESSION_ID not set: exit 0 silently
27
+ * - Existing valid config.json: no-op (idempotent)
28
+ * - All errors: exit 0 (never block session start)
29
+ *
30
+ * PORTABILITY (#713): `getPaiDir()` resolves `PAI_DIR` and otherwise
31
+ * `~/.claude` — Claude Code's OWN configuration directory, which is where
32
+ * `teams/` lives on every machine running Claude Code, PAI installed or not.
33
+ * The function name is PAI-flavoured; the directory it returns is not, and
34
+ * the bug this fixes reaches any agent-spawning product equally.
35
+ *
36
+ * Fixes: #151
37
+ */
38
+
39
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
40
+ import { join } from 'path';
41
+ import { getPaiDir } from './lib/paths';
42
+
43
+ const sessionId = process.env.CLAUDE_CODE_SESSION_ID;
44
+
45
+ // Guard: no session ID → exit silently
46
+ if (!sessionId) {
47
+ process.exit(0);
48
+ }
49
+
50
+ try {
51
+ const shortId = sessionId.substring(0, 8);
52
+ const teamDir = join(getPaiDir(), 'teams', `session-${shortId}`);
53
+ const configPath = join(teamDir, 'config.json');
54
+
55
+ // Check if config already exists and is valid JSON
56
+ if (existsSync(configPath)) {
57
+ try {
58
+ JSON.parse(readFileSync(configPath, 'utf-8'));
59
+ // Valid JSON exists — idempotent no-op
60
+ process.exit(0);
61
+ } catch {
62
+ // Invalid JSON — overwrite below
63
+ console.error(`[TeamInit] Invalid config.json at ${configPath} — recreating`);
64
+ }
65
+ }
66
+
67
+ // Create directory if missing
68
+ if (!existsSync(teamDir)) {
69
+ mkdirSync(teamDir, { recursive: true });
70
+ }
71
+
72
+ // Write minimal config
73
+ const config = {
74
+ session_id: `session-${shortId}`,
75
+ created: new Date().toISOString(),
76
+ };
77
+
78
+ writeFileSync(configPath, JSON.stringify(config), 'utf-8');
79
+ console.error(`[TeamInit] Created team config: session-${shortId}`);
80
+ } catch (err) {
81
+ // Never block session start
82
+ console.error(`[TeamInit] Error (non-fatal): ${String(err).slice(0, 80)}`);
83
+ }
84
+
85
+ process.exit(0);
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TestSuiteGuard.hook.ts -- PreToolUse on Bash
4
+ * SC-473, SC-370. Tier 3 mechanical enforcement for DIR-L29 + issue #67.
5
+ *
6
+ * Thin trigger: detect a full-suite Bash command, ask lib/test-suite-lock.ts,
7
+ * report the verdict. Both the per-session budget and the cross-session
8
+ * concurrency cap live in the lib module.
9
+ */
10
+
11
+ import { parseHookInput } from './lib/utils';
12
+ import { deriveRunId, deriveWorkerId, evaluateFullSuiteRequest } from '../lib/test-suite-lock';
13
+
14
+ async function main() {
15
+ const input = await parseHookInput();
16
+ if (!input) process.exit(0);
17
+ if (input.tool_name !== 'Bash') process.exit(0);
18
+
19
+ const command = (input.tool_input?.command as string) || '';
20
+ const sessionId = input.session_id || 'default';
21
+ // Sub-agents inherit the parent's session_id, so the rate budget has to be
22
+ // keyed on the worker — session plus working directory (#239). The release
23
+ // hook derives the same identity; acquire and release must agree.
24
+ const workerId = deriveWorkerId(sessionId, input.cwd);
25
+ // ...and the run the worker belongs to, which is the bound #239's fix left
26
+ // open: every agent in a ship run got its own four. Null outside a run
27
+ // worktree, and then only the per-worker rate applies (#194).
28
+ const runId = deriveRunId(input.cwd) ?? undefined;
29
+
30
+ // Fails open: a broken guard must never be able to block the suite it
31
+ // guards. It does NOT fail silently, which is a different thing and was the
32
+ // defect — a guard whose broken state and whose satisfied state look
33
+ // identical cannot be known to have ever fired (#194 SC-642).
34
+ try {
35
+ // `cwd` decides whose repository this suite belongs to (#510). A full
36
+ // suite of a scratch tree — a reviewer's `git archive` export, a fixture
37
+ // repo — is twenty tests and under a second, and charging it against a
38
+ // budget sized for this repository's 400-second run made careful review
39
+ // the thing the guard rationed.
40
+ const decision = evaluateFullSuiteRequest(sessionId, command, {
41
+ workerId,
42
+ runId,
43
+ cwd: input.cwd,
44
+ });
45
+ if (!decision.allow) {
46
+ console.log(JSON.stringify({
47
+ decision: 'block',
48
+ reason: decision.reason,
49
+ }));
50
+ } else if (decision.warning) {
51
+ // Allowed, but the cap is not being enforced. This must reach the
52
+ // transcript: stderr from a hook that exits 0 is only visible under
53
+ // --debug, so the earlier console.error was itself a silent fail-open.
54
+ console.log(JSON.stringify({ systemMessage: decision.warning }));
55
+ }
56
+ } catch (e) {
57
+ // systemMessage, not stderr: stderr from a hook that exits 0 is only
58
+ // visible under --debug, so printing there is the same silence with extra
59
+ // steps.
60
+ console.log(JSON.stringify({
61
+ systemMessage:
62
+ `GUARD-FAILURE-VISIBLE: TestSuiteGuard could not evaluate this full-suite request ` +
63
+ `and allowed it. DIR-L29 is NOT being enforced right now. ` +
64
+ `${(e as Error)?.message ?? e}`,
65
+ }));
66
+ process.exit(0);
67
+ }
68
+ }
69
+
70
+ main();
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TestSuiteRelease.hook.ts -- PostToolUse on Bash
4
+ * Issue #67, SC-370.
5
+ *
6
+ * Thin trigger: when a full suite finishes, hand its concurrency slot back so
7
+ * the next session is not stuck waiting out the 420s TTL after a ~190s run.
8
+ *
9
+ * The TTL is the backstop for when this never fires (crash, reboot, kill -9) --
10
+ * it is what stops a dead session from wedging the repo, so slot correctness
11
+ * does not depend on this hook running.
12
+ *
13
+ * REGISTERED, in user scope. The header this replaced carried #898's
14
+ * unregistered declaration and said the TTL backstop above had been the only
15
+ * mechanism since #67. That was false in both of its claims. Measured
16
+ * 2026-10-21 by parsing `~/.claude/settings.json`:
17
+ *
18
+ * PostToolUse matcher='Bash' bun ${RUNGATE_HOOKS_DIR}/TestSuiteRelease.hook.ts
19
+ *
20
+ * #898's census counted THIS REPOSITORY's registries and read zero as
21
+ * absence; "registered nowhere" is a claim about every scope. The repo's own
22
+ * `test/test-suite-guard-registration.test.ts` has asserted the opposite since
23
+ * #67-A and was green the whole time. `lib/hook-scopes.ts` is the reading that
24
+ * now cannot be taken from one scope (#713, #910).
25
+ *
26
+ * ## Execution evidence, which was the part nobody could check
27
+ *
28
+ * This hook used to write nothing. So "did it release the slot?" had no
29
+ * answer available to any search, and an absent slot file was equally
30
+ * consistent with a release that fired and a TTL that expired. Every decision
31
+ * on a full-suite command now leaves a record in `hook-firings.jsonl` under
32
+ * the rungate work dir -- `released`, `declined-background`, or
33
+ * `release-failed`.
34
+ *
35
+ * Only full-suite commands are recorded. This hook is attached to EVERY Bash
36
+ * call in every session, and a record per call is a file nobody can read.
37
+ */
38
+
39
+ import { parseHookInput } from './lib/utils';
40
+ import { deriveWorkerId, isFullSuiteCommand, releaseFullSuiteSlot } from '../lib/test-suite-lock';
41
+ import { commandDigestFacts, errorFacts, recordHookFiring } from '../lib/hook-evidence';
42
+
43
+ const HOOK = 'TestSuiteRelease';
44
+
45
+ async function main() {
46
+ const input = await parseHookInput();
47
+ if (!input) process.exit(0);
48
+ if (input.tool_name !== 'Bash') process.exit(0);
49
+
50
+ const command = (input.tool_input?.command as string) || '';
51
+ const sessionId = input.session_id || 'default';
52
+ // Never the raw command: a Bash call routinely carries leading env
53
+ // assignments, and those carry tokens (#970 review, finding 1).
54
+ const facts = commandDigestFacts(command);
55
+
56
+ try {
57
+ // Out of population: not a full suite, so this hook has nothing to say
58
+ // about it and records nothing. Everything below IS in population, and
59
+ // every path out of it leaves a record -- a decline and a hook that never
60
+ // ran are otherwise the same observation, which is #910.
61
+ if (!isFullSuiteCommand(command)) process.exit(0);
62
+
63
+ // A backgrounded Bash call returns immediately while the suite keeps
64
+ // running. Releasing here would hand the slot back mid-run and restore the
65
+ // concurrency the guard exists to prevent. Let the TTL reclaim it instead.
66
+ if (input.tool_input?.run_in_background) {
67
+ recordHookFiring(HOOK, 'declined-background', { ...facts, sessionId, cwd: input.cwd });
68
+ process.exit(0);
69
+ }
70
+
71
+ // Same derivation as the guard (#239): a release that named only the
72
+ // session could free a sibling worker's slot while its suite still runs.
73
+ const workerId = deriveWorkerId(sessionId, input.cwd);
74
+ releaseFullSuiteSlot(sessionId, { workerId });
75
+ recordHookFiring(HOOK, 'released', { ...facts, sessionId, workerId, cwd: input.cwd });
76
+ } catch (e) {
77
+ // A failed release is recovered by the TTL; never surface it as a tool
78
+ // error. It IS recorded: a release that threw and a release that never
79
+ // happened leave the same empty lock dir behind.
80
+ recordHookFiring(HOOK, 'release-failed', { ...facts, sessionId, ...errorFacts(e) });
81
+ process.exit(0);
82
+ }
83
+ }
84
+
85
+ main();
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * TopLevelCdGuard.hook.ts — PreToolUse on Bash
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): no hook exceeds 150 lines
7
+ *
8
+ * The decision lives in lib/top-level-cd.ts and not here — hooks are thin
9
+ * triggers (HOOK-ARCHITECTURE-SPEC), the same shape as VerifyPhaseLock over
10
+ * lib/issue-create-override.ts and BashToolGuard over lib/bash-file-read.ts.
11
+ *
12
+ * Refuses a Bash command whose TOP LEVEL begins with or chains to `cd`.
13
+ *
14
+ * Why a hook and not a sentence. A top-level `cd` moves the SESSION's primary
15
+ * working directory, and the agent runtime resolves `isolation: 'worktree'`
16
+ * against that directory — so a `cd` out of the repo kills another agent's
17
+ * worktree creation hours later, with no error naming the cause. The prose
18
+ * rule existed, at maximum emphasis, at the top of every brief. On 2026-10-21
19
+ * four independent actors broke it in one evening, including the person who
20
+ * wrote it and the agent that built this hook. The conclusion was not to state
21
+ * it more loudly: `VerifyPhaseLock` holds because it is not advice.
22
+ *
23
+ * REGISTERED, as a hard refusal, by #992. Jason's decision, taken against the
24
+ * measurement on that issue — 32.7% of 31,577 recorded commands carry a
25
+ * top-level `cd`, so this fires often, and that is the point rather than an
26
+ * argument against it. The registration is four positions and they must agree
27
+ * (`.claude/rules/self-referential-tests.md`): this comment's `SC-` ids,
28
+ * `.claude/rungate/hooks.json`, the current-state table in
29
+ * `specs/HOOK-ARCHITECTURE-SPEC.md`, and `.claude/settings.json`.
30
+ *
31
+ * It is registered at PROJECT scope. `${CLAUDE_PROJECT_DIR}` resolves to the
32
+ * worktree a session is in, every worktree carries the committed
33
+ * `.claude/settings.json`, and worktree isolation — the thing a stray `cd`
34
+ * breaks — is a harness concern. Machine-wide registration lives in
35
+ * `~/.claude/settings.json`, which no PR can carry and no test here can
36
+ * honestly assert (`test/hook-registration-reconciler.test.ts`).
37
+ *
38
+ * ## The rung, and what #1040 left behind
39
+ *
40
+ * #1040 built the ladder — `RUNGATE_CD_GUARD` reads `warn` | `block` | `off`
41
+ * — and took no rung, so the decision would be a configuration choice rather
42
+ * than a code change made under pressure. The choice has now been made and
43
+ * it is `block`: `cdGuardMode`'s default moved, so the hook refuses unless a
44
+ * caller opts out. `warn` and `off` are both still reachable, which is what
45
+ * makes this reversible without touching code.
46
+ *
47
+ * It is SCOPED to harnessed projects via `lib/harness-project.ts`, the same
48
+ * decider `BashToolGuard` uses — #1040's scoping, unchanged. A top-level
49
+ * `cd` costs something only in a session with concurrent agents holding
50
+ * worktrees.
51
+ *
52
+ * ## What this will cost, measured rather than guessed
53
+ *
54
+ * 21 Bash commands in this repo's own agent prompts — `workflows/ship.js`,
55
+ * `prove.js`, `verify.js` — open with a top-level `cd` and are refused by
56
+ * this guard. Those workflows are not in use (`.claude/rules/ship-workflow.md`,
57
+ * direct-ship mode since 2026-10-19) and the count is on #992's PR, but it is
58
+ * the first thing to fix if harness mode comes back. `git -C`, a subshell and
59
+ * `bun --cwd` are each a one-line change at those sites.
60
+ *
61
+ * The parse, and what it cannot see, is `lib/top-level-cd.ts`. Read its
62
+ * WHAT THIS DOES NOT COVER block before trusting this to stop anything.
63
+ *
64
+ * Issue: #992
65
+ */
66
+
67
+ import { parseHookInput } from './lib/parseStdin';
68
+ import { CD_GUARD_DECISION, cdGuardMode, topLevelCdRefusal } from '../lib/top-level-cd';
69
+ import { isHarnessProject } from '../lib/harness-project';
70
+
71
+ async function main() {
72
+ const payload = await parseHookInput();
73
+ if (!payload) process.exit(0);
74
+
75
+ if (payload.tool_name !== 'Bash') process.exit(0);
76
+
77
+ // Scope before parse: outside a harnessed project there are no peer
78
+ // worktrees to kill, so there is nothing for this to protect.
79
+ if (!isHarnessProject(process.cwd())) process.exit(0);
80
+
81
+ const { mode, unrecognised } = cdGuardMode();
82
+ if (mode === 'off') process.exit(0);
83
+
84
+ // The raw value, NOT `|| ''`. An absent command is unreadable, and the one
85
+ // decider refuses it rather than letting the guard pass over nothing.
86
+ const refusal = topLevelCdRefusal(payload.tool_input?.command);
87
+ if (refusal === null) process.exit(0);
88
+
89
+ const note = unrecognised
90
+ ? `\n(${'RUNGATE_CD_GUARD'}=${JSON.stringify(unrecognised)} is not a mode I know; refusing, which is the default.)`
91
+ : '';
92
+
93
+ // `mode` is the configured RUNG and `CD_GUARD_DECISION` is the field the
94
+ // hook protocol reads. They spell the same word today and are not the same
95
+ // fact — collapsing them would break the rung if the protocol ever renamed
96
+ // its verdict — so they stay two names.
97
+ if (mode === 'block') {
98
+ console.log(JSON.stringify({ decision: CD_GUARD_DECISION, reason: refusal.message + note }));
99
+ process.exit(0);
100
+ }
101
+
102
+ // WARN: the command RUNS. Written to stderr so it reaches the transcript
103
+ // without becoming a tool result the model might read as a refusal.
104
+ console.error(`[top-level-cd] ${refusal.message}${note}`);
105
+ process.exit(0);
106
+ }
107
+
108
+ main();
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * VerifyPhaseLock.hook.ts — PreToolUse on Bash
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * Blocks `gh issue create` during VERIFY phase.
9
+ * Use verifyBlockers[] instead. Allows `gh issue create` carrying one of the
10
+ * override labels in lib/issue-create-override.ts.
11
+ *
12
+ * The decision lives in lib/ and not here (#365, HOOK-ARCHITECTURE-SPEC:
13
+ * hooks are thin triggers). It used to be a substring test on the whole
14
+ * command, which a `follow-up` in an issue TITLE satisfied.
15
+ *
16
+ * Issue: #443
17
+ */
18
+
19
+ import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
20
+ import { join } from 'path';
21
+ import { parseHookInput } from './lib/parseStdin';
22
+ import { verifyPhaseRefusal } from '../lib/issue-create-override';
23
+
24
+ const WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.PAI_WORK_DIR || join(process.env.HOME!, '.rungate');
25
+
26
+ function findActiveWorkflow(): { path: string; data: any } | null {
27
+ if (!existsSync(WORK_DIR)) return null;
28
+ let best: { path: string; data: any; mtime: number } | null = null;
29
+
30
+ try {
31
+ for (const entry of readdirSync(WORK_DIR, { withFileTypes: true })) {
32
+ if (!entry.isDirectory()) continue;
33
+ const wfPath = join(WORK_DIR, entry.name, 'workflow-state.json');
34
+ if (existsSync(wfPath)) {
35
+ try {
36
+ const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
37
+ const mtime = statSync(wfPath).mtimeMs;
38
+ if (!best || mtime > best.mtime) {
39
+ best = { path: wfPath, data, mtime };
40
+ }
41
+ } catch {}
42
+ }
43
+ const nested = join(WORK_DIR, entry.name);
44
+ try {
45
+ for (const sub of readdirSync(nested, { withFileTypes: true })) {
46
+ if (!sub.isDirectory()) continue;
47
+ const nestedWf = join(nested, sub.name, 'workflow-state.json');
48
+ if (!existsSync(nestedWf)) continue;
49
+ try {
50
+ const data = JSON.parse(readFileSync(nestedWf, 'utf-8'));
51
+ const mtime = statSync(nestedWf).mtimeMs;
52
+ if (!best || mtime > best.mtime) {
53
+ best = { path: nestedWf, data, mtime };
54
+ }
55
+ } catch {}
56
+ }
57
+ } catch {}
58
+ }
59
+ } catch {}
60
+
61
+ return best ? { path: best.path, data: best.data } : null;
62
+ }
63
+
64
+ async function main() {
65
+ const payload = await parseHookInput();
66
+ if (!payload) process.exit(0);
67
+
68
+ if (payload.tool_name !== 'Bash') process.exit(0);
69
+
70
+ const cmd = payload.tool_input?.command || '';
71
+
72
+ // Ask the owner BEFORE reading the workflow state. Cheap, and it keeps the
73
+ // whole decision in one place rather than half here and half in lib/.
74
+ const refusal = verifyPhaseRefusal(cmd);
75
+ if (refusal === null) process.exit(0);
76
+
77
+ const wf = findActiveWorkflow();
78
+ if (!wf || wf.data.phase !== 'VERIFY') process.exit(0);
79
+
80
+ console.log(JSON.stringify({ decision: "block", reason: refusal }));
81
+ process.exit(0);
82
+ }
83
+
84
+ main();
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * WorkflowStateGuard.hook.ts -- PreToolUse on Write, Edit
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): Hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): No hook exceeds 150 lines
7
+ *
8
+ * Blocks direct Write/Edit of workflow-state.json.
9
+ * All writes must go through writeWorkflowState() for Zod validation.
10
+ *
11
+ * ## One of two hooks on this artifact, and what this one is authoritative for (#1152)
12
+ *
13
+ * `GateResultProtection.hook.ts` matches the same tool calls. The split:
14
+ *
15
+ * - THIS hook is authoritative for **whether a tool call may write the
16
+ * artifact at all** — it refuses every Write/Edit regardless of content,
17
+ * because the sanctioned writer is `writeWorkflowState()` and the Write
18
+ * and Edit tools bypass its Zod validation.
19
+ * - `GateResultProtection` is authoritative for **what a permitted write may
20
+ * contain** — forged, erased or changed gate results, and `phase` DONE.
21
+ *
22
+ * Neither subsumes the other. THIS hook is the one that ships
23
+ * (`deployToConsumers: true`); the specific guard is OPT-IN and a scaffolded
24
+ * consumer does not get it. So on a consumer tree this is the ONLY guard on
25
+ * the artifact — which is why its matcher being case-SENSITIVE while the
26
+ * specific guard's is case-folded (#1184) is a consumer-reachable gap and not
27
+ * a tidiness question.
28
+ *
29
+ * The contract is executed, not described:
30
+ * `test/workflow-state-write-contract.test.ts` runs both hooks over one corpus
31
+ * and records both answers. Change either hook and update that table and
32
+ * `specs/HOOK-ARCHITECTURE-SPEC.md` § "The workflow-state.json write contract"
33
+ * in the same commit.
34
+ */
35
+
36
+ import { parseHookInput } from './lib/utils';
37
+
38
+ async function main() {
39
+ const input = await parseHookInput();
40
+ if (!input) process.exit(0);
41
+
42
+ const tool = input.tool_name;
43
+ if (tool !== 'Write' && tool !== 'Edit') process.exit(0);
44
+
45
+ const toolInput = input.tool_input || {};
46
+
47
+ // Write tool uses file_path; Edit tool uses file_path
48
+ const path = (toolInput.file_path as string) || (toolInput.path as string) || '';
49
+
50
+ if (!path.includes('workflow-state.json')) process.exit(0);
51
+
52
+ // Block the write
53
+ const reason = [
54
+ 'BLOCKED: workflow-state.json is protected.',
55
+ 'All writes must go through writeWorkflowState() for Zod validation.',
56
+ 'Use this pattern instead:',
57
+ '',
58
+ 'bun -e "import {writeWorkflowState} from \'./gates/orchestrator.ts\'; import {readFileSync} from \'fs\'; const s = JSON.parse(readFileSync(\'WORK_DIR/workflow-state.json\',\'utf8\')); /* apply fix */; writeWorkflowState(\'WORK_DIR/workflow-state.json\', s);"',
59
+ ].join('\n');
60
+
61
+ console.log(JSON.stringify({ decision: 'block', reason }));
62
+ }
63
+
64
+ main();
@@ -0,0 +1,9 @@
1
+ {
2
+ "agents": {
3
+ "marcus": { "match": ["marcus", "engineer", "marcus webb"], "exclude": ["council"] },
4
+ "quinn": { "match": ["quinn", "qatester", "quinn torres"], "exclude": [] },
5
+ "rook": { "match": ["rook", "pentester", "rook blackburn"], "exclude": [] },
6
+ "serena": { "match": ["serena", "architect", "serena blackwood"], "exclude": [] },
7
+ "aditi": { "match": ["aditi", "designer", "aditi sharma"], "exclude": [] }
8
+ }
9
+ }