brl-subagent 2.6.0 → 2.7.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,
@@ -54,6 +55,7 @@ import {
54
55
  type RecoveryMode,
55
56
  } from "./types";
56
57
  import { validateGraph, topologicalSort } from "./scheduler";
58
+ import { runModePrologue } from "./mode-prologue";
57
59
  import { resolveTemplate, loadAllTemplates, loadBuiltinTemplates, validateTemplatePresetRefs, extractParamNames } from "./templates";
58
60
  import { pkgPath } from "./paths";
59
61
 
@@ -69,21 +71,26 @@ import {
69
71
  type HeadState,
70
72
  } from "./git";
71
73
  import { preflightCheck } from "./preflight";
72
- import { gateSessionCost, rejectApprovalAlwaysInBackground, runPreTaskValidation, validateDelegationTargets, formatValidationWarnings } from "./prelude";
74
+ import { depthLimitRejection, formatValidationWarnings, gateSessionCost, modelNotConfiguredRejection, rejectApprovalAlwaysInBackground, rejection, resolveModeModel, resolveSubagentModelPrecedence, runPreTaskValidation, validateDelegationTargets, validateUnitPrePass, type SubagentModelResolution } from "./prelude";
73
75
  import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile, formatPresetRestriction, formatToolRestriction } from "./presets";
74
- import { modelIsAvailable } from "./model-availability";
76
+ import { modelIsAvailable, parseModelString } from "./model-availability";
75
77
  import { validatePreTask, diagnoseFailure, DEFAULT_BACKGROUND_DEADLINE_MS } from "./validate";
76
78
  import {
77
79
  defaultBackgroundFor,
78
80
  findUnknownParams,
79
81
  KNOWN_DELEGATE_KEYS,
82
+ resolveDispatchPreset,
80
83
  resolveEffectiveApprovalMode,
81
84
  resolveSubagentParams,
85
+ resolveThinkingDispatchSwitch,
82
86
  shouldRejectBackgroundForBatch,
83
87
  snapshotOriginalParams,
88
+ THINKING_SWITCH_NOTICE,
84
89
  type DispatchShape,
90
+ type ResolveInputParams,
85
91
  } from "./params";
86
92
  import { delegateTaskParamsSchema } from "./schema";
93
+ import { readProcessChecks } from "./project-flags";
87
94
  import { createSessionState, resolveTerminalRunEntry, type SessionState } from "./state";
88
95
  import { makeLiveOnUpdate, createUnitRun, finalizeUnitRun, finalizeUnitRunCrash, pruneHistoryIfNeeded, registerLiveRun } from "./unit-run";
89
96
  import { buildSubagentPrompt, describePromptMode } from "./prompt";
@@ -146,6 +153,7 @@ import {
146
153
  claimTerminalNotice,
147
154
  resolveRunEntry,
148
155
  } from "./notify-completion";
156
+ import { isTransportRetryable, TRANSPORT_RETRY_TOAST } from "./transport-retry";
149
157
 
150
158
  // ---------------------------------------------------------------------------
151
159
  // Helpers
@@ -219,6 +227,53 @@ export function cleanupSessionState(state: SessionState): void {
219
227
  state.pendingQueue.length = 0;
220
228
  }
221
229
 
230
+ /**
231
+ * Issue #401/#411: the resume preamble a transport auto-retry builds and delivers
232
+ * as a `<resume-context>` section on the child's system prompt — never inside
233
+ * the `<task>` fence. A dropped connection costs the child its context, not its
234
+ * files: the retry spawns into the same directory, so the work it already did
235
+ * (commits, written files, a bank) is still there. The preamble turns a blind
236
+ * replay into a resume by naming what to inspect first.
237
+ *
238
+ * Kept bounded (5 lines max) and deliberately vetted for runtime vocabulary —
239
+ * it is prompt text a user can see in the child's system prompt.
240
+ *
241
+ * Issue #404: it also names the retained SDK session directory when one exists.
242
+ * That is the only artifact that holds attempt 1's CONVERSATION — the output log
243
+ * is a start/steering stub — and the settle path retains it for exactly this
244
+ * class of run. The pointer is absolute and computed conductor-side at build
245
+ * time: the retry's child can run in a different cwd (worktree/branch mode), so
246
+ * a relative path would point at the wrong tree. The exists gate is deliberate:
247
+ * an attempt whose session was not retained (size floor, marker failure, a
248
+ * legacy run) gets the bank-only preamble, never a dead path.
249
+ */
250
+ function buildRetryResumePreamble(
251
+ run: SubagentRun,
252
+ nextAttempt: number,
253
+ retainedSessionDir?: string,
254
+ ): string {
255
+ const sanitize = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "-");
256
+ const label = sanitize(run.label ?? "");
257
+ // A label made only of separators ("---") is not a filename; fall back to the
258
+ // (UUID-shaped, hence already safe) id.
259
+ const bankLabel = /[A-Za-z0-9]/.test(label) ? label : sanitize(run.id);
260
+ const lines = [
261
+ `[attempt ${nextAttempt} — the previous attempt (${run.id}) died on a transport failure.`,
262
+ "This directory may already contain its uncommitted edits.",
263
+ `Before acting, inspect: \`git status --short\`, \`git log --oneline -8\`, and the progress bank at /tmp/brl-${bankLabel}-bank.md if it exists.`,
264
+ "Continue from what exists; do NOT redo committed, written, or banked work.]",
265
+ ];
266
+ if (retainedSessionDir) {
267
+ // Insert before the closing line so the block still reads as one unit.
268
+ lines.splice(
269
+ lines.length - 1,
270
+ 0,
271
+ `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.`,
272
+ );
273
+ }
274
+ return lines.join("\n");
275
+ }
276
+
222
277
  // ---------------------------------------------------------------------------
223
278
  // Extension entry point
224
279
  // ---------------------------------------------------------------------------
@@ -234,6 +289,87 @@ type _KnownDelegateKey = (typeof KNOWN_DELEGATE_KEYS extends Set<infer K> ? K :
234
289
  type _ExpectNever<T extends never> = T;
235
290
  type _DelegateParamCoverage = _ExpectNever<Exclude<_KnownDelegateKey, keyof DelegateTaskParams>>;
236
291
 
292
+ /**
293
+ * Issue #379: `ResolveInputParams` derives from the schema via `Pick`, so a
294
+ * params field ADDED to the schema is not in the resolver's input until the
295
+ * key list names it — and a missed field is invisible at runtime (the key
296
+ * reaches execute and is silently unused). Only the compiler can catch it.
297
+ *
298
+ * The excluded keys are the ones resolution deliberately does not read: the
299
+ * execution-shape inputs (`chain`/`tasks`/`graph`), the template machinery
300
+ * (`template` is the exception — it IS read, so it stays in the resolver;
301
+ * `params` is not), the retry inputs, and the per-dispatch fields
302
+ * (`model`/`priority`/`background`) that resolve outside this merge.
303
+ */
304
+ type _NonResolutionDelegateKey =
305
+ | "chain"
306
+ | "tasks"
307
+ | "graph"
308
+ | "params"
309
+ | "retryRunId"
310
+ | "retryOnTimeout"
311
+ | "model"
312
+ | "priority"
313
+ | "background"
314
+ // Issue #412: `force`/`noJev` are consumed at the validation seam (they
315
+ // reach `validatePreTask`, not the merge), so `force` stays in the resolver's
316
+ // key list while `noJev` — never read by resolution — is excluded here.
317
+ | "noJev";
318
+ type _ResolveInputCoverage = _ExpectNever<
319
+ Exclude<_KnownDelegateKey, keyof ResolveInputParams | _NonResolutionDelegateKey>
320
+ >;
321
+
322
+ /**
323
+ * Issue #381 (audit D4): the one graph-node → SubTaskParams mapping, shared by
324
+ * the graph pre-pass and the per-wave dispatch. GraphTask is a structural
325
+ * superset of SubTaskParams, so the node-only scheduling fields are dropped by
326
+ * destructuring instead of re-listing every per-subtask field — a field added
327
+ * to either type can no longer be silently forgotten at one of the two sites.
328
+ */
329
+ function graphTaskToSubTaskParams(node: GraphTask): SubTaskParams {
330
+ const { id: _id, dependsOn: _dependsOn, ...subTask } = node;
331
+ return subTask;
332
+ }
333
+
334
+ /**
335
+ * Issue #376 (audit D3): the one `SubagentResult` → `SubTaskResult` field
336
+ * mapping, shared by every dispatch mode (chain, parallel, graph). The ten
337
+ * assignments plus the error classification were copied per mode, so a field
338
+ * added to `SubTaskResult` could be silently forgotten at one of the sites —
339
+ * and `errorCategory` could be passed through unclassified. Callers add their
340
+ * own mode-specific fields (`step`/`task`/`label`) around this mapping.
341
+ */
342
+ function toSubTaskResult(
343
+ result: SubagentResult,
344
+ ): Pick<
345
+ SubTaskResult,
346
+ | "exitCode"
347
+ | "messages"
348
+ | "stderr"
349
+ | "usage"
350
+ | "model"
351
+ | "stopReason"
352
+ | "errorMessage"
353
+ | "errorCategory"
354
+ | "gitBranch"
355
+ | "gitDiff"
356
+ > {
357
+ return {
358
+ exitCode: result.exitCode,
359
+ messages: result.messages,
360
+ stderr: result.stderr,
361
+ usage: result.usage,
362
+ model: result.model,
363
+ stopReason: result.stopReason,
364
+ errorMessage: result.errorMessage,
365
+ // The classification path is part of the mapping: every mode derives the
366
+ // category from the raw result, never from the runner's own field.
367
+ errorCategory: classifyError(result),
368
+ gitBranch: result.gitBranch,
369
+ gitDiff: result.gitDiff,
370
+ };
371
+ }
372
+
237
373
  export default function (pi: ExtensionAPI) {
238
374
  const log = createLogger("brl-subagent");
239
375
 
@@ -288,73 +424,16 @@ export default function (pi: ExtensionAPI) {
288
424
  // Parameter resolution (extracted to src/params.ts — issue #59)
289
425
  // -------------------------------------------------------------------
290
426
 
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
-
427
+ // The model-precedence chain lives in prelude.ts (issue #379) so the batch
428
+ // modes' tail (`resolveModeModel`) and these single/background paths resolve
429
+ // identically; this wrapper keeps their call shape (context + preset +
430
+ // per-call override) unchanged.
299
431
  function resolveSubagentModel(
300
432
  ctx: ExtensionContext,
301
433
  preset: SubagentPreset | undefined,
302
434
  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 };
435
+ ): SubagentModelResolution {
436
+ return resolveSubagentModelPrecedence({ state, ctx, log, preset, perCallModel });
358
437
  }
359
438
 
360
439
  // C3: Resolve a step's model override (step.model > global resolved model).
@@ -475,115 +554,22 @@ export default function (pi: ExtensionAPI) {
475
554
  // startedAt (captured once, at mode entry, not at completion).
476
555
  const chainModeStartedAt = new Date().toISOString();
477
556
 
478
- // R5: Check session cost limit before spawning
479
- const costError = gateSessionCost({
557
+ // Mode prologue (issue #379): cost → depth → resolve → targets →
558
+ // preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
559
+ // Chain's per-mode inputs are only the label and the unit count; H1 here
560
+ // validates the MODE-level params (top-level tasks are empty, so only the
561
+ // hard outputFile-vs-write conflict applies), while every step's own
562
+ // cwd/outputFile/tools belong to the per-step pass below (issue #222).
563
+ const pro = runModePrologue({
564
+ params,
480
565
  state,
481
566
  ctx,
482
567
  log,
568
+ label: "Chain",
483
569
  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
570
  });
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
- }
571
+ if (!pro.ok) return pro.error;
572
+ const { globalParams, resolvedCwd, currentDepth } = pro;
587
573
 
588
574
  // Per-step pre-pass (issue #222): resolve + validate EVERY step before
589
575
  // any spawn, so a single bad step rejects the chain with nothing
@@ -593,72 +579,38 @@ export default function (pi: ExtensionAPI) {
593
579
  // step's output (only its TASK text consumes {previous}), so the pass
594
580
  // can run up front — and must, because discovering step 5's bad cwd
595
581
  // 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,
582
+ const stepPass = validateUnitPrePass({
583
+ units: chainSteps,
584
+ label: "Chain",
585
+ gitMode: globalParams.resolvedGitMode,
586
+ ctx,
587
+ log,
588
+ force: params.force as boolean | undefined,
589
+ noJev: params.noJev,
590
+ merge: (step) => mergeSubTaskParams(globalParams, step),
591
+ describe: (_step, merged, i) => ({
592
+ prefix: `Step ${i + 1} ("${displayTaskName(merged)}")`,
615
593
  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
- }
594
+ }),
595
+ });
596
+ if (!stepPass.ok) return stepPass.error;
597
+ const stepCwds = stepPass.units.map((u) => u.cwd);
598
+ const stepWarnings = stepPass.warnings;
599
+
600
+ // Mode tail (issue #379): resolve the model (preset + per-call override,
601
+ // auto-route included in `resolvedPreset`), reject an empty resolution,
602
+ // then the circuit breaker. It runs AFTER the per-step pass — IN8 keeps
603
+ // a bad step's rejection ahead of an unconfigured model.
604
+ const tail = resolveModeModel({
605
+ state,
606
+ ctx,
607
+ log,
608
+ preset: globalParams.resolvedPreset,
609
+ perCallModel: params.model,
610
+ });
611
+ if (!tail.ok) return tail.error;
612
+ const subagentModel = tail.model;
613
+ const modelStr = tail.modelStr;
662
614
 
663
615
  // Resolve priority (issue #114: no config knob — the call-level default)
664
616
  const chainPriority: Priority = (
@@ -825,17 +777,8 @@ export default function (pi: ExtensionAPI) {
825
777
  // shape finalizeRunRecord expects, errorCategory included).
826
778
  finalizeUnitRun(state, pi, ctx, run, result, log);
827
779
 
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;
780
+ // Fill SubTaskResult (one shared field mapping — issue #376/D3).
781
+ Object.assign(subTaskResult, toSubTaskResult(result));
839
782
 
840
783
  chainResults.push(subTaskResult);
841
784
 
@@ -998,101 +941,22 @@ export default function (pi: ExtensionAPI) {
998
941
  ): Promise<ToolResult<SubagentResult | ParallelDetails | undefined>> {
999
942
  const taskList: SubTaskParams[] = params.tasks!;
1000
943
 
1001
- // R5: Check session cost limit before spawning
1002
- const costError = gateSessionCost({
944
+ // Mode prologue (issue #379): cost → depth → resolve → targets →
945
+ // preflight → H1, the sequence every batch mode shares (mode-prologue.ts).
946
+ // Parallel's per-mode inputs are only the label and the unit count; H1
947
+ // validates the MODE-level params (top-level tasks are empty, so only the
948
+ // hard outputFile-vs-write conflict applies — issue #34), while every
949
+ // task's own cwd/outputFile/tools belong to the per-task pass below.
950
+ const pro = runModePrologue({
951
+ params,
1003
952
  state,
1004
953
  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
- },
1050
- state,
1051
- ctx,
1052
- 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
954
  log,
1086
955
  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
- },
956
+ units: taskList.length,
1094
957
  });
1095
- if (preTask.error) return preTask.error;
958
+ if (!pro.ok) return pro.error;
959
+ const { globalParams, resolvedCwd, currentDepth } = pro;
1096
960
 
1097
961
  // Per-task pre-pass (issue #220, extended by #222): validate EVERY task
1098
962
  // before any spawn, so a single bad task rejects the batch with nothing
@@ -1104,73 +968,38 @@ export default function (pi: ExtensionAPI) {
1104
968
  // mode-level cwd. Per-task warnings are prefixed with their unit and
1105
969
  // collected here to ride the final result. The mode-entry validation
1106
970
  // 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,
971
+ const taskPass = validateUnitPrePass({
972
+ units: taskList,
973
+ label: "Parallel",
974
+ gitMode: globalParams.resolvedGitMode,
975
+ ctx,
976
+ log,
977
+ force: params.force as boolean | undefined,
978
+ noJev: params.noJev,
979
+ merge: (task) => mergeSubTaskParams(globalParams, task),
980
+ describe: (_task, merged, i) => ({
981
+ prefix: `Task ${i + 1} ("${displayTaskName(merged)}")`,
1127
982
  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
- }
983
+ }),
984
+ });
985
+ if (!taskPass.ok) return taskPass.error;
986
+ // Parallel index → the task's own validated cwd (issue #222).
987
+ const taskCwds = taskPass.units.map((u) => u.cwd);
988
+ const taskWarnings = taskPass.warnings;
1162
989
 
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
- }
990
+ // Mode tail (issue #379): model resolution (preset + per-call override,
991
+ // auto-route included in `resolvedPreset`), the empty-model rejection and
992
+ // the circuit check. Runs AFTER the per-task pass (IN8).
993
+ const tail = resolveModeModel({
994
+ state,
995
+ ctx,
996
+ log,
997
+ preset: globalParams.resolvedPreset,
998
+ perCallModel: params.model,
999
+ });
1000
+ if (!tail.ok) return tail.error;
1001
+ const subagentModel = tail.model;
1002
+ const modelStr = tail.modelStr;
1174
1003
 
1175
1004
  // Build base prompt once
1176
1005
  const basePrompt = ctx.getSystemPrompt();
@@ -1281,17 +1110,8 @@ export default function (pi: ExtensionAPI) {
1281
1110
  run.childMarker,
1282
1111
  );
1283
1112
 
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;
1113
+ // Fill SubTaskResult (one shared field mapping — issue #376/D3).
1114
+ Object.assign(subTaskResult, toSubTaskResult(result));
1295
1115
 
1296
1116
  results[index] = subTaskResult;
1297
1117
  completedCount++;
@@ -1473,166 +1293,43 @@ export default function (pi: ExtensionAPI) {
1473
1293
  // startedAt (captured once, at mode entry, not at completion).
1474
1294
  const graphModeStartedAt = new Date().toISOString();
1475
1295
 
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({
1296
+ // Mode prologue (issue #379): cost → depth → resolve → targets →
1297
+ // preflight → H1, with the DAG check as the graph-only pre-cost hook — a
1298
+ // malformed graph (empty / over-limit / duplicate id / missing dep) is
1299
+ // rejected before the session spends anything (IN1 boundary). Cycles are
1300
+ // NOT caught here; topologicalSort rejects them after the tail.
1301
+ const pro = runModePrologue({
1302
+ params,
1493
1303
  state,
1494
1304
  ctx,
1495
1305
  log,
1306
+ label: "Graph",
1496
1307
  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;
1308
+ beforeCost: () => {
1309
+ const errors = validateGraph(graphTasks);
1310
+ return errors.length === 0
1311
+ ? undefined
1312
+ : rejection(`Graph validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`);
1540
1313
  },
1314
+ });
1315
+ if (!pro.ok) return pro.error;
1316
+ const { globalParams, resolvedCwd, currentDepth } = pro;
1317
+
1318
+ // Mode tail (issue #379): model resolution (preset + per-call override,
1319
+ // auto-route included in `resolvedPreset`), the empty-model rejection and
1320
+ // the circuit check. It runs BEFORE the topological sort and the per-node
1321
+ // pass (IN8/IN11): a graph with a bad node AND an unconfigured model
1322
+ // reports the MODEL error first.
1323
+ const tail = resolveModeModel({
1541
1324
  state,
1542
1325
  ctx,
1543
1326
  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,
1327
+ preset: globalParams.resolvedPreset,
1328
+ perCallModel: params.model,
1589
1329
  });
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
- }
1330
+ if (!tail.ok) return tail.error;
1331
+ const subagentModel = tail.model;
1332
+ const modelStr = tail.modelStr;
1636
1333
 
1637
1334
  // Resolve priority — the FALLBACK for per-unit priority (issue #114): a
1638
1335
  // task-level priority on graph[] items wins per slot; this is the floor.
@@ -1670,57 +1367,30 @@ export default function (pi: ExtensionAPI) {
1670
1367
  // wording is still validated, and refusing to validate up front would
1671
1368
  // mean a bad node in the LAST wave is discovered after every earlier
1672
1369
  // 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
- }
1370
+ const nodePass = validateUnitPrePass({
1371
+ units: graphTasks,
1372
+ label: "Graph",
1373
+ gitMode: globalParams.resolvedGitMode,
1374
+ ctx,
1375
+ log,
1376
+ force: params.force as boolean | undefined,
1377
+ noJev: params.noJev,
1378
+ merge: (node) => mergeSubTaskParams(globalParams, graphTaskToSubTaskParams(node)),
1379
+ describe: (node, merged) => ({
1380
+ prefix: `Node "${node.id}"`,
1381
+ logContext: { id: node.id },
1382
+ // Placeholder TOKENS stripped (issue #222 review): the rules
1383
+ // read the declared string, so a `{<id>}` whose dependency id
1384
+ // is a blocking keyword would block on a token, not on text
1385
+ // the host wrote. The declared wording around it is unchanged
1386
+ // and still validated. Graph policy — it stays here, not in
1387
+ // the shared helper.
1388
+ task: merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, " "),
1389
+ }),
1390
+ });
1391
+ if (!nodePass.ok) return nodePass.error;
1392
+ const nodeCwds = new Map(nodePass.units.map((u) => [u.unit.id, u.cwd] as const));
1393
+ const nodeWarnings = nodePass.warnings;
1724
1394
 
1725
1395
  // Build base prompt once
1726
1396
  const basePrompt = ctx.getSystemPrompt();
@@ -1776,21 +1446,7 @@ export default function (pi: ExtensionAPI) {
1776
1446
  // sibling node advances the counter (same-wave siblings run
1777
1447
  // concurrently, so the value must be pinned here).
1778
1448
  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
- };
1449
+ const subTaskParams = graphTaskToSubTaskParams(graphTask);
1794
1450
 
1795
1451
  const merged = mergeSubTaskParams(globalParams, subTaskParams);
1796
1452
  // Issue #222: the node's OWN validated cwd (pre-pass);
@@ -1897,19 +1553,12 @@ export default function (pi: ExtensionAPI) {
1897
1553
  run.childMarker,
1898
1554
  );
1899
1555
 
1556
+ // One shared field mapping — issue #376/D3 (the graph literal was a
1557
+ // third copy of it).
1900
1558
  const subTaskResult: SubTaskResult = {
1901
1559
  task: merged.task,
1902
1560
  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,
1561
+ ...toSubTaskResult(result),
1913
1562
  };
1914
1563
 
1915
1564
  // Issue #133: finalize the per-node run entry — status, duration,
@@ -2085,26 +1734,7 @@ export default function (pi: ExtensionAPI) {
2085
1734
  if (costError) return costError;
2086
1735
 
2087
1736
  // 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
- );
1737
+ const globalParams = resolveSubagentParams(params, state, ctx, log);
2108
1738
 
2109
1739
  // Resolve the global model once (per-call model beats preset/config).
2110
1740
  const globalModelResult = resolveSubagentModel(
@@ -2189,6 +1819,8 @@ export default function (pi: ExtensionAPI) {
2189
1819
  gitMode: globalParams.resolvedGitMode,
2190
1820
  outputFile: merged.outputFile,
2191
1821
  force: params.force as boolean | undefined,
1822
+ cwd: targets.cwd,
1823
+ noJev: params.noJev,
2192
1824
  },
2193
1825
  });
2194
1826
  if (preTask.error) return preTask.error;
@@ -2327,6 +1959,9 @@ export default function (pi: ExtensionAPI) {
2327
1959
  thinkingLevel: ThinkingLevel;
2328
1960
  priority?: string;
2329
1961
  systemPrompt: string;
1962
+ /** Issue #411: conductor-authored resume context for an auto-retry,
1963
+ * delivered on the system-prompt side (never inside the task fence). */
1964
+ resumeContext?: string;
2330
1965
  cwd: string;
2331
1966
  toolOptions?: SubagentToolOptions;
2332
1967
  timeout?: number;
@@ -2359,6 +1994,7 @@ export default function (pi: ExtensionAPI) {
2359
1994
  // run entry + drill-in header carry it like foreground runs.
2360
1995
  priority: spawn.priority,
2361
1996
  systemPrompt: spawn.systemPrompt,
1997
+ resumeContext: spawn.resumeContext,
2362
1998
  cwd: spawn.cwd,
2363
1999
  toolOptions: spawn.toolOptions,
2364
2000
  timeout: spawn.timeout,
@@ -2601,16 +2237,29 @@ export default function (pi: ExtensionAPI) {
2601
2237
  async function spawnBackgroundRun(
2602
2238
  pi: ExtensionAPI,
2603
2239
  ctx: ExtensionContext,
2604
- params: Omit<Parameters<typeof resolveSubagentParams>[0], "task"> & {
2605
- task?: string;
2606
- model?: string;
2607
- priority?: string;
2608
- },
2240
+ /**
2241
+ * Two shapes, both passed WITHOUT an assertion (issue #379):
2242
+ * - `DelegateTaskParams` — a fresh dispatch, schema-validated;
2243
+ * - the `resolveRetryParams` bag — rebuilt from a run record, whose
2244
+ * `priority` is the unvalidated persisted string. It is the only field
2245
+ * the two shapes disagree on, and claiming the recorded value was
2246
+ * schema-validated would be a lie: records are read back from disk.
2247
+ */
2248
+ params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
2609
2249
  singleTask: string,
2610
2250
  // Option B U1: the spawn entry a retryRunId resolved to, so a retried
2611
2251
  // background run inherits dispatchId/resumeOf/attempt (record identity,
2612
2252
  // not a delegate param — D4).
2613
2253
  retrySourceRun?: SubagentRun,
2254
+ /**
2255
+ * Issue #401/#411: the resume preamble for a TRANSPORT auto-retry. It rides
2256
+ * the child's system prompt only (as a `<resume-context>` section) — never
2257
+ * inside the `<task>` fence. `resolveSubagentParams`, every gate and every
2258
+ * H1 check above still see `singleTask` (which stays byte-identical to the
2259
+ * recorded original), so routing, capability warnings and pre-flight checks
2260
+ * cannot be steered by the preamble's wording.
2261
+ */
2262
+ attemptContext?: string,
2614
2263
  ): Promise<ToolResult<undefined>> {
2615
2264
  // Phase 6.5: Background execution — spawn session and return ID immediately.
2616
2265
  // Resolve the preset and its model BEFORE the background branch so the
@@ -2676,6 +2325,8 @@ export default function (pi: ExtensionAPI) {
2676
2325
  gitMode: bgResolved.resolvedGitMode,
2677
2326
  outputFile: bgResolvedOutputFile,
2678
2327
  force: params.force,
2328
+ cwd: targets.cwd,
2329
+ noJev: params.noJev,
2679
2330
  },
2680
2331
  });
2681
2332
  if (bgPreTask.error) return bgPreTask.error;
@@ -2694,7 +2345,12 @@ export default function (pi: ExtensionAPI) {
2694
2345
  // Option B U1: durability identity (retry inherits the original dispatch).
2695
2346
  const bgIdentity = newDispatchIdentity(retrySourceRun);
2696
2347
  const agent = await startBackgroundAgent(pi, ctx, {
2348
+ // Issue #411: the preamble rides the system-prompt side
2349
+ // (`resumeContext`), never the task. The task stays the recorded
2350
+ // original, and the snapshot keeps it too, so a later retry of this
2351
+ // retry resolves from the un-prefixed text and never compounds.
2697
2352
  task: singleTask,
2353
+ resumeContext: attemptContext,
2698
2354
  type: params.preset || 'general-purpose',
2699
2355
  description: params.label,
2700
2356
  model: bgModel,
@@ -2705,7 +2361,9 @@ export default function (pi: ExtensionAPI) {
2705
2361
  toolOptions: bgResolved.toolOptions,
2706
2362
  timeout: bgResolved.timeout,
2707
2363
  gitMode: bgResolved.resolvedGitMode,
2708
- originalParams: snapshotOriginalParams(params),
2364
+ originalParams: attemptContext
2365
+ ? { ...snapshotOriginalParams(params), task: singleTask }
2366
+ : snapshotOriginalParams(params),
2709
2367
  sanitizeCwd: bgResolved.effectiveCwd,
2710
2368
  dispatchId: bgIdentity.dispatchId,
2711
2369
  resumeOf: bgIdentity.resumeOf,
@@ -2862,7 +2520,7 @@ export default function (pi: ExtensionAPI) {
2862
2520
  `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
2521
  buildTemplateGuideline(templateSummary),
2864
2522
  "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.",
2523
+ "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
2524
  "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
2525
  "",
2868
2526
  "## Conductor Guardrails",
@@ -3081,6 +2739,68 @@ export default function (pi: ExtensionAPI) {
3081
2739
  // self-evident (issue #361 review).
3082
2740
  const explicitBackground = params.background;
3083
2741
 
2742
+ // Issue #412 (rule 2: "no deadline ⇒ durable path") — the dispatch-shape
2743
+ // pre-flight. A high/xhigh-thinking run the conductor asked to run
2744
+ // FOREGROUND with an explicit timeout is the shape that lost 14 minutes of
2745
+ // plan critique on 2026-10-31: foreground runs persist nothing, so the
2746
+ // deadline kills the work outright, while a background run keeps its
2747
+ // session and is retried on a transport error. The switch is applied HERE
2748
+ // — after template/retry resolution and BEFORE `useBackground` is resolved
2749
+ // and before any run record is written — so the shape every downstream
2750
+ // reader sees (the spawn, the retry snapshot, the pending-work record) is
2751
+ // the switched one. Moving it after `snapshotOriginalParams` would record
2752
+ // `background:false` and silently cost the run its transport auto-retry
2753
+ // (`transport-retry.ts` classifies off that snapshot).
2754
+ // Issue #415: the switch is OUR process (a conductor decision rule), not
2755
+ // product behavior — a user's explicit foreground timeout is usually a
2756
+ // budget cap, so a GLOBAL switch could triple time and cost against
2757
+ // their instruction. The umbrella project-local `processChecks` flag
2758
+ // gates it (fail-open: no/malformed manifest → off). Resolve the
2759
+ // dispatch cwd ONCE, the way the target validation below will.
2760
+ const processChecksCwd =
2761
+ params.cwd === undefined ? ctx.cwd : path.resolve(ctx.cwd, params.cwd);
2762
+ const processChecks = readProcessChecks(processChecksCwd);
2763
+ // The preset the dispatch will actually run with — an auto-routed
2764
+ // `code-reviewer`/`debugger` is a high-thinking run even though the
2765
+ // caller declared no level, so the pre-flight resolves the SAME preset
2766
+ // the merge below will (one rule, `resolveDispatchPreset`).
2767
+ const declaredPresetForSwitch = resolveDispatchPreset(params, state).preset;
2768
+ const thinkingSwitch = resolveThinkingDispatchSwitch({
2769
+ processChecks,
2770
+ thinkingLevel: (params.thinkingLevel ?? declaredPresetForSwitch?.thinkingLevel) as
2771
+ | ThinkingLevel
2772
+ | undefined,
2773
+ explicitBackground,
2774
+ timeout: params.timeout,
2775
+ force: params.force,
2776
+ shape: dispatchShape,
2777
+ });
2778
+ if (thinkingSwitch === "switch") {
2779
+ params.background = true;
2780
+ // Drop the foreground deadline: the 30-minute background default
2781
+ // (DEFAULT_BACKGROUND_DEADLINE_MS) applies instead. Recorded as
2782
+ // undefined, so a retry re-derives it rather than restoring the cap.
2783
+ params.timeout = undefined;
2784
+ log.info("Dispatch pre-flight: high-thinking foreground switched to background", {
2785
+ thinkingLevel: params.thinkingLevel,
2786
+ timeout: "dropped (background default applies)",
2787
+ });
2788
+ pi.sendMessage({
2789
+ customType: "delegate-notification",
2790
+ content: THINKING_SWITCH_NOTICE,
2791
+ display: true,
2792
+ details: { thinkingLevel: params.thinkingLevel, previousTimeout: "dropped" },
2793
+ }, { deliverAs: "followUp" });
2794
+ ctx.ui.notify(THINKING_SWITCH_NOTICE, "warning");
2795
+ } else if (thinkingSwitch === "forced") {
2796
+ // The override is recorded, not silent: the dispatch text is the reason
2797
+ // (`force` has no reason field — ADR 0007's contract stays unchanged).
2798
+ log.info("Dispatch pre-flight: high-thinking foreground forced", {
2799
+ thinkingLevel: params.thinkingLevel,
2800
+ timeout: params.timeout,
2801
+ });
2802
+ }
2803
+
3084
2804
  // background: true with chain/graph was silently ignored — the batch ran
3085
2805
  // foreground (blocking until every unit finished) while the caller believed
3086
2806
  // it was background. Both remain rejected loudly at dispatch validation;
@@ -3185,19 +2905,7 @@ export default function (pi: ExtensionAPI) {
3185
2905
  currentDepth,
3186
2906
  maxDepth: state.config.maxSubagentDepth,
3187
2907
  });
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
- };
2908
+ return depthLimitRejection(currentDepth, state.config.maxSubagentDepth);
3201
2909
  }
3202
2910
 
3203
2911
  const {
@@ -3264,6 +2972,8 @@ export default function (pi: ExtensionAPI) {
3264
2972
  gitMode: resolvedGitMode,
3265
2973
  outputFile: resolvedOutputFile,
3266
2974
  force: params.force,
2975
+ cwd: resolvedCwd,
2976
+ noJev: params.noJev,
3267
2977
  });
3268
2978
  if (validation.warnings.length > 0) {
3269
2979
  log.warn("Pre-task validation warnings", { warnings: validation.warnings });
@@ -3293,18 +3003,7 @@ export default function (pi: ExtensionAPI) {
3293
3003
  const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
3294
3004
  if (!modelStr || modelStr === "/") {
3295
3005
  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
- };
3006
+ return modelNotConfiguredRejection();
3308
3007
  }
3309
3008
 
3310
3009
  // Create run record
@@ -3850,19 +3549,7 @@ export default function (pi: ExtensionAPI) {
3850
3549
  },
3851
3550
 
3852
3551
  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
- },
3552
+ args: DelegateTaskParams,
3866
3553
  theme: Theme,
3867
3554
  _context: unknown,
3868
3555
  ) {
@@ -3889,6 +3576,8 @@ export default function (pi: ExtensionAPI) {
3889
3576
  description: [
3890
3577
  "Check the status of a background agent and retrieve its result.",
3891
3578
  "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.",
3579
+ "Accepts a full agent id or a unique 8-character id prefix.",
3580
+ "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
3581
  "Returns the agent's status, result (if completed), and transcript path.",
3893
3582
  ].join(" "),
3894
3583
  parameters: Type.Object({
@@ -3902,14 +3591,64 @@ export default function (pi: ExtensionAPI) {
3902
3591
  ),
3903
3592
  }),
3904
3593
  execute: async (toolCallId, params) => {
3905
- const { getAgent } = await import('./session-manager');
3594
+ const { getAgent, resolveAgentId, findRetryLineage, isTerminalAgentStatus, RETRY_SCAN_WINDOW_MS, RETRY_SCAN_WINDOW_DAYS } = await import('./session-manager');
3906
3595
  const { getTranscript } = await import('./transcript');
3907
-
3908
- const agent = getAgent(params.agent_id);
3596
+
3597
+ // The notices render the first 8 hex characters of an id; resolve a
3598
+ // unique prefix before both the record read and the lineage lookup.
3599
+ // Ambiguity fails closed — a guess here could report the wrong run.
3600
+ const resolution = resolveAgentId(params.agent_id);
3601
+ if (resolution.kind === 'ambiguous') {
3602
+ return {
3603
+ content: [{
3604
+ type: "text" as const,
3605
+ text: `Agent id prefix "${params.agent_id}" is ambiguous — matches: ${resolution.matches.join(', ')}`,
3606
+ }],
3607
+ details: undefined,
3608
+ isError: true,
3609
+ };
3610
+ }
3611
+ // Anything that is not a full id or a matching 8-hex prefix keeps
3612
+ // today's message — there is no id to resolve against the stores.
3613
+ if (resolution.kind === 'unresolved') {
3614
+ return {
3615
+ content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
3616
+ details: undefined,
3617
+ isError: true,
3618
+ };
3619
+ }
3620
+ const agentId = resolution.id;
3621
+
3622
+ const agent = getAgent(agentId);
3909
3623
 
3910
3624
  if (!agent) {
3625
+ const lineage = findRetryLineage(agentId);
3626
+ if (lineage.latest && lineage.latest.id !== agentId) {
3627
+ const latest = lineage.latest;
3628
+ return {
3629
+ content: [{
3630
+ type: "text" as const,
3631
+ 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()}).`,
3632
+ }],
3633
+ details: undefined,
3634
+ isError: true,
3635
+ };
3636
+ }
3637
+
3638
+ const registryRun = lineage.inflight.find((run) => run.id === agentId);
3639
+ const registryStarted = registryRun
3640
+ ? (Number.isFinite(Date.parse(registryRun.startedAt))
3641
+ ? new Date(registryRun.startedAt).toISOString()
3642
+ : registryRun.startedAt)
3643
+ : undefined;
3644
+ const registryText = registryRun
3645
+ ? `no recent retry lineage recorded, but the registry still lists run ${registryRun.id} (attempt ${registryRun.attempt ?? 1}, started ${registryStarted}).`
3646
+ : `no recent retry lineage recorded (scanned the last ${RETRY_SCAN_WINDOW_DAYS} days), and no registry record either.`;
3911
3647
  return {
3912
- content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
3648
+ content: [{
3649
+ type: "text" as const,
3650
+ text: `Agent ${params.agent_id} not found — ${registryText}`,
3651
+ }],
3913
3652
  details: undefined,
3914
3653
  isError: true,
3915
3654
  };
@@ -3927,6 +3666,22 @@ export default function (pi: ExtensionAPI) {
3927
3666
  if (agent.error) {
3928
3667
  resultText += `Error: ${agent.error}\n`;
3929
3668
  }
3669
+
3670
+ // A terminal source can be the WRONG run to act on: the retry that
3671
+ // actually finished is a later attempt of the same dispatch. Name it
3672
+ // so a terminal status is not read as the final word.
3673
+ if (isTerminalAgentStatus(agent.status)) {
3674
+ const lineage = findRetryLineage(agentId, agent);
3675
+ if (lineage.latest && lineage.latest.id !== agentId) {
3676
+ const latest = lineage.latest;
3677
+ resultText += `Superseded by ${latest.id} (attempt ${latest.attempt}, ${latest.status}, started ${new Date(latest.startedAt).toISOString()})\n`;
3678
+ } else if (agent.startedAt < Date.now() - RETRY_SCAN_WINDOW_MS) {
3679
+ // The lineage scan is windowed: an older run cannot be shown a
3680
+ // later attempt that fell outside it. Say so instead of implying
3681
+ // there is none.
3682
+ resultText += `Retry lineage not checked: this run started more than ${RETRY_SCAN_WINDOW_DAYS} days ago.\n`;
3683
+ }
3684
+ }
3930
3685
 
3931
3686
  if (agent.result) {
3932
3687
  resultText += `\nResult:\n`;
@@ -3953,7 +3708,7 @@ export default function (pi: ExtensionAPI) {
3953
3708
 
3954
3709
  // Include transcript if verbose
3955
3710
  if (params.verbose) {
3956
- const transcript = getTranscript(params.agent_id);
3711
+ const transcript = getTranscript(agentId);
3957
3712
  if (transcript.length > 0) {
3958
3713
  resultText += `\n\nTranscript (${transcript.length} entries):\n`;
3959
3714
  for (const entry of transcript.slice(-10)) { // Last 10 entries
@@ -3963,7 +3718,7 @@ export default function (pi: ExtensionAPI) {
3963
3718
  }
3964
3719
 
3965
3720
  // Include transcript path
3966
- resultText += `\nTranscript: ${transcriptDisplayPath(params.agent_id)}`;
3721
+ resultText += `\nTranscript: ${transcriptDisplayPath(agentId)}`;
3967
3722
 
3968
3723
  return {
3969
3724
  content: [{ type: "text" as const, text: resultText }],
@@ -4313,6 +4068,76 @@ export default function (pi: ExtensionAPI) {
4313
4068
  });
4314
4069
  }
4315
4070
 
4071
+ /**
4072
+ * Issue #365: re-dispatch a background run that settled with a transport-class
4073
+ * failure, using the `retryRunId` machinery. `resolveRetryParams({}, run)`
4074
+ * restores the recorded params and `spawnBackgroundRun(..., run)` mints the
4075
+ * lineage (`resumeOf` + `attempt: 2`), so the retry re-runs the normal gates
4076
+ * (cost, approval, pre-task) and is visible in the record.
4077
+ *
4078
+ * Issue #401/#411: the retry carries a resume preamble (`attemptContext`) that
4079
+ * is injected into the child's system prompt only (as a `<resume-context>`
4080
+ * section), never inside the `<task>` fence. The task handed to
4081
+ * `resolveSubagentParams` stays the recorded original, so auto-routing, H1
4082
+ * keyword warnings and the capability checks behave exactly as they did on
4083
+ * attempt 1.
4084
+ *
4085
+ * Returns TRUE when the retry was actually spawned — the caller then SUPPRESSES
4086
+ * the source run's completion notice, because the retry's own terminal settle
4087
+ * is the wake. A gate rejection or a throwing spawn returns FALSE and the
4088
+ * caller reports the original failure exactly as before (no silent drop).
4089
+ */
4090
+ async function scheduleTransportRetry(
4091
+ ctx: ExtensionContext,
4092
+ run: SubagentRun,
4093
+ ): Promise<boolean> {
4094
+ const sourceAttempt = run.attempt ?? 1;
4095
+ try {
4096
+ const retryParams = resolveRetryParams({}, run);
4097
+ // Issue #404: point at the retained session ONLY when it is really
4098
+ // there. Resolve this conductor-side: the child may run in another cwd.
4099
+ // An invalid id cannot have a session dir (and `backgroundSessionDir`
4100
+ // throws on one) — no pointer, no throw.
4101
+ let retainedSessionDir: string | undefined;
4102
+ try {
4103
+ const { retainedSessionPointer } = await import('./session-manager');
4104
+ const candidate = retainedSessionPointer(run.id);
4105
+ if (fs.existsSync(candidate)) retainedSessionDir = candidate;
4106
+ } catch {
4107
+ retainedSessionDir = undefined;
4108
+ }
4109
+ const result = await spawnBackgroundRun(
4110
+ pi,
4111
+ ctx,
4112
+ retryParams,
4113
+ retryParams.task!,
4114
+ run,
4115
+ buildRetryResumePreamble(run, sourceAttempt + 1, retainedSessionDir),
4116
+ );
4117
+ if (result.isError) {
4118
+ log.warn("Transport auto-retry spawn rejected — surfacing the original failure", {
4119
+ sourceId: run.id,
4120
+ attempt: sourceAttempt,
4121
+ error: result.content[0]?.type === "text" ? result.content[0].text : undefined,
4122
+ });
4123
+ return false;
4124
+ }
4125
+ } catch (err) {
4126
+ log.warn("Transport auto-retry spawn failed — surfacing the original failure", {
4127
+ sourceId: run.id,
4128
+ attempt: sourceAttempt,
4129
+ error: (err as Error).message,
4130
+ });
4131
+ return false;
4132
+ }
4133
+ log.info("Background run settled — transport auto-retry scheduled", {
4134
+ sourceId: run.id,
4135
+ attempt: sourceAttempt + 1,
4136
+ });
4137
+ ctx.ui.notify(TRANSPORT_RETRY_TOAST, "warning");
4138
+ return true;
4139
+ }
4140
+
4316
4141
  async function deliverCompletionAlert(event: SubagentEvent): Promise<void> {
4317
4142
  const id = event.agentId;
4318
4143
  if (!claimTerminalNotice(id)) return;
@@ -4324,6 +4149,14 @@ export default function (pi: ExtensionAPI) {
4324
4149
  if (!agent) return; // pruned or foreign id — nothing to notify
4325
4150
  const knob = state.config.completionNotify ?? "all";
4326
4151
  const run = resolveRunEntry(state.getRunEntries(ctx), id);
4152
+ // Issue #365: a transport-class background failure is re-dispatched once
4153
+ // and the source notice is suppressed (the retry's settle is the wake).
4154
+ // Every other terminal type — and every non-retryable failure — keeps the
4155
+ // existing path unchanged.
4156
+ if (event.type === "subagent:failed" && run && isTransportRetryable(run)) {
4157
+ const retried = await scheduleTransportRetry(ctx, run);
4158
+ if (retried) return;
4159
+ }
4327
4160
  const message = buildCompletionMessage(agent, run);
4328
4161
  // Issue #179 (D2): resolve delivery from the CLASSIFIED notification
4329
4162
  // status, not the raw agent status — otherwise a run whose completion