omp-conductor 0.17.1 → 0.18.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 (65) hide show
  1. package/README.md +34 -0
  2. package/REFERENCE.md +71 -17
  3. package/agents/to-spec.md +90 -0
  4. package/package.json +2 -1
  5. package/schema/config.schema.json +53 -1
  6. package/src/admission.ts +308 -76
  7. package/src/ask.ts +307 -10
  8. package/src/backups.ts +2 -2
  9. package/src/board.ts +17 -3
  10. package/src/briefs/orchestrator.md +43 -14
  11. package/src/briefs/to-spec.md +84 -0
  12. package/src/briefs/worker.md +37 -19
  13. package/src/cli.ts +2 -0
  14. package/src/command-help.ts +19 -1
  15. package/src/command-manifest.ts +27 -2
  16. package/src/commands/context.ts +1 -0
  17. package/src/commands/drain.ts +176 -0
  18. package/src/commands/extend.ts +6 -10
  19. package/src/commands/status.ts +5 -1
  20. package/src/commands/watch.ts +110 -3
  21. package/src/commands/worker.ts +9 -10
  22. package/src/config-schema.ts +57 -0
  23. package/src/config.ts +102 -2
  24. package/src/daemon.ts +1220 -1517
  25. package/src/dashboard/app.js +4 -1
  26. package/src/dashboard/server.ts +5 -2
  27. package/src/decisions.ts +279 -16
  28. package/src/depends-on.ts +261 -1
  29. package/src/diff-flags.ts +425 -1
  30. package/src/digest-schedule.ts +37 -0
  31. package/src/doctor.ts +52 -0
  32. package/src/escalate.ts +9 -3
  33. package/src/failure-class.ts +43 -4
  34. package/src/fleet.ts +166 -24
  35. package/src/gitops.ts +188 -81
  36. package/src/graph-health.ts +55 -8
  37. package/src/graph.ts +379 -69
  38. package/src/harness-loader.ts +59 -0
  39. package/src/host.ts +567 -2
  40. package/src/lifecycle.ts +158 -6
  41. package/src/omp.ts +269 -20
  42. package/src/orchestrator-tick.ts +1489 -26
  43. package/src/orchestrator.ts +12 -0
  44. package/src/privileged.ts +1 -4
  45. package/src/release-policy.ts +503 -9
  46. package/src/routing.ts +11 -3
  47. package/src/session-host.ts +115 -5
  48. package/src/settlement.ts +1780 -0
  49. package/src/setup-host.ts +1205 -6
  50. package/src/setup-install.ts +119 -30
  51. package/src/setup-wizard.ts +88 -2
  52. package/src/setup.ts +119 -13
  53. package/src/shell.ts +15 -0
  54. package/src/status-render.ts +100 -11
  55. package/src/store.ts +519 -45
  56. package/src/to-spec.ts +387 -0
  57. package/src/tracker/github.ts +150 -14
  58. package/src/types.ts +470 -16
  59. package/src/upgrade-verify.ts +209 -2
  60. package/src/upgrade.ts +175 -1
  61. package/src/verbs/protocol.ts +39 -0
  62. package/src/verbs/server.ts +770 -40
  63. package/src/verbs/socket.ts +24 -5
  64. package/src/worker.ts +239 -9
  65. package/src/worktree.ts +142 -18
@@ -0,0 +1,1780 @@
1
+ /**
2
+ * The settlement half of the dispatcher — push-result sweeps, orphan
3
+ * reconciliation, worktree settlement and failure classification recovery
4
+ * (`daemon.ts` composes; this owns the region).
5
+ *
6
+ * Extracted from `daemon.ts` (TerrifiedBug/conductor#705) so the second most
7
+ * contested region of the composition root is a lane of its own: a settlement
8
+ * diff must not have to touch the composition root. This is a move, not a
9
+ * rewrite — behaviour is byte-identical; a later slice reworks the seams.
10
+ *
11
+ * The module is a leaf: it never imports `daemon.ts`, and `daemon.ts` never
12
+ * re-exports it. What it needs from the daemon that only the daemon owns —
13
+ * the pause-sentinel ops used by the provider-credit recovery — arrives as
14
+ * fields of the structural {@link SettlementDeps}, wired at the call sites.
15
+ */
16
+
17
+ import { existsSync, readFileSync } from "node:fs";
18
+ import { log, errText, safeEscalate } from "./log.ts";
19
+ import { hasContinuationBudget } from "./admission.ts";
20
+ import {
21
+ UNREADABLE_TREE_FLAG,
22
+ analyseSettlement,
23
+ deriveChangedLine,
24
+ } from "./diff-flags.ts";
25
+ import { classifyRun, normalise, type ClassifyFacts } from "./failure-class.ts";
26
+ import { GhPrMissingError } from "./tracker/github.ts";
27
+ import { formatModelsTried, modelsTried } from "./model-fallback.ts";
28
+ import { PR_LOOKUP_WINDOW_MS } from "./decisions.ts";
29
+ import {
30
+ removeWorktree,
31
+ salvageWip,
32
+ type RunPublisher,
33
+ type SalvageOutcome,
34
+ } from "./worktree.ts";
35
+ import type {
36
+ Caps,
37
+ Escalation,
38
+ FailureClass,
39
+ FileLane,
40
+ MergedPrInfo,
41
+ OpenCloser,
42
+ PrState,
43
+ ProjectConfig,
44
+ RecoveryAction,
45
+ RunRecord,
46
+ RunState,
47
+ SettlementFlag,
48
+ Store,
49
+ Tracker,
50
+ } from "./types.ts";
51
+
52
+ /** Fleet-wide escalations still need an issue number in the payload; 0 is the
53
+ * sentinel that reads as "no issue" in every renderer. One per module —
54
+ * `admission.ts`, `daemon.ts` and this module each hold their own copy. */
55
+ const NO_ISSUE = 0;
56
+
57
+ /**
58
+ * The slice of the daemon's `Deps` settlement reads. Defined here rather than
59
+ * imported from `daemon.ts` (that would be the cycle this leaf exists to
60
+ * avoid); the composition root wires it at the call sites, and
61
+ * `daemon.test.ts`'s shared fake satisfies it (its `deps()` helper gained the
62
+ * two pause-op passthroughs below when this module landed).
63
+ *
64
+ * `isPaused`/`setPaused` are the pause-sentinel ops, owned by the daemon
65
+ * (the pause cluster has a long list of other consumers that import them from
66
+ * there); the composition root wires them in. Keeping them off the object is
67
+ * what lets this module stay a leaf.
68
+ */
69
+ export interface SettlementDeps {
70
+ project: ProjectConfig;
71
+ caps: Caps;
72
+ tracker: Tracker;
73
+ store: Store;
74
+ escalate(e: Escalation): Promise<void>;
75
+ /** Whether the pause sentinel is set, daemon-owned. */
76
+ isPaused(project?: string): boolean;
77
+ /** Writes the pause sentinel, daemon-owned. */
78
+ setPaused(
79
+ paused: boolean,
80
+ provenance: { source: string; reason?: string },
81
+ project?: string,
82
+ ): void;
83
+ }
84
+
85
+ /** What the settlement audit of one green run produced: the advisory flags
86
+ * (test weakening only — the file-list disclosure is derived, not flagged),
87
+ * whether the diff was cut short, and the `changed:` line composed from the
88
+ * PR's own diff. */
89
+ export interface SettlementAuditResult {
90
+ flags: SettlementFlag[];
91
+ truncated: boolean;
92
+ /** The `changed:` file list derived from the PR's diff, present whenever the
93
+ * diff could be read. Absent means the tree could not be read, and `flags`
94
+ * then carries exactly {@link UNREADABLE_TREE_FLAG}. */
95
+ changedLine?: string;
96
+ }
97
+
98
+ /**
99
+ * Audit a worker's own account of its work against the pull request it pushed.
100
+ *
101
+ * The thin half of the split #85 established: this fetches, {@link
102
+ * analyseSettlement} decides. It runs beside {@link verifyPushedGreenClaim} and
103
+ * shares none of its authority — that function decides a run's state, this one
104
+ * cannot, by construction. It returns evidence and the caller appends it.
105
+ *
106
+ * A diff that cannot be read is a finding (`changed-line-missing`), never an
107
+ * empty flag list: nothing was derived and nothing was checked, and that must
108
+ * not read as a clean bill.
109
+ */
110
+ export async function collectSettlementFlags(
111
+ tracker: Pick<Tracker, "prDiff" | "prBody">,
112
+ claim: { prUrl?: string; issueText: string; sessionFile?: string; lane?: FileLane },
113
+ ): Promise<SettlementAuditResult> {
114
+ if (claim.prUrl === undefined) return { flags: [UNREADABLE_TREE_FLAG], truncated: false };
115
+ // The diff and the claimed-proof body read in parallel; both are advisory,
116
+ // and an unreadable either one costs that half of the audit and never a
117
+ // run's state.
118
+ const [diff, prBody] = await Promise.all([
119
+ tracker.prDiff(claim.prUrl),
120
+ tracker.prBody(claim.prUrl),
121
+ ]);
122
+ if (diff === undefined) return { flags: [UNREADABLE_TREE_FLAG], truncated: false };
123
+ // Absent session/transcript stays silent — no command can be checked —
124
+ // never "every claim is verified", the same "could not read" posture as
125
+ // `changed-line-missing`.
126
+ let transcript: string | undefined;
127
+ if (claim.sessionFile !== undefined) {
128
+ try {
129
+ transcript = readFileSync(claim.sessionFile, "utf8");
130
+ } catch {
131
+ transcript = undefined;
132
+ }
133
+ }
134
+ return {
135
+ flags: analyseSettlement({
136
+ issueText: claim.issueText,
137
+ diff,
138
+ ...(prBody === undefined ? {} : { prBody }),
139
+ ...(transcript === undefined ? {} : { transcript }),
140
+ ...(claim.lane === undefined ? {} : { lane: claim.lane }),
141
+ }),
142
+ truncated: diff.truncated,
143
+ changedLine: deriveChangedLine(diff),
144
+ };
145
+ }
146
+
147
+
148
+
149
+ // ------------------------------------------------------------------- pushed-green settlement
150
+
151
+ /** What a resolved PR turns its `pushed-green` row into. */
152
+ export interface Settlement {
153
+ state: "merged" | "failed";
154
+ /** The log line after `#<n> settled: `, and — for a rejection — the row's own
155
+ * `lastError`, because a `failed` row whose worker succeeded has to say so. */
156
+ reason: string;
157
+ }
158
+
159
+ /**
160
+ * What one `pushed-green` row becomes now its PR has an answer, or undefined to
161
+ * leave the row exactly as it is.
162
+ *
163
+ * A `pushed-green` row is the only one nothing ever revisited: the worker is
164
+ * finished, `reconcileOrphanedRuns` only settles rows that held a process, and
165
+ * `merged` went unwritten from day one. So they accumulated — three of them on
166
+ * the reference fleet on 2026-08-07, every PR merged and every issue closed,
167
+ * with `/healthz` still reporting three active runs and their issues
168
+ * permanently unclaimable, because the busy set *is* the active set (#18).
169
+ *
170
+ * The mapping, and why each answer is the only honest one:
171
+ *
172
+ * - `merged` — the work landed. That is what `merged` was reserved for.
173
+ * - `closed` — a human read the work and said no. Leaving it `pushed-green`
174
+ * forever is a lie; `failed` records that it did not land and releases the
175
+ * busy guard, so an issue a human re-queues can be attempted again. A row
176
+ * that had reached `pushed-green` or `pushed-pending` is classified
177
+ * `returned-for-revision` at settlement. A review decision asks for another
178
+ * implementation pass, not a failure, so it consumes the continuation budget
179
+ * instead of the failed-attempt budget.
180
+ * - `missing` — the claimed PR definitively does not exist (a definitive 404
181
+ * from the tracker, never a transient outage). Work was pushed but no PR
182
+ * ever appeared, so the honest terminal is the same as `closed`: `failed`,
183
+ * work preserved on the branch and the issue returned to the queue as a
184
+ * continuation. Nothing retrying can recover — a missing PR does not grow
185
+ * back (#779).
186
+ * - `open`, and undefined — nothing changes. Undefined is "could not tell": a
187
+ * flaky network, a revoked token. Settling on it would record a merge that
188
+ * never happened, and the next tick asks again for free. An ambiguous answer
189
+ * must never settle a row.
190
+ */
191
+ export function settlementFor(
192
+ pr: PrState | "missing" | undefined,
193
+ prUrl: string,
194
+ ): Settlement | undefined {
195
+ if (pr === "merged") return { state: "merged", reason: `${prUrl} merged` };
196
+ if (pr === "closed") return { state: "failed", reason: `${prUrl} closed without merging` };
197
+ if (pr === "missing") return { state: "failed", reason: `PR ${prUrl} does not exist` };
198
+ return undefined;
199
+ }
200
+
201
+ /**
202
+ * Records the in-progress label's release as a projection op (#201).
203
+ *
204
+ * Settlement used to write only half of what it knew. On 2026-08-09 that cost
205
+ * the reference fleet two issues in one night: veltro#331 settled to `failed`
206
+ * at 23:53Z once the orchestrator closed veltro#332 unmerged, and veltro#344
207
+ * settled to `merged` at 05:54Z once chad#452 squash-merged. Both rows left the
208
+ * active set correctly; an authoritative `gh issue view` on each afterwards
209
+ * still showed `agent:in-progress` — permanently unclaimable with no supported
210
+ * way back (#18).
211
+ *
212
+ * The outbox makes the row transition and the label one fact again: the
213
+ * removal is enqueued in the same breath as the row is terminalised, the
214
+ * projector applies it with unbounded retry, and while it is pending the
215
+ * eligibility overlay treats the label as already gone. A tracker that refuses
216
+ * the write (403, rate limit) can no longer strand the row — that is `#184`
217
+ * and `#198` closed. No `pushed-*` row is ever written terminal with its
218
+ * label release owed but unrecorded, because enqueueing is a local store write
219
+ * that cannot fail on the tracker.
220
+ *
221
+ * Synchronous. The op is durable the moment this returns.
222
+ */
223
+ export function releaseInProgress(
224
+ d: Pick<SettlementDeps, "project" | "store">,
225
+ issue: number,
226
+ why: string,
227
+ ): void {
228
+ const label = d.project.stateLabels.inProgress;
229
+ d.store.enqueueLabelOps(d.project.name, [{ issue, op: "remove", label }]);
230
+ log(`#${issue} released ${label} (queued): ${why}`);
231
+ }
232
+
233
+ /**
234
+ * Records the queue label's release as a projection op (#607).
235
+ *
236
+ * A settled merge means the work landed. Whether the merge closed the issue or
237
+ * the PR carried no closing keyword and left it open, the issue must not stay
238
+ * claimable — and the queue label is the claim gate. Before this function
239
+ * existed nothing ever took it off a settled issue: the claim path only adds
240
+ * the in-progress label, so `ready-for-agent` rode along through the run and
241
+ * outlived the merge. By 2026-08-17 the closed-issue backlog still carrying it
242
+ * exceeded GitHub's 50-result listing page on this fleet's tracker.
243
+ *
244
+ * Same outbox discipline as {@link releaseInProgress}: the removal is a
245
+ * durable local write enqueued in the same breath as the terminal row, the
246
+ * projector applies it with unbounded retry, and while it is pending the
247
+ * eligibility overlay treats the label as already gone. A removal that races a
248
+ * human's own removal lands as a no-op on the tracker (REST DELETE of an
249
+ * absent label is idempotent), so it can never resurrect a label the operator
250
+ * took off.
251
+ *
252
+ * Synchronous. The op is durable the moment this returns.
253
+ */
254
+ export function releaseQueueLabel(
255
+ d: Pick<SettlementDeps, "project" | "store">,
256
+ issue: number,
257
+ why: string,
258
+ ): void {
259
+ const label = d.project.queueLabel;
260
+ d.store.enqueueLabelOps(d.project.name, [{ issue, op: "remove", label }]);
261
+ log(`#${issue} released ${label} (queued): ${why}`);
262
+ }
263
+
264
+
265
+ /**
266
+ * Asks the tracker about every `pushed-green` PR and settles the ones that
267
+ * resolved.
268
+ *
269
+ * Effects at the call site, decision in {@link settlementFor} — the same split
270
+ * as `checkIntegrity`/`watchOrchestrator`. Exported like `admitCandidates`
271
+ * rather than kept private, because half of what has to hold is about the sweep
272
+ * and not the mapping: that a row without a PR costs no API call, and that one
273
+ * unreachable PR does not stop the others from settling.
274
+ *
275
+ * The label is released too, which reverses what this function first promised.
276
+ * It used to leave tracker labels alone exactly as {@link reconcileOrphanedRuns}
277
+ * does, reasoning that a merge closes the issue anyway and that deciding what an
278
+ * issue's labels should say next is the orchestrator's drain duty. There turned
279
+ * out to be no such path: on 2026-08-09 two settled rows left their issues
280
+ * carrying `agent:in-progress` forever, with the brief forbidding the
281
+ * orchestrator from touching it and `unblock` declining to (see
282
+ * {@link releaseInProgress}). The row transition and the label are one fact, and
283
+ * writing half of it is the whole of that bug.
284
+ *
285
+ * Releasing it is safe here specifically because of what these rows are. A
286
+ * `pushed-green` or `pushed-pending` row has no process behind it — its worker
287
+ * exited and its worktree is gone — so a terminal answer about its PR proves no
288
+ * worker owns the issue, and the duplicate-dispatch interlock the label exists
289
+ * for is spent. {@link reconcileOrphanedRuns} still leaves labels alone for the
290
+ * opposite reason: an orphaned `running` row is work nobody has read yet. And
291
+ * the brief's rule stays absolute, because this is a daemon-owned write through
292
+ * the same Tracker port the dispatcher claimed the issue with — orphan detection
293
+ * is only trustworthy while every state label on the tracker came from this
294
+ * package.
295
+ *
296
+ * The two writes are ordered label-then-row, and the order is load-bearing. This
297
+ * sweep is the only thing that revisits a `pushed-*` row, so the terminal state
298
+ * is also the row's exit from it: written first, a tracker that then failed on
299
+ * the label would leave `agent:in-progress` with nothing left to retry it — #18
300
+ * exactly, in the last window able to reach it. Writing the label first makes
301
+ * failure cost a repeated `gh` call on the next tick instead, and the row stays
302
+ * in the busy set throughout, so no second worker can be sent at the issue while
303
+ * it waits.
304
+ */
305
+ export async function settlePushedGreen(
306
+ d: Pick<SettlementDeps, "project" | "tracker" | "store">,
307
+ ): Promise<number> {
308
+ const { project, tracker, store } = d;
309
+ // Runs the sweep resolved by terminalising the row. Every terminal write
310
+ // below increments it; the tick attributes it as `settled` on the pass's
311
+ // dispatch record, so a held pass is visible as work done, not just as a
312
+ // clock that moved (#497).
313
+ let settled = 0;
314
+ // Filtered from the active set rather than asked for with a new query: active
315
+ // is live workers plus these, so the list is bounded by the worker cap plus
316
+ // the number of PRs awaiting a merge — a handful, by construction. A fleet
317
+ // where that is not a handful has a merge problem, not a dispatch one.
318
+ const pending = store
319
+ .activeRuns(project.name)
320
+ .filter((r) => r.state === "pushed-green" || r.state === "pushed-pending");
321
+
322
+ for (const run of pending) {
323
+ // Nothing to ask about. A pushed result requires a PR, so a malformed row
324
+ // must not buy a `gh` call every five minutes forever.
325
+ if (run.prUrl === undefined) continue;
326
+
327
+ let pr: PrState | "missing" | undefined;
328
+ try {
329
+ pr = await tracker.prState(run.prUrl);
330
+ } catch (err) {
331
+ // The adapter throws exactly one classified error: `GhPrMissingError`,
332
+ // an individual REST 404 the adapter has corroborated with a
333
+ // same-repository pulls-list read, so the claimed PR definitively does
334
+ // not exist (#779). That is not "could not tell" — retrying can never
335
+ // conjure the PR — so the row is settled as a missing PR through the
336
+ // same mapping as a closed one: work preserved on the branch, busy guard
337
+ // released, issue back on the queue. A raw 404 that was never
338
+ // corroborated (a hidden repository, a lost token scope) stays "could
339
+ // not tell": the instance check is the corroboration, and every other
340
+ // failure retries next tick, per row — a tracker that throws
341
+ // unclassified must cost its own row, not the whole sweep.
342
+ if (err instanceof GhPrMissingError) {
343
+ pr = "missing";
344
+ } else {
345
+ log(`#${run.issue} not settled: PR state lookup failed (${errText(err)}) — retrying next tick`);
346
+ continue;
347
+ }
348
+ }
349
+
350
+ const settlement = settlementFor(pr, run.prUrl);
351
+ if (settlement !== undefined) {
352
+ // A mediated merge enters a second, bounded observation phase. Record the
353
+ // exact merge commit before the row leaves the active set; if GitHub cannot
354
+ // supply it yet, retry this settlement next tick rather than create a
355
+ // merged row whose base result can never be attributed.
356
+ let merged: MergedPrInfo | undefined;
357
+ if (settlement.state === "merged") {
358
+ try {
359
+ merged = await tracker.mergedPrInfo(run.prUrl);
360
+ } catch (err) {
361
+ log(`#${run.issue} not settled: merge identity lookup failed (${errText(err)}) — retrying next tick`);
362
+ continue;
363
+ }
364
+ if (merged === undefined) {
365
+ log(`#${run.issue} not settled: merge identity unavailable — retrying next tick`);
366
+ continue;
367
+ }
368
+ }
369
+
370
+ // The label removal and the terminal row are one fact again (#201): the
371
+ // release is enqueued — a durable local write that cannot fail on the
372
+ // tracker — in the same breath as the row is terminalised.
373
+ releaseInProgress(d, run.issue, settlement.reason);
374
+ if (settlement.state === "merged") {
375
+ // #607: merged work is done — whether the merge closed the issue or
376
+ // the PR carried no closing keyword and left it open — so the claim
377
+ // gate comes off too, through the same durable projection. A failed
378
+ // settlement (closed without merging) keeps the queue label: the
379
+ // issue is meant to return to the queue for another attempt.
380
+ releaseQueueLabel(d, run.issue, settlement.reason);
381
+ }
382
+ const patch: Partial<RunRecord> = {
383
+ state: settlement.state,
384
+ endedAt: Date.now(),
385
+ ...(merged === undefined
386
+ ? {}
387
+ : {
388
+ mergeSha: merged.mergeSha,
389
+ baseRef: merged.baseRef,
390
+ baseCheck: "pending",
391
+ }),
392
+ };
393
+ if (settlement.state === "failed") {
394
+ patch.lastError = settlement.reason;
395
+ patch.failureClass = "returned-for-revision";
396
+ patch.recoveryAction = "none";
397
+ }
398
+ store.updateRun(run.id, patch);
399
+ settled += 1;
400
+ log(`#${run.issue} settled: ${settlement.reason}`);
401
+ continue;
402
+ }
403
+
404
+ if (run.state !== "pushed-pending" || pr !== "open" || run.headSha === undefined) continue;
405
+ let verification;
406
+ try {
407
+ verification = await tracker.verifyPr(run.prUrl, run.headSha);
408
+ } catch (err) {
409
+ log(`#${run.issue} checks not settled (${errText(err)}) — retrying next tick`);
410
+ continue;
411
+ }
412
+ if (verification === undefined) continue;
413
+ if (verification.status === "green") {
414
+ store.updateRun(run.id, { state: "pushed-green", lastError: null });
415
+ log(`#${run.issue} checks settled: ${verification.reason}`);
416
+ } else if (verification.status === "failed") {
417
+ // Equally terminal, so the release is enqueued before the row writes,
418
+ // for the same reason as the settlement branch above (see there). The
419
+ // green branch releases nothing — that row is still awaiting a merge,
420
+ // and its live PR is exactly the work the label must keep guarding.
421
+ releaseInProgress(d, run.issue, verification.reason);
422
+ store.updateRun(run.id, { state: "failed", lastError: verification.reason });
423
+ settled += 1;
424
+ log(`#${run.issue} checks failed: ${verification.reason}`);
425
+ } else {
426
+ store.updateRun(run.id, { lastError: verification.reason });
427
+ }
428
+ }
429
+ return settled;
430
+ }
431
+
432
+
433
+ // ------------------------------------------------------------------- salvaged-PR adoption
434
+
435
+ const ADOPTABLE_PR_STATES: Partial<Record<RunState, true>> = {
436
+ failed: true,
437
+ killed: true,
438
+ orphaned: true,
439
+ blocked: true,
440
+ };
441
+
442
+ /**
443
+ * Reattaches a recovered PR to the terminal run that owns it (#245).
444
+ *
445
+ * A worker can fail before its completion report records `prUrl`, then have its
446
+ * dirty tree committed and pushed by salvage. If that branch already has a PR,
447
+ * the orchestrator otherwise has no policy-compliant path to inspect or merge
448
+ * it: ownership is store-backed. Adoption is deliberately stricter than
449
+ * admission. The tracker query proves the PR closes this run's issue; exact
450
+ * branch and canonical repository matches prove it is this run's recovered
451
+ * work, not an unrelated closer. Missing identity is refusal, never a guess.
452
+ *
453
+ * The newest run per issue is inspected, at most ten per tick and only inside
454
+ * the same 30-day window as mediated PR verbs. The cursor advances through the
455
+ * full eligible set so persistent non-matches cannot starve older recovered
456
+ * work. Successful adoption is idempotent because the row gains `prUrl`;
457
+ * non-matches are logged once per daemon process.
458
+ */
459
+ const rejectedSalvagedPrRuns = new Set<string>();
460
+ const salvagedPrCursor = new Map<string, string>();
461
+
462
+ export async function adoptSalvagedPrs(
463
+ d: Pick<SettlementDeps, "project" | "tracker" | "store">,
464
+ now = Date.now(),
465
+ ): Promise<void> {
466
+ const { project, tracker, store } = d;
467
+ const eligible = store
468
+ .recentRuns(project.name, now - PR_LOOKUP_WINDOW_MS)
469
+ .filter(
470
+ (run) =>
471
+ ADOPTABLE_PR_STATES[run.state] === true &&
472
+ run.prUrl === undefined &&
473
+ run.branch.trim() !== "",
474
+ );
475
+ const previous = salvagedPrCursor.get(project.name);
476
+ const previousIndex =
477
+ previous === undefined ? -1 : eligible.findIndex((run) => run.id === previous);
478
+ const start = previousIndex === -1 ? 0 : (previousIndex + 1) % eligible.length;
479
+ const candidates = Array.from(
480
+ { length: Math.min(SALVAGED_PR_ADOPTION_BATCH, eligible.length) },
481
+ (_, offset) => eligible[(start + offset) % eligible.length]!,
482
+ );
483
+ const last = candidates.at(-1);
484
+ if (last !== undefined) salvagedPrCursor.set(project.name, last.id);
485
+
486
+ for (const run of candidates) {
487
+ const repo = project.routing.repos[run.repo];
488
+ const repoIdentity = repo === undefined ? undefined : githubRepo(repo.cloneUrl);
489
+ let closers: OpenCloser[];
490
+ try {
491
+ closers = await tracker.openClosersFor(run.issue);
492
+ } catch (err) {
493
+ log(`#${run.issue} PR adoption lookup failed (${errText(err)}) — retrying next tick`);
494
+ continue;
495
+ }
496
+
497
+ const closer = closers.find(
498
+ (candidate) =>
499
+ candidate.headRefName !== "" &&
500
+ candidate.headRefName === run.branch &&
501
+ repo !== undefined &&
502
+ candidate.repo !== "" &&
503
+ candidate.repo === repoIdentity,
504
+ );
505
+ if (closer === undefined) {
506
+ if (!rejectedSalvagedPrRuns.has(run.id)) {
507
+ const observed = closers[0];
508
+ const reason =
509
+ observed === undefined
510
+ ? "no open closing PR"
511
+ : observed.headRefName === ""
512
+ ? "closer has no head branch identity"
513
+ : observed.headRefName !== run.branch
514
+ ? `closer head ${observed.headRefName} does not match retained branch ${run.branch}`
515
+ : observed.repo === ""
516
+ ? "closer has no repository identity"
517
+ : `closer repository ${observed.repo} does not match routed repository`;
518
+ log(`#${run.issue} PR not adopted onto attempt ${run.attempt}: ${reason}`);
519
+ rejectedSalvagedPrRuns.add(run.id);
520
+ }
521
+ continue;
522
+ }
523
+
524
+ const flag: SettlementFlag = {
525
+ kind: "pr-adopted",
526
+ file: "(recovery)",
527
+ detail: `${closer.url} matched retained branch ${run.branch} in ${closer.repo}`,
528
+ };
529
+ store.updateRun(run.id, {
530
+ prUrl: closer.url,
531
+ settlementFlags: [...(run.settlementFlags ?? []), flag],
532
+ });
533
+ rejectedSalvagedPrRuns.delete(run.id);
534
+ log(
535
+ `#${run.issue} adopted PR ${closer.url} onto attempt ${run.attempt}` +
536
+ (run.salvageSha === undefined ? "" : ` (salvaged head ${run.salvageSha})`),
537
+ );
538
+ }
539
+ }
540
+
541
+ /** Canonical `owner/repo` identity from a configured network clone URL. */
542
+ function githubRepo(cloneUrl: string): string | undefined {
543
+ const normalized = cloneUrl.replace(/\/$/, "").replace(/\.git$/, "");
544
+ const match = /^(?:https?:\/\/[^/]+\/|ssh:\/\/git@[^/]+\/|git@[^:]+:)([^/\s]+\/[^/\s]+)$/.exec(
545
+ normalized,
546
+ );
547
+ return match?.[1];
548
+ }
549
+
550
+
551
+ // ------------------------------------------------------------------- worktree settlement
552
+
553
+ /**
554
+ * Persist the operator-stop transition before releasing its live controller.
555
+ * The row is terminal first, then its in-progress label is removed through the
556
+ * same durable projection outbox as every other lifecycle transition.
557
+ */
558
+ export function recordOperatorStop(
559
+ store: Pick<Store, "updateRun" | "enqueueLabelOps">,
560
+ args: {
561
+ project: string;
562
+ issue: number;
563
+ runId: string;
564
+ inProgress: string;
565
+ reason: string;
566
+ patch: Partial<RunRecord>;
567
+ },
568
+ ): void {
569
+ store.updateRun(args.runId, {
570
+ ...args.patch,
571
+ state: "stopped",
572
+ lastError: `operator stopped: ${args.reason}`,
573
+ });
574
+ store.enqueueLabelOps(args.project, [
575
+ { issue: args.issue, op: "remove", label: args.inProgress },
576
+ ]);
577
+ }
578
+
579
+ /**
580
+ * What a salvage attempt contributes to the escalation: where the work went, or
581
+ * that it went nowhere. Split from the effects below for the same reason
582
+ * `checkIntegrity` is — this wording is the whole thing a human acts on, so it
583
+ * is worth a test holding it, and the sha in it is the only pointer to work
584
+ * that no longer has any other copy.
585
+ *
586
+ * `retained` is not cosmetic. These lines used to promise a tree "kept for
587
+ * inspection" unconditionally, which was true only because salvage ran only on
588
+ * the paths that keep one. A blocked run's tree is removed the moment its work
589
+ * is safely on the branch, and sending an operator to a path this process just
590
+ * deleted is the same class of mistake as #118 itself.
591
+ */
592
+ export function salvageLines(
593
+ outcome: SalvageOutcome,
594
+ worktree: string,
595
+ retained: boolean,
596
+ ): string[] {
597
+ const fate = retained
598
+ ? `Worktree kept for inspection: ${worktree}`
599
+ : `Worktree removed: ${worktree}`;
600
+
601
+ if (outcome.kind === "nothing") return [`${fate} — nothing uncommitted to salvage`];
602
+
603
+ if (outcome.kind === "failed") {
604
+ return [
605
+ `WIP SALVAGE FAILED: ${outcome.error}`,
606
+ `Uncommitted work in ${worktree} is the only copy of it, so the tree was kept.`,
607
+ "This issue is held out of dispatch until the tree is recovered by hand and",
608
+ "`omp-conductor unblock <n> --force` records that you accepted it.",
609
+ ];
610
+ }
611
+
612
+ const where =
613
+ `WIP committed to ${outcome.branch} @ ${outcome.sha}` +
614
+ (outcome.pushed
615
+ ? " and pushed — the work outlives this worktree"
616
+ : ` but NOT pushed (${outcome.pushError ?? "no reason given"}) — it lives only in this host's mirror`);
617
+ // Manifest belongs in the escalation too: opening the commit is how the
618
+ // orchestrator talked itself into scrubbing a worker tree (#38).
619
+ const n = outcome.files.length;
620
+ const count = `${n} file${n === 1 ? "" : "s"}`;
621
+ const manifest =
622
+ outcome.newPaths.length === 0
623
+ ? `${count} (all modifications to tracked paths)`
624
+ : `${count}; new: ${outcome.newPaths.slice(0, 12).join(", ")}${
625
+ outcome.newPaths.length > 12 ? `, … +${outcome.newPaths.length - 12} more` : ""
626
+ }`;
627
+ return [where, manifest, fate];
628
+ }
629
+
630
+ /** Everything a settled run has to record and say about its worktree. */
631
+ export interface WorktreeSettlement {
632
+ outcome: SalvageOutcome;
633
+ /** Whether the tree still exists now the run is over. */
634
+ retained: boolean;
635
+ /** Escalation lines naming where the work went. */
636
+ lines: string[];
637
+ /** Row fields recording the durable ref, or the failure that blocks a re-claim. */
638
+ patch: Pick<RunRecord, "salvageSha" | "salvageError">;
639
+ }
640
+
641
+ /**
642
+ * Decides what becomes of a finished run's worktree: save the work, then keep
643
+ * or remove the tree, then say which.
644
+ *
645
+ * One function because the two halves are one decision and splitting them is
646
+ * how #118 happened — the removal at the end of dispatch had no idea whether
647
+ * anything had been saved, and the salvage at the top of the failure branch had
648
+ * no idea the blocked branch fell through to a `--force` removal.
649
+ *
650
+ * A salvage that *fails* retains the tree whatever the caller asked for. There
651
+ * was real work, git refused to commit it, and the tree is now the only copy in
652
+ * existence: deleting it on schedule would be the data loss this whole path
653
+ * exists to prevent. The issue is held out of dispatch until an operator says
654
+ * otherwise, because the next attempt's `worktree remove --force` would finish
655
+ * the job (see `admitCandidates`).
656
+ *
657
+ * Exported so a test can drive the real decision against a real git tree.
658
+ */
659
+ export async function settleWorktree(
660
+ args: {
661
+ issue: number;
662
+ attempt: number;
663
+ /** Clause for the commit subject: "killed by the turns cap", "blocked …". */
664
+ ending: string;
665
+ worktree: string;
666
+ /** The run's branch, so the pre-removal publish names the right ref. */
667
+ branch: string;
668
+ /**
669
+ * Publishes the run branch on the privileged side. Required rather than
670
+ * optional: the run's commits live in a repository of its own,
671
+ * so a removal that did not publish first would delete the only copy —
672
+ * which is #121's data loss with one extra step. `undefined` is a visible
673
+ * decision at the call site, never an omission.
674
+ */
675
+ publish: RunPublisher | undefined;
676
+ } & (
677
+ | /** Terminal-failure and orphan trees are evidence, and are kept even when clean. */
678
+ { tree: "keep" }
679
+ | { tree: "remove"; mirrorPath: string }
680
+ ),
681
+ ): Promise<WorktreeSettlement> {
682
+ const { issue, attempt, ending, worktree, branch, publish } = args;
683
+ const outcome = await salvageWip(worktree, issue, attempt, ending, publish);
684
+ const retained = args.tree === "keep" || outcome.kind === "failed";
685
+ if (!retained && args.tree === "remove") {
686
+ // Before the removal, always — not only when salvage found something. A run
687
+ // that *committed* and could not publish has its work in its own repository
688
+ // and nowhere else, and salvage never sees a committed tree because it is
689
+ // clean. The mirror fetch inside `publish` is what preserves it; the push
690
+ // to GitHub can fail (no network, protected ref) and the work still lives.
691
+ const published = await publish?.(branch);
692
+ if (published !== undefined && !published.ok) {
693
+ log(`#${issue} publish before removal failed, work is preserved in the mirror: ${published.stderr}`);
694
+ }
695
+ await removeWorktree(args.mirrorPath, worktree);
696
+ }
697
+
698
+ const lines = salvageLines(outcome, worktree, retained);
699
+ log(`#${issue} salvage: ${lines.join(" ")}`);
700
+ return {
701
+ outcome,
702
+ retained,
703
+ lines,
704
+ patch:
705
+ outcome.kind === "salvaged"
706
+ ? { salvageSha: outcome.sha }
707
+ : outcome.kind === "failed"
708
+ ? { salvageError: outcome.error }
709
+ : {},
710
+ };
711
+ }
712
+
713
+
714
+ // ------------------------------------------------------------------- orphan & stale-label reconciliation
715
+
716
+ /** Bounded listing per state label, so one reconcile cannot walk a whole repo. */
717
+ const RECONCILE_LIMIT = 50;
718
+
719
+ /**
720
+ * Clear labels from issues that no longer need them (#132's `superseded`).
721
+ *
722
+ * Three structural signals, all cheap and all observed on this fleet: an issue
723
+ * that is closed but still carries an `agent:*` state label, a closed issue
724
+ * still carrying the queue label — the claim gate on work that can never be
725
+ * claimed again, which the merge path only recently learned to remove itself
726
+ * (#607), leaving a 50+-issue backlog — and an open issue carrying `failed`
727
+ * whose sub-issues have all closed. On 2026-08-09 four issues (#307,
728
+ * #297, #140, #82) carried `agent:failed` while every one of them was already
729
+ * complete — the label was residue of a turns-cap kill from two days earlier,
730
+ * and nothing in the loop ever revisited it. The board counted four phantom
731
+ * failures while the genuinely stuck issues were invisible.
732
+ *
733
+ * The queue label is swept off closed issues only: an open issue carrying it
734
+ * is claimable work by definition, and a reconcile that guessed would strip
735
+ * the interlock that keeps two workers off one issue.
736
+ *
737
+ * Positive evidence only. A tracker that cannot list answers empty, and an empty
738
+ * answer removes nothing: a reconcile that guessed would strip the interlock
739
+ * that keeps two workers off one issue.
740
+ */
741
+ export async function reconcileStaleLabels(d: Pick<SettlementDeps, "project" | "tracker" | "store">): Promise<void> {
742
+ const { project, tracker, store } = d;
743
+ const labels = [
744
+ project.stateLabels.failed,
745
+ project.stateLabels.blocked,
746
+ project.stateLabels.inProgress,
747
+ project.queueLabel,
748
+ ];
749
+
750
+ for (const label of labels) {
751
+ const carrying = await tracker.listLabeled(label, RECONCILE_LIMIT).catch(() => []);
752
+ for (const issue of carrying) {
753
+ if (issue.state === "closed") {
754
+ // Never retain an `agent:*` label on a closed issue: the work is done by
755
+ // some route, and the label only makes the board lie about it. Enqueue
756
+ // rather than call — a refused write must not lose the decision; the
757
+ // projector retries the removal until the tracker takes it (#201).
758
+ store.enqueueLabelOps(project.name, [{ issue: issue.number, op: "remove", label }]);
759
+ log(`#${issue.number} reconciled: closed issue no longer carries ${label} (queued)`);
760
+ continue;
761
+ }
762
+
763
+ if (label !== project.stateLabels.failed) continue;
764
+ const children = await tracker.childrenOf(issue.number).catch(() => []);
765
+ if (children.length === 0 || children.some((c) => c.state !== "closed")) continue;
766
+
767
+ const key = `${project.name}:superseded:${issue.number}`;
768
+ if (store.wasNotified(key)) continue;
769
+ const list = children.map((c) => `#${c.number}`).join(", ");
770
+ store.enqueueLabelOps(project.name, [{ issue: issue.number, op: "remove", label }]);
771
+ try {
772
+ await tracker.comment(
773
+ issue.number,
774
+ `superseded: all sub-issues closed (${list}) — this label was stale; propose closing if the ` +
775
+ `acceptance criteria are met on the default branch.`,
776
+ );
777
+ store.markNotified(key);
778
+ log(`#${issue.number} reconciled: superseded by ${list}`);
779
+ } catch (err) {
780
+ // The label removal is already queued and will land regardless; the
781
+ // comment is the only half that can fail here (#201).
782
+ log(`#${issue.number} could not comment the superseded note (${errText(err)}) — retrying next tick`);
783
+ }
784
+ }
785
+ }
786
+ }
787
+
788
+ /**
789
+ * Settles `claimed`/`running` rows left by a dead daemon process and, before
790
+ * marking each one `orphaned`, salvages any dirty worktree.
791
+ *
792
+ * Found live after a host restart killed two workers mid-run, and again on
793
+ * every package deploy that restarted while workers were live (#35): without
794
+ * the salvage call the next attempt's `worktree remove --force` destroyed
795
+ * uncommitted edits that had no other copy. Cap-kills already salvaged (#27);
796
+ * this is the same call site for the restart path.
797
+ *
798
+ * Only the rows change. The issue keeps its in-progress label — that label is
799
+ * the crash guard against double-dispatch, and deciding what a dead worker's
800
+ * remains are worth (an open PR? a salvaged sha? a clean tree?) is the
801
+ * orchestrator's drain-duty judgement, not something to automate here. The
802
+ * rows also keep counting toward `maxAttemptsPerIssue`, so a loop of deaths
803
+ * still escalates instead of retrying forever.
804
+ *
805
+ * `pushed-green` rows are deliberately left alone: they hold no process — they
806
+ * are finished work waiting on a human merge, and they must keep occupying the
807
+ * issue so a second attempt cannot land on a live PR. What eventually settles
808
+ * them is {@link settlePushedGreen}, on the tick, by asking the tracker what
809
+ * became of the PR — the one question a restart cannot answer by inference.
810
+ */
811
+ export async function reconcileOrphanedRuns(
812
+ store: Store,
813
+ project: string,
814
+ /**
815
+ * Resolves the privileged publisher for one orphaned run. Optional because a
816
+ * test driving the row transitions has no repo to publish to; production
817
+ * always passes it, and without it a salvaged WIP commit stays local — which
818
+ * is the half of #121 that reaches a human.
819
+ */
820
+ publish?: (run: RunRecord) => RunPublisher,
821
+ ): Promise<RunRecord[]> {
822
+ // Live runs only: `pushed-green` holds no process, so it cannot be orphaned by
823
+ // a process dying — it is finished work waiting on a human merge.
824
+ const stale = store.liveRuns(project);
825
+ const endedAt = Date.now();
826
+ for (const r of stale) {
827
+ // Salvage before the row flips: the worktree path is on the record, and
828
+ // salvageWip is a no-op for a missing/clean tree. The clause matches the
829
+ // cap-kill wording so triage reads the same either way, and the tree is
830
+ // kept because an orphan's remains are the orchestrator's drain-duty call.
831
+ const settlement =
832
+ r.worktree === ""
833
+ ? undefined
834
+ : await settleWorktree({
835
+ issue: r.issue,
836
+ attempt: r.attempt,
837
+ ending: "killed by a daemon restart",
838
+ worktree: r.worktree,
839
+ branch: r.branch,
840
+ // An orphan's tree is kept, so its commits are not about to be
841
+ // deleted — but a WIP salvage still has to reach GitHub, which is
842
+ // #121's whole point and is now the daemon's hop to make.
843
+ publish: publish?.(r),
844
+ tree: "keep",
845
+ });
846
+ store.updateRun(r.id, { state: "orphaned", endedAt, ...settlement?.patch });
847
+ }
848
+ return stale;
849
+ }
850
+
851
+
852
+
853
+
854
+ // ------------------------------------------------------------------- classification & recovery
855
+
856
+ /** A dispatch-infra run (turn-0 git failure) is requeued so the next tick
857
+ * retries — but only a bounded number of times. Three strikes for one issue
858
+ * means the mirror itself is broken, not unlucky, and the sweep escalates
859
+ * instead of burning a turn-0 run per tick forever (#168, #177). */
860
+ const DISPATCH_INFRA_MAX_STRIKES = 3;
861
+ /** A provider-transient requeue (stream stalled mid-run) is retried, but only a
862
+ * bounded number of times: three aborted streams for one issue means the
863
+ * provider itself is degraded, not unlucky, and the sweep escalates to a
864
+ * human instead of requeueing into a down provider forever (#220). */
865
+ const PROVIDER_TRANSIENT_MAX_STRIKES = 3;
866
+ /** A provider-capacity requeue (sustained in-session rate limiting) is retried,
867
+ * but only a bounded number of times: three throttled runs for one issue mean
868
+ * the provider is at capacity, not unlucky, and the sweep escalates to a human
869
+ * instead of requeueing into a throttled provider forever (#573). The issue's
870
+ * own chain moves onto its next model per strike (via {@link FAILOVER_CLASSES}),
871
+ * so a bounded chain is exhaustible; this caps the unbounded no-chain case. */
872
+ const PROVIDER_CAPACITY_MAX_STRIKES = 3;
873
+ /** Terminal rows inspected for a salvaged PR per tick. GitHub provenance reads
874
+ * are maintenance, but a backlog must not turn one tick into an API burst. */
875
+ const SALVAGED_PR_ADOPTION_BATCH = 10;
876
+
877
+ /** The failure classes `countContinuations` deliberately does not charge — the
878
+ * inverted copy of its exclusions, kept beside the breakdown that consumes it
879
+ * so the two can only drift together (#439). `orphan-clean` is absent on
880
+ * purpose: daemon orphans consume the continuation budget, which is exactly
881
+ * why the requeue side has to respect the ceiling instead of racing it. */
882
+ const NON_CONTINUATION_CLASSES: Partial<Record<FailureClass, true>> = {
883
+ "admin-kill": true,
884
+ "settlement-stuck": true,
885
+ "env-start-failure": true,
886
+ "dispatch-infra": true,
887
+ "provider-credit": true,
888
+ "provider-transient": true,
889
+ "provider-capacity": true,
890
+ };
891
+
892
+ /** How one issue spent its continuation budget, grouped by failure class —
893
+ * the exact rows `continuationsFor` charges, so an exhaustion escalation
894
+ * reports the same budget it says is spent. `unclassified` groups rows that
895
+ * charged before the class was written (a pre-upgrade NULL). */
896
+ function continuationBreakdown(runs: readonly RunRecord[]): Map<string, number> {
897
+ const perClass = new Map<string, number>();
898
+ for (const r of runs) {
899
+ const chargedAsKilledOrOrphaned =
900
+ (r.state === "killed" || r.state === "orphaned" || r.state === "blocked") &&
901
+ (r.failureClass === undefined || NON_CONTINUATION_CLASSES[r.failureClass] === undefined);
902
+ const chargedAsReturned = r.state === "failed" && r.failureClass === "returned-for-revision";
903
+ if (!chargedAsKilledOrOrphaned && !chargedAsReturned) continue;
904
+ const cls = r.failureClass ?? "unclassified";
905
+ perClass.set(cls, (perClass.get(cls) ?? 0) + 1);
906
+ }
907
+ return perClass;
908
+ }
909
+
910
+ /** The newest attempt's preserved work, if any, so an exhaustion escalation can
911
+ * say whether continuing is worthwhile: `salvageSha`/`headSha`/`prUrl` are the
912
+ * three artifacts a run can leave, and all null on a branch nothing reached. */
913
+ function newestContinuableRun(runs: readonly RunRecord[]): RunRecord | undefined {
914
+ const newestFirst = [...runs].reverse();
915
+ return newestFirst.find(
916
+ (r) => r.salvageSha !== undefined || r.headSha !== undefined || r.prUrl !== undefined,
917
+ );
918
+ }
919
+
920
+ /** The fenced-block info string that marks an exhaustion postmortem comment, so
921
+ * a grooming scout re-slicing the issue can find and parse the whole block by
922
+ * grepping for it. */
923
+ export const POSTMORTEM_MARKER = "conductor-postmortem";
924
+
925
+ /** How one issue's attempt chain failed, as "3× ci-deterministic, 1× …" — the
926
+ * digest shape for naming what the exhaustion was. Groups every row by its
927
+ * failure class, whether or not it charged the continuation budget, because
928
+ * the postmortem tells the whole story and not just the budget half (#290). */
929
+ export function attemptClassBreakdown(runs: readonly RunRecord[]): string {
930
+ const perClass = new Map<string, number>();
931
+ for (const r of runs) {
932
+ const cls = r.failureClass ?? "unclassified";
933
+ perClass.set(cls, (perClass.get(cls) ?? 0) + 1);
934
+ }
935
+ if (perClass.size === 0) return "unclassified";
936
+ return Array.from(perClass, ([cls, n]) => `${n}× ${cls}`).join(", ");
937
+ }
938
+
939
+ /** Wall-clock duration of one run as a compact human string ("45m", "1h30m"). */
940
+ export function humanDuration(ms: number): string {
941
+ const seconds = Math.max(0, Math.round(ms / 1_000));
942
+ if (seconds < 60) return `${seconds}s`;
943
+ const minutes = Math.round(seconds / 60);
944
+ if (minutes < 60) return `${minutes}m`;
945
+ const hours = Math.floor(minutes / 60);
946
+ const rest = minutes % 60;
947
+ return rest === 0 ? `${hours}h` : `${hours}h${rest}m`;
948
+ }
949
+
950
+ /** Flatten and bound a run's last error to one greppable table line. */
951
+ export function oneLineBrief(text: string | undefined): string | undefined {
952
+ if (text === undefined || text.trim() === "") return undefined;
953
+ const flat = text.replace(/\s+/g, " ").trim();
954
+ return flat.length > 90 ? `${flat.slice(0, 89)}…` : flat;
955
+ }
956
+
957
+ /**
958
+ * The exhaustion postmortem block: one greppable fenced block covering every
959
+ * attempt in the chain — continuation rows included — with per-attempt turns,
960
+ * wall clock, failure class and a one-line last error, the explicit salvage
961
+ * state, the spend total and the transcript paths for local inspection.
962
+ *
963
+ * Pure so the tests hold the shape, not the transport: the writer below owns
964
+ * the once-only guarantee, this owns what "once" looks like.
965
+ */
966
+ export function formatExhaustionPostmortem(args: {
967
+ issue: number;
968
+ runs: readonly RunRecord[];
969
+ reason: string;
970
+ }): string {
971
+ const { issue, runs, reason } = args;
972
+ const artifact = newestContinuableRun(runs);
973
+ const totalSpend = runs.reduce((sum, r) => sum + r.spendUsd, 0);
974
+ const spend = `$${totalSpend.toFixed(2)}`;
975
+ const attemptLines = runs.map((r) => {
976
+ const wall = r.endedAt === undefined ? "—" : humanDuration(r.endedAt - r.startedAt);
977
+ const cls = r.failureClass ?? "unclassified";
978
+ const error = oneLineBrief(r.lastError) ?? "—";
979
+ return (
980
+ ` attempt ${r.attempt} ${r.state.padEnd(12)} turns ${r.turns}/${r.maxTurns} ` +
981
+ `${cls.padEnd(24)} ${wall.padStart(4)} last error: ${error}`
982
+ );
983
+ });
984
+ const salvage =
985
+ artifact === undefined
986
+ ? "Salvaged WIP: absent — no attempt preserved a branch, head SHA or pull request."
987
+ : `Salvaged WIP: present — branch ${artifact.branch} at ${artifact.headSha ?? artifact.salvageSha}` +
988
+ `${artifact.prUrl === undefined ? "" : ` (PR ${artifact.prUrl})`}.`;
989
+ return [
990
+ `\`\`\`${POSTMORTEM_MARKER}`,
991
+ `#${issue} exhausted: ${attemptClassBreakdown(runs)}`,
992
+ reason,
993
+ "",
994
+ `Attempts (${runs.length} total, ${spend} spend):`,
995
+ ...attemptLines,
996
+ salvage,
997
+ `Spend total: ${spend} across ${runs.length} attempts.`,
998
+ "Transcripts:",
999
+ ...runs.map((r) => (r.sessionFile === undefined ? " (none)" : ` ${r.sessionFile}`)),
1000
+ "```",
1001
+ ].join("\n");
1002
+ }
1003
+
1004
+ /** Dedupe key prefix for the exhaustion postmortem comment, per issue. */
1005
+ function postmortemDedupeKey(project: string, issue: number): string {
1006
+ return `${project}:postmortem:${issue}`;
1007
+ }
1008
+
1009
+ /**
1010
+ * The exhaustion postmortem: written exactly once per issue, at the point the
1011
+ * continuation budget is spent and the issue is settled toward a human.
1012
+ *
1013
+ * The comment and the material event are both gated by the store's notification
1014
+ * ledger — the same idempotence guard the escalator uses — so re-settling an
1015
+ * already-postmortemed issue posts nothing and records nothing. A body-string
1016
+ * match on the issue would be the wrong guard: an issue re-scoped and re-run
1017
+ * would still carry the old block, and the guarantee asked of this is "decided
1018
+ * once", not "deduped against what is already written".
1019
+ *
1020
+ * The digest must name the exhaustion even if the comment write fails, so the
1021
+ * material event is recorded before the write and unconditionally (the ledger
1022
+ * is append-only, and the gate above already ran once). The comment failure is
1023
+ * logged rather than taking the sweep down with it.
1024
+ */
1025
+ async function postExhaustionPostmortem(d: Pick<SettlementDeps, "project" | "tracker" | "store">, run: RunRecord, reason: string): Promise<void> {
1026
+ const { project, tracker, store } = d;
1027
+ const key = postmortemDedupeKey(project.name, run.issue);
1028
+ if (store.wasNotified(key)) return;
1029
+ const runs = store.runsForIssue(project.name, run.issue);
1030
+ const body = formatExhaustionPostmortem({ issue: run.issue, runs, reason });
1031
+ const occurredAt = Date.now();
1032
+ store.recordMaterialEvent({
1033
+ project: project.name,
1034
+ category: "exhaustion",
1035
+ summary: `#${run.issue} exhausted: ${attemptClassBreakdown(runs)}`,
1036
+ evidence: body,
1037
+ occurredAt,
1038
+ recordedAt: occurredAt,
1039
+ });
1040
+ try {
1041
+ await tracker.comment(run.issue, body);
1042
+ store.markNotified(key);
1043
+ log(`#${run.issue} posted exhaustion postmortem (${runs.length} attempts)`);
1044
+ } catch (err) {
1045
+ log(`#${run.issue} postmortem comment could not be posted (${errText(err)})`);
1046
+ }
1047
+ }
1048
+
1049
+ /**
1050
+ * The escalator throws when no transport is configured or Telegram rejects, and
1051
+ * only records the dedup marker on success. A page that cannot be delivered
1052
+ * must not take the tick down with it — log it and let the next tick retry.
1053
+ *
1054
+ * Returns whether it actually went out, because "page once" and "page once
1055
+ * *successfully*" are different promises: a caller that latches a once-only
1056
+ * gate on the attempt turns one failed delivery into permanent silence about a
1057
+ * condition that is still true.
1058
+ */
1059
+
1060
+ export async function reactToProviderCredit(
1061
+ d: Pick<SettlementDeps, "project" | "escalate" | "isPaused" | "setPaused">,
1062
+ issue: number,
1063
+ message: string,
1064
+ sessionFile: string | undefined,
1065
+ ): Promise<void> {
1066
+ const { project } = d;
1067
+ const alreadyPaused = d.isPaused(project.name);
1068
+ if (!alreadyPaused) d.setPaused(true, { source: "provider-credit", reason: message }, project.name);
1069
+ log(
1070
+ `#${issue} provider refused for credit — dispatch ${alreadyPaused ? "remains paused" : "paused"}: ${message}`,
1071
+ );
1072
+ // Fleet-scoped and run-independent on purpose. The notification ledger
1073
+ // dedupes on `project:issue:tier:summary`, so `NO_ISSUE` plus a summary
1074
+ // carrying no run or attempt pages once for the fleet, not once per run.
1075
+ await safeEscalate(d, {
1076
+ tier: 2,
1077
+ category: "fleet-stopped",
1078
+ project: project.name,
1079
+ issue: NO_ISSUE,
1080
+ summary: `Model provider refused for credit — ${project.name} is paused`,
1081
+ detail: [
1082
+ message,
1083
+ "",
1084
+ "No implementation attempt was charged: this is a billing state, not a",
1085
+ "failed implementation. Each affected issue keeps its queue label and",
1086
+ "re-dispatches on `omp-conductor resume` once the provider has credit.",
1087
+ `Session: ${sessionFile ?? "(no transcript)"}`,
1088
+ ].join("\n"),
1089
+ });
1090
+ }
1091
+
1092
+ /** Bounded per tick: each row costs tracker calls to gather facts for. */
1093
+ const CLASSIFY_BATCH = 20;
1094
+
1095
+ /** Tool calls quoted as evidence for a run that spun to its turn cap. */
1096
+ const SPIN_EVIDENCE_CALLS = 10;
1097
+
1098
+ /**
1099
+ * The last few tool names a transcript recorded, newest last.
1100
+ *
1101
+ * `turn-cap-spinning` escalates rather than requeueing, and the acceptance
1102
+ * criterion is that the escalation carries evidence of what the worker was doing
1103
+ * when it hit the cap — otherwise the orchestrator opens the transcript and
1104
+ * re-derives it, which is the manual triage this whole sweep removes.
1105
+ */
1106
+ export function lastToolCalls(sessionFile: string | undefined, limit = SPIN_EVIDENCE_CALLS): string[] {
1107
+ if (sessionFile === undefined) return [];
1108
+ let text: string;
1109
+ try {
1110
+ text = readFileSync(sessionFile, "utf8");
1111
+ } catch {
1112
+ return [];
1113
+ }
1114
+ const names: string[] = [];
1115
+ for (const line of text.split("\n")) {
1116
+ if (line.length === 0) continue;
1117
+ let row: unknown;
1118
+ try {
1119
+ row = JSON.parse(line) as unknown;
1120
+ } catch {
1121
+ continue;
1122
+ }
1123
+ if (row === null || typeof row !== "object") continue;
1124
+ const rec = row as { readonly [key: string]: unknown };
1125
+ // Both shapes the harness has written: a top-level tool event, and a tool
1126
+ // block inside an assistant message.
1127
+ const direct = rec["toolName"];
1128
+ if (typeof direct === "string") {
1129
+ names.push(direct);
1130
+ continue;
1131
+ }
1132
+ const message = rec["message"];
1133
+ if (message === null || typeof message !== "object") continue;
1134
+ const content = (message as { readonly [key: string]: unknown })["content"];
1135
+ if (!Array.isArray(content)) continue;
1136
+ for (const part of content) {
1137
+ if (part === null || typeof part !== "object") continue;
1138
+ const p = part as { readonly [key: string]: unknown };
1139
+ if (p["type"] !== "tool_use") continue;
1140
+ const name = p["name"];
1141
+ if (typeof name === "string") names.push(name);
1142
+ }
1143
+ }
1144
+ return names.slice(-limit);
1145
+ }
1146
+
1147
+ /**
1148
+ * The last error a transcript recorded, or undefined when it recorded none.
1149
+ *
1150
+ * The harness writes `{"stopReason":"error","errorStatus":402,"errorId":402,
1151
+ * "errorMessage":"402 This request requires more credits, ..."}`. The daemon
1152
+ * read none of it, so three runs died `unknown` with an empty `lastError` and
1153
+ * charged an attempt each for a billing state (#220).
1154
+ *
1155
+ * Scanned newest-first: a session that recovered from an early error and then
1156
+ * died of something else must report the something else, and a session that
1157
+ * recovered from its only error and finished cleanly reports the error anyway
1158
+ * because there is no terminal verdict to outrank it (#220).
1159
+ */
1160
+ /** Transcript error shape — the daemon owns the same interface for
1161
+ * `completionLastError`; declared inline here so this leaf never imports it.
1162
+ *
1163
+ * `kind: "provider-stream"` marks a record the harness itself attributed to a
1164
+ * provider abort (see {@link assistantStopError}), so the classifier can trust
1165
+ * the attribution without matching any vendor's wording (#743). */
1166
+ export type TranscriptError = {
1167
+ status?: number;
1168
+ message: string;
1169
+ kind?: "provider-stream";
1170
+ };
1171
+
1172
+ /**
1173
+ * The provider's own message in a synthetic tool-result record, or undefined
1174
+ * when the record is not the harness attributing a mid-stream provider abort
1175
+ * (#743).
1176
+ *
1177
+ * The harness writes this when the provider dies while the assistant is still
1178
+ * producing and a pending tool call never runs:
1179
+ *
1180
+ * {"type":"message","message":{"role":"toolResult","isError":true,
1181
+ * "toolName":"edit","content":[{"type":"text","text":"Tool call was not
1182
+ * executed because the provider stream ended with an error before the tool
1183
+ * could run: …"}],"details":{"__synthetic":true,
1184
+ * "source":"assistant_stop_error","executed":false,
1185
+ * "upstreamError":"server_error: Upstream error from DeepInfra:
1186
+ * Exception: Response payload is not completed"}}}
1187
+ *
1188
+ * The `source` field is the harness's own marker, so recognition survives any
1189
+ * provider's wording; `upstreamError` (falling back to the record's text) is
1190
+ * the provider's own prose, carried as evidence.
1191
+ *
1192
+ * Deliberately narrower than "any isError toolResult": the marker is what makes
1193
+ * the attribution structural. An `isError` tool result without it is a tool
1194
+ * call that failed on its own — the session's work, not a provider fault — and
1195
+ * must keep falling through.
1196
+ */
1197
+ function assistantStopError(rec: { readonly [key: string]: unknown }): string | undefined {
1198
+ if (rec["type"] !== "message") return undefined;
1199
+ const message = rec["message"];
1200
+ if (message === null || typeof message !== "object") return undefined;
1201
+ const msg = message as { readonly [key: string]: unknown };
1202
+ if (msg["role"] !== "toolResult" || msg["isError"] !== true) return undefined;
1203
+ const details = msg["details"];
1204
+ if (details === null || typeof details !== "object") return undefined;
1205
+ const detail = details as { readonly [key: string]: unknown };
1206
+ if (detail["source"] !== "assistant_stop_error") return undefined;
1207
+ const upstream = detail["upstreamError"];
1208
+ if (typeof upstream === "string" && upstream.trim() !== "") return upstream.trim();
1209
+ const content = msg["content"];
1210
+ if (!Array.isArray(content)) return undefined;
1211
+ for (const part of content) {
1212
+ if (part === null || typeof part !== "object") continue;
1213
+ const p = part as { readonly [key: string]: unknown };
1214
+ if (p["type"] !== "text" || typeof p["text"] !== "string") continue;
1215
+ if (p["text"].trim() !== "") return p["text"].trim();
1216
+ }
1217
+ return undefined;
1218
+ }
1219
+
1220
+ export function readSessionError(sessionFile: string | undefined): TranscriptError | undefined {
1221
+ if (sessionFile === undefined) return undefined;
1222
+ let text: string;
1223
+ try {
1224
+ text = readFileSync(sessionFile, "utf8");
1225
+ } catch {
1226
+ return undefined;
1227
+ }
1228
+ const lines = text.split("\n");
1229
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
1230
+ const line = lines[i];
1231
+ if (line === undefined || line.length === 0) continue;
1232
+ let row: unknown;
1233
+ try {
1234
+ row = JSON.parse(line) as unknown;
1235
+ } catch {
1236
+ continue;
1237
+ }
1238
+ if (row === null || typeof row !== "object") continue;
1239
+ const rec = row as { readonly [key: string]: unknown };
1240
+ // A provider abort mid-stream lands as a synthetic tool-result record, not
1241
+ // a `stopReason:error` row: the pending tool call "was not executed because
1242
+ // the provider stream ended with an error". The harness's own `source`
1243
+ // marker is the attribution — no vendor prose to match — and the provider's
1244
+ // own text rides along as evidence (#743).
1245
+ if (rec["type"] === "message") {
1246
+ const providerText = assistantStopError(rec);
1247
+ if (providerText !== undefined) {
1248
+ return { message: providerText, kind: "provider-stream" };
1249
+ }
1250
+ }
1251
+ if (rec["stopReason"] !== "error") continue;
1252
+ const message = rec["errorMessage"];
1253
+ if (typeof message !== "string" || message.trim() === "") continue;
1254
+ const status = rec["errorStatus"];
1255
+ return {
1256
+ ...(typeof status === "number" && Number.isFinite(status) ? { status } : {}),
1257
+ message: message.trim(),
1258
+ };
1259
+ }
1260
+ return undefined;
1261
+ }
1262
+
1263
+ /**
1264
+ * Classify every unclassified terminal run, persist the verdict, and perform the
1265
+ * one recovery its class names (#132).
1266
+ *
1267
+ * Half this fleet's spend produced no merged PR, and every one of those runs
1268
+ * ended at a human who re-derived the same triage by hand and then threw the
1269
+ * conclusion away. The mechanical classes — a cancelled runner, a kill from a
1270
+ * daemon restart, a green PR whose base moved, a row whose PR had already merged
1271
+ * — need no judgement at all; the genuinely human ones are worth a person's
1272
+ * attention only if they arrive with their evidence already gathered.
1273
+ *
1274
+ * Facts are fetched per row and only the ones that row needs: a `killed` row
1275
+ * costs nothing, a `failed` row with a PR costs a state read and a check read.
1276
+ * A `pushed-green` row that classifies to nothing is left completely untouched —
1277
+ * it is healthy, and writing a class onto it would take it out of this sweep for
1278
+ * good.
1279
+ */
1280
+ export async function classifyAndRecover(d: SettlementDeps): Promise<number> {
1281
+ const { project, caps, tracker, store } = d;
1282
+ // Settle recoveries, counted for the pass's dispatch record — a row whose PR
1283
+ // merged is settled here when the settle sweep could not establish identity
1284
+ // (#497). Every other exit returns 0.
1285
+ let settled = 0;
1286
+ for (const run of store.runsNeedingClassification(project.name, CLASSIFY_BATCH)) {
1287
+ const facts: ClassifyFacts = {};
1288
+ let classifiedRun = run;
1289
+ if (run.state === "failed" || run.state === "killed") {
1290
+ const sessionError = readSessionError(run.sessionFile);
1291
+ if (sessionError !== undefined) {
1292
+ if (run.lastError === undefined || run.lastError === sessionError.message) {
1293
+ facts.sessionError = sessionError;
1294
+ }
1295
+ if (run.lastError === undefined) {
1296
+ store.updateRun(run.id, { lastError: sessionError.message });
1297
+ classifiedRun = { ...run, lastError: sessionError.message };
1298
+ }
1299
+ }
1300
+ }
1301
+ try {
1302
+ if (run.prUrl !== undefined) {
1303
+ const pr = await tracker.prState(run.prUrl);
1304
+ if (pr !== undefined) facts.pr = pr;
1305
+ if (run.state === "pushed-green" && facts.pr === "open") {
1306
+ facts.mergeable = await tracker.mergeable(run.prUrl);
1307
+ }
1308
+ if (run.state === "failed" && facts.pr === "open") {
1309
+ facts.checks = await tracker.checkConclusions(run.prUrl);
1310
+ // When a check failed with a reachable log, pull its tail so the
1311
+ // table can tell an infra outage (#177) from a real test failure by
1312
+ // the log's own words. First failure wins; a log that cannot be
1313
+ // fetched is left undefined and classification stays conservative.
1314
+ // GitHub reports check states as `FAILURE` while the classifier reads
1315
+ // them lowercased — normalise so the live seam and the table agree on
1316
+ // which check is the failure whose log we pull (#177).
1317
+ const firstFailure = facts.checks.find((c) => normalise(c.state) === "failure" && c.link !== undefined);
1318
+ if (firstFailure?.link !== undefined) {
1319
+ facts.failingLog = await tracker.checkLog(firstFailure.link);
1320
+ }
1321
+ }
1322
+ }
1323
+ } catch (err) {
1324
+ // The tracker throws exactly one classified error: `GhPrMissingError`,
1325
+ // an individual REST 404 the adapter corroborated with a
1326
+ // same-repository pulls-list read, so the claimed PR definitively does
1327
+ // not exist (#779). That is a fact, not "could not tell" — retrying can
1328
+ // never conjure the PR — so it is recorded as the absent-PR fact and
1329
+ // classification proceeds instead of leaving the row in
1330
+ // `selectUnclassified` to be offered forever. Everything else (a 5xx, a
1331
+ // revoked token, an opaque 404) is genuinely unreadable and the next
1332
+ // tick asks again for free.
1333
+ if (err instanceof GhPrMissingError) {
1334
+ facts.pr = "missing";
1335
+ } else {
1336
+ // Per row, like every other sweep here: one unreachable PR must not stop
1337
+ // the rest from being classified. The next tick asks again for free.
1338
+ log(`#${run.issue} not classified: fact gathering failed (${errText(err)}) — retrying next tick`);
1339
+ continue;
1340
+ }
1341
+ }
1342
+
1343
+ const { cls, recovery, evidence } = classifyRun(classifiedRun, facts, caps);
1344
+
1345
+ // A healthy green PR is not a failure of any class. Leaving the row
1346
+ // unclassified is what keeps it eligible for the sweep on the tick where its
1347
+ // base does move under it.
1348
+ if (run.state === "pushed-green" && cls === "unknown") continue;
1349
+
1350
+ // A recovery of `none` is the classifier naming no failure class for the
1351
+ // row at all: a terminal `failed` row whose PR is open and every check is
1352
+ // green is the strongest mechanical success evidence there is short of
1353
+ // merge, so it is not a failed attempt. Restore it to `pushed-green` — the
1354
+ // settle sweep owns the merge decision from there, `failuresFor` stops
1355
+ // counting it, and no `[unknown]` escalation is persisted. Nothing else is
1356
+ // written, so the row stays in the normal `pushed-green` lifecycle
1357
+ // (merge-conflict on a moved base, settle on a merged or closed PR) rather
1358
+ // than being pinned by a class it never had (#766).
1359
+ if (recovery === "none") {
1360
+ store.updateRun(run.id, { state: "pushed-green" });
1361
+ log(`#${run.issue} restored to pushed-green: ${evidence}`);
1362
+ continue;
1363
+ }
1364
+
1365
+ const retry = run.failureClass !== undefined;
1366
+ store.updateRun(run.id, { failureClass: cls, recoveryAction: recovery });
1367
+ log(
1368
+ retry
1369
+ ? `#${run.issue} retrying ${recovery} for ${cls}: ${evidence}`
1370
+ : `#${run.issue} classified ${cls} → ${recovery}: ${evidence}`,
1371
+ );
1372
+ if (recovery === "settle") settled += 1;
1373
+ await recoverRun(d, classifiedRun, cls, recovery, evidence);
1374
+ }
1375
+ return settled;
1376
+ }
1377
+
1378
+ /** Performs the one action a class names. Never chooses one of its own. */
1379
+ async function recoverRun(
1380
+ d: SettlementDeps,
1381
+ run: RunRecord,
1382
+ cls: FailureClass,
1383
+ recovery: RecoveryAction,
1384
+ evidence: string,
1385
+ ): Promise<void> {
1386
+ const { project, caps, tracker, store } = d;
1387
+ const inProgress = project.stateLabels.inProgress;
1388
+
1389
+ if (recovery === "settle") {
1390
+ // Enqueue the release with the terminal write (see `settlePushedGreen`):
1391
+ // the outbox keeps the label and the row one fact, so a tracker refusal
1392
+ // can no longer strand `agent:in-progress` with nothing left to retry it
1393
+ // (#18, #201).
1394
+ releaseInProgress(d, run.issue, `PR merged: ${evidence}`);
1395
+ // #607: a recovered row whose PR is observed merged is settled work, so
1396
+ // the claim gate comes off with the same projection as the sweep does.
1397
+ releaseQueueLabel(d, run.issue, `PR merged: ${evidence}`);
1398
+ store.updateRun(run.id, { state: "merged", endedAt: Date.now(), recoveredAt: Date.now() });
1399
+ log(`#${run.issue} settled from ${cls}: ${evidence}`);
1400
+ return;
1401
+ }
1402
+
1403
+ if (recovery === "continue") {
1404
+ // Two classes recover by continuing, and only one of them has anything left
1405
+ // to do here.
1406
+ //
1407
+ // `turn-cap-progress` was already handed back by the completion path, which
1408
+ // swapped its labels and left the branch retained. There is nothing to
1409
+ // perform, and writing anything would be actively wrong: overwriting
1410
+ // `lastError` with a rebase brief tells the continuation worker to rebase a
1411
+ // run that simply ran out of turns, and re-swapping labels the completion
1412
+ // path already swapped is a pair of no-op `gh` calls. Record-only, so the
1413
+ // sweep stops re-offering it.
1414
+ if (cls === "turn-cap-progress") {
1415
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1416
+ log(`#${run.issue} already continuing from ${cls}: ${evidence}`);
1417
+ return;
1418
+ }
1419
+
1420
+ // `wall-clock-cap-progress`: the completion path only auto-continues
1421
+ // turn-cap kills, so a wall-clock kill with work to show reaches this
1422
+ // sweep still holding the failed label. Swap it for the queue — the branch
1423
+ // is retained, so the next dispatch reattaches it and briefs a resume from
1424
+ // the recorded work. Killed rows gathered no tracker facts, so the
1425
+ // issue-open guard mirrors the requeue path's. The continuation gate is
1426
+ // the same one the turns path applies at kill time
1427
+ // (`shouldContinueAfterTurnsCap`): the row is already charged, and once
1428
+ // the ceiling is spent, handing back the queue label would offer a
1429
+ // candidate admission can never accept — only the failed label comes off,
1430
+ // and the exhaustion reaches a human (#490, #348).
1431
+ if (cls === "wall-clock-cap-progress") {
1432
+ const state = await tracker.issueState(run.issue).catch(() => undefined);
1433
+ if (state !== "open") {
1434
+ log(`#${run.issue} not continued from ${cls}: issue is ${state ?? "unreadable"}`);
1435
+ return;
1436
+ }
1437
+ const continuation = store.continuationsFor(project.name, run.issue);
1438
+ if (hasContinuationBudget(continuation, caps.maxContinuationsPerIssue)) {
1439
+ swapToQueue(d, run.issue, project.stateLabels.failed);
1440
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1441
+ log(`#${run.issue} requeued for a wall-clock continuation: ${evidence}`);
1442
+ } else {
1443
+ store.enqueueLabelOps(project.name, [
1444
+ { issue: run.issue, op: "remove", label: project.stateLabels.failed },
1445
+ ]);
1446
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1447
+ await safeEscalate(d, {
1448
+ tier: 1,
1449
+ project: project.name,
1450
+ issue: run.issue,
1451
+ summary: `#${run.issue} exhausted its continuation budget on wall-clock cap kills`,
1452
+ detail: [
1453
+ `Attempt ${run.attempt} hit the wall-clock cap with work to continue from, but ${continuation} continuation(s) are already charged against a cap of ${caps.maxContinuationsPerIssue}.`,
1454
+ evidence,
1455
+ `Work to continue: branch ${run.branch} at ${run.headSha ?? run.salvageSha}${run.prUrl === undefined ? "" : ` — ${run.prUrl}`}.`,
1456
+ "The issue cannot finish inside the wall-clock cap, so another run would burn a worker slot for the same outcome. Re-scope it, raise maxContinuationsPerIssue for it, or finish the remaining work by hand.",
1457
+ ].join("\n"),
1458
+ });
1459
+ await postExhaustionPostmortem(
1460
+ d,
1461
+ run,
1462
+ `Attempt ${run.attempt} hit the wall-clock cap with work to continue from, but ${continuation} continuation(s) are already charged against a cap of ${caps.maxContinuationsPerIssue}.`,
1463
+ );
1464
+ log(`#${run.issue} not continued from ${cls}: continuation budget exhausted`);
1465
+ }
1466
+ return;
1467
+ }
1468
+
1469
+ // `merge-conflict`: the branch is retained and its PR is open, so #50's
1470
+ // continuation guard admits it and the next tick briefs a rebase.
1471
+ //
1472
+ // The outbox makes the retry contract one-sided: the swap is enqueued — a
1473
+ // durable local write that cannot fail on the tracker — before
1474
+ // `recoveredAt` is written, so the row can never again be taken out of
1475
+ // `runsNeedingClassification` with its label swap still owed. That was
1476
+ // the defect 0.4.4 claimed to have fixed and did not, for this one
1477
+ // recovery; the projector retries until the tracker takes the swap, and
1478
+ // while it is pending the eligibility overlay keeps the issue coherent
1479
+ // (#201).
1480
+ swapToQueue(d, run.issue, inProgress);
1481
+ store.updateRun(run.id, {
1482
+ state: "killed",
1483
+ lastError:
1484
+ "merge-conflict: base moved under a green PR — rebase, regenerate recorded artifacts, push without force",
1485
+ recoveredAt: Date.now(),
1486
+ });
1487
+ log(`#${run.issue} requeued for a rebase continuation: ${evidence}`);
1488
+ return;
1489
+ }
1490
+
1491
+ if (recovery === "requeue") {
1492
+ if (cls === "provider-credit") {
1493
+ await reactToProviderCredit(d, run.issue, evidence, run.sessionFile);
1494
+ }
1495
+ // A dispatch-infra requeue that keeps landing on the same issue means the
1496
+ // mirror for its repo is persistently broken — a ref-lock that retry already
1497
+ // exhausted, a dead remote. Requeueing forever spends a turn-0 run per tick
1498
+ // with no chance of success, so after a bounded number of strikes this
1499
+ // escalates to a human instead (#168, #177).
1500
+ if (cls === "dispatch-infra" && store.classCountFor(project.name, run.issue, "dispatch-infra") >= DISPATCH_INFRA_MAX_STRIKES) {
1501
+ await safeEscalate(d, {
1502
+ tier: 1,
1503
+ project: project.name,
1504
+ issue: run.issue,
1505
+ summary: `[dispatch-infra] #${run.issue}: the mirror for ${run.repo} is failing persistently — ${evidence}`,
1506
+ detail: [
1507
+ `The dispatcher could not provision a worktree for #${run.issue} ${DISPATCH_INFRA_MAX_STRIKES} times in a row, all before the worker's first turn.`,
1508
+ "The mirror on this host needs attention (check disk, SSH/HTTPS credentials, and the mirror root).",
1509
+ ].join("\n"),
1510
+ });
1511
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1512
+ log(`#${run.issue} escalated from persistent ${cls}: ${evidence}`);
1513
+ return;
1514
+ }
1515
+ // Same bound for provider-transient: an issue whose stream keeps stalling
1516
+ // mid-run is requeued free (no attempt, no continuation charged) — but a
1517
+ // provider that aborts three times for one issue is down, and a human has
1518
+ // to check its status before hand-requeueing (#220). The escalation names
1519
+ // every model the chain tried, so a merged branch built on a different
1520
+ // model is attributable (#286).
1521
+ if (
1522
+ cls === "provider-transient" &&
1523
+ store.classCountFor(project.name, run.issue, "provider-transient") >= PROVIDER_TRANSIENT_MAX_STRIKES
1524
+ ) {
1525
+ const tried = formatModelsTried(modelsTried(store.runsForIssue(project.name, run.issue)));
1526
+ await safeEscalate(d, {
1527
+ tier: 1,
1528
+ project: project.name,
1529
+ issue: run.issue,
1530
+ summary: `[provider-transient] #${run.issue}: the provider keeps aborting mid-stream — ${evidence}`,
1531
+ detail: [
1532
+ `The provider aborted the stream for #${run.issue} ${PROVIDER_TRANSIENT_MAX_STRIKES} times without the run ever producing a verdict (0 tokens billed each time).`,
1533
+ ...(tried === ""
1534
+ ? []
1535
+ : [`Models tried: ${tried}.`]),
1536
+ "Check provider status before requeueing by hand.",
1537
+ ].join("\n"),
1538
+ });
1539
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1540
+ log(`#${run.issue} escalated from persistent ${cls}: ${evidence}`);
1541
+ return;
1542
+ }
1543
+ // Same bound for provider-capacity: a run the provider throttled into the
1544
+ // ground is requeued free (no attempt charged) — but a provider that
1545
+ // throttles the same issue three times is at capacity, and a human has to
1546
+ // check its status before hand-requeueing (#573). On a chain-configured
1547
+ // project each requeue already moved the next attempt to the next chain
1548
+ // model, so this escalation is what catches the no-chain case and the
1549
+ // exhausted chain; it names every model the chain tried.
1550
+ if (
1551
+ cls === "provider-capacity" &&
1552
+ store.classCountFor(project.name, run.issue, "provider-capacity") >= PROVIDER_CAPACITY_MAX_STRIKES
1553
+ ) {
1554
+ const tried = formatModelsTried(modelsTried(store.runsForIssue(project.name, run.issue)));
1555
+ await safeEscalate(d, {
1556
+ tier: 1,
1557
+ project: project.name,
1558
+ issue: run.issue,
1559
+ summary: `[provider-capacity] #${run.issue}: the model provider is throttling this run into the ground — ${evidence}`,
1560
+ detail: [
1561
+ `The provider answered #${run.issue} with sustained in-session rate limits ${PROVIDER_CAPACITY_MAX_STRIKES} times in a row; the harness retried each and was exhausted.`,
1562
+ ...(tried === ""
1563
+ ? []
1564
+ : [`Models tried: ${tried}.`]),
1565
+ "Check the provider's rate-limit status (and its throughput-oriented routes) before requeueing by hand.",
1566
+ ].join("\n"),
1567
+ });
1568
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1569
+ log(`#${run.issue} escalated from persistent ${cls}: ${evidence}`);
1570
+ return;
1571
+ }
1572
+ // Only when the tracker still shows this issue as ours to hand back. An
1573
+ // issue that is closed, or has no state label, was resolved by another route
1574
+ // and requeueing it would dispatch work nobody asked for.
1575
+ const state = await tracker.issueState(run.issue).catch(() => undefined);
1576
+ if (state !== "open") {
1577
+ log(`#${run.issue} not requeued from ${cls}: issue is ${state ?? "unreadable"}`);
1578
+ return;
1579
+ }
1580
+ // A clean orphan whose queue label is already absent is a deliberate
1581
+ // withdrawal — the operator took the issue out of the queue (e.g. so a
1582
+ // daemon restart could not re-dispatch work known to be unsafe) — and
1583
+ // recovery must not recreate that intent (#423). Read the live label set;
1584
+ // when the queue label is gone, release the dispatcher-owned in-progress
1585
+ // label and stop, leaving the operator's withdrawal to survive recovery.
1586
+ if (cls === "orphan-clean") {
1587
+ const snapshot = await tracker.issueSnapshot(run.issue).catch(() => undefined);
1588
+ if (snapshot === undefined) {
1589
+ log(`#${run.issue} not requeued from orphan-clean: cannot confirm ${project.queueLabel} (unreadable, retrying)`);
1590
+ return;
1591
+ }
1592
+ if (!snapshot.labels.includes(project.queueLabel)) {
1593
+ store.enqueueLabelOps(project.name, [{ issue: run.issue, op: "remove", label: inProgress }]);
1594
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1595
+ log(`#${run.issue} not requeued from orphan-clean: ${project.queueLabel} removed before recovery (operator withdrawal)`);
1596
+ return;
1597
+ }
1598
+ // #439: an orphan-clean row charges the continuation budget, so once
1599
+ // `hasContinuationBudget` is spent — exactly the predicate `admitCandidates`
1600
+ // holds the issue on — requeueing re-adds a queue label for a candidate the
1601
+ // dispatcher can never admit. Stop handing it back and hold it instead: the
1602
+ // queue label comes off (so admission never re-holds on every dispatch),
1603
+ // the in-progress label is released, and a single diagnosis escalates once.
1604
+ // `orphan-clean` is deliberately NOT a global exclusion from the budget (a
1605
+ // worker that genuinely keeps dying mid-work must still be bounded); this is
1606
+ // the missing ceiling check this path never had (#348's invariant).
1607
+ const continuations = store.continuationsFor(project.name, run.issue);
1608
+ if (!hasContinuationBudget(continuations, caps.maxContinuationsPerIssue)) {
1609
+ const runs = store.runsForIssue(project.name, run.issue);
1610
+ const breakdown = continuationBreakdown(runs);
1611
+ const artifact = newestContinuableRun(runs);
1612
+ const onlyDaemonStops = breakdown.size === 1 && breakdown.get("orphan-clean") === continuations;
1613
+ const classLine = Array.from(breakdown, ([cls, n]) => `${n} ${cls}`).join(", ");
1614
+ const artifactLine =
1615
+ artifact === undefined
1616
+ ? "The attempts left no salvage commit, head SHA or PR — the branch is empty, so start clean from a re-scope rather than continuing from nothing."
1617
+ : `Work to continue: branch ${artifact.branch} at ${artifact.headSha ?? artifact.salvageSha}${artifact.prUrl === undefined ? "" : ` — ${artifact.prUrl}`}.`;
1618
+ store.enqueueLabelOps(project.name, [
1619
+ { issue: run.issue, op: "remove", label: inProgress },
1620
+ { issue: run.issue, op: "remove", label: project.queueLabel },
1621
+ ]);
1622
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1623
+ await safeEscalate(d, {
1624
+ tier: 1,
1625
+ project: project.name,
1626
+ issue: run.issue,
1627
+ summary: `#${run.issue} exhausted its ${caps.maxContinuationsPerIssue}-continuation budget on ${cls}`,
1628
+ detail: [
1629
+ `Attempt ${run.attempt} is not requeued: ${continuations} continuation(s) charged against a cap of ${caps.maxContinuationsPerIssue}.`,
1630
+ `Continuations by failure class: ${classLine}.`,
1631
+ onlyDaemonStops
1632
+ ? "Every continuation was a daemon stop — the work never failed; the budget was spent by daemon deaths, not the issue."
1633
+ : "Continuations span real work — inspect what each attempt left behind before continuing.",
1634
+ artifactLine,
1635
+ "What you can do: raise maxContinuationsPerIssue for this issue, re-scope it, or continue from the preserved work (or start clean if none).",
1636
+ ].join("\n"),
1637
+ });
1638
+ await postExhaustionPostmortem(
1639
+ d,
1640
+ run,
1641
+ `Attempt ${run.attempt} is not requeued: ${continuations} continuation(s) charged against a cap of ${caps.maxContinuationsPerIssue}.`,
1642
+ );
1643
+ log(`#${run.issue} not requeued from orphan-clean: continuation budget exhausted`);
1644
+ return;
1645
+ }
1646
+ }
1647
+ const label = cls === "orphan-clean" ? inProgress : project.stateLabels.failed;
1648
+ swapToQueue(d, run.issue, label);
1649
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1650
+ log(`#${run.issue} requeued from ${cls}: ${evidence}`);
1651
+ return;
1652
+ }
1653
+
1654
+ if (recovery === "rerun-checks") {
1655
+ if (run.prUrl === undefined) return;
1656
+ try {
1657
+ await tracker.rerunFailedChecks(run.prUrl);
1658
+ } catch (err) {
1659
+ log(`#${run.issue} check re-run failed (${errText(err)}) — retrying next tick`);
1660
+ return;
1661
+ }
1662
+ // Back to pending rather than green: the existing settle sweep re-verifies
1663
+ // it against the recorded head on a later tick, so nothing here has to guess
1664
+ // whether the re-run passed.
1665
+ store.updateRun(run.id, { state: "pushed-pending", lastError: null, recoveredAt: Date.now() });
1666
+ log(`#${run.issue} re-ran infrastructure checks: ${evidence}`);
1667
+ return;
1668
+ }
1669
+
1670
+ if (recovery === "escalate") {
1671
+ const detail = [evidence];
1672
+ if (cls === "turn-cap-spinning" || cls === "wall-clock-cap-spinning") {
1673
+ const calls = lastToolCalls(run.sessionFile);
1674
+ detail.push(
1675
+ calls.length === 0
1676
+ ? "transcript unreadable — no tool calls could be recovered"
1677
+ : `Last ${calls.length} tool calls: ${calls.join(" → ")}`,
1678
+ );
1679
+ }
1680
+ if (run.lastError !== undefined && cls !== "question") detail.push(run.lastError);
1681
+ // #172: an unwritten transcript is "the run died before it flushed", not a
1682
+ // link to a file the operator will open and find missing.
1683
+ detail.push(
1684
+ run.sessionFile === undefined
1685
+ ? "Session: (no transcript)"
1686
+ : existsSync(run.sessionFile)
1687
+ ? `Session: ${run.sessionFile}`
1688
+ : `Session: ${run.sessionFile} (file was never written — the run died before its transcript was flushed)`,
1689
+ );
1690
+ // The class and the run are in the summary, which is what the notifications
1691
+ // ledger dedupes on — so one class escalates once per run rather than every
1692
+ // five minutes.
1693
+ await safeEscalate(d, {
1694
+ tier: 1,
1695
+ project: project.name,
1696
+ issue: run.issue,
1697
+ runId: run.id,
1698
+ summary: `[${cls}] #${run.issue} attempt ${run.attempt}: ${evidence}`,
1699
+ detail: detail.join("\n"),
1700
+ });
1701
+ // The hand-off IS the recovery for these classes: there is nothing else this
1702
+ // package can do, and leaving the row unrecovered would re-escalate forever.
1703
+ store.updateRun(run.id, { recoveredAt: Date.now() });
1704
+ return;
1705
+ }
1706
+
1707
+ // `hold` (orphan-dirty) and `none`: recorded, nothing performed. The existing
1708
+ // unsalvaged-WIP admission hold already fails dispatch closed until an
1709
+ // operator acknowledges the tree, which is the only safe move when the
1710
+ // worktree holds the only copy of real work.
1711
+ }
1712
+
1713
+ /**
1714
+ * Enqueue a state-label → queue-label swap for projection (#201).
1715
+ *
1716
+ * The swap is two ops in id order — remove first, then add — which is the
1717
+ * atomicity the projector guarantees: the issue never sits newly eligible
1718
+ * without a queue label on its way back, and the add never lands before the
1719
+ * remove when GitHub fails between them. Enqueueing is a durable local write
1720
+ * that cannot fail on the tracker, so the caller records its recovery
1721
+ * immediately and the projector retries the swap until the tracker takes it —
1722
+ * that closes the 0.4.4 hole where a refused label swap stranded the row
1723
+ * permanently under a log line promising a retry.
1724
+ */
1725
+ export function swapToQueue(d: Pick<SettlementDeps, "project" | "store">, issue: number, label: string): void {
1726
+ d.store.enqueueLabelOps(d.project.name, [
1727
+ { issue, op: "remove", label },
1728
+ { issue, op: "add", label: d.project.queueLabel },
1729
+ ]);
1730
+ }
1731
+
1732
+
1733
+ // ------------------------------------------------------------------- status rendering of salvaged runs
1734
+
1735
+ /**
1736
+ * The WIP block: every issue whose newest attempt left work behind, and
1737
+ * whether that work is safe.
1738
+ *
1739
+ * Blocked runs used to be invisible here, which is exactly how #118 stayed
1740
+ * invisible for a full attempt cycle — the operator saw a blocked issue and had
1741
+ * no way to tell "stopped with 34 uncommitted files" from "stopped clean".
1742
+ * A preserved line is informational; an UNSALVAGED line is an alarm, and it
1743
+ * names the directory because that directory is the work.
1744
+ */
1745
+ export function formatSalvagedRuns(runs: readonly RunRecord[]): string[] {
1746
+ if (runs.length === 0) return [];
1747
+ const lines = ["", "wip"];
1748
+ for (const r of runs) {
1749
+ lines.push(
1750
+ r.salvageError !== undefined && r.salvageAckAt === undefined
1751
+ ? ` #${r.issue} UNSALVAGED ${r.worktree === "" ? "(path not recorded)" : r.worktree} — ` +
1752
+ `only copy, dispatch held (${r.salvageError})`
1753
+ : r.salvageError !== undefined
1754
+ ? ` #${r.issue} accepted as lost attempt ${r.attempt} (${r.salvageError})`
1755
+ : ` #${r.issue} preserved ${r.salvageSha ?? "?"} on ${r.branch} (attempt ${r.attempt}, ${r.state})`,
1756
+ );
1757
+ }
1758
+ return lines;
1759
+ }
1760
+
1761
+ /**
1762
+ * The quarantined block (#737): retained worktrees whose object store could
1763
+ * not be made sound, so the daemon refused to fetch into them and their
1764
+ * commits cannot be verified against any remote. Distinct from the `wip` block
1765
+ * on purpose — quarantine is not work the exit left behind, it is a tree the
1766
+ * daemon is refusing to trust, and "potentially stranded" outranks any
1767
+ * wording that reads like routine retention. The line names the directory
1768
+ * because the directory is the work.
1769
+ */
1770
+ export function formatQuarantinedRuns(runs: readonly RunRecord[]): string[] {
1771
+ if (runs.length === 0) return [];
1772
+ const lines = ["", "quarantined"];
1773
+ for (const r of runs) {
1774
+ lines.push(
1775
+ ` #${r.issue} QUARANTINED ${r.worktree === "" ? "(path not recorded)" : r.worktree} — ` +
1776
+ (r.quarantineDetail ?? "object store could not be made sound"),
1777
+ );
1778
+ }
1779
+ return lines;
1780
+ }