brl-subagent 2.9.0 → 2.9.1

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.
@@ -47,7 +47,14 @@ import {
47
47
  import { clearHeadState, readHeadState, writeHeadState, HEAD_STATE_VERSION } from './headstate';
48
48
  import { effectiveBackgroundBudget } from './validate';
49
49
  import { currentProcessOwner, classifyOwner, defaultRecoveryDeps } from './recovery';
50
- import { persistRunRecord, listInflightRuns, clearInflightRun, type InflightRun } from './run-registry';
50
+ import {
51
+ persistRunRecord,
52
+ listInflightRuns,
53
+ clearInflightRun,
54
+ markRecordFlipPending,
55
+ type InflightRun,
56
+ type RecordFlipStatus,
57
+ } from './run-registry';
51
58
  import { isTransportRetryable } from './transport-retry';
52
59
  import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
53
60
  import { buildEngineeringBarSection } from './engineering-bar';
@@ -132,6 +139,51 @@ export function __testResetGitBranchLocks(): void {
132
139
  gitBranchLockOwners.clear();
133
140
  }
134
141
 
142
+ /**
143
+ * Issue #450 (D5): `prompt()`'s rejection value and a synchronous throw are both
144
+ * `unknown` by contract, and a normaliser that is not TOTAL replaces the failure
145
+ * it describes: `String(reason)` throws for a hostile `toPrimitive`/Proxy, and
146
+ * `reason instanceof Error` throws for a Proxy whose `getPrototypeOf` trap
147
+ * throws (spec E18 — pre-fix the caller received `Error: conversion failed`
148
+ * instead of its own throw). Every branch below is total.
149
+ */
150
+ function normalizeThrown(thrown: unknown): Error {
151
+ try {
152
+ return thrown instanceof Error ? thrown : new Error(String(thrown));
153
+ } catch {
154
+ return new Error('unprintable thrown value'); // never a second throw
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Issue #450 (D5): the message of an arbitrary thrown value, total for EVERY
160
+ * input — including an Error-shaped Proxy whose `.message` getter throws.
161
+ */
162
+ function thrownMessage(thrown: unknown): string {
163
+ try {
164
+ return normalizeThrown(thrown).message;
165
+ } catch {
166
+ return 'unprintable thrown value'; // an Error-shaped Proxy whose .message throws
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Issue #450 (D5): a log call on an ERROR path must never replace the error it
172
+ * reports — a throwing sink becomes the caller's error and skips every later
173
+ * step of the cleanup. Both sink faults are now contained at the sink itself:
174
+ * #543 the console mirror (swallowed like a file-write fault), #545 the entry
175
+ * build (`JSON.stringify` on a cyclic or `BigInt` `data` used to throw). This
176
+ * wrapper stays as belt-and-braces, local to the settle/pre-start paths, where
177
+ * a third fault class would otherwise become the caller's error.
178
+ */
179
+ function safeLog(write: () => void): void {
180
+ try {
181
+ write();
182
+ } catch {
183
+ // a throwing sink must not mask the original throw nor skip a later step
184
+ }
185
+ }
186
+
135
187
  // Robust UUID generation with fallback
136
188
  function generateUUID(): string {
137
189
  try {
@@ -465,14 +517,12 @@ function persistAgent(agent: BackgroundAgent): void {
465
517
  // F24: agent.id may come from a disk-loaded record (loadAgent JSON.parse's
466
518
  // the id field unvalidated). A planted record with a traversal id would
467
519
  // make join() escape STORAGE_DIR — validate BEFORE building the write path.
468
- try {
469
- assertSafeAgentId(agent.id);
470
- } catch {
520
+ const filePath = agentRecordPath(agent.id);
521
+ if (!filePath) {
471
522
  log.error(`Refusing to persist agent with invalid id: ${agent.id}`);
472
523
  return;
473
524
  }
474
525
  ensureStorageDir();
475
- const filePath = join(STORAGE_DIR, `${agent.id}.json`);
476
526
  // Strip live/non-serializable fields before stringify — `_sessionRef` holds the
477
527
  // ENTIRE live pi session graph (1.4MB+ for an empty session, and uninitialized
478
528
  // getters like Theme can make JSON.stringify throw). `_sessionFile` (U2) is the
@@ -492,16 +542,65 @@ function persistAgent(agent: BackgroundAgent): void {
492
542
  }
493
543
 
494
544
  /**
495
- * Load agent record from disk
545
+ * The agent store's record path for `id`: `<STORAGE_DIR>/<id>.json`.
546
+ *
547
+ * F24: ids reach the store from disk and from LLM tool params, and `join` does
548
+ * not sanitize `../` or absolute segments — validate BEFORE building the write
549
+ * path. `null` means "no record is addressable for this id" (the writer could
550
+ * never have created one), which every reader treats as absent.
551
+ *
552
+ * Issue #546 (major 2): the ONE path helper. `persistAgent`, `loadAgent`, the
553
+ * tri-state reader and `flipAgentRecord` all build the path here, so the
554
+ * absence test and the write target cannot drift apart.
496
555
  */
497
- function loadAgent(id: string): BackgroundAgent | null {
498
- const filePath = join(STORAGE_DIR, `${id}.json`);
499
- if (!existsSync(filePath)) return null;
556
+ function agentRecordPath(id: string): string | null {
500
557
  try {
501
- return JSON.parse(readFileSync(filePath, 'utf-8'));
558
+ assertSafeAgentId(id);
502
559
  } catch {
503
560
  return null;
504
561
  }
562
+ return join(STORAGE_DIR, `${id}.json`);
563
+ }
564
+
565
+ /**
566
+ * Issue #546 (major 2): the disk-only, TRI-STATE read of one agent record.
567
+ *
568
+ * `loadAgent` collapses "there is no record" and "there is a record I cannot
569
+ * parse" into `null`, and the flip must not: the first means nothing durable can
570
+ * go stale (retire the marker), the second means we know nothing (keep it).
571
+ * `exists` is the stat of the validated path, so a chmod-000 or corrupt file
572
+ * reports `{ record: null, exists: true }`.
573
+ */
574
+ export function readAgentRecordFromDisk(id: string): { record: BackgroundAgent | null; exists: boolean } {
575
+ const filePath = agentRecordPath(id);
576
+ if (!filePath) return { record: null, exists: false };
577
+ try {
578
+ statSync(filePath);
579
+ } catch (err) {
580
+ // ONLY `ENOENT` is a CONFIRMED absence. `existsSync` also answers false when a
581
+ // parent directory cannot be traversed (EACCES): reporting that as absence
582
+ // lets the flip retire a marker over a record that is still `running`
583
+ // (r2 major 1). An uncertain stat is treated like an unreadable record —
584
+ // `exists: true`, `record: null` — so the marker is kept and counted failed.
585
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { record: null, exists: false };
586
+ log.warn(`Could not stat agent record ${id} — treating it as unreadable`, {
587
+ error: err instanceof Error ? err.message : String(err),
588
+ });
589
+ return { record: null, exists: true };
590
+ }
591
+ try {
592
+ return { record: JSON.parse(readFileSync(filePath, 'utf-8')), exists: true };
593
+ } catch {
594
+ return { record: null, exists: true };
595
+ }
596
+ }
597
+
598
+ /**
599
+ * Load agent record from disk. `null` on absent OR unreadable — use
600
+ * `readAgentRecordFromDisk` wherever the difference matters (issue #546).
601
+ */
602
+ function loadAgent(id: string): BackgroundAgent | null {
603
+ return readAgentRecordFromDisk(id).record;
505
604
  }
506
605
 
507
606
  /**
@@ -651,6 +750,12 @@ function isSafeAgentId(id: string): boolean {
651
750
  }
652
751
  }
653
752
 
753
+ /**
754
+ * Issue #546: what a record flip actually did — the value the boot ledger counts
755
+ * (see `flipAgentRecord`). `false` is the fail-closed "not settled" outcome.
756
+ */
757
+ export type AgentFlipOutcome = 'repaired' | 'retired' | false;
758
+
654
759
  export function isTerminalAgentStatus(status: AgentStatus): boolean {
655
760
  return status === 'completed' || status === 'failed' || status === 'stopped';
656
761
  }
@@ -1106,6 +1211,134 @@ export function updateAgentStatus(id: string, status: AgentStatus, error?: strin
1106
1211
  return agent;
1107
1212
  }
1108
1213
 
1214
+ /**
1215
+ * Issue #546: the agent-record step, in its TWO contracts — ONE shared disk
1216
+ * verdict, two different assumptions BEFORE the write.
1217
+ *
1218
+ * `settleLiveAgentRecord` is the LIVE pre-start writer (#542's pin). It runs in
1219
+ * the process that owns the in-memory map, so the MEMORY record must become
1220
+ * terminal in EVERY fault — an absent record, an unreadable record, a persist
1221
+ * that `persistAgent` swallows. A `running` memory row after a failed pre-start
1222
+ * is a lie this same process is still asked about (`get_subagent_result`,
1223
+ * `get_agent_status`), and it is exactly what #542 fixed: r3 reintroduced it by
1224
+ * making the live writer share the boot's disk-only decision.
1225
+ *
1226
+ * `flipAgentRecord` is the boot REPLAY (`recoverInflightRuns`'s
1227
+ * `applyRecordFlip`). A fresh process has no memory to trust, so it decides from
1228
+ * the DISK alone: absent ⇒ retire; present-but-unreadable ⇒ keep the marker and
1229
+ * count a failure; `running` + a provably dead owner ⇒ flip (the flip itself
1230
+ * loads the record into memory); already terminal ⇒ retire with no write.
1231
+ *
1232
+ * RETIREMENT IS THE SAME RULE ON BOTH SIDES: retire only when the disk is
1233
+ * terminal or PROVABLY absent (`ENOENT`); keep the marker when the disk is
1234
+ * `running` or unreadable. That is `terminalVerdictAfterWrite`.
1235
+ *
1236
+ * TOTAL: neither function throws. The outcome vocabulary:
1237
+ *
1238
+ * - `'retired'` — nothing durable is left to repair: no record is stored, or
1239
+ * (replay only) it was already terminal, so no `completedAt` re-stamp and no
1240
+ * second `subagent:failed`. The marker may be retired;
1241
+ * - `'repaired'` — the record was written and the store says terminal;
1242
+ * - `false` — the end state is UNCERTAIN: present-but-unreadable/corrupt,
1243
+ * a write that did not land, or a live id that is in neither the map nor the
1244
+ * store. The caller keeps the marker (fail-closed).
1245
+ */
1246
+ export function flipAgentRecord(id: string, status: RecordFlipStatus, error?: string): AgentFlipOutcome {
1247
+ // PRE-FLIP READ: the DISK, not the in-memory map (major 2 + 3). `getAgent` is
1248
+ // memory-first, and that map is module state that can hold a record another
1249
+ // process already flipped — deciding on it would re-stamp `completedAt` and
1250
+ // re-emit `subagent:failed` for a run that is already settled. Reading the
1251
+ // store first makes a boot that begins after another finished INERT, makes a
1252
+ // same-process retry attempt the write again once the store is writable, and
1253
+ // separates confirmed absence from present-but-unreadable.
1254
+ const before = readAgentRecordFromDisk(id);
1255
+ if (!before.exists) return 'retired'; // confirmed absence (or unsafe id)
1256
+ if (!before.record) {
1257
+ // Present but unreadable/corrupt: we know nothing, so we may not retire the
1258
+ // only marker that can repair it.
1259
+ log.warn(`Could not read the agent record for ${id} — keeping the record-flip marker`, {});
1260
+ return false;
1261
+ }
1262
+ if (isTerminalAgentStatus(before.record.status)) return 'retired'; // replay is inert
1263
+ let touched: BackgroundAgent | null = null;
1264
+ try {
1265
+ touched = updateAgentStatus(id, status, error);
1266
+ } catch (err) {
1267
+ log.warn(`Failed to flip the terminal record for ${id}`, {
1268
+ error: err instanceof Error ? err.message : String(err),
1269
+ });
1270
+ } finally {
1271
+ // persistAgent strips the ref from the persisted copy anyway, so this is
1272
+ // memory-only — and it must run even when the flip's own try failed.
1273
+ if (touched) touched._sessionRef = undefined;
1274
+ }
1275
+ return terminalVerdictAfterWrite(id);
1276
+ }
1277
+
1278
+ /**
1279
+ * The DISK verdict after a terminal write, shared by both contracts above:
1280
+ *
1281
+ * - `'repaired'` — the store says the record is terminal;
1282
+ * - `'retired'` — no record is stored (confirmed `ENOENT`, or the id is not
1283
+ * addressable): nothing durable can go stale, so the marker's only purpose
1284
+ * is vacuous;
1285
+ * - `false` — the store cannot tell: present-but-unreadable/corrupt, or
1286
+ * the write was swallowed and the record is STILL `running`. `false` is the
1287
+ * value that keeps the caller's marker for the next boot.
1288
+ *
1289
+ * `persistAgent` swallows write errors (V8), so a throw-free write is not a
1290
+ * landed write: the verdict is read from the STORE, never inferred from a
1291
+ * return value.
1292
+ */
1293
+ function terminalVerdictAfterWrite(id: string): AgentFlipOutcome {
1294
+ const after = readAgentRecordFromDisk(id);
1295
+ if (!after.exists) return 'retired'; // vanished/writable: nothing durable left
1296
+ if (!after.record) {
1297
+ log.warn(`Could not re-read the agent record for ${id} after the flip`, {});
1298
+ return false;
1299
+ }
1300
+ return isTerminalAgentStatus(after.record.status) ? 'repaired' : false;
1301
+ }
1302
+
1303
+ /**
1304
+ * Issue #546 r4 (the #542 pin): the LIVE writer's record step — MEMORY first,
1305
+ * disk verdict second. TOTAL: it never throws.
1306
+ *
1307
+ * The memory write is NOT conditional on the disk. Whatever the store says —
1308
+ * absent, unreadable, still `running` after a swallowed persist — this process's
1309
+ * record must read terminal the moment the pre-start path returns. Only the
1310
+ * RETIREMENT is conditional, and it is conditional on the disk:
1311
+ *
1312
+ * disk absent → `'retired'` (nothing durable to repair: retire the marker)
1313
+ * disk terminal → `'repaired'` (retire the marker)
1314
+ * disk `running` → `false` (a persist was swallowed: KEEP the marker)
1315
+ * disk unreadable → `false` (we cannot tell: KEEP the marker)
1316
+ *
1317
+ * `updateAgentStatus` returns `null` only when the id is in neither the map nor
1318
+ * the store — impossible for an id this process just registered, and a `false`
1319
+ * (keep the marker) if it ever happens, because then nothing is pinned.
1320
+ *
1321
+ * `_sessionRef` is NOT released here: the caller's release is a plain statement
1322
+ * outside every `try` (it cannot throw and must always run) and `persistAgent`
1323
+ * strips the ref from the persisted copy anyway.
1324
+ */
1325
+ function settleLiveAgentRecord(id: string, status: RecordFlipStatus, error?: string): AgentFlipOutcome {
1326
+ try {
1327
+ if (!updateAgentStatus(id, status, error)) {
1328
+ log.warn(`Could not settle the live agent record for ${id} — it is in neither the map nor the store`, {});
1329
+ return false;
1330
+ }
1331
+ } catch (err) {
1332
+ // Contained: `updateAgentStatus` mutates the map BEFORE it persists and
1333
+ // emits, so the memory record is terminal even when this throws. The disk
1334
+ // verdict below still decides whether the marker may be retired.
1335
+ log.warn(`Failed to flip the terminal record for ${id}`, {
1336
+ error: err instanceof Error ? err.message : String(err),
1337
+ });
1338
+ }
1339
+ return terminalVerdictAfterWrite(id);
1340
+ }
1341
+
1109
1342
  /**
1110
1343
  * Issue #179 (D4): when a run ends in a failure, the prose extracted by
1111
1344
  * extractFinalOutput may come from an EARLIER turn — the failing turn carries
@@ -1679,7 +1912,18 @@ export async function spawnBackgroundSession(
1679
1912
  const finalizeRunEntry = (
1680
1913
  status: "done" | "failed",
1681
1914
  error?: string,
1682
- terminal?: { stopReason?: string; errorCategory?: ErrorCategory; prune?: boolean },
1915
+ terminal?: {
1916
+ stopReason?: string;
1917
+ errorCategory?: ErrorCategory;
1918
+ prune?: boolean;
1919
+ /**
1920
+ * Issue #546: do NOT retire the registry entry here — the caller owns the
1921
+ * retirement and performs it only once the record flip is durable. Only the
1922
+ * pre-start terminal path passes this; every other writer keeps
1923
+ * retire-then-append.
1924
+ */
1925
+ deferRetire?: boolean;
1926
+ },
1683
1927
  ): SubagentRun | undefined => {
1684
1928
  // Issue #511 (U2): settling includes the scratch directory's `.done` marker.
1685
1929
  // This is the SINGLE terminal choke point for a background run (git-setup
@@ -1793,7 +2037,7 @@ export async function spawnBackgroundSession(
1793
2037
  ? { ...(run.originalParams ?? {}), errorCategory }
1794
2038
  : run.originalParams,
1795
2039
  };
1796
- persistRunRecord(pi, entry);
2040
+ persistRunRecord(pi, entry, undefined, { deferRetire: terminal?.deferRetire });
1797
2041
  // Issue #453: set only AFTER the append resolved. A throwing write therefore
1798
2042
  // leaves `entryWritten === false`, so a later settle still classifies the run
1799
2043
  // instead of amending a record that was never written (mutant M3).
@@ -1856,7 +2100,7 @@ export async function spawnBackgroundSession(
1856
2100
  }
1857
2101
  } catch (err) {
1858
2102
  log.warn(`getCurrentBranch failed during cleanup for background agent ${id}`, {
1859
- error: (err as Error).message,
2103
+ error: thrownMessage(err),
1860
2104
  });
1861
2105
  // Issue #466: KEEP the record — we cannot tell where the tree is, which
1862
2106
  // is exactly the crash-equivalent state the boot's retry is for.
@@ -1890,7 +2134,7 @@ export async function spawnBackgroundSession(
1890
2134
  : diffResult.diff;
1891
2135
  }
1892
2136
  } catch (err) {
1893
- log.warn(`captureDiff failed for background agent ${id}`, { error: (err as Error).message });
2137
+ log.warn(`captureDiff failed for background agent ${id}`, { error: thrownMessage(err) });
1894
2138
  }
1895
2139
  try {
1896
2140
  const restoreResult = restoreHead(gitCwd, headState);
@@ -1903,12 +2147,12 @@ export async function spawnBackgroundSession(
1903
2147
  clearHeadState(headStateRepoRoot());
1904
2148
  }
1905
2149
  } catch (err) {
1906
- log.warn(`restoreHead failed for background agent ${id}`, { error: (err as Error).message });
2150
+ log.warn(`restoreHead failed for background agent ${id}`, { error: thrownMessage(err) });
1907
2151
  }
1908
2152
  try {
1909
2153
  deleteBranch(gitCwd, workBranchName);
1910
2154
  } catch (err) {
1911
- log.warn(`deleteBranch failed for background agent ${id}`, { error: (err as Error).message });
2155
+ log.warn(`deleteBranch failed for background agent ${id}`, { error: thrownMessage(err) });
1912
2156
  }
1913
2157
  } finally {
1914
2158
  releaseGitLock?.();
@@ -1923,6 +2167,94 @@ export async function spawnBackgroundSession(
1923
2167
  // no-op by construction.
1924
2168
  let deadlineHandle: ReturnType<typeof setTimeout> | undefined;
1925
2169
 
2170
+ /**
2171
+ * Issue #465 (b) / #466 (ADR 0026 D4) / #542: the terminal write for a run that
2172
+ * was PROVABLY never issued — the branch refusals below and every pre-start
2173
+ * throw end here. ONE definition.
2174
+ *
2175
+ * **ORDER.** The three writes run **run entry → record flip → transcript**. This
2176
+ * is deliberately NOT #466's record-first order, for two measured reasons:
2177
+ *
2178
+ * 1. **Crash window.** A kill after the run-entry append **commits** and before
2179
+ * the record flip leaves a **`running` agent with a terminal run entry** — not
2180
+ * a terminal agent with an unfinalized run. The first residue costs a stale
2181
+ * row whose run entry already says `failed`, registry retired, session dir
2182
+ * pruned, and which no retry or interrupted-run surface can pick up
2183
+ * (§Residual window, **including the earlier window inside this step**). The
2184
+ * second is F1's: an unfinalized `running` run entry, a leaked registry
2185
+ * entry, and a retained session dir only a manual sweep removes.
2186
+ * 2. **Reentrancy.** The `subagent:failed` event is emitted by the record flip —
2187
+ * the **second** write. So the run-entry prune/retention decision
2188
+ * (`finalizeRunEntry`'s `!agent.interruptedAt` gate) has already been taken
2189
+ * when a listener runs, and a listener that synchronously sets
2190
+ * `interruptedAt` cannot change the retention outcome. Under the record-first
2191
+ * order it can, and it does: measured, the directory survives.
2192
+ *
2193
+ * **ATTEMPTED, NOT COMMITTED.** The event follows the run-entry write being
2194
+ * **attempted**, not its having been committed. `persistRunRecord` retires the
2195
+ * registry **before** it appends (`run-registry.ts:345-352`), so an append that
2196
+ * throws leaves no terminal entry; and **each step is contained separately** —
2197
+ * every caller rethrows the ORIGINAL failure (`failPreStart(…); throw err`), so
2198
+ * no step may replace it or suppress another (`updateAgentStatus` is total only
2199
+ * through its error-reporting path, R1/D3; the transcript note is not total at
2200
+ * all, R2). The consequence on the STEP-A fault is stated plainly: the record
2201
+ * flip and the note still happen, so the residue is **`agent=failed` with the
2202
+ * run entry uncommitted (`running`)** — the designed outcome of a fault, not a
2203
+ * second defect, and pinned separately from the committed case (test (b)).
2204
+ *
2205
+ * **NOTHING IS CAPTURED and the ref is dropped INLINE, outside every `try`.**
2206
+ * `captureAndReleaseSession` is not used here: it would fabricate a
2207
+ * `finalOutput` for a session that never produced one, and it is declared below
2208
+ * call site A — a TDZ reference there. `persistAgent` strips `_sessionRef`
2209
+ * anyway, so the release is memory-only and must nonetheless always run (the
2210
+ * issue's second bullet).
2211
+ */
2212
+ const markSpawnFailedBeforePrompt = (message: string): void => {
2213
+ // STEP 0 (#546) — the durable INTENT, written while the registry entry still
2214
+ // exists: retirement is an unlink, so a marker written after it has nowhere to
2215
+ // live. Best-effort and total; `false` means the entry was already gone, in
2216
+ // which case there is nothing for a crash to strand.
2217
+ const marked = markRecordFlipPending(id, { status: 'failed', error: message, at: new Date().toISOString() });
2218
+ if (!marked) {
2219
+ // Issue #546 (major 1): a marker that did not land must NOT defer the
2220
+ // retirement. With no durable intent, STEP A takes the PRE-#546 order
2221
+ // (retire, then append) — a crash in its window is the historical residue
2222
+ // (record `running`, entry gone, no marker: unrepairable by design), which
2223
+ // is strictly better than an entry that looks repairable and is not.
2224
+ // `writeAtomic` is temp-file + rename, so a failed write cannot leave a
2225
+ // half-marked entry: the store holds either the old entry or the full one.
2226
+ safeLog(() => log.warn(`spawnBackgroundSession: record-flip marker not written for ${id} — using the pre-#546 retire-then-append order`, {}));
2227
+ }
2228
+ try { // STEP A — run entry (+ retention/prune; retirement DEFERRED only when marked)
2229
+ finalizeRunEntry('failed', message, { deferRetire: marked });
2230
+ } catch (err) {
2231
+ safeLog(() => log.warn(`spawnBackgroundSession: pre-start finalize failed for ${id}`,
2232
+ { error: thrownMessage(err) }));
2233
+ }
2234
+ // STEP B — record flip (completedAt + error, emits subagent:failed). Issue
2235
+ // #546 r4: the LIVE writer's variant — the MEMORY record becomes terminal in
2236
+ // every fault (#542's pin), and only the RETIREMENT is decided from the disk.
2237
+ // `landed === false` means the store is `running` or unreadable, so the
2238
+ // marker must survive for the next boot.
2239
+ const landed = settleLiveAgentRecord(id, 'failed', message);
2240
+ try { // STEP C — transcript note (no-op+warn when the file is missing)
2241
+ transcript.completeTranscript(id, 'failed');
2242
+ } catch (err) {
2243
+ safeLog(() => log.warn(`spawnBackgroundSession: pre-start transcript note failed for ${id}`,
2244
+ { error: thrownMessage(err) }));
2245
+ }
2246
+ agent._sessionRef = undefined; // outside every try — cannot throw, must always run
2247
+ // STEP D (#546) — retire LAST, and only when the flip is durable. Retiring a
2248
+ // run whose record is still `running` is the whole defect: the registry entry
2249
+ // is the only thing a fresh process can read, so keeping it turns this crash
2250
+ // into an ordinary interrupted candidate the next boot can finish.
2251
+ if (marked && landed && !clearInflightRun(id)) {
2252
+ // The record is settled but the entry survived (major 4): keep going — the
2253
+ // next boot sees a terminal record and re-attempts only the retirement.
2254
+ safeLog(() => log.warn(`spawnBackgroundSession: record settled but the registry entry survived for ${id} — the next boot retries the retirement`, {}));
2255
+ }
2256
+ };
2257
+
1926
2258
  /**
1927
2259
  * Issue #447: the pre-start cleanup. Every throw between the durable
1928
2260
  * dispatch records (agent record + run entry + registry entry, written
@@ -1934,22 +2266,39 @@ export async function spawnBackgroundSession(
1934
2266
  * was never issued nothing can be writing to that dir and no retry will be
1935
2267
  * offered for it, so there is no reader to retain it for.
1936
2268
  *
2269
+ * "Never issued" is a CONTRACT, not an observation — issue #450 D2.1: it
2270
+ * holds because the call site invokes (a) the SDK's own `async` `prompt`
2271
+ * through (b) a plain property read, with (c) a side-effect-free argument.
2272
+ * A wrapper/getter that starts the real method and then throws breaks all of
2273
+ * that (spec E24: `live=true` after the synchronous throw); such a call shape
2274
+ * must NOT reach this function. See the REGIME 1 comment at the call site.
2275
+ *
1937
2276
  * The terminal write is best-effort so a throw in the cleanup cannot mask
1938
2277
  * the original spawn error: `persistRunRecord` retires the registry entry
1939
2278
  * BEFORE appending the entry, and `clearInflightRun` is idempotent, so the
1940
2279
  * residue is gone either way.
2280
+ *
2281
+ * Issue #542: STEP 2 is the FULL terminal flip — run entry, record flip and
2282
+ * transcript note — via `markSpawnFailedBeforePrompt` (its contract comment
2283
+ * above states the order, the attemptedness rule and the containment rule).
2284
+ * The "pruning is provably safe here" argument above is unchanged by it.
1941
2285
  */
1942
2286
  const failPreStart = (message: string): void => {
1943
2287
  if (deadlineHandle) clearTimeout(deadlineHandle);
1944
- cleanupWorkBranch();
1945
- try {
1946
- finalizeRunEntry('failed', message);
2288
+ // EVERY step is contained: a throw here would replace the original spawn failure at
2289
+ // every call site (all do `failPreStart(...); throw err`).
2290
+ try { // STEP 1 — teardown (defence in depth, M18 green)
2291
+ cleanupWorkBranch();
1947
2292
  } catch (err) {
1948
- log.warn(`spawnBackgroundSession: pre-start finalize failed for ${id}`, {
1949
- error: (err as Error).message,
1950
- });
2293
+ safeLog(() => log.error(`spawnBackgroundSession: work-branch teardown failed for ${id} — the original spawn failure is preserved`,
2294
+ { error: thrownMessage(err) }));
1951
2295
  }
1952
- clearInflightRun(id);
2296
+ // STEP 2 — the FULL terminal flip (#542): marker, run entry, record flip and
2297
+ // transcript note, each contained in the shared helper (which is total).
2298
+ // #546: the helper also owns the registry retirement (its STEP D), because the
2299
+ // retire is now conditional on the record flip being durable — a blanket
2300
+ // `clearInflightRun` here would delete the marker that repairs this crash.
2301
+ markSpawnFailedBeforePrompt(message);
1953
2302
  };
1954
2303
 
1955
2304
  /** The pre-start failure stamp: the issue's honest reason plus the cause. */
@@ -1957,23 +2306,6 @@ export async function spawnBackgroundSession(
1957
2306
  `${PROMPT_NEVER_ISSUED_MESSAGE}: ` +
1958
2307
  sanitizeErrorMessage(err instanceof Error ? err.message : String(err), effectiveCwd);
1959
2308
 
1960
- /**
1961
- * Issue #465 (b) / #466 (ADR 0026 D4): the terminal write for a branch
1962
- * dispatch refused before the prompt — record flip -> run entry ->
1963
- * transcript, the same three writes every refused spawn ends with. ONE
1964
- * definition for both pre-flight refusals AND the branch-setup-throw path
1965
- * below, so the sequence and its message cannot drift apart between them;
1966
- * each step is contained, because a cleanup fault must never mask the
1967
- * refusal itself.
1968
- */
1969
- const markBranchSpawnFailed = (message: string): void => {
1970
- try {
1971
- updateAgentStatus(id, 'failed', message);
1972
- finalizeRunEntry('failed', message);
1973
- transcript.completeTranscript(id, 'failed');
1974
- } catch { /* best-effort, same discipline as the setup-throw path */ }
1975
- };
1976
-
1977
2309
  // Start transcript for this agent. Issue #447 (S2): a throw here used to
1978
2310
  // leave a `running` run entry and a live registry entry that the next boot
1979
2311
  // offered as an interrupted, retryable run — clean it and rethrow.
@@ -2098,14 +2430,14 @@ export async function spawnBackgroundSession(
2098
2430
  // Mirror the branch-setup-throw path below: the agent record was already
2099
2431
  // persisted as 'running' above, so a refusal that only THROWS leaves a
2100
2432
  // zombie row `get_subagent_result` reports as running forever (measured,
2101
- // #460 §4.4 — `failPreStart` alone stops at the run entry). Record flip ->
2102
- // run entry -> transcript (one shared helper), then the throw that reaches
2103
- // the caller's spawn-failure result. `finalizeRunEntry` already retires the
2104
- // registry entry (a non-running write clears it); the explicit call is the
2105
- // belt for a finalize that threw — registry residue is what boot recovery
2106
- // reads, and this dispatch provably never started.
2107
- markBranchSpawnFailed(reason);
2108
- clearInflightRun(id);
2433
+ // #460 §4.4 — `failPreStart` alone stops at the run entry). The pre-start
2434
+ // terminal flip is the shared helper — see its contract comment above —
2435
+ // then the throw that reaches the caller's spawn-failure result.
2436
+ // `finalizeRunEntry` already retires the registry entry (a non-running
2437
+ // write clears it); the explicit call is the belt for a finalize that
2438
+ // threw — registry residue is what boot recovery reads, and this dispatch
2439
+ // provably never started.
2440
+ markSpawnFailedBeforePrompt(reason);
2109
2441
  throw new Error(reason);
2110
2442
  }
2111
2443
  // Issue #465 (d): release the process-wide spawn queue BEFORE the per-repo
@@ -2208,11 +2540,12 @@ export async function spawnBackgroundSession(
2208
2540
  releaseGitLock?.();
2209
2541
  releaseGitLock = undefined;
2210
2542
  // Sanitize ONCE and reuse for the terminal write and the thrown error.
2211
- const sanitizedError = sanitizeErrorMessage((err as Error).message, effectiveCwd);
2543
+ const sanitizedError = sanitizeErrorMessage(thrownMessage(err), effectiveCwd);
2212
2544
  // Issue #98: the refused spawn is a failure — flip the record and finalize
2213
2545
  // the run entry so no zombie 'running' entry survives (lockstep, one
2214
- // shared sequence with both pre-flight refusals).
2215
- markBranchSpawnFailed(
2546
+ // shared sequence with both pre-flight refusals: see the helper's contract
2547
+ // comment above).
2548
+ markSpawnFailedBeforePrompt(
2216
2549
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
2217
2550
  throw new Error(
2218
2551
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}. ` +
@@ -2486,20 +2819,24 @@ export async function spawnBackgroundSession(
2486
2819
  // attach and cleanupWorkBranch would never run — catch here so the work
2487
2820
  // branch is not orphaned (it is a real filesystem branch).
2488
2821
  let runPromise: Promise<unknown>;
2489
- try {
2490
- runPromise = session.prompt(wrapTask(params.task));
2491
- } catch (err) {
2492
- // Issue #98 (review F1): a synchronous prompt() throw never reaches the
2493
- // settle handlers — finalize the run entry so no zombie 'running' entry
2494
- // survives (findSpawnRunById would otherwise resolve and retry a run that
2495
- // never started). #447: the same cleanup also clears the deadline armed
2496
- // above and retires the registry entry.
2497
- failPreStart(sanitizeErrorMessage((err as Error).message, effectiveCwd));
2498
- throw err;
2499
- }
2822
+ let resolveSettled!: () => void;
2823
+ let rejectSettled!: (reason: unknown) => void;
2824
+ const settled = new Promise<void>((resolve, reject) => {
2825
+ resolveSettled = resolve;
2826
+ rejectSettled = reject;
2827
+ });
2500
2828
 
2501
- runPromise.then(() => {
2502
- if (deadlineHandle) clearTimeout(deadlineHandle);
2829
+ const markSettleEntry = (kind: 'success' | 'fault'): void => {
2830
+ try {
2831
+ log.debug(`spawnBackgroundSession: settle body entered for ${id} (${kind})`);
2832
+ } catch {
2833
+ // best effort — the marker must never change the settle path
2834
+ }
2835
+ };
2836
+
2837
+ const onSettled = (): void => {
2838
+ markSettleEntry('success'); // FIRST statement
2839
+ if (deadlineHandle) clearTimeout(deadlineHandle); // deadline clear, second
2503
2840
  try {
2504
2841
  // Probe contract (sdk-abort-contract.test.ts): prompt() RESOLVES on abort
2505
2842
  // — the SDK's runWithLifecycle catches the AbortError and converts it into
@@ -2643,14 +2980,20 @@ export async function spawnBackgroundSession(
2643
2980
  // Issue #53: any throw in this handler would escape as an
2644
2981
  // uncaughtException and kill pi. Log and mark the record terminal —
2645
2982
  // never rethrow.
2646
- log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2647
- error: (err as Error).message,
2648
- });
2983
+ safeLog(() =>
2984
+ log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2985
+ error: thrownMessage(err),
2986
+ }),
2987
+ );
2649
2988
  markTerminalBestEffort('completed');
2650
2989
  }
2651
- }).catch((err: Error) => {
2652
- if (deadlineHandle) clearTimeout(deadlineHandle);
2990
+ };
2991
+
2992
+ const onSettleFault = (reason: unknown): void => {
2993
+ markSettleEntry('fault'); // FIRST statement
2994
+ if (deadlineHandle) clearTimeout(deadlineHandle); // deadline clear, second
2653
2995
  try {
2996
+ const err = normalizeThrown(reason); // D5: TOTAL, never throws
2654
2997
  // W4: capture partial work + discard the work branch on failure — a failed
2655
2998
  // background agent may still have produced reviewable changes.
2656
2999
  const gitInfo = cleanupWorkBranch();
@@ -2709,13 +3052,108 @@ export async function spawnBackgroundSession(
2709
3052
  // Issue #53: any throw in this handler would escape as an
2710
3053
  // uncaughtException and kill pi. Log and mark the record terminal —
2711
3054
  // never rethrow.
2712
- log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2713
- error: (err as Error).message,
2714
- });
3055
+ safeLog(() =>
3056
+ log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
3057
+ error: thrownMessage(err),
3058
+ }),
3059
+ );
2715
3060
  markTerminalBestEffort('failed');
2716
3061
  }
2717
- });
2718
-
3062
+ };
3063
+
3064
+ // THE ATTACH: both settle handlers are on our own promise before the session
3065
+ // is asked to start. The #450 window snapshot pin covers this statement.
3066
+ settled.then(onSettled).catch(onSettleFault);
3067
+
3068
+ // ---- REGIME 1: pre-start ------------------------------------------------
3069
+ // The one statement in this regime is the prompt CALL. A synchronous throw
3070
+ // from it is proof that the prompt was never issued ONLY under three
3071
+ // preconditions, and all three hold at this site TODAY (issue #450 D2.1):
3072
+ //
3073
+ // (a) the callee is the SDK's own `async` method — `AgentSession.prompt`
3074
+ // (node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js:1704,
3075
+ // typed `prompt(text): Promise<void>` in agent-session.d.ts:573). An
3076
+ // `async` function cannot throw to its caller: such a throw happened
3077
+ // BEFORE entry.
3078
+ // (b) it is reached by a PLAIN property read on the session object — no
3079
+ // getter, no Proxy. A getter can start the real method and THEN throw,
3080
+ // so the caller sees a synchronous throw while the session is already
3081
+ // running (spec E24: `syncThrow=yes`, `live=true`). That shape VOIDS
3082
+ // the proof and must be handled as a post-start fault.
3083
+ // (c) the argument is evaluated without side effects (`wrapTask` is one
3084
+ // `String.replace`, src/prompt.ts:67).
3085
+ //
3086
+ // If a future edit wraps `session.prompt` — a retry wrapper, a decorator, an
3087
+ // injected session double that starts work — then (a)/(b) no longer hold,
3088
+ // this regime's premise is GONE, and `failPreStart`'s directory prune plus
3089
+ // branch release would hit a LIVE session. Re-derive D2.1 before keeping it.
3090
+ try {
3091
+ runPromise = session.prompt(wrapTask(params.task));
3092
+ } catch (err) {
3093
+ // Issue #98 (review F1): a synchronous prompt() throw never reaches the
3094
+ // settle handlers — finalize the run entry so no zombie 'running' entry
3095
+ // survives (findSpawnRunById would otherwise resolve and retry a run that
3096
+ // never started). #447: the same cleanup also clears the deadline armed
3097
+ // above and retires the registry entry.
3098
+ const reason = thrownMessage(err); // D5: total
3099
+ failPreStart(sanitizeErrorMessage(reason, effectiveCwd)); // D5: contained, never throws
3100
+ throw err; // D6: deferred NOT settled
3101
+ }
3102
+
3103
+ // ---- REGIME 2: post-start -----------------------------------------------
3104
+ // The prompt has been issued, so NOTHING in here may declare "never issued":
3105
+ // `failPreStart` / `markSpawnFailedBeforePrompt` would prune a LIVE session's
3106
+ // directory and release its branch lock while the session may still be
3107
+ // writing (strictly worse than the fault it reports). No `failPreStart`, no
3108
+ // deadline clear, no second bound —
3109
+ // the deadline armed above stays the monitor of last resort (ADR 0023
3110
+ // decision 1: ONE owner), and the spawn still resolves with a `running`
3111
+ // agent (#439 boundary: a post-start routing fault must not reject the spawn).
3112
+ //
3113
+ // WHY the intrinsic and not `runPromise.then(...)`: `PerformPromiseThen`
3114
+ // performs `SpeciesConstructor(promise)`, which READS `constructor` and then
3115
+ // `constructor[Symbol.species]` — and how it does that depends on the value; a
3116
+ // Proxy's `then` trap or a throwing `then` accessor is reached by the `.then`
3117
+ // METHOD READ, not by the intrinsic. Routing through `Promise.prototype.then`
3118
+ // therefore never touches the value's own `then`, which is what makes the
3119
+ // SUPPORTED value's attach byte-equivalent to `runPromise.then(...)` while a
3120
+ // malformed return is REFUSED here and logged instead of starting work.
3121
+ //
3122
+ // NOT `await`, and NOT `Promise.resolve(...)`: both were measured and both
3123
+ // destroy the contract below — `await` (and `Promise.resolve`) treats a
3124
+ // NON-thenable as a resolution, so `{}` would run the success body and record
3125
+ // a live run as `completed`, and the routing fault would go unlogged. See the
3126
+ // spec's Q2 rows A1 and R3.
3127
+ //
3128
+ // Issue #450 (D2.3/D3/Acceptance 8 — THE CONTRACT; the same words in all three places):
3129
+ //
3130
+ // SUPPORTED — an ordinary native `Promise<void>` of this realm whose `constructor`
3131
+ // and `Symbol.species` reads both complete without a throw and resolve to the
3132
+ // intrinsic `Promise`: the routing attaches and no later rejection can be stranded.
3133
+ //
3134
+ // UNSUPPORTED — every other value, NO GUARANTEE; measured, it splits three ways:
3135
+ // · REFUSED, NOTHING STRANDED: a non-thenable or a custom thenable — thrown here,
3136
+ // logged, the run is left to the deadline.
3137
+ // · REFUSED, REJECTION UNOWNED: a Proxy over a promise, or a native promise whose
3138
+ // `constructor` or `Symbol.species` read throws — thrown here, logged, and the
3139
+ // value's later rejection has no handler, so the host exits 1 (default and strict).
3140
+ // · ACCEPTED, NOT RELIED ON: a same-realm subclass and a cross-realm promise route
3141
+ // and deliver (exit 0). `await` would also own the species-throwing case, but it
3142
+ // registers a non-promise return as a success (spec E50), so it is not the routing.
3143
+ try {
3144
+ void Promise.prototype.then.call(runPromise, resolveSettled, rejectSettled); // D2.3
3145
+ } catch (err) {
3146
+ // A SENSOR, not a new fault: the run already started, so this only reports
3147
+ // that it is unmonitored. `safeLog` is load-bearing — a throwing console
3148
+ // mirror here would reject the spawn (#439) and destroy the boundary above.
3149
+ safeLog(() => // a sensor, not a new fault
3150
+ log.error(
3151
+ `spawnBackgroundSession: settle routing failed for ${id} — the run is unmonitored; its deadline remains the only bound`,
3152
+ { error: thrownMessage(err) },
3153
+ ),
3154
+ );
3155
+ }
3156
+
2719
3157
  return agent;
2720
3158
  } finally {
2721
3159
  releaseSpawnQueue();