brl-subagent 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  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 +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
@@ -1,10 +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 } 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';
8
26
  import { accumulateUsage } from './runner';
9
27
  import * as eventBus from './event-bus';
10
28
  import * as transcript from './transcript';
@@ -12,13 +30,28 @@ import { createEvent } from './event-bus';
12
30
  import { assertSafeAgentId, sanitizeErrorMessage } from './sanitize';
13
31
  import { wrapTask } from './prompt';
14
32
  import { createLogger } from './logging';
15
- import { getCurrentBranch, getHeadState, restoreHead, createWorkBranch, captureDiff, deleteBranch, hasUncommittedChanges, getRepoRoot, commitAll, captureWorkingDiff } from './git';
16
- import type { HeadState } from './git';
17
- import { normalizeTimeout, DEFAULT_BACKGROUND_DEADLINE_MS } from './validate';
18
- import { currentProcessOwner } from './recovery';
19
- import { persistRunRecord, listInflightRuns, type InflightRun } from './run-registry';
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';
47
+ import { clearHeadState, readHeadState, writeHeadState, HEAD_STATE_VERSION } from './headstate';
48
+ import { effectiveBackgroundBudget } from './validate';
49
+ import { currentProcessOwner, classifyOwner, defaultRecoveryDeps } from './recovery';
50
+ import { persistRunRecord, listInflightRuns, clearInflightRun, type InflightRun } from './run-registry';
20
51
  import { isTransportRetryable } from './transport-retry';
21
52
  import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
53
+ import { buildEngineeringBarSection } from './engineering-bar';
54
+ import { prepareRunScratch, markSettled } from './scratch-spawn';
22
55
 
23
56
  const log = createLogger('brl-subagent');
24
57
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
@@ -34,6 +67,61 @@ var spawnQueue: Promise<void> = Promise.resolve();
34
67
  // working tree and must serialize (issue #224).
35
68
  const gitBranchLocks = new Map<string, Promise<void>>();
36
69
 
70
+ /**
71
+ * Issue #465 (b): WHO holds each branch lock (run id). `gitBranchLocks` records
72
+ * only that a repository is locked — and a waiter that is refused (rather than
73
+ * left hanging) has to say whose run it is waiting on.
74
+ *
75
+ * Set once the lock is actually acquired, and cleared ONLY by the matching
76
+ * release: a queued spawn's chain entry may already have replaced ours, so an
77
+ * owner must never be deleted by a stale id. In-process state, like the lock
78
+ * itself — neither survives a restart, which is why a restart is the documented
79
+ * recovery from a wedged owner.
80
+ */
81
+ const gitBranchLockOwners = new Map<string, string>();
82
+
83
+ /**
84
+ * Issue #465 (b): how long a terminal-but-unsettled owner is given before later
85
+ * branch-mode dispatches are refused. 30 s is a measurement, not a guess: the
86
+ * cooperative settle lag after a deadline measured 88 ms (W460P-P6) plus the
87
+ * largest observed `cleanupWorkBranch` (commitAll + captureDiff + restoreHead +
88
+ * deleteBranch) — orders of magnitude below this — while a human staring at a
89
+ * hung dispatch deserves an answer well inside a minute. The grace bounds only
90
+ * the false-positive window; after the first refusal it changes nothing.
91
+ */
92
+ const DEFAULT_STUCK_OWNER_GRACE_MS = 30_000;
93
+ let stuckOwnerGraceMs = DEFAULT_STUCK_OWNER_GRACE_MS;
94
+
95
+ /**
96
+ * TEST-ONLY: shorten the stuck-owner grace. A unit test cannot wait out the
97
+ * shipped 30 s, and the predicate's shape (not its constant) is what it pins.
98
+ */
99
+ export function __setStuckOwnerGraceMs(ms: number): void {
100
+ stuckOwnerGraceMs = ms;
101
+ }
102
+
103
+ /**
104
+ * Issue #465 (b): is `runId` a branch-lock owner that is terminal on paper but
105
+ * still holding its SDK session — i.e. the settle (the only releaser of the
106
+ * branch lock) never ran?
107
+ *
108
+ * `_sessionRef` is the clause that separates "settling" from "wedged": every
109
+ * settle path releases the lock in `cleanupWorkBranch` and only then clears the
110
+ * ref, so a run that is still reachable here has not begun its teardown. It is
111
+ * defence in depth rather than the only guard — `completedAt` plus the grace
112
+ * already covers the settle-in-flight window that a deadline opens (measured
113
+ * 88 ms, W460P-P6) — and removing it changes no verdict this tree can reach
114
+ * (the six settle paths order the release before the clear). It stays because
115
+ * the next change to that ordering must not silently turn a settling run into a
116
+ * refused one.
117
+ */
118
+ function isStuckTerminalOwner(runId: string): boolean {
119
+ const owner = agents.get(runId);
120
+ if (!owner?.completedAt) return false;
121
+ if (owner._sessionRef === undefined) return false;
122
+ return Date.now() - owner.completedAt >= stuckOwnerGraceMs;
123
+ }
124
+
37
125
  /**
38
126
  * TEST-ONLY: release every held git branch lock. The lock is normally held
39
127
  * for the agent's lifetime (released at settle), but tests that never settle
@@ -41,6 +129,7 @@ const gitBranchLocks = new Map<string, Promise<void>>();
41
129
  */
42
130
  export function __testResetGitBranchLocks(): void {
43
131
  gitBranchLocks.clear();
132
+ gitBranchLockOwners.clear();
44
133
  }
45
134
 
46
135
  // Robust UUID generation with fallback
@@ -503,7 +592,11 @@ export const RETRY_SCAN_WINDOW_DAYS = RETRY_SCAN_WINDOW_MS / (24 * 60 * 60 * 100
503
592
  /** The short form rendered by notices: the first 8 hex characters of a UUID. */
504
593
  const SHORT_AGENT_ID_RE = /^[0-9a-f]{8}$/i;
505
594
 
506
- const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
595
+ /**
596
+ * The single source of the retry-identity key set, shared with the scanner tests
597
+ * (`src/__tests__/json-scanner.test.ts`).
598
+ */
599
+ export const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
507
600
  'id',
508
601
  'dispatchId',
509
602
  'resumeOf',
@@ -637,8 +730,27 @@ function skipWhitespace(text: string, index: number): number {
637
730
  return i;
638
731
  }
639
732
 
640
- /** Read one JSON string starting at `start` (which must be `"`). */
641
- function readJsonStringAt(text: string, start: number): { value: string; end: number } {
733
+ /**
734
+ * Read one JSON string starting at `start`; returns the decoded `value` and the
735
+ * offset just past the closing quote. Offsets are UTF-16 code units.
736
+ *
737
+ * Contract (pinned by `src/__tests__/json-scanner.test.ts`, issue #428):
738
+ * - precondition: `start` is the `"` that opens the value.
739
+ * - never throws; `end` is always a number in
740
+ * `[start, max(start, text.length)]` (when `start` is past the end, it
741
+ * returns `start`).
742
+ * - unterminated string -> `end === text.length` and `value` is the raw
743
+ * remainder (D1): a corrupt record is skipped by the caller, never surfaced
744
+ * as an error.
745
+ * - the value is `JSON.parse`'s when it parses. When it does not (an invalid
746
+ * escape), the fallback returns the RAW text between the quotes with a
747
+ * correct `end` (D5) — best-effort: an invalid escape inside `"id"` yields a
748
+ * value `assertSafeAgentId` rejects, so the record leaves retry lineage.
749
+ * - an escape consumes exactly one following character, including `\\` and
750
+ * `\"`; a `"` reached after an escape is content, not a terminator.
751
+ * Exposed for tests; not part of the reader API (architecture-rules.test.ts).
752
+ */
753
+ export function readJsonStringAt(text: string, start: number): { value: string; end: number } {
642
754
  let i = start + 1;
643
755
  let escaped = false;
644
756
  while (i < text.length) {
@@ -667,8 +779,27 @@ function readJsonStringAt(text: string, start: number): { value: string; end: nu
667
779
  return { value: text.slice(start + 1), end: i };
668
780
  }
669
781
 
670
- /** Skip one JSON value (scalar, object, or array) without parsing it. */
671
- function skipJsonValue(text: string, start: number): number {
782
+ /**
783
+ * Skip one JSON value (scalar, object, or array) without parsing it; returns the
784
+ * offset just past the value. Offsets are UTF-16 code units.
785
+ *
786
+ * Contract (pinned by `src/__tests__/json-scanner.test.ts`, issue #428):
787
+ * - precondition: `start` is the value's FIRST character; the caller has
788
+ * already skipped whitespace (`scanTopLevelScalars` does, via `skipWhitespace`).
789
+ * - never throws; always returns a number in
790
+ * `[start, max(start, text.length)]` (when `start` is past the end, it
791
+ * returns `start`).
792
+ * - unterminated container or string -> `text.length` (D1: corrupt records are
793
+ * dropped upstream by `readAgentIdentity`, never surfaced as an error).
794
+ * - containers are depth-counted on a single pass, +1 for `{`/`[` and -1 for
795
+ * `}`/`]`; the counting is bracket-TYPE-AGNOSTIC, so `'[1}'` ends at 3.
796
+ * Strictness is `JSON.parse`'s job (D3).
797
+ * - the scalar branch scans to the first `,` or `}` or EOF — it does NOT stop
798
+ * at `]` (D4), so `'1]'` returns 2. Both call sites sit in an object's
799
+ * top-level value position, so `]` is unreachable on valid input.
800
+ * Exposed for tests; not part of the reader API (architecture-rules.test.ts).
801
+ */
802
+ export function skipJsonValue(text: string, start: number): number {
672
803
  if (text[start] === '"') return readJsonStringAt(text, start).end;
673
804
  if (text[start] === '{' || text[start] === '[') {
674
805
  let depth = 0;
@@ -708,8 +839,23 @@ function parseJsonScalar(raw: string): JsonScalar {
708
839
  * Extract top-level scalar fields from a record's JSON text. Nested values
709
840
  * (notably `result.messages` and `finalOutput`) are skipped, not parsed — the
710
841
  * reader only ever touches the six identity keys.
842
+ *
843
+ * Contract (pinned by `src/__tests__/json-scanner.test.ts`, issue #428):
844
+ * - never throws; a record with no leading `{` yields an empty map.
845
+ * - whitespace around the braces, keys, `:` and values is skipped with
846
+ * `/\s/` — deliberately WIDER than JSON's four whitespace characters, so a
847
+ * BOM- or NBSP-prefixed record is still read instead of silently vanishing
848
+ * from retry lineage (D2).
849
+ * - a wanted key holding a container is skipped, not read (the key stays
850
+ * absent); a wanted key holding a scalar is parsed with `parseJsonScalar`.
851
+ * - a non-wanted key's value is skipped with `skipJsonValue`, whole — a nested
852
+ * `"status"` or `"attempt"` inside `result.messages` is never mistaken for a
853
+ * top-level one.
854
+ * - a duplicate key keeps the last value; a malformed byte stops the scan
855
+ * rather than hanging it.
856
+ * Exposed for tests; not part of the reader API (architecture-rules.test.ts).
711
857
  */
712
- function scanTopLevelScalars(text: string, wanted: ReadonlySet<string>): Map<string, JsonScalar> {
858
+ export function scanTopLevelScalars(text: string, wanted: ReadonlySet<string>): Map<string, JsonScalar> {
713
859
  const out = new Map<string, JsonScalar>();
714
860
  let i = skipWhitespace(text, 0);
715
861
  if (text[i] !== '{') return out;
@@ -1121,6 +1267,42 @@ export async function steerAgent(id: string, message: string): Promise<Backgroun
1121
1267
  */
1122
1268
  export { transcriptPath as getTranscriptPath } from './transcript-path';
1123
1269
 
1270
+ /**
1271
+ * Issue #466 (ADR 0026 D4): the pre-flight refusal for a repository whose
1272
+ * durable head-state record is still unresolved and whose owner is NOT alive —
1273
+ * i.e. the boot could not repair it (a dirty tree, an unreadable record, a
1274
+ * failed restore, or a boot that never ran in this project).
1275
+ *
1276
+ * Returns the message, or undefined when the dispatch may proceed. Ordered
1277
+ * BEFORE the dirty check because an unresolved record is the more specific
1278
+ * fact: the tree is on a branch a dead run left behind, and only this record
1279
+ * names its base. A record with a corrupt shape, and a record whose owner is
1280
+ * ALIVE, never refuse — the first cannot be acted on by either side (L1/L2 of
1281
+ * the dossier), and a live owner may still be writing its own run.
1282
+ *
1283
+ * The message names the BRANCH, the BASE and the COMMANDS (never a path):
1284
+ * `sanitizeErrorMessage` neutralises the cwd and its parent downstream (#460 §4.2).
1285
+ */
1286
+ function unresolvedHeadStateRefusal(repoRoot: string): string | undefined {
1287
+ const read = readHeadState(repoRoot);
1288
+ if (read.state !== 'ok') return undefined;
1289
+ const record = read.record;
1290
+ if (classifyOwner(record.owner, defaultRecoveryDeps()) === 'alive') return undefined;
1291
+ const base = record.base.detached
1292
+ ? `detached HEAD at ${record.base.sha.slice(0, 8)}`
1293
+ : record.base.branch;
1294
+ const checkout = record.base.detached
1295
+ ? `git checkout --detach ${record.base.sha}`
1296
+ : `git checkout ${record.base.branch}`;
1297
+ return (
1298
+ `this repository still carries an unresolved branch-run state: the working tree was left on ` +
1299
+ `${record.workBranch} by an interrupted run whose recorded base is ${base}. ` +
1300
+ `Inspect it with \`git status\`, then restore the base by hand: ` +
1301
+ `git stash push -u -m "brl-subagent interrupted work" && ${checkout}. ` +
1302
+ `Keep ${record.workBranch} until its work is reviewed — it is the only copy.`
1303
+ );
1304
+ }
1305
+
1124
1306
  /**
1125
1307
  * Spawn a background session using pi's session API
1126
1308
  *
@@ -1170,9 +1352,43 @@ export async function spawnBackgroundSession(
1170
1352
  let resolveNext!: () => void;
1171
1353
  spawnQueue = new Promise<void>(r => { resolveNext = r; });
1172
1354
  await prev;
1355
+
1356
+ // Issue #465 (d): the queue's critical section is the pi API access below
1357
+ // (the dynamic import + createAgentSession), NOT the per-repo git wait
1358
+ // further down — which can last a whole run. The release is therefore
1359
+ // explicit AND idempotent: the branch block releases before it waits on
1360
+ // another run's repository, and the `finally` still releases on every other
1361
+ // exit path (measured before this: a healthy branch-mode run made an
1362
+ // unrelated non-git spawn stay PENDING for its entire duration).
1363
+ let spawnQueueReleased = false;
1364
+ const releaseSpawnQueue = (): void => {
1365
+ if (spawnQueueReleased) return;
1366
+ spawnQueueReleased = true;
1367
+ resolveNext();
1368
+ };
1173
1369
 
1174
1370
  try {
1175
1371
  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.
1377
+ //
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
+ }
1176
1392
  const effectiveCwd = params.cwd ?? ctx.cwd;
1177
1393
  // Dynamic import — static import fails under concurrent jiti loads
1178
1394
  const { getAgentDir, createAgentSession, SessionManager, SettingsManager, DefaultResourceLoader } = await import('@earendil-works/pi-coding-agent');
@@ -1245,6 +1461,15 @@ export async function spawnBackgroundSession(
1245
1461
  if (params.resumeContext?.trim()) {
1246
1462
  sections.push(`\n<resume-context>\n${params.resumeContext.trim()}\n</resume-context>\n`);
1247
1463
  }
1464
+ // Issue #421: the project's engineering bar is the LAST section, so a retry's
1465
+ // resume preamble stays adjacent to the system prompt it qualifies. It is
1466
+ // injected here — not chosen by the conductor — so no preset selection can
1467
+ // drop it. Gated by the project flag (ADR 0019); `engineering-bar.ts` owns the
1468
+ // read, the failure warning and the framing, so this builder still
1469
+ // interpolates only the two caller fields pinned by the neutralization ratchet
1470
+ // in session-manager.test.ts.
1471
+ const barSection = buildEngineeringBarSection(effectiveCwd, log);
1472
+ if (barSection) sections.push(barSection);
1248
1473
  //
1249
1474
  // F25: ALWAYS build our own loader (even without a systemPrompt). If
1250
1475
  // resourceLoader is undefined, createAgentSession constructs its own
@@ -1309,6 +1534,11 @@ export async function spawnBackgroundSession(
1309
1534
  const attempt = params.attempt ?? 1;
1310
1535
  const owner = currentProcessOwner();
1311
1536
 
1537
+ // Issue #453 (decision 5): the run's budget, computed ONCE. The record's
1538
+ // `timeoutMs` (what the monitor displays as `deadlineAt`) and the armed timer
1539
+ // derive from the same value, so the display cannot drift from the timer.
1540
+ const budgetMs = effectiveBackgroundBudget(params.timeout);
1541
+
1312
1542
  // Create agent record
1313
1543
  const agent: BackgroundAgent = {
1314
1544
  id,
@@ -1317,10 +1547,21 @@ export async function spawnBackgroundSession(
1317
1547
  description: params.description || params.task.slice(0, 50),
1318
1548
  status: 'running',
1319
1549
  startedAt: Date.now(),
1550
+ // Issue #423: the EFFECTIVE budget (explicit timeout, else the 30m default),
1551
+ // stamped BEFORE persistAgent so the initial record already carries it — a
1552
+ // result/wake read after the spawn closure is gone must not fall back to
1553
+ // "unknown".
1554
+ timeoutMs: budgetMs,
1320
1555
  task: params.task,
1321
1556
  model: params.model || 'unknown',
1322
1557
  thinkingLevel: params.thinkingLevel || 'medium',
1323
1558
  priority: params.priority,
1559
+ // Issue #474: the directory this run was spawned in, stamped so a settled
1560
+ // failure can report the worktree it may have left. `effectiveCwd` is the
1561
+ // resolved, validated absolute path (params.cwd ?? ctx.cwd), and
1562
+ // `persistAgent` strips only the live-only pointers — so this survives the
1563
+ // record and the completion wake can read it.
1564
+ cwd: effectiveCwd,
1324
1565
  dispatchId,
1325
1566
  resumeOf: params.resumeOf,
1326
1567
  attempt,
@@ -1360,6 +1601,16 @@ export async function spawnBackgroundSession(
1360
1601
  attempt,
1361
1602
  owner,
1362
1603
  recoveryPosture: params.recoveryPosture,
1604
+ // Issue #511 (U2): the run's scratch directory (`<root>/runs/<id>`, 0700),
1605
+ // created above. Persisted at spawn so the retry preamble (U3) and the
1606
+ // settle path read one value rather than re-deriving a location.
1607
+ scratchDir: scratch.runDir,
1608
+ // Issue #447: the acceptance marker starts `null` — the dispatch is
1609
+ // TRACKED from here on (agent record + registry entry) but the prompt has
1610
+ // not been issued. Only the write immediately above `session.prompt()`
1611
+ // turns it into a timestamp; a boot scan that finds `null` knows nothing
1612
+ // was started (a pre-upgrade record simply lacks the field instead).
1613
+ acceptedAt: null,
1363
1614
  };
1364
1615
  persistRunRecord(pi, run, "background");
1365
1616
 
@@ -1370,45 +1621,78 @@ export async function spawnBackgroundSession(
1370
1621
  //
1371
1622
  // U2 (D2) retention: this is the SINGLE terminal choke point for a background
1372
1623
  // run — git-setup refusal, a synchronous prompt throw, the .then completed /
1373
- // provider-failed / aborted branches, the .catch stopped / failed branches and
1374
- // the markTerminalBestEffort catch-all ALL land here exactly once (the
1375
- // runFinalized guard). The session-dir decision below therefore covers every
1376
- // settle path. The index.ts poller crash notices are NOT settlements (they flip
1377
- // only the live UI state and leave the run/agent record to this settle); an
1378
- // interrupted run (U1 boot-scan mark) never reaches this function and KEEPS its
1379
- // file (D3).
1380
- let runFinalized = false;
1624
+ // provider-failed / aborted branches, the .catch stopped / failed branches, the
1625
+ // markTerminalBestEffort catch-all and (since #453) the deadline timer ALL land
1626
+ // here. The session-dir decision below therefore covers every settle path. The
1627
+ // index.ts poller crash notices are NOT settlements (they flip only the live UI
1628
+ // state and leave the run/agent record to this settle); an interrupted run (U1
1629
+ // boot-scan mark) never reaches this function and KEEPS its file (D3).
1630
+ //
1631
+ // Issue #453 (ADR 0023 decision 3): TWO once-only guards, not one.
1632
+ // - `entryWritten` — a terminal RECORD for this id is durable. The deadline
1633
+ // may write it first (a classification snapshot); every later write is then
1634
+ // a payload AMENDMENT of that snapshot, never a second classification.
1635
+ // - `pruned` — the session-dir decision has been made. Only a SETTLE makes it
1636
+ // (the deadline passes `prune: false`), and it is made even when the entry
1637
+ // already exists — otherwise a cooperative timeout would stop pruning.
1638
+ // Collapsing the two is the M4 mutant the dir-survives test kills.
1639
+ let entryWritten = false;
1640
+ let pruned = false;
1641
+ /**
1642
+ * The DEADLINE's classification snapshot — the amendment's base, and ONLY the
1643
+ * deadline ever sets it (see the arm site). A settle→settle re-entry (the
1644
+ * catch-all after a throwing handler) therefore still writes nothing, which is
1645
+ * the single-terminal-entry contract the old `runFinalized` guard enforced.
1646
+ */
1647
+ let snapshot: SubagentRun | undefined;
1648
+
1649
+ /**
1650
+ * This call's OWN classification. The retention/prune gate reads THIS — never
1651
+ * the snapshot's — because at the deadline a run looks like `timeout` (not
1652
+ * transport-retryable) while its true settle category may decide otherwise
1653
+ * (ADR 0023 decision 3).
1654
+ *
1655
+ * Issue #179 (D1/D2): the classifier's explicit category wins (it knows the
1656
+ * terminal stopReason); otherwise fall back to the legacy message-based
1657
+ * classification (refused spawns, sync throws, preflight rejections, the
1658
+ * catch-all) so no failure is ever left uncategorized.
1659
+ */
1660
+ const classifyFailure = (
1661
+ status: "done" | "failed",
1662
+ error?: string,
1663
+ terminal?: { errorCategory?: ErrorCategory },
1664
+ ): ErrorCategory | undefined =>
1665
+ status === "failed"
1666
+ ? terminal?.errorCategory ??
1667
+ (error
1668
+ ? classifyError({
1669
+ messages: [],
1670
+ usage: { ...EMPTY_USAGE },
1671
+ exitCode: 1,
1672
+ stderr: "",
1673
+ errorMessage: error,
1674
+ })
1675
+ : undefined)
1676
+ : undefined;
1677
+
1678
+ /** Returns the entry it appended (the terminal record or the amendment), if any. */
1381
1679
  const finalizeRunEntry = (
1382
1680
  status: "done" | "failed",
1383
1681
  error?: string,
1384
- terminal?: { stopReason?: string; errorCategory?: ErrorCategory },
1385
- ): void => {
1386
- if (runFinalized) return;
1387
- runFinalized = true;
1682
+ terminal?: { stopReason?: string; errorCategory?: ErrorCategory; prune?: boolean },
1683
+ ): SubagentRun | undefined => {
1684
+ // Issue #511 (U2): settling includes the scratch directory's `.done` marker.
1685
+ // This is the SINGLE terminal choke point for a background run (git-setup
1686
+ // refusal, a synchronous prompt throw, the .then/.catch branches, the
1687
+ // catch-all and the deadline), so the marker is written here and no settle
1688
+ // path can forget it. Best-effort: `markSettled` logs and never throws, so
1689
+ // it cannot change the run's outcome. A run with no directory (a pre-U2
1690
+ // record) is a no-op.
1691
+ markSettled(run, log);
1388
1692
  const usage = agent.result?.usage ?? EMPTY_USAGE;
1389
1693
  const finalOutput = agent.finalOutput ?? "";
1390
- // Issue #179 (D1/D2): the classifier's explicit category wins (it knows the
1391
- // terminal stopReason); otherwise fall back to the legacy message-based
1392
- // classification (refused spawns, sync throws, preflight rejections, the
1393
- // catch-all) so no failure is ever left uncategorized.
1394
- //
1395
- // Issue #404: HOISTED above the session-dir decision below — the retention
1396
- // gate must read the same category/value the run record is about to get, and
1397
- // that decision has to happen before the record write (see the invariant
1398
- // note there). `classifyError` is pure and total, so hoisting costs nothing.
1399
- const errorCategory =
1400
- status === "failed"
1401
- ? terminal?.errorCategory ??
1402
- (error
1403
- ? classifyError({
1404
- messages: [],
1405
- usage: { ...EMPTY_USAGE },
1406
- exitCode: 1,
1407
- stderr: "",
1408
- errorMessage: error,
1409
- })
1410
- : undefined)
1411
- : undefined;
1694
+ // The TRUE category of THIS call — see the note on `classifyFailure`.
1695
+ const errorCategory = classifyFailure(status, error, terminal);
1412
1696
  // U2 (D2) prune + #404 retention. THE INVARIANT: the prune/mark decision
1413
1697
  // precedes the run-record write, and everything above it is pure — so no
1414
1698
  // throw between the decision and the write can leave a terminal run's session
@@ -1418,7 +1702,12 @@ export async function spawnBackgroundSession(
1418
1702
  // run that will be re-dispatched has a reader for the retained session, and
1419
1703
  // it is built from the values this record is about to carry, so the reader
1420
1704
  // and the retainer can never disagree.
1421
- if (!agent.interruptedAt) {
1705
+ //
1706
+ // Issue #453: gated on `pruned` (not on `entryWritten`) and skipped when the
1707
+ // CALLER asks (`prune: false` — the deadline). One flag for both would make a
1708
+ // successful deadline write suppress this decision (mutant M4).
1709
+ if ((terminal?.prune ?? true) && !pruned && !agent.interruptedAt) {
1710
+ pruned = true;
1422
1711
  // The CAPTURED dir — tests swap STORAGE_DIR per case, and a mid-run change
1423
1712
  // of root must never mis-target the delete or the marker.
1424
1713
  const sessionDir = agent._sessionFile ? dirname(agent._sessionFile) : backgroundSessionDir(id);
@@ -1435,6 +1724,39 @@ export async function spawnBackgroundSession(
1435
1724
  pruneSessionDir(id, sessionDir);
1436
1725
  }
1437
1726
  }
1727
+
1728
+ // Issue #453 (ADR 0023 decision 4): a second write is an AMENDMENT — the
1729
+ // deadline already wrote the classification, so only the PAYLOAD moves
1730
+ // (cost/usage/output/final detail). `status`, `errorCategory`, `stopReason`
1731
+ // and `errorMessage` are the snapshot's and are never rewritten: a late
1732
+ // settle's real usage must not re-open what the run WAS (that would be a
1733
+ // second classification claim — mutant M7).
1734
+ if (entryWritten) {
1735
+ // No snapshot => this is a settle RE-ENTRY (the settle already wrote the
1736
+ // record); nothing new to say. Only a deadline snapshot is amendable.
1737
+ if (!snapshot) return undefined;
1738
+ const amended: SubagentRun = {
1739
+ ...snapshot,
1740
+ turns: usage.turns,
1741
+ finishedAt: new Date().toISOString(),
1742
+ durationMs: Date.now() - startedAtMs,
1743
+ cost: usage.cost,
1744
+ tokensIn: usage.input,
1745
+ tokensOut: usage.output,
1746
+ outputSummary: finalOutput.slice(0, 200),
1747
+ fullOutput: finalOutput || undefined,
1748
+ };
1749
+ persistRunRecord(pi, amended);
1750
+ log.info("Background run amended after a late settle", {
1751
+ agentId: id,
1752
+ status: amended.status,
1753
+ errorCategory: amended.errorCategory,
1754
+ turns: usage.turns,
1755
+ tokensOut: usage.output,
1756
+ cost: usage.cost,
1757
+ });
1758
+ return amended;
1759
+ }
1438
1760
  // Issue #187: capture the RAW terminal reason BEFORE coercion. `finalTurnError`
1439
1761
  // means "the final turn was a PROVIDER error" (isProviderError); deriving it
1440
1762
  // from the COERCED reason would turn a missing/success reason into 'error' and
@@ -1472,6 +1794,10 @@ export async function spawnBackgroundSession(
1472
1794
  : run.originalParams,
1473
1795
  };
1474
1796
  persistRunRecord(pi, entry);
1797
+ // Issue #453: set only AFTER the append resolved. A throwing write therefore
1798
+ // leaves `entryWritten === false`, so a later settle still classifies the run
1799
+ // instead of amending a record that was never written (mutant M3).
1800
+ entryWritten = true;
1475
1801
  // Issue #179 (D6): the explicit settle line — the log's job is to record the
1476
1802
  // CLASSIFIED OUTCOME, which cwd alone can never convey.
1477
1803
  log.info("Background run settled", {
@@ -1483,10 +1809,180 @@ export async function spawnBackgroundSession(
1483
1809
  errorCategory,
1484
1810
  error: error ?? null,
1485
1811
  });
1812
+ return entry;
1813
+ };
1814
+
1815
+ // Issue #447: git teardown state + the teardown itself, declared BEFORE the
1816
+ // pre-start region (the closures do nothing at declaration time) so the ONE
1817
+ // pre-start cleanup below can reach them; the branch is only CREATED later,
1818
+ // in the `gitMode === 'branch'` block further down.
1819
+ let headState: HeadState | undefined;
1820
+ let workBranchName: string | undefined;
1821
+ let releaseGitLock: (() => void) | undefined;
1822
+ // Idempotency guard for cleanupWorkBranch: it must be safe to call from both
1823
+ // the normal settle path and the catch-all that runs when a settle step
1824
+ // throws FIRST (before its own cleanup call). Without this the second call
1825
+ // would re-restore/re-delete and log spurious warnings.
1826
+ let gitCleanupDone = false;
1827
+ const gitCwd = params.cwd ?? ctx.cwd;
1828
+ // Issue #466: the repository root the head-state record is keyed by — the SAME
1829
+ // resolution the branch lock below uses, so the write and the clear cannot
1830
+ // disagree about which record they own (a record keyed on `process.cwd()`
1831
+ // would name the wrong repo for a run dispatched with `cwd` elsewhere).
1832
+ const headStateRepoRoot = (): string => getRepoRoot(gitCwd) ?? gitCwd;
1833
+
1834
+ // Branch teardown — commit the agent's work (so the diff is real), capture
1835
+ // the diff, switch back to the original branch, delete the work branch, and
1836
+ // release the per-repo git lock. Runs on EVERY settle path. C1: agents
1837
+ // rarely commit, so captureDiff(base...HEAD) alone would be empty and the
1838
+ // uncommitted edits would leak into the base working tree on switch —
1839
+ // commitAll first makes the diff real and the switch clean.
1840
+ const cleanupWorkBranch = (): { gitBranch?: string; gitDiff?: string } => {
1841
+ if (gitCleanupDone || !workBranchName || !headState) return {};
1842
+ gitCleanupDone = true;
1843
+ const info: { gitBranch?: string; gitDiff?: string } = { gitBranch: workBranchName };
1844
+ // The lock MUST be released on every exit path — early returns included.
1845
+ try {
1846
+ try {
1847
+ const stillOnOurBranch = getCurrentBranch(gitCwd) === workBranchName;
1848
+ if (!stillOnOurBranch) {
1849
+ log.warn(`cleanupWorkBranch: tree moved off ${workBranchName} — skipping switch/delete`, {
1850
+ agentId: id,
1851
+ });
1852
+ // Issue #466: the tree is VERIFIED off our branch (moved by hand), so
1853
+ // the record has nothing left to repair — clear it (M7's counterpart).
1854
+ clearHeadState(headStateRepoRoot());
1855
+ return info;
1856
+ }
1857
+ } catch (err) {
1858
+ log.warn(`getCurrentBranch failed during cleanup for background agent ${id}`, {
1859
+ error: (err as Error).message,
1860
+ });
1861
+ // Issue #466: KEEP the record — we cannot tell where the tree is, which
1862
+ // is exactly the crash-equivalent state the boot's retry is for.
1863
+ return info;
1864
+ }
1865
+ try {
1866
+ // C1: commit the agent's work so captureDiff sees it. If no identity is
1867
+ // configured, fall back to capturing the working-tree diff directly.
1868
+ const dirty = hasUncommittedChanges(gitCwd);
1869
+ if (dirty) {
1870
+ const commitResult = commitAll(gitCwd, `brl-subagent ${id}: background work`);
1871
+ if (commitResult.ok) {
1872
+ log.info('Committed background agent work on work branch', {
1873
+ sha: commitResult.sha,
1874
+ branch: workBranchName,
1875
+ agentId: id,
1876
+ });
1877
+ } else {
1878
+ log.warn(`commitAll failed for background agent ${id} — capturing working diff`, {
1879
+ error: commitResult.error,
1880
+ });
1881
+ const workingDiff = captureWorkingDiff(gitCwd);
1882
+ if (workingDiff) info.gitDiff = workingDiff;
1883
+ }
1884
+ }
1885
+ const diffResult = captureDiff(gitCwd, headState.sha);
1886
+ if (diffResult.ok && diffResult.diff.trim()) {
1887
+ // Merge committed + working diffs — either can exist alone.
1888
+ info.gitDiff = info.gitDiff
1889
+ ? `${info.gitDiff}\n${diffResult.diff}`
1890
+ : diffResult.diff;
1891
+ }
1892
+ } catch (err) {
1893
+ log.warn(`captureDiff failed for background agent ${id}`, { error: (err as Error).message });
1894
+ }
1895
+ try {
1896
+ const restoreResult = restoreHead(gitCwd, headState);
1897
+ if (!restoreResult.ok) {
1898
+ log.warn(`restoreHead failed for background agent ${id}`, { error: restoreResult.error });
1899
+ // Issue #466: a FAILED restore keeps the record (mutants M3/M4) — the
1900
+ // tree is still on the work branch and the base lives only here.
1901
+ } else {
1902
+ // Verified off the work branch: the record has done its job.
1903
+ clearHeadState(headStateRepoRoot());
1904
+ }
1905
+ } catch (err) {
1906
+ log.warn(`restoreHead failed for background agent ${id}`, { error: (err as Error).message });
1907
+ }
1908
+ try {
1909
+ deleteBranch(gitCwd, workBranchName);
1910
+ } catch (err) {
1911
+ log.warn(`deleteBranch failed for background agent ${id}`, { error: (err as Error).message });
1912
+ }
1913
+ } finally {
1914
+ releaseGitLock?.();
1915
+ releaseGitLock = undefined;
1916
+ }
1917
+ return info;
1486
1918
  };
1487
1919
 
1488
- // Start transcript for this agent
1489
- transcript.startTranscript(agent.id, params.task);
1920
+ // Issue #447: the deadline handle is declared HERE, above the pre-start
1921
+ // region, so the pre-start cleanup can clear it. It is only ARMED below
1922
+ // (just before prompt()), so on the earlier throw sites clearing it is a
1923
+ // no-op by construction.
1924
+ let deadlineHandle: ReturnType<typeof setTimeout> | undefined;
1925
+
1926
+ /**
1927
+ * Issue #447: the pre-start cleanup. Every throw between the durable
1928
+ * dispatch records (agent record + run entry + registry entry, written
1929
+ * above) and `session.prompt()` funnels here: the transcript start, the
1930
+ * acceptance write, and the prompt call itself each rethrow through it.
1931
+ *
1932
+ * PRUNING IS PROVABLY SAFE HERE — and only here. `finalizeRunEntry` prunes
1933
+ * the run's session dir per its #404 retention gate; for a run whose prompt
1934
+ * was never issued nothing can be writing to that dir and no retry will be
1935
+ * offered for it, so there is no reader to retain it for.
1936
+ *
1937
+ * The terminal write is best-effort so a throw in the cleanup cannot mask
1938
+ * the original spawn error: `persistRunRecord` retires the registry entry
1939
+ * BEFORE appending the entry, and `clearInflightRun` is idempotent, so the
1940
+ * residue is gone either way.
1941
+ */
1942
+ const failPreStart = (message: string): void => {
1943
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1944
+ cleanupWorkBranch();
1945
+ try {
1946
+ finalizeRunEntry('failed', message);
1947
+ } catch (err) {
1948
+ log.warn(`spawnBackgroundSession: pre-start finalize failed for ${id}`, {
1949
+ error: (err as Error).message,
1950
+ });
1951
+ }
1952
+ clearInflightRun(id);
1953
+ };
1954
+
1955
+ /** The pre-start failure stamp: the issue's honest reason plus the cause. */
1956
+ const neverIssued = (err: unknown): string =>
1957
+ `${PROMPT_NEVER_ISSUED_MESSAGE}: ` +
1958
+ sanitizeErrorMessage(err instanceof Error ? err.message : String(err), effectiveCwd);
1959
+
1960
+ /**
1961
+ * Issue #465 (b) / #466 (ADR 0026 D4): the terminal write for a branch
1962
+ * dispatch refused before the prompt — record flip -> run entry ->
1963
+ * transcript, the same three writes every refused spawn ends with. ONE
1964
+ * definition for both pre-flight refusals AND the branch-setup-throw path
1965
+ * below, so the sequence and its message cannot drift apart between them;
1966
+ * each step is contained, because a cleanup fault must never mask the
1967
+ * refusal itself.
1968
+ */
1969
+ const markBranchSpawnFailed = (message: string): void => {
1970
+ try {
1971
+ updateAgentStatus(id, 'failed', message);
1972
+ finalizeRunEntry('failed', message);
1973
+ transcript.completeTranscript(id, 'failed');
1974
+ } catch { /* best-effort, same discipline as the setup-throw path */ }
1975
+ };
1976
+
1977
+ // Start transcript for this agent. Issue #447 (S2): a throw here used to
1978
+ // leave a `running` run entry and a live registry entry that the next boot
1979
+ // offered as an interrupted, retryable run — clean it and rethrow.
1980
+ try {
1981
+ transcript.startTranscript(agent.id, params.task);
1982
+ } catch (err) {
1983
+ failPreStart(neverIssued(err));
1984
+ throw err;
1985
+ }
1490
1986
 
1491
1987
  // Store session ref for live monitor polling
1492
1988
  agent._sessionRef = session;
@@ -1556,15 +2052,6 @@ export async function spawnBackgroundSession(
1556
2052
  // hard failure — never spawn an unisolated background agent that was asked
1557
2053
  // for isolation (fail-loud, same principle as foreground's fallback but
1558
2054
  // background cannot warn-and-continue safely).
1559
- let headState: HeadState | undefined;
1560
- let workBranchName: string | undefined;
1561
- let releaseGitLock: (() => void) | undefined;
1562
- // Idempotency guard for cleanupWorkBranch: it must be safe to call from both
1563
- // the normal settle path and the catch-all that runs when a settle step
1564
- // throws FIRST (before its own cleanup call). Without this the second call
1565
- // would re-restore/re-delete and log spurious warnings.
1566
- let gitCleanupDone = false;
1567
- const gitCwd = params.cwd ?? ctx.cwd;
1568
2055
  if (params.gitMode === 'branch') {
1569
2056
  // C2: serialize the FULL branch lifecycle per repo. The spawnQueue only
1570
2057
  // covers setup; without this lock, a second concurrent branch-mode spawn
@@ -1572,21 +2059,94 @@ export async function spawnBackgroundSession(
1572
2059
  // fight over the shared working tree (stranding the repo on an orphan
1573
2060
  // branch). The lock is released in cleanupWorkBranch (or on setup throw).
1574
2061
  // Key: resolved repository root, cwd fallback for non-repo paths (#224).
1575
- const lockKey = getRepoRoot(gitCwd) ?? gitCwd;
2062
+ // Issue #466: ONE definition, shared with the head-state record's key — the
2063
+ // lock, the write and the clear can then never name different repositories.
2064
+ const lockKey = headStateRepoRoot();
2065
+ // Issue #465 (b): refuse a dispatch whose repository is held by a run that
2066
+ // is terminal on paper but never settled — the settle is the only releaser
2067
+ // of this lock (#460 §1.1), so waiting for it never ends. Checked BEFORE the
2068
+ // chain link is installed and before any wait, so the refusal is immediate
2069
+ // and the caller gets a spawn failure naming the owner instead of a tool
2070
+ // call that hangs forever (measured: W460P-P10).
2071
+ const holderId = gitBranchLockOwners.get(lockKey);
2072
+ if (holderId && isStuckTerminalOwner(holderId)) {
2073
+ const holder = agents.get(holderId)!;
2074
+ const heldFor = Math.round((Date.now() - holder.completedAt!) / 1000);
2075
+ const workBranch = holder.workBranch ?? '(unknown)';
2076
+ // Issue #466 (dossier §7): the second half of this message must not outlive
2077
+ // #465's own world. Post-#466 the boot DOES repair a provable orphan (the
2078
+ // head-state table's row 7), so "restart clears it, restore the base by
2079
+ // hand" is false for exactly the case this refusal names — the lock is the
2080
+ // restart's business, the trailer is the base's. The manual commands stay,
2081
+ // but only for the needs-manual rows (dirty tree, unreadable record).
2082
+ const reason = sanitizeErrorMessage(
2083
+ `gitMode 'branch' refused: this repository is locked by run ${holderId}, ` +
2084
+ `which has been terminal (${holder.status}${holder.error ? `: ${holder.error}` : ''}) ` +
2085
+ `for ${heldFor}s but has not settled — its SDK session is still held, so the ` +
2086
+ `branch lock cannot be released while it may still write. The work branch ` +
2087
+ `${workBranch} is still checked out; this process keeps the repository on it ` +
2088
+ `for the rest of its life, and only a restart releases the lock. That restart ` +
2089
+ `is also the repair: at the next boot the recorded base is restored — when the ` +
2090
+ `owner is provably dead, HEAD is exactly ${workBranch} and the working tree is ` +
2091
+ `clean — and ${workBranch} is KEPT with the run's commits. If the boot cannot ` +
2092
+ `repair it (uncommitted changes in the tree, or an unreadable record) it names ` +
2093
+ `the reason and keeps the record; the tree then needs the manual steps — ` +
2094
+ `git stash push -u -m "brl-subagent interrupted work" && ` +
2095
+ `git checkout <recorded base> — and ${workBranch} stays until its work is reviewed.`,
2096
+ effectiveCwd,
2097
+ );
2098
+ // Mirror the branch-setup-throw path below: the agent record was already
2099
+ // persisted as 'running' above, so a refusal that only THROWS leaves a
2100
+ // 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);
2109
+ throw new Error(reason);
2110
+ }
2111
+ // Issue #465 (d): release the process-wide spawn queue BEFORE the per-repo
2112
+ // wait below — that wait is bounded by another run's lifetime, so holding
2113
+ // the queue through it blocks every spawn in the process, not just this
2114
+ // repository's. The git chain itself is unchanged: this spawn still cannot
2115
+ // touch the working tree until the lock is handed over.
2116
+ releaseSpawnQueue();
1576
2117
  const prev = gitBranchLocks.get(lockKey) ?? Promise.resolve();
1577
2118
  let release!: () => void;
1578
2119
  const gate = new Promise<void>(r => { release = r; });
1579
2120
  const entry = prev.then(() => gate);
1580
2121
  gitBranchLocks.set(lockKey, entry);
1581
2122
  await prev;
2123
+ gitBranchLockOwners.set(lockKey, id);
1582
2124
  releaseGitLock = () => {
1583
2125
  // Delete the map entry ONLY if we are still the head of the chain — a
1584
- // queued spawn behind us replaced the entry with its own.
2126
+ // queued spawn behind us replaced the entry with its own. The owner is
2127
+ // held to the same rule: a stale release must not disown the new holder
2128
+ // (that would turn the next dispatch's refusal back into a silent wait).
1585
2129
  if (gitBranchLocks.get(lockKey) === entry) gitBranchLocks.delete(lockKey);
2130
+ if (gitBranchLockOwners.get(lockKey) === id) gitBranchLockOwners.delete(lockKey);
1586
2131
  release();
1587
2132
  };
1588
2133
 
1589
2134
  try {
2135
+ // Issue #466 (ADR 0026 D4): BEFORE the dirty check — an unresolved record
2136
+ // is the more specific fact, and a tree left on a dead run's branch would
2137
+ // otherwise only produce "working tree has uncommitted changes" (or, when
2138
+ // clean, a NEW branch based on the orphan: exactly the silent wrong base
2139
+ // this issue is about).
2140
+ //
2141
+ // Dossier §7 order: #465's refusal above is the FIRST gate and it wins,
2142
+ // because a wedged owner is a live process that may still write (and the
2143
+ // record it wrote names itself as ALIVE, so this guard would decline to
2144
+ // act anyway). This is the SECOND gate, and it fires only for a record
2145
+ // whose owner is NOT alive — `unresolvedHeadStateRefusal` returns
2146
+ // undefined for a live owner (M12).
2147
+ const unresolved = unresolvedHeadStateRefusal(lockKey);
2148
+ if (unresolved) throw new Error(unresolved);
2149
+
1590
2150
  // C1: isolation is only real when the base tree is clean. A dirty tree
1591
2151
  // would ride onto the work branch, get clobbered by the agent's writes,
1592
2152
  // and leak back into the base working tree on switch — refuse loudly.
@@ -1597,15 +2157,48 @@ export async function spawnBackgroundSession(
1597
2157
  );
1598
2158
  }
1599
2159
  headState = getHeadState(gitCwd);
1600
- const branchResult = createWorkBranch(gitCwd, headState.sha);
2160
+ // Issue #466 (D1): the durable record is written INSIDE the lock, after
2161
+ // the dirty check and BEFORE the branch exists — the write-ahead property
2162
+ // that makes a crash in `createWorkBranch` (and in the teardown window)
2163
+ // repairable. The name is minted here so the record can name the branch.
2164
+ workBranchName = newWorkBranchName();
2165
+ if (!writeHeadState({
2166
+ version: HEAD_STATE_VERSION,
2167
+ repoRoot: lockKey,
2168
+ runId: id,
2169
+ kind: 'background',
2170
+ base: headState,
2171
+ workBranch: workBranchName,
2172
+ owner,
2173
+ createdAt: new Date().toISOString(),
2174
+ })) {
2175
+ // A store failure must never refuse a run (same discipline as the
2176
+ // registry): the run proceeds, only its crash-recoverability degrades.
2177
+ log.warn('headState record could not be written — an interrupted run will name no base', {
2178
+ agentId: id,
2179
+ workBranch: workBranchName,
2180
+ });
2181
+ }
2182
+ const branchResult = createWorkBranch(gitCwd, headState.sha, workBranchName);
1601
2183
  if (branchResult.ok) {
1602
- workBranchName = branchResult.branch;
2184
+ // Issue #465 (b): stamp the work branch on the DURABLE record, not only
2185
+ // in this closure. `agent.result.gitBranch` is written at settle, which
2186
+ // is exactly what a wedged run never does — and a live-only field would
2187
+ // die with the process that needs to name it. (#466 mints the name
2188
+ // above, so the created branch IS `workBranchName`.)
2189
+ agent.workBranch = workBranchName;
2190
+ persistAgent(agent);
1603
2191
  log.info('Created work branch for background agent', {
1604
2192
  branch: workBranchName,
1605
2193
  base: headState.branch,
1606
2194
  agentId: id,
1607
2195
  });
1608
2196
  } else {
2197
+ // Nothing was created, so there is nothing to repair: clear the record
2198
+ // and drop the name, or cleanupWorkBranch would act on a branch that
2199
+ // never existed.
2200
+ clearHeadState(lockKey);
2201
+ workBranchName = undefined;
1609
2202
  throw new Error(`createWorkBranch failed: ${branchResult.error}`);
1610
2203
  }
1611
2204
  } catch (err) {
@@ -1614,17 +2207,13 @@ export async function spawnBackgroundSession(
1614
2207
  // (get_subagent_result would otherwise report 'running' forever).
1615
2208
  releaseGitLock?.();
1616
2209
  releaseGitLock = undefined;
1617
- // Sanitize ONCE and reuse for the status update and the thrown error.
2210
+ // Sanitize ONCE and reuse for the terminal write and the thrown error.
1618
2211
  const sanitizedError = sanitizeErrorMessage((err as Error).message, effectiveCwd);
1619
- try {
1620
- updateAgentStatus(id, 'failed',
1621
- `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
1622
- // Issue #98: the refused spawn is a failure — finalize the run entry so
1623
- // no zombie 'running' entry survives (lockstep with the record flip).
1624
- finalizeRunEntry('failed',
1625
- `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
1626
- transcript.completeTranscript(id, 'failed');
1627
- } catch { /* ignore */ }
2212
+ // Issue #98: the refused spawn is a failure — flip the record and finalize
2213
+ // the run entry so no zombie 'running' entry survives (lockstep, one
2214
+ // shared sequence with both pre-flight refusals).
2215
+ markBranchSpawnFailed(
2216
+ `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
1628
2217
  throw new Error(
1629
2218
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}. ` +
1630
2219
  `Refusing to spawn the background agent unisolated.`,
@@ -1633,82 +2222,6 @@ export async function spawnBackgroundSession(
1633
2222
  }
1634
2223
  }
1635
2224
 
1636
- // Branch teardown — commit the agent's work (so the diff is real), capture
1637
- // the diff, switch back to the original branch, delete the work branch, and
1638
- // release the per-repo git lock. Runs on EVERY settle path. C1: agents
1639
- // rarely commit, so captureDiff(base...HEAD) alone would be empty and the
1640
- // uncommitted edits would leak into the base working tree on switch —
1641
- // commitAll first makes the diff real and the switch clean.
1642
- const cleanupWorkBranch = (): { gitBranch?: string; gitDiff?: string } => {
1643
- if (gitCleanupDone || !workBranchName || !headState) return {};
1644
- gitCleanupDone = true;
1645
- const info: { gitBranch?: string; gitDiff?: string } = { gitBranch: workBranchName };
1646
- // The lock MUST be released on every exit path — early returns included.
1647
- try {
1648
- try {
1649
- const stillOnOurBranch = getCurrentBranch(gitCwd) === workBranchName;
1650
- if (!stillOnOurBranch) {
1651
- log.warn(`cleanupWorkBranch: tree moved off ${workBranchName} — skipping switch/delete`, {
1652
- agentId: id,
1653
- });
1654
- return info;
1655
- }
1656
- } catch (err) {
1657
- log.warn(`getCurrentBranch failed during cleanup for background agent ${id}`, {
1658
- error: (err as Error).message,
1659
- });
1660
- return info;
1661
- }
1662
- try {
1663
- // C1: commit the agent's work so captureDiff sees it. If no identity is
1664
- // configured, fall back to capturing the working-tree diff directly.
1665
- const dirty = hasUncommittedChanges(gitCwd);
1666
- if (dirty) {
1667
- const commitResult = commitAll(gitCwd, `brl-subagent ${id}: background work`);
1668
- if (commitResult.ok) {
1669
- log.info('Committed background agent work on work branch', {
1670
- sha: commitResult.sha,
1671
- branch: workBranchName,
1672
- agentId: id,
1673
- });
1674
- } else {
1675
- log.warn(`commitAll failed for background agent ${id} — capturing working diff`, {
1676
- error: commitResult.error,
1677
- });
1678
- const workingDiff = captureWorkingDiff(gitCwd);
1679
- if (workingDiff) info.gitDiff = workingDiff;
1680
- }
1681
- }
1682
- const diffResult = captureDiff(gitCwd, headState.sha);
1683
- if (diffResult.ok && diffResult.diff.trim()) {
1684
- // Merge committed + working diffs — either can exist alone.
1685
- info.gitDiff = info.gitDiff
1686
- ? `${info.gitDiff}\n${diffResult.diff}`
1687
- : diffResult.diff;
1688
- }
1689
- } catch (err) {
1690
- log.warn(`captureDiff failed for background agent ${id}`, { error: (err as Error).message });
1691
- }
1692
- try {
1693
- const restoreResult = restoreHead(gitCwd, headState);
1694
- if (!restoreResult.ok) {
1695
- log.warn(`restoreHead failed for background agent ${id}`, { error: restoreResult.error });
1696
- }
1697
- } catch (err) {
1698
- log.warn(`restoreHead failed for background agent ${id}`, { error: (err as Error).message });
1699
- }
1700
- try {
1701
- deleteBranch(gitCwd, workBranchName);
1702
- } catch (err) {
1703
- log.warn(`deleteBranch failed for background agent ${id}`, { error: (err as Error).message });
1704
- }
1705
- } finally {
1706
- releaseGitLock?.();
1707
- releaseGitLock = undefined;
1708
- }
1709
- return info;
1710
- };
1711
-
1712
2225
  // Issue #376 (audit D8): the aborted settle path is reached from BOTH
1713
2226
  // handlers — the .then (probe contract: an abort RESOLVES the prompt) and the
1714
2227
  // .catch (the prompt rejects while the agent is already 'stopped'). Both must
@@ -1744,15 +2257,22 @@ export async function spawnBackgroundSession(
1744
2257
  // Issue #122: a timed-out run burned tokens — record the real usage
1745
2258
  // (the git-diff block above must not leave the empty fallback).
1746
2259
  recordSessionUsage();
2260
+ // Issue #31: capture the final output while the session is still live, then
2261
+ // release the ref on the terminal path (memory retention; the poller treats
2262
+ // a nulled ref on a terminal agent as expected).
2263
+ //
2264
+ // Issue #453 [c 4]: the CAPTURE now PRECEDES the record. These fields are the
2265
+ // terminal entry's payload, and after a deadline stop this call writes the
2266
+ // AMENDMENT — so output produced after the deadline (the child kept running
2267
+ // until the abort landed, and the SDK may still deliver the final turn) must
2268
+ // be in `agent.finalOutput` by the time the amendment reads it. It used to
2269
+ // finalize first, which persisted the pre-deadline (usually empty) output.
2270
+ captureAndReleaseSession();
1747
2271
  // Issue #120 (Track 1): agent.error carries the reason when the stop was a
1748
2272
  // deadline timeout ('Timed out after Xms' → 'timeout'); a user cancel
1749
2273
  // (stop_subagent) sets no error, so fall back to the honest user-abort
1750
2274
  // stamp (→ 'aborted') instead of the old ambiguous 'Aborted or timed out'.
1751
2275
  finalizeRunEntry('failed', agent.error ?? SUBAGENT_ABORTED_MESSAGE, { stopReason });
1752
- // Issue #31: capture the final output while the session is still live,
1753
- // then release the ref on the terminal path (memory retention; the poller
1754
- // treats a nulled ref on a terminal agent as expected).
1755
- captureAndReleaseSession();
1756
2276
  };
1757
2277
 
1758
2278
  // Issue #53: the settle handlers (.then/.catch below) run in promise
@@ -1823,6 +2343,145 @@ export async function spawnBackgroundSession(
1823
2343
  // The session will run independently
1824
2344
  // F27: wrap in the task-as-data fence — the user message is DATA, not
1825
2345
  // instructions (see SUBAGENT_INSTRUCTIONS Task Boundary).
2346
+
2347
+ /**
2348
+ * The ONE place a background deadline is created — and its written contract
2349
+ * (issue #453, ADR 0023).
2350
+ *
2351
+ * OWNERSHIP. The session-manager owns the deadline on every path (explicit
2352
+ * timeout and the 30 m default); no caller arms or clears one. It is installed
2353
+ * before `prompt()`, so no statement anywhere after this call — a caller throw
2354
+ * included — can leave the run unbounded. The only thing that clears it is the
2355
+ * run's own settlement.
2356
+ *
2357
+ * WHAT THE DEADLINE OWNS: nothing that outlives the call. The deadline owns no
2358
+ * filesystem or git resource, waits for no settle, never prunes the run's
2359
+ * session dir and never releases the branch lock; ONLY A SETTLE DOES. What it
2360
+ * does is bounded and idempotent: flip the agent to `stopped` (which also sets
2361
+ * `completedAt`, so the caller's poller releases the live row on its next
2362
+ * tick), note the transcript, attempt ONE cooperative abort, and write the
2363
+ * classification SNAPSHOT (`failed` + `timeout`, `prune: false`).
2364
+ *
2365
+ * ORDERING IS THE CONTRACT. status → abort → snapshot. A throwing status or
2366
+ * transcript write must never leave the record saying 'stopped' while the child
2367
+ * keeps running, and a throwing append must never suppress the abort — each
2368
+ * step is contained and the abort sits between the other two. The status flip
2369
+ * stays BEFORE the abort because the settle classifies the run from it.
2370
+ *
2371
+ * TIME ORIGIN. The two arguments are deliberately separate: `budgetMs` is the
2372
+ * run's budget and is the ONLY value the reason may name; `delayMs` is the
2373
+ * REMAINDER still owed at arm time (the budget is anchored at record creation).
2374
+ * One argument for both is the defect this replaced: the timer fired at
2375
+ * arm + budget (drifting past the displayed `startedAt + timeoutMs`), and using
2376
+ * the remainder as the reason would truncate the budget a user asked for.
2377
+ *
2378
+ * STATED LIMITS (unchanged, and in the CHANGELOG): the abort is COOPERATIVE. A
2379
+ * prompt that ignores it keeps running; its run then keeps its session dir, its
2380
+ * branch lock until process exit, and no registry entry (the terminal snapshot
2381
+ * retires that claim). Nothing here can force it, and nothing here pretends to.
2382
+ */
2383
+ const armDeadline = (budgetMs: number, delayMs: number): ReturnType<typeof setTimeout> =>
2384
+ setTimeout(() => {
2385
+ if (agent.completedAt) return; // already settled — nothing to abort
2386
+ const reason = `Timed out after ${budgetMs}ms`;
2387
+ let bookkeepingFailure: unknown;
2388
+ try {
2389
+ updateAgentStatus(id, 'stopped', reason);
2390
+ transcript.completeTranscript(id, 'stopped');
2391
+ } catch (err) {
2392
+ bookkeepingFailure = err;
2393
+ }
2394
+ // Independent of the bookkeeping above (#448) — exactly one abort attempt.
2395
+ try {
2396
+ session.abort().catch((err: Error) => {
2397
+ // Abort can reject if the session is mid-dispose; the status flip
2398
+ // above is already recorded, so this is non-fatal — but a rejected
2399
+ // abort must not be silent (#448 review nit).
2400
+ log.warn(`spawnBackgroundSession: abort rejected for ${id}`, { error: err.message });
2401
+ });
2402
+ } catch (err) {
2403
+ // abort() threw synchronously — a timer callback must never throw
2404
+ // uncaught (that would crash the host process).
2405
+ log.warn(`spawnBackgroundSession: abort failed to start for ${id}`, {
2406
+ error: (err as Error).message,
2407
+ });
2408
+ }
2409
+ // Issue #453: the durable classification SNAPSHOT. `timeout` is the run
2410
+ // vocabulary's existing category (there is no `stopped` status for a run —
2411
+ // `running | done | failed`), and `prune: false` is what keeps a
2412
+ // still-writing SDK session's directory alive. Contained: a failed append
2413
+ // must not escape the timer (it would kill the host), and it must NOT undo
2414
+ // the abort above — `entryWritten` stays false, so the settle still writes
2415
+ // the terminal record when (if) it arrives.
2416
+ try {
2417
+ // `snapshot` is assigned from the RETURNED entry, i.e. only after the
2418
+ // append resolved — this is what makes the late settle an amendment
2419
+ // rather than a second classification.
2420
+ snapshot = finalizeRunEntry('failed', reason, {
2421
+ stopReason: 'aborted',
2422
+ errorCategory: 'timeout',
2423
+ prune: false,
2424
+ });
2425
+ } catch (err) {
2426
+ log.warn(`spawnBackgroundSession: deadline record write failed for ${id}`, {
2427
+ error: (err as Error).message,
2428
+ });
2429
+ }
2430
+ if (bookkeepingFailure) {
2431
+ // Surfaced through the log (the same audit surface the settle paths
2432
+ // use) — never absorbed into silence.
2433
+ log.warn(`spawnBackgroundSession: deadline bookkeeping failed for ${id}`, {
2434
+ error:
2435
+ bookkeepingFailure instanceof Error
2436
+ ? bookkeepingFailure.message
2437
+ : String(bookkeepingFailure),
2438
+ });
2439
+ }
2440
+ }, delayMs);
2441
+
2442
+ // Issue #453 (ADR 0023, decision 1): ONE owner. This function arms the run's
2443
+ // deadline on EVERY path — the explicit timeout when there is one, else the
2444
+ // 30 m default — and no caller arms a second one (`deadlineOwner` is gone with
2445
+ // the caller's timer). It is armed HERE, before prompt(), so the run is
2446
+ // bounded even when prompt() throws synchronously (the catch below clears it).
2447
+ //
2448
+ // `effectiveBackgroundBudget` is the single definition of the default and of
2449
+ // the normalization (never re-spelled here): a raw value that is 0, negative,
2450
+ // NaN, Infinity or >= 2^31 means "no explicit timeout", so the default applies
2451
+ // (issue #240 — never an instant kill) and an explicit 45 m is honored verbatim
2452
+ // (it is not a ceiling).
2453
+ //
2454
+ // Issue #453 / ADR 0023 decision 5: the budget is anchored at RECORD CREATION.
2455
+ // `startedAtMs` is the agent record's own clock (epoch ms — the same field the
2456
+ // monitor turns into `deadlineAt`), and the setup between that line and here
2457
+ // (transcript start, record persist, branch setup, a branch-lock wait) is time
2458
+ // the run has already spent, so it is subtracted. `Math.max(0, …)` is required:
2459
+ // a negative remainder must fire immediately, not overflow. `normalizeTimeout`
2460
+ // is the WRONG path for a remainder — it maps 0 or negative to "no timeout",
2461
+ // which would silently disarm a run that is already over budget.
2462
+ deadlineHandle = armDeadline(budgetMs, Math.max(0, budgetMs - (Date.now() - startedAtMs)));
2463
+
2464
+ // Issue #447: the ACCEPTANCE marker — ONE write, immediately before the
2465
+ // prompt, that turns `acceptedAt: null` into a timestamp on both durable
2466
+ // records (run entry + registry entry, in lockstep through the single
2467
+ // `persistRunRecord` choke point). Past this line a run that dies is
2468
+ // genuinely "started, outcome unknown" (#439); before it, it is provably
2469
+ // never-started. A run whose acceptance cannot be recorded must NOT start —
2470
+ // otherwise the residue problem returns — so a throw here cleans up and
2471
+ // rethrows instead of prompting.
2472
+ run.acceptedAt = new Date().toISOString();
2473
+ try {
2474
+ persistRunRecord(pi, run, "background");
2475
+ } catch (err) {
2476
+ // The stamp above never became durable, so the in-memory value must not ride
2477
+ // into the terminal record this cleanup writes: the entry would claim
2478
+ // `acceptedAt=<ISO>` while its message says the prompt was never issued
2479
+ // (2026-11-07 review). Back to the creation sentinel before settling.
2480
+ run.acceptedAt = null;
2481
+ failPreStart(neverIssued(err));
2482
+ throw err;
2483
+ }
2484
+
1826
2485
  // NOTE: if prompt() throws SYNCHRONOUSLY, the .then/.catch below never
1827
2486
  // attach and cleanupWorkBranch would never run — catch here so the work
1828
2487
  // branch is not orphaned (it is a real filesystem branch).
@@ -1830,50 +2489,17 @@ export async function spawnBackgroundSession(
1830
2489
  try {
1831
2490
  runPromise = session.prompt(wrapTask(params.task));
1832
2491
  } catch (err) {
1833
- cleanupWorkBranch();
1834
2492
  // Issue #98 (review F1): a synchronous prompt() throw never reaches the
1835
2493
  // settle handlers — finalize the run entry so no zombie 'running' entry
1836
2494
  // survives (findSpawnRunById would otherwise resolve and retry a run that
1837
- // never started).
1838
- finalizeRunEntry('failed', sanitizeErrorMessage((err as Error).message, effectiveCwd));
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));
1839
2498
  throw err;
1840
2499
  }
1841
2500
 
1842
- // W3 (issue #28): per-agent deadline — abort the session when exceeded.
1843
- // Armed immediately after the prompt call so in-prompt preflight (auth
1844
- // check, model resolution) counts toward the deadline; the abort lands in
1845
- // the .then below as an aborted run (probe contract). We pre-set the status
1846
- // so the .then keeps 'stopped' with the timeout reason recorded. The raw
1847
- // value is normalized here (issue #240): a raw >=2^31 or Infinity would make
1848
- // Node fire the timer at ~1ms (instant kill), so normalizeTimeout maps it to
1849
- // undefined. An explicit timeout is HONORED verbatim (no ceiling); only the
1850
- // no-timeout fallback uses the 30m background default. The `params.timeout`
1851
- // guard below keeps this timer unarmed on the no-timeout path, where the
1852
- // index.ts deadline timer owns the no-timeout default (no redundant timer).
1853
- let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
1854
- if (params.timeout && params.timeout > 0) {
1855
- timeoutHandle = setTimeout(() => {
1856
- try {
1857
- if (agent.completedAt) return; // already settled — nothing to abort
1858
- updateAgentStatus(id, 'stopped', `Timed out after ${params.timeout}ms`);
1859
- transcript.completeTranscript(id, 'stopped');
1860
- session.abort().catch(() => {
1861
- // Abort can reject if the session is mid-dispose; the status flip
1862
- // above is already recorded, so this is non-fatal.
1863
- });
1864
- } catch (err) {
1865
- // Timer callbacks must never throw uncaught — that crashes the host
1866
- // process. updateAgentStatus/completeTranscript can throw (persist
1867
- // fs failure, transcript deleted); the abort is best-effort.
1868
- log.warn(`spawnBackgroundSession: timeout handler error for ${id}`, {
1869
- error: (err as Error).message,
1870
- });
1871
- }
1872
- }, normalizeTimeout(params.timeout) ?? DEFAULT_BACKGROUND_DEADLINE_MS);
1873
- }
1874
-
1875
2501
  runPromise.then(() => {
1876
- if (timeoutHandle) clearTimeout(timeoutHandle);
2502
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1877
2503
  try {
1878
2504
  // Probe contract (sdk-abort-contract.test.ts): prompt() RESOLVES on abort
1879
2505
  // — the SDK's runWithLifecycle catches the AbortError and converts it into
@@ -1881,8 +2507,23 @@ export async function spawnBackgroundSession(
1881
2507
  // HERE, not in .catch. Two signals distinguish stop from completion:
1882
2508
  // 1. stopAgent pre-set status to 'stopped' before calling abort();
1883
2509
  // 2. the last assistant message carries stopReason "aborted".
1884
- const lastAssistant = [...(session.messages ?? [])].reverse().find(m => m.role === 'assistant');
2510
+ //
2511
+ // Issue #449: the projection is read ONCE here — `evidence` below is
2512
+ // derived from the same read the stopReason comes from. The SDK can remove
2513
+ // the only assistant message from this projection before settling (a
2514
+ // recoverable-length omission: `_omitRecoveryAttempt`, then a compaction
2515
+ // that never runs on a young branch), so "no assistant message" is real
2516
+ // evidence about the settle and not a read failure.
2517
+ const projectedMessages = session.messages;
2518
+ const lastAssistant = [...(projectedMessages ?? [])].reverse().find(m => m.role === 'assistant');
1885
2519
  const terminalStopReason = lastAssistant?.stopReason;
2520
+ // Issue #449: "absent" means exactly one thing — an array that was READ and
2521
+ // holds no assistant message. A missing/unreadable projection is "unknown"
2522
+ // (a throwing getter never reaches here; the settle catch-all owns it), and
2523
+ // any assistant message is "present" whatever it contains.
2524
+ const assistantEvidence: AssistantEvidence = Array.isArray(projectedMessages)
2525
+ ? projectedMessages.some((m) => m.role === 'assistant') ? 'present' : 'absent'
2526
+ : 'unknown';
1886
2527
  const aborted = agent.status === 'stopped' || terminalStopReason === 'aborted';
1887
2528
  if (aborted) {
1888
2529
  // Session was aborted — mark stopped. If stopAgent already flipped the
@@ -1911,16 +2552,29 @@ export async function spawnBackgroundSession(
1911
2552
  // classifyError for the provider-error case.
1912
2553
  const providerErrorMessage =
1913
2554
  lastAssistant?.errorMessage ?? session.state?.errorMessage;
1914
- const outcome = classifyTerminalOutcome(terminalStopReason, providerErrorMessage);
2555
+ const outcome = classifyTerminalOutcome(terminalStopReason, providerErrorMessage, {
2556
+ assistantEvidence,
2557
+ });
1915
2558
 
1916
2559
  if (outcome.status === 'failed') {
1917
2560
  // Mid-run provider death / truncation / incomplete turn.
1918
2561
  agent.status = 'failed';
1919
2562
  agent.completedAt = Date.now();
1920
- const sanitizedError = sanitizeErrorMessage(
1921
- providerErrorMessage ?? defaultTerminalMessage(terminalStopReason),
1922
- effectiveCwd,
1923
- );
2563
+ // Issue #449: `assistantEvidence === 'absent'` is exactly the case this
2564
+ // classifier's formerly-default arm now fails on (a zero-assistant
2565
+ // projection has no last assistant, so `terminalStopReason` is
2566
+ // undefined). The omitted message cannot be recovered, so the reason
2567
+ // states the observation and offers truncation only as a possibility —
2568
+ // it never asserts truncation as fact. It also WINS over a stale
2569
+ // `session.state.errorMessage`, which this branch used to prefer; the
2570
+ // stale text may be appended, never substituted.
2571
+ const failureReason =
2572
+ assistantEvidence === 'absent'
2573
+ ? providerErrorMessage
2574
+ ? `${NO_ASSISTANT_OUTPUT_REASON}\n${providerErrorMessage}`
2575
+ : NO_ASSISTANT_OUTPUT_REASON
2576
+ : (providerErrorMessage ?? defaultTerminalMessage(terminalStopReason));
2577
+ const sanitizedError = sanitizeErrorMessage(failureReason, effectiveCwd);
1924
2578
  agent.error = sanitizedError;
1925
2579
  const gitInfo = cleanupWorkBranch();
1926
2580
  agent.result = {
@@ -1995,7 +2649,7 @@ export async function spawnBackgroundSession(
1995
2649
  markTerminalBestEffort('completed');
1996
2650
  }
1997
2651
  }).catch((err: Error) => {
1998
- if (timeoutHandle) clearTimeout(timeoutHandle);
2652
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1999
2653
  try {
2000
2654
  // W4: capture partial work + discard the work branch on failure — a failed
2001
2655
  // background agent may still have produced reviewable changes.
@@ -2064,6 +2718,6 @@ export async function spawnBackgroundSession(
2064
2718
 
2065
2719
  return agent;
2066
2720
  } finally {
2067
- resolveNext();
2721
+ releaseSpawnQueue();
2068
2722
  }
2069
2723
  }