pi-durable-subagents 1.0.40 → 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,27 +16,29 @@ 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";
23
23
  import { buildPiArgs } from "../../compat/pi-args.js";
24
- import { parseModel, plainModel, resolveModel } from "../../compat/model.js";
24
+ import { parseModel, plainModel, resolveModel, sameModel } from "../../compat/model.js";
25
25
  import { buildCallResult } from "../../compat/result.js";
26
26
  import createEffects from "./effects/index.js";
27
27
  import { continueSession } from "./generation.js";
28
- import { boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
29
- import { SessionFold, answerKey, digestOpenQuestion } from "./digest.js";
28
+ import { answerInFlight, boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
29
+ import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./digest.js";
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";
41
+ import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
40
42
  import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
41
43
  const MEM_RECORD_MS = 30000;
42
44
  /** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
@@ -48,9 +50,10 @@ const ignoreMissing = (error) => { if (error.code !== "ENOENT")
48
50
  const callOf = (exec) => exec.slice(0, exec.lastIndexOf("#"));
49
51
  const shutdownError = () => Object.assign(new Error("executor shutdown; call resumes on recovery"), { name: "ExecutorShutdown" });
50
52
  const extension = fileURLToPath(new URL(`../../agent/extension.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url));
51
- const entriesFor = (journal, call) => journal.entries().filter(e => e.call === call);
53
+ const entriesFor = callEntries;
52
54
  const current = (journal, call) => entriesFor(journal, call).findLast(e => e.type === JT.exec)?.exec;
53
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");
54
57
  const has = (journal, type, exec) => entriesOf(journal, type, exec).length > 0;
55
58
  /** The run of executions of `call` whose launches failed for a reason of the environment, ending at `exec`: its first
56
59
  * execution and the one before it (absent for the call's first). Undefined when `exec` did not fail so. */
@@ -99,6 +102,7 @@ export function requestedModel(journal, call, followUp) {
99
102
  }
100
103
  return wanted;
101
104
  }
105
+ const callWid = (call) => /^(.*)@\d+\/.*@\d+$/.exec(call)?.[1];
102
106
  function address(call) {
103
107
  const match = /^(.*)@(\d+)\/(.*)@(\d+)$/.exec(call);
104
108
  if (!match)
@@ -151,9 +155,11 @@ export default function createExecutor(ledgers, options = {}) {
151
155
  // F1: execs whose fence failed in this process; they are retried only by the sweep.
152
156
  const failing = new Set();
153
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();
154
160
  const sweepTimer = setInterval(() => {
155
161
  if (!sweeping)
156
- 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) })
157
163
  .catch(error => console.error(`durable-subagents: sweep failed, retrying in K1: ${String(error)}`)).finally(() => { sweeping = undefined; });
158
164
  }, options.sweepMs ?? 30000);
159
165
  sweepTimer.unref();
@@ -345,13 +351,37 @@ export default function createExecutor(ledgers, options = {}) {
345
351
  done.add(rid);
346
352
  }
347
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). */
348
357
  async function collectSealed(call) {
349
358
  const sender = await outbox, dir = inbox(call);
350
- 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 []; })) {
351
361
  if (name.endsWith(".json") && !name.startsWith("."))
352
362
  await sender.markResolved(name.slice(0, -5));
353
363
  await rm(join(dir, name), { force: true });
354
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
+ }
355
385
  }
356
386
  /** P7, P27: Record forward-delivered once when a forward's child receipt is first observed; serial sections only. */
357
387
  /** The reply to a model send says which model and when it applies (orchestrator ledger `send-note`, once per rid). */
@@ -378,13 +408,13 @@ export default function createExecutor(ledgers, options = {}) {
378
408
  const entries = await readCall(journal, call);
379
409
  await forwardsDelivered(journal, call, entries);
380
410
  const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
381
- for (const e of journal.entries().filter(e => e.type === "forward" && e.dest === call)) {
382
- 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)) {
383
413
  // A notify the call never received is not lost: it becomes a pending note (before its forward is retired, so a
384
414
  // crash in between finds the forward open again and the note is written once). A withdrawn one is not.
385
- const envelope = e.envelope, all = journal.entries();
386
- const withdrawn = all.some(r => r.type === "forward" && r.dest === call && r.envelope.kind === "withdraw" && r.envelope.body.rids?.includes(String(e.rid2)));
387
- 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))
388
418
  await journal.append(PENDING_NOTE, { rid: e.rid, call, key: address(call).key, message: String(envelope.body?.message ?? "") });
389
419
  // A follow-up the call never took is not lost either: the orchestrator opens the next generation with it (or a
390
420
  // later follow-up takes it along). A stop is final and drops it; a withdrawn one is gone.
@@ -409,7 +439,9 @@ export default function createExecutor(ledgers, options = {}) {
409
439
  return hit;
410
440
  }
411
441
  const roots = worktreeRoots(), writes = new WorktreeIndex();
412
- 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;
413
445
  const origin = (w) => writes.origin(w.journal) ?? orch.entries().find(e => e.type === JT.created && e.wid === address(w.call).wid)?.origin;
414
446
  // Serial sections only: wrote and attention are durable before another writer or seal can interleave.
415
447
  /** Remind of every pair of calls that wrote in `root` and have not ended, once per pair and journal. The index must be
@@ -450,7 +482,7 @@ export default function createExecutor(ledgers, options = {}) {
450
482
  async function resolveWorktrees(call) {
451
483
  for (const { id, journal, item } of indexed().open()) {
452
484
  const pair = worktreeCalls(id);
453
- if (call ? pair.includes(call) : pair.some(c => writes.ended(c)))
485
+ if (call ? pair.includes(call) : pair.some(endedCall))
454
486
  await journal.append(JT.attentionResolved, { id, rev: item.rev, resolution: "ended" });
455
487
  }
456
488
  }
@@ -473,7 +505,8 @@ export default function createExecutor(ledgers, options = {}) {
473
505
  }
474
506
  async function finish(journal, call, exec, result) {
475
507
  const a = active.get(call);
476
- 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)) {
477
510
  const started = Date.now(), prior = activeTotal(journal.entries(), call);
478
511
  const check = async () => {
479
512
  if (stopped(a))
@@ -714,6 +747,8 @@ export default function createExecutor(ledgers, options = {}) {
714
747
  }
715
748
  async function acquireLoop(a, exec, decide, mine, writer) {
716
749
  let continuation = false;
750
+ let pinnedWait;
751
+ let waitMark = "";
717
752
  for (;;) {
718
753
  let signal;
719
754
  const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
@@ -724,10 +759,30 @@ export default function createExecutor(ledgers, options = {}) {
724
759
  return;
725
760
  if (writer && !await writerAdmit(a, writer))
726
761
  return;
727
- const decision = await decide(), models = decision.candidates, pool = decision.pool;
762
+ const decision = await decide(), pool = decision.pool;
763
+ let models = decision.candidates;
764
+ const pinned = decision.spill?.[0];
765
+ const full = (m) => holdings().filter(h => h.pool === m.provider).length >= (settings().providers?.[m.provider ?? ""]?.slots ?? Infinity);
766
+ if (pinned && full(pinned)) {
767
+ if (!sameModel(pinnedWait?.model, pinned))
768
+ pinnedWait = { model: pinned, since: Date.now() };
769
+ const ms = settings().k?.resumeSpillMs;
770
+ if (ms !== null && (ms ?? 120_000) >= 0 && Date.now() - pinnedWait.since >= (ms ?? 120_000))
771
+ models = [...models, ...spillCandidates(pinned, decision.spill)];
772
+ }
773
+ else
774
+ pinnedWait = undefined;
775
+ const mark = pinnedWait ? JSON.stringify(pinnedWait.model) : "";
776
+ if (mark !== waitMark) {
777
+ await a.ticket.journal.append("slot-wait", { call: a.ticket.callId, exec, ...(pinnedWait ? { model: plainModel(pinnedWait.model), since: pinnedWait.since, pool } : {}) });
778
+ waitMark = mark;
779
+ }
728
780
  continuation = decision.continuation;
729
781
  for (const model of models) {
730
- if (!continuation && pool && models.length > 1 && skipped(pool, model))
782
+ const spilling = !!pinned && !sameModel(model, pinned);
783
+ if (pool && (spilling || !continuation && models.length > 1) && skipped(pool, model))
784
+ continue;
785
+ if (failedModel(modelFailures(a.ticket.journal, a.ticket.callId), model))
731
786
  continue;
732
787
  // A pool entry with afterMs waits its turn: it is taken only once this acquisition has waited that long.
733
788
  if (model.afterMs !== undefined && Date.now() - mine.since < model.afterMs)
@@ -774,6 +829,10 @@ export default function createExecutor(ledgers, options = {}) {
774
829
  await orch.append("provider-probe", { provider, exec });
775
830
  }
776
831
  const plain = plainModel(model);
832
+ if (spilling && pinnedWait) {
833
+ continuation = false;
834
+ await a.ticket.journal.append("spilled", { call: a.ticket.callId, exec, pool, from: plainModel(pinned), to: plain, waitedMs: Date.now() - pinnedWait.since });
835
+ }
777
836
  await a.ticket.journal.append("selected", { exec, model: plain, ...(pool ? { pool } : {}) });
778
837
  return plain;
779
838
  }
@@ -807,25 +866,30 @@ export default function createExecutor(ledgers, options = {}) {
807
866
  const { defaultModel: configured, pools } = settings();
808
867
  const raw = t.spec.model ?? t.agent.model ?? configured ?? await defaultModel();
809
868
  const pool = raw && pools?.[raw] ? raw : undefined;
810
- const candidates = raw ? resolveModel(raw, pools) : [{ id: "" }];
811
- const candidate = recorded && candidates.some(m => m.provider === recorded.provider && m.id === recorded.id);
869
+ const failures = modelFailures(t.journal, t.callId);
870
+ const candidates = (raw ? resolveModel(raw, pools) : [{ id: "" }]).filter(m => !failedModel(failures, m));
871
+ if (!candidates.length)
872
+ throw new Error(`model-unavailable: no usable model remains; ${String(failures.at(-1)?.reason ?? raw)}`);
873
+ const matches = (m, other) => sameModel(m, other) || !!other && t.journal.entries().some(e => e.type === "model-ready" && sameModel(e.selected, m) && sameModel(e.model, other));
874
+ const candidate = recorded && candidates.some(m => matches(m, recorded));
812
875
  // Leave the session's model for the pool's others when its pool skips it after losses, or its provider's usage
813
876
  // window is used up; and at a new generation, go back to the pool's order of preference.
814
877
  // A new generation of a pool call starts from the pool also when the session's model is not one of its models
815
878
  // (switched outside it, or the follow-up named the pool).
816
- const skip = pool && (candidate ? previous && ownSegment && skipped(pool, recorded) || unavailable(recorded.provider) || !ownSegment && !!t.continueFrom
817
- : !ownSegment && !!t.continueFrom);
879
+ const skip = pool && (previous && has(t.journal, "model-unavailable", previous) || (candidate ? previous && ownSegment && skipped(pool, recorded) || unavailable(recorded.provider) || !ownSegment && !!t.continueFrom
880
+ : !ownSegment && !!t.continueFrom));
818
881
  // A model the call was asked to use replaces the session's: launched with it, and holding its provider's slot.
819
882
  const wanted = requestedModel(t.journal, t.callId, t.model);
820
883
  // It outranks the pool's order at a new generation too, also when it names the model the session already has.
821
884
  // A requested model of the call's own pool keeps the pool: a used-up window still moves the call on.
822
885
  const keep = pool && candidates.some(m => m.provider === wanted?.provider && m.id === wanted?.id) ? pool : undefined;
823
- if (wanted)
886
+ if (wanted && !failedModel(failures, wanted))
824
887
  return recorded && !freshFork && recorded.provider === wanted.provider && recorded.id === wanted.id
825
888
  ? { candidates: [recorded], continuation: true, pool: keep }
826
889
  : { candidates: [wanted], continuation: false, pool: keep };
827
- if (recorded && !freshFork && !skip)
828
- return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined };
890
+ if (recorded && !freshFork && !skip && !failedModel(failures, recorded))
891
+ return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined,
892
+ spill: candidate && pool && !parentPinned(t) ? [recorded, ...candidates.map(m => matches(m, recorded) ? { ...m, id: recorded.id } : m)] : undefined };
829
893
  return { candidates, continuation: false, pool };
830
894
  }
831
895
  /** Resolve a bound answer before it waits for admission; also repairs an interrupted append pair. Called serially. */
@@ -875,12 +939,53 @@ export default function createExecutor(ledgers, options = {}) {
875
939
  await resolveQuestion(journal, call, item.qid, item.rev, "carried");
876
940
  }
877
941
  }
942
+ /** Model identity receipts are durable before the observer fences an unavailable execution. Serial sections only. */
943
+ async function unavailableModel(journal, exec, selected, actual, reason) {
944
+ if (!has(journal, "model-unavailable", exec))
945
+ await journal.append("model-unavailable", { exec, selected, actual, reason: `selected ${selected.provider}/${selected.id}, pi would use ${actual.provider ?? "none"}/${actual.id}: ${reason}`, until: Date.now() + MODEL_RETRY_MS });
946
+ }
947
+ function allowedModels(journal, exec) {
948
+ const log = journal.entries(), selected = log.find(e => e.type === "selected" && e.exec === exec)?.model;
949
+ const models = selected ? [selected] : [];
950
+ for (const e of log) {
951
+ const envelope = e.envelope;
952
+ if (e.type !== "forward" || e.dest !== callOf(exec) || envelope?.kind !== "model")
953
+ continue;
954
+ if (log.some(r => r.type === "forward-delivered" && r.rid2 === e.rid2 && r.reason !== undefined))
955
+ continue;
956
+ if (log.some(r => r.type === "forward" && r.dest === e.dest && r.envelope?.kind === "withdraw" && r.envelope.body?.rids?.includes(String(e.rid2))))
957
+ continue;
958
+ const body = envelope.body;
959
+ if (body.exec && body.exec !== exec)
960
+ continue;
961
+ models.push({ provider: body.provider, id: body.model });
962
+ }
963
+ for (const e of log)
964
+ if (e.type === "model-ready" && e.exec === exec && models.some(m => sameModel(m, e.selected)))
965
+ models.push(e.model);
966
+ return models;
967
+ }
968
+ async function modelControl(journal, exec, event) {
969
+ if (event.exec !== exec)
970
+ return;
971
+ return serial(async () => {
972
+ if (event.type === CT.modelUnavailable) {
973
+ await unavailableModel(journal, exec, event.selected, event.actual, String(event.reason));
974
+ return false;
975
+ }
976
+ if (event.type === CT.modelReady && allowedModels(journal, exec).some(m => sameModel(m, event.selected)) &&
977
+ !journal.entries().some(e => e.type === "model-ready" && e.exec === exec && sameModel(e.selected, event.selected)))
978
+ await journal.append("model-ready", { exec, selected: event.selected, model: event.model, virtual: event.virtual === true });
979
+ return !has(journal, "model-unavailable", exec);
980
+ });
981
+ }
878
982
  /** The model each execution last answered with (`selected`, then `model-used`), cached per execution. */
879
983
  const inUse = new Map();
880
984
  async function switched(exec, journal, event) {
881
985
  const message = event.message, provider = message?.provider;
882
986
  if (!provider)
883
987
  return;
988
+ let accepted = true;
884
989
  await serial(async () => {
885
990
  // Evidence of the model in use: the provider and model of each assistant message, recorded when it changes.
886
991
  if (message.role === "assistant" && message.model) {
@@ -894,6 +999,13 @@ export default function createExecutor(ledgers, options = {}) {
894
999
  await journal.append("model-used", { exec, model: { provider, id: message.model } });
895
1000
  inUse.set(exec, name);
896
1001
  }
1002
+ const virtual = journal.entries().findLast(e => e.type === "model-ready" && e.exec === exec)?.virtual === true;
1003
+ if (!virtual && !allowedModels(journal, exec).some(m => sameModel(m, { provider, id: message.model }))) {
1004
+ const selected = journal.entries().find(e => e.type === "selected" && e.exec === exec)?.model;
1005
+ await unavailableModel(journal, exec, selected, { provider, id: message.model }, "child reported an unselected model");
1006
+ accepted = false;
1007
+ return;
1008
+ }
897
1009
  }
898
1010
  const target = holdings().find(h => h.exec === exec && h.pool === provider && h.reserved);
899
1011
  if (!target)
@@ -905,6 +1017,7 @@ export default function createExecutor(ledgers, options = {}) {
905
1017
  }
906
1018
  });
907
1019
  wake();
1020
+ return accepted;
908
1021
  }
909
1022
  /** The model an execution last answered with, or was launched on. */
910
1023
  function modelOf(journal, exec) {
@@ -1055,16 +1168,22 @@ export default function createExecutor(ledgers, options = {}) {
1055
1168
  await effects.afterSeal(t, result);
1056
1169
  return result;
1057
1170
  }
1058
- try {
1059
- await continueSession(home, t, session);
1060
- cwd = (await effects.prepare(t, { sessionPath: session })).cwd;
1061
- }
1062
- 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) {
1063
1182
  const exec = current(journal, t.callId) ?? `${t.callId}#1.1`;
1064
1183
  if (!current(journal, t.callId))
1065
1184
  await serial(() => journal.append(JT.exec, { call: t.callId, exec }));
1066
1185
  await fence(journal, exec, { park: a });
1067
- return finish(journal, t.callId, exec, makeResult("failed", "", String(error)));
1186
+ return finish(journal, t.callId, exec, makeResult("failed", "", unprepared));
1068
1187
  }
1069
1188
  for (;;) {
1070
1189
  const old = sealed(journal, t.callId);
@@ -1118,7 +1237,22 @@ export default function createExecutor(ledgers, options = {}) {
1118
1237
  bound = pendingAnswer;
1119
1238
  if (exec) {
1120
1239
  await fence(journal, exec, { park: a });
1121
- await questions(t, entries = await readCall(journal, t.callId));
1240
+ entries = await readCall(journal, t.callId);
1241
+ await serial(() => repairConsumedAnswers(journal, t.callId, entries));
1242
+ await questions(t, entries);
1243
+ bound ??= journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId && e.reason === "answered-in-session");
1244
+ // A binding excuses only the execution it was bound to (the asker it ended) and the first launch after it while
1245
+ // that launch never started a child. Every later or started execution is judged by its own evidence, so a
1246
+ // child that dies before writing its exec marker counts toward lossBound instead of relaunching forever.
1247
+ if (bound) {
1248
+ const all = journal.entries(), execSeq = all.find(r => r.type === JT.exec && r.exec === exec).seq;
1249
+ const firstAfter = !all.some(r => r.type === JT.exec && r.call === t.callId && r.seq > bound.seq && r.seq < execSeq);
1250
+ if (!(bound.seq > execSeq || firstAfter && !has(journal, "tracked", exec) &&
1251
+ !digestOf(t.callId, entries).execAt.has(exec)))
1252
+ bound = undefined;
1253
+ }
1254
+ if (bound)
1255
+ await release(exec);
1122
1256
  // D6: after the fence the session is final. A bound answer it closed (answered, superseded, or re-asked as a newer
1123
1257
  // revision) is settled; if the session still has an open question of this call, the call does not launch: it
1124
1258
  // hibernates again on that question (its attention is open, so the parent is asked), and resumes only on a new
@@ -1142,8 +1276,18 @@ export default function createExecutor(ledgers, options = {}) {
1142
1276
  return finish(journal, t.callId, exec, makeResult("timeout"));
1143
1277
  if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
1144
1278
  return finish(journal, t.callId, exec, makeResult("budget"));
1279
+ for (const e of entries)
1280
+ if (e.customType === CT.modelUnavailable && e.data?.exec === exec)
1281
+ await modelControl(journal, exec, { type: CT.modelUnavailable, ...e.data });
1282
+ const modelFailure = entriesOf(journal, "model-unavailable", exec).at(-1);
1283
+ if (modelFailure) {
1284
+ const selected = entriesOf(journal, "selected", exec).at(-1);
1285
+ if (!selected?.pool)
1286
+ return finish(journal, t.callId, exec, makeResult("failed", "", `model-unavailable: ${String(modelFailure.reason)}`));
1287
+ await release(exec);
1288
+ }
1145
1289
  // A child that never started (its launch failed for a reason of the environment) lost nothing: launch again.
1146
- if (!bound && !has(journal, "spawn-env-failed", exec)) {
1290
+ if (!bound && !modelFailure && !has(journal, "spawn-env-failed", exec)) {
1147
1291
  // P28: an execution cut off while its only unfinished tool call is the open question's `ask` (before it
1148
1292
  // hibernated) was waiting, not working: it hibernates now and resumes with the answer, like a planned
1149
1293
  // hibernation; it is neither a loss nor, for `once`, an unknown outcome.
@@ -1289,13 +1433,18 @@ export default function createExecutor(ledgers, options = {}) {
1289
1433
  return;
1290
1434
  await serial(async () => {
1291
1435
  const attention = entriesOf(journal, JT.attention).find(e => isEntry(e, JT.attention) && e.item.qid === q.qid && e.item.call === t.callId && e.item.rev === q.rev);
1292
- if (attention && Date.now() - attention.ts >= (config.k?.hibernateMs ?? 120000) && !has(journal, JT.fenced, exec) && hibernation(journal, t.callId)?.exec !== exec) {
1436
+ const all = journal.entries();
1437
+ if (attention && Date.now() - attention.ts >= (config.k?.hibernateMs ?? 120000) && !interrupted(a) && current(journal, t.callId) === exec &&
1438
+ openAsked(all, t.callId, q.qid, q.rev) && !answerInFlight(all, t.callId) &&
1439
+ !all.some(e => e.type === "answer-bound" && e.call === t.callId && e.qid === q.qid && e.rev === q.rev) &&
1440
+ !has(journal, JT.fenced, exec) && hibernation(journal, t.callId)?.exec !== exec) {
1293
1441
  await journal.append("hibernated", { call: t.callId, exec, qid: q.qid, rev: q.rev });
1294
1442
  a.wake();
1295
1443
  }
1296
1444
  });
1297
1445
  }, recordUsage: values => recordUsage(t, values), usage: entries => digestOf(t.callId, entries).usage,
1298
1446
  wrote: path => wrote(t, exec, cwd, path),
1447
+ modelControl: event => modelControl(journal, exec, event),
1299
1448
  switched: event => switched(exec, journal, event), answered: event => answered(t, exec, event), pendingSwitch: () => pendingSwitch(exec),
1300
1449
  });
1301
1450
  }
@@ -1306,14 +1455,57 @@ export default function createExecutor(ledgers, options = {}) {
1306
1455
  }
1307
1456
  }
1308
1457
  /**
1309
- * P28: an answer forwarded to the child while the question was still open but before the call hibernated (a restart
1310
- * or crash cut the asker off, or the planned hibernation fenced it first) never reached a live child. Once the call
1311
- * hibernates it is bound to the question like an answer given during hibernation; the forward is retired, so the
1312
- * reply "apply" already given (and any retry with the same rid) stays true.
1458
+ * P28: reconcile an answer forwarded before an interrupted asker hibernated. A consumed answer continues the
1459
+ * session; an unconsumed one binds like an answer given during hibernation and retires its original forward.
1460
+ * The reply "apply" already given (and any retry with the same rid) stays true.
1313
1461
  */
1314
1462
  async function adoptAnswer(journal, call, sleeping) {
1315
1463
  const entries = await readCall(journal, call);
1316
- await serial(() => adopt(journal, call, sleeping, entries));
1464
+ await serial(async () => { await repairConsumedAnswers(journal, call, entries); await adopt(journal, call, sleeping, entries); });
1465
+ }
1466
+ /** A fenced asker may have consumed its forwarded answer before the fence. Publish the binding first, then its
1467
+ * derived resolution and delivery: every prefix is repaired on retry/recovery. Never resend the answer; the next
1468
+ * execution uses a plain continue in the same session. Called serially, only after the current execution is fenced. */
1469
+ async function repairConsumedAnswers(journal, call, entries) {
1470
+ const exec = current(journal, call);
1471
+ if (!exec || !has(journal, JT.fenced, exec) || sealed(journal, call) || journal.entries().some(e => e.type === "retired" && e.call === call))
1472
+ return;
1473
+ const digest = digestOf(call, entries);
1474
+ for (const f of entriesOf(journal, "forward").filter(e => e.dest === call)) {
1475
+ const env = f.envelope, qid = env.cond?.qid, rev = env.cond?.rev;
1476
+ if (env.kind !== "answer" || !digest.questions.some(q => q.qid === qid && q.rev === rev) ||
1477
+ journal.entries().some(e => e.type === "forward-retired" && e.rid2 === f.rid2))
1478
+ continue;
1479
+ const receipt = digest.receipts.get(String(f.rid2)), details = receipt?.message?.details ?? receipt?.details;
1480
+ if (!receipt || details?.qid !== qid || details?.rev !== rev)
1481
+ continue;
1482
+ // The binding must not outlive the evidence it derives: fsync the native receipt before journal publication.
1483
+ await collectReceipts(call, [...entries]);
1484
+ const binding = journal.entries().find(e => e.type === "answer-bound" && e.call === call && e.qid === qid && e.rev === rev);
1485
+ // A normal settled turn needs no continuation, nor does an answer consumed in an earlier execution. A receipt
1486
+ // in this execution counts even if observation already resolved its attention before the fence.
1487
+ const sleeping = hibernation(journal, call), segment = digest.execAt.get(exec);
1488
+ const at = entries.indexOf(receipt), consumedHere = segment !== undefined && at > segment;
1489
+ // The execution stopped ON that ask: its result is the answer receipt and nothing ran after it (no report, no
1490
+ // question, no tool call, no finished assistant turn, no other unfinished tool). Otherwise the execution went on
1491
+ // working after the answer and its own evidence (report, once + dangling, loss) decides as usual.
1492
+ const after = entries.slice(at + 1);
1493
+ const stoppedOnAsk = consumedHere && receipt.message?.role === "toolResult" && receipt.message.toolName === "ask" &&
1494
+ !evidence([...entries], exec).dangling.length &&
1495
+ !after.some(e => e.type === "custom" && (e.customType === CT.report || e.customType === CT.question) ||
1496
+ e.message?.role === "assistant" && ((Array.isArray(e.message.content) && e.message.content.some(b => b.type === "toolCall")) ||
1497
+ (e.message.stopReason !== "aborted" && e.message.stopReason !== "error")));
1498
+ const superseded = supersededBy(details);
1499
+ const sleepingAnswered = sleeping?.exec === exec && (sleeping.qid === qid && sleeping.rev === rev ||
1500
+ superseded.some(q => q.qid === sleeping.qid && q.rev === sleeping.rev));
1501
+ if (!binding && (sleepingAnswered || stoppedOnAsk && !has(journal, "settled", exec)))
1502
+ await journal.append("answer-bound", { call, qid, rev, rid: f.rid, rid2: f.rid2, hash: f.hash, reason: "answered-in-session",
1503
+ ...(superseded.length ? { superseded } : {}) });
1504
+ await resolveBoundAnswer(journal, call, qid, rev);
1505
+ for (const q of superseded)
1506
+ await resolveQuestion(journal, call, q.qid, q.rev, "superseded");
1507
+ }
1508
+ await forwardsDelivered(journal, call, [...entries]);
1317
1509
  }
1318
1510
  /** The forward whose adoption was begun (its envelope withdrawn from the child's inbox) and not yet bound. */
1319
1511
  async function adoptionBegun(journal, call) {
@@ -1325,9 +1517,20 @@ export default function createExecutor(ledgers, options = {}) {
1325
1517
  * adoption was begun before a crash (its envelope is withdrawn, so it can reach the child only through this binding).
1326
1518
  * Called serially. */
1327
1519
  async function adopt(journal, call, sleeping, entries, onlyBegun = false) {
1328
- const all = journal.entries();
1329
- if (boundAnswer(all, sleeping))
1520
+ const all = journal.entries(), bound = boundAnswer(all, sleeping);
1521
+ if (bound) {
1522
+ // Repair an adoption cut off after its binding but before resolution/retirement. The original forward and
1523
+ // derived bound identity prove adoption; a consumed answer instead keeps its original delivered identity.
1524
+ await resolveBoundAnswer(journal, call, bound.qid, bound.rev);
1525
+ await resolveSuperseded(journal, call);
1526
+ const f = all.find(e => e.type === "forward" && e.dest === call && e.rid === bound.rid &&
1527
+ contentHash([String(e.rid2), "hibernated"]) === bound.rid2);
1528
+ if (f && !all.some(e => e.type === "forward-retired" && e.rid2 === f.rid2))
1529
+ await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
1530
+ if (f)
1531
+ await (await outbox).markResolved(String(f.rid2));
1330
1532
  return;
1533
+ }
1331
1534
  const begun = await adoptionBegun(journal, call);
1332
1535
  const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
1333
1536
  // The answer to the question it hibernated on, else to another of its questions still open (an earlier one).
@@ -1425,6 +1628,14 @@ export default function createExecutor(ledgers, options = {}) {
1425
1628
  if (prior) {
1426
1629
  if (prior.hash !== hash)
1427
1630
  return { action: "reject", reason: "identity-conflict" };
1631
+ if (prior.envelope.kind === "answer") {
1632
+ await repairConsumedAnswers(ctx.journal, dest, await readCall(ctx.journal, dest));
1633
+ const exec = current(ctx.journal, dest);
1634
+ if (exec && has(ctx.journal, JT.fenced, exec)) {
1635
+ active.get(dest)?.wake();
1636
+ wake();
1637
+ }
1638
+ }
1428
1639
  if (!ctx.journal.entries().some(e => e.type === "forward-retired" && e.rid2 === prior.rid2))
1429
1640
  await replayForward(prior);
1430
1641
  return { action: "apply" };
@@ -1440,6 +1651,12 @@ export default function createExecutor(ledgers, options = {}) {
1440
1651
  return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
1441
1652
  if (req.kind === "send" && req.body.kind === "answer") {
1442
1653
  const sleeping = hibernation(ctx.journal, dest);
1654
+ await repairConsumedAnswers(ctx.journal, dest, await readCall(ctx.journal, dest));
1655
+ const exec = current(ctx.journal, dest);
1656
+ if (exec && has(ctx.journal, JT.fenced, exec)) {
1657
+ active.get(dest)?.wake();
1658
+ wake();
1659
+ }
1443
1660
  // An adoption begun before a crash (the earlier answer withdrawn from the inbox, not yet bound) binds first.
1444
1661
  if (sleeping && current(ctx.journal, dest) === sleeping.exec && !boundAnswer(ctx.journal.entries(), sleeping) && await adoptionBegun(ctx.journal, dest))
1445
1662
  await adopt(ctx.journal, dest, sleeping, await readCall(ctx.journal, dest), true);
@@ -1613,38 +1830,52 @@ export default function createExecutor(ledgers, options = {}) {
1613
1830
  }
1614
1831
  }
1615
1832
  },
1616
- async recover(wid, journal) {
1833
+ async recover(wid, journal, options = {}) {
1617
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
+ }
1618
1840
  indexSweep(journal);
1619
- 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());
1620
1845
  await effects.recover(journal);
1621
- 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) {
1622
1850
  // F1: an exec whose fence fails stays unfenced and holding; its call parks until a sweep retires it.
1623
1851
  const exec = String(e.exec);
1624
1852
  if (await fence(journal, exec))
1625
1853
  await release(exec);
1626
1854
  }
1627
1855
  // Writers that waited before the restart keep their order while their calls come back.
1628
- for (const e of journal.entries()) {
1629
- const call = String(e.call);
1630
- if (e.type === "writer-wait" && !writerWaits.has(call))
1631
- writerWaits.set(call, { root: String(e.root), since: e.ts, recovered: Date.now() });
1632
- else if (e.type === "writer-acquired" || e.type === JT.sealed || e.type === "retired") {
1633
- const w = writerWaits.get(call);
1634
- if (w?.recovered !== undefined)
1635
- 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
+ }
1636
1867
  }
1637
- }
1638
- 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)));
1639
1869
  for (const call of calls) {
1640
1870
  const session = await readCall(journal, call), values = sessionUsage(session, call);
1641
1871
  await serial(async () => {
1872
+ await repairConsumedAnswers(journal, call, session);
1642
1873
  await forwardsDelivered(journal, call, session);
1643
- 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));
1644
1875
  for (const u of values)
1645
1876
  if (!recorded.has(u.id))
1646
1877
  await journal.append("usage", { call, ...u });
1647
- if (sealed(journal, call) || journal.entries().some(e => e.type === "retired" && e.call === call)) {
1878
+ if (sealed(journal, call) || retiredCall(journal, call)) {
1648
1879
  await retireForwards(journal, call);
1649
1880
  await retireAttention(journal, call);
1650
1881
  await unknownAttention(journal, call);
@@ -1658,13 +1889,36 @@ export default function createExecutor(ledgers, options = {}) {
1658
1889
  if (!active.has(call))
1659
1890
  forgetCall(call);
1660
1891
  }
1661
- 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)))
1662
1894
  await replayForward(e);
1663
- await (await outbox).republishPending();
1664
- // E2: republication may restore envelopes of sealed calls; those are resolved by the seal.
1665
- for (const call of calls)
1666
- 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))
1667
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);
1668
1922
  },
1669
1923
  async retire(widRev) {
1670
1924
  const journal = journals.get(widRev.slice(0, widRev.lastIndexOf("@")));