pi-durable-subagents 1.0.41 → 1.0.42

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.
@@ -16,7 +16,7 @@ import { delimiter, dirname, join } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { CT, JT, attentionEntries, isEntry } from "../../types.js";
18
18
  import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
19
- import { readJournalSnapshot } from "../../kernel/journal.js";
19
+ import { readJournalSnapshot, syncDirectory } from "../../kernel/journal.js";
20
20
  import { Outbox } from "../../kernel/mailbox.js";
21
21
  import { contentHash, forwardRid } from "../../kernel/ids.js";
22
22
  import { capacity, seal } from "../../kernel/guards.js";
@@ -30,11 +30,12 @@ import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./dige
30
30
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
31
31
  import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.js";
32
32
  import { activeTotal } from "./time.js";
33
- import { entriesOf, trackedState, usageIds } from "./indexes.js";
33
+ import { callEntries, entriesOf, forwardsTo, trackedState, usageIds } from "./indexes.js";
34
+ import { RECOVERED, RECOVERY_VERSION, completeCalls } from "./recovered.js";
34
35
  import { observeExecution } from "./observe.js";
35
36
  import { availableMemory } from "./memory.js";
36
37
  import { reached, sessionUsage, totalUsage } from "./usage.js";
37
- import { indexSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
38
+ import { indexSweep, seededSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
38
39
  import { gateRetired } from "./effects/gate.js";
39
40
  import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
40
41
  import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
@@ -49,9 +50,10 @@ const ignoreMissing = (error) => { if (error.code !== "ENOENT")
49
50
  const callOf = (exec) => exec.slice(0, exec.lastIndexOf("#"));
50
51
  const shutdownError = () => Object.assign(new Error("executor shutdown; call resumes on recovery"), { name: "ExecutorShutdown" });
51
52
  const extension = fileURLToPath(new URL(`../../agent/extension.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url));
52
- const entriesFor = (journal, call) => journal.entries().filter(e => e.call === call);
53
+ const entriesFor = callEntries;
53
54
  const current = (journal, call) => entriesFor(journal, call).findLast(e => e.type === JT.exec)?.exec;
54
55
  const sealed = (journal, call) => entriesFor(journal, call).find(e => e.type === JT.sealed)?.result;
56
+ const retiredCall = (journal, call) => entriesFor(journal, call).some(e => e.type === "retired");
55
57
  const has = (journal, type, exec) => entriesOf(journal, type, exec).length > 0;
56
58
  /** The run of executions of `call` whose launches failed for a reason of the environment, ending at `exec`: its first
57
59
  * execution and the one before it (absent for the call's first). Undefined when `exec` did not fail so. */
@@ -100,6 +102,7 @@ export function requestedModel(journal, call, followUp) {
100
102
  }
101
103
  return wanted;
102
104
  }
105
+ const callWid = (call) => /^(.*)@\d+\/.*@\d+$/.exec(call)?.[1];
103
106
  function address(call) {
104
107
  const match = /^(.*)@(\d+)\/(.*)@(\d+)$/.exec(call);
105
108
  if (!match)
@@ -152,9 +155,11 @@ export default function createExecutor(ledgers, options = {}) {
152
155
  // F1: execs whose fence failed in this process; they are retried only by the sweep.
153
156
  const failing = new Set();
154
157
  // F2: a sweep error is transient: report it and retry at the next K1; it never blocks dispatch.
158
+ /** The sweep state of settled journals not decoded (recover with `settled`). */
159
+ const seeds = new WeakMap();
155
160
  const sweepTimer = setInterval(() => {
156
161
  if (!sweeping)
157
- sweeping = sweepExecutions([...journals.values()].filter(j => !j.closed), containment, { failing: exec => failing.has(exec), fenced: swept, failed: fenceFailed })
162
+ sweeping = sweepExecutions([...journals.values()].filter(j => !j.closed), containment, { failing: exec => failing.has(exec), fenced: swept, failed: fenceFailed, seeded: journal => seeds.get(journal) })
158
163
  .catch(error => console.error(`durable-subagents: sweep failed, retrying in K1: ${String(error)}`)).finally(() => { sweeping = undefined; });
159
164
  }, options.sweepMs ?? 30000);
160
165
  sweepTimer.unref();
@@ -346,13 +351,37 @@ export default function createExecutor(ledgers, options = {}) {
346
351
  done.add(rid);
347
352
  }
348
353
  }
354
+ /** Remove a sealed call's inbox files, then sync the directory: the removals are durable before anything recorded
355
+ * after them (a `recovered` receipt). The directory is synced whenever it exists, also when it is already empty (an
356
+ * earlier attempt may have removed the files and failed to sync); a failure rejects (the caller records no receipt). */
349
357
  async function collectSealed(call) {
350
358
  const sender = await outbox, dir = inbox(call);
351
- for (const name of await readdir(dir).catch(error => { ignoreMissing(error); return []; })) {
359
+ let exists = true;
360
+ for (const name of await readdir(dir).catch(error => { ignoreMissing(error); exists = false; return []; })) {
352
361
  if (name.endsWith(".json") && !name.startsWith("."))
353
362
  await sender.markResolved(name.slice(0, -5));
354
363
  await rm(join(dir, name), { force: true });
355
364
  }
365
+ if (exists)
366
+ await (options.syncDirectory ?? syncDirectory)(dir);
367
+ }
368
+ /** Sealed or retired calls a batched recovery read, finished by finishRecovery. */
369
+ const unfinished = [];
370
+ /** The end of the recovery of sealed or retired calls, after republication: the inbox cleanup of the sealed ones (E2),
371
+ * then each call's `recovered` receipt (recovered.ts), once. A failed cleanup records none: the next start recovers
372
+ * the call again. */
373
+ async function finishCalls(journal, calls) {
374
+ for (const call of calls) {
375
+ // F1: an execution whose fence failed is fenced again by every start (and the sweep) until it is: no receipt yet.
376
+ let clean = entriesFor(journal, call).every(e => e.type !== JT.exec || has(journal, JT.fenced, String(e.exec)));
377
+ if (clean && sealed(journal, call))
378
+ await collectSealed(call).catch(error => { clean = false; console.error(`durable-subagents: inbox cleanup of ${call} failed: ${String(error)}`); });
379
+ if (clean)
380
+ await serial(async () => {
381
+ if (!journal.closed && !completeCalls(journal, address(call).wid).has(call))
382
+ await journal.append(RECOVERED, { call, v: RECOVERY_VERSION });
383
+ });
384
+ }
356
385
  }
357
386
  /** P7, P27: Record forward-delivered once when a forward's child receipt is first observed; serial sections only. */
358
387
  /** The reply to a model send says which model and when it applies (orchestrator ledger `send-note`, once per rid). */
@@ -379,13 +408,13 @@ export default function createExecutor(ledgers, options = {}) {
379
408
  const entries = await readCall(journal, call);
380
409
  await forwardsDelivered(journal, call, entries);
381
410
  const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
382
- for (const e of journal.entries().filter(e => e.type === "forward" && e.dest === call)) {
383
- if (!receipts.has(String(e.rid2)) && !journal.entries().some(r => r.type === "forward-retired" && r.rid2 === e.rid2)) {
411
+ for (const e of [...forwardsTo(journal, call)]) {
412
+ if (!receipts.has(String(e.rid2)) && !entriesOf(journal, "forward-retired").some(r => r.rid2 === e.rid2)) {
384
413
  // A notify the call never received is not lost: it becomes a pending note (before its forward is retired, so a
385
414
  // crash in between finds the forward open again and the note is written once). A withdrawn one is not.
386
- const envelope = e.envelope, all = journal.entries();
387
- const withdrawn = all.some(r => r.type === "forward" && r.dest === call && r.envelope.kind === "withdraw" && r.envelope.body.rids?.includes(String(e.rid2)));
388
- if (envelope.kind === "notify" && !withdrawn && !all.some(r => r.type === PENDING_NOTE && r.rid === e.rid))
415
+ const envelope = e.envelope;
416
+ const withdrawn = forwardsTo(journal, call).some(r => r.envelope.kind === "withdraw" && r.envelope.body.rids?.includes(String(e.rid2)));
417
+ if (envelope.kind === "notify" && !withdrawn && !entriesOf(journal, PENDING_NOTE).some(r => r.rid === e.rid))
389
418
  await journal.append(PENDING_NOTE, { rid: e.rid, call, key: address(call).key, message: String(envelope.body?.message ?? "") });
390
419
  // A follow-up the call never took is not lost either: the orchestrator opens the next generation with it (or a
391
420
  // later follow-up takes it along). A stop is final and drops it; a withdrawn one is gone.
@@ -410,7 +439,9 @@ export default function createExecutor(ledgers, options = {}) {
410
439
  return hit;
411
440
  }
412
441
  const roots = worktreeRoots(), writes = new WorktreeIndex();
413
- const indexed = () => writes.scan(journals.values());
442
+ // A journal not decoded (a settled workflow) has no open reminder and only ended calls: nothing of it is indexed.
443
+ const indexed = () => writes.scan([...journals.values()].filter(j => j.loaded !== false));
444
+ const endedCall = (call) => writes.ended(call) || journals.get(callWid(call) ?? "")?.loaded === false;
414
445
  const origin = (w) => writes.origin(w.journal) ?? orch.entries().find(e => e.type === JT.created && e.wid === address(w.call).wid)?.origin;
415
446
  // Serial sections only: wrote and attention are durable before another writer or seal can interleave.
416
447
  /** Remind of every pair of calls that wrote in `root` and have not ended, once per pair and journal. The index must be
@@ -451,7 +482,7 @@ export default function createExecutor(ledgers, options = {}) {
451
482
  async function resolveWorktrees(call) {
452
483
  for (const { id, journal, item } of indexed().open()) {
453
484
  const pair = worktreeCalls(id);
454
- if (call ? pair.includes(call) : pair.some(c => writes.ended(c)))
485
+ if (call ? pair.includes(call) : pair.some(endedCall))
455
486
  await journal.append(JT.attentionResolved, { id, rev: item.rev, resolution: "ended" });
456
487
  }
457
488
  }
@@ -474,7 +505,8 @@ export default function createExecutor(ledgers, options = {}) {
474
505
  }
475
506
  async function finish(journal, call, exec, result) {
476
507
  const a = active.get(call);
477
- if (a && !sealed(journal, call) && !["stopped", "timeout", "budget"].includes(result.status)) {
508
+ // A refused call (CallTicket.refusal) runs none of the pre-seal effects (gate, output publication): it did no work.
509
+ if (a && a.ticket.refusal === undefined && !sealed(journal, call) && !["stopped", "timeout", "budget"].includes(result.status)) {
478
510
  const started = Date.now(), prior = activeTotal(journal.entries(), call);
479
511
  const check = async () => {
480
512
  if (stopped(a))
@@ -1136,16 +1168,22 @@ export default function createExecutor(ledgers, options = {}) {
1136
1168
  await effects.afterSeal(t, result);
1137
1169
  return result;
1138
1170
  }
1139
- try {
1140
- await continueSession(home, t, session);
1141
- cwd = (await effects.prepare(t, { sessionPath: session })).cwd;
1142
- }
1143
- catch (error) {
1171
+ // A call that cannot run (CallTicket.refusal) or whose preparation failed is sealed failed without a child.
1172
+ let unprepared = t.refusal;
1173
+ if (unprepared === undefined)
1174
+ try {
1175
+ await continueSession(home, t, session);
1176
+ cwd = (await effects.prepare(t, { sessionPath: session })).cwd;
1177
+ }
1178
+ catch (error) {
1179
+ unprepared = String(error);
1180
+ }
1181
+ if (unprepared !== undefined) {
1144
1182
  const exec = current(journal, t.callId) ?? `${t.callId}#1.1`;
1145
1183
  if (!current(journal, t.callId))
1146
1184
  await serial(() => journal.append(JT.exec, { call: t.callId, exec }));
1147
1185
  await fence(journal, exec, { park: a });
1148
- return finish(journal, t.callId, exec, makeResult("failed", "", String(error)));
1186
+ return finish(journal, t.callId, exec, makeResult("failed", "", unprepared));
1149
1187
  }
1150
1188
  for (;;) {
1151
1189
  const old = sealed(journal, t.callId);
@@ -1792,39 +1830,52 @@ export default function createExecutor(ledgers, options = {}) {
1792
1830
  }
1793
1831
  }
1794
1832
  },
1795
- async recover(wid, journal) {
1833
+ async recover(wid, journal, options = {}) {
1796
1834
  journals.set(wid, journal);
1835
+ // A settled workflow (orchestrator/settled.ts) not decoded: every call recovered; only the sweep needs its executions.
1836
+ if (journal.loaded === false && options.settled) {
1837
+ seeds.set(journal, seededSweep(options.settled.sweep));
1838
+ return { calls: 0, skipped: options.settled.calls };
1839
+ }
1797
1840
  indexSweep(journal);
1798
- await serial(() => resolveWorktrees());
1841
+ // Batched (the engine recovers every workflow, then calls finishRecovery): the steps that do not depend on the
1842
+ // workflow run once, in finishRecovery.
1843
+ if (!options.batch)
1844
+ await serial(() => resolveWorktrees());
1799
1845
  await effects.recover(journal);
1800
- for (const e of journal.entries().filter(e => e.type === JT.exec)) {
1846
+ // A call whose recovery ran to its end before (and that nothing concerned since) is not read again: all its
1847
+ // executions were fenced and released, its session read, its forwards, attention and inbox settled.
1848
+ const complete = completeCalls(journal, wid), execs = entriesOf(journal, JT.exec).filter(e => !complete.has(String(e.call)));
1849
+ for (const e of execs) {
1801
1850
  // F1: an exec whose fence fails stays unfenced and holding; its call parks until a sweep retires it.
1802
1851
  const exec = String(e.exec);
1803
1852
  if (await fence(journal, exec))
1804
1853
  await release(exec);
1805
1854
  }
1806
1855
  // Writers that waited before the restart keep their order while their calls come back.
1807
- for (const e of journal.entries()) {
1808
- const call = String(e.call);
1809
- if (e.type === "writer-wait" && !writerWaits.has(call))
1810
- writerWaits.set(call, { root: String(e.root), since: e.ts, recovered: Date.now() });
1811
- else if (e.type === "writer-acquired" || e.type === JT.sealed || e.type === "retired") {
1812
- const w = writerWaits.get(call);
1813
- if (w?.recovered !== undefined)
1814
- writerWaits.delete(call);
1856
+ const waits = entriesOf(journal, "writer-wait");
1857
+ if (waits.length)
1858
+ for (const e of [...waits, ...entriesOf(journal, "writer-acquired"), ...entriesOf(journal, JT.sealed), ...entriesOf(journal, "retired")].sort((x, y) => x.seq - y.seq)) {
1859
+ const call = String(e.call);
1860
+ if (e.type === "writer-wait" && !writerWaits.has(call))
1861
+ writerWaits.set(call, { root: String(e.root), since: e.ts, recovered: Date.now() });
1862
+ else if (e.type === "writer-acquired" || e.type === JT.sealed || e.type === "retired") {
1863
+ const w = writerWaits.get(call);
1864
+ if (w?.recovered !== undefined)
1865
+ writerWaits.delete(call);
1866
+ }
1815
1867
  }
1816
- }
1817
- const calls = new Set(journal.entries().filter(e => e.type === JT.exec).map(e => String(e.call)));
1868
+ const calls = new Set(execs.map(e => String(e.call)));
1818
1869
  for (const call of calls) {
1819
1870
  const session = await readCall(journal, call), values = sessionUsage(session, call);
1820
1871
  await serial(async () => {
1821
1872
  await repairConsumedAnswers(journal, call, session);
1822
1873
  await forwardsDelivered(journal, call, session);
1823
- const recorded = new Set(journal.entries().filter(e => e.type === "usage" && e.call === call).map(e => e.id));
1874
+ const recorded = new Set(entriesFor(journal, call).filter(e => e.type === "usage").map(e => e.id));
1824
1875
  for (const u of values)
1825
1876
  if (!recorded.has(u.id))
1826
1877
  await journal.append("usage", { call, ...u });
1827
- if (sealed(journal, call) || journal.entries().some(e => e.type === "retired" && e.call === call)) {
1878
+ if (sealed(journal, call) || retiredCall(journal, call)) {
1828
1879
  await retireForwards(journal, call);
1829
1880
  await retireAttention(journal, call);
1830
1881
  await unknownAttention(journal, call);
@@ -1838,13 +1889,36 @@ export default function createExecutor(ledgers, options = {}) {
1838
1889
  if (!active.has(call))
1839
1890
  forgetCall(call);
1840
1891
  }
1841
- for (const e of journal.entries().filter(e => e.type === "forward" && !journal.entries().some(r => r.type === "forward-retired" && r.rid2 === e.rid2)))
1892
+ const retiredForwards = new Set(entriesOf(journal, "forward-retired").map(r => r.rid2));
1893
+ for (const e of entriesOf(journal, "forward").filter(e => !retiredForwards.has(e.rid2)))
1842
1894
  await replayForward(e);
1843
- await (await outbox).republishPending();
1844
- // E2: republication may restore envelopes of sealed calls; those are resolved by the seal.
1845
- for (const call of calls)
1846
- if (sealed(journal, call))
1895
+ const ended = [...calls].filter(call => sealed(journal, call) || retiredCall(journal, call));
1896
+ if (options.batch)
1897
+ unfinished.push({ journal, calls: ended });
1898
+ else {
1899
+ await (await outbox).republishPending();
1900
+ await finishCalls(journal, ended);
1901
+ }
1902
+ return { calls: calls.size, skipped: new Set(entriesOf(journal, JT.exec).map(e => String(e.call))).size - calls.size };
1903
+ },
1904
+ async finishRecovery() {
1905
+ const batch = unfinished.splice(0);
1906
+ await serial(() => resolveWorktrees());
1907
+ const sender = await outbox;
1908
+ await sender.republishPending();
1909
+ // E2: republication may restore envelopes of sealed calls, also of calls skipped as complete; the seal resolves them.
1910
+ const destinations = sender.pendingDestinations();
1911
+ for (const call of destinations) {
1912
+ const wid = callWid(call), journal = wid === undefined ? undefined : journals.get(wid);
1913
+ if (wid !== undefined && journal && completeCalls(journal, wid).has(call) && sealed(journal, call))
1847
1914
  await collectSealed(call).catch(error => console.error(`durable-subagents: inbox cleanup of ${call} failed: ${String(error)}`));
1915
+ }
1916
+ for (const { journal, calls } of batch)
1917
+ await finishCalls(journal, calls);
1918
+ },
1919
+ recovered(journal, call) {
1920
+ const wid = address(call).wid;
1921
+ return completeCalls(journal, wid).has(call) && ![...folded().writers.values()].some(w => w.call === call);
1848
1922
  },
1849
1923
  async retire(widRev) {
1850
1924
  const journal = journals.get(widRev.slice(0, widRev.lastIndexOf("@")));
@@ -23,6 +23,40 @@ export function entriesOf(journal, type, exec) {
23
23
  }
24
24
  return (exec === undefined ? index.types.get(type) : index.execs.get(type)?.get(exec)) ?? [];
25
25
  }
26
+ const keyedIndexes = new Map();
27
+ function keyed(journal, keyOf, key) {
28
+ let byJournal = keyedIndexes.get(keyOf);
29
+ if (!byJournal) {
30
+ byJournal = new WeakMap();
31
+ keyedIndexes.set(keyOf, byJournal);
32
+ }
33
+ let index = byJournal.get(journal);
34
+ if (!index) {
35
+ index = { count: 0, keys: new Map() };
36
+ byJournal.set(journal, index);
37
+ }
38
+ const entries = journal.committed?.() ?? journal.entries();
39
+ while (index.count < entries.length) {
40
+ const e = entries[index.count++], k = keyOf(e);
41
+ if (k === undefined)
42
+ continue;
43
+ const bucket = index.keys.get(k);
44
+ if (bucket)
45
+ bucket.push(e);
46
+ else
47
+ index.keys.set(k, [e]);
48
+ }
49
+ return index.keys.get(key) ?? [];
50
+ }
51
+ const byCall = (e) => typeof e.call === "string" ? e.call : undefined;
52
+ const byDest = (e) => e.type === "forward" && typeof e.dest === "string" ? e.dest : undefined;
53
+ const byRid2 = (e) => e.type === "forward" && typeof e.rid2 === "string" ? e.rid2 : undefined;
54
+ /** The entries whose `call` field names `call`, in journal order. */
55
+ export function callEntries(journal, call) { return keyed(journal, byCall, call); }
56
+ /** The `forward` entries whose destination is `call`, in journal order. */
57
+ export function forwardsTo(journal, call) { return keyed(journal, byDest, call); }
58
+ /** The `forward` entry with this forwarded identity (the first, should a replay have recorded it twice). */
59
+ export function forwardOf(journal, rid2) { return keyed(journal, byRid2, rid2)[0]; }
26
60
  const identities = new WeakMap();
27
61
  export function trackedState(journal, exec) {
28
62
  let byExec = identities.get(journal);
@@ -0,0 +1,85 @@
1
+ import { entriesOf, forwardOf } from "./indexes.js";
2
+ /** Bump whenever the recovery of a sealed or retired call gains a step: every call is then recovered once more. */
3
+ export const RECOVERY_VERSION = 1;
4
+ export const RECOVERED = "recovered";
5
+ const CALL = /^(.*)@(\d+)\/(.*)@(\d+)$/;
6
+ const digit = (code) => code >= 48 && code <= 57;
7
+ /** The calls among `among` (call ids of workflow `wid`) that entry `e` concerns: one whose id appears in any string of
8
+ * the entry (fields such as call, exec, dest, target, from, an attention item or its id; an id followed by a digit is a
9
+ * longer generation, not this one), a `call`/`generation` of the same key, and the destination of the forward a
10
+ * `rid2` names. Receipts themselves concern nothing. Conservative: a false match only costs one more read. */
11
+ export function concernedCalls(e, wid, among, forwardDest, lengths = [...new Set([...among].map(c => c.length))]) {
12
+ const found = new Set();
13
+ if (e.type === RECOVERED || !among.size)
14
+ return found;
15
+ const marker = `${wid}@`;
16
+ const visit = (value) => {
17
+ if (typeof value === "string") {
18
+ for (let p = value.indexOf(marker); p >= 0; p = value.indexOf(marker, p + 1))
19
+ for (const length of lengths) {
20
+ if (p + length > value.length)
21
+ continue;
22
+ const id = value.substr(p, length);
23
+ if (among.has(id) && !digit(value.charCodeAt(p + length)))
24
+ found.add(id);
25
+ }
26
+ }
27
+ else if (Array.isArray(value))
28
+ for (const v of value)
29
+ visit(v);
30
+ else if (value && typeof value === "object")
31
+ for (const v of Object.values(value))
32
+ visit(v);
33
+ };
34
+ visit(e);
35
+ if ((e.type === "generation" || e.type === "call") && e.key !== undefined)
36
+ for (const call of among)
37
+ if (CALL.exec(call)?.[3] === String(e.key))
38
+ found.add(call);
39
+ if (typeof e.rid2 === "string" && forwardDest) {
40
+ const dest = forwardDest(e.rid2);
41
+ if (dest !== undefined && among.has(dest))
42
+ found.add(dest);
43
+ }
44
+ return found;
45
+ }
46
+ /** Whether entry `e` of workflow `wid`'s journal concerns `call` (concernedCalls for one call). */
47
+ export function concerns(e, call, forwardDest) {
48
+ const wid = CALL.exec(call)?.[1] ?? call;
49
+ return concernedCalls(e, wid, new Set([call]), forwardDest).size > 0;
50
+ }
51
+ const complete = new WeakMap();
52
+ /** The calls of workflow `wid` whose recovery is complete: their latest `recovered` entry has the current version and
53
+ * no later entry concerns them. One pass over the entries after the earliest such receipt; cached per journal length. */
54
+ export function completeCalls(journal, wid) {
55
+ const entries = journal.committed?.() ?? journal.entries(), cached = complete.get(journal);
56
+ if (cached && cached.length === entries.length)
57
+ return cached.calls;
58
+ const receipts = new Map();
59
+ for (const r of entriesOf(journal, RECOVERED)) {
60
+ const call = String(r.call);
61
+ if (r.v === RECOVERY_VERSION)
62
+ receipts.set(call, r.seq);
63
+ else
64
+ receipts.delete(call);
65
+ }
66
+ const calls = new Set(receipts.keys());
67
+ if (calls.size) {
68
+ const lengths = [...new Set([...calls].map(c => c.length))], dest = (rid2) => {
69
+ const d = forwardOf(journal, rid2)?.dest;
70
+ return typeof d === "string" ? d : undefined;
71
+ };
72
+ const from = Math.min(...receipts.values());
73
+ // seq is dense from 1: the entries after the earliest receipt start at index `from`.
74
+ for (let i = entries[from - 1]?.seq === from ? from : 0; i < entries.length && calls.size; i++) {
75
+ const e = entries[i];
76
+ if (e.seq <= from)
77
+ continue;
78
+ for (const call of concernedCalls(e, wid, calls, dest, lengths))
79
+ if (receipts.get(call) < e.seq)
80
+ calls.delete(call);
81
+ }
82
+ }
83
+ complete.set(journal, { length: entries.length, calls });
84
+ return calls;
85
+ }
@@ -11,6 +11,7 @@ const EMPTY = { entries: [], corrupt: [] };
11
11
  /** C5, E4, F3: Read complete native entries incrementally; an unfinished trailing line is ignored and a malformed
12
12
  * complete line is skipped (pi's own loader does the same), reported by its 1-based line number in `corrupt`. */
13
13
  export async function readSessionState(path) {
14
+ reads++;
14
15
  const file = await open(path, "r").catch(error => { if (error.code === "ENOENT")
15
16
  return undefined; throw error; });
16
17
  if (!file) {
@@ -63,6 +64,9 @@ export async function readSessionState(path) {
63
64
  await file.close();
64
65
  }
65
66
  }
67
+ let reads = 0;
68
+ /** How many session reads (readSessionState calls) this process made: a diagnostic, e.g. of what a recovery read. */
69
+ export function sessionReads() { return reads; }
66
70
  /** C5: Complete native session entries (see readSessionState). The result is shared: never mutate it. */
67
71
  export async function readSession(path) {
68
72
  return (await readSessionState(path)).entries;
@@ -61,6 +61,22 @@ export async function fenceAttentionResolved(journal, id) {
61
61
  await journal.append(JT.attentionResolved, { id: `fence:${id}`, rev: item.rev, resolution: "fenced" });
62
62
  }
63
63
  const sweeps = new WeakMap();
64
+ export function sweepSeed(journal) {
65
+ const { failed, fenced, tracked, execs } = indexSweep(journal);
66
+ return execs.map(e => {
67
+ const exec = String(e.exec);
68
+ const ids = [...new Set((tracked.get(exec) ?? []).map(p => `${p.pid} ${p.start}`))];
69
+ // Only a failure not fenced since is still a failure: a fenced one would make the sweep record (and decode) again.
70
+ return { exec, call: String(e.call), ...(failed.has(exec) && !fenced.has(exec) ? { failed: true } : {}), tracked: ids };
71
+ });
72
+ }
73
+ const procOf = (id) => { const space = id.indexOf(" "); return { pid: Number(id.slice(0, space)), ppid: 0, start: id.slice(space + 1) }; };
74
+ /** The sweep state of a journal that is not decoded, from its seed (every execution fenced, no open gate): no failed
75
+ * fence is open (settledFacts requires it), so none is seeded, also from an older record. */
76
+ export function seededSweep(seed) {
77
+ return { count: 0, fenced: new Set(seed.map(s => s.exec)), retired: new Set(), failed: new Set(), gated: new Set(),
78
+ tracked: new Map(seed.map(s => [s.exec, s.tracked.map(procOf)])), execs: seed.map(s => ({ seq: 0, ts: 0, type: JT.exec, exec: s.exec, call: s.call })), gates: [] };
79
+ }
64
80
  /** A1: Fold old history during recovery, so the first sweep does not allocate it on the timer path. */
65
81
  export function indexSweep(journal) {
66
82
  let state = sweeps.get(journal);
@@ -97,7 +113,7 @@ export function indexSweep(journal) {
97
113
  export async function sweepExecutions(journals, containment, hooks = {}) {
98
114
  const targets = [];
99
115
  for (const journal of journals) {
100
- const { fenced, retired, failed, gated, tracked, execs, gates } = indexSweep(journal);
116
+ const { fenced, retired, failed, gated, tracked, execs, gates } = (journal.loaded === false ? hooks.seeded?.(journal) : undefined) ?? indexSweep(journal);
101
117
  // A gate whose recovery fence failed has no outcome yet; it is retried here until its processes are gone.
102
118
  for (const e of gates) {
103
119
  const id = String(e.id);
@@ -5,8 +5,9 @@
5
5
  // provider-*: used-up usage windows (providers.ts).
6
6
  // config{hash,config}: the orchestrator settings in effect from here; config-rejected{error,hash?}: a change of
7
7
  // config.json refused, while the earlier settings stay (cleared by the next config record).
8
- // orchestrator{version,pid,pi?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its package
9
- // version, the pi it launches) and its exit (why: idle, restart, signal, error).
8
+ // orchestrator{version,pid,pi?,recovery?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its
9
+ // package version, the pi it launches) and its exit (why: idle, restart, signal, error). `recovery`: it recovers the
10
+ // home's workflows before it dispatches anything, until its recovered{pid,ms,workflows,calls,skipped}.
10
11
  // restart{rid,force,reason?,initiator?,from?,live}: accepted restart; the next start consumes its status provenance.
11
12
  // Old records lack reason/initiator/from and remain readable (A1).
12
13
  // writer-hold/writer-release{root,call}: the writer lock of a worktree root, held by one call until it ends.
@@ -37,9 +38,13 @@ export function applyLedger(state, e) {
37
38
  else if (e.type === "restart")
38
39
  state.pendingRestart = e.force === true ? { ts: e.ts, reason: e.reason, initiator: e.initiator, from: e.from } : undefined;
39
40
  else if (isEntry(e, "orchestrator")) {
40
- state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
41
+ state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(e.recovery === true ? { recovery: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
41
42
  delete state.pendingRestart;
42
43
  }
44
+ else if (isEntry(e, "recovered")) {
45
+ if (state.orchestrator && state.orchestrator.pid === Number(e.pid))
46
+ state.orchestrator.recovered = { ts: e.ts, ms: Number(e.ms) };
47
+ }
43
48
  else if (e.type === "writer-hold") {
44
49
  if (!state.writers.has(String(e.root)))
45
50
  state.writers.set(String(e.root), { call: String(e.call), ts: e.ts });
@@ -61,7 +61,9 @@ export async function main(options = {}) {
61
61
  const pi = resolvePi(process.env).path ?? resolvePi({ PATH: process.env.PATH }).path;
62
62
  if (!pi)
63
63
  console.error('durable-subagents: pi not found (DSA_PI_BIN unset or not executable, not on PATH); subagents launch `pi` from PATH');
64
- await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true, pi: pi ?? null });
64
+ // `recovery: true` announces the `recovered` entry this pid appends once its recovery ends (none if it fails first).
65
+ await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true, pi: pi ?? null, recovery: true });
66
+ const recoveryStarted = performance.now();
65
67
  const factory = options.executor ?? (await import(__rewriteRelativeImportExtension(new URL(import.meta.url.endsWith('.ts') ? './executor/index.ts' : './executor/index.js', import.meta.url).href))).default;
66
68
  const executor = factory(ledgers, pi ? { pi } : {});
67
69
  engine = new Engine(ledgers, executor, options);
@@ -72,7 +74,8 @@ export async function main(options = {}) {
72
74
  watcher = watchConfig({ path: configPath(home), stamp, config, orch: ledgers.orch, intervalMs: Math.min(1000, config.k?.trackerMs ?? 1000),
73
75
  apply: change => executor.reconfigure ? executor.reconfigure(change) : change() });
74
76
  }
75
- await engine.recover();
77
+ const recovered = await engine.recover();
78
+ await ledgers.orch.append('recovered', { pid: process.pid, ms: Math.round(performance.now() - recoveryStarted), ...recovered });
76
79
  await engine.loop(options.signal);
77
80
  const reason = options.signal?.reason;
78
81
  exit = engine.restartRequested ? { reason: 'restart' }