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
@@ -5,7 +5,69 @@
5
5
  * scanning, and signal logging. The hook file is a thin trigger that
6
6
  * delegates all logic here.
7
7
  *
8
- * Issue: #544
8
+ * Issue: #544. Fail-open closed by #1155.
9
+ *
10
+ * ## A state that could not be read is not a state with no failures (#1155)
11
+ *
12
+ * This module decides whether an agent is walking away from a gate FAIL. It
13
+ * used to answer that question from a bare `catch` commented "skip malformed",
14
+ * so a `workflow-state.json` that would not parse read as **no gate failure** —
15
+ * the condition that should refuse most loudly producing the most permissive
16
+ * result. That is *Silent Default Substitution* (`.claude/rules/config-access.md`)
17
+ * and the same fail-open class `lib/gate-result-protection.ts` closed.
18
+ *
19
+ * Measured 2026-10-22, because "malformed" was covering more than one thing:
20
+ *
21
+ * - **Three** distinct throw sources reached that one catch — a `JSON.parse`
22
+ * SyntaxError, a TypeError from reading `.phase` off a parsed `null`, and
23
+ * an fs error when the path exists but cannot be read (EISDIR, EACCES, or
24
+ * a delete racing the `existsSync` above it).
25
+ * - **The catch was not the only fail-open.** A state parsing to `42`, `"x"`
26
+ * or `[]` throws nothing at all: `.phase` is `undefined`, `gates || {}` is
27
+ * empty, and the old code returned `null` down the *normal* path. So six
28
+ * inputs read as a clean run, not three. `gate-result-protection` already
29
+ * refuses the non-object parses by name; this module now agrees with it.
30
+ *
31
+ * Three states that the old `null` conflated are now distinct, and only the
32
+ * middle one refuses:
33
+ *
34
+ * | On disk | Reading |
35
+ * |---|---|
36
+ * | no work dir, or no state file — a first run | `MEASURED`, no failure |
37
+ * | present, parses, no blocking gate FAIL | `MEASURED`, no failure |
38
+ * | present and unreadable, unparseable, or not an object | `UNMEASURED` |
39
+ *
40
+ * ## Why the refusal is scoped to Skill calls, and is not a wider block
41
+ *
42
+ * A bare refusal here would be worse than the bug: `GateEnforcement` is a
43
+ * PreToolUse hook on `.*`, so refusing every tool call would make a single
44
+ * corrupt state file a denial of service on the session — and a guard nobody
45
+ * can get out from under gets switched off, after which it guards nothing.
46
+ * So the recovery path was measured before the failure mode was chosen:
47
+ *
48
+ * - `makeEnforcementDecision` already blocks **only** `Skill` calls. Bash,
49
+ * Read, Edit and Agent are nagged, never blocked — that is the existing
50
+ * design's own escape hatch and it predates this change.
51
+ * - `WorkflowStateGuard` refuses direct `Write`/`Edit` of the artifact and
52
+ * names the repair: `bun -e "… writeWorkflowState(…)"`.
53
+ * - `BashWriteGuard` inspects only `>`/`>>`, `tee`, `cp` and `mv` targets,
54
+ * so that `bun -e` command carries no write target it can see and is
55
+ * allowed through.
56
+ *
57
+ * The repair therefore runs over Bash, which this refusal leaves open. There
58
+ * is no deadlock, and `test/gate-enforcement.test.ts` holds that as a control
59
+ * rather than as a comment: if a later change starts blocking Bash here, the
60
+ * control goes red.
61
+ *
62
+ * The refusal is **immediate** rather than strike-counted. Strikes are keyed
63
+ * on `issue` + `gate` by `loadStrikeCount`, and an unreadable state supplies
64
+ * neither — there is nothing to count against. Same reasoning as an OUTCOME
65
+ * AC failure, which also blocks on sight.
66
+ *
67
+ * One more consequence of the old `catch` is worth naming, because it is not
68
+ * the one the issue was filed about: `runGateEnforcement` deletes
69
+ * `gate-pending.json` when it sees no failure, so a corrupt state file also
70
+ * **erased the strike counter**. An unmeasured reading now leaves it alone.
9
71
  */
10
72
 
11
73
  import {
@@ -18,6 +80,7 @@ import {
18
80
  writeFileSync,
19
81
  } from 'fs';
20
82
  import { checkDocHygiene } from './doc-hygiene';
83
+ import { BLOCKING_GATES } from './gate-names';
21
84
 
22
85
  export interface GateFailure {
23
86
  check: string;
@@ -62,13 +125,60 @@ export function formatFailures(failures: GateFailure[]): string {
62
125
  return failures.map(f => ` - ${f.check}: ${f.detail}`).join('\n');
63
126
  }
64
127
 
128
+ /**
129
+ * Whether every state file under the work directory could actually be read.
130
+ * `UNMEASURED` means at least one could not — which is not the same answer as
131
+ * "no gate failed", and must never be collapsed into it.
132
+ */
133
+ export type WorkflowReading = 'MEASURED' | 'UNMEASURED';
134
+
135
+ export interface WorkflowScan {
136
+ reading: WorkflowReading;
137
+ /** The first blocking gate FAIL found, in scope > verify > ship priority. */
138
+ failure: WorkflowGateFailure | null;
139
+ /** One line per unreadable path. Non-empty exactly when UNMEASURED. */
140
+ unmeasuredReasons: string[];
141
+ }
142
+
143
+ /** A plain JSON object — not an array, not null, not a scalar. */
144
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
145
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
146
+ }
147
+
148
+ /** What one state file yielded: a failure, or a reason it could not be read. */
149
+ interface FileReading {
150
+ failure: WorkflowGateFailure | null;
151
+ unmeasured: string | null;
152
+ }
153
+
154
+ const READABLE: FileReading = { failure: null, unmeasured: null };
155
+
65
156
  /**
66
157
  * Scan workflow-state.json files under workDir for active gate failures.
67
158
  * Returns the first failure found (scope > verify > ship priority).
68
159
  * Checks both direct children and nested subdirectories.
160
+ *
161
+ * An unreadable state does not abort the scan: a readable sibling can still
162
+ * carry a real FAIL, and discarding it would trade one fail-open for another.
163
+ * Both answers are carried — `failure` for the actionable one, `reading` for
164
+ * whether the sweep was complete.
69
165
  */
70
- export function findWorkflowGateFailure(workDir: string): WorkflowGateFailure | null {
71
- if (!existsSync(workDir)) return null;
166
+ export function findWorkflowGateFailure(workDir: string): WorkflowScan {
167
+ const reasons: string[] = [];
168
+ // An absent work directory is a first run, not a corrupt one. MEASURED.
169
+ if (!existsSync(workDir)) return { reading: 'MEASURED', failure: null, unmeasuredReasons: [] };
170
+
171
+ let failure: WorkflowGateFailure | null = null;
172
+
173
+ // First failure wins, as before — but the sweep RUNS TO COMPLETION rather
174
+ // than returning on it. Stopping early would make `reading` depend on
175
+ // readdir order: a corrupt state sorting after a failing one would go
176
+ // unreported, and the same two files would answer differently on a
177
+ // filesystem that enumerated them the other way round.
178
+ const take = (r: FileReading): void => {
179
+ if (r.unmeasured) reasons.push(r.unmeasured);
180
+ if (r.failure && !failure) failure = r.failure;
181
+ };
72
182
 
73
183
  try {
74
184
  const dirs = readdirSync(workDir, { withFileTypes: true })
@@ -76,39 +186,71 @@ export function findWorkflowGateFailure(workDir: string): WorkflowGateFailure |
76
186
 
77
187
  for (const d of dirs) {
78
188
  // Level 1: direct children
79
- const result = checkWorkflowFile(`${workDir}/${d.name}/workflow-state.json`, d.name);
80
- if (result) return result;
189
+ take(checkWorkflowFile(`${workDir}/${d.name}/workflow-state.json`, d.name));
81
190
 
82
191
  // Level 2: nested subdirectories
83
192
  try {
84
193
  const subDirs = readdirSync(`${workDir}/${d.name}`, { withFileTypes: true })
85
194
  .filter(sd => sd.isDirectory());
86
195
  for (const sd of subDirs) {
87
- const nestedResult = checkWorkflowFile(
196
+ take(checkWorkflowFile(
88
197
  `${workDir}/${d.name}/${sd.name}/workflow-state.json`,
89
198
  `${d.name}/${sd.name}`,
90
- );
91
- if (nestedResult) return nestedResult;
199
+ ));
92
200
  }
93
- } catch { /* skip */ }
201
+ } catch (err) {
202
+ reasons.push(`${workDir}/${d.name}: directory could not be listed (${err})`);
203
+ }
94
204
  }
95
- } catch { /* skip */ }
205
+ } catch (err) {
206
+ reasons.push(`${workDir}: work directory could not be listed (${err})`);
207
+ }
96
208
 
97
- return null;
209
+ return {
210
+ reading: reasons.length === 0 ? 'MEASURED' : 'UNMEASURED',
211
+ failure,
212
+ unmeasuredReasons: reasons,
213
+ };
98
214
  }
99
215
 
100
216
  /**
101
217
  * Check a single workflow-state.json file for gate failures.
218
+ *
219
+ * Returns a reason rather than `null` whenever the file is present but could
220
+ * not be read as a workflow state — see the module docstring for the six
221
+ * inputs that used to come back as a clean run.
102
222
  */
103
- function checkWorkflowFile(wfPath: string, slug: string): WorkflowGateFailure | null {
104
- if (!existsSync(wfPath)) return null;
223
+ function checkWorkflowFile(wfPath: string, slug: string): FileReading {
224
+ // Genuinely absent: this issue simply has no state yet.
225
+ if (!existsSync(wfPath)) return READABLE;
105
226
 
227
+ let wf: unknown;
106
228
  try {
107
- const wf = JSON.parse(readFileSync(wfPath, 'utf-8'));
108
- if (wf.phase === 'DONE') return null;
229
+ wf = JSON.parse(readFileSync(wfPath, 'utf-8'));
230
+ } catch (err) {
231
+ return { failure: null, unmeasured: `${wfPath}: could not be read as JSON (${err})` };
232
+ }
233
+
234
+ // A workflow state is always an object. An array, a null or a scalar is a
235
+ // reading that could not be taken, and throws nothing on the way past.
236
+ if (!isPlainObject(wf)) {
237
+ return {
238
+ failure: null,
239
+ unmeasured: `${wfPath}: parsed to ${Array.isArray(wf) ? 'an array' : typeof wf}, not a workflow state object`,
240
+ };
241
+ }
109
242
 
110
- const gates = wf.gates || {};
111
- for (const gateName of ['scope', 'verify', 'ship']) {
243
+ try {
244
+ if (wf.phase === 'DONE') return READABLE;
245
+
246
+ const gates = (isPlainObject(wf.gates) ? wf.gates : {}) as Record<string, {
247
+ result?: string;
248
+ failures?: { check?: string; id?: string; detail?: string; message?: string }[];
249
+ }>;
250
+ // #1137: the registry, not a second copy of it. This list and
251
+ // GateResultProtection's agreed on every input anyone had, so nothing
252
+ // could go red when they diverged.
253
+ for (const gateName of BLOCKING_GATES) {
112
254
  const gate = gates[gateName];
113
255
  if (gate?.result === 'FAIL' && Array.isArray(gate.failures) && gate.failures.length > 0) {
114
256
  const acs = Array.isArray(wf.acs) ? wf.acs : [];
@@ -116,22 +258,27 @@ function checkWorkflowFile(wfPath: string, slug: string): WorkflowGateFailure |
116
258
  (ac: { type?: string; verdict?: string }) => ac.type === 'OUTCOME' && ac.verdict === 'FAIL',
117
259
  );
118
260
  return {
119
- gate: gateName,
120
- issue: wf.issue,
121
- slug: wf.slug || slug,
122
- failures: gate.failures.map(
123
- (f: { check?: string; id?: string; detail?: string; message?: string }) => ({
261
+ unmeasured: null,
262
+ failure: {
263
+ gate: gateName,
264
+ issue: wf.issue as number,
265
+ slug: (wf.slug as string) || slug,
266
+ failures: gate.failures.map(f => ({
124
267
  check: f.check || f.id || 'unknown',
125
268
  detail: f.detail || f.message || JSON.stringify(f),
126
- }),
127
- ),
128
- hasOutcomeAcFailure,
269
+ })),
270
+ hasOutcomeAcFailure,
271
+ },
129
272
  };
130
273
  }
131
274
  }
132
- } catch { /* skip malformed */ }
275
+ } catch (err) {
276
+ // Nothing above should throw now that the shape is checked first — so if
277
+ // one does, that is an unread state, not a clean one. Refuse, don't skip.
278
+ return { failure: null, unmeasured: `${wfPath}: could not be interpreted (${err})` };
279
+ }
133
280
 
134
- return null;
281
+ return READABLE;
135
282
  }
136
283
 
137
284
  /**
@@ -290,8 +437,55 @@ export function logEnforcementSignal(
290
437
  });
291
438
  }
292
439
 
440
+ /**
441
+ * What an agent is told when the gate state cannot be read. It names the
442
+ * artifact, the reason, and the one command that can repair it — a refusal
443
+ * with no way out is a denial of service, not a guard.
444
+ */
445
+ export function unmeasuredStateReason(reasons: string[]): string {
446
+ return [
447
+ 'UNMEASURED: the harness gate state could not be read, so whether a gate is ' +
448
+ 'currently FAILing is unknown — and an unknown is not a pass.',
449
+ ...reasons.map(r => ` - ${r}`),
450
+ '',
451
+ 'Repair the state, then retry. workflow-state.json is not directly writable ' +
452
+ '(WorkflowStateGuard); go through the validating writer:',
453
+ ' bun -e "import {writeWorkflowState} from \'./gates/orchestrator.ts\'; ' +
454
+ 'writeWorkflowState(\'WORK_DIR/workflow-state.json\', STATE);"',
455
+ '',
456
+ 'Bash, Read and Edit are not blocked — only Skill calls are, so the repair ' +
457
+ 'above is reachable right now.',
458
+ ].join('\n');
459
+ }
460
+
293
461
  export function runGateEnforcement(input: GateEnforcementInput): GateEnforcementResult {
294
- const wfFailure = findWorkflowGateFailure(input.workDir);
462
+ const scan = findWorkflowGateFailure(input.workDir);
463
+ const wfFailure = scan.failure;
464
+
465
+ // #1155: no readable failure, but the sweep was incomplete. Refuse rather
466
+ // than report the clean run we did not actually observe. Skill-scoped, and
467
+ // the strike counter is left alone — an unmeasured reading is not evidence
468
+ // that the gate it was counting against has been fixed.
469
+ if (!wfFailure && scan.reading === 'UNMEASURED') {
470
+ const reason = unmeasuredStateReason(scan.unmeasuredReasons);
471
+ logSignal(input.signalsDir, input.signalsFile, {
472
+ ts: new Date().toISOString(),
473
+ type: 'gate_enforcement',
474
+ reading: 'UNMEASURED',
475
+ tool: input.toolName,
476
+ action: input.toolName === 'Skill' ? 'block' : 'nag',
477
+ reasons: scan.unmeasuredReasons,
478
+ });
479
+
480
+ if (input.toolName === 'Skill') {
481
+ return { stdout: JSON.stringify({ decision: 'block', reason }), action: 'block' };
482
+ }
483
+ return {
484
+ stdout: ['<system-reminder>', `⚠️ ${reason}`, '</system-reminder>'].join('\n'),
485
+ action: 'nag',
486
+ };
487
+ }
488
+
295
489
  if (!wfFailure) {
296
490
  if (existsSync(input.pendingFile)) {
297
491
  try {
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Gate names, and the two different questions people ask about them (#1137).
3
+ *
4
+ * A LEAF module with no imports, so there is one thing to mutate and every
5
+ * tree can reach it — `hooks/` and `gates/` both import from `lib/`, and
6
+ * `lib/` is in `package.json` `files[]` while `gates/` is not, so this is the
7
+ * only directory a published hook may take a gate name from.
8
+ *
9
+ * ## Why there are two lists and not one
10
+ *
11
+ * The first draft of this file had one, `PROTECTED_GATES`, and used it as the
12
+ * guard's allowlist. A review round found that wrong twice over, and both
13
+ * corrections are worth keeping:
14
+ *
15
+ * 1. The list was INCOMPLETE. `gates/gate-executor.ts` calls
16
+ * `writeGateResult(sf, "merge", …)`, `(sf, "gaps", …)` and the dynamic
17
+ * `(sf, gate, …)` that `prove` reaches, so `gates.merge.result`,
18
+ * `gates.gaps.result` and `gates.prove.result` are all persisted and none
19
+ * of them was guarded. None is visible to a `gates\.[a-z]+` grep, because
20
+ * the name arrives as a function ARGUMENT and the write is
21
+ * `state.gates[gate] = …`.
22
+ * 2. An enumerated allowlist on a security boundary is correct exactly until
23
+ * someone adds a gate, and nothing makes the next person update it.
24
+ *
25
+ * So the guard no longer reads a list at all. `lib/gate-result-protection.ts`
26
+ * blocks a `result` under ANY key of `gates`, which cannot go stale — the
27
+ * question "is the list complete?" stops being askable. Neither list below is
28
+ * the guard's allowlist, and adding a name to either must never be required
29
+ * to make the guard see a new gate.
30
+ */
31
+
32
+ /**
33
+ * Gates whose FAIL blocks an agent, in the priority order
34
+ * `findWorkflowGateFailure` reports them: scope, then verify, then ship.
35
+ *
36
+ * NOT a security boundary and NOT the set of gates that record a result —
37
+ * `merge`, `prove` and `gaps` record results and are deliberately absent.
38
+ * `gaps` is WARN-only and is passed `fails = 0` unconditionally, so it can
39
+ * never be a blocking failure; `merge` and `prove` run after the ship gate
40
+ * has already decided. Widening this list would start nagging agents about
41
+ * gates that are not theirs to fix.
42
+ *
43
+ * Consumed by `lib/gate-enforcement.ts`.
44
+ */
45
+ export const BLOCKING_GATES = ['scope', 'verify', 'ship'] as const;
46
+
47
+ export type BlockingGate = (typeof BLOCKING_GATES)[number];
48
+
49
+ /**
50
+ * Every gate name `writeGateResult` is called with, so every key that can
51
+ * appear under `gates` carrying a `result`.
52
+ *
53
+ * **This is a TEST POPULATION, not an allowlist.** Nothing in the guard reads
54
+ * it. `test/gate-name-registry.test.ts` asserts the gate-agnostic guard
55
+ * refuses a forged result for every name here, so adding a name STRENGTHENS
56
+ * the evidence and forgetting to add one cannot weaken the guard. That
57
+ * direction is the whole point: a list that can only make the test weaker by
58
+ * omission is safe to leave slightly stale, and an allowlist is not.
59
+ *
60
+ * Derived 2026-10-22 from the `writeGateResult` call sites in
61
+ * `gates/gate-executor.ts` and the argument vocabulary in `gates/run-gate.ts`.
62
+ */
63
+ export const RESULT_BEARING_GATES = [
64
+ 'scope',
65
+ 'verify',
66
+ 'ship',
67
+ 'merge',
68
+ 'prove',
69
+ 'gaps',
70
+ ] as const;
71
+
72
+ export type ResultBearingGate = (typeof RESULT_BEARING_GATES)[number];