omp-conductor 0.15.13 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/REFERENCE.md +72 -2
  2. package/package.json +2 -1
  3. package/schema/config.schema.json +7 -0
  4. package/src/admission.ts +849 -0
  5. package/src/ask.ts +47 -0
  6. package/src/backups.ts +19 -7
  7. package/src/board.ts +1 -2
  8. package/src/briefs/orchestrator.md +62 -4
  9. package/src/cli.ts +26 -0
  10. package/src/commands/context.ts +3 -0
  11. package/src/commands/decision.ts +10 -1
  12. package/src/commands/doctor.ts +2 -0
  13. package/src/commands/message.ts +8 -1
  14. package/src/commands/restart.ts +15 -3
  15. package/src/commands/restore-db.ts +146 -0
  16. package/src/commands/stop.ts +24 -15
  17. package/src/commands/tail.ts +204 -44
  18. package/src/commands/unfreeze.ts +56 -0
  19. package/src/commands/watch.ts +77 -0
  20. package/src/config-schema.ts +13 -0
  21. package/src/config.ts +54 -0
  22. package/src/daemon.ts +255 -530
  23. package/src/dashboard/server.ts +2 -1
  24. package/src/decisions.ts +32 -7
  25. package/src/depends-on.ts +122 -0
  26. package/src/doctor.ts +297 -5
  27. package/src/escalate.ts +191 -19
  28. package/src/failure-class.ts +47 -0
  29. package/src/fleet.ts +168 -452
  30. package/src/gitops.ts +86 -1
  31. package/src/log.ts +40 -0
  32. package/src/model-fallback.ts +3 -2
  33. package/src/omp-settings.ts +114 -0
  34. package/src/omp.ts +39 -0
  35. package/src/orchestrator-tick.ts +7 -1
  36. package/src/reports.ts +124 -12
  37. package/src/session-host.ts +6 -0
  38. package/src/setup-wizard.ts +36 -0
  39. package/src/setup.ts +58 -1
  40. package/src/status-render.ts +445 -0
  41. package/src/stop-provenance.ts +53 -0
  42. package/src/store.ts +352 -11
  43. package/src/transcript.ts +1 -1
  44. package/src/types.ts +187 -4
  45. package/src/unblock.ts +1 -1
  46. package/src/upgrade-verify.ts +1 -1
  47. package/src/upgrade.ts +1 -2
  48. package/src/verbs/server.ts +25 -0
  49. package/src/worker.ts +358 -10
  50. package/src/worktree.ts +13 -1
@@ -0,0 +1,849 @@
1
+ /**
2
+ * The admission half of the dispatcher (`daemon.ts` composes; this owns the
3
+ * gates).
4
+ *
5
+ * Extracted from `daemon.ts` so the most contested region — who gets a worker
6
+ * this tick — is a lane of its own: #283, #419, #420, #421, #507 and #555 all
7
+ * live here, and a diff touching only admission must not have to touch the
8
+ * composition root. Behavior is deliberately untouched by the move; a later
9
+ * slice reworks the seams.
10
+ *
11
+ * What admission is allowed to consult is the point of the module. It reads a
12
+ * structural slice of the daemon's deps — never the whole `Deps` and never the
13
+ * module that owns them, which would be the circular import the split exists
14
+ * to rule out. Adding a field to the daemon's deps must not break these tests.
15
+ */
16
+
17
+ import { join } from "node:path";
18
+ import { log, errText, safeEscalate } from "./log.ts";
19
+ import type {
20
+ Caps,
21
+ Escalation,
22
+ IssueSnapshot,
23
+ OpenCloser,
24
+ ProjectConfig,
25
+ RunRecord,
26
+ Tracker,
27
+ Store,
28
+ AdmissionHoldReason,
29
+ } from "./types.ts";
30
+ import { readPlanUsage, type PlanUsageStatus, type UsageSource } from "./usage.ts";
31
+ import type { CriticalBaseProbe, CriticalBaseVerdict, RunLaneProbe } from "./gitops.ts";
32
+ import { repoSlugFor } from "./gitops.ts";
33
+ import { branchName, type Routed } from "./routing.ts";
34
+ import { parseDependsOn } from "./depends-on.ts";
35
+
36
+ /** Fleet-wide escalations still need an issue number in the payload; 0 is the
37
+ * sentinel that reads as "no issue" in every renderer. */
38
+ const NO_ISSUE = 0;
39
+
40
+ /**
41
+ * The slice of the daemon's `Deps` admission reads. Defined here rather than
42
+ * imported from `daemon.ts` (that would be the cycle this module exists to
43
+ * avoid); every `daemon.test.ts` fake already satisfies it, so the seam costs
44
+ * nothing.
45
+ */
46
+ export interface AdmissionDeps {
47
+ project: ProjectConfig;
48
+ caps: Caps;
49
+ tracker: Tracker;
50
+ store: Store;
51
+ usage: UsageSource;
52
+ escalate(e: Escalation): Promise<void>;
53
+ probeCriticalBase?: CriticalBaseProbe;
54
+ probeWorktreeLane?: RunLaneProbe;
55
+ /**
56
+ * Reads one issue's tracker state in a repository the admission tracker is
57
+ * NOT bound to — the cross-repo half of the Depends-on interlock (#420).
58
+ * The tracker bound to `project.tracker.repo` can only answer same-repo
59
+ * references; a `owner/repo#n` prerequisite naming a different routed repo
60
+ * goes through this. Undefined means "could not tell" (same posture as
61
+ * {@link Tracker.issueSnapshot}); a routed prerequisite it cannot answer
62
+ * fails that candidate closed. Unset, admission fails a routed cross-repo
63
+ * prerequisite closed too — the daemon always wires it.
64
+ */
65
+ probeIssueIn?: (repo: string, issue: number) => Promise<IssueSnapshot | undefined>;
66
+ }
67
+ /** `stops` are the operational ends that each require one resume. */
68
+ export function hasContinuationBudget(stops: number, maxContinuations: number): boolean {
69
+ return stops <= maxContinuations;
70
+ }
71
+
72
+ /** True while unspent failed-implementation attempts remain. This is the
73
+ * dispatcher's admission gate: once every `maxAttemptsPerIssue` slot is
74
+ * spent, the issue is held as `failed-attempts` forever, and the `unblock`
75
+ * verb withholds the queue label on the same predicate (#348). */
76
+ export function hasFailedAttemptBudget(failures: number, maxAttempts: number): boolean {
77
+ return failures < maxAttempts;
78
+ }
79
+
80
+ /** A candidate cleared for dispatch, with the attempt number it will run as. */
81
+ export interface Admission {
82
+ r: Routed;
83
+ attempt: number;
84
+ }
85
+
86
+ export interface AdmissionHold {
87
+ issue: number;
88
+ reason: AdmissionHoldReason;
89
+ /** Human-readable "what" for the surface the reason group alone cannot say —
90
+ * the overlapping file and the run holding it for `file-lane`. Survives only
91
+ * far enough to be rendered; it never leaves the current pass's summary. */
92
+ detail?: string;
93
+ }
94
+
95
+ export interface AdmissionPass {
96
+ admitted: Admission[];
97
+ holds: AdmissionHold[];
98
+ }
99
+
100
+
101
+ /**
102
+ * What a held plan-usage gate says to a human, if anything.
103
+ *
104
+ * Three different problems hide behind one hold, and they want different
105
+ * tiers. Reaching the threshold is the guard *working*: tier 1, because the
106
+ * fleet resumes on its own at the provider's reset and nobody needs to get
107
+ * out of bed. Everything else — a window nothing reports, a window that
108
+ * resolves to two allowances, a meter that has been unreadable for half an
109
+ * hour — is dispatch stopped with no self-recovery, which is tier 2.
110
+ *
111
+ * Each summary carries the fact that will change when the situation does (the
112
+ * reset instant, the configured id, the date), because the escalation ledger
113
+ * dedupes on the summary: a stable one pages once and then goes quiet, which
114
+ * is right for a repeated tick and wrong for the next window.
115
+ */
116
+ function planUsageEscalation(project: string, plan: PlanUsageStatus): Escalation | undefined {
117
+ const base = { project, issue: NO_ISSUE };
118
+ if (plan.state === "at-cap") {
119
+ const window = plan.window?.id ?? plan.cap?.windowId ?? "the configured window";
120
+ const resets =
121
+ plan.resetsAt === undefined
122
+ ? new Date().toISOString().slice(0, 10)
123
+ : new Date(plan.resetsAt).toISOString();
124
+ return {
125
+ ...base,
126
+ tier: 1,
127
+ summary: `Plan allowance cap reached on ${window} — ${project} is not claiming new work (window ${resets})`,
128
+ detail: [
129
+ plan.detail,
130
+ "Running workers finish normally; only new claims are held.",
131
+ "Dispatch resumes by itself once the provider reports the window reset or usage below the threshold —",
132
+ "no `resume` needed. Raise `caps.planUsage.maxUsedFraction` only if you mean to spend the rest.",
133
+ ].join("\n"),
134
+ };
135
+ }
136
+ if (plan.state === "blind") {
137
+ return {
138
+ ...base,
139
+ tier: 2,
140
+ category: "fleet-stopped",
141
+ // Dated: a meter that breaks again next month is a new incident, not a
142
+ // repeat of this one.
143
+ summary: `Plan usage source unreadable — ${project} is not claiming new work (${new Date().toISOString().slice(0, 10)})`,
144
+ detail: [
145
+ plan.detail,
146
+ "The guard admitted work while the failure looked transient and has now stopped.",
147
+ "Check `omp usage --json` on the fleet host, or set `caps.planUsage` to null if this fleet is unmetered.",
148
+ ].join("\n"),
149
+ };
150
+ }
151
+ if (
152
+ plan.state === "window-missing" ||
153
+ plan.state === "window-ambiguous" ||
154
+ plan.state === "window-uncomparable"
155
+ ) {
156
+ return {
157
+ ...base,
158
+ tier: 2,
159
+ category: "fleet-stopped",
160
+ summary: `Plan usage cap names an unusable window "${plan.cap?.windowId ?? "?"}" — ${project} is not claiming new work`,
161
+ detail: [
162
+ plan.detail,
163
+ "Run `omp usage --json` and copy an allowance `id` into `caps.planUsage.windowId`,",
164
+ "or set `caps.planUsage` to null if this fleet is unmetered.",
165
+ ].join("\n"),
166
+ };
167
+ }
168
+ return undefined;
169
+ }
170
+
171
+
172
+ /**
173
+ * The candidate half of the file-lane interlock: the machine-readable list of
174
+ * files an issue declares it will touch (#555).
175
+ *
176
+ * The orchestrator already writes exactly this list into every promotion brief
177
+ * in prose; this parses that same sentence out of the issue body so the
178
+ * interlock is load-bearing rather than advisory. A body line beginning with
179
+ * "file lane" (case-insensitive, optional bold/heading markers) is accepted,
180
+ * and paths are read as backtick-delimited spans (the brief form) with a bare
181
+ * comma/space-separated fallback that keeps tokens that look like relative
182
+ * paths. Anything else — including an absent line, which is the default — is
183
+ * an empty lane: the issue is admitted exactly as today (`fail open`), and the
184
+ * gate never refuse work for wanting a lane. Exported so the format is pinned
185
+ * independent of admission.
186
+ */
187
+ export function declaredLane(body: string): string[] {
188
+ const match = body.match(
189
+ /^\s*(?:[#>*-]\s*)*file[- ]lane\s*[:=]\s*([^\n]*)$/im,
190
+ );
191
+ if (match === null) return [];
192
+ const rest = match[1] ?? "";
193
+ const backticked = [...rest.matchAll(/`([^`]+)`/g)]
194
+ .map((m) => m[1]!.trim())
195
+ .filter(isPathLike);
196
+ if (backticked.length > 0) return [...new Set(backticked)];
197
+ return [...new Set(rest.split(/[,\s]+/).map((s) => s.trim()).filter(isPathLike))];
198
+ }
199
+
200
+ /** A plausible relative path: it has a `.` extension or a directory separator. */
201
+ function isPathLike(token: string): boolean {
202
+ return token !== "" && !/\s/.test(token) && (token.includes("/") || /\.[A-Za-z0-9]{1,10}$/.test(token));
203
+ }
204
+
205
+ /**
206
+ * Where a `owner/repo` cross-repo reference can be read. Only repositories
207
+ * routed in THIS fleet are resolvable (#420): the issue source repo
208
+ * (`project.tracker.repo`) is answered by the existing tracker, and any routed
209
+ * work repo by {@link AdmissionDeps.probeIssueIn}. Anything else is unresolved
210
+ * — the caller fails closed rather than guess which repo was meant, and never
211
+ * silently resolves the reference against the candidate's own repo.
212
+ */
213
+ function crossRepoTarget(project: ProjectConfig, ownerRepo: string): "tracker" | "routed" | undefined {
214
+ if (ownerRepo === project.tracker.repo) return "tracker";
215
+ for (const routed of Object.values(project.routing.repos)) {
216
+ if (repoSlugFor(routed) === ownerRepo) return "routed";
217
+ }
218
+ return undefined;
219
+ }
220
+
221
+ /**
222
+ * Which routed candidates get a worker this tick — in queue order, never more
223
+ * than `slots` of them. Every non-admission receives a stable reason code.
224
+ *
225
+ * Exported so the admission rules can be pinned without spawning a worker.
226
+ * Every one of them exists because of a live incident, and each guards a
227
+ * different way the same issue gets worked twice — including epic siblings
228
+ * racing onto the same files (#48).
229
+ *
230
+ * Takes the slice of `Deps` it actually reads rather than the whole thing: what
231
+ * admission is allowed to consult is the point of the function, and a `Deps`
232
+ * that grows a field has no business breaking these tests.
233
+ */
234
+ export async function admitCandidates(
235
+ d: AdmissionDeps,
236
+ routed: Routed[],
237
+ slots: number,
238
+ ): Promise<AdmissionPass> {
239
+ const { project, caps, tracker, store } = d;
240
+ const activeRuns = store.activeRuns(project.name);
241
+ const busyIssues = activeRuns.map((r) => r.issue);
242
+ const busy = new Set(busyIssues);
243
+ // issue -> its active run rows, for the pushed-green admission bypass (#175):
244
+ // only a worker-free pushed-green row may be bypassed, and only when *every*
245
+ // active run for the issue is worker-free. A live (claimed/running) row still
246
+ // holds unconditionally.
247
+ const activeByIssue = new Map<number, RunRecord[]>();
248
+ for (const run of activeRuns) {
249
+ const list = activeByIssue.get(run.issue);
250
+ if (list === undefined) activeByIssue.set(run.issue, [run]);
251
+ else list.push(run);
252
+ }
253
+ // Live worker count per repo, seeded from live runs and incremented as this
254
+ // same pass admits — so two same-repo candidates can never both clear the
255
+ // per-repo cap in one tick (#186).
256
+ const liveByRepo = new Map<string, number>();
257
+ for (const run of store.liveRuns(project.name)) {
258
+ liveByRepo.set(run.repo, (liveByRepo.get(run.repo) ?? 0) + 1);
259
+ }
260
+ const holds: AdmissionHold[] = [];
261
+ const hold = (issue: number, reason: AdmissionHoldReason, detail?: string): void => {
262
+ holds.push({ issue, reason, ...(detail === undefined ? {} : { detail }) });
263
+ };
264
+
265
+ // The file-lane interlock (#555): repo -> file -> the issue holding that file.
266
+ // Seeded from the *actual* worktrees/branches of active runs — never from
267
+ // their issue bodies, which is precisely how #288 collided — and extended as
268
+ // this pass admits candidates with declared lanes, so two overlapping
269
+ // candidates cannot both clear the gate in one tick. Keyed by repo because a
270
+ // path only collides within its own checkout: a `daemon.ts` on the api repo
271
+ // and one on the web repo are different files. Built lazily and once, only
272
+ // when the first candidate that declares a lane reaches the gate, so a queue
273
+ // of laneless issues pays nothing for it.
274
+ let laneOccupancy: Map<string, Map<string, number>> | undefined;
275
+ const ensureLaneOccupancy = async (): Promise<Map<string, Map<string, number>>> => {
276
+ if (laneOccupancy !== undefined) return laneOccupancy;
277
+ const occupied = new Map<string, Map<string, number>>();
278
+ for (const run of activeRuns) {
279
+ if (d.probeWorktreeLane === undefined) break;
280
+ const base = project.routing.repos[run.repo]?.defaultBranch ?? "main";
281
+ let files: string[];
282
+ try {
283
+ files = await d.probeWorktreeLane({
284
+ worktree: run.worktree,
285
+ baseRef: `refs/remotes/origin/${base}`,
286
+ ...(run.branch === "" ? {} : { branchRef: `refs/heads/${run.branch}` }),
287
+ mirror: join(project.mirrorRoot, `${run.repo}.git`),
288
+ });
289
+ } catch {
290
+ // Fail open, like an unreadable lane: the gate never refuses a
291
+ // well-formed issue because one probe could not be answered.
292
+ files = [];
293
+ }
294
+ for (const file of files) {
295
+ if (occupied.get(run.repo)?.has(file) === true) continue;
296
+ let perRepo = occupied.get(run.repo);
297
+ if (perRepo === undefined) {
298
+ perRepo = new Map();
299
+ occupied.set(run.repo, perRepo);
300
+ }
301
+ perRepo.set(file, run.issue);
302
+ }
303
+ }
304
+ laneOccupancy = occupied;
305
+ return occupied;
306
+ };
307
+
308
+ // The plan allowance is a fleet-wide question, so it is asked once per pass
309
+ // and answers for every candidate — unlike every gate below it, which is
310
+ // per-issue. It sits here rather than beside the spend cap in `tick` for one
311
+ // reason: the spend cap *pauses the daemon* and waits for a human, and a
312
+ // weekly plan window resets by itself. A guard that demanded `resume` after
313
+ // every rollover would cost more operator attention than the guard saves
314
+ // (#110). Already-running workers are untouched and settle normally.
315
+ //
316
+ // Placed after the cheap local busy-set read and before the first tracker
317
+ // call, so a held fleet spends no GitHub API budget discovering it is held.
318
+ const plan = await readPlanUsage(caps.planUsage, d.usage);
319
+ if (plan.blocking) {
320
+ for (const r of routed) hold(r.issue.number, "plan-usage-cap");
321
+ log(`plan usage gate holding ${String(routed.length)} candidate(s): ${plan.detail}`);
322
+ const escalation = planUsageEscalation(project.name, plan);
323
+ if (escalation !== undefined) await safeEscalate(d, escalation);
324
+ return { admitted: [], holds };
325
+ }
326
+
327
+ // parent -> repo name -> blocking issue. Seeded from active runs (including
328
+ // pushed-green), then extended by candidates admitted earlier in this same
329
+ // pass so two siblings of one epic never both clear the gate in one tick.
330
+ // A busy issue whose run row cannot be resolved occupies the sentinel repo
331
+ // "" — treated as matching every repo, failing toward holding (#197).
332
+ const occupiedParents = new Map<number, Map<string, number>>();
333
+ const parentCache = new Map<number, number | undefined>();
334
+
335
+ const resolveParent = async (issue: number): Promise<number | undefined> => {
336
+ if (parentCache.has(issue)) return parentCache.get(issue);
337
+ const parent = await tracker.parentOf(issue);
338
+ parentCache.set(issue, parent);
339
+ return parent;
340
+ };
341
+
342
+ // Bounded by concurrent workers, not queue depth. A failed lookup here cannot
343
+ // mark an epic occupied; candidates still fail closed on their own parentOf.
344
+ for (const issue of busyIssues) {
345
+ try {
346
+ const parent = await resolveParent(issue);
347
+ if (parent === undefined) continue;
348
+ // The runs table records which repo each attempt worked in, and sibling
349
+ // holds are now per-repo, so a busy child only occupies its epic under
350
+ // that repo's name (same spelling as `createRun` writes from
351
+ // `r.repo.name`). A busy issue with no resolvable run row occupies the
352
+ // sentinel "" instead — matching every repo, failing toward holding.
353
+ const repo = store.latestRun(project.name, issue)?.repo ?? "";
354
+ const siblings = occupiedParents.get(parent);
355
+ if (siblings === undefined) {
356
+ occupiedParents.set(parent, new Map([[repo, issue]]));
357
+ } else if (!siblings.has(repo) && !siblings.has("")) {
358
+ siblings.set(repo, issue);
359
+ }
360
+ } catch (err) {
361
+ log(`#${issue} parent lookup failed while seeding epic occupancy (${errText(err)})`);
362
+ }
363
+ }
364
+
365
+ const admitted: Admission[] = [];
366
+ for (const r of routed) {
367
+ const issue = r.issue.number;
368
+ if (admitted.length >= slots) {
369
+ hold(issue, "capacity");
370
+ continue;
371
+ }
372
+ if (busy.has(issue)) {
373
+ // A pushed-green row is worker-free by definition (it is not in
374
+ // LIVE_STATES): its PR is live but no process is writing to its branch.
375
+ // So an issue whose active runs are ALL pushed-green is not actually
376
+ // occupied — the corrective attempt the operator unblocked may be
377
+ // admitted as a continuation of that PR, and the open-PR gate below
378
+ // decides the identity. Any live row still holds (#175).
379
+ const allWorkerFree = (activeByIssue.get(issue) ?? []).every((r) => r.state === "pushed-green");
380
+ if (!allWorkerFree) {
381
+ hold(issue, "issue-active");
382
+ continue;
383
+ }
384
+ }
385
+
386
+ // Per-repo concurrency: the mirror, branch-protection staleness and shared
387
+ // CI egress are all per-repo collision domains, so extra slots should land
388
+ // on other repos rather than stacking workers into the same one (#186).
389
+ const liveInRepo = liveByRepo.get(r.repo.name) ?? 0;
390
+ if (liveInRepo >= caps.maxConcurrentWorkersPerRepo) {
391
+ hold(issue, "repo-active");
392
+ log(`#${issue} skipped: ${liveInRepo} live worker(s) already in ${r.repo.name} (cap ${caps.maxConcurrentWorkersPerRepo})`);
393
+ continue;
394
+ }
395
+
396
+ const priorRuns = store.attemptsFor(project.name, issue);
397
+ const failures = store.failuresFor(project.name, issue);
398
+ if (!hasFailedAttemptBudget(failures, caps.maxAttemptsPerIssue)) {
399
+ hold(issue, "failed-attempts");
400
+ await safeEscalate(d, {
401
+ tier: 1,
402
+ project: project.name,
403
+ issue,
404
+ summary: `#${issue} has used all ${caps.maxAttemptsPerIssue} failed attempts`,
405
+ detail: [
406
+ r.issue.title,
407
+ r.issue.url,
408
+ "Another implementation attempt almost always means the issue itself is underspecified.",
409
+ "Rewrite the acceptance criteria, or take it off the queue.",
410
+ ].join("\n"),
411
+ });
412
+ continue;
413
+ }
414
+
415
+ const continuations = store.continuationsFor(project.name, issue);
416
+ if (!hasContinuationBudget(continuations, caps.maxContinuationsPerIssue)) {
417
+ hold(issue, "continuations");
418
+ await safeEscalate(d, {
419
+ tier: 1,
420
+ project: project.name,
421
+ issue,
422
+ summary: `#${issue} exceeded its ${caps.maxContinuationsPerIssue}-continuation budget`,
423
+ detail: [
424
+ r.issue.title,
425
+ r.issue.url,
426
+ "Repeated cap kills, daemon orphans, or answered blocks need an operator to inspect progress.",
427
+ ].join("\n"),
428
+ });
429
+ continue;
430
+ }
431
+
432
+ // Fail closed on work that exists only in a run repo. `addRunRepo` clears
433
+ // the tree at <workspaceRoot>/<issue> before it provisions, so admitting
434
+ // this issue is what finally destroys the copy the salvage could not save
435
+ // (#118). Nothing here can recover it — git already refused once — so the
436
+ // only safe move is to refuse the claim and keep saying why until an
437
+ // operator has looked and run `unblock --force`.
438
+ const newest = store.latestRun(project.name, issue);
439
+ if (newest?.salvageError !== undefined && newest.salvageAckAt === undefined) {
440
+ hold(issue, "unsalvaged-wip");
441
+ await safeEscalate(d, {
442
+ tier: 1,
443
+ project: project.name,
444
+ issue,
445
+ summary: `#${issue} is holding unsalvaged work and will not be re-claimed`,
446
+ detail: [
447
+ r.issue.title,
448
+ r.issue.url,
449
+ `Attempt ${newest.attempt} could not commit its uncommitted changes: ${newest.salvageError}`,
450
+ `The only copy is the worktree ${newest.worktree === "" ? "(path not recorded)" : newest.worktree}.`,
451
+ "Dispatch is held because claiming this issue removes that tree.",
452
+ "Recover it by hand, then `omp-conductor unblock <n> --force` to release the hold.",
453
+ ].join("\n"),
454
+ });
455
+ continue;
456
+ }
457
+
458
+ // #428 half (a): a preserved continuation that predates a configured
459
+ // critical-base/safety marker must not be reattached. A base safety fix
460
+ // protects only branches forked after it landed — a continuation forked
461
+ // before it still carries the dangerous test/runtime code, and re-running
462
+ // it on the shared host is what SIGTERMed the production daemon. Fail
463
+ // closed: only a probe that proves every marker is in the reattach
464
+ // source's ancestry admits, and a project that names a marker but has no
465
+ // probe wired (never happens outside tests) holds. Both the hold and the
466
+ // escalation are durable across restart and orphan recovery because this
467
+ // gate runs every admission pass; the branch is re-admitted automatically
468
+ // once the operator updates it to contain the marker, without losing work.
469
+ const markers = project.criticalBase ?? [];
470
+ if (markers.length > 0) {
471
+ const branch = branchName(r.issue);
472
+ let verdict: CriticalBaseVerdict;
473
+ if (d.probeCriticalBase === undefined) {
474
+ verdict = { state: "unknown", error: "no critical-base probe is wired in this deployment" };
475
+ } else {
476
+ try {
477
+ verdict = await d.probeCriticalBase(r.repo, markers, branch);
478
+ } catch (err) {
479
+ verdict = { state: "unknown", error: errText(err) };
480
+ }
481
+ }
482
+ if (verdict.state === "stale") {
483
+ hold(issue, "stale-base");
484
+ log(
485
+ `#${issue} held (stale-base): continuation branch ${branch} predates critical-base marker ${verdict.marker}`,
486
+ );
487
+ await safeEscalate(d, {
488
+ tier: 1,
489
+ project: project.name,
490
+ issue,
491
+ summary: `#${issue} continuation branch predates a critical base safety commit and is held (stale-base)`,
492
+ detail: [
493
+ r.issue.title,
494
+ r.issue.url,
495
+ `The retained branch ${branch} does not contain critical-base marker ${verdict.marker}.`,
496
+ ...(verdict.range.length > 0
497
+ ? [`Base commits the branch is missing: ${verdict.range.join(", ")}`]
498
+ : []),
499
+ "Recovery: merge current base into the branch so it contains the marker, and the next",
500
+ "admission pass re-admits it automatically without losing the branch's work; or review",
501
+ "the branch by hand and clear the hold once the fix is present.",
502
+ ].join("\n"),
503
+ });
504
+ continue;
505
+ }
506
+ if (verdict.state === "unknown") {
507
+ // Fail closed: a branch that cannot be *proven* to contain the marker
508
+ // is refused, and the reason names the unverifiable marker so the
509
+ // operator can fix the fetch or the marker rather than guess.
510
+ hold(issue, "stale-base");
511
+ log(
512
+ `#${issue} held (stale-base): continuation branch ${branch} could not be verified ` +
513
+ `against critical-base marker(s) ${markers.join(", ")} (${verdict.error})`,
514
+ );
515
+ await safeEscalate(d, {
516
+ tier: 1,
517
+ project: project.name,
518
+ issue,
519
+ summary: `#${issue} continuation branch could not be verified against a critical base safety commit and is held (stale-base)`,
520
+ detail: [
521
+ r.issue.title,
522
+ r.issue.url,
523
+ `The retained branch ${branch} could not be verified against critical-base marker(s) ${markers.join(", ")}: ${verdict.error}`,
524
+ "Recovery: merge current base into the branch so it contains the marker, and the next",
525
+ "admission pass re-admits it automatically without losing the branch's work; or review",
526
+ "the branch by hand and clear the hold once the fix is present.",
527
+ ].join("\n"),
528
+ });
529
+ continue;
530
+ }
531
+ }
532
+
533
+ // Soft concurrency per epic, per repository: at most one in-flight child of
534
+ // a given parent in each repo. Children of one epic in *different* repos
535
+ // parallelise freely — `repo-active` / `maxConcurrentWorkersPerRepo` owns
536
+ // the same-repo collision domain (#197). The "" sentinel matches every
537
+ // repo. No parent means today's concurrent admission. Cheap local filters
538
+ // already ran; this sits before the open-PR API call so a held sibling
539
+ // frees the slot for unrelated work without spending a closers query.
540
+ let parent: number | undefined;
541
+ try {
542
+ parent = await resolveParent(issue);
543
+ } catch (err) {
544
+ hold(issue, "parent-lookup-error");
545
+ log(`#${issue} held: parent check failed (${errText(err)}) — retrying next tick`);
546
+ continue;
547
+ }
548
+ if (parent !== undefined) {
549
+ const occupied = occupiedParents.get(parent);
550
+ const blocker = occupied?.get(r.repo.name) ?? occupied?.get("");
551
+ // The gate serializes siblings under one epic: a held candidate must not
552
+ // proceed while a *different* child of the parent is occupied. But a
553
+ // candidate's own worker-free pushed-green row is exactly the work it is
554
+ // continuing, not a rival — the unblocked continuation of that same
555
+ // issue must not be rejected by its own occupancy, or the retained
556
+ // continuation deadlocks forever with the PR open.
557
+ if (blocker !== undefined && blocker !== issue) {
558
+ hold(issue, "sibling-active");
559
+ log(`#${issue} skipped: sibling #${blocker} in flight under epic #${parent} in ${r.repo.name}`);
560
+ continue;
561
+ }
562
+ }
563
+
564
+ // The busy set is built from run rows, so it can only speak for work this
565
+ // database recorded. Work pushed before this store existed — a migration, a
566
+ // wiped or relocated state dir, a restore onto a new host — looks exactly
567
+ // like fresh work, and a worker sent at it re-implements a finished PR. The
568
+ // tracker is the only party that remembers, so it is asked. The cost is
569
+ // bounded by free slots, not by queue depth: the call sits behind the two
570
+ // cheap local filters and candidates beyond capacity skip it.
571
+ let closer: OpenCloser | undefined;
572
+ try {
573
+ closer = await tracker.openCloserFor(issue);
574
+ } catch (err) {
575
+ // Fail closed, per candidate. An API error means "unknown whether
576
+ // finished work exists", and admitting on unknown recreates precisely the
577
+ // duplicate-work failure this guard exists to kill: the worst case of
578
+ // holding is a five-minute delay, the worst case of admitting is a burned
579
+ // attempt and a second PR on the same issue. Holding one candidate rather
580
+ // than aborting the loop keeps a transient GitHub failure from deadlocking
581
+ // the whole dispatcher; the next tick retries by itself.
582
+ hold(issue, "open-pr-lookup-error");
583
+ log(`#${issue} held: open-PR check failed (${errText(err)}) — retrying next tick`);
584
+ continue;
585
+ }
586
+ if (closer !== undefined) {
587
+ const latest = store.latestRun(project.name, issue);
588
+ // Terminality is the first half of the test and is not negotiable: while a
589
+ // run is live its worker is still pushing to that branch, and a second
590
+ // worker sent at the same PR is exactly the duplicate-work failure this
591
+ // guard exists to kill. Only a run that has stopped can be continued.
592
+ const retained =
593
+ latest?.state === "blocked" ||
594
+ latest?.state === "failed" ||
595
+ latest?.state === "killed" ||
596
+ latest?.state === "orphaned" ||
597
+ latest?.state === "pushed-green"
598
+ ? latest
599
+ : undefined;
600
+ // The second half asks "is this open PR our retained work", and accepts
601
+ // two identities for it, because the branch is the durable artefact of a
602
+ // retained run and the PR is not. A cap kill can end a run before any PR
603
+ // exists: veltro#324 attempt 1 was killed at the turns cap on
604
+ // 2026-08-09T00:47Z before its worker opened one, so the row kept `branch`
605
+ // and `prUrl` stayed NULL. chad#438 was opened from that exact branch
606
+ // afterwards, and URL equality — the only test 0.3.20 had — can never match
607
+ // a URL the terminal run never recorded, so every tick held #324 as
608
+ // `open-pr` until an operator closed recoverable work to free the branch
609
+ // (#50). An ordinary issue whose open PR is unrelated still fails both
610
+ // identities and stays ineligible, and an empty `headRefName` (a reply that
611
+ // did not carry the field) is never a match: unknown is not identity.
612
+ let resume: string | undefined;
613
+ if (retained !== undefined) {
614
+ if (retained.prUrl === closer.url) {
615
+ resume = `from ${retained.state} run (matched recorded PR URL)`;
616
+ } else if (closer.headRefName !== "" && retained.branch === closer.headRefName) {
617
+ resume = `from ${retained.state} run (matched retained branch ${closer.headRefName})`;
618
+ }
619
+ }
620
+ if (resume === undefined) {
621
+ hold(issue, "open-pr");
622
+ log(`#${issue} skipped: open PR ${closer.url} already closes it`);
623
+ continue;
624
+ }
625
+ log(`#${issue} continuing retained PR ${closer.url} ${resume}`);
626
+ }
627
+
628
+ // The queue comes from GitHub's eventually-consistent search index. Re-read
629
+ // state and labels directly at the last possible moment so a just-closed or
630
+ // explicitly dequeued issue cannot turn a stale candidate into another
631
+ // attempt (#247).
632
+ let snapshot: IssueSnapshot | undefined;
633
+ try {
634
+ snapshot = await tracker.issueSnapshot(issue);
635
+ } catch {
636
+ snapshot = undefined;
637
+ }
638
+ if (snapshot === undefined) {
639
+ hold(issue, "issue-state-lookup-error");
640
+ log(`#${issue} held: issue snapshot check failed — retrying next tick`);
641
+ continue;
642
+ }
643
+ if (snapshot.state === "closed") {
644
+ hold(issue, "issue-closed");
645
+ log(`#${issue} skipped: issue is closed (search index lag)`);
646
+ continue;
647
+ }
648
+ if (!snapshot.labels.includes(project.queueLabel)) {
649
+ hold(issue, "issue-dequeued");
650
+ log(`#${issue} skipped: queue label ${project.queueLabel} was removed (search index lag)`);
651
+ continue;
652
+ }
653
+
654
+ // The Depends-on interlock (#419/#420): a candidate declares the issues it
655
+ // must not be dispatched before — same-repo (`#123`) or cross-repo
656
+ // (`owner/repo#123`) — and any *open* prerequisite holds it until every
657
+ // referenced issue is closed. Prerequisite state is read fresh from the
658
+ // tracker at claim time, every pass — never cached across ticks — so a
659
+ // prerequisite that reopens re-holds on the next tick. Cross-repo
660
+ // references resolve only against repositories routed in this fleet;
661
+ // graph cycles are a later slice (#421).
662
+ const dependsOn = parseDependsOn(r.issue.body);
663
+ if (dependsOn.malformed.length > 0) {
664
+ // A marker line with no strict `#<n>` reference (e.g. `Depends-on:
665
+ // #abc`) is ignored as a gate — it never holds, and it never crashes —
666
+ // but it is flagged so the issue is never *silently* dispatched with a
667
+ // dependency nobody read. Emitted once: the escalation ledger dedupes on
668
+ // the stable project/issue/tier/summary key, so repeated ticks do not
669
+ // re-page the orchestrator for the same malformed body.
670
+ await safeEscalate(d, {
671
+ tier: 1,
672
+ project: project.name,
673
+ issue,
674
+ summary: `#${issue} has a malformed Depends-on declaration and its undeclared prerequisite was not held`,
675
+ detail: [
676
+ r.issue.title,
677
+ r.issue.url,
678
+ ...dependsOn.malformed.map((line) => `Malformed declaration: ${line}`),
679
+ "Depends-on references must be bare issue numbers (`#<n>`). Groom the body",
680
+ "so the dependency is honoured, or the issue is dispatched without it.",
681
+ ].join("\n"),
682
+ });
683
+ log(`#${issue} flagged: malformed depends-on declaration(s): ${dependsOn.malformed.join("; ")}`);
684
+ }
685
+ if (dependsOn.refs.length > 0) {
686
+ let blocking: number | undefined;
687
+ let unreadable: number | undefined;
688
+ for (const ref of dependsOn.refs) {
689
+ let state: IssueSnapshot | undefined;
690
+ try {
691
+ state = await tracker.issueSnapshot(ref);
692
+ } catch {
693
+ state = undefined;
694
+ }
695
+ if (state?.state === "open") {
696
+ blocking = ref;
697
+ break;
698
+ }
699
+ if (state === undefined) {
700
+ unreadable = ref;
701
+ break;
702
+ }
703
+ }
704
+ // Fail closed on an unreadable prerequisite: admitting on unknown would
705
+ // dispatch work whose prerequisite may still be open, and the next tick
706
+ // rereads the tracker itself, so a transient failure just defers.
707
+ if (blocking !== undefined) {
708
+ hold(issue, "depends-on", `blocked by #${blocking}`);
709
+ log(`#${issue} held (depends-on): prerequisite #${blocking} is open`);
710
+ continue;
711
+ }
712
+ if (unreadable !== undefined) {
713
+ hold(issue, "depends-on", `prerequisite #${unreadable} state unreadable`);
714
+ log(`#${issue} held (depends-on): prerequisite #${unreadable} state unreadable`);
715
+ continue;
716
+ }
717
+ }
718
+ if (dependsOn.crossRefs.length > 0) {
719
+ // The cross-repo half (#420): each `owner/repo#n` is read from the repo
720
+ // it names. The fully qualified form travels in the `detail` string, so
721
+ // status/digest render it as `blocked by owner/repo#123` while same-repo
722
+ // refs stay compact `blocked by #5`.
723
+ let blocking: string | undefined;
724
+ let unreadable: string | undefined;
725
+ let unresolved: string | undefined;
726
+ for (const ref of dependsOn.crossRefs) {
727
+ const where = crossRepoTarget(project, ref.repo);
728
+ const full = `${ref.repo}#${ref.issue}`;
729
+ if (where === undefined) {
730
+ unresolved = full;
731
+ break;
732
+ }
733
+ let state: IssueSnapshot | undefined;
734
+ try {
735
+ if (where === "tracker") {
736
+ // The qualified form of the candidate's own tracker repo: the
737
+ // same state read the same-repo interlock uses.
738
+ state = await tracker.issueSnapshot(ref.issue);
739
+ } else if (d.probeIssueIn === undefined) {
740
+ // No resolver wired — fail closed, never guess the issue's state.
741
+ state = undefined;
742
+ } else {
743
+ state = await d.probeIssueIn(ref.repo, ref.issue);
744
+ }
745
+ } catch {
746
+ state = undefined;
747
+ }
748
+ if (state?.state === "open") {
749
+ blocking = full;
750
+ break;
751
+ }
752
+ if (state === undefined) {
753
+ unreadable = full;
754
+ break;
755
+ }
756
+ }
757
+ // Same fail-closed posture as same-repo refs: an open prerequisite
758
+ // holds, an unreadable one holds (the next tick rereads it fresh), and
759
+ // an unresolved repo holds because the dispatcher cannot verify the
760
+ // dependency — it is never silently treated as closed. Only the
761
+ // unresolved repo also surfaces one material event for grooming, and it
762
+ // follows the malformed-declaration escalation's stable-summary
763
+ // dedupe, so repeated ticks page once, not per tick.
764
+ if (blocking !== undefined) {
765
+ hold(issue, "depends-on", `blocked by ${blocking}`);
766
+ log(`#${issue} held (depends-on): cross-repo prerequisite ${blocking} is open`);
767
+ continue;
768
+ }
769
+ if (unreadable !== undefined) {
770
+ hold(issue, "depends-on", `prerequisite ${unreadable} state unreadable`);
771
+ log(`#${issue} held (depends-on): cross-repo prerequisite ${unreadable} state unreadable`);
772
+ continue;
773
+ }
774
+ if (unresolved !== undefined) {
775
+ hold(issue, "depends-on", `blocked by ${unresolved} — repo not routed in this fleet`);
776
+ log(`#${issue} held (depends-on): cross-repo prerequisite ${unresolved} is not a routed repo`);
777
+ await safeEscalate(d, {
778
+ tier: 1,
779
+ project: project.name,
780
+ issue,
781
+ summary: `#${issue} depends on ${unresolved}, a repo not routed in this fleet — held until groomed`,
782
+ detail: [
783
+ r.issue.title,
784
+ r.issue.url,
785
+ `Unroutable prerequisite: ${unresolved}`,
786
+ "Depends-on cross-repo references must name a repository routed in this project",
787
+ "(`routing.repos` or the tracker repo). Groom the body or route the repo.",
788
+ ].join("\n"),
789
+ });
790
+ continue;
791
+ }
792
+ }
793
+
794
+ // The file-lane interlock (#555): a candidate whose declared lane overlaps
795
+ // a live run's *actual* lane is held until that run's work has merged, so
796
+ // no second worker is sent at files another worker is still writing. The
797
+ // gate is the mechanical version of the prose rule that failed three times
798
+ // in one day. Only the machine-readable lane participates: a candidate
799
+ // without one is admitted exactly as today (fail open), and a candidate's
800
+ // own retained run never holds it — that is the continuation it continues.
801
+ const lane = declaredLane(r.issue.body);
802
+ if (lane.length > 0) {
803
+ const occupied = await ensureLaneOccupancy();
804
+ const perRepo = occupied.get(r.repo.name);
805
+ let blocked = false;
806
+ for (const file of lane) {
807
+ const holder = perRepo?.get(file);
808
+ if (holder !== undefined && holder !== issue) {
809
+ const detail = `${file} held by run #${holder}`;
810
+ hold(issue, "file-lane", detail);
811
+ log(`#${issue} held (file-lane): ${detail}`);
812
+ blocked = true;
813
+ break;
814
+ }
815
+ }
816
+ if (blocked) continue;
817
+ }
818
+
819
+ admitted.push({ r, attempt: priorRuns + 1 });
820
+ liveByRepo.set(r.repo.name, (liveByRepo.get(r.repo.name) ?? 0) + 1);
821
+ // Same-pass sibling occupancy for the file-lane gate: once admitted, a
822
+ // candidate's declared lane occupies for the rest of the pass, so a later
823
+ // overlapping candidate is held rather than both clearing in one tick.
824
+ if (lane.length > 0) {
825
+ const occupied = await ensureLaneOccupancy();
826
+ let perRepo = occupied.get(r.repo.name);
827
+ if (perRepo === undefined) {
828
+ perRepo = new Map();
829
+ occupied.set(r.repo.name, perRepo);
830
+ }
831
+ for (const file of lane) {
832
+ if (!perRepo.has(file)) perRepo.set(file, issue);
833
+ }
834
+ }
835
+ if (parent !== undefined) {
836
+ // Extend the epic's occupancy under this repo (slot empty by construction
837
+ // here — the gate above would have held the candidate otherwise) so a
838
+ // same-repo sibling later in this pass does not clear the gate (#197).
839
+ let siblings = occupiedParents.get(parent);
840
+ if (siblings === undefined) {
841
+ siblings = new Map();
842
+ occupiedParents.set(parent, siblings);
843
+ }
844
+ if (!siblings.has(r.repo.name)) siblings.set(r.repo.name, issue);
845
+ }
846
+ }
847
+
848
+ return { admitted, holds };
849
+ }