pi-durable-subagents 1.0.42 → 1.0.45

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.
@@ -2,12 +2,16 @@
2
2
  import { forgetJournalSnapshot, readJournalFold } from "../kernel/journal.js";
3
3
  import { orchLedger } from "../paths.js";
4
4
  import { JT } from "../types.js";
5
- import { applyLedger, emptyLedger } from "./ledger.js";
5
+ import { LEDGER_ENTRY_TYPES, applyLedger, emptyLedger } from "./ledger.js";
6
6
  import { labelsOf } from "../events/derive.js";
7
7
  export function emptyReaderLedger() {
8
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
9
  byWid: new Map(), byOrigin: new Map(), state: emptyLedger(), createdRids: new Map(), decisions: new Map(), resolutions: new Map(), sendNotes: new Map() };
10
10
  }
11
+ /** Reader-only projections, combined with applyLedger's type list by the byte filter. */
12
+ export const READER_ENTRY_TYPES = [JT.created, 'create-intent', 'revise-intent', 'request', 'pruned', 'drain', 'undrain',
13
+ JT.applied, JT.rejected, 'send-note'];
14
+ const discardedLedgerTypes = ['switch-observed', 'skip', 'writer-hold', 'writer-release'];
11
15
  export function applyReaderLedger(ix, e) {
12
16
  if (e.type === JT.created) {
13
17
  if (!ix.created.has(e.wid))
@@ -78,7 +82,7 @@ export function applyReaderLedger(ix, e) {
78
82
  // A holder needs only pool/slot/exec, not any extra payload the entry might carry.
79
83
  if (e.type === "hold")
80
84
  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")
85
+ else if (!discardedLedgerTypes.includes(e.type))
82
86
  applyLedger(ix.state, e);
83
87
  ix.state.seen++;
84
88
  }
@@ -89,13 +93,19 @@ export function readerHold(ix, wid, origin) {
89
93
  return last?.type === "drain" && (!created || created.seq < last.seq) ? last : undefined;
90
94
  }
91
95
  const readers = new Map();
96
+ // Canonical writer JSON: these are exactly the types that affect reader projections or applyLedger below.
97
+ const needles = [...new Set([...READER_ENTRY_TYPES.filter(type => type !== 'request'),
98
+ ...LEDGER_ENTRY_TYPES.filter(type => !discardedLedgerTypes.includes(type))])].map(type => `"type":${JSON.stringify(type)}`);
99
+ // Request records only affect labels/session for runs; the other request kinds have no reader projection.
100
+ needles.push('"kind":"run"');
92
101
  export function readerLedger(home) {
93
102
  const path = orchLedger(home);
94
103
  // Drop any raw snapshot loaded by another read path in this process. This reader never creates one itself.
95
104
  forgetJournalSnapshot(path);
96
105
  try {
97
- const record = readJournalFold(path, readers.get(path), emptyReaderLedger, applyReaderLedger);
106
+ const record = readJournalFold(path, readers.get(path), emptyReaderLedger, applyReaderLedger, { needles });
98
107
  if (record) {
108
+ record.state.state.seen = record.seen;
99
109
  readers.set(path, record);
100
110
  return record;
101
111
  }
@@ -18,7 +18,9 @@ export function restartInputError(body, subagent = false) {
18
18
  return "restart force needs the 12-hex token from a refused restart; first show the user the running executions";
19
19
  return undefined;
20
20
  }
21
- export function restartRefusal(home, live, body, tool = false, now = Date.now()) {
21
+ /** `commands`: command calls running now. They are never in `live` (nor in the token): a restart leaves them running and
22
+ * the successor adopts them; a refusal shown for other executions says so in one line. */
23
+ export function restartRefusal(home, live, body, tool = false, now = Date.now(), commands = 0) {
22
24
  const invalid = restartInputError(body);
23
25
  if (invalid)
24
26
  return invalid;
@@ -53,6 +55,7 @@ export function restartRefusal(home, live, body, tool = false, now = Date.now())
53
55
  `${origin}:`, ...executions.map(l => ` ${l.wid}/${l.key} ${age(now - l.since)}${l.phase === "gate" ? " gate" : ""}${leases.has(l.callId) ? ` ${leases.get(l.callId)}` : ""}`),
54
56
  ]),
55
57
  ...(others.length ? ["not fenced (a restart leaves these leases held):", ...others] : []),
58
+ ...(commands > 0 ? [`not fenced: ${commands} command call${commands === 1 ? "" : "s"} keep${commands === 1 ? "s" : ""} running across the restart`] : []),
56
59
  `token: ${token}`,
57
60
  tool ? `to fence exactly these: subagents {action:"restart", force:"${token}", reason:"<why>"}` : `to fence exactly these: pi-durable-subagents restart --force ${token} --reason "<why>"`,
58
61
  ].join("\n");
@@ -17,6 +17,7 @@ import { revisionEntries, terminalEntry } from "./store.js";
17
17
  import { RECOVERY_VERSION } from "./executor/recovered.js";
18
18
  import { sweepSeed } from "./executor/sweep.js";
19
19
  import { callEntries } from "./executor/indexes.js";
20
+ import { unsealedCommandCalls } from "./executor/command.js";
20
21
  /** Bump whenever the record gains a field or settledFacts a condition: every record is then rebuilt once. */
21
22
  export const SETTLED_VERSION = 2;
22
23
  export const settledPath = (home, wid) => join(cacheDir(home), "settled", `${wid}.json`);
@@ -41,6 +42,9 @@ export function settledFacts(wf, recovered) {
41
42
  if (!fenced.has(String(e.exec)))
42
43
  return `unfenced:${String(e.exec)}`;
43
44
  }
45
+ // A command call with an attempt and no seal may still run: the next start adopts it.
46
+ for (const call of unsealedCommandCalls(log))
47
+ return `live:${call}`;
44
48
  for (const call of calls) {
45
49
  if (!ended.has(call))
46
50
  return `live:${call}`;
@@ -107,9 +111,17 @@ export function readSettled(home, wid) {
107
111
  return undefined;
108
112
  if (!record.journal || typeof record.journal.size !== "number" || !record.done || typeof record.revision !== "number" || !Array.isArray(record.sweep) || !Array.isArray(record.resumed))
109
113
  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)))
114
+ // Version 2 records held fenced tags with obsolete pid/start lineage. Keep their tags only; no rebuild is needed.
115
+ const tags = [];
116
+ for (const s of record.sweep) {
117
+ if (typeof s === "string")
118
+ tags.push(s);
119
+ else if (s && typeof s === "object" && typeof s.exec === "string")
120
+ tags.push(s.exec);
121
+ else
112
122
  return undefined;
123
+ }
124
+ record.sweep = tags;
113
125
  return record;
114
126
  }
115
127
  /** Write the record of a settled workflow from its decoded journal (best effort: a failure only costs a decode at the
@@ -3,7 +3,7 @@
3
3
  import { initiatorSummary, restartLine } from "./restart.js";
4
4
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
- import { compileFanout } from "../compat/fanout.js";
6
+ import { FANOUT_BODIES } from "../compat/fanout.js";
7
7
  import { crc32, forgetJournalSnapshot, forgetJournalSnapshotsIf, journalAppends, readJournalRecord, readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
8
8
  import { readCache, writeCache } from "../kernel/cache.js";
9
9
  import { digestDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
@@ -31,6 +31,44 @@ export function modelStatusText(c, now = Date.now()) {
31
31
  (c.routedModel ? ` (routed ${c.routedModel})` : "") +
32
32
  (m ? ` (used ${m.used}, selected ${m.selected})` : "") + (c.modelUnavailable ? ` (model-unavailable: ${c.modelUnavailable})` : "");
33
33
  }
34
+ /** A command call's command as one line: an argv array joined with spaces (an argument that needs it single-quoted as
35
+ * for sh), a string as it is. */
36
+ export function commandText(command) {
37
+ if (Array.isArray(command))
38
+ return command.map(a => { const s = String(a); return /^[A-Za-z0-9_./:=@%+,-]+$/.test(s) ? s : `'${s.replaceAll("'", "'\\''")}'`; }).join(" ");
39
+ return String(command ?? "");
40
+ }
41
+ /** R8: The pinned refusal of a send to a command call (the engine gives the same reason). */
42
+ export const commandSendRefusal = (kind) => `command call: ${kind} is not supported (stop it, or start a new call)`;
43
+ /** R8, F5: Whether a send address names a command call, matched whole as the engine's findCall does, among the
44
+ * current revision's calls: `<wid>/<key>`, `<wid>@<rev>/<key>@<gen>`, or a bare wid of a workflow with one key. A key
45
+ * may contain `@` and digits: nothing is stripped. Read-only; false for anything it cannot resolve. */
46
+ export function isCommandTarget(home, to) {
47
+ if (typeof to !== "string" || !to)
48
+ return false;
49
+ const wid = to.split(/[@/]/, 1)[0]; // a wid has neither '@' nor '/'
50
+ if (!wid || !existsSync(journalPath(home, wid)))
51
+ return false;
52
+ let entries;
53
+ try {
54
+ entries = readJournalSnapshot(journalPath(home, wid));
55
+ }
56
+ catch {
57
+ return false;
58
+ }
59
+ const rev = Math.max(1, ...entries.filter(e => e.type === "wf-created" || e.type === "revised").map(e => Number(e.revision) || 1));
60
+ const start = entries.findLastIndex(e => e.type === "revised");
61
+ const calls = (start < 0 ? entries : entries.slice(start)).filter(e => e.type === "call" || e.type === "generation");
62
+ const keys = new Set(calls.map(e => String(e.key)));
63
+ const named = calls.findLast(e => to === `${wid}/${e.key}` || to === `${wid}@${rev}/${e.key}@${e.gen}` || (to === wid && keys.size === 1));
64
+ if (!named)
65
+ return false;
66
+ return calls.findLast(e => e.key === named.key).spec?.command !== undefined;
67
+ }
68
+ /** A command clipped to one display line of at most `n` characters ("command: <clipped>" in status and the UI). */
69
+ export function commandLine(command, n = 80) {
70
+ return clip(command.replace(/\s+/g, " ").trim(), n);
71
+ }
34
72
  /** A workflow has live work: it runs, or follow-ups opened on it after it finished have not ended yet. */
35
73
  export function isLive(wf) {
36
74
  return wf.status === "running" || (wf.followUps ?? 0) > 0;
@@ -46,8 +84,8 @@ export function progressOf(wf) {
46
84
  const done = [...latest.values()].filter(c => c.phase === "sealed").length;
47
85
  return { done, total: wf.planned ?? latest.size, plus: wf.planned === undefined && wf.status === "running" };
48
86
  }
49
- // v12 §4: the exact bodies compileFanout emits after the `const steps = [...];` line, so only true fanouts count as planned.
50
- const fanoutBodies = [compileFanout({ tasks: [] }).source, compileFanout({ chain: [] }).source].map(s => s.slice(s.indexOf("\n") + 1));
87
+ // v12 §4: the exact bodies compileFanout emits (or emitted) after the `const steps = [...];` line, so only true fanouts count as planned.
88
+ const fanoutBodies = FANOUT_BODIES;
51
89
  /** v12 §4: The planned total of a pinned script: its steps count when it is a compiled tasks/chain fanout; scripts have none. */
52
90
  export function plannedFromScript(source) {
53
91
  const cut = source.indexOf("\n"), head = source.slice(0, Math.max(0, cut)), rest = source.slice(cut + 1);
@@ -101,6 +139,7 @@ function snapshotReducer(wid, entries) {
101
139
  let terminal = current.findLast(e => e.type === JT.done || (e.type === "resumed" && !e.call));
102
140
  const calls = new Map();
103
141
  const byExec = new Map();
142
+ const byCommand = new Map(); // command attempt id -> its call
104
143
  const hibernating = new Map(); // callId → exec that decided to hibernate and is not fenced yet
105
144
  const fenced = new Set();
106
145
  const resolved = new Set();
@@ -133,7 +172,9 @@ function snapshotReducer(wid, entries) {
133
172
  const result = e.type === "refused" ? refusedResult(key, e.reason) :
134
173
  e.type === "reused" ? entries.find(s => s.type === JT.sealed && s.call === e.from)?.result : undefined;
135
174
  const wanted = e.spec?.model;
175
+ const command = e.spec?.command;
136
176
  calls.set(callId, { key, gen, callId, pos: Number(e.pos), agent: String(e.spec?.agent ?? ""),
177
+ ...(command !== undefined ? { command: commandText(command) } : {}),
137
178
  // Until a slot is acquired (`selected`), show the model the call asked for, not nothing.
138
179
  ...(typeof wanted === "string" && wanted ? { model: wanted } : {}),
139
180
  phase: result ? "sealed" : "queued", ...(result ? { result, endedAt: e.ts } : {}),
@@ -168,6 +209,26 @@ function snapshotReducer(wid, entries) {
168
209
  hibernating.delete(call.callId);
169
210
  }
170
211
  }
212
+ else if (e.type === "command-intent") {
213
+ // A command call runs from its intent until its seal; it never has an `exec`, so nothing treats it as an execution.
214
+ const call = calls.get(String(e.call));
215
+ if (call && call.phase !== "sealed") {
216
+ call.commandRun = { attempt: Number(e.n) || 1, id: String(e.id) };
217
+ call.phase = "running";
218
+ call.startedAt = e.ts;
219
+ call.lastActivity = e.ts;
220
+ delete call.writerWait;
221
+ byCommand.set(String(e.id), call);
222
+ }
223
+ }
224
+ else if (e.type === "command-started") {
225
+ const call = byCommand.get(String(e.id)), dir = e.dir;
226
+ if (call && call.commandRun?.id === e.id) {
227
+ call.commandRun = { ...call.commandRun, ...(Number.isSafeInteger(e.pid) ? { pid: Number(e.pid) } : {}), ...(typeof dir === "string" ? { log: join(dir, "output.log") } : {}) };
228
+ call.startedAt = e.ts;
229
+ call.lastActivity = e.ts;
230
+ }
231
+ }
171
232
  else if (e.type === "slot-wait") {
172
233
  const call = byExec.get(String(e.exec));
173
234
  if (call && call.exec === e.exec) {
@@ -771,6 +832,8 @@ function forgetRemovedWorkflows(home, names, pruned) {
771
832
  paths.delete(wid);
772
833
  }
773
834
  }
835
+ /** Ledger types that determine holdOf/heldIn (other ledgerIndex projections do not affect holds). */
836
+ export const HOLD_ENTRY_TYPES = [JT.created, 'drain', 'undrain'];
774
837
  /** Drain: the one hold rule. drain/undrain entries apply to every workflow (no scope), one session's (`origin`) or one
775
838
  * workflow (`wid`). A workflow is held when the newest entry that applies to it is a drain recorded after it was created. */
776
839
  export function holdOf(ledger, wid, origin) {
@@ -890,7 +953,8 @@ export function queueWait(c, state, now = Date.now(), starting = orchestratorSta
890
953
  return undefined;
891
954
  if (starting)
892
955
  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;
956
+ // A command call takes no provider slot: only the orchestrator's start and a writer lock hold it back.
957
+ const settings = state.config?.settings ?? {}, pools = settings.pools ?? {}, wanted = c.command !== undefined ? undefined : c.poolWait?.model ?? c.model ?? settings.defaultModel;
894
958
  let providers = [];
895
959
  if (wanted && Object.hasOwn(pools, wanted)) {
896
960
  try {
@@ -1074,6 +1138,20 @@ export function formatUsage(u) {
1074
1138
  const n = (v) => v >= 1e6 ? `${(v / 1e6).toFixed(2)}M` : v >= 1e3 ? `${(v / 1e3).toFixed(1)}K` : String(v);
1075
1139
  return `${n(u.input)} in / ${n(u.output)} out${u.costUsd > 0 ? `, $${u.costUsd.toFixed(u.costUsd < 0.01 ? 4 : 2)}` : ""}`;
1076
1140
  }
1141
+ /** The CommandStatus of a command call (empty for an agent call): pid only while it is live. */
1142
+ export function commandStatus(c, now = Date.now()) {
1143
+ if (c.command === undefined)
1144
+ return {};
1145
+ const run = c.commandRun, data = c.result?.data, live = c.phase !== "sealed" && run !== undefined;
1146
+ return { command: commandLine(c.command),
1147
+ ...(live && run.pid !== undefined ? { pid: run.pid } : {}), ...(live && (run.attempt ?? 1) > 1 ? { attempt: run.attempt } : {}),
1148
+ ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1149
+ ...(typeof data?.exitCode === "number" ? { exitCode: data.exitCode } : {}), ...(typeof data?.signal === "string" ? { signal: data.signal } : {}) };
1150
+ }
1151
+ /** "pid 123" / "exit 3" / "SIGKILL" of a command call's status line (empty for an agent call or before the start). */
1152
+ export function commandFacts(c) {
1153
+ return [c.pid !== undefined ? `pid ${c.pid}` : "", c.attempt ? `attempt ${c.attempt}` : "", c.for ?? "", c.exitCode !== undefined ? `exit ${c.exitCode}` : "", c.signal ?? ""].filter(Boolean).join(", ");
1154
+ }
1077
1155
  /** P25, T10: Compact one workflow snapshot: per-call one-line facts, usage, open attention; no outputs or entries. */
1078
1156
  export function compactWorkflow(wf, leases) {
1079
1157
  const progress = progressOf(wf); // v12 §4
@@ -1085,7 +1163,7 @@ export function compactWorkflow(wf, leases) {
1085
1163
  ...(wf.planned !== undefined ? { planned: wf.planned } : {}), done: progress.done,
1086
1164
  calls: wf.calls.map(c => {
1087
1165
  const r = c.result, last = r?.output?.split("\n").map(l => l.trim()).filter(Boolean).at(-1);
1088
- return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
1166
+ return { key: c.key, gen: c.gen, callId: c.callId, phase: c.phase, ...modelStatus(c), ...commandStatus(c), ...(r ? { status: r.status, ok: r.ok } : {}),
1089
1167
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1090
1168
  ...(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 } : {}),
1091
1169
  ...(last ? { lastLine: clip(last, 200) } : {}), ...(r?.error ? { error: clip(r.error, 300) } : {}), ...(c.hibernated ? { hibernated: true } : {}),
@@ -1272,12 +1350,13 @@ export function statusBrief(home, options = {}) {
1272
1350
  const brief = (w) => {
1273
1351
  const p = progressOf(w), open = w.attention.filter(a => a.kind !== "finished");
1274
1352
  const calls = latestCalls(w).filter(c => c.phase !== "sealed" || (c.result && !c.result.ok) || c.notesPending).map((c) => {
1275
- const live = c.phase !== "sealed", quiet = c.lastActivity !== undefined ? now - c.lastActivity : undefined;
1276
- return { key: c.key, agent: c.agent, phase: c.phase, ...modelStatus(c), ...(c.model ? { model: c.model } : {}),
1353
+ // A command call shows its command, pid and age instead of a model, quiet time and tokens.
1354
+ const live = c.phase !== "sealed", quiet = c.lastActivity !== undefined ? now - c.lastActivity : undefined, agent = c.command === undefined;
1355
+ return { key: c.key, agent: c.agent, phase: c.phase, ...modelStatus(c), ...(c.model ? { model: c.model } : {}), ...commandStatus(c, now),
1277
1356
  ...(c.sharedWorktree ? { sharedWorktree: c.sharedWorktree } : {}),
1278
1357
  ...(live && c.startedAt !== undefined ? { for: age(now - c.startedAt) } : {}),
1279
- ...(live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1280
- ...(live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1358
+ ...(agent && live && c.phase !== "asking" && quiet !== undefined && quiet >= 60_000 ? { quiet: age(quiet) } : {}),
1359
+ ...(agent && live && c.startedAt !== undefined ? { tokens: tokens(c.usage) } : {}),
1281
1360
  ...(c.result ? { status: c.result.status, ...(c.result.error ? { error: clip(c.result.error, 200) } : {}) } : {}),
1282
1361
  ...(c.hibernated ? { hibernated: true } : {}), ...(c.answered ? { answered: c.answered } : {}), ...(c.answerForwarded ? { answerForwarded: c.answerForwarded } : {}), ...(live && c.writerWait ? { writerWait: c.writerWait } : {}),
1283
1362
  ...(live && byCall.get(c.callId) ? { lease: byCall.get(c.callId) } : {}),
@@ -18,6 +18,19 @@ import { readSettled, settledPath } from "./settled.js";
18
18
  import { publishFile } from "../kernel/mailbox.js";
19
19
  import { digestDir, factsDir, journalPath, pinnedDir, workflowDir } from "../paths.js";
20
20
  import { JT } from "../types.js";
21
+ /** The same record checks for asynchronous verification and a synchronous released-pins reload. */
22
+ function pinRecordFiles(dir, hash, record, verify) {
23
+ const { digest, ...body } = record;
24
+ if (body.snapshot !== hash || typeof digest !== 'string' || (verify && contentHash(body) !== digest))
25
+ return undefined;
26
+ if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
27
+ return undefined;
28
+ const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
29
+ if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
30
+ return undefined;
31
+ return { pins: body.pins, scriptPath: join(dir, 'script.js'), inputs: Object.fromEntries(Object.entries(body.inputs).map(([name, file]) => [name, join(dir, String(file))])),
32
+ originPath: body.origin === true ? join(dir, 'origin.jsonl') : undefined };
33
+ }
21
34
  /** Every file publishPins writes for one revision, relative to its directory (inputs given relative too). */
22
35
  function publishedFiles(inputs, origin) {
23
36
  return [...new Set(['script.js', 'args.json', 'agents.json', 'inputs.json', ...inputs, ...(origin ? ['origin.jsonl'] : [])])];
@@ -186,10 +199,31 @@ export class Store {
186
199
  /** Called after each append to a workflow journal (the event pump derives from it). */
187
200
  appended;
188
201
  ledgers;
189
- /** Terminal workflows materialized from their `pins.json` without verifying it: the revision and the intent to verify
190
- * it with (see ready). */
202
+ /** Terminal workflows awaiting file verification; reuse their immutable revision intent instead of a wrapper. */
191
203
  unverified = new Map();
192
204
  verifying = new Map();
205
+ /** A request can verify pins and then be refused before live work starts. Release those pins after the request. */
206
+ pinRest = new Map();
207
+ /** Share one accessor pair per store, so released history carries no per-workflow getter/setter closures. */
208
+ pinAccessors = (() => {
209
+ const store = this;
210
+ return { enumerable: true, configurable: true,
211
+ get() { const pins = store.releasedPins(this); this.pins = pins; store.restPins(this); return pins; },
212
+ set(pins) { Object.defineProperty(this, 'pins', { value: pins, enumerable: true, configurable: true, writable: true }); } };
213
+ })();
214
+ restPins(wf) {
215
+ if (wf.journal.closed || !wf.journal.resting || !Object.hasOwn(Object.getOwnPropertyDescriptor(wf, 'pins') ?? {}, 'value'))
216
+ return;
217
+ clearTimeout(this.pinRest.get(wf.wid));
218
+ const revision = wf.revision;
219
+ const timer = setTimeout(() => {
220
+ this.pinRest.delete(wf.wid);
221
+ if (this.workflows.get(wf.wid) === wf && wf.revision === revision && wf.journal.resting && !wf.journal.closed && !this.verifying.has(wf.wid))
222
+ this.releasePins(wf);
223
+ }, 1000);
224
+ timer.unref();
225
+ this.pinRest.set(wf.wid, timer);
226
+ }
193
227
  /** What the store looks up in the orchestrator ledger, folded over appended entries only (first entry wins, as find). */
194
228
  ix = { seen: 0, pruned: new Set(), created: new Set(), createIntents: [], createByRid: new Map(),
195
229
  createByWid: new Map(), reviseByRid: new Map(), rids: new Map() };
@@ -383,17 +417,16 @@ export class Store {
383
417
  async pinnedFiles(wid, revision, intent, verify = true) {
384
418
  const dir = revision === 1 ? pinnedDir(this.ledgers.home, wid) : join(pinnedDir(this.ledgers.home, wid), `r${revision}`);
385
419
  const ref = intent.pins ? undefined : intent.snapshot;
386
- if (ref) {
387
- const files = await this.recorded(dir, ref.hash, verify).catch(() => undefined);
388
- if (files)
389
- return files;
390
- }
420
+ const hash = ref?.hash ?? contentHash(intent.pins);
421
+ const recorded = await this.recorded(dir, hash, verify).catch(() => undefined);
422
+ if (recorded)
423
+ return recorded;
391
424
  const files = await this.publishPins(wid, revision, await this.pinned(intent));
392
- if (ref) {
425
+ {
393
426
  const hashes = {};
394
427
  for (const name of publishedFiles(Object.values(files.inputs).map(path => relative(dir, path)), files.originPath !== undefined))
395
428
  hashes[name] = await fileHash(join(dir, name));
396
- const body = { snapshot: ref.hash, pins: files.pins,
429
+ const body = { snapshot: hash, pins: files.pins,
397
430
  inputs: Object.fromEntries(Object.entries(files.inputs).map(([name, path]) => [name, relative(dir, path)])), origin: files.originPath !== undefined, files: hashes };
398
431
  await replaceFile(dir, 'pins.json', JSON.stringify({ ...body, digest: contentHash(body) }));
399
432
  }
@@ -402,21 +435,15 @@ export class Store {
402
435
  /** The files `pins.json` in `dir` records for snapshot `hash`, when the record and every file verify; else undefined.
403
436
  * Without `verify`, only the record's form is checked (its digest and the file hashes are left to `ready`). */
404
437
  async recorded(dir, hash, verify = true) {
405
- const { digest, ...body } = JSON.parse(await readFile(join(dir, 'pins.json'), 'utf8'));
406
- // The digest covers everything the record decides (pins, input names → files, origin, file hashes).
407
- if (body.snapshot !== hash || typeof digest !== 'string' || (verify && contentHash(body) !== digest))
408
- return undefined;
409
- if (!body.pins || typeof body.pins !== 'object' || !body.inputs || typeof body.inputs !== 'object' || !body.files || typeof body.files !== 'object')
410
- return undefined;
411
- const names = publishedFiles(Object.values(body.inputs).map(String), body.origin === true);
412
- if (names.length !== Object.keys(body.files).length || names.some(name => !Object.hasOwn(body.files, name)))
438
+ const record = JSON.parse(await readFile(join(dir, 'pins.json'), 'utf8'));
439
+ const files = pinRecordFiles(dir, hash, record, verify !== false);
440
+ if (!files)
413
441
  return undefined;
414
- if (verify)
415
- for (const name of names)
416
- if (body.files[name] !== await fileHash(join(dir, name)))
442
+ if (verify === true)
443
+ for (const name of Object.keys(record.files))
444
+ if (record.files[name] !== await fileHash(join(dir, name)))
417
445
  return undefined;
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))])),
419
- originPath: body.origin === true ? join(dir, 'origin.jsonl') : undefined };
446
+ return files;
420
447
  }
421
448
  /** P14, A2: Publish a new revision only after the engine has retired its predecessor. */
422
449
  async revise(intent) {
@@ -428,29 +455,91 @@ export class Store {
428
455
  Object.assign(wf, files, { revision });
429
456
  this.unverified.delete(wf.wid);
430
457
  }
458
+ pinIntent(wf) {
459
+ const intent = wf.revision === 1 ? this.index().createByWid.get(wf.wid)
460
+ : wf.journal.loaded === false ? wf.settled?.revised : wf.journal.entries().findLast(e => e.type === 'revised');
461
+ if (!intent)
462
+ throw new Error(`Missing pinned revision: ${wf.wid}@${wf.revision}`);
463
+ return intent;
464
+ }
465
+ /** Reload metadata with ready's form/digest checks and immutable-snapshot fallback, without rechecking file bytes. */
466
+ releasedPins(wf) {
467
+ const intent = this.pinIntent(wf), hash = intent.pins ? contentHash(intent.pins) : intent.snapshot.hash;
468
+ const dir = wf.revision === 1 ? pinnedDir(this.ledgers.home, wf.wid) : join(pinnedDir(this.ledgers.home, wf.wid), `r${wf.revision}`);
469
+ try {
470
+ const recorded = pinRecordFiles(dir, hash, JSON.parse(readFileSync(join(dir, 'pins.json'), 'utf8')), true);
471
+ if (recorded)
472
+ return recorded.pins;
473
+ }
474
+ catch { /* The same immutable fallback as ready's asynchronous reload. */ }
475
+ let source = intent.pins;
476
+ if (!source) {
477
+ const ref = intent.snapshot;
478
+ if (!ref)
479
+ throw new Error('Missing pinned snapshot');
480
+ const snapshot = JSON.parse(readFileSync(join(this.ledgers.home, ref.path), 'utf8'));
481
+ if (contentHash(snapshot) !== ref.hash || !snapshot.pins)
482
+ throw new Error('Staged snapshot hash mismatch');
483
+ source = snapshot.pins;
484
+ }
485
+ const { origin: _origin, inputs: _inputs, ...pins } = source;
486
+ return { ...pins, inputs: {} };
487
+ }
488
+ /** Whether the workflow's pins are in memory (not released behind the lazy accessor). */
489
+ pinsResident(wf) { return !Object.getOwnPropertyDescriptor(wf, 'pins')?.get; }
490
+ /** Release terminal pins. The next read caches checked metadata until the same idle release runs again. */
491
+ releasePins(wf) {
492
+ clearTimeout(this.pinRest.get(wf.wid));
493
+ this.pinRest.delete(wf.wid);
494
+ if (Object.getOwnPropertyDescriptor(wf, 'pins')?.get)
495
+ return;
496
+ Object.defineProperty(wf, 'pins', this.pinAccessors);
497
+ }
431
498
  /** A1: Verify the pinned files of a workflow materialized unverified (a terminal one) before its script, inputs, origin
432
499
  * or pins are used again: the record's digest and every file's hash, else the snapshot path (which republishes a
433
500
  * missing file and refuses a changed one). Nothing evaluates from a file that does not hash as recorded. Idempotent;
434
501
  * a refusal is raised again by every later call. */
435
502
  async ready(wf) {
436
- if (!this.unverified.has(wf.wid))
503
+ if (!this.unverified.has(wf.wid)) {
504
+ const revision = wf.revision, unloaded = Object.getOwnPropertyDescriptor(wf, 'pins')?.get;
505
+ if (unloaded) {
506
+ const intent = this.pinIntent(wf);
507
+ const dir = wf.revision === 1 ? pinnedDir(this.ledgers.home, wf.wid) : join(pinnedDir(this.ledgers.home, wf.wid), `r${wf.revision}`);
508
+ const hash = intent.pins ? contentHash(intent.pins) : intent.snapshot.hash;
509
+ const recorded = await this.recorded(dir, hash, 'record').catch(() => undefined);
510
+ // These files were verified in this process. If their cache record changed, recover the same pins from the
511
+ // immutable snapshot, without changing when file verification is required.
512
+ const pins = recorded?.pins ?? await (async () => {
513
+ const { origin: _origin, inputs: _inputs, ...kept } = await this.pinned(intent);
514
+ return { ...kept, inputs: {} };
515
+ })();
516
+ if (wf.revision === revision && Object.getOwnPropertyDescriptor(wf, 'pins')?.get === unloaded)
517
+ wf.pins = pins;
518
+ }
519
+ this.restPins(wf);
437
520
  return;
521
+ }
438
522
  let run = this.verifying.get(wf.wid);
439
523
  if (!run) {
440
524
  run = (async () => {
441
525
  const pending = this.unverified.get(wf.wid);
442
526
  if (!pending)
443
527
  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)
528
+ const revision = wf.revision, files = await this.pinnedFiles(wf.wid, revision, pending);
529
+ if (this.workflows.get(wf.wid) !== wf || this.unverified.get(wf.wid) !== pending)
530
+ return; // A revision or owner changed meanwhile.
531
+ if (revision === wf.revision)
448
532
  Object.assign(wf, files);
449
533
  this.unverified.delete(wf.wid);
450
534
  })().finally(() => this.verifying.delete(wf.wid));
451
535
  this.verifying.set(wf.wid, run);
452
536
  }
453
- await run;
537
+ try {
538
+ await run;
539
+ }
540
+ finally {
541
+ this.restPins(wf);
542
+ }
454
543
  }
455
544
  /** Whether a workflow's pinned files were verified in this process (see ready). */
456
545
  verified(wid) { return !this.unverified.has(wid); }
@@ -465,7 +554,8 @@ export class Store {
465
554
  : wf.journal.entries().find(e => e.type === 'revised' && e.revision === revision);
466
555
  if (!intent)
467
556
  throw new Error(`Missing pinned revision: ${wf.wid}@${revision}`);
468
- return { ...wf, revision, ...await this.pinnedFiles(wf.wid, revision, intent) };
557
+ const { wid, origin, cwd, journal, settled } = wf;
558
+ return { wid, origin, cwd, journal, ...(settled ? { settled } : {}), revision, ...await this.pinnedFiles(wid, revision, intent) };
469
559
  }
470
560
  /** A1, housekeeping: Wids with a committed pruned entry; they are gone and never materialize again. */
471
561
  pruned() { return this.index().pruned; }
@@ -481,6 +571,8 @@ export class Store {
481
571
  }
482
572
  /** A1, A2: Retire a pruned workflow's handle after its pruned entry is committed; nothing appends to it again. */
483
573
  async drop(wid) {
574
+ clearTimeout(this.pinRest.get(wid));
575
+ this.pinRest.delete(wid);
484
576
  const wf = this.workflows.get(wid);
485
577
  this.workflows.delete(wid);
486
578
  await wf?.journal.close();
@@ -536,7 +628,8 @@ export class Store {
536
628
  const current = settled.revised ?? intent, files = await this.pinnedFiles(wid, settled.revision, current, false);
537
629
  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
630
  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 });
631
+ this.releasePins(wf);
632
+ this.unverified.set(wid, current);
540
633
  lazy.onAppend = () => this.appended?.(wid);
541
634
  this.workflows.set(wid, wf);
542
635
  if (!this.index().created.has(String(intent.rid)))
@@ -563,8 +656,10 @@ export class Store {
563
656
  const ended = !first && entries.length > 0 && terminalEntry(entries) !== undefined;
564
657
  const files = first ?? (ended ? await this.pinnedFiles(wid, revision, current, false) : await this.pinnedFiles(wid, 1, intent));
565
658
  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 });
659
+ if (ended) {
660
+ this.releasePins(wf);
661
+ this.unverified.set(wid, current);
662
+ }
568
663
  }
569
664
  catch (error) {
570
665
  await journal.close();
@@ -583,5 +678,10 @@ export class Store {
583
678
  return wf;
584
679
  }
585
680
  /** A1: Close shared journals only after engine and executor activity retires. */
586
- async close() { await Promise.all([...this.workflows.values()].map(w => w.journal.close())); }
681
+ async close() {
682
+ for (const timer of this.pinRest.values())
683
+ clearTimeout(timer);
684
+ this.pinRest.clear();
685
+ await Promise.all([...this.workflows.values()].map(w => w.journal.close()));
686
+ }
587
687
  }
@@ -0,0 +1,98 @@
1
+ // Command calls (CallSpec.command): the launcher. A command runs detached in its own session under a tiny /bin/sh
2
+ // wrapper that runs it, then records its exit status atomically in the attempt directory (`exit.tmp`, renamed to `exit`)
3
+ // and exits with the same status. Its output (stdout and stderr, interleaved) is appended to `output.log` in the same
4
+ // directory through a descriptor the orchestrator opens, passes and closes: no pipe leads back into the orchestrator and
5
+ // no node process stays resident for the life of the command, so it outlives the orchestrator that started it.
6
+ import { spawn } from "node:child_process";
7
+ import { closeSync, openSync } from "node:fs";
8
+ import { mkdir, readFile, stat, open } from "node:fs/promises";
9
+ import { constants } from "node:os";
10
+ import { join } from "node:path";
11
+ import { captureStart } from "./proctable.js";
12
+ import { findOnPath } from "./launch.js";
13
+ export const COMMAND_LOG = "output.log";
14
+ export const COMMAND_EXIT = "exit";
15
+ /** The output a result carries: the last bytes of `output.log`. */
16
+ export const OUTPUT_TAIL_BYTES = 16 * 1024;
17
+ /** The wrapper: `$1` is the attempt directory, `$2` the absolute `mv`, the rest the command's argv. Its own steps use
18
+ * only shell builtins and that absolute `mv` with every expansion quoted, so they work under any environment the
19
+ * command gets (PATH unset or bogus, IFS, LC_*). The argv runs through `exec` in a subshell: it is always a program
20
+ * (looked up on the command's PATH; a shell builtin name such as `exit` is no builtin there, 127 when no program has
21
+ * it), and its end, however it comes, never skips recording the status. A program named by a path that does not exist
22
+ * is 127 before `exec`: some shells (bash 3.2, the macOS /bin/sh) report 126 for it instead. */
23
+ const WRAPPER = 'd="$1"; m="$2"; shift 2; ( case "$1" in (*/*) [ -e "$1" ] || { printf "%s: %s: not found\\n" "$0" "$1" >&2; exit 127; } ;; esac; exec "$@" ); s="$?"; printf "%s\\n" "$s" > "$d/exit.tmp" && "$m" -f "$d/exit.tmp" "$d/exit"; exit "$s"';
24
+ /** `mv` for the wrapper: from this process's PATH, else /bin or /usr/bin; resolved once. */
25
+ let mvPath;
26
+ export function resolveMv(PATH = process.env.PATH) {
27
+ mvPath ??= findOnPath("mv", PATH) ?? findOnPath("mv", "/bin:/usr/bin") ?? "/bin/mv";
28
+ return mvPath;
29
+ }
30
+ /** The argv the wrapper runs: an argv as given (a program, never shell syntax), a string through `/bin/sh -c`. */
31
+ export const commandArgv = (command) => typeof command === "string" ? ["/bin/sh", "-c", command] : [...command];
32
+ export async function spawnCommand(spec) {
33
+ await mkdir(spec.dir, { recursive: true });
34
+ const fd = openSync(join(spec.dir, COMMAND_LOG), "a");
35
+ try {
36
+ const mv = resolveMv(), argv = commandArgv(spec.command);
37
+ if (spec.proceed && !spec.proceed())
38
+ return undefined;
39
+ const child = spawn("/bin/sh", ["-c", WRAPPER, "dsa-command", spec.dir, mv, ...argv], { cwd: spec.cwd, env: spec.env, detached: true, stdio: ["ignore", fd, fd] });
40
+ const exited = new Promise(resolve => { child.once("exit", () => resolve()); child.once("error", () => resolve()); });
41
+ await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
42
+ child.unref();
43
+ const pid = child.pid;
44
+ const start = child.exitCode !== null || child.signalCode !== null ? "" : await captureStart(pid).catch(() => "");
45
+ return { pid, start, exited };
46
+ }
47
+ finally {
48
+ closeSync(fd);
49
+ }
50
+ }
51
+ /** The status the wrapper recorded, or undefined while there is none (the command runs, or ended without one). */
52
+ export async function readExitRecord(dir) {
53
+ const path = join(dir, COMMAND_EXIT);
54
+ let text, at;
55
+ try {
56
+ [text, at] = await Promise.all([readFile(path, "utf8"), stat(path).then(s => s.mtimeMs)]);
57
+ }
58
+ catch (error) {
59
+ if (error.code === "ENOENT")
60
+ return undefined;
61
+ throw error;
62
+ }
63
+ const status = Number(text.trim());
64
+ return Number.isInteger(status) && status >= 0 ? { status, at } : undefined;
65
+ }
66
+ const signalNames = new Map(Object.entries(constants.signals).map(([name, n]) => [n, name]));
67
+ /** How an exit status reads. The wrapper sees the status of a shell: a command killed by signal N exits 128+N. A command
68
+ * that itself exits with a status above 128 (`exit 130`) therefore reads as killed by that signal: the two cannot be
69
+ * told apart from the status alone (the shell convention). */
70
+ export function exitMeaning(status) {
71
+ const name = status > 128 ? signalNames.get(status - 128) : undefined;
72
+ return name ? { exitCode: null, signal: name } : { exitCode: status, signal: null };
73
+ }
74
+ /** The last `bytes` of a file, starting on a UTF-8 character boundary ("" when it is missing). */
75
+ export async function readTail(path, bytes = OUTPUT_TAIL_BYTES) {
76
+ const file = await open(path, "r").catch(error => { if (error.code === "ENOENT")
77
+ return undefined; throw error; });
78
+ if (!file)
79
+ return "";
80
+ try {
81
+ const { size } = await file.stat(), from = Math.max(0, size - bytes), buffer = Buffer.alloc(size - from);
82
+ for (let read = 0; read < buffer.length;) {
83
+ const { bytesRead } = await file.read(buffer, read, buffer.length - read, from + read);
84
+ if (!bytesRead)
85
+ break;
86
+ read += bytesRead;
87
+ }
88
+ // Skip continuation bytes (10xxxxxx) a cut in the middle of a character left at the start.
89
+ let skip = 0;
90
+ if (from > 0)
91
+ while (skip < buffer.length && skip < 4 && (buffer[skip] & 0xc0) === 0x80)
92
+ skip++;
93
+ return buffer.subarray(skip).toString("utf8");
94
+ }
95
+ finally {
96
+ await file.close();
97
+ }
98
+ }