pi-durable-subagents 1.0.39 → 1.0.41

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.
@@ -0,0 +1,40 @@
1
+ // Rebuildable reader caches: checked payloads, published whole, with no durable authority.
2
+ import { randomUUID } from "node:crypto";
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+ import { crc32 } from "./journal.js";
6
+ export function readCache(path) {
7
+ try {
8
+ const { checksum, ...record } = JSON.parse(readFileSync(path, "utf8"));
9
+ return checksum === crc32(Buffer.from(JSON.stringify(record))) ? record : undefined;
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ }
15
+ /** A disappeared journal means pruning won: neither an in-flight reader nor another window recreates its cache. */
16
+ export function writeCache(path, record, journal) {
17
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
18
+ try {
19
+ if (!existsSync(journal))
20
+ return;
21
+ mkdirSync(dirname(path), { recursive: true });
22
+ writeFileSync(tmp, JSON.stringify({ ...record, checksum: crc32(Buffer.from(JSON.stringify(record))) }), { flag: "wx" });
23
+ renameSync(tmp, path);
24
+ if (!existsSync(journal)) {
25
+ rmSync(path, { force: true });
26
+ // A facts cache has one directory per workflow; remove it only if it is empty.
27
+ try {
28
+ rmdirSync(dirname(path));
29
+ }
30
+ catch { /* another cache may still live here */ }
31
+ }
32
+ }
33
+ catch { /* A cache failure only costs another read. */ }
34
+ finally {
35
+ try {
36
+ rmSync(tmp, { force: true });
37
+ }
38
+ catch { /* best effort */ }
39
+ }
40
+ }
@@ -63,11 +63,24 @@ export async function syncDirectory(path) {
63
63
  await file.close();
64
64
  }
65
65
  }
66
- // Readers poll journals (UI, main agent, CLI). Committed bytes never change, so a snapshot is extended by decoding
67
- // only the bytes appended since the last read; a different inode or a shorter file is read from scratch.
68
66
  const snapshots = new Map();
69
67
  /** A1, C11: Read a committed snapshot without repairing or writing its tail. The result is shared and frozen. */
70
68
  export function readJournalSnapshot(path) {
69
+ return (readJournalRecord(path)?.entries ?? []);
70
+ }
71
+ /** Drop a journal's cached entries (a reader that keeps what it derived from them no longer needs them in memory);
72
+ * the next read decodes the file again. */
73
+ export function forgetJournalSnapshot(path) { snapshots.delete(path); }
74
+ /** Drop loaded snapshots selected by a compact reader; work is proportional to loaded journals, not settled history. */
75
+ export function forgetJournalSnapshotsIf(match) {
76
+ for (const path of snapshots.keys())
77
+ if (match(path))
78
+ snapshots.delete(path);
79
+ }
80
+ /** Whether a reader still retains this journal's decoded snapshot (for diagnostics). */
81
+ export function hasJournalSnapshot(path) { return snapshots.has(path); }
82
+ /** readJournalSnapshot with the identity of what was read; undefined when the file does not exist. */
83
+ export function readJournalRecord(path) {
71
84
  let fd;
72
85
  try {
73
86
  fd = openSync(path, 'r');
@@ -75,15 +88,15 @@ export function readJournalSnapshot(path) {
75
88
  catch (error) {
76
89
  if (error.code === 'ENOENT') {
77
90
  snapshots.delete(path);
78
- return [];
91
+ return undefined;
79
92
  }
80
93
  throw error;
81
94
  }
82
95
  try {
83
- const { ino, size } = fstatSync(fd), cached = snapshots.get(path);
84
- if (cached && cached.ino === ino && cached.size === size)
85
- return cached.entries;
86
- const from = cached && cached.ino === ino && size > cached.size ? cached.length : 0;
96
+ const { dev, ino, size } = fstatSync(fd), cached = snapshots.get(path);
97
+ if (cached && cached.dev === dev && cached.ino === ino && cached.size === size)
98
+ return cached;
99
+ const from = cached && cached.dev === dev && cached.ino === ino && size > cached.size ? cached.length : 0;
87
100
  const bytes = Buffer.alloc(size - from);
88
101
  for (let read = 0; read < bytes.length;) {
89
102
  const n = readSync(fd, bytes, read, bytes.length - read, from + read);
@@ -93,8 +106,9 @@ export function readJournalSnapshot(path) {
93
106
  }
94
107
  const decoded = decode(bytes, from ? cached.entries : []);
95
108
  const entries = Object.freeze(decoded.entries);
96
- snapshots.set(path, { ino, size, length: from + decoded.length, entries });
97
- return entries;
109
+ const record = { dev, ino, size, length: from + decoded.length, entries };
110
+ snapshots.set(path, record);
111
+ return record;
98
112
  }
99
113
  finally {
100
114
  closeSync(fd);
@@ -114,8 +128,8 @@ export function readJournalUncached(path) {
114
128
  throw error;
115
129
  }
116
130
  try {
117
- const { ino, size } = fstatSync(fd), cached = snapshots.get(path);
118
- if (cached && cached.ino === ino && cached.size === size)
131
+ const { dev, ino, size } = fstatSync(fd), cached = snapshots.get(path);
132
+ if (cached && cached.dev === dev && cached.ino === ino && cached.size === size)
119
133
  return { ino, size, entries: cached.entries };
120
134
  const bytes = Buffer.alloc(size);
121
135
  for (let read = 0; read < bytes.length;) {
@@ -130,6 +144,66 @@ export function readJournalUncached(path) {
130
144
  closeSync(fd);
131
145
  }
132
146
  }
147
+ /** Fold a committed prefix a bounded chunk at a time. Only one record (possibly larger than a chunk) is buffered;
148
+ * newly appended bytes extend the state, and replacement or shrink rebuilds it. Never repairs the journal. */
149
+ export function readJournalFold(path, prior, empty, apply) {
150
+ let fd;
151
+ try {
152
+ fd = openSync(path, 'r');
153
+ }
154
+ catch (error) {
155
+ if (error.code === 'ENOENT')
156
+ return undefined;
157
+ throw error;
158
+ }
159
+ try {
160
+ const { dev, ino, size } = fstatSync(fd);
161
+ if (prior && prior.dev === dev && prior.ino === ino && prior.size === size)
162
+ return prior;
163
+ const kept = prior && prior.dev === dev && prior.ino === ino && size >= prior.size;
164
+ const record = kept ? { ...prior, size } : { dev, ino, size, length: 0, seen: 0, state: empty() };
165
+ let offset = record.length, pending = Buffer.alloc(0);
166
+ const buffer = Buffer.alloc(Math.min(64 * 1024, Math.max(1, size - offset)));
167
+ while (offset < size) {
168
+ const n = readSync(fd, buffer, 0, Math.min(buffer.length, size - offset), offset);
169
+ if (!n)
170
+ throw new Error(`Journal changed during read: ${path}`);
171
+ offset += n;
172
+ const bytes = pending.length ? Buffer.concat([pending, buffer.subarray(0, n)]) : buffer.subarray(0, n);
173
+ let start = 0, end;
174
+ while ((end = bytes.indexOf(10, start)) >= 0) {
175
+ let entry;
176
+ try {
177
+ const json = unframeLine(bytes.subarray(start, end));
178
+ if (json === undefined)
179
+ throw new Error('CRC');
180
+ entry = JSON.parse(json);
181
+ if (entry.seq !== record.seen + 1 || !Number.isFinite(entry.ts) || typeof entry.type !== 'string')
182
+ throw new Error('Envelope');
183
+ }
184
+ catch (cause) {
185
+ if (offset - bytes.length + end !== size - 1)
186
+ throw new Error(`Journal corruption at byte ${record.length}`, { cause });
187
+ return record;
188
+ }
189
+ apply(record.state, entry);
190
+ record.seen++;
191
+ record.length += end + 1 - start;
192
+ start = end + 1;
193
+ }
194
+ pending = Buffer.from(bytes.subarray(start));
195
+ }
196
+ return record;
197
+ }
198
+ finally {
199
+ closeSync(fd);
200
+ }
201
+ }
202
+ /** Find one record without retaining history (request-time lookups that do not belong in a compact polling state). */
203
+ export function findJournalEntry(path, match) {
204
+ return readJournalFold(path, undefined, () => ({}), (state, entry) => { if (!state.found && match(entry))
205
+ state.found = entry; })?.state.found;
206
+ }
133
207
  /** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
134
208
  export const JOURNAL_REST_MS = 1000;
135
209
  let descriptors = 0, appends = 0;
@@ -10,7 +10,7 @@ import { join } from "node:path";
10
10
  import { contentHash } from "../kernel/ids.js";
11
11
  /** The keys the orchestrator reads; config.json also holds pi-side settings (ui, onQuit) that it ignores. */
12
12
  const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "k"];
13
- const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs"];
13
+ const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs", "resumeSpillMs"];
14
14
  export const configPath = (home) => join(home, "config.json");
15
15
  /** The orchestrator's part of a parsed config.json. */
16
16
  export function orchestratorSettings(raw) {
@@ -71,6 +71,11 @@ export function configProblem(raw) {
71
71
  for (const [key, v] of Object.entries(k)) {
72
72
  if (!K.includes(key))
73
73
  return `k.${key} is not a K-parameter (${K.join(", ")})`;
74
+ if (key === "resumeSpillMs") {
75
+ if (v !== null && !(typeof v === "number" && Number.isFinite(v)))
76
+ return "k.resumeSpillMs must be a finite number of milliseconds or null";
77
+ continue;
78
+ }
74
79
  if (!count(v) || (key !== "lossBound" && key !== "spawnBudget" && v === 0))
75
80
  return `k.${key} must be a positive number`;
76
81
  }
@@ -37,6 +37,17 @@ export function openAsked(entries, call, qid, rev) {
37
37
  return items.some(e => e.item.rev === rev) && !items.some(e => e.item.rev > rev) &&
38
38
  !entries.some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev) && !supersededByBinding(entries, call, qid, rev);
39
39
  }
40
+ /** An answer already forwarded to any open question prevents a planned hibernation, even while its receipt is
41
+ * unconfirmed. Read this inside the serial section that commits the hibernation, never from a prior snapshot. */
42
+ export function answerInFlight(entries, call) {
43
+ return entries.some(e => {
44
+ if (e.type !== "forward" || e.dest !== call)
45
+ return false;
46
+ const env = e.envelope;
47
+ return env?.kind === "answer" && openAsked(entries, call, env.cond?.qid, env.cond?.rev) &&
48
+ !entries.some(r => r.type === "forward-retired" && r.rid2 === e.rid2);
49
+ });
50
+ }
40
51
  /** D2: qid@rev of `call` was superseded by a durable binding: an `answer-bound` names it in `superseded`. The binding is
41
52
  * the source of truth; the attention resolution `superseded` is derived from it (and may lag it across a crash). */
42
53
  export function supersededByBinding(entries, call, qid, rev) {
@@ -21,12 +21,12 @@ 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";
@@ -37,6 +37,7 @@ import { reached, sessionUsage, totalUsage } from "./usage.js";
37
37
  import { indexSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
38
38
  import { gateRetired } from "./effects/gate.js";
39
39
  import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
40
+ import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
40
41
  import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
41
42
  const MEM_RECORD_MS = 30000;
42
43
  /** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
@@ -714,6 +715,8 @@ export default function createExecutor(ledgers, options = {}) {
714
715
  }
715
716
  async function acquireLoop(a, exec, decide, mine, writer) {
716
717
  let continuation = false;
718
+ let pinnedWait;
719
+ let waitMark = "";
717
720
  for (;;) {
718
721
  let signal;
719
722
  const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
@@ -724,10 +727,30 @@ export default function createExecutor(ledgers, options = {}) {
724
727
  return;
725
728
  if (writer && !await writerAdmit(a, writer))
726
729
  return;
727
- const decision = await decide(), models = decision.candidates, pool = decision.pool;
730
+ const decision = await decide(), pool = decision.pool;
731
+ let models = decision.candidates;
732
+ const pinned = decision.spill?.[0];
733
+ const full = (m) => holdings().filter(h => h.pool === m.provider).length >= (settings().providers?.[m.provider ?? ""]?.slots ?? Infinity);
734
+ if (pinned && full(pinned)) {
735
+ if (!sameModel(pinnedWait?.model, pinned))
736
+ pinnedWait = { model: pinned, since: Date.now() };
737
+ const ms = settings().k?.resumeSpillMs;
738
+ if (ms !== null && (ms ?? 120_000) >= 0 && Date.now() - pinnedWait.since >= (ms ?? 120_000))
739
+ models = [...models, ...spillCandidates(pinned, decision.spill)];
740
+ }
741
+ else
742
+ pinnedWait = undefined;
743
+ const mark = pinnedWait ? JSON.stringify(pinnedWait.model) : "";
744
+ if (mark !== waitMark) {
745
+ await a.ticket.journal.append("slot-wait", { call: a.ticket.callId, exec, ...(pinnedWait ? { model: plainModel(pinnedWait.model), since: pinnedWait.since, pool } : {}) });
746
+ waitMark = mark;
747
+ }
728
748
  continuation = decision.continuation;
729
749
  for (const model of models) {
730
- if (!continuation && pool && models.length > 1 && skipped(pool, model))
750
+ const spilling = !!pinned && !sameModel(model, pinned);
751
+ if (pool && (spilling || !continuation && models.length > 1) && skipped(pool, model))
752
+ continue;
753
+ if (failedModel(modelFailures(a.ticket.journal, a.ticket.callId), model))
731
754
  continue;
732
755
  // A pool entry with afterMs waits its turn: it is taken only once this acquisition has waited that long.
733
756
  if (model.afterMs !== undefined && Date.now() - mine.since < model.afterMs)
@@ -774,6 +797,10 @@ export default function createExecutor(ledgers, options = {}) {
774
797
  await orch.append("provider-probe", { provider, exec });
775
798
  }
776
799
  const plain = plainModel(model);
800
+ if (spilling && pinnedWait) {
801
+ continuation = false;
802
+ await a.ticket.journal.append("spilled", { call: a.ticket.callId, exec, pool, from: plainModel(pinned), to: plain, waitedMs: Date.now() - pinnedWait.since });
803
+ }
777
804
  await a.ticket.journal.append("selected", { exec, model: plain, ...(pool ? { pool } : {}) });
778
805
  return plain;
779
806
  }
@@ -807,25 +834,30 @@ export default function createExecutor(ledgers, options = {}) {
807
834
  const { defaultModel: configured, pools } = settings();
808
835
  const raw = t.spec.model ?? t.agent.model ?? configured ?? await defaultModel();
809
836
  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);
837
+ const failures = modelFailures(t.journal, t.callId);
838
+ const candidates = (raw ? resolveModel(raw, pools) : [{ id: "" }]).filter(m => !failedModel(failures, m));
839
+ if (!candidates.length)
840
+ throw new Error(`model-unavailable: no usable model remains; ${String(failures.at(-1)?.reason ?? raw)}`);
841
+ 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));
842
+ const candidate = recorded && candidates.some(m => matches(m, recorded));
812
843
  // Leave the session's model for the pool's others when its pool skips it after losses, or its provider's usage
813
844
  // window is used up; and at a new generation, go back to the pool's order of preference.
814
845
  // A new generation of a pool call starts from the pool also when the session's model is not one of its models
815
846
  // (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);
847
+ const skip = pool && (previous && has(t.journal, "model-unavailable", previous) || (candidate ? previous && ownSegment && skipped(pool, recorded) || unavailable(recorded.provider) || !ownSegment && !!t.continueFrom
848
+ : !ownSegment && !!t.continueFrom));
818
849
  // A model the call was asked to use replaces the session's: launched with it, and holding its provider's slot.
819
850
  const wanted = requestedModel(t.journal, t.callId, t.model);
820
851
  // It outranks the pool's order at a new generation too, also when it names the model the session already has.
821
852
  // A requested model of the call's own pool keeps the pool: a used-up window still moves the call on.
822
853
  const keep = pool && candidates.some(m => m.provider === wanted?.provider && m.id === wanted?.id) ? pool : undefined;
823
- if (wanted)
854
+ if (wanted && !failedModel(failures, wanted))
824
855
  return recorded && !freshFork && recorded.provider === wanted.provider && recorded.id === wanted.id
825
856
  ? { candidates: [recorded], continuation: true, pool: keep }
826
857
  : { candidates: [wanted], continuation: false, pool: keep };
827
- if (recorded && !freshFork && !skip)
828
- return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined };
858
+ if (recorded && !freshFork && !skip && !failedModel(failures, recorded))
859
+ return { candidates: [recorded], continuation: true, pool: candidate ? pool : undefined,
860
+ spill: candidate && pool && !parentPinned(t) ? [recorded, ...candidates.map(m => matches(m, recorded) ? { ...m, id: recorded.id } : m)] : undefined };
829
861
  return { candidates, continuation: false, pool };
830
862
  }
831
863
  /** Resolve a bound answer before it waits for admission; also repairs an interrupted append pair. Called serially. */
@@ -875,12 +907,53 @@ export default function createExecutor(ledgers, options = {}) {
875
907
  await resolveQuestion(journal, call, item.qid, item.rev, "carried");
876
908
  }
877
909
  }
910
+ /** Model identity receipts are durable before the observer fences an unavailable execution. Serial sections only. */
911
+ async function unavailableModel(journal, exec, selected, actual, reason) {
912
+ if (!has(journal, "model-unavailable", exec))
913
+ 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 });
914
+ }
915
+ function allowedModels(journal, exec) {
916
+ const log = journal.entries(), selected = log.find(e => e.type === "selected" && e.exec === exec)?.model;
917
+ const models = selected ? [selected] : [];
918
+ for (const e of log) {
919
+ const envelope = e.envelope;
920
+ if (e.type !== "forward" || e.dest !== callOf(exec) || envelope?.kind !== "model")
921
+ continue;
922
+ if (log.some(r => r.type === "forward-delivered" && r.rid2 === e.rid2 && r.reason !== undefined))
923
+ continue;
924
+ if (log.some(r => r.type === "forward" && r.dest === e.dest && r.envelope?.kind === "withdraw" && r.envelope.body?.rids?.includes(String(e.rid2))))
925
+ continue;
926
+ const body = envelope.body;
927
+ if (body.exec && body.exec !== exec)
928
+ continue;
929
+ models.push({ provider: body.provider, id: body.model });
930
+ }
931
+ for (const e of log)
932
+ if (e.type === "model-ready" && e.exec === exec && models.some(m => sameModel(m, e.selected)))
933
+ models.push(e.model);
934
+ return models;
935
+ }
936
+ async function modelControl(journal, exec, event) {
937
+ if (event.exec !== exec)
938
+ return;
939
+ return serial(async () => {
940
+ if (event.type === CT.modelUnavailable) {
941
+ await unavailableModel(journal, exec, event.selected, event.actual, String(event.reason));
942
+ return false;
943
+ }
944
+ if (event.type === CT.modelReady && allowedModels(journal, exec).some(m => sameModel(m, event.selected)) &&
945
+ !journal.entries().some(e => e.type === "model-ready" && e.exec === exec && sameModel(e.selected, event.selected)))
946
+ await journal.append("model-ready", { exec, selected: event.selected, model: event.model, virtual: event.virtual === true });
947
+ return !has(journal, "model-unavailable", exec);
948
+ });
949
+ }
878
950
  /** The model each execution last answered with (`selected`, then `model-used`), cached per execution. */
879
951
  const inUse = new Map();
880
952
  async function switched(exec, journal, event) {
881
953
  const message = event.message, provider = message?.provider;
882
954
  if (!provider)
883
955
  return;
956
+ let accepted = true;
884
957
  await serial(async () => {
885
958
  // Evidence of the model in use: the provider and model of each assistant message, recorded when it changes.
886
959
  if (message.role === "assistant" && message.model) {
@@ -894,6 +967,13 @@ export default function createExecutor(ledgers, options = {}) {
894
967
  await journal.append("model-used", { exec, model: { provider, id: message.model } });
895
968
  inUse.set(exec, name);
896
969
  }
970
+ const virtual = journal.entries().findLast(e => e.type === "model-ready" && e.exec === exec)?.virtual === true;
971
+ if (!virtual && !allowedModels(journal, exec).some(m => sameModel(m, { provider, id: message.model }))) {
972
+ const selected = journal.entries().find(e => e.type === "selected" && e.exec === exec)?.model;
973
+ await unavailableModel(journal, exec, selected, { provider, id: message.model }, "child reported an unselected model");
974
+ accepted = false;
975
+ return;
976
+ }
897
977
  }
898
978
  const target = holdings().find(h => h.exec === exec && h.pool === provider && h.reserved);
899
979
  if (!target)
@@ -905,6 +985,7 @@ export default function createExecutor(ledgers, options = {}) {
905
985
  }
906
986
  });
907
987
  wake();
988
+ return accepted;
908
989
  }
909
990
  /** The model an execution last answered with, or was launched on. */
910
991
  function modelOf(journal, exec) {
@@ -1118,7 +1199,22 @@ export default function createExecutor(ledgers, options = {}) {
1118
1199
  bound = pendingAnswer;
1119
1200
  if (exec) {
1120
1201
  await fence(journal, exec, { park: a });
1121
- await questions(t, entries = await readCall(journal, t.callId));
1202
+ entries = await readCall(journal, t.callId);
1203
+ await serial(() => repairConsumedAnswers(journal, t.callId, entries));
1204
+ await questions(t, entries);
1205
+ bound ??= journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId && e.reason === "answered-in-session");
1206
+ // A binding excuses only the execution it was bound to (the asker it ended) and the first launch after it while
1207
+ // that launch never started a child. Every later or started execution is judged by its own evidence, so a
1208
+ // child that dies before writing its exec marker counts toward lossBound instead of relaunching forever.
1209
+ if (bound) {
1210
+ const all = journal.entries(), execSeq = all.find(r => r.type === JT.exec && r.exec === exec).seq;
1211
+ const firstAfter = !all.some(r => r.type === JT.exec && r.call === t.callId && r.seq > bound.seq && r.seq < execSeq);
1212
+ if (!(bound.seq > execSeq || firstAfter && !has(journal, "tracked", exec) &&
1213
+ !digestOf(t.callId, entries).execAt.has(exec)))
1214
+ bound = undefined;
1215
+ }
1216
+ if (bound)
1217
+ await release(exec);
1122
1218
  // D6: after the fence the session is final. A bound answer it closed (answered, superseded, or re-asked as a newer
1123
1219
  // revision) is settled; if the session still has an open question of this call, the call does not launch: it
1124
1220
  // hibernates again on that question (its attention is open, so the parent is asked), and resumes only on a new
@@ -1142,8 +1238,18 @@ export default function createExecutor(ledgers, options = {}) {
1142
1238
  return finish(journal, t.callId, exec, makeResult("timeout"));
1143
1239
  if (ev.budget || reached(totalUsage(journal.entries(), t.callId), t.spec.budget))
1144
1240
  return finish(journal, t.callId, exec, makeResult("budget"));
1241
+ for (const e of entries)
1242
+ if (e.customType === CT.modelUnavailable && e.data?.exec === exec)
1243
+ await modelControl(journal, exec, { type: CT.modelUnavailable, ...e.data });
1244
+ const modelFailure = entriesOf(journal, "model-unavailable", exec).at(-1);
1245
+ if (modelFailure) {
1246
+ const selected = entriesOf(journal, "selected", exec).at(-1);
1247
+ if (!selected?.pool)
1248
+ return finish(journal, t.callId, exec, makeResult("failed", "", `model-unavailable: ${String(modelFailure.reason)}`));
1249
+ await release(exec);
1250
+ }
1145
1251
  // 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)) {
1252
+ if (!bound && !modelFailure && !has(journal, "spawn-env-failed", exec)) {
1147
1253
  // P28: an execution cut off while its only unfinished tool call is the open question's `ask` (before it
1148
1254
  // hibernated) was waiting, not working: it hibernates now and resumes with the answer, like a planned
1149
1255
  // hibernation; it is neither a loss nor, for `once`, an unknown outcome.
@@ -1289,13 +1395,18 @@ export default function createExecutor(ledgers, options = {}) {
1289
1395
  return;
1290
1396
  await serial(async () => {
1291
1397
  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) {
1398
+ const all = journal.entries();
1399
+ if (attention && Date.now() - attention.ts >= (config.k?.hibernateMs ?? 120000) && !interrupted(a) && current(journal, t.callId) === exec &&
1400
+ openAsked(all, t.callId, q.qid, q.rev) && !answerInFlight(all, t.callId) &&
1401
+ !all.some(e => e.type === "answer-bound" && e.call === t.callId && e.qid === q.qid && e.rev === q.rev) &&
1402
+ !has(journal, JT.fenced, exec) && hibernation(journal, t.callId)?.exec !== exec) {
1293
1403
  await journal.append("hibernated", { call: t.callId, exec, qid: q.qid, rev: q.rev });
1294
1404
  a.wake();
1295
1405
  }
1296
1406
  });
1297
1407
  }, recordUsage: values => recordUsage(t, values), usage: entries => digestOf(t.callId, entries).usage,
1298
1408
  wrote: path => wrote(t, exec, cwd, path),
1409
+ modelControl: event => modelControl(journal, exec, event),
1299
1410
  switched: event => switched(exec, journal, event), answered: event => answered(t, exec, event), pendingSwitch: () => pendingSwitch(exec),
1300
1411
  });
1301
1412
  }
@@ -1306,14 +1417,57 @@ export default function createExecutor(ledgers, options = {}) {
1306
1417
  }
1307
1418
  }
1308
1419
  /**
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.
1420
+ * P28: reconcile an answer forwarded before an interrupted asker hibernated. A consumed answer continues the
1421
+ * session; an unconsumed one binds like an answer given during hibernation and retires its original forward.
1422
+ * The reply "apply" already given (and any retry with the same rid) stays true.
1313
1423
  */
1314
1424
  async function adoptAnswer(journal, call, sleeping) {
1315
1425
  const entries = await readCall(journal, call);
1316
- await serial(() => adopt(journal, call, sleeping, entries));
1426
+ await serial(async () => { await repairConsumedAnswers(journal, call, entries); await adopt(journal, call, sleeping, entries); });
1427
+ }
1428
+ /** A fenced asker may have consumed its forwarded answer before the fence. Publish the binding first, then its
1429
+ * derived resolution and delivery: every prefix is repaired on retry/recovery. Never resend the answer; the next
1430
+ * execution uses a plain continue in the same session. Called serially, only after the current execution is fenced. */
1431
+ async function repairConsumedAnswers(journal, call, entries) {
1432
+ const exec = current(journal, call);
1433
+ if (!exec || !has(journal, JT.fenced, exec) || sealed(journal, call) || journal.entries().some(e => e.type === "retired" && e.call === call))
1434
+ return;
1435
+ const digest = digestOf(call, entries);
1436
+ for (const f of entriesOf(journal, "forward").filter(e => e.dest === call)) {
1437
+ const env = f.envelope, qid = env.cond?.qid, rev = env.cond?.rev;
1438
+ if (env.kind !== "answer" || !digest.questions.some(q => q.qid === qid && q.rev === rev) ||
1439
+ journal.entries().some(e => e.type === "forward-retired" && e.rid2 === f.rid2))
1440
+ continue;
1441
+ const receipt = digest.receipts.get(String(f.rid2)), details = receipt?.message?.details ?? receipt?.details;
1442
+ if (!receipt || details?.qid !== qid || details?.rev !== rev)
1443
+ continue;
1444
+ // The binding must not outlive the evidence it derives: fsync the native receipt before journal publication.
1445
+ await collectReceipts(call, [...entries]);
1446
+ const binding = journal.entries().find(e => e.type === "answer-bound" && e.call === call && e.qid === qid && e.rev === rev);
1447
+ // A normal settled turn needs no continuation, nor does an answer consumed in an earlier execution. A receipt
1448
+ // in this execution counts even if observation already resolved its attention before the fence.
1449
+ const sleeping = hibernation(journal, call), segment = digest.execAt.get(exec);
1450
+ const at = entries.indexOf(receipt), consumedHere = segment !== undefined && at > segment;
1451
+ // The execution stopped ON that ask: its result is the answer receipt and nothing ran after it (no report, no
1452
+ // question, no tool call, no finished assistant turn, no other unfinished tool). Otherwise the execution went on
1453
+ // working after the answer and its own evidence (report, once + dangling, loss) decides as usual.
1454
+ const after = entries.slice(at + 1);
1455
+ const stoppedOnAsk = consumedHere && receipt.message?.role === "toolResult" && receipt.message.toolName === "ask" &&
1456
+ !evidence([...entries], exec).dangling.length &&
1457
+ !after.some(e => e.type === "custom" && (e.customType === CT.report || e.customType === CT.question) ||
1458
+ e.message?.role === "assistant" && ((Array.isArray(e.message.content) && e.message.content.some(b => b.type === "toolCall")) ||
1459
+ (e.message.stopReason !== "aborted" && e.message.stopReason !== "error")));
1460
+ const superseded = supersededBy(details);
1461
+ const sleepingAnswered = sleeping?.exec === exec && (sleeping.qid === qid && sleeping.rev === rev ||
1462
+ superseded.some(q => q.qid === sleeping.qid && q.rev === sleeping.rev));
1463
+ if (!binding && (sleepingAnswered || stoppedOnAsk && !has(journal, "settled", exec)))
1464
+ await journal.append("answer-bound", { call, qid, rev, rid: f.rid, rid2: f.rid2, hash: f.hash, reason: "answered-in-session",
1465
+ ...(superseded.length ? { superseded } : {}) });
1466
+ await resolveBoundAnswer(journal, call, qid, rev);
1467
+ for (const q of superseded)
1468
+ await resolveQuestion(journal, call, q.qid, q.rev, "superseded");
1469
+ }
1470
+ await forwardsDelivered(journal, call, [...entries]);
1317
1471
  }
1318
1472
  /** The forward whose adoption was begun (its envelope withdrawn from the child's inbox) and not yet bound. */
1319
1473
  async function adoptionBegun(journal, call) {
@@ -1325,9 +1479,20 @@ export default function createExecutor(ledgers, options = {}) {
1325
1479
  * adoption was begun before a crash (its envelope is withdrawn, so it can reach the child only through this binding).
1326
1480
  * Called serially. */
1327
1481
  async function adopt(journal, call, sleeping, entries, onlyBegun = false) {
1328
- const all = journal.entries();
1329
- if (boundAnswer(all, sleeping))
1482
+ const all = journal.entries(), bound = boundAnswer(all, sleeping);
1483
+ if (bound) {
1484
+ // Repair an adoption cut off after its binding but before resolution/retirement. The original forward and
1485
+ // derived bound identity prove adoption; a consumed answer instead keeps its original delivered identity.
1486
+ await resolveBoundAnswer(journal, call, bound.qid, bound.rev);
1487
+ await resolveSuperseded(journal, call);
1488
+ const f = all.find(e => e.type === "forward" && e.dest === call && e.rid === bound.rid &&
1489
+ contentHash([String(e.rid2), "hibernated"]) === bound.rid2);
1490
+ if (f && !all.some(e => e.type === "forward-retired" && e.rid2 === f.rid2))
1491
+ await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
1492
+ if (f)
1493
+ await (await outbox).markResolved(String(f.rid2));
1330
1494
  return;
1495
+ }
1331
1496
  const begun = await adoptionBegun(journal, call);
1332
1497
  const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
1333
1498
  // The answer to the question it hibernated on, else to another of its questions still open (an earlier one).
@@ -1425,6 +1590,14 @@ export default function createExecutor(ledgers, options = {}) {
1425
1590
  if (prior) {
1426
1591
  if (prior.hash !== hash)
1427
1592
  return { action: "reject", reason: "identity-conflict" };
1593
+ if (prior.envelope.kind === "answer") {
1594
+ await repairConsumedAnswers(ctx.journal, dest, await readCall(ctx.journal, dest));
1595
+ const exec = current(ctx.journal, dest);
1596
+ if (exec && has(ctx.journal, JT.fenced, exec)) {
1597
+ active.get(dest)?.wake();
1598
+ wake();
1599
+ }
1600
+ }
1428
1601
  if (!ctx.journal.entries().some(e => e.type === "forward-retired" && e.rid2 === prior.rid2))
1429
1602
  await replayForward(prior);
1430
1603
  return { action: "apply" };
@@ -1440,6 +1613,12 @@ export default function createExecutor(ledgers, options = {}) {
1440
1613
  return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
1441
1614
  if (req.kind === "send" && req.body.kind === "answer") {
1442
1615
  const sleeping = hibernation(ctx.journal, dest);
1616
+ await repairConsumedAnswers(ctx.journal, dest, await readCall(ctx.journal, dest));
1617
+ const exec = current(ctx.journal, dest);
1618
+ if (exec && has(ctx.journal, JT.fenced, exec)) {
1619
+ active.get(dest)?.wake();
1620
+ wake();
1621
+ }
1443
1622
  // An adoption begun before a crash (the earlier answer withdrawn from the inbox, not yet bound) binds first.
1444
1623
  if (sleeping && current(ctx.journal, dest) === sleeping.exec && !boundAnswer(ctx.journal.entries(), sleeping) && await adoptionBegun(ctx.journal, dest))
1445
1624
  await adopt(ctx.journal, dest, sleeping, await readCall(ctx.journal, dest), true);
@@ -1639,6 +1818,7 @@ export default function createExecutor(ledgers, options = {}) {
1639
1818
  for (const call of calls) {
1640
1819
  const session = await readCall(journal, call), values = sessionUsage(session, call);
1641
1820
  await serial(async () => {
1821
+ await repairConsumedAnswers(journal, call, session);
1642
1822
  await forwardsDelivered(journal, call, session);
1643
1823
  const recorded = new Set(journal.entries().filter(e => e.type === "usage" && e.call === call).map(e => e.id));
1644
1824
  for (const u of values)