brl-subagent 2.7.0 → 2.8.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.
@@ -4,7 +4,8 @@ import { basename, dirname, join, resolve } from 'path';
4
4
  import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync } from 'fs';
5
5
  import type { Dirent } from 'fs';
6
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';
7
+ import { EMPTY_USAGE, classifyError, classifyTerminalOutcome, isProviderError, coherentFailureReason, SUBAGENT_ABORTED_MESSAGE, NO_ASSISTANT_OUTPUT_REASON, PROMPT_NEVER_ISSUED_MESSAGE } from './types';
8
+ import type { AssistantEvidence } from './types';
8
9
  import { accumulateUsage } from './runner';
9
10
  import * as eventBus from './event-bus';
10
11
  import * as transcript from './transcript';
@@ -12,13 +13,15 @@ import { createEvent } from './event-bus';
12
13
  import { assertSafeAgentId, sanitizeErrorMessage } from './sanitize';
13
14
  import { wrapTask } from './prompt';
14
15
  import { createLogger } from './logging';
15
- import { getCurrentBranch, getHeadState, restoreHead, createWorkBranch, captureDiff, deleteBranch, hasUncommittedChanges, getRepoRoot, commitAll, captureWorkingDiff } from './git';
16
+ import { getCurrentBranch, getHeadState, restoreHead, createWorkBranch, newWorkBranchName, captureDiff, deleteBranch, hasUncommittedChanges, getRepoRoot, commitAll, captureWorkingDiff } from './git';
16
17
  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';
18
+ import { clearHeadState, readHeadState, writeHeadState, HEAD_STATE_VERSION } from './headstate';
19
+ import { effectiveBackgroundBudget } from './validate';
20
+ import { currentProcessOwner, classifyOwner, defaultRecoveryDeps } from './recovery';
21
+ import { persistRunRecord, listInflightRuns, clearInflightRun, type InflightRun } from './run-registry';
20
22
  import { isTransportRetryable } from './transport-retry';
21
23
  import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
24
+ import { buildEngineeringBarSection } from './engineering-bar';
22
25
 
23
26
  const log = createLogger('brl-subagent');
24
27
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
@@ -34,6 +37,61 @@ var spawnQueue: Promise<void> = Promise.resolve();
34
37
  // working tree and must serialize (issue #224).
35
38
  const gitBranchLocks = new Map<string, Promise<void>>();
36
39
 
40
+ /**
41
+ * Issue #465 (b): WHO holds each branch lock (run id). `gitBranchLocks` records
42
+ * only that a repository is locked — and a waiter that is refused (rather than
43
+ * left hanging) has to say whose run it is waiting on.
44
+ *
45
+ * Set once the lock is actually acquired, and cleared ONLY by the matching
46
+ * release: a queued spawn's chain entry may already have replaced ours, so an
47
+ * owner must never be deleted by a stale id. In-process state, like the lock
48
+ * itself — neither survives a restart, which is why a restart is the documented
49
+ * recovery from a wedged owner.
50
+ */
51
+ const gitBranchLockOwners = new Map<string, string>();
52
+
53
+ /**
54
+ * Issue #465 (b): how long a terminal-but-unsettled owner is given before later
55
+ * branch-mode dispatches are refused. 30 s is a measurement, not a guess: the
56
+ * cooperative settle lag after a deadline measured 88 ms (W460P-P6) plus the
57
+ * largest observed `cleanupWorkBranch` (commitAll + captureDiff + restoreHead +
58
+ * deleteBranch) — orders of magnitude below this — while a human staring at a
59
+ * hung dispatch deserves an answer well inside a minute. The grace bounds only
60
+ * the false-positive window; after the first refusal it changes nothing.
61
+ */
62
+ const DEFAULT_STUCK_OWNER_GRACE_MS = 30_000;
63
+ let stuckOwnerGraceMs = DEFAULT_STUCK_OWNER_GRACE_MS;
64
+
65
+ /**
66
+ * TEST-ONLY: shorten the stuck-owner grace. A unit test cannot wait out the
67
+ * shipped 30 s, and the predicate's shape (not its constant) is what it pins.
68
+ */
69
+ export function __setStuckOwnerGraceMs(ms: number): void {
70
+ stuckOwnerGraceMs = ms;
71
+ }
72
+
73
+ /**
74
+ * Issue #465 (b): is `runId` a branch-lock owner that is terminal on paper but
75
+ * still holding its SDK session — i.e. the settle (the only releaser of the
76
+ * branch lock) never ran?
77
+ *
78
+ * `_sessionRef` is the clause that separates "settling" from "wedged": every
79
+ * settle path releases the lock in `cleanupWorkBranch` and only then clears the
80
+ * ref, so a run that is still reachable here has not begun its teardown. It is
81
+ * defence in depth rather than the only guard — `completedAt` plus the grace
82
+ * already covers the settle-in-flight window that a deadline opens (measured
83
+ * 88 ms, W460P-P6) — and removing it changes no verdict this tree can reach
84
+ * (the six settle paths order the release before the clear). It stays because
85
+ * the next change to that ordering must not silently turn a settling run into a
86
+ * refused one.
87
+ */
88
+ function isStuckTerminalOwner(runId: string): boolean {
89
+ const owner = agents.get(runId);
90
+ if (!owner?.completedAt) return false;
91
+ if (owner._sessionRef === undefined) return false;
92
+ return Date.now() - owner.completedAt >= stuckOwnerGraceMs;
93
+ }
94
+
37
95
  /**
38
96
  * TEST-ONLY: release every held git branch lock. The lock is normally held
39
97
  * for the agent's lifetime (released at settle), but tests that never settle
@@ -41,6 +99,7 @@ const gitBranchLocks = new Map<string, Promise<void>>();
41
99
  */
42
100
  export function __testResetGitBranchLocks(): void {
43
101
  gitBranchLocks.clear();
102
+ gitBranchLockOwners.clear();
44
103
  }
45
104
 
46
105
  // Robust UUID generation with fallback
@@ -503,7 +562,11 @@ export const RETRY_SCAN_WINDOW_DAYS = RETRY_SCAN_WINDOW_MS / (24 * 60 * 60 * 100
503
562
  /** The short form rendered by notices: the first 8 hex characters of a UUID. */
504
563
  const SHORT_AGENT_ID_RE = /^[0-9a-f]{8}$/i;
505
564
 
506
- const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
565
+ /**
566
+ * The single source of the retry-identity key set, shared with the scanner tests
567
+ * (`src/__tests__/json-scanner.test.ts`).
568
+ */
569
+ export const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
507
570
  'id',
508
571
  'dispatchId',
509
572
  'resumeOf',
@@ -637,8 +700,27 @@ function skipWhitespace(text: string, index: number): number {
637
700
  return i;
638
701
  }
639
702
 
640
- /** Read one JSON string starting at `start` (which must be `"`). */
641
- function readJsonStringAt(text: string, start: number): { value: string; end: number } {
703
+ /**
704
+ * Read one JSON string starting at `start`; returns the decoded `value` and the
705
+ * offset just past the closing quote. Offsets are UTF-16 code units.
706
+ *
707
+ * Contract (pinned by `src/__tests__/json-scanner.test.ts`, issue #428):
708
+ * - precondition: `start` is the `"` that opens the value.
709
+ * - never throws; `end` is always a number in
710
+ * `[start, max(start, text.length)]` (when `start` is past the end, it
711
+ * returns `start`).
712
+ * - unterminated string -> `end === text.length` and `value` is the raw
713
+ * remainder (D1): a corrupt record is skipped by the caller, never surfaced
714
+ * as an error.
715
+ * - the value is `JSON.parse`'s when it parses. When it does not (an invalid
716
+ * escape), the fallback returns the RAW text between the quotes with a
717
+ * correct `end` (D5) — best-effort: an invalid escape inside `"id"` yields a
718
+ * value `assertSafeAgentId` rejects, so the record leaves retry lineage.
719
+ * - an escape consumes exactly one following character, including `\\` and
720
+ * `\"`; a `"` reached after an escape is content, not a terminator.
721
+ * Exposed for tests; not part of the reader API (architecture-rules.test.ts).
722
+ */
723
+ export function readJsonStringAt(text: string, start: number): { value: string; end: number } {
642
724
  let i = start + 1;
643
725
  let escaped = false;
644
726
  while (i < text.length) {
@@ -667,8 +749,27 @@ function readJsonStringAt(text: string, start: number): { value: string; end: nu
667
749
  return { value: text.slice(start + 1), end: i };
668
750
  }
669
751
 
670
- /** Skip one JSON value (scalar, object, or array) without parsing it. */
671
- function skipJsonValue(text: string, start: number): number {
752
+ /**
753
+ * Skip one JSON value (scalar, object, or array) without parsing it; returns the
754
+ * offset just past the value. Offsets are UTF-16 code units.
755
+ *
756
+ * Contract (pinned by `src/__tests__/json-scanner.test.ts`, issue #428):
757
+ * - precondition: `start` is the value's FIRST character; the caller has
758
+ * already skipped whitespace (`scanTopLevelScalars` does, via `skipWhitespace`).
759
+ * - never throws; always returns a number in
760
+ * `[start, max(start, text.length)]` (when `start` is past the end, it
761
+ * returns `start`).
762
+ * - unterminated container or string -> `text.length` (D1: corrupt records are
763
+ * dropped upstream by `readAgentIdentity`, never surfaced as an error).
764
+ * - containers are depth-counted on a single pass, +1 for `{`/`[` and -1 for
765
+ * `}`/`]`; the counting is bracket-TYPE-AGNOSTIC, so `'[1}'` ends at 3.
766
+ * Strictness is `JSON.parse`'s job (D3).
767
+ * - the scalar branch scans to the first `,` or `}` or EOF — it does NOT stop
768
+ * at `]` (D4), so `'1]'` returns 2. Both call sites sit in an object's
769
+ * top-level value position, so `]` is unreachable on valid input.
770
+ * Exposed for tests; not part of the reader API (architecture-rules.test.ts).
771
+ */
772
+ export function skipJsonValue(text: string, start: number): number {
672
773
  if (text[start] === '"') return readJsonStringAt(text, start).end;
673
774
  if (text[start] === '{' || text[start] === '[') {
674
775
  let depth = 0;
@@ -708,8 +809,23 @@ function parseJsonScalar(raw: string): JsonScalar {
708
809
  * Extract top-level scalar fields from a record's JSON text. Nested values
709
810
  * (notably `result.messages` and `finalOutput`) are skipped, not parsed — the
710
811
  * reader only ever touches the six identity keys.
812
+ *
813
+ * Contract (pinned by `src/__tests__/json-scanner.test.ts`, issue #428):
814
+ * - never throws; a record with no leading `{` yields an empty map.
815
+ * - whitespace around the braces, keys, `:` and values is skipped with
816
+ * `/\s/` — deliberately WIDER than JSON's four whitespace characters, so a
817
+ * BOM- or NBSP-prefixed record is still read instead of silently vanishing
818
+ * from retry lineage (D2).
819
+ * - a wanted key holding a container is skipped, not read (the key stays
820
+ * absent); a wanted key holding a scalar is parsed with `parseJsonScalar`.
821
+ * - a non-wanted key's value is skipped with `skipJsonValue`, whole — a nested
822
+ * `"status"` or `"attempt"` inside `result.messages` is never mistaken for a
823
+ * top-level one.
824
+ * - a duplicate key keeps the last value; a malformed byte stops the scan
825
+ * rather than hanging it.
826
+ * Exposed for tests; not part of the reader API (architecture-rules.test.ts).
711
827
  */
712
- function scanTopLevelScalars(text: string, wanted: ReadonlySet<string>): Map<string, JsonScalar> {
828
+ export function scanTopLevelScalars(text: string, wanted: ReadonlySet<string>): Map<string, JsonScalar> {
713
829
  const out = new Map<string, JsonScalar>();
714
830
  let i = skipWhitespace(text, 0);
715
831
  if (text[i] !== '{') return out;
@@ -1121,6 +1237,42 @@ export async function steerAgent(id: string, message: string): Promise<Backgroun
1121
1237
  */
1122
1238
  export { transcriptPath as getTranscriptPath } from './transcript-path';
1123
1239
 
1240
+ /**
1241
+ * Issue #466 (ADR 0026 D4): the pre-flight refusal for a repository whose
1242
+ * durable head-state record is still unresolved and whose owner is NOT alive —
1243
+ * i.e. the boot could not repair it (a dirty tree, an unreadable record, a
1244
+ * failed restore, or a boot that never ran in this project).
1245
+ *
1246
+ * Returns the message, or undefined when the dispatch may proceed. Ordered
1247
+ * BEFORE the dirty check because an unresolved record is the more specific
1248
+ * fact: the tree is on a branch a dead run left behind, and only this record
1249
+ * names its base. A record with a corrupt shape, and a record whose owner is
1250
+ * ALIVE, never refuse — the first cannot be acted on by either side (L1/L2 of
1251
+ * the dossier), and a live owner may still be writing its own run.
1252
+ *
1253
+ * The message names the BRANCH, the BASE and the COMMANDS (never a path):
1254
+ * `sanitizeErrorMessage` neutralises the cwd and its parent downstream (#460 §4.2).
1255
+ */
1256
+ function unresolvedHeadStateRefusal(repoRoot: string): string | undefined {
1257
+ const read = readHeadState(repoRoot);
1258
+ if (read.state !== 'ok') return undefined;
1259
+ const record = read.record;
1260
+ if (classifyOwner(record.owner, defaultRecoveryDeps()) === 'alive') return undefined;
1261
+ const base = record.base.detached
1262
+ ? `detached HEAD at ${record.base.sha.slice(0, 8)}`
1263
+ : record.base.branch;
1264
+ const checkout = record.base.detached
1265
+ ? `git checkout --detach ${record.base.sha}`
1266
+ : `git checkout ${record.base.branch}`;
1267
+ return (
1268
+ `this repository still carries an unresolved branch-run state: the working tree was left on ` +
1269
+ `${record.workBranch} by an interrupted run whose recorded base is ${base}. ` +
1270
+ `Inspect it with \`git status\`, then restore the base by hand: ` +
1271
+ `git stash push -u -m "brl-subagent interrupted work" && ${checkout}. ` +
1272
+ `Keep ${record.workBranch} until its work is reviewed — it is the only copy.`
1273
+ );
1274
+ }
1275
+
1124
1276
  /**
1125
1277
  * Spawn a background session using pi's session API
1126
1278
  *
@@ -1170,6 +1322,20 @@ export async function spawnBackgroundSession(
1170
1322
  let resolveNext!: () => void;
1171
1323
  spawnQueue = new Promise<void>(r => { resolveNext = r; });
1172
1324
  await prev;
1325
+
1326
+ // Issue #465 (d): the queue's critical section is the pi API access below
1327
+ // (the dynamic import + createAgentSession), NOT the per-repo git wait
1328
+ // further down — which can last a whole run. The release is therefore
1329
+ // explicit AND idempotent: the branch block releases before it waits on
1330
+ // another run's repository, and the `finally` still releases on every other
1331
+ // exit path (measured before this: a healthy branch-mode run made an
1332
+ // unrelated non-git spawn stay PENDING for its entire duration).
1333
+ let spawnQueueReleased = false;
1334
+ const releaseSpawnQueue = (): void => {
1335
+ if (spawnQueueReleased) return;
1336
+ spawnQueueReleased = true;
1337
+ resolveNext();
1338
+ };
1173
1339
 
1174
1340
  try {
1175
1341
  const id = generateUUID();
@@ -1245,6 +1411,15 @@ export async function spawnBackgroundSession(
1245
1411
  if (params.resumeContext?.trim()) {
1246
1412
  sections.push(`\n<resume-context>\n${params.resumeContext.trim()}\n</resume-context>\n`);
1247
1413
  }
1414
+ // Issue #421: the project's engineering bar is the LAST section, so a retry's
1415
+ // resume preamble stays adjacent to the system prompt it qualifies. It is
1416
+ // injected here — not chosen by the conductor — so no preset selection can
1417
+ // drop it. Gated by the project flag (ADR 0019); `engineering-bar.ts` owns the
1418
+ // read, the failure warning and the framing, so this builder still
1419
+ // interpolates only the two caller fields pinned by the neutralization ratchet
1420
+ // in session-manager.test.ts.
1421
+ const barSection = buildEngineeringBarSection(effectiveCwd, log);
1422
+ if (barSection) sections.push(barSection);
1248
1423
  //
1249
1424
  // F25: ALWAYS build our own loader (even without a systemPrompt). If
1250
1425
  // resourceLoader is undefined, createAgentSession constructs its own
@@ -1309,6 +1484,11 @@ export async function spawnBackgroundSession(
1309
1484
  const attempt = params.attempt ?? 1;
1310
1485
  const owner = currentProcessOwner();
1311
1486
 
1487
+ // Issue #453 (decision 5): the run's budget, computed ONCE. The record's
1488
+ // `timeoutMs` (what the monitor displays as `deadlineAt`) and the armed timer
1489
+ // derive from the same value, so the display cannot drift from the timer.
1490
+ const budgetMs = effectiveBackgroundBudget(params.timeout);
1491
+
1312
1492
  // Create agent record
1313
1493
  const agent: BackgroundAgent = {
1314
1494
  id,
@@ -1317,6 +1497,11 @@ export async function spawnBackgroundSession(
1317
1497
  description: params.description || params.task.slice(0, 50),
1318
1498
  status: 'running',
1319
1499
  startedAt: Date.now(),
1500
+ // Issue #423: the EFFECTIVE budget (explicit timeout, else the 30m default),
1501
+ // stamped BEFORE persistAgent so the initial record already carries it — a
1502
+ // result/wake read after the spawn closure is gone must not fall back to
1503
+ // "unknown".
1504
+ timeoutMs: budgetMs,
1320
1505
  task: params.task,
1321
1506
  model: params.model || 'unknown',
1322
1507
  thinkingLevel: params.thinkingLevel || 'medium',
@@ -1360,6 +1545,12 @@ export async function spawnBackgroundSession(
1360
1545
  attempt,
1361
1546
  owner,
1362
1547
  recoveryPosture: params.recoveryPosture,
1548
+ // Issue #447: the acceptance marker starts `null` — the dispatch is
1549
+ // TRACKED from here on (agent record + registry entry) but the prompt has
1550
+ // not been issued. Only the write immediately above `session.prompt()`
1551
+ // turns it into a timestamp; a boot scan that finds `null` knows nothing
1552
+ // was started (a pre-upgrade record simply lacks the field instead).
1553
+ acceptedAt: null,
1363
1554
  };
1364
1555
  persistRunRecord(pi, run, "background");
1365
1556
 
@@ -1370,45 +1561,70 @@ export async function spawnBackgroundSession(
1370
1561
  //
1371
1562
  // U2 (D2) retention: this is the SINGLE terminal choke point for a background
1372
1563
  // 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;
1564
+ // provider-failed / aborted branches, the .catch stopped / failed branches, the
1565
+ // markTerminalBestEffort catch-all and (since #453) the deadline timer ALL land
1566
+ // here. The session-dir decision below therefore covers every settle path. The
1567
+ // index.ts poller crash notices are NOT settlements (they flip only the live UI
1568
+ // state and leave the run/agent record to this settle); an interrupted run (U1
1569
+ // boot-scan mark) never reaches this function and KEEPS its file (D3).
1570
+ //
1571
+ // Issue #453 (ADR 0023 decision 3): TWO once-only guards, not one.
1572
+ // - `entryWritten` — a terminal RECORD for this id is durable. The deadline
1573
+ // may write it first (a classification snapshot); every later write is then
1574
+ // a payload AMENDMENT of that snapshot, never a second classification.
1575
+ // - `pruned` — the session-dir decision has been made. Only a SETTLE makes it
1576
+ // (the deadline passes `prune: false`), and it is made even when the entry
1577
+ // already exists — otherwise a cooperative timeout would stop pruning.
1578
+ // Collapsing the two is the M4 mutant the dir-survives test kills.
1579
+ let entryWritten = false;
1580
+ let pruned = false;
1581
+ /**
1582
+ * The DEADLINE's classification snapshot — the amendment's base, and ONLY the
1583
+ * deadline ever sets it (see the arm site). A settle→settle re-entry (the
1584
+ * catch-all after a throwing handler) therefore still writes nothing, which is
1585
+ * the single-terminal-entry contract the old `runFinalized` guard enforced.
1586
+ */
1587
+ let snapshot: SubagentRun | undefined;
1588
+
1589
+ /**
1590
+ * This call's OWN classification. The retention/prune gate reads THIS — never
1591
+ * the snapshot's — because at the deadline a run looks like `timeout` (not
1592
+ * transport-retryable) while its true settle category may decide otherwise
1593
+ * (ADR 0023 decision 3).
1594
+ *
1595
+ * Issue #179 (D1/D2): the classifier's explicit category wins (it knows the
1596
+ * terminal stopReason); otherwise fall back to the legacy message-based
1597
+ * classification (refused spawns, sync throws, preflight rejections, the
1598
+ * catch-all) so no failure is ever left uncategorized.
1599
+ */
1600
+ const classifyFailure = (
1601
+ status: "done" | "failed",
1602
+ error?: string,
1603
+ terminal?: { errorCategory?: ErrorCategory },
1604
+ ): ErrorCategory | undefined =>
1605
+ status === "failed"
1606
+ ? terminal?.errorCategory ??
1607
+ (error
1608
+ ? classifyError({
1609
+ messages: [],
1610
+ usage: { ...EMPTY_USAGE },
1611
+ exitCode: 1,
1612
+ stderr: "",
1613
+ errorMessage: error,
1614
+ })
1615
+ : undefined)
1616
+ : undefined;
1617
+
1618
+ /** Returns the entry it appended (the terminal record or the amendment), if any. */
1381
1619
  const finalizeRunEntry = (
1382
1620
  status: "done" | "failed",
1383
1621
  error?: string,
1384
- terminal?: { stopReason?: string; errorCategory?: ErrorCategory },
1385
- ): void => {
1386
- if (runFinalized) return;
1387
- runFinalized = true;
1622
+ terminal?: { stopReason?: string; errorCategory?: ErrorCategory; prune?: boolean },
1623
+ ): SubagentRun | undefined => {
1388
1624
  const usage = agent.result?.usage ?? EMPTY_USAGE;
1389
1625
  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;
1626
+ // The TRUE category of THIS call — see the note on `classifyFailure`.
1627
+ const errorCategory = classifyFailure(status, error, terminal);
1412
1628
  // U2 (D2) prune + #404 retention. THE INVARIANT: the prune/mark decision
1413
1629
  // precedes the run-record write, and everything above it is pure — so no
1414
1630
  // throw between the decision and the write can leave a terminal run's session
@@ -1418,7 +1634,12 @@ export async function spawnBackgroundSession(
1418
1634
  // run that will be re-dispatched has a reader for the retained session, and
1419
1635
  // it is built from the values this record is about to carry, so the reader
1420
1636
  // and the retainer can never disagree.
1421
- if (!agent.interruptedAt) {
1637
+ //
1638
+ // Issue #453: gated on `pruned` (not on `entryWritten`) and skipped when the
1639
+ // CALLER asks (`prune: false` — the deadline). One flag for both would make a
1640
+ // successful deadline write suppress this decision (mutant M4).
1641
+ if ((terminal?.prune ?? true) && !pruned && !agent.interruptedAt) {
1642
+ pruned = true;
1422
1643
  // The CAPTURED dir — tests swap STORAGE_DIR per case, and a mid-run change
1423
1644
  // of root must never mis-target the delete or the marker.
1424
1645
  const sessionDir = agent._sessionFile ? dirname(agent._sessionFile) : backgroundSessionDir(id);
@@ -1435,6 +1656,39 @@ export async function spawnBackgroundSession(
1435
1656
  pruneSessionDir(id, sessionDir);
1436
1657
  }
1437
1658
  }
1659
+
1660
+ // Issue #453 (ADR 0023 decision 4): a second write is an AMENDMENT — the
1661
+ // deadline already wrote the classification, so only the PAYLOAD moves
1662
+ // (cost/usage/output/final detail). `status`, `errorCategory`, `stopReason`
1663
+ // and `errorMessage` are the snapshot's and are never rewritten: a late
1664
+ // settle's real usage must not re-open what the run WAS (that would be a
1665
+ // second classification claim — mutant M7).
1666
+ if (entryWritten) {
1667
+ // No snapshot => this is a settle RE-ENTRY (the settle already wrote the
1668
+ // record); nothing new to say. Only a deadline snapshot is amendable.
1669
+ if (!snapshot) return undefined;
1670
+ const amended: SubagentRun = {
1671
+ ...snapshot,
1672
+ turns: usage.turns,
1673
+ finishedAt: new Date().toISOString(),
1674
+ durationMs: Date.now() - startedAtMs,
1675
+ cost: usage.cost,
1676
+ tokensIn: usage.input,
1677
+ tokensOut: usage.output,
1678
+ outputSummary: finalOutput.slice(0, 200),
1679
+ fullOutput: finalOutput || undefined,
1680
+ };
1681
+ persistRunRecord(pi, amended);
1682
+ log.info("Background run amended after a late settle", {
1683
+ agentId: id,
1684
+ status: amended.status,
1685
+ errorCategory: amended.errorCategory,
1686
+ turns: usage.turns,
1687
+ tokensOut: usage.output,
1688
+ cost: usage.cost,
1689
+ });
1690
+ return amended;
1691
+ }
1438
1692
  // Issue #187: capture the RAW terminal reason BEFORE coercion. `finalTurnError`
1439
1693
  // means "the final turn was a PROVIDER error" (isProviderError); deriving it
1440
1694
  // from the COERCED reason would turn a missing/success reason into 'error' and
@@ -1472,6 +1726,10 @@ export async function spawnBackgroundSession(
1472
1726
  : run.originalParams,
1473
1727
  };
1474
1728
  persistRunRecord(pi, entry);
1729
+ // Issue #453: set only AFTER the append resolved. A throwing write therefore
1730
+ // leaves `entryWritten === false`, so a later settle still classifies the run
1731
+ // instead of amending a record that was never written (mutant M3).
1732
+ entryWritten = true;
1475
1733
  // Issue #179 (D6): the explicit settle line — the log's job is to record the
1476
1734
  // CLASSIFIED OUTCOME, which cwd alone can never convey.
1477
1735
  log.info("Background run settled", {
@@ -1483,10 +1741,180 @@ export async function spawnBackgroundSession(
1483
1741
  errorCategory,
1484
1742
  error: error ?? null,
1485
1743
  });
1744
+ return entry;
1745
+ };
1746
+
1747
+ // Issue #447: git teardown state + the teardown itself, declared BEFORE the
1748
+ // pre-start region (the closures do nothing at declaration time) so the ONE
1749
+ // pre-start cleanup below can reach them; the branch is only CREATED later,
1750
+ // in the `gitMode === 'branch'` block further down.
1751
+ let headState: HeadState | undefined;
1752
+ let workBranchName: string | undefined;
1753
+ let releaseGitLock: (() => void) | undefined;
1754
+ // Idempotency guard for cleanupWorkBranch: it must be safe to call from both
1755
+ // the normal settle path and the catch-all that runs when a settle step
1756
+ // throws FIRST (before its own cleanup call). Without this the second call
1757
+ // would re-restore/re-delete and log spurious warnings.
1758
+ let gitCleanupDone = false;
1759
+ const gitCwd = params.cwd ?? ctx.cwd;
1760
+ // Issue #466: the repository root the head-state record is keyed by — the SAME
1761
+ // resolution the branch lock below uses, so the write and the clear cannot
1762
+ // disagree about which record they own (a record keyed on `process.cwd()`
1763
+ // would name the wrong repo for a run dispatched with `cwd` elsewhere).
1764
+ const headStateRepoRoot = (): string => getRepoRoot(gitCwd) ?? gitCwd;
1765
+
1766
+ // Branch teardown — commit the agent's work (so the diff is real), capture
1767
+ // the diff, switch back to the original branch, delete the work branch, and
1768
+ // release the per-repo git lock. Runs on EVERY settle path. C1: agents
1769
+ // rarely commit, so captureDiff(base...HEAD) alone would be empty and the
1770
+ // uncommitted edits would leak into the base working tree on switch —
1771
+ // commitAll first makes the diff real and the switch clean.
1772
+ const cleanupWorkBranch = (): { gitBranch?: string; gitDiff?: string } => {
1773
+ if (gitCleanupDone || !workBranchName || !headState) return {};
1774
+ gitCleanupDone = true;
1775
+ const info: { gitBranch?: string; gitDiff?: string } = { gitBranch: workBranchName };
1776
+ // The lock MUST be released on every exit path — early returns included.
1777
+ try {
1778
+ try {
1779
+ const stillOnOurBranch = getCurrentBranch(gitCwd) === workBranchName;
1780
+ if (!stillOnOurBranch) {
1781
+ log.warn(`cleanupWorkBranch: tree moved off ${workBranchName} — skipping switch/delete`, {
1782
+ agentId: id,
1783
+ });
1784
+ // Issue #466: the tree is VERIFIED off our branch (moved by hand), so
1785
+ // the record has nothing left to repair — clear it (M7's counterpart).
1786
+ clearHeadState(headStateRepoRoot());
1787
+ return info;
1788
+ }
1789
+ } catch (err) {
1790
+ log.warn(`getCurrentBranch failed during cleanup for background agent ${id}`, {
1791
+ error: (err as Error).message,
1792
+ });
1793
+ // Issue #466: KEEP the record — we cannot tell where the tree is, which
1794
+ // is exactly the crash-equivalent state the boot's retry is for.
1795
+ return info;
1796
+ }
1797
+ try {
1798
+ // C1: commit the agent's work so captureDiff sees it. If no identity is
1799
+ // configured, fall back to capturing the working-tree diff directly.
1800
+ const dirty = hasUncommittedChanges(gitCwd);
1801
+ if (dirty) {
1802
+ const commitResult = commitAll(gitCwd, `brl-subagent ${id}: background work`);
1803
+ if (commitResult.ok) {
1804
+ log.info('Committed background agent work on work branch', {
1805
+ sha: commitResult.sha,
1806
+ branch: workBranchName,
1807
+ agentId: id,
1808
+ });
1809
+ } else {
1810
+ log.warn(`commitAll failed for background agent ${id} — capturing working diff`, {
1811
+ error: commitResult.error,
1812
+ });
1813
+ const workingDiff = captureWorkingDiff(gitCwd);
1814
+ if (workingDiff) info.gitDiff = workingDiff;
1815
+ }
1816
+ }
1817
+ const diffResult = captureDiff(gitCwd, headState.sha);
1818
+ if (diffResult.ok && diffResult.diff.trim()) {
1819
+ // Merge committed + working diffs — either can exist alone.
1820
+ info.gitDiff = info.gitDiff
1821
+ ? `${info.gitDiff}\n${diffResult.diff}`
1822
+ : diffResult.diff;
1823
+ }
1824
+ } catch (err) {
1825
+ log.warn(`captureDiff failed for background agent ${id}`, { error: (err as Error).message });
1826
+ }
1827
+ try {
1828
+ const restoreResult = restoreHead(gitCwd, headState);
1829
+ if (!restoreResult.ok) {
1830
+ log.warn(`restoreHead failed for background agent ${id}`, { error: restoreResult.error });
1831
+ // Issue #466: a FAILED restore keeps the record (mutants M3/M4) — the
1832
+ // tree is still on the work branch and the base lives only here.
1833
+ } else {
1834
+ // Verified off the work branch: the record has done its job.
1835
+ clearHeadState(headStateRepoRoot());
1836
+ }
1837
+ } catch (err) {
1838
+ log.warn(`restoreHead failed for background agent ${id}`, { error: (err as Error).message });
1839
+ }
1840
+ try {
1841
+ deleteBranch(gitCwd, workBranchName);
1842
+ } catch (err) {
1843
+ log.warn(`deleteBranch failed for background agent ${id}`, { error: (err as Error).message });
1844
+ }
1845
+ } finally {
1846
+ releaseGitLock?.();
1847
+ releaseGitLock = undefined;
1848
+ }
1849
+ return info;
1850
+ };
1851
+
1852
+ // Issue #447: the deadline handle is declared HERE, above the pre-start
1853
+ // region, so the pre-start cleanup can clear it. It is only ARMED below
1854
+ // (just before prompt()), so on the earlier throw sites clearing it is a
1855
+ // no-op by construction.
1856
+ let deadlineHandle: ReturnType<typeof setTimeout> | undefined;
1857
+
1858
+ /**
1859
+ * Issue #447: the pre-start cleanup. Every throw between the durable
1860
+ * dispatch records (agent record + run entry + registry entry, written
1861
+ * above) and `session.prompt()` funnels here: the transcript start, the
1862
+ * acceptance write, and the prompt call itself each rethrow through it.
1863
+ *
1864
+ * PRUNING IS PROVABLY SAFE HERE — and only here. `finalizeRunEntry` prunes
1865
+ * the run's session dir per its #404 retention gate; for a run whose prompt
1866
+ * was never issued nothing can be writing to that dir and no retry will be
1867
+ * offered for it, so there is no reader to retain it for.
1868
+ *
1869
+ * The terminal write is best-effort so a throw in the cleanup cannot mask
1870
+ * the original spawn error: `persistRunRecord` retires the registry entry
1871
+ * BEFORE appending the entry, and `clearInflightRun` is idempotent, so the
1872
+ * residue is gone either way.
1873
+ */
1874
+ const failPreStart = (message: string): void => {
1875
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1876
+ cleanupWorkBranch();
1877
+ try {
1878
+ finalizeRunEntry('failed', message);
1879
+ } catch (err) {
1880
+ log.warn(`spawnBackgroundSession: pre-start finalize failed for ${id}`, {
1881
+ error: (err as Error).message,
1882
+ });
1883
+ }
1884
+ clearInflightRun(id);
1486
1885
  };
1487
1886
 
1488
- // Start transcript for this agent
1489
- transcript.startTranscript(agent.id, params.task);
1887
+ /** The pre-start failure stamp: the issue's honest reason plus the cause. */
1888
+ const neverIssued = (err: unknown): string =>
1889
+ `${PROMPT_NEVER_ISSUED_MESSAGE}: ` +
1890
+ sanitizeErrorMessage(err instanceof Error ? err.message : String(err), effectiveCwd);
1891
+
1892
+ /**
1893
+ * Issue #465 (b) / #466 (ADR 0026 D4): the terminal write for a branch
1894
+ * dispatch refused before the prompt — record flip -> run entry ->
1895
+ * transcript, the same three writes every refused spawn ends with. ONE
1896
+ * definition for both pre-flight refusals AND the branch-setup-throw path
1897
+ * below, so the sequence and its message cannot drift apart between them;
1898
+ * each step is contained, because a cleanup fault must never mask the
1899
+ * refusal itself.
1900
+ */
1901
+ const markBranchSpawnFailed = (message: string): void => {
1902
+ try {
1903
+ updateAgentStatus(id, 'failed', message);
1904
+ finalizeRunEntry('failed', message);
1905
+ transcript.completeTranscript(id, 'failed');
1906
+ } catch { /* best-effort, same discipline as the setup-throw path */ }
1907
+ };
1908
+
1909
+ // Start transcript for this agent. Issue #447 (S2): a throw here used to
1910
+ // leave a `running` run entry and a live registry entry that the next boot
1911
+ // offered as an interrupted, retryable run — clean it and rethrow.
1912
+ try {
1913
+ transcript.startTranscript(agent.id, params.task);
1914
+ } catch (err) {
1915
+ failPreStart(neverIssued(err));
1916
+ throw err;
1917
+ }
1490
1918
 
1491
1919
  // Store session ref for live monitor polling
1492
1920
  agent._sessionRef = session;
@@ -1556,15 +1984,6 @@ export async function spawnBackgroundSession(
1556
1984
  // hard failure — never spawn an unisolated background agent that was asked
1557
1985
  // for isolation (fail-loud, same principle as foreground's fallback but
1558
1986
  // 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
1987
  if (params.gitMode === 'branch') {
1569
1988
  // C2: serialize the FULL branch lifecycle per repo. The spawnQueue only
1570
1989
  // covers setup; without this lock, a second concurrent branch-mode spawn
@@ -1572,21 +1991,94 @@ export async function spawnBackgroundSession(
1572
1991
  // fight over the shared working tree (stranding the repo on an orphan
1573
1992
  // branch). The lock is released in cleanupWorkBranch (or on setup throw).
1574
1993
  // Key: resolved repository root, cwd fallback for non-repo paths (#224).
1575
- const lockKey = getRepoRoot(gitCwd) ?? gitCwd;
1994
+ // Issue #466: ONE definition, shared with the head-state record's key — the
1995
+ // lock, the write and the clear can then never name different repositories.
1996
+ const lockKey = headStateRepoRoot();
1997
+ // Issue #465 (b): refuse a dispatch whose repository is held by a run that
1998
+ // is terminal on paper but never settled — the settle is the only releaser
1999
+ // of this lock (#460 §1.1), so waiting for it never ends. Checked BEFORE the
2000
+ // chain link is installed and before any wait, so the refusal is immediate
2001
+ // and the caller gets a spawn failure naming the owner instead of a tool
2002
+ // call that hangs forever (measured: W460P-P10).
2003
+ const holderId = gitBranchLockOwners.get(lockKey);
2004
+ if (holderId && isStuckTerminalOwner(holderId)) {
2005
+ const holder = agents.get(holderId)!;
2006
+ const heldFor = Math.round((Date.now() - holder.completedAt!) / 1000);
2007
+ const workBranch = holder.workBranch ?? '(unknown)';
2008
+ // Issue #466 (dossier §7): the second half of this message must not outlive
2009
+ // #465's own world. Post-#466 the boot DOES repair a provable orphan (the
2010
+ // head-state table's row 7), so "restart clears it, restore the base by
2011
+ // hand" is false for exactly the case this refusal names — the lock is the
2012
+ // restart's business, the trailer is the base's. The manual commands stay,
2013
+ // but only for the needs-manual rows (dirty tree, unreadable record).
2014
+ const reason = sanitizeErrorMessage(
2015
+ `gitMode 'branch' refused: this repository is locked by run ${holderId}, ` +
2016
+ `which has been terminal (${holder.status}${holder.error ? `: ${holder.error}` : ''}) ` +
2017
+ `for ${heldFor}s but has not settled — its SDK session is still held, so the ` +
2018
+ `branch lock cannot be released while it may still write. The work branch ` +
2019
+ `${workBranch} is still checked out; this process keeps the repository on it ` +
2020
+ `for the rest of its life, and only a restart releases the lock. That restart ` +
2021
+ `is also the repair: at the next boot the recorded base is restored — when the ` +
2022
+ `owner is provably dead, HEAD is exactly ${workBranch} and the working tree is ` +
2023
+ `clean — and ${workBranch} is KEPT with the run's commits. If the boot cannot ` +
2024
+ `repair it (uncommitted changes in the tree, or an unreadable record) it names ` +
2025
+ `the reason and keeps the record; the tree then needs the manual steps — ` +
2026
+ `git stash push -u -m "brl-subagent interrupted work" && ` +
2027
+ `git checkout <recorded base> — and ${workBranch} stays until its work is reviewed.`,
2028
+ effectiveCwd,
2029
+ );
2030
+ // Mirror the branch-setup-throw path below: the agent record was already
2031
+ // persisted as 'running' above, so a refusal that only THROWS leaves a
2032
+ // zombie row `get_subagent_result` reports as running forever (measured,
2033
+ // #460 §4.4 — `failPreStart` alone stops at the run entry). Record flip ->
2034
+ // run entry -> transcript (one shared helper), then the throw that reaches
2035
+ // the caller's spawn-failure result. `finalizeRunEntry` already retires the
2036
+ // registry entry (a non-running write clears it); the explicit call is the
2037
+ // belt for a finalize that threw — registry residue is what boot recovery
2038
+ // reads, and this dispatch provably never started.
2039
+ markBranchSpawnFailed(reason);
2040
+ clearInflightRun(id);
2041
+ throw new Error(reason);
2042
+ }
2043
+ // Issue #465 (d): release the process-wide spawn queue BEFORE the per-repo
2044
+ // wait below — that wait is bounded by another run's lifetime, so holding
2045
+ // the queue through it blocks every spawn in the process, not just this
2046
+ // repository's. The git chain itself is unchanged: this spawn still cannot
2047
+ // touch the working tree until the lock is handed over.
2048
+ releaseSpawnQueue();
1576
2049
  const prev = gitBranchLocks.get(lockKey) ?? Promise.resolve();
1577
2050
  let release!: () => void;
1578
2051
  const gate = new Promise<void>(r => { release = r; });
1579
2052
  const entry = prev.then(() => gate);
1580
2053
  gitBranchLocks.set(lockKey, entry);
1581
2054
  await prev;
2055
+ gitBranchLockOwners.set(lockKey, id);
1582
2056
  releaseGitLock = () => {
1583
2057
  // 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.
2058
+ // queued spawn behind us replaced the entry with its own. The owner is
2059
+ // held to the same rule: a stale release must not disown the new holder
2060
+ // (that would turn the next dispatch's refusal back into a silent wait).
1585
2061
  if (gitBranchLocks.get(lockKey) === entry) gitBranchLocks.delete(lockKey);
2062
+ if (gitBranchLockOwners.get(lockKey) === id) gitBranchLockOwners.delete(lockKey);
1586
2063
  release();
1587
2064
  };
1588
2065
 
1589
2066
  try {
2067
+ // Issue #466 (ADR 0026 D4): BEFORE the dirty check — an unresolved record
2068
+ // is the more specific fact, and a tree left on a dead run's branch would
2069
+ // otherwise only produce "working tree has uncommitted changes" (or, when
2070
+ // clean, a NEW branch based on the orphan: exactly the silent wrong base
2071
+ // this issue is about).
2072
+ //
2073
+ // Dossier §7 order: #465's refusal above is the FIRST gate and it wins,
2074
+ // because a wedged owner is a live process that may still write (and the
2075
+ // record it wrote names itself as ALIVE, so this guard would decline to
2076
+ // act anyway). This is the SECOND gate, and it fires only for a record
2077
+ // whose owner is NOT alive — `unresolvedHeadStateRefusal` returns
2078
+ // undefined for a live owner (M12).
2079
+ const unresolved = unresolvedHeadStateRefusal(lockKey);
2080
+ if (unresolved) throw new Error(unresolved);
2081
+
1590
2082
  // C1: isolation is only real when the base tree is clean. A dirty tree
1591
2083
  // would ride onto the work branch, get clobbered by the agent's writes,
1592
2084
  // and leak back into the base working tree on switch — refuse loudly.
@@ -1597,15 +2089,48 @@ export async function spawnBackgroundSession(
1597
2089
  );
1598
2090
  }
1599
2091
  headState = getHeadState(gitCwd);
1600
- const branchResult = createWorkBranch(gitCwd, headState.sha);
2092
+ // Issue #466 (D1): the durable record is written INSIDE the lock, after
2093
+ // the dirty check and BEFORE the branch exists — the write-ahead property
2094
+ // that makes a crash in `createWorkBranch` (and in the teardown window)
2095
+ // repairable. The name is minted here so the record can name the branch.
2096
+ workBranchName = newWorkBranchName();
2097
+ if (!writeHeadState({
2098
+ version: HEAD_STATE_VERSION,
2099
+ repoRoot: lockKey,
2100
+ runId: id,
2101
+ kind: 'background',
2102
+ base: headState,
2103
+ workBranch: workBranchName,
2104
+ owner,
2105
+ createdAt: new Date().toISOString(),
2106
+ })) {
2107
+ // A store failure must never refuse a run (same discipline as the
2108
+ // registry): the run proceeds, only its crash-recoverability degrades.
2109
+ log.warn('headState record could not be written — an interrupted run will name no base', {
2110
+ agentId: id,
2111
+ workBranch: workBranchName,
2112
+ });
2113
+ }
2114
+ const branchResult = createWorkBranch(gitCwd, headState.sha, workBranchName);
1601
2115
  if (branchResult.ok) {
1602
- workBranchName = branchResult.branch;
2116
+ // Issue #465 (b): stamp the work branch on the DURABLE record, not only
2117
+ // in this closure. `agent.result.gitBranch` is written at settle, which
2118
+ // is exactly what a wedged run never does — and a live-only field would
2119
+ // die with the process that needs to name it. (#466 mints the name
2120
+ // above, so the created branch IS `workBranchName`.)
2121
+ agent.workBranch = workBranchName;
2122
+ persistAgent(agent);
1603
2123
  log.info('Created work branch for background agent', {
1604
2124
  branch: workBranchName,
1605
2125
  base: headState.branch,
1606
2126
  agentId: id,
1607
2127
  });
1608
2128
  } else {
2129
+ // Nothing was created, so there is nothing to repair: clear the record
2130
+ // and drop the name, or cleanupWorkBranch would act on a branch that
2131
+ // never existed.
2132
+ clearHeadState(lockKey);
2133
+ workBranchName = undefined;
1609
2134
  throw new Error(`createWorkBranch failed: ${branchResult.error}`);
1610
2135
  }
1611
2136
  } catch (err) {
@@ -1614,17 +2139,13 @@ export async function spawnBackgroundSession(
1614
2139
  // (get_subagent_result would otherwise report 'running' forever).
1615
2140
  releaseGitLock?.();
1616
2141
  releaseGitLock = undefined;
1617
- // Sanitize ONCE and reuse for the status update and the thrown error.
2142
+ // Sanitize ONCE and reuse for the terminal write and the thrown error.
1618
2143
  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 */ }
2144
+ // Issue #98: the refused spawn is a failure — flip the record and finalize
2145
+ // the run entry so no zombie 'running' entry survives (lockstep, one
2146
+ // shared sequence with both pre-flight refusals).
2147
+ markBranchSpawnFailed(
2148
+ `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
1628
2149
  throw new Error(
1629
2150
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}. ` +
1630
2151
  `Refusing to spawn the background agent unisolated.`,
@@ -1633,82 +2154,6 @@ export async function spawnBackgroundSession(
1633
2154
  }
1634
2155
  }
1635
2156
 
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
2157
  // Issue #376 (audit D8): the aborted settle path is reached from BOTH
1713
2158
  // handlers — the .then (probe contract: an abort RESOLVES the prompt) and the
1714
2159
  // .catch (the prompt rejects while the agent is already 'stopped'). Both must
@@ -1744,15 +2189,22 @@ export async function spawnBackgroundSession(
1744
2189
  // Issue #122: a timed-out run burned tokens — record the real usage
1745
2190
  // (the git-diff block above must not leave the empty fallback).
1746
2191
  recordSessionUsage();
2192
+ // Issue #31: capture the final output while the session is still live, then
2193
+ // release the ref on the terminal path (memory retention; the poller treats
2194
+ // a nulled ref on a terminal agent as expected).
2195
+ //
2196
+ // Issue #453 [c 4]: the CAPTURE now PRECEDES the record. These fields are the
2197
+ // terminal entry's payload, and after a deadline stop this call writes the
2198
+ // AMENDMENT — so output produced after the deadline (the child kept running
2199
+ // until the abort landed, and the SDK may still deliver the final turn) must
2200
+ // be in `agent.finalOutput` by the time the amendment reads it. It used to
2201
+ // finalize first, which persisted the pre-deadline (usually empty) output.
2202
+ captureAndReleaseSession();
1747
2203
  // Issue #120 (Track 1): agent.error carries the reason when the stop was a
1748
2204
  // deadline timeout ('Timed out after Xms' → 'timeout'); a user cancel
1749
2205
  // (stop_subagent) sets no error, so fall back to the honest user-abort
1750
2206
  // stamp (→ 'aborted') instead of the old ambiguous 'Aborted or timed out'.
1751
2207
  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
2208
  };
1757
2209
 
1758
2210
  // Issue #53: the settle handlers (.then/.catch below) run in promise
@@ -1823,6 +2275,145 @@ export async function spawnBackgroundSession(
1823
2275
  // The session will run independently
1824
2276
  // F27: wrap in the task-as-data fence — the user message is DATA, not
1825
2277
  // instructions (see SUBAGENT_INSTRUCTIONS Task Boundary).
2278
+
2279
+ /**
2280
+ * The ONE place a background deadline is created — and its written contract
2281
+ * (issue #453, ADR 0023).
2282
+ *
2283
+ * OWNERSHIP. The session-manager owns the deadline on every path (explicit
2284
+ * timeout and the 30 m default); no caller arms or clears one. It is installed
2285
+ * before `prompt()`, so no statement anywhere after this call — a caller throw
2286
+ * included — can leave the run unbounded. The only thing that clears it is the
2287
+ * run's own settlement.
2288
+ *
2289
+ * WHAT THE DEADLINE OWNS: nothing that outlives the call. The deadline owns no
2290
+ * filesystem or git resource, waits for no settle, never prunes the run's
2291
+ * session dir and never releases the branch lock; ONLY A SETTLE DOES. What it
2292
+ * does is bounded and idempotent: flip the agent to `stopped` (which also sets
2293
+ * `completedAt`, so the caller's poller releases the live row on its next
2294
+ * tick), note the transcript, attempt ONE cooperative abort, and write the
2295
+ * classification SNAPSHOT (`failed` + `timeout`, `prune: false`).
2296
+ *
2297
+ * ORDERING IS THE CONTRACT. status → abort → snapshot. A throwing status or
2298
+ * transcript write must never leave the record saying 'stopped' while the child
2299
+ * keeps running, and a throwing append must never suppress the abort — each
2300
+ * step is contained and the abort sits between the other two. The status flip
2301
+ * stays BEFORE the abort because the settle classifies the run from it.
2302
+ *
2303
+ * TIME ORIGIN. The two arguments are deliberately separate: `budgetMs` is the
2304
+ * run's budget and is the ONLY value the reason may name; `delayMs` is the
2305
+ * REMAINDER still owed at arm time (the budget is anchored at record creation).
2306
+ * One argument for both is the defect this replaced: the timer fired at
2307
+ * arm + budget (drifting past the displayed `startedAt + timeoutMs`), and using
2308
+ * the remainder as the reason would truncate the budget a user asked for.
2309
+ *
2310
+ * STATED LIMITS (unchanged, and in the CHANGELOG): the abort is COOPERATIVE. A
2311
+ * prompt that ignores it keeps running; its run then keeps its session dir, its
2312
+ * branch lock until process exit, and no registry entry (the terminal snapshot
2313
+ * retires that claim). Nothing here can force it, and nothing here pretends to.
2314
+ */
2315
+ const armDeadline = (budgetMs: number, delayMs: number): ReturnType<typeof setTimeout> =>
2316
+ setTimeout(() => {
2317
+ if (agent.completedAt) return; // already settled — nothing to abort
2318
+ const reason = `Timed out after ${budgetMs}ms`;
2319
+ let bookkeepingFailure: unknown;
2320
+ try {
2321
+ updateAgentStatus(id, 'stopped', reason);
2322
+ transcript.completeTranscript(id, 'stopped');
2323
+ } catch (err) {
2324
+ bookkeepingFailure = err;
2325
+ }
2326
+ // Independent of the bookkeeping above (#448) — exactly one abort attempt.
2327
+ try {
2328
+ session.abort().catch((err: Error) => {
2329
+ // Abort can reject if the session is mid-dispose; the status flip
2330
+ // above is already recorded, so this is non-fatal — but a rejected
2331
+ // abort must not be silent (#448 review nit).
2332
+ log.warn(`spawnBackgroundSession: abort rejected for ${id}`, { error: err.message });
2333
+ });
2334
+ } catch (err) {
2335
+ // abort() threw synchronously — a timer callback must never throw
2336
+ // uncaught (that would crash the host process).
2337
+ log.warn(`spawnBackgroundSession: abort failed to start for ${id}`, {
2338
+ error: (err as Error).message,
2339
+ });
2340
+ }
2341
+ // Issue #453: the durable classification SNAPSHOT. `timeout` is the run
2342
+ // vocabulary's existing category (there is no `stopped` status for a run —
2343
+ // `running | done | failed`), and `prune: false` is what keeps a
2344
+ // still-writing SDK session's directory alive. Contained: a failed append
2345
+ // must not escape the timer (it would kill the host), and it must NOT undo
2346
+ // the abort above — `entryWritten` stays false, so the settle still writes
2347
+ // the terminal record when (if) it arrives.
2348
+ try {
2349
+ // `snapshot` is assigned from the RETURNED entry, i.e. only after the
2350
+ // append resolved — this is what makes the late settle an amendment
2351
+ // rather than a second classification.
2352
+ snapshot = finalizeRunEntry('failed', reason, {
2353
+ stopReason: 'aborted',
2354
+ errorCategory: 'timeout',
2355
+ prune: false,
2356
+ });
2357
+ } catch (err) {
2358
+ log.warn(`spawnBackgroundSession: deadline record write failed for ${id}`, {
2359
+ error: (err as Error).message,
2360
+ });
2361
+ }
2362
+ if (bookkeepingFailure) {
2363
+ // Surfaced through the log (the same audit surface the settle paths
2364
+ // use) — never absorbed into silence.
2365
+ log.warn(`spawnBackgroundSession: deadline bookkeeping failed for ${id}`, {
2366
+ error:
2367
+ bookkeepingFailure instanceof Error
2368
+ ? bookkeepingFailure.message
2369
+ : String(bookkeepingFailure),
2370
+ });
2371
+ }
2372
+ }, delayMs);
2373
+
2374
+ // Issue #453 (ADR 0023, decision 1): ONE owner. This function arms the run's
2375
+ // deadline on EVERY path — the explicit timeout when there is one, else the
2376
+ // 30 m default — and no caller arms a second one (`deadlineOwner` is gone with
2377
+ // the caller's timer). It is armed HERE, before prompt(), so the run is
2378
+ // bounded even when prompt() throws synchronously (the catch below clears it).
2379
+ //
2380
+ // `effectiveBackgroundBudget` is the single definition of the default and of
2381
+ // the normalization (never re-spelled here): a raw value that is 0, negative,
2382
+ // NaN, Infinity or >= 2^31 means "no explicit timeout", so the default applies
2383
+ // (issue #240 — never an instant kill) and an explicit 45 m is honored verbatim
2384
+ // (it is not a ceiling).
2385
+ //
2386
+ // Issue #453 / ADR 0023 decision 5: the budget is anchored at RECORD CREATION.
2387
+ // `startedAtMs` is the agent record's own clock (epoch ms — the same field the
2388
+ // monitor turns into `deadlineAt`), and the setup between that line and here
2389
+ // (transcript start, record persist, branch setup, a branch-lock wait) is time
2390
+ // the run has already spent, so it is subtracted. `Math.max(0, …)` is required:
2391
+ // a negative remainder must fire immediately, not overflow. `normalizeTimeout`
2392
+ // is the WRONG path for a remainder — it maps 0 or negative to "no timeout",
2393
+ // which would silently disarm a run that is already over budget.
2394
+ deadlineHandle = armDeadline(budgetMs, Math.max(0, budgetMs - (Date.now() - startedAtMs)));
2395
+
2396
+ // Issue #447: the ACCEPTANCE marker — ONE write, immediately before the
2397
+ // prompt, that turns `acceptedAt: null` into a timestamp on both durable
2398
+ // records (run entry + registry entry, in lockstep through the single
2399
+ // `persistRunRecord` choke point). Past this line a run that dies is
2400
+ // genuinely "started, outcome unknown" (#439); before it, it is provably
2401
+ // never-started. A run whose acceptance cannot be recorded must NOT start —
2402
+ // otherwise the residue problem returns — so a throw here cleans up and
2403
+ // rethrows instead of prompting.
2404
+ run.acceptedAt = new Date().toISOString();
2405
+ try {
2406
+ persistRunRecord(pi, run, "background");
2407
+ } catch (err) {
2408
+ // The stamp above never became durable, so the in-memory value must not ride
2409
+ // into the terminal record this cleanup writes: the entry would claim
2410
+ // `acceptedAt=<ISO>` while its message says the prompt was never issued
2411
+ // (2026-11-07 review). Back to the creation sentinel before settling.
2412
+ run.acceptedAt = null;
2413
+ failPreStart(neverIssued(err));
2414
+ throw err;
2415
+ }
2416
+
1826
2417
  // NOTE: if prompt() throws SYNCHRONOUSLY, the .then/.catch below never
1827
2418
  // attach and cleanupWorkBranch would never run — catch here so the work
1828
2419
  // branch is not orphaned (it is a real filesystem branch).
@@ -1830,50 +2421,17 @@ export async function spawnBackgroundSession(
1830
2421
  try {
1831
2422
  runPromise = session.prompt(wrapTask(params.task));
1832
2423
  } catch (err) {
1833
- cleanupWorkBranch();
1834
2424
  // Issue #98 (review F1): a synchronous prompt() throw never reaches the
1835
2425
  // settle handlers — finalize the run entry so no zombie 'running' entry
1836
2426
  // survives (findSpawnRunById would otherwise resolve and retry a run that
1837
- // never started).
1838
- finalizeRunEntry('failed', sanitizeErrorMessage((err as Error).message, effectiveCwd));
2427
+ // never started). #447: the same cleanup also clears the deadline armed
2428
+ // above and retires the registry entry.
2429
+ failPreStart(sanitizeErrorMessage((err as Error).message, effectiveCwd));
1839
2430
  throw err;
1840
2431
  }
1841
2432
 
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
2433
  runPromise.then(() => {
1876
- if (timeoutHandle) clearTimeout(timeoutHandle);
2434
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1877
2435
  try {
1878
2436
  // Probe contract (sdk-abort-contract.test.ts): prompt() RESOLVES on abort
1879
2437
  // — the SDK's runWithLifecycle catches the AbortError and converts it into
@@ -1881,8 +2439,23 @@ export async function spawnBackgroundSession(
1881
2439
  // HERE, not in .catch. Two signals distinguish stop from completion:
1882
2440
  // 1. stopAgent pre-set status to 'stopped' before calling abort();
1883
2441
  // 2. the last assistant message carries stopReason "aborted".
1884
- const lastAssistant = [...(session.messages ?? [])].reverse().find(m => m.role === 'assistant');
2442
+ //
2443
+ // Issue #449: the projection is read ONCE here — `evidence` below is
2444
+ // derived from the same read the stopReason comes from. The SDK can remove
2445
+ // the only assistant message from this projection before settling (a
2446
+ // recoverable-length omission: `_omitRecoveryAttempt`, then a compaction
2447
+ // that never runs on a young branch), so "no assistant message" is real
2448
+ // evidence about the settle and not a read failure.
2449
+ const projectedMessages = session.messages;
2450
+ const lastAssistant = [...(projectedMessages ?? [])].reverse().find(m => m.role === 'assistant');
1885
2451
  const terminalStopReason = lastAssistant?.stopReason;
2452
+ // Issue #449: "absent" means exactly one thing — an array that was READ and
2453
+ // holds no assistant message. A missing/unreadable projection is "unknown"
2454
+ // (a throwing getter never reaches here; the settle catch-all owns it), and
2455
+ // any assistant message is "present" whatever it contains.
2456
+ const assistantEvidence: AssistantEvidence = Array.isArray(projectedMessages)
2457
+ ? projectedMessages.some((m) => m.role === 'assistant') ? 'present' : 'absent'
2458
+ : 'unknown';
1886
2459
  const aborted = agent.status === 'stopped' || terminalStopReason === 'aborted';
1887
2460
  if (aborted) {
1888
2461
  // Session was aborted — mark stopped. If stopAgent already flipped the
@@ -1911,16 +2484,29 @@ export async function spawnBackgroundSession(
1911
2484
  // classifyError for the provider-error case.
1912
2485
  const providerErrorMessage =
1913
2486
  lastAssistant?.errorMessage ?? session.state?.errorMessage;
1914
- const outcome = classifyTerminalOutcome(terminalStopReason, providerErrorMessage);
2487
+ const outcome = classifyTerminalOutcome(terminalStopReason, providerErrorMessage, {
2488
+ assistantEvidence,
2489
+ });
1915
2490
 
1916
2491
  if (outcome.status === 'failed') {
1917
2492
  // Mid-run provider death / truncation / incomplete turn.
1918
2493
  agent.status = 'failed';
1919
2494
  agent.completedAt = Date.now();
1920
- const sanitizedError = sanitizeErrorMessage(
1921
- providerErrorMessage ?? defaultTerminalMessage(terminalStopReason),
1922
- effectiveCwd,
1923
- );
2495
+ // Issue #449: `assistantEvidence === 'absent'` is exactly the case this
2496
+ // classifier's formerly-default arm now fails on (a zero-assistant
2497
+ // projection has no last assistant, so `terminalStopReason` is
2498
+ // undefined). The omitted message cannot be recovered, so the reason
2499
+ // states the observation and offers truncation only as a possibility —
2500
+ // it never asserts truncation as fact. It also WINS over a stale
2501
+ // `session.state.errorMessage`, which this branch used to prefer; the
2502
+ // stale text may be appended, never substituted.
2503
+ const failureReason =
2504
+ assistantEvidence === 'absent'
2505
+ ? providerErrorMessage
2506
+ ? `${NO_ASSISTANT_OUTPUT_REASON}\n${providerErrorMessage}`
2507
+ : NO_ASSISTANT_OUTPUT_REASON
2508
+ : (providerErrorMessage ?? defaultTerminalMessage(terminalStopReason));
2509
+ const sanitizedError = sanitizeErrorMessage(failureReason, effectiveCwd);
1924
2510
  agent.error = sanitizedError;
1925
2511
  const gitInfo = cleanupWorkBranch();
1926
2512
  agent.result = {
@@ -1995,7 +2581,7 @@ export async function spawnBackgroundSession(
1995
2581
  markTerminalBestEffort('completed');
1996
2582
  }
1997
2583
  }).catch((err: Error) => {
1998
- if (timeoutHandle) clearTimeout(timeoutHandle);
2584
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1999
2585
  try {
2000
2586
  // W4: capture partial work + discard the work branch on failure — a failed
2001
2587
  // background agent may still have produced reviewable changes.
@@ -2064,6 +2650,6 @@ export async function spawnBackgroundSession(
2064
2650
 
2065
2651
  return agent;
2066
2652
  } finally {
2067
- resolveNext();
2653
+ releaseSpawnQueue();
2068
2654
  }
2069
2655
  }