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,290 @@
1
+ /**
2
+ * Which run wrote what is in a WORK_DIR, and whether that run is still alive
3
+ * (#288).
4
+ *
5
+ * `WORK_DIR` is `~/.rungate/<slug>/`, and the slug is repo + issue number. So
6
+ * every run of one issue writes into one directory, nothing clears it and
7
+ * nothing stamps it. After a failed run the directory holds a complete,
8
+ * plausible, WRONG set of artefacts and a reader has no way to tell.
9
+ *
10
+ * Measured: `~/.rungate/pai-harness-254/workflow-state.json` was read while a
11
+ * fresh #254 run was in flight. It showed `phase: VERIFY`, 6 ACs and a
12
+ * populated `rook-findings.json`. The run was actually at `setup`, three
13
+ * agents in. Everything read was the previous night's failed run, and a
14
+ * healthy run was cancelled on that misreading.
15
+ *
16
+ * ## No new write sites
17
+ *
18
+ * Disposition is derived from what the harness already writes — the marker,
19
+ * the run id in the state file, the state's own `updatedTs` heartbeat, and
20
+ * the ship gate's verdict. `workflows/ship.js` has 45 return points, and a
21
+ * design requiring a stamp at each would be wrong by the time the 46th was
22
+ * added. Nothing here needs ship.js to remember anything.
23
+ */
24
+ import {
25
+ existsSync,
26
+ mkdirSync,
27
+ readFileSync,
28
+ readdirSync,
29
+ renameSync,
30
+ writeFileSync,
31
+ } from "fs";
32
+ import { join } from "path";
33
+ import { randomUUID } from "crypto";
34
+
35
+ /** The marker file that says whose directory this is. */
36
+ export const RUN_MARKER_FILE = "run.json";
37
+
38
+ /** Directory prefix a swept run's artefacts are moved under. */
39
+ export const ARCHIVE_PREFIX = "previous-run-";
40
+
41
+ /**
42
+ * How long a run may go without writing before a reader calls it abandoned.
43
+ *
44
+ * Generous on purpose. A container rebuild and a full suite can leave the
45
+ * state file untouched for a long stretch, and calling a live run abandoned
46
+ * is the mistake that gets a healthy run cancelled — which is the mistake
47
+ * this module exists to prevent, not one to reintroduce from the other side.
48
+ */
49
+ export const HEARTBEAT_WINDOW_MS = 4 * 3_600_000;
50
+
51
+ export interface RunMarker {
52
+ runId: string;
53
+ issue: number;
54
+ slug: string;
55
+ startedTs: string;
56
+ }
57
+
58
+ export interface BeginRunOptions {
59
+ issue: number;
60
+ slug: string;
61
+ /** Supplied by tests and by a caller that already minted one. */
62
+ runId?: string;
63
+ }
64
+
65
+ export type DispositionStatus =
66
+ | "NO_MARKER"
67
+ | "UNREADABLE"
68
+ | "MIXED"
69
+ | "RUNNING"
70
+ | "ABANDONED"
71
+ | "COMPLETED";
72
+
73
+ export interface Disposition {
74
+ status: DispositionStatus;
75
+ runId?: string;
76
+ startedTs?: string;
77
+ shipVerdict?: string;
78
+ /** Why, when the status alone does not say it. */
79
+ detail?: string;
80
+ }
81
+
82
+ /**
83
+ * The only shape a run id may have.
84
+ *
85
+ * It is interpolated into a directory name, and it arrives from a JSON file
86
+ * sitting in a directory this module's entire premise is that it cannot
87
+ * trust. A `runId` of `../../../etc` would make `beginRun` rename the
88
+ * previous run's artefacts outside the work directory — the sweep is a
89
+ * `renameSync`, so a traversal there does not read a file, it MOVES one.
90
+ * Flagged by security review of `2559c8fa`.
91
+ */
92
+ const RUN_ID_SHAPE = /^run_[A-Za-z0-9_-]{1,64}$/;
93
+
94
+ /** Whether a value is usable as a run id, and therefore as a path segment. */
95
+ export function isRunId(value: unknown): value is string {
96
+ return typeof value === "string" && RUN_ID_SHAPE.test(value);
97
+ }
98
+
99
+ /**
100
+ * A run id that cannot collide with the run before it.
101
+ *
102
+ * Not a timestamp. The two runs this has to tell apart are a failed run and
103
+ * its immediate re-run, which is exactly the pair a second-resolution clock
104
+ * reports as one.
105
+ */
106
+ export function newRunId(): string {
107
+ return `run_${randomUUID().replace(/-/g, "")}`;
108
+ }
109
+
110
+ function markerPath(dir: string): string {
111
+ return join(dir, RUN_MARKER_FILE);
112
+ }
113
+
114
+ function readJson(path: string): unknown {
115
+ try {
116
+ return JSON.parse(readFileSync(path, "utf-8"));
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ }
121
+
122
+ function isRecord(v: unknown): v is Record<string, unknown> {
123
+ return typeof v === "object" && v !== null && !Array.isArray(v);
124
+ }
125
+
126
+ /**
127
+ * The marker, or null when there is none, when there is an unreadable one,
128
+ * and when the id in it is not one this module would have minted.
129
+ *
130
+ * A malformed id lands on the same `null` as a malformed file, which is the
131
+ * right place for it: the only use of a previous run's id is to name the
132
+ * directory its artefacts are moved into, and `beginRun` already mints a
133
+ * fresh one when it has no name to use.
134
+ */
135
+ export function readRunMarker(dir: string): RunMarker | null {
136
+ const raw = readJson(markerPath(dir));
137
+ if (!isRecord(raw) || !isRunId(raw.runId)) return null;
138
+ return {
139
+ runId: raw.runId,
140
+ issue: typeof raw.issue === "number" ? raw.issue : -1,
141
+ slug: typeof raw.slug === "string" ? raw.slug : "",
142
+ startedTs: typeof raw.startedTs === "string" ? raw.startedTs : "",
143
+ };
144
+ }
145
+
146
+ /** Entries in `dir` that are not this run's and not bookkeeping. */
147
+ export function staleArtefacts(dir: string, runId: string): string[] {
148
+ const marker = readRunMarker(dir);
149
+ if (marker && marker.runId === runId) return [];
150
+ return readdirSync(dir).filter(
151
+ name => name !== RUN_MARKER_FILE && !name.startsWith(ARCHIVE_PREFIX),
152
+ );
153
+ }
154
+
155
+ /**
156
+ * Claim the directory for a new run, moving everything that is not this
157
+ * run's out of the way first.
158
+ *
159
+ * ARCHIVED, never deleted. `scripts/preserve-worktree-work.ts` exists because
160
+ * output a run refused to collect is still output, sometimes the only copy —
161
+ * trading a misattribution bug for a data-loss bug is not a fix. The archive
162
+ * is named for the run that WROTE the files, so a reader walking the
163
+ * directory gets a history rather than a pile.
164
+ *
165
+ * Existing archives are left where they are. Sweeping them into each other
166
+ * would nest a tenth run's directory nine deep and bury the first.
167
+ */
168
+ export function beginRun(dir: string, opts: BeginRunOptions): RunMarker {
169
+ // A supplied id becomes this directory's name in the NEXT run's archive, so
170
+ // it is checked here rather than at the point it is joined — refusing a bad
171
+ // one now is the difference between a loud error and a rename somewhere
172
+ // else on the filesystem a run later.
173
+ if (opts.runId !== undefined && !isRunId(opts.runId)) {
174
+ throw new TypeError(
175
+ `beginRun was given a runId that is not one: ${JSON.stringify(opts.runId)}. ` +
176
+ `It becomes a directory name, so it must match ${RUN_ID_SHAPE}.`,
177
+ );
178
+ }
179
+ mkdirSync(dir, { recursive: true });
180
+
181
+ const previous = readRunMarker(dir);
182
+ // `previous` is null both when there was no marker and when there was an
183
+ // unreadable one. Either way the files beside it are not this run's, and a
184
+ // marker nobody can parse is not evidence that they are. The id is a
185
+ // placeholder in that case, so the archive still has a name.
186
+ const leftovers = readdirSync(dir).filter(
187
+ name => name !== RUN_MARKER_FILE && !name.startsWith(ARCHIVE_PREFIX),
188
+ );
189
+ if (leftovers.length > 0) {
190
+ const archive = join(dir, `${ARCHIVE_PREFIX}${previous?.runId ?? newRunId()}`);
191
+ mkdirSync(archive, { recursive: true });
192
+ for (const name of leftovers) renameSync(join(dir, name), join(archive, name));
193
+ }
194
+
195
+ const marker: RunMarker = {
196
+ runId: opts.runId || newRunId(),
197
+ issue: opts.issue,
198
+ slug: opts.slug,
199
+ startedTs: new Date().toISOString(),
200
+ };
201
+ writeFileSync(markerPath(dir), JSON.stringify(marker, null, 2));
202
+ return marker;
203
+ }
204
+
205
+ /**
206
+ * What a reader should believe about this directory.
207
+ *
208
+ * The order matters, and each step is the question the one before it leaves
209
+ * open:
210
+ *
211
+ * 1. No marker — say that, rather than a verdict about a run. Every WORK_DIR
212
+ * in `~/.rungate` is in this state until its next run.
213
+ * 2. An unreadable marker — also said, not repaired.
214
+ * 3. The state file naming a different run than the marker, or naming none:
215
+ * MIXED. This is the misreading itself, caught. Neither value is more
216
+ * trustworthy than the other, so neither wins.
217
+ * 4. A ship verdict — the run reached its end. COMPLETED is about whether it
218
+ * finished, not whether it liked what it found; a FAIL counts, or every
219
+ * refusal would file as abandoned and hide the ones that really were.
220
+ * 5. Otherwise the heartbeat decides, and an unparseable one is ABANDONED.
221
+ * Defaulting it to `now` would report every corrupt directory as live.
222
+ */
223
+ export function runDisposition(dir: string, nowMs: number): Disposition {
224
+ if (!existsSync(markerPath(dir))) return { status: "NO_MARKER" };
225
+
226
+ const marker = readRunMarker(dir);
227
+ if (!marker) {
228
+ return { status: "UNREADABLE", detail: `${RUN_MARKER_FILE} could not be parsed` };
229
+ }
230
+
231
+ const base = { runId: marker.runId, startedTs: marker.startedTs };
232
+ const state = readJson(join(dir, "workflow-state.json"));
233
+
234
+ // No state file yet. `beginRun` stamps before `initWorkflow` writes, so
235
+ // there is a real window where this is the honest reading of a healthy run.
236
+ if (!isRecord(state)) return { ...base, status: "RUNNING" };
237
+
238
+ const stateRunId = typeof state.runId === "string" ? state.runId : "";
239
+ if (stateRunId !== marker.runId) {
240
+ return {
241
+ ...base,
242
+ status: "MIXED",
243
+ detail:
244
+ `workflow-state.json was written by ${stateRunId || "a run that recorded no id"}, ` +
245
+ `and ${RUN_MARKER_FILE} says this directory belongs to ${marker.runId}`,
246
+ };
247
+ }
248
+
249
+ const gates = isRecord(state.gates) ? state.gates : {};
250
+ const ship = isRecord(gates.ship) ? gates.ship : undefined;
251
+ if (ship && typeof ship.verdict === "string" && ship.verdict) {
252
+ return { ...base, status: "COMPLETED", shipVerdict: ship.verdict };
253
+ }
254
+
255
+ const beat = typeof state.updatedTs === "string" ? Date.parse(state.updatedTs) : NaN;
256
+ if (!Number.isFinite(beat)) {
257
+ return { ...base, status: "ABANDONED", detail: "updatedTs could not be read as a time" };
258
+ }
259
+ if (nowMs - beat > HEARTBEAT_WINDOW_MS) {
260
+ return {
261
+ ...base,
262
+ status: "ABANDONED",
263
+ detail: `nothing has been written for ${Math.round((nowMs - beat) / 3_600_000)}h`,
264
+ };
265
+ }
266
+ return { ...base, status: "RUNNING" };
267
+ }
268
+
269
+ /**
270
+ * Where each AC's MET verdict came from (#288).
271
+ *
272
+ * A run that inherited six passing ACs and a run that implemented six passing
273
+ * ACs produce the same artefact, which is the reading `acCoverage` was added
274
+ * for in #251, missing on the neighbouring field. Every AC in the list is
275
+ * labelled — an absent entry is what an AC nobody classified looks like, and
276
+ * the two have to stay distinguishable.
277
+ */
278
+ export function acProvenance(priorWork: unknown): Record<string, { source: string; branch?: string }> | undefined {
279
+ if (!isRecord(priorWork)) return undefined;
280
+ const statuses = Array.isArray(priorWork.acStatus) ? priorWork.acStatus : [];
281
+ const branch = typeof priorWork.branch === "string" ? priorWork.branch : "";
282
+
283
+ const out: Record<string, { source: string; branch?: string }> = {};
284
+ for (const entry of statuses) {
285
+ if (!isRecord(entry) || typeof entry.id !== "string" || !entry.id) continue;
286
+ out[entry.id] =
287
+ entry.status === "MET" ? { source: "adopted", branch } : { source: "this-run" };
288
+ }
289
+ return out;
290
+ }
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env bun
2
+ import { readFileSync, existsSync, writeFileSync } from "fs";
3
+ import { join, resolve } from "path";
4
+ import { type GateResult } from "./orchestrator";
5
+ import { executeGate, parseTestResults, type GateExecutorInput, type GateExecutorResult } from "./gate-executor";
6
+ import { harnessRootFor } from "../lib/paths";
7
+
8
+ export { parseTestResults };
9
+
10
+ /**
11
+ * The tree the gate runs its own subprocesses in, resolved ONCE per run (#190).
12
+ *
13
+ * `gates/gate-executor.ts` used to call `harnessRoot()` at each of seven `cwd:`
14
+ * sites, so the tree a gate EXECUTED in was decided seven times over, by the
15
+ * environment and by wherever `lib/paths.ts` had been loaded from — never by
16
+ * the run. One of those subprocesses is `bun scripts/sync-spec-tests.ts`, which
17
+ * WRITES, so a misresolved root did not merely read the wrong tree, it edited
18
+ * it. The executor now receives a root and resolves none.
19
+ *
20
+ * Resolution order, and why:
21
+ *
22
+ * 1. `HARNESS_ROOT` when the caller set it. This is the override CI and the
23
+ * ship workflow use to name a tree on purpose, and it is the mitigation
24
+ * in use today; it has to keep winning.
25
+ * 2. Otherwise the checkout THIS FILE lives in. Not the main repository —
26
+ * `git rev-parse --git-common-dir` hands back the main checkout from
27
+ * inside a linked worktree, which is the opposite of what a gate needs.
28
+ * The files a worktree run is grading are the worktree's, so that is
29
+ * where its subprocesses belong.
30
+ *
31
+ * `harnessRootFor` rather than a bare string: it refuses an empty root instead
32
+ * of resolving one. `HARNESS_ROOT=` — an unset shell variable interpolated into
33
+ * a command — used to fall through `process.env.HARNESS_ROOT || <fallback>`
34
+ * silently and run the gate somewhere nobody chose. A run with no root is now a
35
+ * refusal, which is a thing you can see.
36
+ *
37
+ * `env` is a parameter so the refusal can be exercised without mutating the
38
+ * process; test/gate-root-threading.test.ts runs the empty-root case against
39
+ * both this module and a mutant whose `harnessRootFor` is the identity, and
40
+ * requires that the mutant does NOT refuse.
41
+ */
42
+ export function resolveRunRoot(env: Record<string, string | undefined> = process.env): string {
43
+ const named = env.HARNESS_ROOT;
44
+ if (named !== undefined) return harnessRootFor(named);
45
+ return harnessRootFor(resolve(import.meta.dir, ".."));
46
+ }
47
+
48
+ // ── Gate contract interfaces (SC-373) ─────────────────────────────────────
49
+
50
+ export interface RunGateInput {
51
+ gate: string;
52
+ slug: string;
53
+ issue: number;
54
+ }
55
+
56
+ export type ParseTestOutput = GateResult[];
57
+
58
+ if (!import.meta.main) {
59
+ // Imported as module — skip main execution
60
+ } else {
61
+
62
+ const args = process.argv.slice(2);
63
+ let gate = "";
64
+ let slug = "";
65
+ let issue = 0;
66
+ let treeUnderTest = "";
67
+ let worktreesJson = "";
68
+
69
+ for (let i = 0; i < args.length; i++) {
70
+ if (args[i] === "--gate" && args[i + 1]) gate = args[++i];
71
+ if (args[i] === "--slug" && args[i + 1]) slug = args[++i];
72
+ if (args[i] === "--issue" && args[i + 1]) issue = parseInt(args[++i]);
73
+ // #314 — the tree a check MEASURES, as opposed to projectRoot, which is
74
+ // where config is READ. ship.js owns this value (its `commitDir`) and the
75
+ // Workflow sandbox cannot write the state file itself, so it is threaded in
76
+ // here rather than inferred. Inferring it would be guessing at exactly the
77
+ // fact the gates were previously wrong about.
78
+ if (args[i] === "--tree-under-test" && args[i + 1]) treeUnderTest = args[++i];
79
+ // #414 — every worktree the run built in, as JSON, for the same reason
80
+ // `--tree-under-test` is threaded rather than inferred: ship.js owns the
81
+ // list and the Workflow sandbox cannot write the state file. One tree is
82
+ // not enough, because a decomposed run has one worktree per sub-issue and
83
+ // #218's incident was a SECOND agent landing in the wrong checkout while
84
+ // the first was correct.
85
+ if (args[i] === "--worktrees" && args[i + 1]) worktreesJson = args[++i];
86
+ }
87
+
88
+ if (!gate || !["scope", "verify", "ship", "merge", "prove", "gaps"].includes(gate)) {
89
+ console.error("Usage: bun run gates/run-gate.ts --gate scope|verify|ship|merge|prove|gaps --slug SLUG [--issue NUM]");
90
+ process.exit(1);
91
+ }
92
+
93
+ const WORK_DIR = join(process.env.RUNGATE_WORK_DIR || join(process.env.HOME || "", ".rungate"), slug);
94
+ const SF = join(WORK_DIR, "workflow-state.json");
95
+
96
+ if (!existsSync(SF)) {
97
+ console.error(`BLOCKED — ${SF} not found`);
98
+ process.exit(1);
99
+ }
100
+
101
+ const state = JSON.parse(readFileSync(SF, "utf-8"));
102
+ if (!issue) issue = state.issue || 0;
103
+ if (!slug) slug = state.slug || "";
104
+
105
+ // #314 — persist the tree under test before any check reads it, and CLEAR it
106
+ // when the caller named none.
107
+ //
108
+ // Writing only on supply is not enough. ship.js runs four gates against one
109
+ // state file, so a value left behind by an earlier gate would be inherited
110
+ // silently by a later one that named no tree — and the path it inherits is the
111
+ // worktree of whatever phase last wrote it, which by the Ship phase may have
112
+ // been collected away. Absent has to mean absent, or the UNMEASURED refusal
113
+ // the checks perform has a hole in it exactly where a caller forgot the flag.
114
+ if (treeUnderTest) {
115
+ state.treeUnderTest = treeUnderTest;
116
+ } else {
117
+ delete state.treeUnderTest;
118
+ }
119
+
120
+ // #414 — the same write-or-clear rule, for the same reason. A list left
121
+ // behind by an earlier gate would be inherited by a later one that named
122
+ // none, and by the Ship phase those worktrees may have been collected away;
123
+ // the gate would then refuse on paths that are correctly gone, or — worse —
124
+ // read a stale path that still exists and report a repository nobody built
125
+ // in. Absent has to mean absent.
126
+ //
127
+ // Unparseable REFUSES rather than clearing. "the caller sent nothing" and
128
+ // "the caller sent something this cannot read" are different facts, and
129
+ // treating the second as the first switches the check off at exactly the
130
+ // moment its input is suspect.
131
+ if (worktreesJson) {
132
+ let parsed: unknown;
133
+ try {
134
+ parsed = JSON.parse(worktreesJson);
135
+ } catch (e) {
136
+ console.error(`BLOCKED — --worktrees is not valid JSON: ${(e as Error).message}`);
137
+ process.exit(1);
138
+ }
139
+ if (!Array.isArray(parsed) || parsed.some(w => !w || typeof (w as { path?: unknown }).path !== "string")) {
140
+ console.error("BLOCKED — --worktrees must be an array of { path, reportedRepo? }");
141
+ process.exit(1);
142
+ }
143
+ state.worktrees = parsed;
144
+ } else {
145
+ delete state.worktrees;
146
+ }
147
+ writeFileSync(SF, JSON.stringify(state, null, 2));
148
+
149
+ // Gate idempotency guard
150
+ if (!process.argv.includes("--force") && state.gates?.[gate]?.result === "PASS") {
151
+ console.log(`Gate ${gate}: already PASSED (attempt ${state.gates[gate].attempt}). Use --force to re-run.`);
152
+ console.log(`\n${gate} GATE: PASS (cached)`);
153
+ process.exit(0);
154
+ }
155
+
156
+ // Delegate to gate executor.
157
+ // executeGate is async — without the await, result.exitCode was undefined and
158
+ // process.exit(undefined) exited 0, so every gate reported PASS and the
159
+ // executor was killed mid-flight.
160
+ const result = await executeGate({ gate, slug, issue, workDir: WORK_DIR, stateFilePath: SF, harnessRoot: resolveRunRoot() });
161
+
162
+ process.exit(result.exitCode);
163
+ } // end if (import.meta.main)