pi-durable-subagents 1.0.43 → 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.
@@ -1,20 +1,32 @@
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.
13
+ // Command calls (CallSpec.command) record no exec/tracked/fenced entries (nothing that handles agent executions picks them
14
+ // up): command-intent{call,id,n} before the spawn (id = command:<call>#<n> is the attempt and its process tag DSA_EXEC;
15
+ // n is 1, or 2 for the single rerun); command-started{call,id,pid,start,dir} after it (the wrapper's identity, the
16
+ // attempt directory; its ts starts the wall-clock timeout); command-spawn-failed{call,id,error}: the command could not
17
+ // start (it seals failed, never reruns); command-timeout{call,id}: the deadline passed, recorded before the process tree
18
+ // is ended (as stop-intent is for a stop), so a crash during that fence still seals timeout; command-withdrawn{call,id}:
19
+ // the intent was recorded but no process started (a retirement or the orchestrator's exit came first): a later start
20
+ // decides again, as if there were no intent.
11
21
  // fence-failed{exec,error} is documented in sweep.ts. The orchestrator ledger owns hold/release{pool,slot,exec}
12
22
  // and mem{available,admitted,exec} (every admission; a repeated refusal at most every 30 s per call). All transitions are serialized before publication.
13
- import { mkdir, open, readdir, readFile, realpath, rm, unlink, writeFile } from "node:fs/promises";
23
+ import { mkdir, open, readdir, readFile, realpath, rm, stat, unlink, writeFile } from "node:fs/promises";
24
+ import { watch } from "node:fs";
25
+ import { setTimeout as delay } from "node:timers/promises";
14
26
  import { homedir } from "node:os";
15
27
  import { delimiter, dirname, join } from "node:path";
16
28
  import { fileURLToPath } from "node:url";
17
- import { CT, JT, attentionEntries, isEntry } from "../../types.js";
29
+ import { CT, JT, attentionEntries, isCommandCall, isEntry } from "../../types.js";
18
30
  import { binDir, callDir, callInbox, callSession, journalPath, outboxRoot } from "../../paths.js";
19
31
  import { readJournalSnapshot, syncDirectory } from "../../kernel/journal.js";
20
32
  import { Outbox } from "../../kernel/mailbox.js";
@@ -25,6 +37,7 @@ import { parseModel, plainModel, resolveModel, sameModel } from "../../compat/mo
25
37
  import { buildCallResult } from "../../compat/result.js";
26
38
  import createEffects from "./effects/index.js";
27
39
  import { continueSession } from "./generation.js";
40
+ import { fenceAgent } from "./ended.js";
28
41
  import { answerInFlight, boundAnswer, hibernation, openAsked, openQuestion, supersededByBinding } from "./hibernate.js";
29
42
  import { SessionFold, answerKey, digestOpenQuestion, supersededBy } from "./digest.js";
30
43
  import { emptyLedger, foldLedger, holdings as holdingsOf, settingsOf } from "../ledger.js";
@@ -40,7 +53,18 @@ import { gateRetired } from "./effects/gate.js";
40
53
  import { WorktreeIndex, worktreeCalls, worktreeLabel, worktreePair, worktreeRoots } from "./worktree.js";
41
54
  import { failedModel, modelFailures, MODEL_RETRY_MS, parentPinned, spillCandidates } from "./pool.js";
42
55
  import { PENDING_NOTE, UNDELIVERED_FOLLOW_UP } from "../notes.js";
56
+ import { COMMAND_LOG, exitMeaning, readExitRecord, readTail, spawnCommand } from "../../platform/command.js";
57
+ import { captureStart } from "../../platform/proctable.js";
58
+ import { heldIn } from "../snapshot.js";
59
+ import { COMMAND_INTENT, COMMAND_SPAWN_FAILED, COMMAND_STARTED, COMMAND_TIMEOUT, COMMAND_WITHDRAWN, commandDirName, commandEnvironment, commandId, retiredCommandAttempts } from "./command.js";
43
60
  const MEM_RECORD_MS = 30000;
61
+ /** How long the processes of a stopped or timed-out command get between SIGTERM and SIGKILL. */
62
+ const COMMAND_GRACE_MS = 2000;
63
+ /** A command's exit status as a result: 0 is ok; otherwise the error names the status, or the signal (exitMeaning). */
64
+ function exitResult(status) {
65
+ const meaning = exitMeaning(status);
66
+ return status === 0 ? meaning : { ...meaning, error: meaning.signal ? `Command killed by ${meaning.signal}` : `Command exited ${status}` };
67
+ }
44
68
  /** A4, P29: A child admitted within this window may not show in MemAvailable yet; its share is reserved explicitly. */
45
69
  const MEM_WARMUP_MS = 30000;
46
70
  /** Quota refusals in a row that find a provider's usage window used up while pi is still retrying. */
@@ -123,6 +147,11 @@ export function continueMessage(dangling) {
123
147
  "(background ones included) were stopped with it: do not wait for them or their output; check what they left " +
124
148
  "and start again what is still needed. Tool calls whose outcomes are unknown: " + (dangling.join(", ") || "none") + ".";
125
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.";
126
155
  /** An asker hibernates while it waits (its execution is stopped to free the provider slot), so the answer says so. */
127
156
  export const HIBERNATED_NOTE = "While you waited for the answer below your execution was stopped; processes your tools had " +
128
157
  "started (background ones included) were stopped with it. Check them before relying on them.";
@@ -218,7 +247,7 @@ export default function createExecutor(ledgers, options = {}) {
218
247
  if (!failing.has(exec)) {
219
248
  let retired = false;
220
249
  try {
221
- await containment.fence(exec, tracked(journal, exec));
250
+ await fenceAgent(containment, journal, exec, tracked(journal, exec), opts.child);
222
251
  retired = true;
223
252
  }
224
253
  catch (error) {
@@ -1158,7 +1187,306 @@ export default function createExecutor(ledgers, options = {}) {
1158
1187
  while (!interrupted(a) && Date.now() < until)
1159
1188
  await new Promise(resolve => { const timer = setTimeout(resolve, Math.min(until - Date.now(), config.k?.trackerMs ?? 1000)); a.wake = () => { clearTimeout(timer); resolve(); }; });
1160
1189
  }
1190
+ // ---- Command calls: no model, slot, usage, hibernation or budget; the process outlives the orchestrator. ----
1191
+ const commandTick = () => Math.min(config.k?.trackerMs ?? 1000, 1000);
1192
+ const hasStopIntent = (journal, call) => entriesFor(journal, call).some(e => e.type === "stop-intent");
1193
+ /** The wrapper's identity of an attempt (from its latest command-started), for scans and fences. */
1194
+ const commandKnown = (started) => started && started.start ? [{ pid: Number(started.pid), ppid: 0, start: String(started.start) }] : [];
1195
+ /** The processes of an attempt: tagged with its id, the wrapper while it lives, and their live descendants. */
1196
+ async function commandProcesses(id, known) {
1197
+ return (await containment.scan(new Map([[id, known]]), { fresh: true })).get(id) ?? [];
1198
+ }
1199
+ /** End an attempt's whole process tree: SIGTERM, a grace period, then the fence (SIGKILL until a rescan finds none).
1200
+ * A failing fence is retried until it works; the orchestrator's exit interrupts it (the next start fences again). */
1201
+ async function endCommand(id, known) {
1202
+ let live = await commandProcesses(id, known);
1203
+ if (!live.length)
1204
+ return;
1205
+ for (const p of live) {
1206
+ if (p.start !== "" && await captureStart(p.pid).catch(() => "") !== p.start)
1207
+ continue;
1208
+ try {
1209
+ process.kill(p.pid, "SIGTERM");
1210
+ }
1211
+ catch (error) {
1212
+ if (error.code !== "ESRCH")
1213
+ throw error;
1214
+ }
1215
+ }
1216
+ const graceUntil = Date.now() + COMMAND_GRACE_MS;
1217
+ while (Date.now() < graceUntil) {
1218
+ await delay(100);
1219
+ live = await commandProcesses(id, known);
1220
+ if (!live.length)
1221
+ return;
1222
+ }
1223
+ for (;;) {
1224
+ try {
1225
+ await containment.fence(id, [...known, ...live]);
1226
+ return;
1227
+ }
1228
+ catch (error) {
1229
+ console.error(`durable-subagents: fence of ${id} failed: ${String(error)}; retrying`);
1230
+ if (closed)
1231
+ throw shutdownError();
1232
+ await delay(commandTick());
1233
+ }
1234
+ }
1235
+ }
1236
+ /** Seal a command call through the normal seal path (forwards, attention, inbox) with the pinned result: a stop or a
1237
+ * recorded timeout of the attempt wins, as they do for agent calls. */
1238
+ async function sealCommand(journal, t, id, outcome, dir) {
1239
+ const call = t.callId, output = dir ? await readTail(join(dir, COMMAND_LOG)) : "";
1240
+ const value = await serial(async () => {
1241
+ const old = sealed(journal, call);
1242
+ if (old)
1243
+ return old;
1244
+ if (closed || retiredCall(journal, call))
1245
+ throw shutdownError();
1246
+ const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id);
1247
+ let { status, error } = outcome;
1248
+ if (hasStopIntent(journal, call)) {
1249
+ status = "stopped";
1250
+ error = undefined;
1251
+ }
1252
+ else if (entriesFor(journal, call).some(e => e.type === COMMAND_TIMEOUT && e.id === id)) {
1253
+ status = "timeout";
1254
+ error = `Command timed out after ${t.spec.timeoutMs} ms`;
1255
+ }
1256
+ const durationMs = started ? Math.max(0, Math.round((outcome.at ?? Date.now()) - started.ts)) : 0;
1257
+ const result = { ...buildCallResult({ key: t.key, gen: t.gen, status, output, ...(error ? { error } : {}) }),
1258
+ data: { exitCode: outcome.exitCode ?? null, signal: outcome.signal ?? null, durationMs }, usage: { input: 0, output: 0, costUsd: 0 } };
1259
+ await journal.append(JT.sealed, { call, exec: id, result });
1260
+ await retireForwards(journal, call);
1261
+ await retireAttention(journal, call);
1262
+ await unknownAttention(journal, call);
1263
+ return result;
1264
+ });
1265
+ await collectSealed(call).catch(error => console.error(`durable-subagents: inbox cleanup of ${call} failed: ${String(error)}`));
1266
+ wake();
1267
+ return value;
1268
+ }
1269
+ /** Whether a drain holds workflow `wid` now (the engine's hold rule): a held command call does not start. */
1270
+ const held = (wid) => heldIn(orch.entries())(wid);
1271
+ /** Why a command call cannot start attempt `n` now: retired or closed (the run ends), stopped (it seals), held (the
1272
+ * run ends; the engine runs the call again after resume), or undefined. */
1273
+ const commandBlocked = (a) => {
1274
+ const t = a.ticket;
1275
+ if (closed || a.suspended || a.retired || retiredCall(t.journal, t.callId))
1276
+ return "shutdown";
1277
+ if (stopped(a))
1278
+ return "stopped";
1279
+ if (held(t.wid))
1280
+ return "held";
1281
+ return undefined;
1282
+ };
1283
+ /** The writer lock of a command call with `writer: true`, before its first attempt; the reason it stopped waiting. */
1284
+ async function commandWriter(a) {
1285
+ const t = a.ticket, root = await roots(t.cwd, "x") ?? await realpath(t.cwd).catch(() => t.cwd);
1286
+ for (;;) {
1287
+ const blocked = commandBlocked(a);
1288
+ if (blocked)
1289
+ return blocked;
1290
+ let signal;
1291
+ const changed = new Promise(resolve => { signal = resolve; waiters.add(resolve); });
1292
+ if (await serial(async () => !commandBlocked(a) && await writerAdmit(a, root))) {
1293
+ waiters.delete(signal);
1294
+ return undefined;
1295
+ }
1296
+ a.wake = signal;
1297
+ const timer = setTimeout(signal, commandTick());
1298
+ try {
1299
+ await changed;
1300
+ }
1301
+ finally {
1302
+ clearTimeout(timer);
1303
+ waiters.delete(signal);
1304
+ }
1305
+ }
1306
+ }
1307
+ /** Record the intent of attempt `n` (the start decision): in one serial step with the checks of commandBlocked, so no
1308
+ * stop, retirement, close or hold slips in between. `a.commandStarting` marks the decision for suspend(). */
1309
+ function commandIntent(a, n) {
1310
+ const t = a.ticket, journal = t.journal, call = t.callId;
1311
+ return serial(async () => {
1312
+ const blocked = commandBlocked(a);
1313
+ if (blocked)
1314
+ return blocked;
1315
+ const existing = entriesFor(journal, call).findLast(e => e.type === COMMAND_INTENT && e.n === n && !intentWithdrawn(journal, call, String(e.id), e.seq));
1316
+ if (existing)
1317
+ return existing;
1318
+ a.commandStarting = true;
1319
+ return journal.append(COMMAND_INTENT, { call, id: commandId(call, n), n });
1320
+ });
1321
+ }
1322
+ /** Whether a later command-withdrawn voids the intent at `seq` (no process was started for it). */
1323
+ const intentWithdrawn = (journal, call, id, seq) => entriesFor(journal, call).some(e => e.type === COMMAND_WITHDRAWN && e.id === id && e.seq > seq);
1324
+ /** Start the attempt whose intent is recorded; records command-started, or command-spawn-failed when it cannot start.
1325
+ * Rechecked synchronously right before the spawn: a stop means no process (the watch seals it stopped), a retirement or the orchestrator's exit
1326
+ * withdraws the intent (nothing started; the next start decides again). */
1327
+ async function launchCommand(a, id, dir) {
1328
+ const t = a.ticket;
1329
+ let spawned;
1330
+ try {
1331
+ if (!(await stat(t.cwd).catch(() => undefined))?.isDirectory())
1332
+ throw new Error(`cwd ${t.cwd} is not a directory`);
1333
+ await rm(join(dir, "exit"), { force: true });
1334
+ await rm(join(dir, "exit.tmp"), { force: true });
1335
+ // The last check is synchronous, right before the spawn (spawnCommand calls it after its own preparation).
1336
+ let refused;
1337
+ const proceed = () => {
1338
+ if (stopped(a))
1339
+ refused = "stopped";
1340
+ else if (closed || a.retired || retiredCall(t.journal, t.callId))
1341
+ refused = "withdrawn";
1342
+ return refused === undefined;
1343
+ };
1344
+ const result = await spawnCommand({ command: t.spec.command, cwd: t.cwd, dir, proceed,
1345
+ env: commandEnvironment(home, id, t.callId, t.spec.env) });
1346
+ if (!result) {
1347
+ if (refused === "withdrawn")
1348
+ await serial(() => t.journal.append(COMMAND_WITHDRAWN, { call: t.callId, id }));
1349
+ return undefined;
1350
+ }
1351
+ spawned = result;
1352
+ }
1353
+ catch (error) {
1354
+ await serial(() => t.journal.append(COMMAND_SPAWN_FAILED, { call: t.callId, id, error: String(error instanceof Error ? error.message : error).slice(0, 300) }));
1355
+ return undefined;
1356
+ }
1357
+ await serial(() => t.journal.append(COMMAND_STARTED, { call: t.callId, id, pid: spawned.pid, start: spawned.start, dir }));
1358
+ return spawned;
1359
+ }
1360
+ /** Run, adopt or settle a command call (see the journal records at the top). One attempt runs at a time; a lost first
1361
+ * attempt of a `rerun: true` call starts once more, only after a scan found none of its processes. A start (the
1362
+ * first attempt or the rerun) waits while the workflow is held: the run ends and the engine runs it after resume. */
1363
+ async function executeCommand(a) {
1364
+ const t = a.ticket, journal = t.journal, call = t.callId;
1365
+ const own = () => entriesFor(journal, call);
1366
+ const dirOf = (n) => join(callDir(home, t.wid, t.key, t.gen), commandDirName(n));
1367
+ const fail = (error) => sealCommand(journal, t, commandId(call, 1), { status: "failed", error });
1368
+ const latest = () => { const e = own().findLast(e => e.type === COMMAND_INTENT); return e && !intentWithdrawn(journal, call, String(e.id), e.seq) ? e : undefined; };
1369
+ /** Start attempt `n`: the intent, then the process; undefined when it did not start (and the run goes on). */
1370
+ const begin = async (n) => {
1371
+ const intent = await commandIntent(a, n);
1372
+ if (intent === "stopped")
1373
+ return undefined;
1374
+ if (intent === "shutdown" || intent === "held")
1375
+ throw shutdownError();
1376
+ return { spawned: await launchCommand(a, String(intent.id), dirOf(n)) };
1377
+ };
1378
+ let spawned;
1379
+ for (;;) {
1380
+ const old = sealed(journal, call);
1381
+ if (old)
1382
+ return old;
1383
+ if (closed || a.retired || retiredCall(journal, call)) {
1384
+ if (!closed) {
1385
+ const intent = latest();
1386
+ if (intent)
1387
+ await endCommand(String(intent.id), commandKnown(own().findLast(e => e.type === COMMAND_STARTED && e.id === intent.id)));
1388
+ }
1389
+ throw shutdownError();
1390
+ }
1391
+ let intent = latest();
1392
+ if (!intent) {
1393
+ if (t.refusal !== undefined)
1394
+ return fail(t.refusal);
1395
+ const n = Math.max(1, ...own().filter(e => e.type === COMMAND_INTENT).map(e => Number(e.n)));
1396
+ if (stopped(a))
1397
+ return sealCommand(journal, t, commandId(call, n), { status: "stopped" });
1398
+ if (t.spec.writer === true) {
1399
+ const blocked = await commandWriter(a);
1400
+ if (blocked === "stopped")
1401
+ continue;
1402
+ if (blocked)
1403
+ throw shutdownError();
1404
+ }
1405
+ spawned = (await begin(n))?.spawned;
1406
+ continue;
1407
+ }
1408
+ const id = String(intent.id), n = Number(intent.n), dir = dirOf(n);
1409
+ const failed = own().find(e => e.type === COMMAND_SPAWN_FAILED && e.id === id);
1410
+ if (failed)
1411
+ return sealCommand(journal, t, id, { status: "failed", error: `Command could not start: ${String(failed.error)}` });
1412
+ const outcome = await watchCommand(a, id, dir, intent, spawned);
1413
+ spawned = undefined;
1414
+ if (outcome !== "lost")
1415
+ return outcome;
1416
+ if (n === 1 && t.spec.rerun === true) {
1417
+ // The scan found no process of the first attempt: start it once more (attempt 2 never reruns), a new start.
1418
+ if (!own().some(e => e.type === COMMAND_INTENT && e.n === 2)) {
1419
+ spawned = (await begin(2))?.spawned;
1420
+ continue;
1421
+ }
1422
+ }
1423
+ return sealCommand(journal, t, id, { status: "unknown", error: "Command ended without an exit record" }, dir);
1424
+ }
1425
+ }
1426
+ /** Watch one attempt until it has an outcome: its exit record, a stop, its deadline, or its loss (no exit record and
1427
+ * no process left). The orchestrator's exit ends the watch without touching the process (ExecutorShutdown). */
1428
+ async function watchCommand(a, id, dir, intent, spawned) {
1429
+ const t = a.ticket, journal = t.journal, call = t.callId;
1430
+ let watcher;
1431
+ try {
1432
+ watcher = watch(dir, () => a.wake());
1433
+ watcher.on("error", () => watcher?.close());
1434
+ }
1435
+ catch {
1436
+ watcher = undefined;
1437
+ }
1438
+ void spawned?.exited.then(() => a.wake());
1439
+ try {
1440
+ for (;;) {
1441
+ const started = entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id), known = commandKnown(started);
1442
+ // The timeout is wall clock from the start (command-started, else the intent: a crash before the started record),
1443
+ // downtime included.
1444
+ const deadline = t.spec.timeoutMs !== undefined ? (started ?? intent).ts + t.spec.timeoutMs : undefined;
1445
+ const exit = await readExitRecord(dir);
1446
+ if (exit) {
1447
+ // Processes the command left behind (background ones included) end with it, as a call's processes always do.
1448
+ if (!closed)
1449
+ await endCommand(id, known);
1450
+ // An exit after the deadline (seen late: the orchestrator was down) is a timeout, with the record's data.
1451
+ const late = deadline !== undefined && exit.at > deadline;
1452
+ return await sealCommand(journal, t, id, { status: late ? "timeout" : exit.status === 0 ? "ok" : "failed", ...exitResult(exit.status),
1453
+ ...(late ? { error: `Command timed out after ${t.spec.timeoutMs} ms` } : {}), at: exit.at }, dir);
1454
+ }
1455
+ if (closed)
1456
+ throw shutdownError();
1457
+ if (a.retired || retiredCall(journal, call)) {
1458
+ await endCommand(id, known);
1459
+ throw shutdownError();
1460
+ }
1461
+ if (hasStopIntent(journal, call)) {
1462
+ await endCommand(id, known);
1463
+ return await sealCommand(journal, t, id, { status: "stopped" }, dir);
1464
+ }
1465
+ if (deadline !== undefined && Date.now() >= deadline || entriesFor(journal, call).some(e => e.type === COMMAND_TIMEOUT && e.id === id)) {
1466
+ await serial(async () => { if (!entriesFor(journal, call).some(e => e.type === COMMAND_TIMEOUT && e.id === id))
1467
+ await journal.append(COMMAND_TIMEOUT, { call, id }); });
1468
+ await endCommand(id, known);
1469
+ return await sealCommand(journal, t, id, { status: "timeout" }, dir);
1470
+ }
1471
+ const wrapper = !!started?.start && await captureStart(Number(started.pid)).catch(() => "") === started.start;
1472
+ if (!wrapper && !(await commandProcesses(id, known)).length) {
1473
+ // The wrapper may have written its record just before it ended.
1474
+ const late = await readExitRecord(dir);
1475
+ if (!late)
1476
+ return "lost";
1477
+ continue;
1478
+ }
1479
+ const wait = Math.max(1, Math.min(commandTick(), deadline !== undefined ? deadline - Date.now() : Infinity));
1480
+ await new Promise(resolve => { const timer = setTimeout(resolve, wait); a.wake = () => { clearTimeout(timer); resolve(); }; });
1481
+ }
1482
+ }
1483
+ finally {
1484
+ watcher?.close();
1485
+ }
1486
+ }
1161
1487
  async function execute(a) {
1488
+ if (isCommandCall(a.ticket.spec))
1489
+ return executeCommand(a);
1162
1490
  const t = a.ticket, journal = t.journal;
1163
1491
  const session = callSession(home, t.wid, t.key, t.gen), dir = callDir(home, t.wid, t.key, t.gen);
1164
1492
  const makeResult = (status, output = "", error) => buildCallResult({ key: t.key, gen: t.gen, status, output, ...(error ? { error } : {}) });
@@ -1355,7 +1683,7 @@ export default function createExecutor(ledgers, options = {}) {
1355
1683
  await mkdir(dir, { recursive: true });
1356
1684
  const prompt = join(dir, "system.txt"), schema = join(dir, "schema.json");
1357
1685
  // These are derived launch inputs, reconstructed from the pinned ticket after a crash.
1358
- await writeFile(prompt, t.agent.body);
1686
+ await writeFile(prompt, `${t.agent.body}\n\n${CHILD_LIFECYCLE_NOTE}`);
1359
1687
  if (t.spec.schema !== undefined)
1360
1688
  await writeFile(schema, JSON.stringify(t.spec.schema));
1361
1689
  const sender = await outbox;
@@ -1421,6 +1749,12 @@ export default function createExecutor(ledgers, options = {}) {
1421
1749
  }
1422
1750
  await serial(() => spawnEnvResolved(t));
1423
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
+ });
1424
1758
  await track(journal, exec, [{ pid: child.pid, start: child.start, ppid: process.pid }]);
1425
1759
  await observeExecution({ home, config, ticket: t, exec, child, serial, read: () => readCall(journal, t.callId),
1426
1760
  setWake: fn => { a.wake = fn; }, interrupted: () => !!interrupted(a),
@@ -1795,7 +2129,7 @@ export default function createExecutor(ledgers, options = {}) {
1795
2129
  const journal = journals.get(target.wid);
1796
2130
  if (!journal)
1797
2131
  return;
1798
- const calls = new Set(journal.entries().filter(e => e.type === JT.exec && (!target.callId || e.call === target.callId)).map(e => String(e.call)));
2132
+ const calls = new Set(journal.entries().filter(e => (e.type === JT.exec || e.type === COMMAND_INTENT) && (!target.callId || e.call === target.callId)).map(e => String(e.call)));
1799
2133
  for (const a of active.values())
1800
2134
  if (a.ticket.wid === target.wid && (!target.callId || a.ticket.callId === target.callId))
1801
2135
  calls.add(a.ticket.callId);
@@ -1818,6 +2152,16 @@ export default function createExecutor(ledgers, options = {}) {
1818
2152
  const a = active.get(call);
1819
2153
  if (a)
1820
2154
  await settledOrParked(a);
2155
+ else if (entriesFor(journal, call).some(e => e.type === COMMAND_INTENT)) {
2156
+ // A command call nobody watches here (not adopted yet): end its tree, then seal it stopped.
2157
+ if (sealed(journal, call) || retiredCall(journal, call))
2158
+ continue;
2159
+ const intent = entriesFor(journal, call).findLast(e => e.type === COMMAND_INTENT), id = String(intent.id);
2160
+ await endCommand(id, commandKnown(entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === id)));
2161
+ const { wid, key, gen } = address(call);
2162
+ await sealCommand(journal, { wid, key, gen, callId: call, spec: {} }, id, { status: "stopped" }, join(callDir(home, wid, key, gen), commandDirName(Number(intent.n)))).catch(error => { if (error?.name !== "ExecutorShutdown")
2163
+ throw error; });
2164
+ }
1821
2165
  else {
1822
2166
  const exec = current(journal, call);
1823
2167
  if (!exec || sealed(journal, call))
@@ -1845,6 +2189,10 @@ export default function createExecutor(ledgers, options = {}) {
1845
2189
  await effects.recover(journal);
1846
2190
  // A call whose recovery ran to its end before (and that nothing concerned since) is not read again: all its
1847
2191
  // executions were fenced and released, its session read, its forwards, attention and inbox settled.
2192
+ // A retired command call's processes, if any still run (an orchestrator ended during its retirement), end now.
2193
+ if (entriesOf(journal, COMMAND_INTENT).length)
2194
+ for (const r of retiredCommandAttempts(journal.entries()))
2195
+ await endCommand(r.id, r.start ? [{ pid: r.pid, ppid: 0, start: r.start }] : []);
1848
2196
  const complete = completeCalls(journal, wid), execs = entriesOf(journal, JT.exec).filter(e => !complete.has(String(e.call)));
1849
2197
  for (const e of execs) {
1850
2198
  // F1: an exec whose fence fails stays unfenced and holding; its call parks until a sweep retires it.
@@ -1924,7 +2272,7 @@ export default function createExecutor(ledgers, options = {}) {
1924
2272
  const journal = journals.get(widRev.slice(0, widRev.lastIndexOf("@")));
1925
2273
  if (!journal)
1926
2274
  return;
1927
- const calls = new Set(journal.entries().filter(e => e.type === JT.exec && String(e.call).startsWith(`${widRev}/`)).map(e => String(e.call)));
2275
+ const calls = new Set(journal.entries().filter(e => (e.type === JT.exec || e.type === COMMAND_INTENT) && String(e.call).startsWith(`${widRev}/`)).map(e => String(e.call)));
1928
2276
  for (const a of active.values())
1929
2277
  if (a.ticket.widRev === widRev) {
1930
2278
  a.retired = true;
@@ -1944,19 +2292,30 @@ export default function createExecutor(ledgers, options = {}) {
1944
2292
  for (const e of journal.entries().filter(e => e.type === JT.exec && e.call === call))
1945
2293
  if (await fence(journal, String(e.exec)))
1946
2294
  await release(String(e.exec));
2295
+ // A command call's processes end with its retirement (one nobody watched here included).
2296
+ const intent = sealed(journal, call) ? undefined : entriesFor(journal, call).findLast(e => e.type === COMMAND_INTENT);
2297
+ if (intent)
2298
+ await endCommand(String(intent.id), commandKnown(entriesFor(journal, call).findLast(e => e.type === COMMAND_STARTED && e.id === intent.id)));
1947
2299
  await serial(async () => { await retireForwards(journal, call); await retireAttention(journal, call); });
1948
2300
  }
1949
2301
  },
1950
2302
  busy: () => active.size > 0,
2303
+ exclusive: fn => serial(fn),
1951
2304
  quiesce() {
1952
2305
  paused = true;
1953
2306
  const live = [...active.values()].filter(a => a.live).map(a => ({ wid: a.ticket.wid, key: a.ticket.key, gen: a.ticket.gen, callId: a.ticket.callId, ...a.live }));
1954
- return { live, resume: () => { paused = false; for (const fn of [...unpaused])
2307
+ // Command calls never count as live: they keep running across a restart and the successor adopts them.
2308
+ const commands = [...active.values()].filter(a => isCommandCall(a.ticket.spec)).length;
2309
+ return { live, commands, resume: () => { paused = false; for (const fn of [...unpaused])
1955
2310
  fn(); } };
1956
2311
  },
1957
2312
  suspend(only) {
2313
+ // A drain with fence does not fence command calls: they keep running and seal (the held workflow starts nothing
2314
+ // after them). Only the orchestrator's exit (shutdown) ends their watchers, leaving the processes running.
2315
+ // One that has not started (no intent: waiting for the writer lock, say) is suspended like a call not launched.
2316
+ const suspendable = (a) => closed || !isCommandCall(a.ticket.spec) || (!a.commandStarting && !entriesFor(a.ticket.journal, a.ticket.callId).some(e => e.type === COMMAND_INTENT));
1958
2317
  if (only) { // scoped (one session's quit, one workflow): other workflows keep running and dispatching
1959
- const targets = [...active.values()].filter(a => only(a.ticket.wid));
2318
+ const targets = [...active.values()].filter(a => only(a.ticket.wid) && suspendable(a));
1960
2319
  for (const a of targets) {
1961
2320
  a.suspended = true;
1962
2321
  a.controller.abort();
@@ -1973,14 +2332,15 @@ export default function createExecutor(ledgers, options = {}) {
1973
2332
  }
1974
2333
  if (suspending)
1975
2334
  return suspending;
1976
- for (const a of active.values()) {
2335
+ const targets = [...active.values()].filter(suspendable);
2336
+ for (const a of targets) {
1977
2337
  a.suspended = true;
1978
2338
  a.controller.abort();
1979
2339
  a.wake();
1980
2340
  }
1981
2341
  wake();
1982
2342
  suspending = (async () => {
1983
- const results = await Promise.allSettled([...active.values()].map(a => a.promise));
2343
+ const results = await Promise.allSettled(targets.map(a => a.promise));
1984
2344
  await queue;
1985
2345
  const failed = results.find(r => r.status === "rejected" && r.reason?.name !== "ExecutorShutdown");
1986
2346
  if (failed?.status === "rejected")
@@ -1995,6 +2355,12 @@ export default function createExecutor(ledgers, options = {}) {
1995
2355
  clearInterval(sweepTimer);
1996
2356
  try {
1997
2357
  await this.suspend();
2358
+ // Command watchers end at once (their processes keep running; the next start adopts them), also when an
2359
+ // earlier drain's suspension was still settling and did not include them.
2360
+ const commands = [...active.values()].filter(a => isCommandCall(a.ticket.spec));
2361
+ for (const a of commands)
2362
+ a.wake();
2363
+ await Promise.allSettled(commands.map(a => a.promise));
1998
2364
  await sweeping;
1999
2365
  }
2000
2366
  finally {
@@ -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);
@@ -12,7 +12,7 @@ import { realpathSync } from 'node:fs';
12
12
  import { join, resolve } from 'node:path';
13
13
  import { binDir, dsaHome, orchLedger, orchLock } from "../paths.js";
14
14
  import { removeStaleTemps, writeShim } from "../platform/lease.js";
15
- import { launchOrchestrator, resolvePi } from "../platform/launch.js";
15
+ import { launchOrchestrator, PER_CALL_ENV, resolvePi } from "../platform/launch.js";
16
16
  import { openJournal } from "../kernel/journal.js";
17
17
  import { OsLock } from "../platform/lock.js";
18
18
  import { captureStart } from "../platform/proctable.js";
@@ -23,7 +23,9 @@ import { packageVersion } from "../version.js";
23
23
  * applied restart request ended it (the caller starts the successor once the lock is released). */
24
24
  export async function main(options = {}) {
25
25
  // Serves every session: whichever pi session started it, its children and their CLI runs must not name that session.
26
- delete process.env.DSA_SESSION;
26
+ // Nor any call's identity, should it have been started from inside one (its processes inherit this environment).
27
+ for (const name of PER_CALL_ENV)
28
+ delete process.env[name];
27
29
  const home = options.home ?? dsaHome();
28
30
  await mkdir(home, { recursive: true });
29
31
  const lock = await new OsLock().tryAcquire(orchLock(home));