pi-durable-subagents 1.0.41 → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,134 @@
1
+ // Settled workflows: a rebuildable cache (DSA_HOME/cache/settled/<wid>.json, never authority) that lets a start open
2
+ // the journal of a finished workflow without decoding it. The record is valid only for the journal bytes it names
3
+ // (inode, size, entry count and last line, see JournalExpectation); anything else opens the journal as before.
4
+ // It holds exactly what a start and the orchestrator's loops over every workflow read of such a workflow; every other
5
+ // use decodes the journal first (a lazy handle decodes on its first entries() or append), so code that does not know
6
+ // about it stays correct.
7
+ import { join } from "node:path";
8
+ import { rmSync } from "node:fs";
9
+ import { readCache, writeCache } from "../kernel/cache.js";
10
+ import { journalExpectation } from "../kernel/journal.js";
11
+ import { cacheDir, journalPath } from "../paths.js";
12
+ import { JT, isEntry } from "../types.js";
13
+ import { quiet } from "../events/pump.js";
14
+ import { foldWaits, liveWaitCalls } from "../events/waiting.js";
15
+ import { pendingFollowUps } from "./notes.js";
16
+ import { revisionEntries, terminalEntry } from "./store.js";
17
+ import { RECOVERY_VERSION } from "./executor/recovered.js";
18
+ import { sweepSeed } from "./executor/sweep.js";
19
+ import { callEntries } from "./executor/indexes.js";
20
+ /** Bump whenever the record gains a field or settledFacts a condition: every record is then rebuilt once. */
21
+ export const SETTLED_VERSION = 2;
22
+ export const settledPath = (home, wid) => join(cacheDir(home), "settled", `${wid}.json`);
23
+ /** Why a workflow is not settled, or its facts. Settled: it ended (its current revision is terminal) and nothing a start
24
+ * or a later request would act on is left: every call with an execution is fenced, ended and recovered (`recovered`:
25
+ * its receipt is current and it holds no writer lock), no follow-up is open or pending, every forward is retired or delivered, no
26
+ * worktree cleanup or reminder, gate, writer wait or fence failure is open, its finished attention is recorded (for the workflow
27
+ * and each generation), and no call is live for the waiting tracker. */
28
+ export function settledFacts(wf, recovered) {
29
+ const log = wf.journal.entries(), rev = revisionEntries(wf), done = terminalEntry(rev);
30
+ if (!done)
31
+ return "running";
32
+ const has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
33
+ const sealedCalls = new Set(log.filter(e => e.type === JT.sealed).map(e => String(e.call)));
34
+ const ended = new Set([...sealedCalls, ...log.filter(e => e.type === "retired").map(e => String(e.call))]);
35
+ const fenced = new Set(log.filter(e => e.type === JT.fenced).map(e => String(e.exec)));
36
+ const calls = new Set();
37
+ for (const e of log)
38
+ if (e.type === JT.exec) {
39
+ const call = String(e.call);
40
+ calls.add(call);
41
+ if (!fenced.has(String(e.exec)))
42
+ return `unfenced:${String(e.exec)}`;
43
+ }
44
+ for (const call of calls) {
45
+ if (!ended.has(call))
46
+ return `live:${call}`;
47
+ if (!recovered(call))
48
+ return `unrecovered:${call}`;
49
+ }
50
+ // Follow-ups: every generation of the current revision ended, its finished attention recorded; none pending.
51
+ const attention = new Set(log.filter(e => isEntry(e, JT.attention)).map(e => `${e.item.id}\0${e.item.rev}`));
52
+ const items = new Set(log.filter(e => isEntry(e, JT.attention)).map(e => String(e.item.id)));
53
+ const finished = (id) => items.has(id);
54
+ for (const e of rev)
55
+ if (e.type === "generation") {
56
+ const id = `${wf.wid}@${wf.revision}/${e.key}@${e.gen}`;
57
+ if (!ended.has(id))
58
+ return `open-generation:${id}`;
59
+ if (sealedCalls.has(id) && !finished(`finished:${id}`))
60
+ return `unfinished-generation:${id}`;
61
+ }
62
+ if (rev.some(e => e.type === "forward-retired" && e.reason === "undelivered-follow-up"))
63
+ for (const key of new Set(rev.filter(e => e.type === "call" || e.type === "generation").map(e => String(e.key))))
64
+ if (pendingFollowUps(rev, key).length)
65
+ return `pending-follow-up:${key}`;
66
+ // A forward is settled when it was retired or its call received it (a replay then only republishes an envelope the
67
+ // outbox still has pending, which the start's republication does for every envelope anyway).
68
+ const settledForwards = new Set(log.filter(e => e.type === "forward-retired" || e.type === "forward-delivered").map(e => String(e.rid2)));
69
+ for (const e of log)
70
+ if (e.type === "forward" && !settledForwards.has(String(e.rid2)))
71
+ return `open-forward:${String(e.rid2)}`;
72
+ // Worktrees: a successful call's cleanup recorded; no open reminder.
73
+ for (const call of sealedCalls) {
74
+ const own = callEntries(wf.journal, call);
75
+ const result = own.find(e => e.type === JT.sealed)?.result;
76
+ if (result?.status === "ok" && own.some(e => e.type === "wt-intent") && !own.some(e => e.type === "wt-removed" || e.type === "wt-kept"))
77
+ return `worktree:${call}`;
78
+ }
79
+ const resolved = new Set(log.filter(e => e.type === JT.attentionResolved).map(e => `${String(e.id)}\0${String(e.rev)}`));
80
+ for (const e of log)
81
+ if (isEntry(e, JT.attention) && e.item.kind === "conflict" && String(e.item.id).startsWith("worktree:") && !resolved.has(`${e.item.id}\0${e.item.rev}`))
82
+ return `reminder:${e.item.id}`;
83
+ for (const e of log)
84
+ if (e.type === "gate-intent" && !has("gate", "id", e.id))
85
+ return `gate:${String(e.id)}`;
86
+ // A writer wait not followed by its acquisition or its call's end: recovery restores it.
87
+ for (const e of log)
88
+ if (e.type === "writer-wait" && !log.some(r => r.seq > e.seq && r.call === e.call && (r.type === "writer-acquired" || r.type === JT.sealed || r.type === "retired")))
89
+ return `writer-wait:${String(e.call)}`;
90
+ if (log.some(e => e.type === "fence-failed" && !log.some(r => r.seq > e.seq && ((r.type === JT.fenced && r.exec === e.exec) || (r.type === "gate" && r.id === e.exec) ||
91
+ (r.type === JT.attentionResolved && r.id === `fence:${String(e.exec)}`)))))
92
+ return "fence-failed";
93
+ // The workflow's own finished attention (Engine.attention) is recorded for its latest end.
94
+ if (!attention.has(`finished:${wf.wid}\0${log.filter(e => e.type === JT.done).length}`))
95
+ return "finished-attention";
96
+ if (liveWaitCalls(foldWaits(wf.wid, log)).length)
97
+ return "waits";
98
+ const revised = log.findLast(e => e.type === "revised");
99
+ return { revision: wf.revision, ...(revised ? { revised } : {}), done: { seq: done.seq, ts: done.ts, type: done.type, status: done.status }, resumed: log.filter(e => e.type === "resumed" && e.rid !== undefined).map(e => String(e.rid)),
100
+ quiet: quiet(wf.wid, log), calls: calls.size, sweep: sweepSeed(wf.journal) };
101
+ }
102
+ /** The settled record of `wid` when it is of this version and was written for the same workflow; not yet checked
103
+ * against the journal (openLazyJournal does). */
104
+ export function readSettled(home, wid) {
105
+ const record = readCache(settledPath(home, wid));
106
+ if (!record || record.v !== SETTLED_VERSION || record.recovery !== RECOVERY_VERSION || record.wid !== wid)
107
+ return undefined;
108
+ if (!record.journal || typeof record.journal.size !== "number" || !record.done || typeof record.revision !== "number" || !Array.isArray(record.sweep) || !Array.isArray(record.resumed))
109
+ return undefined;
110
+ for (const s of record.sweep)
111
+ if (typeof s?.exec !== "string" || typeof s.call !== "string" || !Array.isArray(s.tracked) || s.tracked.some(id => typeof id !== "string" || !/^\d+ /.test(id)))
112
+ return undefined;
113
+ return record;
114
+ }
115
+ /** Write the record of a settled workflow from its decoded journal (best effort: a failure only costs a decode at the
116
+ * next start). Returns whether it was written; a workflow that is not settled has its record removed. */
117
+ export function writeSettled(home, wf, recovered) {
118
+ const path = settledPath(home, wf.wid), facts = settledFacts(wf, recovered);
119
+ const journal = typeof facts === "string" ? undefined : journalExpectation(wf.journal);
120
+ if (typeof facts === "string" || !journal) {
121
+ try {
122
+ rmSync(path, { force: true });
123
+ }
124
+ catch { /* a cache */ }
125
+ return false;
126
+ }
127
+ const record = { v: SETTLED_VERSION, recovery: RECOVERY_VERSION, wid: wf.wid, journal, ...facts };
128
+ writeCache(path, record, journalPath(home, wf.wid));
129
+ return true;
130
+ }
131
+ /** Whether a workflow's journal is open lazily and not decoded yet: its settled record still describes it. */
132
+ export function lazy(wf) {
133
+ return wf.journal.loaded === false && wf.settled !== undefined;
134
+ }
@@ -8,7 +8,7 @@ import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends,
8
8
  import { readCache, writeCache } from "../kernel/cache.js";
9
9
  import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
10
10
  import { JT, attentionEntries, isEntry } from "../types.js";
11
- import { resolveModel } from "../compat/model.js";
11
+ import { parseModel, resolveModel } from "../compat/model.js";
12
12
  import {} from "./ledger.js";
13
13
  import { readerHold, readerLedger, readerLedgerIdentity } from "./reader-ledger.js";
14
14
  import { packageVersion } from "../version.js";
@@ -433,7 +433,7 @@ const folds = new Map();
433
433
  const derived = new WeakMap();
434
434
  export function workflowSnapshot(home, wid, ledger) {
435
435
  const base = workflowDigest(home, wid, ledger).snapshot;
436
- const wf = base.calls.some(c => c.poolWait) ? withPoolSlots(base, readerLedger(home).state.state) : base;
436
+ const wf = base.calls.some(c => c.poolWait || c.phase === "queued") ? withLedgerFacts(base, readerLedger(home).state.state) : base;
437
437
  const planned = plannedTotal(home, wid, wf.rev);
438
438
  return planned === undefined ? wf : { ...wf, planned };
439
439
  }
@@ -856,15 +856,91 @@ export function labelsText(labels, width = 60) {
856
856
  return text ? `[${clip(text, Math.max(1, width - 3))}]` : "";
857
857
  }
858
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))
859
+ /** The orchestrator that is still recovering the home's workflows: its start entry says it recovers first, it has not
860
+ * recorded `recovered` and its process lives. Undefined for an orchestrator that does not say so (older versions). */
861
+ export function orchestratorStarting(state) {
862
+ const o = state.orchestrator;
863
+ if (!o?.recovery || o.recovered || o.exited)
864
+ return undefined;
865
+ // Readers ask on every refresh; the process check is kept for a second per start entry.
866
+ const now = Date.now(), hit = startingChecks.get(o);
867
+ const alive = hit && now >= hit.at && now - hit.at < 1000 ? hit.alive : processAlive(o.pid, o.start);
868
+ if (!hit || hit.alive !== alive || now < hit.at || now - hit.at >= 1000)
869
+ startingChecks.set(o, { at: now, alive });
870
+ return alive ? { pid: o.pid, since: o.ts } : undefined;
871
+ }
872
+ const startingChecks = new WeakMap();
873
+ /** A queued call's wait as one phrase: "orchestrator starting (12s)", "waiting for a free slot (p 2/2)", ... */
874
+ export function queuedText(w, now = Date.now(), span = age) {
875
+ return w.reason === "starting" ? `orchestrator starting (${span(now - (w.since ?? now))})` : w.detail;
876
+ }
877
+ const providerOf = (model) => { try {
878
+ return parseModel(model).provider;
879
+ }
880
+ catch {
881
+ return undefined;
882
+ } };
883
+ /** Why a queued call waits, from what the orchestrator ledger records (precedence as events/waiting.ts): the
884
+ * orchestrator still recovering; every candidate provider used up and not admitted now; the writer lock of its worktree;
885
+ * every candidate provider full. Undefined when none is known: a call is never said to wait for a slot without a full
886
+ * provider (memory headroom and an admission in progress look the same from here). Candidates: the provider it waits
887
+ * for to resume on, else those of the model or pool it asked for (else the configured default). */
888
+ export function queueWait(c, state, now = Date.now(), starting = orchestratorStarting(state)) {
889
+ if (c.phase !== "queued")
890
+ return undefined;
891
+ if (starting)
892
+ return { reason: "starting", detail: "orchestrator starting", since: starting.since };
893
+ const settings = state.config?.settings ?? {}, pools = settings.pools ?? {}, wanted = c.poolWait?.model ?? c.model ?? settings.defaultModel;
894
+ let providers = [];
895
+ if (wanted && Object.hasOwn(pools, wanted)) {
896
+ try {
897
+ providers = [...new Set(resolveModel(wanted, pools).map(m => m.provider).filter((p) => !!p))];
898
+ }
899
+ catch { /* an invalid pool: unknown */ }
900
+ }
901
+ else if (wanted) {
902
+ const p = providerOf(wanted);
903
+ if (p)
904
+ providers = [p];
905
+ }
906
+ const used = providers.map(p => [p, state.exhausted.get(p)]);
907
+ if (used.length && used.every(([, x]) => x && (now < x.nextTry || x.probe !== undefined)))
908
+ return { reason: "provider-exhausted", detail: `${providers.join(", ")} usage window${providers.length > 1 ? "s" : ""} used up` };
909
+ if (c.writerWait)
910
+ return { reason: "writer-lock", detail: `waiting for the writer lock of ${c.writerWait.root}` };
911
+ if (!providers.length)
912
+ return undefined;
913
+ let full = true;
914
+ const lines = providers.map(p => {
915
+ let held = 0;
916
+ for (const h of state.held.values())
917
+ if (h.pool === p)
918
+ held++;
919
+ const limit = settings.providers?.[p]?.slots;
920
+ if (limit === undefined || held < limit)
921
+ full = false;
922
+ return slotLine(p, held, limit);
923
+ });
924
+ return full ? { reason: "slot", detail: `waiting for a free slot (${lines.join(", ")})` } : undefined;
925
+ }
926
+ /** A mark of the ledger facts a workflow's queued calls show: they are derived again when it changes. */
927
+ function queueMark(wf, state, mark) {
928
+ if (!wf.calls.some(c => c.poolWait || c.phase === "queued"))
929
+ return undefined;
930
+ return `${mark}:${[...state.exhausted.values()].map(x => x.nextTry > Date.now()).join(",")}:${orchestratorStarting(state)?.since ?? ""}`;
931
+ }
932
+ /** Free slots and why queued calls wait are live ledger state, not repeated workflow journal records. */
933
+ function withLedgerFacts(wf, state) {
934
+ if (!wf.calls.some(c => c.poolWait || c.phase === "queued"))
862
935
  return wf;
863
- const held = new Map();
936
+ const held = new Map(), now = Date.now(), starting = orchestratorStarting(state);
864
937
  for (const h of state.held.values())
865
938
  held.set(h.pool, (held.get(h.pool) ?? 0) + 1);
866
939
  const pools = state.config?.settings.pools, limits = state.config?.settings.providers;
867
940
  return { ...wf, calls: wf.calls.map(c => {
941
+ const why = queueWait(c, state, now, starting);
942
+ if (why)
943
+ c = { ...c, queuedFor: why };
868
944
  const wait = c.poolWait;
869
945
  if (!wait)
870
946
  return c;
@@ -892,10 +968,10 @@ function snapshotWithLedger(home, wid, ix, mark) {
892
968
  const pendingRevision = (ix.revisions.get(wid) ?? 0) > (digests.get(pathsOf(home, wid).journal)?.digest.snapshot.rev ?? 0);
893
969
  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
970
  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;
971
+ const slotMark = queueMark(base, ix.state, mark);
896
972
  if (hit && hit.planned === planned && hit.labels === l && hit.session === s && hit.paused === paused && hit.slotMark === slotMark)
897
973
  return hit.wf;
898
- const live = withPoolSlots(base, ix.state);
974
+ const live = withLedgerFacts(base, ix.state);
899
975
  const planned1 = planned === undefined ? live : { ...live, planned }, labelled1 = labelled(planned1, l, s);
900
976
  const wf = paused ? { ...labelled1, paused: true } : labelled1;
901
977
  decorated.set(base, { planned, labels: l, session: s, paused, slotMark, wf });
@@ -1014,7 +1090,7 @@ export function compactWorkflow(wf, leases) {
1014
1090
  ...(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 } : {}),
1015
1091
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
1016
1092
  ...(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) } : {}),
1017
- ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
1093
+ ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(c.queuedFor && !r && !wf.paused ? { queued: queuedText(c.queuedFor) } : {}) };
1018
1094
  }),
1019
1095
  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 } : {}) })),
1020
1096
  ...(wf.paused ? { paused: true } : {}), ...(wf.followUps ? { followUps: wf.followUps } : {}), ...(wf.labels ? { labels: wf.labels } : {}),
@@ -1078,7 +1154,9 @@ export function orchestratorView(state, loaded = packageVersion(), now = Date.no
1078
1154
  return {};
1079
1155
  const r = o.forceRestart, note = r && now - r.ts < 24 * 60 * 60_000
1080
1156
  ? `; restarted by force ${age(now - r.ts)} ago by ${initiatorSummary(r.initiator, r.from)}: ${restartLine(r.reason ?? "no reason recorded")}` : "";
1081
- return { orchestrator: `${o.version} (pid ${o.pid})${note}`, ...(o.version === loaded ? {} : { versionNote: versionNote(o.version, loaded) }) };
1157
+ // Still recovering the home's workflows: nothing is dispatched yet, whatever the slots say.
1158
+ const starting = orchestratorStarting(state), phase = starting ? `, starting ${age(now - starting.since)}` : "";
1159
+ return { orchestrator: `${o.version} (pid ${o.pid}${phase})${note}`, ...(o.version === loaded ? {} : { versionNote: versionNote(o.version, loaded) }) };
1082
1160
  }
1083
1161
  /** Whether the recorded orchestrator still runs. On Linux its start time also tells it from a later process given the
1084
1162
  * same pid after a crash (elsewhere the pid alone is checked). */
@@ -1204,7 +1282,7 @@ export function statusBrief(home, options = {}) {
1204
1282
  ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1205
1283
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
1206
1284
  ...(live && c.switching ? { switching: c.switching } : {}), ...(live && c.switchFailed ? { switchFailed: c.switchFailed } : {}),
1207
- ...(c.notesPending ? { notesPending: c.notesPending } : {}) };
1285
+ ...(c.notesPending ? { notesPending: c.notesPending } : {}), ...(live && c.queuedFor && !w.paused ? { queued: queuedText(c.queuedFor, now) } : {}) };
1208
1286
  });
1209
1287
  const asking = open.filter(a => a.kind === "question" && a.call).map(a => ({ to: `${w.wid}/${callKey(a.call)}`, ...(a.qid ? { qid: a.qid } : {}),
1210
1288
  ...(w.calls.some(c => c.callId === a.call && c.hibernated) ? { hibernated: true } : {}), question: clip(a.text, 300) }));
@@ -13,7 +13,8 @@ import { discoverAgents } from "../compat/agents.js";
13
13
  import { parseFrontmatter } from "../compat/frontmatter.js";
14
14
  import { compileFanout } from "../compat/fanout.js";
15
15
  import { contentHash, ulid } from "../kernel/ids.js";
16
- import { openJournal, syncDirectory } from "../kernel/journal.js";
16
+ import { openJournal, openLazyJournal, syncDirectory } from "../kernel/journal.js";
17
+ import { readSettled, settledPath } from "./settled.js";
17
18
  import { publishFile } from "../kernel/mailbox.js";
18
19
  import { digestDir, factsDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
19
20
  import { JT } from "../types.js";
@@ -185,7 +186,40 @@ export class Store {
185
186
  /** Called after each append to a workflow journal (the event pump derives from it). */
186
187
  appended;
187
188
  ledgers;
189
+ /** Terminal workflows materialized from their `pins.json` without verifying it: the revision and the intent to verify
190
+ * it with (see ready). */
191
+ unverified = new Map();
192
+ verifying = new Map();
193
+ /** What the store looks up in the orchestrator ledger, folded over appended entries only (first entry wins, as find). */
194
+ ix = { seen: 0, pruned: new Set(), created: new Set(), createIntents: [], createByRid: new Map(),
195
+ createByWid: new Map(), reviseByRid: new Map(), rids: new Map() };
188
196
  constructor(ledgers) { this.ledgers = ledgers; }
197
+ index() {
198
+ const ix = this.ix, entries = this.ledgers.orch.committed?.() ?? this.ledgers.orch.entries();
199
+ while (ix.seen < entries.length) {
200
+ const e = entries[ix.seen++];
201
+ if (e.type === 'pruned')
202
+ ix.pruned.add(String(e.wid));
203
+ else if (e.type === JT.created)
204
+ ix.created.add(String(e.rid));
205
+ else if (e.type === 'create-intent' || e.type === 'revise-intent') {
206
+ const byRid = e.type === 'create-intent' ? ix.createByRid : ix.reviseByRid, rid = String(e.rid), wid = String(e.wid);
207
+ if (e.type === 'create-intent') {
208
+ ix.createIntents.push(e);
209
+ if (!ix.createByWid.has(wid))
210
+ ix.createByWid.set(wid, e);
211
+ }
212
+ if (!byRid.has(rid))
213
+ byRid.set(rid, e);
214
+ const rids = ix.rids.get(wid);
215
+ if (rids)
216
+ rids.push(rid);
217
+ else
218
+ ix.rids.set(wid, [rid]);
219
+ }
220
+ }
221
+ return ix;
222
+ }
189
223
  stagePath(rid) {
190
224
  if (!rid || rid === '.' || rid === '..')
191
225
  throw new Error('Invalid staging identity');
@@ -215,6 +249,7 @@ export class Store {
215
249
  const change = req.body, wf = this.workflows.get(change?.wid);
216
250
  if (!wf)
217
251
  throw new Error('unknown-workflow');
252
+ await this.ready(wf);
218
253
  body = { cwd: wf.cwd, ...(change.workflow !== undefined ? { workflow: change.workflow } : { source: change.source ?? wf.pins.source }),
219
254
  args: Object.hasOwn(change, 'args') ? change.args : wf.pins.args, inputs: wf.pins.inputSources,
220
255
  usageBudget: wf.pins.usageBudget, maxCalls: wf.pins.maxCalls };
@@ -295,7 +330,8 @@ export class Store {
295
330
  }
296
331
  /** P3, P6: Remove staging only after a durable rejection or withdrawal without a committed intent. */
297
332
  async discardStage(rid) {
298
- if (this.ledgers.orch.entries().some(e => (e.type === 'create-intent' || e.type === 'revise-intent') && e.rid === rid))
333
+ const ix = this.index();
334
+ if (ix.createByRid.has(rid) || ix.reviseByRid.has(rid))
299
335
  return;
300
336
  await rm(this.stagePath(rid), { recursive: true, force: true });
301
337
  await syncDirectory(join(this.ledgers.home, 'staging')).catch(error => { if (error.code !== 'ENOENT')
@@ -303,14 +339,14 @@ export class Store {
303
339
  }
304
340
  /** A5: Fix the workflow identity and snapshot reference before filesystem effects. */
305
341
  async create(req) {
306
- let intent = this.ledgers.orch.entries().find(e => e.type === 'create-intent' && e.rid === req.rid);
342
+ let intent = this.index().createByRid.get(req.rid);
307
343
  intent ??= await this.ledgers.orch.append('create-intent', { rid: req.rid, wid: ulid(), origin: req.from, cwd: req.body.cwd,
308
344
  ...(req.body.name !== undefined ? { name: req.body.name } : {}), snapshot: await this.reference(req.rid) });
309
345
  return this.materialize(intent);
310
346
  }
311
347
  /** P14, A5: Bind the next revision before retiring any old authority. */
312
348
  async revisionIntent(req, wf) {
313
- return this.ledgers.orch.entries().find(e => e.type === 'revise-intent' && e.rid === req.rid) ??
349
+ return this.index().reviseByRid.get(req.rid) ??
314
350
  await this.ledgers.orch.append('revise-intent', { rid: req.rid, wid: wf.wid, revision: wf.revision + 1, snapshot: await this.reference(req.rid) });
315
351
  }
316
352
  async publishPins(wid, revision, pins) {
@@ -344,11 +380,11 @@ export class Store {
344
380
  * workflow), and use it only when it is well formed, names this snapshot, its pins hash to its digest and every file
345
381
  * hashes as recorded — otherwise they take the snapshot path, whose byte comparison reports a changed file as a
346
382
  * conflict, and record it again. */
347
- async pinnedFiles(wid, revision, intent) {
383
+ async pinnedFiles(wid, revision, intent, verify = true) {
348
384
  const dir = revision === 1 ? pinnedDir(this.ledgers.home, wid) : join(pinnedDir(this.ledgers.home, wid), `r${revision}`);
349
385
  const ref = intent.pins ? undefined : intent.snapshot;
350
386
  if (ref) {
351
- const files = await this.recorded(dir, ref.hash).catch(() => undefined);
387
+ const files = await this.recorded(dir, ref.hash, verify).catch(() => undefined);
352
388
  if (files)
353
389
  return files;
354
390
  }
@@ -363,20 +399,22 @@ export class Store {
363
399
  }
364
400
  return files;
365
401
  }
366
- /** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined. */
367
- async recorded(dir, hash) {
402
+ /** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined.
403
+ * Without `verify`, only the record's form is checked (its digest and the file hashes are left to `ready`). */
404
+ async recorded(dir, hash, verify = true) {
368
405
  const { digest, ...body } = JSON.parse(await readFile(join(dir, 'pins.json'), 'utf8'));
369
406
  // The digest covers everything the record decides (pins, input names → files, origin, file hashes).
370
- if (body.snapshot !== hash || typeof digest !== 'string' || contentHash(body) !== digest)
407
+ if (body.snapshot !== hash || typeof digest !== 'string' || (verify && contentHash(body) !== digest))
371
408
  return undefined;
372
409
  if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
373
410
  return undefined;
374
411
  const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
375
412
  if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
376
413
  return undefined;
377
- for (const name of names)
378
- if (body.files[name] !== await fileHash(join(dir, name)))
379
- return undefined;
414
+ if (verify)
415
+ for (const name of names)
416
+ if (body.files[name] !== await fileHash(join(dir, name)))
417
+ return undefined;
380
418
  return { pins: body.pins, scriptPath: join(dir, 'script.js'), inputs: Object.fromEntries(Object.entries(body.inputs).map(([name, file]) => [name, join(dir, String(file))])),
381
419
  originPath: body.origin === true ? join(dir, 'origin.jsonl') : undefined };
382
420
  }
@@ -388,20 +426,49 @@ export class Store {
388
426
  const revision = Number(intent.revision), files = await this.pinnedFiles(wf.wid, revision, intent);
389
427
  await wf.journal.append('revised', { rid: intent.rid, revision, snapshot: intent.snapshot });
390
428
  Object.assign(wf, files, { revision });
429
+ this.unverified.delete(wf.wid);
391
430
  }
431
+ /** A1: Verify the pinned files of a workflow materialized unverified (a terminal one) before its script, inputs, origin
432
+ * or pins are used again: the record's digest and every file's hash, else the snapshot path (which republishes a
433
+ * missing file and refuses a changed one). Nothing evaluates from a file that does not hash as recorded. Idempotent;
434
+ * a refusal is raised again by every later call. */
435
+ async ready(wf) {
436
+ if (!this.unverified.has(wf.wid))
437
+ return;
438
+ let run = this.verifying.get(wf.wid);
439
+ if (!run) {
440
+ run = (async () => {
441
+ const pending = this.unverified.get(wf.wid);
442
+ if (!pending)
443
+ return;
444
+ const files = pending.revision === wf.revision ? await this.pinnedFiles(wf.wid, pending.revision, pending.intent) : undefined;
445
+ if (this.unverified.get(wf.wid) !== pending)
446
+ return; // A revision published meanwhile was verified by revise.
447
+ if (files && pending.revision === wf.revision)
448
+ Object.assign(wf, files);
449
+ this.unverified.delete(wf.wid);
450
+ })().finally(() => this.verifying.delete(wf.wid));
451
+ this.verifying.set(wf.wid, run);
452
+ }
453
+ await run;
454
+ }
455
+ /** Whether a workflow's pinned files were verified in this process (see ready). */
456
+ verified(wid) { return !this.unverified.has(wid); }
392
457
  /** P32: Rebuild a historical ticket from that revision's immutable snapshot. */
393
458
  async atRevision(wf, revision) {
394
- if (revision === wf.revision)
459
+ if (revision === wf.revision) {
460
+ await this.ready(wf);
395
461
  return wf;
462
+ }
396
463
  const intent = revision === 1
397
- ? this.ledgers.orch.entries().find(e => e.type === 'create-intent' && e.wid === wf.wid)
464
+ ? this.index().createByWid.get(wf.wid)
398
465
  : wf.journal.entries().find(e => e.type === 'revised' && e.revision === revision);
399
466
  if (!intent)
400
467
  throw new Error(`Missing pinned revision: ${wf.wid}@${revision}`);
401
468
  return { ...wf, revision, ...await this.pinnedFiles(wf.wid, revision, intent) };
402
469
  }
403
470
  /** A1, housekeeping: Wids with a committed pruned entry; they are gone and never materialize again. */
404
- pruned() { return new Set(this.ledgers.orch.entries().filter(e => e.type === 'pruned').map(e => String(e.wid))); }
471
+ pruned() { return this.index().pruned; }
405
472
  /** Housekeeping: Bytes a prune of `wid` frees: its workflow directory and the staging dirs of its requests. */
406
473
  async footprint(wid) {
407
474
  let total = await diskUsage(workflowDir(this.ledgers.home, wid));
@@ -410,7 +477,7 @@ export class Store {
410
477
  return total;
411
478
  }
412
479
  stagedRids(wid) {
413
- return this.ledgers.orch.entries().filter(e => (e.type === 'create-intent' || e.type === 'revise-intent') && e.wid === wid).map(e => String(e.rid));
480
+ return [...this.index().rids.get(wid) ?? []];
414
481
  }
415
482
  /** A1, A2: Retire a pruned workflow's handle after its pruned entry is committed; nothing appends to it again. */
416
483
  async drop(wid) {
@@ -429,6 +496,7 @@ export class Store {
429
496
  throw error; });
430
497
  // Readers' caches of it (derived, never authoritative: no sync needed).
431
498
  await rm(join(digestDir(this.ledgers.home), `${wid}.json`), { force: true });
499
+ await rm(settledPath(this.ledgers.home, wid), { force: true });
432
500
  const cached = await readdir(digestDir(this.ledgers.home)).catch(error => { if (error.code !== 'ENOENT')
433
501
  throw error; return []; });
434
502
  for (const name of cached)
@@ -448,28 +516,69 @@ export class Store {
448
516
  console.error(`durable-subagents: removal of pruned workflow ${wid} failed, retrying at next start: ${String(error)}`);
449
517
  }
450
518
  }
451
- for (const intent of this.ledgers.orch.entries().filter(e => e.type === 'create-intent'))
519
+ for (const intent of [...this.index().createIntents])
452
520
  if (!pruned.has(String(intent.wid)))
453
521
  await this.materialize(intent);
454
522
  }
523
+ /** A1: A workflow that already ended (its journal's current revision is terminal) is materialized from its pinned
524
+ * files' record without verifying them (see ready): a start does not hash the pinned files of finished history. */
455
525
  async materialize(intent) {
456
526
  const wid = intent.wid, existing = this.workflows.get(wid);
457
527
  if (existing)
458
528
  return existing;
459
529
  if (this.pruned().has(wid))
460
530
  throw new Error(`Workflow ${wid} was pruned`);
461
- const files = await this.pinnedFiles(wid, 1, intent);
462
- const journal = await openJournal(journalPath(this.ledgers.home, wid));
531
+ const path = journalPath(this.ledgers.home, wid);
532
+ // A settled workflow (settled.ts) whose journal is still what its record describes opens without decoding it.
533
+ const settled = readSettled(this.ledgers.home, wid), lazy = settled && await openLazyJournal(path, settled.journal);
534
+ if (settled && lazy) {
535
+ try {
536
+ const current = settled.revised ?? intent, files = await this.pinnedFiles(wid, settled.revision, current, false);
537
+ const facts = { revision: settled.revision, ...(settled.revised ? { revised: settled.revised } : {}), done: settled.done, resumed: settled.resumed, quiet: settled.quiet, calls: settled.calls, sweep: settled.sweep };
538
+ const wf = { wid, revision: settled.revision, origin: intent.origin, cwd: intent.cwd, journal: lazy, ...files, settled: facts };
539
+ this.unverified.set(wid, { revision: settled.revision, intent: current });
540
+ lazy.onAppend = () => this.appended?.(wid);
541
+ this.workflows.set(wid, wf);
542
+ if (!this.index().created.has(String(intent.rid)))
543
+ await this.ledgers.orch.append(JT.created, { rid: intent.rid, wid, origin: intent.origin });
544
+ return wf;
545
+ }
546
+ catch (error) {
547
+ this.workflows.delete(wid);
548
+ this.unverified.delete(wid);
549
+ await lazy.close();
550
+ throw error;
551
+ }
552
+ }
553
+ // A new workflow publishes its pins before its journal exists (a failed publication leaves no journal).
554
+ const fresh = await stat(path).then(() => false, error => { if (error.code === 'ENOENT')
555
+ return true; throw error; });
556
+ const first = fresh ? await this.pinnedFiles(wid, 1, intent) : undefined;
557
+ const journal = await openJournal(path);
558
+ let wf;
559
+ try {
560
+ const entries = journal.entries(), revised = entries.findLast(e => e.type === 'revised');
561
+ const revision = revised ? Number(revised.revision) : 1, current = revised ?? intent;
562
+ // terminalEntry over the whole journal: a `revised` after the last done supersedes it, as in the revision's view.
563
+ const ended = !first && entries.length > 0 && terminalEntry(entries) !== undefined;
564
+ const files = first ?? (ended ? await this.pinnedFiles(wid, revision, current, false) : await this.pinnedFiles(wid, 1, intent));
565
+ wf = { wid, revision: ended ? revision : 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
566
+ if (ended)
567
+ this.unverified.set(wid, { revision, intent: current });
568
+ }
569
+ catch (error) {
570
+ await journal.close();
571
+ throw error;
572
+ }
463
573
  journal.onAppend = () => this.appended?.(wid);
464
- const wf = { wid, revision: 1, origin: intent.origin, cwd: intent.cwd, journal, ...files };
465
574
  this.workflows.set(wid, wf);
466
575
  if (!journal.entries().length)
467
576
  await journal.append('wf-created', { rid: intent.rid, origin: intent.origin, cwd: intent.cwd, revision: 1,
468
577
  ...(intent.name !== undefined ? { name: intent.name } : {}) });
469
578
  const revised = journal.entries().findLast(e => e.type === 'revised');
470
- if (revised)
579
+ if (revised && wf.revision !== Number(revised.revision))
471
580
  Object.assign(wf, await this.pinnedFiles(wid, Number(revised.revision), revised), { revision: Number(revised.revision) });
472
- if (!this.ledgers.orch.entries().some(e => e.type === JT.created && e.rid === intent.rid))
581
+ if (!this.index().created.has(String(intent.rid)))
473
582
  await this.ledgers.orch.append(JT.created, { rid: intent.rid, wid, origin: intent.origin });
474
583
  return wf;
475
584
  }
package/dist/ui/tool.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Text } from "@earendil-works/pi-tui";
2
- import { plainReason } from "./view.js";
2
+ import { plainReason, queuedPhrase } from "./view.js";
3
3
  const short = (id) => typeof id === "string" ? (id.length > 12 ? `${id.slice(0, 10)}…` : id) : "";
4
4
  const clip = (s, n) => s.length > n ? `${s.slice(0, n - 1)}…` : s;
5
5
  /** UI §5: One line per tool call: what was asked, never the raw arguments (scripts and task prompts stay out of the transcript). */
@@ -32,7 +32,7 @@ export function resultLines(details) {
32
32
  const d = (details ?? {});
33
33
  if (typeof d.wid === "string" && typeof d.key === "string" && typeof d.phase === "string") {
34
34
  const r = d.result;
35
- return [`${d.key} · ${r?.status ?? (d.phase === "queued" && d.answered ? "queued (answered, waiting for a slot)" : d.phase)}${typeof d.model === "string" ? ` · ${d.model}` : ""}`];
35
+ return [`${d.key} · ${r?.status ?? (d.phase === "queued" ? queuedPhrase(d, Date.now()) : d.phase)}${typeof d.model === "string" ? ` · ${d.model}` : ""}`];
36
36
  }
37
37
  if (typeof d.wid === "string" && !Array.isArray(d.calls))
38
38
  return [`started workflow ${d.wid}`, ...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : [])];
@@ -53,7 +53,9 @@ export function resultLines(details) {
53
53
  return `${w.name ?? short(w.wid)} · ${w.paused ? "paused" : w.followUps ? `follow-up running (run ${w.status})` : w.status} · ${w.progress} done${failed ? ` · ${failed} not ok` : ""}${asks ? ` · ${asks} asking` : ""}${alerts ? ` · ${alerts} alert${alerts > 1 ? "s" : ""}` : ""}`;
54
54
  });
55
55
  const finished = Array.isArray(d.finished) ? d.finished.length + Number(d.olderFinished ?? 0) : 0;
56
- return [...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : []), ...(rows.length ? rows.slice(0, 6) : ["nothing running"]),
56
+ // The orchestrator line ("1.0.42 (pid 7, starting 12s)") while it recovers: nothing queued starts until then.
57
+ const starting = typeof d.orchestrator === "string" ? /^[^(]*\(pid \d+, starting ([^)]+)\)/.exec(d.orchestrator)?.[1] : undefined;
58
+ return [...(typeof d.paused === "string" ? [`⚠ ${d.paused}`] : []), ...(starting ? [`orchestrator starting (${starting})`] : []), ...(rows.length ? rows.slice(0, 6) : ["nothing running"]),
57
59
  ...(rows.length > 6 ? [`… ${rows.length - 6} more`] : []), ...(finished ? [`${finished} finished`] : [])];
58
60
  }
59
61
  if (Array.isArray(d.workflows)) {