pi-durable-subagents 1.0.25 → 1.0.28

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.
@@ -3,7 +3,8 @@
3
3
  // recorded (until resume); workflows created after it run normally.
4
4
  // Workflow entries: ev {n}; call {pos,key,gen,spec,fingerprint}; refused {pos,key,spec,fingerprint,reason};
5
5
  // reused {pos,key,gen,spec,fingerprint,from}; exposed {pos}; value {n,kind,value};
6
- // generation{rid,key,gen,from,spec,revision,opening} is a send resolution outside the script;
6
+ // generation{rid,key,gen,from,spec,revision,opening,notes?} is a send resolution outside the script (notes: the pending
7
+ // notes its opening carries, see notes.ts); pending-note{rid,call,key,message} records a notify for a sealed call;
7
8
  // its seal has a finished attention independent of workflow completion.
8
9
  // resumed {rid,n} supersedes a terminal park. emit {pos,value} records script outputs.
9
10
  // stop-requested {rid,call?} marks a call or workflow stop as taking effect, so its replay is applied, not already-sealed.
@@ -32,6 +33,9 @@ import { WaitTracker, waitCollector, startWaiting } from "../events/waiting.js";
32
33
  import { readPage } from "../events/log.js";
33
34
  import { eventsLog } from "../paths.js";
34
35
  import { parseModel } from "../compat/model.js";
36
+ import { PENDING_NOTE, pendingNotes, unsettledNotify, withNotes } from "./notes.js";
37
+ import { journalAppends } from "../kernel/journal.js";
38
+ import { STATS_EVERY_MS, readBytes, writeStats } from "./stats.js";
35
39
  const tail = (text, n) => text.length > n ? `…${text.slice(-(n - 1))}` : text;
36
40
  const charged = (u) => u && (u.input || u.output || u.costUsd) ? formatUsage(u) : undefined;
37
41
  const wakeStatus = (status) => {
@@ -141,12 +145,53 @@ export class Engine {
141
145
  hold(wid) {
142
146
  this.running.set(wid, (this.running.get(wid) ?? 0) + 1);
143
147
  let released = false;
144
- return () => { if (released)
145
- return; released = true; const n = this.running.get(wid) - 1; if (n)
146
- this.running.set(wid, n);
147
- else
148
- this.running.delete(wid); };
148
+ return () => {
149
+ if (released)
150
+ return;
151
+ released = true;
152
+ const n = this.running.get(wid) - 1;
153
+ if (n)
154
+ this.running.set(wid, n);
155
+ else
156
+ this.running.delete(wid);
157
+ const wf = this.store.workflows.get(wid);
158
+ if (wf)
159
+ this.settle(wf);
160
+ };
161
+ }
162
+ /** Nothing of the workflow is live: it ended (or parked), no script runs, no executor run or follow-up is open. */
163
+ quiescent(wf) {
164
+ if (!this.terminal(wf) || this.states.has(wf.wid) || this.running.has(wf.wid) || this.openFollowUps(wf))
165
+ return false;
166
+ for (const id of this.generations)
167
+ if (id.startsWith(`${wf.wid}@`))
168
+ return false;
169
+ return true;
170
+ }
171
+ /** A workflow with nothing live rests its journal: the descriptor closes and nothing reads it periodically; the next
172
+ * append (a follow-up, resume, revise, stop, prune or a late executor record) reopens it. Only a descriptor is
173
+ * released: the entries stay in memory, so every decision reads them as before. */
174
+ settle(wf) { if (!wf.journal.closed)
175
+ wf.journal.resting = this.quiescent(wf); }
176
+ /** Intake passes that ran (ms timestamps of the last minute) and the ledger length after the last one. */
177
+ passes = [];
178
+ consumed;
179
+ /** Counters of this process for status and doctor (published to orchestrator-stats.json). */
180
+ stats(now = Date.now()) {
181
+ while (this.passes.length && this.passes[0] < now - 60_000)
182
+ this.passes.shift();
183
+ let live = 0, open = 0;
184
+ for (const wf of this.store.workflows.values()) {
185
+ if (!wf.journal.resting)
186
+ live++;
187
+ if (wf.journal.descriptorOpen !== false && !wf.journal.closed)
188
+ open++;
189
+ }
190
+ const rchar = readBytes(), since = Math.min(60_000, now - this.started);
191
+ return { pid: process.pid, at: now, workflows: this.store.workflows.size, liveWorkflows: live, openJournals: open,
192
+ passesPerSecond: Math.round(this.passes.length / Math.max(1, since / 1000) * 100) / 100, ...(rchar !== undefined ? { readBytes: rchar } : {}) };
149
193
  }
194
+ started = Date.now();
150
195
  terminal(wf) { return terminalEntry(revisionEntries(wf)); }
151
196
  lifecycle() { return this.ledgers.orch.entries().filter(e => ['admitted', 'applied', 'rejected', 'withdrawn'].includes(e.type)); }
152
197
  /** A2, P10: Recover executor authority before replaying each unfinished workflow. */
@@ -186,6 +231,8 @@ export class Engine {
186
231
  this.dispatchGeneration(wf, entry);
187
232
  }
188
233
  await this.intake();
234
+ for (const wf of this.store.workflows.values())
235
+ this.settle(wf);
189
236
  this.startWaiting();
190
237
  }
191
238
  /** Every k.waitCheckMs (read here, at orchestrator start), why each live call does not move, as `waiting`/`moving`
@@ -230,6 +277,7 @@ export class Engine {
230
277
  async startWorkflow(wf) {
231
278
  if (this.terminal(wf))
232
279
  return;
280
+ wf.journal.resting = false;
233
281
  await this.resolveFinished(wf);
234
282
  const log = revisionEntries(wf);
235
283
  const ev = Math.max(0, ...wf.journal.entries().filter(e => e.type === 'ev').map(e => e.n)) + 1;
@@ -241,11 +289,24 @@ export class Engine {
241
289
  }
242
290
  /** P5, P6, A3: Commit lifecycle decisions in kernel order before acknowledging intake. */
243
291
  intake() { return this.serial(() => this.consume()); }
292
+ /** The 1 s poll behind the inbox watcher: a full pass only when a request file waits, the ledger changed since the
293
+ * last pass, or an admitted request is unresolved; otherwise an idle orchestrator reads one empty directory. */
294
+ async pollIntake() {
295
+ const files = await readdir(orchInbox(this.ledgers.home)).catch(error => { if (error.code === 'ENOENT')
296
+ return []; throw error; });
297
+ const last = this.consumed;
298
+ if (!files.length && last && !last.pending && last.length === this.ledgers.orch.entries().length)
299
+ return;
300
+ await this.consume();
301
+ }
244
302
  async consume() {
303
+ this.passes.push(Date.now());
245
304
  const scanned = (await scanInbox(orchInbox(this.ledgers.home))).filter(r => r.to === 'orch');
246
- const retained = this.ledgers.orch.entries().filter(e => e.type === 'request').map(e => e.request);
247
- const candidates = [...retained, ...scanned];
248
305
  const before = reduceLifecycle(this.lifecycle()), staged = new Set();
306
+ // Only unresolved admitted envelopes can still be decided: a resolved one only re-binds its own rid (A1), so the
307
+ // pass hashes and clones what is open, not the whole request history.
308
+ const retained = this.ledgers.orch.entries().filter(e => e.type === 'request' && !before.resolved.has(e.request.rid)).map(e => e.request);
309
+ const candidates = [...retained, ...scanned];
249
310
  for (const request of candidates) {
250
311
  if (!['run', 'revise'].includes(request.kind) || before.admitted.has(request.rid) || before.tombstones.has(request.rid) || staged.has(request.rid))
251
312
  continue;
@@ -292,6 +353,8 @@ export class Engine {
292
353
  throw error; });
293
354
  }
294
355
  }
356
+ const after = reduceLifecycle(this.lifecycle());
357
+ this.consumed = { length: this.ledgers.orch.entries().length, pending: [...after.admitted.keys()].some(rid => !after.resolved.has(rid)) };
295
358
  }
296
359
  findCall(to, bareWid = false) {
297
360
  for (const wf of this.store.workflows.values()) {
@@ -389,6 +452,8 @@ export class Engine {
389
452
  const seal = wf.journal.entries().find(e => e.type === JT.sealed && e.call === from);
390
453
  if (seal && send.kind === 'steer')
391
454
  return { action: 'reject', reason: `finished:${seal.result.status} — use kind "follow-up" to continue it` };
455
+ if (send.kind === 'notify')
456
+ return this.notify(req, wf, entry, from, seal !== undefined);
392
457
  // A pool's name is a model too: the call keeps the pool, and its order and failover apply to the new generation.
393
458
  const pools = this.ledgers.config.pools, pool = send.model !== undefined && pools && Object.hasOwn(pools, send.model);
394
459
  if (send.kind === 'follow-up' && send.model !== undefined && !pool) {
@@ -401,12 +466,20 @@ export class Engine {
401
466
  }
402
467
  }
403
468
  if (seal && send.kind === 'follow-up') {
469
+ // Pending notes ride on the opening message, recorded in the same entry (consumed exactly once). A notify whose
470
+ // fate the seal has not settled yet may still become a note: wait for it.
471
+ const log = revisionEntries(wf);
472
+ if (unsettledNotify(log, from))
473
+ return { action: 'defer' };
474
+ const notes = pendingNotes(log, String(entry.key));
404
475
  const gen = Math.max(0, ...wf.journal.entries().filter(e => ['call', 'generation'].includes(e.type) && e.key === entry.key).map(e => Number(e.gen))) + 1;
405
476
  // A follow-up's model replaces the continued session's for this generation and those continuing it.
406
477
  const spec = send.model !== undefined ? { ...entry.spec, model: send.model } : entry.spec;
407
478
  if (send.model !== undefined)
408
479
  await this.note(req.rid, send.model, 'next-generation');
409
- const opened = await wf.journal.append('generation', { rid: req.rid, key: entry.key, gen, from, spec, revision: wf.revision, opening: { rid: req.rid, kind: send.kind, message: send.message ?? '' }, ...(send.model !== undefined && !pool ? { model: send.model } : {}) });
480
+ const message = withNotes(notes.map(n => String(n.message)), send.message ?? '');
481
+ const opened = await wf.journal.append('generation', { rid: req.rid, key: entry.key, gen, from, spec, revision: wf.revision, opening: { rid: req.rid, kind: send.kind, message },
482
+ ...(notes.length ? { notes: notes.map(n => String(n.rid)) } : {}), ...(send.model !== undefined && !pool ? { model: send.model } : {}) });
410
483
  this.dispatchGeneration(wf, opened);
411
484
  return { action: 'apply' };
412
485
  }
@@ -613,19 +686,64 @@ export class Engine {
613
686
  if (this.generations.has(id) || this.held(wf.wid) || wf.journal.entries().some(e => e.type === 'retired' && e.call === id))
614
687
  return;
615
688
  this.generations.add(id);
689
+ wf.journal.resting = false;
616
690
  void this.executor.run(ticket).then(() => this.background(async () => {
617
691
  if (!wf.journal.entries().some(e => e.type === JT.sealed && e.call === id))
618
692
  throw new Error(`Generation returned without seal: ${id}`);
619
693
  if (!wf.journal.entries().some(e => isEntry(e, JT.attention) && e.item.id === `finished:${id}`))
620
694
  await wf.journal.append(JT.attention, { item: { id: `finished:${id}`, rev: 1, kind: 'finished', wid: wf.wid, call: id, text: finishedText(wf.wid, wf.journal.entries(), id), origin: wf.origin } });
621
695
  this.generations.delete(id);
696
+ this.settle(wf);
622
697
  }), error => {
623
698
  this.generations.delete(id);
699
+ this.settle(wf);
624
700
  if (error instanceof Error && error.name === 'ExecutorShutdown')
625
701
  return;
626
702
  this.background(async () => { throw error; });
627
703
  });
628
704
  }
705
+ /** A notify: forwarded to a running call (the executor says steered or held-until-answer); for a sealed call, or one
706
+ * that sealed before the forward was recorded, a pending note in the workflow journal (`noted`). A replay (the
707
+ * orchestrator died before its decision was recorded) follows what already happened to this rid: a forward the child
708
+ * received is no note; one retired at the seal already became its note; one not settled yet is waited for. The reply
709
+ * (the rid's latest `send-note`) is corrected to match. */
710
+ async notify(req, wf, entry, from, sealed) {
711
+ const message = req.body.message;
712
+ if (typeof message !== 'string' || !message)
713
+ return { action: 'reject', reason: 'malformed: notify needs a message' };
714
+ // Forwards of this rid to any generation of the key (a follow-up may have opened a newer one since).
715
+ const callKey = (call) => call.slice(0, call.lastIndexOf('@'));
716
+ const forwards = () => revisionEntries(wf).filter(e => e.type === 'forward' && e.rid === req.rid && callKey(String(e.dest)) === callKey(from));
717
+ if (!sealed && forwards().every(f => f.dest === from)) {
718
+ const decision = await this.executor.forward(req, this.context(wf, entry));
719
+ if (!(decision.action === 'reject' && decision.reason === 'call-sealed'))
720
+ return decision;
721
+ }
722
+ const log = revisionEntries(wf), noted = () => revisionEntries(wf).some(e => e.type === PENDING_NOTE && e.rid === req.rid);
723
+ const forwarded = forwards();
724
+ if (forwarded.length) {
725
+ if (forwarded.some(f => !log.some(r => r.rid2 === f.rid2 && (r.type === 'forward-delivered' || r.type === 'forward-retired'))))
726
+ return { action: 'defer' };
727
+ await this.delivery(req.rid, noted() ? 'noted' : undefined);
728
+ return { action: 'apply' };
729
+ }
730
+ if (!noted()) {
731
+ // Notes keep the order they were accepted in: one forwarded earlier becomes a note first.
732
+ if (unsettledNotify(log, from))
733
+ return { action: 'defer' };
734
+ await wf.journal.append(PENDING_NOTE, { rid: req.rid, call: from, key: entry.key, message });
735
+ }
736
+ await this.delivery(req.rid, 'noted');
737
+ return { action: 'apply' };
738
+ }
739
+ /** Make the rid's reply say `delivery` (the latest `send-note` counts; see sendReceipt); undefined: the forward reached
740
+ * the call (or was withdrawn), so a recorded held-until-answer stays and anything else says steered. */
741
+ async delivery(rid, delivery) {
742
+ const last = this.ledgers.orch.entries().findLast(e => e.type === 'send-note' && e.rid === rid);
743
+ const want = delivery ?? (last?.delivery === 'held-until-answer' ? 'held-until-answer' : 'steered');
744
+ if (last?.delivery !== want)
745
+ await this.ledgers.orch.append('send-note', { rid, delivery: want });
746
+ }
629
747
  /** The reply to a send that names a model says which model and when it applies (orchestrator ledger `send-note`). */
630
748
  async note(rid, model, effect) {
631
749
  if (!this.ledgers.orch.entries().some(e => e.type === 'send-note' && e.rid === rid))
@@ -824,6 +942,7 @@ export class Engine {
824
942
  if (st)
825
943
  this.evaluator.send({ t: 'stop', wid: wf.wid, ev: st.ev });
826
944
  this.states.delete(wf.wid);
945
+ this.settle(wf);
827
946
  }
828
947
  /** K6, P5: Watch with polling fallback and exit only after continuous quiescence. */
829
948
  async loop(signal) {
@@ -831,7 +950,11 @@ export class Engine {
831
950
  await mkdir(inbox, { recursive: true });
832
951
  this.watcher = watch(inbox, () => this.background(() => this.consume()));
833
952
  this.watcher.on('error', () => { this.watcher?.close(); });
834
- this.poll = setInterval(() => this.background(() => this.consume()), 1000);
953
+ this.poll = setInterval(() => this.background(() => this.pollIntake()), 1000);
954
+ const publish = () => { this.statsWritten = this.statsWritten.then(() => writeStats(this.ledgers.home, this.stats())).catch(error => console.error(`durable-subagents: orchestrator stats not written: ${String(error)}`)); };
955
+ publish();
956
+ this.publishing = setInterval(publish, STATS_EVERY_MS);
957
+ this.publishing.unref?.();
835
958
  let idleSince = performance.now();
836
959
  try {
837
960
  while (!signal?.aborted && !this.closed && !this.restarting) {
@@ -840,7 +963,7 @@ export class Engine {
840
963
  throw this.failure;
841
964
  const files = await readdir(inbox);
842
965
  // Held (drained) workflows cannot progress until a resume request, which restarts the orchestrator: they do not keep it alive.
843
- if (this.generations.size || [...this.store.workflows.values()].some(w => !this.terminal(w) && !this.held(w.wid)) || this.executor.busy() || files.length)
966
+ if (this.generations.size || this.executor.busy() || files.length || this.unfinished())
844
967
  idleSince = performance.now();
845
968
  else if (performance.now() - idleSince >= (this.ledgers.config.k?.idleExitMs ?? 10_000))
846
969
  return;
@@ -850,13 +973,35 @@ export class Engine {
850
973
  finally {
851
974
  this.watcher?.close();
852
975
  clearInterval(this.poll);
853
- }
976
+ clearInterval(this.publishing);
977
+ await this.statsWritten;
978
+ }
979
+ }
980
+ publishing;
981
+ statsWritten = Promise.resolve();
982
+ /** A workflow that can still progress (not terminal, not held). Both depend only on journal entries and the set of
983
+ * workflows, so the answer is reused until this process appends to a journal or the set changes. */
984
+ unfinished() {
985
+ const key = `${journalAppends()}:${this.store.workflows.size}`;
986
+ if (this.unfinishedAt?.key === key)
987
+ return this.unfinishedAt.value;
988
+ let value = false;
989
+ for (const w of this.store.workflows.values())
990
+ if (!this.terminal(w) && !this.held(w.wid)) {
991
+ value = true;
992
+ break;
993
+ }
994
+ this.unfinishedAt = { key, value };
995
+ return value;
854
996
  }
997
+ unfinishedAt;
855
998
  /** A1, A2: Retire asynchronous producers before closing their journals. */
856
999
  async close() {
857
1000
  this.closed = true;
858
1001
  this.watcher?.close();
859
1002
  clearInterval(this.poll);
1003
+ clearInterval(this.publishing);
1004
+ await this.statsWritten;
860
1005
  await this.waiting?.stop();
861
1006
  await this.queue;
862
1007
  await this.evaluator.close();
@@ -8,6 +8,8 @@ import { Containment } from "../platform/containment.js";
8
8
  import { ulid } from "../kernel/ids.js";
9
9
  import { scriptLogPath } from "./snapshot.js";
10
10
  const LOG_LIMIT = 1 << 20, LOG_LINE = 8192, LOG_FULL = '[script.log limit (1 MiB) reached; further console output is dropped]\n';
11
+ /** The process scan of an evaluator host that runs no script (see start). */
12
+ const IDLE_SCAN_MS = 60_000;
11
13
  const LOG_FULL_BYTES = Buffer.byteLength(LOG_FULL);
12
14
  /** P10, P22: One contained evaluator host, retired before any replacement starts. */
13
15
  export class EvaluatorClient {
@@ -19,6 +21,8 @@ export class EvaluatorClient {
19
21
  stopping = false;
20
22
  logs = Promise.resolve();
21
23
  logSizes = new Map();
24
+ /** Workflows whose script the host runs now (started, not stopped, done or failed). */
25
+ scripts = new Set();
22
26
  constructor(ledgers) { this.ledgers = ledgers; }
23
27
  /** P10/P11: Persist one script console line per log event; diagnostics never fail the orchestrator. */
24
28
  log(line) {
@@ -100,18 +104,25 @@ export class EvaluatorClient {
100
104
  createInterface({ input: child.stderr }).on('line', line => this.log(line));
101
105
  createInterface({ input: child.stdout }).on('line', line => {
102
106
  try {
103
- message(JSON.parse(line));
107
+ const parsed = JSON.parse(line);
108
+ if (parsed.t === 'done' || parsed.t === 'error')
109
+ this.scripts.delete(parsed.wid);
110
+ message(parsed);
104
111
  }
105
112
  catch (error) {
106
113
  died(error);
107
114
  }
108
115
  });
109
116
  void child.exited.then(died, died);
110
- let scanning = false;
117
+ let scanning = false, scanned = -Infinity;
118
+ this.scripts.clear();
111
119
  this.timer = setInterval(() => {
112
- if (scanning)
120
+ // Scripts run in vm contexts of worker threads and cannot start processes; the host itself starts none. While no
121
+ // script runs the scan only confirms that, so it runs every IDLE_SCAN_MS instead of every tracker period.
122
+ if (scanning || (!this.scripts.size && performance.now() - scanned < IDLE_SCAN_MS))
113
123
  return;
114
124
  scanning = true;
125
+ scanned = performance.now();
115
126
  this.scan = (async () => {
116
127
  const found = await this.containment.scan(new Map([[exec, known]]));
117
128
  for (const process of found.get(exec) ?? []) {
@@ -127,6 +138,10 @@ export class EvaluatorClient {
127
138
  send(message) {
128
139
  if (!this.child || this.stopping)
129
140
  throw new Error('Evaluator unavailable');
141
+ if (message.t === 'start')
142
+ this.scripts.add(message.wid);
143
+ else if (message.t === 'stop')
144
+ this.scripts.delete(message.wid);
130
145
  this.child.stdin.write(`${JSON.stringify(message)}\n`);
131
146
  }
132
147
  /** A2: Stop tracking and prove retirement before releasing journal authority. */
@@ -0,0 +1,80 @@
1
+ // What the periodic observation of a live call needs from its native session, folded incrementally: readSessionState
2
+ // extends its entries array with the same entry objects when the file grew, so a fold over a prefix is reused and
3
+ // only appended entries are visited. A session read from scratch (rewritten, replaced) restarts the fold. Each fold
4
+ // equals what the whole-array function it replaces computes over the same entries (see the tests).
5
+ import { CT } from "../../types.js";
6
+ import { askOf, cutAskResult, receiptId } from "./session.js";
7
+ import { messageUsage } from "./usage.js";
8
+ export const answerKey = (qid, rev) => JSON.stringify([qid, rev]);
9
+ /** A fold of one session for one call, extended over appended entries. */
10
+ export class SessionFold {
11
+ call;
12
+ entries;
13
+ first;
14
+ last;
15
+ count = 0;
16
+ own = false;
17
+ /** Entries visited since the fold started (a test counter: it grows with appended entries, not with the session). */
18
+ visited = 0;
19
+ state;
20
+ constructor(call) { this.call = call; this.state = SessionFold.empty(); }
21
+ static empty() {
22
+ return { usage: [], receipts: new Map(), questions: [], answered: new Set(), lastQuestion: -1, questionAt: new Map(), execAt: new Map(), results: new Map() };
23
+ }
24
+ update(entries) {
25
+ if (entries === this.entries)
26
+ return this.state;
27
+ const extended = this.count <= entries.length && (this.count === 0 || entries[0] === this.first && entries[this.count - 1] === this.last);
28
+ if (!extended) {
29
+ this.state = SessionFold.empty();
30
+ this.count = 0;
31
+ this.own = false;
32
+ }
33
+ const s = this.state;
34
+ for (; this.count < entries.length; this.count++) {
35
+ const e = entries[this.count], i = this.count;
36
+ this.visited++;
37
+ if (e.type === "custom" && e.customType === CT.exec) {
38
+ this.own = typeof e.data?.exec === "string" && e.data.exec.startsWith(`${this.call}#`);
39
+ s.execAt.set(e.data?.exec, i);
40
+ }
41
+ const u = this.own && e.message && messageUsage(e.message);
42
+ if (u)
43
+ s.usage.push(u);
44
+ const rid = receiptId(e);
45
+ if (rid && !s.receipts.has(rid) && !(e.customType === CT.rejected && e.data?.reason === "identity-conflict"))
46
+ s.receipts.set(rid, e);
47
+ if (e.customType === CT.question) {
48
+ s.questionAt.set(e.data?.qid, i);
49
+ if (e.type === "custom") {
50
+ s.lastQuestion = i;
51
+ if (e.data && typeof e.data.qid === "string" && typeof e.data.rev === "number")
52
+ s.questions.push({ qid: e.data.qid, rev: e.data.rev, question: e.data.question });
53
+ }
54
+ }
55
+ const details = e.message?.details ?? e.details;
56
+ if (details && rid !== undefined)
57
+ s.answered.add(answerKey(details.qid, details.rev));
58
+ const m = e.message;
59
+ if (m?.role === "toolResult" && typeof m.toolCallId === "string" && !s.results.has(m.toolCallId))
60
+ s.results.set(m.toolCallId, e);
61
+ }
62
+ this.entries = entries;
63
+ this.first = entries[0];
64
+ this.last = entries[this.count - 1];
65
+ return s;
66
+ }
67
+ }
68
+ /** openQuestion (hibernate.ts) from a digest of the same entries. */
69
+ export function digestOpenQuestion(entries, s) {
70
+ const at = s.lastQuestion, q = entries[at]?.data;
71
+ if (!q || typeof q.qid !== "string" || typeof q.rev !== "number")
72
+ return;
73
+ if (s.answered.has(answerKey(q.qid, q.rev)))
74
+ return;
75
+ const ask = askOf(entries, at);
76
+ const result = ask === undefined ? undefined : s.results.get(ask);
77
+ if (ask === undefined || result && !cutAskResult(result.message))
78
+ return;
79
+ return { qid: q.qid, rev: q.rev, question: String(q.question) };
80
+ }
@@ -1,7 +1,8 @@
1
1
  // Private journal entries (A1): tracked{exec,pid,start}; loss{exec}; settled{exec};
2
2
  // stop-intent{call}; forward{rid,rid2,dest,hash,envelope:{to,kind,body,cond?}};
3
3
  // forward-delivered{rid,rid2,call,reason?}: the first observed child receipt of a forward (once per forward; reason when
4
- // the child resolved it as rejected, e.g. withdrawn); forward-retired{rid,rid2,reason}: sealed/retired without a receipt (P27).
4
+ // the child resolved it as rejected, e.g. withdrawn); forward-retired{rid,rid2,reason}: sealed/retired without a receipt (P27);
5
+ // an undelivered notify becomes a pending-note{rid,call,key,message} first (../notes.ts).
5
6
  // observation{exec,event}; selected{exec,model}; switch-observed{exec,rid,pool}.
6
7
  // P28 entries are documented in hibernate.ts; generation session publication in generation.ts.
7
8
  // session-corrupt{call,line}: a malformed native session line was skipped (once per line, E4).
@@ -23,6 +24,7 @@ import { buildCallResult } from "../../compat/result.js";
23
24
  import createEffects from "./effects/index.js";
24
25
  import { continueSession } from "./generation.js";
25
26
  import { hibernation, openQuestion } from "./hibernate.js";
27
+ import { SessionFold, answerKey, digestOpenQuestion } from "./digest.js";
26
28
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
27
29
  import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.js";
28
30
  import { activeTotal } from "./time.js";
@@ -33,6 +35,7 @@ import { reached, sessionUsage, totalUsage } from "./usage.js";
33
35
  import { indexSweep, recordFenceFailure, resolveFenceAttention, serialContainment, skipLostCandidate, sweepExecutions } from "./sweep.js";
34
36
  import { gateRetired } from "./effects/gate.js";
35
37
  import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
38
+ import { PENDING_NOTE } from "../notes.js";
36
39
  const MEM_RECORD_MS = 30000;
37
40
  /** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
38
41
  const MEM_WARMUP_MS = 30000;
@@ -272,15 +275,26 @@ export default function createExecutor(ledgers, options = {}) {
272
275
  // E2: inbox files are deleted once their resolution is durable: a child receipt (after an fsync of the session)
273
276
  // or the call's seal. The child never re-applies a resolved request: its receipts are in the session it recovers.
274
277
  const collected = new Map();
278
+ // Per call: what the periodic checks need from its session, folded over appended entries only (digest.ts).
279
+ const folds = new Map();
280
+ const digestOf = (call, entries) => {
281
+ let fold = folds.get(call);
282
+ // Only a running call keeps its fold (it ends with the call); a one-off read (recovery, retirement) folds once.
283
+ if (!fold) {
284
+ fold = new SessionFold(call);
285
+ if (active.has(call))
286
+ folds.set(call, fold);
287
+ }
288
+ return fold.update(entries);
289
+ };
290
+ const forgetCall = (call) => { const a = address(call); forgetSession(callSession(home, a.wid, a.key, a.gen)); folds.delete(call); };
275
291
  async function collectReceipts(call, entries) {
276
292
  const done = collected.get(call) ?? new Set();
277
293
  collected.set(call, done);
278
294
  const fresh = new Set();
279
- for (const e of entries) {
280
- const rid = receiptId(e);
281
- if (rid && !done.has(rid) && !/^\.|[/\\\0]/.test(rid) && !(e.customType === CT.rejected && e.data?.reason === "identity-conflict"))
295
+ for (const rid of digestOf(call, entries).receipts.keys())
296
+ if (!done.has(rid) && !/^\.|[/\\\0]/.test(rid))
282
297
  fresh.add(rid);
283
- }
284
298
  if (!fresh.size)
285
299
  return;
286
300
  const a = address(call), file = await open(callSession(home, a.wid, a.key, a.gen), "r");
@@ -312,17 +326,12 @@ export default function createExecutor(ledgers, options = {}) {
312
326
  await orch.append("send-note", { rid, model, effect, ...(pool ? { pool } : {}) });
313
327
  }
314
328
  async function forwardsDelivered(journal, call, entries) {
315
- const all = journal.entries();
316
- const open = all.filter(e => e.type === "forward" && e.dest === call &&
317
- !all.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || (r.type === "forward-delivered" && r.call === call))));
329
+ const retired = entriesOf(journal, "forward-retired"), delivered = entriesOf(journal, "forward-delivered");
330
+ const open = entriesOf(journal, "forward").filter(e => e.dest === call &&
331
+ !retired.some(r => r.rid2 === e.rid2) && !delivered.some(r => r.rid2 === e.rid2 && r.call === call));
318
332
  if (!open.length)
319
333
  return;
320
- const receipts = new Map();
321
- for (const e of entries) {
322
- const rid = receiptId(e);
323
- if (rid && !receipts.has(rid) && !(e.customType === CT.rejected && e.data?.reason === "identity-conflict"))
324
- receipts.set(rid, e);
325
- }
334
+ const receipts = digestOf(call, entries).receipts;
326
335
  for (const e of open) {
327
336
  const receipt = receipts.get(String(e.rid2));
328
337
  if (!receipt)
@@ -336,8 +345,15 @@ export default function createExecutor(ledgers, options = {}) {
336
345
  await forwardsDelivered(journal, call, entries);
337
346
  const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
338
347
  for (const e of journal.entries().filter(e => e.type === "forward" && e.dest === call)) {
339
- if (!receipts.has(String(e.rid2)) && !journal.entries().some(r => r.type === "forward-retired" && r.rid2 === e.rid2))
348
+ if (!receipts.has(String(e.rid2)) && !journal.entries().some(r => r.type === "forward-retired" && r.rid2 === e.rid2)) {
349
+ // A notify the call never received is not lost: it becomes a pending note (before its forward is retired, so a
350
+ // crash in between finds the forward open again and the note is written once). A withdrawn one is not.
351
+ const envelope = e.envelope, all = journal.entries();
352
+ const withdrawn = all.some(r => r.type === "forward" && r.dest === call && r.envelope.kind === "withdraw" && r.envelope.body.rids?.includes(String(e.rid2)));
353
+ if (envelope.kind === "notify" && !withdrawn && !all.some(r => r.type === PENDING_NOTE && r.rid === e.rid))
354
+ await journal.append(PENDING_NOTE, { rid: e.rid, call, key: address(call).key, message: String(envelope.body?.message ?? "") });
340
355
  await journal.append("forward-retired", { rid: e.rid, rid2: e.rid2, reason: "retired-without-child-receipt" });
356
+ }
341
357
  await (await outbox).markResolved(String(e.rid2));
342
358
  }
343
359
  }
@@ -694,20 +710,12 @@ export default function createExecutor(ledgers, options = {}) {
694
710
  await collectReceipts(t.callId, entries).catch(error => console.error(`durable-subagents: inbox cleanup of ${t.callId} failed: ${String(error)}`));
695
711
  await serial(async () => {
696
712
  await forwardsDelivered(t.journal, t.callId, entries);
697
- for (const e of entries) {
698
- if (e.type !== "custom" || e.customType !== CT.question || !e.data)
699
- continue;
700
- const { qid, rev, question } = e.data;
701
- if (typeof qid !== "string" || typeof rev !== "number")
702
- continue;
713
+ const digest = digestOf(t.callId, entries);
714
+ for (const { qid, rev, question } of digest.questions) {
703
715
  const id = `q:${t.callId}:${qid}`;
704
- if (!t.journal.entries().some(r => isEntry(r, JT.attention) && r.item.id === id && r.item.rev === rev))
716
+ if (!entriesOf(t.journal, JT.attention).some(r => isEntry(r, JT.attention) && r.item.id === id && r.item.rev === rev))
705
717
  await t.journal.append(JT.attention, { item: { id, rev, kind: "question", text: String(question), wid: t.wid, call: t.callId, qid, session: callSession(home, t.wid, t.key, t.gen) } });
706
- const answered = entries.some(r => {
707
- const details = r.message?.details ?? r.details;
708
- return details?.qid === qid && details?.rev === rev && receiptId(r) !== undefined;
709
- });
710
- if (answered && !t.journal.entries().some(r => r.type === JT.attentionResolved && r.id === id && r.rev === rev))
718
+ if (digest.answered.has(answerKey(qid, rev)) && !entriesOf(t.journal, JT.attentionResolved).some(r => r.id === id && r.rev === rev))
711
719
  await t.journal.append(JT.attentionResolved, { id, rev, resolution: "answered" });
712
720
  }
713
721
  });
@@ -1027,18 +1035,18 @@ export default function createExecutor(ledgers, options = {}) {
1027
1035
  track: () => track(journal, exec), fence: async () => { await fence(journal, exec, { child, park: a }); },
1028
1036
  questions: async (entries) => {
1029
1037
  await questions(t, entries);
1030
- const q = openQuestion(entries);
1031
- const segment = entries.findLastIndex(e => e.type === "custom" && e.customType === CT.exec && e.data?.exec === exec);
1032
- if (!q || interrupted(a) || segment < 0 || !entries.slice(segment + 1).some(e => e.customType === CT.question && e.data?.qid === q.qid) || journal.entries().some(e => e.type === "answer-bound" && e.call === t.callId && e.qid === q.qid && e.rev === q.rev))
1038
+ const digest = digestOf(t.callId, entries), q = digestOpenQuestion(entries, digest);
1039
+ const segment = digest.execAt.get(exec) ?? -1;
1040
+ if (!q || interrupted(a) || segment < 0 || !((digest.questionAt.get(q.qid) ?? -1) > segment) || entriesOf(journal, "answer-bound").some(e => e.call === t.callId && e.qid === q.qid && e.rev === q.rev))
1033
1041
  return;
1034
1042
  await serial(async () => {
1035
- const attention = journal.entries().find(e => isEntry(e, JT.attention) && e.item.qid === q.qid && e.item.call === t.callId && e.item.rev === q.rev);
1043
+ 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);
1036
1044
  if (attention && Date.now() - attention.ts >= (config.k?.hibernateMs ?? 120000) && !has(journal, JT.fenced, exec) && hibernation(journal, t.callId)?.exec !== exec) {
1037
1045
  await journal.append("hibernated", { call: t.callId, exec, qid: q.qid, rev: q.rev });
1038
1046
  a.wake();
1039
1047
  }
1040
1048
  });
1041
- }, recordUsage: values => recordUsage(t, values),
1049
+ }, recordUsage: values => recordUsage(t, values), usage: entries => digestOf(t.callId, entries).usage,
1042
1050
  wrote: path => wrote(t, exec, cwd, path),
1043
1051
  switched: event => switched(exec, journal, event), answered: event => answered(t, exec, event), pendingSwitch: () => pendingSwitch(exec),
1044
1052
  });
@@ -1126,7 +1134,7 @@ export default function createExecutor(ledgers, options = {}) {
1126
1134
  for (const e of refusals.keys())
1127
1135
  if (callOf(e) === ticket.callId)
1128
1136
  refusals.delete(e);
1129
- forgetSession(callSession(home, ticket.wid, ticket.key, ticket.gen));
1137
+ forgetCall(ticket.callId);
1130
1138
  wake();
1131
1139
  }
1132
1140
  });
@@ -1245,6 +1253,10 @@ export default function createExecutor(ledgers, options = {}) {
1245
1253
  const send = req.body;
1246
1254
  kind = send.kind;
1247
1255
  body = kind === "model" ? undefined : { message: send.message ?? "" };
1256
+ // A notify is held by the child while its question is open (asking, or hibernated until the answer): the
1257
+ // reply says which (orchestrator ledger `send-note`, once per rid, before the forward is recorded).
1258
+ if (kind === "notify" && !orch.entries().some(e => e.type === "send-note" && e.rid === req.rid))
1259
+ await orch.append("send-note", { rid: req.rid, delivery: openQuestion(await readCall(ctx.journal, dest)) ? "held-until-answer" : "steered" });
1248
1260
  }
1249
1261
  else
1250
1262
  return { action: "reject", reason: "unsupported" };
@@ -1347,10 +1359,8 @@ export default function createExecutor(ledgers, options = {}) {
1347
1359
  await unknownAttention(journal, call);
1348
1360
  }
1349
1361
  });
1350
- if (!active.has(call)) {
1351
- const a = address(call);
1352
- forgetSession(callSession(home, a.wid, a.key, a.gen));
1353
- }
1362
+ if (!active.has(call))
1363
+ forgetCall(call);
1354
1364
  }
1355
1365
  for (const e of journal.entries().filter(e => e.type === "forward" && !journal.entries().some(r => r.type === "forward-retired" && r.rid2 === e.rid2)))
1356
1366
  await replayForward(e);