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,827 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync, statSync, unlinkSync, appendFileSync } from "fs";
2
+ import { join, dirname } from "path";
3
+ import { createHash, createHmac, randomBytes } from "crypto";
4
+ import { execSync } from "child_process";
5
+ import { WorkflowStateSchema, ACSchema, AfkBatchPlanSchema, REJECTED_SKIP_REASONS } from "./schema";
6
+ import { ZodError } from "zod";
7
+ import { createGitHubClient, addLabels, addComment, type GitHubClient } from "../lib/github";
8
+ import { computeACHash } from "../lib/workflow-security";
9
+ import { verifiedPush, leftWorkLocal, type PushOutcome } from "../lib/verified-push";
10
+ import { acProvenance, beginRun } from "./run-attribution";
11
+ import { unionNames } from "../lib/junit-checks";
12
+ import { recordStateWrite } from "../lib/trajectory";
13
+
14
+ /**
15
+ * ADR-009 acHash over AC *definition* fields only.
16
+ *
17
+ * This projection + hash was duplicated verbatim at the scope-PASS site and
18
+ * the writeWorkflowState site. #43 was an acHash bug; having two copies is
19
+ * how a fix lands in one of them and not the other. Both now call this, and
20
+ * this delegates to lib/workflow-security.ts so the shipped helper and the
21
+ * production path cannot diverge (they previously did — the lib sorts, these
22
+ * did not, so the "extracted" function computed a different hash than the
23
+ * code it was extracted from).
24
+ *
25
+ * Verdict and evidence fields are excluded on purpose: gates populate them
26
+ * after scope, and including them caused false mismatches.
27
+ */
28
+ export function hashAcDefinitions(acs: Array<Record<string, unknown>>): string {
29
+ return computeACHash(
30
+ acs.map((ac) => ({
31
+ id: ac.id, type: ac.type, statement: ac.statement,
32
+ specElement: ac.specElement, threshold: ac.threshold,
33
+ evidenceMethod: ac.evidenceMethod,
34
+ })) as any,
35
+ );
36
+ }
37
+
38
+ export interface GateResult {
39
+ check: string;
40
+ result: "PASS" | "FAIL" | "WARN";
41
+ detail: string;
42
+ }
43
+
44
+ // ── Gate contract interfaces (SC-373) ─────────────────────────────────────
45
+
46
+ export interface WriteGateResultInput {
47
+ sf: string;
48
+ gate: string;
49
+ passes: number;
50
+ fails: number;
51
+ warns: number;
52
+ results: GateResult[];
53
+ projectRoot?: string;
54
+ }
55
+
56
+ export interface InitWorkflowInput {
57
+ issue: number;
58
+ repo: string;
59
+ issueRepo?: string;
60
+ projectRoot: string;
61
+ slug: string;
62
+ issueGoal: string;
63
+ sizing?: { predicted?: string; ceremonyTier?: string };
64
+ sourceSpecs?: Array<{ path: string; citedInDiscovery: boolean; specElements?: string[] }>;
65
+ bootstrappedFrom?: string;
66
+ /** The coverage decision discovery made (#251). Null when it made none. */
67
+ acCoverage?: {
68
+ criteriaCount: number;
69
+ acCount: number;
70
+ covered: string[];
71
+ deferrals: Array<{ specElement: string; reason: string; subIssue?: number }>;
72
+ uncovered: string[];
73
+ } | null;
74
+ /**
75
+ * The prior branch this run adopted work from, as detection reported it
76
+ * (#288).
77
+ *
78
+ * Declared so it cannot be dropped again without a type error. ship.js has
79
+ * passed this since the field existed, and nothing persisted it: the call
80
+ * is assembled into a `bun -e` template string and evaluated at runtime, so
81
+ * TypeScript never saw the excess property and the drop was silent.
82
+ *
83
+ * `undefined` and `null` are different. Absent means nothing looked;
84
+ * `null` means detection ran and found none. Writing `null` for both is
85
+ * what makes #185 and #223 so hard to investigate — prior-branch detection
86
+ * leaves no trace, so every post-mortem reconstructs it from scratch.
87
+ */
88
+ priorWork?: {
89
+ branch?: string;
90
+ refName?: string;
91
+ commitCount?: number | null;
92
+ acStatus?: Array<{ id: string; status: string; evidence?: string }>;
93
+ } | null;
94
+ }
95
+
96
+ interface WorkflowState {
97
+ [key: string]: any;
98
+ }
99
+
100
+ function readState(sf: string): WorkflowState {
101
+ return JSON.parse(readFileSync(sf, "utf-8"));
102
+ }
103
+
104
+ function writeState(sf: string, state: WorkflowState): void {
105
+ const tmp = `${sf}.${process.pid}.tmp`;
106
+ const json = JSON.stringify(state, null, 2);
107
+ writeFileSync(tmp, json);
108
+ try {
109
+ JSON.parse(readFileSync(tmp, "utf-8"));
110
+ const { renameSync } = require("fs");
111
+ renameSync(tmp, sf);
112
+ } catch {
113
+ try { unlinkSync(tmp); } catch {}
114
+ throw new Error("writeState produced invalid JSON");
115
+ }
116
+ }
117
+
118
+ function gitSha(cwd?: string): string {
119
+ try {
120
+ return execSync("git rev-parse HEAD", { encoding: "utf-8", timeout: 5000, cwd }).trim();
121
+ } catch {
122
+ return "unknown";
123
+ }
124
+ }
125
+
126
+ function isoNow(): string {
127
+ return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
128
+ }
129
+
130
+ const PHASE_ADVANCE: Record<string, string> = {
131
+ scope: "BUILD",
132
+ verify: "SHIP",
133
+ ship: "DONE",
134
+ };
135
+
136
+ export function writeGateResult(
137
+ sf: string,
138
+ gate: string,
139
+ passes: number,
140
+ fails: number,
141
+ warns: number,
142
+ results: GateResult[],
143
+ projectRoot?: string,
144
+ checksRun?: string[] | null,
145
+ ): { resultVal: "PASS" | "FAIL"; attempt: number } {
146
+ const state = readState(sf);
147
+ let resultVal: "PASS" | "FAIL" = fails === 0 ? "PASS" : "FAIL";
148
+
149
+ // #514: Block phase advance when non-OUTCOME ACs have FAIL verdicts
150
+ if ((gate === "verify" || gate === "ship") && resultVal === "PASS") {
151
+ const failedACs = (state.acs || []).filter(
152
+ (ac: any) => ac.verdict === "FAIL" && ac.type !== "OUTCOME"
153
+ );
154
+ if (failedACs.length > 0) {
155
+ resultVal = "FAIL";
156
+ for (const ac of failedACs) {
157
+ results.push({
158
+ check: `ac-verdict-fail: ${ac.id}`,
159
+ result: "FAIL",
160
+ detail: `${ac.id} has FAIL verdict`,
161
+ });
162
+ }
163
+ fails += failedACs.length;
164
+ }
165
+ }
166
+
167
+ const prev = state.gates?.[gate]?.attempt ?? 0;
168
+ const attempt = prev + 1;
169
+ const ts = isoNow();
170
+ // #531. The TREE UNDER TEST, not the project root. `commitSha` is read back
171
+ // by three gate checks to build "what did this branch change", and on a
172
+ // worktree run `projectRoot` is the main checkout — which is sitting on
173
+ // whatever branch somebody left it on. Run `wf_e230fddc-a71` recorded the
174
+ // tip of an unrelated branch and the gate then refused over a Dockerfile
175
+ // and seven `.tsx` files the shipped branch has never contained. The state
176
+ // named the right tree the whole time; the writer read HEAD from somewhere
177
+ // else. Same precedent as the test census at
178
+ // `gates/gate-executor.ts`'s `censusRoot`.
179
+ //
180
+ // `treeUnderTest` comes out of the state file, so it is a state-controlled
181
+ // working directory. Three things bound that, and they are written down
182
+ // because "it was already like this" is not a containment argument:
183
+ // `gitSha` spawns a FIXED command and passes the path as `cwd`, not into a
184
+ // shell, so there is nothing to inject; it is the same value `treeRoot()`
185
+ // already hands to the three diff reads and `censusRoot` to the census, so
186
+ // this introduces no new trust; and a path that is not a git tree yields
187
+ // `"unknown"`, which `lib/branch-diff.ts` refuses by name rather than
188
+ // sending to git as a revision.
189
+ const sha = gitSha(state.treeUnderTest || projectRoot);
190
+
191
+ const failures = results.filter(r => r.result === "FAIL");
192
+
193
+ // #532. Every check this run reported a verdict for, PASS and FAIL alike.
194
+ // The ship gate re-runs the verify checks, so a `verify checks >` name
195
+ // missing from `gates.ship.failures` means either it passed there or ship
196
+ // never ran it — opposite facts, and the failure list cannot tell them
197
+ // apart. This is the positive witness that can.
198
+ //
199
+ // It is NOT `results.map(...)`: bun prints no `(pass)` markers, so
200
+ // `results` is a failure list and a `checksRun` built from it would retire
201
+ // nothing on any run that has ever happened. The names come from the
202
+ // JUnit report the gate run wrote (lib/junit-checks.ts); the union below
203
+ // adds the verdicts this function appends after the caller read them.
204
+ //
205
+ // `undefined` and `null` are both "this gate said nothing about what it
206
+ // ran", and the field is left OFF rather than written empty — an empty
207
+ // list says the gate ran nothing, which is a claim, and a wrong one.
208
+ const measuredChecks = unionNames(checksRun ?? null, results.map(r => r.check));
209
+
210
+ state.gates = state.gates || {};
211
+ state.gates[gate] = {
212
+ result: resultVal,
213
+ attempt,
214
+ failures,
215
+ ...(measuredChecks === null ? {} : { checksRun: measuredChecks }),
216
+ ts,
217
+ commitSha: sha,
218
+ };
219
+ state.updatedTs = ts;
220
+ state.changelog = state.changelog || [];
221
+ state.changelog.push({
222
+ ts,
223
+ event: `gate-${gate}`,
224
+ detail: `${passes} pass, ${fails} fail, ${warns} warn`,
225
+ actor: "gate-runner",
226
+ });
227
+
228
+ // ADR-009: Record AC hash at scope PASS for cross-gate consistency
229
+ // Hash only AC definitions (inputs), not verdicts/evidence (outputs populated by gates)
230
+ if (gate === "scope" && resultVal === "PASS") {
231
+ state.gates.scope.acHash = hashAcDefinitions(state.acs || []);
232
+ }
233
+
234
+ if (gate === "ship" && resultVal === "PASS") {
235
+ state.mergeCommitSha = sha;
236
+ }
237
+
238
+ // #514 SC-2: Ship gate failure resets phase to VERIFY for re-iteration
239
+ if (gate === "ship" && resultVal === "FAIL") {
240
+ state.phase = "VERIFY";
241
+ state.changelog.push({
242
+ ts,
243
+ event: "ship-fail-regression",
244
+ detail: "Ship gate FAIL — resetting to VERIFY for re-iteration",
245
+ actor: "gate-runner",
246
+ });
247
+ }
248
+
249
+ const next = resultVal === "PASS" ? PHASE_ADVANCE[gate] : undefined;
250
+ if (next) {
251
+ state.phaseTimings = state.phaseTimings || {};
252
+ const currentPhase = state.phase;
253
+ const currentTimings = state.phaseTimings[currentPhase] || [];
254
+ if (currentTimings.length > 0) {
255
+ currentTimings[currentTimings.length - 1].exitedTs = ts;
256
+ }
257
+ state.phaseTimings[currentPhase] = currentTimings;
258
+
259
+ state.phaseTimings[next] = (state.phaseTimings[next] || []).concat([
260
+ { enteredTs: ts, source: "gate-runner" },
261
+ ]);
262
+ state.phase = next;
263
+ }
264
+
265
+ writeState(sf, state);
266
+ return { resultVal, attempt };
267
+ }
268
+
269
+ import { ensureGateSalt, gateSaltPath } from "../lib/paths";
270
+
271
+ const GATE_SALT_PATH = gateSaltPath();
272
+
273
+ export function generateHmac(sf: string, slug: string, issue: number, projectRoot?: string): string {
274
+ // Creation + chmod moved to ensureGateSalt() so every reader shares one
275
+ // definition. Inlined here, it made the salt's existence a side effect of
276
+ // this function having run, which other tests were silently relying on.
277
+ const salt = readFileSync(ensureGateSalt(), "utf-8").trim();
278
+ const sha = gitSha(projectRoot);
279
+ const input = `${slug}:${issue}:PASS:${sha}`;
280
+ const hash = createHmac("sha256", salt).update(input).digest("hex").slice(0, 16);
281
+
282
+ const state = readState(sf);
283
+ state.gates = state.gates || {};
284
+ state.gates.ship = state.gates.ship || {};
285
+ state.gates.ship.hash = hash;
286
+ writeState(sf, state);
287
+
288
+ return hash;
289
+ }
290
+
291
+ export function runConvergence(
292
+ sf: string,
293
+ gate: string,
294
+ resultVal: string,
295
+ ceremonyProfilePath: string,
296
+ ): { action: "circuit-break" | "stall" | "loop-back" | "skip"; iteration?: number } {
297
+ if (gate !== "verify" || resultVal !== "FAIL") {
298
+ return { action: "skip" };
299
+ }
300
+
301
+ const state = readState(sf);
302
+ const profile = JSON.parse(readFileSync(ceremonyProfilePath, "utf-8"));
303
+ const tier = state.sizing?.ceremonyTier || "STANDARD";
304
+ const maxIter = profile.tiers?.[tier]?.maxIterations ?? 5;
305
+
306
+ const loopbacks = (state.changelog || []).filter(
307
+ (e: any) => e.event === "iteration-loopback",
308
+ );
309
+ const iterCount = loopbacks.length;
310
+
311
+ const failNames = (state.gates?.verify?.failures || [])
312
+ .map((f: any) => f.check)
313
+ .sort()
314
+ .join(",");
315
+
316
+ // Read previous hash BEFORE appending new one
317
+ let prevHash = "";
318
+ if (iterCount >= 1) {
319
+ prevHash = loopbacks[loopbacks.length - 1]?.failureHash || "";
320
+ }
321
+
322
+ const ts = isoNow();
323
+ const newIter = iterCount + 1;
324
+
325
+ state.changelog = state.changelog || [];
326
+ state.changelog.push({
327
+ ts,
328
+ event: "iteration-loopback",
329
+ detail: `iteration ${newIter} — failures: ${failNames}`,
330
+ failureHash: failNames,
331
+ actor: "gate-runner",
332
+ });
333
+
334
+ // Circuit breaker
335
+ if (newIter >= maxIter) {
336
+ state.phaseTimings = state.phaseTimings || {};
337
+ const currentPhase = state.phase;
338
+ const currentTimings = state.phaseTimings[currentPhase] || [];
339
+ if (currentTimings.length > 0) {
340
+ currentTimings[currentTimings.length - 1].exitedTs = ts;
341
+ }
342
+ state.phaseTimings[currentPhase] = currentTimings;
343
+ state.phaseTimings["CIRCUIT_BREAK"] = [{ enteredTs: ts, source: "gate-runner" }];
344
+ state.phase = "CIRCUIT_BREAK";
345
+ writeState(sf, state);
346
+ return { action: "circuit-break", iteration: newIter };
347
+ }
348
+
349
+ // Stall detection
350
+ if (prevHash && prevHash === failNames) {
351
+ state.changelog.push({
352
+ ts,
353
+ event: "council-recommended",
354
+ detail: "same failure hash in consecutive iterations — consider council review",
355
+ actor: "gate-runner",
356
+ });
357
+ }
358
+
359
+ // Loop back to BUILD
360
+ state.phaseTimings = state.phaseTimings || {};
361
+ const currentPhase = state.phase;
362
+ const currentTimings = state.phaseTimings[currentPhase] || [];
363
+ if (currentTimings.length > 0) {
364
+ currentTimings[currentTimings.length - 1].exitedTs = ts;
365
+ }
366
+ state.phaseTimings[currentPhase] = currentTimings;
367
+
368
+ const buildTimings = state.phaseTimings["BUILD"] || [];
369
+ state.phaseTimings["BUILD"] = buildTimings.concat([
370
+ { enteredTs: ts, source: "gate-runner", iteration: buildTimings.length + 1 },
371
+ ]);
372
+ state.phase = "BUILD";
373
+ writeState(sf, state);
374
+
375
+ const isStall = prevHash !== "" && prevHash === failNames;
376
+ return { action: isStall ? "stall" : "loop-back", iteration: newIter };
377
+ }
378
+
379
+ export function generateShipEvidence(
380
+ sf: string,
381
+ workDir: string,
382
+ issue: number,
383
+ issueRepo: string,
384
+ passes: number,
385
+ fails: number,
386
+ warns: number,
387
+ ): string {
388
+ const state = readState(sf);
389
+ const sha = gitSha();
390
+ const ts = isoNow();
391
+
392
+ const loopbacks = (state.changelog || []).filter(
393
+ (e: any) => e.event === "iteration-loopback",
394
+ );
395
+ const iterCount = loopbacks.length + 1;
396
+ const predicted = state.sizing?.predicted || "unknown";
397
+
398
+ const acEvidence = (state.acs || []).map((ac: any) => ({
399
+ criterion: `${ac.id}: ${ac.statement}`,
400
+ result: ac.verdict || "SKIP",
401
+ detail: ac.evidence?.content || ac.evidence || "no evidence",
402
+ }));
403
+
404
+ // Auto-push, BEFORE the evidence is written (#213).
405
+ //
406
+ // The order is the point. This used to be the last thing the function did,
407
+ // inside `try { … } catch {}`, and `runGate` only calls this function once
408
+ // the ship gate has already recorded PASS — so a rejected push, an unset
409
+ // upstream, or a push that reached no remote all produced a run that
410
+ // reported success with the commit still on the local branch, and left no
411
+ // trace anywhere a human or a later gate would look.
412
+ //
413
+ // Running it first means the outcome lands in ship-evidence.json, which is
414
+ // the artefact the run is judged by. It still does not fail the gate: the
415
+ // verdict was reached before this function was called, and inventing a
416
+ // second place for a gate to fail would hide the first. Recorded and loud,
417
+ // not fatal.
418
+ //
419
+ // GATE_PASSED_PUSH is carried over verbatim: scripts/git-hooks/pre-push
420
+ // reads it and skips re-running the gates when the SHA matches the one the
421
+ // ship gate recorded. #213's body calls it "set here and read nowhere" —
422
+ // that is wrong, and dropping it would make every gate-passed push re-run
423
+ // the whole suite from inside the hook.
424
+ // The tree is process.cwd(), deliberately, and NOT `state.projectRoot`.
425
+ // Two reasons, and the second is the one that settles it:
426
+ //
427
+ // - `mergeCommitSha` above comes from `gitSha()` with no argument, which is
428
+ // process.cwd(). A push from a different tree would confirm a remote
429
+ // against a SHA this evidence never measured — the two have to be the
430
+ // same repo or the artefact contradicts itself.
431
+ // - `state.projectRoot` is a value read out of workflow-state.json. Letting
432
+ // a field in a state file choose which repository a `git push` runs
433
+ // against is a privileged operation taking its target from data, and the
434
+ // code this replaces did not do that. Minimal scope: keep the tree the
435
+ // old call used.
436
+ //
437
+ // `verifiedPush` is total and documented not to throw, but this is
438
+ // post-verdict bookkeeping and the old code could not crash the run no
439
+ // matter what. An unexpected throw is recorded as UNMEASURED, which
440
+ // `leftWorkLocal` already treats as "work may be local" — fail closed.
441
+ let pushOutcome: PushOutcome | null = null;
442
+ if (issueRepo && issue > 0) {
443
+ try {
444
+ // `expectRepo` is the other half of the cwd decision above (#430). The
445
+ // tree is process.cwd() for the reasons given, and `issueRepo` says
446
+ // which repository the run believes it is shipping — so the two are
447
+ // compared rather than assumed to agree. A fixture `issueRepo` run from
448
+ // a real checkout, which is what test/contract.test.ts was doing, now
449
+ // refuses instead of pushing.
450
+ pushOutcome = verifiedPush(process.cwd(), {
451
+ env: { ...process.env, GATE_PASSED_PUSH: "1" },
452
+ expectRepo: issueRepo,
453
+ });
454
+ } catch (e: any) {
455
+ pushOutcome = {
456
+ kind: "unmeasured",
457
+ detail: `the auto-push threw (${e?.name ?? typeof e}), so whether the commit reached ` +
458
+ `the remote is unknown. UNMEASURED is not PASS.`,
459
+ };
460
+ }
461
+ }
462
+ if (pushOutcome) {
463
+ const line = `Auto-push: ${pushOutcome.kind} — ${pushOutcome.detail}`;
464
+ if (leftWorkLocal(pushOutcome)) {
465
+ console.error(`\n⚠️ SHIP EVIDENCE MAY DESCRIBE A COMMIT THAT IS NOT ON THE REMOTE`);
466
+ console.error(` ${line}`);
467
+ } else {
468
+ console.log(line);
469
+ }
470
+ }
471
+
472
+ const evidence = {
473
+ contractVersion: "1.0",
474
+ issueNumber: issue,
475
+ gateOut: { status: "PASS" as const, evidence: acEvidence },
476
+ mergeCommitSha: sha,
477
+ capturedAt: ts,
478
+ iterationCount: iterCount,
479
+ sizing: { predicted, actual: predicted },
480
+ // Absent when there was no issue to ship against, which is the one case
481
+ // where no push was attempted. Absent and "attempted, outcome unknown"
482
+ // must not look the same — that equivalence is the whole of #213.
483
+ ...(pushOutcome ? { push: pushOutcome, pushLeftWorkLocal: leftWorkLocal(pushOutcome) } : {}),
484
+ };
485
+
486
+ const evidencePath = join(workDir, "ship-evidence.json");
487
+ writeFileSync(evidencePath, JSON.stringify(evidence, null, 2));
488
+
489
+ // GitHub: add shipped label + post comment via Octokit (best-effort, fire-and-forget)
490
+ // Uses POST additive label strategy (D-5) — never PUT/replace
491
+ if (issueRepo && issue > 0) {
492
+ try {
493
+ const github = createGitHubClient();
494
+ addLabels(github, issueRepo, issue, ["shipped"]).catch(() => {});
495
+
496
+ const scTable = (state.acs || [])
497
+ .map((ac: any) => `| ${ac.id} | ${ac.verdict || "SKIP"} | ${ac.evidence?.content || "—"} |`)
498
+ .join("\n");
499
+
500
+ const commentBody = [
501
+ "## Ship Complete (automated)\n",
502
+ `**Commit:** ${sha}`,
503
+ `**Gate:** ${passes} pass, ${fails} fail, ${warns} warn\n`,
504
+ "### SC Results",
505
+ "| SC | Verdict | Evidence |",
506
+ "|---|---|---|",
507
+ scTable,
508
+ "\nChain mode — issue stays open for /prove.",
509
+ ].join("\n");
510
+
511
+ addComment(github, issueRepo, issue, commentBody).catch(() => {});
512
+ } catch {}
513
+ }
514
+
515
+ return evidencePath;
516
+ }
517
+
518
+ const GATE_PENDING_PATH = join(
519
+ process.env.HOME || "",
520
+ ".claude",
521
+ "MEMORY",
522
+ "STATE",
523
+ "gate-pending.json",
524
+ );
525
+
526
+ export function writeGateSummary(
527
+ gate: string,
528
+ passes: number,
529
+ fails: number,
530
+ warns: number,
531
+ results: GateResult[],
532
+ issue: number,
533
+ slug: string,
534
+ sessionId: string,
535
+ ): "BLOCKED" | "ALL CLEAR" {
536
+ console.log("-----------------------------------");
537
+ console.log(`${gate} GATE: ${passes} pass, ${fails} fail, ${warns} warn`);
538
+
539
+ if (fails > 0) {
540
+ mkdirSync(dirname(GATE_PENDING_PATH), { recursive: true });
541
+ const failItems = results
542
+ .filter(r => r.result === "FAIL")
543
+ .map(r => ({ check: r.check, detail: r.detail }));
544
+
545
+ const pending = {
546
+ session_id: sessionId || "unknown",
547
+ gate,
548
+ issue,
549
+ slug,
550
+ failures: failItems,
551
+ strike_count: 0,
552
+ max_strikes: 3,
553
+ outcome_ac_failure: false,
554
+ created_at: isoNow(),
555
+ expires_ts: Math.floor(Date.now() / 1000) + 14400,
556
+ };
557
+
558
+ writeFileSync(GATE_PENDING_PATH, JSON.stringify(pending, null, 2));
559
+ console.log("BLOCKED");
560
+ return "BLOCKED";
561
+ }
562
+
563
+ try { unlinkSync(GATE_PENDING_PATH); } catch {}
564
+ console.log("ALL CLEAR");
565
+ return "ALL CLEAR";
566
+ }
567
+
568
+ // ── acHash field-level diff (#43) ────────────────────────────────────────
569
+
570
+ export interface AcHashDiffResult {
571
+ changed: boolean;
572
+ changedFields: Array<{ acId: string; field: string; before: unknown; after: unknown }>;
573
+ }
574
+
575
+ /**
576
+ * Compare AC definition fields between the scope-time hash snapshot and the current ACs.
577
+ * Logs field-level diff showing exactly which AC fields changed, enabling root-cause
578
+ * diagnosis when acHash mismatches occur.
579
+ */
580
+ export function diffAcHashFields(
581
+ scopeAcDefs: Array<Record<string, unknown>>,
582
+ currentAcs: Array<Record<string, unknown>>,
583
+ ): AcHashDiffResult {
584
+ const HASH_FIELDS = ["id", "type", "statement", "specElement", "threshold", "evidenceMethod"] as const;
585
+ const changedFields: AcHashDiffResult["changedFields"] = [];
586
+
587
+ const currentDefs = currentAcs.map((ac) => {
588
+ const def: Record<string, unknown> = {};
589
+ for (const f of HASH_FIELDS) def[f] = ac[f];
590
+ return def;
591
+ });
592
+
593
+ // Length mismatch
594
+ if (scopeAcDefs.length !== currentDefs.length) {
595
+ changedFields.push({
596
+ acId: "*",
597
+ field: "count",
598
+ before: scopeAcDefs.length,
599
+ after: currentDefs.length,
600
+ });
601
+ }
602
+
603
+ // Per-AC field comparison
604
+ const maxLen = Math.max(scopeAcDefs.length, currentDefs.length);
605
+ for (let i = 0; i < maxLen; i++) {
606
+ const before = scopeAcDefs[i];
607
+ const after = currentDefs[i];
608
+ if (!before || !after) continue;
609
+ for (const field of HASH_FIELDS) {
610
+ const bVal = JSON.stringify(before[field]);
611
+ const aVal = JSON.stringify(after[field]);
612
+ if (bVal !== aVal) {
613
+ changedFields.push({
614
+ acId: String(after.id ?? before.id ?? `index-${i}`),
615
+ field,
616
+ before: before[field],
617
+ after: after[field],
618
+ });
619
+ }
620
+ }
621
+ }
622
+
623
+ return { changed: changedFields.length > 0, changedFields };
624
+ }
625
+
626
+ // ── Write-time Zod validation (#453) ─────────────────────────────────────
627
+
628
+ export function writeWorkflowState(sf: string, state: Record<string, unknown>): void {
629
+ try {
630
+ WorkflowStateSchema.passthrough().parse(state);
631
+ } catch (err) {
632
+ if (err instanceof ZodError) {
633
+ const messages = err.issues.map(issue => {
634
+ if (issue.code === "invalid_enum_value") {
635
+ return `${issue.path.join(".")}: expected one of [${issue.options.join(", ")}], got "${issue.received}"`;
636
+ }
637
+ return `${issue.path.join(".")}: ${issue.message}`;
638
+ });
639
+ throw new Error(`Workflow state validation failed:\n${messages.join("\n")}`);
640
+ }
641
+ throw err;
642
+ }
643
+
644
+ // ADR-009: Recompute acHash when ACs are modified through writeWorkflowState.
645
+ // Root cause: heal agents modify AC definition fields (statement, evidenceMethod, threshold)
646
+ // between scope and verify/ship gates, causing false hash mismatches. writeWorkflowState is
647
+ // the authorized modification path — it recomputes acHash from definition fields only,
648
+ // excluding mutable verdict and evidence fields, keeping the hash stable.
649
+ const gates = state.gates as Record<string, any> | undefined;
650
+ const acs = state.acs as Array<Record<string, unknown>> | undefined;
651
+ if (gates?.scope?.acHash && acs?.length) {
652
+ gates.scope.acHash = hashAcDefinitions(acs);
653
+ }
654
+
655
+ // #60 — the one door every state write goes through, which is why the
656
+ // mutation record lives here rather than at the call sites. Read BEFORE the
657
+ // write, because afterwards there is nothing left to diff against.
658
+ //
659
+ // `null` for a first write, not an empty object: "there was no prior state"
660
+ // and "the prior state was empty" are different facts and only one of them
661
+ // is an initial write. A read that throws is also `null` and that is a
662
+ // deliberate loss — a corrupt prior state must not stop this write, and the
663
+ // row it produces says `<initial write>`, which is wrong but visibly so
664
+ // beside a run that already has rows.
665
+ let before: Record<string, unknown> | null = null;
666
+ try {
667
+ before = existsSync(sf) ? (JSON.parse(readFileSync(sf, "utf-8")) as Record<string, unknown>) : null;
668
+ } catch {
669
+ before = null;
670
+ }
671
+
672
+ writeState(sf, state as WorkflowState);
673
+ recordStateWrite(sf, before, state, process.env.RUNGATE_AGENT_LABEL || undefined);
674
+ }
675
+
676
+ // ── Structured workflow authoring (#454) ─────────────────────────────────
677
+
678
+ export function initWorkflow(sf: string, opts: InitWorkflowInput): void {
679
+ const ts = isoNow();
680
+
681
+ // Claim the directory before writing into it (#288). The stamp and the
682
+ // sweep are one action on purpose: a marker written without the sweep
683
+ // leaves the previous run's findings sitting beside a marker claiming the
684
+ // directory belongs to this one, which is worse than no marker at all.
685
+ const marker = beginRun(dirname(sf), { issue: opts.issue, slug: opts.slug });
686
+
687
+ const state: Record<string, any> = {
688
+ schemaVersion: 2,
689
+ runId: marker.runId,
690
+ issue: opts.issue,
691
+ repo: opts.repo,
692
+ issueRepo: opts.issueRepo || opts.repo,
693
+ projectRoot: opts.projectRoot,
694
+ slug: opts.slug,
695
+ issueGoal: opts.issueGoal,
696
+ phase: "GOAL",
697
+ acs: [],
698
+ gates: {},
699
+ changelog: [],
700
+ startTs: ts,
701
+ updatedTs: ts,
702
+ };
703
+
704
+ if (opts.sizing) state.sizing = opts.sizing;
705
+ if (opts.sourceSpecs) state.sourceSpecs = opts.sourceSpecs;
706
+ if (opts.bootstrappedFrom) state.bootstrappedFrom = opts.bootstrappedFrom;
707
+ // Written even when the run covered everything: "six ACs for six criteria,
708
+ // nothing deferred" is the reading that makes a short AC list legible, and
709
+ // an absent record would leave it looking exactly like a silent drop (#251).
710
+ if (opts.acCoverage) state.acCoverage = opts.acCoverage;
711
+ // `in`, not truthiness: an explicit null is detection reporting that it
712
+ // looked and found nothing, which is a measurement and is recorded. An
713
+ // absent key is nobody having looked (#288).
714
+ if ("priorWork" in opts) {
715
+ state.priorWork = opts.priorWork;
716
+ const provenance = acProvenance(opts.priorWork);
717
+ if (provenance) state.acProvenance = provenance;
718
+ }
719
+
720
+ WorkflowStateSchema.passthrough().parse(state);
721
+ mkdirSync(dirname(sf), { recursive: true });
722
+ writeState(sf, state);
723
+ }
724
+
725
+ export function writeACs(sf: string, acs: Array<{
726
+ id: string;
727
+ type?: string;
728
+ statement: string;
729
+ threshold?: { op: string; value: string | number; unit?: string };
730
+ evidenceMethod?: { type: string; command?: string };
731
+ specElement?: string;
732
+ }>): void {
733
+ const state = readState(sf);
734
+
735
+ state.acs = acs.map(ac => {
736
+ const enriched = { ...ac, evidence: null, verdict: "PENDING" as const };
737
+ const result = ACSchema.safeParse(enriched);
738
+ if (!result.success) {
739
+ const issues = result.error.issues.map(i => i.message).join('; ');
740
+ console.warn(`WARN: AC ${ac.id} has validation issues (will be caught at gate time): ${issues}`);
741
+ }
742
+ return enriched as (typeof state.acs)[number];
743
+ });
744
+
745
+ writeState(sf, state);
746
+ }
747
+
748
+ // ── AFK batch plan helpers (#468) ──────────────────────────────────────
749
+
750
+ const AFK_BATCH_FILE = "afk-batch.json";
751
+
752
+ function readBatchPlan(dir: string): any {
753
+ const fp = join(dir, AFK_BATCH_FILE);
754
+ return JSON.parse(readFileSync(fp, "utf-8"));
755
+ }
756
+
757
+ function writeBatchPlanFile(dir: string, plan: any): void {
758
+ AfkBatchPlanSchema.parse(plan);
759
+ const fp = join(dir, AFK_BATCH_FILE);
760
+ writeFileSync(fp, JSON.stringify(plan, null, 2));
761
+ }
762
+
763
+ export function initBatchPlan(dir: string, planned: number[]): void {
764
+ mkdirSync(dir, { recursive: true });
765
+ const plan = {
766
+ approvedAt: isoNow(),
767
+ planned,
768
+ shipped: [],
769
+ skipped: [],
770
+ inProgress: null,
771
+ };
772
+ writeBatchPlanFile(dir, plan);
773
+ }
774
+
775
+ export function recordBatchShipped(dir: string, issue: number): void {
776
+ const plan = readBatchPlan(dir);
777
+ if (!plan.shipped.includes(issue)) {
778
+ plan.shipped.push(issue);
779
+ }
780
+ if (plan.inProgress === issue) {
781
+ plan.inProgress = null;
782
+ }
783
+ writeBatchPlanFile(dir, plan);
784
+ }
785
+
786
+ export function recordBatchSkipped(dir: string, issue: number, reason: string, delegationAction?: string): void {
787
+ // Enforce rejection rules before mutating state
788
+ if (REJECTED_SKIP_REASONS.includes(reason.toLowerCase())) {
789
+ throw new Error(`Rejected skip reason: "${reason}" — must delegate instead`);
790
+ }
791
+ const plan = readBatchPlan(dir);
792
+ const entry: any = { issue, reason };
793
+ if (delegationAction !== undefined) {
794
+ entry.delegationAction = delegationAction;
795
+ }
796
+ plan.skipped.push(entry);
797
+ if (plan.inProgress === issue) {
798
+ plan.inProgress = null;
799
+ }
800
+ writeBatchPlanFile(dir, plan);
801
+ }
802
+
803
+ // #513: Mark ACs without evidenceMethod.command as SKIP
804
+ export function markCommandlessACsAsSkip(sf: string): number {
805
+ const state = readState(sf);
806
+ let count = 0;
807
+ for (const ac of state.acs || []) {
808
+ if (ac.verdict && ac.verdict !== "PENDING") continue;
809
+ if (!ac.evidenceMethod?.command) {
810
+ ac.verdict = "SKIP";
811
+ ac.evidence = { type: "manual-attestation", content: "No evidenceMethod.command defined" };
812
+ count++;
813
+ }
814
+ }
815
+ if (count > 0) writeState(sf, state);
816
+ return count;
817
+ }
818
+
819
+ export function validateBatchComplete(dir: string): { complete: boolean; missing: number[] } {
820
+ const plan = readBatchPlan(dir);
821
+ const resolved = new Set([
822
+ ...plan.shipped,
823
+ ...plan.skipped.map((s: any) => s.issue),
824
+ ]);
825
+ const missing = plan.planned.filter((n: number) => !resolved.has(n));
826
+ return { complete: missing.length === 0, missing };
827
+ }