brl-subagent 2.8.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.
Files changed (48) hide show
  1. package/AGENT.md +17 -2
  2. package/README.md +3 -3
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +360 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +3 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +1 -1
  11. package/src/git.ts +220 -8
  12. package/src/headstate.ts +3 -3
  13. package/src/history.ts +21 -3
  14. package/src/index.ts +109 -4473
  15. package/src/loader.ts +1 -1
  16. package/src/logging.ts +67 -4
  17. package/src/mode-prologue.ts +4 -10
  18. package/src/mode-runners.ts +1575 -0
  19. package/src/notify-completion.ts +35 -8
  20. package/src/params.ts +14 -13
  21. package/src/preflight.ts +123 -16
  22. package/src/prelude.ts +14 -5
  23. package/src/presets.ts +3 -5
  24. package/src/proc.ts +2 -3
  25. package/src/recovery-engine.ts +1 -1
  26. package/src/recovery-surface.ts +1 -2
  27. package/src/recovery.ts +238 -10
  28. package/src/reports.ts +1 -7
  29. package/src/run-registry.ts +133 -10
  30. package/src/runner.ts +47 -18
  31. package/src/runtime.ts +50 -0
  32. package/src/sanitize.ts +20 -2
  33. package/src/scheduler.ts +1 -2
  34. package/src/schema.ts +4 -2
  35. package/src/scratch-root.ts +909 -0
  36. package/src/scratch-spawn.ts +256 -0
  37. package/src/session-manager.ts +587 -81
  38. package/src/state.ts +12 -14
  39. package/src/templates.ts +3 -5
  40. package/src/terminal-notifier.ts +405 -0
  41. package/src/transcript.ts +1 -1
  42. package/src/tui-format.ts +3 -1
  43. package/src/tui.ts +46 -36
  44. package/src/types.ts +29 -3
  45. package/src/unit-params.ts +113 -0
  46. package/src/unit-run.ts +35 -15
  47. package/src/validate.ts +28 -9
  48. package/src/worktree-report.ts +142 -0
@@ -1,11 +1,28 @@
1
1
  // Purpose: Background execution: SDK sessions (`createAgentSession`), agent records, timeouts, steering, and settle paths.
2
2
  import { randomUUID } from 'crypto';
3
3
  import { basename, dirname, join, resolve } from 'path';
4
- import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync } from 'fs';
5
- import type { Dirent } from 'fs';
6
- import type { BackgroundAgent, AgentStatus, GitMode, RecoveryMode, SubagentResult, SubagentRun, ThinkingLevel, SubagentToolOptions, UsageStats, ErrorCategory } from './types';
7
- import { EMPTY_USAGE, classifyError, classifyTerminalOutcome, isProviderError, coherentFailureReason, SUBAGENT_ABORTED_MESSAGE, NO_ASSISTANT_OUTPUT_REASON, PROMPT_NEVER_ISSUED_MESSAGE } from './types';
8
- import type { AssistantEvidence } from './types';
4
+ import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync, type Dirent } from 'fs';
5
+ import {
6
+ EMPTY_USAGE,
7
+ classifyError,
8
+ classifyTerminalOutcome,
9
+ isProviderError,
10
+ coherentFailureReason,
11
+ SUBAGENT_ABORTED_MESSAGE,
12
+ NO_ASSISTANT_OUTPUT_REASON,
13
+ PROMPT_NEVER_ISSUED_MESSAGE,
14
+ type BackgroundAgent,
15
+ type AgentStatus,
16
+ type GitMode,
17
+ type RecoveryMode,
18
+ type SubagentResult,
19
+ type SubagentRun,
20
+ type ThinkingLevel,
21
+ type SubagentToolOptions,
22
+ type UsageStats,
23
+ type ErrorCategory,
24
+ type AssistantEvidence,
25
+ } from './types';
9
26
  import { accumulateUsage } from './runner';
10
27
  import * as eventBus from './event-bus';
11
28
  import * as transcript from './transcript';
@@ -13,15 +30,35 @@ import { createEvent } from './event-bus';
13
30
  import { assertSafeAgentId, sanitizeErrorMessage } from './sanitize';
14
31
  import { wrapTask } from './prompt';
15
32
  import { createLogger } from './logging';
16
- import { getCurrentBranch, getHeadState, restoreHead, createWorkBranch, newWorkBranchName, captureDiff, deleteBranch, hasUncommittedChanges, getRepoRoot, commitAll, captureWorkingDiff } from './git';
17
- import type { HeadState } from './git';
33
+ import {
34
+ getCurrentBranch,
35
+ getHeadState,
36
+ restoreHead,
37
+ createWorkBranch,
38
+ newWorkBranchName,
39
+ captureDiff,
40
+ deleteBranch,
41
+ hasUncommittedChanges,
42
+ getRepoRoot,
43
+ commitAll,
44
+ captureWorkingDiff,
45
+ type HeadState,
46
+ } from './git';
18
47
  import { clearHeadState, readHeadState, writeHeadState, HEAD_STATE_VERSION } from './headstate';
19
48
  import { effectiveBackgroundBudget } from './validate';
20
49
  import { currentProcessOwner, classifyOwner, defaultRecoveryDeps } from './recovery';
21
- 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';
22
58
  import { isTransportRetryable } from './transport-retry';
23
59
  import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
24
60
  import { buildEngineeringBarSection } from './engineering-bar';
61
+ import { prepareRunScratch, markSettled } from './scratch-spawn';
25
62
 
26
63
  const log = createLogger('brl-subagent');
27
64
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
@@ -102,6 +139,51 @@ export function __testResetGitBranchLocks(): void {
102
139
  gitBranchLockOwners.clear();
103
140
  }
104
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
+
105
187
  // Robust UUID generation with fallback
106
188
  function generateUUID(): string {
107
189
  try {
@@ -435,14 +517,12 @@ function persistAgent(agent: BackgroundAgent): void {
435
517
  // F24: agent.id may come from a disk-loaded record (loadAgent JSON.parse's
436
518
  // the id field unvalidated). A planted record with a traversal id would
437
519
  // make join() escape STORAGE_DIR — validate BEFORE building the write path.
438
- try {
439
- assertSafeAgentId(agent.id);
440
- } catch {
520
+ const filePath = agentRecordPath(agent.id);
521
+ if (!filePath) {
441
522
  log.error(`Refusing to persist agent with invalid id: ${agent.id}`);
442
523
  return;
443
524
  }
444
525
  ensureStorageDir();
445
- const filePath = join(STORAGE_DIR, `${agent.id}.json`);
446
526
  // Strip live/non-serializable fields before stringify — `_sessionRef` holds the
447
527
  // ENTIRE live pi session graph (1.4MB+ for an empty session, and uninitialized
448
528
  // getters like Theme can make JSON.stringify throw). `_sessionFile` (U2) is the
@@ -462,16 +542,65 @@ function persistAgent(agent: BackgroundAgent): void {
462
542
  }
463
543
 
464
544
  /**
465
- * 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.
466
555
  */
467
- function loadAgent(id: string): BackgroundAgent | null {
468
- const filePath = join(STORAGE_DIR, `${id}.json`);
469
- if (!existsSync(filePath)) return null;
556
+ function agentRecordPath(id: string): string | null {
470
557
  try {
471
- return JSON.parse(readFileSync(filePath, 'utf-8'));
558
+ assertSafeAgentId(id);
472
559
  } catch {
473
560
  return null;
474
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;
475
604
  }
476
605
 
477
606
  /**
@@ -621,6 +750,12 @@ function isSafeAgentId(id: string): boolean {
621
750
  }
622
751
  }
623
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
+
624
759
  export function isTerminalAgentStatus(status: AgentStatus): boolean {
625
760
  return status === 'completed' || status === 'failed' || status === 'stopped';
626
761
  }
@@ -1076,6 +1211,134 @@ export function updateAgentStatus(id: string, status: AgentStatus, error?: strin
1076
1211
  return agent;
1077
1212
  }
1078
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
+
1079
1342
  /**
1080
1343
  * Issue #179 (D4): when a run ends in a failure, the prose extracted by
1081
1344
  * extractFinalOutput may come from an EARLIER turn — the failing turn carries
@@ -1339,6 +1602,26 @@ export async function spawnBackgroundSession(
1339
1602
 
1340
1603
  try {
1341
1604
  const id = generateUUID();
1605
+ // Issue #511 (U2): the scratch seam for the BACKGROUND surface. This function
1606
+ // is the single place a background agent record and run entry are created
1607
+ // (single, fan-out and the transport retry all pass through it), so the run's
1608
+ // directory is resolved and created HERE — before the SDK is asked for a
1609
+ // session, and therefore before `session.prompt()` can start the child.
1610
+ //
1611
+ // A refusal is PRE-SPAWN and NAMED: it throws before any record exists, and
1612
+ // both pipeline callers translate a throw from this function into their
1613
+ // ordinary "Failed to spawn background agent: …" result — the same shape as
1614
+ // every other spawn failure.
1615
+ //
1616
+ // NOTE, stated rather than implied: a background run is an IN-PROCESS SDK
1617
+ // session, so there is no child environment to carry `BRL_SCRATCH` (the SDK
1618
+ // composes the shell env from `process.env` at command time, which a per-run
1619
+ // value cannot vary without race). The directory and the record's
1620
+ // `scratchDir` are this surface's whole carrier.
1621
+ const scratch = prepareRunScratch(id, { log });
1622
+ if (!scratch.ok) {
1623
+ throw new Error(`scratch root unavailable (${scratch.code}): ${scratch.message}`);
1624
+ }
1342
1625
  const effectiveCwd = params.cwd ?? ctx.cwd;
1343
1626
  // Dynamic import — static import fails under concurrent jiti loads
1344
1627
  const { getAgentDir, createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader } = await import('@earendil-works/pi-coding-agent');
@@ -1506,6 +1789,12 @@ export async function spawnBackgroundSession(
1506
1789
  model: params.model || 'unknown',
1507
1790
  thinkingLevel: params.thinkingLevel || 'medium',
1508
1791
  priority: params.priority,
1792
+ // Issue #474: the directory this run was spawned in, stamped so a settled
1793
+ // failure can report the worktree it may have left. `effectiveCwd` is the
1794
+ // resolved, validated absolute path (params.cwd ?? ctx.cwd), and
1795
+ // `persistAgent` strips only the live-only pointers — so this survives the
1796
+ // record and the completion wake can read it.
1797
+ cwd: effectiveCwd,
1509
1798
  dispatchId,
1510
1799
  resumeOf: params.resumeOf,
1511
1800
  attempt,
@@ -1545,6 +1834,10 @@ export async function spawnBackgroundSession(
1545
1834
  attempt,
1546
1835
  owner,
1547
1836
  recoveryPosture: params.recoveryPosture,
1837
+ // Issue #511 (U2): the run's scratch directory (`<root>/runs/<id>`, 0700),
1838
+ // created above. Persisted at spawn so the retry preamble (U3) and the
1839
+ // settle path read one value rather than re-deriving a location.
1840
+ scratchDir: scratch.runDir,
1548
1841
  // Issue #447: the acceptance marker starts `null` — the dispatch is
1549
1842
  // TRACKED from here on (agent record + registry entry) but the prompt has
1550
1843
  // not been issued. Only the write immediately above `session.prompt()`
@@ -1619,8 +1912,27 @@ export async function spawnBackgroundSession(
1619
1912
  const finalizeRunEntry = (
1620
1913
  status: "done" | "failed",
1621
1914
  error?: string,
1622
- 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
+ },
1623
1927
  ): SubagentRun | undefined => {
1928
+ // Issue #511 (U2): settling includes the scratch directory's `.done` marker.
1929
+ // This is the SINGLE terminal choke point for a background run (git-setup
1930
+ // refusal, a synchronous prompt throw, the .then/.catch branches, the
1931
+ // catch-all and the deadline), so the marker is written here and no settle
1932
+ // path can forget it. Best-effort: `markSettled` logs and never throws, so
1933
+ // it cannot change the run's outcome. A run with no directory (a pre-U2
1934
+ // record) is a no-op.
1935
+ markSettled(run, log);
1624
1936
  const usage = agent.result?.usage ?? EMPTY_USAGE;
1625
1937
  const finalOutput = agent.finalOutput ?? "";
1626
1938
  // The TRUE category of THIS call — see the note on `classifyFailure`.
@@ -1725,7 +2037,7 @@ export async function spawnBackgroundSession(
1725
2037
  ? { ...(run.originalParams ?? {}), errorCategory }
1726
2038
  : run.originalParams,
1727
2039
  };
1728
- persistRunRecord(pi, entry);
2040
+ persistRunRecord(pi, entry, undefined, { deferRetire: terminal?.deferRetire });
1729
2041
  // Issue #453: set only AFTER the append resolved. A throwing write therefore
1730
2042
  // leaves `entryWritten === false`, so a later settle still classifies the run
1731
2043
  // instead of amending a record that was never written (mutant M3).
@@ -1788,7 +2100,7 @@ export async function spawnBackgroundSession(
1788
2100
  }
1789
2101
  } catch (err) {
1790
2102
  log.warn(`getCurrentBranch failed during cleanup for background agent ${id}`, {
1791
- error: (err as Error).message,
2103
+ error: thrownMessage(err),
1792
2104
  });
1793
2105
  // Issue #466: KEEP the record — we cannot tell where the tree is, which
1794
2106
  // is exactly the crash-equivalent state the boot's retry is for.
@@ -1822,7 +2134,7 @@ export async function spawnBackgroundSession(
1822
2134
  : diffResult.diff;
1823
2135
  }
1824
2136
  } catch (err) {
1825
- 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) });
1826
2138
  }
1827
2139
  try {
1828
2140
  const restoreResult = restoreHead(gitCwd, headState);
@@ -1835,12 +2147,12 @@ export async function spawnBackgroundSession(
1835
2147
  clearHeadState(headStateRepoRoot());
1836
2148
  }
1837
2149
  } catch (err) {
1838
- 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) });
1839
2151
  }
1840
2152
  try {
1841
2153
  deleteBranch(gitCwd, workBranchName);
1842
2154
  } catch (err) {
1843
- 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) });
1844
2156
  }
1845
2157
  } finally {
1846
2158
  releaseGitLock?.();
@@ -1855,6 +2167,94 @@ export async function spawnBackgroundSession(
1855
2167
  // no-op by construction.
1856
2168
  let deadlineHandle: ReturnType<typeof setTimeout> | undefined;
1857
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
+
1858
2258
  /**
1859
2259
  * Issue #447: the pre-start cleanup. Every throw between the durable
1860
2260
  * dispatch records (agent record + run entry + registry entry, written
@@ -1866,22 +2266,39 @@ export async function spawnBackgroundSession(
1866
2266
  * was never issued nothing can be writing to that dir and no retry will be
1867
2267
  * offered for it, so there is no reader to retain it for.
1868
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
+ *
1869
2276
  * The terminal write is best-effort so a throw in the cleanup cannot mask
1870
2277
  * the original spawn error: `persistRunRecord` retires the registry entry
1871
2278
  * BEFORE appending the entry, and `clearInflightRun` is idempotent, so the
1872
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.
1873
2285
  */
1874
2286
  const failPreStart = (message: string): void => {
1875
2287
  if (deadlineHandle) clearTimeout(deadlineHandle);
1876
- cleanupWorkBranch();
1877
- try {
1878
- 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();
1879
2292
  } catch (err) {
1880
- log.warn(`spawnBackgroundSession: pre-start finalize failed for ${id}`, {
1881
- error: (err as Error).message,
1882
- });
2293
+ safeLog(() => log.error(`spawnBackgroundSession: work-branch teardown failed for ${id} — the original spawn failure is preserved`,
2294
+ { error: thrownMessage(err) }));
1883
2295
  }
1884
- 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);
1885
2302
  };
1886
2303
 
1887
2304
  /** The pre-start failure stamp: the issue's honest reason plus the cause. */
@@ -1889,23 +2306,6 @@ export async function spawnBackgroundSession(
1889
2306
  `${PROMPT_NEVER_ISSUED_MESSAGE}: ` +
1890
2307
  sanitizeErrorMessage(err instanceof Error ? err.message : String(err), effectiveCwd);
1891
2308
 
1892
- /**
1893
- * Issue #465 (b) / #466 (ADR 0026 D4): the terminal write for a branch
1894
- * dispatch refused before the prompt — record flip -> run entry ->
1895
- * transcript, the same three writes every refused spawn ends with. ONE
1896
- * definition for both pre-flight refusals AND the branch-setup-throw path
1897
- * below, so the sequence and its message cannot drift apart between them;
1898
- * each step is contained, because a cleanup fault must never mask the
1899
- * refusal itself.
1900
- */
1901
- const markBranchSpawnFailed = (message: string): void => {
1902
- try {
1903
- updateAgentStatus(id, 'failed', message);
1904
- finalizeRunEntry('failed', message);
1905
- transcript.completeTranscript(id, 'failed');
1906
- } catch { /* best-effort, same discipline as the setup-throw path */ }
1907
- };
1908
-
1909
2309
  // Start transcript for this agent. Issue #447 (S2): a throw here used to
1910
2310
  // leave a `running` run entry and a live registry entry that the next boot
1911
2311
  // offered as an interrupted, retryable run — clean it and rethrow.
@@ -2030,14 +2430,14 @@ export async function spawnBackgroundSession(
2030
2430
  // Mirror the branch-setup-throw path below: the agent record was already
2031
2431
  // persisted as 'running' above, so a refusal that only THROWS leaves a
2032
2432
  // zombie row `get_subagent_result` reports as running forever (measured,
2033
- // #460 §4.4 — `failPreStart` alone stops at the run entry). Record flip ->
2034
- // run entry -> transcript (one shared helper), then the throw that reaches
2035
- // the caller's spawn-failure result. `finalizeRunEntry` already retires the
2036
- // registry entry (a non-running write clears it); the explicit call is the
2037
- // belt for a finalize that threw — registry residue is what boot recovery
2038
- // reads, and this dispatch provably never started.
2039
- markBranchSpawnFailed(reason);
2040
- 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);
2041
2441
  throw new Error(reason);
2042
2442
  }
2043
2443
  // Issue #465 (d): release the process-wide spawn queue BEFORE the per-repo
@@ -2140,11 +2540,12 @@ export async function spawnBackgroundSession(
2140
2540
  releaseGitLock?.();
2141
2541
  releaseGitLock = undefined;
2142
2542
  // Sanitize ONCE and reuse for the terminal write and the thrown error.
2143
- const sanitizedError = sanitizeErrorMessage((err as Error).message, effectiveCwd);
2543
+ const sanitizedError = sanitizeErrorMessage(thrownMessage(err), effectiveCwd);
2144
2544
  // Issue #98: the refused spawn is a failure — flip the record and finalize
2145
2545
  // the run entry so no zombie 'running' entry survives (lockstep, one
2146
- // shared sequence with both pre-flight refusals).
2147
- markBranchSpawnFailed(
2546
+ // shared sequence with both pre-flight refusals: see the helper's contract
2547
+ // comment above).
2548
+ markSpawnFailedBeforePrompt(
2148
2549
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
2149
2550
  throw new Error(
2150
2551
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}. ` +
@@ -2418,20 +2819,24 @@ export async function spawnBackgroundSession(
2418
2819
  // attach and cleanupWorkBranch would never run — catch here so the work
2419
2820
  // branch is not orphaned (it is a real filesystem branch).
2420
2821
  let runPromise: Promise<unknown>;
2421
- try {
2422
- runPromise = session.prompt(wrapTask(params.task));
2423
- } catch (err) {
2424
- // Issue #98 (review F1): a synchronous prompt() throw never reaches the
2425
- // settle handlers — finalize the run entry so no zombie 'running' entry
2426
- // survives (findSpawnRunById would otherwise resolve and retry a run that
2427
- // never started). #447: the same cleanup also clears the deadline armed
2428
- // above and retires the registry entry.
2429
- failPreStart(sanitizeErrorMessage((err as Error).message, effectiveCwd));
2430
- throw err;
2431
- }
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
+ });
2432
2828
 
2433
- runPromise.then(() => {
2434
- 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
2435
2840
  try {
2436
2841
  // Probe contract (sdk-abort-contract.test.ts): prompt() RESOLVES on abort
2437
2842
  // — the SDK's runWithLifecycle catches the AbortError and converts it into
@@ -2575,14 +2980,20 @@ export async function spawnBackgroundSession(
2575
2980
  // Issue #53: any throw in this handler would escape as an
2576
2981
  // uncaughtException and kill pi. Log and mark the record terminal —
2577
2982
  // never rethrow.
2578
- log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2579
- error: (err as Error).message,
2580
- });
2983
+ safeLog(() =>
2984
+ log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2985
+ error: thrownMessage(err),
2986
+ }),
2987
+ );
2581
2988
  markTerminalBestEffort('completed');
2582
2989
  }
2583
- }).catch((err: Error) => {
2584
- 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
2585
2995
  try {
2996
+ const err = normalizeThrown(reason); // D5: TOTAL, never throws
2586
2997
  // W4: capture partial work + discard the work branch on failure — a failed
2587
2998
  // background agent may still have produced reviewable changes.
2588
2999
  const gitInfo = cleanupWorkBranch();
@@ -2641,13 +3052,108 @@ export async function spawnBackgroundSession(
2641
3052
  // Issue #53: any throw in this handler would escape as an
2642
3053
  // uncaughtException and kill pi. Log and mark the record terminal —
2643
3054
  // never rethrow.
2644
- log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2645
- error: (err as Error).message,
2646
- });
3055
+ safeLog(() =>
3056
+ log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
3057
+ error: thrownMessage(err),
3058
+ }),
3059
+ );
2647
3060
  markTerminalBestEffort('failed');
2648
3061
  }
2649
- });
2650
-
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
+
2651
3157
  return agent;
2652
3158
  } finally {
2653
3159
  releaseSpawnQueue();