opencode-model-router 2.8.0 → 2.9.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.
- package/CHANGELOG.md +372 -0
- package/README.md +22 -2
- package/package.json +5 -1
- package/src/commands/output.ts +23 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2656 -114
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
- package/tiers.json +5 -5
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
// RecoveryService (plan task 4.2.4): evidence-based reconciliation of executor ledgers after a restart.
|
|
2
|
+
// Design: docs/qa/critical-path-execution/phase-4.2.md sections 5-8 (R1-R5, L1-L6, D1-D12).
|
|
3
|
+
//
|
|
4
|
+
// `reconcile` is classification only: it never writes a ledger, resets a slot or interrupts a session. The runtime
|
|
5
|
+
// applies the feeds (interrupts orphans, requeues, adopts, runs the probation watch) while it holds the plan's lock.
|
|
6
|
+
|
|
7
|
+
import { realpathSync } from "node:fs";
|
|
8
|
+
import { withoutHostPreamble } from "./host-preamble.js";
|
|
9
|
+
import { ADOPT_TAKEOVER_REASON } from "./ledger.js";
|
|
10
|
+
import type { ProcessIdentity } from "./process-identity.js";
|
|
11
|
+
import { ExecutorError, LAUNCH_HEADER_PATTERN, parseLaunchHeader } from "./types.js";
|
|
12
|
+
import type {
|
|
13
|
+
Attempt, Clock, HostSessionContext, HostSessions, LedgerStore, LedgerV1, LockHolder, PlanId, ReconcileAction,
|
|
14
|
+
RecoveryService, TaskId, TaskNode,
|
|
15
|
+
} from "./types.js";
|
|
16
|
+
|
|
17
|
+
export const RECOVERY_LIVENESS_MS = 60_000;
|
|
18
|
+
export const RECOVERY_POLL_MS = 10_000;
|
|
19
|
+
export const RECOVER_TAKEOVER_REASON = "recover";
|
|
20
|
+
|
|
21
|
+
export type RecoveryHost = Pick<HostSessions, "get" | "context" | "activity" | "interrupt">;
|
|
22
|
+
export type RecoveryLog = (level: "info" | "warn" | "error", msg: string, detail?: Record<string, string | number | boolean | null>) => void;
|
|
23
|
+
export type ChildEvidence = "finished" | "alive" | "unknown" | "lost" | "mismatch";
|
|
24
|
+
|
|
25
|
+
export interface ReconcileFeed extends ReconcileAction {
|
|
26
|
+
/** Latest attempt number, null without attempts. */
|
|
27
|
+
n: number | null;
|
|
28
|
+
/** Child recorded on that attempt. */
|
|
29
|
+
childSessionID: string | null;
|
|
30
|
+
/** The child's context when it was read. */
|
|
31
|
+
context: HostSessionContext | null;
|
|
32
|
+
/** R1a: set when the child's liveness is unknown; the runtime runs the watch, recovery only reports the deadline. */
|
|
33
|
+
probation: { deadlineAt: number; pollMs: number } | null;
|
|
34
|
+
/** The child exists but does not carry this attempt's launch header (reported as evidence `lost`). */
|
|
35
|
+
mismatch: boolean;
|
|
36
|
+
/** Sessions to interrupt: closed attempts' children that still run, plus a mismatching child naming this plan. */
|
|
37
|
+
orphans: string[];
|
|
38
|
+
/** R2: the slot marker names this plan and task; null when the task has no slot (or the state does not use one). */
|
|
39
|
+
slotValid: boolean | null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface RecoveryEngine extends RecoveryService {
|
|
43
|
+
/** Classification only; no writes, interrupts or resets. Called with the plan's lock held. */
|
|
44
|
+
reconcile(l: Readonly<LedgerV1>, tracked: ReadonlySet<string /* nonce */>): Promise<ReconcileFeed[]>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface RecoveryDeps {
|
|
48
|
+
store: LedgerStore;
|
|
49
|
+
host: RecoveryHost;
|
|
50
|
+
/** This session's repository toplevel. */
|
|
51
|
+
toplevel: string;
|
|
52
|
+
holder(sessionID: string): LockHolder;
|
|
53
|
+
slotMarker(slotPath: string): Promise<{ planId: PlanId; taskId: TaskId } | null>;
|
|
54
|
+
clock: Clock;
|
|
55
|
+
log: RecoveryLog;
|
|
56
|
+
livenessMs?: number;
|
|
57
|
+
pollMs?: number;
|
|
58
|
+
/** v2 only: a dead launcher proves inactivity only for a running child with no tool in flight; otherwise keep probation. */
|
|
59
|
+
launcherLiveness?: { self: ProcessIdentity; isAlive: (pid: number) => boolean };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* R1 rules 3-6 for one recorded child. `info` is `HostSessions.get`, `ctx` is `context`, `activity` is `activity`.
|
|
64
|
+
* The first user message, after the v2 host's one preamble line when it carries it (QA-4.2-1), is parsed strictly as a
|
|
65
|
+
* launch header; `sharedContext` is the ledger's (when omitted it is read off the message itself: everything between
|
|
66
|
+
* "PLAN CONTEXT\n" and the blank line before the header line). Rule 5 (amended, QA-4.2-2): the child is finished only when
|
|
67
|
+
* its context ends with the host's explicit terminal entry (`idle` with an outcome); an `idle` without one is not an end.
|
|
68
|
+
*/
|
|
69
|
+
export function classifyChild(
|
|
70
|
+
info: { id: string; parentID: string | null } | null,
|
|
71
|
+
ctx: HostSessionContext | null,
|
|
72
|
+
activity: "active" | "inactive" | "unknown",
|
|
73
|
+
expect: { planId: PlanId; taskId: TaskId; n: number; nonce: string },
|
|
74
|
+
sharedContext?: string,
|
|
75
|
+
): ChildEvidence {
|
|
76
|
+
if (info === null) return "lost";
|
|
77
|
+
const h = headerOf(ctx, sharedContext);
|
|
78
|
+
if (h === null || h.planId !== expect.planId || h.taskId !== expect.taskId || h.attempt !== expect.n || h.nonce !== expect.nonce) {
|
|
79
|
+
return "mismatch";
|
|
80
|
+
}
|
|
81
|
+
if (endedOf(ctx)) return "finished";
|
|
82
|
+
if (activity === "active") return "alive";
|
|
83
|
+
if (activity === "inactive") return "lost";
|
|
84
|
+
return "unknown";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* QA-4.2-2: an explicit terminal entry (the host reported the child ended, with its outcome). A last `idle` without an
|
|
89
|
+
* outcome is not evidence of an end (defensive), so it is never read as finished.
|
|
90
|
+
*/
|
|
91
|
+
function endedOf(ctx: HostSessionContext | null): boolean {
|
|
92
|
+
const last = ctx === null ? undefined : ctx.messages[ctx.messages.length - 1];
|
|
93
|
+
return last !== undefined && last.role === "idle" && last.outcome !== null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function headerOf(ctx: HostSessionContext | null, sharedContext: string | undefined): ReturnType<typeof parseLaunchHeader> {
|
|
97
|
+
const first = ctx === null ? undefined : ctx.messages.find((m) => m.role === "user");
|
|
98
|
+
const raw = first?.text ?? null;
|
|
99
|
+
if (raw === null) return null;
|
|
100
|
+
// QA-4.2-1: on v2 the host prefixes every native subagent's first user message with its one preamble line.
|
|
101
|
+
const prompt = withoutHostPreamble(raw);
|
|
102
|
+
const shared = sharedContext ?? inferSharedContext(prompt);
|
|
103
|
+
return shared === null ? null : parseLaunchHeader(prompt, shared);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Everything between "PLAN CONTEXT\n" and the blank line before the header line. For an editing task that span starts
|
|
108
|
+
* with the executor's read-cap line (DF-2-9); `parseLaunchHeader` reads it back as a prompt without the optional line.
|
|
109
|
+
*/
|
|
110
|
+
function inferSharedContext(prompt: string): string | null {
|
|
111
|
+
const open = "PLAN CONTEXT\n";
|
|
112
|
+
if (!prompt.startsWith(open)) return null;
|
|
113
|
+
const m = LAUNCH_HEADER_PATTERN.exec(prompt);
|
|
114
|
+
if (m === null) return null;
|
|
115
|
+
const end = m.index - 2;
|
|
116
|
+
if (end < open.length - 1 || prompt.slice(end, m.index) !== "\n\n") return null;
|
|
117
|
+
return prompt.slice(open.length, end);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function normalizeToplevel(p: string): string {
|
|
121
|
+
let real = p;
|
|
122
|
+
try {
|
|
123
|
+
real = realpathSync(p);
|
|
124
|
+
} catch {
|
|
125
|
+
// a path that cannot be resolved is compared as written
|
|
126
|
+
}
|
|
127
|
+
let s = real.replace(/\\/g, "/");
|
|
128
|
+
while (s.length > 1 && s.endsWith("/") && !/^[A-Za-z]:\/$/.test(s)) s = s.slice(0, -1);
|
|
129
|
+
return process.platform === "win32" ? s.toLowerCase() : s;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** L5: real path, `/` separators, case-folded on win32. */
|
|
133
|
+
export function sameToplevel(a: string, b: string): boolean {
|
|
134
|
+
return normalizeToplevel(a) === normalizeToplevel(b);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function isLockHeld(e: unknown): boolean {
|
|
138
|
+
return e instanceof ExecutorError && e.code === "E_LOCK_HELD";
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const TERMINAL = new Set(["completed", "aborted"]);
|
|
142
|
+
/** States whose slot marker is checked (R2). */
|
|
143
|
+
const SLOT_STATES = new Set(["ready", "dispatched", "running", "completed", "verifying", "verified"]);
|
|
144
|
+
/** States that always get a feed. */
|
|
145
|
+
const REPORTED_STATES = new Set([
|
|
146
|
+
"ready", "dispatched", "running", "completed", "verifying", "verified", "integrating", "failed", "conflict", "reverted",
|
|
147
|
+
]);
|
|
148
|
+
const ORPHAN_OUTCOMES = new Set(["lost", "capacity", "interrupted"]);
|
|
149
|
+
|
|
150
|
+
interface ChildRead {
|
|
151
|
+
evidence: ChildEvidence;
|
|
152
|
+
context: HostSessionContext | null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
type LauncherActivity = (t: TaskNode, a: Attempt, child: string) => Promise<"inactive" | "unknown">;
|
|
156
|
+
|
|
157
|
+
export function createRecoveryService(d: RecoveryDeps): RecoveryEngine {
|
|
158
|
+
const livenessMs = d.livenessMs ?? RECOVERY_LIVENESS_MS;
|
|
159
|
+
const pollMs = d.pollMs ?? RECOVERY_POLL_MS;
|
|
160
|
+
let recovered = false;
|
|
161
|
+
|
|
162
|
+
async function inspect(l: Readonly<LedgerV1>, t: TaskNode, a: Attempt, childId: string, launcherActivity: LauncherActivity): Promise<ChildRead> {
|
|
163
|
+
const expect = { planId: l.planId, taskId: t.id, n: a.n, nonce: a.nonce };
|
|
164
|
+
try {
|
|
165
|
+
const info = await d.host.get(childId);
|
|
166
|
+
if (info === null) return { evidence: "lost", context: null };
|
|
167
|
+
const ctx = await d.host.context(childId);
|
|
168
|
+
let ev = classifyChild(info, ctx, "unknown", expect, l.sharedContext);
|
|
169
|
+
if (ev === "unknown") {
|
|
170
|
+
let activity = await d.host.activity(childId);
|
|
171
|
+
if (activity === "unknown" && d.launcherLiveness !== undefined && t.state === "running") {
|
|
172
|
+
if (ctx?.toolInFlight === false) activity = await launcherActivity(t, a, childId);
|
|
173
|
+
else d.log("info", "recovery: the child stopped with a tool call in flight; keeping the liveness probation", { taskId: t.id, n: a.n });
|
|
174
|
+
}
|
|
175
|
+
ev = classifyChild(info, ctx, activity, expect, l.sharedContext);
|
|
176
|
+
}
|
|
177
|
+
return { evidence: ev, context: ctx };
|
|
178
|
+
} catch (e) {
|
|
179
|
+
d.log("warn", "recovery: host evidence unavailable; treating the child as unknown", {
|
|
180
|
+
planId: l.planId, taskId: t.id, sessionID: childId, error: e instanceof Error ? e.message : String(e),
|
|
181
|
+
});
|
|
182
|
+
return { evidence: "unknown", context: null };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** True when the session is alive-ish (not idle) and its launch header names this plan. */
|
|
187
|
+
async function namesPlanAndRuns(l: Readonly<LedgerV1>, sessionID: string): Promise<boolean> {
|
|
188
|
+
try {
|
|
189
|
+
const info = await d.host.get(sessionID);
|
|
190
|
+
if (info === null) return false;
|
|
191
|
+
const ctx = await d.host.context(sessionID);
|
|
192
|
+
if (endedOf(ctx)) return false;
|
|
193
|
+
const h = headerOf(ctx, l.sharedContext);
|
|
194
|
+
return h !== null && h.planId === l.planId;
|
|
195
|
+
} catch (e) {
|
|
196
|
+
d.log("warn", "recovery: orphan check failed", {
|
|
197
|
+
planId: l.planId, sessionID, error: e instanceof Error ? e.message : String(e),
|
|
198
|
+
});
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function reconcileTask(
|
|
204
|
+
l: Readonly<LedgerV1>, t: TaskNode, tracked: ReadonlySet<string>, launcherActivity: LauncherActivity,
|
|
205
|
+
): Promise<ReconcileFeed | null> {
|
|
206
|
+
const latest: Attempt | undefined = t.attempts[t.attempts.length - 1];
|
|
207
|
+
const child = latest?.childSessionID ?? null;
|
|
208
|
+
const feed: ReconcileFeed = {
|
|
209
|
+
taskId: t.id, from: t.state, evidence: "none", action: "none",
|
|
210
|
+
n: latest?.n ?? null, childSessionID: child, context: null, probation: null, mismatch: false, orphans: [], slotValid: null,
|
|
211
|
+
};
|
|
212
|
+
// D12 / R1 rule 1: a launch this process tracks is never reconciled.
|
|
213
|
+
if (latest !== undefined && tracked.has(latest.nonce)) {
|
|
214
|
+
feed.evidence = "alive";
|
|
215
|
+
return feed;
|
|
216
|
+
}
|
|
217
|
+
const orphans = new Set<string>();
|
|
218
|
+
// Orphans: closed attempts' children that still run (the latest attempt's own child is handled by the matrix).
|
|
219
|
+
const matrixOwnsLatest = t.state === "ready" || t.state === "dispatched" || t.state === "running";
|
|
220
|
+
for (const a of t.attempts) {
|
|
221
|
+
if ((a === latest && matrixOwnsLatest) || a.childSessionID === null || a.endedAt === null || a.outcome === null) continue;
|
|
222
|
+
if (!ORPHAN_OUTCOMES.has(a.outcome) || (matrixOwnsLatest && a.childSessionID === child)) continue;
|
|
223
|
+
if (await namesPlanAndRuns(l, a.childSessionID)) orphans.add(a.childSessionID);
|
|
224
|
+
}
|
|
225
|
+
if (t.slot !== null && SLOT_STATES.has(t.state)) {
|
|
226
|
+
const marker = await d.slotMarker(t.slot);
|
|
227
|
+
feed.slotValid = marker !== null && marker.planId === l.planId && marker.taskId === t.id;
|
|
228
|
+
}
|
|
229
|
+
const slotBad = feed.slotValid === false;
|
|
230
|
+
const probation = (): { deadlineAt: number; pollMs: number } => ({ deadlineAt: d.clock.now() + livenessMs, pollMs });
|
|
231
|
+
|
|
232
|
+
const fromRead = async (a: Attempt, c: string): Promise<ChildRead> => {
|
|
233
|
+
const r = await inspect(l, t, a, c, launcherActivity);
|
|
234
|
+
feed.context = r.context;
|
|
235
|
+
if (r.evidence === "mismatch") {
|
|
236
|
+
feed.mismatch = true;
|
|
237
|
+
feed.evidence = "lost";
|
|
238
|
+
if (await namesPlanAndRuns(l, c)) orphans.add(c);
|
|
239
|
+
} else if (r.evidence === "unknown") {
|
|
240
|
+
feed.evidence = "alive";
|
|
241
|
+
} else {
|
|
242
|
+
feed.evidence = r.evidence;
|
|
243
|
+
}
|
|
244
|
+
return r;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
switch (t.state) {
|
|
248
|
+
case "ready": {
|
|
249
|
+
if (latest === undefined || child === null) break;
|
|
250
|
+
const adoptable = latest.outcome === "lost" && latest.endedAt !== null && t.slot !== null;
|
|
251
|
+
const r = await fromRead(latest, child);
|
|
252
|
+
if (adoptable && !slotBad) {
|
|
253
|
+
if (r.evidence === "finished" || r.evidence === "alive") feed.action = "adopt";
|
|
254
|
+
else if (r.evidence === "unknown") {
|
|
255
|
+
feed.action = "adopt";
|
|
256
|
+
feed.probation = probation();
|
|
257
|
+
}
|
|
258
|
+
} else {
|
|
259
|
+
// `ready`, other: a child that still runs is an orphan; a finished or gone one is ignored.
|
|
260
|
+
if (r.evidence === "alive" || r.evidence === "unknown") {
|
|
261
|
+
orphans.add(child);
|
|
262
|
+
feed.action = "interrupt-orphan";
|
|
263
|
+
}
|
|
264
|
+
// R2: the slot is gone or foreign, so the lost attempt cannot be adopted; the runtime clears the slot.
|
|
265
|
+
if (adoptable && slotBad && feed.action === "none") feed.action = "requeue-lost";
|
|
266
|
+
}
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
case "dispatched": {
|
|
270
|
+
// A dispatched attempt never has a child id (row 10): requeue at once (C12).
|
|
271
|
+
feed.action = "requeue-lost";
|
|
272
|
+
if (child !== null && latest !== undefined) await fromRead(latest, child);
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
case "running": {
|
|
276
|
+
if (latest === undefined || child === null) {
|
|
277
|
+
feed.action = "requeue-lost";
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
const r = await fromRead(latest, child);
|
|
281
|
+
if (slotBad) {
|
|
282
|
+
feed.action = "requeue-lost";
|
|
283
|
+
if (r.evidence === "alive" || r.evidence === "unknown") orphans.add(child);
|
|
284
|
+
} else if (r.evidence === "finished") feed.action = "process-result";
|
|
285
|
+
else if (r.evidence === "alive") feed.action = "adopt";
|
|
286
|
+
else if (r.evidence === "unknown") {
|
|
287
|
+
feed.action = "adopt";
|
|
288
|
+
feed.probation = probation();
|
|
289
|
+
} else feed.action = "requeue-lost";
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
case "completed":
|
|
293
|
+
case "verifying":
|
|
294
|
+
feed.action = "reverify";
|
|
295
|
+
break;
|
|
296
|
+
case "verified":
|
|
297
|
+
feed.action = "re-enqueue";
|
|
298
|
+
break;
|
|
299
|
+
case "integrating":
|
|
300
|
+
feed.action = "resume-integration";
|
|
301
|
+
break;
|
|
302
|
+
default:
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
feed.orphans = [...orphans].sort();
|
|
306
|
+
if (!REPORTED_STATES.has(t.state) && feed.orphans.length === 0) return null;
|
|
307
|
+
return feed;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function reconcile(l: Readonly<LedgerV1>, tracked: ReadonlySet<string>): Promise<ReconcileFeed[]> {
|
|
311
|
+
// History-class metrics survive journal rotation. Read once, lazily, and never touch the store without the v2 dep.
|
|
312
|
+
let launchers: Promise<Array<Record<string, string>> | null> | undefined;
|
|
313
|
+
const launcherActivity: LauncherActivity = async (t, a, child) => {
|
|
314
|
+
const dep = d.launcherLiveness;
|
|
315
|
+
if (dep === undefined) return "unknown";
|
|
316
|
+
launchers ??= (async () => {
|
|
317
|
+
try {
|
|
318
|
+
const records: Array<Record<string, string>> = [];
|
|
319
|
+
for (const e of (await d.store.exportPlan(l.planId)).events) {
|
|
320
|
+
if (e.type === "metric" && e.metric.name === "counter" && e.metric.key === "child-process") records.push(e.metric.labels);
|
|
321
|
+
}
|
|
322
|
+
return records;
|
|
323
|
+
} catch (e) {
|
|
324
|
+
d.log("warn", "recovery: launcher history unavailable; treating the child as unknown", {
|
|
325
|
+
planId: l.planId, error: e instanceof Error ? e.message : String(e),
|
|
326
|
+
});
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
})();
|
|
330
|
+
const records = await launchers;
|
|
331
|
+
if (records === null) return "unknown";
|
|
332
|
+
// Resumes reuse the attempt/nonce/child. Only the current durable resume round can prove launcher death;
|
|
333
|
+
// an older process's evidence must not mark a child resumed by this process as inactive.
|
|
334
|
+
const matches = records.filter((r) => r.taskId === t.id && r.n === String(a.n) && r.nonce === a.nonce && r.child === child
|
|
335
|
+
&& (r.resumes === undefined ? (a.resumes ?? 0) === 0 : r.resumes === String(a.resumes ?? 0)));
|
|
336
|
+
if (matches.length !== 1) return "unknown";
|
|
337
|
+
const r = matches[0]!;
|
|
338
|
+
// Malformed or ambiguous history is not proof of death.
|
|
339
|
+
if (r.hostname !== dep.self.hostname || typeof r.pid !== "string" || !/^[1-9]\d*$/.test(r.pid)
|
|
340
|
+
|| typeof r.token !== "string" || r.token === "") return "unknown";
|
|
341
|
+
const pid = Number(r.pid);
|
|
342
|
+
if (!Number.isSafeInteger(pid)) return "unknown";
|
|
343
|
+
const dead = pid === dep.self.pid ? r.token !== dep.self.token : !dep.isAlive(pid);
|
|
344
|
+
if (!dead) return "unknown";
|
|
345
|
+
d.log("info", "recovery: child launcher is dead; treating the child as inactive", { taskId: t.id, n: a.n, pid });
|
|
346
|
+
return "inactive";
|
|
347
|
+
};
|
|
348
|
+
const out: ReconcileFeed[] = [];
|
|
349
|
+
for (const id of Object.keys(l.tasks).sort()) {
|
|
350
|
+
const t = l.tasks[id];
|
|
351
|
+
if (t === undefined) continue;
|
|
352
|
+
const f = await reconcileTask(l, t, tracked, launcherActivity);
|
|
353
|
+
if (f !== null) out.push(f);
|
|
354
|
+
}
|
|
355
|
+
return out;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
async function recover(): Promise<Array<{ planId: PlanId; actions: ReconcileAction[] }>> {
|
|
359
|
+
if (recovered) return [];
|
|
360
|
+
recovered = true;
|
|
361
|
+
const out: Array<{ planId: PlanId; actions: ReconcileAction[] }> = [];
|
|
362
|
+
for (const e of await d.store.list()) {
|
|
363
|
+
if (e.status !== "running" && e.status !== "paused") continue;
|
|
364
|
+
if (!sameToplevel(e.toplevel, d.toplevel)) continue;
|
|
365
|
+
try {
|
|
366
|
+
const l = await d.store.read(e.planId);
|
|
367
|
+
if (l.status !== "running" && l.status !== "paused") continue;
|
|
368
|
+
if (!sameToplevel(l.repo.toplevel, d.toplevel)) continue;
|
|
369
|
+
out.push({ planId: e.planId, actions: await reconcile(l, new Set<string>()) });
|
|
370
|
+
} catch (err) {
|
|
371
|
+
d.log("warn", "recovery: plan skipped", {
|
|
372
|
+
planId: e.planId, error: err instanceof Error ? err.message : String(err),
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
return out;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function adopt(planId: PlanId, sessionID: string): Promise<void> {
|
|
380
|
+
const l = await d.store.read(planId);
|
|
381
|
+
if (!sameToplevel(l.repo.toplevel, d.toplevel)) {
|
|
382
|
+
throw new ExecutorError("E_PLAN_STATE", "plan belongs to another repository", { planId, toplevel: l.repo.toplevel });
|
|
383
|
+
}
|
|
384
|
+
if (TERMINAL.has(l.status)) {
|
|
385
|
+
throw new ExecutorError("E_PLAN_STATE", `plan is ${l.status}`, { planId, status: l.status });
|
|
386
|
+
}
|
|
387
|
+
const holder = d.holder(sessionID);
|
|
388
|
+
let writer;
|
|
389
|
+
try {
|
|
390
|
+
writer = await d.store.open(planId, holder);
|
|
391
|
+
} catch (e) {
|
|
392
|
+
if (!isLockHeld(e)) throw e;
|
|
393
|
+
writer = await d.store.takeover(planId, holder, ADOPT_TAKEOVER_REASON);
|
|
394
|
+
}
|
|
395
|
+
try {
|
|
396
|
+
await writer.append([{ type: "orchestrator-bound", sessionID, reason: "adopt" }]);
|
|
397
|
+
} finally {
|
|
398
|
+
await writer.close();
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
return { recover, adopt, reconcile };
|
|
403
|
+
}
|