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.
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * See AGENT.md for the conductor-facing capability reference.
6
6
  */
7
7
 
8
+ import * as fs from "node:fs";
8
9
  import * as path from "node:path";
9
10
  import type {
10
11
  AgentToolResult,
@@ -35,8 +36,10 @@ import type {
35
36
  TaskTemplate,
36
37
  ToolResult,
37
38
  SubagentEvent,
39
+ SubagentEventListener,
38
40
  } from "./types";
39
41
  import {
42
+ declaredThinkingLevel,
40
43
  resolveThinkingLevel,
41
44
  EMPTY_USAGE,
42
45
  getFinalOutput,
@@ -51,9 +54,12 @@ import {
51
54
  DEFAULT_PRIORITY,
52
55
  type GitMode,
53
56
  type BackgroundAgent,
57
+ type BackgroundAgentIdentity,
58
+ type BackgroundAgentSpawnResult,
54
59
  type RecoveryMode,
55
60
  } from "./types";
56
61
  import { validateGraph, topologicalSort } from "./scheduler";
62
+ import { runModePrologue } from "./mode-prologue";
57
63
  import { resolveTemplate, loadAllTemplates, loadBuiltinTemplates, validateTemplatePresetRefs, extractParamNames } from "./templates";
58
64
  import { pkgPath } from "./paths";
59
65
 
@@ -61,29 +67,42 @@ import { sanitizeTask, validateCwd, validateOutputFile, stripAnsi, capOutput, ge
61
67
  import {
62
68
  hasUncommittedChanges,
63
69
  createWorkBranch,
70
+ newWorkBranchName,
64
71
  captureDiff,
65
72
  getHeadState,
73
+ getHeadBranch,
74
+ getRepoRoot,
75
+ listWorkBranches,
66
76
  restoreHead,
67
77
  deleteBranch,
68
78
  mergeWorkBranch,
69
79
  type HeadState,
70
80
  } from "./git";
71
81
  import { preflightCheck } from "./preflight";
72
- import { gateSessionCost, rejectApprovalAlwaysInBackground, runPreTaskValidation, validateDelegationTargets, formatValidationWarnings } from "./prelude";
82
+ import { depthLimitRejection, formatValidationWarnings, gateSessionCost, invalidThinkingLevelRejection, modelNotConfiguredRejection, rejectApprovalAlwaysInBackground, rejection, resolveModeModel, resolveSubagentModelPrecedence, runPreTaskValidation, validateDelegationTargets, validateUnitPrePass, type SubagentModelResolution } from "./prelude";
73
83
  import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile, formatPresetRestriction, formatToolRestriction } from "./presets";
74
- import { modelIsAvailable } from "./model-availability";
75
- import { validatePreTask, diagnoseFailure, DEFAULT_BACKGROUND_DEADLINE_MS } from "./validate";
84
+ import { modelIsAvailable, parseModelString } from "./model-availability";
85
+ import { validatePreTask, diagnoseFailure } from "./validate";
76
86
  import {
77
87
  defaultBackgroundFor,
78
88
  findUnknownParams,
79
89
  KNOWN_DELEGATE_KEYS,
90
+ resolveDispatchPreset,
80
91
  resolveEffectiveApprovalMode,
81
92
  resolveSubagentParams,
93
+ resolveThinkingDispatchSwitch,
94
+ shouldDropUnitTimeout,
82
95
  shouldRejectBackgroundForBatch,
83
96
  snapshotOriginalParams,
97
+ THINKING_SWITCH_NOTICE,
98
+ THINKING_TIMEOUT_DROP_NOTICE,
99
+ THINKING_UNIT_TIMEOUT_DROP_NOTICE,
84
100
  type DispatchShape,
101
+ type ResolveInputParams,
102
+ type UnitShape,
85
103
  } from "./params";
86
104
  import { delegateTaskParamsSchema } from "./schema";
105
+ import { readProcessChecks } from "./project-flags";
87
106
  import { createSessionState, resolveTerminalRunEntry, type SessionState } from "./state";
88
107
  import { makeLiveOnUpdate, createUnitRun, finalizeUnitRun, finalizeUnitRunCrash, pruneHistoryIfNeeded, registerLiveRun } from "./unit-run";
89
108
  import { buildSubagentPrompt, describePromptMode } from "./prompt";
@@ -92,7 +111,19 @@ import {
92
111
  recoverProduction,
93
112
  currentProcessOwner,
94
113
  newDispatchIdentity,
114
+ classifyOwner,
115
+ defaultRecoveryDeps,
95
116
  } from "./recovery";
117
+ import {
118
+ buildHeadStateNotice,
119
+ reconcileHeadStates,
120
+ sweepHeadStates,
121
+ writeHeadState,
122
+ clearHeadState,
123
+ HEAD_STATE_VERSION,
124
+ type HeadStateDeps,
125
+ type HeadStateOutcome,
126
+ } from "./headstate";
96
127
  import { markInterrupted, listInflightRuns, clearInflightRun } from "./run-registry";
97
128
  import { acquireSlot, clearProgressLinger, releaseSlot, repaintStatus, stopProgressTicker } from "./concurrency";
98
129
  import { transcriptDisplayPath } from "./transcript-path";
@@ -141,11 +172,16 @@ import { Intercom } from "./messaging";
141
172
  import * as eventBus from "./event-bus";
142
173
  import {
143
174
  buildCompletionMessage,
175
+ formatBudgetLine,
176
+ normalizeCompletionStatus,
144
177
  resolveDelivery,
145
178
  sendCompletionNotification,
146
179
  claimTerminalNotice,
147
180
  resolveRunEntry,
181
+ buildMonitoringDegradedParagraph,
182
+ sendMonitoringDegradedAdvisory,
148
183
  } from "./notify-completion";
184
+ import { isTransportRetryable, TRANSPORT_RETRY_TOAST } from "./transport-retry";
149
185
 
150
186
  // ---------------------------------------------------------------------------
151
187
  // Helpers
@@ -219,6 +255,53 @@ export function cleanupSessionState(state: SessionState): void {
219
255
  state.pendingQueue.length = 0;
220
256
  }
221
257
 
258
+ /**
259
+ * Issue #401/#411: the resume preamble a transport auto-retry builds and delivers
260
+ * as a `<resume-context>` section on the child's system prompt — never inside
261
+ * the `<task>` fence. A dropped connection costs the child its context, not its
262
+ * files: the retry spawns into the same directory, so the work it already did
263
+ * (commits, written files, a bank) is still there. The preamble turns a blind
264
+ * replay into a resume by naming what to inspect first.
265
+ *
266
+ * Kept bounded (5 lines max) and deliberately vetted for runtime vocabulary —
267
+ * it is prompt text a user can see in the child's system prompt.
268
+ *
269
+ * Issue #404: it also names the retained SDK session directory when one exists.
270
+ * That is the only artifact that holds attempt 1's CONVERSATION — the output log
271
+ * is a start/steering stub — and the settle path retains it for exactly this
272
+ * class of run. The pointer is absolute and computed conductor-side at build
273
+ * time: the retry's child can run in a different cwd (worktree/branch mode), so
274
+ * a relative path would point at the wrong tree. The exists gate is deliberate:
275
+ * an attempt whose session was not retained (size floor, marker failure, a
276
+ * legacy run) gets the bank-only preamble, never a dead path.
277
+ */
278
+ function buildRetryResumePreamble(
279
+ run: SubagentRun,
280
+ nextAttempt: number,
281
+ retainedSessionDir?: string,
282
+ ): string {
283
+ const sanitize = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "-");
284
+ const label = sanitize(run.label ?? "");
285
+ // A label made only of separators ("---") is not a filename; fall back to the
286
+ // (UUID-shaped, hence already safe) id.
287
+ const bankLabel = /[A-Za-z0-9]/.test(label) ? label : sanitize(run.id);
288
+ const lines = [
289
+ `[attempt ${nextAttempt} — the previous attempt (${run.id}) died on a transport failure.`,
290
+ "This directory may already contain its uncommitted edits.",
291
+ `Before acting, inspect: \`git status --short\`, \`git log --oneline -8\`, and the progress bank at /tmp/brl-${bankLabel}-bank.md if it exists.`,
292
+ "Continue from what exists; do NOT redo committed, written, or banked work.]",
293
+ ];
294
+ if (retainedSessionDir) {
295
+ // Insert before the closing line so the block still reads as one unit.
296
+ lines.splice(
297
+ lines.length - 1,
298
+ 0,
299
+ `The previous attempt's session is retained at ${retainedSessionDir} — read the newest .jsonl inside (ISO-prefixed names sort lexicographically) to recover what it had worked out.`,
300
+ );
301
+ }
302
+ return lines.join("\n");
303
+ }
304
+
222
305
  // ---------------------------------------------------------------------------
223
306
  // Extension entry point
224
307
  // ---------------------------------------------------------------------------
@@ -234,6 +317,119 @@ type _KnownDelegateKey = (typeof KNOWN_DELEGATE_KEYS extends Set<infer K> ? K :
234
317
  type _ExpectNever<T extends never> = T;
235
318
  type _DelegateParamCoverage = _ExpectNever<Exclude<_KnownDelegateKey, keyof DelegateTaskParams>>;
236
319
 
320
+ /**
321
+ * Issue #379: `ResolveInputParams` derives from the schema via `Pick`, so a
322
+ * params field ADDED to the schema is not in the resolver's input until the
323
+ * key list names it — and a missed field is invisible at runtime (the key
324
+ * reaches execute and is silently unused). Only the compiler can catch it.
325
+ *
326
+ * The excluded keys are the ones resolution deliberately does not read: the
327
+ * execution-shape inputs (`chain`/`tasks`/`graph`), the template machinery
328
+ * (`template` is the exception — it IS read, so it stays in the resolver;
329
+ * `params` is not), the retry inputs, and the per-dispatch fields
330
+ * (`model`/`priority`/`background`) that resolve outside this merge.
331
+ */
332
+ type _NonResolutionDelegateKey =
333
+ | "chain"
334
+ | "tasks"
335
+ | "graph"
336
+ | "params"
337
+ | "retryRunId"
338
+ | "retryOnTimeout"
339
+ | "model"
340
+ | "priority"
341
+ | "background"
342
+ // Issue #412: `force`/`noJev` are consumed at the validation seam (they
343
+ // reach `validatePreTask`, not the merge), so `force` stays in the resolver's
344
+ // key list while `noJev` — never read by resolution — is excluded here.
345
+ | "noJev";
346
+ type _ResolveInputCoverage = _ExpectNever<
347
+ Exclude<_KnownDelegateKey, keyof ResolveInputParams | _NonResolutionDelegateKey>
348
+ >;
349
+
350
+ /**
351
+ * Issue #381 (audit D4): the one graph-node → SubTaskParams mapping, shared by
352
+ * the graph pre-pass and the per-wave dispatch. GraphTask is a structural
353
+ * superset of SubTaskParams, so the node-only scheduling fields are dropped by
354
+ * destructuring instead of re-listing every per-subtask field — a field added
355
+ * to either type can no longer be silently forgotten at one of the two sites.
356
+ */
357
+ function graphTaskToSubTaskParams(node: GraphTask): SubTaskParams {
358
+ const { id: _id, dependsOn: _dependsOn, ...subTask } = node;
359
+ return subTask;
360
+ }
361
+
362
+ /**
363
+ * Issue #434: what every unit of ONE dispatch needs from the dispatch-level
364
+ * pre-flight — threaded from `execute` into the four batch handlers, never
365
+ * re-derived at a unit site.
366
+ *
367
+ * - `processChecks` is the project opt-in `execute` already resolved from the
368
+ * dispatch's OWN cwd. Re-reading it per unit (from a relative
369
+ * `params.cwd`) judges a different directory than the dispatch did.
370
+ * - `dispatchDeclaredLevel` is the declared (uncapped) level the dispatch arm
371
+ * judged, so a unit that declares only a `timeout` is still judged against
372
+ * the thinking level it actually inherits.
373
+ * - `force` and `unitShape` are the dispatch-level facts the unit projection
374
+ * asks for; `params` is in scope at every unit site, so passing them here is
375
+ * what keeps the predicate's inputs in ONE place.
376
+ * - `noticeEmitted` is the one-shot flag on this shared object (all handlers
377
+ * received the same reference): the unit projection emits AT MOST one
378
+ * additional notice per dispatch, and a dispatch-arm notice starts it true
379
+ * (the drop still happens — the deadline is the hazard, the notice is the
380
+ * report). A flag on the shared context, not a boolean copy, because the
381
+ * first unit to reach its run is whichever won the slot, not the first in
382
+ * the array.
383
+ */
384
+ interface BatchGuardContext {
385
+ processChecks: boolean;
386
+ dispatchDeclaredLevel: ThinkingLevel | undefined;
387
+ /** The dispatch's `force` — the override applies to every unit of it. */
388
+ force: boolean | undefined;
389
+ unitShape: UnitShape;
390
+ /** True once any notice for this dispatch went out — mutated at the unit site. */
391
+ noticeEmitted: boolean;
392
+ }
393
+
394
+ /**
395
+ * Issue #376 (audit D3): the one `SubagentResult` → `SubTaskResult` field
396
+ * mapping, shared by every dispatch mode (chain, parallel, graph). The ten
397
+ * assignments plus the error classification were copied per mode, so a field
398
+ * added to `SubTaskResult` could be silently forgotten at one of the sites —
399
+ * and `errorCategory` could be passed through unclassified. Callers add their
400
+ * own mode-specific fields (`step`/`task`/`label`) around this mapping.
401
+ */
402
+ function toSubTaskResult(
403
+ result: SubagentResult,
404
+ ): Pick<
405
+ SubTaskResult,
406
+ | "exitCode"
407
+ | "messages"
408
+ | "stderr"
409
+ | "usage"
410
+ | "model"
411
+ | "stopReason"
412
+ | "errorMessage"
413
+ | "errorCategory"
414
+ | "gitBranch"
415
+ | "gitDiff"
416
+ > {
417
+ return {
418
+ exitCode: result.exitCode,
419
+ messages: result.messages,
420
+ stderr: result.stderr,
421
+ usage: result.usage,
422
+ model: result.model,
423
+ stopReason: result.stopReason,
424
+ errorMessage: result.errorMessage,
425
+ // The classification path is part of the mapping: every mode derives the
426
+ // category from the raw result, never from the runner's own field.
427
+ errorCategory: classifyError(result),
428
+ gitBranch: result.gitBranch,
429
+ gitDiff: result.gitDiff,
430
+ };
431
+ }
432
+
237
433
  export default function (pi: ExtensionAPI) {
238
434
  const log = createLogger("brl-subagent");
239
435
 
@@ -241,7 +437,7 @@ export default function (pi: ExtensionAPI) {
241
437
  let state = createSessionState(log);
242
438
 
243
439
  // Issue #147: the completion-push subscriber needs the session context to
244
- // resolve the run entry (state.getRunEntries(ctx)). The event-bus listener
440
+ // resolve the run entry (state.getLogicalRunEntries(ctx)). The event-bus listener
245
441
  // receives no ctx, so capture it in session_start where it is available.
246
442
  let sessionCtx: ExtensionContext | undefined;
247
443
 
@@ -288,73 +484,16 @@ export default function (pi: ExtensionAPI) {
288
484
  // Parameter resolution (extracted to src/params.ts — issue #59)
289
485
  // -------------------------------------------------------------------
290
486
 
291
- /** Parse "provider/model-id" into {provider, id}. Returns null on bad format. */
292
- function parseModelString(s: string): { provider: string; id: string } | null {
293
- const trimmed = s.trim();
294
- const idx = trimmed.indexOf("/");
295
- if (idx <= 0 || idx === trimmed.length - 1) return null;
296
- return { provider: trimmed.slice(0, idx), id: trimmed.slice(idx + 1) };
297
- }
298
-
487
+ // The model-precedence chain lives in prelude.ts (issue #379) so the batch
488
+ // modes' tail (`resolveModeModel`) and these single/background paths resolve
489
+ // identically; this wrapper keeps their call shape (context + preset +
490
+ // per-call override) unchanged.
299
491
  function resolveSubagentModel(
300
492
  ctx: ExtensionContext,
301
493
  preset: SubagentPreset | undefined,
302
494
  perCallModel?: string, // NEW: top-level delegate_task model param (issue #96)
303
- ):
304
- | { ok: true; model: { provider: string; id: string } }
305
- | { ok: false; error: ToolResult<SubagentResult | undefined> } {
306
- // Precedence: per-call model > preset.model > state.config.model > conductor model
307
- let subagentModel: { provider: string; id: string } | undefined;
308
-
309
- if (perCallModel) {
310
- const parsed = parseModelString(perCallModel);
311
- if (!parsed) {
312
- log.warn("Model override is not a valid provider/model-id, falling back", { model: perCallModel });
313
- } else if (modelIsAvailable(ctx.modelRegistry, parsed)) {
314
- log.info("Using per-call model override", { model: perCallModel });
315
- return { ok: true, model: parsed };
316
- } else {
317
- log.warn("Model override unavailable, falling back", { model: perCallModel });
318
- }
319
- }
320
-
321
- if (preset?.model) {
322
- const parsed = parseModelString(preset.model);
323
- if (parsed && modelIsAvailable(ctx.modelRegistry, parsed)) {
324
- subagentModel = parsed;
325
- log.info("Using preset model", { preset: preset.name, model: preset.model });
326
- } else {
327
- // Fallback: preset model unavailable → configured model
328
- log.warn("Preset model unavailable, falling back to configured model", {
329
- preset: preset.name,
330
- model: preset.model,
331
- });
332
- }
333
- }
334
-
335
- if (!subagentModel) {
336
- subagentModel =
337
- state.config.model ||
338
- (ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined);
339
- }
340
-
341
- if (!subagentModel) {
342
- return {
343
- ok: false,
344
- error: {
345
- content: [
346
- {
347
- type: "text" as const,
348
- text: "No model available. Configure API keys first, then use /brl-subagent to set a model.",
349
- },
350
- ],
351
- details: undefined,
352
- isError: true,
353
- },
354
- };
355
- }
356
-
357
- return { ok: true, model: subagentModel };
495
+ ): SubagentModelResolution {
496
+ return resolveSubagentModelPrecedence({ state, ctx, log, preset, perCallModel });
358
497
  }
359
498
 
360
499
  // C3: Resolve a step's model override (step.model > global resolved model).
@@ -459,6 +598,74 @@ export default function (pi: ExtensionAPI) {
459
598
  merged.label ??
460
599
  (merged.task.length > 60 ? `${merged.task.slice(0, 57)}...` : merged.task);
461
600
 
601
+ /**
602
+ * Issue #434: apply the dispatch pre-flight's UNIT projection to one merged
603
+ * unit — `merged.timeout = undefined` before the unit's run record exists, so
604
+ * the retry snapshot records an absent deadline (ADR 0009) and no
605
+ * `createUnitRun`/`startBackgroundAgent` ever sees it. The decision itself
606
+ * lives in `shouldDropUnitTimeout` (params.ts): re-stating the condition here
607
+ * is the drift #361's resolver extraction exists to prevent.
608
+ *
609
+ * EVERY input is threaded (`ctx`'s guard) or the unit's own declaration
610
+ * (`step`) — the unit site reads no config, no manifest and no cap of its
611
+ * own. `merged.thinkingLevel` is deliberately not an input: it is the capped
612
+ * level, and the default cap would silently disable the guard.
613
+ *
614
+ * Emission discipline (issue #434 [c2]): called from the unit's dispatch
615
+ * point, AFTER its slot is held and immediately BEFORE its run — a pre-pass
616
+ * would announce a unit that a cancellation can still skip. At most ONE
617
+ * notice per dispatch: a dispatch-arm notice suppresses this one entirely
618
+ * (the drop still happens — the deadline is the hazard, the notice is the
619
+ * report), and the first unit to reach its run claims it.
620
+ */
621
+ function applyUnitShapeGuard(
622
+ ctx: ExtensionContext,
623
+ guard: BatchGuardContext,
624
+ step: SubTaskParams,
625
+ merged: ReturnType<typeof mergeSubTaskParams>,
626
+ ): void {
627
+ const shouldDrop = shouldDropUnitTimeout({
628
+ processChecks: guard.processChecks,
629
+ force: guard.force,
630
+ dispatchDeclaredLevel: guard.dispatchDeclaredLevel,
631
+ unitShape: guard.unitShape,
632
+ declaredLevel: step.thinkingLevel as ThinkingLevel | "" | undefined,
633
+ declaredTimeout: step.timeout,
634
+ mergedTimeout: merged.timeout,
635
+ });
636
+ if (!shouldDrop) return;
637
+
638
+ const previousTimeout = merged.timeout;
639
+ const unit = displayTaskName(merged);
640
+ const effectiveLevel = step.thinkingLevel || guard.dispatchDeclaredLevel;
641
+ // The drop precedes `createUnitRun`: that is what makes the recorded
642
+ // `originalParams.timeout` absent, so a retry re-derives instead of
643
+ // restoring the cap (ADR 0009). A drop after it passes every
644
+ // runner-argument assertion and still restores the deadline on retry.
645
+ merged.timeout = undefined;
646
+ log.info("Dispatch pre-flight: unit-declared timeout dropped, unit stays foreground", {
647
+ unit,
648
+ thinkingLevel: effectiveLevel,
649
+ previousTimeout,
650
+ });
651
+ if (!guard.noticeEmitted) {
652
+ guard.noticeEmitted = true;
653
+ pi.sendMessage({
654
+ customType: "delegate-notification",
655
+ content: THINKING_UNIT_TIMEOUT_DROP_NOTICE,
656
+ display: true,
657
+ details: {
658
+ unit,
659
+ thinkingLevel: effectiveLevel,
660
+ // The ACTUAL ms value, mirroring the dispatch drop arm: the
661
+ // friction log needs the number to tell a budget cap from a clock.
662
+ previousTimeout,
663
+ },
664
+ }, { deliverAs: "followUp" });
665
+ ctx.ui.notify(THINKING_UNIT_TIMEOUT_DROP_NOTICE, "warning");
666
+ }
667
+ }
668
+
462
669
  // -------------------------------------------------------------------
463
670
  // P1: runChainMode
464
671
  // -------------------------------------------------------------------
@@ -468,6 +675,7 @@ export default function (pi: ExtensionAPI) {
468
675
  signal: AbortSignal | undefined,
469
676
  onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
470
677
  ctx: ExtensionContext,
678
+ guard: BatchGuardContext,
471
679
  ): Promise<ToolResult<SubagentResult | ChainDetails | undefined>> {
472
680
  const chainSteps: SubTaskParams[] = params.chain!;
473
681
 
@@ -475,115 +683,22 @@ export default function (pi: ExtensionAPI) {
475
683
  // startedAt (captured once, at mode entry, not at completion).
476
684
  const chainModeStartedAt = new Date().toISOString();
477
685
 
478
- // R5: Check session cost limit before spawning
479
- const costError = gateSessionCost({
686
+ // Mode prologue (issue #379): cost → depth → resolve → targets →
687
+ // preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
688
+ // Chain's per-mode inputs are only the label and the unit count; H1 here
689
+ // validates the MODE-level params (top-level tasks are empty, so only the
690
+ // hard outputFile-vs-write conflict applies), while every step's own
691
+ // cwd/outputFile/tools belong to the per-step pass below (issue #222).
692
+ const pro = runModePrologue({
693
+ params,
480
694
  state,
481
695
  ctx,
482
696
  log,
697
+ label: "Chain",
483
698
  units: chainSteps.length,
484
- label: "Chain delegation",
485
- });
486
- if (costError) return costError;
487
-
488
- // Reject delegation if recursion depth exceeds configured max
489
- const currentDepth = getCurrentDepth();
490
- if (currentDepth >= state.config.maxSubagentDepth) {
491
- log.warn("Chain delegation rejected: max depth reached", {
492
- currentDepth,
493
- maxDepth: state.config.maxSubagentDepth,
494
- });
495
- return {
496
- content: [
497
- {
498
- type: "text" as const,
499
- text:
500
- `Cannot delegate further: subagent recursion depth limit reached ` +
501
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
502
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
503
- },
504
- ],
505
- details: undefined,
506
- isError: true,
507
- };
508
- }
509
-
510
- // Resolve global params once
511
- const globalParams = resolveSubagentParams(
512
- params as {
513
- task: string;
514
- label?: string;
515
- preset?: string;
516
- systemPrompt?: string;
517
- inheritSystemPrompt?: boolean;
518
- thinkingLevel?: string;
519
- outputFile?: string;
520
- timeout?: number;
521
- cwd?: string;
522
- tools?: string[];
523
- excludeTools?: string[];
524
- noBuiltinTools?: boolean;
525
- gitMode?: string;
526
- },
527
- state,
528
- ctx,
529
- log,
530
- );
531
-
532
- // Validate CWD once
533
- const cwdResult = validateCwd(globalParams.effectiveCwd, ctx.cwd);
534
- if (!cwdResult.ok) {
535
- return {
536
- content: [
537
- { type: "text" as const, text: `Invalid cwd: ${cwdResult.error}` },
538
- ],
539
- details: undefined,
540
- isError: true,
541
- };
542
- }
543
- const resolvedCwd = cwdResult.value;
544
-
545
- // Pre-flight checks — fail fast before consuming resources
546
- const pfResult = preflightCheck(resolvedCwd);
547
- if (!pfResult.ok) {
548
- log.warn("Chain pre-flight check failed", { error: pfResult.error });
549
- return {
550
- content: [
551
- {
552
- type: "text" as const,
553
- text: `Pre-flight check failed: ${pfResult.error}`,
554
- },
555
- ],
556
- details: undefined,
557
- isError: true,
558
- };
559
- }
560
-
561
- // H1: Pre-task validation at mode entry — deterministic check that
562
- // tools/thinking match the task (mirrors single/background modes, issue
563
- // #32). Chain top-level tasks are empty (modeCount forbids task+chain), so
564
- // keyword warnings skip on empty text and only the hard outputFile-vs-write
565
- // conflict applies (issue #34). The mode-level outputFile on globalParams is
566
- // the one validated here; every step's own cwd/outputFile/tools are
567
- // validated by the per-step pre-pass below (issue #222).
568
- const validation = validatePreTask({
569
- task: globalParams.task,
570
- toolOptions: globalParams.toolOptions,
571
- thinkingLevel: globalParams.thinkingLevel,
572
- gitMode: globalParams.resolvedGitMode,
573
- outputFile: globalParams.outputFile,
574
699
  });
575
- if (validation.warnings.length > 0) {
576
- log.warn("Chain pre-task validation warnings", { warnings: validation.warnings });
577
- }
578
- if (!validation.valid) {
579
- const errText = validation.errors.join("; ");
580
- log.warn("Chain pre-task validation failed", { errors: validation.errors });
581
- return {
582
- content: [{ type: "text" as const, text: errText }],
583
- details: undefined,
584
- isError: true,
585
- };
586
- }
700
+ if (!pro.ok) return pro.error;
701
+ const { globalParams, resolvedCwd, currentDepth } = pro;
587
702
 
588
703
  // Per-step pre-pass (issue #222): resolve + validate EVERY step before
589
704
  // any spawn, so a single bad step rejects the chain with nothing
@@ -593,72 +708,40 @@ export default function (pi: ExtensionAPI) {
593
708
  // step's output (only its TASK text consumes {previous}), so the pass
594
709
  // can run up front — and must, because discovering step 5's bad cwd
595
710
  // after four steps already ran would waste their whole budget.
596
- const stepCwds: string[] = [];
597
- const stepWarnings: string[] = [];
598
- for (let i = 0; i < chainSteps.length; i++) {
599
- const merged = mergeSubTaskParams(globalParams, chainSteps[i]);
600
- const stepPrefix = `Step ${i + 1} ("${displayTaskName(merged)}")`;
601
-
602
- const stepTargets = validateDelegationTargets({
603
- ctx,
604
- effectiveCwd: merged.effectiveCwd,
605
- outputFile: merged.outputFile,
606
- prefix: stepPrefix,
607
- });
608
- if (!stepTargets.ok) return stepTargets.error;
609
- stepCwds.push(stepTargets.cwd);
610
-
611
- const stepValidation = runPreTaskValidation({
612
- log,
613
- label: "Chain",
614
- prefix: stepPrefix,
711
+ const stepPass = validateUnitPrePass({
712
+ units: chainSteps,
713
+ label: "Chain",
714
+ gitMode: globalParams.resolvedGitMode,
715
+ ctx,
716
+ log,
717
+ force: params.force as boolean | undefined,
718
+ noJev: params.noJev,
719
+ // Issue #443: the DECLARED per-step level (the merged one is resolved).
720
+ declaredThinkingLevel: (step) => step.thinkingLevel,
721
+ merge: (step) => mergeSubTaskParams(globalParams, step),
722
+ describe: (_step, merged, i) => ({
723
+ prefix: `Step ${i + 1} ("${displayTaskName(merged)}")`,
615
724
  logContext: { step: i + 1 },
616
- preTask: {
617
- task: merged.task,
618
- toolOptions: merged.toolOptions,
619
- thinkingLevel: merged.thinkingLevel,
620
- gitMode: globalParams.resolvedGitMode,
621
- outputFile: merged.outputFile,
622
- force: params.force as boolean | undefined,
623
- },
624
- });
625
- if (stepValidation.error) return stepValidation.error;
626
- for (const w of stepValidation.warnings) stepWarnings.push(`${stepPrefix}: ${w}`);
627
- }
628
-
629
- // Resolve model once (per-call top-level model override beats preset)
630
- const modelResult = resolveSubagentModel(ctx, globalParams.resolvedPreset, params.model as string | undefined);
631
- if (!modelResult.ok) return modelResult.error;
632
- const subagentModel = modelResult.model;
633
-
634
- const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
635
- if (!modelStr || modelStr === "/") {
636
- log.warn("Model string is empty after resolution", { model: subagentModel });
637
- return {
638
- content: [
639
- {
640
- type: "text" as const,
641
- text:
642
- "Subagent model is not configured. " +
643
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
644
- },
645
- ],
646
- details: undefined,
647
- isError: true,
648
- };
649
- }
650
-
651
- // R1: Circuit breaker check — reject if circuit is open
652
- const circuitCheck = state.checkCircuit();
653
- if (circuitCheck.isOpen) {
654
- return {
655
- content: [
656
- { type: "text" as const, text: circuitCheck.message! },
657
- ],
658
- details: undefined,
659
- isError: true,
660
- };
661
- }
725
+ }),
726
+ });
727
+ if (!stepPass.ok) return stepPass.error;
728
+ const stepCwds = stepPass.units.map((u) => u.cwd);
729
+ const stepWarnings = stepPass.warnings;
730
+
731
+ // Mode tail (issue #379): resolve the model (preset + per-call override,
732
+ // auto-route included in `resolvedPreset`), reject an empty resolution,
733
+ // then the circuit breaker. It runs AFTER the per-step pass — IN8 keeps
734
+ // a bad step's rejection ahead of an unconfigured model.
735
+ const tail = resolveModeModel({
736
+ state,
737
+ ctx,
738
+ log,
739
+ preset: globalParams.resolvedPreset,
740
+ perCallModel: params.model,
741
+ });
742
+ if (!tail.ok) return tail.error;
743
+ const subagentModel = tail.model;
744
+ const modelStr = tail.modelStr;
662
745
 
663
746
  // Resolve priority (issue #114: no config knob — the call-level default)
664
747
  const chainPriority: Priority = (
@@ -695,6 +778,12 @@ export default function (pi: ExtensionAPI) {
695
778
  // Merge params for this step
696
779
  const merged = mergeSubTaskParams(globalParams, step);
697
780
 
781
+ // Issue #434: the unit projection of the dispatch pre-flight (#412/#431).
782
+ // A chain holds its ONE mode-level slot across the whole loop, so the
783
+ // slot is already held here; the drop lands BEFORE `createUnitRun`
784
+ // below, or the retry snapshot would restore the deadline (ADR 0009).
785
+ applyUnitShapeGuard(ctx, guard, step, merged);
786
+
698
787
  // C3: Resolve this step's model override (step.model > global resolved model)
699
788
  const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
700
789
 
@@ -775,7 +864,7 @@ export default function (pi: ExtensionAPI) {
775
864
  // parallel mode's issue #119 registration). Fall back to
776
865
  // "Step N" when the step carries no label (liveRowName would
777
866
  // otherwise show the truncated task).
778
- registerLiveRun(state, run, ctx, merged.label ?? `Step ${i + 1}`);
867
+ registerLiveRun(state, run, ctx, merged.label ?? `Step ${i + 1}`, merged.timeout);
779
868
 
780
869
  // Wrap onUpdate so the live monitor sees per-step progress
781
870
  // (mirrors parallel mode's taskOnUpdate).
@@ -825,17 +914,8 @@ export default function (pi: ExtensionAPI) {
825
914
  // shape finalizeRunRecord expects, errorCategory included).
826
915
  finalizeUnitRun(state, pi, ctx, run, result, log);
827
916
 
828
- // Fill SubTaskResult
829
- subTaskResult.exitCode = result.exitCode;
830
- subTaskResult.messages = result.messages;
831
- subTaskResult.stderr = result.stderr;
832
- subTaskResult.usage = result.usage;
833
- subTaskResult.model = result.model;
834
- subTaskResult.stopReason = result.stopReason;
835
- subTaskResult.errorMessage = result.errorMessage;
836
- subTaskResult.errorCategory = classifyError(result);
837
- subTaskResult.gitBranch = result.gitBranch;
838
- subTaskResult.gitDiff = result.gitDiff;
917
+ // Fill SubTaskResult (one shared field mapping — issue #376/D3).
918
+ Object.assign(subTaskResult, toSubTaskResult(result));
839
919
 
840
920
  chainResults.push(subTaskResult);
841
921
 
@@ -995,104 +1075,26 @@ export default function (pi: ExtensionAPI) {
995
1075
  signal: AbortSignal | undefined,
996
1076
  onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
997
1077
  ctx: ExtensionContext,
1078
+ guard: BatchGuardContext,
998
1079
  ): Promise<ToolResult<SubagentResult | ParallelDetails | undefined>> {
999
1080
  const taskList: SubTaskParams[] = params.tasks!;
1000
1081
 
1001
- // R5: Check session cost limit before spawning
1002
- const costError = gateSessionCost({
1003
- state,
1004
- ctx,
1005
- log,
1006
- units: taskList.length,
1007
- label: "Parallel delegation",
1008
- });
1009
- if (costError) return costError;
1010
-
1011
- // Reject delegation if recursion depth exceeds configured max
1012
- const currentDepth = getCurrentDepth();
1013
- if (currentDepth >= state.config.maxSubagentDepth) {
1014
- log.warn("Parallel delegation rejected: max depth reached", {
1015
- currentDepth,
1016
- maxDepth: state.config.maxSubagentDepth,
1017
- });
1018
- return {
1019
- content: [
1020
- {
1021
- type: "text" as const,
1022
- text:
1023
- `Cannot delegate further: subagent recursion depth limit reached ` +
1024
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
1025
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
1026
- },
1027
- ],
1028
- details: undefined,
1029
- isError: true,
1030
- };
1031
- }
1032
-
1033
- // Resolve global params once
1034
- const globalParams = resolveSubagentParams(
1035
- params as {
1036
- task: string;
1037
- label?: string;
1038
- preset?: string;
1039
- systemPrompt?: string;
1040
- inheritSystemPrompt?: boolean;
1041
- thinkingLevel?: string;
1042
- outputFile?: string;
1043
- timeout?: number;
1044
- cwd?: string;
1045
- tools?: string[];
1046
- excludeTools?: string[];
1047
- noBuiltinTools?: boolean;
1048
- gitMode?: string;
1049
- },
1082
+ // Mode prologue (issue #379): cost → depth → resolve → targets →
1083
+ // preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
1084
+ // Parallel's per-mode inputs are only the label and the unit count; H1
1085
+ // validates the MODE-level params (top-level tasks are empty, so only the
1086
+ // hard outputFile-vs-write conflict applies — issue #34), while every
1087
+ // task's own cwd/outputFile/tools belong to the per-task pass below.
1088
+ const pro = runModePrologue({
1089
+ params,
1050
1090
  state,
1051
1091
  ctx,
1052
1092
  log,
1053
- );
1054
-
1055
- // Validate CWD once
1056
- const targets = validateDelegationTargets({ ctx, effectiveCwd: globalParams.effectiveCwd });
1057
- if (!targets.ok) return targets.error;
1058
- const resolvedCwd = targets.cwd;
1059
-
1060
- // Pre-flight checks — fail fast before consuming resources
1061
- const pfResult = preflightCheck(resolvedCwd);
1062
- if (!pfResult.ok) {
1063
- log.warn("Parallel pre-flight check failed", { error: pfResult.error });
1064
- return {
1065
- content: [
1066
- {
1067
- type: "text" as const,
1068
- text: `Pre-flight check failed: ${pfResult.error}`,
1069
- },
1070
- ],
1071
- details: undefined,
1072
- isError: true,
1073
- };
1074
- }
1075
-
1076
- // H1: Pre-task validation at mode entry — deterministic check that
1077
- // tools/thinking match the task (mirrors single/background modes, issue
1078
- // #32). Parallel top-level tasks are empty (modeCount forbids task+tasks),
1079
- // so keyword warnings skip on empty text and only the hard
1080
- // outputFile-vs-write conflict applies (issue #34). The mode-level
1081
- // outputFile on globalParams is the one validated here; every task's own
1082
- // cwd/outputFile/tools are validated by the per-task pre-pass below
1083
- // (issue #222).
1084
- const preTask = runPreTaskValidation({
1085
- log,
1086
1093
  label: "Parallel",
1087
- preTask: {
1088
- task: globalParams.task,
1089
- toolOptions: globalParams.toolOptions,
1090
- thinkingLevel: globalParams.thinkingLevel,
1091
- gitMode: globalParams.resolvedGitMode,
1092
- outputFile: globalParams.outputFile,
1093
- },
1094
+ units: taskList.length,
1094
1095
  });
1095
- if (preTask.error) return preTask.error;
1096
+ if (!pro.ok) return pro.error;
1097
+ const { globalParams, resolvedCwd, currentDepth } = pro;
1096
1098
 
1097
1099
  // Per-task pre-pass (issue #220, extended by #222): validate EVERY task
1098
1100
  // before any spawn, so a single bad task rejects the batch with nothing
@@ -1104,73 +1106,40 @@ export default function (pi: ExtensionAPI) {
1104
1106
  // mode-level cwd. Per-task warnings are prefixed with their unit and
1105
1107
  // collected here to ride the final result. The mode-entry validation
1106
1108
  // above stays for the mode-level outputFile (issue #34).
1107
- const taskWarnings: string[] = [];
1108
- // Parallel index → the task's own validated cwd (issue #222).
1109
- const taskCwds: string[] = [];
1110
- for (let i = 0; i < taskList.length; i++) {
1111
- const merged = mergeSubTaskParams(globalParams, taskList[i]);
1112
- const taskPrefix = `Task ${i + 1} ("${displayTaskName(merged)}")`;
1113
-
1114
- const taskTargets = validateDelegationTargets({
1115
- ctx,
1116
- effectiveCwd: merged.effectiveCwd,
1117
- outputFile: merged.outputFile,
1118
- prefix: taskPrefix,
1119
- });
1120
- if (!taskTargets.ok) return taskTargets.error;
1121
- taskCwds.push(taskTargets.cwd);
1122
-
1123
- const unitValidation = runPreTaskValidation({
1124
- log,
1125
- label: "Parallel",
1126
- prefix: taskPrefix,
1109
+ const taskPass = validateUnitPrePass({
1110
+ units: taskList,
1111
+ label: "Parallel",
1112
+ gitMode: globalParams.resolvedGitMode,
1113
+ ctx,
1114
+ log,
1115
+ force: params.force as boolean | undefined,
1116
+ noJev: params.noJev,
1117
+ // Issue #443: the DECLARED per-task level (the merged one is resolved).
1118
+ declaredThinkingLevel: (task) => task.thinkingLevel,
1119
+ merge: (task) => mergeSubTaskParams(globalParams, task),
1120
+ describe: (_task, merged, i) => ({
1121
+ prefix: `Task ${i + 1} ("${displayTaskName(merged)}")`,
1127
1122
  logContext: { task: i + 1 },
1128
- preTask: {
1129
- task: merged.task,
1130
- toolOptions: merged.toolOptions,
1131
- thinkingLevel: merged.thinkingLevel,
1132
- gitMode: globalParams.resolvedGitMode,
1133
- outputFile: merged.outputFile,
1134
- force: params.force as boolean | undefined,
1135
- },
1136
- });
1137
- if (unitValidation.error) return unitValidation.error;
1138
- for (const w of unitValidation.warnings) taskWarnings.push(`${taskPrefix}: ${w}`);
1139
- }
1140
-
1141
- // Resolve model once (per-call top-level model override beats preset)
1142
- const modelResult = resolveSubagentModel(ctx, globalParams.resolvedPreset, params.model as string | undefined);
1143
- if (!modelResult.ok) return modelResult.error;
1144
- const subagentModel = modelResult.model;
1145
-
1146
- const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
1147
- if (!modelStr || modelStr === "/") {
1148
- log.warn("Model string is empty after resolution", { model: subagentModel });
1149
- return {
1150
- content: [
1151
- {
1152
- type: "text" as const,
1153
- text:
1154
- "Subagent model is not configured. " +
1155
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
1156
- },
1157
- ],
1158
- details: undefined,
1159
- isError: true,
1160
- };
1161
- }
1123
+ }),
1124
+ });
1125
+ if (!taskPass.ok) return taskPass.error;
1126
+ // Parallel index → the task's own validated cwd (issue #222).
1127
+ const taskCwds = taskPass.units.map((u) => u.cwd);
1128
+ const taskWarnings = taskPass.warnings;
1162
1129
 
1163
- // R1: Circuit breaker check — reject if circuit is open
1164
- const circuitCheck = state.checkCircuit();
1165
- if (circuitCheck.isOpen) {
1166
- return {
1167
- content: [
1168
- { type: "text" as const, text: circuitCheck.message! },
1169
- ],
1170
- details: undefined,
1171
- isError: true,
1172
- };
1173
- }
1130
+ // Mode tail (issue #379): model resolution (preset + per-call override,
1131
+ // auto-route included in `resolvedPreset`), the empty-model rejection and
1132
+ // the circuit check. Runs AFTER the per-task pass (IN8).
1133
+ const tail = resolveModeModel({
1134
+ state,
1135
+ ctx,
1136
+ log,
1137
+ preset: globalParams.resolvedPreset,
1138
+ perCallModel: params.model,
1139
+ });
1140
+ if (!tail.ok) return tail.error;
1141
+ const subagentModel = tail.model;
1142
+ const modelStr = tail.modelStr;
1174
1143
 
1175
1144
  // Build base prompt once
1176
1145
  const basePrompt = ctx.getSystemPrompt();
@@ -1189,6 +1158,14 @@ export default function (pi: ExtensionAPI) {
1189
1158
  unitCwd: string,
1190
1159
  ): Promise<boolean> => {
1191
1160
 
1161
+ // Issue #434: the unit projection of the dispatch pre-flight. Applied
1162
+ // HERE, not in the launcher's pre-merge: the launcher awaits
1163
+ // `acquireSlot` and only then calls this, so a unit cancelled while
1164
+ // waiting for its slot is never announced (and never dropped). The
1165
+ // drop still precedes `createUnitRun` below, so the retry snapshot
1166
+ // records an absent deadline rather than restoring the cap.
1167
+ applyUnitShapeGuard(ctx, guard, taskList[index], merged);
1168
+
1192
1169
  // C3: Resolve this step's model override (step.model > global resolved model)
1193
1170
  const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
1194
1171
 
@@ -1226,8 +1203,9 @@ export default function (pi: ExtensionAPI) {
1226
1203
  pruneHistoryIfNeeded(state, ctx, log);
1227
1204
 
1228
1205
  // Register for live monitor — parallel subtasks now appear in the
1229
- // drill-in with their per-unit priority (issue #119).
1230
- registerLiveRun(state, run, ctx);
1206
+ // drill-in with their per-unit priority (issue #119). The merged
1207
+ // timeout rides along as the display deadline (issue #423).
1208
+ registerLiveRun(state, run, ctx, undefined, merged.timeout);
1231
1209
 
1232
1210
  log.debug("Parallel subtask run registered", { runId, index });
1233
1211
 
@@ -1281,17 +1259,8 @@ export default function (pi: ExtensionAPI) {
1281
1259
  run.childMarker,
1282
1260
  );
1283
1261
 
1284
- // Fill SubTaskResult
1285
- subTaskResult.exitCode = result.exitCode;
1286
- subTaskResult.messages = result.messages;
1287
- subTaskResult.stderr = result.stderr;
1288
- subTaskResult.usage = result.usage;
1289
- subTaskResult.model = result.model;
1290
- subTaskResult.stopReason = result.stopReason;
1291
- subTaskResult.errorMessage = result.errorMessage;
1292
- subTaskResult.errorCategory = classifyError(result);
1293
- subTaskResult.gitBranch = result.gitBranch;
1294
- subTaskResult.gitDiff = result.gitDiff;
1262
+ // Fill SubTaskResult (one shared field mapping — issue #376/D3).
1263
+ Object.assign(subTaskResult, toSubTaskResult(result));
1295
1264
 
1296
1265
  results[index] = subTaskResult;
1297
1266
  completedCount++;
@@ -1466,6 +1435,7 @@ export default function (pi: ExtensionAPI) {
1466
1435
  signal: AbortSignal | undefined,
1467
1436
  onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
1468
1437
  ctx: ExtensionContext,
1438
+ guard: BatchGuardContext,
1469
1439
  ): Promise<ToolResult<SubagentResult | GraphDetails | undefined>> {
1470
1440
  const graphTasks: GraphTask[] = params.graph!;
1471
1441
 
@@ -1473,166 +1443,43 @@ export default function (pi: ExtensionAPI) {
1473
1443
  // startedAt (captured once, at mode entry, not at completion).
1474
1444
  const graphModeStartedAt = new Date().toISOString();
1475
1445
 
1476
- // Validate graph
1477
- const errors = validateGraph(graphTasks);
1478
- if (errors.length > 0) {
1479
- return {
1480
- content: [
1481
- {
1482
- type: "text" as const,
1483
- text: `Graph validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`,
1484
- },
1485
- ],
1486
- details: undefined,
1487
- isError: true,
1488
- };
1489
- }
1490
-
1491
- // R5: Check session cost limit before spawning
1492
- const costError = gateSessionCost({
1446
+ // Mode prologue (issue #379): cost → depth → resolve → targets →
1447
+ // preflight → H1, with the DAG check as the graph-only pre-cost hook — a
1448
+ // malformed graph (empty / over-limit / duplicate id / missing dep) is
1449
+ // rejected before the session spends anything (IN1 boundary). Cycles are
1450
+ // NOT caught here; topologicalSort rejects them after the tail.
1451
+ const pro = runModePrologue({
1452
+ params,
1493
1453
  state,
1494
1454
  ctx,
1495
1455
  log,
1456
+ label: "Graph",
1496
1457
  units: graphTasks.length,
1497
- label: "Graph delegation",
1498
- });
1499
- if (costError) return costError;
1500
-
1501
- // Reject delegation if recursion depth exceeds configured max
1502
- const currentDepth = getCurrentDepth();
1503
- if (currentDepth >= state.config.maxSubagentDepth) {
1504
- log.warn("Graph delegation rejected: max depth reached", {
1505
- currentDepth,
1506
- maxDepth: state.config.maxSubagentDepth,
1507
- });
1508
- return {
1509
- content: [
1510
- {
1511
- type: "text" as const,
1512
- text:
1513
- `Cannot delegate further: subagent recursion depth limit reached ` +
1514
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
1515
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
1516
- },
1517
- ],
1518
- details: undefined,
1519
- isError: true,
1520
- };
1521
- }
1522
-
1523
- // Resolve global params once
1524
- const globalParams = resolveSubagentParams(
1525
- params as {
1526
- task: string;
1527
- label?: string;
1528
- preset?: string;
1529
- systemPrompt?: string;
1530
- inheritSystemPrompt?: boolean;
1531
- thinkingLevel?: string;
1532
- outputFile?: string;
1533
- timeout?: number;
1534
- cwd?: string;
1535
- tools?: string[];
1536
- excludeTools?: string[];
1537
- noBuiltinTools?: boolean;
1538
- gitMode?: string;
1539
- approvalMode?: string;
1458
+ beforeCost: () => {
1459
+ const errors = validateGraph(graphTasks);
1460
+ return errors.length === 0
1461
+ ? undefined
1462
+ : rejection(`Graph validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
1540
1463
  },
1541
- state,
1542
- ctx,
1543
- log,
1544
- );
1545
-
1546
- // Validate CWD once
1547
- const cwdResult = validateCwd(globalParams.effectiveCwd, ctx.cwd);
1548
- if (!cwdResult.ok) {
1549
- return {
1550
- content: [
1551
- { type: "text" as const, text: `Invalid cwd: ${cwdResult.error}` },
1552
- ],
1553
- details: undefined,
1554
- isError: true,
1555
- };
1556
- }
1557
- const resolvedCwd = cwdResult.value;
1558
-
1559
- // Pre-flight checks
1560
- const pfResult = preflightCheck(resolvedCwd);
1561
- if (!pfResult.ok) {
1562
- log.warn("Graph pre-flight check failed", { error: pfResult.error });
1563
- return {
1564
- content: [
1565
- {
1566
- type: "text" as const,
1567
- text: `Pre-flight check failed: ${pfResult.error}`,
1568
- },
1569
- ],
1570
- details: undefined,
1571
- isError: true,
1572
- };
1573
- }
1574
-
1575
- // H1: Pre-task validation at mode entry — deterministic check that
1576
- // tools/thinking match the task (mirrors single/background modes, issue
1577
- // #32). Graph top-level tasks are empty (modeCount forbids task+graph),
1578
- // so keyword warnings skip on empty text and only the hard
1579
- // outputFile-vs-write conflict applies (issue #34). The mode-level
1580
- // outputFile on globalParams is the one validated here; every node's own
1581
- // cwd/outputFile/tools are validated by the per-node pre-pass below
1582
- // (issue #222).
1583
- const validation = validatePreTask({
1584
- task: globalParams.task,
1585
- toolOptions: globalParams.toolOptions,
1586
- thinkingLevel: globalParams.thinkingLevel,
1587
- gitMode: globalParams.resolvedGitMode,
1588
- outputFile: globalParams.outputFile,
1589
- });
1590
- if (validation.warnings.length > 0) {
1591
- log.warn("Graph pre-task validation warnings", { warnings: validation.warnings });
1592
- }
1593
- if (!validation.valid) {
1594
- const errText = validation.errors.join("; ");
1595
- log.warn("Graph pre-task validation failed", { errors: validation.errors });
1596
- return {
1597
- content: [{ type: "text" as const, text: errText }],
1598
- details: undefined,
1599
- isError: true,
1600
- };
1601
- }
1602
-
1603
- // Resolve model once (per-call top-level model override beats preset)
1604
- const modelResult = resolveSubagentModel(ctx, globalParams.resolvedPreset, params.model as string | undefined);
1605
- if (!modelResult.ok) return modelResult.error;
1606
- const subagentModel = modelResult.model;
1607
-
1608
- const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
1609
- if (!modelStr || modelStr === "/") {
1610
- log.warn("Model string is empty after resolution", { model: subagentModel });
1611
- return {
1612
- content: [
1613
- {
1614
- type: "text" as const,
1615
- text:
1616
- "Subagent model is not configured. " +
1617
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
1618
- },
1619
- ],
1620
- details: undefined,
1621
- isError: true,
1622
- };
1623
- }
1624
-
1625
- // R1: Circuit breaker check
1626
- const circuitCheck = state.checkCircuit();
1627
- if (circuitCheck.isOpen) {
1628
- return {
1629
- content: [
1630
- { type: "text" as const, text: circuitCheck.message! },
1631
- ],
1632
- details: undefined,
1633
- isError: true,
1634
- };
1635
- }
1464
+ });
1465
+ if (!pro.ok) return pro.error;
1466
+ const { globalParams, resolvedCwd, currentDepth } = pro;
1467
+
1468
+ // Mode tail (issue #379): model resolution (preset + per-call override,
1469
+ // auto-route included in `resolvedPreset`), the empty-model rejection and
1470
+ // the circuit check. It runs BEFORE the topological sort and the per-node
1471
+ // pass (IN8/IN11): a graph with a bad node AND an unconfigured model
1472
+ // reports the MODEL error first.
1473
+ const tail = resolveModeModel({
1474
+ state,
1475
+ ctx,
1476
+ log,
1477
+ preset: globalParams.resolvedPreset,
1478
+ perCallModel: params.model,
1479
+ });
1480
+ if (!tail.ok) return tail.error;
1481
+ const subagentModel = tail.model;
1482
+ const modelStr = tail.modelStr;
1636
1483
 
1637
1484
  // Resolve priority — the FALLBACK for per-unit priority (issue #114): a
1638
1485
  // task-level priority on graph[] items wins per slot; this is the floor.
@@ -1670,57 +1517,32 @@ export default function (pi: ExtensionAPI) {
1670
1517
  // wording is still validated, and refusing to validate up front would
1671
1518
  // mean a bad node in the LAST wave is discovered after every earlier
1672
1519
  // wave already spent its budget.
1673
- const nodeCwds = new Map<string, string>();
1674
- const nodeWarnings: string[] = [];
1675
- for (const graphTask of graphTasks) {
1676
- const merged = mergeSubTaskParams(globalParams, {
1677
- task: graphTask.task,
1678
- label: graphTask.label,
1679
- model: graphTask.model,
1680
- thinkingLevel: graphTask.thinkingLevel,
1681
- priority: graphTask.priority,
1682
- cwd: graphTask.cwd,
1683
- timeout: graphTask.timeout,
1684
- outputFile: graphTask.outputFile,
1685
- tools: graphTask.tools,
1686
- excludeTools: graphTask.excludeTools,
1687
- noBuiltinTools: graphTask.noBuiltinTools,
1688
- systemPrompt: graphTask.systemPrompt,
1689
- inheritSystemPrompt: graphTask.inheritSystemPrompt,
1690
- });
1691
- const nodePrefix = `Node "${graphTask.id}"`;
1692
-
1693
- const nodeTargets = validateDelegationTargets({
1694
- ctx,
1695
- effectiveCwd: merged.effectiveCwd,
1696
- outputFile: merged.outputFile,
1697
- prefix: nodePrefix,
1698
- });
1699
- if (!nodeTargets.ok) return nodeTargets.error;
1700
- nodeCwds.set(graphTask.id, nodeTargets.cwd);
1701
-
1702
- const nodeValidation = runPreTaskValidation({
1703
- log,
1704
- label: "Graph",
1705
- prefix: nodePrefix,
1706
- logContext: { id: graphTask.id },
1707
- preTask: {
1708
- // Placeholder TOKENS stripped (issue #222 review): the rules
1709
- // read the declared string, so a `{<id>}` whose dependency id
1710
- // is a blocking keyword would block on a token, not on text
1711
- // the host wrote. The declared wording around it is unchanged
1712
- // and still validated.
1713
- task: merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, " "),
1714
- toolOptions: merged.toolOptions,
1715
- thinkingLevel: merged.thinkingLevel,
1716
- gitMode: globalParams.resolvedGitMode,
1717
- outputFile: merged.outputFile,
1718
- force: params.force as boolean | undefined,
1719
- },
1720
- });
1721
- if (nodeValidation.error) return nodeValidation.error;
1722
- for (const w of nodeValidation.warnings) nodeWarnings.push(`${nodePrefix}: ${w}`);
1723
- }
1520
+ const nodePass = validateUnitPrePass({
1521
+ units: graphTasks,
1522
+ label: "Graph",
1523
+ gitMode: globalParams.resolvedGitMode,
1524
+ ctx,
1525
+ log,
1526
+ force: params.force as boolean | undefined,
1527
+ noJev: params.noJev,
1528
+ // Issue #443: the DECLARED per-node level (the merged one is resolved).
1529
+ declaredThinkingLevel: (node) => node.thinkingLevel,
1530
+ merge: (node) => mergeSubTaskParams(globalParams, graphTaskToSubTaskParams(node)),
1531
+ describe: (node, merged) => ({
1532
+ prefix: `Node "${node.id}"`,
1533
+ logContext: { id: node.id },
1534
+ // Placeholder TOKENS stripped (issue #222 review): the rules
1535
+ // read the declared string, so a `{<id>}` whose dependency id
1536
+ // is a blocking keyword would block on a token, not on text
1537
+ // the host wrote. The declared wording around it is unchanged
1538
+ // and still validated. Graph policy — it stays here, not in
1539
+ // the shared helper.
1540
+ task: merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, " "),
1541
+ }),
1542
+ });
1543
+ if (!nodePass.ok) return nodePass.error;
1544
+ const nodeCwds = new Map(nodePass.units.map((u) => [u.unit.id, u.cwd] as const));
1545
+ const nodeWarnings = nodePass.warnings;
1724
1546
 
1725
1547
  // Build base prompt once
1726
1548
  const basePrompt = ctx.getSystemPrompt();
@@ -1776,21 +1598,7 @@ export default function (pi: ExtensionAPI) {
1776
1598
  // sibling node advances the counter (same-wave siblings run
1777
1599
  // concurrently, so the value must be pinned here).
1778
1600
  const globalNode = ++globalNodeCounter;
1779
- const subTaskParams: SubTaskParams = {
1780
- task: graphTask.task,
1781
- label: graphTask.label,
1782
- model: graphTask.model,
1783
- thinkingLevel: graphTask.thinkingLevel,
1784
- priority: graphTask.priority,
1785
- cwd: graphTask.cwd,
1786
- timeout: graphTask.timeout,
1787
- outputFile: graphTask.outputFile,
1788
- tools: graphTask.tools,
1789
- excludeTools: graphTask.excludeTools,
1790
- noBuiltinTools: graphTask.noBuiltinTools,
1791
- systemPrompt: graphTask.systemPrompt,
1792
- inheritSystemPrompt: graphTask.inheritSystemPrompt,
1793
- };
1601
+ const subTaskParams = graphTaskToSubTaskParams(graphTask);
1794
1602
 
1795
1603
  const merged = mergeSubTaskParams(globalParams, subTaskParams);
1796
1604
  // Issue #222: the node's OWN validated cwd (pre-pass);
@@ -1840,6 +1648,12 @@ export default function (pi: ExtensionAPI) {
1840
1648
  const subagentId = graphTask.id;
1841
1649
  intercom.register(subagentId);
1842
1650
 
1651
+ // Issue #434: the unit projection of the dispatch pre-flight, applied
1652
+ // after this node's slot is held (a node cancelled above never
1653
+ // reaches here) and BEFORE `createUnitRun` below, so the retry
1654
+ // snapshot records the dropped deadline (ADR 0009).
1655
+ applyUnitShapeGuard(ctx, guard, subTaskParams, merged);
1656
+
1843
1657
  // Issue #133: status-bar breakdown — the node's dispatch-wide
1844
1658
  // position (globalNode, not the wave-local nodeIndex) so a later
1845
1659
  // wave reports its true global ordinal.
@@ -1869,7 +1683,8 @@ export default function (pi: ExtensionAPI) {
1869
1683
  // is host-global, so raw graph-task ids would collide across
1870
1684
  // concurrent graph runs (the intercom namespace is per-run and
1871
1685
  // stays untouched).
1872
- registerLiveRun(state, run, ctx);
1686
+ // Issue #423: the merged timeout rides along as the display deadline.
1687
+ registerLiveRun(state, run, ctx, undefined, merged.timeout);
1873
1688
 
1874
1689
  let nodeSuccess = false;
1875
1690
  try {
@@ -1897,19 +1712,12 @@ export default function (pi: ExtensionAPI) {
1897
1712
  run.childMarker,
1898
1713
  );
1899
1714
 
1715
+ // One shared field mapping — issue #376/D3 (the graph literal was a
1716
+ // third copy of it).
1900
1717
  const subTaskResult: SubTaskResult = {
1901
1718
  task: merged.task,
1902
1719
  label: merged.label,
1903
- exitCode: result.exitCode,
1904
- messages: result.messages,
1905
- stderr: result.stderr,
1906
- usage: result.usage,
1907
- model: result.model,
1908
- stopReason: result.stopReason,
1909
- errorMessage: result.errorMessage,
1910
- errorCategory: classifyError(result),
1911
- gitBranch: result.gitBranch,
1912
- gitDiff: result.gitDiff,
1720
+ ...toSubTaskResult(result),
1913
1721
  };
1914
1722
 
1915
1723
  // Issue #133: finalize the per-node run entry — status, duration,
@@ -2070,6 +1878,7 @@ export default function (pi: ExtensionAPI) {
2070
1878
  ctx: ExtensionContext,
2071
1879
  params: DelegateTaskParams,
2072
1880
  signal: AbortSignal | undefined,
1881
+ guard: BatchGuardContext,
2073
1882
  ): Promise<ToolResult<SubagentResult | undefined>> {
2074
1883
  const taskList: SubTaskParams[] = params.tasks!;
2075
1884
 
@@ -2085,26 +1894,7 @@ export default function (pi: ExtensionAPI) {
2085
1894
  if (costError) return costError;
2086
1895
 
2087
1896
  // Resolve global params once — same call shape as runParallelMode.
2088
- const globalParams = resolveSubagentParams(
2089
- params as {
2090
- task: string;
2091
- label?: string;
2092
- preset?: string;
2093
- systemPrompt?: string;
2094
- inheritSystemPrompt?: boolean;
2095
- thinkingLevel?: string;
2096
- outputFile?: string;
2097
- timeout?: number;
2098
- cwd?: string;
2099
- tools?: string[];
2100
- excludeTools?: string[];
2101
- noBuiltinTools?: boolean;
2102
- gitMode?: string;
2103
- },
2104
- state,
2105
- ctx,
2106
- log,
2107
- );
1897
+ const globalParams = resolveSubagentParams(params, state, ctx, log);
2108
1898
 
2109
1899
  // Resolve the global model once (per-call model beats preset/config).
2110
1900
  const globalModelResult = resolveSubagentModel(
@@ -2166,6 +1956,16 @@ export default function (pi: ExtensionAPI) {
2166
1956
  const merged = mergeSubTaskParams(globalParams, taskList[i]);
2167
1957
  const name = displayTaskName(merged);
2168
1958
  const taskPrefix = `Task ${i + 1} ("${name}")`;
1959
+ // Issue #443: the DECLARED per-task level — `merged.thinkingLevel` is
1960
+ // already resolved, so an unknown declaration is indistinguishable from
1961
+ // an omitted one by the time the spawn pass reads it. Checked here, in
1962
+ // the all-before-any-spawn pass, so a bad SECOND task rejects the whole
1963
+ // batch with nothing started.
1964
+ const declaredThinkingError = invalidThinkingLevelRejection(
1965
+ taskList[i].thinkingLevel,
1966
+ taskPrefix,
1967
+ );
1968
+ if (declaredThinkingError) return declaredThinkingError;
2169
1969
  // Per-task model override wins; the global model is the fallback.
2170
1970
  const stepModel = resolveStepModel(ctx, merged.model, globalModel);
2171
1971
 
@@ -2189,6 +1989,8 @@ export default function (pi: ExtensionAPI) {
2189
1989
  gitMode: globalParams.resolvedGitMode,
2190
1990
  outputFile: merged.outputFile,
2191
1991
  force: params.force as boolean | undefined,
1992
+ cwd: targets.cwd,
1993
+ noJev: params.noJev,
2192
1994
  },
2193
1995
  });
2194
1996
  if (preTask.error) return preTask.error;
@@ -2198,8 +2000,17 @@ export default function (pi: ExtensionAPI) {
2198
2000
  }
2199
2001
 
2200
2002
  // Spawn pass — sequential, in task order, through the shared tail.
2201
- const started: Array<{ id: string; label?: string }> = [];
2003
+ // Issue #439: a unit's report is built from its plain identity record plus
2004
+ // its own containment ledger, so a degraded unit is still reported as
2005
+ // STARTED — including when a LATER unit fails or the batch is cancelled.
2006
+ const started: Array<{ id: string; label?: string; tailFailures: string[] }> = [];
2202
2007
  const startedIdsText = (): string => started.map((s) => s.id).join(", ");
2008
+ /** The degraded paragraph for every unit whose monitoring did not attach. */
2009
+ const degradedReport = (): string =>
2010
+ started
2011
+ .filter((s) => s.tailFailures.length > 0)
2012
+ .map((s) => buildMonitoringDegradedParagraph(s, s.tailFailures))
2013
+ .join("");
2203
2014
 
2204
2015
  for (let i = 0; i < fanOutTasks.length; i++) {
2205
2016
  if (signal?.aborted) {
@@ -2213,7 +2024,8 @@ export default function (pi: ExtensionAPI) {
2213
2024
  return {
2214
2025
  content: [{ type: "text" as const, text:
2215
2026
  `Background fan-out cancelled after starting ${started.length} of ${fanOutTasks.length} agents ` +
2216
- `(${startedIdsText()}) — they are detached and will still wake you.`
2027
+ `(${startedIdsText()}) — they are detached and will still wake you.` +
2028
+ degradedReport()
2217
2029
  }],
2218
2030
  details: undefined,
2219
2031
  isError: true,
@@ -2221,6 +2033,12 @@ export default function (pi: ExtensionAPI) {
2221
2033
  }
2222
2034
 
2223
2035
  const { merged, model, cwd, outputFile } = fanOutTasks[i];
2036
+ // Issue #434: called with the dispatch's `unitShape`, which is
2037
+ // "background" here — a detached unit's deadline is the legitimate
2038
+ // 30-minute budget, so nothing is dropped and no unit notice is ever
2039
+ // emitted on this path. The call is here (not omitted) so the exclusion
2040
+ // is visible at the spawn site instead of hidden in a never-taken branch.
2041
+ applyUnitShapeGuard(ctx, guard, taskList[i], merged);
2224
2042
  const name = displayTaskName(merged);
2225
2043
  const subagentPrompt = buildSubagentPrompt(
2226
2044
  ctx.getSystemPrompt(),
@@ -2232,9 +2050,9 @@ export default function (pi: ExtensionAPI) {
2232
2050
  );
2233
2051
  const unitPriority = merged.priority ?? (params.priority as string | undefined);
2234
2052
 
2235
- let agent: BackgroundAgent;
2053
+ let spawned: BackgroundAgentSpawnResult;
2236
2054
  try {
2237
- agent = await startBackgroundAgent(pi, ctx, {
2055
+ spawned = await startBackgroundAgent(pi, ctx, {
2238
2056
  task: merged.task,
2239
2057
  type: (params.preset as string | undefined) || 'general-purpose',
2240
2058
  description: merged.label,
@@ -2280,18 +2098,23 @@ export default function (pi: ExtensionAPI) {
2280
2098
  : "";
2281
2099
  return {
2282
2100
  content: [{ type: "text" as const, text:
2283
- `Failed to spawn background agent for Task ${i + 1} ("${name}"): ${message}` + alreadyStarted
2101
+ `Failed to spawn background agent for Task ${i + 1} ("${name}"): ${message}` + alreadyStarted +
2102
+ // A degraded EARLIER unit is still a started run: its report must
2103
+ // survive this later unit's failure.
2104
+ degradedReport()
2284
2105
  }],
2285
2106
  details: undefined,
2286
2107
  isError: true,
2287
2108
  };
2288
2109
  }
2289
- started.push({ id: agent.id, label: merged.label });
2110
+ started.push({ id: spawned.identity.id, label: merged.label, tailFailures: spawned.tailFailures });
2290
2111
  }
2291
2112
 
2292
2113
  // Text-only result: ids in task order + the wake hint. C: per-task
2293
2114
  // validation warnings ride the immediate SPAWN result (prefixed with
2294
2115
  // their task) so the conductor can stop/re-dispatch in the same turn.
2116
+ // Issue #439: a unit whose monitoring did not attach is still reported
2117
+ // STARTED, with its own degraded paragraph — `isError` stays false.
2295
2118
  const lines = started
2296
2119
  .map((s, i) => `${i + 1}. ${s.label ? `"${s.label}" ` : ""}— ${s.id}`)
2297
2120
  .join("\n");
@@ -2300,7 +2123,8 @@ export default function (pi: ExtensionAPI) {
2300
2123
  `Background agents started: ${started.length}\n\n` +
2301
2124
  `${lines}\n\n` +
2302
2125
  `You'll be woken with a completion message as each finishes; use get_subagent_result({ agent_id }) for retrieval and stall checks.` +
2303
- formatValidationWarnings(taskWarnings)
2126
+ formatValidationWarnings(taskWarnings) +
2127
+ degradedReport()
2304
2128
  }],
2305
2129
  details: undefined,
2306
2130
  };
@@ -2312,8 +2136,11 @@ export default function (pi: ExtensionAPI) {
2312
2136
  // (tasks fan-out): the session-manager import, the spawn call, live-monitor
2313
2137
  // registration, footer counters, the 2s progress poller and the default
2314
2138
  // deadline timer live here exactly once. Callers keep their own prelude,
2315
- // checks, validations and result formatting. THROWS on spawn failure —
2316
- // callers translate the error into their own result shape.
2139
+ // checks, validations and result formatting. THROWS only on spawn failure —
2140
+ // callers translate THAT into their own failure shape. Everything after the
2141
+ // spawn is contained (issue #439): it returns `{ agent, identity,
2142
+ // tailFailures }`, and a non-empty `tailFailures` is a STARTED run with
2143
+ // degraded monitoring, never a failed spawn.
2317
2144
  // -------------------------------------------------------------------
2318
2145
 
2319
2146
  async function startBackgroundAgent(
@@ -2327,6 +2154,9 @@ export default function (pi: ExtensionAPI) {
2327
2154
  thinkingLevel: ThinkingLevel;
2328
2155
  priority?: string;
2329
2156
  systemPrompt: string;
2157
+ /** Issue #411: conductor-authored resume context for an auto-retry,
2158
+ * delivered on the system-prompt side (never inside the task fence). */
2159
+ resumeContext?: string;
2330
2160
  cwd: string;
2331
2161
  toolOptions?: SubagentToolOptions;
2332
2162
  timeout?: number;
@@ -2341,8 +2171,8 @@ export default function (pi: ExtensionAPI) {
2341
2171
  // Option B U3 (D4): recovery posture snapshot for the background run.
2342
2172
  recoveryPosture?: RecoveryMode;
2343
2173
  },
2344
- ): Promise<BackgroundAgent> {
2345
- const { spawnBackgroundSession, setAgentFinalOutput, extractFinalOutput, updateAgentStatus } = await import('./session-manager');
2174
+ ): Promise<BackgroundAgentSpawnResult> {
2175
+ const { spawnBackgroundSession, setAgentFinalOutput, extractFinalOutput } = await import('./session-manager');
2346
2176
  // Issue #31 (PR #76 review, DRY): extract final output from a
2347
2177
  // possibly-released ref — the poller may observe a terminal agent
2348
2178
  // whose ref was already nulled by the settlement path.
@@ -2359,8 +2189,11 @@ export default function (pi: ExtensionAPI) {
2359
2189
  // run entry + drill-in header carry it like foreground runs.
2360
2190
  priority: spawn.priority,
2361
2191
  systemPrompt: spawn.systemPrompt,
2192
+ resumeContext: spawn.resumeContext,
2362
2193
  cwd: spawn.cwd,
2363
2194
  toolOptions: spawn.toolOptions,
2195
+ // Issue #453: the deadline rides the spawn's own timer (one owner). The
2196
+ // caller passes the budget only — no ownership flag, no timer of its own.
2364
2197
  timeout: spawn.timeout,
2365
2198
  gitMode: spawn.gitMode,
2366
2199
  // Issue #98/#108: snapshotOriginalParams is the single source of truth
@@ -2374,223 +2207,286 @@ export default function (pi: ExtensionAPI) {
2374
2207
  recoveryPosture: spawn.recoveryPosture,
2375
2208
  });
2376
2209
 
2210
+ // -----------------------------------------------------------------
2211
+ // Post-spawn containment (issue #439).
2212
+ //
2213
+ // The session EXISTS from here on: the run is live and will wake the
2214
+ // conductor however this tail behaves. A fault in the tail must therefore
2215
+ // classify the run as STARTED with degraded monitoring — never as a failed
2216
+ // spawn. Before this containment an escaping throw reached the callers'
2217
+ // catch, which said "Failed to spawn background agent" while the agent was
2218
+ // running, and the transport retry read that as "did not start".
2219
+ //
2220
+ // Boundary statement (falsifiable). Two different records, and only one of
2221
+ // them is read here:
2222
+ // - `identity` below is a plain record THIS module constructs. Reading its
2223
+ // properties cannot throw; only a monkey-patched accessor could, and this
2224
+ // module never installs one. A fault that wants to reach the degraded
2225
+ // report must therefore be injected at a STATEMENT (a throwing
2226
+ // registerLiveSubagent, a throwing scheduler, a rejecting spawn), which is
2227
+ // what the #439 tests do.
2228
+ // - `agent` (the live record from the spawn) is read ONLY by the identity
2229
+ // capture immediately below and by the poller's terminal-state guard;
2230
+ // every later statement reads `identity` and the captured
2231
+ // primitives instead. The capture itself sits before the outer try, so a
2232
+ // getter-backed `agent` (which the production spawn cannot produce but an
2233
+ // injected one can) would still escape to the caller's catch — that is the
2234
+ // one unpinned read, stated rather than claimed away (2026-11-07 review).
2235
+ // The callers format their results from `identity` alone, so an
2236
+ // adversarial accessor on the live record cannot reach the report text.
2237
+ // If a future change makes `identity` a proxy or getter-backed, this boundary
2238
+ // is void: the failing test is the one asserting a started run never reports
2239
+ // "Failed to spawn".
2240
+ //
2241
+ // Two independently contained groups record into `tailFailures` — G1
2242
+ // bookkeeping, G2 poller — so a fault in one never skips the other. The
2243
+ // deadline is NOT one of them (issue #453): it is the spawn's, armed before
2244
+ // the spawn returned, so no statement here can leave a run unbounded. An
2245
+ // outer catch backstops the ledger itself, and the degraded result is
2246
+ // assembled from `identity` only.
2247
+ // -----------------------------------------------------------------
2248
+ const identity: BackgroundAgentIdentity = {
2249
+ id: agent.id,
2250
+ label: spawn.description,
2251
+ description: agent.description,
2252
+ task: agent.task,
2253
+ status: agent.status,
2254
+ model: agent.model,
2255
+ };
2256
+
2257
+ const tailFailures: string[] = [];
2258
+ /** Record a contained fault. The text reaches the conductor and the user: sanitize. */
2259
+ const recordTailFailure = (group: string, err: unknown): void => {
2260
+ tailFailures.push(
2261
+ `${group}: ${sanitizeErrorMessage(err instanceof Error ? err.message : String(err), spawn.sanitizeCwd)}`,
2262
+ );
2263
+ };
2264
+
2265
+ let pollInterval: ReturnType<typeof setInterval> | undefined;
2266
+ /** G1 completed the counter increment — the ONLY runs that may decrement. */
2267
+ let countedForThisRun = false;
2268
+ let completed = false;
2269
+
2270
+ /** Stop the live-poll. The deadline is NOT the caller's to stop (issue #453). */
2271
+ const stopTailPolling = (): void => {
2272
+ if (pollInterval !== undefined) clearInterval(pollInterval);
2273
+ };
2274
+
2275
+ /**
2276
+ * Release this run's live counter — the ONE decrement shape for all five
2277
+ * poller/deadline sites. Gated on `countedForThisRun` AND on the finalize
2278
+ * claim: a run that never incremented (G1 failed before it) must not
2279
+ * decrement, and a run the stale sweep already finalized had its decrement
2280
+ * taken there (PR #71 review). The first gate is what keeps the ordering in
2281
+ * G1 honest — without it, a row registered before the increment let the
2282
+ * sweep's decrement land on a SIBLING's count.
2283
+ *
2284
+ * Belt-and-braces, stated as such (2026-11-07 review): with the current
2285
+ * increment-first order in G1, `countedForThisRun` is always true by the time
2286
+ * any callback can call this, so removing the flag alone changes nothing and
2287
+ * no test pins it (an extra removal mutant survived). It is kept because the
2288
+ * ORDERING is the real invariant: when the row is registered before the
2289
+ * increment, the flag is the only thing standing between a settle and a
2290
+ * sibling's count — M8 (reorder G1) fails T2b exactly because of it.
2291
+ *
2292
+ * Stated limit: the decrement is only reachable from a monitor that a run
2293
+ * owns. If G1 AND G2 BOTH fail for the same run (counted, no row, no poller)
2294
+ * nothing can release its count, so the footer's active count stays one high
2295
+ * for the session. That is the honest reading — the run is real and
2296
+ * unmonitored — and the alternative (releasing from a group that never
2297
+ * attached) is how a sibling's count gets stolen.
2298
+ *
2299
+ * Issue #453: the deadline used to be a third releaser. It is not any more
2300
+ * and does not need to be — the poller sees the spawn's `stopped` +
2301
+ * `completedAt` on its next tick and releases there, which is exactly how an
2302
+ * explicit-timeout run has always been released.
2303
+ */
2304
+ const releaseLiveCount = (): void => {
2305
+ if (!countedForThisRun) return;
2306
+ if (!state.finalizeLiveSubagent(identity.id)) return;
2307
+ state.activeSubagents--;
2308
+ if (state.activeSubagents < 0) state.activeSubagents = 0;
2309
+ };
2310
+
2377
2311
  // Issue #318 (from #316 review): the two poller crash sites share one
2378
2312
  // claimed notification envelope. Content is the only variable; the
2379
2313
  // claim guard, display, details and deliverAs live here once.
2314
+ // Issue #439: best-effort — the claim and the send sit in their own try, so
2315
+ // neither a throwing claim nor a throwing send can turn a crash notice into
2316
+ // a fault on the run's reporting path.
2380
2317
  const sendCrashNotice = (content: string): void => {
2381
- if (claimTerminalNotice(agent.id)) {
2318
+ try {
2319
+ if (!claimTerminalNotice(identity.id)) return;
2320
+ } catch {
2321
+ return;
2322
+ }
2323
+ try {
2382
2324
  pi.sendMessage({
2383
2325
  customType: "subagent-notification",
2384
2326
  content,
2385
2327
  display: true,
2386
- details: { agentId: agent.id }
2328
+ details: { agentId: identity.id }
2387
2329
  }, { deliverAs: "followUp" });
2388
- }
2330
+ } catch { /* best-effort */ }
2389
2331
  };
2390
2332
 
2391
- // Register for live monitor
2392
- state.registerLiveSubagent(agent.id, {
2393
- id: agent.id,
2394
- label: agent.description,
2395
- task: agent.task,
2396
- model: agent.model,
2397
- thinkingLevel: agent.thinkingLevel,
2398
- priority: agent.priority,
2399
- startedAt: agent.startedAt,
2400
- ctx,
2401
- });
2402
-
2403
- // Update footer counters
2404
- state.activeSubagents++;
2405
- repaintStatus(state, ctx);
2333
+ try {
2334
+ // ---- G1: bookkeeping ------------------------------------------
2335
+ // Ordering (issue #439, measured): counter FIRST, then the live row,
2336
+ // then the repaint. A row therefore always implies a counted run, so the
2337
+ // stale sweep's decrement can only release this run's own count.
2338
+ try {
2339
+ state.activeSubagents++;
2340
+ countedForThisRun = true;
2341
+ state.registerLiveSubagent(identity.id, {
2342
+ id: identity.id,
2343
+ label: identity.description,
2344
+ task: identity.task,
2345
+ model: identity.model,
2346
+ thinkingLevel: agent.thinkingLevel,
2347
+ priority: agent.priority,
2348
+ startedAt: agent.startedAt,
2349
+ // Issue #423: the persisted EFFECTIVE budget, anchored on the record's
2350
+ // own start clock — the same clock the deadline timers use.
2351
+ ...(agent.timeoutMs !== undefined
2352
+ ? { deadlineAt: agent.startedAt + agent.timeoutMs }
2353
+ : {}),
2354
+ ctx,
2355
+ });
2356
+ repaintStatus(state, ctx);
2357
+ } catch (err) {
2358
+ recordTailFailure("live-monitor bookkeeping", err);
2359
+ }
2406
2360
 
2407
- let completed = false;
2408
-
2409
- // Poll for live progress
2410
- const pollInterval = setInterval(() => {
2361
+ // ---- G2: live progress poller --------------------------------
2362
+ // Issue #453: this poller is the CLEANUP OWNER for a deadline stop. The
2363
+ // spawn's timer sets `status: 'stopped'` + `completedAt` (via
2364
+ // updateAgentStatus) and aborts; on its next tick the poller below sees
2365
+ // the terminal record and does every caller-owned step — output capture,
2366
+ // the finalize claim, the counter decrement, the repaint — then stops
2367
+ // itself. Nothing here arms or clears a deadline.
2411
2368
  try {
2412
- if (completed) return;
2413
-
2414
- const session = agent._sessionRef;
2415
- // Issue #31: a nulled ref on a TERMINAL agent is expected (the
2416
- // settlement path releases the ref) — fall through to finalize
2417
- // below instead of treating it as a crash. A nulled ref on a
2418
- // live agent is still a crash.
2419
- if (!session && !agent.completedAt) {
2420
- // Session ref not available — session may have crashed.
2421
- // Defensive: the ref is assigned synchronously before the poller starts
2422
- // and is never nulled, so this is mostly unreachable — but keep the
2423
- // bookkeeping safe regardless.
2424
- completed = true;
2425
- clearInterval(pollInterval);
2426
- clearTimeout(hardCapHandle);
2427
- // Capture whatever output exists (may be empty — fine).
2428
- setAgentFinalOutput(agent.id, state.subagentSessions.get(agent.id)?.liveOutput ?? '');
2429
- // Gate the counter on the finalize claim: if the
2430
- // stale sweep already finalized this entry, the
2431
- // decrement happened there (PR #71 review).
2432
- if (state.finalizeLiveSubagent(agent.id)) {
2433
- state.activeSubagents--;
2434
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2435
- }
2436
- state.failedSubagents++;
2437
- repaintStatus(state, ctx);
2438
- sendCrashNotice(`Background agent "${agent.description}" crashed.`);
2439
- return;
2440
- }
2441
-
2442
- // While running, update the live monitor.
2443
- // Once completedAt is set, skip straight to finalize below.
2444
- // Issue #31: past the guard above, the only nulled-ref path left is a
2445
- // TERMINAL agent (settlement releases the ref), so a live agent always
2446
- // has its session — the guard already returned on the live-nulled-ref
2447
- // crash path. The compiler can't correlate the two checks, so assert it.
2448
- if (!agent.completedAt) {
2449
- const finalOutput = extractFinalOutput(session!);
2450
-
2369
+ pollInterval = setInterval(() => {
2451
2370
  try {
2452
- const stats = session!.getSessionStats();
2453
- state.updateLiveSubagent(agent.id, finalOutput, stats.tokens.input, stats.tokens.output);
2454
- } catch {
2455
- state.updateLiveSubagent(agent.id, finalOutput, 0, 0);
2456
- }
2457
- }
2458
-
2459
- // Authoritative completion: the prompt promise settled — status and
2460
- // completedAt are set by .then()/.catch() in spawnBackgroundSession.
2461
- // Do NOT rely on !session.isStreaming: it is false during prompt()
2462
- // preflight (auth check, model resolution) and for failed starts.
2463
- if (agent.completedAt) {
2464
- completed = true;
2465
- clearInterval(pollInterval);
2466
- clearTimeout(hardCapHandle);
2467
-
2468
- // Issue #31: prefer the output already captured at settlement;
2469
- // the ref may already be nulled on terminal agents, so never
2470
- // overwrite with empty and stay null-safe.
2471
- const finalOutput = agent.finalOutput ?? extractAgentFinalOutput(agent);
2472
- setAgentFinalOutput(agent.id, finalOutput);
2473
-
2474
- // Gate the counter on the finalize claim: if the
2475
- // stale sweep already finalized this entry, the
2476
- // decrement happened there (PR #71 review).
2477
- if (state.finalizeLiveSubagent(agent.id)) {
2478
- state.activeSubagents--;
2479
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2480
- }
2481
-
2482
- if (agent.status === 'failed') {
2483
- state.failedSubagents++;
2484
- repaintStatus(state, ctx);
2485
- // Issue #315: the terminal wake (`subagent-completion`, emitted by
2486
- // the session-manager settle) is the ONE notice for a failed run.
2487
- // The status here was set by that settle, so the wake already
2488
- // delivered — this legacy poller notice would duplicate it.
2489
- } else if (agent.status === 'stopped') {
2490
- // User-initiated stop (stop_subagent) or deadline abort
2491
- // (timeout/deadline) — not a failure.
2492
- repaintStatus(state, ctx);
2493
- } else {
2494
- state.completedSubagents++;
2495
- state.unseenSubagents++;
2496
- repaintStatus(state, ctx);
2371
+ if (completed) return;
2372
+
2373
+ const session = agent._sessionRef;
2374
+ // Issue #31: a nulled ref on a TERMINAL agent is expected (the
2375
+ // settlement path releases the ref) — fall through to finalize
2376
+ // below instead of treating it as a crash. A nulled ref on a
2377
+ // live agent is still a crash.
2378
+ if (!session && !agent.completedAt) {
2379
+ // Session ref not available — session may have crashed.
2380
+ // Defensive: the ref is assigned synchronously before the poller starts
2381
+ // and is never nulled, so this is mostly unreachable — but keep the
2382
+ // bookkeeping safe regardless.
2383
+ completed = true;
2384
+ stopTailPolling();
2385
+ // Capture whatever output exists (may be empty — fine).
2386
+ setAgentFinalOutput(identity.id, state.subagentSessions.get(identity.id)?.liveOutput ?? '');
2387
+ releaseLiveCount();
2388
+ state.failedSubagents++;
2389
+ repaintStatus(state, ctx);
2390
+ sendCrashNotice(`Background agent "${identity.description}" crashed.`);
2391
+ return;
2392
+ }
2393
+
2394
+ // While running, update the live monitor.
2395
+ // Once completedAt is set, skip straight to finalize below.
2396
+ // Issue #31: past the guard above, the only nulled-ref path left is a
2397
+ // TERMINAL agent (settlement releases the ref), so a live agent always
2398
+ // has its session — the guard already returned on the live-nulled-ref
2399
+ // crash path. The compiler can't correlate the two checks, so assert it.
2400
+ if (!agent.completedAt) {
2401
+ const finalOutput = extractFinalOutput(session!);
2402
+
2403
+ try {
2404
+ const stats = session!.getSessionStats();
2405
+ state.updateLiveSubagent(identity.id, finalOutput, stats.tokens.input, stats.tokens.output);
2406
+ } catch {
2407
+ state.updateLiveSubagent(identity.id, finalOutput, 0, 0);
2408
+ }
2409
+ }
2410
+
2411
+ // Authoritative completion: the prompt promise settled — status and
2412
+ // completedAt are set by .then()/.catch() in spawnBackgroundSession.
2413
+ // Do NOT rely on !session.isStreaming: it is false during prompt()
2414
+ // preflight (auth check, model resolution) and for failed starts.
2415
+ if (agent.completedAt) {
2416
+ completed = true;
2417
+ stopTailPolling();
2418
+
2419
+ // Issue #31: prefer the output already captured at settlement;
2420
+ // the ref may already be nulled on terminal agents, so never
2421
+ // overwrite with empty and stay null-safe.
2422
+ const finalOutput = agent.finalOutput ?? extractAgentFinalOutput(agent);
2423
+ setAgentFinalOutput(identity.id, finalOutput);
2424
+
2425
+ releaseLiveCount();
2426
+
2427
+ if (agent.status === 'failed') {
2428
+ state.failedSubagents++;
2429
+ repaintStatus(state, ctx);
2430
+ // Issue #315: the terminal wake (`subagent-completion`, emitted by
2431
+ // the session-manager settle) is the ONE notice for a failed run.
2432
+ // The status here was set by that settle, so the wake already
2433
+ // delivered — this legacy poller notice would duplicate it.
2434
+ } else if (agent.status === 'stopped') {
2435
+ // User-initiated stop (stop_subagent) or deadline abort
2436
+ // (timeout/deadline) — not a failure.
2437
+ repaintStatus(state, ctx);
2438
+ } else {
2439
+ state.completedSubagents++;
2440
+ state.unseenSubagents++;
2441
+ repaintStatus(state, ctx);
2442
+ }
2443
+ }
2444
+ } catch (err) {
2445
+ if (!completed) {
2446
+ completed = true;
2447
+ stopTailPolling();
2448
+ try {
2449
+ setAgentFinalOutput(identity.id, extractAgentFinalOutput(agent));
2450
+ } catch { /* ignore */ }
2451
+ releaseLiveCount();
2452
+ state.failedSubagents++;
2453
+ repaintStatus(state, ctx);
2454
+ sendCrashNotice(`Background agent "${identity.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
2455
+ }
2497
2456
  }
2498
- }
2457
+ }, 2000);
2499
2458
  } catch (err) {
2500
- if (!completed) {
2501
- completed = true;
2502
- clearInterval(pollInterval);
2503
- clearTimeout(hardCapHandle);
2504
- try {
2505
- setAgentFinalOutput(agent.id, extractAgentFinalOutput(agent));
2506
- } catch { /* ignore */ }
2507
- // Gate the counter on the finalize claim: if the
2508
- // stale sweep already finalized this entry, the
2509
- // decrement happened there (PR #71 review).
2510
- if (state.finalizeLiveSubagent(agent.id)) {
2511
- state.activeSubagents--;
2512
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2513
- }
2514
- state.failedSubagents++;
2515
- repaintStatus(state, ctx);
2516
- sendCrashNotice(`Background agent "${agent.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
2517
- }
2459
+ recordTailFailure("progress polling", err);
2518
2460
  }
2519
- }, 2000);
2520
-
2521
- // Default deadline: stop polling AND abort the session after the
2522
- // deadline. W2 (issue #28): previously this only stopped the poller —
2523
- // the pi session kept running forever (orphaned). Now it pre-sets
2524
- // 'stopped' (so the .then keeps it, per W1) and aborts the session.
2525
- // Issue #240: an explicit per-agent timeout is HONORED verbatim; this
2526
- // deadline DEFAULTS to 30m only when no timeout is given. It is a
2527
- // default, not a ceiling. Issue #244: exactly ONE deadline timer per
2528
- // run — an explicit timeout is owned by the session-manager W3 timer,
2529
- // so this index timer arms ONLY on the no-timeout path, mirroring
2530
- // spawnBackgroundSession's `params.timeout && params.timeout > 0` guard
2531
- // (with no timeout, it owns the 30m default, #28).
2532
- const hasExplicitDeadline = spawn.timeout !== undefined && spawn.timeout > 0;
2533
- const hardCapMs = spawn.timeout ?? DEFAULT_BACKGROUND_DEADLINE_MS;
2534
- const hardCapHandle: ReturnType<typeof setTimeout> | undefined =
2535
- hasExplicitDeadline ? undefined : setTimeout(() => {
2536
- if (!completed && !agent.completedAt) {
2537
- try {
2538
- completed = true;
2539
- clearInterval(pollInterval);
2540
- // Pre-set stopped BEFORE aborting so the .then in
2541
- // spawnBackgroundSession keeps the stopped state.
2542
- updateAgentStatus(agent.id, 'stopped', `Timed out (${hardCapMs}ms deadline)`);
2543
- agent._sessionRef?.abort().catch(() => {
2544
- // Abort may reject if the session is mid-dispose;
2545
- // the status flip above is already recorded.
2546
- });
2547
- // Capture whatever final output exists in the session
2548
- const hardCapSession = agent._sessionRef;
2549
- const hardCapFinalOutput = hardCapSession ? extractFinalOutput(hardCapSession) : '';
2550
- setAgentFinalOutput(agent.id, hardCapFinalOutput);
2551
- // Gate the counter on the finalize claim: if the
2552
- // stale sweep already finalized this entry, the
2553
- // decrement happened there (PR #71 review).
2554
- if (state.finalizeLiveSubagent(agent.id)) {
2555
- state.activeSubagents--;
2556
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2557
- }
2558
- // m6: deadline abort is a stop, not a completion — mirror the
2559
- // W3/poller stopped path (no completedSubagents increment).
2560
- repaintStatus(state, ctx);
2561
- } catch (err) {
2562
- // Defensive: never let the deadline timer throw uncaught — that would
2563
- // skip finalizeLiveSubagent, the counter decrement, and the notification.
2564
- // Do all fallible work first (output capture), then mutate counters,
2565
- // then notify — a throw mid-path can't double-fire mutations.
2566
- completed = true;
2567
- clearInterval(pollInterval);
2568
- // m3: the try may have thrown BEFORE updateAgentStatus ran (e.g.
2569
- // persistAgent fs failure) — leave the record terminal so
2570
- // get_subagent_result doesn't report 'running' and the W3 timer
2571
- // guard (!agent.completedAt) can't re-fire later.
2572
- try {
2573
- updateAgentStatus(agent.id, 'stopped', `Timed out (${hardCapMs}ms deadline)`);
2574
- } catch { /* ignore */ }
2575
- try {
2576
- setAgentFinalOutput(agent.id, extractAgentFinalOutput(agent));
2577
- } catch { /* ignore */ }
2578
- // Gate the counter on the finalize claim: if the
2579
- // stale sweep already finalized this entry, the
2580
- // decrement happened there (PR #71 review).
2581
- if (state.finalizeLiveSubagent(agent.id)) {
2582
- state.activeSubagents--;
2583
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2584
- }
2585
- state.failedSubagents++;
2586
- repaintStatus(state, ctx);
2587
- }
2461
+
2462
+ try {
2463
+ log.info("Background agent spawned", { agentId: identity.id, task: spawn.task, model: identity.model });
2464
+ } catch (err) {
2465
+ recordTailFailure("spawn log", err);
2588
2466
  }
2589
- }, hardCapMs);
2590
-
2591
- log.info("Background agent spawned", { agentId: agent.id, task: spawn.task, model: agent.model });
2467
+ } catch (err) {
2468
+ // Backstop: the groups above swallow their own faults, so this can only
2469
+ // see a fault in the ledger machinery itself. The degraded result below is
2470
+ // assembled from `identity` — never from a property read on `agent`.
2471
+ recordTailFailure("spawn tail", err);
2472
+ }
2473
+
2474
+ if (tailFailures.length > 0) {
2475
+ // ONE advisory per run, after aggregation. It is NOT a terminal notice
2476
+ // and never takes the terminal claim (issue #439 contract): the run's
2477
+ // genuine completion notice is still delivered when it settles.
2478
+ // 2026-11-07 review: this call is INSIDE the outer containment, not after
2479
+ // it — the advisory's own dispatch surfaces are contained too, and the
2480
+ // inner per-channel tries in `sendMonitoringDegradedAdvisory` cover the
2481
+ // case where one channel throws (so one failure cannot lose both).
2482
+ try {
2483
+ sendMonitoringDegradedAdvisory(pi, ctx, identity, tailFailures);
2484
+ } catch (err) {
2485
+ recordTailFailure("monitoring advisory", err);
2486
+ }
2487
+ }
2592
2488
 
2593
- return agent;
2489
+ return { agent, identity, tailFailures };
2594
2490
  }
2595
2491
 
2596
2492
  // -------------------------------------------------------------------
@@ -2601,17 +2497,43 @@ export default function (pi: ExtensionAPI) {
2601
2497
  async function spawnBackgroundRun(
2602
2498
  pi: ExtensionAPI,
2603
2499
  ctx: ExtensionContext,
2604
- params: Omit<Parameters<typeof resolveSubagentParams>[0], "task"> & {
2605
- task?: string;
2606
- model?: string;
2607
- priority?: string;
2608
- },
2500
+ /**
2501
+ * Two shapes, both passed WITHOUT an assertion (issue #379):
2502
+ * - `DelegateTaskParams` — a fresh dispatch, schema-validated;
2503
+ * - the `resolveRetryParams` bag — rebuilt from a run record, whose
2504
+ * `priority` is the unvalidated persisted string. It is the only field
2505
+ * the two shapes disagree on, and claiming the recorded value was
2506
+ * schema-validated would be a lie: records are read back from disk.
2507
+ */
2508
+ params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
2609
2509
  singleTask: string,
2610
2510
  // Option B U1: the spawn entry a retryRunId resolved to, so a retried
2611
2511
  // background run inherits dispatchId/resumeOf/attempt (record identity,
2612
2512
  // not a delegate param — D4).
2613
2513
  retrySourceRun?: SubagentRun,
2514
+ /**
2515
+ * Issue #401/#411: the resume preamble for a TRANSPORT auto-retry. It rides
2516
+ * the child's system prompt only (as a `<resume-context>` section) — never
2517
+ * inside the `<task>` fence. `resolveSubagentParams`, every gate and every
2518
+ * H1 check above still see `singleTask` (which stays byte-identical to the
2519
+ * recorded original), so routing, capability warnings and pre-flight checks
2520
+ * cannot be steered by the preamble's wording.
2521
+ */
2522
+ attemptContext?: string,
2614
2523
  ): Promise<ToolResult<undefined>> {
2524
+ // Issue #443: the DECLARED level, guarded before `bgResolved` clamps it.
2525
+ // This is the seam for the TRANSPORT auto-retry (`scheduleTransportRetry`
2526
+ // re-enters here with `resolveRetryParams`' rebuilt bag and never passes
2527
+ // through `execute`), and the reason a restored record carrying an unknown
2528
+ // level cannot launch a session at pi's default. A rejection here surfaces
2529
+ // as the ORIGINAL failure's notice — the caller reports it unchanged.
2530
+ const bgDeclaredThinkingLevel = declaredThinkingLevel(
2531
+ params.thinkingLevel,
2532
+ resolveDispatchPreset({ ...params, task: singleTask }, state).preset?.thinkingLevel,
2533
+ );
2534
+ const bgDeclaredThinkingError = invalidThinkingLevelRejection(bgDeclaredThinkingLevel);
2535
+ if (bgDeclaredThinkingError) return bgDeclaredThinkingError;
2536
+
2615
2537
  // Phase 6.5: Background execution — spawn session and return ID immediately.
2616
2538
  // Resolve the preset and its model BEFORE the background branch so the
2617
2539
  // preset's model (and system prompt) are honored in background mode.
@@ -2676,6 +2598,8 @@ export default function (pi: ExtensionAPI) {
2676
2598
  gitMode: bgResolved.resolvedGitMode,
2677
2599
  outputFile: bgResolvedOutputFile,
2678
2600
  force: params.force,
2601
+ cwd: targets.cwd,
2602
+ noJev: params.noJev,
2679
2603
  },
2680
2604
  });
2681
2605
  if (bgPreTask.error) return bgPreTask.error;
@@ -2693,8 +2617,13 @@ export default function (pi: ExtensionAPI) {
2693
2617
 
2694
2618
  // Option B U1: durability identity (retry inherits the original dispatch).
2695
2619
  const bgIdentity = newDispatchIdentity(retrySourceRun);
2696
- const agent = await startBackgroundAgent(pi, ctx, {
2620
+ const spawned = await startBackgroundAgent(pi, ctx, {
2621
+ // Issue #411: the preamble rides the system-prompt side
2622
+ // (`resumeContext`), never the task. The task stays the recorded
2623
+ // original, and the snapshot keeps it too, so a later retry of this
2624
+ // retry resolves from the un-prefixed text and never compounds.
2697
2625
  task: singleTask,
2626
+ resumeContext: attemptContext,
2698
2627
  type: params.preset || 'general-purpose',
2699
2628
  description: params.label,
2700
2629
  model: bgModel,
@@ -2705,7 +2634,9 @@ export default function (pi: ExtensionAPI) {
2705
2634
  toolOptions: bgResolved.toolOptions,
2706
2635
  timeout: bgResolved.timeout,
2707
2636
  gitMode: bgResolved.resolvedGitMode,
2708
- originalParams: snapshotOriginalParams(params),
2637
+ originalParams: attemptContext
2638
+ ? { ...snapshotOriginalParams(params), task: singleTask }
2639
+ : snapshotOriginalParams(params),
2709
2640
  sanitizeCwd: bgResolved.effectiveCwd,
2710
2641
  dispatchId: bgIdentity.dispatchId,
2711
2642
  resumeOf: bgIdentity.resumeOf,
@@ -2726,22 +2657,34 @@ export default function (pi: ExtensionAPI) {
2726
2657
  ? `\n\n[auto-routed to preset '${bgAutoRoutedPreset.name}'${bgAutoRouteKeyword ? ` (matched keyword '${bgAutoRouteKeyword}')` : ""} — ${bgResolved.toolOptions ? formatToolRestriction(bgResolved.toolOptions) : formatPresetRestriction(bgAutoRoutedPreset)}]`
2727
2658
  : "";
2728
2659
 
2660
+ // Issue #439: everything the result states comes from `identity`, the plain
2661
+ // record captured at spawn time — never a property read on the live agent.
2662
+ // A non-empty `tailFailures` is a STARTED run with degraded monitoring, so
2663
+ // this stays a success (`isError` false) with the degraded paragraph;
2664
+ // the transport retry reads `isError` as "did not start" and must not see
2665
+ // a started run here.
2729
2666
  return {
2730
2667
  content: [{
2731
2668
  type: "text" as const,
2732
- text: `Background agent started: ${agent.id}\n\n` +
2733
- `Description: ${agent.description}\n` +
2734
- `Task: ${agent.task}\n` +
2735
- `Status: ${agent.status}\n\n` +
2736
- `You'll be woken with a completion message when it finishes; use get_subagent_result({ agent_id: "${agent.id}" }) for retrieval and stall checks.` +
2669
+ text: `Background agent started: ${spawned.identity.id}\n\n` +
2670
+ `Description: ${spawned.identity.description}\n` +
2671
+ `Task: ${spawned.identity.task}\n` +
2672
+ `Status: ${spawned.identity.status}\n\n` +
2673
+ `You'll be woken with a completion message when it finishes; use get_subagent_result({ agent_id: "${spawned.identity.id}" }) for retrieval and stall checks.` +
2737
2674
  bgAutoRouteNote +
2738
2675
  // C: warnings ride the immediate SPAWN result so the conductor
2739
2676
  // can stop/re-dispatch in the same turn.
2740
- formatValidationWarnings(bgPreTask.warnings),
2677
+ formatValidationWarnings(bgPreTask.warnings) +
2678
+ buildMonitoringDegradedParagraph(spawned.identity, spawned.tailFailures),
2741
2679
  }],
2742
2680
  details: undefined,
2681
+ isError: false,
2743
2682
  };
2744
2683
  } catch (err) {
2684
+ // Issue #439: this catch is reachable ONLY for a pre-spawn gate or a
2685
+ // rejected `spawnBackgroundSession`. Everything after a successful spawn
2686
+ // is contained in `startBackgroundAgent` — a run that started never lands
2687
+ // here, so the wording below can never describe a live run.
2745
2688
  const message = sanitizeErrorMessage(
2746
2689
  err instanceof Error ? err.message : String(err),
2747
2690
  bgResolved.effectiveCwd,
@@ -2862,7 +2805,7 @@ export default function (pi: ExtensionAPI) {
2862
2805
  `Use preset to apply a delegation configuration (built-in or custom via /brl-subagent preset). Preset values are defaults — explicit parameters override them. IMPORTANT: some presets restrict tools — e.g. outputFile requires the subagent's write tool, which security-auditor and code-reviewer exclude. Built-in presets: ${presetRestrictionSummary}. Custom presets are NOT listed here — inspect them via /brl-subagent preset before combining with outputFile or tool-dependent work. When combining a preset with outputFile or tool-dependent work, verify the preset allows the required tools.`,
2863
2806
  buildTemplateGuideline(templateSummary),
2864
2807
  "To retry a failed subagent, pass its run ID as retryRunId. The retry restores the recorded params - including background, gitMode, approvalMode, force - with explicit values on this call winning. Multi-step runs degrade to a single task. See the retryRunId description for the full field list.",
2865
- "Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. Background runs are not auto-retried; re-dispatch with retryRunId.",
2808
+ "Set retryOnTimeout: true to automatically retry a FOREGROUND subagent that times out. Only retries once — the second timeout is treated as a final failure. A background run is not retried on its deadline, but it IS retried once automatically when it dies on a transport-class error (a dropped connection before the work started), recorded as attempt 2 and announced with a warning toast — do not re-dispatch it yourself. Any other background failure needs an explicit retryRunId.",
2866
2809
  "Background is the CONDITIONAL default for delegate_task. With background omitted, a single task or a tasks fan-out runs in the BACKGROUND when the effective approvalMode is 'auto' (call param, else config): the tool returns an agent ID immediately, and with tasks it fans out — every task starts as its own background agent, one ID per task in task order, and the conductor is woken once per agent as each finishes. It stays FOREGROUND when the effective approvalMode is 'writes' or 'always' (a background run has no approval dialog, so a gate that needs the user must keep blocking), and for chain and graph (they block by definition; an explicit background: true with chain/graph is rejected). Pass background: false for a quick probe whose answer the next step needs inline; pass background: true to force a background run where the default would block. Background runs wake the conductor with a structured completion message when they finish — do not poll: polling is only correct when completion notifications are disabled (completionNotify \"off\"); one status check as a stall check is legitimate. A background run defaults to a 30-minute deadline when no timeout is given.",
2867
2810
  "",
2868
2811
  "## Conductor Guardrails",
@@ -3081,6 +3024,118 @@ export default function (pi: ExtensionAPI) {
3081
3024
  // self-evident (issue #361 review).
3082
3025
  const explicitBackground = params.background;
3083
3026
 
3027
+ // Issue #412 (rule 2: "no deadline ⇒ durable path") — the dispatch-shape
3028
+ // pre-flight. A high/xhigh-thinking run the conductor asked to run
3029
+ // FOREGROUND with an explicit timeout is the shape that lost 14 minutes of
3030
+ // plan critique on 2026-10-31: foreground runs persist nothing, so the
3031
+ // deadline kills the work outright, while a background run keeps its
3032
+ // session and is retried on a transport error. The switch is applied HERE
3033
+ // — after template/retry resolution and BEFORE `useBackground` is resolved
3034
+ // and before any run record is written — so the shape every downstream
3035
+ // reader sees (the spawn, the retry snapshot, the pending-work record) is
3036
+ // the switched one. Moving it after `snapshotOriginalParams` would record
3037
+ // `background:false` and silently cost the run its transport auto-retry
3038
+ // (`transport-retry.ts` classifies off that snapshot).
3039
+ // Issue #415: the switch is OUR process (a conductor decision rule), not
3040
+ // product behavior — a user's explicit foreground timeout is usually a
3041
+ // budget cap, so a GLOBAL switch could triple time and cost against
3042
+ // their instruction. The umbrella project-local `processChecks` flag
3043
+ // gates it (fail-open: no/malformed manifest → off). Resolve the
3044
+ // dispatch cwd ONCE, the way the target validation below will.
3045
+ const processChecksCwd =
3046
+ params.cwd === undefined ? ctx.cwd : path.resolve(ctx.cwd, params.cwd);
3047
+ const processChecks = readProcessChecks(processChecksCwd);
3048
+ // The preset the dispatch will actually run with — an auto-routed
3049
+ // `code-reviewer`/`debugger` is a high-thinking run even though the
3050
+ // caller declared no level, so the pre-flight resolves the SAME preset
3051
+ // the merge below will (one rule, `resolveDispatchPreset`).
3052
+ const declaredPresetForSwitch = resolveDispatchPreset(params, state).preset;
3053
+ // Issue #443: guard the EFFECTIVE DECLARED level here — the per-call value
3054
+ // or the selected preset's (named, or auto-routed by the line above) —
3055
+ // BEFORE `resolveSubagentParams` clamps it. `params.thinkingLevel` is
3056
+ // already the post-template, post-`retryRunId` value by this point, so a
3057
+ // level restored from a run record is judged too; a preset object injected
3058
+ // in memory never passed a schema or the preset-file validator, so this
3059
+ // is its only check. Everything below runs through this one seam: the
3060
+ // single, background, chain, parallel and graph handlers are all reached
3061
+ // from here, and the per-unit declarations are guarded by the pre-passes.
3062
+ const effectiveDeclaredThinkingLevel = declaredThinkingLevel(
3063
+ params.thinkingLevel,
3064
+ declaredPresetForSwitch?.thinkingLevel,
3065
+ );
3066
+ const declaredThinkingError = invalidThinkingLevelRejection(effectiveDeclaredThinkingLevel);
3067
+ if (declaredThinkingError) return declaredThinkingError;
3068
+ // The EFFECTIVE approval mode (call param, else the configured default) —
3069
+ // the same resolver `resolveSubagentParams` and the #361 default use, so the
3070
+ // pre-flight cannot judge a mode the child will not run with. Reading
3071
+ // `params.approvalMode` raw here would miss a config-tier mode entirely.
3072
+ const effectiveApprovalModeForSwitch = resolveEffectiveApprovalMode(
3073
+ params.approvalMode,
3074
+ state,
3075
+ );
3076
+ const thinkingSwitch = resolveThinkingDispatchSwitch({
3077
+ processChecks,
3078
+ thinkingLevel: effectiveDeclaredThinkingLevel as ThinkingLevel | undefined,
3079
+ explicitBackground,
3080
+ timeout: params.timeout,
3081
+ force: params.force,
3082
+ shape: dispatchShape,
3083
+ effectiveApprovalMode: effectiveApprovalModeForSwitch,
3084
+ });
3085
+ if (thinkingSwitch === "switch") {
3086
+ params.background = true;
3087
+ // Drop the foreground deadline: the 30-minute background default
3088
+ // (DEFAULT_BACKGROUND_DEADLINE_MS) applies instead. Recorded as
3089
+ // undefined, so a retry re-derives it rather than restoring the cap.
3090
+ params.timeout = undefined;
3091
+ log.info("Dispatch pre-flight: high-thinking foreground switched to background", {
3092
+ thinkingLevel: params.thinkingLevel,
3093
+ timeout: "dropped (background default applies)",
3094
+ });
3095
+ pi.sendMessage({
3096
+ customType: "delegate-notification",
3097
+ content: THINKING_SWITCH_NOTICE,
3098
+ display: true,
3099
+ details: { thinkingLevel: params.thinkingLevel, previousTimeout: "dropped" },
3100
+ }, { deliverAs: "followUp" });
3101
+ ctx.ui.notify(THINKING_SWITCH_NOTICE, "warning");
3102
+ } else if (thinkingSwitch === "drop-timeout") {
3103
+ // Issue #431 — the second arm: the shape cannot move (an effective
3104
+ // 'always'/'writes' run needs the interactive gate, and switching an
3105
+ // explicit-foreground 'always' dispatch would be REJECTED — #433), so
3106
+ // the only thing the pre-flight can remove is the deadline. Clearing it
3107
+ // HERE, before `snapshotOriginalParams` records the run (:3035
3108
+ // foreground, :2374 background), is what makes a retry re-derive an
3109
+ // absent deadline instead of restoring the cap (ADR 0009).
3110
+ const previousTimeout = params.timeout;
3111
+ params.timeout = undefined;
3112
+ log.info("Dispatch pre-flight: high-thinking foreground timeout dropped, shape kept", {
3113
+ thinkingLevel: params.thinkingLevel,
3114
+ previousTimeout,
3115
+ effectiveApprovalMode: effectiveApprovalModeForSwitch,
3116
+ });
3117
+ pi.sendMessage({
3118
+ customType: "delegate-notification",
3119
+ content: THINKING_TIMEOUT_DROP_NOTICE,
3120
+ display: true,
3121
+ details: {
3122
+ thinkingLevel: params.thinkingLevel,
3123
+ // The ACTUAL ms value, not "dropped": the friction log needs the
3124
+ // number to tell a budget cap from a tight clock.
3125
+ previousTimeout,
3126
+ effectiveApprovalMode: effectiveApprovalModeForSwitch,
3127
+ },
3128
+ }, { deliverAs: "followUp" });
3129
+ ctx.ui.notify(THINKING_TIMEOUT_DROP_NOTICE, "warning");
3130
+ } else if (thinkingSwitch === "forced") {
3131
+ // The override is recorded, not silent: the dispatch text is the reason
3132
+ // (`force` has no reason field — ADR 0007's contract stays unchanged).
3133
+ log.info("Dispatch pre-flight: high-thinking foreground forced", {
3134
+ thinkingLevel: params.thinkingLevel,
3135
+ timeout: params.timeout,
3136
+ });
3137
+ }
3138
+
3084
3139
  // background: true with chain/graph was silently ignored — the batch ran
3085
3140
  // foreground (blocking until every unit finished) while the caller believed
3086
3141
  // it was background. Both remain rejected loudly at dispatch validation;
@@ -3119,6 +3174,26 @@ export default function (pi: ExtensionAPI) {
3119
3174
  // unit retries as a single foreground run (issue #229), unaffected here.
3120
3175
  params.background ??= useBackground;
3121
3176
 
3177
+ // Issue #434: the unit projection's inputs, resolved ONCE here so no
3178
+ // unit site can re-derive them (a relative `params.cwd` re-read of the
3179
+ // manifest measured `false` where this resolution measured `true`).
3180
+ // `noticeEmitted` starts true when the DISPATCH arm announced its own
3181
+ // change: the drop still reaches every eligible unit, but the dispatch
3182
+ // already spoke, and a second notice would double-report one decision.
3183
+ // (`forced` emits nothing — the caller asked for the explicit pair, so
3184
+ // there is nothing to announce and no arm acted.)
3185
+ const batchGuard: BatchGuardContext = {
3186
+ processChecks,
3187
+ dispatchDeclaredLevel: effectiveDeclaredThinkingLevel as ThinkingLevel | undefined,
3188
+ force: params.force as boolean | undefined,
3189
+ // A `tasks` fan-out spawns detached background units (their deadline is
3190
+ // the legitimate budget); every other batch handler runs its units
3191
+ // foreground. Chain/graph can never be background: an explicit
3192
+ // `background: true` batch was rejected above.
3193
+ unitShape: isParallel && useBackground ? "background" : "foreground",
3194
+ noticeEmitted: thinkingSwitch === "switch" || thinkingSwitch === "drop-timeout",
3195
+ };
3196
+
3122
3197
  if (isChain) {
3123
3198
  if (params.chain!.length > MAX_CHAIN_STEPS) {
3124
3199
  return {
@@ -3132,7 +3207,7 @@ export default function (pi: ExtensionAPI) {
3132
3207
  isError: true,
3133
3208
  };
3134
3209
  }
3135
- return runChainMode(params, signal, onUpdate, ctx);
3210
+ return runChainMode(params, signal, onUpdate, ctx, batchGuard);
3136
3211
  }
3137
3212
 
3138
3213
  if (isParallel) {
@@ -3148,12 +3223,12 @@ export default function (pi: ExtensionAPI) {
3148
3223
  isError: true,
3149
3224
  };
3150
3225
  }
3151
- if (useBackground) return runBackgroundFanOut(pi, ctx, params, signal);
3152
- return runParallelMode(params, signal, onUpdate, ctx);
3226
+ if (useBackground) return runBackgroundFanOut(pi, ctx, params, signal, batchGuard);
3227
+ return runParallelMode(params, signal, onUpdate, ctx, batchGuard);
3153
3228
  }
3154
3229
 
3155
3230
  if (isGraph) {
3156
- return runGraphMode(params, signal, onUpdate, ctx);
3231
+ return runGraphMode(params, signal, onUpdate, ctx, batchGuard);
3157
3232
  }
3158
3233
 
3159
3234
  // Single mode: isSingle is true (modeCount===1, none of chain/parallel/graph),
@@ -3185,19 +3260,7 @@ export default function (pi: ExtensionAPI) {
3185
3260
  currentDepth,
3186
3261
  maxDepth: state.config.maxSubagentDepth,
3187
3262
  });
3188
- return {
3189
- content: [
3190
- {
3191
- type: "text" as const,
3192
- text:
3193
- `Cannot delegate further: subagent recursion depth limit reached ` +
3194
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
3195
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
3196
- },
3197
- ],
3198
- details: undefined,
3199
- isError: true,
3200
- };
3263
+ return depthLimitRejection(currentDepth, state.config.maxSubagentDepth);
3201
3264
  }
3202
3265
 
3203
3266
  const {
@@ -3264,6 +3327,8 @@ export default function (pi: ExtensionAPI) {
3264
3327
  gitMode: resolvedGitMode,
3265
3328
  outputFile: resolvedOutputFile,
3266
3329
  force: params.force,
3330
+ cwd: resolvedCwd,
3331
+ noJev: params.noJev,
3267
3332
  });
3268
3333
  if (validation.warnings.length > 0) {
3269
3334
  log.warn("Pre-task validation warnings", { warnings: validation.warnings });
@@ -3293,18 +3358,7 @@ export default function (pi: ExtensionAPI) {
3293
3358
  const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
3294
3359
  if (!modelStr || modelStr === "/") {
3295
3360
  log.warn("Model string is empty after resolution", { model: subagentModel });
3296
- return {
3297
- content: [
3298
- {
3299
- type: "text" as const,
3300
- text:
3301
- "Subagent model is not configured. " +
3302
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
3303
- },
3304
- ],
3305
- details: undefined,
3306
- isError: true,
3307
- };
3361
+ return modelNotConfiguredRejection();
3308
3362
  }
3309
3363
 
3310
3364
  // Create run record
@@ -3339,11 +3393,23 @@ export default function (pi: ExtensionAPI) {
3339
3393
  pruneHistoryIfNeeded(state, ctx, log);
3340
3394
 
3341
3395
  // Register for live monitor
3342
- registerLiveRun(state, run, ctx);
3396
+ // Issue #423: the merged timeout is the display deadline (absent → no
3397
+ // deadline; a foreground run has no 30m default).
3398
+ registerLiveRun(state, run, ctx, undefined, timeout);
3343
3399
 
3344
3400
  // P3: Git integration — set up work branch if gitMode is "branch"
3345
3401
  let headState: HeadState | undefined;
3346
3402
  let workBranchName: string | undefined;
3403
+ // Issue #466 (ADR 0026 D6): the foreground path creates the same work
3404
+ // branch with the same crash exposure, so it writes and clears the same
3405
+ // durable record — with `kind: "foreground"`, so "no record" means "no
3406
+ // orphan" for every branch run, not just background ones.
3407
+ let headStateRoot: string | undefined;
3408
+ const clearForegroundHeadState = (): void => {
3409
+ if (!headStateRoot) return;
3410
+ clearHeadState(headStateRoot);
3411
+ headStateRoot = undefined;
3412
+ };
3347
3413
  if (resolvedGitMode === "branch") {
3348
3414
  try {
3349
3415
  headState = getHeadState(resolvedCwd);
@@ -3354,9 +3420,27 @@ export default function (pi: ExtensionAPI) {
3354
3420
  });
3355
3421
  }
3356
3422
 
3357
- const branchResult = createWorkBranch(resolvedCwd, headState.sha);
3423
+ // Written BEFORE the branch exists (D1): the name must be minted here.
3424
+ headStateRoot = getRepoRoot(resolvedCwd) ?? resolvedCwd;
3425
+ workBranchName = newWorkBranchName();
3426
+ if (!writeHeadState({
3427
+ version: HEAD_STATE_VERSION,
3428
+ repoRoot: headStateRoot,
3429
+ runId: run.id,
3430
+ kind: "foreground",
3431
+ base: headState,
3432
+ workBranch: workBranchName,
3433
+ owner: currentProcessOwner(),
3434
+ createdAt: new Date().toISOString(),
3435
+ })) {
3436
+ log.warn("headState record could not be written — an interrupted run will name no base", {
3437
+ runId: run.id,
3438
+ workBranch: workBranchName,
3439
+ });
3440
+ }
3441
+
3442
+ const branchResult = createWorkBranch(resolvedCwd, headState.sha, workBranchName);
3358
3443
  if (branchResult.ok) {
3359
- workBranchName = branchResult.branch;
3360
3444
  log.info("Created work branch for subagent", {
3361
3445
  branch: workBranchName,
3362
3446
  base: headState.branch,
@@ -3365,12 +3449,16 @@ export default function (pi: ExtensionAPI) {
3365
3449
  log.error("Failed to create work branch, falling back to 'none'", {
3366
3450
  error: branchResult.error,
3367
3451
  });
3452
+ // Nothing was created: nothing to repair.
3453
+ clearForegroundHeadState();
3368
3454
  headState = undefined;
3455
+ workBranchName = undefined;
3369
3456
  }
3370
3457
  } catch (err) {
3371
3458
  log.warn("Not a git repository or git error; falling back to gitMode 'none'", {
3372
3459
  error: (err as Error).message,
3373
3460
  });
3461
+ clearForegroundHeadState();
3374
3462
  headState = undefined;
3375
3463
  workBranchName = undefined;
3376
3464
  }
@@ -3389,6 +3477,9 @@ export default function (pi: ExtensionAPI) {
3389
3477
  branch: headState.branch,
3390
3478
  detached: headState.detached,
3391
3479
  });
3480
+ // Issue #466: verified off the work branch — the record is done.
3481
+ // A FAILED restore keeps it: the base lives only in the record.
3482
+ clearForegroundHeadState();
3392
3483
  } else {
3393
3484
  log.warn("Failed to restore original HEAD during cleanup", {
3394
3485
  branch: headState.branch,
@@ -3553,6 +3644,12 @@ export default function (pi: ExtensionAPI) {
3553
3644
  result.errorMessage?.includes("timed out")
3554
3645
  ) {
3555
3646
  log.info("Auto-retrying after timeout", { runId });
3647
+ // Issue #423: the retry restarts the clock, so its display deadline is
3648
+ // re-anchored on it (the same clock `startedAt` carries). Registering
3649
+ // also clears the finalize claim, so the row is live again.
3650
+ const retryStartedAt = Date.now();
3651
+ const retryDeadlineAt =
3652
+ timeout && timeout > 0 ? retryStartedAt + timeout : undefined;
3556
3653
  state.registerLiveSubagent(runId, {
3557
3654
  id: runId,
3558
3655
  label,
@@ -3560,7 +3657,8 @@ export default function (pi: ExtensionAPI) {
3560
3657
  model: run.model,
3561
3658
  thinkingLevel,
3562
3659
  priority: params.priority,
3563
- startedAt: Date.now(),
3660
+ startedAt: retryStartedAt,
3661
+ ...(retryDeadlineAt !== undefined ? { deadlineAt: retryDeadlineAt } : {}),
3564
3662
  ctx,
3565
3663
  });
3566
3664
 
@@ -3621,6 +3719,9 @@ export default function (pi: ExtensionAPI) {
3621
3719
  branch: headState.branch,
3622
3720
  detached: headState.detached,
3623
3721
  });
3722
+ // Issue #466: the tree is verified off the work branch, so the
3723
+ // durable record has nothing left to repair.
3724
+ clearForegroundHeadState();
3624
3725
 
3625
3726
  // P4: Change approval workflow — let user review the diff
3626
3727
  const diffContent = (result.gitDiff ?? "").trim();
@@ -3724,7 +3825,7 @@ export default function (pi: ExtensionAPI) {
3724
3825
 
3725
3826
  // E4: SLA tracking — compute metrics if enabled
3726
3827
  if (state.config.slaTrackingEnabled) {
3727
- const recentRuns = state.getRunEntries(ctx).slice(0, state.config.slaWindowSize);
3828
+ const recentRuns = state.getLogicalRunEntries(ctx).slice(0, state.config.slaWindowSize);
3728
3829
  const metrics = computeSLAMetrics(recentRuns);
3729
3830
  log.info("SLA metrics computed", {
3730
3831
  totalRuns: metrics.totalRuns,
@@ -3850,19 +3951,7 @@ export default function (pi: ExtensionAPI) {
3850
3951
  },
3851
3952
 
3852
3953
  renderCall(
3853
- args: {
3854
- task?: string;
3855
- label?: string;
3856
- systemPrompt?: string;
3857
- inheritSystemPrompt?: boolean;
3858
- thinkingLevel?: string;
3859
- outputFile?: string;
3860
- timeout?: number;
3861
- cwd?: string;
3862
- tools?: string[];
3863
- excludeTools?: string[];
3864
- noBuiltinTools?: boolean;
3865
- },
3954
+ args: DelegateTaskParams,
3866
3955
  theme: Theme,
3867
3956
  _context: unknown,
3868
3957
  ) {
@@ -3889,6 +3978,8 @@ export default function (pi: ExtensionAPI) {
3889
3978
  description: [
3890
3979
  "Check the status of a background agent and retrieve its result.",
3891
3980
  "The conductor is woken with a completion message when the agent finishes; use this for post-wake retrieval, stall checks, and detail access — not for polling.",
3981
+ "Accepts a full agent id or a unique 8-character id prefix.",
3982
+ "When the id belongs to a retried run, the answer names the latest attempt; a finished run that was superseded also reports its successor.",
3892
3983
  "Returns the agent's status, result (if completed), and transcript path.",
3893
3984
  ].join(" "),
3894
3985
  parameters: Type.Object({
@@ -3902,14 +3993,64 @@ export default function (pi: ExtensionAPI) {
3902
3993
  ),
3903
3994
  }),
3904
3995
  execute: async (toolCallId, params) => {
3905
- const { getAgent } = await import('./session-manager');
3996
+ const { getAgent, resolveAgentId, findRetryLineage, isTerminalAgentStatus, RETRY_SCAN_WINDOW_MS, RETRY_SCAN_WINDOW_DAYS } = await import('./session-manager');
3906
3997
  const { getTranscript } = await import('./transcript');
3907
-
3908
- const agent = getAgent(params.agent_id);
3998
+
3999
+ // The notices render the first 8 hex characters of an id; resolve a
4000
+ // unique prefix before both the record read and the lineage lookup.
4001
+ // Ambiguity fails closed — a guess here could report the wrong run.
4002
+ const resolution = resolveAgentId(params.agent_id);
4003
+ if (resolution.kind === 'ambiguous') {
4004
+ return {
4005
+ content: [{
4006
+ type: "text" as const,
4007
+ text: `Agent id prefix "${params.agent_id}" is ambiguous — matches: ${resolution.matches.join(', ')}`,
4008
+ }],
4009
+ details: undefined,
4010
+ isError: true,
4011
+ };
4012
+ }
4013
+ // Anything that is not a full id or a matching 8-hex prefix keeps
4014
+ // today's message — there is no id to resolve against the stores.
4015
+ if (resolution.kind === 'unresolved') {
4016
+ return {
4017
+ content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
4018
+ details: undefined,
4019
+ isError: true,
4020
+ };
4021
+ }
4022
+ const agentId = resolution.id;
4023
+
4024
+ const agent = getAgent(agentId);
3909
4025
 
3910
4026
  if (!agent) {
4027
+ const lineage = findRetryLineage(agentId);
4028
+ if (lineage.latest && lineage.latest.id !== agentId) {
4029
+ const latest = lineage.latest;
4030
+ return {
4031
+ content: [{
4032
+ type: "text" as const,
4033
+ text: `Agent ${params.agent_id} not found — run ${params.agent_id} was retried as ${latest.id} (attempt ${latest.attempt}, ${latest.status}, started ${new Date(latest.startedAt).toISOString()}).`,
4034
+ }],
4035
+ details: undefined,
4036
+ isError: true,
4037
+ };
4038
+ }
4039
+
4040
+ const registryRun = lineage.inflight.find((run) => run.id === agentId);
4041
+ const registryStarted = registryRun
4042
+ ? (Number.isFinite(Date.parse(registryRun.startedAt))
4043
+ ? new Date(registryRun.startedAt).toISOString()
4044
+ : registryRun.startedAt)
4045
+ : undefined;
4046
+ const registryText = registryRun
4047
+ ? `no recent retry lineage recorded, but the registry still lists run ${registryRun.id} (attempt ${registryRun.attempt ?? 1}, started ${registryStarted}).`
4048
+ : `no recent retry lineage recorded (scanned the last ${RETRY_SCAN_WINDOW_DAYS} days), and no registry record either.`;
3911
4049
  return {
3912
- content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
4050
+ content: [{
4051
+ type: "text" as const,
4052
+ text: `Agent ${params.agent_id} not found — ${registryText}`,
4053
+ }],
3913
4054
  details: undefined,
3914
4055
  isError: true,
3915
4056
  };
@@ -3923,10 +4064,37 @@ export default function (pi: ExtensionAPI) {
3923
4064
  resultText += `Completed: ${new Date(agent.completedAt).toISOString()}\n`;
3924
4065
  resultText += `Duration: ${agent.completedAt - agent.startedAt}ms\n`;
3925
4066
  }
4067
+
4068
+ // Issue #423: the budget the run actually ran under — from the PERSISTED
4069
+ // record, so it survives the closure that armed the timer. The result
4070
+ // path has no run entry to consult, so the timeout evidence is the
4071
+ // agent's own error stamp (one shared predicate owns both paths).
4072
+ const budgetLine = formatBudgetLine(
4073
+ agent,
4074
+ normalizeCompletionStatus(agent.status),
4075
+ undefined,
4076
+ );
4077
+ if (budgetLine) resultText += `${budgetLine}\n`;
3926
4078
 
3927
4079
  if (agent.error) {
3928
4080
  resultText += `Error: ${agent.error}\n`;
3929
4081
  }
4082
+
4083
+ // A terminal source can be the WRONG run to act on: the retry that
4084
+ // actually finished is a later attempt of the same dispatch. Name it
4085
+ // so a terminal status is not read as the final word.
4086
+ if (isTerminalAgentStatus(agent.status)) {
4087
+ const lineage = findRetryLineage(agentId, agent);
4088
+ if (lineage.latest && lineage.latest.id !== agentId) {
4089
+ const latest = lineage.latest;
4090
+ resultText += `Superseded by ${latest.id} (attempt ${latest.attempt}, ${latest.status}, started ${new Date(latest.startedAt).toISOString()})\n`;
4091
+ } else if (agent.startedAt < Date.now() - RETRY_SCAN_WINDOW_MS) {
4092
+ // The lineage scan is windowed: an older run cannot be shown a
4093
+ // later attempt that fell outside it. Say so instead of implying
4094
+ // there is none.
4095
+ resultText += `Retry lineage not checked: this run started more than ${RETRY_SCAN_WINDOW_DAYS} days ago.\n`;
4096
+ }
4097
+ }
3930
4098
 
3931
4099
  if (agent.result) {
3932
4100
  resultText += `\nResult:\n`;
@@ -3953,7 +4121,7 @@ export default function (pi: ExtensionAPI) {
3953
4121
 
3954
4122
  // Include transcript if verbose
3955
4123
  if (params.verbose) {
3956
- const transcript = getTranscript(params.agent_id);
4124
+ const transcript = getTranscript(agentId);
3957
4125
  if (transcript.length > 0) {
3958
4126
  resultText += `\n\nTranscript (${transcript.length} entries):\n`;
3959
4127
  for (const entry of transcript.slice(-10)) { // Last 10 entries
@@ -3963,7 +4131,7 @@ export default function (pi: ExtensionAPI) {
3963
4131
  }
3964
4132
 
3965
4133
  // Include transcript path
3966
- resultText += `\nTranscript: ${transcriptDisplayPath(params.agent_id)}`;
4134
+ resultText += `\nTranscript: ${transcriptDisplayPath(agentId)}`;
3967
4135
 
3968
4136
  return {
3969
4137
  content: [{ type: "text" as const, text: resultText }],
@@ -4115,18 +4283,96 @@ export default function (pi: ExtensionAPI) {
4115
4283
  if (record.kind === "agent") markAgentInterrupted(record.id, interruptedAt);
4116
4284
  return durable;
4117
4285
  },
4286
+ // Issue #447: a dispatch whose acceptance marker is still `null` never
4287
+ // reached `session.prompt()`. It is finalized `failed` here — a
4288
+ // terminal write, so `persistRunRecord` retires the registry entry in
4289
+ // the same call and no interrupted/retry surface can pick it up.
4290
+ finalizeNeverStarted: (run) => {
4291
+ state.persistRun(pi, run);
4292
+ },
4118
4293
  });
4119
4294
  // Report the scan whenever it did anything durable OR attempted a mark
4120
4295
  // that failed — a failure-only boot must not be silent (issue #304).
4121
4296
  if (summary.marked > 0 || summary.markFailures > 0) {
4122
4297
  log.warn("Boot recovery marked interrupted runs", { ...summary });
4123
4298
  }
4299
+ // Issue #447: never-started dispatches are finalized, not marked — a
4300
+ // separate line so the two outcomes cannot be read as one another.
4301
+ if (summary.neverStarted > 0) {
4302
+ log.info("Boot recovery finalized never-started dispatches", {
4303
+ count: summary.neverStarted,
4304
+ });
4305
+ }
4124
4306
  } catch (err) {
4125
4307
  // Recovery is best-effort hygiene — it must never break session start.
4126
4308
  log.warn("Boot recovery scan failed", { error: (err as Error).message });
4127
4309
  }
4128
4310
  }
4129
4311
 
4312
+ /**
4313
+ * Issue #466 (ADR 0026 D2): the git/process surface the head-state table
4314
+ * reads, wired once so the boot step and its tests cannot drift apart.
4315
+ */
4316
+ function headStateDeps(): HeadStateDeps {
4317
+ const procDeps = defaultRecoveryDeps();
4318
+ return {
4319
+ getRepoRoot,
4320
+ classifyOwner: (owner) => classifyOwner(owner, procDeps),
4321
+ getHeadBranch,
4322
+ restoreHead,
4323
+ hasUncommittedChanges,
4324
+ listWorkBranches,
4325
+ };
4326
+ }
4327
+
4328
+ /**
4329
+ * Issue #466: the boot's ONE git-mutating step, between the scan (which only
4330
+ * marks records) and the notices. Best-effort like the scan — a failing store
4331
+ * must never break session start — but every record still ends in exactly one
4332
+ * LOGGED verdict (D5: silence is not a verdict).
4333
+ *
4334
+ * The repair itself is NEVER gated by `config.recovery`: a tree left on a dead
4335
+ * run's branch is a correctness problem, not a recovery offer. Only the notice
4336
+ * below is gated.
4337
+ */
4338
+ function reconcileHeadStatesAtBoot(): HeadStateOutcome[] {
4339
+ try {
4340
+ const outcomes = reconcileHeadStates(headStateDeps());
4341
+ for (const outcome of outcomes) {
4342
+ log.info("Boot head-state verdict", { ...outcome });
4343
+ }
4344
+ // Housekeeping, never part of the repair contract: only a record whose
4345
+ // repository no longer resolves (or that cannot be parsed) is swept, so
4346
+ // a live orphan's base is never deleted by age.
4347
+ const swept = sweepHeadStates({
4348
+ repoGone: (record) => getRepoRoot(record.repoRoot) === undefined,
4349
+ });
4350
+ if (swept > 0) log.info("Swept stale head-state records", { count: swept });
4351
+ return outcomes;
4352
+ } catch (err) {
4353
+ log.warn("Boot head-state reconciliation failed", { error: (err as Error).message });
4354
+ return [];
4355
+ }
4356
+ }
4357
+
4358
+ /**
4359
+ * Issue #466 (D5): the repair and the needs-manual verdict reach the user
4360
+ * once, on the same `nextTurn` channel as the recovery notice, and are gated
4361
+ * by `config.recovery !== "off"` like every other boot surface.
4362
+ */
4363
+ function maybeSendHeadStateNotice(outcomes: HeadStateOutcome[]): void {
4364
+ if (state.config.recovery === "off") return;
4365
+ const notice = buildHeadStateNotice(outcomes);
4366
+ if (!notice) return;
4367
+ try {
4368
+ pi.sendMessage(notice, resolveRecoveryNoticeDelivery());
4369
+ log.info("Head-state notice delivered", { count: notice.details.count });
4370
+ } catch (err) {
4371
+ // The notice is best-effort — it must never break session start.
4372
+ log.warn("Head-state notice failed", { error: (err as Error).message });
4373
+ }
4374
+ }
4375
+
4130
4376
  /**
4131
4377
  * Option B U3 Fix A: the recovery visibility bridge, wired for the two
4132
4378
  * extension consumers that resolve a run id (the retryRunId branch and the
@@ -4140,7 +4386,7 @@ export default function (pi: ExtensionAPI) {
4140
4386
  ctx: ExtensionContext,
4141
4387
  getAgent: RecoveryAgentLookup,
4142
4388
  ): SubagentRun[] {
4143
- return visibleRunEntriesForSession(state.getRunEntries(ctx), getAgent);
4389
+ return visibleRunEntriesForSession(state.getLogicalRunEntries(ctx), getAgent);
4144
4390
  }
4145
4391
 
4146
4392
  /**
@@ -4258,10 +4504,18 @@ export default function (pi: ExtensionAPI) {
4258
4504
  // records interrupted BEFORE anything else touches their worktrees.
4259
4505
  await performBootRecovery();
4260
4506
 
4507
+ // Issue #466 (ADR 0026 D2/D5): reconcile the durable head-state records —
4508
+ // the ONE step allowed to move git at boot, and only for a record whose
4509
+ // owner it has proved dead.
4510
+ const headStateOutcomes = reconcileHeadStatesAtBoot();
4511
+
4261
4512
  // Option B U3 (D2): after the scan, surface every unresolved interrupted
4262
4513
  // run ONCE, at the next turn boundary (never mid-turn).
4263
4514
  await maybeSendRecoveryNotice(ctx);
4264
4515
 
4516
+ // Issue #466: the head-state verdicts ride the same nextTurn channel.
4517
+ maybeSendHeadStateNotice(headStateOutcomes);
4518
+
4265
4519
  // Issue #356: boot is a config-paint edge — route it through the same
4266
4520
  // chokepoint as every other footer repaint. With no runs in flight the
4267
4521
  // chokepoint draws the idle config line the old direct call painted.
@@ -4270,6 +4524,17 @@ export default function (pi: ExtensionAPI) {
4270
4524
 
4271
4525
  // F7: Clean up session-bound state on shutdown
4272
4526
  pi.on("session_shutdown", async (_event, _ctx) => {
4527
+ // Issue #437: release THIS runtime's terminal subscribers FIRST — before
4528
+ // any await or fallible cleanup. A clean replacement (/new, /resume,
4529
+ // /fork, /reload, quit) tears this runtime down and loads a new factory
4530
+ // instance; the old listeners used to survive and win the shared terminal
4531
+ // claim for the NEW session's run, delivering (or throwing) through dead
4532
+ // pi/ctx handles. Only our three exact identities are removed, and the
4533
+ // release is idempotent, so other subscribers and a later runtime are
4534
+ // untouched. `releaseTerminalSubscriptions` is a hoisted declaration
4535
+ // below (the subscription block is registered after this handler).
4536
+ releaseTerminalSubscriptions();
4537
+
4273
4538
  log.info("Session shutting down", {
4274
4539
  activeSubagents: state.activeSubagents,
4275
4540
  });
@@ -4307,10 +4572,118 @@ export default function (pi: ExtensionAPI) {
4307
4572
  // the point; details are best-effort — the notification must never throw or
4308
4573
  // block on their absence.
4309
4574
  const terminalTypes = ["subagent:completed", "subagent:failed", "subagent:stopped"] as const;
4575
+
4576
+ // Issue #437: keep the EXACT listener references this factory instance owns.
4577
+ // Anonymous subscriptions could never be released, so a shut-down runtime's
4578
+ // listeners stayed on the shared bus forever. Ownership is per factory
4579
+ // invocation: the array and the released flag are this runtime's alone, so a
4580
+ // replacement's listeners are never in the removal set.
4581
+ const terminalSubscriptions: Array<{
4582
+ type: (typeof terminalTypes)[number];
4583
+ listener: SubagentEventListener;
4584
+ }> = [];
4585
+ let terminalSubscriptionsReleased = false;
4586
+
4587
+ /**
4588
+ * Issue #437: unsubscribe exactly the listeners registered above.
4589
+ *
4590
+ * Idempotent — a repeated/double `session_shutdown` (or a late one after the
4591
+ * replacement runtime is already live) is a no-op. Synchronous, so it can run
4592
+ * as the first statement of `session_shutdown`, before any await or fallible
4593
+ * cleanup. Never touches another subscriber or another runtime's listeners.
4594
+ */
4595
+ function releaseTerminalSubscriptions(): void {
4596
+ if (terminalSubscriptionsReleased) return;
4597
+ terminalSubscriptionsReleased = true;
4598
+ for (const { type, listener } of terminalSubscriptions) {
4599
+ eventBus.off(type, listener);
4600
+ }
4601
+ terminalSubscriptions.length = 0;
4602
+ }
4603
+
4310
4604
  for (const type of terminalTypes) {
4311
- eventBus.on(type, (event) => {
4605
+ const listener: SubagentEventListener = (event) => {
4312
4606
  void deliverCompletionAlert(event);
4607
+ };
4608
+ terminalSubscriptions.push({ type, listener });
4609
+ eventBus.on(type, listener);
4610
+ }
4611
+
4612
+ /**
4613
+ * Issue #365: re-dispatch a background run that settled with a transport-class
4614
+ * failure, using the `retryRunId` machinery. `resolveRetryParams({}, run)`
4615
+ * restores the recorded params and `spawnBackgroundRun(..., run)` mints the
4616
+ * lineage (`resumeOf` + `attempt: 2`), so the retry re-runs the normal gates
4617
+ * (cost, approval, pre-task) and is visible in the record.
4618
+ *
4619
+ * Issue #401/#411: the retry carries a resume preamble (`attemptContext`) that
4620
+ * is injected into the child's system prompt only (as a `<resume-context>`
4621
+ * section), never inside the `<task>` fence. The task handed to
4622
+ * `resolveSubagentParams` stays the recorded original, so auto-routing, H1
4623
+ * keyword warnings and the capability checks behave exactly as they did on
4624
+ * attempt 1.
4625
+ *
4626
+ * Returns TRUE when the retry was actually spawned — the caller then SUPPRESSES
4627
+ * the source run's completion notice, because the retry's own terminal settle
4628
+ * is the wake. A gate rejection or a throwing spawn returns FALSE and the
4629
+ * caller reports the original failure exactly as before (no silent drop).
4630
+ *
4631
+ * Issue #439: this reads only `isError`, and a retry whose post-spawn tail
4632
+ * faulted is still a SUCCESSFUL spawn (`isError: false`, degraded monitoring).
4633
+ * It therefore returns TRUE for it: the source notice stays suppressed and the
4634
+ * degraded advisory is the signal that the retry started with degraded
4635
+ * monitoring. Reading a contained tail failure as "did not start" would
4636
+ * surface the source failure for a run that is live.
4637
+ */
4638
+ async function scheduleTransportRetry(
4639
+ ctx: ExtensionContext,
4640
+ run: SubagentRun,
4641
+ ): Promise<boolean> {
4642
+ const sourceAttempt = run.attempt ?? 1;
4643
+ try {
4644
+ const retryParams = resolveRetryParams({}, run);
4645
+ // Issue #404: point at the retained session ONLY when it is really
4646
+ // there. Resolve this conductor-side: the child may run in another cwd.
4647
+ // An invalid id cannot have a session dir (and `backgroundSessionDir`
4648
+ // throws on one) — no pointer, no throw.
4649
+ let retainedSessionDir: string | undefined;
4650
+ try {
4651
+ const { retainedSessionPointer } = await import('./session-manager');
4652
+ const candidate = retainedSessionPointer(run.id);
4653
+ if (fs.existsSync(candidate)) retainedSessionDir = candidate;
4654
+ } catch {
4655
+ retainedSessionDir = undefined;
4656
+ }
4657
+ const result = await spawnBackgroundRun(
4658
+ pi,
4659
+ ctx,
4660
+ retryParams,
4661
+ retryParams.task!,
4662
+ run,
4663
+ buildRetryResumePreamble(run, sourceAttempt + 1, retainedSessionDir),
4664
+ );
4665
+ if (result.isError) {
4666
+ log.warn("Transport auto-retry spawn rejected — surfacing the original failure", {
4667
+ sourceId: run.id,
4668
+ attempt: sourceAttempt,
4669
+ error: result.content[0]?.type === "text" ? result.content[0].text : undefined,
4670
+ });
4671
+ return false;
4672
+ }
4673
+ } catch (err) {
4674
+ log.warn("Transport auto-retry spawn failed — surfacing the original failure", {
4675
+ sourceId: run.id,
4676
+ attempt: sourceAttempt,
4677
+ error: (err as Error).message,
4678
+ });
4679
+ return false;
4680
+ }
4681
+ log.info("Background run settled — transport auto-retry scheduled", {
4682
+ sourceId: run.id,
4683
+ attempt: sourceAttempt + 1,
4313
4684
  });
4685
+ ctx.ui.notify(TRANSPORT_RETRY_TOAST, "warning");
4686
+ return true;
4314
4687
  }
4315
4688
 
4316
4689
  async function deliverCompletionAlert(event: SubagentEvent): Promise<void> {
@@ -4323,7 +4696,15 @@ export default function (pi: ExtensionAPI) {
4323
4696
  const agent = getAgent(id);
4324
4697
  if (!agent) return; // pruned or foreign id — nothing to notify
4325
4698
  const knob = state.config.completionNotify ?? "all";
4326
- const run = resolveRunEntry(state.getRunEntries(ctx), id);
4699
+ const run = resolveRunEntry(state.getLogicalRunEntries(ctx), id);
4700
+ // Issue #365: a transport-class background failure is re-dispatched once
4701
+ // and the source notice is suppressed (the retry's settle is the wake).
4702
+ // Every other terminal type — and every non-retryable failure — keeps the
4703
+ // existing path unchanged.
4704
+ if (event.type === "subagent:failed" && run && isTransportRetryable(run)) {
4705
+ const retried = await scheduleTransportRetry(ctx, run);
4706
+ if (retried) return;
4707
+ }
4327
4708
  const message = buildCompletionMessage(agent, run);
4328
4709
  // Issue #179 (D2): resolve delivery from the CLASSIFIED notification
4329
4710
  // status, not the raw agent status — otherwise a run whose completion