rungate 0.8.0 → 0.8.2

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 (73) 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/BashWriteGuard.hook.ts +19 -0
  39. package/hooks/GateResultProtection.hook.ts +27 -1
  40. package/hooks/VerifyPhaseLock.hook.ts +51 -11
  41. package/hooks/WorkflowStateGuard.hook.ts +24 -0
  42. package/lib/ai-review-rounds.ts +462 -0
  43. package/lib/bash-file-read.ts +17 -3
  44. package/lib/bash-write-guard.ts +1285 -50
  45. package/lib/distribution-standing.ts +75 -4
  46. package/lib/failure-intake.ts +12 -4
  47. package/lib/file-extensions.ts +81 -0
  48. package/lib/finding-arbiter.ts +1015 -0
  49. package/lib/finding-jury.ts +537 -0
  50. package/lib/gate-enforcement.ts +171 -43
  51. package/lib/gate-result-protection.ts +12 -2
  52. package/lib/generators/code-map.ts +55 -4
  53. package/lib/generators/types.ts +27 -1
  54. package/lib/github.ts +55 -0
  55. package/lib/interpreters.ts +64 -0
  56. package/lib/issue-create-override.ts +69 -8
  57. package/lib/issue-filing-gate.ts +605 -0
  58. package/lib/js-top-level-code.ts +20 -2
  59. package/lib/junit-checks.ts +239 -1
  60. package/lib/package-closure.ts +114 -0
  61. package/lib/publish-window.ts +287 -0
  62. package/lib/scaffold/ai-review-findings.ts +142 -3
  63. package/lib/scaffold/ai-review-step.ts +1012 -18
  64. package/lib/scaffold/managed-workflow.ts +163 -4
  65. package/lib/scaffold/steps.ts +498 -22
  66. package/lib/scanner.ts +13 -4
  67. package/lib/ticked-sc-symbols.ts +361 -0
  68. package/lib/transcript-checker.ts +6 -0
  69. package/lib/workflow-actions.ts +18 -0
  70. package/package.json +3 -1
  71. package/scripts/arbitrate-finding.ts +224 -0
  72. package/scripts/generate-code-map.ts +18 -10
  73. package/scripts/sync-sc-status.ts +82 -8
@@ -0,0 +1,968 @@
1
+ import { test, expect, describe, beforeEach, afterEach } from "bun:test";
2
+ import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync, statSync } from "fs";
3
+ import { join } from "path";
4
+ import { gateSaltPath } from "../lib/paths";
5
+ import {
6
+ writeGateResult,
7
+ generateHmac,
8
+ runConvergence,
9
+ generateShipEvidence,
10
+ writeGateSummary,
11
+ writeWorkflowState,
12
+ initWorkflow,
13
+ writeACs,
14
+ markCommandlessACsAsSkip,
15
+ initBatchPlan,
16
+ recordBatchShipped,
17
+ recordBatchSkipped,
18
+ validateBatchComplete,
19
+ } from "./orchestrator";
20
+
21
+ const TMP_DIR = `/tmp/orchestrator-test-${process.pid}`;
22
+ const SF = join(TMP_DIR, "workflow-state.json");
23
+ const PROFILE = join(TMP_DIR, "ceremony-profiles.json");
24
+ const PENDING = join(process.env.HOME || "", ".claude", "MEMORY", "STATE", "gate-pending.json");
25
+
26
+ function makeState(overrides: Record<string, any> = {}): any {
27
+ return {
28
+ schemaVersion: 2,
29
+ issue: 432,
30
+ slug: "test-orch",
31
+ phase: "SCOPE",
32
+ issueGoal: "Port orchestrator",
33
+ acs: [
34
+ {
35
+ id: "SC-1",
36
+ // #339: `type` is required now — `acs-have-type` is named by every
37
+ // ceremony profile and the schema had the field optional, so the
38
+ // check could not fail. Every one of the 456 ACs in the recorded run
39
+ // history already carried one; this fixture did not.
40
+ type: "CODE",
41
+ statement: "orchestrator.ts file exists on disk and is valid",
42
+ threshold: { op: "==", value: "true" },
43
+ evidenceMethod: { type: "FILE_EXISTS" },
44
+ evidence: null,
45
+ },
46
+ ],
47
+ gates: {},
48
+ changelog: [],
49
+ sizing: { predicted: "M", ceremonyTier: "STANDARD" },
50
+ phaseTimings: {},
51
+ ...overrides,
52
+ };
53
+ }
54
+
55
+ function makeProfile(): any {
56
+ return {
57
+ tiers: {
58
+ LIGHT: { maxIterations: 3, checks: { scope: [], verify: [], ship: [] } },
59
+ STANDARD: { maxIterations: 5, checks: { scope: [], verify: [], ship: [] } },
60
+ THOROUGH: { maxIterations: 8, checks: { scope: [], verify: [], ship: [] } },
61
+ },
62
+ };
63
+ }
64
+
65
+ beforeEach(() => {
66
+ mkdirSync(TMP_DIR, { recursive: true });
67
+ writeFileSync(SF, JSON.stringify(makeState(), null, 2));
68
+ writeFileSync(PROFILE, JSON.stringify(makeProfile(), null, 2));
69
+ });
70
+
71
+ afterEach(() => {
72
+ rmSync(TMP_DIR, { recursive: true, force: true });
73
+ try { rmSync(PENDING, { force: true }); } catch {}
74
+ });
75
+
76
+ // ═══ writeGateResult ═══════════════════════════════════════════════════
77
+
78
+ describe("writeGateResult", () => {
79
+ test("writes correct gate result to workflow state", () => {
80
+ const results = [
81
+ { check: "acs-exist", result: "PASS" as const, detail: "3 ACs" },
82
+ { check: "sizing", result: "PASS" as const, detail: "size=M" },
83
+ ];
84
+ const { resultVal, attempt } = writeGateResult(SF, "scope", 2, 0, 0, results);
85
+
86
+ expect(resultVal).toBe("PASS");
87
+ expect(attempt).toBe(1);
88
+
89
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
90
+ expect(state.gates.scope.result).toBe("PASS");
91
+ expect(state.gates.scope.attempt).toBe(1);
92
+ expect(state.gates.scope.failures).toEqual([]);
93
+ expect(state.gates.scope.ts).toBeTruthy();
94
+ expect(state.gates.scope.commitSha).toBeTruthy();
95
+ });
96
+
97
+ test("records failures when checks fail", () => {
98
+ const results = [
99
+ { check: "acs-exist", result: "FAIL" as const, detail: "no ACs" },
100
+ { check: "sizing", result: "PASS" as const, detail: "size=M" },
101
+ ];
102
+ const { resultVal } = writeGateResult(SF, "scope", 1, 1, 0, results);
103
+
104
+ expect(resultVal).toBe("FAIL");
105
+
106
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
107
+ expect(state.gates.scope.result).toBe("FAIL");
108
+ expect(state.gates.scope.failures).toHaveLength(1);
109
+ expect(state.gates.scope.failures[0].check).toBe("acs-exist");
110
+ });
111
+
112
+ test("advances phase on PASS: scope->BUILD", () => {
113
+ const results = [{ check: "acs-exist", result: "PASS" as const, detail: "ok" }];
114
+ writeGateResult(SF, "scope", 1, 0, 0, results);
115
+
116
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
117
+ expect(state.phase).toBe("BUILD");
118
+ expect(state.phaseTimings.BUILD).toHaveLength(1);
119
+ expect(state.phaseTimings.BUILD[0].enteredTs).toBeTruthy();
120
+ });
121
+
122
+ test("advances phase on PASS: verify->SHIP", () => {
123
+ writeFileSync(SF, JSON.stringify(makeState({ phase: "VERIFY" }), null, 2));
124
+ const results = [{ check: "all-pass", result: "PASS" as const, detail: "ok" }];
125
+ writeGateResult(SF, "verify", 1, 0, 0, results);
126
+
127
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
128
+ expect(state.phase).toBe("SHIP");
129
+ });
130
+
131
+ test("advances phase on PASS: ship->DONE", () => {
132
+ writeFileSync(SF, JSON.stringify(makeState({ phase: "SHIP" }), null, 2));
133
+ const results = [{ check: "all-pass", result: "PASS" as const, detail: "ok" }];
134
+ writeGateResult(SF, "ship", 1, 0, 0, results);
135
+
136
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
137
+ expect(state.phase).toBe("DONE");
138
+ expect(state.mergeCommitSha).toBeTruthy();
139
+ });
140
+
141
+ test("does NOT advance phase on FAIL", () => {
142
+ const results = [{ check: "acs-exist", result: "FAIL" as const, detail: "none" }];
143
+ writeGateResult(SF, "scope", 0, 1, 0, results);
144
+
145
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
146
+ expect(state.phase).toBe("SCOPE");
147
+ });
148
+
149
+ // #514 SC-1: Phase cannot advance to DONE when non-OUTCOME AC has verdict FAIL
150
+ test("blocks ship→DONE when non-OUTCOME AC has FAIL verdict", () => {
151
+ writeFileSync(SF, JSON.stringify(makeState({
152
+ phase: "SHIP",
153
+ acs: [
154
+ {
155
+ id: "SC-1", type: "CODE",
156
+ statement: "function exists and is callable from CLI",
157
+ threshold: { op: "==", value: "true" },
158
+ evidenceMethod: { type: "GREP_CHECK" },
159
+ evidence: { type: "command-output", content: "false" },
160
+ verdict: "FAIL",
161
+ },
162
+ ],
163
+ }), null, 2));
164
+
165
+ const results = [{ check: "all-pass", result: "PASS" as const, detail: "ok" }];
166
+ const { resultVal } = writeGateResult(SF, "ship", 1, 0, 0, results);
167
+
168
+ expect(resultVal).toBe("FAIL");
169
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
170
+ expect(state.phase).not.toBe("DONE");
171
+ });
172
+
173
+ test("blocks verify→SHIP when non-OUTCOME AC has FAIL verdict", () => {
174
+ writeFileSync(SF, JSON.stringify(makeState({
175
+ phase: "VERIFY",
176
+ acs: [
177
+ {
178
+ id: "SC-1", type: "CODE",
179
+ statement: "function exists and is callable from CLI",
180
+ threshold: { op: "==", value: "true" },
181
+ evidenceMethod: { type: "GREP_CHECK" },
182
+ evidence: { type: "command-output", content: "false" },
183
+ verdict: "FAIL",
184
+ },
185
+ ],
186
+ }), null, 2));
187
+
188
+ const results = [{ check: "all-pass", result: "PASS" as const, detail: "ok" }];
189
+ const { resultVal } = writeGateResult(SF, "verify", 1, 0, 0, results);
190
+
191
+ expect(resultVal).toBe("FAIL");
192
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
193
+ expect(state.phase).not.toBe("SHIP");
194
+ });
195
+
196
+ test("allows ship→DONE when OUTCOME AC has FAIL (OUTCOME exemption)", () => {
197
+ writeFileSync(SF, JSON.stringify(makeState({
198
+ phase: "SHIP",
199
+ acs: [
200
+ {
201
+ id: "SC-1", type: "OUTCOME",
202
+ statement: "batch completes with success message visible",
203
+ threshold: { op: "==", value: "true" },
204
+ evidenceMethod: { type: "PLAYWRIGHT" },
205
+ evidence: null,
206
+ verdict: "FAIL",
207
+ },
208
+ ],
209
+ }), null, 2));
210
+
211
+ const results = [{ check: "all-pass", result: "PASS" as const, detail: "ok" }];
212
+ const { resultVal } = writeGateResult(SF, "ship", 1, 0, 0, results);
213
+
214
+ expect(resultVal).toBe("PASS");
215
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
216
+ expect(state.phase).toBe("DONE");
217
+ });
218
+
219
+ test("allows advance when all ACs are PASS or SKIP", () => {
220
+ writeFileSync(SF, JSON.stringify(makeState({
221
+ phase: "SHIP",
222
+ acs: [
223
+ {
224
+ id: "SC-1", type: "CODE",
225
+ statement: "function exists and is callable from CLI",
226
+ threshold: { op: "==", value: "true" },
227
+ evidenceMethod: { type: "GREP_CHECK", command: "echo true" },
228
+ evidence: { type: "command-output", content: "true" },
229
+ verdict: "PASS",
230
+ },
231
+ {
232
+ id: "SC-2", type: "CODE",
233
+ statement: "file includes the expected configuration value",
234
+ threshold: { op: "==", value: "true" },
235
+ evidenceMethod: { type: "FILE_EXISTS" },
236
+ evidence: { type: "manual-attestation", content: "No command" },
237
+ verdict: "SKIP",
238
+ },
239
+ ],
240
+ }), null, 2));
241
+
242
+ const results = [{ check: "all-pass", result: "PASS" as const, detail: "ok" }];
243
+ const { resultVal } = writeGateResult(SF, "ship", 1, 0, 0, results);
244
+
245
+ expect(resultVal).toBe("PASS");
246
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
247
+ expect(state.phase).toBe("DONE");
248
+ });
249
+
250
+ // #514 SC-2: Ship gate failure resets phase to VERIFY
251
+ test("ship gate FAIL resets phase to VERIFY", () => {
252
+ writeFileSync(SF, JSON.stringify(makeState({ phase: "SHIP" }), null, 2));
253
+ const results = [{ check: "code-committed", result: "FAIL" as const, detail: "not committed" }];
254
+ writeGateResult(SF, "ship", 0, 1, 0, results);
255
+
256
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
257
+ expect(state.phase).toBe("VERIFY");
258
+ const regression = state.changelog.find((e: any) => e.event === "ship-fail-regression");
259
+ expect(regression).toBeTruthy();
260
+ });
261
+
262
+ test("increments attempt number", () => {
263
+ const results = [{ check: "x", result: "FAIL" as const, detail: "d" }];
264
+ writeGateResult(SF, "scope", 0, 1, 0, results);
265
+ writeGateResult(SF, "scope", 0, 1, 0, results);
266
+
267
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
268
+ expect(state.gates.scope.attempt).toBe(2);
269
+ });
270
+ });
271
+
272
+ // ═══ generateHmac ══════════════════════════════════════════════════════
273
+
274
+ describe("generateHmac", () => {
275
+ test("computes hash and writes to workflow state", () => {
276
+ writeFileSync(SF, JSON.stringify(makeState({
277
+ phase: "SHIP",
278
+ gates: { ship: { result: "PASS", attempt: 1, failures: [], ts: "t" } },
279
+ }), null, 2));
280
+
281
+ const hash = generateHmac(SF, "test-orch", 432);
282
+ expect(hash).toHaveLength(16);
283
+ expect(/^[0-9a-f]{16}$/.test(hash)).toBe(true);
284
+
285
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
286
+ expect(state.gates.ship.hash).toBe(hash);
287
+ });
288
+
289
+ test("salt file has chmod 600", () => {
290
+ // Was `join(process.env.HOME, ".claude/hooks/lib/.gate-salt")` — a path from
291
+ // an earlier layout. generateHmac writes to gateSaltPath(), which is
292
+ // <harnessRoot>/gates/.gate-salt (lib/paths.ts:21), so this assertion had
293
+ // not been looking at the file under test for however long ago that move
294
+ // happened. It passed only because a leftover file from the old layout was
295
+ // still sitting on the developer's disk; CI, with no such leftover, got
296
+ // ENOENT. Asking the code where it writes is the whole fix.
297
+ generateHmac(SF, "test-orch", 432);
298
+
299
+ const perms = statSync(gateSaltPath()).mode & 0o777;
300
+ expect(perms).toBe(0o600);
301
+ });
302
+ });
303
+
304
+ // ═══ runConvergence ════════════════════════════════════════════════════
305
+
306
+ describe("runConvergence", () => {
307
+ test("skips when gate != verify or result != FAIL", () => {
308
+ const r1 = runConvergence(SF, "scope", "FAIL", PROFILE);
309
+ expect(r1.action).toBe("skip");
310
+
311
+ const r2 = runConvergence(SF, "verify", "PASS", PROFILE);
312
+ expect(r2.action).toBe("skip");
313
+ });
314
+
315
+ test("fires circuit breaker at maxIterations", () => {
316
+ const changelog = Array.from({ length: 4 }, (_, i) => ({
317
+ ts: "t",
318
+ event: "iteration-loopback",
319
+ detail: `iteration ${i + 1}`,
320
+ failureHash: `fail-${i}`,
321
+ actor: "gate-runner",
322
+ }));
323
+
324
+ writeFileSync(SF, JSON.stringify(makeState({
325
+ phase: "VERIFY",
326
+ changelog,
327
+ gates: { verify: { result: "FAIL", failures: [{ check: "x", result: "FAIL", detail: "d" }] } },
328
+ }), null, 2));
329
+
330
+ const result = runConvergence(SF, "verify", "FAIL", PROFILE);
331
+ expect(result.action).toBe("circuit-break");
332
+ expect(result.iteration).toBe(5);
333
+
334
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
335
+ expect(state.phase).toBe("CIRCUIT_BREAK");
336
+ });
337
+
338
+ test("detects stall: same failureHash in consecutive iterations", () => {
339
+ const changelog = [
340
+ {
341
+ ts: "t",
342
+ event: "iteration-loopback",
343
+ detail: "iteration 1",
344
+ failureHash: "x",
345
+ actor: "gate-runner",
346
+ },
347
+ ];
348
+
349
+ writeFileSync(SF, JSON.stringify(makeState({
350
+ phase: "VERIFY",
351
+ changelog,
352
+ gates: { verify: { result: "FAIL", failures: [{ check: "x", result: "FAIL", detail: "d" }] } },
353
+ }), null, 2));
354
+
355
+ const result = runConvergence(SF, "verify", "FAIL", PROFILE);
356
+ expect(result.action).toBe("stall");
357
+
358
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
359
+ const councilEvents = state.changelog.filter((e: any) => e.event === "council-recommended");
360
+ expect(councilEvents.length).toBe(1);
361
+ });
362
+
363
+ test("preserves read-before-append ordering", () => {
364
+ writeFileSync(SF, JSON.stringify(makeState({
365
+ phase: "VERIFY",
366
+ changelog: [],
367
+ gates: { verify: { result: "FAIL", failures: [{ check: "a", result: "FAIL", detail: "d" }] } },
368
+ }), null, 2));
369
+
370
+ // First iteration — no previous hash to compare
371
+ const r1 = runConvergence(SF, "verify", "FAIL", PROFILE);
372
+ expect(r1.action).toBe("loop-back");
373
+
374
+ // Second iteration with different failures — should NOT be stall
375
+ const state2 = JSON.parse(readFileSync(SF, "utf-8"));
376
+ state2.gates.verify.failures = [{ check: "b", result: "FAIL", detail: "d" }];
377
+ writeFileSync(SF, JSON.stringify(state2, null, 2));
378
+
379
+ const r2 = runConvergence(SF, "verify", "FAIL", PROFILE);
380
+ expect(r2.action).toBe("loop-back");
381
+
382
+ const finalState = JSON.parse(readFileSync(SF, "utf-8"));
383
+ const loopbacks = finalState.changelog.filter((e: any) => e.event === "iteration-loopback");
384
+ expect(loopbacks).toHaveLength(2);
385
+ expect(loopbacks[0].failureHash).not.toBe(loopbacks[1].failureHash);
386
+ });
387
+
388
+ test("loops back to BUILD phase", () => {
389
+ writeFileSync(SF, JSON.stringify(makeState({
390
+ phase: "VERIFY",
391
+ gates: { verify: { result: "FAIL", failures: [{ check: "x", result: "FAIL", detail: "d" }] } },
392
+ }), null, 2));
393
+
394
+ runConvergence(SF, "verify", "FAIL", PROFILE);
395
+
396
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
397
+ expect(state.phase).toBe("BUILD");
398
+ expect(state.phaseTimings.BUILD).toHaveLength(1);
399
+ });
400
+ });
401
+
402
+ // ═══ generateShipEvidence ══════════════════════════════════════════════
403
+
404
+ describe("generateShipEvidence", () => {
405
+ test("writes valid ship-evidence.json", () => {
406
+ writeFileSync(SF, JSON.stringify(makeState({
407
+ phase: "SHIP",
408
+ acs: [
409
+ {
410
+ id: "SC-1",
411
+ statement: "file exists on disk and is accessible",
412
+ verdict: "PASS",
413
+ evidence: { type: "file-citation", content: "found" },
414
+ threshold: { op: "==", value: "true" },
415
+ evidenceMethod: { type: "FILE_EXISTS" },
416
+ },
417
+ ],
418
+ }), null, 2));
419
+
420
+ const path = generateShipEvidence(SF, TMP_DIR, 432, "", 1, 0, 0);
421
+
422
+ expect(existsSync(path)).toBe(true);
423
+ const evidence = JSON.parse(readFileSync(path, "utf-8"));
424
+ expect(evidence.contractVersion).toBe("1.0");
425
+ expect(evidence.issueNumber).toBe(432);
426
+ expect(evidence.gateOut.status).toBe("PASS");
427
+ expect(evidence.gateOut.evidence).toHaveLength(1);
428
+ expect(evidence.mergeCommitSha).toBeTruthy();
429
+ expect(evidence.capturedAt).toBeTruthy();
430
+ expect(evidence.iterationCount).toBeGreaterThanOrEqual(1);
431
+ expect(evidence.sizing.predicted).toBe("M");
432
+ });
433
+ });
434
+
435
+ // ═══ writeGateSummary ══════════════════════════════════════════════════
436
+
437
+ describe("writeGateSummary", () => {
438
+ test("writes gate-pending.json on FAIL", () => {
439
+ const results = [
440
+ { check: "acs-exist", result: "FAIL" as const, detail: "no ACs" },
441
+ ];
442
+
443
+ const outcome = writeGateSummary("scope", 0, 1, 0, results, 432, "test", "sess-1");
444
+
445
+ expect(outcome).toBe("BLOCKED");
446
+ expect(existsSync(PENDING)).toBe(true);
447
+
448
+ const pending = JSON.parse(readFileSync(PENDING, "utf-8"));
449
+ expect(pending.gate).toBe("scope");
450
+ expect(pending.issue).toBe(432);
451
+ expect(pending.failures).toHaveLength(1);
452
+ expect(pending.failures[0].check).toBe("acs-exist");
453
+ expect(pending.strike_count).toBe(0);
454
+ expect(pending.max_strikes).toBe(3);
455
+ });
456
+
457
+ test("deletes gate-pending.json on PASS", () => {
458
+ // Create a pending file first
459
+ mkdirSync(join(process.env.HOME || "", ".claude", "MEMORY", "STATE"), { recursive: true });
460
+ writeFileSync(PENDING, JSON.stringify({ gate: "old" }));
461
+ expect(existsSync(PENDING)).toBe(true);
462
+
463
+ const results = [
464
+ { check: "acs-exist", result: "PASS" as const, detail: "3 ACs" },
465
+ ];
466
+ const outcome = writeGateSummary("scope", 1, 0, 0, results, 432, "test", "sess-1");
467
+
468
+ expect(outcome).toBe("ALL CLEAR");
469
+ expect(existsSync(PENDING)).toBe(false);
470
+ });
471
+ });
472
+
473
+ // ═══ writeWorkflowState ══════════════════════════════════════════════════
474
+
475
+ describe("writeWorkflowState", () => {
476
+ test("writes valid state to disk", () => {
477
+ const state = makeState();
478
+ writeWorkflowState(SF, state);
479
+ const written = JSON.parse(readFileSync(SF, "utf-8"));
480
+ expect(written.schemaVersion).toBe(2);
481
+ expect(written.phase).toBe("SCOPE");
482
+ expect(written.slug).toBe("test-orch");
483
+ });
484
+
485
+ test("throws on invalid phase enum", () => {
486
+ const state = makeState({ phase: "INVALID_PHASE" });
487
+ expect(() => writeWorkflowState(SF, state)).toThrow(/expected/i);
488
+ });
489
+
490
+ test("throws on invalid threshold op 'eq'", () => {
491
+ const state = makeState({
492
+ acs: [{
493
+ id: "SC-1",
494
+ statement: "test fixture validates gate behavior correctly",
495
+ threshold: { op: "eq", value: "true" },
496
+ evidenceMethod: { type: "GREP_CHECK" },
497
+ evidence: null,
498
+ }],
499
+ });
500
+ expect(() => writeWorkflowState(SF, state)).toThrow(/expected/i);
501
+ });
502
+
503
+ test("error message includes valid enum values", () => {
504
+ const state = makeState({ phase: "BOGUS" });
505
+ try {
506
+ writeWorkflowState(SF, state);
507
+ throw new Error("should have thrown");
508
+ } catch (err: any) {
509
+ expect(err.message).toContain("GOAL");
510
+ expect(err.message).toContain("BUILD");
511
+ expect(err.message).toContain("VERIFY");
512
+ }
513
+ });
514
+
515
+ test("passes through extra fields via passthrough()", () => {
516
+ const state = { ...makeState(), customField: "preserved" };
517
+ writeWorkflowState(SF, state);
518
+ const written = JSON.parse(readFileSync(SF, "utf-8"));
519
+ expect(written.customField).toBe("preserved");
520
+ });
521
+ });
522
+
523
+ // ═══ initWorkflow ════════════════════════════════════════════════════════
524
+
525
+ describe("initWorkflow", () => {
526
+ test("creates workflow-state.json with correct initial structure", () => {
527
+ const target = join(TMP_DIR, "sub", "workflow-state.json");
528
+ initWorkflow(target, {
529
+ issue: 453,
530
+ repo: "hornjason/pai-config",
531
+ projectRoot: "/tmp/test",
532
+ slug: "write-time-validation",
533
+ issueGoal: "Add Zod write-time validation",
534
+ });
535
+
536
+ expect(existsSync(target)).toBe(true);
537
+ const state = JSON.parse(readFileSync(target, "utf-8"));
538
+ expect(state.schemaVersion).toBe(2);
539
+ expect(state.phase).toBe("GOAL");
540
+ expect(state.acs).toEqual([]);
541
+ expect(state.gates).toEqual({});
542
+ expect(state.changelog).toEqual([]);
543
+ expect(state.issue).toBe(453);
544
+ expect(state.slug).toBe("write-time-validation");
545
+ expect(state.issueGoal).toBe("Add Zod write-time validation");
546
+ });
547
+
548
+ test("sets issueRepo to opts.issueRepo when provided", () => {
549
+ const target = join(TMP_DIR, "init-test-1.json");
550
+ initWorkflow(target, {
551
+ issue: 453,
552
+ repo: "hornjason/pai-config",
553
+ issueRepo: "hornjason/asaCommandCenter",
554
+ projectRoot: "/tmp/test",
555
+ slug: "test",
556
+ issueGoal: "test goal",
557
+ });
558
+
559
+ const state = JSON.parse(readFileSync(target, "utf-8"));
560
+ expect(state.issueRepo).toBe("hornjason/asaCommandCenter");
561
+ });
562
+
563
+ test("defaults issueRepo to opts.repo when not provided", () => {
564
+ const target = join(TMP_DIR, "init-test-2.json");
565
+ initWorkflow(target, {
566
+ issue: 453,
567
+ repo: "hornjason/pai-config",
568
+ projectRoot: "/tmp/test",
569
+ slug: "test",
570
+ issueGoal: "test goal",
571
+ });
572
+
573
+ const state = JSON.parse(readFileSync(target, "utf-8"));
574
+ expect(state.issueRepo).toBe("hornjason/pai-config");
575
+ });
576
+
577
+ test("creates parent directory if it doesn't exist", () => {
578
+ const target = join(TMP_DIR, "deep", "nested", "dir", "workflow-state.json");
579
+ initWorkflow(target, {
580
+ issue: 453,
581
+ repo: "hornjason/pai-config",
582
+ projectRoot: "/tmp/test",
583
+ slug: "test",
584
+ issueGoal: "test goal",
585
+ });
586
+
587
+ expect(existsSync(target)).toBe(true);
588
+ });
589
+
590
+ test("includes optional fields when provided", () => {
591
+ const target = join(TMP_DIR, "init-opts.json");
592
+ initWorkflow(target, {
593
+ issue: 453,
594
+ repo: "hornjason/pai-config",
595
+ projectRoot: "/tmp/test",
596
+ slug: "test",
597
+ issueGoal: "test goal",
598
+ sizing: { predicted: "M", ceremonyTier: "STANDARD" },
599
+ sourceSpecs: [{ path: "spec.md", citedInDiscovery: true }],
600
+ bootstrappedFrom: "session-abc",
601
+ });
602
+
603
+ const state = JSON.parse(readFileSync(target, "utf-8"));
604
+ expect(state.sizing.predicted).toBe("M");
605
+ expect(state.sourceSpecs).toHaveLength(1);
606
+ expect(state.bootstrappedFrom).toBe("session-abc");
607
+ });
608
+ });
609
+
610
+ // ═══ writeACs ════════════════════════════════════════════════════════════
611
+
612
+ describe("writeACs", () => {
613
+ test("writes ACs with evidence null and verdict PENDING", () => {
614
+ writeFileSync(SF, JSON.stringify(makeState(), null, 2));
615
+ writeACs(SF, [
616
+ {
617
+ id: "SC-1",
618
+ type: "CODE",
619
+ statement: "writeWorkflowState function exists and is callable",
620
+ threshold: { op: "==", value: "true" },
621
+ evidenceMethod: { type: "GREP_CHECK" },
622
+ },
623
+ {
624
+ id: "SC-2",
625
+ type: "OUTCOME",
626
+ statement: "invalid enum value throws validation error",
627
+ threshold: { op: ">=", value: "2" },
628
+ evidenceMethod: { type: "BUN_TEST" },
629
+ },
630
+ ]);
631
+
632
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
633
+ expect(state.acs).toHaveLength(2);
634
+ expect(state.acs[0].evidence).toBeNull();
635
+ expect(state.acs[0].verdict).toBe("PENDING");
636
+ expect(state.acs[1].evidence).toBeNull();
637
+ expect(state.acs[1].verdict).toBe("PENDING");
638
+ });
639
+
640
+ test("writes ACs with invalid type enum (warns, caught at gate time)", () => {
641
+ writeFileSync(SF, JSON.stringify(makeState(), null, 2));
642
+ writeACs(SF, [
643
+ {
644
+ id: "SC-1",
645
+ type: "INVALID_TYPE" as any,
646
+ statement: "test fixture validates gate behavior correctly",
647
+ threshold: { op: "==", value: "true" },
648
+ evidenceMethod: { type: "GREP_CHECK" },
649
+ },
650
+ ]);
651
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
652
+ expect(state.acs).toHaveLength(1);
653
+ expect(state.acs[0].id).toBe("SC-1");
654
+ });
655
+
656
+ test("writes ACs with invalid threshold op (warns, caught at gate time)", () => {
657
+ writeFileSync(SF, JSON.stringify(makeState(), null, 2));
658
+ writeACs(SF, [
659
+ {
660
+ id: "SC-1",
661
+ statement: "test fixture validates gate behavior correctly",
662
+ threshold: { op: "eq" as any, value: "true" },
663
+ evidenceMethod: { type: "GREP_CHECK" },
664
+ },
665
+ ]);
666
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
667
+ expect(state.acs).toHaveLength(1);
668
+ expect(state.acs[0].id).toBe("SC-1");
669
+ });
670
+
671
+ test("preserves existing state fields", () => {
672
+ writeFileSync(SF, JSON.stringify(makeState({
673
+ phase: "BUILD",
674
+ gates: { scope: { result: "PASS", attempt: 1 } },
675
+ }), null, 2));
676
+
677
+ writeACs(SF, [
678
+ {
679
+ id: "SC-1",
680
+ statement: "test fixture validates gate behavior correctly",
681
+ threshold: { op: "==", value: "true" },
682
+ evidenceMethod: { type: "GREP_CHECK" },
683
+ },
684
+ ]);
685
+
686
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
687
+ expect(state.phase).toBe("BUILD");
688
+ expect(state.gates.scope.result).toBe("PASS");
689
+ expect(state.acs).toHaveLength(1);
690
+ });
691
+ });
692
+
693
+ // ═══ AFK Batch Plan (#468) ═══════════════════════════════════════════
694
+
695
+ describe("initBatchPlan", () => {
696
+ test("creates valid afk-batch.json with planned issues", () => {
697
+ const batchDir = join(TMP_DIR, "batch");
698
+ initBatchPlan(batchDir, [100, 101, 102]);
699
+
700
+ const fp = join(batchDir, "afk-batch.json");
701
+ expect(existsSync(fp)).toBe(true);
702
+
703
+ const plan = JSON.parse(readFileSync(fp, "utf-8"));
704
+ expect(plan.planned).toEqual([100, 101, 102]);
705
+ expect(plan.shipped).toEqual([]);
706
+ expect(plan.skipped).toEqual([]);
707
+ expect(plan.inProgress).toBeNull();
708
+ expect(plan.approvedAt).toBeTruthy();
709
+ });
710
+
711
+ test("creates parent directory if needed", () => {
712
+ const batchDir = join(TMP_DIR, "deep", "nested", "batch");
713
+ initBatchPlan(batchDir, [200]);
714
+
715
+ expect(existsSync(join(batchDir, "afk-batch.json"))).toBe(true);
716
+ });
717
+ });
718
+
719
+ describe("recordBatchShipped", () => {
720
+ test("moves issue to shipped array", () => {
721
+ const batchDir = join(TMP_DIR, "batch-ship");
722
+ initBatchPlan(batchDir, [100, 101, 102]);
723
+ recordBatchShipped(batchDir, 100);
724
+
725
+ const plan = JSON.parse(readFileSync(join(batchDir, "afk-batch.json"), "utf-8"));
726
+ expect(plan.shipped).toEqual([100]);
727
+ expect(plan.planned).toEqual([100, 101, 102]);
728
+ });
729
+
730
+ test("does not duplicate if called twice", () => {
731
+ const batchDir = join(TMP_DIR, "batch-ship-dup");
732
+ initBatchPlan(batchDir, [100]);
733
+ recordBatchShipped(batchDir, 100);
734
+ recordBatchShipped(batchDir, 100);
735
+
736
+ const plan = JSON.parse(readFileSync(join(batchDir, "afk-batch.json"), "utf-8"));
737
+ expect(plan.shipped).toEqual([100]);
738
+ });
739
+
740
+ test("clears inProgress when shipped issue matches", () => {
741
+ const batchDir = join(TMP_DIR, "batch-ship-ip");
742
+ initBatchPlan(batchDir, [100, 101]);
743
+
744
+ // Manually set inProgress
745
+ const fp = join(batchDir, "afk-batch.json");
746
+ const plan = JSON.parse(readFileSync(fp, "utf-8"));
747
+ plan.inProgress = 100;
748
+ writeFileSync(fp, JSON.stringify(plan, null, 2));
749
+
750
+ recordBatchShipped(batchDir, 100);
751
+
752
+ const updated = JSON.parse(readFileSync(fp, "utf-8"));
753
+ expect(updated.inProgress).toBeNull();
754
+ });
755
+ });
756
+
757
+ describe("recordBatchSkipped", () => {
758
+ test("rejects 'needs investigation' as skip reason", () => {
759
+ const batchDir = join(TMP_DIR, "batch-skip-reject");
760
+ initBatchPlan(batchDir, [100]);
761
+
762
+ expect(() => recordBatchSkipped(batchDir, 100, "needs investigation")).toThrow(/Rejected skip reason/);
763
+ });
764
+
765
+ test("rejects 'needs browser testing' as skip reason", () => {
766
+ const batchDir = join(TMP_DIR, "batch-skip-reject2");
767
+ initBatchPlan(batchDir, [100]);
768
+
769
+ expect(() => recordBatchSkipped(batchDir, 100, "needs browser testing")).toThrow(/Rejected skip reason/);
770
+ });
771
+
772
+ test("rejects 'can't do from here' as skip reason", () => {
773
+ const batchDir = join(TMP_DIR, "batch-skip-reject3");
774
+ initBatchPlan(batchDir, [100]);
775
+
776
+ expect(() => recordBatchSkipped(batchDir, 100, "can't do from here")).toThrow(/Rejected skip reason/);
777
+ });
778
+
779
+ test("accepts valid skip reason with delegation action", () => {
780
+ const batchDir = join(TMP_DIR, "batch-skip-valid");
781
+ initBatchPlan(batchDir, [100, 101]);
782
+
783
+ recordBatchSkipped(batchDir, 100, "spawned Quinn, awaiting results", "Quinn QA pass pending");
784
+
785
+ const plan = JSON.parse(readFileSync(join(batchDir, "afk-batch.json"), "utf-8"));
786
+ expect(plan.skipped).toHaveLength(1);
787
+ expect(plan.skipped[0].issue).toBe(100);
788
+ expect(plan.skipped[0].reason).toBe("spawned Quinn, awaiting results");
789
+ expect(plan.skipped[0].delegationAction).toBe("Quinn QA pass pending");
790
+ });
791
+
792
+ test("accepts 'closed as by-design with evidence' as skip reason", () => {
793
+ const batchDir = join(TMP_DIR, "batch-skip-bydesign");
794
+ initBatchPlan(batchDir, [100]);
795
+
796
+ recordBatchSkipped(batchDir, 100, "closed as by-design with evidence");
797
+
798
+ const plan = JSON.parse(readFileSync(join(batchDir, "afk-batch.json"), "utf-8"));
799
+ expect(plan.skipped).toHaveLength(1);
800
+ });
801
+
802
+ test("clears inProgress when skipped issue matches", () => {
803
+ const batchDir = join(TMP_DIR, "batch-skip-ip");
804
+ initBatchPlan(batchDir, [100]);
805
+
806
+ const fp = join(batchDir, "afk-batch.json");
807
+ const plan = JSON.parse(readFileSync(fp, "utf-8"));
808
+ plan.inProgress = 100;
809
+ writeFileSync(fp, JSON.stringify(plan, null, 2));
810
+
811
+ recordBatchSkipped(batchDir, 100, "closed as by-design with evidence");
812
+
813
+ const updated = JSON.parse(readFileSync(fp, "utf-8"));
814
+ expect(updated.inProgress).toBeNull();
815
+ });
816
+ });
817
+
818
+ describe("validateBatchComplete", () => {
819
+ test("returns complete when all planned issues are shipped", () => {
820
+ const batchDir = join(TMP_DIR, "batch-complete");
821
+ initBatchPlan(batchDir, [100, 101, 102]);
822
+ recordBatchShipped(batchDir, 100);
823
+ recordBatchShipped(batchDir, 101);
824
+ recordBatchShipped(batchDir, 102);
825
+
826
+ const result = validateBatchComplete(batchDir);
827
+ expect(result.complete).toBe(true);
828
+ expect(result.missing).toEqual([]);
829
+ });
830
+
831
+ test("returns complete when mix of shipped and skipped covers all planned", () => {
832
+ const batchDir = join(TMP_DIR, "batch-complete-mix");
833
+ initBatchPlan(batchDir, [100, 101, 102]);
834
+ recordBatchShipped(batchDir, 100);
835
+ recordBatchShipped(batchDir, 101);
836
+ recordBatchSkipped(batchDir, 102, "closed as by-design with evidence");
837
+
838
+ const result = validateBatchComplete(batchDir);
839
+ expect(result.complete).toBe(true);
840
+ expect(result.missing).toEqual([]);
841
+ });
842
+
843
+ test("returns incomplete with missing issues", () => {
844
+ const batchDir = join(TMP_DIR, "batch-incomplete");
845
+ initBatchPlan(batchDir, [100, 101, 102]);
846
+ recordBatchShipped(batchDir, 100);
847
+
848
+ const result = validateBatchComplete(batchDir);
849
+ expect(result.complete).toBe(false);
850
+ expect(result.missing).toEqual([101, 102]);
851
+ });
852
+
853
+ test("returns complete for empty plan", () => {
854
+ const batchDir = join(TMP_DIR, "batch-empty");
855
+ initBatchPlan(batchDir, []);
856
+
857
+ const result = validateBatchComplete(batchDir);
858
+ expect(result.complete).toBe(true);
859
+ expect(result.missing).toEqual([]);
860
+ });
861
+ });
862
+
863
+ // ═══ markCommandlessACsAsSkip (#513) ══════════════════════════════════
864
+
865
+ describe("markCommandlessACsAsSkip", () => {
866
+ test("marks ACs without evidenceMethod.command as SKIP", () => {
867
+ writeFileSync(SF, JSON.stringify(makeState({
868
+ acs: [
869
+ {
870
+ id: "SC-1",
871
+ statement: "function exists and is callable from CLI",
872
+ threshold: { op: "==", value: "true" },
873
+ evidenceMethod: { type: "FILE_EXISTS" },
874
+ evidence: null,
875
+ verdict: "PENDING",
876
+ },
877
+ ],
878
+ }), null, 2));
879
+
880
+ const count = markCommandlessACsAsSkip(SF);
881
+ expect(count).toBe(1);
882
+
883
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
884
+ expect(state.acs[0].verdict).toBe("SKIP");
885
+ expect(state.acs[0].evidence.content).toContain("No evidenceMethod.command");
886
+ });
887
+
888
+ test("does not touch ACs with a command", () => {
889
+ writeFileSync(SF, JSON.stringify(makeState({
890
+ acs: [
891
+ {
892
+ id: "SC-1",
893
+ statement: "function exists and is callable from CLI",
894
+ threshold: { op: "==", value: "true" },
895
+ evidenceMethod: { type: "COMMAND", command: "echo true" },
896
+ evidence: null,
897
+ verdict: "PENDING",
898
+ },
899
+ ],
900
+ }), null, 2));
901
+
902
+ const count = markCommandlessACsAsSkip(SF);
903
+ expect(count).toBe(0);
904
+
905
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
906
+ expect(state.acs[0].verdict).toBe("PENDING");
907
+ });
908
+
909
+ test("skips ACs that already have non-PENDING verdict", () => {
910
+ writeFileSync(SF, JSON.stringify(makeState({
911
+ acs: [
912
+ {
913
+ id: "SC-1",
914
+ statement: "function exists and is callable from CLI",
915
+ threshold: { op: "==", value: "true" },
916
+ evidenceMethod: { type: "FILE_EXISTS" },
917
+ evidence: { type: "command-output", content: "true" },
918
+ verdict: "PASS",
919
+ },
920
+ ],
921
+ }), null, 2));
922
+
923
+ const count = markCommandlessACsAsSkip(SF);
924
+ expect(count).toBe(0);
925
+
926
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
927
+ expect(state.acs[0].verdict).toBe("PASS");
928
+ });
929
+
930
+ test("handles mixed ACs — only marks commandless PENDING ones", () => {
931
+ writeFileSync(SF, JSON.stringify(makeState({
932
+ acs: [
933
+ {
934
+ id: "SC-1",
935
+ statement: "function exists and is callable from CLI",
936
+ threshold: { op: "==", value: "true" },
937
+ evidenceMethod: { type: "COMMAND", command: "echo true" },
938
+ evidence: null,
939
+ verdict: "PENDING",
940
+ },
941
+ {
942
+ id: "SC-2",
943
+ statement: "file includes the expected configuration value",
944
+ threshold: { op: "==", value: "true" },
945
+ evidenceMethod: { type: "FILE_EXISTS" },
946
+ evidence: null,
947
+ verdict: "PENDING",
948
+ },
949
+ {
950
+ id: "SC-3",
951
+ statement: "output matches the expected formatting pattern",
952
+ threshold: { op: "==", value: "true" },
953
+ evidenceMethod: { type: "COMMAND", command: "echo true" },
954
+ evidence: { type: "command-output", content: "true" },
955
+ verdict: "PASS",
956
+ },
957
+ ],
958
+ }), null, 2));
959
+
960
+ const count = markCommandlessACsAsSkip(SF);
961
+ expect(count).toBe(1);
962
+
963
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
964
+ expect(state.acs[0].verdict).toBe("PENDING");
965
+ expect(state.acs[1].verdict).toBe("SKIP");
966
+ expect(state.acs[2].verdict).toBe("PASS");
967
+ });
968
+ });