pi-durable-subagents 1.0.45 → 1.1.0

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/dist/cli/main.js CHANGED
@@ -17,6 +17,7 @@ import { leaseLines, leaseState } from "../platform/lease.js";
17
17
  import { resolvePi } from "../platform/launch.js";
18
18
  import { currentOrchestrator, decidedBy, legacyRestart, cliInitiator, waitExit, waitSuccessor } from "./restart.js";
19
19
  import { restartInputError } from "../orchestrator/restart.js";
20
+ import { packageVersion } from "../version.js";
20
21
  const commands = ["smoke", "tail", "status", "events", "start", "resume", "drain", "stop", "stop-all", "prune", "restart", "leases", "doctor", "install-service", "uninstall-service", "help"];
21
22
  /** P25: Reject ambiguous CLI arguments before any durable action. */
22
23
  export function parseArgs(args) {
@@ -182,7 +183,7 @@ export function serviceEntryError(entry) {
182
183
  return `install-service refuses to run from an npx cache (${entry}); the cache can be pruned and the service would break. Install the CLI with \`npm i -g pi-durable-subagents\` and run \`pi-durable-subagents install-service\` again.`;
183
184
  return undefined;
184
185
  }
185
- export const HELP = "pi-durable-subagents: smoke | status [wid] [--json] | status <wid> [--tail <n>] [--grep <regex>] [--json] | events <wid> [--json] | events --all [--since <cursor>] [--limit <n>] [--json] [--wait-ms <n>] | tail [wid] [--json] | start | resume [wid] | drain | stop <wid|callId> | stop-all | run --request <id> --spec <file|-> [--labels <json>] [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>] | send --request <id> --to <run-id|wid/key> [--to ...] [--call <key>] --kind follow-up|answer|steer|notify|model [--qid <qid> --rev <n>] [--message <text|@file>] [--model <m>] [--json] [--wait-ms <n>] | stop --request <id> <run-id|wid|wid/key> [--json] [--wait-ms <n>] | describe --key <id> | describe <wid> [--json] | prune [wid] [--older-than <days>] | restart [--force <token> --reason <text>] | hold <resource> [--shared | --slots <n>] [--max-wait <s> | --no-wait] [--note <text>] -- <command…> | leases [--json] | doctor [--json] | install-service [--dry-run] | uninstall-service [--dry-run] | chaos [--scenario <1-9>] [--keep] [--json] | drill failover [--keep] [--json]";
186
+ export const HELP = "pi-durable-subagents: smoke | status [wid] [--json] | status <wid> [--tail <n>] [--grep <regex>] [--json] | events <wid> [--json] | events --all [--since <cursor>] [--limit <n>] [--json] [--wait-ms <n>] | tail [wid] [--json] | start | resume [wid] | drain | stop <wid|callId> | stop-all | version | --version | run --request <id> [--wake caller] --spec <file|-> [--labels <json>] [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>] | run --request <id> [--wake caller] [--cwd <dir>] [--timeout-ms <n>] [--name <text>] [--labels <json>] [--session <id>] [--json] [--wait-ms <n>] -- <program> [args…] | send --request <id> --to <run-id|wid/key> [--to ...] [--call <key>] --kind follow-up|answer|steer|notify|model [--qid <qid> --rev <n>] [--message <text|@file>] [--model <m>] [--json] [--wait-ms <n>] | stop --request <id> <run-id|wid|wid/key> [--json] [--wait-ms <n>] | describe --key <id> | describe <wid> [--json] | prune [wid] [--older-than <days>] | restart [--force <token> --reason <text>] | hold <resource> [--shared | --slots <n>] [--priority <n>] [--yield] [--expect <duration>] [--max-wait <s> | --no-wait] [--note <text>] -- <command…> | leases [--json] | doctor [--json] | install-service [--dry-run] | uninstall-service [--dry-run] | chaos [--scenario <1-9>] [--keep] [--json] | drill failover [--keep] [--json]";
186
187
  /** Restart: the orchestrator exits when no execution runs (or `force`) and the installed version takes over. */
187
188
  async function restartCommand(home, env, write, options) {
188
189
  const body = { ...(typeof options.force === "string" ? { token: options.force } : options.force === true ? { force: true } : {}), ...(options.reason !== undefined ? { reason: options.reason } : {}), initiator: cliInitiator(env) };
@@ -238,6 +239,10 @@ async function restartCommand(home, env, write, options) {
238
239
  }
239
240
  /** P1, P21, P25, P38: Dispatch the public CLI using durable requests and read-only snapshots. */
240
241
  export async function main(args = process.argv.slice(2), options = {}) {
242
+ if (args.length === 1 && (args[0] === "version" || args[0] === "--version")) {
243
+ (options.write ?? console.log)(`pi-durable-subagents ${packageVersion()}`);
244
+ return 0;
245
+ }
241
246
  if (args[0] === "hold") {
242
247
  const { hold, parseHold } = await import("./hold.js");
243
248
  return hold(parseHold(args.slice(1)), { env: options.env ?? process.env });
@@ -8,8 +8,8 @@ import { findJournalEntry, readJournalFold, readJournalSnapshot } from "../kerne
8
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, HOLD_ENTRY_TYPES, commandLine, commandSendRefusal, isCommandTarget, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
- import { leaseCalls, leaseState } from "../platform/lease.js";
11
+ import { NOTIFY_SINCE, WAKE_SINCE, HOLD_ENTRY_TYPES, commandLine, commandSendRefusal, isCommandTarget, heldIn, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
+ import { leaseCalls, leaseState, callAddress } 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";
@@ -17,6 +17,7 @@ import { startOrchestrator, submitIdentified } from "./control.js";
17
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 { awaitingRuns, wakeStatus } from "../orchestrator/reader-ledger.js";
20
21
  import { LEDGER_ENTRY_TYPES, emptyLedger, foldLedger } from "../orchestrator/ledger.js";
21
22
  export const EXIT = { ok: 0, rejected: 1, conflict: 3, pending: 75 };
22
23
  /** Strict `--name value` / `--flag` parsing; unknown or repeated options are errors, except those given in `repeated`
@@ -88,7 +89,7 @@ export async function describe(home, key, now = Date.now()) {
88
89
  // A send or stop has no workflow of its own: its decision is the outcome.
89
90
  if (decided && found.request.kind !== "run")
90
91
  return { state: "applied", ...head };
91
- return { state: "pending", ...head };
92
+ return { state: "pending", ...head, ...(wakeStatus(home, found.request) ? { wake: wakeStatus(home, found.request) } : {}) };
92
93
  }
93
94
  /** `{labels}` of a run request that has any. */
94
95
  function labelsOf(request) {
@@ -121,7 +122,7 @@ function describeWorkflow(home, wid, entries, now) {
121
122
  const pruned = entries.find(e => e.type === "pruned" && e.wid === wid);
122
123
  if (pruned)
123
124
  return { state: "pruned", wid, pruned: { ...(pruned.status !== undefined ? { status: String(pruned.status) } : {}), endedAt: Number(pruned.endedAt) },
124
- ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(home, entries, wid).run) };
125
+ ...(typeof pruned.request === "string" ? { request: pruned.request } : {}), ...(typeof pruned.spec_digest === "string" ? { spec_digest: pruned.spec_digest } : {}), ...labelsOf(runOf(home, entries, wid).run), ...(pruned.wake ? { wake: pruned.wake } : {}) };
125
126
  if (!/^[^/\\\0]+$/.test(wid) || wid === "." || wid === ".." || !existsSync(journalPath(home, wid)))
126
127
  return { state: "absent", wid };
127
128
  // The snapshot and the journal the wait fold reads must be the same bytes (a writer-wait appended between the two reads
@@ -145,7 +146,9 @@ function describeWorkflow(home, wid, entries, now) {
145
146
  ...(c.hibernated ? { hibernated: true } : {}), ...waits.get(c.callId)
146
147
  };
147
148
  const run = c.command !== undefined ? c.commandRun : undefined, live = !r && run !== undefined;
148
- return { key: c.key, gen: c.gen, phase: c.phase, agent: c.agent, ...(c.model ? { model: c.model } : {}),
149
+ const awaiting = awaitingRuns(home, wid, c.key, wf.rev);
150
+ return { key: c.key, gen: c.gen, phase: c.phase, agent: c.agent, ...(c.phase === 'sealed' && c.endedAt !== undefined ? { sealedAt: c.endedAt } : {}), ...(awaiting ? { awaiting } : {}),
151
+ ...(c.endedAtSeal ? { endedAtSeal: c.endedAtSeal } : {}), ...(c.endedAtSealMore ? { endedAtSealMore: c.endedAtSealMore } : {}), ...(c.model ? { model: c.model } : {}),
149
152
  ...(c.command !== undefined ? { command: commandLine(c.command, 200) } : {}), ...(run?.attempt !== undefined ? { attempt: run.attempt } : {}),
150
153
  ...(live && run.pid !== undefined ? { pid: run.pid } : {}), ...(live && c.startedAt !== undefined ? { elapsed: commandAge(now - c.startedAt) } : {}),
151
154
  ...(run?.log ? { log: run.log } : {}),
@@ -158,7 +161,7 @@ function describeWorkflow(home, wid, entries, now) {
158
161
  const state = questions.length ? "asking" : isLive(wf) || wf.status === "parked" ? "running" : "sealed";
159
162
  const fence = lastFence(journal, entries);
160
163
  return { state, wid, ...(id ? { request: id } : {}), ...(admitted ? { spec_digest: specDigest(admitted) } : {}), ...labelsOf(run), status: wf.status, ...(wf.error ? { error: wf.error } : {}),
161
- calls, ...(questions.length ? { questions } : {}), ...(attention.length ? { attention } : {}), ...(fence ? { lastFence: fence } : {}) };
164
+ ...(wakeStatus(home, run, wid) ? { wake: wakeStatus(home, run, wid) } : {}), calls, ...(questions.length ? { questions } : {}), ...(attention.length ? { attention } : {}), ...(fence ? { lastFence: fence } : {}) };
162
165
  }
163
166
  /** Best effort: why the latest fence that interrupted work happened. The per-execution classification and the
164
167
  * reason are shared with the event log's `fenced` events (src/events/fence.ts). */
@@ -178,6 +181,8 @@ export function renderDescription(d) {
178
181
  lines.push(` labels: ${Object.entries(d.labels).map(([k, v]) => `${k}=${v}`).join(" ")}`);
179
182
  if (d.pruned)
180
183
  lines.push(` pruned: ${d.pruned.status ?? "?"} at ${new Date(d.pruned.endedAt ?? 0).toISOString()}`);
184
+ if (d.wake)
185
+ lines.push(` wake: ${d.wake.to} ${d.wake.state}${d.wake.rev ? ` rev ${d.wake.rev}` : ''}${d.wake.generation ? ` generation ${d.wake.generation}` : ''}${d.wake.reason ? ` (${d.wake.reason})` : ''}`);
181
186
  if (d.error)
182
187
  lines.push(` error: ${d.error}`);
183
188
  for (const c of d.calls ?? []) {
@@ -187,6 +192,11 @@ export function renderDescription(d) {
187
192
  : ` ${c.key}@${c.gen} ${c.agent} ${c.phase}${c.status ? ` ${c.status}` : ""}${c.model ? ` (${c.model})` : ""}${c.error ? ` — ${c.error}` : ""}`);
188
193
  if (c.command !== undefined)
189
194
  lines.push(` command: ${c.command}`, ...(c.log ? [` log: ${c.log}`] : []));
195
+ if (c.awaiting)
196
+ for (const run of c.awaiting)
197
+ lines.push(` awaiting: ${run.request}${run.wid ? ` (${run.wid})` : ''} ${run.state}`);
198
+ if (c.endedAtSeal)
199
+ lines.push(` ended at seal: ${JSON.stringify(c.endedAtSeal)}${c.endedAtSealMore ? ` (${c.endedAtSealMore} more)` : ''}`);
190
200
  if (c.waiting)
191
201
  lines.push(` waiting: ${JSON.stringify(c.waiting)}`);
192
202
  if (c.data !== undefined)
@@ -312,21 +322,40 @@ export function runSession(flag, env) {
312
322
  * form ({agent,task,…}, {command,…} or {tasks|chain:[…],…}); it is validated by the tool's own normalizer and agent check. */
313
323
  export const runCommand = (args, ctx) => refusable(args, ctx, runRequest);
314
324
  async function runRequest(args, ctx, seen) {
315
- const { values, positionals } = flags(args, { request: "value", spec: "value", cwd: "value", labels: "value", session: "value", json: "flag", "wait-ms": "value" });
325
+ const dash = args.indexOf("--"), argv = dash < 0 ? undefined : args.slice(dash + 1);
326
+ const { values, positionals } = flags(dash < 0 ? args : args.slice(0, dash), { request: "value", spec: "value", wake: "value", "timeout-ms": "value", name: "value", cwd: "value", labels: "value", session: "value", json: "flag", "wait-ms": "value" });
316
327
  const id = text(values, "request"), file = text(values, "spec"), json = values.json === true, wait = waitMs(values, ctx);
317
328
  seen.id = id;
318
329
  seen.json = json;
319
- if (!id || !file || positionals.length)
320
- throw new Error("usage: run --request <id> --spec <file|-> [--labels <json>] [--session <pi session id>] [--cwd <dir>] [--json] [--wait-ms <n>]");
330
+ if (file !== undefined && argv !== undefined)
331
+ throw new Error("--spec and -- are mutually exclusive");
332
+ if (argv === undefined && (values["timeout-ms"] !== undefined || values.name !== undefined))
333
+ throw new Error("--timeout-ms and --name require -- <program> [args…]");
334
+ if (!id || (file === undefined && argv === undefined) || positionals.length || (argv !== undefined && !argv[0]))
335
+ throw new Error("usage: run --request <id> [--wake caller] (--spec <file|-> | -- <program> [args…])");
336
+ const wake = text(values, "wake");
337
+ if (wake !== undefined && wake !== "caller")
338
+ throw new Error("--wake takes exactly caller");
339
+ if (wake && !ctx.env.DSA_CALL)
340
+ throw new Error("--wake caller needs DSA_CALL: run it from inside a subagent call");
341
+ if (wake && callAddress(ctx.env.DSA_CALL) === ctx.env.DSA_CALL)
342
+ throw new Error("--wake caller needs a valid DSA_CALL");
343
+ const timeout = text(values, "timeout-ms");
344
+ if (timeout !== undefined && (!/^[1-9]\d*$/.test(timeout) || !Number.isSafeInteger(Number(timeout))))
345
+ throw new Error("--timeout-ms needs a positive integer");
321
346
  requestRid(id);
322
347
  const raw = text(values, "labels"), labels = raw !== undefined ? parseLabels(raw) : undefined;
323
- const bytes = file === "-" ? await (ctx.stdin ?? stdin)() : readFileSync(resolve(ctx.cwd ?? process.cwd(), file), "utf8");
324
348
  let spec;
325
- try {
326
- spec = JSON.parse(bytes);
327
- }
328
- catch (error) {
329
- throw new Error(`--spec is not JSON: ${error.message}`);
349
+ if (argv !== undefined)
350
+ spec = { command: argv, ...(timeout !== undefined ? { timeoutMs: Number(timeout) } : {}), ...(values.name !== undefined ? { name: text(values, "name") } : {}) };
351
+ else {
352
+ const bytes = file === "-" ? await (ctx.stdin ?? stdin)() : readFileSync(resolve(ctx.cwd ?? process.cwd(), file), "utf8");
353
+ try {
354
+ spec = JSON.parse(bytes);
355
+ }
356
+ catch (error) {
357
+ throw new Error(`--spec is not JSON: ${error.message}`);
358
+ }
330
359
  }
331
360
  if (!spec || typeof spec !== "object" || Array.isArray(spec))
332
361
  throw new Error("--spec must be a JSON object");
@@ -345,10 +374,17 @@ async function runRequest(args, ctx, seen) {
345
374
  const session = runSession(text(values, "session"), ctx.env);
346
375
  if (session)
347
376
  body.session = session;
377
+ if (wake) {
378
+ body.wake = { to: callAddress(ctx.env.DSA_CALL) };
379
+ body.caller = ctx.env.DSA_CALL;
380
+ }
348
381
  seen.digest = specDigest({ kind: "run", body });
349
382
  // An id already recorded is decided by that record: the same content gets its first outcome (the agents it named may
350
383
  // have changed since), other content is a request-conflict. Only a new id is checked here.
351
384
  const prior = (await findRequest(ctx.home, requestRid(id)))?.request;
385
+ const old = wake && !prior ? orchestratorTooOld(ctx.home, 'run --wake', WAKE_SINCE) : undefined;
386
+ if (old)
387
+ throw new Error(old);
352
388
  if (!prior)
353
389
  checkAgents(body, () => discoverAgents(dir, { home: ctx.env.HOME || undefined, agentDir: ctx.env.PI_CODING_AGENT_DIR || undefined }).agents.map(a => a.name));
354
390
  const done = await submitAndWait(ctx, seen, id, "run", body, undefined, wait, json);
@@ -57,7 +57,7 @@ export function unknownAgent(name, agents) {
57
57
  return `unknown agent ${JSON.stringify(name)}; available agents: ${agents.map(a => a.name).sort().join(", ") || "none"}`;
58
58
  }
59
59
  /** v12 §3: Wake with bounded latest-per-key results, preferring structured reports and preserving clipped tails. */
60
- export function finishedText(wid, entries, call) {
60
+ export function finishedText(wid, entries, call, commandOutput = false) {
61
61
  const snap = snapshotFromEntries(wid, entries), label = snap.name ?? wid;
62
62
  const latest = new Map(snap.calls.map(c => [c.key, c]));
63
63
  const calls = call ? snap.calls.filter(c => c.callId === call) : [...latest.values()];
@@ -74,7 +74,7 @@ export function finishedText(wid, entries, call) {
74
74
  // Share the space fairly: short results take what they need and the rest goes to longer ones (one agent may use it
75
75
  // all), so a notice is cut only when the results really exceed it; usage and the full-output hint are never lost.
76
76
  const want = calls.map(c => {
77
- const message = c.result && Object.hasOwn(c.result, 'data') ? JSON.stringify(c.result.data) : c.result?.output;
77
+ const message = commandOutput && c.command !== undefined ? c.result?.output : c.result && Object.hasOwn(c.result, 'data') ? JSON.stringify(c.result.data) : c.result?.output;
78
78
  return 120 + (message?.length ?? 0) + Math.min(320, c.result?.error?.length ?? 0);
79
79
  });
80
80
  const shares = new Array(calls.length).fill(0);
@@ -95,12 +95,25 @@ export function finishedText(wid, entries, call) {
95
95
  const title = `\n${tail(name, allowance - 1)}`;
96
96
  const error = result?.error && allowance - title.length > 10 ? `\n Error: ${tail(result.error, Math.min(300, allowance - title.length - 9))}` : '';
97
97
  const space = allowance - title.length - error.length;
98
- const message = result && Object.hasOwn(result, 'data') ? JSON.stringify(result.data) : result?.output;
98
+ const message = commandOutput && c.command !== undefined ? result?.output : result && Object.hasOwn(result, 'data') ? JSON.stringify(result.data) : result?.output;
99
99
  const line = title + (message && space > 4 ? `\n ${tail(message.trimEnd(), space - 3)}` : '') + error;
100
100
  lines.push(line);
101
101
  }
102
102
  return `${prefix}${lines.join('')}${footer}`;
103
103
  }
104
+ export function wakeText(rid, wid, done, entries) {
105
+ const calls = [...new Map(snapshotFromEntries(wid, entries).calls.map(c => [c.key, c])).values()];
106
+ const lines = calls.slice(0, 20).map(c => {
107
+ const data = c.command !== undefined ? c.result?.data : undefined;
108
+ const ms = data?.durationMs ?? (c.endedAt !== undefined && c.startedAt !== undefined ? c.endedAt - c.startedAt : 0);
109
+ return `${c.key}: ${callStatus(c)}${data?.exitCode != null ? ` exit ${data.exitCode}` : ''}${data?.signal ? ` signal ${data.signal}` : ''} (${Math.max(0, Math.round(ms))}ms)`;
110
+ });
111
+ if (calls.length > 20)
112
+ lines.push(`… ${calls.length - 20} more`);
113
+ const head = `Durable run ${rid} (${wid}) that you started with --wake caller finished: ${done.status}.\n${lines.join('\n')}\n`;
114
+ const prefix = head.slice(0, 4000), space = 4000 - prefix.length;
115
+ return prefix + (space > 0 ? tail(finishedText(wid, entries, undefined, true), space) : '');
116
+ }
104
117
  /** A1, P2, P10, P11: Serialize decisions while executions run independently. */
105
118
  /** A key's latest call in the current revision: its first call or its newest generation. */
106
119
  function latestCall(wf, key) {
@@ -172,7 +185,7 @@ export class Engine {
172
185
  }
173
186
  /** Nothing of the workflow is live: it ended (or parked), no script runs, no executor run or follow-up is open. */
174
187
  quiescent(wf) {
175
- if (!this.terminal(wf) || this.states.has(wf.wid) || this.running.has(wf.wid) || this.openFollowUps(wf))
188
+ if (!this.terminal(wf) || this.wakePending(wf) || this.states.has(wf.wid) || this.running.has(wf.wid) || this.openFollowUps(wf))
176
189
  return false;
177
190
  for (const id of this.generations)
178
191
  if (id.startsWith(`${wf.wid}@`))
@@ -517,7 +530,8 @@ export class Engine {
517
530
  throw error; });
518
531
  }
519
532
  }
520
- this.consumed = { length: this.intakeSeen, pending: view.open.size > 0 };
533
+ await this.deliverWakes();
534
+ this.consumed = { length: this.intakeSeen, pending: this.lifecycle().open.size > 0 };
521
535
  }
522
536
  findCall(to, bareWid = false) {
523
537
  for (const wf of this.store.workflows.values()) {
@@ -571,6 +585,23 @@ export class Engine {
571
585
  }
572
586
  if (req.kind === 'run') {
573
587
  const created = this.ledgers.orch.entries().find(e => e.type === JT.created && e.rid === req.rid);
588
+ if (!created && req.body?.wake !== undefined) {
589
+ const { wake, caller } = req.body;
590
+ const match = typeof caller === 'string' && /^([^@/]+)@(\d+)\/(.+)@(\d+)$/.exec(caller);
591
+ const parent = match ? this.store.workflows.get(match[1]) : undefined;
592
+ const refuse = (reason) => ({ action: 'reject', reason: `wake caller: ${reason}` });
593
+ if (!match || !wake || wake.to !== `${match[1]}/${match[3]}`)
594
+ return refuse('invalid caller');
595
+ if (!parent || this.store.pruned().has(parent.wid))
596
+ return refuse('workflow missing or pruned');
597
+ if (parent.revision !== Number(match[2]))
598
+ return refuse('stale-revision');
599
+ const entry = latestCall(parent, match[3]);
600
+ if (!entry)
601
+ return refuse('unknown key');
602
+ if (isCommandCall(entry.spec))
603
+ return refuse('command call');
604
+ }
574
605
  // Senders validate labels; a hand-written request must not bypass that.
575
606
  const labels = req.body?.labels, invalid = !created && labels !== undefined ? labelsProblem(labels) : undefined;
576
607
  if (invalid)
@@ -838,6 +869,8 @@ export class Engine {
838
869
  /** Housekeeping: Why a workflow cannot be pruned: not final (parked or running), open executor work, an unresolved
839
870
  * fence failure, or ended after the cutoff. */
840
871
  unprunable(wf, cutoff) {
872
+ if (this.wakePending(wf))
873
+ return 'wake pending';
841
874
  const done = this.terminal(wf), status = done ? String(done.status) : 'running';
842
875
  if (!['done', 'failed', 'stopped'].includes(status))
843
876
  return `not-finished:${status}`;
@@ -877,7 +910,9 @@ export class Engine {
877
910
  catch (error) {
878
911
  return `event-log: ${error instanceof Error ? error.message : String(error)}`;
879
912
  }
880
- await this.ledgers.orch.append('pruned', { rid, wid: wf.wid, endedAt: done.ts, bytes, status: String(done.status), ...identity });
913
+ const wake = wf.wake && wf.journal.entries().findLast(e => e.type === 'wake-outcome');
914
+ const wakeReceipt = wake ? { wake: { to: wf.wake.to, state: wake.state, rev: wake.rev, ...(wake.generation !== undefined ? { generation: wake.generation } : {}), ...(wake.reason !== undefined ? { reason: wake.reason } : {}) } } : {};
915
+ await this.ledgers.orch.append('pruned', { rid, wid: wf.wid, endedAt: done.ts, bytes, status: String(done.status), ...identity, ...wakeReceipt });
881
916
  this.states.delete(wf.wid);
882
917
  await this.store.drop(wf.wid);
883
918
  try {
@@ -1244,6 +1279,78 @@ export class Engine {
1244
1279
  if (done && !wf.journal.entries().some(e => isEntry(e, JT.attention) && e.item.id === `finished:${wf.wid}` && e.item.rev === rev)) {
1245
1280
  await wf.journal.append(JT.attention, { item: { id: `finished:${wf.wid}`, rev, kind: 'finished', wid: wf.wid, text: finishedText(wf.wid, wf.journal.entries()) } });
1246
1281
  }
1282
+ await this.deliverWake(wf);
1283
+ }
1284
+ /** A pending wake keeps the journal decoded and unprunable until its durable outcome is recorded. */
1285
+ wakePending(wf) {
1286
+ if (!wf.wake || lazy(wf))
1287
+ return false;
1288
+ const log = wf.journal.entries(), rev = log.filter(e => e.type === JT.done).length;
1289
+ return !rev || !log.some(e => e.type === 'wake-outcome' && e.rev === rev);
1290
+ }
1291
+ async deliverWakes() {
1292
+ for (const wf of this.store.workflows.values())
1293
+ if (wf.wake && !lazy(wf)) {
1294
+ await this.deliverWake(wf);
1295
+ this.settle(wf);
1296
+ }
1297
+ }
1298
+ /** The intent pins the message before admission. Lifecycle resolution and send's existing generation/forward
1299
+ * receipts make every crash cut replayable, including a crash between the send effect and its decision. */
1300
+ waking = new Map();
1301
+ deliverWake(wf) {
1302
+ const pending = this.waking.get(wf.wid);
1303
+ if (pending)
1304
+ return pending;
1305
+ const run = this.deliverWakeNow(wf).finally(() => { if (this.waking.get(wf.wid) === run)
1306
+ this.waking.delete(wf.wid); });
1307
+ this.waking.set(wf.wid, run);
1308
+ return run;
1309
+ }
1310
+ async deliverWakeNow(wf) {
1311
+ if (!wf.wake || lazy(wf))
1312
+ return;
1313
+ const { rid, to, caller } = wf.wake;
1314
+ const dones = wf.journal.entries().filter(e => e.type === JT.done);
1315
+ for (const [n, done] of dones.entries()) {
1316
+ const rev = n + 1;
1317
+ if (wf.journal.entries().some(e => e.type === 'wake-outcome' && e.rev === rev))
1318
+ continue;
1319
+ let intent = wf.journal.entries().find(e => e.type === 'wake-request' && e.rev === rev);
1320
+ if (!intent) {
1321
+ const target = this.findCall(to), id = target && `${target.wf.wid}@${target.wf.revision}/${target.entry.key}@${target.entry.gen}`;
1322
+ const seal = target?.wf.journal.entries().find(e => e.type === JT.sealed && e.call === id);
1323
+ if (target && `${target.wf.wid}@${target.wf.revision}` === caller.slice(0, caller.indexOf('/')) && seal?.result?.status === 'stopped') {
1324
+ await wf.journal.append('wake-outcome', { rev, state: 'skipped', reason: 'caller stopped' });
1325
+ continue;
1326
+ }
1327
+ const request = { rid: `wake-${contentHash([rid, rev]).slice(0, 32)}`, from: `wake:${rid}:${rev}`, to: 'orch', sseq: 1,
1328
+ kind: 'send', cond: { epoch: caller.slice(0, caller.indexOf('/')) }, body: { to, kind: 'follow-up', message: wakeText(requestId(rid) ?? rid, wf.wid, done, wf.journal.entries().filter(e => e.seq <= done.seq)) } };
1329
+ intent = await wf.journal.append('wake-request', { rev, request });
1330
+ }
1331
+ const request = intent.request;
1332
+ for (const { type, ...fields } of planDecisions(this.lifecycle(), [request], () => ({ action: 'defer' }))) {
1333
+ if (type === 'admitted')
1334
+ await this.ledgers.orch.append('request', { request });
1335
+ await this.ledgers.orch.append(type, fields);
1336
+ }
1337
+ let resolution = this.lifecycle().resolved.get(request.rid);
1338
+ if (!resolution) {
1339
+ const decision = await this.decide(request);
1340
+ if (decision.action === 'defer')
1341
+ return;
1342
+ for (const { type, ...fields } of planDecisions(this.lifecycle(), [request], () => decision))
1343
+ await this.ledgers.orch.append(type, fields);
1344
+ resolution = this.lifecycle().resolved.get(request.rid);
1345
+ }
1346
+ if (!resolution)
1347
+ continue;
1348
+ const target = this.findCall(to), opened = target && revisionEntries(target.wf).find(e => e.type === 'generation' && generationRids(e).includes(request.rid));
1349
+ const forward = target && target.wf.journal.entries().find(e => e.type === 'forward' && e.rid === request.rid);
1350
+ const generation = opened ? Number(opened.gen) : forward ? Number(String(forward.dest).match(/@(\d+)$/)?.[1]) : undefined;
1351
+ await wf.journal.append('wake-outcome', { rev, state: resolution.type === 'applied' ? 'applied' : 'rejected',
1352
+ ...(resolution.type === 'rejected' ? { reason: resolution.reason } : {}), ...(generation !== undefined ? { generation } : {}) });
1353
+ }
1247
1354
  }
1248
1355
  async resolveFinished(wf) {
1249
1356
  for (const { item } of attentionEntries(wf.journal.entries())) {
@@ -1,6 +1,13 @@
1
1
  // Command calls: the workflow journal records the executor writes for them (documented in index.ts) and the questions
2
2
  // the engine and recovery ask of them. Pure functions of the journal's entries.
3
+ import { delimiter } from "node:path";
4
+ import { binDir } from "../../paths.js";
3
5
  import { JT } from "../../types.js";
6
+ /** EX3: Custom/inherited tools win; the orchestrator's shim is the last PATH entry, never an empty entry. */
7
+ export function commandEnvironment(home, id, call, env) {
8
+ const bin = binDir(home), PATH = [...(env?.PATH ?? process.env.PATH ?? "").split(delimiter).filter(p => p && p !== bin), bin].join(delimiter);
9
+ return { ...process.env, ...env, PATH, DSA_EXEC: id, DSA_CALL: call, DSA_HOME: home };
10
+ }
4
11
  export const COMMAND_INTENT = "command-intent";
5
12
  export const COMMAND_STARTED = "command-started";
6
13
  export const COMMAND_SPAWN_FAILED = "command-spawn-failed";
@@ -0,0 +1,23 @@
1
+ import { commandLine } from "../../platform/cmdline.js";
2
+ /** EX1 / WK8: Agent fences only. The direct child's tracked identity is retained across recovery (old journals: first tracked). */
3
+ export async function fenceAgent(containment, journal, exec, tracked, child) {
4
+ const options = { beforeKill: async (targets, signal) => {
5
+ const identities = journal.entries().filter(e => e.type === "tracked" && e.exec === exec);
6
+ const direct = child ?? identities.find(e => e.child === true) ?? identities[0];
7
+ // R-11-3: a crash after spawn but before tracked leaves no provable direct identity. Roots of the target
8
+ // forest may be pi or orphaned descendants: omit all roots rather than ever reporting the direct child.
9
+ const pids = new Set(targets.map(p => p.pid));
10
+ const others = direct ? targets.filter(p => p.pid !== direct.pid || p.start !== direct.start)
11
+ : targets.filter(p => pids.has(p.ppid));
12
+ if (!others.length || signal.aborted)
13
+ return;
14
+ const commands = await Promise.all(others.map(async (p) => ({ pid: p.pid, command: await commandLine(p.pid, signal) })));
15
+ const procs = commands.slice(0, 20);
16
+ // The timeout cancels command reads and prevents an outstanding read from appending after the kill/seal.
17
+ if (signal.aborted)
18
+ return;
19
+ await journal.append("ended", { exec, call: exec.slice(0, exec.lastIndexOf("#")), procs,
20
+ ...(others.length > procs.length ? { more: others.length - procs.length } : {}) });
21
+ } };
22
+ await containment.fence(exec, tracked, options);
23
+ }
@@ -1,10 +1,12 @@
1
- // Private journal entries (A1): tracked{exec,pid,start}; loss{exec}; settled{exec};
1
+ // Private journal entries (A1): tracked{exec,pid,start,child?} (child:true identifies the direct pi process);
2
+ // loss{exec}; settled{exec};
2
3
  // stop-intent{call}; forward{rid,rid2,dest,hash,envelope:{to,kind,body,cond?}};
3
4
  // forward-delivered{rid,rid2,call,reason?}: the first observed child receipt of a forward (once per forward; reason when
4
5
  // the child resolved it as rejected, e.g. withdrawn); forward-retired{rid,rid2,reason}: sealed/retired without a receipt (P27);
5
6
  // an undelivered notify becomes a pending-note{rid,call,key,message} first (../notes.ts).
6
7
  // observation{exec,event}; selected{exec,model}; switch-observed{exec,rid,pool}.
7
8
  // P28 entries are documented in hibernate.ts; generation session publication in generation.ts.
9
+ // ended{exec,call,procs:[{pid,command}],more?}: agent fence SIGKILL targets other than its direct child (EX1/WK8).
8
10
  // session-corrupt{call,line}: a malformed native session line was skipped (once per line, E4).
9
11
  // spawn-env-failed{exec,call,command,error}: launching the child failed for a reason of the environment (ENOENT, EACCES:
10
12
  // pi or its interpreter missing or not executable); the call stays queued and launches again after a backoff.
@@ -35,6 +37,7 @@ import { parseModel, plainModel, resolveModel, sameModel } from "../../compat/mo
35
37
  import { buildCallResult } from "../../compat/result.js";
36
38
  import createEffects from "./effects/index.js";
37
39
  import { continueSession } from "./generation.js";
40
+ import { fenceAgent } from "./ended.js";
38
41
  import { answerInFlight, boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
39
42
  import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./digest.js";
40
43
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
@@ -53,7 +56,7 @@ import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
53
56
  import { COMMAND_LOG, exitMeaning, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
54
57
  import { captureStart } from "../../platform/proctable.js";
55
58
  import { heldIn } from "../snapshot.js";
56
- import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandId, retiredCommandAttempts } from "./command.js";
59
+ import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
57
60
  const MEM_RECORD_MS = 30000;
58
61
  /** How long the processes of a stopped or timed-out command get between SIGTERM and SIGKILL. */
59
62
  const COMMAND_GRACE_MS = 2000;
@@ -144,6 +147,11 @@ export function continueMessage(dangling) {
144
147
  "(background ones included) were stopped with it: do not wait for them or their output; check what they left " +
145
148
  "and start again what is still needed. Tool calls whose outcomes are unknown: " + (dangling.join(", ") || "none") + ".";
146
149
  }
150
+ /** EX2: Appended to every derived agent prompt, never to the pinned agent definition. */
151
+ export const CHILD_LIFECYCLE_NOTE = "Processes you start end when your turn ends: dsa stops every process of this call when it seals.\n" +
152
+ "To run something that must outlive your turn (a long build, test suite or measurement), start it as a durable command call and end your turn:\n" +
153
+ " pi-durable-subagents run --request <unique id> --wake caller -- <program> [args…]\n" +
154
+ "It keeps running after your turn; when it finishes you get a follow-up with its exit status and output tail.";
147
155
  /** An asker hibernates while it waits (its execution is stopped to free the provider slot), so the answer says so. */
148
156
  export const HIBERNATED_NOTE = "While you waited for the answer below your execution was stopped; processes your tools had " +
149
157
  "started (background ones included) were stopped with it. Check them before relying on them.";
@@ -239,7 +247,7 @@ export default function createExecutor(ledgers, options = {}) {
239
247
  if (!failing.has(exec)) {
240
248
  let retired = false;
241
249
  try {
242
- await containment.fence(exec, tracked(journal, exec));
250
+ await fenceAgent(containment, journal, exec, tracked(journal, exec), opts.child);
243
251
  retired = true;
244
252
  }
245
253
  catch (error) {
@@ -1334,7 +1342,7 @@ export default function createExecutor(ledgers, options = {}) {
1334
1342
  return refused === undefined;
1335
1343
  };
1336
1344
  const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed,
1337
- env: { ...process.env, ...t.spec.env, DSA_EXEC: id, DSA_CALL: t.callId, DSA_HOME: home } });
1345
+ env: commandEnvironment(home, id, t.callId, t.spec.env) });
1338
1346
  if (!result) {
1339
1347
  if (refused === "withdrawn")
1340
1348
  await serial(() => t.journal.append(COMMAND_WITHDRAWN, { call: t.callId, id }));
@@ -1675,7 +1683,7 @@ export default function createExecutor(ledgers, options = {}) {
1675
1683
  await mkdir(dir, { recursive: true });
1676
1684
  const prompt = join(dir, "system.txt"), schema = join(dir, "schema.json");
1677
1685
  // These are derived launch inputs, reconstructed from the pinned ticket after a crash.
1678
- await writeFile(prompt, t.agent.body);
1686
+ await writeFile(prompt, `${t.agent.body}\n\n${CHILD_LIFECYCLE_NOTE}`);
1679
1687
  if (t.spec.schema !== undefined)
1680
1688
  await writeFile(schema, JSON.stringify(t.spec.schema));
1681
1689
  const sender = await outbox;
@@ -1741,6 +1749,12 @@ export default function createExecutor(ledgers, options = {}) {
1741
1749
  }
1742
1750
  await serial(() => spawnEnvResolved(t));
1743
1751
  try {
1752
+ // EX1: retain the direct identity even if pi exited before start capture; otherwise a surviving grandchild
1753
+ // could become the first tracked process and be mistaken for pi on a recovery fence.
1754
+ if (child.pid > 0)
1755
+ await serial(async () => {
1756
+ await journal.append("tracked", { exec, pid: child.pid, start: child.start, child: true });
1757
+ });
1744
1758
  await track(journal, exec, [{ pid: child.pid, start: child.start, ppid: process.pid }]);
1745
1759
  await observeExecution({ home, config, ticket: t, exec, child, serial, read: () => readCall(journal, t.callId),
1746
1760
  setWake: fn => { a.wake = fn; }, interrupted: () => !!interrupted(a),
@@ -1,6 +1,7 @@
1
1
  import { JT, attentionEntries, isEntry } from "../../types.js";
2
2
  import { Containment as PlatformContainment } from "../../platform/containment.js";
3
3
  import { ProcessTable } from "../../platform/proctable.js";
4
+ import { fenceAgent } from "./ended.js";
4
5
  /** C2, F4: Real observers share snapshots; injected tables retain serialized access. */
5
6
  export function serialContainment(table) {
6
7
  if (!table || table instanceof ProcessTable)
@@ -152,7 +153,10 @@ export async function sweepExecutions(journals, containment, hooks = {}) {
152
153
  continue;
153
154
  }
154
155
  try {
155
- await containment.fence(t.exec, t.tracked);
156
+ if (t.exec.startsWith("gate:"))
157
+ await containment.fence(t.exec, t.tracked);
158
+ else
159
+ await fenceAgent(containment, t.journal, t.exec, t.tracked);
156
160
  }
157
161
  catch (error) {
158
162
  await hooks.failed?.(t.journal, t.exec, t.call, error);
@@ -1,16 +1,16 @@
1
1
  // Pi-side ledger state: only projections used by readers, never decoded ledger history or run bodies.
2
2
  import { forgetJournalSnapshot, readJournalFold } from "../kernel/journal.js";
3
- import { orchLedger } from "../paths.js";
3
+ import { orchLedger, journalPath } from "../paths.js";
4
4
  import { JT } from "../types.js";
5
5
  import { LEDGER_ENTRY_TYPES, applyLedger, emptyLedger } from "./ledger.js";
6
6
  import { labelsOf } from "../events/derive.js";
7
7
  export function emptyReaderLedger() {
8
8
  return { created: new Map(), origins: new Map(), intents: new Map(), revisions: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(),
9
- byWid: new Map(), byOrigin: new Map(), state: emptyLedger(), createdRids: new Map(), decisions: new Map(), resolutions: new Map(), sendNotes: new Map() };
9
+ byWid: new Map(), byOrigin: new Map(), state: emptyLedger(), createdRids: new Map(), decisions: new Map(), resolutions: new Map(), sendNotes: new Map(), wakeRuns: new Map(), wakeByTo: new Map() };
10
10
  }
11
11
  /** Reader-only projections, combined with applyLedger's type list by the byte filter. */
12
12
  export const READER_ENTRY_TYPES = [JT.created, 'create-intent', 'revise-intent', 'request', 'pruned', 'drain', 'undrain',
13
- JT.applied, JT.rejected, 'send-note'];
13
+ JT.admitted, JT.applied, JT.rejected, 'send-note'];
14
14
  const discardedLedgerTypes = ['switch-observed', 'skip', 'writer-hold', 'writer-release'];
15
15
  export function applyReaderLedger(ix, e) {
16
16
  if (e.type === JT.created) {
@@ -42,6 +42,10 @@ export function applyReaderLedger(ix, e) {
42
42
  }
43
43
  else if (e.type === "request") {
44
44
  const r = e.request;
45
+ const body = r?.kind === 'run' ? r.body : undefined;
46
+ if (body?.wake && typeof body.wake.to === 'string' && typeof body.caller === 'string' && typeof r?.rid === 'string' && !ix.wakeRuns.has(r.rid)) {
47
+ ix.wakeRuns.set(r.rid, { rid: r.rid, to: body.wake.to, caller: body.caller });
48
+ }
45
49
  const labels = r?.kind === "run" ? labelsOf(r.body) : undefined;
46
50
  if (labels && typeof r?.rid === "string")
47
51
  ix.runLabels.set(r.rid, labels);
@@ -49,6 +53,15 @@ export function applyReaderLedger(ix, e) {
49
53
  if (typeof session === "string" && session && typeof r?.rid === "string")
50
54
  ix.runSessions.set(r.rid, session);
51
55
  }
56
+ else if (e.type === JT.admitted && e.kind === 'run') {
57
+ const run = ix.wakeRuns.get(String(e.rid));
58
+ if (run && !run.admitted) {
59
+ run.admitted = true;
60
+ const list = ix.wakeByTo.get(run.to) ?? [];
61
+ list.push(run.rid);
62
+ ix.wakeByTo.set(run.to, list);
63
+ }
64
+ }
52
65
  else if (e.type === "pruned") {
53
66
  ix.pruned.add(String(e.wid));
54
67
  ix.labels.delete(String(e.wid));
@@ -94,9 +107,9 @@ export function readerHold(ix, wid, origin) {
94
107
  }
95
108
  const readers = new Map();
96
109
  // Canonical writer JSON: these are exactly the types that affect reader projections or applyLedger below.
97
- const needles = [...new Set([...READER_ENTRY_TYPES.filter(type => type !== 'request'),
110
+ const needles = [...new Set([...READER_ENTRY_TYPES.filter(type => type !== 'request' && type !== JT.admitted),
98
111
  ...LEDGER_ENTRY_TYPES.filter(type => !discardedLedgerTypes.includes(type))])].map(type => `"type":${JSON.stringify(type)}`);
99
- // Request records only affect labels/session for runs; the other request kinds have no reader projection.
112
+ // Run requests and run admissions affect labels/session and caller wake routing; other request kinds have no projection.
100
113
  needles.push('"kind":"run"');
101
114
  export function readerLedger(home) {
102
115
  const path = orchLedger(home);
@@ -117,4 +130,51 @@ export function readerLedger(home) {
117
130
  throw error;
118
131
  } // a partial fold is never retried as an accepted prefix
119
132
  }
133
+ const wakeReaders = new Map();
134
+ /** Only matching wake runs are read, incrementally, with a byte filter for completion and wake receipts. */
135
+ function wakeFacts(home, wid) {
136
+ const path = journalPath(home, wid);
137
+ try {
138
+ const record = readJournalFold(path, wakeReaders.get(path), () => ({ rev: 0 }), (state, e) => {
139
+ if (e.type === JT.done)
140
+ state.rev++;
141
+ if (e.type === 'wake-outcome')
142
+ state.outcome = { state: e.state, rev: Number(e.rev),
143
+ ...(typeof e.generation === 'number' ? { generation: e.generation } : {}), ...(typeof e.reason === 'string' ? { reason: e.reason } : {}) };
144
+ }, { needles: ['"type":"workflow-done"', '"type":"wake-outcome"'] });
145
+ if (record) {
146
+ wakeReaders.set(path, record);
147
+ return record.state;
148
+ }
149
+ wakeReaders.delete(path);
150
+ return { rev: 0 };
151
+ }
152
+ catch (error) {
153
+ wakeReaders.delete(path);
154
+ throw error;
155
+ }
156
+ }
157
+ export function wakeStatus(home, request, wid) {
158
+ const body = request?.kind === 'run' ? request.body : undefined;
159
+ if (!body?.wake)
160
+ return undefined;
161
+ const facts = wid ? wakeFacts(home, wid) : { rev: 0 };
162
+ return { to: body.wake.to, ...(facts.outcome && facts.outcome.rev === facts.rev ? facts.outcome : { state: 'pending' }) };
163
+ }
164
+ export function awaitingRuns(home, wid, key, revision) {
165
+ const ix = readerLedger(home).state, out = [];
166
+ for (const rid of ix.wakeByTo.get(`${wid}/${key}`) ?? []) {
167
+ const run = ix.wakeRuns.get(rid);
168
+ if (run.caller.slice(0, run.caller.indexOf('/')) !== `${wid}@${revision}` || ix.decisions.get(rid)?.type === 'rejected')
169
+ continue;
170
+ const created = ix.createdRids.get(rid), child = created ? String(created.wid) : undefined;
171
+ if (child && ix.pruned.has(child))
172
+ continue;
173
+ const facts = child ? wakeFacts(home, child) : undefined;
174
+ if (facts?.rev && facts.outcome?.rev === facts.rev)
175
+ continue;
176
+ out.push({ request: rid.startsWith('req:') ? rid.slice(4) : rid, ...(child ? { wid: child } : {}), state: !child ? 'pending' : facts?.rev ? 'finished' : 'running' });
177
+ }
178
+ return out.length ? out : undefined;
179
+ }
120
180
  export const readerLedgerIdentity = (record) => `${record.dev}:${record.ino}:${record.size}`;
@@ -30,6 +30,8 @@ export function settledFacts(wf, recovered) {
30
30
  const log = wf.journal.entries(), rev = revisionEntries(wf), done = terminalEntry(rev);
31
31
  if (!done)
32
32
  return "running";
33
+ if (wf.wake && !log.some(e => e.type === "wake-outcome" && e.rev === log.filter(e => e.type === JT.done).length))
34
+ return "wake pending";
33
35
  const has = (type, field, value) => log.some(e => e.type === type && e[field] === value);
34
36
  const sealedCalls = new Set(log.filter(e => e.type === JT.sealed).map(e => String(e.call)));
35
37
  const ended = new Set([...sealedCalls, ...log.filter(e => e.type === "retired").map(e => String(e.call))]);