pi-durable-subagents 1.0.39 → 1.0.41

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.
@@ -4,16 +4,33 @@ import { initiatorSummary, restartLine } from "./restart.js";
4
4
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { compileFanout } from "../compat/fanout.js";
7
- import { readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
8
- import { journalPath, orchLedger, pinnedDir, workflowDir } from "../paths.js";
9
- import { JT, isEntry } from "../types.js";
10
- import { emptyLedger, foldLedger } from "./ledger.js";
7
+ import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends, readJournalRecord, readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
8
+ import { readCache, writeCache } from "../kernel/cache.js";
9
+ import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
10
+ import { JT, attentionEntries, isEntry } from "../types.js";
11
+ import { resolveModel } from "../compat/model.js";
12
+ import {} from "./ledger.js";
13
+ import { readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
11
14
  import { packageVersion } from "../version.js";
12
15
  import { worktreeCalls, worktreeLabel } from "./executor/worktree.js";
13
16
  import { leaseCalls, leaseLines, leaseState } from "../platform/lease.js";
14
17
  import { labelsOf } from "../events/derive.js";
15
- import { PENDING_NOTE } from "./notes.js";
18
+ import { PENDING_NOTE, generationRids, UNDELIVERED_FOLLOW_UP } from "./notes.js";
16
19
  import { readStats } from "./stats.js";
20
+ export function answerForwardedNote(c, now = Date.now()) {
21
+ const answer = c.answerForwarded;
22
+ return answer && now - answer.at >= 30_000 ? `answer forwarded ${age(now - answer.at)} ago, not delivered` : "";
23
+ }
24
+ const modelName = (m) => { const v = m; return v.provider ? `${v.provider}/${v.id}` : v.id; };
25
+ const modelStatus = (c) => Object.fromEntries(Object.entries(c).filter(([key]) => ["routedModel", "modelMismatch", "modelUnavailable", "poolWait", "spill"].includes(key)));
26
+ /** Scheduling and model identity facts shared by detailed and compact text status. */
27
+ export function modelStatusText(c, now = Date.now()) {
28
+ const w = c.poolWait, s = c.spill, m = c.modelMismatch;
29
+ return (w ? ` (queued ${age(now - w.since)} on ${w.model.split("/")[0]} (full)${w.free.length ? `; pool has free slots: ${w.free.join(", ")}` : ""})` : "") +
30
+ (s ? ` (spilled after ${age(s.waitedMs)}: ${s.from.split("/")[0]} full -> ${s.to})` : "") +
31
+ (c.routedModel ? ` (routed ${c.routedModel})` : "") +
32
+ (m ? ` (used ${m.used}, selected ${m.selected})` : "") + (c.modelUnavailable ? ` (model-unavailable: ${c.modelUnavailable})` : "");
33
+ }
17
34
  /** A workflow has live work: it runs, or follow-ups opened on it after it finished have not ended yet. */
18
35
  export function isLive(wf) {
19
36
  return wf.status === "running" || (wf.followUps ?? 0) > 0;
@@ -48,7 +65,8 @@ export function plannedFromScript(source) {
48
65
  const plannedByPath = new Map();
49
66
  /** v12 §4: The current revision's planned total, read lazily from the pinned run body and cached (pins are immutable). */
50
67
  function plannedTotal(home, wid, rev) {
51
- const path = join(pinnedDir(home, wid), rev === 1 ? "script.js" : join(`r${rev}`, "script.js"));
68
+ const scripts = pathsOf(home, wid).scripts;
69
+ const path = scripts[rev] ??= join(pinnedDir(home, wid), rev === 1 ? "script.js" : join(`r${rev}`, "script.js"));
52
70
  if (!plannedByPath.has(path)) {
53
71
  try {
54
72
  plannedByPath.set(path, plannedFromScript(readFileSync(path, "utf8")));
@@ -138,6 +156,9 @@ function snapshotReducer(wid, entries) {
138
156
  // An execution waits for a provider slot and memory before it launches; it is running once `selected` says so
139
157
  // (otherwise a call still waiting for a slot reads "thinking · 2m").
140
158
  call.exec = String(e.exec);
159
+ delete call.poolWait;
160
+ delete call.usedModel;
161
+ delete call.virtualModel;
141
162
  call.phase = "queued";
142
163
  call.startedAt ??= e.ts;
143
164
  call.lastActivity = e.ts;
@@ -147,6 +168,32 @@ function snapshotReducer(wid, entries) {
147
168
  hibernating.delete(call.callId);
148
169
  }
149
170
  }
171
+ else if (e.type === "slot-wait") {
172
+ const call = byExec.get(String(e.exec));
173
+ if (call && call.exec === e.exec) {
174
+ if (e.model)
175
+ call.poolWait = { since: Number(e.since), model: modelName(e.model), ...(typeof e.pool === "string" ? { pool: e.pool } : {}), free: [] };
176
+ else
177
+ delete call.poolWait;
178
+ }
179
+ }
180
+ else if (e.type === "spilled") {
181
+ const call = byExec.get(String(e.exec));
182
+ if (call)
183
+ call.spill = { from: modelName(e.from), to: modelName(e.to), waitedMs: Number(e.waitedMs) };
184
+ }
185
+ else if (e.type === "model-unavailable") {
186
+ const call = byExec.get(String(e.exec));
187
+ if (call)
188
+ call.modelUnavailable = String(e.reason);
189
+ }
190
+ else if (e.type === "model-ready") {
191
+ const call = byExec.get(String(e.exec));
192
+ if (call && call.exec === e.exec) {
193
+ call.selectedModel = modelName(e.model);
194
+ call.virtualModel = e.virtual === true;
195
+ }
196
+ }
150
197
  else if (e.type === "writer-wait" || e.type === "writer-acquired") {
151
198
  const call = calls.get(String(e.call)), holder = String(e.holder ?? "");
152
199
  if (call && e.type === "writer-wait")
@@ -195,8 +242,13 @@ function snapshotReducer(wid, entries) {
195
242
  }
196
243
  else if (e.type === "selected") {
197
244
  const call = byExec.get(String(e.exec)), m = e.model;
198
- if (call && m)
245
+ if (call && call.exec === e.exec && m) {
199
246
  call.model = m.provider ? `${m.provider}/${m.id}` : m.id;
247
+ call.selectedModel = call.model;
248
+ delete call.poolWait;
249
+ delete call.usedModel;
250
+ delete call.virtualModel;
251
+ }
200
252
  if (call && call.exec === e.exec && call.phase === "queued") {
201
253
  call.phase = "running";
202
254
  delete call.answered;
@@ -207,14 +259,21 @@ function snapshotReducer(wid, entries) {
207
259
  else if (e.type === "model-used") {
208
260
  // Evidence of a switch: the execution answered with another model than it launched with.
209
261
  const call = byExec.get(String(e.exec)), m = e.model;
210
- if (call && m)
262
+ if (call && call.exec === e.exec && m) {
211
263
  call.model = m.provider ? `${m.provider}/${m.id}` : m.id;
264
+ call.usedModel = call.model;
265
+ if (sends.get(call.callId)?.some(s => s.kind === "model" && !s.reason && s.model?.toLowerCase() === call.model?.toLowerCase()))
266
+ call.selectedModel = call.model;
267
+ }
212
268
  }
213
269
  else if (e.type === "observation") {
214
270
  // Only what the agent did counts as activity; tracker scans and time checkpoints are bookkeeping.
215
271
  const call = byExec.get(String(e.exec));
216
272
  if (call)
217
273
  call.lastActivity = e.ts;
274
+ const event = e.event;
275
+ if (call && call.exec === e.exec && event?.type === "message_start" && event.provider && event.model)
276
+ call.usedModel = `${event.provider}/${event.model}`;
218
277
  if (call && e.type === "observation" && e.event?.type === "tool_execution_start")
219
278
  tools.set(call.callId, (tools.get(call.callId) ?? 0) + 1);
220
279
  }
@@ -242,6 +301,7 @@ function snapshotReducer(wid, entries) {
242
301
  delete call.answered;
243
302
  delete call.hibernated;
244
303
  delete call.writerWait;
304
+ delete call.poolWait;
245
305
  hibernating.delete(call.callId);
246
306
  }
247
307
  else if (isEntry(e, JT.attention)) {
@@ -251,7 +311,9 @@ function snapshotReducer(wid, entries) {
251
311
  else if (e.type === "forward") {
252
312
  const envelope = e.envelope;
253
313
  const send = { rid: String(e.rid), kind: String(envelope?.kind ?? ""), state: "pending", at: e.ts,
254
- ...(envelope?.kind === "model" && envelope.body?.provider ? { model: `${envelope.body.provider}/${envelope.body.model}` } : {}) };
314
+ ...(envelope?.kind === "model" && envelope.body?.provider ? { model: `${envelope.body.provider}/${envelope.body.model}` } : {}),
315
+ ...(envelope?.kind === "answer" && typeof envelope.cond?.qid === "string" && typeof envelope.cond.rev === "number"
316
+ ? { question: { qid: envelope.cond.qid, rev: envelope.cond.rev } } : {}) };
255
317
  const list = sends.get(String(e.dest)) ?? [];
256
318
  list.push(send);
257
319
  sends.set(String(e.dest), list);
@@ -299,6 +361,8 @@ function snapshotReducer(wid, entries) {
299
361
  const usageOf = (callId) => sealedUsage.get(callId) ?? live.get(callId);
300
362
  const counts = { queued: 0, running: 0, asking: 0, sealed: 0 };
301
363
  for (const c of list) {
364
+ if (c.phase !== "sealed" && c.phase !== "queued")
365
+ delete c.poolWait;
302
366
  counts[c.phase]++;
303
367
  const usage = usageOf(c.callId);
304
368
  if (usage)
@@ -312,12 +376,21 @@ function snapshotReducer(wid, entries) {
312
376
  const pending = forwarded.filter(pendingMessage).length;
313
377
  if (pending)
314
378
  c.pending = pending;
379
+ const answer = c.phase === "asking" && forwarded.find(s => s.kind === "answer" && s.state === "pending" && s.question &&
380
+ openAttention.some(a => a.call === c.callId && a.qid === s.question.qid && a.rev === s.question.rev));
381
+ if (answer)
382
+ c.answerForwarded = { rid: answer.rid, ...answer.question, at: answer.at };
315
383
  const last = c.phase !== "sealed" && !retired.has(c.callId) ? forwarded.findLast(s => s.kind === "model" && s.reason !== "withdrawn" && s.reason !== "stale-execution") : undefined;
316
384
  if (last?.reason !== undefined)
317
385
  c.switchFailed = `${last.model} (${last.reason})`;
318
- else if (last && last.state !== "retired" && last.model !== c.model?.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, ""))
386
+ else if (last && last.state !== "retired" && last.model !== (c.virtualModel ? c.selectedModel : c.model)?.replace(/:(off|minimal|low|medium|high|xhigh|max)$/, ""))
319
387
  c.switching = last.model;
320
388
  }
389
+ const selected = c.switching ?? c.selectedModel;
390
+ if (c.usedModel && c.virtualModel)
391
+ c.routedModel = c.usedModel;
392
+ else if (c.usedModel && selected && c.usedModel.toLowerCase() !== selected.toLowerCase())
393
+ c.modelMismatch = { used: c.usedModel, selected };
321
394
  }
322
395
  for (const [key, rids] of notes) {
323
396
  const n = [...rids].filter(rid => !carried.has(rid)).length, call = list.findLast(c => c.key === key);
@@ -358,8 +431,218 @@ export function snapshotFromEntries(wid, entries) {
358
431
  const FOLDS = 256; // workflows whose fold state is kept; pruned and long-idle ones fall out
359
432
  const folds = new Map();
360
433
  const derived = new WeakMap();
361
- export function workflowSnapshot(home, wid) {
362
- const path = journalPath(home, wid), entries = readJournalSnapshot(path), hit = derived.get(entries);
434
+ export function workflowSnapshot(home, wid, ledger) {
435
+ const base = workflowDigest(home, wid, ledger).snapshot;
436
+ const wf = base.calls.some(c => c.poolWait) ? withPoolSlots(base, readerLedger(home).state.state) : base;
437
+ const planned = plannedTotal(home, wid, wf.rev);
438
+ return planned === undefined ? wf : { ...wf, planned };
439
+ }
440
+ /** P37: a generation opened by a send (possibly after the workflow finished) that has no seal yet is pending work. */
441
+ const opened = new WeakMap();
442
+ export function openGeneration(entries) {
443
+ const hit = opened.get(entries);
444
+ if (hit?.length === entries.length)
445
+ return hit.open;
446
+ // Sealed call ids end in `/<key>@<gen>`; collect every such suffix once instead of rescanning per generation.
447
+ const sealed = new Set();
448
+ for (const s of entries)
449
+ if (s.type === JT.sealed) {
450
+ const call = String(s.call);
451
+ for (let i = call.indexOf("/"); i >= 0; i = call.indexOf("/", i + 1))
452
+ sealed.add(call.slice(i));
453
+ }
454
+ const open = entries.some(g => g.type === "generation" && !sealed.has(`/${String(g.key)}@${String(g.gen)}`));
455
+ opened.set(entries, { length: entries.length, open });
456
+ return open;
457
+ }
458
+ const unresolvedByEntries = new WeakMap();
459
+ /** P15: The attention items of one immutable journal snapshot without an `attention-resolved`, computed once per snapshot. */
460
+ export function unresolvedAttention(entries) {
461
+ let items = unresolvedByEntries.get(entries);
462
+ if (items)
463
+ return items;
464
+ const done = new Set(entries.filter(e => e.type === JT.attentionResolved).map(e => `${e.id}\0${e.rev}`));
465
+ items = attentionEntries(entries).map(e => e.item).filter(item => !done.has(`${item.id}\0${item.rev}`));
466
+ unresolvedByEntries.set(entries, items);
467
+ return items;
468
+ }
469
+ // A settled workflow's digest is kept in memory and on disk (DSA_HOME/cache), keyed by the journal's inode and committed
470
+ // size: committed bytes never change (A1), so the same device, inode and size reduce to the same digest. Readers used to
471
+ // decode every historical journal at each pi start (hundreds of MB: seconds of pi's main thread and hundreds of MB
472
+ // per pi window) only to find them finished. The key also names this reduction's code, so a changed reducer reads its
473
+ // journals again instead of trusting digests an older one wrote.
474
+ const DIGEST_FORMAT = 2;
475
+ let digestCode;
476
+ function digestVersion() {
477
+ if (digestCode === undefined) {
478
+ try {
479
+ const ext = import.meta.url.endsWith(".ts") ? "ts" : "js";
480
+ digestCode = `${DIGEST_FORMAT}.${crc32(Buffer.concat([new URL(import.meta.url), ...[`../types.${ext}`, `./executor/worktree.${ext}`, `./notes.${ext}`].map(p => new URL(p, import.meta.url))].map(u => readFileSync(u))))}`;
481
+ }
482
+ catch {
483
+ digestCode = "";
484
+ }
485
+ }
486
+ return digestCode;
487
+ }
488
+ const digests = new Map();
489
+ const FINAL_STATUS = new Set(["done", "failed", "stopped"]);
490
+ /** Post-seal/recovery work that can append without a new request must not enter a polling trust window. */
491
+ export function pendingRecovery(wid, entries) {
492
+ const start = entries.findLastIndex(e => e.type === "revised"), current = start < 0 ? entries : entries.slice(start);
493
+ const consumed = new Set(current.filter(e => e.type === "generation").flatMap(generationRids));
494
+ const retiredForwards = new Map(entries.filter(e => e.type === "forward-retired").map(e => [String(e.rid2), e]));
495
+ const delivered = new Set(entries.filter(e => e.type === "forward-delivered").map(e => String(e.rid2)));
496
+ // collectSealed repairs forwarding receipts of older revisions as well.
497
+ for (const e of entries)
498
+ if (e.type === "forward" && !retiredForwards.has(String(e.rid2)) && !delivered.has(String(e.rid2)))
499
+ return true;
500
+ for (const e of current)
501
+ if (e.type === "forward" && retiredForwards.get(String(e.rid2))?.reason === UNDELIVERED_FOLLOW_UP && !consumed.has(String(e.rid)))
502
+ return true;
503
+ const fenced = new Set(entries.filter(e => e.type === JT.fenced).map(e => e.exec));
504
+ const gates = new Set(entries.filter(e => e.type === "gate").map(e => e.id));
505
+ const cleaned = new Set(entries.filter(e => e.type === "wt-removed" || e.type === "wt-kept").map(e => e.call));
506
+ const seals = new Map(entries.filter(e => e.type === JT.sealed).map(e => [e.call, e]));
507
+ const attention = attentionEntries(entries), resolved = new Set(entries.filter(e => e.type === JT.attentionResolved).map(e => JSON.stringify([e.id, e.rev])));
508
+ const hasAttention = (id, rev) => attention.some(e => e.item.id === id && (rev === undefined || e.item.rev === rev));
509
+ // Engine.attention repairs completion notices, including on already-ended workflows after a crash.
510
+ if (current.some(e => e.type === JT.done) && !hasAttention(`finished:${wid}`, entries.filter(e => e.type === JT.done).length))
511
+ return true;
512
+ for (const e of entries) {
513
+ if (e.type === JT.exec && !fenced.has(e.exec))
514
+ return true;
515
+ if (e.type === "gate-intent" && !gates.has(e.id))
516
+ return true;
517
+ if (e.type === "wt-intent" && seals.get(e.call)?.result?.status === "ok" && !cleaned.has(e.call))
518
+ return true;
519
+ if (e.type === JT.sealed && e.result?.status === "unknown" && !hasAttention(`unknown:${String(e.call)}`))
520
+ return true;
521
+ if (e.type === "generation" && e.revision !== undefined) {
522
+ const call = `${wid}@${e.revision}/${String(e.key)}@${String(e.gen)}`;
523
+ if (seals.has(call) && !hasAttention(`finished:${call}`))
524
+ return true;
525
+ }
526
+ }
527
+ // Retirement, fence repair, and cross-workflow conflict resolution can still close these items.
528
+ for (const { item } of attention)
529
+ if (!resolved.has(JSON.stringify([item.id, item.rev]))) {
530
+ if (item.id.startsWith("fence:") || item.kind === "conflict")
531
+ return true;
532
+ if (item.call && seals.has(item.call) && item.kind !== "finished" && item.id !== `unknown:${item.call}`)
533
+ return true;
534
+ }
535
+ return false;
536
+ }
537
+ function digestOf(wf, entries, complete) {
538
+ const settled = complete && FINAL_STATUS.has(wf.status) && !wf.active && !wf.followUps &&
539
+ entries.some(e => e.type === JT.done) && !openGeneration(entries) && !pendingRecovery(wf.wid, entries);
540
+ const tasks = Object.create(null);
541
+ if (settled)
542
+ for (const e of entries)
543
+ if (e.type === "call")
544
+ tasks[`${e.key}\0${e.gen}`] = String(e.spec?.task ?? "");
545
+ return settled ? { snapshot: wf, settled: { attention: structuredClone(unresolvedAttention(entries)), tasks } } : { snapshot: wf };
546
+ }
547
+ function storedDigest(home, wid, dev, ino, size) {
548
+ const stored = readCache(join(digestDir(home), `${wid}.json`));
549
+ const d = stored?.digest, wf = d?.snapshot;
550
+ if (!(digestVersion() && stored?.v === digestVersion() && stored.home === home && stored.dev === dev && stored.ino === ino && stored.size === size &&
551
+ d?.settled && Array.isArray(d.settled.attention) && d.settled.tasks && wf?.wid === wid && Array.isArray(wf.calls) &&
552
+ Array.isArray(wf.attention) && wf.counts && FINAL_STATUS.has(wf.status) && !wf.active && !wf.followUps))
553
+ return undefined;
554
+ // The reducer always sets pos with Number(e.pos); a missing position is NaN, which JSON represents as null.
555
+ for (const call of wf.calls)
556
+ if (call.pos === null)
557
+ call.pos = NaN;
558
+ return d;
559
+ }
560
+ /** Concurrent windows publish independently; an old writer's identity cannot pass a new journal's key. */
561
+ function storeDigest(home, wid, record, digest) {
562
+ const v = digestVersion();
563
+ if (v)
564
+ writeCache(join(digestDir(home), `${wid}.json`), { v, home, dev: record.dev, ino: record.ino, size: record.size, digest }, journalPath(home, wid));
565
+ }
566
+ // Path strings per workflow: joining them for every workflow on every UI refresh cost pi's main thread milliseconds.
567
+ const pathsByHome = new Map();
568
+ function pathsOf(home, wid) {
569
+ let byWid = pathsByHome.get(home);
570
+ if (!byWid)
571
+ pathsByHome.set(home, byWid = new Map());
572
+ let paths = byWid.get(wid);
573
+ if (!paths)
574
+ byWid.set(wid, paths = { journal: journalPath(home, wid), scripts: [] });
575
+ return paths;
576
+ }
577
+ /** Intake commits requests before applying their generation or revision, then decisions afterward. Recovery and
578
+ * late attention can also append without a fresh request: an unchanged ledger skips settled journal IO only for
579
+ * this bounded window. Local appends end it too; turn boundaries check immediately. */
580
+ export const SETTLED_RECHECK_MS = 5000;
581
+ /** P25: The current digest of one workflow, from its committed journal. With `ledger` (the orchestrator ledger's
582
+ * identity, see allWorkflows) a settled digest checked under the same ledger less than SETTLED_RECHECK_MS ago is
583
+ * reused without a stat. */
584
+ export function workflowDigest(home, wid, ledger) {
585
+ const path = pathsOf(home, wid).journal, memo = digests.get(path), now = Date.now();
586
+ if (memo?.digest.settled)
587
+ releasable.add(path);
588
+ if (ledger !== undefined && memo?.digest.settled && memo.ledger === ledger && memo.appends === journalAppends() && now >= memo.checked && now - memo.checked < SETTLED_RECHECK_MS)
589
+ return memo.digest;
590
+ let dev, ino, size;
591
+ try {
592
+ ({ dev, ino, size } = statSync(path));
593
+ }
594
+ catch (error) {
595
+ if (error.code !== "ENOENT")
596
+ throw error;
597
+ }
598
+ if (memo && memo.dev === dev && memo.ino === ino && memo.size === size) {
599
+ memo.ledger = ledger;
600
+ memo.checked = now;
601
+ memo.appends = journalAppends();
602
+ return memo.digest;
603
+ }
604
+ if (dev !== undefined && ino !== undefined && size !== undefined && !memo) {
605
+ const stored = storedDigest(home, wid, dev, ino, size);
606
+ if (stored) {
607
+ digests.set(path, { dev, ino, size, digest: stored, checked: now, ledger, appends: journalAppends() });
608
+ releasable.add(path);
609
+ return stored;
610
+ }
611
+ }
612
+ const record = readJournalRecord(path), entries = record?.entries ?? [];
613
+ const digest = digestOf(foldSnapshot(path, wid, entries), entries, !!record && record.length === record.size);
614
+ if (!record) {
615
+ digests.delete(path);
616
+ return digest;
617
+ }
618
+ digests.set(path, { dev: record.dev, ino: record.ino, size: record.size, digest, checked: now, ledger, appends: journalAppends() });
619
+ if (digest.settled) {
620
+ storeDigest(home, wid, record, digest);
621
+ releasable.add(path);
622
+ }
623
+ return digest;
624
+ }
625
+ /** Last journal identity check of the current digest. Reuse never renews this timestamp. */
626
+ export function workflowDigestChecked(home, wid) {
627
+ return digests.get(pathsOf(home, wid).journal)?.checked ?? -Infinity;
628
+ }
629
+ /** The digest is all a poller reads of a settled workflow: its entries and fold state need not stay in memory. Pollers
630
+ * (allWorkflows, the main agent's workflows) release them after a pass; a one-off reader that compares journal
631
+ * snapshots by identity around a digest (describe) keeps them. */
632
+ const releasable = new Set();
633
+ /** Explicit one-off readers may load settled history between polling passes. */
634
+ export function releaseLoadedSettledJournals() {
635
+ forgetJournalSnapshotsIf(path => !!digests.get(path)?.digest.settled);
636
+ }
637
+ export function releaseSettledJournals() {
638
+ for (const path of releasable) {
639
+ forgetJournalSnapshot(path);
640
+ folds.delete(path);
641
+ }
642
+ releasable.clear();
643
+ }
644
+ function foldSnapshot(path, wid, entries) {
645
+ const hit = derived.get(entries);
363
646
  let wf;
364
647
  if (hit?.wid === wid)
365
648
  wf = hit.snapshot;
@@ -393,12 +676,11 @@ export function workflowSnapshot(home, wid) {
393
676
  else
394
677
  folds.delete(path);
395
678
  }
396
- const planned = plannedTotal(home, wid, wf.rev);
397
- return planned === undefined ? wf : { ...wf, planned };
679
+ return wf;
398
680
  }
399
681
  /** Ops: wids archived by `prune` (orchestrator ledger `pruned{wid}`); they no longer exist for any reader. */
400
682
  function prunedIds(home) {
401
- return ledgerIndex(readJournalSnapshot(orchLedger(home))).pruned;
683
+ return readerLedger(home).state.pruned;
402
684
  }
403
685
  const ledgerIndexes = new WeakMap();
404
686
  export function ledgerIndex(ledger) {
@@ -471,8 +753,24 @@ function workflowIds(home) {
471
753
  throw error;
472
754
  }
473
755
  const pruned = prunedIds(home);
756
+ forgetRemovedWorkflows(home, wids, pruned);
474
757
  return wids.filter(wid => !pruned.has(wid));
475
758
  }
759
+ function forgetRemovedWorkflows(home, names, pruned) {
760
+ const paths = pathsByHome.get(home), present = new Set(names);
761
+ if (paths)
762
+ for (const [wid, p] of paths)
763
+ if (pruned.has(wid) || !present.has(wid)) {
764
+ digests.delete(p.journal);
765
+ folds.delete(p.journal);
766
+ forgetJournalSnapshot(p.journal);
767
+ firstOrigins.delete(p.journal);
768
+ for (const script of p.scripts)
769
+ if (script)
770
+ plannedByPath.delete(script);
771
+ paths.delete(wid);
772
+ }
773
+ }
476
774
  /** Drain: the one hold rule. drain/undrain entries apply to every workflow (no scope), one session's (`origin`) or one
477
775
  * workflow (`wid`). A workflow is held when the newest entry that applies to it is a drain recorded after it was created. */
478
776
  export function holdOf(ledger, wid, origin) {
@@ -491,10 +789,10 @@ export function heldIn(ledger) {
491
789
  }
492
790
  /** Drain: the workflows a drain (stop-all, a quit pi) holds until resume, and since when. */
493
791
  export function heldWorkflows(home) {
494
- const ledger = readJournalSnapshot(orchLedger(home)), ix = ledgerIndex(ledger);
792
+ const ix = readerLedger(home).state;
495
793
  const origin = (wid) => ix.created.get(wid)?.origin;
496
- const hold = (wid) => holdOf(ledger, wid, origin(wid));
497
- const since = ix.lastDrain !== undefined ? ledger[ix.lastDrain].ts : undefined;
794
+ const hold = (wid) => readerHold(ix, wid, origin(wid));
795
+ const since = ix.lastDrain?.ts;
498
796
  return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined, labels: wid => ix.labels.get(wid), session: wid => ix.sessions.get(wid) };
499
797
  }
500
798
  /** The origin of a workflow's `wf-created`, the first entry of its journal, for a workflow the ledger does not attribute
@@ -557,14 +855,90 @@ export function labelsText(labels, width = 60) {
557
855
  const text = Object.entries(labels).map(([k, v]) => `${k}=${v}`).join(" ").replace(/\s+/g, " ");
558
856
  return text ? `[${clip(text, Math.max(1, width - 3))}]` : "";
559
857
  }
858
+ const decorated = new WeakMap();
859
+ /** Free slots are live ledger state, not repeated workflow journal records. */
860
+ function withPoolSlots(wf, state) {
861
+ if (!wf.calls.some(c => c.poolWait))
862
+ return wf;
863
+ const held = new Map();
864
+ for (const h of state.held.values())
865
+ held.set(h.pool, (held.get(h.pool) ?? 0) + 1);
866
+ const pools = state.config?.settings.pools, limits = state.config?.settings.providers;
867
+ return { ...wf, calls: wf.calls.map(c => {
868
+ const wait = c.poolWait;
869
+ if (!wait)
870
+ return c;
871
+ let providers = [];
872
+ if (wait.pool && pools?.[wait.pool]) {
873
+ try {
874
+ providers = resolveModel(wait.pool, pools).map(m => m.provider).filter((p) => !!p);
875
+ }
876
+ catch { /* A removed or invalid pool has no available entries to show. */ }
877
+ }
878
+ const pinned = wait.model.split("/")[0];
879
+ const free = [...new Set(providers)].filter(p => p !== pinned && (held.get(p) ?? 0) < (limits?.[p]?.slots ?? Infinity) &&
880
+ !(state.exhausted.get(p)?.nextTry && state.exhausted.get(p).nextTry > Date.now()));
881
+ return { ...c, poolWait: { ...wait, free } };
882
+ }) };
883
+ }
560
884
  /** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
561
885
  export function allWorkflows(home) {
562
886
  return snapshotsOf(home, workflowIds(home));
563
887
  }
888
+ export function ledgerIdentity(record) {
889
+ return record ? `${record.dev}:${record.ino}:${record.size}` : "";
890
+ }
891
+ function snapshotWithLedger(home, wid, ix, mark) {
892
+ const pendingRevision = (ix.revisions.get(wid) ?? 0) > (digests.get(pathsOf(home, wid).journal)?.digest.snapshot.rev ?? 0);
893
+ const base = workflowDigest(home, wid, pendingRevision ? undefined : mark).snapshot, planned = plannedTotal(home, wid, base.rev), l = ix.labels.get(wid), s = ix.sessions.get(wid);
894
+ const paused = isLive(base) && !!readerHold(ix, wid, ix.created.get(wid)?.origin), hit = decorated.get(base);
895
+ const slotMark = base.calls.some(c => c.poolWait) ? `${mark}:${[...ix.state.exhausted.values()].map(x => x.nextTry > Date.now()).join(",")}` : undefined;
896
+ if (hit && hit.planned === planned && hit.labels === l && hit.session === s && hit.paused === paused && hit.slotMark === slotMark)
897
+ return hit.wf;
898
+ const live = withPoolSlots(base, ix.state);
899
+ const planned1 = planned === undefined ? live : { ...live, planned }, labelled1 = labelled(planned1, l, s);
900
+ const wf = paused ? { ...labelled1, paused: true } : labelled1;
901
+ decorated.set(base, { planned, labels: l, session: s, paused, slotMark, wf });
902
+ return wf;
903
+ }
564
904
  function snapshotsOf(home, wids) {
565
- const { held, labels, session } = heldWorkflows(home);
566
- return wids.sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid), session(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
905
+ const record = readerLedger(home), mark = readerLedgerIdentity(record);
906
+ try {
907
+ return wids.sort().reverse().map(wid => snapshotWithLedger(home, wid, record.state, mark));
908
+ }
909
+ finally {
910
+ releaseSettledJournals();
911
+ }
912
+ }
913
+ /** Directory effects follow committed create-intent/pruned entries (Store.create/materialize, Engine.prune).
914
+ * Check identity first for the fast path; if a scan is needed, read the attributing ledger AFTER listing w/. */
915
+ const listings = new Map();
916
+ export function readerWorkflowListing(home, fresh = false) {
917
+ let record = readerLedger(home);
918
+ const memo = listings.get(home), now = Date.now();
919
+ if (!fresh && memo && memo.mark === readerLedgerIdentity(record) && now >= memo.checked && now - memo.checked < SETTLED_RECHECK_MS)
920
+ return { record, names: memo.names, checked: memo.checked };
921
+ let names;
922
+ try {
923
+ names = readdirSync(join(home, "w"));
924
+ }
925
+ catch (error) {
926
+ if (error.code !== "ENOENT")
927
+ throw error;
928
+ names = [];
929
+ }
930
+ record = readerLedger(home);
931
+ forgetRemovedWorkflows(home, names, record.state.pruned);
932
+ // An intent can be committed before its directory is materialized. Until all unpruned intents are present,
933
+ // a second pass must list again even if no more ledger bytes arrive (including a create during this scan).
934
+ const present = new Set(names), incomplete = [...record.state.intents.keys()].some(wid => !record.state.pruned.has(wid) && !present.has(wid));
935
+ if (incomplete)
936
+ listings.delete(home);
937
+ else
938
+ listings.set(home, { mark: readerLedgerIdentity(record), checked: now, names });
939
+ return { record, names, checked: now };
567
940
  }
941
+ const ownPasses = new Map();
568
942
  /** The workflows `own` ("main:<pi session id>") shows as its own (`ownedBy`), snapshotted exactly as `allWorkflows`
569
943
  * does: the same list as `allWorkflows(home).filter(w => ownedBy(w, own))`, but who owns a workflow is decided from
570
944
  * the orchestrator ledger alone (the origin of its create-intent or `created`, the session its run named), so the
@@ -580,14 +954,42 @@ export function ownWorkflows(home, own, options = {}) {
580
954
  // create-intent before it creates the directory, so every directory listed here already has its intent in a ledger
581
955
  // read afterwards; a workflow another session creates in between is attributed without opening its journal. (Read
582
956
  // the other way round, such a workflow would look unknown to the ledger and its journal would be read.)
583
- const wids = workflowIds(home), ix = ledgerIndex(readJournalSnapshot(orchLedger(home)));
584
- const mine = wids.filter(wid => {
957
+ const { record, names, checked: listed } = readerWorkflowListing(home), ix = record.state, mark = readerLedgerIdentity(record), now = Date.now();
958
+ let passes = ownPasses.get(home);
959
+ if (!passes)
960
+ ownPasses.set(home, passes = new Map());
961
+ const key = JSON.stringify([own, !!options.started]), prior = passes.get(key);
962
+ const current = prior && prior.names === names && !prior.retryUnknown && prior.mark === mark && prior.appends === journalAppends() && now >= prior.checked && now - prior.checked < SETTLED_RECHECK_MS;
963
+ const includes = (w) => options.started ? w.origin === own : ownedBy(w, own);
964
+ if (current && !prior.pending.length) {
965
+ // Another explicit reader may have loaded these journals since the preceding pass.
966
+ releaseLoadedSettledJournals();
967
+ return prior.result;
968
+ }
969
+ const candidates = current ? prior.candidates : names.filter(wid => !wid.startsWith(".") && !ix.pruned.has(wid)).filter(wid => {
585
970
  const known = ix.intents.has(wid) || ix.created.has(wid), session = ix.sessions.get(wid);
586
971
  const origin = known ? ix.intents.get(wid) ?? ix.created.get(wid)?.origin : firstOrigin(home, wid);
587
972
  return origin === own || (!options.started && session !== undefined && `main:${session}` === own);
588
- });
589
- // The journal decides as well: a workflow whose wf-created is not written yet has no origin, as in allWorkflows.
590
- return snapshotsOf(home, mine).filter(w => options.started ? w.origin === own : ownedBy(w, own));
973
+ }).sort().reverse();
974
+ try {
975
+ const changed = new Map((current ? prior.pending : candidates).map(wid => [wid, snapshotWithLedger(home, wid, ix, mark)]));
976
+ const old = new Map(prior?.result.map(w => [w.wid, w]));
977
+ const result = candidates.map(wid => changed.get(wid) ?? old.get(wid)).filter(w => w && includes(w));
978
+ const same = prior && prior.result.length === result.length && result.every((w, i) => w === prior.result[i]);
979
+ // A rescan can reuse digests checked earlier: the outer pass inherits the oldest dependency check.
980
+ let checked = current ? prior.checked : Math.min(now, listed);
981
+ const pending = candidates.filter(wid => {
982
+ const memo = digests.get(pathsOf(home, wid).journal), digest = memo?.digest;
983
+ if (digest?.settled)
984
+ checked = Math.min(checked, memo.checked);
985
+ return !digest?.settled || (ix.revisions.get(wid) ?? 0) > digest.snapshot.rev;
986
+ });
987
+ passes.set(key, { mark, checked, appends: journalAppends(), names, retryUnknown: names.some(wid => !ix.intents.has(wid) && !ix.created.has(wid) && !ix.pruned.has(wid)), candidates, pending, result: same ? prior.result : result });
988
+ return same ? prior.result : result;
989
+ }
990
+ finally {
991
+ releaseSettledJournals();
992
+ }
591
993
  }
592
994
  /** P10/P11: Per-workflow script console log written by the orchestrator (bounded, human-readable). */
593
995
  export function scriptLogPath(home, wid) { return join(workflowDir(home, wid), "script.log"); }
@@ -607,11 +1009,11 @@ export function compactWorkflow(wf, leases) {
607
1009
  ...(wf.planned !== undefined ? { planned: wf.planned } : {}), done: progress.done,
608
1010
  calls: wf.calls.map(c => {
609
1011
  const r = c.result, last = r?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1);
610
- return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...(r ? { status: r.status, ok: r.ok } : {}),
1012
+ return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
611
1013
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
612
1014
  ...(c.model ? { model: c.model } : {}), ...(c.tools ? { tools: c.tools } : {}), ...(c.pending ? { pending: c.pending } : {}), ...(c.switching ? { switching: c.switching } : {}), ...(c.switchFailed ? { switchFailed: c.switchFailed } : {}), ...(nonzero(c.usage) ? { usage: c.usage } : {}),
613
1015
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
614
- ...(c.answered ? { answered: c.answered } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
1016
+ ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(c.writerWait && !r ? { writerWait: c.writerWait } : {}), ...(!r && leases?.get(c.callId) ? { lease: leases.get(c.callId) } : {}),
615
1017
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
616
1018
  }),
617
1019
  attention: wf.attention.map(a => ({ id: a.id, rev: a.rev, kind: a.kind, text: clip(a.text, 300), ...(a.call ? { call: a.call } : {}), ...(a.qid ? { qid: a.qid } : {}) })),
@@ -621,9 +1023,9 @@ export function compactWorkflow(wf, leases) {
621
1023
  function origins(home) {
622
1024
  const ids = new Map();
623
1025
  const pruned = prunedIds(home);
624
- for (const e of readJournalSnapshot(orchLedger(home)))
625
- if (e.type === JT.created && !pruned.has(String(e.wid)))
626
- ids.set(String(e.wid), e.origin);
1026
+ for (const [wid, origin] of readerLedger(home).state.origins)
1027
+ if (!pruned.has(wid))
1028
+ ids.set(wid, origin);
627
1029
  for (const wid of workflowIds(home))
628
1030
  if (!ids.has(wid))
629
1031
  ids.set(wid, undefined);
@@ -653,8 +1055,7 @@ export function statusView(home, options = {}) {
653
1055
  }
654
1056
  /** The stats the running orchestrator published (none when no orchestrator runs). */
655
1057
  export function runningStats(home) {
656
- const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
657
- ledgerStates.set(path, state);
1058
+ const state = readerLedger(home).state.state;
658
1059
  const o = state.orchestrator, stats = o && !o.exited && processAlive(o.pid, o.start) ? readStats(home, o.pid) : undefined;
659
1060
  return stats ? { orchestratorStats: stats } : {};
660
1061
  }
@@ -668,7 +1069,7 @@ const latestCalls = (wf) => [...new Map(wf.calls.map(c => [c.key, c])).values()]
668
1069
  /** Provider slots from the orchestrator ledger: holders per provider (hold/release{pool,slot,exec}) and the limits of
669
1070
  * the settings in effect (the latest config{hash,config}); config-rejected after it is reported too. */
670
1071
  // One fold per orchestrator ledger, extended as it grows (ledger.ts; the executor folds the same entries the same way).
671
- const ledgerStates = new Map();
1072
+ // Pi readers share the compact incremental fold in reader-ledger.ts.
672
1073
  /** The orchestrator running now (its last `orchestrator` record, without an exit, whose process lives), and a note when
673
1074
  * its version is not the one this process loaded: running work stays on the version it started with. */
674
1075
  export function orchestratorView(state, loaded = packageVersion(), now = Date.now()) {
@@ -721,8 +1122,7 @@ export const NOTIFY_SINCE = "1.0.28";
721
1122
  * older orchestrator would accept the request and its child would drop it); none when none runs (the next one starts
722
1123
  * on the installed version) or it is current. */
723
1124
  export function orchestratorTooOld(home, feature, since, loaded = packageVersion()) {
724
- const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
725
- ledgerStates.set(path, state);
1125
+ const state = readerLedger(home).state.state;
726
1126
  const o = state.orchestrator;
727
1127
  if (!o || o.exited || !processAlive(o.pid, o.start) || !newer(since, o.version) || !newer(loaded, o.version))
728
1128
  return undefined;
@@ -731,8 +1131,7 @@ export function orchestratorTooOld(home, feature, since, loaded = packageVersion
731
1131
  }
732
1132
  /** orchestratorView of the home's orchestrator ledger. */
733
1133
  export function runningOrchestrator(home) {
734
- const path = orchLedger(home), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), readJournalSnapshot(path));
735
- ledgerStates.set(path, state);
1134
+ const state = readerLedger(home).state.state;
736
1135
  return orchestratorView(state);
737
1136
  }
738
1137
  /** One `exhausted` line of the status views (the `provider-exhausted` wait uses it as its detail). */
@@ -751,13 +1150,12 @@ export function originLabel(origin) {
751
1150
  return origin.startsWith("main:") ? `session ${origin.slice(5, 13)}` : clip(restartLine(origin), 40);
752
1151
  }
753
1152
  export function slotsView(home, now = Date.now()) {
754
- const path = orchLedger(home), entries = readJournalSnapshot(path), state = foldLedger(ledgerStates.get(path) ?? emptyLedger(), entries);
755
- ledgerStates.set(path, state);
1153
+ const ix = readerLedger(home).state, state = ix.state;
756
1154
  const { held, config, rejected } = state, used = state.exhausted;
757
1155
  const exhausted = [...used].sort(([a], [b]) => a.localeCompare(b)).map(([p, x]) => exhaustedLine(p, x, now));
758
1156
  const limits = config?.settings.providers ?? {};
759
1157
  const holders = new Map(), byOrigin = new Map();
760
- const created = ledgerIndex(entries).created;
1158
+ const created = ix.created;
761
1159
  for (const e of held.values())
762
1160
  if (e.pool !== "memory") {
763
1161
  holders.set(e.pool, (holders.get(e.pool) ?? 0) + 1);
@@ -797,13 +1195,13 @@ export function statusBrief(home, options = {}) {
797
1195
  const p = progressOf(w), open = w.attention.filter(a => a.kind !== "finished");
798
1196
  const calls = latestCalls(w).filter(c => c.phase !== "sealed" || (c.result && !c.result.ok) || c.notesPending).map((c) => {
799
1197
  const live = c.phase !== "sealed", quiet = c.lastActivity !== undefined ? now - c.lastActivity : undefined;
800
- return { key: c.key, agent: c.agent, phase: c.phase, ...(c.model ? { model: c.model } : {}),
1198
+ return { key: c.key, agent: c.agent, phase: c.phase, ...modelStatus(c), ...(c.model ? { model: c.model } : {}),
801
1199
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
802
1200
  ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
803
1201
  ...(live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
804
1202
  ...(live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
805
1203
  ...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
806
- ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1204
+ ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
807
1205
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
808
1206
  ...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {}),
809
1207
  ...(c.notesPending ? { notesPending: c.notesPending } : {}) };