brl-subagent 2.9.0 → 2.9.2

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,23 @@
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, type Dirent } from 'fs';
4
+ import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync, unlinkSync, type Dirent } from 'fs';
5
5
  import {
6
6
  EMPTY_USAGE,
7
7
  classifyError,
8
8
  classifyTerminalOutcome,
9
9
  isProviderError,
10
+ isTerminalAgentStatusValue,
10
11
  coherentFailureReason,
11
12
  SUBAGENT_ABORTED_MESSAGE,
12
13
  NO_ASSISTANT_OUTPUT_REASON,
14
+ CANCELLED_RETRY_MESSAGE,
13
15
  PROMPT_NEVER_ISSUED_MESSAGE,
14
16
  type BackgroundAgent,
15
17
  type AgentStatus,
16
18
  type GitMode,
17
19
  type RecoveryMode,
20
+ type RetryCause,
18
21
  type SubagentResult,
19
22
  type SubagentRun,
20
23
  type ThinkingLevel,
@@ -46,12 +49,22 @@ import {
46
49
  } from './git';
47
50
  import { clearHeadState, readHeadState, writeHeadState, HEAD_STATE_VERSION } from './headstate';
48
51
  import { effectiveBackgroundBudget } from './validate';
49
- import { currentProcessOwner, classifyOwner, defaultRecoveryDeps } from './recovery';
50
- import { persistRunRecord, listInflightRuns, clearInflightRun, type InflightRun } from './run-registry';
52
+ import { currentProcessOwner, classifyOwner, defaultRecoveryDeps, type AgentRecordFailureReason } from './recovery';
53
+ import {
54
+ persistRunRecord,
55
+ listInflightRuns,
56
+ clearInflightRun,
57
+ markRecordFlipPending,
58
+ type InflightRun,
59
+ type RecordFlipStatus,
60
+ } from './run-registry';
51
61
  import { isTransportRetryable } from './transport-retry';
52
62
  import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
63
+ import { writeFileAtomicSync } from './atomic-write';
53
64
  import { buildEngineeringBarSection } from './engineering-bar';
54
65
  import { prepareRunScratch, markSettled } from './scratch-spawn';
66
+ import { readRequiredGuard, resolveGuardPath, verifyGuardLoaded } from './background-guard';
67
+ import { clearArmedRetry, isRetryCancelRequested } from './retry-armed';
55
68
 
56
69
  const log = createLogger('brl-subagent');
57
70
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
@@ -132,6 +145,51 @@ export function __testResetGitBranchLocks(): void {
132
145
  gitBranchLockOwners.clear();
133
146
  }
134
147
 
148
+ /**
149
+ * Issue #450 (D5): `prompt()`'s rejection value and a synchronous throw are both
150
+ * `unknown` by contract, and a normaliser that is not TOTAL replaces the failure
151
+ * it describes: `String(reason)` throws for a hostile `toPrimitive`/Proxy, and
152
+ * `reason instanceof Error` throws for a Proxy whose `getPrototypeOf` trap
153
+ * throws (spec E18 — pre-fix the caller received `Error: conversion failed`
154
+ * instead of its own throw). Every branch below is total.
155
+ */
156
+ function normalizeThrown(thrown: unknown): Error {
157
+ try {
158
+ return thrown instanceof Error ? thrown : new Error(String(thrown));
159
+ } catch {
160
+ return new Error('unprintable thrown value'); // never a second throw
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Issue #450 (D5): the message of an arbitrary thrown value, total for EVERY
166
+ * input — including an Error-shaped Proxy whose `.message` getter throws.
167
+ */
168
+ function thrownMessage(thrown: unknown): string {
169
+ try {
170
+ return normalizeThrown(thrown).message;
171
+ } catch {
172
+ return 'unprintable thrown value'; // an Error-shaped Proxy whose .message throws
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Issue #450 (D5): a log call on an ERROR path must never replace the error it
178
+ * reports — a throwing sink becomes the caller's error and skips every later
179
+ * step of the cleanup. Both sink faults are now contained at the sink itself:
180
+ * #543 the console mirror (swallowed like a file-write fault), #545 the entry
181
+ * build (`JSON.stringify` on a cyclic or `BigInt` `data` used to throw). This
182
+ * wrapper stays as belt-and-braces, local to the settle/pre-start paths, where
183
+ * a third fault class would otherwise become the caller's error.
184
+ */
185
+ function safeLog(write: () => void): void {
186
+ try {
187
+ write();
188
+ } catch {
189
+ // a throwing sink must not mask the original throw nor skip a later step
190
+ }
191
+ }
192
+
135
193
  // Robust UUID generation with fallback
136
194
  function generateUUID(): string {
137
195
  try {
@@ -418,6 +476,51 @@ function sweepRetainedSessions(currentDir: string): void {
418
476
  }
419
477
  }
420
478
 
479
+ // ---------------------------------------------------------------------------
480
+ // Issue #554: temp residue from the atomic record writer.
481
+ //
482
+ // A SIGKILL cannot run `writeFileAtomicSync`'s cleanup, so `.tmp` siblings
483
+ // accumulate in the agent store (measured: 8 leftovers in 20 kills). The record
484
+ // scans filter `.json`, so they are invisible to every reader — which is exactly
485
+ // why they need their own bounded sweep instead of aging out silently.
486
+ //
487
+ // The 1-hour age floor is the safety property: a temp belonging to a LIVE
488
+ // writer must survive another process's boot, and a writer that is merely slow
489
+ // can hold one for seconds, not an hour. A fresh temp is NEVER removed.
490
+ // ---------------------------------------------------------------------------
491
+
492
+ /** Only temps older than this are sweepable — a live writer's temp is younger. */
493
+ export const AGENT_TEMP_MAX_AGE_MS = 60 * 60 * 1000;
494
+
495
+ /**
496
+ * Remove `*.tmp` residue in the agent store older than one hour. Returns the
497
+ * number removed. Never throws: the store may be missing or unwritable, and a
498
+ * boot must not fail on hygiene.
499
+ */
500
+ export function sweepAgentRecordTemps(): number {
501
+ let names: string[];
502
+ try {
503
+ names = readdirSync(STORAGE_DIR);
504
+ } catch {
505
+ return 0; // store absent/unreadable — nothing to bound
506
+ }
507
+ const now = Date.now();
508
+ let swept = 0;
509
+ for (const name of names) {
510
+ if (!name.endsWith('.tmp')) continue;
511
+ const file = join(STORAGE_DIR, name);
512
+ try {
513
+ if (now - statSync(file).mtimeMs <= AGENT_TEMP_MAX_AGE_MS) continue;
514
+ unlinkSync(file);
515
+ swept += 1;
516
+ } catch {
517
+ // vanished between the readdir and the stat/unlink, or the store is not
518
+ // writable — leave it for the next boot.
519
+ }
520
+ }
521
+ return swept;
522
+ }
523
+
421
524
  /**
422
525
  * Retain `dir` for the #401 resume preamble: brand it with the retention marker
423
526
  * (its mtime is the recency source) and enforce the caps.
@@ -465,14 +568,12 @@ function persistAgent(agent: BackgroundAgent): void {
465
568
  // F24: agent.id may come from a disk-loaded record (loadAgent JSON.parse's
466
569
  // the id field unvalidated). A planted record with a traversal id would
467
570
  // make join() escape STORAGE_DIR — validate BEFORE building the write path.
468
- try {
469
- assertSafeAgentId(agent.id);
470
- } catch {
571
+ const filePath = agentRecordPath(agent.id);
572
+ if (!filePath) {
471
573
  log.error(`Refusing to persist agent with invalid id: ${agent.id}`);
472
574
  return;
473
575
  }
474
576
  ensureStorageDir();
475
- const filePath = join(STORAGE_DIR, `${agent.id}.json`);
476
577
  // Strip live/non-serializable fields before stringify — `_sessionRef` holds the
477
578
  // ENTIRE live pi session graph (1.4MB+ for an empty session, and uninitialized
478
579
  // getters like Theme can make JSON.stringify throw). `_sessionFile` (U2) is the
@@ -480,11 +581,16 @@ function persistAgent(agent: BackgroundAgent): void {
480
581
  // persisted record field (D4).
481
582
  const { _sessionRef, _sessionFile, ...persistable } = agent;
482
583
  try {
584
+ // Issue #554: atomic (temp+rename) so a SIGKILL between the truncate and the
585
+ // write cannot leave a torn record. `mode` is applied on the temp and
586
+ // survives the rename (the inode changes; the record is still `0o600`).
483
587
  // F6 (issue #29): records contain task, error, result.messages (full
484
588
  // conversation) and finalOutput — write owner-only (0o600) so other local
485
589
  // users cannot read subagent tasks/output. mode applies on file CREATE;
486
- // pre-existing files keep their old mode (not retroactive).
487
- writeFileSync(filePath, JSON.stringify(persistable, null, 2), { encoding: 'utf-8', mode: 0o600 });
590
+ // pre-existing files keep their old mode (not retroactive) — and a
591
+ // read-only record no longer blocks the write: a writable DIRECTORY does
592
+ // (issue #554's accepted permission-contract change).
593
+ writeFileAtomicSync(filePath, JSON.stringify(persistable, null, 2));
488
594
  } catch (err) {
489
595
  // Log but never throw — persistence must not break execution
490
596
  log.error(`Failed to persist agent ${agent.id}`, { error: err instanceof Error ? err.message : String(err) });
@@ -492,16 +598,90 @@ function persistAgent(agent: BackgroundAgent): void {
492
598
  }
493
599
 
494
600
  /**
495
- * Load agent record from disk
601
+ * The agent store's record path for `id`: `<STORAGE_DIR>/<id>.json`.
602
+ *
603
+ * F24: ids reach the store from disk and from LLM tool params, and `join` does
604
+ * not sanitize `../` or absolute segments — validate BEFORE building the write
605
+ * path. `null` means "no record is addressable for this id" (the writer could
606
+ * never have created one), which every reader treats as absent.
607
+ *
608
+ * Issue #546 (major 2): the ONE path helper. `persistAgent`, `loadAgent`, the
609
+ * tri-state reader and `flipAgentRecord` all build the path here, so the
610
+ * absence test and the write target cannot drift apart.
496
611
  */
497
- function loadAgent(id: string): BackgroundAgent | null {
498
- const filePath = join(STORAGE_DIR, `${id}.json`);
499
- if (!existsSync(filePath)) return null;
612
+ function agentRecordPath(id: string): string | null {
500
613
  try {
501
- return JSON.parse(readFileSync(filePath, 'utf-8'));
614
+ assertSafeAgentId(id);
502
615
  } catch {
503
616
  return null;
504
617
  }
618
+ return join(STORAGE_DIR, `${id}.json`);
619
+ }
620
+
621
+ /** The tri-state record read plus the #554 named failure kind. */
622
+ export interface AgentRecordRead {
623
+ record: BackgroundAgent | null;
624
+ exists: boolean;
625
+ /** `"corrupt"` when the bytes are not JSON; `"unreadable"` when stat/read failed. */
626
+ reason?: AgentRecordFailureReason;
627
+ }
628
+
629
+ /**
630
+ * Issue #546 (major 2): the disk-only, TRI-STATE read of one agent record.
631
+ *
632
+ * `loadAgent` collapses "there is no record" and "there is a record I cannot
633
+ * parse" into `null`, and the flip must not: the first means nothing durable can
634
+ * go stale (retire the marker), the second means we know nothing (keep it).
635
+ * `exists` is the stat of the validated path, so a chmod-000 or corrupt file
636
+ * reports `{ record: null, exists: true }`.
637
+ *
638
+ * Issue #554: the two failure kinds are NAMED on the result (`reason`) instead
639
+ * of being collapsed — `"corrupt"` (the file read but JSON.parse rejected it:
640
+ * repair the file) vs `"unreadable"` (stat/read failed: fix permissions or the
641
+ * filesystem). The flip's decisions are unchanged; only the boot ledger can now
642
+ * count the corrupt subset by name.
643
+ */
644
+ export function readAgentRecordFromDisk(id: string): AgentRecordRead {
645
+ const filePath = agentRecordPath(id);
646
+ if (!filePath) return { record: null, exists: false };
647
+ try {
648
+ statSync(filePath);
649
+ } catch (err) {
650
+ // ONLY `ENOENT` is a CONFIRMED absence. `existsSync` also answers false when a
651
+ // parent directory cannot be traversed (EACCES): reporting that as absence
652
+ // lets the flip retire a marker over a record that is still `running`
653
+ // (r2 major 1). An uncertain stat is treated like an unreadable record —
654
+ // `exists: true`, `record: null` — so the marker is kept and counted failed.
655
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { record: null, exists: false };
656
+ log.warn(`Could not stat agent record ${id} — treating it as unreadable`, {
657
+ error: err instanceof Error ? err.message : String(err),
658
+ });
659
+ return { record: null, exists: true, reason: 'unreadable' };
660
+ }
661
+ let text: string;
662
+ try {
663
+ text = readFileSync(filePath, 'utf-8');
664
+ } catch (err) {
665
+ log.warn(`Could not read agent record ${id} — treating it as unreadable`, {
666
+ error: err instanceof Error ? err.message : String(err),
667
+ });
668
+ return { record: null, exists: true, reason: 'unreadable' };
669
+ }
670
+ try {
671
+ return { record: JSON.parse(text), exists: true };
672
+ } catch {
673
+ // The bytes are there and they are not JSON (a torn write before #554, or a
674
+ // zero-byte file). Never repaired or retired here — the count names them.
675
+ return { record: null, exists: true, reason: 'corrupt' };
676
+ }
677
+ }
678
+
679
+ /**
680
+ * Load agent record from disk. `null` on absent OR unreadable — use
681
+ * `readAgentRecordFromDisk` wherever the difference matters (issue #546).
682
+ */
683
+ function loadAgent(id: string): BackgroundAgent | null {
684
+ return readAgentRecordFromDisk(id).record;
505
685
  }
506
686
 
507
687
  /**
@@ -603,6 +783,9 @@ export const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
603
783
  'attempt',
604
784
  'status',
605
785
  'startedAt',
786
+ // Issue #616: the retry cause. Read by the shallow scanner so a dispatch-scoped
787
+ // stop can scope itself to `transport` without a full record parse.
788
+ 'retryCause',
606
789
  ]);
607
790
 
608
791
  const AGENT_STATUSES: ReadonlySet<string> = new Set([
@@ -623,6 +806,12 @@ export interface RetryRecordIdentity {
623
806
  status: AgentStatus;
624
807
  /** Epoch milliseconds (agent records store ms; registry ISO is normalised). */
625
808
  startedAt: number;
809
+ /**
810
+ * Issue #616: why this attempt exists, when the record says. ABSENT means
811
+ * UNKNOWN — neither cause is assumed, and unknown is never the stop-scoped
812
+ * `transport`.
813
+ */
814
+ retryCause?: RetryCause;
626
815
  }
627
816
 
628
817
  export type AgentIdResolution =
@@ -640,6 +829,13 @@ export interface RetryLineage {
640
829
  latest: RetryRecordIdentity | null;
641
830
  /** Registry entries that name the id itself or a member of its family. */
642
831
  inflight: InflightRun[];
832
+ /**
833
+ * Issue #616 (Q7): whether the scan was TRUNCATED, which is what a caller
834
+ * needs to avoid printing a universal claim over a partial read. `capped` is
835
+ * the `RETRY_SCAN_CAP` cut; a record older than `windowDays` is the caller's
836
+ * own check (it knows the requested record's `startedAt`).
837
+ */
838
+ bounds: { capped: boolean; windowDays: number };
643
839
  }
644
840
 
645
841
  function isSafeAgentId(id: string): boolean {
@@ -651,8 +847,16 @@ function isSafeAgentId(id: string): boolean {
651
847
  }
652
848
  }
653
849
 
850
+ /**
851
+ * Issue #546: what a record flip actually did — the value the boot ledger counts
852
+ * (see `flipAgentRecord`). `false` is the fail-closed "not settled" outcome.
853
+ */
854
+ export type AgentFlipOutcome = 'repaired' | 'retired' | false;
855
+
654
856
  export function isTerminalAgentStatus(status: AgentStatus): boolean {
655
- return status === 'completed' || status === 'failed' || status === 'stopped';
857
+ // Issue #616: the vocabulary lives in `types.ts` (one definition, two readers —
858
+ // this export and the stop contract's post-stop verification).
859
+ return isTerminalAgentStatusValue(status);
656
860
  }
657
861
 
658
862
  function isAgentStatus(value: unknown): value is AgentStatus {
@@ -935,6 +1139,7 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
935
1139
 
936
1140
  const dispatchId = fields.get('dispatchId');
937
1141
  const resumeOf = fields.get('resumeOf');
1142
+ const retryCause = fields.get('retryCause');
938
1143
  return {
939
1144
  id,
940
1145
  status,
@@ -942,6 +1147,8 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
942
1147
  attempt,
943
1148
  ...(typeof dispatchId === 'string' ? { dispatchId } : {}),
944
1149
  ...(typeof resumeOf === 'string' ? { resumeOf } : {}),
1150
+ // Issue #616: an unrecognized cause is ABSENT (unknown), never coerced.
1151
+ ...(retryCause === 'transport' || retryCause === 'manual' ? { retryCause } : {}),
945
1152
  };
946
1153
  }
947
1154
 
@@ -949,14 +1156,18 @@ function readAgentIdentity(file: string): RetryRecordIdentity | null {
949
1156
  * The bounded store read: stat every record (cheap), keep the ones inside the
950
1157
  * mtime window, sort newest-first, cap at `RETRY_SCAN_CAP`, then read only the
951
1158
  * surviving files' identity fields. Corrupt/unsafe records are skipped.
1159
+ *
1160
+ * `capped` reports whether the CAP cut anything (issue #616, Q7): a caller that
1161
+ * makes a universal claim over the answer must be able to say the scan was
1162
+ * truncated.
952
1163
  */
953
- function readRecentAgentIdentities(): RetryRecordIdentity[] {
1164
+ function readRecentAgentIdentities(): { records: RetryRecordIdentity[]; capped: boolean } {
954
1165
  let files: string[];
955
1166
  try {
956
- if (!existsSync(STORAGE_DIR)) return [];
1167
+ if (!existsSync(STORAGE_DIR)) return { records: [], capped: false };
957
1168
  files = readdirSync(STORAGE_DIR);
958
1169
  } catch {
959
- return [];
1170
+ return { records: [], capped: false };
960
1171
  }
961
1172
 
962
1173
  const cutoff = Date.now() - RETRY_SCAN_WINDOW_MS;
@@ -975,12 +1186,13 @@ function readRecentAgentIdentities(): RetryRecordIdentity[] {
975
1186
  }
976
1187
 
977
1188
  recent.sort((a, b) => b.mtime - a.mtime);
1189
+ const capped = recent.length > RETRY_SCAN_CAP;
978
1190
  const records: RetryRecordIdentity[] = [];
979
1191
  for (const entry of recent.slice(0, RETRY_SCAN_CAP)) {
980
1192
  const record = readAgentIdentity(entry.file);
981
1193
  if (record) records.push(record);
982
1194
  }
983
- return records;
1195
+ return { records, capped };
984
1196
  }
985
1197
 
986
1198
  function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
@@ -993,6 +1205,7 @@ function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
993
1205
  attempt: agent.attempt ?? 1,
994
1206
  ...(agent.dispatchId ? { dispatchId: agent.dispatchId } : {}),
995
1207
  ...(agent.resumeOf ? { resumeOf: agent.resumeOf } : {}),
1208
+ ...(agent.retryCause ? { retryCause: agent.retryCause } : {}),
996
1209
  };
997
1210
  }
998
1211
 
@@ -1001,13 +1214,35 @@ function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
1001
1214
  if (startedAt === null) return null;
1002
1215
  return {
1003
1216
  id: run.id,
1217
+ // The registry has no status field: an entry being present IS the claim that
1218
+ // the run is in flight. Review 624 (F4): that claim is the WEAKEST one in the
1219
+ // family and is only used when no persisted record exists — see the fold in
1220
+ // `findRetryLineage`.
1004
1221
  status: 'running',
1005
1222
  startedAt,
1006
1223
  attempt: run.attempt ?? 1,
1007
1224
  ...(run.dispatchId ? { dispatchId: run.dispatchId } : {}),
1225
+ ...(run.retryCause ? { retryCause: run.retryCause } : {}),
1008
1226
  };
1009
1227
  }
1010
1228
 
1229
+ /**
1230
+ * The persisted identity for `id`, read OUTSIDE the shallow scan window.
1231
+ *
1232
+ * Review 624 (F4): `readRecentAgentIdentities` is bounded (7-day mtime window,
1233
+ * 200-record cap), so a record can be absent from it while its registry entry
1234
+ * survives — the crash-residue shape. One targeted read per registry entry (a
1235
+ * handful at most, never a scan) makes "the persisted record wins" independent
1236
+ * of that window. A record whose embedded id disagrees with its file name is not
1237
+ * this run's record and is ignored.
1238
+ */
1239
+ function persistedIdentityFor(id: string): RetryRecordIdentity | null {
1240
+ const file = agentRecordPath(id);
1241
+ if (!file) return null;
1242
+ const persisted = readAgentIdentity(file);
1243
+ return persisted && persisted.id === id ? persisted : null;
1244
+ }
1245
+
1011
1246
  /**
1012
1247
  * Find the logical dispatch family for `id`.
1013
1248
  *
@@ -1017,20 +1252,34 @@ function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
1017
1252
  * in so an in-flight retry is visible without a store record.
1018
1253
  */
1019
1254
  export function findRetryLineage(id: string, source?: BackgroundAgent | null): RetryLineage {
1020
- const empty: RetryLineage = { id, family: [], found: null, latest: null, inflight: [] };
1255
+ const empty: RetryLineage = {
1256
+ id,
1257
+ family: [],
1258
+ found: null,
1259
+ latest: null,
1260
+ inflight: [],
1261
+ bounds: { capped: false, windowDays: RETRY_SCAN_WINDOW_DAYS },
1262
+ };
1021
1263
  if (!isSafeAgentId(id)) return empty;
1022
1264
 
1265
+ const scan = readRecentAgentIdentities();
1023
1266
  const byId = new Map<string, RetryRecordIdentity>();
1024
- for (const record of readRecentAgentIdentities()) byId.set(record.id, record);
1267
+ for (const record of scan.records) byId.set(record.id, record);
1025
1268
 
1026
1269
  const sourceIdentity = source && source.id === id ? identityFromAgent(source) : null;
1027
1270
  if (sourceIdentity) byId.set(id, sourceIdentity);
1028
1271
 
1029
1272
  const registry = safeListInflightRuns();
1030
1273
  for (const run of registry) {
1031
- const identity = identityFromRegistry(run);
1032
- // A persisted record is authoritative over the registry's "running" view.
1033
- if (identity && !byId.has(identity.id)) byId.set(identity.id, identity);
1274
+ if (byId.has(run.id)) continue;
1275
+ // Review 624 (F4): a PERSISTED record is authoritative over the registry's
1276
+ // hardcoded `running` — even when the record fell outside the shallow scan
1277
+ // (its 7-day window or its 200-record cap). Without this, crash residue (a
1278
+ // registry entry outliving a terminal record) planned the terminal attempt as
1279
+ // live, `stopAgent` returned it unchanged, and the report printed
1280
+ // "Stopped agent …" for an attempt that was already dead.
1281
+ const identity = persistedIdentityFor(run.id) ?? identityFromRegistry(run);
1282
+ if (identity) byId.set(identity.id, identity);
1034
1283
  }
1035
1284
 
1036
1285
  const all = [...byId.values()];
@@ -1056,7 +1305,14 @@ export function findRetryLineage(id: string, source?: BackgroundAgent | null): R
1056
1305
  (run) => run.id === id || (familyDispatch !== undefined && run.dispatchId === familyDispatch),
1057
1306
  );
1058
1307
 
1059
- return { id, family, found, latest, inflight };
1308
+ return {
1309
+ id,
1310
+ family,
1311
+ found,
1312
+ latest,
1313
+ inflight,
1314
+ bounds: { capped: scan.capped, windowDays: RETRY_SCAN_WINDOW_DAYS },
1315
+ };
1060
1316
  }
1061
1317
 
1062
1318
  /**
@@ -1075,6 +1331,32 @@ export function markAgentInterrupted(id: string, interruptedAt: string): Backgro
1075
1331
  return agent;
1076
1332
  }
1077
1333
 
1334
+ /**
1335
+ * Issue #574: state the run's KIND on the record, so the status flip that
1336
+ * follows persists it. A deadline and a user stop are both `status:"stopped"`;
1337
+ * only the category tells the two frictions apart.
1338
+ *
1339
+ * WHY BEFORE THE FLIP AND NOT AFTER: `updateAgentStatus` persists the record
1340
+ * itself, so a stamp written afterwards is absent from the bytes an observer
1341
+ * reads at the flip — and never lands at all if the settle that would write it
1342
+ * never arrives (a real stop is exactly that case: `stopAgent` persists
1343
+ * `stopped` before any abort settles).
1344
+ *
1345
+ * The `agents.set` is load-bearing: `getAgent` is memory-first, so a record that
1346
+ * exists only on disk would be re-loaded WITHOUT this stamp between the call and
1347
+ * its persist. Re-inserting the stamped object makes the flip write what this
1348
+ * function just said.
1349
+ */
1350
+ function stampAgentKind(
1351
+ agent: BackgroundAgent,
1352
+ errorCategory: ErrorCategory,
1353
+ stopReason: string,
1354
+ ): void {
1355
+ agent.errorCategory = errorCategory;
1356
+ agent.stopReason = stopReason;
1357
+ agents.set(agent.id, agent);
1358
+ }
1359
+
1078
1360
  /**
1079
1361
  * Update agent status
1080
1362
  */
@@ -1106,6 +1388,134 @@ export function updateAgentStatus(id: string, status: AgentStatus, error?: strin
1106
1388
  return agent;
1107
1389
  }
1108
1390
 
1391
+ /**
1392
+ * Issue #546: the agent-record step, in its TWO contracts — ONE shared disk
1393
+ * verdict, two different assumptions BEFORE the write.
1394
+ *
1395
+ * `settleLiveAgentRecord` is the LIVE pre-start writer (#542's pin). It runs in
1396
+ * the process that owns the in-memory map, so the MEMORY record must become
1397
+ * terminal in EVERY fault — an absent record, an unreadable record, a persist
1398
+ * that `persistAgent` swallows. A `running` memory row after a failed pre-start
1399
+ * is a lie this same process is still asked about (`get_subagent_result`,
1400
+ * `get_agent_status`), and it is exactly what #542 fixed: r3 reintroduced it by
1401
+ * making the live writer share the boot's disk-only decision.
1402
+ *
1403
+ * `flipAgentRecord` is the boot REPLAY (`recoverInflightRuns`'s
1404
+ * `applyRecordFlip`). A fresh process has no memory to trust, so it decides from
1405
+ * the DISK alone: absent ⇒ retire; present-but-unreadable ⇒ keep the marker and
1406
+ * count a failure; `running` + a provably dead owner ⇒ flip (the flip itself
1407
+ * loads the record into memory); already terminal ⇒ retire with no write.
1408
+ *
1409
+ * RETIREMENT IS THE SAME RULE ON BOTH SIDES: retire only when the disk is
1410
+ * terminal or PROVABLY absent (`ENOENT`); keep the marker when the disk is
1411
+ * `running` or unreadable. That is `terminalVerdictAfterWrite`.
1412
+ *
1413
+ * TOTAL: neither function throws. The outcome vocabulary:
1414
+ *
1415
+ * - `'retired'` — nothing durable is left to repair: no record is stored, or
1416
+ * (replay only) it was already terminal, so no `completedAt` re-stamp and no
1417
+ * second `subagent:failed`. The marker may be retired;
1418
+ * - `'repaired'` — the record was written and the store says terminal;
1419
+ * - `false` — the end state is UNCERTAIN: present-but-unreadable/corrupt,
1420
+ * a write that did not land, or a live id that is in neither the map nor the
1421
+ * store. The caller keeps the marker (fail-closed).
1422
+ */
1423
+ export function flipAgentRecord(id: string, status: RecordFlipStatus, error?: string): AgentFlipOutcome {
1424
+ // PRE-FLIP READ: the DISK, not the in-memory map (major 2 + 3). `getAgent` is
1425
+ // memory-first, and that map is module state that can hold a record another
1426
+ // process already flipped — deciding on it would re-stamp `completedAt` and
1427
+ // re-emit `subagent:failed` for a run that is already settled. Reading the
1428
+ // store first makes a boot that begins after another finished INERT, makes a
1429
+ // same-process retry attempt the write again once the store is writable, and
1430
+ // separates confirmed absence from present-but-unreadable.
1431
+ const before = readAgentRecordFromDisk(id);
1432
+ if (!before.exists) return 'retired'; // confirmed absence (or unsafe id)
1433
+ if (!before.record) {
1434
+ // Present but unreadable/corrupt: we know nothing, so we may not retire the
1435
+ // only marker that can repair it.
1436
+ log.warn(`Could not read the agent record for ${id} — keeping the record-flip marker`, {});
1437
+ return false;
1438
+ }
1439
+ if (isTerminalAgentStatus(before.record.status)) return 'retired'; // replay is inert
1440
+ let touched: BackgroundAgent | null = null;
1441
+ try {
1442
+ touched = updateAgentStatus(id, status, error);
1443
+ } catch (err) {
1444
+ log.warn(`Failed to flip the terminal record for ${id}`, {
1445
+ error: err instanceof Error ? err.message : String(err),
1446
+ });
1447
+ } finally {
1448
+ // persistAgent strips the ref from the persisted copy anyway, so this is
1449
+ // memory-only — and it must run even when the flip's own try failed.
1450
+ if (touched) touched._sessionRef = undefined;
1451
+ }
1452
+ return terminalVerdictAfterWrite(id);
1453
+ }
1454
+
1455
+ /**
1456
+ * The DISK verdict after a terminal write, shared by both contracts above:
1457
+ *
1458
+ * - `'repaired'` — the store says the record is terminal;
1459
+ * - `'retired'` — no record is stored (confirmed `ENOENT`, or the id is not
1460
+ * addressable): nothing durable can go stale, so the marker's only purpose
1461
+ * is vacuous;
1462
+ * - `false` — the store cannot tell: present-but-unreadable/corrupt, or
1463
+ * the write was swallowed and the record is STILL `running`. `false` is the
1464
+ * value that keeps the caller's marker for the next boot.
1465
+ *
1466
+ * `persistAgent` swallows write errors (V8), so a throw-free write is not a
1467
+ * landed write: the verdict is read from the STORE, never inferred from a
1468
+ * return value.
1469
+ */
1470
+ function terminalVerdictAfterWrite(id: string): AgentFlipOutcome {
1471
+ const after = readAgentRecordFromDisk(id);
1472
+ if (!after.exists) return 'retired'; // vanished/writable: nothing durable left
1473
+ if (!after.record) {
1474
+ log.warn(`Could not re-read the agent record for ${id} after the flip`, {});
1475
+ return false;
1476
+ }
1477
+ return isTerminalAgentStatus(after.record.status) ? 'repaired' : false;
1478
+ }
1479
+
1480
+ /**
1481
+ * Issue #546 r4 (the #542 pin): the LIVE writer's record step — MEMORY first,
1482
+ * disk verdict second. TOTAL: it never throws.
1483
+ *
1484
+ * The memory write is NOT conditional on the disk. Whatever the store says —
1485
+ * absent, unreadable, still `running` after a swallowed persist — this process's
1486
+ * record must read terminal the moment the pre-start path returns. Only the
1487
+ * RETIREMENT is conditional, and it is conditional on the disk:
1488
+ *
1489
+ * disk absent → `'retired'` (nothing durable to repair: retire the marker)
1490
+ * disk terminal → `'repaired'` (retire the marker)
1491
+ * disk `running` → `false` (a persist was swallowed: KEEP the marker)
1492
+ * disk unreadable → `false` (we cannot tell: KEEP the marker)
1493
+ *
1494
+ * `updateAgentStatus` returns `null` only when the id is in neither the map nor
1495
+ * the store — impossible for an id this process just registered, and a `false`
1496
+ * (keep the marker) if it ever happens, because then nothing is pinned.
1497
+ *
1498
+ * `_sessionRef` is NOT released here: the caller's release is a plain statement
1499
+ * outside every `try` (it cannot throw and must always run) and `persistAgent`
1500
+ * strips the ref from the persisted copy anyway.
1501
+ */
1502
+ function settleLiveAgentRecord(id: string, status: RecordFlipStatus, error?: string): AgentFlipOutcome {
1503
+ try {
1504
+ if (!updateAgentStatus(id, status, error)) {
1505
+ log.warn(`Could not settle the live agent record for ${id} — it is in neither the map nor the store`, {});
1506
+ return false;
1507
+ }
1508
+ } catch (err) {
1509
+ // Contained: `updateAgentStatus` mutates the map BEFORE it persists and
1510
+ // emits, so the memory record is terminal even when this throws. The disk
1511
+ // verdict below still decides whether the marker may be retired.
1512
+ log.warn(`Failed to flip the terminal record for ${id}`, {
1513
+ error: err instanceof Error ? err.message : String(err),
1514
+ });
1515
+ }
1516
+ return terminalVerdictAfterWrite(id);
1517
+ }
1518
+
1109
1519
  /**
1110
1520
  * Issue #179 (D4): when a run ends in a failure, the prose extracted by
1111
1521
  * extractFinalOutput may come from an EARLIER turn — the failing turn carries
@@ -1193,6 +1603,11 @@ export async function stopAgent(id: string): Promise<BackgroundAgent | null> {
1193
1603
  return agent;
1194
1604
  }
1195
1605
 
1606
+ // Issue #574: the KIND comes before the flip that persists it — this is the
1607
+ // earliest observable point of a user stop (the abort settles later, if at
1608
+ // all).
1609
+ stampAgentKind(agent, 'aborted', 'aborted');
1610
+
1196
1611
  // Mark stopped BEFORE aborting so the spawnBackgroundSession .then handler
1197
1612
  // (which fires after the run settles) keeps the stopped state.
1198
1613
  updateAgentStatus(id, 'stopped');
@@ -1341,6 +1756,11 @@ export async function spawnBackgroundSession(
1341
1756
  dispatchId?: string;
1342
1757
  resumeOf?: string;
1343
1758
  attempt?: number;
1759
+ /** Issue #616: why this attempt exists — `transport` for the automatic
1760
+ * background retry, `manual` for a caller-driven `retryRunId` retry. Absent
1761
+ * on a first dispatch, and then it reads as UNKNOWN (never `transport`).
1762
+ * Recorded on the agent record, the run entry and the registry entry. */
1763
+ retryCause?: RetryCause;
1344
1764
  /** Option B U3 (D4): recovery posture at dispatch — snapshotted onto the
1345
1765
  * agent record + run entry so the boot notice reads the posture the run
1346
1766
  * was actually dispatched under. Absent reads as "offer". */
@@ -1369,26 +1789,23 @@ export async function spawnBackgroundSession(
1369
1789
 
1370
1790
  try {
1371
1791
  const id = generateUUID();
1372
- // Issue #511 (U2): the scratch seam for the BACKGROUND surface. This function
1373
- // is the single place a background agent record and run entry are created
1374
- // (single, fan-out and the transport retry all pass through it), so the run's
1375
- // directory is resolved and created HERE — before the SDK is asked for a
1376
- // session, and therefore before `session.prompt()` can start the child.
1792
+ // Issue #620: the conductor's required background guard is RESOLVED AND
1793
+ // CONTAINED here — before the SDK is imported, before the loader exists, and
1794
+ // therefore before any agent record or run entry can exist. The resolution
1795
+ // root is `ctx.cwd` (the CONDUCTOR's project), never `params.cwd` — the child's
1796
+ // directory is model-chosen, so a guard resolved against it would be a guard
1797
+ // the model chooses. A missing, escaping or malformed guard throws here and
1798
+ // the pipeline's existing catch renders it as an ordinary spawn failure.
1377
1799
  //
1378
- // A refusal is PRE-SPAWN and NAMED: it throws before any record exists, and
1379
- // both pipeline callers translate a throw from this function into their
1380
- // ordinary "Failed to spawn background agent: …" result — the same shape as
1381
- // every other spawn failure.
1382
- //
1383
- // NOTE, stated rather than implied: a background run is an IN-PROCESS SDK
1384
- // session, so there is no child environment to carry `BRL_SCRATCH` (the SDK
1385
- // composes the shell env from `process.env` at command time, which a per-run
1386
- // value cannot vary without race). The directory and the record's
1387
- // `scratchDir` are this surface's whole carrier.
1388
- const scratch = prepareRunScratch(id, { log });
1389
- if (!scratch.ok) {
1390
- throw new Error(`scratch root unavailable (${scratch.code}): ${scratch.message}`);
1391
- }
1800
+ // ORDER, stated because it is load-bearing twice: resolve → reload → verify →
1801
+ // scratch → createAgentSession. The scratch directory is created AFTER the
1802
+ // guard is verified (PR #627 review, F3), so a refused spawn — missing, broken
1803
+ // or handler-less guard — leaves NO `runs/<uuid>` directory behind, matching the
1804
+ // "no agent record, no run entry" promise both refusals make. Nothing between
1805
+ // the resolver and the verifier needs the directory: the loader and the session
1806
+ // manager are given `effectiveCwd`, not the scratch path.
1807
+ const guardName = readRequiredGuard(ctx.cwd);
1808
+ const guardPath = guardName === null ? null : resolveGuardPath(ctx.cwd, guardName);
1392
1809
  const effectiveCwd = params.cwd ?? ctx.cwd;
1393
1810
  // Dynamic import — static import fails under concurrent jiti loads
1394
1811
  const { getAgentDir, createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader } = await import('@earendil-works/pi-coding-agent');
@@ -1482,6 +1899,12 @@ export async function spawnBackgroundSession(
1482
1899
  // deliberate security choice: background sessions have no trust prompt, so
1483
1900
  // nothing is imported from anywhere — the prompt is fully specified by the
1484
1901
  // caller. Users needing skills/extensions should use foreground delegation.
1902
+ //
1903
+ // Issue #620 is the ONE exception, and it is not a discovery path: the
1904
+ // conductor's project NAMED a guard in its own manifest, `resolveGuardPath`
1905
+ // turned that name into one absolute, contained, realpathed file, and no key
1906
+ // at all is added otherwise. F5: a relative entry would resolve against the
1907
+ // loader's cwd — the CHILD's — so the entry is absolute by construction.
1485
1908
  const loader = new DefaultResourceLoader({
1486
1909
  cwd: effectiveCwd,
1487
1910
  agentDir,
@@ -1489,8 +1912,44 @@ export async function spawnBackgroundSession(
1489
1912
  ...(sections.length ? { appendSystemPrompt: sections } : {}),
1490
1913
  noExtensions: true,
1491
1914
  noSkills: true,
1915
+ ...(guardPath === null ? {} : { additionalExtensionPaths: [guardPath] }),
1492
1916
  });
1493
1917
  await loader.reload();
1918
+ // Issue #620: loading is not registration (F9: `reload()` never throws). The
1919
+ // named guard is verified BEFORE createAgentSession, so an absent, errored or
1920
+ // handler-less guard refuses the spawn rather than producing a run that looks
1921
+ // guarded and is not. A refusal here throws before any agent record.
1922
+ if (guardPath !== null) {
1923
+ verifyGuardLoaded(loader, guardPath);
1924
+ log.info("Background guard verified", {
1925
+ agentId: id,
1926
+ guard: guardName,
1927
+ path: guardPath,
1928
+ handlers: ["tool_call", "before_agent_start"],
1929
+ });
1930
+ }
1931
+ // Issue #511 (U2): the scratch seam for the BACKGROUND surface, reached only
1932
+ // once the guard is verified (F3 of the PR #627 review: a refused spawn must not
1933
+ // leave an orphan run directory). This function is the single place a background
1934
+ // agent record and run entry are created (single, fan-out and the transport retry
1935
+ // all pass through it), so the run's directory is resolved and created HERE —
1936
+ // before the SDK is asked for a session, and therefore before `session.prompt()`
1937
+ // can start the child.
1938
+ //
1939
+ // A refusal is PRE-SPAWN and NAMED: it throws before any record exists, and
1940
+ // both pipeline callers translate a throw from this function into their
1941
+ // ordinary "Failed to spawn background agent: …" result — the same shape as
1942
+ // every other spawn failure.
1943
+ //
1944
+ // NOTE, stated rather than implied: a background run is an IN-PROCESS SDK
1945
+ // session, so there is no child environment to carry `BRL_SCRATCH` (the SDK
1946
+ // composes the shell env from `process.env` at command time, which a per-run
1947
+ // value cannot vary without race). The directory and the record's
1948
+ // `scratchDir` are this surface's whole carrier.
1949
+ const scratch = prepareRunScratch(id, { log });
1950
+ if (!scratch.ok) {
1951
+ throw new Error(`scratch root unavailable (${scratch.code}): ${scratch.message}`);
1952
+ }
1494
1953
  const resourceLoader: InstanceType<typeof DefaultResourceLoader> = loader;
1495
1954
 
1496
1955
  // Create the session — honor the resolved tool restrictions so the
@@ -1565,6 +2024,10 @@ export async function spawnBackgroundSession(
1565
2024
  dispatchId,
1566
2025
  resumeOf: params.resumeOf,
1567
2026
  attempt,
2027
+ // Issue #616: the retry's cause, persisted on the record so a
2028
+ // dispatch-scoped stop can scope itself to automatic transport retries and
2029
+ // never to a manual one. Absent on a first dispatch (⇒ unknown).
2030
+ retryCause: params.retryCause,
1568
2031
  owner,
1569
2032
  // Option B U3 (D4): per-run recovery posture snapshot. Additive — absent
1570
2033
  // reads as "offer" via `runRecoveryPosture`/the notice collector.
@@ -1599,6 +2062,7 @@ export async function spawnBackgroundSession(
1599
2062
  dispatchId,
1600
2063
  resumeOf: params.resumeOf,
1601
2064
  attempt,
2065
+ retryCause: params.retryCause,
1602
2066
  owner,
1603
2067
  recoveryPosture: params.recoveryPosture,
1604
2068
  // Issue #511 (U2): the run's scratch directory (`<root>/runs/<id>`, 0700),
@@ -1679,7 +2143,18 @@ export async function spawnBackgroundSession(
1679
2143
  const finalizeRunEntry = (
1680
2144
  status: "done" | "failed",
1681
2145
  error?: string,
1682
- terminal?: { stopReason?: string; errorCategory?: ErrorCategory; prune?: boolean },
2146
+ terminal?: {
2147
+ stopReason?: string;
2148
+ errorCategory?: ErrorCategory;
2149
+ prune?: boolean;
2150
+ /**
2151
+ * Issue #546: do NOT retire the registry entry here — the caller owns the
2152
+ * retirement and performs it only once the record flip is durable. Only the
2153
+ * pre-start terminal path passes this; every other writer keeps
2154
+ * retire-then-append.
2155
+ */
2156
+ deferRetire?: boolean;
2157
+ },
1683
2158
  ): SubagentRun | undefined => {
1684
2159
  // Issue #511 (U2): settling includes the scratch directory's `.done` marker.
1685
2160
  // This is the SINGLE terminal choke point for a background run (git-setup
@@ -1793,13 +2268,20 @@ export async function spawnBackgroundSession(
1793
2268
  ? { ...(run.originalParams ?? {}), errorCategory }
1794
2269
  : run.originalParams,
1795
2270
  };
1796
- persistRunRecord(pi, entry);
2271
+ persistRunRecord(pi, entry, undefined, { deferRetire: terminal?.deferRetire });
1797
2272
  // Issue #453: set only AFTER the append resolved. A throwing write therefore
1798
2273
  // leaves `entryWritten === false`, so a later settle still classifies the run
1799
2274
  // instead of amending a record that was never written (mutant M3).
1800
2275
  entryWritten = true;
1801
2276
  // Issue #179 (D6): the explicit settle line — the log's job is to record the
1802
2277
  // CLASSIFIED OUTCOME, which cwd alone can never convey.
2278
+ // Issue #556: the row carries the LINEAGE too. Without it the only way to
2279
+ // group a retry with what it resumed was spawn adjacency in the log, which
2280
+ // reads wrong across concurrent runs — the durable records had the answer
2281
+ // and the log did not. `attempt` defaults to the documented 1 (a record
2282
+ // written before the field existed IS a first attempt); `resumeOf` is
2283
+ // OMITTED, never null: an absent key is what "this run resumed nothing"
2284
+ // looks like, and a null would read as a lookup that failed.
1803
2285
  log.info("Background run settled", {
1804
2286
  agentId: id,
1805
2287
  status,
@@ -1808,6 +2290,8 @@ export async function spawnBackgroundSession(
1808
2290
  tokensOut: usage.output,
1809
2291
  errorCategory,
1810
2292
  error: error ?? null,
2293
+ attempt: entry.attempt ?? 1,
2294
+ ...(entry.resumeOf !== undefined ? { resumeOf: entry.resumeOf } : {}),
1811
2295
  });
1812
2296
  return entry;
1813
2297
  };
@@ -1856,7 +2340,7 @@ export async function spawnBackgroundSession(
1856
2340
  }
1857
2341
  } catch (err) {
1858
2342
  log.warn(`getCurrentBranch failed during cleanup for background agent ${id}`, {
1859
- error: (err as Error).message,
2343
+ error: thrownMessage(err),
1860
2344
  });
1861
2345
  // Issue #466: KEEP the record — we cannot tell where the tree is, which
1862
2346
  // is exactly the crash-equivalent state the boot's retry is for.
@@ -1890,7 +2374,7 @@ export async function spawnBackgroundSession(
1890
2374
  : diffResult.diff;
1891
2375
  }
1892
2376
  } catch (err) {
1893
- log.warn(`captureDiff failed for background agent ${id}`, { error: (err as Error).message });
2377
+ log.warn(`captureDiff failed for background agent ${id}`, { error: thrownMessage(err) });
1894
2378
  }
1895
2379
  try {
1896
2380
  const restoreResult = restoreHead(gitCwd, headState);
@@ -1903,12 +2387,12 @@ export async function spawnBackgroundSession(
1903
2387
  clearHeadState(headStateRepoRoot());
1904
2388
  }
1905
2389
  } catch (err) {
1906
- log.warn(`restoreHead failed for background agent ${id}`, { error: (err as Error).message });
2390
+ log.warn(`restoreHead failed for background agent ${id}`, { error: thrownMessage(err) });
1907
2391
  }
1908
2392
  try {
1909
2393
  deleteBranch(gitCwd, workBranchName);
1910
2394
  } catch (err) {
1911
- log.warn(`deleteBranch failed for background agent ${id}`, { error: (err as Error).message });
2395
+ log.warn(`deleteBranch failed for background agent ${id}`, { error: thrownMessage(err) });
1912
2396
  }
1913
2397
  } finally {
1914
2398
  releaseGitLock?.();
@@ -1923,6 +2407,94 @@ export async function spawnBackgroundSession(
1923
2407
  // no-op by construction.
1924
2408
  let deadlineHandle: ReturnType<typeof setTimeout> | undefined;
1925
2409
 
2410
+ /**
2411
+ * Issue #465 (b) / #466 (ADR 0026 D4) / #542: the terminal write for a run that
2412
+ * was PROVABLY never issued — the branch refusals below and every pre-start
2413
+ * throw end here. ONE definition.
2414
+ *
2415
+ * **ORDER.** The three writes run **run entry → record flip → transcript**. This
2416
+ * is deliberately NOT #466's record-first order, for two measured reasons:
2417
+ *
2418
+ * 1. **Crash window.** A kill after the run-entry append **commits** and before
2419
+ * the record flip leaves a **`running` agent with a terminal run entry** — not
2420
+ * a terminal agent with an unfinalized run. The first residue costs a stale
2421
+ * row whose run entry already says `failed`, registry retired, session dir
2422
+ * pruned, and which no retry or interrupted-run surface can pick up
2423
+ * (§Residual window, **including the earlier window inside this step**). The
2424
+ * second is F1's: an unfinalized `running` run entry, a leaked registry
2425
+ * entry, and a retained session dir only a manual sweep removes.
2426
+ * 2. **Reentrancy.** The `subagent:failed` event is emitted by the record flip —
2427
+ * the **second** write. So the run-entry prune/retention decision
2428
+ * (`finalizeRunEntry`'s `!agent.interruptedAt` gate) has already been taken
2429
+ * when a listener runs, and a listener that synchronously sets
2430
+ * `interruptedAt` cannot change the retention outcome. Under the record-first
2431
+ * order it can, and it does: measured, the directory survives.
2432
+ *
2433
+ * **ATTEMPTED, NOT COMMITTED.** The event follows the run-entry write being
2434
+ * **attempted**, not its having been committed. `persistRunRecord` retires the
2435
+ * registry **before** it appends (`run-registry.ts:345-352`), so an append that
2436
+ * throws leaves no terminal entry; and **each step is contained separately** —
2437
+ * every caller rethrows the ORIGINAL failure (`failPreStart(…); throw err`), so
2438
+ * no step may replace it or suppress another (`updateAgentStatus` is total only
2439
+ * through its error-reporting path, R1/D3; the transcript note is not total at
2440
+ * all, R2). The consequence on the STEP-A fault is stated plainly: the record
2441
+ * flip and the note still happen, so the residue is **`agent=failed` with the
2442
+ * run entry uncommitted (`running`)** — the designed outcome of a fault, not a
2443
+ * second defect, and pinned separately from the committed case (test (b)).
2444
+ *
2445
+ * **NOTHING IS CAPTURED and the ref is dropped INLINE, outside every `try`.**
2446
+ * `captureAndReleaseSession` is not used here: it would fabricate a
2447
+ * `finalOutput` for a session that never produced one, and it is declared below
2448
+ * call site A — a TDZ reference there. `persistAgent` strips `_sessionRef`
2449
+ * anyway, so the release is memory-only and must nonetheless always run (the
2450
+ * issue's second bullet).
2451
+ */
2452
+ const markSpawnFailedBeforePrompt = (message: string): void => {
2453
+ // STEP 0 (#546) — the durable INTENT, written while the registry entry still
2454
+ // exists: retirement is an unlink, so a marker written after it has nowhere to
2455
+ // live. Best-effort and total; `false` means the entry was already gone, in
2456
+ // which case there is nothing for a crash to strand.
2457
+ const marked = markRecordFlipPending(id, { status: 'failed', error: message, at: new Date().toISOString() });
2458
+ if (!marked) {
2459
+ // Issue #546 (major 1): a marker that did not land must NOT defer the
2460
+ // retirement. With no durable intent, STEP A takes the PRE-#546 order
2461
+ // (retire, then append) — a crash in its window is the historical residue
2462
+ // (record `running`, entry gone, no marker: unrepairable by design), which
2463
+ // is strictly better than an entry that looks repairable and is not.
2464
+ // `writeAtomic` is temp-file + rename, so a failed write cannot leave a
2465
+ // half-marked entry: the store holds either the old entry or the full one.
2466
+ safeLog(() => log.warn(`spawnBackgroundSession: record-flip marker not written for ${id} — using the pre-#546 retire-then-append order`, {}));
2467
+ }
2468
+ try { // STEP A — run entry (+ retention/prune; retirement DEFERRED only when marked)
2469
+ finalizeRunEntry('failed', message, { deferRetire: marked });
2470
+ } catch (err) {
2471
+ safeLog(() => log.warn(`spawnBackgroundSession: pre-start finalize failed for ${id}`,
2472
+ { error: thrownMessage(err) }));
2473
+ }
2474
+ // STEP B — record flip (completedAt + error, emits subagent:failed). Issue
2475
+ // #546 r4: the LIVE writer's variant — the MEMORY record becomes terminal in
2476
+ // every fault (#542's pin), and only the RETIREMENT is decided from the disk.
2477
+ // `landed === false` means the store is `running` or unreadable, so the
2478
+ // marker must survive for the next boot.
2479
+ const landed = settleLiveAgentRecord(id, 'failed', message);
2480
+ try { // STEP C — transcript note (no-op+warn when the file is missing)
2481
+ transcript.completeTranscript(id, 'failed');
2482
+ } catch (err) {
2483
+ safeLog(() => log.warn(`spawnBackgroundSession: pre-start transcript note failed for ${id}`,
2484
+ { error: thrownMessage(err) }));
2485
+ }
2486
+ agent._sessionRef = undefined; // outside every try — cannot throw, must always run
2487
+ // STEP D (#546) — retire LAST, and only when the flip is durable. Retiring a
2488
+ // run whose record is still `running` is the whole defect: the registry entry
2489
+ // is the only thing a fresh process can read, so keeping it turns this crash
2490
+ // into an ordinary interrupted candidate the next boot can finish.
2491
+ if (marked && landed && !clearInflightRun(id)) {
2492
+ // The record is settled but the entry survived (major 4): keep going — the
2493
+ // next boot sees a terminal record and re-attempts only the retirement.
2494
+ safeLog(() => log.warn(`spawnBackgroundSession: record settled but the registry entry survived for ${id} — the next boot retries the retirement`, {}));
2495
+ }
2496
+ };
2497
+
1926
2498
  /**
1927
2499
  * Issue #447: the pre-start cleanup. Every throw between the durable
1928
2500
  * dispatch records (agent record + run entry + registry entry, written
@@ -1934,22 +2506,39 @@ export async function spawnBackgroundSession(
1934
2506
  * was never issued nothing can be writing to that dir and no retry will be
1935
2507
  * offered for it, so there is no reader to retain it for.
1936
2508
  *
2509
+ * "Never issued" is a CONTRACT, not an observation — issue #450 D2.1: it
2510
+ * holds because the call site invokes (a) the SDK's own `async` `prompt`
2511
+ * through (b) a plain property read, with (c) a side-effect-free argument.
2512
+ * A wrapper/getter that starts the real method and then throws breaks all of
2513
+ * that (spec E24: `live=true` after the synchronous throw); such a call shape
2514
+ * must NOT reach this function. See the REGIME 1 comment at the call site.
2515
+ *
1937
2516
  * The terminal write is best-effort so a throw in the cleanup cannot mask
1938
2517
  * the original spawn error: `persistRunRecord` retires the registry entry
1939
2518
  * BEFORE appending the entry, and `clearInflightRun` is idempotent, so the
1940
2519
  * residue is gone either way.
2520
+ *
2521
+ * Issue #542: STEP 2 is the FULL terminal flip — run entry, record flip and
2522
+ * transcript note — via `markSpawnFailedBeforePrompt` (its contract comment
2523
+ * above states the order, the attemptedness rule and the containment rule).
2524
+ * The "pruning is provably safe here" argument above is unchanged by it.
1941
2525
  */
1942
2526
  const failPreStart = (message: string): void => {
1943
2527
  if (deadlineHandle) clearTimeout(deadlineHandle);
1944
- cleanupWorkBranch();
1945
- try {
1946
- finalizeRunEntry('failed', message);
2528
+ // EVERY step is contained: a throw here would replace the original spawn failure at
2529
+ // every call site (all do `failPreStart(...); throw err`).
2530
+ try { // STEP 1 — teardown (defence in depth, M18 green)
2531
+ cleanupWorkBranch();
1947
2532
  } catch (err) {
1948
- log.warn(`spawnBackgroundSession: pre-start finalize failed for ${id}`, {
1949
- error: (err as Error).message,
1950
- });
2533
+ safeLog(() => log.error(`spawnBackgroundSession: work-branch teardown failed for ${id} — the original spawn failure is preserved`,
2534
+ { error: thrownMessage(err) }));
1951
2535
  }
1952
- clearInflightRun(id);
2536
+ // STEP 2 — the FULL terminal flip (#542): marker, run entry, record flip and
2537
+ // transcript note, each contained in the shared helper (which is total).
2538
+ // #546: the helper also owns the registry retirement (its STEP D), because the
2539
+ // retire is now conditional on the record flip being durable — a blanket
2540
+ // `clearInflightRun` here would delete the marker that repairs this crash.
2541
+ markSpawnFailedBeforePrompt(message);
1953
2542
  };
1954
2543
 
1955
2544
  /** The pre-start failure stamp: the issue's honest reason plus the cause. */
@@ -1958,20 +2547,58 @@ export async function spawnBackgroundSession(
1958
2547
  sanitizeErrorMessage(err instanceof Error ? err.message : String(err), effectiveCwd);
1959
2548
 
1960
2549
  /**
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.
2550
+ * Issue #616 (Q3): settle a retry whose cancel was found at the pre-prompt
2551
+ * gate. The prompt is NEVER issued, so no deadline is armed yet and there is
2552
+ * no live session to abort — the record, the run entry and the transcript are
2553
+ * the whole settlement, and the status is `stopped` (this is a stop, not a
2554
+ * failure).
2555
+ *
2556
+ * ORDER: record flip → run entry → transcript, each contained separately, so a
2557
+ * throw in one cannot suppress another and cannot escape as the spawn result.
2558
+ * The run-entry write retires the registry entry (its status is terminal) and
2559
+ * prunes the per-run session dir — safe here for the same reason `failPreStart`
2560
+ * documents: the prompt was provably never issued, so nothing can be writing
2561
+ * to that directory and no retry will be offered for this run.
2562
+ *
2563
+ * ACCEPTED RESIDUE (stated, not papered over): a crash between these writes
2564
+ * leaves either a terminal record with a `running` run entry or a `running`
2565
+ * record with a retired entry. Both are the ordinary #439/#546 residue class
2566
+ * and neither is repairable by the boot scan — the window is three synchronous
2567
+ * statements wide.
1968
2568
  */
1969
- const markBranchSpawnFailed = (message: string): void => {
2569
+ const settleCancelledRetry = (): void => {
2570
+ const reason = CANCELLED_RETRY_MESSAGE;
1970
2571
  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 */ }
2572
+ // Issue #574: the KIND precedes the flip that persists it, exactly as
2573
+ // `stopAgent` does for a user stop.
2574
+ stampAgentKind(agent, 'aborted', 'aborted');
2575
+ updateAgentStatus(id, 'stopped', reason);
2576
+ } catch (err) {
2577
+ safeLog(() =>
2578
+ log.warn(`spawnBackgroundSession: cancelled-retry record flip failed for ${id}`, {
2579
+ error: thrownMessage(err),
2580
+ }),
2581
+ );
2582
+ }
2583
+ try {
2584
+ finalizeRunEntry('failed', reason, { stopReason: 'aborted', errorCategory: 'aborted' });
2585
+ } catch (err) {
2586
+ safeLog(() =>
2587
+ log.warn(`spawnBackgroundSession: cancelled-retry run entry failed for ${id}`, {
2588
+ error: thrownMessage(err),
2589
+ }),
2590
+ );
2591
+ }
2592
+ try {
2593
+ transcript.completeTranscript(id, 'stopped');
2594
+ } catch (err) {
2595
+ safeLog(() =>
2596
+ log.warn(`spawnBackgroundSession: cancelled-retry transcript note failed for ${id}`, {
2597
+ error: thrownMessage(err),
2598
+ }),
2599
+ );
2600
+ }
2601
+ agent._sessionRef = undefined; // outside every try — cannot throw, must always run
1975
2602
  };
1976
2603
 
1977
2604
  // Start transcript for this agent. Issue #447 (S2): a throw here used to
@@ -2098,14 +2725,14 @@ export async function spawnBackgroundSession(
2098
2725
  // Mirror the branch-setup-throw path below: the agent record was already
2099
2726
  // persisted as 'running' above, so a refusal that only THROWS leaves a
2100
2727
  // 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);
2728
+ // #460 §4.4 — `failPreStart` alone stops at the run entry). The pre-start
2729
+ // terminal flip is the shared helper — see its contract comment above —
2730
+ // then the throw that reaches the caller's spawn-failure result.
2731
+ // `finalizeRunEntry` already retires the registry entry (a non-running
2732
+ // write clears it); the explicit call is the belt for a finalize that
2733
+ // threw — registry residue is what boot recovery reads, and this dispatch
2734
+ // provably never started.
2735
+ markSpawnFailedBeforePrompt(reason);
2109
2736
  throw new Error(reason);
2110
2737
  }
2111
2738
  // Issue #465 (d): release the process-wide spawn queue BEFORE the per-repo
@@ -2208,11 +2835,12 @@ export async function spawnBackgroundSession(
2208
2835
  releaseGitLock?.();
2209
2836
  releaseGitLock = undefined;
2210
2837
  // Sanitize ONCE and reuse for the terminal write and the thrown error.
2211
- const sanitizedError = sanitizeErrorMessage((err as Error).message, effectiveCwd);
2838
+ const sanitizedError = sanitizeErrorMessage(thrownMessage(err), effectiveCwd);
2212
2839
  // Issue #98: the refused spawn is a failure — flip the record and finalize
2213
2840
  // the run entry so no zombie 'running' entry survives (lockstep, one
2214
- // shared sequence with both pre-flight refusals).
2215
- markBranchSpawnFailed(
2841
+ // shared sequence with both pre-flight refusals: see the helper's contract
2842
+ // comment above).
2843
+ markSpawnFailedBeforePrompt(
2216
2844
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
2217
2845
  throw new Error(
2218
2846
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}. ` +
@@ -2235,6 +2863,18 @@ export async function spawnBackgroundSession(
2235
2863
  gitInfo: { gitBranch?: string; gitDiff?: string },
2236
2864
  stopReason: string,
2237
2865
  ): void => {
2866
+ // Issue #574: FILL ONLY — never re-classify. `updateAgentStatus` already
2867
+ // persisted the kind at the flip; this shared helper runs for BOTH a user
2868
+ // stop and a deadline, and a deadline's kind is `timeout`, so an
2869
+ // unconditional stamp here would overwrite it and lose the friction. The
2870
+ // stamp is for a record that reached the abort settle with NO kind (a
2871
+ // status flipped by a path that did not classify) — and only that.
2872
+ if (!agent.errorCategory) {
2873
+ agent.errorCategory = 'aborted';
2874
+ agent.stopReason = 'aborted';
2875
+ agents.set(id, agent);
2876
+ persistAgent(agent);
2877
+ }
2238
2878
  // W4/M1: capture whatever the branch produced before discarding it — an
2239
2879
  // aborted background agent's partial work is still worth reviewing, and
2240
2880
  // must be RECORDED, not just captured-and-deleted.
@@ -2384,6 +3024,9 @@ export async function spawnBackgroundSession(
2384
3024
  setTimeout(() => {
2385
3025
  if (agent.completedAt) return; // already settled — nothing to abort
2386
3026
  const reason = `Timed out after ${budgetMs}ms`;
3027
+ // Issue #574: the deadline states its OWN kind before the flip persists
3028
+ // it — the snapshot below lands later and may not land at all.
3029
+ stampAgentKind(agent, 'timeout', 'aborted');
2387
3030
  let bookkeepingFailure: unknown;
2388
3031
  try {
2389
3032
  updateAgentStatus(id, 'stopped', reason);
@@ -2439,6 +3082,65 @@ export async function spawnBackgroundSession(
2439
3082
  }
2440
3083
  }, delayMs);
2441
3084
 
3085
+ // ---------------------------------------------------------------------
3086
+ // Issue #616 (Q3): THE ARMED-RETRY CANCEL GATE.
3087
+ //
3088
+ // The automatic transport retry is unaddressable between its id being minted
3089
+ // (above) and its agent record landing: nothing durable names it, so a
3090
+ // `stop_subagent` of the dispatch can only reach the dead attempt 1. The
3091
+ // arming site (`scheduleTransportRetry`) therefore records a durable INTENT
3092
+ // before the spawn, and a stop that finds it sets the cancel. This is where
3093
+ // that cancel is honoured — before the deadline is armed and before the
3094
+ // ACCEPTANCE write, so a cancelled retry never claims `acceptedAt` and never
3095
+ // reaches `session.prompt()`.
3096
+ //
3097
+ // The check reads the marker KEYED BY THE SOURCE RUN (`params.resumeOf`,
3098
+ // inherited through `newDispatchIdentity`), not by our own id — our id is the
3099
+ // thing the marker had to be written without.
3100
+ //
3101
+ // THE SLIVER, AFTER review 624 r2: TWO checks cover the whole gate -> prompt
3102
+ // path. A stop landing before the marker check is honoured by it; one landing
3103
+ // after it but before the prompt can only flip the RECORD (see the belt below)
3104
+ // and is caught by the status read. What remains between that read and the
3105
+ // `session.prompt()` call is ATOMIC UNTIL THE FIRST `await` (the rest of the
3106
+ // path is hundreds of lines but zero awaits, so a racing stop in this process
3107
+ // cannot interleave inside it); a stop landing after the prompt falls back on
3108
+ // the record and the live session.
3109
+ // ---------------------------------------------------------------------
3110
+ //
3111
+ // BOTH the check and the clear are gated on `retryCause === "transport"`: the
3112
+ // marker is armed by, and describes, the AUTOMATIC retry only. A caller-driven
3113
+ // retry of the same source lands on the same `resumeOf`/`attempt` pair, and it
3114
+ // must neither consume another retry's cancel nor clear its intent.
3115
+ const armedRetrySource =
3116
+ params.resumeOf && params.retryCause === 'transport' ? params.resumeOf : undefined;
3117
+ const markerCancelled = !!armedRetrySource && isRetryCancelRequested(armedRetrySource, attempt);
3118
+ // ---------------------------------------------------------------------
3119
+ // Review 624 r2 (B1, THE BELT): a stop that landed between this run's record
3120
+ // write (above) and this gate could only FLIP THE RECORD — `session.abort()`
3121
+ // is a no-op on a session with no active run (the SDK aborts `activeRun`
3122
+ // only), and this run has not prompted yet. The stretch in between is not
3123
+ // small: the spawn queue and, for gitMode 'branch', another run's repository
3124
+ // lock can hold it for minutes, and the age rule above deliberately never
3125
+ // reclaims a cancel, so it cannot cover this case. The record can, and needs
3126
+ // no marker: if our OWN agent is already terminal, the prompt must not be
3127
+ // issued.
3128
+ //
3129
+ // Together with the marker check this settles the whole post-record /
3130
+ // pre-prompt stretch: before the marker clear the cancel is honoured here,
3131
+ // after it the cancel reaches the record and is caught by this line.
3132
+ // ---------------------------------------------------------------------
3133
+ const stoppedBeforePrompt = isTerminalAgentStatus(agent.status);
3134
+ // Past this line the retry IS addressable by its own id — the agent record and
3135
+ // the registry entry are durable — so the intent marker has done its job and
3136
+ // must go. Otherwise a later stop would keep disclosing an "armed" retry that
3137
+ // is in fact a normal running record.
3138
+ if (armedRetrySource) clearArmedRetry(armedRetrySource, attempt);
3139
+ if (markerCancelled || stoppedBeforePrompt) {
3140
+ settleCancelledRetry();
3141
+ return agent;
3142
+ }
3143
+
2442
3144
  // Issue #453 (ADR 0023, decision 1): ONE owner. This function arms the run's
2443
3145
  // deadline on EVERY path — the explicit timeout when there is one, else the
2444
3146
  // 30 m default — and no caller arms a second one (`deadlineOwner` is gone with
@@ -2486,20 +3188,24 @@ export async function spawnBackgroundSession(
2486
3188
  // attach and cleanupWorkBranch would never run — catch here so the work
2487
3189
  // branch is not orphaned (it is a real filesystem branch).
2488
3190
  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
- }
3191
+ let resolveSettled!: () => void;
3192
+ let rejectSettled!: (reason: unknown) => void;
3193
+ const settled = new Promise<void>((resolve, reject) => {
3194
+ resolveSettled = resolve;
3195
+ rejectSettled = reject;
3196
+ });
2500
3197
 
2501
- runPromise.then(() => {
2502
- if (deadlineHandle) clearTimeout(deadlineHandle);
3198
+ const markSettleEntry = (kind: 'success' | 'fault'): void => {
3199
+ try {
3200
+ log.debug(`spawnBackgroundSession: settle body entered for ${id} (${kind})`);
3201
+ } catch {
3202
+ // best effort — the marker must never change the settle path
3203
+ }
3204
+ };
3205
+
3206
+ const onSettled = (): void => {
3207
+ markSettleEntry('success'); // FIRST statement
3208
+ if (deadlineHandle) clearTimeout(deadlineHandle); // deadline clear, second
2503
3209
  try {
2504
3210
  // Probe contract (sdk-abort-contract.test.ts): prompt() RESOLVES on abort
2505
3211
  // — the SDK's runWithLifecycle catches the AbortError and converts it into
@@ -2530,6 +3236,9 @@ export async function spawnBackgroundSession(
2530
3236
  // status (pre-set 'stopped' + completedAt + event + transcript), only
2531
3237
  // the transcript note is missing from this path.
2532
3238
  if (agent.status !== 'stopped') {
3239
+ // Issue #574: this branch calls the flip itself, so it states the kind
3240
+ // first — otherwise the record would be 'stopped' with no category.
3241
+ stampAgentKind(agent, 'aborted', 'aborted');
2533
3242
  updateAgentStatus(id, 'stopped');
2534
3243
  transcript.completeTranscript(id, 'stopped');
2535
3244
  }
@@ -2643,14 +3352,20 @@ export async function spawnBackgroundSession(
2643
3352
  // Issue #53: any throw in this handler would escape as an
2644
3353
  // uncaughtException and kill pi. Log and mark the record terminal —
2645
3354
  // never rethrow.
2646
- log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2647
- error: (err as Error).message,
2648
- });
3355
+ safeLog(() =>
3356
+ log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
3357
+ error: thrownMessage(err),
3358
+ }),
3359
+ );
2649
3360
  markTerminalBestEffort('completed');
2650
3361
  }
2651
- }).catch((err: Error) => {
2652
- if (deadlineHandle) clearTimeout(deadlineHandle);
3362
+ };
3363
+
3364
+ const onSettleFault = (reason: unknown): void => {
3365
+ markSettleEntry('fault'); // FIRST statement
3366
+ if (deadlineHandle) clearTimeout(deadlineHandle); // deadline clear, second
2653
3367
  try {
3368
+ const err = normalizeThrown(reason); // D5: TOTAL, never throws
2654
3369
  // W4: capture partial work + discard the work branch on failure — a failed
2655
3370
  // background agent may still have produced reviewable changes.
2656
3371
  const gitInfo = cleanupWorkBranch();
@@ -2709,13 +3424,108 @@ export async function spawnBackgroundSession(
2709
3424
  // Issue #53: any throw in this handler would escape as an
2710
3425
  // uncaughtException and kill pi. Log and mark the record terminal —
2711
3426
  // never rethrow.
2712
- log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
2713
- error: (err as Error).message,
2714
- });
3427
+ safeLog(() =>
3428
+ log.error(`spawnBackgroundSession: completion handler failed for ${id}`, {
3429
+ error: thrownMessage(err),
3430
+ }),
3431
+ );
2715
3432
  markTerminalBestEffort('failed');
2716
3433
  }
2717
- });
2718
-
3434
+ };
3435
+
3436
+ // THE ATTACH: both settle handlers are on our own promise before the session
3437
+ // is asked to start. The #450 window snapshot pin covers this statement.
3438
+ settled.then(onSettled).catch(onSettleFault);
3439
+
3440
+ // ---- REGIME 1: pre-start ------------------------------------------------
3441
+ // The one statement in this regime is the prompt CALL. A synchronous throw
3442
+ // from it is proof that the prompt was never issued ONLY under three
3443
+ // preconditions, and all three hold at this site TODAY (issue #450 D2.1):
3444
+ //
3445
+ // (a) the callee is the SDK's own `async` method — `AgentSession.prompt`
3446
+ // (node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js:1704,
3447
+ // typed `prompt(text): Promise<void>` in agent-session.d.ts:573). An
3448
+ // `async` function cannot throw to its caller: such a throw happened
3449
+ // BEFORE entry.
3450
+ // (b) it is reached by a PLAIN property read on the session object — no
3451
+ // getter, no Proxy. A getter can start the real method and THEN throw,
3452
+ // so the caller sees a synchronous throw while the session is already
3453
+ // running (spec E24: `syncThrow=yes`, `live=true`). That shape VOIDS
3454
+ // the proof and must be handled as a post-start fault.
3455
+ // (c) the argument is evaluated without side effects (`wrapTask` is one
3456
+ // `String.replace`, src/prompt.ts:67).
3457
+ //
3458
+ // If a future edit wraps `session.prompt` — a retry wrapper, a decorator, an
3459
+ // injected session double that starts work — then (a)/(b) no longer hold,
3460
+ // this regime's premise is GONE, and `failPreStart`'s directory prune plus
3461
+ // branch release would hit a LIVE session. Re-derive D2.1 before keeping it.
3462
+ try {
3463
+ runPromise = session.prompt(wrapTask(params.task));
3464
+ } catch (err) {
3465
+ // Issue #98 (review F1): a synchronous prompt() throw never reaches the
3466
+ // settle handlers — finalize the run entry so no zombie 'running' entry
3467
+ // survives (findSpawnRunById would otherwise resolve and retry a run that
3468
+ // never started). #447: the same cleanup also clears the deadline armed
3469
+ // above and retires the registry entry.
3470
+ const reason = thrownMessage(err); // D5: total
3471
+ failPreStart(sanitizeErrorMessage(reason, effectiveCwd)); // D5: contained, never throws
3472
+ throw err; // D6: deferred NOT settled
3473
+ }
3474
+
3475
+ // ---- REGIME 2: post-start -----------------------------------------------
3476
+ // The prompt has been issued, so NOTHING in here may declare "never issued":
3477
+ // `failPreStart` / `markSpawnFailedBeforePrompt` would prune a LIVE session's
3478
+ // directory and release its branch lock while the session may still be
3479
+ // writing (strictly worse than the fault it reports). No `failPreStart`, no
3480
+ // deadline clear, no second bound —
3481
+ // the deadline armed above stays the monitor of last resort (ADR 0023
3482
+ // decision 1: ONE owner), and the spawn still resolves with a `running`
3483
+ // agent (#439 boundary: a post-start routing fault must not reject the spawn).
3484
+ //
3485
+ // WHY the intrinsic and not `runPromise.then(...)`: `PerformPromiseThen`
3486
+ // performs `SpeciesConstructor(promise)`, which READS `constructor` and then
3487
+ // `constructor[Symbol.species]` — and how it does that depends on the value; a
3488
+ // Proxy's `then` trap or a throwing `then` accessor is reached by the `.then`
3489
+ // METHOD READ, not by the intrinsic. Routing through `Promise.prototype.then`
3490
+ // therefore never touches the value's own `then`, which is what makes the
3491
+ // SUPPORTED value's attach byte-equivalent to `runPromise.then(...)` while a
3492
+ // malformed return is REFUSED here and logged instead of starting work.
3493
+ //
3494
+ // NOT `await`, and NOT `Promise.resolve(...)`: both were measured and both
3495
+ // destroy the contract below — `await` (and `Promise.resolve`) treats a
3496
+ // NON-thenable as a resolution, so `{}` would run the success body and record
3497
+ // a live run as `completed`, and the routing fault would go unlogged. See the
3498
+ // spec's Q2 rows A1 and R3.
3499
+ //
3500
+ // Issue #450 (D2.3/D3/Acceptance 8 — THE CONTRACT; the same words in all three places):
3501
+ //
3502
+ // SUPPORTED — an ordinary native `Promise<void>` of this realm whose `constructor`
3503
+ // and `Symbol.species` reads both complete without a throw and resolve to the
3504
+ // intrinsic `Promise`: the routing attaches and no later rejection can be stranded.
3505
+ //
3506
+ // UNSUPPORTED — every other value, NO GUARANTEE; measured, it splits three ways:
3507
+ // · REFUSED, NOTHING STRANDED: a non-thenable or a custom thenable — thrown here,
3508
+ // logged, the run is left to the deadline.
3509
+ // · REFUSED, REJECTION UNOWNED: a Proxy over a promise, or a native promise whose
3510
+ // `constructor` or `Symbol.species` read throws — thrown here, logged, and the
3511
+ // value's later rejection has no handler, so the host exits 1 (default and strict).
3512
+ // · ACCEPTED, NOT RELIED ON: a same-realm subclass and a cross-realm promise route
3513
+ // and deliver (exit 0). `await` would also own the species-throwing case, but it
3514
+ // registers a non-promise return as a success (spec E50), so it is not the routing.
3515
+ try {
3516
+ void Promise.prototype.then.call(runPromise, resolveSettled, rejectSettled); // D2.3
3517
+ } catch (err) {
3518
+ // A SENSOR, not a new fault: the run already started, so this only reports
3519
+ // that it is unmonitored. `safeLog` is load-bearing — a throwing console
3520
+ // mirror here would reject the spawn (#439) and destroy the boundary above.
3521
+ safeLog(() => // a sensor, not a new fault
3522
+ log.error(
3523
+ `spawnBackgroundSession: settle routing failed for ${id} — the run is unmonitored; its deadline remains the only bound`,
3524
+ { error: thrownMessage(err) },
3525
+ ),
3526
+ );
3527
+ }
3528
+
2719
3529
  return agent;
2720
3530
  } finally {
2721
3531
  releaseSpawnQueue();