pi-durable-subagents 1.0.41 → 1.0.43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.43
4
+
5
+ Steady-state cost no longer grows with history. Behaviour, file formats and recorded decisions are unchanged.
6
+ Measured on a copy of a real home (2084 workflows, 51k orchestrator ledger entries):
7
+
8
+ - Orchestrator memory: after a restart and 60 s idle, RSS 751 MiB in 1.0.42 and about 320 MiB now (under 200 MiB a
9
+ minute later); JS heap 468 MiB -> 91 MiB. A terminal workflow releases its pinned agents and sources after 1 s idle
10
+ and reloads them, checked as before, when a request needs them; a damaged pin still seals only that follow-up
11
+ `pin-failed`. The sweep keeps process identities only for executions that were never fenced (a fenced execution
12
+ keeps its tag, so a straggler is still found and killed after a restart). The orchestrator's outbox keeps only
13
+ pending requests in memory.
14
+ - Request intake costs the new work, not the history: the orchestrator folds its ledger incrementally and indexes open
15
+ requests, and decisions get a read-only view instead of a deep copy. With one request every 5 s the orchestrator used
16
+ 26.6 CPU s/min in 1.0.42 and 1.7 now; a pass with nothing new fell from 264 ms to 0.5 ms.
17
+ - CLI request lookups filter journal lines by bytes before decoding them and remember, per file, which request ids a
18
+ verified prefix does not contain (no envelopes are kept). `send`: 4.1 s -> 1.5 s CPU and 455 -> 130 MiB RSS; `run`
19
+ 3.7 -> 1.2 s; `describe --key` 1.7 -> 1.0 s. A cold `status` is unchanged.
20
+ - The pi session reads its own outbox incrementally instead of folding it on every poll.
21
+ - A restart reaches the evaluator in about 2.5 s. Upgrading from 1.0.42 needs no one-time pass (the first start took
22
+ 2.6 s on this home); upgrading from 1.0.41 still runs the one-time pass of 1.0.42 (about 40 s on this home).
23
+
24
+ ## 1.0.42
25
+
26
+ - The orchestrator starts in seconds on a large home. Measured on a copy of a real home (2084 workflows, 432 MB of
27
+ journals): a restart reached the evaluator after 82 s in 1.0.41 and after 3.5 s now; peak memory fell from 1.5 GiB
28
+ to about 710 MiB. Recovery records a receipt per recovered call and skips calls whose receipt is still current;
29
+ lookups that scanned every journal per call are indexed; pinned files of terminal workflows are checked when a
30
+ request needs them rather than at every start.
31
+ - Settled workflows open without decoding their journals. A rebuildable record under `cache/settled/` (validated
32
+ against the journal's inode, size, entry count and last line; any mismatch takes the full path and rewrites it)
33
+ stands in until something reads or appends to the journal, which then decodes it in full. Only terminal workflows
34
+ with nothing left for recovery to do are eligible.
35
+ - The first start after upgrading does a one-time pass that writes the receipts and records (about 40 s on the home
36
+ above).
37
+ - A pinned file that changed no longer stops the orchestrator or leaves a generation hanging: the generation's call
38
+ is sealed `failed` with `pin-failed: <file>` without starting a child, and a follow-up runs again once the file is
39
+ restored. Resume, revise and follow-up of such a workflow are refused with `pin-failed`.
40
+ - `status` says why a queued call does not move: `orchestrator starting (<age>)` while the orchestrator recovers
41
+ (also on the orchestrator line), the writer lock, a full provider (`waiting for a free slot (<provider> n/n)`) or a
42
+ used-up usage window. Without evidence it says only `queued`; an answered asker shows `queued (answered)`.
43
+ - The orchestrator ledger records `recovery: true` on its start entry and a `recovered` entry with the recovery time
44
+ and counts.
45
+
3
46
  ## 1.0.41
4
47
 
5
48
  - An answer that races the planned hibernation no longer strands its call. In 1.0.40 the parent forwarded an answer,
package/README.md CHANGED
@@ -228,6 +228,20 @@ script run from its bash tool): pi exports `DSA_SESSION`, and `run` names that
228
228
  session (see `--session` below). Other sessions' and a terminal's runs are
229
229
  not shown.
230
230
 
231
+ A queued subagent says why it does not start, as far as the orchestrator has
232
+ recorded it, and `queued` alone when nothing is known:
233
+
234
+ | phrase | meaning |
235
+ | --- | --- |
236
+ | `queued: orchestrator starting (12s)` | the orchestrator is still recovering workflows after a start; nothing is dispatched yet (`status` shows `orchestrator: <version> (pid N, starting 12s)`, the summary line `3 queued: orchestrator starting (12s)`) |
237
+ | `queued: <provider> usage window used up` | every provider it can start on is used up |
238
+ | `queued: waiting for the writer lock of <root>` | another call writes in the same worktree |
239
+ | `queued: waiting for a free slot (<provider> 4/4)` | every provider it can start on is full |
240
+ | `queued (answered)` / `queued (answered): <reason>` | an answered asker waiting to run again, with the reason when one is recorded (as above) |
241
+ | `paused · r resumes` | a drained workflow |
242
+
243
+ The CLI and the tool's status (`queued` per call) say the same.
244
+
231
245
  The list is also where you act. The footer shows the keys for the selected
232
246
  row: `Enter` watch, `s` steer, `f` follow-up, `x` stop (asks `y` first),
233
247
  `m` model, `a` answer. A one-line input opens at the bottom (paste works),
@@ -901,7 +915,21 @@ subagent only watching it.
901
915
  The restart ledger records the reason and initiator; after the next start,
902
916
  `status` shows who forced it and why for 24 hours.
903
917
 
904
- An orchestrator reads requests only after it has recovered its workflows, so
918
+ An orchestrator reads requests only after it has recovered its workflows. Its
919
+ start costs the unfinished work plus a small check per finished workflow, not
920
+ the size of finished history: a call whose recovery completed is recorded in its
921
+ journal and not read again until something concerns it, and a settled workflow
922
+ (ended, nothing open) opens without decoding its journal, from a rebuildable
923
+ record in `DSA_HOME/cache/settled`; the journal is read when a request needs it.
924
+ Pinned files of a finished workflow are verified when a resume, revise or
925
+ follow-up uses them; a changed file refuses that request (`pin-failed`). A
926
+ follow-up generation that is already open when its files no longer verify (at a
927
+ restart, say) is sealed `failed` without starting a subagent, with an error
928
+ starting `pin-failed: ` that names the file; the workflow ends again, and once
929
+ the file is restored a later follow-up runs. The first start after upgrading
930
+ makes a one-time pass that writes these records and receipts (tens of seconds
931
+ on a large home). The ledger's `orchestrator` entry has `recovery: true`, and a
932
+ `recovered` entry with the time taken follows when recovery ends. So
905
933
  a `restart` sent to one that just started waits for it (and says so); if no
906
934
  orchestrator reaches the request in time, `restart` exits 75 and the request
907
935
  stays pending — it is decided later, so do not send another.
@@ -1,11 +1,34 @@
1
1
  import { closeSync, openSync, readSync, statSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
- import { forgetJournalSnapshot, journalAppends, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
4
+ import { forgetJournalSnapshot, journalAppends, readJournalFold, readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
5
  import { journalPath } from "../../paths.js";
6
6
  import { CT, JT } from "../../types.js";
7
7
  import { openGeneration, readerWorkflowListing, releaseLoadedSettledJournals, releaseSettledJournals, SETTLED_RECHECK_MS, unresolvedAttention, workflowDigest, workflowDigestChecked } from "../../orchestrator/snapshot.js";
8
8
  import { readerHold, readerLedgerIdentity } from "../../orchestrator/reader-ledger.js";
9
+ /** Session-outbox reader: retain only pending identities and a verified position, not sent envelopes/history. */
10
+ export class PendingOutboxReader {
11
+ positions = new Map();
12
+ clear() { this.positions.clear(); }
13
+ read(path) {
14
+ const prior = this.positions.get(path);
15
+ this.positions.delete(path); // Never retry partially applied state after a failed read.
16
+ const record = readJournalFold(path, prior, () => new Set(), (pending, entry) => {
17
+ if (entry.type === 'sent')
18
+ pending.add(entry.request.rid);
19
+ else if (entry.type === 'resolved')
20
+ pending.delete(String(entry.rid));
21
+ }, { needles: ['"type":"sent"', '"type":"resolved"'] });
22
+ // A torn tail may be repaired at unchanged size; do not reuse that file identity as a committed position.
23
+ if (record && record.length === record.size) {
24
+ this.positions.set(path, record);
25
+ if (this.positions.size > 64)
26
+ this.positions.delete(this.positions.keys().next().value);
27
+ }
28
+ // A copy: the fold extends its state in place on the next read, so a returned set must not alias it.
29
+ return new Set(record?.state);
30
+ }
31
+ }
9
32
  const passes = new Map();
10
33
  export function workflows(home, origin, fresh = false) {
11
34
  const { record, names, checked: listed } = readerWorkflowListing(home, fresh), ix = record.state, mark = readerLedgerIdentity(record), now = Date.now();
@@ -1,7 +1,7 @@
1
1
  import { restartInputError } from "../../orchestrator/restart.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
- import { readJournalSnapshot } from "../../kernel/journal.js";
4
+ import { readJournalFold } from "../../kernel/journal.js";
5
5
  import { generationRids } from "../../orchestrator/notes.js";
6
6
  import { journalPath } from "../../paths.js";
7
7
  import { validateCallSpec } from "../../compat/spec.js";
@@ -59,7 +59,8 @@ export function followUpReceipt(home, rid, body) {
59
59
  const wid = send.to.split("/")[0].split("@")[0], path = journalPath(home, wid);
60
60
  if (!existsSync(path))
61
61
  return {};
62
- const log = readJournalSnapshot(path), opened = log.find(e => e.type === "generation" && generationRids(e).includes(rid));
62
+ const log = readJournalFold(path, undefined, () => [], (entries, entry) => { entries.push(entry); }, { needles: [JSON.stringify(rid)] })?.state ?? [];
63
+ const opened = log.find(e => e.type === "generation" && generationRids(e).includes(rid));
63
64
  if (opened)
64
65
  return { generation: Number(opened.gen), call: `${wid}/${String(opened.key)}` };
65
66
  const queued = log.find(e => e.type === "forward" && e.rid === rid);
@@ -5,13 +5,12 @@ import { fileURLToPath } from "node:url";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { defineTool } from "@earendil-works/pi-coding-agent";
7
7
  import { Outbox, scanInbox } from "../kernel/mailbox.js";
8
- import { readJournalSnapshot } from "../kernel/journal.js";
9
8
  import { readerLedger } from "../orchestrator/reader-ledger.js";
10
9
  import { OsLock } from "../platform/lock.js";
11
10
  import { launchOrchestrator } from "../platform/launch.js";
12
11
  import { dsaHome, orchInbox, orchLock, outboxRoot } from "../paths.js";
13
12
  import { CT, JT } from "../types.js";
14
- import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
13
+ import { PendingOutboxReader, attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
15
14
  import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
16
15
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
17
16
  import { parameters } from "./main/schema.js";
@@ -50,6 +49,7 @@ export function registerMain(pi, ui) {
50
49
  let queue = Promise.resolve(), timer;
51
50
  let reserved = [], notes = [], stopped = true, lastStarter = 0;
52
51
  let polling = false;
52
+ const pendingReader = new PendingOutboxReader();
53
53
  const sink = (text) => { notes.push(text); };
54
54
  function serial(fn) {
55
55
  const result = queue.then(fn);
@@ -66,14 +66,7 @@ export function registerMain(pi, ui) {
66
66
  }
67
67
  function pendingOutbox() { return pendingRids().size > 0; }
68
68
  function pendingRids() {
69
- const pending = new Set();
70
- for (const entry of readJournalSnapshot(join(outboxRoot(home), "outbox", `${sender}.jsonl`))) {
71
- if (entry.type === "sent")
72
- pending.add(entry.request.rid);
73
- else if (entry.type === "resolved")
74
- pending.delete(String(entry.rid));
75
- }
76
- return pending;
69
+ return pendingReader.read(join(outboxRoot(home), "outbox", `${sender}.jsonl`));
77
70
  }
78
71
  async function starter(submitting = false) {
79
72
  if (stopped)
@@ -145,6 +138,7 @@ export function registerMain(pi, ui) {
145
138
  await queue;
146
139
  await outbox?.close();
147
140
  outbox = undefined;
141
+ pendingReader.clear();
148
142
  if (noteSink === sink)
149
143
  noteSink = undefined;
150
144
  reserved = [];
@@ -439,7 +433,7 @@ export function registerMain(pi, ui) {
439
433
  "run (action optional for exactly one launch form): agent+task; tasks:[call specs] parallel; chain:[call specs] sequential ({previous}); workflow:'./script.js' or source (runs.run(key,spec), runs.all([...]), emit(value), args, runs.input(name)). Optional name, cwd, usageBudget, maxCalls, inputs, labels. With tasks/chain, top-level agent (without task), model, timeoutMs, budget, isolation, context, tools, skills, once, writer are defaults for every step (a step's own value wins); a workflow/source script sets them per runs.run call. timeoutMs is milliseconds of active time (a number); omit it unless a hard limit is needed. Explicit unknown agents are rejected BEFORE creation, with available names; unknown script agents fail only their call.",
440
434
  "agents: list names, descriptions, default models and source for this cwd; use these names for run.",
441
435
  "send to:'<wid>/<key>' (bare '<wid>' only for a single-call workflow): steer on a running call delivers at the next safe point (receipt in status/UI); a steer to a call waiting on its question interrupts the question and the subagent usually asks again — use answer to answer it; sealed → finished:<status> — use kind 'follow-up'. notify tells a call a decision without disturbing it; the reply's delivery says how: steered (running: it gets the note at its next safe point), held-until-answer (waiting on its question: never interrupts it, delivered after the answer) or noted (not running: nothing starts; the note is recorded and the call's next follow-up opens with every pending note; status shows notesPending). to may list several calls for steer, notify, follow-up and model: one request per call, each decided on its own, one result line per target (request:<id> sends <id>:1...<id>:n; a retry with the same list is safe). follow-up continues a sealed call as generation g+1 (reply generation) or queues after a running turn (reply delivery forwarded; if that turn ends without taking it, it opens g+1); follow-up model:'provider/id' or a pool name runs that generation on it. answer: give the qid (or just the call, or nothing when one question is open); to and rev are filled in. A question that needs the user's decision goes to the user; if you answer one yourself, tell the user what you chose. model ('provider/id' or a pool name — its first model not used up): a running call switches at its next provider request; an asking, hibernated or queued call launches on it when it runs again; the reply's model/effect (next-request|next-execution|next-generation) says which. status model = model actually used by the last request; switching = requested, not used yet; switchFailed = refused. A provider content refusal (ToS/usage policy) fails the call at once, not retried. Unknown targets list valid addresses. replaces:[rid] supersedes an earlier send.",
442
- "stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
436
+ "stop target:<wid|<wid>/<key>> is terminal stopped (usage and partial edits kept); a sealed call → already-sealed:<status>, a finished workflow → terminal:<status>. drain holds existing workflows reversibly (new runs unaffected); resume [wid] releases held workflows. restart (after an update) replaces the orchestrator with the installed version: refused with busy:<running executions> while any runs. Never force without the user's explicit approval: show the user the refusal's list first, then supply force:'<token>' and reason. Subagents cannot force; hibernated askers and queued calls do not block it. Never kill the orchestrator process. Commands that need the machine (benchmarks, timing) take a lease: tell the subagent to run them as `pi-durable-subagents hold machine [--shared] -- <command>` (FIFO; `hold <name> --slots N` admits N at a time; status lists lease holders and waiters). status: without wid, what runs (with its run labels, clipped), asks (with its answer address; hibernated:true holds no slot) or failed, writerWait: a call queued for its git worktree's writer lock (one call whose tools include edit/write runs per worktree; spec writer:false or isolation:'worktree' opts out), sharedWorktree names calls sharing observed edit/write roots (reminder), lease: a call holding or waiting for a resource lease, queued: why a queued call does not start (orchestrator starting while it recovers after a start, a used-up provider, a writer lock, full providers; absent when not known), finished workflows one line each, provider slots held/limit, the config in effect and providers whose usage window is used up (avoided until a probe finds them answering again), and the orchestrator version (with ', starting <age>' while it recovers; versionNote when it differs from the loaded one); wid: one workflow, outputs clipped; wid+tail:N: the last N lines of each call's result, wid+grep:'<regex>': only its matching lines (a JS regex run in-process: avoid nested quantifiers like (a+)+; first 2000 chars of a line, last 5000 lines; both: grep, then tail; at most 4000 chars per call); wid+key: one call's full result; full:true: everything. A run reply names calls already queued behind a writer lock (writerWait). A run's rid from {submitted:{rid}} works wherever a wid is expected. revise wid + workflow/source/args starts a revision.",
443
437
  "Control replies are {applied:true,rid} or {applied:false,reason,rid} when decided; otherwise {submitted:{rid}} after 10s.",
444
438
  ...(agents ? [`Available agents: ${agents}.`] : []),
445
439
  "User sees a summary line above the editor; ↓ on an empty editor (or /subagents) opens the list, Enter watches live OR finished calls (finished transcripts remain on disk) and expands finished workflows. List keys: s steer (paste-capable input), x stop (confirm y), m model, a answer when asked, f follow-up on finished calls; action feedback appears in footer.",
@@ -4,8 +4,8 @@ import { join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { Outbox, scanInbox } from "../kernel/mailbox.js";
7
- import { readJournalSnapshot } from "../kernel/journal.js";
8
- import { reduceLifecycle } from "../kernel/lifecycle.js";
7
+ import { readJournalFold, readJournalSnapshot } from "../kernel/journal.js";
8
+ import { isResolution } from "../kernel/lifecycle.js";
9
9
  import { OsLock } from "../platform/lock.js";
10
10
  import { launchOrchestrator } from "../platform/launch.js";
11
11
  import { orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
@@ -34,7 +34,7 @@ async function pendingOutboxes(home) {
34
34
  const names = await readdir(dir).catch(error => { if (error.code === "ENOENT")
35
35
  return []; throw error; });
36
36
  const ledger = readJournalSnapshot(orchLedger(home));
37
- const decided = reduceLifecycle(ledger.filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type))).resolved;
37
+ const decided = new Set(ledger.filter(isResolution).map(e => String(e.rid)));
38
38
  const created = new Set(ledger.filter(e => e.type === JT.created).map(e => String(e.rid)));
39
39
  for (const name of names.filter(n => n.endsWith(".jsonl"))) {
40
40
  const pending = new Map();
@@ -68,11 +68,15 @@ export async function start(home, env, starter = startOrchestrator) {
68
68
  /** P6, housekeeping: Wait (bounded) until the ledger resolves `rid`; undefined when it is still pending at the deadline. */
69
69
  export async function resolution(home, rid, timeoutMs, interval = 100) {
70
70
  const deadline = performance.now() + timeoutMs;
71
+ let journal;
71
72
  for (;;) {
72
- const records = readJournalSnapshot(orchLedger(home)).filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type));
73
- const resolved = reduceLifecycle(records).resolved.get(rid);
74
- if (resolved)
75
- return resolved.type === "rejected" ? { type: "rejected", reason: String(resolved.reason) } : { type: "applied" };
73
+ // The compact reader retains only this rid's first terminal decision and reads appended bytes on each poll.
74
+ journal = readJournalFold(orchLedger(home), journal, () => ({}), (state, entry) => {
75
+ if (!state.resolved && entry.rid === rid && isResolution(entry))
76
+ state.resolved = entry.type === "rejected" ? { type: "rejected", reason: String(entry.reason) } : { type: "applied" };
77
+ }, { needles: [JSON.stringify(rid)] });
78
+ if (journal?.state.resolved)
79
+ return journal.state.resolved;
76
80
  if (performance.now() >= deadline)
77
81
  return undefined;
78
82
  await delay(interval);
@@ -132,9 +136,15 @@ async function withSender(home, fn) {
132
136
  try {
133
137
  const outbox = await Outbox.open(outboxRoot(home), sender, () => orchInbox(home));
134
138
  try {
135
- const records = readJournalSnapshot(orchLedger(home)).filter(e => ["admitted", "applied", "rejected", "withdrawn"].includes(e.type));
136
- for (const rid of reduceLifecycle(records).resolved.keys())
137
- await outbox.markResolved(rid);
139
+ const pending = outbox.pendingRids();
140
+ if (pending.size) {
141
+ const resolved = readJournalFold(orchLedger(home), undefined, () => [], (rids, entry) => {
142
+ if (isResolution(entry) && pending.delete(String(entry.rid)))
143
+ rids.push(String(entry.rid));
144
+ }, { needles: [...pending].map(rid => JSON.stringify(rid)) });
145
+ for (const rid of resolved?.state ?? [])
146
+ await outbox.markResolved(rid);
147
+ }
138
148
  await outbox.republishPending();
139
149
  return await fn(outbox, sender);
140
150
  }
package/dist/cli/main.js CHANGED
@@ -7,7 +7,7 @@ import { setTimeout as delay } from "node:timers/promises";
7
7
  import { dsaHome } from "../paths.js";
8
8
  import { readJournalSnapshot } from "../kernel/journal.js";
9
9
  import { journalPath, orchLedger } from "../paths.js";
10
- import { answerForwardedNote, modelStatusText, allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
10
+ import { answerForwardedNote, modelStatusText, queuedText, allWorkflows, eventsFromEntries, heldWorkflows, isLive, formatUsage, renderEvent, statusDetail, statusView, workflowSnapshot, compactWorkflow, labelsText, outputSelect, statusCompactDetail } from "../orchestrator/snapshot.js";
11
11
  import { statsLine } from "../orchestrator/stats.js";
12
12
  import { resolution, start, startOrchestrator, submit } from "./control.js";
13
13
  import { doctor, renderDoctor, size } from "./doctor.js";
@@ -101,10 +101,20 @@ export function parseArgs(args) {
101
101
  const clip = (text, n) => text.length > n ? `${text.slice(0, n)}…` : text;
102
102
  /** Notes recorded for a call that is not running (send kind "notify"); its next follow-up carries them. */
103
103
  const notesLine = (n) => n ? ` · ${n} note${n > 1 ? "s" : ""} pending` : "";
104
- /** An answered asker waiting for a slot; nothing while a drain holds its workflow (it waits for resume, as the UI says). */
104
+ /** Why a queued call does not start, when the orchestrator ledger says so (an answered asker: "(answered)" first); nothing
105
+ * while a drain holds its workflow (it waits for resume, as the UI says). A writer-lock wait has its own suffix. */
105
106
  const answeredNote = (c, paused) => {
106
107
  const forwarded = answerForwardedNote(c);
107
- return forwarded ? `: ${forwarded}` : c.phase === "queued" && c.answered && !paused ? " (answered, waiting for a slot)" : "";
108
+ if (forwarded)
109
+ return `: ${forwarded}`;
110
+ if (c.phase !== "queued" || paused)
111
+ return "";
112
+ const why = c.queued ?? (c.queuedFor ? queuedText(c.queuedFor) : undefined);
113
+ if (c.writerWait && why === `waiting for the writer lock of ${c.writerWait.root}`)
114
+ return c.answered ? " (answered)" : ""; // its own suffix says it
115
+ if (c.answered)
116
+ return why ? ` (answered): ${why}` : " (answered)"; // no slot claim without a full provider
117
+ return why ? `: ${why}` : "";
108
118
  };
109
119
  /** P25, T10: Render journal-derived status (one line per call, last output line only) without live orchestrator memory. */
110
120
  export function renderStatus(wf) {
@@ -4,20 +4,20 @@
4
4
  import { existsSync, readFileSync } from "node:fs";
5
5
  import { join, resolve } from "node:path";
6
6
  import { setTimeout as delay } from "node:timers/promises";
7
- import { readJournalSnapshot } from "../kernel/journal.js";
8
- import { reduceLifecycle } from "../kernel/lifecycle.js";
7
+ import { findJournalEntry, readJournalFold, readJournalSnapshot } from "../kernel/journal.js";
8
+ import { isResolution, lifecycleResolution } from "../kernel/lifecycle.js";
9
9
  import { journalPath, orchLedger, pinnedDir } from "../paths.js";
10
10
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, REQUEST_ID, requestId, requestRid, RequestsBusy, SESSION_ID, specDigest } from "../requests.js";
11
- import { NOTIFY_SINCE, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
11
+ import { NOTIFY_SINCE, HOLD_ENTRY_TYPES, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
12
  import { leaseCalls, leaseState } from "../platform/lease.js";
13
13
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
14
14
  import { discoverAgents } from "../compat/agents.js";
15
15
  import { JT } from "../types.js";
16
16
  import { startOrchestrator, submitIdentified } from "./control.js";
17
- import { endedExecs, fenceReason } from "../events/fence.js";
17
+ import { FENCE_LEDGER_TYPES, endedExecs, fenceReason } from "../events/fence.js";
18
18
  import { parseLabels } from "../events/labels.js";
19
19
  import { foldWaits, leaseWaits, waitsOf } from "../events/waiting.js";
20
- import { emptyLedger, foldLedger } from "../orchestrator/ledger.js";
20
+ import { LEDGER_ENTRY_TYPES, emptyLedger, foldLedger } from "../orchestrator/ledger.js";
21
21
  export const EXIT = { ok: 0, rejected: 1, conflict: 3, pending: 75 };
22
22
  /** Strict `--name value` / `--flag` parsing; unknown or repeated options are errors, except those given in `repeated`
23
23
  * (every value is kept, in order, in `lists`). */
@@ -55,26 +55,34 @@ function waitMs(values, ctx) {
55
55
  throw new Error("--wait-ms needs a non-negative integer");
56
56
  return raw !== undefined ? Number(raw) : ctx.waitMs ?? 60_000;
57
57
  }
58
- function ledger(home) { return readJournalSnapshot(orchLedger(home)); }
58
+ function ledger(home, needles) {
59
+ return readJournalFold(orchLedger(home), undefined, () => [], (entries, entry) => { entries.push(entry); }, { needles })?.state ?? [];
60
+ }
61
+ // Shared state consulted by describe's waits/holds/fence readers; workflow/request facts also match their identity.
62
+ export const descriptionNeedles = [...new Set(['pruned', ...HOLD_ENTRY_TYPES, ...LEDGER_ENTRY_TYPES, ...FENCE_LEDGER_TYPES])]
63
+ .map(type => `"type":${JSON.stringify(type)}`);
59
64
  function decision(entries, rid) {
60
- const records = entries.filter(e => [JT.admitted, JT.applied, JT.rejected, JT.withdrawn].includes(e.type));
61
- return reduceLifecycle(records).resolved.get(rid);
65
+ return lifecycleResolution(entries, rid);
62
66
  }
63
67
  const createdBy = (entries, rid) => entries.find(e => e.type === JT.created && e.rid === rid);
64
68
  async function stdin() { const chunks = []; for await (const chunk of process.stdin)
65
69
  chunks.push(chunk); return Buffer.concat(chunks).toString("utf8"); }
66
70
  /** The state of a request id (`{request}`) or a workflow (`{wid}`), with full texts (no clipping). */
67
71
  export async function describe(home, key, now = Date.now()) {
68
- const entries = ledger(home);
69
72
  if ("wid" in key)
70
- return describeWorkflow(home, key.wid, entries, now);
71
- const rid = requestRid(key.request), found = await findRequest(home, rid);
73
+ return describeWorkflow(home, key.wid, ledger(home, [...descriptionNeedles, JSON.stringify(key.wid)]), now);
74
+ const rid = requestRid(key.request), entries = ledger(home, [JSON.stringify(rid)]);
75
+ // A committed admitted envelope is immutable; reuse the same read when it already contains it.
76
+ const admitted = entries.find(e => e.type === 'request' && e.request.rid === rid);
77
+ const found = admitted ? { request: admitted.request, admitted: true } : await findRequest(home, rid);
72
78
  if (!found)
73
79
  return { state: "absent", request: key.request };
74
80
  const head = { request: key.request, kind: found.request.kind, spec_digest: specDigest(found.request), ...labelsOf(found.request) };
75
81
  const decided = decision(entries, rid), created = createdBy(entries, rid);
76
- if (found.request.kind === "run" && created)
77
- return { ...await describeWorkflow(home, String(created.wid), entries, now), ...head };
82
+ if (found.request.kind === "run" && created) {
83
+ const wid = String(created.wid), workflowEntries = ledger(home, [...descriptionNeedles, JSON.stringify(wid)]);
84
+ return { ...describeWorkflow(home, wid, workflowEntries, now), ...head };
85
+ }
78
86
  if (decided?.type === "rejected")
79
87
  return { state: "rejected", ...head, reason: String(decided.reason) };
80
88
  // A send or stop has no workflow of its own: its decision is the outcome.
@@ -88,9 +96,11 @@ function labelsOf(request) {
88
96
  return labels && typeof labels === "object" && Object.keys(labels).length ? { labels } : {};
89
97
  }
90
98
  /** The admitted run request that created `wid` (the ledger keeps it after a prune). */
91
- function runOf(entries, wid) {
99
+ function runOf(home, entries, wid) {
92
100
  const created = entries.find(e => e.type === JT.created && e.wid === wid);
93
- return { created, run: created ? entries.find(e => e.type === "request" && e.request.rid === created.rid)?.request : undefined };
101
+ const rid = created?.rid;
102
+ const run = created ? findJournalEntry(orchLedger(home), e => e.type === "request" && e.request.rid === rid, { needles: [JSON.stringify(rid)] })?.request : undefined;
103
+ return { created, run };
94
104
  }
95
105
  /** The pinned agents of a workflow revision, read once on demand (the waiting check needs the model of a call that names none). */
96
106
  function pinnedAgentModel(home, wid, rev) {
@@ -111,7 +121,7 @@ function describeWorkflow(home, wid, entries, now) {
111
121
  const pruned = entries.find(e => e.type === "pruned" && e.wid === wid);
112
122
  if (pruned)
113
123
  return { state: "pruned", wid, pruned: { ...(pruned.status !== undefined ? { status: String(pruned.status) } : {}), endedAt: Number(pruned.endedAt) },
114
- ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(entries, wid).run) };
124
+ ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(home, entries, wid).run) };
115
125
  if (!/^[^/\\\0]+$/.test(wid) || wid === "." || wid === ".." || !existsSync(journalPath(home, wid)))
116
126
  return { state: "absent", wid };
117
127
  // The snapshot and the journal the wait fold reads must be the same bytes (a writer-wait appended between the two reads
@@ -121,7 +131,7 @@ function describeWorkflow(home, wid, entries, now) {
121
131
  journal = again;
122
132
  wf = workflowSnapshot(home, wid);
123
133
  }
124
- const { created, run } = runOf(entries, wid), id = created ? requestId(String(created.rid)) : undefined;
134
+ const { created, run } = runOf(home, entries, wid), id = created ? requestId(String(created.rid)) : undefined;
125
135
  const admitted = id ? run : undefined;
126
136
  const lstate = leaseState(home), slots = slotsView(home, now), leases = leaseCalls(lstate, now);
127
137
  // The same fold and decision the orchestrator's collector uses, from the disk snapshots.
@@ -187,17 +197,25 @@ export async function describeCommand(args, ctx) {
187
197
  ctx.write(values.json ? JSON.stringify(d, null, 2) : renderDescription(d));
188
198
  return 0;
189
199
  }
190
- /** Wait (bounded) for the request's decision: a run's `created` wid, or the lifecycle resolution. */
191
- async function outcome(home, rid, run, timeoutMs) {
200
+ /** Wait (bounded) for the request's decision: a run's `created` wid, or the lifecycle resolution. A command can carry
201
+ * its position across the pre-submit check and the wait; each call still stats and reads fresh appended bytes. */
202
+ async function outcome(home, rid, run, timeoutMs, poll = {}) {
192
203
  const deadline = performance.now() + timeoutMs;
193
204
  for (;;) {
194
- const entries = ledger(home), created = run ? createdBy(entries, rid) : undefined;
195
- if (created)
196
- return { type: "applied", wid: String(created.wid) };
197
- const decided = decision(entries, rid);
198
- if (decided?.type === "rejected")
199
- return { type: "rejected", reason: String(decided.reason) };
200
- if (decided && !run)
205
+ poll.journal = readJournalFold(orchLedger(home), poll.journal, () => ({}), (state, entry) => {
206
+ if (entry.rid !== rid)
207
+ return;
208
+ if (run && entry.type === JT.created && state.created === undefined)
209
+ state.created = String(entry.wid);
210
+ if (!state.decided && isResolution(entry))
211
+ state.decided = entry.type === "rejected" ? { type: "rejected", reason: String(entry.reason) } : { type: "applied" };
212
+ }, { needles: [JSON.stringify(rid)] });
213
+ const state = poll.journal?.state;
214
+ if (state?.created !== undefined)
215
+ return { type: "applied", wid: state.created };
216
+ if (state?.decided?.type === "rejected")
217
+ return state.decided;
218
+ if (state?.decided && !run)
201
219
  return { type: "applied" };
202
220
  if (performance.now() >= deadline)
203
221
  return undefined;
@@ -218,7 +236,7 @@ function pending(ctx, id, json, why = "") {
218
236
  async function submitAndWait(ctx, seen, id, kind, body, cond, wait, json) {
219
237
  // `created` is false only when the id was already decided before this invocation submitted (decisions are
220
238
  // monotonic); racing first attempts may all report created — the wid is what identifies the run.
221
- const rid = requestRid(id), earlier = Boolean(await outcome(ctx.home, rid, kind === "run", 0));
239
+ const rid = requestRid(id), poll = {}, earlier = Boolean(await outcome(ctx.home, rid, kind === "run", 0, poll));
222
240
  let sent;
223
241
  try {
224
242
  sent = await submitIdentified(ctx.home, rid, kind, body, cond, ctx.env, ctx.starter);
@@ -234,7 +252,7 @@ async function submitAndWait(ctx, seen, id, kind, body, cond, wait, json) {
234
252
  }
235
253
  if ("conflict" in sent)
236
254
  return { code: await conflict(ctx, id, sent.digest, json) };
237
- const result = await outcome(ctx.home, rid, kind === "run", wait);
255
+ const result = await outcome(ctx.home, rid, kind === "run", wait, poll);
238
256
  if (!result)
239
257
  return { code: pending(ctx, id, json) };
240
258
  const admitted = (await findRequest(ctx.home, rid))?.request;
@@ -337,11 +355,11 @@ async function runRequest(args, ctx, seen) {
337
355
  async function widOf(home, head) {
338
356
  if (!REQUEST_ID.test(head))
339
357
  return { wid: head };
340
- const rid = requestRid(head), created = createdBy(ledger(home), rid);
358
+ const rid = requestRid(head), created = createdBy(ledger(home, [JSON.stringify(rid)]), rid);
341
359
  if (created)
342
360
  return { wid: String(created.wid) };
343
361
  const found = await findRequest(home, rid);
344
- return found?.request.kind === "run" && decision(ledger(home), rid)?.type !== "rejected" ? { pending: true } : { wid: head };
362
+ return found?.request.kind === "run" && decision(ledger(home, [JSON.stringify(rid)]), rid)?.type !== "rejected" ? { pending: true } : { wid: head };
345
363
  }
346
364
  /** `--to <run-id>[/<key>] | <wid>/<key>` (+ `--call <key>`) → `<wid>/<key>`; a run of one call implies its key. */
347
365
  async function target(home, to, call, prior) {
@@ -436,7 +454,8 @@ async function sendRequest(args, ctx, seen, batch) {
436
454
  seen.json = json;
437
455
  if (!id || !to || !kind || positionals.length)
438
456
  throw new Error(SEND_USAGE);
439
- const rid = requestRid(id), prior = (await findRequest(ctx.home, rid))?.request;
457
+ const related = [`${id}:1`, to.split('/')[0]].filter(value => REQUEST_ID.test(value)).map(requestRid);
458
+ const rid = requestRid(id), prior = (await findRequest(ctx.home, rid, related))?.request;
440
459
  // A single send under an id that names a send to several calls (<id>:1 ...) is other content.
441
460
  if (!prior && await namesMany(ctx.home, id)) {
442
461
  ctx.write(json ? JSON.stringify({ request: id, error: "request-conflict" }) : `${id}: request-conflict - this id names a send to several calls; use a new id`);
@@ -505,7 +524,7 @@ function decided(ctx, id, done, json) {
505
524
  const followed = done.sent.request.kind === "send" ? followUpReceipt(ctx.home, done.sent.request.rid, done.sent.request.body) : {};
506
525
  const opened = followed.generation !== undefined ? followed : undefined;
507
526
  // A notify says how it went (steered, held-until-answer or noted); a model send which model and when it applies.
508
- const notified = done.sent.request.kind === "send" ? sendReceipt(ledger(ctx.home), done.sent.request.rid) : {};
527
+ const notified = done.sent.request.kind === "send" ? sendReceipt(ledger(ctx.home, [JSON.stringify(done.sent.request.rid)]), done.sent.request.rid) : {};
509
528
  const receipt = notified.delivery ? { delivery: notified.delivery, note: notified.note }
510
529
  : followed.delivery ? { delivery: followed.delivery, call: followed.call, note: followed.note } : {};
511
530
  const reply = { request: id, applied: true, ...(opened ? { generation: opened.generation, call: opened.call } : {}), ...receipt, spec_digest: done.sent.digest };
@@ -2,6 +2,8 @@
2
2
  // committed journal entries; `limit` restricts the view to the first `limit` entries (the deriver may read only entries
3
3
  // before the one it derives, so a re-derivation after a crash sees the same history).
4
4
  import { JT } from "../types.js";
5
+ /** Orchestrator entry types read by fenceReason; workflow entries are read separately. */
6
+ export const FENCE_LEDGER_TYPES = ['restart', 'orchestrator', 'orchestrator-exit'];
5
7
  /** Executions whose fence did NOT interrupt work: every execution ends with a fence; one interrupted work only when
6
8
  * the execution neither settled (its turn ended) before it nor hibernated (it waits for an answer), and was not sealed
7
9
  * on purpose: a seal ends an execution on purpose unless its outcome is `unknown` (a `once` call cut off in a tool) or
@@ -290,7 +290,11 @@ export class EventPump {
290
290
  const wf = this.options.store.workflows.get(wid);
291
291
  if (!wf)
292
292
  continue;
293
- const entries = committed(wf.journal), start = this.marks.get(wid) ?? 0;
293
+ const start = this.marks.get(wid) ?? 0;
294
+ // A journal not decoded (a settled workflow) is decoded only when it has entries not derived yet.
295
+ if (wf.journal.loaded === false && (wf.journal.count?.() ?? Infinity) <= start)
296
+ continue;
297
+ const entries = committed(wf.journal);
294
298
  if (entries.length <= start)
295
299
  continue;
296
300
  const id = this.identity(wid);
@@ -332,7 +336,7 @@ export class EventPump {
332
336
  let v = verdicts.get(wid);
333
337
  if (v === undefined) {
334
338
  const wf = this.options.store.workflows.get(wid);
335
- v = wf ? quiet(wid, committed(wf.journal)) : pruned.has(wid);
339
+ v = wf ? (wf.journal.loaded === false && wf.settled ? wf.settled.quiet : quiet(wid, committed(wf.journal))) : pruned.has(wid);
336
340
  verdicts.set(wid, v);
337
341
  }
338
342
  return v;
@@ -419,15 +419,25 @@ export function waitCollector(src) {
419
419
  const current = new Map(), meta = new Map(), present = new Set();
420
420
  for (const wf of src.workflows()) {
421
421
  present.add(wf.wid);
422
+ // A journal not decoded is a settled workflow's (orchestrator/settled.ts): it has no live call, so no wait.
423
+ if (wf.journal.loaded === false)
424
+ continue;
422
425
  const entries = wf.journal.entries();
423
426
  let hit = folds.get(wf.wid);
424
427
  if (hit?.entries !== entries) {
425
428
  hit = { entries, fold: foldWaits(wf.wid, entries, hit?.fold) };
426
429
  folds.set(wf.wid, hit);
427
430
  }
428
- if (!hit.fold.calls.size)
431
+ if (!liveWaitCalls(hit.fold).length)
429
432
  continue;
430
- const agents = wf.pins?.agents;
433
+ // A pins load that fails (released pins, damaged record) leaves the agents unknown, as when pins are absent.
434
+ let agents;
435
+ try {
436
+ agents = wf.pins?.agents;
437
+ }
438
+ catch {
439
+ agents = undefined;
440
+ }
431
441
  for (const [call, wait] of waitsOf(hit.fold, env, agents ? name => agents.find(a => a.name === name)?.model : undefined)) {
432
442
  const c = hit.fold.calls.get(call), m = runs.meta.get(wf.wid);
433
443
  current.set(call, wait);