pi-durable-subagents 1.0.37 → 1.0.39

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.39
4
+
5
+ - A pi session reads only its own workflows. Since 1.0.30 the UI shows only the workflows of its session, yet the pi
6
+ process read, folded and cached every workflow journal of the machine every 500 ms. Ownership is now decided from
7
+ the orchestrator ledger (the origin of a workflow's create-intent or `created`, or the session its run named)
8
+ before any journal is opened, so other sessions' journals are never opened, stat'ed or cached by a pi process.
9
+ Measured on a home with 1,132 workflows (load 16-27): the first refresh of a busy session fell from 9.4 s to 1.6 s,
10
+ a steady refresh from 86 ms to 7 ms and the process RSS from 696 MiB to 325 MiB; a session without workflows went
11
+ from 17.7 s to 0.4 s and 683 MiB to 166 MiB. A session that many runs name (here 759 workflows) still reads all of
12
+ them, so its gain is smaller. `scripts/bench-ui.ts` measures this (read-only).
13
+ - Session start no longer scans every journal: the starter checks whether an orchestrator holds its lock first and
14
+ scans only when none does; the scan stops at the first unfinished workflow and does not keep the journals it read.
15
+ The paused notice at session start and the pause on quit read only the workflows the session started.
16
+ - A workflow directory the ledger does not know (only a hand-made or damaged home has one) is attributed by its
17
+ journal's first entry, read once; a failed read is retried once the file changes.
18
+ - The CLI (`status`, `restart`) and the orchestrator are unchanged.
19
+
20
+ ## 1.0.38
21
+
22
+ - An answer to any open question of a call reaches it. A call whose question was interrupted (by a steer) and that
23
+ asked again in other words while waiting no longer orphans the answer to the first question: a waiting subagent
24
+ takes it as the result of its current question, a hibernated one resumes with it (also when the answer was sent
25
+ before it hibernated), and a subagent that is not waiting gets it as a message at its next safe point. Before, an
26
+ answer to a question other than the one the subagent waited on was held until a later ask, usually forever, and
27
+ then retired.
28
+ - One rule for answers: an answer (or the answer a hibernated asker resumes with) to an open question is delivered
29
+ once, at the first chance, never held. A waiting subagent prefers the answer to the question it waits on when
30
+ several are pending. Follow-ups sent before a pending answer still enter ahead of it, notifies after it.
31
+ - An answer to an earlier question that ends the wait on a later one supersedes the later question: the subagent is
32
+ told it was withdrawn and to ask again if it still needs it, its attention item resolves `superseded` (at once when
33
+ the answer is bound to a hibernated call), `status` no longer shows the call `asking`, and a later answer to it is
34
+ refused `stale-rev`.
35
+ - A question revision gets at most one answer receipt. An answer sent before the call hibernated and bound to the
36
+ hibernation is withdrawn from the subagent's inbox; any further envelope for an answered, superseded or stale
37
+ revision is dropped with a receipt, so nothing waits on it. These records survive a crash between their writes: a
38
+ supersession is derived from the binding that made it, an adoption whose withdrawal went out is completed first, and
39
+ a bound answer the session had already closed is settled without waiting for a receipt. An answer bound to a revision
40
+ the subagent has already asked again is not delivered: the call hibernates again and the parent is asked the newer
41
+ revision.
42
+ - A follow-up generation no longer re-opens the questions of the session it continues (its subagent would refuse
43
+ their answers). Items that 1.0.37 re-opened in a running generation are resolved `carried` at orchestrator start.
44
+ - Follow-ups queued while a call waited on its question reach the resumed model before the answer, in send order.
45
+
3
46
  ## 1.0.37
4
47
 
5
48
  - The process table runs `ps` by its absolute path (`/bin/ps`), so an orchestrator started with a minimal PATH keeps
package/README.md CHANGED
@@ -122,7 +122,7 @@ it something. Each verb means one thing, and a refusal says what would work:
122
122
  | `send steer` | a running subagent | Reaches it at its next safe point. To a finished one: refused, use `follow-up`; To one waiting on its question: it interrupts the question, and the subagent usually asks again; `answer` answers it. |
123
123
  | `send notify` | any subagent | Tells it a decision without disturbing it. The reply's `delivery` says how: `steered` (running: it gets the note at its next safe point, like a steer), `held-until-answer` (waiting on its question: never interrupts it; it gets the note at the first safe point after the answer) or `noted` (not running: nothing starts; the note is recorded, and the call's next follow-up opens with it). |
124
124
  | `send follow-up` | any subagent | A finished one continues in the same session as a new generation (`key@2`); the reply names it (`generation`, `call`). A running one gets it after its current turn; the reply says `delivery: forwarded` and names the running generation (`call: <wid>/<key>@<gen>`). With `model` (a model or a pool's name), the generation that takes it runs on it. |
125
- | `send answer` | an open question | Answers it once. |
125
+ | `send answer` | an open question | Answers it once, at the first chance: as the result of the question it waits on, or (when it no longer waits on that question, say after a steer) as a message at its next safe point. An answer to an earlier question while it waits on a later one ends the later one: that question is withdrawn (`superseded`, the subagent is told to ask again if it still needs it) and takes no answer. |
126
126
  | `send model` | any subagent | A running one switches at its next request; one asking, hibernated or waiting for a slot launches on it when it runs again. A pool's name picks its first model that is not used up (and, for a running call, has a free slot); the reply names the model picked, and a call from that pool stays in it. |
127
127
  | `stop` | a subagent or a workflow | Final: `stopped`, usage kept, edits left as they are. |
128
128
  | `drain` / `resume` | existing workflows | A reversible hold; runs started later are not held. |
@@ -577,6 +577,15 @@ read, in a burst each time a call ends), `pid` and `at` (when it was
577
577
  written). The orchestrator writes these to `orchestrator-stats.json` every
578
578
  10 s; they are shown only while that process runs.
579
579
 
580
+ A pi session reads only its own workflows. Which workflows are its own comes
581
+ from the orchestrator ledger, so its dock and list never open the journals or
582
+ transcripts of other sessions' workflows, however many the machine has. While
583
+ an orchestrator runs, a pi session does not look for pending work at all;
584
+ without one, it looks until it finds the first unfinished workflow and keeps
585
+ none of the journals it read. `node scripts/bench-ui.ts --owner=main:<pi
586
+ session id>` measures what a session pays on its main thread for a given
587
+ `DSA_HOME` (read-only).
588
+
580
589
  ### Where the orchestrator starts
581
590
 
582
591
  Whatever needs it first starts the orchestrator: a pi session, a CLI
@@ -3,7 +3,14 @@ import { CT } from "../../types.js";
3
3
  * session of the previous one (P37), but request sequences are per recipient (P5): records addressed to an earlier
4
4
  * generation stay in history and are skipped here: segments opened by another call's execution marker are foreign. */
5
5
  export function recover(entries, call) {
6
- const records = [], questions = new Map(), answered = new Set();
6
+ const records = [], questions = new Map(), answered = new Set(), superseded = new Set();
7
+ // D2: an answer to another question that ended a blocked ask (or resumed a hibernated one) supersedes that question.
8
+ const supersede = (details) => {
9
+ if (Array.isArray(details?.superseded))
10
+ for (const s of details.superseded)
11
+ if (typeof s?.qid === 'string' && typeof s.rev === 'number')
12
+ superseded.add(`${s.qid}@${s.rev}`);
13
+ };
7
14
  let foreign = false;
8
15
  for (const entry of entries) {
9
16
  if (entry.type === 'custom' && entry.customType === CT.exec) {
@@ -33,6 +40,7 @@ export function recover(entries, call) {
33
40
  else if (entry.type === 'custom_message' && entry.customType === CT.msg) {
34
41
  const details = entry.details;
35
42
  records.push({ type: 'applied', rid: details.rid });
43
+ supersede(details);
36
44
  // P28: a hibernation resume delivers the answer as a continue message; its receipt answers qid@rev.
37
45
  if (details.qid && details.rev)
38
46
  answered.add(`${details.qid}@${details.rev}`);
@@ -41,9 +49,10 @@ export function recover(entries, call) {
41
49
  const details = entry.message.details;
42
50
  if (details?.rid)
43
51
  records.push({ type: 'applied', rid: details.rid });
52
+ supersede(details);
44
53
  if (details?.qid && details.rev)
45
54
  answered.add(`${details.qid}@${details.rev}`);
46
55
  }
47
56
  }
48
- return { records, questions, answered };
57
+ return { records, questions, answered, superseded };
49
58
  }
@@ -11,6 +11,17 @@ import { recover } from "./child/history.js";
11
11
  import { validate } from "./child/schema.js";
12
12
  import { registerLive } from "./child/live.js";
13
13
  const MESSAGES = ['task', 'steer', 'notify', 'follow-up', 'continue'];
14
+ /** D2: the questions a bound continue supersedes: the hibernated asker's own question when it resumes with the answer
15
+ * to another one (the orchestrator names it in the body). */
16
+ function supersededOf(req) {
17
+ const list = req.kind === 'continue' ? req.body?.superseded : undefined;
18
+ return Array.isArray(list) ? list.filter((s) => typeof s?.qid === 'string' && typeof s?.rev === 'number').map(s => ({ qid: s.qid, rev: s.rev })) : [];
19
+ }
20
+ /** The question an envelope answers: an `answer`, or a `continue` that resumes a hibernated asker with its answer (P28). */
21
+ export function answers(req) {
22
+ const qid = req.cond?.qid, rev = req.cond?.rev;
23
+ return (req.kind === 'answer' || req.kind === 'continue') && typeof qid === 'string' && typeof rev === 'number' ? { qid, rev } : undefined;
24
+ }
14
25
  /** P31, P33, P37: Usage of this call only — assistant messages in segments opened by this call's executions,
15
26
  * deduplicated by entry id. Context inherited from an earlier generation or a forked origin is not charged. */
16
27
  export function usage(entries, call) {
@@ -78,20 +89,48 @@ export function registerChild(pi) {
78
89
  if (!active || (mode === 'idle' && !ctx.isIdle()))
79
90
  return [];
80
91
  let delivered = false;
92
+ // Revisions answered (taken) or superseded (planned) by a decision of this intake are closed for the rest of it:
93
+ // one delivery each (D3), and no answer to a question an earlier decision of the same intake superseded (D2).
94
+ const taken = new Set(), planned = new Set();
95
+ const closed = () => new Set([...state.answered, ...state.superseded, ...taken, ...planned]);
96
+ const open = (q) => openness({ open: [...state.questions.values()], closed: closed() }, q);
97
+ const pending = (req, view) => view.admitted.has(req.rid) && !view.resolved.has(req.rid) && !view.tombstones.has(req.rid);
98
+ // An answer to an open question (or a bound continue, P28) that waits to be delivered.
99
+ const waiting = (req, view) => {
100
+ const q = answers(req);
101
+ return !!q && pending(req, view) && open(q);
102
+ };
81
103
  const plans = planDecisions(state.records, candidates, (req, view) => {
82
104
  if (req.to !== call)
83
105
  return { action: 'reject', reason: 'wrong-recipient' };
84
106
  if ([...MESSAGES, 'answer'].includes(req.kind) && typeof req.body?.message !== 'string')
85
107
  return { action: 'reject', reason: 'malformed' };
86
- if (req.kind === 'answer') {
87
- const qid = req.cond?.qid, rev = req.cond?.rev, question = qid ? state.questions.get(qid) : undefined;
88
- if (state.answered.has(`${qid}@${rev}`))
108
+ const q = answers(req);
109
+ // D1, D3, V4: one rule for answers (an `answer`, or a bound `continue`): an open question takes its answer at the
110
+ // first opportunity, once; any further envelope for an answered or superseded revision is dropped with a receipt.
111
+ if (q) {
112
+ const key = `${q.qid}@${q.rev}`;
113
+ if (state.answered.has(key) || taken.has(key))
89
114
  return { action: 'reject', reason: 'already-answered' };
90
- if (!question || question.rev !== rev)
115
+ // Not open: superseded, an older revision, or a question this generation did not ask. A bound continue too: the
116
+ // orchestrator binds the latest revision it observed, and the child may have asked again meanwhile (V4).
117
+ if (!open(q))
91
118
  return { action: 'reject', reason: 'stale-rev' };
92
- if (mode !== 'ask' || delivered || !openness({ open: [...state.questions.values()], blocked }, { qid: qid, rev: rev }))
119
+ if (delivered && mode !== 'boundary' && mode !== 'settle')
120
+ return { action: 'defer' };
121
+ // A blocked ask prefers its own answer when answers to several open questions wait.
122
+ if (mode === 'ask' && blocked && !(q.qid === blocked.qid && q.rev === blocked.rev) && candidates.some(other => pending(other, view) &&
123
+ answers(other)?.qid === blocked.qid && answers(other)?.rev === blocked.rev))
124
+ return { action: 'defer' };
125
+ // Follow-ups ordered before it enter first (fix C): at a boundary they ride ahead (below); here it waits.
126
+ if (mode !== 'ask' && candidates.some(other => other.kind === 'follow-up' && pending(other, view) && view.order.get(other.rid) < view.order.get(req.rid)))
93
127
  return { action: 'defer' };
94
128
  delivered = true;
129
+ taken.add(key);
130
+ for (const s of supersededOf(req))
131
+ planned.add(`${s.qid}@${s.rev}`);
132
+ if (mode === 'ask' && blocked && !(q.qid === blocked.qid && q.rev === blocked.rev))
133
+ planned.add(`${blocked.qid}@${blocked.rev}`);
95
134
  return { action: 'apply' };
96
135
  }
97
136
  if (mode === 'ask' && (req.kind !== 'steer' || delivered))
@@ -103,12 +142,14 @@ export function registerChild(pi) {
103
142
  return body && ctx.modelRegistry.find(body.provider, body.model) ? { action: 'apply' } : { action: 'reject', reason: 'unknown-model' };
104
143
  }
105
144
  if (MESSAGES.includes(req.kind)) {
106
- if ((mode === 'idle' && delivered) || (req.kind === 'follow-up' && mode === 'boundary'))
145
+ // A resumed turn can reach this boundary before an idle intake. Older follow-ups must ride ahead of its
146
+ // bound answer; otherwise continue bypasses them and the model sees stale instructions after the answer.
147
+ const beforeResume = mode === 'boundary' && req.kind === 'follow-up' && candidates.some(other => waiting(other, view) && view.order.get(req.rid) < (view.order.get(other.rid) ?? -1));
148
+ if ((mode === 'idle' && delivered) || (req.kind === 'follow-up' && mode === 'boundary' && !beforeResume))
107
149
  return { action: 'defer' };
108
150
  // A notify never interrupts a question: while an answer waits to be delivered (a hibernated asker resumes with
109
151
  // its answer as a continue) it goes after it, at the next safe point. In ask mode it was deferred above.
110
- if (req.kind === 'notify' && candidates.some(other => !view.resolved.has(other.rid) && !view.tombstones.has(other.rid) &&
111
- (other.kind === 'answer' && !state.answered.has(`${other.cond?.qid}@${other.cond?.rev}`) || other.kind === 'continue' && other.cond?.qid !== undefined)))
152
+ if (req.kind === 'notify' && candidates.some(other => waiting(other, view)))
112
153
  return { action: 'defer' };
113
154
  delivered = true;
114
155
  return { action: 'apply' };
@@ -118,7 +159,7 @@ export function registerChild(pi) {
118
159
  // Idle delivery starts pi immediately. Commit only through that message's receipt;
119
160
  // later decisions must be reconsidered at the next boundary, in history order.
120
161
  if (mode === 'idle') {
121
- const firstMessage = plans.findIndex(d => d.type === 'applied' && MESSAGES.includes(byRid.get(d.rid).kind));
162
+ const firstMessage = plans.findIndex(d => d.type === 'applied' && [...MESSAGES, 'answer'].includes(byRid.get(d.rid).kind));
122
163
  if (firstMessage >= 0)
123
164
  plans.splice(firstMessage + 1);
124
165
  }
@@ -150,19 +191,35 @@ export function registerChild(pi) {
150
191
  record(CT.model, { rid: req.rid, provider: body.provider, model: body.model, ...(body.thinking ? { thinking: body.thinking } : {}) });
151
192
  }
152
193
  else if (mode === 'ask' && waiter) {
153
- const text = req.body.message;
154
- answer = req.kind === 'answer'
155
- ? { content: [{ type: 'text', text }], details: { rid: req.rid, qid: waiter.qid, rev: waiter.rev } }
156
- : { content: [{ type: 'text', text: `${JSON.stringify({ interrupted_by: 'steer', open: waiter.qid })}\n${text}` }], details: { rid: req.rid, kind: 'steer' } };
157
- if (req.kind === 'answer')
158
- state.answered.add(`${waiter.qid}@${waiter.rev}`);
194
+ const text = req.body.message, q = answers(req);
195
+ if (q) {
196
+ const carried = supersededOf(req);
197
+ // D2: an answer to another open question ends the blocked ask too; the blocked question is superseded (the
198
+ // model is told so), and a later answer to it is rejected.
199
+ const own = q.qid === waiter.qid && q.rev === waiter.rev;
200
+ const note = own ? '' : `${JSON.stringify({ answers_earlier_question: q.qid, withdrawn: waiter.qid })}\n` +
201
+ `Your question "${waiter.question}" is withdrawn: this answers your earlier question instead. Ask again if you still need it answered.\n` +
202
+ (req.kind === 'answer' ? `Question: ${state.questions.get(q.qid)?.question ?? q.qid}\nAnswer: ` : '');
203
+ const superseded = [...carried, ...(own ? [] : [{ qid: waiter.qid, rev: waiter.rev }])];
204
+ answer = { content: [{ type: 'text', text: `${note}${text}` }], details: { rid: req.rid, qid: q.qid, rev: q.rev, ...(superseded.length ? { superseded } : {}) } };
205
+ state.answered.add(`${q.qid}@${q.rev}`);
206
+ for (const s of superseded)
207
+ state.superseded.add(`${s.qid}@${s.rev}`);
208
+ }
209
+ else
210
+ answer = { content: [{ type: 'text', text: `${JSON.stringify({ interrupted_by: 'steer', open: waiter.qid })}\n${text}` }], details: { rid: req.rid, kind: 'steer' } };
159
211
  }
160
212
  else {
161
- // P28: a continue bound to a question (hibernation resume) is that question's answer receipt.
162
- const bound = req.kind === 'continue' && req.cond?.qid && req.cond.rev ? { qid: req.cond.qid, rev: req.cond.rev } : undefined;
163
- if (bound)
164
- state.answered.add(`${bound.qid}@${bound.rev}`);
165
- entries.push({ type: 'custom_message', customType: CT.msg, content: req.body.message, display: true, details: { rid: req.rid, kind: req.kind, from: req.from, ...bound } });
213
+ // P28: a continue bound to a question (hibernation resume) is that question's answer receipt; D1: so is an
214
+ // answer delivered outside an ask (its ask ended by a steer or a reminder), as a message at this boundary.
215
+ const q = answers(req), body = req.body, superseded = supersededOf(req);
216
+ if (q)
217
+ state.answered.add(`${q.qid}@${q.rev}`);
218
+ for (const s of superseded)
219
+ state.superseded.add(`${s.qid}@${s.rev}`);
220
+ const content = req.kind === 'answer'
221
+ ? `The answer to your earlier question arrived.\nQuestion: ${state.questions.get(q.qid)?.question ?? q.qid}\nAnswer: ${body.message}` : body.message;
222
+ entries.push({ type: 'custom_message', customType: CT.msg, content, display: true, details: { rid: req.rid, kind: req.kind, from: req.from, ...q, ...(superseded.length ? { superseded } : {}) } });
166
223
  }
167
224
  }
168
225
  }
@@ -1,7 +1,7 @@
1
1
  import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
2
2
  import { StringDecoder } from "node:string_decoder";
3
3
  import { join } from "node:path";
4
- import { readJournalSnapshot } from "../../kernel/journal.js";
4
+ import { readJournalSnapshot, readJournalUncached } from "../../kernel/journal.js";
5
5
  import { journalPath, orchLedger } from "../../paths.js";
6
6
  import { CT, JT, attentionEntries } from "../../types.js";
7
7
  import { holdOf, ledgerIndex } from "../../orchestrator/snapshot.js";
@@ -51,11 +51,66 @@ export function openGeneration(entries) {
51
51
  opened.set(entries, { length: entries.length, open });
52
52
  return open;
53
53
  }
54
+ /** Whether one journal is unfinished, by file identity: a journal that has not changed is not read again. */
55
+ const decided = new Map();
56
+ function unfinishedJournal(path, known) {
57
+ let stat;
58
+ try {
59
+ stat = statSync(path);
60
+ }
61
+ catch (error) {
62
+ if (error.code !== "ENOENT")
63
+ throw error;
64
+ decided.delete(path);
65
+ return true;
66
+ } // no done yet
67
+ const hit = decided.get(path);
68
+ if (hit && hit.ino === stat.ino && hit.size === stat.size)
69
+ return hit.unfinished;
70
+ // Read without keeping the entries in the shared journal cache: a pi process scans every workflow only when no
71
+ // orchestrator runs, and keeping every journal of the machine cost it hundreds of MB.
72
+ const read = known ?? readJournalUncached(path);
73
+ if (!read) {
74
+ decided.delete(path);
75
+ return true;
76
+ }
77
+ const unfinished = !read.entries.some(e => e.type === JT.done) || openGeneration(read.entries);
78
+ decided.set(path, { ino: read.ino, size: read.size, unfinished });
79
+ return unfinished;
80
+ }
54
81
  /** P1: Workflow-side pending work shared by every starter: a workflow without JT.done or with an unsealed generation,
55
- * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself. */
82
+ * unless a drain (stop-all) holds it: held work waits for an explicit resume, which starts the orchestrator itself.
83
+ * Stops at the first unfinished workflow (newest first); a held workflow the ledger attributes is skipped without
84
+ * reading its journal, and an unchanged journal is not read again. */
56
85
  export function unfinishedWorkflow(home) {
57
- const ledger = readJournalSnapshot(orchLedger(home));
58
- return workflows(home).some(w => (!w.entries.some(e => e.type === JT.done) || openGeneration(w.entries)) && !holdOf(ledger, w.wid, w.origin));
86
+ const ledger = readJournalSnapshot(orchLedger(home)), { created, pruned } = ledgerIndex(ledger);
87
+ let names;
88
+ try {
89
+ names = readdirSync(join(home, "w"));
90
+ }
91
+ catch (error) {
92
+ if (error.code !== "ENOENT")
93
+ throw error;
94
+ names = [];
95
+ }
96
+ const ids = [...new Set([...[...created.keys()].map(String), ...names].filter(wid => !pruned.has(wid)))].sort().reverse();
97
+ for (const wid of ids) {
98
+ const path = journalPath(home, wid);
99
+ // The hold rule is the one workflows() applies: the ledger's `created` names the origin a drain may hold; only for
100
+ // a wid the ledger has no `created` for is the journal read first, for a `created` entry of its own.
101
+ const known = created.get(wid);
102
+ if (known && holdOf(ledger, wid, known.origin))
103
+ continue;
104
+ let read;
105
+ if (!known) {
106
+ read = readJournalUncached(path);
107
+ if (holdOf(ledger, wid, read?.entries.find(e => e.type === JT.created)?.origin))
108
+ continue;
109
+ }
110
+ if (unfinishedJournal(path, read))
111
+ return true;
112
+ }
113
+ return false;
59
114
  }
60
115
  const receipts = new WeakMap();
61
116
  const receiptsOf = (entry) => entry.type === "custom_message" && entry.customType === CT.attention
@@ -12,7 +12,7 @@ import { launchOrchestrator } from "../platform/launch.js";
12
12
  import { dsaHome, orchInbox, orchLedger, orchLock, outboxRoot } from "../paths.js";
13
13
  import { CT, JT } from "../types.js";
14
14
  import { attention, presentText, presented, resolved, unfinishedWorkflow } from "./main/snapshots.js";
15
- import { NOTIFY_SINCE, isLive, orchestratorTooOld, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
15
+ import { NOTIFY_SINCE, isLive, orchestratorTooOld, ownWorkflows, pausedElsewhere, runningOrchestrator, statusBrief, statusCallDetail, statusCompactDetail, statusDetail, statusView, widOfRid, outputSelect, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
16
16
  import { BATCH, checkAgents, followUpReceipt, outcomeLine, request, sendReceipt } from "./main/tool.js";
17
17
  import { parameters } from "./main/schema.js";
18
18
  import { batchConflict, batchDigest, findRequest, manyIds, namesMany, requestRid, sendIdentified } from "../requests.js";
@@ -82,14 +82,17 @@ export function registerMain(pi, ui) {
82
82
  if (stopped)
83
83
  return;
84
84
  await reconcile();
85
- const pending = submitting || pendingOutbox() || (await scanInbox(orchInbox(home))).length > 0 || unfinishedWorkflow(home);
86
- if (!pending)
87
- return;
85
+ // A running orchestrator (it holds its lock) serves every pending request and workflow: then nothing is scanned.
86
+ // Only without one is pending work looked for, stopping at the first; the scan reads workflow journals without
87
+ // keeping them (see unfinishedWorkflow).
88
88
  await mkdir(home, { recursive: true });
89
89
  const lock = await new OsLock().tryAcquire(orchLock(home));
90
90
  if (!lock)
91
91
  return;
92
92
  await lock.release();
93
+ const pending = submitting || pendingOutbox() || (await scanInbox(orchInbox(home))).length > 0 || unfinishedWorkflow(home);
94
+ if (!pending)
95
+ return;
93
96
  const entry = process.env.DSA_ORCHESTRATOR_ENTRY ?? fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../orchestrator/main.ts" : "../orchestrator/main.js", import.meta.url));
94
97
  // Inside pi: started even when pi cannot be resolved here (the orchestrator falls back to its own lookup).
95
98
  await launchOrchestrator(entry, process.env, { home });
@@ -191,7 +194,8 @@ export function registerMain(pi, ui) {
191
194
  pi.on("session_start", async (_event, context) => {
192
195
  await start(context);
193
196
  // Quit pause: say once, at the session's start, which of its workflows wait for a resume.
194
- const paused = statusView(home, { origin: sender }).workflows.filter(w => w.origin === sender && isLive(w) && w.paused);
197
+ // Only the workflows this session started are read (ownership comes from the orchestrator ledger), not every one.
198
+ const paused = ownWorkflows(home, sender, { started: true }).filter(w => w.origin === sender && isLive(w) && w.paused);
195
199
  if (paused.length)
196
200
  pi.sendMessage({ customType: CT.note, display: true, content: `${paused.length} subagent workflow${paused.length > 1 ? "s were" : " was"} paused when pi quit (${paused.map(w => w.name ?? w.wid).join(", ")}). Ask to resume, or open /subagents (or ↓) and press r.` });
197
201
  });
@@ -202,7 +206,7 @@ export function registerMain(pi, ui) {
202
206
  pi.on("session_shutdown", async (event) => {
203
207
  if (event.reason === "quit" && quitPolicy(home) === "pause" && outbox && !stopped) {
204
208
  try {
205
- const running = statusView(home, { origin: sender }).workflows.some(w => w.origin === sender && isLive(w) && !w.paused);
209
+ const running = ownWorkflows(home, sender, { started: true }).some(w => w.origin === sender && isLive(w) && !w.paused);
206
210
  if (running)
207
211
  await serial(async () => { await outbox?.send("orch", "drain", { fence: true, origin: sender }); });
208
212
  }
@@ -116,6 +116,13 @@ function applyWait(f, e) {
116
116
  }
117
117
  break;
118
118
  }
119
+ // D6: hibernated again after a bound answer the session had already closed: it waits for a new answer.
120
+ case "hibernated": {
121
+ const c = f.calls.get(String(e.call));
122
+ if (c && c.exec === e.exec)
123
+ delete c.answered;
124
+ break;
125
+ }
119
126
  case "answer-bound": {
120
127
  const c = f.calls.get(String(e.call)), id = `q:${e.call}:${e.qid}`, item = f.items.get(id);
121
128
  if (item?.rev === e.rev)
@@ -10,10 +10,10 @@ export function seal(state, transition) {
10
10
  export function currency(state, transition) {
11
11
  return Object.entries(transition).every(([key, value]) => value === undefined || state[key] === value);
12
12
  }
13
- /** A4, V4, P28: Answers require an open question and matching blocked or hibernated state. */
13
+ /** A4, V4, P28: An answer requires an open question: the current revision of a question the call asked (`open`), not yet
14
+ * answered or superseded (`closed`, keys `qid@rev`). Any open question takes its answer, blocked in an ask or not. */
14
15
  export function openness(state, transition) {
15
- const matches = (q) => q?.qid === transition.qid && q.rev === transition.rev;
16
- return state.open.some(matches) && (matches(state.blocked) || matches(state.hibernated));
16
+ return state.open.some(q => q.qid === transition.qid && q.rev === transition.rev) && !state.closed.has(`${transition.qid}@${transition.rev}`);
17
17
  }
18
18
  /** A4, V5, P5: Dependencies must be earlier admissions, and resolved before application. */
19
19
  export function dependency(state, transition) {
@@ -100,6 +100,36 @@ export function readJournalSnapshot(path) {
100
100
  closeSync(fd);
101
101
  }
102
102
  }
103
+ /** A committed snapshot with the file identity it was read at, without keeping it in the shared snapshot cache (a
104
+ * cached snapshot of the same file is reused): for one-off scans over many journals whose entries are not needed
105
+ * again. `undefined` when the file does not exist. */
106
+ export function readJournalUncached(path) {
107
+ let fd;
108
+ try {
109
+ fd = openSync(path, 'r');
110
+ }
111
+ catch (error) {
112
+ if (error.code === 'ENOENT')
113
+ return undefined;
114
+ throw error;
115
+ }
116
+ try {
117
+ const { ino, size } = fstatSync(fd), cached = snapshots.get(path);
118
+ if (cached && cached.ino === ino && cached.size === size)
119
+ return { ino, size, entries: cached.entries };
120
+ const bytes = Buffer.alloc(size);
121
+ for (let read = 0; read < bytes.length;) {
122
+ const n = readSync(fd, bytes, read, bytes.length - read, read);
123
+ if (!n)
124
+ break;
125
+ read += n;
126
+ }
127
+ return { ino, size, entries: decode(bytes).entries };
128
+ }
129
+ finally {
130
+ closeSync(fd);
131
+ }
132
+ }
103
133
  /** How long a resting journal keeps its descriptor after its last append (a burst of appends opens it once). */
104
134
  export const JOURNAL_REST_MS = 1000;
105
135
  let descriptors = 0, appends = 0;
@@ -6,6 +6,10 @@ import { CT } from "../../types.js";
6
6
  import { askOf, cutAskResult, receiptId } from "./session.js";
7
7
  import { messageUsage } from "./usage.js";
8
8
  export const answerKey = (qid, rev) => JSON.stringify([qid, rev]);
9
+ /** D2: the questions an answer receipt superseded (`details.superseded`: the blocked or hibernated asker's question). */
10
+ export function supersededBy(details) {
11
+ return Array.isArray(details?.superseded) ? details.superseded.filter(q => typeof q?.qid === "string" && typeof q?.rev === "number") : [];
12
+ }
9
13
  /** A fold of one session for one call, extended over appended entries. */
10
14
  export class SessionFold {
11
15
  call;
@@ -19,7 +23,7 @@ export class SessionFold {
19
23
  state;
20
24
  constructor(call) { this.call = call; this.state = SessionFold.empty(); }
21
25
  static empty() {
22
- return { usage: [], receipts: new Map(), questions: [], answered: new Set(), lastQuestion: -1, questionAt: new Map(), execAt: new Map(), results: new Map() };
26
+ return { usage: [], receipts: new Map(), questions: [], answered: new Set(), superseded: new Set(), lastQuestion: -1, questionAt: new Map(), execAt: new Map(), results: new Map() };
23
27
  }
24
28
  update(entries) {
25
29
  if (entries === this.entries)
@@ -48,13 +52,16 @@ export class SessionFold {
48
52
  s.questionAt.set(e.data?.qid, i);
49
53
  if (e.type === "custom") {
50
54
  s.lastQuestion = i;
51
- if (e.data && typeof e.data.qid === "string" && typeof e.data.rev === "number")
55
+ if (this.own && e.data && typeof e.data.qid === "string" && typeof e.data.rev === "number")
52
56
  s.questions.push({ qid: e.data.qid, rev: e.data.rev, question: e.data.question });
53
57
  }
54
58
  }
55
59
  const details = e.message?.details ?? e.details;
56
60
  if (details && rid !== undefined)
57
61
  s.answered.add(answerKey(details.qid, details.rev));
62
+ if (rid !== undefined)
63
+ for (const q of supersededBy(details))
64
+ s.superseded.add(answerKey(q.qid, q.rev));
58
65
  const m = e.message;
59
66
  if (m?.role === "toolResult" && typeof m.toolCallId === "string" && !s.results.has(m.toolCallId))
60
67
  s.results.set(m.toolCallId, e);
@@ -70,7 +77,7 @@ export function digestOpenQuestion(entries, s) {
70
77
  const at = s.lastQuestion, q = entries[at]?.data;
71
78
  if (!q || typeof q.qid !== "string" || typeof q.rev !== "number")
72
79
  return;
73
- if (s.answered.has(answerKey(q.qid, q.rev)))
80
+ if (s.answered.has(answerKey(q.qid, q.rev)) || s.superseded.has(answerKey(q.qid, q.rev)))
74
81
  return;
75
82
  const ask = askOf(entries, at);
76
83
  const result = ask === undefined ? undefined : s.results.get(ask);
@@ -1,7 +1,8 @@
1
1
  // Private workflow entries (P28): hibernated{call,qid,rev,exec};
2
2
  // answer-bound{call,qid,rev,rid,rid2,message,hash}; resumed{call,rid,exec}.
3
- import { CT } from "../../types.js";
3
+ import { CT, JT, attentionEntries } from "../../types.js";
4
4
  import { askOf, cutAskResult, receiptId } from "./session.js";
5
+ import { supersededBy } from "./digest.js";
5
6
  /** P28, V4: Find an unanswered question whose native ask tool remains blocked. */
6
7
  export function openQuestion(entries) {
7
8
  const at = entries.findLastIndex(e => e.type === "custom" && e.customType === CT.question), q = entries[at]?.data;
@@ -9,7 +10,8 @@ export function openQuestion(entries) {
9
10
  return;
10
11
  if (entries.some(e => {
11
12
  const details = e.message?.details ?? e.details;
12
- return !!details && details.qid === q.qid && details.rev === q.rev && receiptId(e) !== undefined;
13
+ return !!details && receiptId(e) !== undefined && (details.qid === q.qid && details.rev === q.rev ||
14
+ supersededBy(details).some(s => s.qid === q.qid && s.rev === q.rev));
13
15
  }))
14
16
  return;
15
17
  // Only the ask that wrote this question counts: it is still blocked when it has no result, or only the error it ended
@@ -25,3 +27,24 @@ export function openQuestion(entries) {
25
27
  export function hibernation(journal, call) {
26
28
  return journal.entries().findLast(e => e.type === "hibernated" && e.call === call);
27
29
  }
30
+ /** P28: The question qid@rev of a call is still open: its attention item is its latest revision and is unresolved.
31
+ * A call hibernated on one question takes the answer to any of its open questions (an earlier one stays open when a
32
+ * steer ended its ask, or the child asked a reminder while it waited). */
33
+ export function openAsked(entries, call, qid, rev) {
34
+ if (typeof qid !== "string" || typeof rev !== "number")
35
+ return false;
36
+ const id = `q:${call}:${qid}`, items = attentionEntries(entries, id);
37
+ return items.some(e => e.item.rev === rev) && !items.some(e => e.item.rev > rev) &&
38
+ !entries.some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev) && !supersededByBinding(entries, call, qid, rev);
39
+ }
40
+ /** D2: qid@rev of `call` was superseded by a durable binding: an `answer-bound` names it in `superseded`. The binding is
41
+ * the source of truth; the attention resolution `superseded` is derived from it (and may lag it across a crash). */
42
+ export function supersededByBinding(entries, call, qid, rev) {
43
+ return entries.some(e => e.type === "answer-bound" && e.call === call && Array.isArray(e.superseded) &&
44
+ e.superseded.some(s => s?.qid === qid && s?.rev === rev));
45
+ }
46
+ /** P28: The answer bound to hibernation `sleeping`: to its question, or (bound after it) to another open question. */
47
+ export function boundAnswer(entries, sleeping) {
48
+ return entries.find(e => e.type === "answer-bound" && e.call === sleeping.call &&
49
+ (e.qid === sleeping.qid && e.rev === sleeping.rev || e.seq > sleeping.seq));
50
+ }
@@ -25,7 +25,7 @@ import { parseModel, plainModel, resolveModel } from "../../compat/model.js";
25
25
  import { buildCallResult } from "../../compat/result.js";
26
26
  import createEffects from "./effects/index.js";
27
27
  import { continueSession } from "./generation.js";
28
- import { hibernation, openQuestion } from "./hibernate.js";
28
+ import { boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
29
29
  import { SessionFold, answerKey, digestOpenQuestion } from "./digest.js";
30
30
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
31
31
  import { evidence, fatalProviderError, quotaExhausted, refusedByProvider, forgetSession, readSessionState, receiptId, sessionModel } from "./session.js";
@@ -122,6 +122,17 @@ export function continueMessage(dangling) {
122
122
  /** An asker hibernates while it waits (its execution is stopped to free the provider slot), so the answer says so. */
123
123
  export const HIBERNATED_NOTE = "While you waited for the answer below your execution was stopped; processes your tools had " +
124
124
  "started (background ones included) were stopped with it. Check them before relying on them.";
125
+ /** D2: an answer bound to another question than the one its call hibernated on supersedes that one. */
126
+ function supersedes(sleeping, qid, rev) {
127
+ return qid === sleeping.qid && rev === sleeping.rev ? {} : { superseded: [{ qid: String(sleeping.qid), rev: Number(sleeping.rev) }] };
128
+ }
129
+ /** D2: what the resumed asker is told of the question it hibernated on, when the answer it resumes with is another's. */
130
+ function withdrawn(entries, call, sleeping, qid, rev) {
131
+ if (qid === sleeping.qid && rev === sleeping.rev)
132
+ return "";
133
+ const text = attentionEntries(entries).find(e => e.item.call === call && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item.text;
134
+ return ` Your later question "${text ?? String(sleeping.qid)}" is withdrawn: the answer below is to your earlier question. Ask again if you still need it answered.`;
135
+ }
125
136
  /** A launch failure the environment causes (the command or its interpreter is missing or not executable): fixing the
126
137
  * environment, or another orchestrator started from a better one, makes the same launch work. */
127
138
  export const environmentSpawnError = (error) => ["ENOENT", "EACCES"].includes(String(error?.code));
@@ -834,9 +845,36 @@ export default function createExecutor(ledgers, options = {}) {
834
845
  await t.journal.append(JT.attention, { item: { id, rev, kind: "question", text: String(question), wid: t.wid, call: t.callId, qid, session: callSession(home, t.wid, t.key, t.gen) } });
835
846
  if (digest.answered.has(answerKey(qid, rev)) || t.journal.entries().some(e => e.type === "answer-bound" && e.call === t.callId && e.qid === qid && e.rev === rev))
836
847
  await resolveBoundAnswer(t.journal, t.callId, qid, rev);
848
+ else if (digest.superseded.has(answerKey(qid, rev)) || supersededByBinding(t.journal.entries(), t.callId, qid, rev))
849
+ await resolveQuestion(t.journal, t.callId, qid, rev, "superseded");
837
850
  }
851
+ await resolveSuperseded(t.journal, t.callId);
852
+ if (entries.length)
853
+ await resolveCarried(t.journal, t.callId, digest.questions);
838
854
  });
839
855
  }
856
+ /** D2, D4: close a question's attention item once (superseded, carried) unless already resolved. Called serially. */
857
+ async function resolveQuestion(journal, call, qid, rev, resolution) {
858
+ const id = `q:${call}:${qid}`;
859
+ if (attentionEntries(journal.entries(), id).some(e => e.item.rev === rev) && !journal.entries().some(e => e.type === JT.attentionResolved && e.id === id && e.rev === rev))
860
+ await journal.append(JT.attentionResolved, { id, rev, resolution });
861
+ }
862
+ /** D2: the questions durable bindings superseded (answer-bound.superseded, the source of truth) resolve `superseded`:
863
+ * after a crash between the binding and its resolution, recovery and observation derive it. Called serially. */
864
+ async function resolveSuperseded(journal, call) {
865
+ for (const b of journal.entries().filter(e => e.type === "answer-bound" && e.call === call && Array.isArray(e.superseded)))
866
+ for (const s of b.superseded)
867
+ await resolveQuestion(journal, call, s.qid, s.rev, "superseded");
868
+ }
869
+ /** D4: a question item of `call` that none of its executions asked (1.0.37 re-opened the questions of the session a
870
+ * generation continues) is resolved `carried`. `own`: the questions the call's executions asked. Called serially. */
871
+ async function resolveCarried(journal, call, own) {
872
+ for (const { item } of attentionEntries(journal.entries())) {
873
+ if (item.kind !== "question" || item.call !== call || own.some(q => q.qid === item.qid && q.rev === item.rev))
874
+ continue;
875
+ await resolveQuestion(journal, call, item.qid, item.rev, "carried");
876
+ }
877
+ }
840
878
  /** The model each execution last answered with (`selected`, then `model-used`), cached per execution. */
841
879
  const inUse = new Map();
842
880
  async function switched(exec, journal, event) {
@@ -1038,6 +1076,26 @@ export default function createExecutor(ledgers, options = {}) {
1038
1076
  let entries = await readCall(journal, t.callId);
1039
1077
  let dangling = [];
1040
1078
  let bound;
1079
+ // D3: a bound answer is settled by its receipt in the session, or by one durable `answer-settled{rid2}` when the
1080
+ // session closed its question revision without it (the child took that answer, or superseded the question, before
1081
+ // it was fenced): the resume never waits for a receipt the child would not give.
1082
+ const answerSettled = (u, session) => session.some(e => receiptId(e) === u.rid2) ||
1083
+ journal.entries().some(e => e.type === "answer-settled" && e.call === t.callId && e.rid2 === u.rid2);
1084
+ const settleClosed = async (u, session) => {
1085
+ if (!u || answerSettled(u, session))
1086
+ return;
1087
+ const d = digestOf(t.callId, session), key = answerKey(u.qid, u.rev);
1088
+ // D6: a newer revision of the question (the child asked it again, a steer having ended the ask, before the fence)
1089
+ // closes the bound one too: the child would refuse it as stale.
1090
+ const reason = d.answered.has(key) ? "answered-in-session" : d.superseded.has(key) ? "superseded-in-session" :
1091
+ d.questions.some(q => q.qid === u.qid && q.rev > Number(u.rev)) ? "newer-revision" : undefined;
1092
+ if (!reason)
1093
+ return;
1094
+ await serial(async () => {
1095
+ if (!journal.entries().some(e => e.type === "answer-settled" && e.call === t.callId && e.rid2 === u.rid2))
1096
+ await journal.append("answer-settled", { call: t.callId, rid2: u.rid2, qid: u.qid, rev: u.rev, reason });
1097
+ });
1098
+ };
1041
1099
  const sleeping = hibernation(journal, t.callId);
1042
1100
  if (exec && sleeping?.exec === exec) {
1043
1101
  await fence(journal, exec, { park: a });
@@ -1048,18 +1106,31 @@ export default function createExecutor(ledgers, options = {}) {
1048
1106
  break;
1049
1107
  if (reached(totalUsage(journal.entries(), t.callId), t.spec.budget) || reached(totalUsage(journal.entries()), t.workflowBudget))
1050
1108
  return finish(journal, t.callId, exec, makeResult("budget"));
1051
- bound = journal.entries().find(e => e.type === "answer-bound" && e.call === t.callId && e.qid === sleeping.qid && e.rev === sleeping.rev);
1109
+ bound = boundAnswer(journal.entries(), sleeping);
1052
1110
  if (bound)
1053
1111
  break;
1054
1112
  await new Promise(resolve => { const timer = setTimeout(resolve, config.k?.trackerMs ?? 1000); a.wake = () => { clearTimeout(timer); resolve(); }; });
1055
1113
  }
1056
1114
  }
1057
1115
  const pendingAnswer = journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId);
1058
- if (!bound && pendingAnswer && !entries.some(e => receiptId(e) === pendingAnswer.rid2))
1116
+ await settleClosed(pendingAnswer, entries);
1117
+ if (!bound && pendingAnswer && !answerSettled(pendingAnswer, entries))
1059
1118
  bound = pendingAnswer;
1060
1119
  if (exec) {
1061
1120
  await fence(journal, exec, { park: a });
1062
1121
  await questions(t, entries = await readCall(journal, t.callId));
1122
+ // D6: after the fence the session is final. A bound answer it closed (answered, superseded, or re-asked as a newer
1123
+ // revision) is settled; if the session still has an open question of this call, the call does not launch: it
1124
+ // hibernates again on that question (its attention is open, so the parent is asked), and resumes only on a new
1125
+ // binding. Otherwise it launches with the plain continue. Each step is idempotent across a crash between them.
1126
+ if (bound) {
1127
+ await settleClosed(bound, entries);
1128
+ const asking = answerSettled(bound, entries) ? digestOpenQuestion(entries, digestOf(t.callId, entries)) : undefined;
1129
+ if (asking && !journal.entries().some(e => e.type === "hibernated" && e.call === t.callId && e.seq > bound.seq)) {
1130
+ await serial(() => journal.append("hibernated", { call: t.callId, exec, qid: asking.qid, rev: asking.rev, reason: "rebound-settled" }));
1131
+ continue;
1132
+ }
1133
+ }
1063
1134
  await recordUsage(t, sessionUsage(entries, t.callId));
1064
1135
  const ev = evidence(entries, exec);
1065
1136
  dangling = ev.dangling;
@@ -1151,7 +1222,10 @@ export default function createExecutor(ledgers, options = {}) {
1151
1222
  });
1152
1223
  // The answer uses its stable forwarded identity across every recovery incarnation.
1153
1224
  const unresolved = journal.entries().findLast(e => e.type === "answer-bound" && e.call === t.callId);
1154
- const receipt = unresolved && entries.some(e => receiptId(e) === unresolved.rid2);
1225
+ // D3: the child takes one answer per question revision; a bound answer to one the session already closed (answered
1226
+ // or superseded) is settled durably instead of sent (it would be dropped), and the execution continues.
1227
+ await settleClosed(unresolved, entries);
1228
+ const receipt = unresolved && answerSettled(unresolved, entries);
1155
1229
  const openingRid = t.opening && contentHash([t.opening.rid, "dispatch"]);
1156
1230
  const openingReceived = openingRid && entries.some(e => receiptId(e) === openingRid);
1157
1231
  // The task has one identity: the dispatch of the call's first execution. A later execution continues only once
@@ -1164,7 +1238,7 @@ export default function createExecutor(ledgers, options = {}) {
1164
1238
  else if (!openingRid && !taskReceived)
1165
1239
  await sender.send(t.callId, "task", { message: t.spec.task }, undefined, { rid: taskRid });
1166
1240
  else if (unresolved && !receipt)
1167
- await sender.send(t.callId, "continue", { message: String(unresolved.message) }, { qid: String(unresolved.qid), rev: Number(unresolved.rev) }, { rid: String(unresolved.rid2) });
1241
+ await sender.send(t.callId, "continue", { message: String(unresolved.message), ...(Array.isArray(unresolved.superseded) ? { superseded: unresolved.superseded } : {}) }, { qid: String(unresolved.qid), rev: Number(unresolved.rev) }, { rid: String(unresolved.rid2) });
1168
1242
  else if (previous) {
1169
1243
  // After launches that failed for a reason of the environment, no child received their dispatches: the first
1170
1244
  // execution of that run of failures keeps its dispatch (rid and content), so one is pending, not one per retry.
@@ -1239,29 +1313,49 @@ export default function createExecutor(ledgers, options = {}) {
1239
1313
  */
1240
1314
  async function adoptAnswer(journal, call, sleeping) {
1241
1315
  const entries = await readCall(journal, call);
1242
- await serial(async () => {
1243
- const all = journal.entries();
1244
- if (all.some(e => e.type === "answer-bound" && e.call === call && e.qid === sleeping.qid && e.rev === sleeping.rev))
1245
- return;
1246
- const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
1247
- const f = all.find(e => {
1248
- if (e.type !== "forward" || e.dest !== call)
1249
- return false;
1250
- const env = e.envelope;
1251
- return env.kind === "answer" && env.cond?.qid === sleeping.qid && env.cond?.rev === sleeping.rev && !receipts.has(String(e.rid2)) &&
1252
- !all.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || r.type === "forward-delivered"));
1253
- });
1254
- if (!f)
1255
- return;
1256
- const item = attentionEntries(all).find(e => e.item.call === call && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
1257
- const message = String(f.envelope.body?.message ?? "");
1258
- // A new identity: the stale answer may still sit in the child's inbox under the forward's rid2.
1259
- await journal.append("answer-bound", { event: true, call, qid: sleeping.qid, rev: sleeping.rev, rid: f.rid, rid2: contentHash([String(f.rid2), "hibernated"]), hash: f.hash,
1260
- message: `${HIBERNATED_NOTE}\n\nQuestion: ${item?.text ?? sleeping.qid}\nAnswer: ${message}` });
1261
- await resolveBoundAnswer(journal, call, sleeping.qid, sleeping.rev);
1262
- await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
1263
- await (await outbox).markResolved(String(f.rid2));
1316
+ await serial(() => adopt(journal, call, sleeping, entries));
1317
+ }
1318
+ /** The forward whose adoption was begun (its envelope withdrawn from the child's inbox) and not yet bound. */
1319
+ async function adoptionBegun(journal, call) {
1320
+ const sender = await outbox, all = journal.entries();
1321
+ return all.find(e => e.type === "forward" && e.dest === call && e.envelope.kind === "answer" &&
1322
+ !all.some(r => r.rid2 === e.rid2 && r.type === "forward-retired") && !!sender.recorded(contentHash([String(e.rid2), "withdraw-adopted"])));
1323
+ }
1324
+ /** P28, D3: bind a pending answer forward to hibernation `sleeping` (see adoptAnswer). `onlyBegun`: only one whose
1325
+ * adoption was begun before a crash (its envelope is withdrawn, so it can reach the child only through this binding).
1326
+ * Called serially. */
1327
+ async function adopt(journal, call, sleeping, entries, onlyBegun = false) {
1328
+ const all = journal.entries();
1329
+ if (boundAnswer(all, sleeping))
1330
+ return;
1331
+ const begun = await adoptionBegun(journal, call);
1332
+ const receipts = new Set(entries.map(receiptId).filter(rid => rid !== undefined));
1333
+ // The answer to the question it hibernated on, else to another of its questions still open (an earlier one).
1334
+ const pending = all.filter(e => {
1335
+ if (e.type !== "forward" || e.dest !== call)
1336
+ return false;
1337
+ const env = e.envelope;
1338
+ return env.kind === "answer" && !receipts.has(String(e.rid2)) && !all.some(r => r.rid2 === e.rid2 && (r.type === "forward-retired" || r.type === "forward-delivered")) &&
1339
+ (env.cond?.qid === sleeping.qid && env.cond?.rev === sleeping.rev || openAsked(all, call, env.cond?.qid, env.cond?.rev));
1264
1340
  });
1341
+ // An adoption begun before a crash is completed first: its envelope is already withdrawn.
1342
+ const f = pending.find(e => e.rid2 === begun?.rid2) ?? (onlyBegun ? undefined : pending.find(e => e.envelope.cond?.qid === sleeping.qid) ?? pending[0]);
1343
+ if (!f)
1344
+ return;
1345
+ const { qid, rev } = f.envelope.cond;
1346
+ const item = attentionEntries(all).find(e => e.item.call === call && e.item.qid === qid && e.item.rev === rev)?.item;
1347
+ const message = String(f.envelope.body?.message ?? "");
1348
+ // A new identity: the stale answer may still sit in the child's inbox under the forward's rid2. It is withdrawn
1349
+ // there (D3; before the bound continue is sent, so the resumed child drops it first): the continue carries the
1350
+ // answer and what it supersedes. Idempotent by rid, so a crash before the binding sends it once.
1351
+ await (await outbox).send(call, "withdraw", { rids: [String(f.rid2)] }, undefined, { rid: contentHash([String(f.rid2), "withdraw-adopted"]) });
1352
+ await journal.append("answer-bound", { event: true, call, qid, rev, rid: f.rid, rid2: contentHash([String(f.rid2), "hibernated"]), hash: f.hash,
1353
+ message: `${HIBERNATED_NOTE}${withdrawn(all, call, sleeping, qid, rev)}\n\nQuestion: ${item?.text ?? qid}\nAnswer: ${message}`, ...supersedes(sleeping, qid, rev) });
1354
+ await resolveBoundAnswer(journal, call, qid, rev);
1355
+ if (qid !== sleeping.qid || rev !== sleeping.rev)
1356
+ await resolveQuestion(journal, call, sleeping.qid, sleeping.rev, "superseded");
1357
+ await journal.append("forward-retired", { rid: f.rid, rid2: f.rid2, reason: "bound-to-hibernation" });
1358
+ await (await outbox).markResolved(String(f.rid2));
1265
1359
  }
1266
1360
  async function replayForward(e) {
1267
1361
  const envelope = e.envelope;
@@ -1346,17 +1440,32 @@ export default function createExecutor(ledgers, options = {}) {
1346
1440
  return { action: "reject", reason: req.kind === "send" && req.body.kind === "answer" ? "retired" : "call-sealed" };
1347
1441
  if (req.kind === "send" && req.body.kind === "answer") {
1348
1442
  const sleeping = hibernation(ctx.journal, dest);
1443
+ // An adoption begun before a crash (the earlier answer withdrawn from the inbox, not yet bound) binds first.
1444
+ if (sleeping && current(ctx.journal, dest) === sleeping.exec && !boundAnswer(ctx.journal.entries(), sleeping) && await adoptionBegun(ctx.journal, dest))
1445
+ await adopt(ctx.journal, dest, sleeping, await readCall(ctx.journal, dest), true);
1349
1446
  const priorAnswer = ctx.journal.entries().find(e => e.type === "answer-bound" && e.call === dest && e.qid === req.cond?.qid && e.rev === req.cond?.rev);
1350
1447
  if (priorAnswer)
1351
1448
  return priorAnswer.rid === req.rid && priorAnswer.hash === hash ? { action: "apply" } : { action: "reject", reason: "already-answered" };
1352
- if (sleeping && current(ctx.journal, dest) === sleeping.exec) {
1353
- if (sleeping.qid !== req.cond?.qid || sleeping.rev !== req.cond?.rev)
1354
- return { action: "reject", reason: "stale-rev" };
1449
+ // D2, D4: a superseded or carried question takes no answer.
1450
+ if (supersededByBinding(ctx.journal.entries(), dest, req.cond?.qid, req.cond?.rev) ||
1451
+ ctx.journal.entries().some(e => e.type === JT.attentionResolved && e.id === `q:${dest}:${req.cond?.qid}` && e.rev === req.cond?.rev && (e.resolution === "superseded" || e.resolution === "carried")))
1452
+ return { action: "reject", reason: "stale-rev" };
1453
+ // A hibernated call takes one answer: to the question it hibernated on, or to another of its open questions (an
1454
+ // earlier one, still open while the child asked a reminder). Once one is bound, a further answer to another
1455
+ // open question is forwarded like any other: the resumed child takes it at its next ask.
1456
+ if (sleeping && current(ctx.journal, dest) === sleeping.exec &&
1457
+ !(sleeping.qid === req.cond?.qid && sleeping.rev === req.cond?.rev) && !openAsked(ctx.journal.entries(), dest, req.cond?.qid, req.cond?.rev))
1458
+ return { action: "reject", reason: "stale-rev" };
1459
+ if (sleeping && current(ctx.journal, dest) === sleeping.exec && !boundAnswer(ctx.journal.entries(), sleeping)) {
1460
+ const { qid, rev } = req.cond;
1355
1461
  const rid2 = forwardRid(req.rid, ctx.widRev, ctx.key, hash);
1356
- const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid === sleeping.qid && e.item.rev === sleeping.rev)?.item;
1462
+ const item = attentionEntries(ctx.journal.entries()).find(e => e.item.call === dest && e.item.qid === qid && e.item.rev === rev)?.item;
1357
1463
  // `event`: the `answered` event derives from this entry (an unmarked older one: from its resolution).
1358
- await ctx.journal.append("answer-bound", { event: true, call: dest, qid: sleeping.qid, rev: sleeping.rev, rid: req.rid, rid2, hash, message: `${HIBERNATED_NOTE}\n\nQuestion: ${item?.text ?? sleeping.qid}\nAnswer: ${req.body.message ?? ""}` });
1359
- await resolveBoundAnswer(ctx.journal, dest, sleeping.qid, sleeping.rev);
1464
+ await ctx.journal.append("answer-bound", { event: true, call: dest, qid, rev, rid: req.rid, rid2, hash,
1465
+ message: `${HIBERNATED_NOTE}${withdrawn(ctx.journal.entries(), dest, sleeping, qid, rev)}\n\nQuestion: ${item?.text ?? qid}\nAnswer: ${req.body.message ?? ""}`, ...supersedes(sleeping, qid, rev) });
1466
+ await resolveBoundAnswer(ctx.journal, dest, qid, rev);
1467
+ if (qid !== sleeping.qid || rev !== sleeping.rev)
1468
+ await resolveQuestion(ctx.journal, dest, sleeping.qid, sleeping.rev, "superseded");
1360
1469
  active.get(dest)?.wake();
1361
1470
  wake();
1362
1471
  return { action: "apply" };
@@ -1540,6 +1649,11 @@ export default function createExecutor(ledgers, options = {}) {
1540
1649
  await retireAttention(journal, call);
1541
1650
  await unknownAttention(journal, call);
1542
1651
  }
1652
+ else {
1653
+ await resolveSuperseded(journal, call);
1654
+ if (session.length)
1655
+ await resolveCarried(journal, call, digestOf(call, session).questions);
1656
+ }
1543
1657
  });
1544
1658
  if (!active.has(call))
1545
1659
  forgetCall(call);
@@ -1,10 +1,10 @@
1
1
  // Read-only status snapshots (P25: `status` is always a fresh snapshot). Pure readers of committed journals:
2
2
  // never depend on orchestrator memory, so the UI, the CLI and the main agent see the same durable state.
3
3
  import { initiatorSummary, restartLine } from "./restart.js";
4
- import { existsSync, readFileSync, readdirSync } from "node:fs";
4
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { compileFanout } from "../compat/fanout.js";
7
- import { readJournalSnapshot } from "../kernel/journal.js";
7
+ import { readJournalSnapshot, readJournalUncached } from "../kernel/journal.js";
8
8
  import { journalPath, orchLedger, pinnedDir, workflowDir } from "../paths.js";
9
9
  import { JT, isEntry } from "../types.js";
10
10
  import { emptyLedger, foldLedger } from "./ledger.js";
@@ -162,6 +162,9 @@ function snapshotReducer(wid, entries) {
162
162
  hibernating.set(call.callId, call.exec);
163
163
  if (fenced.has(call.exec))
164
164
  call.hibernated = true;
165
+ // D6: hibernated again after a bound answer the session had already closed: it waits for a new answer.
166
+ if (call.phase !== "sealed")
167
+ delete call.answered;
165
168
  }
166
169
  }
167
170
  else if (e.type === "answer-bound") {
@@ -401,7 +404,7 @@ const ledgerIndexes = new WeakMap();
401
404
  export function ledgerIndex(ledger) {
402
405
  let ix = ledgerIndexes.get(ledger);
403
406
  if (!ix || ix.length > ledger.length || (ix.length && ledger[ix.length - 1] !== ix.last)) {
404
- ix = { length: 0, created: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(), byWid: new Map(), byOrigin: new Map() };
407
+ ix = { length: 0, created: new Map(), intents: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(), byWid: new Map(), byOrigin: new Map() };
405
408
  ledgerIndexes.set(ledger, ix);
406
409
  }
407
410
  for (let i = ix.length; i < ledger.length; i++) {
@@ -422,6 +425,10 @@ export function ledgerIndex(ledger) {
422
425
  ix.runSessions.delete(String(e.rid));
423
426
  }
424
427
  }
428
+ else if (e.type === "create-intent") {
429
+ if (!ix.intents.has(String(e.wid)))
430
+ ix.intents.set(String(e.wid), e.origin);
431
+ }
425
432
  else if (e.type === "request") {
426
433
  const r = e.request, labels = r?.kind === "run" ? labelsOf(r.body) : undefined;
427
434
  if (labels && typeof r?.rid === "string")
@@ -490,6 +497,50 @@ export function heldWorkflows(home) {
490
497
  const since = ix.lastDrain !== undefined ? ledger[ix.lastDrain].ts : undefined;
491
498
  return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined, labels: wid => ix.labels.get(wid), session: wid => ix.sessions.get(wid) };
492
499
  }
500
+ /** The origin of a workflow's `wf-created`, the first entry of its journal, for a workflow the ledger does not attribute
501
+ * (only a damaged or hand-made home has one), read without keeping the journal in the snapshot cache. The first entry
502
+ * never changes once written, so a successful read is kept for the life of the process. A journal that cannot be read
503
+ * counts as no origin (no session's own) only while it stays as it was: the failure is kept with the file's identity
504
+ * (inode, size, ctime and mode: ctime ticks coarsely, so a chmod right after the failure may leave it unchanged) and
505
+ * the read is retried once that changes. A journal without its first
506
+ * entry yet is asked again. */
507
+ const firstOrigins = new Map();
508
+ function firstOrigin(home, wid) {
509
+ const path = journalPath(home, wid), known = firstOrigins.get(path);
510
+ if (known && "origin" in known)
511
+ return known.origin;
512
+ const identity = () => { try {
513
+ const st = statSync(path);
514
+ return { ino: st.ino, size: st.size, ctimeMs: st.ctimeMs, mode: st.mode };
515
+ }
516
+ catch {
517
+ return undefined;
518
+ } };
519
+ const same = (a, b) => !!a && !!b && a.ino === b.ino && a.size === b.size && a.ctimeMs === b.ctimeMs && a.mode === b.mode;
520
+ // The identity is taken before the read, and a failure is kept only when the file did not change during the read:
521
+ // a chmod between the failed read and a later sample would otherwise be recorded as the failure's identity.
522
+ const before = identity();
523
+ if (known && same(before, known.failed))
524
+ return undefined;
525
+ let first;
526
+ try {
527
+ first = readJournalUncached(path)?.entries[0];
528
+ }
529
+ catch {
530
+ if (same(before, identity()))
531
+ firstOrigins.set(path, { failed: before });
532
+ else
533
+ firstOrigins.delete(path);
534
+ return undefined;
535
+ }
536
+ if (!first) {
537
+ firstOrigins.delete(path);
538
+ return undefined;
539
+ }
540
+ const origin = first.type === "wf-created" ? first.origin : undefined;
541
+ firstOrigins.set(path, { origin });
542
+ return origin;
543
+ }
493
544
  /** The workflow with its run's labels and session, when it has them. */
494
545
  function labelled(wf, labels, session) {
495
546
  return labels || session ? { ...wf, ...(labels ? { labels } : {}), ...(session ? { session } : {}) } : wf;
@@ -508,8 +559,35 @@ export function labelsText(labels, width = 60) {
508
559
  }
509
560
  /** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
510
561
  export function allWorkflows(home) {
562
+ return snapshotsOf(home, workflowIds(home));
563
+ }
564
+ function snapshotsOf(home, wids) {
511
565
  const { held, labels, session } = heldWorkflows(home);
512
- return workflowIds(home).sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid), session(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
566
+ return wids.sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid), session(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
567
+ }
568
+ /** The workflows `own` ("main:<pi session id>") shows as its own (`ownedBy`), snapshotted exactly as `allWorkflows`
569
+ * does: the same list as `allWorkflows(home).filter(w => ownedBy(w, own))`, but who owns a workflow is decided from
570
+ * the orchestrator ledger alone (the origin of its create-intent or `created`, the session its run named), so the
571
+ * journals of other sessions' workflows are never opened. A pi process polls only its own workflows: reading and
572
+ * caching every workflow of the machine cost it seconds at startup and hundreds of MB.
573
+ * The engine records a workflow's create-intent (with its origin) before it creates the workflow's directory, so a
574
+ * workflow just being created is already attributed; its `session` (like `allWorkflows`) shows once `created` lands.
575
+ * A directory under `w/` the ledger knows nothing of (given the order below, only a hand-made or damaged home has one)
576
+ * is attributed by its journal's first entry (see firstOrigin). `started`: only those `own` started itself (origin `own`),
577
+ * not runs of other senders that named its session. */
578
+ export function ownWorkflows(home, own, options = {}) {
579
+ // Order matters: list `w/` first, then read the ledger used for attribution. The engine appends a workflow's
580
+ // create-intent before it creates the directory, so every directory listed here already has its intent in a ledger
581
+ // read afterwards; a workflow another session creates in between is attributed without opening its journal. (Read
582
+ // the other way round, such a workflow would look unknown to the ledger and its journal would be read.)
583
+ const wids = workflowIds(home), ix = ledgerIndex(readJournalSnapshot(orchLedger(home)));
584
+ const mine = wids.filter(wid => {
585
+ const known = ix.intents.has(wid) || ix.created.has(wid), session = ix.sessions.get(wid);
586
+ const origin = known ? ix.intents.get(wid) ?? ix.created.get(wid)?.origin : firstOrigin(home, wid);
587
+ return origin === own || (!options.started && session !== undefined && `main:${session}` === own);
588
+ });
589
+ // The journal decides as well: a workflow whose wf-created is not written yet has no origin, as in allWorkflows.
590
+ return snapshotsOf(home, mine).filter(w => options.started ? w.origin === own : ownedBy(w, own));
513
591
  }
514
592
  /** P10/P11: Per-workflow script console log written by the orchestrator (bounded, human-readable). */
515
593
  export function scriptLogPath(home, wid) { return join(workflowDir(home, wid), "script.log"); }
package/dist/ui/data.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { readJournalSnapshot } from "../kernel/journal.js";
4
- import { allWorkflows } from "../orchestrator/snapshot.js";
4
+ import { allWorkflows, ownWorkflows } from "../orchestrator/snapshot.js";
5
5
  import { callDir, callSession, journalPath, orchLedger } from "../paths.js";
6
6
  import { LIVE_FILE } from "../agent/child/live.js";
7
7
  import { JT } from "../types.js";
@@ -80,8 +80,11 @@ export class UiData {
80
80
  derived = new Map();
81
81
  home;
82
82
  constructor(home) { this.home = home; }
83
- refresh() {
84
- const workflows = allWorkflows(this.home), known = new Set(), deferred = new Map();
83
+ /** Read the workflows `own` ("main:<pi session id>") shows as its own (see ownWorkflows): the pi process reads only
84
+ * its own workflows, so other sessions' journals and call sessions are never opened, stat'ed or cached here. Without
85
+ * an owner every workflow is read (fixtures and tools that show them all). */
86
+ refresh(own) {
87
+ const workflows = own === undefined ? allWorkflows(this.home) : ownWorkflows(this.home, own), known = new Set(), deferred = new Map();
85
88
  const facts = new LazyMap(key => deferred.get(key)?.());
86
89
  const sessions = new LazyMap(key => deferred.has(key) ? deferred.get(key)() : this.transcript(key, sessions));
87
90
  for (const w of workflows) {
package/dist/ui/index.js CHANGED
@@ -67,11 +67,13 @@ export function registerUi(pi, deps) {
67
67
  if (stopped)
68
68
  return;
69
69
  try {
70
- data.refresh();
70
+ // This session's workflows only: ownership comes from the orchestrator ledger, and other sessions' journals are
71
+ // never read by this pi process. orderWorkflows filters by the same rule and orders the list.
72
+ const own = `main:${ctx.sessionManager.getSessionId()}`;
73
+ data.refresh(own);
71
74
  actions.reconcile();
72
75
  for (const result of actions.resolutions.splice(0))
73
76
  screen?.controlResult(result);
74
- const own = `main:${ctx.sessionManager.getSessionId()}`;
75
77
  data.workflows = orderWorkflows(data.workflows, own);
76
78
  // UI §1: the dock — live rows per active agent plus a summary line ("auto"), only the summary ("line"), or nothing.
77
79
  const name = (model) => modelLabel(model, (p, id) => ctx.modelRegistry.find(p, id), data.aliases);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.37",
3
+ "version": "1.0.39",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",