@henryqw/pi-subagent 30.1.0 → 31.1.0

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 (41) hide show
  1. package/CONTEXT.md +2 -2
  2. package/README.md +19 -23
  3. package/dist/direct-herdr.d.ts +5 -0
  4. package/dist/direct-herdr.js +9 -1
  5. package/dist/ephemeral.d.ts +9 -3
  6. package/dist/ephemeral.js +70 -11
  7. package/dist/herdr-runtime.js +4 -0
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/native-host.d.ts +96 -0
  11. package/dist/native-host.js +243 -0
  12. package/dist/runner.d.ts +8 -1
  13. package/dist/runner.js +22 -15
  14. package/dist/schema.d.ts +71 -2
  15. package/dist/schema.js +14 -1
  16. package/dist/workspace-schema.d.ts +11 -0
  17. package/dist/workspace.d.ts +5 -2
  18. package/dist/workspace.js +58 -29
  19. package/docs/measurement.md +12 -1
  20. package/docs/orchestration-architecture.html +4 -4
  21. package/docs/orchestration-architecture.svg +2 -2
  22. package/docs/orchestration.md +72 -259
  23. package/docs/workspace.md +4 -80
  24. package/extensions/admission.ts +36 -11
  25. package/extensions/direct-check-exec.py +91 -0
  26. package/extensions/direct-check-supervisor.mjs +42 -0
  27. package/extensions/direct-check-witness.mjs +34 -0
  28. package/extensions/direct-native.ts +17 -5
  29. package/extensions/direct-outbox.ts +189 -0
  30. package/extensions/direct-owner.ts +49 -0
  31. package/extensions/direct-verification.ts +73 -0
  32. package/extensions/isolated.ts +25 -301
  33. package/extensions/prerequisite-evidence.ts +81 -0
  34. package/extensions/result-transport.ts +6 -4
  35. package/extensions/subagent-command.ts +12 -7
  36. package/extensions/subagent.ts +378 -499
  37. package/extensions/workflow-recovery.ts +359 -0
  38. package/extensions/workflow.ts +156 -40
  39. package/extensions/workspace.ts +16 -74
  40. package/package.json +2 -2
  41. package/skills/pi-subagent/SKILL.md +15 -37
@@ -0,0 +1,359 @@
1
+ import { claimOwner, ownerAlive } from "./direct-owner.ts";
2
+ import { Check } from "typebox/value";
3
+ import { ExecutionPolicySnapshotSchema, type ExecutionPolicySnapshot } from "../dist/schema.js";
4
+ import { prerequisitePacket, answerReference, expandChainTask, type AnswerReference } from "./prerequisite-evidence.ts";
5
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { hostname } from "node:os";
7
+ import { join } from "node:path";
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import { completionDetails, DIRECT_OUTBOX_ANCHOR, DIRECT_RESULT_TYPE, type DirectCompletion } from "./direct-outbox.ts";
11
+ import { utf8Prefix } from "../dist/ephemeral.js";
12
+ import { isDependencyGraph, parseWorkflow, type ParsedWorkflow } from "./workflow.ts";
13
+ import { formatWorkflowResult, workerOutputForMain, type WorkflowTransportEntry } from "./result-transport.ts";
14
+
15
+ const LIMIT = 1024 * 1024;
16
+ const JOURNAL_FILE_LIMIT = 2 * LIMIT + 128;
17
+ const INPUT_LIMIT = 64 * 1024;
18
+ const TEXT_LIMIT = 4096;
19
+ const ID = /^direct-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
20
+ const MARKER = /\n\n\[subagent-recovery (direct-[0-9a-f-]+) ([0-7])\]$/;
21
+ const INTENT = "subagent-workflow-recovery";
22
+
23
+ type Scope = { sessionId: string; sessionFile: string; anchor: string; originEntry?: string };
24
+ type Step = {
25
+ state: "pending" | "started" | "succeeded" | "failed";
26
+ output?: string;
27
+ complete?: boolean;
28
+ answerFile?: string;
29
+ fullAnswer?: AnswerReference;
30
+ turns: Array<{ phase: "worker" | "correction"; output: string; complete: boolean }>;
31
+ checks: Array<{ phase: string; state: "started" | "finished"; code?: number; output?: string }>;
32
+ };
33
+ type Journal = { version: 1; taskId: string; scope: Scope; cwd: string; owner: { host: string; pid: number }; workflow: ParsedWorkflow; policy?: ExecutionPolicySnapshot; steps: Step[]; stopped: boolean };
34
+
35
+ const dir = (file: string) => `${file}.subagent-recovery`;
36
+ const pathFor = (file: string, id: string) => join(dir(file), `${id}.json`);
37
+ const bytes = (s: string) => Buffer.byteLength(s);
38
+ const bounded = (s: string, n = TEXT_LIMIT) => utf8Prefix(s, n);
39
+ const digest = (j: Journal) => createHash("sha256").update(JSON.stringify(j)).digest("hex");
40
+
41
+ function save(path: string, value: Journal, previous: Journal | undefined) {
42
+ if (bytes(JSON.stringify(value)) > LIMIT) throw new Error("Recovery journal exceeds its size limit.");
43
+ const data = JSON.stringify({ ...value, previous });
44
+ if (bytes(data) > JOURNAL_FILE_LIMIT) throw new Error("Recovery journal exceeds its size limit.");
45
+ mkdirSync(dir(value.scope.sessionFile), { recursive: true, mode: 0o700 });
46
+ const temp = join(dir(value.scope.sessionFile), `.${randomUUID()}.tmp`);
47
+ let fd: number | undefined;
48
+ try {
49
+ fd = openSync(temp, "wx", 0o600);
50
+ writeFileSync(fd, data);
51
+ fsyncSync(fd);
52
+ closeSync(fd);
53
+ fd = undefined;
54
+ renameSync(temp, path);
55
+ const parent = openSync(dir(value.scope.sessionFile), "r");
56
+ try { fsyncSync(parent); } finally { closeSync(parent); }
57
+ } finally {
58
+ if (fd !== undefined) closeSync(fd);
59
+ if (existsSync(temp)) unlinkSync(temp);
60
+ }
61
+ }
62
+
63
+ function input(workflow: ParsedWorkflow) {
64
+ const common = workflow.repositories ? { repositories: workflow.repositories } : {};
65
+ return workflow.mode === "single"
66
+ ? { mode: "direct", ...common, ...workflow.delegations[0] }
67
+ : { mode: "direct", ...common, [workflow.mode === "chain" ? "chain" : "tasks"]: workflow.delegations };
68
+ }
69
+
70
+ function validStep(step: Step): boolean {
71
+ if (!step || !["pending", "started", "succeeded", "failed"].includes(step.state)) return false;
72
+ if (step.output !== undefined && (typeof step.output !== "string" || bytes(step.output) > TEXT_LIMIT + 3)) return false;
73
+ if (step.fullAnswer && (step.fullAnswer.path !== step.answerFile || !/^[a-f0-9]{64}$/.test(step.fullAnswer.sha256) || !Number.isSafeInteger(step.fullAnswer.bytes) || step.fullAnswer.bytes < 0)) return false;
74
+ if (step.complete !== undefined && typeof step.complete !== "boolean") return false;
75
+ if (step.answerFile !== undefined && (typeof step.answerFile !== "string" || bytes(step.answerFile) > TEXT_LIMIT)) return false;
76
+ if (!Array.isArray(step.turns) || step.turns.length > 2 || !Array.isArray(step.checks) || step.checks.length > 8) return false;
77
+ if (step.turns.some((turn) => !turn
78
+ || !["worker", "correction"].includes(turn.phase)
79
+ || typeof turn.output !== "string"
80
+ || bytes(turn.output) > TEXT_LIMIT + 3
81
+ || typeof turn.complete !== "boolean")) return false;
82
+ return !step.checks.some((check) => !check || typeof check.phase !== "string" || check.phase.length > 30
83
+ || !["started", "finished"].includes(check.state)
84
+ || (check.code !== undefined && !Number.isSafeInteger(check.code))
85
+ || (check.output !== undefined && (typeof check.output !== "string" || bytes(check.output) > TEXT_LIMIT + 3)));
86
+ }
87
+
88
+ function load(file: string, id: string, expected: unknown): Journal {
89
+ if (!ID.test(id)) throw new Error("Invalid recovery identity.");
90
+ const path = pathFor(file, id);
91
+ if (statSync(path).size > JOURNAL_FILE_LIMIT) throw new Error("Recovery journal is too large.");
92
+ const saved = JSON.parse(readFileSync(path, "utf8"));
93
+ if (!saved || typeof saved !== "object" || Array.isArray(saved)) throw new Error("Invalid recovery journal.");
94
+ const { previous, ...current } = saved;
95
+ const candidates: unknown[] = [current, previous];
96
+ const j = candidates.find((candidate) => candidate && typeof candidate === "object" && digest(candidate as Journal) === expected) as Journal | undefined;
97
+ if (!j) throw new Error("Recovery state does not match the saved branch; no work was dispatched.");
98
+ if (bytes(JSON.stringify(j)) > LIMIT) throw new Error("Recovery journal is too large.");
99
+ if (!j || j.version !== 1 || j.taskId !== id || !j.scope || j.scope.sessionFile !== file
100
+ || typeof j.scope.sessionId !== "string" || typeof j.scope.anchor !== "string" || typeof j.cwd !== "string"
101
+ || !j.owner || typeof j.owner.host !== "string" || !Number.isSafeInteger(j.owner.pid) || j.owner.pid < 1
102
+ || typeof j.stopped !== "boolean" || !j.workflow || !Array.isArray(j.workflow.delegations) || !Array.isArray(j.steps)) {
103
+ throw new Error("Invalid recovery journal.");
104
+ }
105
+ if (j.policy !== undefined && !Check(ExecutionPolicySnapshotSchema, j.policy)) throw new Error("Invalid saved workflow policy.");
106
+ const parsed = parseWorkflow(input(j.workflow));
107
+ if (JSON.stringify(parsed) !== JSON.stringify(j.workflow) || j.steps.length !== parsed.delegations.length || j.steps.some((step) => !validStep(step))) {
108
+ throw new Error("Invalid recovery state.");
109
+ }
110
+ return j;
111
+ }
112
+
113
+ function eligible(j: Journal) {
114
+ if (j.steps.some((s, i) => (s.state === "started" || s.state === "failed") && j.workflow.delegations[i]!.access === "write")) return [];
115
+ const graph = isDependencyGraph(j.workflow);
116
+ return j.workflow.delegations.flatMap((d, i) => {
117
+ if (d.access !== "read" || j.steps[i]!.state !== "pending" || d.continueFrom) return [];
118
+ const earlierIncomplete = j.steps.slice(0, i).some((step) => step.state !== "succeeded");
119
+ if (!graph && j.workflow.mode === "parallel"
120
+ && j.workflow.delegations.some((item) => item.access === "write") && earlierIncomplete) return [];
121
+ let task = d.task;
122
+ let references: (AnswerReference | undefined)[] = [];
123
+ if (j.workflow.mode === "chain" && i > 0) {
124
+ const prior = j.steps[i - 1]!;
125
+ if (prior.state !== "succeeded" || (task.includes("{previous}") && !prior.complete && !prior.fullAnswer)) return [];
126
+ // Keep the compact template in the recovery packet. Expand it only for the child.
127
+ }
128
+ if (graph) {
129
+ const deps = (d.dependsOn ?? []).map((name) => ({ name, index: j.workflow.delegations.findIndex((item) => item.name === name) }));
130
+ if (deps.some(({ index }) => index < 0 || j.steps[index]!.state !== "succeeded")) return [];
131
+ ({ task, references } = prerequisitePacket(task, deps.map(({ name, index }) => {
132
+ const step = j.steps[index]!;
133
+ return { name, output: step.output ?? "", complete: step.complete === true, fullAnswer: step.fullAnswer };
134
+ })));
135
+ }
136
+ const { dependsOn: _dependsOn, ...packet } = d;
137
+ return [{
138
+ index: i, references,
139
+ packet: {
140
+ mode: "direct", ...packet, task: `${task}\n\n[subagent-recovery ${j.taskId} ${i}]`,
141
+ ...(j.workflow.repositories ? { repositories: j.workflow.repositories } : {}),
142
+ },
143
+ }];
144
+ });
145
+ }
146
+
147
+ function recoveredChainTask(template: string, prior?: Step): string {
148
+ if (prior && !prior.complete && template.includes("{previous}")) {
149
+ if (!prior.fullAnswer) throw new Error("The complete preceding chain answer is unavailable.");
150
+ return expandChainTask(template, prior.fullAnswer);
151
+ }
152
+ return expandChainTask(template, prior?.output ?? "");
153
+ }
154
+
155
+ function branchState(ctx: ExtensionContext, entries = ctx.sessionManager.getBranch()) {
156
+ const anchors = new Set<string>();
157
+ const delivered = new Set<string>();
158
+ const digests = new Map<string, unknown>();
159
+ for (const entry of entries) {
160
+ if (entry.type === "custom" && entry.customType === DIRECT_OUTBOX_ANCHOR) anchors.add(entry.id);
161
+ if (entry.type === "custom" && entry.customType === INTENT) {
162
+ const data = entry.data as { taskId?: unknown; digest?: unknown } | undefined;
163
+ if (typeof data?.taskId === "string" && ID.test(data.taskId)) digests.set(data.taskId, data.digest);
164
+ }
165
+ if (entry.type === "custom_message" && entry.customType === DIRECT_RESULT_TYPE) {
166
+ for (const detail of completionDetails(entry.details)) delivered.add(detail.taskId);
167
+ }
168
+ }
169
+ return { anchors, delivered, digests };
170
+ }
171
+
172
+ export function createWorkflowRecovery(report: (message: string) => void) {
173
+ const automaticAttempts = new Set<string>();
174
+ const token = randomUUID();
175
+ return {
176
+ begin(scope: Scope, cwd: string, taskId: string, workflow: ParsedWorkflow, record: (type: string, data: unknown) => void, resumedRead = false, policy?: ExecutionPolicySnapshot) {
177
+ const j: Journal = {
178
+ version: 1, taskId, scope, cwd, owner: { host: hostname(), pid: process.pid }, workflow, ...(policy ? { policy } : {}),
179
+ steps: workflow.delegations.map(() => ({ state: resumedRead ? "started" : "pending", turns: [], checks: [] })), stopped: false,
180
+ };
181
+ // A validated resumed single read already includes its recovery marker and prerequisite evidence.
182
+ if (bytes(JSON.stringify(j)) > (resumedRead ? LIMIT - INPUT_LIMIT : INPUT_LIMIT)) throw new Error("Background workflow exceeds the recovery input limit.");
183
+ let committed: Journal | undefined;
184
+ let failed = false;
185
+ let publishing = false;
186
+ let stopPending = false;
187
+ const persist = () => {
188
+ if (failed || publishing) throw new Error("Recovery journal publication failed or is already in progress; workflow cannot continue.");
189
+ publishing = true;
190
+ try {
191
+ const snapshot = structuredClone(j);
192
+ save(pathFor(scope.sessionFile, taskId), snapshot, committed);
193
+ record(INTENT, { taskId, digest: digest(snapshot) });
194
+ committed = snapshot;
195
+ } catch (error) { failed = true; throw error; }
196
+ finally { publishing = false; }
197
+ if (stopPending) { stopPending = false; persist(); }
198
+ };
199
+ persist();
200
+ return {
201
+ start(index: number, phase: string) {
202
+ if (phase === "worker") j.steps[index]!.state = "started";
203
+ else j.steps[index]!.checks.push({ phase, state: "started" });
204
+ persist();
205
+ },
206
+ evidence(index: number, phase: "worker" | "correction", output: string) {
207
+ j.steps[index]!.turns.push({ phase, output: bounded(output), complete: bytes(output) <= TEXT_LIMIT });
208
+ persist();
209
+ },
210
+ check(index: number, code: number, output: string) {
211
+ const check = j.steps[index]!.checks.at(-1)!;
212
+ check.state = "finished";
213
+ check.code = code;
214
+ check.output = bounded(output);
215
+ persist();
216
+ },
217
+ finish(index: number, success: boolean, output: string, answerFile?: string) {
218
+ const step = j.steps[index]!;
219
+ step.state = success ? "succeeded" : "failed";
220
+ step.output = bounded(output);
221
+ step.complete = bytes(output) <= TEXT_LIMIT;
222
+ if (answerFile !== undefined) { step.answerFile = answerFile; step.fullAnswer = answerReference(answerFile, output); }
223
+ persist();
224
+ },
225
+ stop() {
226
+ j.stopped = true;
227
+ if (publishing) { stopPending = true; return; }
228
+ persist();
229
+ },
230
+ };
231
+ },
232
+ /** Resume only validated, unstarted reads. The original outbox receipt owns the final result. */
233
+ automatic(ctx: ExtensionContext, dispatch: (packet: unknown, options: { requireSuccess: boolean; answerBytes: number }) => Promise<WorkflowTransportEntry>, complete: (scope: Scope, result: DirectCompletion) => void, record: (type: string, data: unknown) => void, inScope: () => boolean = () => true) {
234
+ const file = ctx.sessionManager.getSessionFile();
235
+ if (!file || !existsSync(dir(file))) return Promise.resolve();
236
+ const jobs: Promise<void>[] = [];
237
+ const branch = branchState(ctx);
238
+ if (!branch.digests.size) return Promise.resolve();
239
+ const session = branchState(ctx, ctx.sessionManager.getEntries());
240
+ for (const [id, expected] of branch.digests) {
241
+ const attempt = `${file}\0${id}`;
242
+ if (branch.delivered.has(id) || automaticAttempts.has(attempt) || existsSync(join(`${file}.subagent-outbox`, `${id}.json`))) continue;
243
+ try {
244
+ if (session.digests.get(id) !== expected) continue;
245
+ const j = load(file, id, expected);
246
+ if (j.scope.sessionId !== ctx.sessionManager.getSessionId() || j.cwd !== ctx.cwd || !branch.anchors.has(j.scope.anchor) || j.stopped || ownerAlive(j.owner)) continue;
247
+ if (!claimOwner(dir(file), `${id}.handoff`, token)) continue;
248
+ if (existsSync(join(`${file}.subagent-outbox`, `${id}.json`))) continue;
249
+ automaticAttempts.add(attempt);
250
+ const launchBranch = ctx.sessionManager.getBranch().map(({ id }) => id);
251
+ jobs.push((async () => {
252
+ let committed = structuredClone(j);
253
+ const recovered = new Map<number, WorkflowTransportEntry>();
254
+ const share = Math.floor(TEXT_LIMIT / j.steps.length);
255
+ let scopeChanged = false;
256
+ let publicationError: unknown;
257
+ const current = () => {
258
+ const entries = ctx.sessionManager.getBranch();
259
+ const state = branchState(ctx, entries);
260
+ return inScope() && ctx.sessionManager.getSessionFile() === file && ctx.sessionManager.getSessionId() === j.scope.sessionId
261
+ && launchBranch.every((entry, index) => entries[index]?.id === entry)
262
+ && ctx.cwd === j.cwd && state.anchors.has(j.scope.anchor) && !state.delivered.has(id) && state.digests.get(id) === digest(committed);
263
+ };
264
+ const persist = () => {
265
+ if (!current()) { scopeChanged = true; return false; }
266
+ const snapshot = structuredClone(j);
267
+ save(pathFor(file, id), snapshot, committed);
268
+ record(INTENT, { taskId: id, digest: digest(snapshot) });
269
+ committed = snapshot;
270
+ return true;
271
+ };
272
+ try {
273
+ while (current()) {
274
+ const packets = eligible(j);
275
+ if (!packets.length) break;
276
+ // An existing claim has uncertain execution state, even if its owner died.
277
+ for (const packet of packets) if (existsSync(join(dir(file), `${id}.${packet.index}.claimed`))) j.steps[packet.index]!.state = "started";
278
+ const available = packets.filter(({ index }) => j.steps[index]!.state === "pending");
279
+ if (!available.length) break;
280
+ await Promise.all(available.map(async ({ index, packet }) => {
281
+ let entry: WorkflowTransportEntry;
282
+ try { entry = await dispatch(packet, { requireSuccess: isDependencyGraph(j.workflow) || j.workflow.delegations.some((d) => d.access === "write"), answerBytes: share }); }
283
+ catch (error) { entry = { id: `${id}:${index}`, index, name: j.workflow.delegations[index]!.name, role: j.workflow.delegations[index]!.role, status: "rejected", failure: String(error) }; }
284
+ recovered.set(index, entry.assistantOutput ? { ...entry, assistantOutput: bounded(entry.assistantOutput, share) } : entry);
285
+ const step = j.steps[index]!;
286
+ const text = entry.assistantOutput ?? entry.failure ?? "";
287
+ step.state = entry.status === "succeeded" ? "succeeded" : "failed";
288
+ step.output = bounded(text);
289
+ step.complete = bytes(text) <= TEXT_LIMIT;
290
+ if (entry.answerFile !== undefined) { step.answerFile = entry.answerFile; step.fullAnswer = answerReference(entry.answerFile, text); }
291
+ try { if (!publicationError) persist(); } catch (error) { publicationError = error; }
292
+ }));
293
+ if (scopeChanged || publicationError) break;
294
+ }
295
+ if (!current()) scopeChanged = true;
296
+ const uncertain = Boolean(publicationError) || scopeChanged || j.steps.some((step) => step.state === "started") || j.workflow.delegations.some((d) => d.access === "write");
297
+ const entries: WorkflowTransportEntry[] = j.workflow.delegations.map((d, index) => {
298
+ const step = j.steps[index]!;
299
+ const prior = recovered.get(index);
300
+ return { ...prior, id: `${id}:${index}`, index, name: d.name, role: d.role,
301
+ status: step.state === "succeeded" ? "succeeded" : step.state === "failed" || step.state === "started" ? "rejected" : "skipped",
302
+ ...(prior ? {} : step.state === "succeeded" ? { assistantOutput: bounded(step.output ?? "", share), ...(step.answerFile ? { answerFile: step.answerFile } : {}) } : { failure: step.state === "started" ? "Interrupted worker or check; termination is unproved and it was not replayed." : step.output ?? "No eligible unstarted read; inspect prerequisite and admission evidence." }) };
303
+ });
304
+ const formatted = formatWorkflowResult(j.workflow.mode, entries);
305
+ const blocked = j.steps.some((step) => step.state === "pending") ? "Some steps remain unstarted: their prerequisites, saved answer completeness, or writer admission do not permit automatic dispatch. Inspect the journal.\n" : "";
306
+ const content = `${workerOutputForMain(formatted.text)}\n${uncertain ? "Recovery requires inspection: interrupted workers or writer admission may remain active. Do not replay uncertain work.\n" : ""}${scopeChanged ? "The session branch changed during recovery; remaining reads were not dispatched.\n" : ""}${publicationError ? `Recovery journal publication failed: ${String(publicationError)}. Remaining reads were not dispatched.\n` : ""}${blocked}Local recovery journal: ${pathFor(file, id)}`;
307
+ complete({ ...j.scope, originEntry: launchBranch.at(-1) }, { customType: DIRECT_RESULT_TYPE, content, display: true, details: { ...formatted.details, taskId: id, outcome: formatted.failed || scopeChanged || publicationError ? "failed" : "completed", ...(uncertain ? { recovery: true as const } : {}) } });
308
+ } catch (error) { report(`Workflow recovery ${id}.json: ${String(error)}`); }
309
+ finally { automaticAttempts.delete(attempt); }
310
+ })());
311
+ } catch (error) { report(`Workflow recovery ${id}.json: ${String(error)}`); }
312
+ }
313
+ return Promise.all(jobs).then(() => undefined);
314
+ },
315
+ claim(ctx: ExtensionContext, workflow: ParsedWorkflow): { task: () => string; commit: () => void; policy?: ExecutionPolicySnapshot; uncertainWorkers: number; references: (AnswerReference | undefined)[] } | undefined {
316
+ for (const d of workflow.delegations) {
317
+ const match = MARKER.exec(d.task);
318
+ if (!match) continue;
319
+ const file = ctx.sessionManager.getSessionFile();
320
+ if (!file || workflow.mode !== "single") throw new Error("Recovery packets require a saved session and a single task.");
321
+ const { anchors, digests } = branchState(ctx);
322
+ const session = branchState(ctx, ctx.sessionManager.getEntries());
323
+ if (session.digests.get(match[1]!) !== digests.get(match[1]!)) throw new Error("Invalid or ineligible recovery packet on an earlier session branch.");
324
+ const j = load(file, match[1]!, digests.get(match[1]!));
325
+ const packet = eligible(j).find((item) => item.index === Number(match[2]));
326
+ if (j.stopped || digests.get(j.taskId) !== digest(j) || ownerAlive(j.owner)
327
+ || !existsSync(join(dir(file), `${j.taskId}.handoff`)) || j.cwd !== ctx.cwd
328
+ || j.scope.sessionId !== ctx.sessionManager.getSessionId() || !anchors.has(j.scope.anchor)
329
+ || !packet || JSON.stringify(parseWorkflow(packet.packet)) !== JSON.stringify(workflow)) {
330
+ throw new Error("Invalid or ineligible recovery packet.");
331
+ }
332
+ const target = join(dir(file), `${j.taskId}.${packet.index}.claimed`);
333
+ if (existsSync(target)) throw new Error("Recovery packet was already claimed; do not repeat it.");
334
+ const commit = () => {
335
+ // Revalidate after asynchronous preflight, then atomically exclude other claimants.
336
+ this.claim(ctx, workflow);
337
+ try {
338
+ mkdirSync(target, { mode: 0o700 });
339
+ const parent = openSync(dir(file), "r");
340
+ try { fsyncSync(parent); } finally { closeSync(parent); }
341
+ } catch (error) {
342
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") throw new Error("Recovery packet was already claimed; do not repeat it.");
343
+ throw error;
344
+ }
345
+ };
346
+ let uncertainWorkers = 0;
347
+ for (const [id, expected] of session.digests) {
348
+ const other = id === j.taskId ? j : load(file, id, expected);
349
+ if (other.scope.sessionId !== j.scope.sessionId || other.owner.pid === process.pid && other.owner.host === hostname()) continue;
350
+ uncertainWorkers += other.steps.filter((step, index) => step.state === "started"
351
+ || (step.state === "pending" && existsSync(join(dir(file), `${id}.${index}.claimed`)))).length;
352
+ }
353
+ return { commit, policy: j.policy, uncertainWorkers, references: packet.references, task: () => j.workflow.mode === "chain"
354
+ ? recoveredChainTask(j.workflow.delegations[packet.index]!.task, j.steps[packet.index - 1])
355
+ : d.task };
356
+ }
357
+ },
358
+ };
359
+ }