brl-subagent 2.6.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.
@@ -1,9 +1,11 @@
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 { mkdirSync, writeFileSync, readFileSync, readdirSync, existsSync, rmSync } from 'fs';
4
+ import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync } from 'fs';
5
+ import type { Dirent } from 'fs';
5
6
  import type { BackgroundAgent, AgentStatus, GitMode, RecoveryMode, SubagentResult, SubagentRun, ThinkingLevel, SubagentToolOptions, UsageStats, ErrorCategory } from './types';
6
- 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';
7
9
  import { accumulateUsage } from './runner';
8
10
  import * as eventBus from './event-bus';
9
11
  import * as transcript from './transcript';
@@ -11,11 +13,15 @@ import { createEvent } from './event-bus';
11
13
  import { assertSafeAgentId, sanitizeErrorMessage } from './sanitize';
12
14
  import { wrapTask } from './prompt';
13
15
  import { createLogger } from './logging';
14
- 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';
15
17
  import type { HeadState } from './git';
16
- import { normalizeTimeout, DEFAULT_BACKGROUND_DEADLINE_MS } from './validate';
17
- import { currentProcessOwner } from './recovery';
18
- import { persistRunRecord } 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';
22
+ import { isTransportRetryable } from './transport-retry';
23
+ import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
24
+ import { buildEngineeringBarSection } from './engineering-bar';
19
25
 
20
26
  const log = createLogger('brl-subagent');
21
27
  import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
@@ -31,6 +37,61 @@ var spawnQueue: Promise<void> = Promise.resolve();
31
37
  // working tree and must serialize (issue #224).
32
38
  const gitBranchLocks = new Map<string, Promise<void>>();
33
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
+
34
95
  /**
35
96
  * TEST-ONLY: release every held git branch lock. The lock is normally held
36
97
  * for the agent's lifetime (released at settle), but tests that never settle
@@ -38,6 +99,7 @@ const gitBranchLocks = new Map<string, Promise<void>>();
38
99
  */
39
100
  export function __testResetGitBranchLocks(): void {
40
101
  gitBranchLocks.clear();
102
+ gitBranchLockOwners.clear();
41
103
  }
42
104
 
43
105
  // Robust UUID generation with fallback
@@ -75,7 +137,20 @@ export function __setStorageDir(dir: string): void {
75
137
  function ensureStorageDir(): void {
76
138
  // F6 (issue #29): records hold the full task/result conversation — the dir
77
139
  // must be owner-only (0o700) so other local users cannot list the files.
78
- mkdirSync(STORAGE_DIR, { recursive: true, mode: 0o700 });
140
+ // Issue #408: a create-only `mode` never repaired a pre-existing store, so
141
+ // this runs on EVERY use and chmods a wider directory back to 0o700.
142
+ ensureOwnerOnlyDir(STORAGE_DIR);
143
+ }
144
+
145
+ /**
146
+ * The root that holds the per-run SDK session dirs. The dir mode is what denies
147
+ * other local users traversal; repairing it here keeps a pre-F6 `.pi` store
148
+ * from exposing every retained conversation beneath it.
149
+ */
150
+ function ensureSessionsRoot(): string {
151
+ const root = join(STORAGE_DIR, SESSIONS_SUBDIR);
152
+ ensureOwnerOnlyDir(root);
153
+ return root;
79
154
  }
80
155
 
81
156
  // ---------------------------------------------------------------------------
@@ -95,9 +170,14 @@ function ensureStorageDir(): void {
95
170
  // D5 measurement (one week of use):
96
171
  // du -sh .pi/subagents/sessions
97
172
  // find .pi/subagents/sessions -name '*.jsonl' | wc -l
98
- // The expected steady state is EMPTY between runs (terminal runs prune their
99
- // dir) plus one dir per currently-interrupted run — a non-empty count of
100
- // settled runs means a prune path regressed. There is no runtime metric.
173
+ // The expected steady state between runs is EMPTY, plus:
174
+ // - one dir per currently-interrupted run (kept by design, D3), and
175
+ // - up to RETAINED_MAX_DIRS transport-failed dirs bearing the retention
176
+ // marker (issue #404 — bounded by the settle-time sweep, see the #404
177
+ // block below).
178
+ // These two classes are the documented exceptions: a session dir whose name is
179
+ // NOT one of those is a prune-path regression. Judge by the marker file
180
+ // (`.transport-retained`), not by the raw count. There is no runtime metric.
101
181
  // ---------------------------------------------------------------------------
102
182
 
103
183
  /** Subdirectory of the agent-record store that holds per-run session dirs. */
@@ -113,6 +193,26 @@ export function backgroundSessionDir(id: string): string {
113
193
  return join(STORAGE_DIR, SESSIONS_SUBDIR, id);
114
194
  }
115
195
 
196
+ /**
197
+ * Issue #404: the ABSOLUTE path a retry preamble may name for a retained session.
198
+ * `backgroundSessionDir` is relative to the conductor's storage root (the default
199
+ * `.pi/subagents`); the retried child resolves paths against ITS OWN cwd, which can
200
+ * differ in worktree/branch mode — so the pointer must be resolved HERE, once.
201
+ */
202
+ export function retainedSessionPointer(id: string): string {
203
+ return resolve(backgroundSessionDir(id));
204
+ }
205
+
206
+ /**
207
+ * TRUE when `dir` is shaped exactly like `<...>/sessions/<id>` — the one
208
+ * precondition every path that touches a session directory requires before it
209
+ * can delete or brand it.
210
+ */
211
+ function isSessionDirFor(id: string, dir: string): boolean {
212
+ const target = resolve(dir);
213
+ return basename(target) === id && basename(dirname(target)) === SESSIONS_SUBDIR;
214
+ }
215
+
116
216
  /**
117
217
  * Remove ONE per-run session directory. Defensive by construction: the target
118
218
  * must look like `<...>/sessions/<id>` (basename === id, parent basename ===
@@ -126,13 +226,12 @@ function pruneSessionDir(id: string, dir: string): void {
126
226
  log.error(`Refusing to prune session dir for invalid id: ${id}`);
127
227
  return;
128
228
  }
129
- const target = resolve(dir);
130
- if (basename(target) !== id || basename(dirname(target)) !== SESSIONS_SUBDIR) {
131
- log.error(`Refusing to prune session dir outside ${SESSIONS_SUBDIR}/: ${target}`);
229
+ if (!isSessionDirFor(id, dir)) {
230
+ log.error(`Refusing to prune session dir outside ${SESSIONS_SUBDIR}/: ${resolve(dir)}`);
132
231
  return;
133
232
  }
134
233
  try {
135
- rmSync(target, { recursive: true, force: true });
234
+ rmSync(resolve(dir), { recursive: true, force: true });
136
235
  } catch (err) {
137
236
  // Pruning is hygiene — it must never break execution or a settle path.
138
237
  log.warn(`Failed to prune session dir for ${id}`, {
@@ -162,6 +261,173 @@ export function pruneBackgroundSession(id: string): void {
162
261
  pruneSessionDir(id, backgroundSessionDir(id));
163
262
  }
164
263
 
264
+ // ---------------------------------------------------------------------------
265
+ // Issue #404: bounded retention of a transport-failed run's session.
266
+ //
267
+ // The #401 resume preamble named no artifact beyond the working tree and the
268
+ // bank, because the SDK session dir — the only place the conversation lives —
269
+ // was pruned on every terminal settle. A transport failure is the ONE class a
270
+ // retry re-dispatches automatically, so it is the one class whose session is
271
+ // worth keeping: the retry's child reads the tail of it to recover what attempt
272
+ // 1 had already worked out.
273
+ //
274
+ // Retention is an OPTIMIZATION; boundedness is the invariant. A retained dir is
275
+ // branded with RETAINED_MARKER, and the sweep at the same choke points enforces
276
+ // the caps below over MARKED dirs only — an interrupted run's dir (kept by
277
+ // design, unmarked) and the agent-record store are never candidates. Nothing in
278
+ // this block may throw into a settle path.
279
+ //
280
+ // Root-local, like the U3 D5 boundary above: the sweep walks the sessions root
281
+ // the settled run actually wrote to, so a dir retained under a previous
282
+ // STORAGE_DIR root is not reclaimed by a later settle under a new one.
283
+ // ---------------------------------------------------------------------------
284
+
285
+ /** Brand on a retained session dir — the sweep's only selection criterion. */
286
+ const RETAINED_MARKER = '.transport-retained';
287
+ /** Keep at most this many retained dirs (oldest marker mtime goes first). */
288
+ const RETAINED_MAX_DIRS = 5;
289
+ /** Keep the marked set under this total on-disk size. */
290
+ const RETAINED_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
291
+ /** Drop a retained dir once its marker is older than this. */
292
+ const RETAINED_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
293
+ /**
294
+ * Below this size there is nothing worth a retention slot: a run that died on a
295
+ * connection error before its first assistant turn leaves a start-entry-only
296
+ * file (the SDK writes the header at create()), and pointing a retry at a
297
+ * contentless file is worse than not pointing at all.
298
+ */
299
+ const RETAINED_MIN_BYTES = 2 * 1024;
300
+
301
+ /**
302
+ * Recursive on-disk size of `dir`. Unreadable entries count as zero and
303
+ * symlinks are never followed, so the walk cannot escape `dir`.
304
+ */
305
+ function dirTotalBytes(dir: string): number {
306
+ let total = 0;
307
+ const stack = [dir];
308
+ while (stack.length > 0) {
309
+ const current = stack.pop()!;
310
+ let entries: Dirent[];
311
+ try {
312
+ entries = readdirSync(current, { withFileTypes: true });
313
+ } catch {
314
+ continue; // raced with a delete — size it as absent
315
+ }
316
+ for (const entry of entries) {
317
+ const child = join(current, entry.name);
318
+ if (entry.isDirectory()) {
319
+ stack.push(child);
320
+ } else if (entry.isFile()) {
321
+ try {
322
+ total += statSync(child).size;
323
+ } catch {
324
+ // vanished mid-walk — ignore
325
+ }
326
+ }
327
+ }
328
+ }
329
+ return total;
330
+ }
331
+
332
+ /**
333
+ * Enforce the #404 caps over the marked session dirs beside `currentDir`.
334
+ *
335
+ * `currentDir` is EXEMPT for the settle that just marked it. Without that, a
336
+ * single over-cap dir would be deleted at the instant it was retained — and the
337
+ * largest, most salvageable runs are exactly the ones that would lose. So one
338
+ * dir may overshoot by one; the NEXT settle reclaims it.
339
+ *
340
+ * Best-effort by construction: selection is guarded, and deletion goes through
341
+ * the validated, never-throwing `pruneSessionDir`.
342
+ */
343
+ function sweepRetainedSessions(currentDir: string): void {
344
+ const current = resolve(currentDir);
345
+ const root = dirname(current);
346
+ if (basename(root) !== SESSIONS_SUBDIR) return; // never walk outside sessions/
347
+ let names: string[];
348
+ try {
349
+ names = readdirSync(root, { withFileTypes: true })
350
+ .filter((entry) => entry.isDirectory())
351
+ .map((entry) => entry.name);
352
+ } catch {
353
+ return; // root missing/unreadable — nothing to bound
354
+ }
355
+ const now = Date.now();
356
+ const retained: Array<{ dir: string; size: number; markedAt: number }> = [];
357
+ for (const name of names) {
358
+ // Only ids our own spawn can mint are sweepable; a foreign name is left for
359
+ // a human instead of being deleted on a guess.
360
+ try {
361
+ assertSafeAgentId(name);
362
+ } catch {
363
+ continue;
364
+ }
365
+ const dir = join(root, name);
366
+ const marker = join(dir, RETAINED_MARKER);
367
+ // UNMARKED ⇒ interrupted (D3), live, or foreign. Never a candidate.
368
+ if (!existsSync(marker)) continue;
369
+ try {
370
+ retained.push({ dir, size: dirTotalBytes(dir), markedAt: statSync(marker).mtimeMs });
371
+ } catch {
372
+ // marker disappeared between the check and the stat — re-read as unmarked
373
+ }
374
+ }
375
+ retained.sort((a, b) => a.markedAt - b.markedAt);
376
+ let count = retained.length;
377
+ let total = retained.reduce((sum, entry) => sum + entry.size, 0);
378
+ for (const entry of retained) {
379
+ if (entry.dir === current) continue; // this settle's own dir — see the doc comment
380
+ // Ages ascend with the sort, so the oldest candidate's age speaks for the rest.
381
+ const tooMany = count > RETAINED_MAX_DIRS;
382
+ const tooBig = total > RETAINED_MAX_TOTAL_BYTES;
383
+ const tooOld = now - entry.markedAt > RETAINED_MAX_AGE_MS;
384
+ if (!tooMany && !tooBig && !tooOld) break;
385
+ pruneSessionDir(basename(entry.dir), entry.dir);
386
+ count -= 1;
387
+ total -= entry.size;
388
+ }
389
+ }
390
+
391
+ /**
392
+ * Retain `dir` for the #401 resume preamble: brand it with the retention marker
393
+ * (its mtime is the recency source) and enforce the caps.
394
+ *
395
+ * Returns TRUE when the dir is now retained — the caller then SKIPS the prune —
396
+ * and FALSE when retention was skipped or failed, in which case the caller must
397
+ * prune as before. Fail-closed on purpose: retention is an optimization, while
398
+ * boundedness is the invariant, and a dir whose marker write failed would be
399
+ * invisible to the sweep forever.
400
+ */
401
+ function retainSessionDir(id: string, dir: string): boolean {
402
+ try {
403
+ if (!isSessionDirFor(id, dir) || !existsSync(dir)) return false;
404
+ // Issue #408: a retained settle is the longest-lived session dir — repair
405
+ // the dir mode (the traversal boundary) and its files while it is cheap.
406
+ ensureOwnerOnlyDir(dir);
407
+ repairOwnerOnlyFiles(dir);
408
+ if (dirTotalBytes(dir) < RETAINED_MIN_BYTES) return false;
409
+ writeFileSync(join(dir, RETAINED_MARKER), `${new Date().toISOString()}\n`, {
410
+ encoding: 'utf-8',
411
+ mode: 0o600,
412
+ });
413
+ } catch (err) {
414
+ log.warn(`Not retaining session dir for ${id} (marker write failed)`, {
415
+ error: err instanceof Error ? err.message : String(err),
416
+ });
417
+ return false;
418
+ }
419
+ try {
420
+ sweepRetainedSessions(dir);
421
+ } catch (err) {
422
+ // The sweep guards its own steps; this is belt-and-braces so a settle can
423
+ // never be broken by hygiene.
424
+ log.warn(`Retained-session sweep failed for ${id}`, {
425
+ error: err instanceof Error ? err.message : String(err),
426
+ });
427
+ }
428
+ return true;
429
+ }
430
+
165
431
  /**
166
432
  * Persist agent record to disk
167
433
  */
@@ -257,6 +523,512 @@ export function listPersistedAgents(): BackgroundAgent[] {
257
523
  return records;
258
524
  }
259
525
 
526
+ // ---------------------------------------------------------------------------
527
+ // Issue #396: retry lineage for `get_subagent_result`.
528
+ //
529
+ // A run id is not necessarily the id of the run that actually finished it: the
530
+ // background transport auto-retry (#365) re-dispatches the same logical task as
531
+ // `attempt: 2`, and a manual `retryRunId` can mint attempt 3 whose `resumeOf`
532
+ // points at attempt 2. The durable agent store therefore has to be consulted
533
+ // before "not found" or a terminal source status is reported as final.
534
+ //
535
+ // Two properties drive the implementation:
536
+ //
537
+ // 1. ID FORM — notices render the first 8 hex characters of a UUID, while
538
+ // `resumeOf`/record ids are full UUIDs. Resolve a unique 8-hex prefix
539
+ // before either the record read or the lineage match; an ambiguous prefix
540
+ // is refused explicitly rather than guessed.
541
+ // 2. COST — the agent store is large and never pruned (measured 2026-10:
542
+ // ~1160 records / ~116 MB on the live store; a full parse is ~0.5 s per
543
+ // tool call, and a synthetic 100 KB-payload fixture of the same shape
544
+ // measures ~225 MB). This reader
545
+ // stats first, keeps only records inside a 7-day mtime window, caps the
546
+ // number read at `RETRY_SCAN_CAP`, and extracts just the identity fields
547
+ // with a top-level scanner instead of JSON-parsing result.messages.
548
+ //
549
+ // Deliberately NOT `listPersistedAgents()`: that sweep full-parses every
550
+ // record, and its "production has no caller" comment documents that decision.
551
+ // ---------------------------------------------------------------------------
552
+
553
+ /** How far back the lineage reader looks (mtime of the record file). */
554
+ export const RETRY_SCAN_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
555
+
556
+ /** Upper bound on records read for one lineage answer. */
557
+ const RETRY_SCAN_CAP = 200;
558
+
559
+ /** The scan window in whole days (the user-facing caveat derives from it). */
560
+ export const RETRY_SCAN_WINDOW_DAYS = RETRY_SCAN_WINDOW_MS / (24 * 60 * 60 * 1000);
561
+
562
+ /** The short form rendered by notices: the first 8 hex characters of a UUID. */
563
+ const SHORT_AGENT_ID_RE = /^[0-9a-f]{8}$/i;
564
+
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([
570
+ 'id',
571
+ 'dispatchId',
572
+ 'resumeOf',
573
+ 'attempt',
574
+ 'status',
575
+ 'startedAt',
576
+ ]);
577
+
578
+ const AGENT_STATUSES: ReadonlySet<string> = new Set([
579
+ 'pending',
580
+ 'running',
581
+ 'steered',
582
+ 'completed',
583
+ 'failed',
584
+ 'stopped',
585
+ ]);
586
+
587
+ /** One record's lineage-relevant fields — never its result/transcript. */
588
+ export interface RetryRecordIdentity {
589
+ id: string;
590
+ dispatchId?: string;
591
+ resumeOf?: string;
592
+ attempt: number;
593
+ status: AgentStatus;
594
+ /** Epoch milliseconds (agent records store ms; registry ISO is normalised). */
595
+ startedAt: number;
596
+ }
597
+
598
+ export type AgentIdResolution =
599
+ | { kind: 'resolved'; id: string }
600
+ | { kind: 'ambiguous'; matches: string[] }
601
+ | { kind: 'unresolved'; id: string };
602
+
603
+ export interface RetryLineage {
604
+ id: string;
605
+ /** Every known attempt of the logical dispatch, ordered by attempt/start. */
606
+ family: RetryRecordIdentity[];
607
+ /** The requested id's own record, when it exists. */
608
+ found: RetryRecordIdentity | null;
609
+ /** The newest attempt in the family. */
610
+ latest: RetryRecordIdentity | null;
611
+ /** Registry entries that name the id itself or a member of its family. */
612
+ inflight: InflightRun[];
613
+ }
614
+
615
+ function isSafeAgentId(id: string): boolean {
616
+ try {
617
+ assertSafeAgentId(id);
618
+ return true;
619
+ } catch {
620
+ return false;
621
+ }
622
+ }
623
+
624
+ export function isTerminalAgentStatus(status: AgentStatus): boolean {
625
+ return status === 'completed' || status === 'failed' || status === 'stopped';
626
+ }
627
+
628
+ function isAgentStatus(value: unknown): value is AgentStatus {
629
+ return typeof value === 'string' && AGENT_STATUSES.has(value);
630
+ }
631
+
632
+ function normalizeStartedAt(value: unknown): number | null {
633
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
634
+ if (typeof value === 'string') {
635
+ const parsed = Date.parse(value);
636
+ if (Number.isFinite(parsed)) return parsed;
637
+ }
638
+ return null;
639
+ }
640
+
641
+ function safeListInflightRuns(): InflightRun[] {
642
+ try {
643
+ return listInflightRuns();
644
+ } catch {
645
+ return [];
646
+ }
647
+ }
648
+
649
+ /**
650
+ * Resolve the tool's id parameter before any record lookup. A full UUID passes
651
+ * through; a unique 8-hex prefix resolves to its full id; multiple matches are
652
+ * returned as `ambiguous` (fail closed); anything else stays unresolved and
653
+ * follows today's not-found path.
654
+ *
655
+ * Candidates come from live records, the agent store's file names, and the
656
+ * in-flight registry — every surface on which an id can currently exist.
657
+ */
658
+ export function resolveAgentId(raw: string): AgentIdResolution {
659
+ if (isSafeAgentId(raw)) return { kind: 'resolved', id: raw };
660
+ if (!SHORT_AGENT_ID_RE.test(raw)) return { kind: 'unresolved', id: raw };
661
+
662
+ const needle = raw.toLowerCase();
663
+ const matches = new Set<string>();
664
+
665
+ for (const id of agents.keys()) {
666
+ if (id.toLowerCase().startsWith(needle)) matches.add(id);
667
+ }
668
+
669
+ try {
670
+ if (existsSync(STORAGE_DIR)) {
671
+ for (const file of readdirSync(STORAGE_DIR)) {
672
+ if (!file.endsWith('.json')) continue;
673
+ const id = file.slice(0, -'.json'.length);
674
+ if (isSafeAgentId(id) && id.toLowerCase().startsWith(needle)) matches.add(id);
675
+ }
676
+ }
677
+ } catch {
678
+ // An unreadable store is not a prefix match — fall through to the registry.
679
+ }
680
+
681
+ for (const run of safeListInflightRuns()) {
682
+ if (run.id.toLowerCase().startsWith(needle)) matches.add(run.id);
683
+ }
684
+
685
+ const ids = [...matches].sort();
686
+ if (ids.length === 1) return { kind: 'resolved', id: ids[0] };
687
+ if (ids.length > 1) return { kind: 'ambiguous', matches: ids };
688
+ return { kind: 'unresolved', id: raw };
689
+ }
690
+
691
+ // ---------------------------------------------------------------------------
692
+ // Shallow JSON identity reader
693
+ // ---------------------------------------------------------------------------
694
+
695
+ type JsonScalar = string | number | boolean | null;
696
+
697
+ function skipWhitespace(text: string, index: number): number {
698
+ let i = index;
699
+ while (i < text.length && /\s/.test(text[i])) i += 1;
700
+ return i;
701
+ }
702
+
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 } {
724
+ let i = start + 1;
725
+ let escaped = false;
726
+ while (i < text.length) {
727
+ const char = text[i];
728
+ if (escaped) {
729
+ escaped = false;
730
+ i += 1;
731
+ continue;
732
+ }
733
+ if (char === '\\') {
734
+ escaped = true;
735
+ i += 1;
736
+ continue;
737
+ }
738
+ if (char === '"') {
739
+ const raw = text.slice(start, i + 1);
740
+ i += 1;
741
+ try {
742
+ return { value: JSON.parse(raw) as string, end: i };
743
+ } catch {
744
+ return { value: raw.slice(1, -1), end: i };
745
+ }
746
+ }
747
+ i += 1;
748
+ }
749
+ return { value: text.slice(start + 1), end: i };
750
+ }
751
+
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 {
773
+ if (text[start] === '"') return readJsonStringAt(text, start).end;
774
+ if (text[start] === '{' || text[start] === '[') {
775
+ let depth = 0;
776
+ let inString = false;
777
+ let escaped = false;
778
+ for (let i = start; i < text.length; i += 1) {
779
+ const char = text[i];
780
+ if (inString) {
781
+ if (escaped) escaped = false;
782
+ else if (char === '\\') escaped = true;
783
+ else if (char === '"') inString = false;
784
+ continue;
785
+ }
786
+ if (char === '"') inString = true;
787
+ else if (char === '{' || char === '[') depth += 1;
788
+ else if (char === '}' || char === ']') {
789
+ depth -= 1;
790
+ if (depth === 0) return i + 1;
791
+ }
792
+ }
793
+ return text.length;
794
+ }
795
+ let i = start;
796
+ while (i < text.length && text[i] !== ',' && text[i] !== '}') i += 1;
797
+ return i;
798
+ }
799
+
800
+ function parseJsonScalar(raw: string): JsonScalar {
801
+ if (raw === 'true') return true;
802
+ if (raw === 'false') return false;
803
+ if (raw === 'null') return null;
804
+ if (raw !== '' && Number.isFinite(Number(raw))) return Number(raw);
805
+ return raw;
806
+ }
807
+
808
+ /**
809
+ * Extract top-level scalar fields from a record's JSON text. Nested values
810
+ * (notably `result.messages` and `finalOutput`) are skipped, not parsed — the
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).
827
+ */
828
+ export function scanTopLevelScalars(text: string, wanted: ReadonlySet<string>): Map<string, JsonScalar> {
829
+ const out = new Map<string, JsonScalar>();
830
+ let i = skipWhitespace(text, 0);
831
+ if (text[i] !== '{') return out;
832
+ i += 1;
833
+
834
+ while (i < text.length) {
835
+ i = skipWhitespace(text, i);
836
+ if (i >= text.length) break;
837
+ const char = text[i];
838
+ if (char === '}') break;
839
+ if (char === ',') {
840
+ i += 1;
841
+ continue;
842
+ }
843
+ if (char !== '"') {
844
+ // Malformed object: make progress rather than looping forever.
845
+ i += 1;
846
+ continue;
847
+ }
848
+
849
+ const keyStart = i;
850
+ const key = readJsonStringAt(text, i);
851
+ i = skipWhitespace(text, key.end);
852
+ if (text[i] !== ':') break;
853
+ i = skipWhitespace(text, i + 1);
854
+ if (i >= text.length) break;
855
+
856
+ if (wanted.has(key.value)) {
857
+ const valueStart = text[i];
858
+ if (valueStart === '"') {
859
+ const value = readJsonStringAt(text, i);
860
+ out.set(key.value, value.value);
861
+ i = value.end;
862
+ } else if (valueStart === '{' || valueStart === '[') {
863
+ i = skipJsonValue(text, i);
864
+ } else {
865
+ let end = i;
866
+ while (end < text.length && text[end] !== ',' && text[end] !== '}') end += 1;
867
+ out.set(key.value, parseJsonScalar(text.slice(i, end).trim()));
868
+ i = end;
869
+ }
870
+ } else {
871
+ i = skipJsonValue(text, i);
872
+ }
873
+
874
+ if (i <= keyStart) break;
875
+ }
876
+
877
+ return out;
878
+ }
879
+
880
+ /** Read one agent record's identity fields; null when malformed/incomplete. */
881
+ function readAgentIdentity(file: string): RetryRecordIdentity | null {
882
+ let text: string;
883
+ try {
884
+ text = readFileSync(file, 'utf-8');
885
+ } catch {
886
+ return null;
887
+ }
888
+
889
+ const fields = scanTopLevelScalars(text, RETRY_IDENTITY_KEYS);
890
+ const embeddedId = fields.get('id');
891
+ const id = typeof embeddedId === 'string' ? embeddedId : basename(file, '.json');
892
+ if (!isSafeAgentId(id)) return null;
893
+
894
+ const status = fields.get('status');
895
+ if (!isAgentStatus(status)) return null;
896
+
897
+ const startedAt = normalizeStartedAt(fields.get('startedAt'));
898
+ if (startedAt === null) return null;
899
+
900
+ const attemptValue = fields.get('attempt');
901
+ const attempt =
902
+ typeof attemptValue === 'number' && Number.isFinite(attemptValue) && attemptValue > 0
903
+ ? Math.floor(attemptValue)
904
+ : 1;
905
+
906
+ const dispatchId = fields.get('dispatchId');
907
+ const resumeOf = fields.get('resumeOf');
908
+ return {
909
+ id,
910
+ status,
911
+ startedAt,
912
+ attempt,
913
+ ...(typeof dispatchId === 'string' ? { dispatchId } : {}),
914
+ ...(typeof resumeOf === 'string' ? { resumeOf } : {}),
915
+ };
916
+ }
917
+
918
+ /**
919
+ * The bounded store read: stat every record (cheap), keep the ones inside the
920
+ * mtime window, sort newest-first, cap at `RETRY_SCAN_CAP`, then read only the
921
+ * surviving files' identity fields. Corrupt/unsafe records are skipped.
922
+ */
923
+ function readRecentAgentIdentities(): RetryRecordIdentity[] {
924
+ let files: string[];
925
+ try {
926
+ if (!existsSync(STORAGE_DIR)) return [];
927
+ files = readdirSync(STORAGE_DIR);
928
+ } catch {
929
+ return [];
930
+ }
931
+
932
+ const cutoff = Date.now() - RETRY_SCAN_WINDOW_MS;
933
+ const recent: Array<{ file: string; mtime: number }> = [];
934
+ for (const file of files) {
935
+ if (!file.endsWith('.json')) continue;
936
+ const id = file.slice(0, -'.json'.length);
937
+ if (!isSafeAgentId(id)) continue;
938
+ const fullPath = join(STORAGE_DIR, file);
939
+ try {
940
+ const stat = statSync(fullPath);
941
+ if (stat.mtimeMs >= cutoff) recent.push({ file: fullPath, mtime: stat.mtimeMs });
942
+ } catch {
943
+ // Vanished between readdir and stat — not a lineage candidate.
944
+ }
945
+ }
946
+
947
+ recent.sort((a, b) => b.mtime - a.mtime);
948
+ const records: RetryRecordIdentity[] = [];
949
+ for (const entry of recent.slice(0, RETRY_SCAN_CAP)) {
950
+ const record = readAgentIdentity(entry.file);
951
+ if (record) records.push(record);
952
+ }
953
+ return records;
954
+ }
955
+
956
+ function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
957
+ const startedAt = normalizeStartedAt(agent.startedAt);
958
+ if (startedAt === null) return null;
959
+ return {
960
+ id: agent.id,
961
+ status: agent.status,
962
+ startedAt,
963
+ attempt: agent.attempt ?? 1,
964
+ ...(agent.dispatchId ? { dispatchId: agent.dispatchId } : {}),
965
+ ...(agent.resumeOf ? { resumeOf: agent.resumeOf } : {}),
966
+ };
967
+ }
968
+
969
+ function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
970
+ const startedAt = normalizeStartedAt(run.startedAt);
971
+ if (startedAt === null) return null;
972
+ return {
973
+ id: run.id,
974
+ status: 'running',
975
+ startedAt,
976
+ attempt: run.attempt ?? 1,
977
+ ...(run.dispatchId ? { dispatchId: run.dispatchId } : {}),
978
+ };
979
+ }
980
+
981
+ /**
982
+ * Find the logical dispatch family for `id`.
983
+ *
984
+ * Family membership is `dispatchId` (inherited by every attempt, including a
985
+ * manual attempt 3 whose `resumeOf` names attempt 2). Records without a
986
+ * `dispatchId` fall back to direct `resumeOf` matching. The registry is folded
987
+ * in so an in-flight retry is visible without a store record.
988
+ */
989
+ export function findRetryLineage(id: string, source?: BackgroundAgent | null): RetryLineage {
990
+ const empty: RetryLineage = { id, family: [], found: null, latest: null, inflight: [] };
991
+ if (!isSafeAgentId(id)) return empty;
992
+
993
+ const byId = new Map<string, RetryRecordIdentity>();
994
+ for (const record of readRecentAgentIdentities()) byId.set(record.id, record);
995
+
996
+ const sourceIdentity = source && source.id === id ? identityFromAgent(source) : null;
997
+ if (sourceIdentity) byId.set(id, sourceIdentity);
998
+
999
+ const registry = safeListInflightRuns();
1000
+ for (const run of registry) {
1001
+ const identity = identityFromRegistry(run);
1002
+ // A persisted record is authoritative over the registry's "running" view.
1003
+ if (identity && !byId.has(identity.id)) byId.set(identity.id, identity);
1004
+ }
1005
+
1006
+ const all = [...byId.values()];
1007
+ const found = byId.get(id) ?? sourceIdentity;
1008
+ // Newest-first so the dispatch chosen for an unknown id comes from its most
1009
+ // recent direct descendant, not from readdir order.
1010
+ const direct = all
1011
+ .filter((record) => record.resumeOf === id && record.id !== id)
1012
+ .sort((a, b) => b.attempt - a.attempt || b.startedAt - a.startedAt);
1013
+ const familyDispatch = found?.dispatchId ?? direct[0]?.dispatchId;
1014
+
1015
+ const members = familyDispatch
1016
+ ? all.filter((record) => record.dispatchId === familyDispatch)
1017
+ : [...(found ? [found] : []), ...direct];
1018
+
1019
+ const family = [...new Map(members.map((record) => [record.id, record])).values()];
1020
+ family.sort(
1021
+ (a, b) => a.attempt - b.attempt || a.startedAt - b.startedAt || a.id.localeCompare(b.id),
1022
+ );
1023
+
1024
+ const latest = family.length > 0 ? family[family.length - 1] : null;
1025
+ const inflight = registry.filter(
1026
+ (run) => run.id === id || (familyDispatch !== undefined && run.dispatchId === familyDispatch),
1027
+ );
1028
+
1029
+ return { id, family, found, latest, inflight };
1030
+ }
1031
+
260
1032
  /**
261
1033
  * Option B U1 (D3): read-modify-write the interrupted mark onto a persisted
262
1034
  * agent record. Idempotent: an already-marked record is returned unchanged.
@@ -465,6 +1237,42 @@ export async function steerAgent(id: string, message: string): Promise<Backgroun
465
1237
  */
466
1238
  export { transcriptPath as getTranscriptPath } from './transcript-path';
467
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
+
468
1276
  /**
469
1277
  * Spawn a background session using pi's session API
470
1278
  *
@@ -481,6 +1289,10 @@ export async function spawnBackgroundSession(
481
1289
  model?: string;
482
1290
  thinkingLevel?: ThinkingLevel;
483
1291
  systemPrompt?: string;
1292
+ /** Issue #411: conductor-authored resume context for an auto-retry,
1293
+ * appended to the system prompt as a `<resume-context>` section —
1294
+ * never inside the `<task>` fence. */
1295
+ resumeContext?: string;
484
1296
  cwd?: string;
485
1297
  toolOptions?: SubagentToolOptions;
486
1298
  /** Per-agent deadline in ms — the session is aborted when exceeded (issue #28 W3). */
@@ -510,8 +1322,22 @@ export async function spawnBackgroundSession(
510
1322
  let resolveNext!: () => void;
511
1323
  spawnQueue = new Promise<void>(r => { resolveNext = r; });
512
1324
  await prev;
513
-
514
- try {
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
+ };
1339
+
1340
+ try {
515
1341
  const id = generateUUID();
516
1342
  const effectiveCwd = params.cwd ?? ctx.cwd;
517
1343
  // Dynamic import — static import fails under concurrent jiti loads
@@ -537,6 +1363,11 @@ export async function spawnBackgroundSession(
537
1363
  // inspection, no U4 resume) and the SDK default (`~/.pi/agent/sessions/<cwd-key>/`,
538
1364
  // passed as `undefined`) would scatter our runs into the global store. The
539
1365
  // directory lives beside the agent record: `.pi/subagents/sessions/<id>/`.
1366
+ //
1367
+ // Issue #408: create the sessions root owner-only BEFORE the SDK sees it —
1368
+ // its `mkdirSync` (and ours) applies `mode` only on CREATE, so a pre-existing
1369
+ // 0o755 root would otherwise stay traversable.
1370
+ ensureSessionsRoot();
540
1371
  const sessionManager = SessionManager.create(effectiveCwd, backgroundSessionDir(id));
541
1372
  // Capture the exact path the SDK will write. The settle path derives the
542
1373
  // prune target from THIS (not from a freshly-computed STORAGE_DIR path) so a
@@ -570,9 +1401,25 @@ export async function spawnBackgroundSession(
570
1401
  // plant a newline-named dir + symlink leaf. Not exploitable realistically;
571
1402
  // do not "simplify" the frame (e.g. dropping the "/" marker) without
572
1403
  // re-verifying this property.
573
- const literalPrompt = params.systemPrompt?.trim()
574
- ? `\n<system-prompt>\n${params.systemPrompt}\n</system-prompt>\n`
575
- : undefined;
1404
+ // Issue #411: the appendSystemPrompt entries are built as an ordered array —
1405
+ // <system-prompt> first, then <resume-context> — so an auto-retry's resume
1406
+ // preamble rides the system-prompt side and never the <task> fence.
1407
+ const sections: string[] = [];
1408
+ if (params.systemPrompt?.trim()) {
1409
+ sections.push(`\n<system-prompt>\n${params.systemPrompt}\n</system-prompt>\n`);
1410
+ }
1411
+ if (params.resumeContext?.trim()) {
1412
+ sections.push(`\n<resume-context>\n${params.resumeContext.trim()}\n</resume-context>\n`);
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);
576
1423
  //
577
1424
  // F25: ALWAYS build our own loader (even without a systemPrompt). If
578
1425
  // resourceLoader is undefined, createAgentSession constructs its own
@@ -589,7 +1436,7 @@ export async function spawnBackgroundSession(
589
1436
  cwd: effectiveCwd,
590
1437
  agentDir,
591
1438
  settingsManager,
592
- ...(literalPrompt ? { appendSystemPrompt: [literalPrompt] } : {}),
1439
+ ...(sections.length ? { appendSystemPrompt: sections } : {}),
593
1440
  noExtensions: true,
594
1441
  noSkills: true,
595
1442
  });
@@ -618,6 +1465,15 @@ export async function spawnBackgroundSession(
618
1465
  ...(params.toolOptions?.noBuiltinTools ? { noTools: 'builtin' as const } : {}),
619
1466
  });
620
1467
 
1468
+ // Issue #408: the SDK's `SessionManager.create` made the per-run dir with the
1469
+ // process default mode (0o755). THE DIR MODE IS THE CONFIDENTIALITY BOUNDARY
1470
+ // — no traversal means the session files inside are unreachable by other
1471
+ // local users; the file repair below is defense-in-depth. Best-effort: a
1472
+ // permission failure here must never break a spawn.
1473
+ const spawnedSessionDir = sessionFile ? dirname(sessionFile) : backgroundSessionDir(id);
1474
+ ensureOwnerOnlyDir(spawnedSessionDir);
1475
+ repairOwnerOnlyFiles(spawnedSessionDir);
1476
+
621
1477
  // Set session name
622
1478
  session.setSessionName(`background-${id.slice(0, 8)}`);
623
1479
 
@@ -628,6 +1484,11 @@ export async function spawnBackgroundSession(
628
1484
  const attempt = params.attempt ?? 1;
629
1485
  const owner = currentProcessOwner();
630
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
+
631
1492
  // Create agent record
632
1493
  const agent: BackgroundAgent = {
633
1494
  id,
@@ -636,6 +1497,11 @@ export async function spawnBackgroundSession(
636
1497
  description: params.description || params.task.slice(0, 50),
637
1498
  status: 'running',
638
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,
639
1505
  task: params.task,
640
1506
  model: params.model || 'unknown',
641
1507
  thinkingLevel: params.thinkingLevel || 'medium',
@@ -679,6 +1545,12 @@ export async function spawnBackgroundSession(
679
1545
  attempt,
680
1546
  owner,
681
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,
682
1554
  };
683
1555
  persistRunRecord(pi, run, "background");
684
1556
 
@@ -689,48 +1561,134 @@ export async function spawnBackgroundSession(
689
1561
  //
690
1562
  // U2 (D2) retention: this is the SINGLE terminal choke point for a background
691
1563
  // run — git-setup refusal, a synchronous prompt throw, the .then completed /
692
- // provider-failed / aborted branches, the .catch stopped / failed branches and
693
- // the markTerminalBestEffort catch-all ALL land here exactly once (the
694
- // runFinalized guard). Pruning here therefore covers every settle path. The
695
- // index.ts poller crash notices are NOT settlements (they flip only the live
696
- // UI state and leave the run/agent record to this settle); an interrupted run
697
- // (U1 boot-scan mark) never reaches this function and KEEPS its file (D3).
698
- 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. */
699
1619
  const finalizeRunEntry = (
700
1620
  status: "done" | "failed",
701
1621
  error?: string,
702
- terminal?: { stopReason?: string; errorCategory?: ErrorCategory },
703
- ): void => {
704
- if (runFinalized) return;
705
- runFinalized = true;
706
- // U2 (D2): drop the persisted session now that the run is terminal. Done
707
- // FIRST (before the run-entry write below) so a persist throw cannot leave
708
- // a terminal run's session file behind. Interrupted runs keep theirs.
709
- if (!agent.interruptedAt) {
710
- pruneSessionDir(
711
- id,
712
- agent._sessionFile ? dirname(agent._sessionFile) : backgroundSessionDir(id),
713
- );
714
- }
1622
+ terminal?: { stopReason?: string; errorCategory?: ErrorCategory; prune?: boolean },
1623
+ ): SubagentRun | undefined => {
715
1624
  const usage = agent.result?.usage ?? EMPTY_USAGE;
716
1625
  const finalOutput = agent.finalOutput ?? "";
717
- // Issue #179 (D1/D2): the classifier's explicit category wins (it knows the
718
- // terminal stopReason); otherwise fall back to the legacy message-based
719
- // classification (refused spawns, sync throws, preflight rejections, the
720
- // catch-all) so no failure is ever left uncategorized.
721
- const errorCategory =
722
- status === "failed"
723
- ? terminal?.errorCategory ??
724
- (error
725
- ? classifyError({
726
- messages: [],
727
- usage: { ...EMPTY_USAGE },
728
- exitCode: 1,
729
- stderr: "",
730
- errorMessage: error,
731
- })
732
- : undefined)
733
- : undefined;
1626
+ // The TRUE category of THIS call — see the note on `classifyFailure`.
1627
+ const errorCategory = classifyFailure(status, error, terminal);
1628
+ // U2 (D2) prune + #404 retention. THE INVARIANT: the prune/mark decision
1629
+ // precedes the run-record write, and everything above it is pure — so no
1630
+ // throw between the decision and the write can leave a terminal run's session
1631
+ // dir behind. Interrupted runs keep theirs (D3) and are never marked.
1632
+ //
1633
+ // The retention gate is the auto-retry predicate itself (#365/#401): only a
1634
+ // run that will be re-dispatched has a reader for the retained session, and
1635
+ // it is built from the values this record is about to carry, so the reader
1636
+ // and the retainer can never disagree.
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;
1643
+ // The CAPTURED dir — tests swap STORAGE_DIR per case, and a mid-run change
1644
+ // of root must never mis-target the delete or the marker.
1645
+ const sessionDir = agent._sessionFile ? dirname(agent._sessionFile) : backgroundSessionDir(id);
1646
+ const retained = isTransportRetryable({
1647
+ status,
1648
+ errorCategory,
1649
+ errorMessage: error,
1650
+ attempt: run.attempt,
1651
+ originalParams: run.originalParams,
1652
+ });
1653
+ // Marker write failure => prune: retention is an optimization, boundedness
1654
+ // is the invariant (an unmarked retained dir would escape the sweep).
1655
+ if (!retained || !retainSessionDir(id, sessionDir)) {
1656
+ pruneSessionDir(id, sessionDir);
1657
+ }
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
+ }
734
1692
  // Issue #187: capture the RAW terminal reason BEFORE coercion. `finalTurnError`
735
1693
  // means "the final turn was a PROVIDER error" (isProviderError); deriving it
736
1694
  // from the COERCED reason would turn a missing/success reason into 'error' and
@@ -768,6 +1726,10 @@ export async function spawnBackgroundSession(
768
1726
  : run.originalParams,
769
1727
  };
770
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;
771
1733
  // Issue #179 (D6): the explicit settle line — the log's job is to record the
772
1734
  // CLASSIFIED OUTCOME, which cwd alone can never convey.
773
1735
  log.info("Background run settled", {
@@ -779,10 +1741,180 @@ export async function spawnBackgroundSession(
779
1741
  errorCategory,
780
1742
  error: error ?? null,
781
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);
782
1885
  };
783
1886
 
784
- // Start transcript for this agent
785
- 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
+ }
786
1918
 
787
1919
  // Store session ref for live monitor polling
788
1920
  agent._sessionRef = session;
@@ -852,15 +1984,6 @@ export async function spawnBackgroundSession(
852
1984
  // hard failure — never spawn an unisolated background agent that was asked
853
1985
  // for isolation (fail-loud, same principle as foreground's fallback but
854
1986
  // background cannot warn-and-continue safely).
855
- let headState: HeadState | undefined;
856
- let workBranchName: string | undefined;
857
- let releaseGitLock: (() => void) | undefined;
858
- // Idempotency guard for cleanupWorkBranch: it must be safe to call from both
859
- // the normal settle path and the catch-all that runs when a settle step
860
- // throws FIRST (before its own cleanup call). Without this the second call
861
- // would re-restore/re-delete and log spurious warnings.
862
- let gitCleanupDone = false;
863
- const gitCwd = params.cwd ?? ctx.cwd;
864
1987
  if (params.gitMode === 'branch') {
865
1988
  // C2: serialize the FULL branch lifecycle per repo. The spawnQueue only
866
1989
  // covers setup; without this lock, a second concurrent branch-mode spawn
@@ -868,21 +1991,94 @@ export async function spawnBackgroundSession(
868
1991
  // fight over the shared working tree (stranding the repo on an orphan
869
1992
  // branch). The lock is released in cleanupWorkBranch (or on setup throw).
870
1993
  // Key: resolved repository root, cwd fallback for non-repo paths (#224).
871
- 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();
872
2049
  const prev = gitBranchLocks.get(lockKey) ?? Promise.resolve();
873
2050
  let release!: () => void;
874
2051
  const gate = new Promise<void>(r => { release = r; });
875
2052
  const entry = prev.then(() => gate);
876
2053
  gitBranchLocks.set(lockKey, entry);
877
2054
  await prev;
2055
+ gitBranchLockOwners.set(lockKey, id);
878
2056
  releaseGitLock = () => {
879
2057
  // Delete the map entry ONLY if we are still the head of the chain — a
880
- // 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).
881
2061
  if (gitBranchLocks.get(lockKey) === entry) gitBranchLocks.delete(lockKey);
2062
+ if (gitBranchLockOwners.get(lockKey) === id) gitBranchLockOwners.delete(lockKey);
882
2063
  release();
883
2064
  };
884
2065
 
885
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
+
886
2082
  // C1: isolation is only real when the base tree is clean. A dirty tree
887
2083
  // would ride onto the work branch, get clobbered by the agent's writes,
888
2084
  // and leak back into the base working tree on switch — refuse loudly.
@@ -893,15 +2089,48 @@ export async function spawnBackgroundSession(
893
2089
  );
894
2090
  }
895
2091
  headState = getHeadState(gitCwd);
896
- 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);
897
2115
  if (branchResult.ok) {
898
- 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);
899
2123
  log.info('Created work branch for background agent', {
900
2124
  branch: workBranchName,
901
2125
  base: headState.branch,
902
2126
  agentId: id,
903
2127
  });
904
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;
905
2134
  throw new Error(`createWorkBranch failed: ${branchResult.error}`);
906
2135
  }
907
2136
  } catch (err) {
@@ -910,17 +2139,13 @@ export async function spawnBackgroundSession(
910
2139
  // (get_subagent_result would otherwise report 'running' forever).
911
2140
  releaseGitLock?.();
912
2141
  releaseGitLock = undefined;
913
- // 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.
914
2143
  const sanitizedError = sanitizeErrorMessage((err as Error).message, effectiveCwd);
915
- try {
916
- updateAgentStatus(id, 'failed',
917
- `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
918
- // Issue #98: the refused spawn is a failure — finalize the run entry so
919
- // no zombie 'running' entry survives (lockstep with the record flip).
920
- finalizeRunEntry('failed',
921
- `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}`);
922
- transcript.completeTranscript(id, 'failed');
923
- } 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}`);
924
2149
  throw new Error(
925
2150
  `gitMode 'branch' requested but work branch setup failed: ${sanitizedError}. ` +
926
2151
  `Refusing to spawn the background agent unisolated.`,
@@ -929,80 +2154,57 @@ export async function spawnBackgroundSession(
929
2154
  }
930
2155
  }
931
2156
 
932
- // Branch teardown — commit the agent's work (so the diff is real), capture
933
- // the diff, switch back to the original branch, delete the work branch, and
934
- // release the per-repo git lock. Runs on EVERY settle path. C1: agents
935
- // rarely commit, so captureDiff(base...HEAD) alone would be empty and the
936
- // uncommitted edits would leak into the base working tree on switch —
937
- // commitAll first makes the diff real and the switch clean.
938
- const cleanupWorkBranch = (): { gitBranch?: string; gitDiff?: string } => {
939
- if (gitCleanupDone || !workBranchName || !headState) return {};
940
- gitCleanupDone = true;
941
- const info: { gitBranch?: string; gitDiff?: string } = { gitBranch: workBranchName };
942
- // The lock MUST be released on every exit path — early returns included.
943
- try {
944
- try {
945
- const stillOnOurBranch = getCurrentBranch(gitCwd) === workBranchName;
946
- if (!stillOnOurBranch) {
947
- log.warn(`cleanupWorkBranch: tree moved off ${workBranchName} — skipping switch/delete`, {
948
- agentId: id,
949
- });
950
- return info;
951
- }
952
- } catch (err) {
953
- log.warn(`getCurrentBranch failed during cleanup for background agent ${id}`, {
954
- error: (err as Error).message,
955
- });
956
- return info;
957
- }
958
- try {
959
- // C1: commit the agent's work so captureDiff sees it. If no identity is
960
- // configured, fall back to capturing the working-tree diff directly.
961
- const dirty = hasUncommittedChanges(gitCwd);
962
- if (dirty) {
963
- const commitResult = commitAll(gitCwd, `brl-subagent ${id}: background work`);
964
- if (commitResult.ok) {
965
- log.info('Committed background agent work on work branch', {
966
- sha: commitResult.sha,
967
- branch: workBranchName,
968
- agentId: id,
969
- });
970
- } else {
971
- log.warn(`commitAll failed for background agent ${id} — capturing working diff`, {
972
- error: commitResult.error,
973
- });
974
- const workingDiff = captureWorkingDiff(gitCwd);
975
- if (workingDiff) info.gitDiff = workingDiff;
976
- }
977
- }
978
- const diffResult = captureDiff(gitCwd, headState.sha);
979
- if (diffResult.ok && diffResult.diff.trim()) {
980
- // Merge committed + working diffs — either can exist alone.
981
- info.gitDiff = info.gitDiff
982
- ? `${info.gitDiff}\n${diffResult.diff}`
983
- : diffResult.diff;
984
- }
985
- } catch (err) {
986
- log.warn(`captureDiff failed for background agent ${id}`, { error: (err as Error).message });
987
- }
988
- try {
989
- const restoreResult = restoreHead(gitCwd, headState);
990
- if (!restoreResult.ok) {
991
- log.warn(`restoreHead failed for background agent ${id}`, { error: restoreResult.error });
992
- }
993
- } catch (err) {
994
- log.warn(`restoreHead failed for background agent ${id}`, { error: (err as Error).message });
995
- }
996
- try {
997
- deleteBranch(gitCwd, workBranchName);
998
- } catch (err) {
999
- log.warn(`deleteBranch failed for background agent ${id}`, { error: (err as Error).message });
1000
- }
1001
- } finally {
1002
- releaseGitLock?.();
1003
- releaseGitLock = undefined;
2157
+ // Issue #376 (audit D8): the aborted settle path is reached from BOTH
2158
+ // handlers — the .then (probe contract: an abort RESOLVES the prompt) and the
2159
+ // .catch (the prompt rejects while the agent is already 'stopped'). Both must
2160
+ // record the same partial-work result and the same retryable failure, so they
2161
+ // share one helper.
2162
+ // - `gitInfo` is caller-captured: cleanupWorkBranch is once-per-run
2163
+ // (idempotent), and the .catch failed path reuses that same capture.
2164
+ // - `stopReason` is caller-supplied: the .then can narrow it from the last
2165
+ // assistant message; the .catch has no message to read.
2166
+ const finalizeAbortedRun = (
2167
+ gitInfo: { gitBranch?: string; gitDiff?: string },
2168
+ stopReason: string,
2169
+ ): void => {
2170
+ // W4/M1: capture whatever the branch produced before discarding it — an
2171
+ // aborted background agent's partial work is still worth reviewing, and
2172
+ // must be RECORDED, not just captured-and-deleted.
2173
+ if (gitInfo.gitBranch) {
2174
+ agent.result = {
2175
+ ...(agent.result ?? {}),
2176
+ exitCode: 1,
2177
+ messages: [],
2178
+ stderr: '',
2179
+ usage: agent.result?.usage ?? EMPTY_USAGE,
2180
+ stopReason: 'aborted',
2181
+ gitBranch: gitInfo.gitBranch,
2182
+ gitDiff: gitInfo.gitDiff,
2183
+ } as SubagentResult;
2184
+ agents.set(id, agent);
2185
+ persistAgent(agent);
1004
2186
  }
1005
- return info;
2187
+ // Issue #98: aborts/timeouts are retryable failures (retry schema:
2188
+ // timeout/abort counts as failure) — finalize the run entry.
2189
+ // Issue #122: a timed-out run burned tokens — record the real usage
2190
+ // (the git-diff block above must not leave the empty fallback).
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();
2203
+ // Issue #120 (Track 1): agent.error carries the reason when the stop was a
2204
+ // deadline timeout ('Timed out after Xms' → 'timeout'); a user cancel
2205
+ // (stop_subagent) sets no error, so fall back to the honest user-abort
2206
+ // stamp (→ 'aborted') instead of the old ambiguous 'Aborted or timed out'.
2207
+ finalizeRunEntry('failed', agent.error ?? SUBAGENT_ABORTED_MESSAGE, { stopReason });
1006
2208
  };
1007
2209
 
1008
2210
  // Issue #53: the settle handlers (.then/.catch below) run in promise
@@ -1073,6 +2275,145 @@ export async function spawnBackgroundSession(
1073
2275
  // The session will run independently
1074
2276
  // F27: wrap in the task-as-data fence — the user message is DATA, not
1075
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
+
1076
2417
  // NOTE: if prompt() throws SYNCHRONOUSLY, the .then/.catch below never
1077
2418
  // attach and cleanupWorkBranch would never run — catch here so the work
1078
2419
  // branch is not orphaned (it is a real filesystem branch).
@@ -1080,50 +2421,17 @@ export async function spawnBackgroundSession(
1080
2421
  try {
1081
2422
  runPromise = session.prompt(wrapTask(params.task));
1082
2423
  } catch (err) {
1083
- cleanupWorkBranch();
1084
2424
  // Issue #98 (review F1): a synchronous prompt() throw never reaches the
1085
2425
  // settle handlers — finalize the run entry so no zombie 'running' entry
1086
2426
  // survives (findSpawnRunById would otherwise resolve and retry a run that
1087
- // never started).
1088
- 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));
1089
2430
  throw err;
1090
2431
  }
1091
2432
 
1092
- // W3 (issue #28): per-agent deadline — abort the session when exceeded.
1093
- // Armed immediately after the prompt call so in-prompt preflight (auth
1094
- // check, model resolution) counts toward the deadline; the abort lands in
1095
- // the .then below as an aborted run (probe contract). We pre-set the status
1096
- // so the .then keeps 'stopped' with the timeout reason recorded. The raw
1097
- // value is normalized here (issue #240): a raw >=2^31 or Infinity would make
1098
- // Node fire the timer at ~1ms (instant kill), so normalizeTimeout maps it to
1099
- // undefined. An explicit timeout is HONORED verbatim (no ceiling); only the
1100
- // no-timeout fallback uses the 30m background default. The `params.timeout`
1101
- // guard below keeps this timer unarmed on the no-timeout path, where the
1102
- // index.ts deadline timer owns the no-timeout default (no redundant timer).
1103
- let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
1104
- if (params.timeout && params.timeout > 0) {
1105
- timeoutHandle = setTimeout(() => {
1106
- try {
1107
- if (agent.completedAt) return; // already settled — nothing to abort
1108
- updateAgentStatus(id, 'stopped', `Timed out after ${params.timeout}ms`);
1109
- transcript.completeTranscript(id, 'stopped');
1110
- session.abort().catch(() => {
1111
- // Abort can reject if the session is mid-dispose; the status flip
1112
- // above is already recorded, so this is non-fatal.
1113
- });
1114
- } catch (err) {
1115
- // Timer callbacks must never throw uncaught — that crashes the host
1116
- // process. updateAgentStatus/completeTranscript can throw (persist
1117
- // fs failure, transcript deleted); the abort is best-effort.
1118
- log.warn(`spawnBackgroundSession: timeout handler error for ${id}`, {
1119
- error: (err as Error).message,
1120
- });
1121
- }
1122
- }, normalizeTimeout(params.timeout) ?? DEFAULT_BACKGROUND_DEADLINE_MS);
1123
- }
1124
-
1125
2433
  runPromise.then(() => {
1126
- if (timeoutHandle) clearTimeout(timeoutHandle);
2434
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1127
2435
  try {
1128
2436
  // Probe contract (sdk-abort-contract.test.ts): prompt() RESOLVES on abort
1129
2437
  // — the SDK's runWithLifecycle catches the AbortError and converts it into
@@ -1131,8 +2439,23 @@ export async function spawnBackgroundSession(
1131
2439
  // HERE, not in .catch. Two signals distinguish stop from completion:
1132
2440
  // 1. stopAgent pre-set status to 'stopped' before calling abort();
1133
2441
  // 2. the last assistant message carries stopReason "aborted".
1134
- 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');
1135
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';
1136
2459
  const aborted = agent.status === 'stopped' || terminalStopReason === 'aborted';
1137
2460
  if (aborted) {
1138
2461
  // Session was aborted — mark stopped. If stopAgent already flipped the
@@ -1142,43 +2465,14 @@ export async function spawnBackgroundSession(
1142
2465
  updateAgentStatus(id, 'stopped');
1143
2466
  transcript.completeTranscript(id, 'stopped');
1144
2467
  }
1145
- // W4/M1: capture whatever the branch produced before discarding it — an
1146
- // aborted background agent's partial work is still worth reviewing, and
1147
- // must be RECORDED, not just captured-and-deleted.
1148
- const gitInfo = cleanupWorkBranch();
1149
- if (gitInfo.gitBranch) {
1150
- agent.result = {
1151
- ...(agent.result ?? {}),
1152
- exitCode: 1,
1153
- messages: [],
1154
- stderr: '',
1155
- usage: agent.result?.usage ?? EMPTY_USAGE,
1156
- stopReason: 'aborted',
1157
- gitBranch: gitInfo.gitBranch,
1158
- gitDiff: gitInfo.gitDiff,
1159
- } as SubagentResult;
1160
- agents.set(id, agent);
1161
- persistAgent(agent);
1162
- }
1163
- // Issue #98: aborts/timeouts are retryable failures (retry schema:
1164
- // timeout/abort counts as failure) — finalize the run entry.
1165
- // Issue #122: a timed-out run burned tokens — record the real usage
1166
- // (the git-diff block above must not leave the empty fallback).
1167
- // Issue #120 (Track 1): agent.error carries the reason when the stop was
1168
- // a deadline timeout ('Timed out after Xms' → 'timeout'); a user cancel
1169
- // (stop_subagent) sets no error, so fall back to the honest user-abort
1170
- // stamp (→ 'aborted') instead of the old ambiguous 'Aborted or timed out'.
1171
- recordSessionUsage();
1172
- finalizeRunEntry('failed', agent.error ?? SUBAGENT_ABORTED_MESSAGE, {
1173
- stopReason:
1174
- terminalStopReason && terminalStopReason !== 'stop'
1175
- ? terminalStopReason
1176
- : 'aborted',
1177
- });
1178
- // Issue #31: capture the final output while the session is still
1179
- // live, then release the ref on the terminal path (memory retention;
1180
- // the poller treats a nulled ref on a terminal agent as expected).
1181
- captureAndReleaseSession();
2468
+ // W4/M1 + #98/#122/#120/#31: the same aborted settle as the .catch
2469
+ // stopped branch (issue #376/D8 — one helper, no second copy).
2470
+ finalizeAbortedRun(
2471
+ cleanupWorkBranch(),
2472
+ terminalStopReason && terminalStopReason !== 'stop'
2473
+ ? terminalStopReason
2474
+ : 'aborted',
2475
+ );
1182
2476
  return;
1183
2477
  }
1184
2478
  // Issue #179 (D1/D2): prompt() RESOLVED — but a resolved prompt is NOT
@@ -1190,16 +2484,29 @@ export async function spawnBackgroundSession(
1190
2484
  // classifyError for the provider-error case.
1191
2485
  const providerErrorMessage =
1192
2486
  lastAssistant?.errorMessage ?? session.state?.errorMessage;
1193
- const outcome = classifyTerminalOutcome(terminalStopReason, providerErrorMessage);
2487
+ const outcome = classifyTerminalOutcome(terminalStopReason, providerErrorMessage, {
2488
+ assistantEvidence,
2489
+ });
1194
2490
 
1195
2491
  if (outcome.status === 'failed') {
1196
2492
  // Mid-run provider death / truncation / incomplete turn.
1197
2493
  agent.status = 'failed';
1198
2494
  agent.completedAt = Date.now();
1199
- const sanitizedError = sanitizeErrorMessage(
1200
- providerErrorMessage ?? defaultTerminalMessage(terminalStopReason),
1201
- effectiveCwd,
1202
- );
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);
1203
2510
  agent.error = sanitizedError;
1204
2511
  const gitInfo = cleanupWorkBranch();
1205
2512
  agent.result = {
@@ -1274,7 +2581,7 @@ export async function spawnBackgroundSession(
1274
2581
  markTerminalBestEffort('completed');
1275
2582
  }
1276
2583
  }).catch((err: Error) => {
1277
- if (timeoutHandle) clearTimeout(timeoutHandle);
2584
+ if (deadlineHandle) clearTimeout(deadlineHandle);
1278
2585
  try {
1279
2586
  // W4: capture partial work + discard the work branch on failure — a failed
1280
2587
  // background agent may still have produced reviewable changes.
@@ -1283,33 +2590,11 @@ export async function spawnBackgroundSession(
1283
2590
  // model resolution, invalid task). Abort never rejects (probe contract).
1284
2591
  if (agent.status === 'stopped') {
1285
2592
  // M1: record the partial work even on the stopped path.
1286
- if (gitInfo.gitBranch) {
1287
- agent.result = {
1288
- ...(agent.result ?? {}),
1289
- exitCode: 1,
1290
- messages: [],
1291
- stderr: '',
1292
- usage: agent.result?.usage ?? EMPTY_USAGE,
1293
- stopReason: 'aborted',
1294
- gitBranch: gitInfo.gitBranch,
1295
- gitDiff: gitInfo.gitDiff,
1296
- } as SubagentResult;
1297
- agents.set(id, agent);
1298
- persistAgent(agent);
1299
- }
1300
- // Issue #98: the stopped path is a retryable failure too — finalize
1301
- // the run entry alongside the agent record flip.
1302
- // Issue #122: a stopped/timed-out run burned tokens too — record the
1303
- // real usage (same aborted path semantics as the .then branch).
1304
- // Issue #120 (Track 1): same honest fallback — a deadline timeout keeps
1305
- // agent.error ('Timed out...' → 'timeout'); a user cancel has no error
1306
- // and stamps 'Subagent aborted by user' (→ 'aborted').
1307
- recordSessionUsage();
1308
- finalizeRunEntry('failed', agent.error ?? SUBAGENT_ABORTED_MESSAGE, {
1309
- stopReason: 'aborted',
1310
- });
1311
- // Issue #31: the stopped path is terminal too — capture + release.
1312
- captureAndReleaseSession();
2593
+ // Issue #376 (D8): identical to the .then aborted branch — the work-branch
2594
+ // capture above is reused (cleanupWorkBranch is once-per-run) and there is
2595
+ // no last assistant message here to narrow the reason from.
2596
+ finalizeAbortedRun(gitInfo, 'aborted');
2597
+ // Issue #31: the stopped path is terminal too — its transcript note.
1313
2598
  transcript.completeTranscript(id, 'stopped');
1314
2599
  return;
1315
2600
  }
@@ -1365,6 +2650,6 @@ export async function spawnBackgroundSession(
1365
2650
 
1366
2651
  return agent;
1367
2652
  } finally {
1368
- resolveNext();
2653
+ releaseSpawnQueue();
1369
2654
  }
1370
2655
  }