pi-durable-subagents 1.0.40 → 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.
@@ -23,6 +23,40 @@ export function entriesOf(journal, type, exec) {
23
23
  }
24
24
  return (exec === undefined ? index.types.get(type) : index.execs.get(type)?.get(exec)) ?? [];
25
25
  }
26
+ const keyedIndexes = new Map();
27
+ function keyed(journal, keyOf, key) {
28
+ let byJournal = keyedIndexes.get(keyOf);
29
+ if (!byJournal) {
30
+ byJournal = new WeakMap();
31
+ keyedIndexes.set(keyOf, byJournal);
32
+ }
33
+ let index = byJournal.get(journal);
34
+ if (!index) {
35
+ index = { count: 0, keys: new Map() };
36
+ byJournal.set(journal, index);
37
+ }
38
+ const entries = journal.committed?.() ?? journal.entries();
39
+ while (index.count < entries.length) {
40
+ const e = entries[index.count++], k = keyOf(e);
41
+ if (k === undefined)
42
+ continue;
43
+ const bucket = index.keys.get(k);
44
+ if (bucket)
45
+ bucket.push(e);
46
+ else
47
+ index.keys.set(k, [e]);
48
+ }
49
+ return index.keys.get(key) ?? [];
50
+ }
51
+ const byCall = (e) => typeof e.call === "string" ? e.call : undefined;
52
+ const byDest = (e) => e.type === "forward" && typeof e.dest === "string" ? e.dest : undefined;
53
+ const byRid2 = (e) => e.type === "forward" && typeof e.rid2 === "string" ? e.rid2 : undefined;
54
+ /** The entries whose `call` field names `call`, in journal order. */
55
+ export function callEntries(journal, call) { return keyed(journal, byCall, call); }
56
+ /** The `forward` entries whose destination is `call`, in journal order. */
57
+ export function forwardsTo(journal, call) { return keyed(journal, byDest, call); }
58
+ /** The `forward` entry with this forwarded identity (the first, should a replay have recorded it twice). */
59
+ export function forwardOf(journal, rid2) { return keyed(journal, byRid2, rid2)[0]; }
26
60
  const identities = new WeakMap();
27
61
  export function trackedState(journal, exec) {
28
62
  let byExec = identities.get(journal);
@@ -5,7 +5,7 @@ import { join } from "node:path";
5
5
  import { stat as fileStat } from "node:fs/promises";
6
6
  import { performance } from "node:perf_hooks";
7
7
  import { createInterface } from "node:readline";
8
- import { JT, attentionEntries } from "../../types.js";
8
+ import { CT, JT, attentionEntries } from "../../types.js";
9
9
  import { callDir, callSession } from "../../paths.js";
10
10
  import { monotoneTime } from "../../kernel/guards.js";
11
11
  import { readSession } from "./session.js";
@@ -35,7 +35,7 @@ export async function observeExecution(d) {
35
35
  let size = (await fileStat(session).catch(() => ({ size: 0 }))).size, checkpoint = performance.now();
36
36
  let signal;
37
37
  const boundary = new Promise(resolve => { signal = resolve; d.setWake(resolve); });
38
- let failure, pending = Promise.resolve(), ending = false;
38
+ let failure, pending = Promise.resolve(), ending = false, modelBlocked = false;
39
39
  const has = (type) => entriesOf(t.journal, type, exec).length > 0;
40
40
  const enqueue = (fn) => { if (!ending)
41
41
  pending = pending.then(fn).catch(error => { failure = error; signal(); }); };
@@ -145,14 +145,26 @@ export async function observeExecution(d) {
145
145
  if (event.type === "message_update" || event.type === "tool_execution_update")
146
146
  return;
147
147
  enqueue(async () => {
148
+ if (modelBlocked)
149
+ return;
150
+ if (event.type === CT.modelReady || event.type === CT.modelUnavailable) {
151
+ if (await d.modelControl?.(event) === false) {
152
+ modelBlocked = true;
153
+ signal();
154
+ }
155
+ return;
156
+ }
157
+ if ((event.type === "message_start" || event.type === "message_end") && await d.switched(event) === false) {
158
+ modelBlocked = true;
159
+ signal();
160
+ return;
161
+ }
148
162
  const args = event.args;
149
163
  if (event.type === "tool_execution_start" && (event.toolName === "edit" || event.toolName === "write") && typeof args?.path === "string")
150
164
  await d.wrote?.(args.path);
151
165
  const slim = observation(event);
152
166
  if (slim) {
153
167
  await serial(() => t.journal.append("observation", { exec, event: slim }));
154
- if (event.type === "message_start")
155
- await d.switched(event);
156
168
  if (event.type === "message_end") {
157
169
  await d.recordUsage([{ id: String(slim.id), usage: slim.usage }]);
158
170
  await d.answered?.(event);
@@ -200,6 +212,15 @@ export async function observeExecution(d) {
200
212
  size = nextSize;
201
213
  }
202
214
  const entries = await (d.read ? d.read() : readSession(session));
215
+ for (const e of entries)
216
+ if (e.type === "custom" && (e.customType === CT.modelReady || e.customType === CT.modelUnavailable) && e.data?.exec === exec)
217
+ if (await d.modelControl?.({ type: e.customType, ...e.data }) === false) {
218
+ modelBlocked = true;
219
+ signal();
220
+ return;
221
+ }
222
+ if (modelBlocked)
223
+ return;
203
224
  await d.questions(entries);
204
225
  const values = d.usage ? d.usage(entries) : sessionUsage(entries, t.callId);
205
226
  if (values !== usageList) {
@@ -0,0 +1,39 @@
1
+ import { parseModel, sameModel } from "../../compat/model.js";
2
+ /** A parent model request keeps its pin after it was applied, including in continued generations. */
3
+ export function parentPinned(t) {
4
+ if (t.model)
5
+ return true;
6
+ const log = t.journal.entries(), calls = new Set([t.callId]);
7
+ if (t.continueFrom)
8
+ calls.add(t.continueFrom);
9
+ for (let i = log.length - 1; i >= 0; i--) {
10
+ const e = log[i];
11
+ if (e.type === "generation" && calls.has(`${t.wid}@${e.revision}/${e.key}@${e.gen}`)) {
12
+ if (typeof e.model === "string")
13
+ return true;
14
+ calls.add(String(e.from));
15
+ }
16
+ }
17
+ return log.some(e => {
18
+ if (e.type !== "forward" || !calls.has(String(e.dest)) || e.failover || e.envelope?.kind !== "model")
19
+ return false;
20
+ if (log.some(r => r.type === "forward-delivered" && r.rid2 === e.rid2 && r.reason !== undefined))
21
+ return false;
22
+ return !log.some(r => r.type === "forward" && r.dest === e.dest && r.envelope?.kind === "withdraw" &&
23
+ r.envelope.body?.rids?.includes(String(e.rid2)));
24
+ });
25
+ }
26
+ /** Other providers with the same id first, then pool order; admission still checks afterMs and slots. */
27
+ export function spillCandidates(pinned, candidates) {
28
+ const others = candidates.filter(m => m.provider !== pinned.provider);
29
+ const name = (m) => parseModel(m.id).id.split("/").at(-1).toLowerCase();
30
+ return [...others.filter(m => name(m) === name(pinned)), ...others.filter(m => name(m) !== name(pinned))];
31
+ }
32
+ export const MODEL_RETRY_MS = 600_000;
33
+ export function modelFailures(journal, call) {
34
+ const execs = new Set(journal.entries().filter(e => e.type === "exec" && e.call === call).map(e => e.exec));
35
+ return journal.entries().filter(e => e.type === "model-unavailable" && execs.has(e.exec));
36
+ }
37
+ export function failedModel(failures, model) {
38
+ return failures.some(e => sameModel(e.selected, model) && Number(e.until) > Date.now());
39
+ }
@@ -0,0 +1,85 @@
1
+ import { entriesOf, forwardOf } from "./indexes.js";
2
+ /** Bump whenever the recovery of a sealed or retired call gains a step: every call is then recovered once more. */
3
+ export const RECOVERY_VERSION = 1;
4
+ export const RECOVERED = "recovered";
5
+ const CALL = /^(.*)@(\d+)\/(.*)@(\d+)$/;
6
+ const digit = (code) => code >= 48 && code <= 57;
7
+ /** The calls among `among` (call ids of workflow `wid`) that entry `e` concerns: one whose id appears in any string of
8
+ * the entry (fields such as call, exec, dest, target, from, an attention item or its id; an id followed by a digit is a
9
+ * longer generation, not this one), a `call`/`generation` of the same key, and the destination of the forward a
10
+ * `rid2` names. Receipts themselves concern nothing. Conservative: a false match only costs one more read. */
11
+ export function concernedCalls(e, wid, among, forwardDest, lengths = [...new Set([...among].map(c => c.length))]) {
12
+ const found = new Set();
13
+ if (e.type === RECOVERED || !among.size)
14
+ return found;
15
+ const marker = `${wid}@`;
16
+ const visit = (value) => {
17
+ if (typeof value === "string") {
18
+ for (let p = value.indexOf(marker); p >= 0; p = value.indexOf(marker, p + 1))
19
+ for (const length of lengths) {
20
+ if (p + length > value.length)
21
+ continue;
22
+ const id = value.substr(p, length);
23
+ if (among.has(id) && !digit(value.charCodeAt(p + length)))
24
+ found.add(id);
25
+ }
26
+ }
27
+ else if (Array.isArray(value))
28
+ for (const v of value)
29
+ visit(v);
30
+ else if (value && typeof value === "object")
31
+ for (const v of Object.values(value))
32
+ visit(v);
33
+ };
34
+ visit(e);
35
+ if ((e.type === "generation" || e.type === "call") && e.key !== undefined)
36
+ for (const call of among)
37
+ if (CALL.exec(call)?.[3] === String(e.key))
38
+ found.add(call);
39
+ if (typeof e.rid2 === "string" && forwardDest) {
40
+ const dest = forwardDest(e.rid2);
41
+ if (dest !== undefined && among.has(dest))
42
+ found.add(dest);
43
+ }
44
+ return found;
45
+ }
46
+ /** Whether entry `e` of workflow `wid`'s journal concerns `call` (concernedCalls for one call). */
47
+ export function concerns(e, call, forwardDest) {
48
+ const wid = CALL.exec(call)?.[1] ?? call;
49
+ return concernedCalls(e, wid, new Set([call]), forwardDest).size > 0;
50
+ }
51
+ const complete = new WeakMap();
52
+ /** The calls of workflow `wid` whose recovery is complete: their latest `recovered` entry has the current version and
53
+ * no later entry concerns them. One pass over the entries after the earliest such receipt; cached per journal length. */
54
+ export function completeCalls(journal, wid) {
55
+ const entries = journal.committed?.() ?? journal.entries(), cached = complete.get(journal);
56
+ if (cached && cached.length === entries.length)
57
+ return cached.calls;
58
+ const receipts = new Map();
59
+ for (const r of entriesOf(journal, RECOVERED)) {
60
+ const call = String(r.call);
61
+ if (r.v === RECOVERY_VERSION)
62
+ receipts.set(call, r.seq);
63
+ else
64
+ receipts.delete(call);
65
+ }
66
+ const calls = new Set(receipts.keys());
67
+ if (calls.size) {
68
+ const lengths = [...new Set([...calls].map(c => c.length))], dest = (rid2) => {
69
+ const d = forwardOf(journal, rid2)?.dest;
70
+ return typeof d === "string" ? d : undefined;
71
+ };
72
+ const from = Math.min(...receipts.values());
73
+ // seq is dense from 1: the entries after the earliest receipt start at index `from`.
74
+ for (let i = entries[from - 1]?.seq === from ? from : 0; i < entries.length && calls.size; i++) {
75
+ const e = entries[i];
76
+ if (e.seq <= from)
77
+ continue;
78
+ for (const call of concernedCalls(e, wid, calls, dest, lengths))
79
+ if (receipts.get(call) < e.seq)
80
+ calls.delete(call);
81
+ }
82
+ }
83
+ complete.set(journal, { length: entries.length, calls });
84
+ return calls;
85
+ }
@@ -11,6 +11,7 @@ const EMPTY = { entries: [], corrupt: [] };
11
11
  /** C5, E4, F3: Read complete native entries incrementally; an unfinished trailing line is ignored and a malformed
12
12
  * complete line is skipped (pi's own loader does the same), reported by its 1-based line number in `corrupt`. */
13
13
  export async function readSessionState(path) {
14
+ reads++;
14
15
  const file = await open(path, "r").catch(error => { if (error.code === "ENOENT")
15
16
  return undefined; throw error; });
16
17
  if (!file) {
@@ -63,6 +64,9 @@ export async function readSessionState(path) {
63
64
  await file.close();
64
65
  }
65
66
  }
67
+ let reads = 0;
68
+ /** How many session reads (readSessionState calls) this process made: a diagnostic, e.g. of what a recovery read. */
69
+ export function sessionReads() { return reads; }
66
70
  /** C5: Complete native session entries (see readSessionState). The result is shared: never mutate it. */
67
71
  export async function readSession(path) {
68
72
  return (await readSessionState(path)).entries;
@@ -166,6 +170,10 @@ export function refusedByProvider(text) {
166
170
  export function sessionModel(entries) {
167
171
  // pi restores the model of the last model change or assistant message: a relaunch with `--model` on an existing
168
172
  // session records no model change, so only the answer tells which model the session went on with.
173
+ // Virtual answers name the routed physical model; only a later selection replaces the virtual one.
174
+ const selection = entries.findLast(e => e.type === "model_change" || e.type === "custom" && e.customType === CT.modelReady);
175
+ if (selection?.customType === CT.modelReady && selection.data?.virtual === true)
176
+ return selection.data.model;
169
177
  const last = entries.findLast(e => e.type === "model_change" && e.provider && e.modelId
170
178
  || e.type === "message" && e.message?.role === "assistant" && !!e.message.provider && !!e.message.model);
171
179
  if (!last)
@@ -61,6 +61,22 @@ export async function fenceAttentionResolved(journal, id) {
61
61
  await journal.append(JT.attentionResolved, { id: `fence:${id}`, rev: item.rev, resolution: "fenced" });
62
62
  }
63
63
  const sweeps = new WeakMap();
64
+ export function sweepSeed(journal) {
65
+ const { failed, fenced, tracked, execs } = indexSweep(journal);
66
+ return execs.map(e => {
67
+ const exec = String(e.exec);
68
+ const ids = [...new Set((tracked.get(exec) ?? []).map(p => `${p.pid} ${p.start}`))];
69
+ // Only a failure not fenced since is still a failure: a fenced one would make the sweep record (and decode) again.
70
+ return { exec, call: String(e.call), ...(failed.has(exec) && !fenced.has(exec) ? { failed: true } : {}), tracked: ids };
71
+ });
72
+ }
73
+ const procOf = (id) => { const space = id.indexOf(" "); return { pid: Number(id.slice(0, space)), ppid: 0, start: id.slice(space + 1) }; };
74
+ /** The sweep state of a journal that is not decoded, from its seed (every execution fenced, no open gate): no failed
75
+ * fence is open (settledFacts requires it), so none is seeded, also from an older record. */
76
+ export function seededSweep(seed) {
77
+ return { count: 0, fenced: new Set(seed.map(s => s.exec)), retired: new Set(), failed: new Set(), gated: new Set(),
78
+ tracked: new Map(seed.map(s => [s.exec, s.tracked.map(procOf)])), execs: seed.map(s => ({ seq: 0, ts: 0, type: JT.exec, exec: s.exec, call: s.call })), gates: [] };
79
+ }
64
80
  /** A1: Fold old history during recovery, so the first sweep does not allocate it on the timer path. */
65
81
  export function indexSweep(journal) {
66
82
  let state = sweeps.get(journal);
@@ -97,7 +113,7 @@ export function indexSweep(journal) {
97
113
  export async function sweepExecutions(journals, containment, hooks = {}) {
98
114
  const targets = [];
99
115
  for (const journal of journals) {
100
- const { fenced, retired, failed, gated, tracked, execs, gates } = indexSweep(journal);
116
+ const { fenced, retired, failed, gated, tracked, execs, gates } = (journal.loaded === false ? hooks.seeded?.(journal) : undefined) ?? indexSweep(journal);
101
117
  // A gate whose recovery fence failed has no outcome yet; it is retried here until its processes are gone.
102
118
  for (const e of gates) {
103
119
  const id = String(e.id);
@@ -5,8 +5,9 @@
5
5
  // provider-*: used-up usage windows (providers.ts).
6
6
  // config{hash,config}: the orchestrator settings in effect from here; config-rejected{error,hash?}: a change of
7
7
  // config.json refused, while the earlier settings stay (cleared by the next config record).
8
- // orchestrator{version,pid,pi?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its package
9
- // version, the pi it launches) and its exit (why: idle, restart, signal, error).
8
+ // orchestrator{version,pid,pi?,recovery?} / orchestrator-exit{pid,reason?,signal?,error?}: the orchestrator running (its
9
+ // package version, the pi it launches) and its exit (why: idle, restart, signal, error). `recovery`: it recovers the
10
+ // home's workflows before it dispatches anything, until its recovered{pid,ms,workflows,calls,skipped}.
10
11
  // restart{rid,force,reason?,initiator?,from?,live}: accepted restart; the next start consumes its status provenance.
11
12
  // Old records lack reason/initiator/from and remain readable (A1).
12
13
  // writer-hold/writer-release{root,call}: the writer lock of a worktree root, held by one call until it ends.
@@ -37,9 +38,13 @@ export function applyLedger(state, e) {
37
38
  else if (e.type === "restart")
38
39
  state.pendingRestart = e.force === true ? { ts: e.ts, reason: e.reason, initiator: e.initiator, from: e.from } : undefined;
39
40
  else if (isEntry(e, "orchestrator")) {
40
- state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
41
+ state.orchestrator = { version: String(e.version), pid: Number(e.pid), ...(e.start ? { start: String(e.start) } : {}), ts: e.ts, ...(e.pi !== undefined ? { pi: e.pi } : {}), ...(e.restart === true ? { restart: true } : {}), ...(e.recovery === true ? { recovery: true } : {}), ...(state.pendingRestart ? { forceRestart: state.pendingRestart } : {}) };
41
42
  delete state.pendingRestart;
42
43
  }
44
+ else if (isEntry(e, "recovered")) {
45
+ if (state.orchestrator && state.orchestrator.pid === Number(e.pid))
46
+ state.orchestrator.recovered = { ts: e.ts, ms: Number(e.ms) };
47
+ }
43
48
  else if (e.type === "writer-hold") {
44
49
  if (!state.writers.has(String(e.root)))
45
50
  state.writers.set(String(e.root), { call: String(e.call), ts: e.ts });
@@ -61,7 +61,9 @@ export async function main(options = {}) {
61
61
  const pi = resolvePi(process.env).path ?? resolvePi({ PATH: process.env.PATH }).path;
62
62
  if (!pi)
63
63
  console.error('durable-subagents: pi not found (DSA_PI_BIN unset or not executable, not on PATH); subagents launch `pi` from PATH');
64
- await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true, pi: pi ?? null });
64
+ // `recovery: true` announces the `recovered` entry this pid appends once its recovery ends (none if it fails first).
65
+ await ledgers.orch.append('orchestrator', { version: packageVersion(), pid: process.pid, ...(start ? { start } : {}), restart: true, pi: pi ?? null, recovery: true });
66
+ const recoveryStarted = performance.now();
65
67
  const factory = options.executor ?? (await import(__rewriteRelativeImportExtension(new URL(import.meta.url.endsWith('.ts') ? './executor/index.ts' : './executor/index.js', import.meta.url).href))).default;
66
68
  const executor = factory(ledgers, pi ? { pi } : {});
67
69
  engine = new Engine(ledgers, executor, options);
@@ -72,7 +74,8 @@ export async function main(options = {}) {
72
74
  watcher = watchConfig({ path: configPath(home), stamp, config, orch: ledgers.orch, intervalMs: Math.min(1000, config.k?.trackerMs ?? 1000),
73
75
  apply: change => executor.reconfigure ? executor.reconfigure(change) : change() });
74
76
  }
75
- await engine.recover();
77
+ const recovered = await engine.recover();
78
+ await ledgers.orch.append('recovered', { pid: process.pid, ms: Math.round(performance.now() - recoveryStarted), ...recovered });
76
79
  await engine.loop(options.signal);
77
80
  const reason = options.signal?.reason;
78
81
  exit = engine.restartRequested ? { reason: 'restart' }
@@ -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
+ }