pi-durable-subagents 1.0.41 → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,6 +35,8 @@ import { eventsLog } from "../paths.js";
35
35
  import { parseModel } from "../compat/model.js";
36
36
  import { PENDING_NOTE, generationRids, openingMessage, pendingFollowUps, pendingNotes, unsettledForward, unsettledNotify } from "./notes.js";
37
37
  import { journalAppends } from "../kernel/journal.js";
38
+ import { callEntries, entriesOf } from "./executor/indexes.js";
39
+ import { lazy, writeSettled } from "./settled.js";
38
40
  import { STATS_EVERY_MS, readBytes, writeStats } from "./stats.js";
39
41
  const tail = (text, n) => text.length > n ? `…${text.slice(-(n - 1))}` : text;
40
42
  const charged = (u) => u && (u.input || u.output || u.costUsd) ? formatUsage(u) : undefined;
@@ -128,6 +130,8 @@ export class Engine {
128
130
  }
129
131
  /** Follow-ups (generations) of the current revision that have not ended: on a finished workflow they are its only live work. */
130
132
  openFollowUps(wf) {
133
+ if (lazy(wf))
134
+ return false; // settled: none open
131
135
  const log = revisionEntries(wf), ended = new Set(log.filter(e => e.type === JT.sealed || e.type === 'retired').map(e => String(e.call)));
132
136
  return log.some(e => e.type === 'generation' && !ended.has(`${wf.wid}@${wf.revision}/${e.key}@${e.gen}`));
133
137
  }
@@ -177,8 +181,26 @@ export class Engine {
177
181
  /** A workflow with nothing live rests its journal: the descriptor closes and nothing reads it periodically; the next
178
182
  * append (a follow-up, resume, revise, stop, prune or a late executor record) reopens it. Only a descriptor is
179
183
  * released: the entries stay in memory, so every decision reads them as before. */
180
- settle(wf) { if (!wf.journal.closed)
181
- wf.journal.resting = this.quiescent(wf); }
184
+ settle(wf) {
185
+ if (wf.journal.closed)
186
+ return;
187
+ const quiet = wf.journal.resting = this.quiescent(wf);
188
+ if (quiet)
189
+ this.recordSettled(wf);
190
+ }
191
+ /** Journal lengths of the workflows whose settled record (settled.ts) was last written or found not due. */
192
+ settledAt = new Map();
193
+ /** Write the settled record of a quiescent workflow whose journal is decoded, once per journal length; a workflow
194
+ * that is not settled has its record removed. Never from a poller: from settle (start, seals, ends). */
195
+ recordSettled(wf) {
196
+ if (wf.journal.loaded === false || !this.executor.recovered)
197
+ return;
198
+ const length = wf.journal.count?.() ?? wf.journal.entries().length;
199
+ if (this.settledAt.get(wf.wid) === length)
200
+ return;
201
+ this.settledAt.set(wf.wid, length);
202
+ writeSettled(this.ledgers.home, wf, call => this.executor.recovered(wf.journal, call));
203
+ }
182
204
  /** Intake passes that ran (ms timestamps of the last minute) and the ledger length after the last one. */
183
205
  passes = [];
184
206
  consumed;
@@ -198,16 +220,28 @@ export class Engine {
198
220
  passesPerSecond: Math.round(this.passes.length / Math.max(1, since / 1000) * 100) / 100, ...(rchar !== undefined ? { readBytes: rchar } : {}) };
199
221
  }
200
222
  started = Date.now();
201
- terminal(wf) { return terminalEntry(revisionEntries(wf)); }
223
+ terminal(wf) { return lazy(wf) ? wf.settled.done : terminalEntry(revisionEntries(wf)); }
202
224
  lifecycle() { return this.ledgers.orch.entries().filter(e => ['admitted', 'applied', 'rejected', 'withdrawn'].includes(e.type)); }
203
- /** A2, P10: Recover executor authority before replaying each unfinished workflow. */
225
+ /** A2, P10: Recover executor authority before replaying each unfinished workflow. Returns what it recovered: the
226
+ * workflows, the calls the executor read and repaired, and those it skipped as already recovered. */
204
227
  async recover() {
205
228
  await this.store.recover();
206
229
  // Before any recovery append, so every journal entry from here on is derived promptly (and a new log derives
207
230
  // everything still on disk).
208
231
  await this.events.open();
232
+ // An executor that can finish a batch runs its workflow-independent steps once, after every workflow.
233
+ const batch = this.executor.finishRecovery !== undefined ? { batch: true } : undefined;
234
+ let calls = 0, skipped = 0;
209
235
  for (const wf of this.store.workflows.values()) {
210
- await this.executor.recover(wf.wid, wf.journal);
236
+ // A settled workflow not decoded (settled.ts): nothing below applies to it (its facts say so).
237
+ const settled = lazy(wf) ? { settled: { calls: wf.settled.calls, sweep: wf.settled.sweep } } : undefined;
238
+ const counts = await this.executor.recover(wf.wid, wf.journal, settled ? { ...batch, ...settled } : batch);
239
+ if (counts) {
240
+ calls += counts.calls;
241
+ skipped += counts.skipped;
242
+ }
243
+ if (settled && wf.journal.loaded === false)
244
+ continue;
211
245
  // A seal may survive a crash before post-seal effects, even after workflow completion.
212
246
  let revision = 1;
213
247
  for (const entry of wf.journal.entries()) {
@@ -216,31 +250,55 @@ export class Engine {
216
250
  if (entry.type !== 'call' && entry.type !== 'generation')
217
251
  continue;
218
252
  const call = `${wf.wid}@${revision}/${entry.key}@${entry.gen}`;
219
- const log = wf.journal.entries();
220
- const result = log.find(e => e.type === JT.sealed && e.call === call)?.result;
221
- if (result?.status !== 'ok' || !log.some(e => e.type === 'wt-intent' && e.call === call) ||
222
- log.some(e => ['wt-removed', 'wt-kept'].includes(e.type) && e.call === call))
253
+ if (!this.worktreeUnsettled(wf, call))
254
+ continue;
255
+ // A revision whose pinned files no longer verify skips this step (the start goes on; the next one retries).
256
+ let original;
257
+ try {
258
+ original = await this.store.atRevision(wf, revision);
259
+ }
260
+ catch (error) {
261
+ console.error(`durable-subagents: worktree step of ${call} skipped: pin-failed: ${error instanceof Error ? error.message : String(error)}`);
223
262
  continue;
224
- const original = await this.store.atRevision(wf, revision);
263
+ }
225
264
  await this.executor.run(this.ticket({ wf: original }, entry));
226
265
  }
227
266
  }
267
+ await this.executor.finishRecovery?.();
228
268
  await this.startHost();
229
269
  for (const intent of this.ledgers.orch.entries().filter(e => e.type === 'revise-intent'))
230
270
  await this.revise(intent);
231
271
  for (const wf of this.store.workflows.values()) {
272
+ // Settled and not decoded: its finished attention is recorded, no generation is open, no follow-up pending.
273
+ if (lazy(wf))
274
+ continue;
232
275
  if (!this.terminal(wf))
233
276
  await this.startWorkflow(wf);
234
277
  else
235
278
  await this.attention(wf);
236
279
  for (const entry of revisionEntries(wf).filter(e => e.type === 'generation'))
237
- this.dispatchGeneration(wf, entry);
280
+ if (!this.settledGeneration(wf, entry))
281
+ this.dispatchGeneration(wf, entry);
238
282
  await this.reopenForwarded(wf);
239
283
  }
240
284
  await this.intake();
241
285
  for (const wf of this.store.workflows.values())
242
286
  this.settle(wf);
243
287
  this.startWaiting();
288
+ return { workflows: this.store.workflows.size, calls, skipped };
289
+ }
290
+ /** A successful call with a worktree whose removal (or keeping) is not recorded yet: its post-seal effect is due. */
291
+ worktreeUnsettled(wf, call) {
292
+ const log = callEntries(wf.journal, call), result = log.find(e => e.type === JT.sealed)?.result;
293
+ return result?.status === 'ok' && log.some(e => e.type === 'wt-intent') && !log.some(e => e.type === 'wt-removed' || e.type === 'wt-kept');
294
+ }
295
+ /** A sealed generation a start need not run again: the executor has nothing to recover for it, its finished attention
296
+ * is recorded and no worktree effect is due (running it would only repeat these post-seal steps). */
297
+ settledGeneration(wf, entry) {
298
+ const id = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
299
+ if (!callEntries(wf.journal, id).some(e => e.type === JT.sealed) || !this.executor.recovered?.(wf.journal, id) || this.worktreeUnsettled(wf, id))
300
+ return false;
301
+ return entriesOf(wf.journal, JT.attention).some(e => isEntry(e, JT.attention) && e.item.id === `finished:${id}`);
244
302
  }
245
303
  /** Every k.waitCheckMs (read here, at orchestrator start), why each live call does not move, as `waiting`/`moving`
246
304
  * events through the pump. The tracker starts from the log's latest transition per call, so a restart repeats none
@@ -284,6 +342,11 @@ export class Engine {
284
342
  async startWorkflow(wf) {
285
343
  if (this.terminal(wf))
286
344
  return;
345
+ if (!this.store.verified(wf.wid)) {
346
+ await this.store.ready(wf);
347
+ if (this.terminal(wf))
348
+ return;
349
+ }
287
350
  wf.journal.resting = false;
288
351
  await this.resolveFinished(wf);
289
352
  const log = revisionEntries(wf);
@@ -365,6 +428,9 @@ export class Engine {
365
428
  }
366
429
  findCall(to, bareWid = false) {
367
430
  for (const wf of this.store.workflows.values()) {
431
+ // Every address of a call starts with its wid: another workflow's journal need not be decoded.
432
+ if (wf.journal.loaded === false && !String(to).startsWith(wf.wid))
433
+ continue;
368
434
  const calls = revisionEntries(wf).filter(e => e.type === 'call' || e.type === 'generation');
369
435
  // For sends, a bare wid addresses its call when the workflow has exactly one key (stop <wid> means the workflow).
370
436
  const keys = new Set(calls.map(e => String(e.key)));
@@ -449,7 +515,9 @@ export class Engine {
449
515
  await this.startWorkflow(wf);
450
516
  }
451
517
  else if (req.kind === 'send') {
452
- const existing = [...this.store.workflows.values()].flatMap(wf => wf.journal.entries().filter(e => e.type === 'generation' && generationRids(e).includes(req.rid)).map(entry => ({ wf, entry })))[0];
518
+ // A generation that took this request is in the workflow it addresses (see findCall).
519
+ const to = String(req.body?.to ?? '');
520
+ const existing = [...this.store.workflows.values()].filter(wf => wf.journal.loaded !== false || to.startsWith(wf.wid)).flatMap(wf => wf.journal.entries().filter(e => e.type === 'generation' && generationRids(e).includes(req.rid)).map(entry => ({ wf, entry })))[0];
453
521
  if (existing) {
454
522
  this.dispatchGeneration(existing.wf, existing.entry);
455
523
  return { action: 'apply' };
@@ -484,6 +552,13 @@ export class Engine {
484
552
  // exactly once). A notify or follow-up whose fate the seal has not settled yet may still become one: wait for it.
485
553
  if (unsettledForward(revisionEntries(wf), from))
486
554
  return { action: 'defer' };
555
+ // A1: the generation runs from the workflow's pinned files: verify them (once per process) before opening it.
556
+ try {
557
+ await this.store.ready(wf);
558
+ }
559
+ catch (error) {
560
+ return { action: 'reject', reason: `pin-failed: ${String(error)}` };
561
+ }
487
562
  if (send.model !== undefined)
488
563
  await this.note(req.rid, send.model, 'next-generation');
489
564
  const opened = await this.openGeneration(wf, entry, from, { rid: req.rid, message: send.message ?? '', ...(send.model !== undefined ? { model: send.model } : {}) });
@@ -528,7 +603,7 @@ export class Engine {
528
603
  // A resume releases held work in its scope (one workflow, one session's, or all) and continues parked workflows;
529
604
  // running ones need nothing and final ones are final.
530
605
  const inScope = (wf) => wid ? wf.wid === wid : origin ? wf.origin === origin : true;
531
- const took = (wf) => wf.journal.entries().some(e => e.type === 'resumed' && e.rid === req.rid);
606
+ const took = (wf) => lazy(wf) ? wf.settled.resumed.includes(req.rid) : wf.journal.entries().some(e => e.type === 'resumed' && e.rid === req.rid);
532
607
  const replayed = this.ledgers.orch.entries().some(e => e.type === 'undrain' && e.rid === req.rid);
533
608
  // Held follow-ups of a finished workflow are released too; they run again through dispatchGeneration below.
534
609
  const holding = [...this.store.workflows.values()].filter(wf => inScope(wf) && this.held(wf.wid) && (!this.terminal(wf) || this.openFollowUps(wf)));
@@ -544,6 +619,19 @@ export class Engine {
544
619
  if (!target && ![...this.store.workflows.values()].some(wf => inScope(wf) && (parked(wf) || took(wf))))
545
620
  return { action: 'reject', reason: 'nothing-to-resume' };
546
621
  }
622
+ // A1: the pinned files of a finished workflow this resume starts are verified first (a start no longer hashes
623
+ // them): a changed file refuses the resume before anything is recorded.
624
+ for (const wf of this.store.workflows.values()) {
625
+ const done = this.terminal(wf);
626
+ if (!inScope(wf) || this.store.verified(wf.wid) || !(done?.status === 'parked' || (releasing && !done)))
627
+ continue;
628
+ try {
629
+ await this.store.ready(wf);
630
+ }
631
+ catch (error) {
632
+ return { action: 'reject', reason: `pin-failed: ${String(error)}` };
633
+ }
634
+ }
547
635
  if (releasing && !replayed)
548
636
  await this.ledgers.orch.append('undrain', { rid: req.rid, ...(wid ? { wid } : origin ? { origin } : {}) });
549
637
  for (const wf of this.store.workflows.values()) {
@@ -564,9 +652,11 @@ export class Engine {
564
652
  if (!this.states.has(wf.wid))
565
653
  await this.startWorkflow(wf);
566
654
  }
655
+ // A settled workflow not decoded has no generation to run (each ended, its finished attention recorded).
567
656
  for (const wf of this.store.workflows.values())
568
- for (const entry of revisionEntries(wf).filter(e => e.type === 'generation'))
569
- this.dispatchGeneration(wf, entry);
657
+ if (!lazy(wf))
658
+ for (const entry of revisionEntries(wf).filter(e => e.type === 'generation'))
659
+ this.dispatchGeneration(wf, entry);
570
660
  }
571
661
  else if (req.kind === 'drain') {
572
662
  const { fence, origin, wid } = req.body ?? {}, scoped = Boolean(origin || wid);
@@ -650,6 +740,12 @@ export class Engine {
650
740
  const done = this.terminal(wf), status = done ? String(done.status) : 'running';
651
741
  if (!['done', 'failed', 'stopped'].includes(status))
652
742
  return `not-finished:${status}`;
743
+ if (lazy(wf)) {
744
+ // Settled (settled.ts): no open generation, every execution fenced, no unresolved fence failure.
745
+ if (this.running.has(wf.wid) || [...this.generations].some(id => id.startsWith(`${wf.wid}@`)))
746
+ return 'open-generation';
747
+ return cutoff !== undefined && done.ts > cutoff ? 'too-recent' : undefined;
748
+ }
653
749
  const log = wf.journal.entries(), has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
654
750
  const openGeneration = log.some(e => e.type === 'generation' && !has(JT.sealed, 'call', `${wf.wid}@${e.revision}/${e.key}@${e.gen}`) && !has('retired', 'call', `${wf.wid}@${e.revision}/${e.key}@${e.gen}`));
655
751
  const liveExec = log.some(e => e.type === JT.exec && !has(JT.fenced, 'exec', e.exec) && !has(JT.sealed, 'call', e.call));
@@ -738,15 +834,40 @@ export class Engine {
738
834
  this.opening.delete(wid);
739
835
  }
740
836
  }
741
- dispatchGeneration(wf, entry) {
742
- const ticket = this.ticket({ wf }, entry), id = ticket.callId;
837
+ dispatchGeneration(wf, entry, refusal) {
838
+ // A finished workflow's pinned files are verified before a generation of it runs (the ticket names its origin); a
839
+ // sealed generation's run only repeats post-seal steps, which read no pinned file. When they do not verify, the
840
+ // generation is sealed failed (`pin-failed: …`) without a child, like any call that cannot be prepared: the engine
841
+ // goes on, the workflow ends again, and a later follow-up verifies the files again.
842
+ if (refusal === undefined && !this.store.verified(wf.wid) && !callEntries(wf.journal, `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`).some(e => e.type === JT.sealed)) {
843
+ const revision = wf.revision, current = () => wf.revision === revision && this.store.workflows.get(wf.wid) === wf && !this.closed;
844
+ void this.store.ready(wf).then(() => { if (current())
845
+ this.dispatchGeneration(wf, entry); }, error => {
846
+ if (!current())
847
+ return;
848
+ const reason = `pin-failed: ${error instanceof Error ? error.message : String(error)}`;
849
+ try {
850
+ this.dispatchGeneration(wf, entry, reason);
851
+ }
852
+ catch (failure) {
853
+ console.error(`durable-subagents: ${String(failure)}`);
854
+ }
855
+ });
856
+ return;
857
+ }
858
+ // Pins not verified (a refusal, or the post-seal steps of a sealed generation): the ticket comes from the journal's
859
+ // entry alone, so a damaged pinned record cannot keep the call from sealing.
860
+ const ticket = refusal !== undefined || !this.store.verified(wf.wid) ? { ...this.unpinnedTicket(wf, entry), ...(refusal !== undefined ? { refusal } : {}) }
861
+ : this.ticket({ wf }, entry), id = ticket.callId;
743
862
  if (this.generations.has(id) || this.held(wf.wid) || wf.journal.entries().some(e => e.type === 'retired' && e.call === id))
744
863
  return;
745
864
  this.generations.add(id);
746
865
  wf.journal.resting = false;
747
- void this.executor.run(ticket).then(() => this.background(async () => {
866
+ void this.executor.run(ticket).then(result => this.background(async () => {
748
867
  if (!wf.journal.entries().some(e => e.type === JT.sealed && e.call === id))
749
868
  throw new Error(`Generation returned without seal: ${id}`);
869
+ if (refusal !== undefined)
870
+ console.error(`durable-subagents: generation ${id} sealed ${result.status}${result.status === 'failed' ? `: ${result.error ?? refusal}` : ''}`);
750
871
  await this.reopenForwarded(wf);
751
872
  if (!wf.journal.entries().some(e => isEntry(e, JT.attention) && e.item.id === `finished:${id}`))
752
873
  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 } });
@@ -817,6 +938,21 @@ export class Engine {
817
938
  ...(entry.type === 'generation' ? { continueFrom: entry.from, opening: entry.opening } : {}),
818
939
  ...(entry.type === 'generation' && typeof entry.model === 'string' ? { model: entry.model } : {}) };
819
940
  }
941
+ /** A ticket from the generation entry alone (call id, key, gen, spec, model), none of the workflow's pinned metadata:
942
+ * the agent is the spec's name only. For a call that is sealed without running, or only repeats post-seal steps. */
943
+ unpinnedTicket(wf, entry) {
944
+ const spec = entry.spec, name = String(spec?.agent ?? '');
945
+ let agent;
946
+ try {
947
+ agent = wf.pins.agents.find(a => a.name === name);
948
+ }
949
+ catch { /* damaged pins: the placeholder below */ }
950
+ return { wid: wf.wid, widRev: `${wf.wid}@${wf.revision}`, key: String(entry.key), gen: Number(entry.gen), callId: `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`,
951
+ spec, cwd: resolve(wf.cwd, spec?.cwd ?? '.'), journal: wf.journal,
952
+ agent: agent ?? { name, description: '', body: '', sourcePath: '', source: 'project', systemPromptMode: 'append', inheritProjectContext: false, inheritSkills: false },
953
+ ...(entry.type === 'generation' ? { continueFrom: entry.from, opening: entry.opening } : {}),
954
+ ...(entry.type === 'generation' && typeof entry.model === 'string' ? { model: entry.model } : {}) };
955
+ }
820
956
  sealed(st, entry) {
821
957
  if (entry.type === 'refused')
822
958
  return refusedResult(String(entry.key), entry.reason);
@@ -6,6 +6,7 @@ import { publishFile } from "../../../kernel/mailbox.js";
6
6
  import { callDir } from "../../../paths.js";
7
7
  import { validate } from "../../../agent/child/schema.js";
8
8
  import { fenceAttentionResolved, recordFenceFailure, recordOnce } from "../sweep.js";
9
+ import { entriesOf } from "../indexes.js";
9
10
  const tracked = (journal, id) => journal.entries().filter(e => e.type === "gate-tracked" && e.id === id).map(e => e.process);
10
11
  // Calls parked on an unfenced gate, woken when the sweep records the gate's outcome.
11
12
  const parked = new Map();
@@ -63,12 +64,18 @@ async function fenceGate(journal, intent, containment) {
63
64
  /** P30, A5, F1: Fence unresolved gate identities before recording their outcome as unknown; a gate whose fence fails
64
65
  * never fails recovery: it stays without an outcome and the executor sweep retries it every K1. */
65
66
  export async function recoverGates(journal, containment) {
66
- for (const intent of journal.entries().filter(e => e.type === "gate-intent")) {
67
+ const intents = entriesOf(journal, "gate-intent");
68
+ if (!intents.length)
69
+ return;
70
+ const outcomes = new Set(entriesOf(journal, "gate").map(e => String(e.id)));
71
+ for (const intent of intents) {
67
72
  const id = String(intent.id);
68
- if (journal.entries().some(e => e.type === "gate" && e.id === id))
73
+ if (outcomes.has(id))
69
74
  continue;
70
- if (await fenceGate(journal, intent, containment))
75
+ if (await fenceGate(journal, intent, containment)) {
71
76
  await gateRetired(journal, id);
77
+ outcomes.add(id);
78
+ }
72
79
  }
73
80
  }
74
81
  function apply(result, record) {
@@ -20,7 +20,8 @@ export default function createEffects(ledgers, containment = serialContainment()
20
20
  return { cwd };
21
21
  }),
22
22
  beforeSeal: (t, exec, result, ctl) => serial(t.callId, async () => {
23
- if (ctl.signal.aborted || ["stopped", "timeout", "budget"].includes(result.status))
23
+ // A refused call did no work: no gate, no output (the executor does not call this for one either).
24
+ if (t.refusal !== undefined || ctl.signal.aborted || ["stopped", "timeout", "budget"].includes(result.status))
24
25
  return result;
25
26
  const intent = t.journal.entries().find(e => e.type === "wt-intent" && e.call === t.callId);
26
27
  const gated = await runGate(t, ledgers.home, intent ? String(intent.path) : t.cwd, exec, result, ctl.signal, containment);