pi-durable-subagents 1.0.39 → 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 +24 -0
- package/README.md +15 -1
- package/dist/agent/main/snapshots.js +63 -74
- package/dist/agent/main.js +17 -16
- package/dist/cli/control.js +1 -1
- package/dist/cli/restart.js +2 -2
- package/dist/kernel/cache.js +40 -0
- package/dist/kernel/journal.js +85 -11
- package/dist/orchestrator/reader-ledger.js +110 -0
- package/dist/orchestrator/snapshot.js +334 -34
- package/dist/orchestrator/store.js +9 -1
- package/dist/paths.js +6 -0
- package/dist/requests.js +2 -2
- package/dist/ui/data.js +150 -44
- package/dist/ui/index.js +14 -5
- package/dist/ui/session.js +18 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
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
|
+
|
|
3
27
|
## 1.0.39
|
|
4
28
|
|
|
5
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
|
package/README.md
CHANGED
|
@@ -584,7 +584,21 @@ an orchestrator runs, a pi session does not look for pending work at all;
|
|
|
584
584
|
without one, it looks until it finds the first unfinished workflow and keeps
|
|
585
585
|
none of the journals it read. `node scripts/bench-ui.ts --owner=main:<pi
|
|
586
586
|
session id>` measures what a session pays on its main thread for a given
|
|
587
|
-
`DSA_HOME` (read-only).
|
|
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.
|
|
588
602
|
|
|
589
603
|
### Where the orchestrator starts
|
|
590
604
|
|
|
@@ -1,56 +1,65 @@
|
|
|
1
|
-
import { closeSync, openSync,
|
|
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, readJournalUncached } from "../../kernel/journal.js";
|
|
5
|
-
import { journalPath
|
|
6
|
-
import { CT, JT
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
export function workflows(home, origin) {
|
|
11
|
-
const
|
|
12
|
-
let
|
|
13
|
-
|
|
14
|
-
|
|
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;
|
|
15
19
|
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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;
|
|
20
57
|
}
|
|
21
|
-
|
|
22
|
-
|
|
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 });
|
|
58
|
+
finally {
|
|
59
|
+
releaseSettledJournals();
|
|
33
60
|
}
|
|
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;
|
|
53
61
|
}
|
|
62
|
+
export { openGeneration };
|
|
54
63
|
/** Whether one journal is unfinished, by file identity: a journal that has not changed is not read again. */
|
|
55
64
|
const decided = new Map();
|
|
56
65
|
function unfinishedJournal(path, known) {
|
|
@@ -82,29 +91,20 @@ function unfinishedJournal(path, known) {
|
|
|
82
91
|
* unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
|
|
83
92
|
* Stops at the first unfinished workflow (newest first); a held workflow the ledger attributes is skipped without
|
|
84
93
|
* reading its journal, and an unchanged journal is not read again. */
|
|
85
|
-
export function unfinishedWorkflow(home) {
|
|
86
|
-
const
|
|
87
|
-
let names;
|
|
88
|
-
try {
|
|
89
|
-
names = readdirSync(join(home, "w"));
|
|
90
|
-
}
|
|
91
|
-
catch (error) {
|
|
92
|
-
if (error.code !== "ENOENT")
|
|
93
|
-
throw error;
|
|
94
|
-
names = [];
|
|
95
|
-
}
|
|
94
|
+
export function unfinishedWorkflow(home, fresh = false) {
|
|
95
|
+
const { record, names } = readerWorkflowListing(home, fresh), ix = record.state, { created, pruned } = ix;
|
|
96
96
|
const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
|
|
97
97
|
for (const wid of ids) {
|
|
98
98
|
const path = journalPath(home, wid);
|
|
99
99
|
// The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
|
|
100
100
|
// a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
|
|
101
101
|
const known = created.get(wid);
|
|
102
|
-
if (known &&
|
|
102
|
+
if (known && readerHold(ix, wid, known.origin))
|
|
103
103
|
continue;
|
|
104
104
|
let read;
|
|
105
105
|
if (!known) {
|
|
106
106
|
read = readJournalUncached(path);
|
|
107
|
-
if (
|
|
107
|
+
if (readerHold(ix, wid, read?.entries.find(e => e.type === JT.created)?.origin))
|
|
108
108
|
continue;
|
|
109
109
|
}
|
|
110
110
|
if (unfinishedJournal(path, read))
|
|
@@ -124,22 +124,11 @@ export function presented(ctx) {
|
|
|
124
124
|
receipts.set(owner, { first: entries[0], last: entries.at(-1), length: entries.length, items });
|
|
125
125
|
return items;
|
|
126
126
|
}
|
|
127
|
-
const open = new WeakMap();
|
|
128
|
-
/** The unresolved attention items of one immutable journal snapshot, computed once per snapshot. */
|
|
129
|
-
function unresolved(entries) {
|
|
130
|
-
let items = open.get(entries);
|
|
131
|
-
if (items)
|
|
132
|
-
return items;
|
|
133
|
-
const done = new Set(entries.filter(e => e.type === JT.attentionResolved).map(e => `${e.id}\0${e.rev}`));
|
|
134
|
-
items = attentionEntries(entries).map(e => e.item).filter(item => !done.has(`${item.id}\0${item.rev}`));
|
|
135
|
-
open.set(entries, items);
|
|
136
|
-
return items;
|
|
137
|
-
}
|
|
138
127
|
/** P15, V7: Select only unresolved, unpresented items owned by this session. */
|
|
139
|
-
export function attention(home, sender, seen) {
|
|
128
|
+
export function attention(home, sender, seen, fresh = false) {
|
|
140
129
|
const items = [], shown = new Set(seen.map(s => `${s.id}\0${s.rev}`));
|
|
141
|
-
for (const workflow of workflows(home, sender)) {
|
|
142
|
-
for (const item of
|
|
130
|
+
for (const workflow of workflows(home, sender, fresh)) {
|
|
131
|
+
for (const item of workflow.settled?.attention ?? unresolvedAttention(workflow.entries)) {
|
|
143
132
|
const key = `${item.id}\0${item.rev}`;
|
|
144
133
|
if (shown.has(key))
|
|
145
134
|
continue; // singlePresentation: one presentation per id/rev
|
package/dist/agent/main.js
CHANGED
|
@@ -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 {
|
|
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,
|
|
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, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView,
|
|
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
|
|
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
|
|
67
|
-
|
|
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() {
|
|
@@ -107,7 +104,7 @@ export function registerMain(pi, ui) {
|
|
|
107
104
|
versionTold = orchestrator;
|
|
108
105
|
ctx.ui.notify(`Durable Subagents: ${versionNote}.`, "warning");
|
|
109
106
|
}
|
|
110
|
-
function collect() { return ctx ? attention(home, sender, [...presented(ctx), ...reserved]) : []; }
|
|
107
|
+
function collect(fresh = false) { return ctx ? attention(home, sender, [...presented(ctx), ...reserved], fresh) : []; }
|
|
111
108
|
function message(items) {
|
|
112
109
|
return { type: "custom_message", customType: CT.attention, content: items.map(presentText).join("\n"), display: true, details: { items } };
|
|
113
110
|
}
|
|
@@ -131,7 +128,8 @@ export function registerMain(pi, ui) {
|
|
|
131
128
|
if (stopped)
|
|
132
129
|
return;
|
|
133
130
|
ctx = context;
|
|
134
|
-
|
|
131
|
+
// Polling can reuse a settled digest; a turn boundary must see attention appended just before it.
|
|
132
|
+
const items = collect(true), entries = [];
|
|
135
133
|
if (items.length) {
|
|
136
134
|
entries.push(message(items));
|
|
137
135
|
reserved.push(...items);
|
|
@@ -250,7 +248,10 @@ export function registerMain(pi, ui) {
|
|
|
250
248
|
return args;
|
|
251
249
|
}
|
|
252
250
|
/** "<rid>" or "<rid>/<key>" of a created run → the same address with its wid; anything else is unchanged. */
|
|
253
|
-
function ridToWid(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
|
+
}
|
|
254
255
|
/** A run request without a workflow yet (still pending, or rejected), asked about by its rid. */
|
|
255
256
|
function pendingRun(rid) {
|
|
256
257
|
const decision = decisions().get(rid);
|
|
@@ -394,7 +395,7 @@ export function registerMain(pi, ui) {
|
|
|
394
395
|
return outbox.send("orch", normalized.kind, normalized.body, normalized.cond);
|
|
395
396
|
});
|
|
396
397
|
if ("conflict" in outcome) {
|
|
397
|
-
const created = ledger().
|
|
398
|
+
const created = ledger().createdRids.get(rid);
|
|
398
399
|
return { applied: false, reason: "request-conflict", request: args.request, spec_digest: outcome.digest, ...(created ? { wid: created.wid } : {}),
|
|
399
400
|
note: "this request id was used for different content; use a new id" };
|
|
400
401
|
}
|
|
@@ -402,7 +403,7 @@ export function registerMain(pi, ui) {
|
|
|
402
403
|
// P25: run waits for `created`; control requests wait for their terminal lifecycle record (applied or rejected+reason).
|
|
403
404
|
const deadline = performance.now() + 10_000;
|
|
404
405
|
while (wait || sent.kind === "run") {
|
|
405
|
-
const receipt = sent.kind === "run" ? ledger().
|
|
406
|
+
const receipt = sent.kind === "run" ? ledger().createdRids.get(sent.rid) : undefined;
|
|
406
407
|
const decision = receipt ? undefined : decisions().get(sent.rid);
|
|
407
408
|
if (receipt || decision) {
|
|
408
409
|
await serial(async () => { await outbox?.markResolved(sent.rid); });
|
|
@@ -415,7 +416,7 @@ export function registerMain(pi, ui) {
|
|
|
415
416
|
if (decision.type === "rejected")
|
|
416
417
|
return { applied: false, reason: sent.kind === "resume" && args.wid === undefined ? resumeElsewhere(String(decision.reason)) : decision.reason, rid: sent.rid };
|
|
417
418
|
if (sent.kind !== "run") {
|
|
418
|
-
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) };
|
|
419
420
|
}
|
|
420
421
|
}
|
|
421
422
|
if (performance.now() >= deadline || signal?.aborted)
|
package/dist/cli/control.js
CHANGED
|
@@ -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. */
|
package/dist/cli/restart.js
CHANGED
|
@@ -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 {
|
|
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 =
|
|
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
|
+
}
|
package/dist/kernel/journal.js
CHANGED
|
@@ -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
|
|
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,8 +106,9 @@ export function readJournalSnapshot(path) {
|
|
|
93
106
|
}
|
|
94
107
|
const decoded = decode(bytes, from ? cached.entries : []);
|
|
95
108
|
const entries = Object.freeze(decoded.entries);
|
|
96
|
-
|
|
97
|
-
|
|
109
|
+
const record = { dev, ino, size, length: from + decoded.length, entries };
|
|
110
|
+
snapshots.set(path, record);
|
|
111
|
+
return record;
|
|
98
112
|
}
|
|
99
113
|
finally {
|
|
100
114
|
closeSync(fd);
|
|
@@ -114,8 +128,8 @@ export function readJournalUncached(path) {
|
|
|
114
128
|
throw error;
|
|
115
129
|
}
|
|
116
130
|
try {
|
|
117
|
-
const { ino, size } = fstatSync(fd), cached = snapshots.get(path);
|
|
118
|
-
if (cached && cached.ino === ino && cached.size === size)
|
|
131
|
+
const { dev, ino, size } = fstatSync(fd), cached = snapshots.get(path);
|
|
132
|
+
if (cached && cached.dev === dev && cached.ino === ino && cached.size === size)
|
|
119
133
|
return { ino, size, entries: cached.entries };
|
|
120
134
|
const bytes = Buffer.alloc(size);
|
|
121
135
|
for (let read = 0; read < bytes.length;) {
|
|
@@ -130,6 +144,66 @@ export function readJournalUncached(path) {
|
|
|
130
144
|
closeSync(fd);
|
|
131
145
|
}
|
|
132
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
|
+
}
|
|
133
207
|
/** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
|
|
134
208
|
export const JOURNAL_REST_MS = 1000;
|
|
135
209
|
let descriptors = 0, appends = 0;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Pi-side ledger state: only projections used by readers, never decoded ledger history or run bodies.
|
|
2
|
+
import { forgetJournalSnapshot, readJournalFold } from "../kernel/journal.js";
|
|
3
|
+
import { orchLedger } from "../paths.js";
|
|
4
|
+
import { JT } from "../types.js";
|
|
5
|
+
import { applyLedger, emptyLedger } from "./ledger.js";
|
|
6
|
+
import { labelsOf } from "../events/derive.js";
|
|
7
|
+
export function emptyReaderLedger() {
|
|
8
|
+
return { created: new Map(), origins: new Map(), intents: new Map(), revisions: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(),
|
|
9
|
+
byWid: new Map(), byOrigin: new Map(), state: emptyLedger(), createdRids: new Map(), decisions: new Map(), resolutions: new Map(), sendNotes: new Map() };
|
|
10
|
+
}
|
|
11
|
+
export function applyReaderLedger(ix, e) {
|
|
12
|
+
if (e.type === JT.created) {
|
|
13
|
+
if (!ix.created.has(e.wid))
|
|
14
|
+
ix.created.set(e.wid, { seq: e.seq, ts: e.ts, wid: e.wid, rid: e.rid, origin: e.origin });
|
|
15
|
+
ix.origins.set(String(e.wid), e.origin);
|
|
16
|
+
if (!ix.createdRids.has(e.rid))
|
|
17
|
+
ix.createdRids.set(e.rid, { wid: e.wid });
|
|
18
|
+
const labels = ix.runLabels.get(String(e.rid)), session = ix.runSessions.get(String(e.rid));
|
|
19
|
+
if (labels) {
|
|
20
|
+
if (!ix.labels.has(String(e.wid)))
|
|
21
|
+
ix.labels.set(String(e.wid), labels);
|
|
22
|
+
ix.runLabels.delete(String(e.rid));
|
|
23
|
+
}
|
|
24
|
+
if (session) {
|
|
25
|
+
if (!ix.sessions.has(String(e.wid)))
|
|
26
|
+
ix.sessions.set(String(e.wid), session);
|
|
27
|
+
ix.runSessions.delete(String(e.rid));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
else if (e.type === "create-intent") {
|
|
31
|
+
if (!ix.intents.has(String(e.wid)))
|
|
32
|
+
ix.intents.set(String(e.wid), e.origin);
|
|
33
|
+
}
|
|
34
|
+
else if (e.type === "revise-intent") {
|
|
35
|
+
const revision = Number(e.revision), wid = String(e.wid);
|
|
36
|
+
if (Number.isFinite(revision))
|
|
37
|
+
ix.revisions.set(wid, Math.max(revision, ix.revisions.get(wid) ?? 0));
|
|
38
|
+
}
|
|
39
|
+
else if (e.type === "request") {
|
|
40
|
+
const r = e.request;
|
|
41
|
+
const labels = r?.kind === "run" ? labelsOf(r.body) : undefined;
|
|
42
|
+
if (labels && typeof r?.rid === "string")
|
|
43
|
+
ix.runLabels.set(r.rid, labels);
|
|
44
|
+
const session = r?.kind === "run" ? r.body?.session : undefined;
|
|
45
|
+
if (typeof session === "string" && session && typeof r?.rid === "string")
|
|
46
|
+
ix.runSessions.set(r.rid, session);
|
|
47
|
+
}
|
|
48
|
+
else if (e.type === "pruned") {
|
|
49
|
+
ix.pruned.add(String(e.wid));
|
|
50
|
+
ix.labels.delete(String(e.wid));
|
|
51
|
+
ix.sessions.delete(String(e.wid));
|
|
52
|
+
}
|
|
53
|
+
else if (e.type === "drain" || e.type === "undrain") {
|
|
54
|
+
const drain = { seq: e.seq, ts: e.ts, type: e.type };
|
|
55
|
+
if (e.type === "drain")
|
|
56
|
+
ix.lastDrain = drain;
|
|
57
|
+
if (e.wid === undefined && e.origin === undefined)
|
|
58
|
+
ix.global = drain;
|
|
59
|
+
if (e.wid !== undefined)
|
|
60
|
+
ix.byWid.set(e.wid, drain);
|
|
61
|
+
if (e.origin !== undefined)
|
|
62
|
+
ix.byOrigin.set(e.origin, drain);
|
|
63
|
+
}
|
|
64
|
+
if (e.type === JT.rejected) {
|
|
65
|
+
ix.runLabels.delete(String(e.rid));
|
|
66
|
+
ix.runSessions.delete(String(e.rid));
|
|
67
|
+
}
|
|
68
|
+
if (e.type === JT.applied || e.type === JT.rejected) {
|
|
69
|
+
const resolution = { type: e.type, ...(e.type === JT.rejected ? { reason: String(e.reason) } : {}) };
|
|
70
|
+
if (!ix.resolutions.has(e.rid))
|
|
71
|
+
ix.resolutions.set(e.rid, { seq: e.seq, ...resolution });
|
|
72
|
+
if (!(e.type === JT.rejected && e.reason === "identity-conflict") && !ix.decisions.has(e.rid))
|
|
73
|
+
ix.decisions.set(e.rid, resolution);
|
|
74
|
+
}
|
|
75
|
+
if (e.type === "send-note")
|
|
76
|
+
ix.sendNotes.set(e.rid, { seq: e.seq, ts: e.ts, type: e.type, rid: e.rid, model: e.model, effect: e.effect, pool: e.pool, delivery: e.delivery });
|
|
77
|
+
// applyLedger is shared with the orchestrator; reader projections discard execution-only switch history/skips.
|
|
78
|
+
// A holder needs only pool/slot/exec, not any extra payload the entry might carry.
|
|
79
|
+
if (e.type === "hold")
|
|
80
|
+
applyLedger(ix.state, { seq: e.seq, ts: e.ts, type: e.type, pool: e.pool, slot: e.slot, exec: e.exec });
|
|
81
|
+
else if (e.type !== "switch-observed" && e.type !== "skip" && e.type !== "writer-hold" && e.type !== "writer-release")
|
|
82
|
+
applyLedger(ix.state, e);
|
|
83
|
+
ix.state.seen++;
|
|
84
|
+
}
|
|
85
|
+
export function readerHold(ix, wid, origin) {
|
|
86
|
+
const candidates = [ix.global, ix.byWid.get(wid), origin !== undefined ? ix.byOrigin.get(origin) : undefined];
|
|
87
|
+
const last = candidates.reduce((a, b) => b && (!a || b.seq > a.seq) ? b : a, undefined);
|
|
88
|
+
const created = ix.created.get(wid);
|
|
89
|
+
return last?.type === "drain" && (!created || created.seq < last.seq) ? last : undefined;
|
|
90
|
+
}
|
|
91
|
+
const readers = new Map();
|
|
92
|
+
export function readerLedger(home) {
|
|
93
|
+
const path = orchLedger(home);
|
|
94
|
+
// Drop any raw snapshot loaded by another read path in this process. This reader never creates one itself.
|
|
95
|
+
forgetJournalSnapshot(path);
|
|
96
|
+
try {
|
|
97
|
+
const record = readJournalFold(path, readers.get(path), emptyReaderLedger, applyReaderLedger);
|
|
98
|
+
if (record) {
|
|
99
|
+
readers.set(path, record);
|
|
100
|
+
return record;
|
|
101
|
+
}
|
|
102
|
+
readers.delete(path);
|
|
103
|
+
return { dev: 0, ino: 0, size: 0, length: 0, seen: 0, state: emptyReaderLedger() };
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
readers.delete(path);
|
|
107
|
+
throw error;
|
|
108
|
+
} // a partial fold is never retried as an accepted prefix
|
|
109
|
+
}
|
|
110
|
+
export const readerLedgerIdentity = (record) => `${record.dev}:${record.ino}:${record.size}`;
|