pi-durable-subagents 1.0.41 → 1.0.43

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.
@@ -1,7 +1,7 @@
1
1
  import { link, mkdir, open, readdir, readFile, unlink } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { contentHash, ulid } from "./ids.js";
4
- import { openJournal, syncDirectory } from "./journal.js";
4
+ import { journalEntryAt, openFoldedJournal, syncDirectory } from "./journal.js";
5
5
  function safeName(name) {
6
6
  if (!name || name === '.' || name === '..' || /[/\\\0]/.test(name))
7
7
  throw new Error('Invalid mailbox identity');
@@ -17,22 +17,34 @@ export async function publishFile(dir, name, bytes, same = existing => existing.
17
17
  await file.writeFile(bytes);
18
18
  await file.sync();
19
19
  await file.close();
20
- try {
21
- await link(temp, target);
22
- }
23
- catch (error) {
24
- if (error.code !== 'EEXIST')
25
- throw error;
26
- let identical = false;
20
+ for (let attempt = 0;; attempt++) {
27
21
  try {
28
- identical = same(await readFile(target));
22
+ await link(temp, target);
23
+ }
24
+ catch (error) {
25
+ if (error.code !== 'EEXIST')
26
+ throw error;
27
+ let existing, identical = false;
28
+ try {
29
+ existing = await readFile(target);
30
+ }
31
+ catch (readError) {
32
+ // The recipient can consume an envelope between EEXIST and this read. Retry the no-replace link, at most
33
+ // five attempts; an already resolved recipient safely consumes a duplicate publication again.
34
+ if (readError.code === 'ENOENT' && attempt < 4)
35
+ continue;
36
+ }
37
+ if (existing)
38
+ try {
39
+ identical = same(existing);
40
+ }
41
+ catch { /* Invalid existing content is a conflict. */ }
42
+ await syncDirectory(dir);
43
+ return identical ? 'exists-identical' : 'conflict';
29
44
  }
30
- catch { /* An unreadable existing file is a conflict. */ }
31
45
  await syncDirectory(dir);
32
- return identical ? 'exists-identical' : 'conflict';
46
+ return 'published';
33
47
  }
34
- await syncDirectory(dir);
35
- return 'published';
36
48
  }
37
49
  finally {
38
50
  await file.close();
@@ -76,31 +88,34 @@ export async function scanInbox(inboxDir, report = (path, error) => console.warn
76
88
  /** P38: A single-authority durable sender; serialize send, replay and deletion. */
77
89
  export class Outbox {
78
90
  journal;
91
+ path;
79
92
  sender;
80
93
  inbox;
81
94
  pending = new Map();
82
- sent = new Map();
95
+ /** Historical envelopes live only on disk; offsets keep idempotent sends and recovery lookups bounded. */
96
+ offsets = new Map();
83
97
  high = new Map();
84
98
  queue = Promise.resolve();
85
99
  closed = false;
86
- constructor(journal, sender, inbox) {
87
- this.journal = journal;
100
+ constructor(path, sender, inbox) {
101
+ this.path = path;
88
102
  this.sender = sender;
89
103
  this.inbox = inbox;
90
- for (const entry of journal.entries()) {
104
+ }
105
+ /** P38: Open outbox/<senderId>.jsonl; caller supplies recipient routing. Only pending envelopes stay resident. */
106
+ static async open(root, senderId, inbox) {
107
+ const box = new Outbox(join(root, 'outbox', `${safeName(senderId)}.jsonl`), senderId, inbox);
108
+ box.journal = await openFoldedJournal(box.path, (entry, offset) => {
91
109
  if (entry.type === 'sent') {
92
110
  const req = entry.request;
93
- this.high.set(req.to, Math.max(this.high.get(req.to) ?? 0, req.sseq));
94
- this.pending.set(req.rid, req);
95
- this.sent.set(req.rid, req);
111
+ box.high.set(req.to, Math.max(box.high.get(req.to) ?? 0, req.sseq));
112
+ box.pending.set(req.rid, req);
113
+ box.offsets.set(req.rid, offset);
96
114
  }
97
115
  else if (entry.type === 'resolved')
98
- this.pending.delete(entry.rid);
99
- }
100
- }
101
- /** P38: Open outbox/<senderId>.jsonl; caller supplies recipient routing. */
102
- static async open(root, senderId, inbox) {
103
- return new Outbox(await openJournal(join(root, 'outbox', `${safeName(senderId)}.jsonl`)), senderId, inbox);
116
+ box.pending.delete(entry.rid);
117
+ });
118
+ return box;
104
119
  }
105
120
  serial(fn) {
106
121
  if (this.closed)
@@ -119,7 +134,7 @@ export class Outbox {
119
134
  send(to, kind, body, cond, opts = {}) {
120
135
  const payload = structuredClone({ body, cond });
121
136
  return this.serial(async () => {
122
- const prior = opts.rid ? this.sent.get(opts.rid) : undefined;
137
+ const prior = opts.rid ? this.recorded(opts.rid) : undefined;
123
138
  if (prior) {
124
139
  if (prior.to !== to || prior.kind !== kind || contentHash({ body: prior.body, cond: prior.cond }) !== contentHash({ body: payload.body, cond: payload.cond }))
125
140
  throw new Error(`Outbox identity conflict: ${opts.rid}`);
@@ -129,15 +144,20 @@ export class Outbox {
129
144
  }
130
145
  const req = { rid: opts.rid ?? ulid(), from: this.sender, to, sseq: (this.high.get(to) ?? 0) + 1, kind, body: payload.body, ...(payload.cond ? { cond: payload.cond } : {}) };
131
146
  await this.journal.append('sent', { request: req });
132
- this.high.set(to, req.sseq);
133
- this.pending.set(req.rid, req);
134
- this.sent.set(req.rid, req);
135
147
  await this.publish(req);
136
148
  return structuredClone(req);
137
149
  });
138
150
  }
139
151
  /** The envelope recorded as sent under `rid`, if any. */
140
- recorded(rid) { const req = this.sent.get(rid); return req && structuredClone(req); }
152
+ recorded(rid) {
153
+ const offset = this.offsets.get(rid);
154
+ const req = this.pending.get(rid) ?? (offset === undefined ? undefined : journalEntryAt(this.path, offset).request);
155
+ return req && structuredClone(req);
156
+ }
157
+ /** The identities still awaiting terminal resolution, without copying their envelopes. */
158
+ pendingRids() { return new Set(this.pending.keys()); }
159
+ /** The recipients of unresolved envelopes. */
160
+ pendingDestinations() { return new Set([...this.pending.values()].map(req => req.to)); }
141
161
  /** P38: Re-publish every unresolved envelope under its original identity. */
142
162
  republishPending() { return this.serial(async () => { for (const req of this.pending.values())
143
163
  await this.publish(req); }); }
@@ -147,7 +167,6 @@ export class Outbox {
147
167
  if (!this.pending.has(rid))
148
168
  return;
149
169
  await this.journal.append('resolved', { rid });
150
- this.pending.delete(rid);
151
170
  });
152
171
  }
153
172
  /** C11: Drain outstanding operations before closing the durable log. */
@@ -0,0 +1,47 @@
1
+ /** A map copy that stores only writes; its source must stay unchanged for the copy's lifetime. */
2
+ export class OverlayMap {
3
+ writes = new Map();
4
+ added = 0;
5
+ base;
6
+ constructor(base) { this.base = base; }
7
+ get size() { return this.base.size + this.added; }
8
+ has(key) { return this.writes.has(key) || this.base.has(key); }
9
+ get(key) { return this.writes.has(key) ? this.writes.get(key) : this.base.get(key); }
10
+ set(key, value) { if (!this.has(key))
11
+ this.added++; this.writes.set(key, value); }
12
+ *entries() {
13
+ for (const [key, value] of this.base)
14
+ yield [key, this.writes.has(key) ? this.writes.get(key) : value];
15
+ for (const pair of this.writes)
16
+ if (!this.base.has(pair[0]))
17
+ yield pair;
18
+ }
19
+ *keys() { for (const [key] of this)
20
+ yield key; }
21
+ *values() { for (const [, value] of this)
22
+ yield value; }
23
+ [Symbol.iterator]() { return this.entries(); }
24
+ forEach(callback, thisArg) {
25
+ for (const [key, value] of this)
26
+ callback.call(thisArg, value, key, this);
27
+ }
28
+ }
29
+ /** The set equivalent of OverlayMap. */
30
+ export class OverlaySet {
31
+ writes = new Set();
32
+ base;
33
+ constructor(base) { this.base = base; }
34
+ get size() { return this.base.size + this.writes.size; }
35
+ has(value) { return this.writes.has(value) || this.base.has(value); }
36
+ add(value) { if (!this.base.has(value))
37
+ this.writes.add(value); }
38
+ *values() { yield* this.base; yield* this.writes; }
39
+ keys() { return this.values(); }
40
+ *entries() { for (const value of this)
41
+ yield [value, value]; }
42
+ [Symbol.iterator]() { return this.values(); }
43
+ forEach(callback, thisArg) {
44
+ for (const value of this)
45
+ callback.call(thisArg, value, value, this);
46
+ }
47
+ }
@@ -17,7 +17,7 @@ import { mkdir, readdir, unlink } from 'node:fs/promises';
17
17
  import { resolve, join } from 'node:path';
18
18
  import { setTimeout as delay } from 'node:timers/promises';
19
19
  import { contentHash } from "../kernel/ids.js";
20
- import { planDecisions, reduceLifecycle } from "../kernel/lifecycle.js";
20
+ import { LifecycleFold, planDecisions } from "../kernel/lifecycle.js";
21
21
  import { scanInbox } from "../kernel/mailbox.js";
22
22
  import { orchInbox, pinnedDir } from "../paths.js";
23
23
  import { SESSION_ID, requestId, specDigest } from "../requests.js";
@@ -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,28 @@ 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
+ this.store.releasePins(wf);
191
+ }
192
+ }
193
+ /** Journal lengths of the workflows whose settled record (settled.ts) was last written or found not due. */
194
+ settledAt = new Map();
195
+ /** Write the settled record of a quiescent workflow whose journal is decoded, once per journal length; a workflow
196
+ * that is not settled has its record removed. Never from a poller: from settle (start, seals, ends). */
197
+ recordSettled(wf) {
198
+ if (wf.journal.loaded === false || !this.executor.recovered)
199
+ return;
200
+ const length = wf.journal.count?.() ?? wf.journal.entries().length;
201
+ if (this.settledAt.get(wf.wid) === length)
202
+ return;
203
+ this.settledAt.set(wf.wid, length);
204
+ writeSettled(this.ledgers.home, wf, call => this.executor.recovered(wf.journal, call));
205
+ }
182
206
  /** Intake passes that ran (ms timestamps of the last minute) and the ledger length after the last one. */
183
207
  passes = [];
184
208
  consumed;
@@ -198,16 +222,74 @@ export class Engine {
198
222
  passesPerSecond: Math.round(this.passes.length / Math.max(1, since / 1000) * 100) / 100, ...(rchar !== undefined ? { readBytes: rchar } : {}) };
199
223
  }
200
224
  started = Date.now();
201
- terminal(wf) { return terminalEntry(revisionEntries(wf)); }
202
- 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
+ terminal(wf) { return lazy(wf) ? wf.settled.done : terminalEntry(revisionEntries(wf)); }
226
+ intakeFold = new LifecycleFold();
227
+ intakeSeen = 0;
228
+ /** Journal positions preserve retained-envelope order, even for repeated request entries. */
229
+ retained = new Map();
230
+ retainedAt = new Map();
231
+ sends = new Map();
232
+ rejectedStages = new Set();
233
+ withdrawnStages = new Set();
234
+ /** One writer appends committed entries; folds never advance past an uncommitted append or an awaited decision. */
235
+ lifecycle() {
236
+ const entries = this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries();
237
+ for (; this.intakeSeen < entries.length; this.intakeSeen++) {
238
+ const entry = entries[this.intakeSeen];
239
+ if (entry.type === 'request') {
240
+ const request = entry.request;
241
+ if (request.kind === 'send') {
242
+ const sent = this.sends.get(request.rid) ?? [];
243
+ sent.push({ at: this.intakeSeen, request });
244
+ this.sends.set(request.rid, sent);
245
+ }
246
+ if (!this.intakeFold.resolved.has(request.rid)) {
247
+ this.retained.set(this.intakeSeen, request);
248
+ const positions = this.retainedAt.get(request.rid) ?? new Set();
249
+ positions.add(this.intakeSeen);
250
+ this.retainedAt.set(request.rid, positions);
251
+ }
252
+ }
253
+ else if (['admitted', 'applied', 'rejected', 'withdrawn'].includes(entry.type)) {
254
+ const record = entry;
255
+ this.intakeFold.apply(record);
256
+ if (record.type === 'withdrawn')
257
+ for (const rid of record.rids)
258
+ this.withdrawnStages.add(rid);
259
+ else {
260
+ const resolution = this.intakeFold.resolved.get(record.rid);
261
+ if (resolution) {
262
+ for (const at of this.retainedAt.get(record.rid) ?? [])
263
+ this.retained.delete(at);
264
+ this.retainedAt.delete(record.rid);
265
+ if (resolution.type === 'rejected' && ['run', 'revise'].includes(this.intakeFold.admitted.get(record.rid)?.kind ?? ''))
266
+ this.rejectedStages.add(record.rid);
267
+ }
268
+ }
269
+ }
270
+ }
271
+ return this.intakeFold;
272
+ }
273
+ /** A2, P10: Recover executor authority before replaying each unfinished workflow. Returns what it recovered: the
274
+ * workflows, the calls the executor read and repaired, and those it skipped as already recovered. */
204
275
  async recover() {
205
276
  await this.store.recover();
206
277
  // Before any recovery append, so every journal entry from here on is derived promptly (and a new log derives
207
278
  // everything still on disk).
208
279
  await this.events.open();
280
+ // An executor that can finish a batch runs its workflow-independent steps once, after every workflow.
281
+ const batch = this.executor.finishRecovery !== undefined ? { batch: true } : undefined;
282
+ let calls = 0, skipped = 0;
209
283
  for (const wf of this.store.workflows.values()) {
210
- await this.executor.recover(wf.wid, wf.journal);
284
+ // A settled workflow not decoded (settled.ts): nothing below applies to it (its facts say so).
285
+ const settled = lazy(wf) ? { settled: { calls: wf.settled.calls, sweep: wf.settled.sweep } } : undefined;
286
+ const counts = await this.executor.recover(wf.wid, wf.journal, settled ? { ...batch, ...settled } : batch);
287
+ if (counts) {
288
+ calls += counts.calls;
289
+ skipped += counts.skipped;
290
+ }
291
+ if (settled && wf.journal.loaded === false)
292
+ continue;
211
293
  // A seal may survive a crash before post-seal effects, even after workflow completion.
212
294
  let revision = 1;
213
295
  for (const entry of wf.journal.entries()) {
@@ -216,31 +298,55 @@ export class Engine {
216
298
  if (entry.type !== 'call' && entry.type !== 'generation')
217
299
  continue;
218
300
  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))
301
+ if (!this.worktreeUnsettled(wf, call))
223
302
  continue;
224
- const original = await this.store.atRevision(wf, revision);
303
+ // A revision whose pinned files no longer verify skips this step (the start goes on; the next one retries).
304
+ let original;
305
+ try {
306
+ original = await this.store.atRevision(wf, revision);
307
+ }
308
+ catch (error) {
309
+ console.error(`durable-subagents: worktree step of ${call} skipped: pin-failed: ${error instanceof Error ? error.message : String(error)}`);
310
+ continue;
311
+ }
225
312
  await this.executor.run(this.ticket({ wf: original }, entry));
226
313
  }
227
314
  }
315
+ await this.executor.finishRecovery?.();
228
316
  await this.startHost();
229
317
  for (const intent of this.ledgers.orch.entries().filter(e => e.type === 'revise-intent'))
230
318
  await this.revise(intent);
231
319
  for (const wf of this.store.workflows.values()) {
320
+ // Settled and not decoded: its finished attention is recorded, no generation is open, no follow-up pending.
321
+ if (lazy(wf))
322
+ continue;
232
323
  if (!this.terminal(wf))
233
324
  await this.startWorkflow(wf);
234
325
  else
235
326
  await this.attention(wf);
236
327
  for (const entry of revisionEntries(wf).filter(e => e.type === 'generation'))
237
- this.dispatchGeneration(wf, entry);
328
+ if (!this.settledGeneration(wf, entry))
329
+ this.dispatchGeneration(wf, entry);
238
330
  await this.reopenForwarded(wf);
239
331
  }
240
332
  await this.intake();
241
333
  for (const wf of this.store.workflows.values())
242
334
  this.settle(wf);
243
335
  this.startWaiting();
336
+ return { workflows: this.store.workflows.size, calls, skipped };
337
+ }
338
+ /** A successful call with a worktree whose removal (or keeping) is not recorded yet: its post-seal effect is due. */
339
+ worktreeUnsettled(wf, call) {
340
+ const log = callEntries(wf.journal, call), result = log.find(e => e.type === JT.sealed)?.result;
341
+ return result?.status === 'ok' && log.some(e => e.type === 'wt-intent') && !log.some(e => e.type === 'wt-removed' || e.type === 'wt-kept');
342
+ }
343
+ /** A sealed generation a start need not run again: the executor has nothing to recover for it, its finished attention
344
+ * is recorded and no worktree effect is due (running it would only repeat these post-seal steps). */
345
+ settledGeneration(wf, entry) {
346
+ const id = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
347
+ if (!callEntries(wf.journal, id).some(e => e.type === JT.sealed) || !this.executor.recovered?.(wf.journal, id) || this.worktreeUnsettled(wf, id))
348
+ return false;
349
+ return entriesOf(wf.journal, JT.attention).some(e => isEntry(e, JT.attention) && e.item.id === `finished:${id}`);
244
350
  }
245
351
  /** Every k.waitCheckMs (read here, at orchestrator start), why each live call does not move, as `waiting`/`moving`
246
352
  * events through the pump. The tracker starts from the log's latest transition per call, so a restart repeats none
@@ -282,6 +388,9 @@ export class Engine {
282
388
  }));
283
389
  }
284
390
  async startWorkflow(wf) {
391
+ if (this.terminal(wf))
392
+ return;
393
+ await this.store.ready(wf);
285
394
  if (this.terminal(wf))
286
395
  return;
287
396
  wf.journal.resting = false;
@@ -302,18 +411,17 @@ export class Engine {
302
411
  const files = await readdir(orchInbox(this.ledgers.home)).catch(error => { if (error.code === 'ENOENT')
303
412
  return []; throw error; });
304
413
  const last = this.consumed;
305
- if (!files.length && last && !last.pending && last.length === this.ledgers.orch.entries().length)
414
+ const length = this.ledgers.orch.count?.() ?? (this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries()).length;
415
+ if (!files.length && last && !last.pending && last.length === length)
306
416
  return;
307
417
  await this.consume();
308
418
  }
309
419
  async consume() {
310
420
  this.passes.push(Date.now());
311
421
  const scanned = (await scanInbox(orchInbox(this.ledgers.home))).filter(r => r.to === 'orch');
312
- const before = reduceLifecycle(this.lifecycle()), staged = new Set();
313
- // Only unresolved admitted envelopes can still be decided: a resolved one only re-binds its own rid (A1), so the
314
- // pass hashes and clones what is open, not the whole request history.
315
- const retained = this.ledgers.orch.entries().filter(e => e.type === 'request' && !before.resolved.has(e.request.rid)).map(e => e.request);
316
- const candidates = [...retained, ...scanned];
422
+ const before = this.lifecycle(), staged = new Set();
423
+ // The watermark index removes envelopes only after a committed terminal resolution.
424
+ const candidates = [...this.retained.values(), ...scanned];
317
425
  for (const request of candidates) {
318
426
  if (!['run', 'revise'].includes(request.kind) || before.admitted.has(request.rid) || before.tombstones.has(request.rid) || staged.has(request.rid))
319
427
  continue;
@@ -347,24 +455,26 @@ export class Engine {
347
455
  for (const { type, ...fields } of resolution)
348
456
  await this.ledgers.orch.append(type, fields);
349
457
  }
350
- const view = reduceLifecycle(this.lifecycle());
351
- for (const [rid, resolution] of view.resolved) {
352
- if (resolution.type === 'rejected' && ['run', 'revise'].includes(view.admitted.get(rid)?.kind ?? ''))
458
+ const view = this.lifecycle();
459
+ for (const pending of [this.rejectedStages, this.withdrawnStages]) {
460
+ for (const rid of pending) {
353
461
  await this.store.discardStage(rid);
462
+ pending.delete(rid);
463
+ }
354
464
  }
355
- for (const rid of view.tombstones)
356
- await this.store.discardStage(rid);
357
465
  for (const req of scanned) {
358
466
  if (view.resolved.has(req.rid) || (view.admitted.has(req.rid) && view.admitted.get(req.rid).hash !== contentHash(req))) {
359
467
  await unlink(join(orchInbox(this.ledgers.home), `${req.rid}.json`)).catch(error => { if (error.code !== 'ENOENT')
360
468
  throw error; });
361
469
  }
362
470
  }
363
- const after = reduceLifecycle(this.lifecycle());
364
- this.consumed = { length: this.ledgers.orch.entries().length, pending: [...after.admitted.keys()].some(rid => !after.resolved.has(rid)) };
471
+ this.consumed = { length: this.intakeSeen, pending: view.open.size > 0 };
365
472
  }
366
473
  findCall(to, bareWid = false) {
367
474
  for (const wf of this.store.workflows.values()) {
475
+ // Every address of a call starts with its wid: another workflow's journal need not be decoded.
476
+ if (wf.journal.loaded === false && !String(to).startsWith(wf.wid))
477
+ continue;
368
478
  const calls = revisionEntries(wf).filter(e => e.type === 'call' || e.type === 'generation');
369
479
  // For sends, a bare wid addresses its call when the workflow has exactly one key (stop <wid> means the workflow).
370
480
  const keys = new Set(calls.map(e => String(e.key)));
@@ -385,9 +495,9 @@ export class Engine {
385
495
  context(wf, entry) { return { journal: wf.journal, widRev: `${wf.wid}@${wf.revision}`, key: entry.key, gen: entry.gen }; }
386
496
  async withdraw(req) {
387
497
  const rids = req.body.rids;
498
+ this.lifecycle();
499
+ const sent = [...new Set(rids)].flatMap(rid => this.sends.get(rid) ?? []).sort((a, b) => a.at - b.at).map(item => item.request);
388
500
  for (const wf of this.store.workflows.values()) {
389
- const requests = this.ledgers.orch.entries().filter(e => e.type === 'request').map(e => e.request);
390
- const sent = requests.filter(r => r.kind === 'send' && rids.includes(r.rid));
391
501
  const visited = new Set();
392
502
  for (const target of sent) {
393
503
  const found = this.findCall(target.body.to, true);
@@ -449,7 +559,9 @@ export class Engine {
449
559
  await this.startWorkflow(wf);
450
560
  }
451
561
  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];
562
+ // A generation that took this request is in the workflow it addresses (see findCall).
563
+ const to = String(req.body?.to ?? '');
564
+ 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
565
  if (existing) {
454
566
  this.dispatchGeneration(existing.wf, existing.entry);
455
567
  return { action: 'apply' };
@@ -484,6 +596,13 @@ export class Engine {
484
596
  // exactly once). A notify or follow-up whose fate the seal has not settled yet may still become one: wait for it.
485
597
  if (unsettledForward(revisionEntries(wf), from))
486
598
  return { action: 'defer' };
599
+ // A1: the generation runs from the workflow's pinned files: verify them (once per process) before opening it.
600
+ try {
601
+ await this.store.ready(wf);
602
+ }
603
+ catch (error) {
604
+ return { action: 'reject', reason: `pin-failed: ${String(error)}` };
605
+ }
487
606
  if (send.model !== undefined)
488
607
  await this.note(req.rid, send.model, 'next-generation');
489
608
  const opened = await this.openGeneration(wf, entry, from, { rid: req.rid, message: send.message ?? '', ...(send.model !== undefined ? { model: send.model } : {}) });
@@ -528,7 +647,7 @@ export class Engine {
528
647
  // A resume releases held work in its scope (one workflow, one session's, or all) and continues parked workflows;
529
648
  // running ones need nothing and final ones are final.
530
649
  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);
650
+ const took = (wf) => lazy(wf) ? wf.settled.resumed.includes(req.rid) : wf.journal.entries().some(e => e.type === 'resumed' && e.rid === req.rid);
532
651
  const replayed = this.ledgers.orch.entries().some(e => e.type === 'undrain' && e.rid === req.rid);
533
652
  // Held follow-ups of a finished workflow are released too; they run again through dispatchGeneration below.
534
653
  const holding = [...this.store.workflows.values()].filter(wf => inScope(wf) && this.held(wf.wid) && (!this.terminal(wf) || this.openFollowUps(wf)));
@@ -544,6 +663,19 @@ export class Engine {
544
663
  if (!target && ![...this.store.workflows.values()].some(wf => inScope(wf) && (parked(wf) || took(wf))))
545
664
  return { action: 'reject', reason: 'nothing-to-resume' };
546
665
  }
666
+ // A1: the pinned files of a finished workflow this resume starts are verified first (a start no longer hashes
667
+ // them): a changed file refuses the resume before anything is recorded.
668
+ for (const wf of this.store.workflows.values()) {
669
+ const done = this.terminal(wf);
670
+ if (!inScope(wf) || !(done?.status === 'parked' || (releasing && !done)))
671
+ continue;
672
+ try {
673
+ await this.store.ready(wf);
674
+ }
675
+ catch (error) {
676
+ return { action: 'reject', reason: `pin-failed: ${String(error)}` };
677
+ }
678
+ }
547
679
  if (releasing && !replayed)
548
680
  await this.ledgers.orch.append('undrain', { rid: req.rid, ...(wid ? { wid } : origin ? { origin } : {}) });
549
681
  for (const wf of this.store.workflows.values()) {
@@ -564,9 +696,11 @@ export class Engine {
564
696
  if (!this.states.has(wf.wid))
565
697
  await this.startWorkflow(wf);
566
698
  }
699
+ // A settled workflow not decoded has no generation to run (each ended, its finished attention recorded).
567
700
  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);
701
+ if (!lazy(wf))
702
+ for (const entry of revisionEntries(wf).filter(e => e.type === 'generation'))
703
+ this.dispatchGeneration(wf, entry);
570
704
  }
571
705
  else if (req.kind === 'drain') {
572
706
  const { fence, origin, wid } = req.body ?? {}, scoped = Boolean(origin || wid);
@@ -650,6 +784,12 @@ export class Engine {
650
784
  const done = this.terminal(wf), status = done ? String(done.status) : 'running';
651
785
  if (!['done', 'failed', 'stopped'].includes(status))
652
786
  return `not-finished:${status}`;
787
+ if (lazy(wf)) {
788
+ // Settled (settled.ts): no open generation, every execution fenced, no unresolved fence failure.
789
+ if (this.running.has(wf.wid) || [...this.generations].some(id => id.startsWith(`${wf.wid}@`)))
790
+ return 'open-generation';
791
+ return cutoff !== undefined && done.ts > cutoff ? 'too-recent' : undefined;
792
+ }
653
793
  const log = wf.journal.entries(), has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
654
794
  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
795
  const liveExec = log.some(e => e.type === JT.exec && !has(JT.fenced, 'exec', e.exec) && !has(JT.sealed, 'call', e.call));
@@ -738,15 +878,53 @@ export class Engine {
738
878
  this.opening.delete(wid);
739
879
  }
740
880
  }
741
- dispatchGeneration(wf, entry) {
742
- const ticket = this.ticket({ wf }, entry), id = ticket.callId;
881
+ dispatchGeneration(wf, entry, refusal, checked = false) {
882
+ const id = `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`;
743
883
  if (this.generations.has(id) || this.held(wf.wid) || wf.journal.entries().some(e => e.type === 'retired' && e.call === id))
744
884
  return;
885
+ // A finished workflow's pinned files are verified before a generation of it runs (the ticket names its origin); a
886
+ // sealed generation's run only repeats post-seal steps, which read no pinned file. When they do not verify, the
887
+ // generation is sealed failed (`pin-failed: …`) without a child, like any call that cannot be prepared: the engine
888
+ // goes on, the workflow ends again, and a later follow-up verifies the files again.
889
+ // Released pins (not resident) take the same asynchronous path: a getter must never throw out of this method.
890
+ if (refusal === undefined && !checked && !(this.store.verified(wf.wid) && this.store.pinsResident(wf)) && !callEntries(wf.journal, `${wf.wid}@${wf.revision}/${entry.key}@${entry.gen}`).some(e => e.type === JT.sealed)) {
891
+ const revision = wf.revision, current = () => wf.revision === revision && this.store.workflows.get(wf.wid) === wf && !this.closed;
892
+ void this.store.ready(wf).then(() => { if (current())
893
+ this.dispatchGeneration(wf, entry, undefined, true); }, error => {
894
+ if (!current())
895
+ return;
896
+ const reason = `pin-failed: ${error instanceof Error ? error.message : String(error)}`;
897
+ try {
898
+ this.dispatchGeneration(wf, entry, reason);
899
+ }
900
+ catch (failure) {
901
+ console.error(`durable-subagents: ${String(failure)}`);
902
+ }
903
+ });
904
+ return;
905
+ }
906
+ // Pins not verified (a refusal, or the post-seal steps of a sealed generation): the ticket comes from the journal's
907
+ // entry alone, so a damaged pinned record cannot keep the call from sealing.
908
+ // After ready, pins released again before this dispatch reload through the checked getter; a load that fails
909
+ // seals this generation alone (`pin-failed: …`), so no getter error escapes and ready is not retried in a loop.
910
+ let ticket;
911
+ if (refusal !== undefined || !this.store.verified(wf.wid))
912
+ ticket = { ...this.unpinnedTicket(wf, entry), ...(refusal !== undefined ? { refusal } : {}) };
913
+ else
914
+ try {
915
+ ticket = this.ticket({ wf }, entry);
916
+ }
917
+ catch (error) {
918
+ refusal = `pin-failed: ${error instanceof Error ? error.message : String(error)}`;
919
+ ticket = { ...this.unpinnedTicket(wf, entry), refusal };
920
+ }
745
921
  this.generations.add(id);
746
922
  wf.journal.resting = false;
747
- void this.executor.run(ticket).then(() => this.background(async () => {
923
+ void this.executor.run(ticket).then(result => this.background(async () => {
748
924
  if (!wf.journal.entries().some(e => e.type === JT.sealed && e.call === id))
749
925
  throw new Error(`Generation returned without seal: ${id}`);
926
+ if (refusal !== undefined)
927
+ console.error(`durable-subagents: generation ${id} sealed ${result.status}${result.status === 'failed' ? `: ${result.error ?? refusal}` : ''}`);
750
928
  await this.reopenForwarded(wf);
751
929
  if (!wf.journal.entries().some(e => isEntry(e, JT.attention) && e.item.id === `finished:${id}`))
752
930
  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 +995,21 @@ export class Engine {
817
995
  ...(entry.type === 'generation' ? { continueFrom: entry.from, opening: entry.opening } : {}),
818
996
  ...(entry.type === 'generation' && typeof entry.model === 'string' ? { model: entry.model } : {}) };
819
997
  }
998
+ /** A ticket from the generation entry alone (call id, key, gen, spec, model), none of the workflow's pinned metadata:
999
+ * the agent is the spec's name only. For a call that is sealed without running, or only repeats post-seal steps. */
1000
+ unpinnedTicket(wf, entry) {
1001
+ const spec = entry.spec, name = String(spec?.agent ?? '');
1002
+ let agent;
1003
+ try {
1004
+ agent = wf.pins.agents.find(a => a.name === name);
1005
+ }
1006
+ catch { /* damaged pins: the placeholder below */ }
1007
+ 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}`,
1008
+ spec, cwd: resolve(wf.cwd, spec?.cwd ?? '.'), journal: wf.journal,
1009
+ agent: agent ?? { name, description: '', body: '', sourcePath: '', source: 'project', systemPromptMode: 'append', inheritProjectContext: false, inheritSkills: false },
1010
+ ...(entry.type === 'generation' ? { continueFrom: entry.from, opening: entry.opening } : {}),
1011
+ ...(entry.type === 'generation' && typeof entry.model === 'string' ? { model: entry.model } : {}) };
1012
+ }
820
1013
  sealed(st, entry) {
821
1014
  if (entry.type === 'refused')
822
1015
  return refusedResult(String(entry.key), entry.reason);