pi-durable-subagents 1.0.40 → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,43 @@
1
1
  import { open, mkdir } from 'node:fs/promises';
2
- import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';
2
+ import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, openSync, readFileSync, readSync } from 'node:fs';
3
3
  import { dirname } from 'node:path';
4
+ import * as zlib from 'node:zlib';
4
5
  const TABLE = new Uint32Array(256).map((_, n) => { let c = n; for (let k = 0; k < 8; k++)
5
6
  c = (c & 1) ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0; });
7
+ /** The CRC-32 (IEEE) of `bytes` as an unsigned number: node's native one when it has it (22.2+), else a table. */
8
+ const crcValue = typeof zlib.crc32 === 'function'
9
+ ? bytes => zlib.crc32(bytes)
10
+ : bytes => {
11
+ let crc = 0xffffffff;
12
+ for (let i = 0; i < bytes.length; i++)
13
+ crc = TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
14
+ return (crc ^ 0xffffffff) >>> 0;
15
+ };
6
16
  /** C11: the CRC-32 (IEEE) of a record, 8 lowercase hex digits: the frame of every journal line. */
7
17
  export function crc32(bytes) {
8
- let crc = 0xffffffff;
9
- for (let i = 0; i < bytes.length; i++)
10
- crc = TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
11
- return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0');
18
+ return crcValue(bytes).toString(16).padStart(8, '0');
19
+ }
20
+ /** The value of the 8 lowercase hex digits at `bytes[0..8)` followed by a space, or -1 when they are not that. */
21
+ function frameHead(bytes) {
22
+ if (bytes.length < 9 || bytes[8] !== 32)
23
+ return -1;
24
+ let value = 0;
25
+ for (let i = 0; i < 8; i++) {
26
+ const c = bytes[i], digit = c >= 48 && c <= 57 ? c - 48 : c >= 97 && c <= 102 ? c - 87 : -1;
27
+ if (digit < 0)
28
+ return -1;
29
+ value = value * 16 + digit;
30
+ }
31
+ return value;
12
32
  }
13
33
  /** C11: One framed line `<crc32 hex 8> <json>\n` (the journal format; the event log uses it too). */
14
34
  export function frameLine(json) { return `${crc32(Buffer.from(json))} ${json}\n`; }
15
35
  /** C11: The JSON text of one framed line (without its newline), or undefined when its frame or checksum is wrong. */
16
36
  export function unframeLine(line) {
17
- if (line.length < 10 || line[8] !== 32)
37
+ if (line.length < 10)
18
38
  return undefined;
19
- const head = Buffer.from(line.subarray(0, 8)).toString(), json = line.subarray(9);
20
- return /^[0-9a-f]{8}$/.test(head) && crc32(json) === head ? Buffer.from(json).toString() : undefined;
39
+ const head = frameHead(line), json = line.subarray(9);
40
+ return head >= 0 && crcValue(json) === head ? Buffer.from(json.buffer, json.byteOffset, json.byteLength).toString() : undefined;
21
41
  }
22
42
  /** Entries are immutable history (A1): freeze them so shared snapshots can be handed out without copying. */
23
43
  function freeze(value) {
@@ -36,10 +56,10 @@ function decode(bytes, prior = []) {
36
56
  if (end < 0)
37
57
  break;
38
58
  try {
39
- const line = bytes.subarray(offset, end), json = line.subarray(9);
40
- if (!/^[0-9a-f]{8} $/.test(line.subarray(0, 9).toString()) || crc32(json) !== line.subarray(0, 8).toString())
59
+ const line = bytes.subarray(offset, end), json = line.subarray(9), head = frameHead(line);
60
+ if (head < 0 || crcValue(json) !== head)
41
61
  throw new Error('CRC');
42
- const entry = JSON.parse(json.toString());
62
+ const entry = JSON.parse(bytes.toString('utf8', offset + 9, end));
43
63
  if (entry.seq !== entries.length + 1 || !Number.isFinite(entry.ts) || typeof entry.type !== 'string')
44
64
  throw new Error('Envelope');
45
65
  entries.push(freeze(entry));
@@ -214,35 +234,165 @@ export function openJournalDescriptors() { return descriptors; }
214
234
  /** A1, C11: Repair only the tail, then serialize durable framed appends. A resting handle (`resting = true`) closes its
215
235
  * descriptor once its appends are done and reopens it for the next append; its entries stay in memory. */
216
236
  export async function openJournal(path) {
217
- await mkdir(dirname(path), { recursive: true });
218
- let created = false;
219
- const first = await open(path, 'ax+').then(f => { created = true; return f; }, async (error) => {
220
- if (error.code !== 'EEXIST')
221
- throw error;
222
- return open(path, 'a+');
223
- });
224
- let entries, size;
237
+ return (await openHandle(path));
238
+ }
239
+ /** The expectation a journal handle meets now (its committed bytes, read back from the file), for a later lazy open;
240
+ * undefined when the file has no complete entry or does not end at the committed length. */
241
+ export function journalExpectation(journal) {
242
+ const entries = journal.committed?.() ?? journal.entries(), count = entries.length;
243
+ if (!count)
244
+ return undefined;
245
+ let fd;
225
246
  try {
226
- const bytes = await first.readFile(), decoded = decode(bytes);
227
- entries = decoded.entries;
228
- size = decoded.length;
229
- if (decoded.length !== bytes.length) {
230
- await first.truncate(decoded.length);
231
- await first.sync();
247
+ fd = openSync(journal.path, 'r');
248
+ }
249
+ catch {
250
+ return undefined;
251
+ }
252
+ try {
253
+ const { ino, size } = fstatSync(fd), tail = lastLine(fd, size);
254
+ if (!tail)
255
+ return undefined;
256
+ // The last line must be the last committed entry (a torn tail is truncated by every open, never trusted).
257
+ const json = unframeLine(tail.subarray(0, tail.length - 1));
258
+ if (json === undefined || JSON.parse(json).seq !== count)
259
+ return undefined;
260
+ return { ino, size, count, tail: crc32(tail), tailLength: tail.length };
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ finally {
266
+ closeSync(fd);
267
+ }
268
+ }
269
+ /** The last line of the file (with its newline), when the file ends with one. Reads from the end in chunks. */
270
+ function lastLine(fd, size) {
271
+ if (!size)
272
+ return undefined;
273
+ let chunk = 4096, buffer = Buffer.alloc(0);
274
+ for (let end = size;;) {
275
+ const start = Math.max(0, end - chunk), part = Buffer.alloc(end - start);
276
+ for (let read = 0; read < part.length;) {
277
+ const n = readSync(fd, part, read, part.length - read, start + read);
278
+ if (!n)
279
+ return undefined;
280
+ read += n;
281
+ }
282
+ buffer = Buffer.concat([part, buffer]);
283
+ if (buffer[buffer.length - 1] !== 10)
284
+ return undefined;
285
+ const previous = buffer.lastIndexOf(10, buffer.length - 2);
286
+ if (previous >= 0)
287
+ return buffer.subarray(previous + 1);
288
+ if (start === 0)
289
+ return buffer;
290
+ end = start;
291
+ chunk *= 2;
292
+ }
293
+ }
294
+ /** A1, C11: A journal handle that decodes nothing yet: when the file still is what `expect` describes (same inode and
295
+ * size, the same last line), the handle reports `loaded: false` and `count()` from it, and decodes the whole file
296
+ * (verifying it as openJournal does) on the first access to its entries or the first append. Undefined when the file
297
+ * is not what was expected: the caller opens it eagerly. Decoding later finds the same bytes or throws (one writer). */
298
+ export async function openLazyJournal(path, expect) {
299
+ let fd;
300
+ try {
301
+ fd = openSync(path, 'r');
302
+ }
303
+ catch {
304
+ return undefined;
305
+ }
306
+ try {
307
+ const { ino, size } = fstatSync(fd);
308
+ if (ino !== expect.ino || size !== expect.size || expect.count < 1 || expect.tailLength < 10 || expect.tailLength > size)
309
+ return undefined;
310
+ const tail = Buffer.alloc(expect.tailLength);
311
+ for (let read = 0; read < tail.length;) {
312
+ const n = readSync(fd, tail, read, tail.length - read, size - tail.length + read);
313
+ if (!n)
314
+ return undefined;
315
+ read += n;
232
316
  }
233
- if (created) {
234
- await first.sync();
235
- await syncDirectory(dirname(path));
317
+ if (tail[tail.length - 1] !== 10 || tail.indexOf(10) !== tail.length - 1 || crc32(tail) !== expect.tail)
318
+ return undefined;
319
+ if (size > tail.length) {
320
+ const before = Buffer.alloc(1);
321
+ if (readSync(fd, before, 0, 1, size - tail.length - 1) !== 1 || before[0] !== 10)
322
+ return undefined;
236
323
  }
237
324
  }
238
- catch (error) {
239
- await first.close();
240
- throw error;
325
+ catch {
326
+ return undefined;
327
+ }
328
+ finally {
329
+ closeSync(fd);
241
330
  }
242
- let file = first;
243
- descriptors++;
331
+ return openHandle(path, expect);
332
+ }
333
+ /** Decode a journal synchronously as openJournal does (a torn tail is truncated), for a lazy handle's first access. */
334
+ function loadSync(path, expect) {
335
+ const fd = openSync(path, 'r+');
336
+ try {
337
+ const { ino, size } = fstatSync(fd);
338
+ if (ino !== expect.ino || size !== expect.size)
339
+ throw new Error(`Journal changed while not loaded: ${path} has ${size} bytes, ${expect.size} expected`);
340
+ const bytes = readFileSync(fd), decoded = decode(bytes);
341
+ if (decoded.entries.length !== expect.count)
342
+ throw new Error(`Journal changed while not loaded: ${path} has ${decoded.entries.length} entries, ${expect.count} expected`);
343
+ if (decoded.length !== bytes.length) {
344
+ ftruncateSync(fd, decoded.length);
345
+ fsyncSync(fd);
346
+ }
347
+ return { entries: decoded.entries, size: decoded.length };
348
+ }
349
+ finally {
350
+ closeSync(fd);
351
+ }
352
+ }
353
+ async function openHandle(path, lazy) {
354
+ let entries, size, file;
355
+ if (lazy)
356
+ size = lazy.size;
357
+ else {
358
+ await mkdir(dirname(path), { recursive: true });
359
+ let created = false;
360
+ const first = await open(path, 'ax+').then(f => { created = true; return f; }, async (error) => {
361
+ if (error.code !== 'EEXIST')
362
+ throw error;
363
+ return open(path, 'a+');
364
+ });
365
+ try {
366
+ const bytes = await first.readFile(), decoded = decode(bytes);
367
+ entries = decoded.entries;
368
+ size = decoded.length;
369
+ if (decoded.length !== bytes.length) {
370
+ await first.truncate(decoded.length);
371
+ await first.sync();
372
+ }
373
+ if (created) {
374
+ await first.sync();
375
+ await syncDirectory(dirname(path));
376
+ }
377
+ }
378
+ catch (error) {
379
+ await first.close();
380
+ throw error;
381
+ }
382
+ file = first;
383
+ descriptors++;
384
+ }
385
+ /** The entries, decoding a lazy handle's file first. */
386
+ const all = () => {
387
+ if (!entries) {
388
+ const loaded = loadSync(path, lazy);
389
+ entries = loaded.entries;
390
+ size = loaded.size;
391
+ }
392
+ return entries;
393
+ };
244
394
  let queue = Promise.resolve(), closed = false, failed, view;
245
- let resting = false, restTimer;
395
+ let resting = lazy !== undefined, restTimer;
246
396
  // Only this process writes the file (A2): a reopened file that is not exactly what was committed was changed by
247
397
  // someone else, and appending to it could interleave records.
248
398
  const reopen = async () => {
@@ -283,10 +433,12 @@ export async function openJournal(path) {
283
433
  const handle = {
284
434
  path,
285
435
  // Shared frozen view, rebuilt only after an append (entries are immutable, see freeze()).
286
- entries: () => view ??= Object.freeze(entries.slice()),
436
+ entries: () => view ??= Object.freeze(all().slice()),
287
437
  // The growing array itself (no copy): it is only ever appended to, so a reader may keep it and read below a length
288
438
  // it saw (the event pump reads new entries per tick without copying the journal).
289
- committed: () => entries,
439
+ committed: () => all(),
440
+ get loaded() { return entries !== undefined; },
441
+ count: () => entries ? entries.length : lazy.count,
290
442
  onAppend: undefined,
291
443
  append(type, fields) {
292
444
  if (closed)
@@ -295,6 +447,7 @@ export async function openJournal(path) {
295
447
  const operation = queue.then(async () => {
296
448
  if (failed)
297
449
  throw failed;
450
+ const entries = all();
298
451
  const entry = { ...frozen, seq: entries.length + 1, ts: Date.now(), type };
299
452
  const json = JSON.stringify(entry), bytes = Buffer.from(json), line = `${crc32(bytes)} ${json}\n`;
300
453
  let target;
@@ -138,6 +138,8 @@ export class Outbox {
138
138
  }
139
139
  /** The envelope recorded as sent under `rid`, if any. */
140
140
  recorded(rid) { const req = this.sent.get(rid); return req && structuredClone(req); }
141
+ /** The recipients of unresolved envelopes. */
142
+ pendingDestinations() { return new Set([...this.pending.values()].map(req => req.to)); }
141
143
  /** P38: Re-publish every unresolved envelope under its original identity. */
142
144
  republishPending() { return this.serial(async () => { for (const req of this.pending.values())
143
145
  await this.publish(req); }); }
@@ -10,7 +10,7 @@ import { join } from "node:path";
10
10
  import { contentHash } from "../kernel/ids.js";
11
11
  /** The keys the orchestrator reads; config.json also holds pi-side settings (ui, onQuit) that it ignores. */
12
12
  const KEYS = ["defaultModel", "pools", "providers", "memory", "writerLock", "k"];
13
- const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs"];
13
+ const K = ["lossBound", "checkpointMs", "stallMs", "progressMs", "switchTimeoutMs", "idleExitMs", "trackerMs", "hibernateMs", "spawnBudget", "probeMs", "eventRetentionMs", "waitCheckMs", "resumeSpillMs"];
14
14
  export const configPath = (home) => join(home, "config.json");
15
15
  /** The orchestrator's part of a parsed config.json. */
16
16
  export function orchestratorSettings(raw) {
@@ -71,6 +71,11 @@ export function configProblem(raw) {
71
71
  for (const [key, v] of Object.entries(k)) {
72
72
  if (!K.includes(key))
73
73
  return `k.${key} is not a K-parameter (${K.join(", ")})`;
74
+ if (key === "resumeSpillMs") {
75
+ if (v !== null && !(typeof v === "number" && Number.isFinite(v)))
76
+ return "k.resumeSpillMs must be a finite number of milliseconds or null";
77
+ continue;
78
+ }
74
79
  if (!count(v) || (key !== "lossBound" && key !== "spawnBudget" && v === 0))
75
80
  return `k.${key} must be a positive number`;
76
81
  }
@@ -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) {