pi-durable-subagents 1.0.42 → 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.
@@ -18,6 +18,19 @@ import { readSettled, settledPath } from "./settled.js";
18
18
  import { publishFile } from "../kernel/mailbox.js";
19
19
  import { digestDir, factsDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
20
20
  import { JT } from "../types.js";
21
+ /** The same record checks for asynchronous verification and a synchronous released-pins reload. */
22
+ function pinRecordFiles(dir, hash, record, verify) {
23
+ const { digest, ...body } = record;
24
+ if (body.snapshot !== hash || typeof digest !== 'string' || (verify && contentHash(body) !== digest))
25
+ return undefined;
26
+ if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
27
+ return undefined;
28
+ const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
29
+ if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
30
+ return undefined;
31
+ return { pins: body.pins, scriptPath: join(dir, 'script.js'), inputs: Object.fromEntries(Object.entries(body.inputs).map(([name, file]) => [name, join(dir, String(file))])),
32
+ originPath: body.origin === true ? join(dir, 'origin.jsonl') : undefined };
33
+ }
21
34
  /** Every file publishPins writes for one revision, relative to its directory (inputs given relative too). */
22
35
  function publishedFiles(inputs, origin) {
23
36
  return [...new Set(['script.js', 'args.json', 'agents.json', 'inputs.json', ...inputs, ...(origin ? ['origin.jsonl'] : [])])];
@@ -186,10 +199,31 @@ export class Store {
186
199
  /** Called after each append to a workflow journal (the event pump derives from it). */
187
200
  appended;
188
201
  ledgers;
189
- /** Terminal workflows materialized from their `pins.json` without verifying it: the revision and the intent to verify
190
- * it with (see ready). */
202
+ /** Terminal workflows awaiting file verification; reuse their immutable revision intent instead of a wrapper. */
191
203
  unverified = new Map();
192
204
  verifying = new Map();
205
+ /** A request can verify pins and then be refused before live work starts. Release those pins after the request. */
206
+ pinRest = new Map();
207
+ /** Share one accessor pair per store, so released history carries no per-workflow getter/setter closures. */
208
+ pinAccessors = (() => {
209
+ const store = this;
210
+ return { enumerable: true, configurable: true,
211
+ get() { const pins = store.releasedPins(this); this.pins = pins; store.restPins(this); return pins; },
212
+ set(pins) { Object.defineProperty(this, 'pins', { value: pins, enumerable: true, configurable: true, writable: true }); } };
213
+ })();
214
+ restPins(wf) {
215
+ if (wf.journal.closed || !wf.journal.resting || !Object.hasOwn(Object.getOwnPropertyDescriptor(wf, 'pins') ?? {}, 'value'))
216
+ return;
217
+ clearTimeout(this.pinRest.get(wf.wid));
218
+ const revision = wf.revision;
219
+ const timer = setTimeout(() => {
220
+ this.pinRest.delete(wf.wid);
221
+ if (this.workflows.get(wf.wid) === wf && wf.revision === revision && wf.journal.resting && !wf.journal.closed && !this.verifying.has(wf.wid))
222
+ this.releasePins(wf);
223
+ }, 1000);
224
+ timer.unref();
225
+ this.pinRest.set(wf.wid, timer);
226
+ }
193
227
  /** What the store looks up in the orchestrator ledger, folded over appended entries only (first entry wins, as find). */
194
228
  ix = { seen: 0, pruned: new Set(), created: new Set(), createIntents: [], createByRid: new Map(),
195
229
  createByWid: new Map(), reviseByRid: new Map(), rids: new Map() };
@@ -383,17 +417,16 @@ export class Store {
383
417
  async pinnedFiles(wid, revision, intent, verify = true) {
384
418
  const dir = revision === 1 ? pinnedDir(this.ledgers.home, wid) : join(pinnedDir(this.ledgers.home, wid), `r${revision}`);
385
419
  const ref = intent.pins ? undefined : intent.snapshot;
386
- if (ref) {
387
- const files = await this.recorded(dir, ref.hash, verify).catch(() => undefined);
388
- if (files)
389
- return files;
390
- }
420
+ const hash = ref?.hash ?? contentHash(intent.pins);
421
+ const recorded = await this.recorded(dir, hash, verify).catch(() => undefined);
422
+ if (recorded)
423
+ return recorded;
391
424
  const files = await this.publishPins(wid, revision, await this.pinned(intent));
392
- if (ref) {
425
+ {
393
426
  const hashes = {};
394
427
  for (const name of publishedFiles(Object.values(files.inputs).map(path => relative(dir, path)), files.originPath !== undefined))
395
428
  hashes[name] = await fileHash(join(dir, name));
396
- const body = { snapshot: ref.hash, pins: files.pins,
429
+ const body = { snapshot: hash, pins: files.pins,
397
430
  inputs: Object.fromEntries(Object.entries(files.inputs).map(([name, path]) => [name, relative(dir, path)])), origin: files.originPath !== undefined, files: hashes };
398
431
  await replaceFile(dir, 'pins.json', JSON.stringify({ ...body, digest: contentHash(body) }));
399
432
  }
@@ -402,21 +435,15 @@ export class Store {
402
435
  /** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined.
403
436
  * Without `verify`, only the record's form is checked (its digest and the file hashes are left to `ready`). */
404
437
  async recorded(dir, hash, verify = true) {
405
- const { digest, ...body } = JSON.parse(await readFile(join(dir, 'pins.json'), 'utf8'));
406
- // The digest covers everything the record decides (pins, input names → files, origin, file hashes).
407
- if (body.snapshot !== hash || typeof digest !== 'string' || (verify && contentHash(body) !== digest))
408
- return undefined;
409
- if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
410
- return undefined;
411
- const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
412
- if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
438
+ const record = JSON.parse(await readFile(join(dir, 'pins.json'), 'utf8'));
439
+ const files = pinRecordFiles(dir, hash, record, verify !== false);
440
+ if (!files)
413
441
  return undefined;
414
- if (verify)
415
- for (const name of names)
416
- if (body.files[name] !== await fileHash(join(dir, name)))
442
+ if (verify === true)
443
+ for (const name of Object.keys(record.files))
444
+ if (record.files[name] !== await fileHash(join(dir, name)))
417
445
  return undefined;
418
- return { pins: body.pins, scriptPath: join(dir, 'script.js'), inputs: Object.fromEntries(Object.entries(body.inputs).map(([name, file]) => [name, join(dir, String(file))])),
419
- originPath: body.origin === true ? join(dir, 'origin.jsonl') : undefined };
446
+ return files;
420
447
  }
421
448
  /** P14, A2: Publish a new revision only after the engine has retired its predecessor. */
422
449
  async revise(intent) {
@@ -428,29 +455,91 @@ export class Store {
428
455
  Object.assign(wf, files, { revision });
429
456
  this.unverified.delete(wf.wid);
430
457
  }
458
+ pinIntent(wf) {
459
+ const intent = wf.revision === 1 ? this.index().createByWid.get(wf.wid)
460
+ : wf.journal.loaded === false ? wf.settled?.revised : wf.journal.entries().findLast(e => e.type === 'revised');
461
+ if (!intent)
462
+ throw new Error(`Missing pinned revision: ${wf.wid}@${wf.revision}`);
463
+ return intent;
464
+ }
465
+ /** Reload metadata with ready's form/digest checks and immutable-snapshot fallback, without rechecking file bytes. */
466
+ releasedPins(wf) {
467
+ const intent = this.pinIntent(wf), hash = intent.pins ? contentHash(intent.pins) : intent.snapshot.hash;
468
+ const dir = wf.revision === 1 ? pinnedDir(this.ledgers.home, wf.wid) : join(pinnedDir(this.ledgers.home, wf.wid), `r${wf.revision}`);
469
+ try {
470
+ const recorded = pinRecordFiles(dir, hash, JSON.parse(readFileSync(join(dir, 'pins.json'), 'utf8')), true);
471
+ if (recorded)
472
+ return recorded.pins;
473
+ }
474
+ catch { /* The same immutable fallback as ready's asynchronous reload. */ }
475
+ let source = intent.pins;
476
+ if (!source) {
477
+ const ref = intent.snapshot;
478
+ if (!ref)
479
+ throw new Error('Missing pinned snapshot');
480
+ const snapshot = JSON.parse(readFileSync(join(this.ledgers.home, ref.path), 'utf8'));
481
+ if (contentHash(snapshot) !== ref.hash || !snapshot.pins)
482
+ throw new Error('Staged snapshot hash mismatch');
483
+ source = snapshot.pins;
484
+ }
485
+ const { origin: _origin, inputs: _inputs, ...pins } = source;
486
+ return { ...pins, inputs: {} };
487
+ }
488
+ /** Whether the workflow's pins are in memory (not released behind the lazy accessor). */
489
+ pinsResident(wf) { return !Object.getOwnPropertyDescriptor(wf, 'pins')?.get; }
490
+ /** Release terminal pins. The next read caches checked metadata until the same idle release runs again. */
491
+ releasePins(wf) {
492
+ clearTimeout(this.pinRest.get(wf.wid));
493
+ this.pinRest.delete(wf.wid);
494
+ if (Object.getOwnPropertyDescriptor(wf, 'pins')?.get)
495
+ return;
496
+ Object.defineProperty(wf, 'pins', this.pinAccessors);
497
+ }
431
498
  /** A1: Verify the pinned files of a workflow materialized unverified (a terminal one) before its script, inputs, origin
432
499
  * or pins are used again: the record's digest and every file's hash, else the snapshot path (which republishes a
433
500
  * missing file and refuses a changed one). Nothing evaluates from a file that does not hash as recorded. Idempotent;
434
501
  * a refusal is raised again by every later call. */
435
502
  async ready(wf) {
436
- if (!this.unverified.has(wf.wid))
503
+ if (!this.unverified.has(wf.wid)) {
504
+ const revision = wf.revision, unloaded = Object.getOwnPropertyDescriptor(wf, 'pins')?.get;
505
+ if (unloaded) {
506
+ const intent = this.pinIntent(wf);
507
+ const dir = wf.revision === 1 ? pinnedDir(this.ledgers.home, wf.wid) : join(pinnedDir(this.ledgers.home, wf.wid), `r${wf.revision}`);
508
+ const hash = intent.pins ? contentHash(intent.pins) : intent.snapshot.hash;
509
+ const recorded = await this.recorded(dir, hash, 'record').catch(() => undefined);
510
+ // These files were verified in this process. If their cache record changed, recover the same pins from the
511
+ // immutable snapshot, without changing when file verification is required.
512
+ const pins = recorded?.pins ?? await (async () => {
513
+ const { origin: _origin, inputs: _inputs, ...kept } = await this.pinned(intent);
514
+ return { ...kept, inputs: {} };
515
+ })();
516
+ if (wf.revision === revision && Object.getOwnPropertyDescriptor(wf, 'pins')?.get === unloaded)
517
+ wf.pins = pins;
518
+ }
519
+ this.restPins(wf);
437
520
  return;
521
+ }
438
522
  let run = this.verifying.get(wf.wid);
439
523
  if (!run) {
440
524
  run = (async () => {
441
525
  const pending = this.unverified.get(wf.wid);
442
526
  if (!pending)
443
527
  return;
444
- const files = pending.revision === wf.revision ? await this.pinnedFiles(wf.wid, pending.revision, pending.intent) : undefined;
445
- if (this.unverified.get(wf.wid) !== pending)
446
- return; // A revision published meanwhile was verified by revise.
447
- if (files && pending.revision === wf.revision)
528
+ const revision = wf.revision, files = await this.pinnedFiles(wf.wid, revision, pending);
529
+ if (this.workflows.get(wf.wid) !== wf || this.unverified.get(wf.wid) !== pending)
530
+ return; // A revision or owner changed meanwhile.
531
+ if (revision === wf.revision)
448
532
  Object.assign(wf, files);
449
533
  this.unverified.delete(wf.wid);
450
534
  })().finally(() => this.verifying.delete(wf.wid));
451
535
  this.verifying.set(wf.wid, run);
452
536
  }
453
- await run;
537
+ try {
538
+ await run;
539
+ }
540
+ finally {
541
+ this.restPins(wf);
542
+ }
454
543
  }
455
544
  /** Whether a workflow's pinned files were verified in this process (see ready). */
456
545
  verified(wid) { return !this.unverified.has(wid); }
@@ -465,7 +554,8 @@ export class Store {
465
554
  : wf.journal.entries().find(e => e.type === 'revised' && e.revision === revision);
466
555
  if (!intent)
467
556
  throw new Error(`Missing pinned revision: ${wf.wid}@${revision}`);
468
- return { ...wf, revision, ...await this.pinnedFiles(wf.wid, revision, intent) };
557
+ const { wid, origin, cwd, journal, settled } = wf;
558
+ return { wid, origin, cwd, journal, ...(settled ? { settled } : {}), revision, ...await this.pinnedFiles(wid, revision, intent) };
469
559
  }
470
560
  /** A1, housekeeping: Wids with a committed pruned entry; they are gone and never materialize again. */
471
561
  pruned() { return this.index().pruned; }
@@ -481,6 +571,8 @@ export class Store {
481
571
  }
482
572
  /** A1, A2: Retire a pruned workflow's handle after its pruned entry is committed; nothing appends to it again. */
483
573
  async drop(wid) {
574
+ clearTimeout(this.pinRest.get(wid));
575
+ this.pinRest.delete(wid);
484
576
  const wf = this.workflows.get(wid);
485
577
  this.workflows.delete(wid);
486
578
  await wf?.journal.close();
@@ -536,7 +628,8 @@ export class Store {
536
628
  const current = settled.revised ?? intent, files = await this.pinnedFiles(wid, settled.revision, current, false);
537
629
  const facts = { revision: settled.revision, ...(settled.revised ? { revised: settled.revised } : {}), done: settled.done, resumed: settled.resumed, quiet: settled.quiet, calls: settled.calls, sweep: settled.sweep };
538
630
  const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts };
539
- this.unverified.set(wid, { revision: settled.revision, intent: current });
631
+ this.releasePins(wf);
632
+ this.unverified.set(wid, current);
540
633
  lazy.onAppend = () => this.appended?.(wid);
541
634
  this.workflows.set(wid, wf);
542
635
  if (!this.index().created.has(String(intent.rid)))
@@ -563,8 +656,10 @@ export class Store {
563
656
  const ended = !first && entries.length > 0 && terminalEntry(entries) !== undefined;
564
657
  const files = first ?? (ended ? await this.pinnedFiles(wid, revision, current, false) : await this.pinnedFiles(wid, 1, intent));
565
658
  wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
566
- if (ended)
567
- this.unverified.set(wid, { revision, intent: current });
659
+ if (ended) {
660
+ this.releasePins(wf);
661
+ this.unverified.set(wid, current);
662
+ }
568
663
  }
569
664
  catch (error) {
570
665
  await journal.close();
@@ -583,5 +678,10 @@ export class Store {
583
678
  return wf;
584
679
  }
585
680
  /** A1: Close shared journals only after engine and executor activity retires. */
586
- async close() { await Promise.all([...this.workflows.values()].map(w => w.journal.close())); }
681
+ async close() {
682
+ for (const timer of this.pinRest.values())
683
+ clearTimeout(timer);
684
+ this.pinRest.clear();
685
+ await Promise.all([...this.workflows.values()].map(w => w.journal.close()));
686
+ }
587
687
  }
package/dist/requests.js CHANGED
@@ -7,7 +7,7 @@ import { readdir } from 'node:fs/promises';
7
7
  import { join } from 'node:path';
8
8
  import { setTimeout as delay } from 'node:timers/promises';
9
9
  import { contentHash } from "./kernel/ids.js";
10
- import { findJournalEntry, readJournalSnapshot } from "./kernel/journal.js";
10
+ import { readJournalFold } from "./kernel/journal.js";
11
11
  import { publishRequest } from "./kernel/mailbox.js";
12
12
  import { OsLock } from "./platform/lock.js";
13
13
  import { orchInbox, orchLedger, outboxRoot } from "./paths.js";
@@ -65,17 +65,53 @@ export function specDigest(req) {
65
65
  }
66
66
  return contentHash({ kind: req.kind, body, cond: req.cond });
67
67
  }
68
+ // Repeated request checks verify the same immutable prefixes, including on either side of a lock. Retain only
69
+ // negative positions, never envelopes: every check still stats the file and folds fresh appended bytes. The bound
70
+ // counts files, not hinted IDs: one hinted lookup cannot evict its earlier files within the file budget.
71
+ const misses = new Map(), MISS_FILES = 1024, MISS_IDS = 64;
72
+ function requestIn(path, rid, type, related, touched) {
73
+ const probes = [...new Set([rid, ...related])].slice(0, MISS_IDS), key = JSON.stringify([path, type]);
74
+ touched.add(key);
75
+ const known = misses.get(key);
76
+ misses.delete(key); // A failed read must not retain a partially extended prefix or absence set.
77
+ const reusable = known && probes.every(id => known.state.has(id));
78
+ // Watch every cached absent ID while extending: otherwise an appended envelope could invalidate an older hint.
79
+ const watched = new Set(reusable ? known.state : probes);
80
+ let found;
81
+ const record = readJournalFold(path, reusable ? { ...known, state: watched } : undefined, () => watched, (absent, entry) => {
82
+ if (entry.type !== type)
83
+ return;
84
+ const id = entry.request.rid;
85
+ absent.delete(id);
86
+ if (!found && id === rid)
87
+ found = entry;
88
+ }, { needles: [...watched].map(id => JSON.stringify(id)) });
89
+ // Keep positions and absent IDs only, never the found envelope. Torn tails cannot be cached: a repair may
90
+ // commit a line at the same inode/size. Each future check still stats and folds freshly appended bytes.
91
+ if (record && record.length === record.size && record.state.size) {
92
+ if (misses.size >= MISS_FILES) {
93
+ // More files than the budget: omit later positions rather than evict this lookup's earliest files.
94
+ const evict = [...misses.keys()].find(candidate => !touched.has(candidate));
95
+ if (evict !== undefined)
96
+ misses.delete(evict);
97
+ }
98
+ if (misses.size < MISS_FILES)
99
+ misses.set(key, record);
100
+ }
101
+ return found;
102
+ }
68
103
  /** The envelope recorded for `rid`: the orchestrator's admitted copy (ledger `request`, kept after prune), else any
69
- * sender's outbox `sent` entry (published or about to be). Read-only. */
70
- export async function findRequest(home, rid) {
71
- const admitted = findJournalEntry(orchLedger(home), e => e.type === 'request' && e.request.rid === rid);
104
+ * sender's outbox `sent` entry (published or about to be). Read-only. Related IDs are only hints for sharing a
105
+ * verified negative prefix; their eventual lookups still read fresh state and preserve first-match/file order. */
106
+ export async function findRequest(home, rid, related = []) {
107
+ const touched = new Set(), admitted = requestIn(orchLedger(home), rid, 'request', related, touched);
72
108
  if (admitted)
73
109
  return { request: admitted.request, admitted: true };
74
110
  const dir = join(outboxRoot(home), 'outbox');
75
111
  const names = await readdir(dir).catch(error => { if (error.code === 'ENOENT')
76
112
  return []; throw error; });
77
113
  for (const name of names.filter(n => n.endsWith('.jsonl')).sort()) {
78
- const sent = readJournalSnapshot(join(dir, name)).find(e => e.type === 'sent' && e.request.rid === rid);
114
+ const sent = requestIn(join(dir, name), rid, 'sent', related, touched);
79
115
  if (sent)
80
116
  return { request: sent.request, admitted: false };
81
117
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.42",
3
+ "version": "1.0.43",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",