pi-durable-subagents 1.0.38 → 1.0.40

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.40
4
+
5
+ - Readers keep rebuildable digests of settled workflows and facts of final calls in `DSA_HOME/cache`, keyed by
6
+ journal or session identity and the deriving code. Prune removes these cache entries with their workflow.
7
+
8
+ - A pi session uses these digests for its own workflows, keeps unchanged workflow objects, and releases settled
9
+ journals and fold state after each pass. An unchanged ledger permits at most five seconds without journal IO;
10
+ a ledger change forces a check, and turn boundaries check immediately for late attention. Final call facts release
11
+ their transcripts and recheck session identity within
12
+ five seconds. Concurrent cache writes are atomic, checked, and cannot recreate a pruned workflow's cache.
13
+ - Pi readers fold the ledger's committed prefix in bounded chunks into compact per-home state, without retaining
14
+ decoded history. Replacement and truncation rebuild it. Unchanged passes skip the workflow directory scan and
15
+ reuse settled results and the ordered UI view by identity; the dock and open list do not request redundant renders.
16
+ Incomplete creation or revision intents and unsettled workflows are still checked on the next pass.
17
+ - Workflows with pending undelivered follow-ups or unfinished recovery bookkeeping are not settled. Recovery-only
18
+ follow-ups therefore appear on the next poll, even without a new ledger entry. Missing completion notices, pending
19
+ forwards, fences, gates, successful worktree cleanup and retired questions also prevent the trust window.
20
+ - `scripts/bench-ui.ts` uses a temporary cache and reports steady RSS and live heap after history release. `--cache-home`
21
+ reuses caches for a second run; `node --expose-gc` collects released history before and after steady-state polling.
22
+ - Measured against 1.0.39 on a home with 1,530 workflows, for a session owning 197 of them (load 1.3, warm cache): a
23
+ steady refresh fell from 9.0 ms to 2.7 ms (p50), the steady RSS from 345 MiB to 145 MiB with a 26 MiB live heap, the
24
+ first refresh from 1.2 s to 0.4 s and the session-start notice from 0.71 s to 0.12 s. With an empty cache the first
25
+ refresh is unchanged (1.2 s) and the RSS stays near 300 MiB until the allocator returns memory.
26
+
27
+ ## 1.0.39
28
+
29
+ - A pi session reads only its own workflows. Since 1.0.30 the UI shows only the workflows of its session, yet the pi
30
+ process read, folded and cached every workflow journal of the machine every 500 ms. Ownership is now decided from
31
+ the orchestrator ledger (the origin of a workflow's create-intent or `created`, or the session its run named)
32
+ before any journal is opened, so other sessions' journals are never opened, stat'ed or cached by a pi process.
33
+ Measured on a home with 1,132 workflows (load 16-27): the first refresh of a busy session fell from 9.4 s to 1.6 s,
34
+ a steady refresh from 86 ms to 7 ms and the process RSS from 696 MiB to 325 MiB; a session without workflows went
35
+ from 17.7 s to 0.4 s and 683 MiB to 166 MiB. A session that many runs name (here 759 workflows) still reads all of
36
+ them, so its gain is smaller. `scripts/bench-ui.ts` measures this (read-only).
37
+ - Session start no longer scans every journal: the starter checks whether an orchestrator holds its lock first and
38
+ scans only when none does; the scan stops at the first unfinished workflow and does not keep the journals it read.
39
+ The paused notice at session start and the pause on quit read only the workflows the session started.
40
+ - A workflow directory the ledger does not know (only a hand-made or damaged home has one) is attributed by its
41
+ journal's first entry, read once; a failed read is retried once the file changes.
42
+ - The CLI (`status`, `restart`) and the orchestrator are unchanged.
43
+
3
44
  ## 1.0.38
4
45
 
5
46
  - An answer to any open question of a call reaches it. A call whose question was interrupted (by a steer) and that
package/README.md CHANGED
@@ -577,6 +577,29 @@ read, in a burst each time a call ends), `pid` and `at` (when it was
577
577
  written). The orchestrator writes these to `orchestrator-stats.json` every
578
578
  10 s; they are shown only while that process runs.
579
579
 
580
+ A pi session reads only its own workflows. Which workflows are its own comes
581
+ from the orchestrator ledger, so its dock and list never open the journals or
582
+ transcripts of other sessions' workflows, however many the machine has. While
583
+ an orchestrator runs, a pi session does not look for pending work at all;
584
+ without one, it looks until it finds the first unfinished workflow and keeps
585
+ none of the journals it read. `node scripts/bench-ui.ts --owner=main:<pi
586
+ session id>` measures what a session pays on its main thread for a given
587
+ `DSA_HOME` (read-only). The measurement uses a temporary cache; pass
588
+ `--cache-home=<temporary directory>` to reuse it across runs, and run with
589
+ `node --expose-gc` to measure RSS after released history is collected.
590
+
591
+ Readers keep digests of settled workflows and facts of final calls in
592
+ `DSA_HOME/cache`. These are rebuildable: deleting the cache costs one slower
593
+ read. Digests are keyed by journal identity and reducer code; final facts by
594
+ call seal, session identity and deriving code. A settled journal is released
595
+ after each pass. Polling skips its journal IO while the ledger stays unchanged,
596
+ for at most five seconds. Turn boundaries check immediately for late attention.
597
+ Ledger changes force a journal check;
598
+ final sessions are also rechecked within five seconds. Only an explicitly
599
+ opened final call keeps its transcript. Prune removes the workflow's caches.
600
+ `DSA_CACHE_HOME=<directory>` places the derived cache under that directory
601
+ instead of `DSA_HOME`, without changing where authoritative data is read.
602
+
580
603
  ### Where the orchestrator starts
581
604
 
582
605
  Whatever needs it first starts the orchestrator: a pi session, a CLI
@@ -1,61 +1,116 @@
1
- import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
1
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
- import { readJournalSnapshot } from "../../kernel/journal.js";
5
- import { journalPath, orchLedger } from "../../paths.js";
6
- import { CT, JT, attentionEntries } from "../../types.js";
7
- import { holdOf, ledgerIndex } from "../../orchestrator/snapshot.js";
8
- /** P15, P25: Read workflow snapshots without modifying another domain's history; a wid with an orchestrator.jsonl
9
- * `pruned{wid}` entry is gone (housekeeping), even while its directory is still being removed. */
10
- export function workflows(home, origin) {
11
- const ledger = readJournalSnapshot(orchLedger(home)), { created: createdBy, pruned } = ledgerIndex(ledger);
12
- let names;
4
+ import { forgetJournalSnapshot, journalAppends, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
+ import { journalPath } from "../../paths.js";
6
+ import { CT, JT } from "../../types.js";
7
+ import { openGeneration, readerWorkflowListing, releaseLoadedSettledJournals, releaseSettledJournals, SETTLED_RECHECK_MS, unresolvedAttention, workflowDigest, workflowDigestChecked } from "../../orchestrator/snapshot.js";
8
+ import { readerHold, readerLedgerIdentity } from "../../orchestrator/reader-ledger.js";
9
+ const passes = new Map();
10
+ export function workflows(home, origin, fresh = false) {
11
+ const { record, names, checked: listed } = readerWorkflowListing(home, fresh), ix = record.state, mark = readerLedgerIdentity(record), now = Date.now();
12
+ let byOrigin = passes.get(home);
13
+ if (!byOrigin)
14
+ passes.set(home, byOrigin = new Map());
15
+ const prior = byOrigin.get(origin), current = !fresh && prior && prior.names === names && !prior.retryUnknown && prior.mark === mark && prior.appends === journalAppends() && now >= prior.checked && now - prior.checked < SETTLED_RECHECK_MS;
16
+ if (current && !prior.pending.length) {
17
+ releaseLoadedSettledJournals();
18
+ return prior.result;
19
+ }
20
+ const ids = current ? prior.ids : [...new Set([...[...ix.created.keys()].map(String), ...names].filter(wid => !ix.pruned.has(wid)))].sort()
21
+ .filter(wid => origin === undefined || !ix.created.has(wid) || ix.created.get(wid)?.origin === origin);
22
+ const digests = new Map(current ? prior.digests : []), old = new Map(prior?.result.map(w => [w.wid, w])), changes = new Map();
23
+ try {
24
+ for (const wid of current ? prior.pending : ids) {
25
+ const pendingRevision = (ix.revisions.get(wid) ?? 0) > (prior?.digests.get(wid)?.snapshot.rev ?? 0);
26
+ const known = ix.created.get(wid), digest = workflowDigest(home, wid, fresh || pendingRevision ? undefined : mark), path = journalPath(home, wid);
27
+ const from = known ? known.origin : readJournalUncached(path)?.entries.find(e => e.type === JT.created)?.origin;
28
+ if (origin !== undefined && from !== origin) {
29
+ old.delete(wid);
30
+ digests.set(wid, digest);
31
+ continue;
32
+ }
33
+ if (prior?.digests.get(wid) === digest && old.get(wid)?.origin === from) {
34
+ digests.set(wid, digest);
35
+ continue;
36
+ }
37
+ digests.set(wid, digest);
38
+ changes.set(wid, { wid, origin: from, ...(digest.settled ? { settled: digest.settled } : {}), get entries() {
39
+ const entries = readJournalSnapshot(path);
40
+ if (digest.settled)
41
+ forgetJournalSnapshot(path);
42
+ return entries;
43
+ } });
44
+ }
45
+ const result = ids.map(wid => changes.get(wid) ?? old.get(wid)).filter((w) => !!w);
46
+ const same = prior && prior.result.length === result.length && result.every((w, i) => w === prior.result[i]);
47
+ // Digest reuse and another reader's listing refresh cannot extend this pass's trust window.
48
+ let checked = current ? prior.checked : Math.min(now, listed);
49
+ const pending = ids.filter(wid => {
50
+ const d = digests.get(wid);
51
+ if (d?.settled)
52
+ checked = Math.min(checked, workflowDigestChecked(home, wid));
53
+ return !d?.settled || (ix.revisions.get(wid) ?? 0) > d.snapshot.rev;
54
+ });
55
+ byOrigin.set(origin, { mark, checked, appends: journalAppends(), names, retryUnknown: ids.some(wid => !ix.created.has(wid)), ids, pending, digests, result: same ? prior.result : result });
56
+ return same ? prior.result : result;
57
+ }
58
+ finally {
59
+ releaseSettledJournals();
60
+ }
61
+ }
62
+ export { openGeneration };
63
+ /** Whether one journal is unfinished, by file identity: a journal that has not changed is not read again. */
64
+ const decided = new Map();
65
+ function unfinishedJournal(path, known) {
66
+ let stat;
13
67
  try {
14
- names = readdirSync(join(home, "w"));
68
+ stat = statSync(path);
15
69
  }
16
70
  catch (error) {
17
71
  if (error.code !== "ENOENT")
18
72
  throw error;
19
- names = [];
20
- }
21
- const ids = new Set([...[...createdBy.keys()].map(String), ...names].filter(wid => !pruned.has(wid)));
22
- const result = [];
23
- for (const wid of [...ids].sort()) {
24
- // With an origin wanted, a workflow the ledger attributes to another session is skipped without reading its journal.
25
- const known = createdBy.get(wid);
26
- if (origin !== undefined && known && known.origin !== origin)
27
- continue;
28
- const entries = readJournalSnapshot(journalPath(home, wid));
29
- const created = known ?? entries.find(e => e.type === JT.created);
30
- if (origin !== undefined && created?.origin !== origin)
31
- continue;
32
- result.push({ wid, origin: created?.origin, entries });
73
+ decided.delete(path);
74
+ return true;
75
+ } // no done yet
76
+ const hit = decided.get(path);
77
+ if (hit && hit.ino === stat.ino && hit.size === stat.size)
78
+ return hit.unfinished;
79
+ // Read without keeping the entries in the shared journal cache: a pi process scans every workflow only when no
80
+ // orchestrator runs, and keeping every journal of the machine cost it hundreds of MB.
81
+ const read = known ?? readJournalUncached(path);
82
+ if (!read) {
83
+ decided.delete(path);
84
+ return true;
33
85
  }
34
- return result;
35
- }
36
- /** P37: a generation opened by a send (possibly after the workflow finished) that has no seal yet is pending work. */
37
- const opened = new WeakMap();
38
- export function openGeneration(entries) {
39
- const hit = opened.get(entries);
40
- if (hit?.length === entries.length)
41
- return hit.open;
42
- // Sealed call ids end in `/<key>@<gen>`; collect every such suffix once instead of rescanning per generation.
43
- const sealed = new Set();
44
- for (const s of entries)
45
- if (s.type === JT.sealed) {
46
- const call = String(s.call);
47
- for (let i = call.indexOf("/"); i >= 0; i = call.indexOf("/", i + 1))
48
- sealed.add(call.slice(i));
49
- }
50
- const open = entries.some(g => g.type === "generation" && !sealed.has(`/${String(g.key)}@${String(g.gen)}`));
51
- opened.set(entries, { length: entries.length, open });
52
- return open;
86
+ const unfinished = !read.entries.some(e => e.type === JT.done) || openGeneration(read.entries);
87
+ decided.set(path, { ino: read.ino, size: read.size, unfinished });
88
+ return unfinished;
53
89
  }
54
90
  /** P1: Workflow-side pending work shared by every starter: a workflow without JT.done or with an unsealed generation,
55
- * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself. */
56
- export function unfinishedWorkflow(home) {
57
- const ledger = readJournalSnapshot(orchLedger(home));
58
- return workflows(home).some(w => (!w.entries.some(e => e.type === JT.done) || openGeneration(w.entries)) && !holdOf(ledger, w.wid, w.origin));
91
+ * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
92
+ * Stops at the first unfinished workflow (newest first); a held workflow the ledger attributes is skipped without
93
+ * reading its journal, and an unchanged journal is not read again. */
94
+ export function unfinishedWorkflow(home, fresh = false) {
95
+ const { record, names } = readerWorkflowListing(home, fresh), ix = record.state, { created, pruned } = ix;
96
+ const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
97
+ for (const wid of ids) {
98
+ const path = journalPath(home, wid);
99
+ // The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
100
+ // a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
101
+ const known = created.get(wid);
102
+ if (known && readerHold(ix, wid, known.origin))
103
+ continue;
104
+ let read;
105
+ if (!known) {
106
+ read = readJournalUncached(path);
107
+ if (readerHold(ix, wid, read?.entries.find(e => e.type === JT.created)?.origin))
108
+ continue;
109
+ }
110
+ if (unfinishedJournal(path, read))
111
+ return true;
112
+ }
113
+ return false;
59
114
  }
60
115
  const receipts = new WeakMap();
61
116
  const receiptsOf = (entry) => entry.type === "custom_message" && entry.customType === CT.attention
@@ -69,22 +124,11 @@ export function presented(ctx) {
69
124
  receipts.set(owner, { first: entries[0], last: entries.at(-1), length: entries.length, items });
70
125
  return items;
71
126
  }
72
- const open = new WeakMap();
73
- /** The unresolved attention items of one immutable journal snapshot, computed once per snapshot. */
74
- function unresolved(entries) {
75
- let items = open.get(entries);
76
- if (items)
77
- return items;
78
- const done = new Set(entries.filter(e => e.type === JT.attentionResolved).map(e => `${e.id}\0${e.rev}`));
79
- items = attentionEntries(entries).map(e => e.item).filter(item => !done.has(`${item.id}\0${item.rev}`));
80
- open.set(entries, items);
81
- return items;
82
- }
83
127
  /** P15, V7: Select only unresolved, unpresented items owned by this session. */
84
- export function attention(home, sender, seen) {
128
+ export function attention(home, sender, seen, fresh = false) {
85
129
  const items = [], shown = new Set(seen.map(s => `${s.id}\0${s.rev}`));
86
- for (const workflow of workflows(home, sender)) {
87
- for (const item of unresolved(workflow.entries)) {
130
+ for (const workflow of workflows(home, sender, fresh)) {
131
+ for (const item of workflow.settled?.attention ?? unresolvedAttention(workflow.entries)) {
88
132
  const key = `${item.id}\0${item.rev}`;
89
133
  if (shown.has(key))
90
134
  continue; // singlePresentation: one presentation per id/rev
@@ -6,13 +6,13 @@ import { setTimeout as delay } from "node:timers/promises";
6
6
  import { defineTool } from "@earendil-works/pi-coding-agent";
7
7
  import { Outbox, scanInbox } from "../kernel/mailbox.js";
8
8
  import { readJournalSnapshot } from "../kernel/journal.js";
9
- import { reduceLifecycle } from "../kernel/lifecycle.js";
9
+ import { readerLedger } from "../orchestrator/reader-ledger.js";
10
10
  import { OsLock } from "../platform/lock.js";
11
11
  import { launchOrchestrator } from "../platform/launch.js";
12
- import { dsaHome, orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
12
+ import { dsaHome, orchInbox, orchLock, outboxRoot } from "../paths.js";
13
13
  import { CT, JT } from "../types.js";
14
14
  import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
15
- import { NOTIFY_SINCE, isLive, orchestratorTooOld, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
15
+ import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
16
16
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
17
17
  import { parameters } from "./main/schema.js";
18
18
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
@@ -56,16 +56,13 @@ export function registerMain(pi, ui) {
56
56
  queue = result.catch(() => { });
57
57
  return result;
58
58
  }
59
- function ledger() { return readJournalSnapshot(orchLedger(home)); }
60
- function decisions() {
61
- return reduceLifecycle(ledger().filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type))).resolved;
62
- }
59
+ function ledger() { return readerLedger(home).state; }
60
+ function decisions() { return ledger().decisions; }
63
61
  async function reconcile() {
64
62
  for (const rid of decisions().keys())
65
63
  await outbox?.markResolved(rid);
66
- for (const entry of ledger())
67
- if (entry.type === JT.created)
68
- await outbox?.markResolved(String(entry.rid));
64
+ for (const rid of ledger().createdRids.keys())
65
+ await outbox?.markResolved(String(rid));
69
66
  }
70
67
  function pendingOutbox() { return pendingRids().size > 0; }
71
68
  function pendingRids() {
@@ -82,14 +79,17 @@ export function registerMain(pi, ui) {
82
79
  if (stopped)
83
80
  return;
84
81
  await reconcile();
85
- const pending = submitting || pendingOutbox() || (await scanInbox(orchInbox(home))).length > 0 || unfinishedWorkflow(home);
86
- if (!pending)
87
- return;
82
+ // A running orchestrator (it holds its lock) serves every pending request and workflow: then nothing is scanned.
83
+ // Only without one is pending work looked for, stopping at the first; the scan reads workflow journals without
84
+ // keeping them (see unfinishedWorkflow).
88
85
  await mkdir(home, { recursive: true });
89
86
  const lock = await new OsLock().tryAcquire(orchLock(home));
90
87
  if (!lock)
91
88
  return;
92
89
  await lock.release();
90
+ const pending = submitting || pendingOutbox() || (await scanInbox(orchInbox(home))).length > 0 || unfinishedWorkflow(home);
91
+ if (!pending)
92
+ return;
93
93
  const entry = process.env.DSA_ORCHESTRATOR_ENTRY ?? fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../orchestrator/main.ts" : "../orchestrator/main.js", import.meta.url));
94
94
  // Inside pi: started even when pi cannot be resolved here (the orchestrator falls back to its own lookup).
95
95
  await launchOrchestrator(entry, process.env, { home });
@@ -104,7 +104,7 @@ export function registerMain(pi, ui) {
104
104
  versionTold = orchestrator;
105
105
  ctx.ui.notify(`Durable Subagents: ${versionNote}.`, "warning");
106
106
  }
107
- function collect() { return ctx ? attention(home, sender, [...presented(ctx), ...reserved]) : []; }
107
+ function collect(fresh = false) { return ctx ? attention(home, sender, [...presented(ctx), ...reserved], fresh) : []; }
108
108
  function message(items) {
109
109
  return { type: "custom_message", customType: CT.attention, content: items.map(presentText).join("\n"), display: true, details: { items } };
110
110
  }
@@ -128,7 +128,8 @@ export function registerMain(pi, ui) {
128
128
  if (stopped)
129
129
  return;
130
130
  ctx = context;
131
- const items = collect(), entries = [];
131
+ // Polling can reuse a settled digest; a turn boundary must see attention appended just before it.
132
+ const items = collect(true), entries = [];
132
133
  if (items.length) {
133
134
  entries.push(message(items));
134
135
  reserved.push(...items);
@@ -191,7 +192,8 @@ export function registerMain(pi, ui) {
191
192
  pi.on("session_start", async (_event, context) => {
192
193
  await start(context);
193
194
  // Quit pause: say once, at the session's start, which of its workflows wait for a resume.
194
- const paused = statusView(home, { origin: sender }).workflows.filter(w => w.origin === sender && isLive(w) && w.paused);
195
+ // Only the workflows this session started are read (ownership comes from the orchestrator ledger), not every one.
196
+ const paused = ownWorkflows(home, sender, { started: true }).filter(w => w.origin === sender && isLive(w) && w.paused);
195
197
  if (paused.length)
196
198
  pi.sendMessage({ customType: CT.note, display: true, content: `${paused.length} subagent workflow${paused.length > 1 ? "s were" : " was"} paused when pi quit (${paused.map(w => w.name ?? w.wid).join(", ")}). Ask to resume, or open /subagents (or ↓) and press r.` });
197
199
  });
@@ -202,7 +204,7 @@ export function registerMain(pi, ui) {
202
204
  pi.on("session_shutdown", async (event) => {
203
205
  if (event.reason === "quit" && quitPolicy(home) === "pause" && outbox && !stopped) {
204
206
  try {
205
- const running = statusView(home, { origin: sender }).workflows.some(w => w.origin === sender && isLive(w) && !w.paused);
207
+ const running = ownWorkflows(home, sender, { started: true }).some(w => w.origin === sender && isLive(w) && !w.paused);
206
208
  if (running)
207
209
  await serial(async () => { await outbox?.send("orch", "drain", { fence: true, origin: sender }); });
208
210
  }
@@ -246,7 +248,10 @@ export function registerMain(pi, ui) {
246
248
  return args;
247
249
  }
248
250
  /** "<rid>" or "<rid>/<key>" of a created run → the same address with its wid; anything else is unchanged. */
249
- function ridToWid(value) { return widOfRid(ledger(), value); }
251
+ function ridToWid(value) {
252
+ const cut = value.indexOf("/"), head = cut < 0 ? value : value.slice(0, cut), created = head ? ledger().createdRids.get(head) : undefined;
253
+ return created ? `${String(created.wid)}${value.slice(head.length)}` : value;
254
+ }
250
255
  /** A run request without a workflow yet (still pending, or rejected), asked about by its rid. */
251
256
  function pendingRun(rid) {
252
257
  const decision = decisions().get(rid);
@@ -390,7 +395,7 @@ export function registerMain(pi, ui) {
390
395
  return outbox.send("orch", normalized.kind, normalized.body, normalized.cond);
391
396
  });
392
397
  if ("conflict" in outcome) {
393
- const created = ledger().find(e => e.type === JT.created && e.rid === rid);
398
+ const created = ledger().createdRids.get(rid);
394
399
  return { applied: false, reason: "request-conflict", request: args.request, spec_digest: outcome.digest, ...(created ? { wid: created.wid } : {}),
395
400
  note: "this request id was used for different content; use a new id" };
396
401
  }
@@ -398,7 +403,7 @@ export function registerMain(pi, ui) {
398
403
  // P25: run waits for `created`; control requests wait for their terminal lifecycle record (applied or rejected+reason).
399
404
  const deadline = performance.now() + 10_000;
400
405
  while (wait || sent.kind === "run") {
401
- const receipt = sent.kind === "run" ? ledger().find(e => e.type === JT.created && e.rid === sent.rid) : undefined;
406
+ const receipt = sent.kind === "run" ? ledger().createdRids.get(sent.rid) : undefined;
402
407
  const decision = receipt ? undefined : decisions().get(sent.rid);
403
408
  if (receipt || decision) {
404
409
  await serial(async () => { await outbox?.markResolved(sent.rid); });
@@ -411,7 +416,7 @@ export function registerMain(pi, ui) {
411
416
  if (decision.type === "rejected")
412
417
  return { applied: false, reason: sent.kind === "resume" && args.wid === undefined ? resumeElsewhere(String(decision.reason)) : decision.reason, rid: sent.rid };
413
418
  if (sent.kind !== "run") {
414
- return { applied: true, rid: sent.rid, ...followUpReceipt(home, sent.rid, sent.body), ...sendReceipt(ledger(), sent.rid) };
419
+ return { applied: true, rid: sent.rid, ...followUpReceipt(home, sent.rid, sent.body), ...sendReceipt([ledger().sendNotes.get(sent.rid)].filter((e) => !!e), sent.rid) };
415
420
  }
416
421
  }
417
422
  if (performance.now() >= deadline || signal?.aborted)
@@ -55,7 +55,7 @@ async function pendingOutboxes(home) {
55
55
  /** P1: The pending-work rule shared with the main agent's starter: a non-empty orchestrator inbox, a pending
56
56
  * request to the orchestrator in any sender outbox, a workflow without JT.done, or an unsealed generation. */
57
57
  export async function pendingWork(home) {
58
- return (await scanInbox(orchInbox(home))).length > 0 || await pendingOutboxes(home) || unfinishedWorkflow(home);
58
+ return (await scanInbox(orchInbox(home))).length > 0 || await pendingOutboxes(home) || unfinishedWorkflow(home, true);
59
59
  }
60
60
  /** P1: The optional service's starter: start the orchestrator only when work is pending; publish no request
61
61
  * (unlike `resume`, it never undoes a drain or stop-all). Returns whether the starter was invoked. */
@@ -13,11 +13,11 @@ import { journalPath, orchLedger } from "../paths.js";
13
13
  import { PS } from "../platform/proctable.js";
14
14
  import { JT } from "../types.js";
15
15
  import { restartInputError, restartRefusal } from "../orchestrator/restart.js";
16
- import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
16
+ import { readerLedger } from "../orchestrator/reader-ledger.js";
17
17
  import { allWorkflows, liveCalls, processAlive } from "../orchestrator/snapshot.js";
18
18
  /** The orchestrator that runs now: the last `orchestrator` record without an exit, whose process lives. */
19
19
  export function currentOrchestrator(home) {
20
- const o = foldLedger(emptyLedger(), readJournalSnapshot(orchLedger(home))).orchestrator;
20
+ const o = readerLedger(home).state.state.orchestrator;
21
21
  return o && !o.exited && processAlive(o.pid, o.start) ? { version: o.version, pid: o.pid, ...(o.start ? { start: o.start } : {}), ts: o.ts, ...(o.restart ? { restart: true } : {}) } : undefined;
22
22
  }
23
23
  /** Best-effort provenance; never read the live DSA home to identify the invoking process. */
@@ -0,0 +1,40 @@
1
+ // Rebuildable reader caches: checked payloads, published whole, with no durable authority.
2
+ import { randomUUID } from "node:crypto";
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+ import { crc32 } from "./journal.js";
6
+ export function readCache(path) {
7
+ try {
8
+ const { checksum, ...record } = JSON.parse(readFileSync(path, "utf8"));
9
+ return checksum === crc32(Buffer.from(JSON.stringify(record))) ? record : undefined;
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ }
15
+ /** A disappeared journal means pruning won: neither an in-flight reader nor another window recreates its cache. */
16
+ export function writeCache(path, record, journal) {
17
+ const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
18
+ try {
19
+ if (!existsSync(journal))
20
+ return;
21
+ mkdirSync(dirname(path), { recursive: true });
22
+ writeFileSync(tmp, JSON.stringify({ ...record, checksum: crc32(Buffer.from(JSON.stringify(record))) }), { flag: "wx" });
23
+ renameSync(tmp, path);
24
+ if (!existsSync(journal)) {
25
+ rmSync(path, { force: true });
26
+ // A facts cache has one directory per workflow; remove it only if it is empty.
27
+ try {
28
+ rmdirSync(dirname(path));
29
+ }
30
+ catch { /* another cache may still live here */ }
31
+ }
32
+ }
33
+ catch { /* A cache failure only costs another read. */ }
34
+ finally {
35
+ try {
36
+ rmSync(tmp, { force: true });
37
+ }
38
+ catch { /* best effort */ }
39
+ }
40
+ }
@@ -63,11 +63,24 @@ export async function syncDirectory(path) {
63
63
  await file.close();
64
64
  }
65
65
  }
66
- // Readers poll journals (UI, main agent, CLI). Committed bytes never change, so a snapshot is extended by decoding
67
- // only the bytes appended since the last read; a different inode or a shorter file is read from scratch.
68
66
  const snapshots = new Map();
69
67
  /** A1, C11: Read a committed snapshot without repairing or writing its tail. The result is shared and frozen. */
70
68
  export function readJournalSnapshot(path) {
69
+ return (readJournalRecord(path)?.entries ?? []);
70
+ }
71
+ /** Drop a journal's cached entries (a reader that keeps what it derived from them no longer needs them in memory);
72
+ * the next read decodes the file again. */
73
+ export function forgetJournalSnapshot(path) { snapshots.delete(path); }
74
+ /** Drop loaded snapshots selected by a compact reader; work is proportional to loaded journals, not settled history. */
75
+ export function forgetJournalSnapshotsIf(match) {
76
+ for (const path of snapshots.keys())
77
+ if (match(path))
78
+ snapshots.delete(path);
79
+ }
80
+ /** Whether a reader still retains this journal's decoded snapshot (for diagnostics). */
81
+ export function hasJournalSnapshot(path) { return snapshots.has(path); }
82
+ /** readJournalSnapshot with the identity of what was read; undefined when the file does not exist. */
83
+ export function readJournalRecord(path) {
71
84
  let fd;
72
85
  try {
73
86
  fd = openSync(path, 'r');
@@ -75,15 +88,15 @@ export function readJournalSnapshot(path) {
75
88
  catch (error) {
76
89
  if (error.code === 'ENOENT') {
77
90
  snapshots.delete(path);
78
- return [];
91
+ return undefined;
79
92
  }
80
93
  throw error;
81
94
  }
82
95
  try {
83
- const { ino, size } = fstatSync(fd), cached = snapshots.get(path);
84
- if (cached && cached.ino === ino && cached.size === size)
85
- return cached.entries;
86
- const from = cached && cached.ino === ino && size > cached.size ? cached.length : 0;
96
+ const { dev, ino, size } = fstatSync(fd), cached = snapshots.get(path);
97
+ if (cached && cached.dev === dev && cached.ino === ino && cached.size === size)
98
+ return cached;
99
+ const from = cached && cached.dev === dev && cached.ino === ino && size > cached.size ? cached.length : 0;
87
100
  const bytes = Buffer.alloc(size - from);
88
101
  for (let read = 0; read < bytes.length;) {
89
102
  const n = readSync(fd, bytes, read, bytes.length - read, from + read);
@@ -93,13 +106,104 @@ export function readJournalSnapshot(path) {
93
106
  }
94
107
  const decoded = decode(bytes, from ? cached.entries : []);
95
108
  const entries = Object.freeze(decoded.entries);
96
- snapshots.set(path, { ino, size, length: from + decoded.length, entries });
97
- return entries;
109
+ const record = { dev, ino, size, length: from + decoded.length, entries };
110
+ snapshots.set(path, record);
111
+ return record;
112
+ }
113
+ finally {
114
+ closeSync(fd);
115
+ }
116
+ }
117
+ /** A committed snapshot with the file identity it was read at, without keeping it in the shared snapshot cache (a
118
+ * cached snapshot of the same file is reused): for one-off scans over many journals whose entries are not needed
119
+ * again. `undefined` when the file does not exist. */
120
+ export function readJournalUncached(path) {
121
+ let fd;
122
+ try {
123
+ fd = openSync(path, 'r');
124
+ }
125
+ catch (error) {
126
+ if (error.code === 'ENOENT')
127
+ return undefined;
128
+ throw error;
129
+ }
130
+ try {
131
+ const { dev, ino, size } = fstatSync(fd), cached = snapshots.get(path);
132
+ if (cached && cached.dev === dev && cached.ino === ino && cached.size === size)
133
+ return { ino, size, entries: cached.entries };
134
+ const bytes = Buffer.alloc(size);
135
+ for (let read = 0; read < bytes.length;) {
136
+ const n = readSync(fd, bytes, read, bytes.length - read, read);
137
+ if (!n)
138
+ break;
139
+ read += n;
140
+ }
141
+ return { ino, size, entries: decode(bytes).entries };
98
142
  }
99
143
  finally {
100
144
  closeSync(fd);
101
145
  }
102
146
  }
147
+ /** Fold a committed prefix a bounded chunk at a time. Only one record (possibly larger than a chunk) is buffered;
148
+ * newly appended bytes extend the state, and replacement or shrink rebuilds it. Never repairs the journal. */
149
+ export function readJournalFold(path, prior, empty, apply) {
150
+ let fd;
151
+ try {
152
+ fd = openSync(path, 'r');
153
+ }
154
+ catch (error) {
155
+ if (error.code === 'ENOENT')
156
+ return undefined;
157
+ throw error;
158
+ }
159
+ try {
160
+ const { dev, ino, size } = fstatSync(fd);
161
+ if (prior && prior.dev === dev && prior.ino === ino && prior.size === size)
162
+ return prior;
163
+ const kept = prior && prior.dev === dev && prior.ino === ino && size >= prior.size;
164
+ const record = kept ? { ...prior, size } : { dev, ino, size, length: 0, seen: 0, state: empty() };
165
+ let offset = record.length, pending = Buffer.alloc(0);
166
+ const buffer = Buffer.alloc(Math.min(64 * 1024, Math.max(1, size - offset)));
167
+ while (offset < size) {
168
+ const n = readSync(fd, buffer, 0, Math.min(buffer.length, size - offset), offset);
169
+ if (!n)
170
+ throw new Error(`Journal changed during read: ${path}`);
171
+ offset += n;
172
+ const bytes = pending.length ? Buffer.concat([pending, buffer.subarray(0, n)]) : buffer.subarray(0, n);
173
+ let start = 0, end;
174
+ while ((end = bytes.indexOf(10, start)) >= 0) {
175
+ let entry;
176
+ try {
177
+ const json = unframeLine(bytes.subarray(start, end));
178
+ if (json === undefined)
179
+ throw new Error('CRC');
180
+ entry = JSON.parse(json);
181
+ if (entry.seq !== record.seen + 1 || !Number.isFinite(entry.ts) || typeof entry.type !== 'string')
182
+ throw new Error('Envelope');
183
+ }
184
+ catch (cause) {
185
+ if (offset - bytes.length + end !== size - 1)
186
+ throw new Error(`Journal corruption at byte ${record.length}`, { cause });
187
+ return record;
188
+ }
189
+ apply(record.state, entry);
190
+ record.seen++;
191
+ record.length += end + 1 - start;
192
+ start = end + 1;
193
+ }
194
+ pending = Buffer.from(bytes.subarray(start));
195
+ }
196
+ return record;
197
+ }
198
+ finally {
199
+ closeSync(fd);
200
+ }
201
+ }
202
+ /** Find one record without retaining history (request-time lookups that do not belong in a compact polling state). */
203
+ export function findJournalEntry(path, match) {
204
+ return readJournalFold(path, undefined, () => ({}), (state, entry) => { if (!state.found && match(entry))
205
+ state.found = entry; })?.state.found;
206
+ }
103
207
  /** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
104
208
  export const JOURNAL_REST_MS = 1000;
105
209
  let descriptors = 0, appends = 0;