brl-subagent 2.5.2 → 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,13 +71,27 @@ 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
- import { findUnknownParams, KNOWN_DELEGATE_KEYS, resolveSubagentParams, snapshotOriginalParams } from "./params";
78
+ import {
79
+ defaultBackgroundFor,
80
+ findUnknownParams,
81
+ KNOWN_DELEGATE_KEYS,
82
+ resolveDispatchPreset,
83
+ resolveEffectiveApprovalMode,
84
+ resolveSubagentParams,
85
+ resolveThinkingDispatchSwitch,
86
+ shouldRejectBackgroundForBatch,
87
+ snapshotOriginalParams,
88
+ THINKING_SWITCH_NOTICE,
89
+ type DispatchShape,
90
+ type ResolveInputParams,
91
+ } from "./params";
77
92
  import { delegateTaskParamsSchema } from "./schema";
78
- import { createSessionState, resolveTerminalRunEntry } from "./state";
93
+ import { readProcessChecks } from "./project-flags";
94
+ import { createSessionState, resolveTerminalRunEntry, type SessionState } from "./state";
79
95
  import { makeLiveOnUpdate, createUnitRun, finalizeUnitRun, finalizeUnitRunCrash, pruneHistoryIfNeeded, registerLiveRun } from "./unit-run";
80
96
  import { buildSubagentPrompt, describePromptMode } from "./prompt";
81
97
  import { runSubagent, cleanupTempDirs, reapActiveChildren } from "./runner";
@@ -85,7 +101,7 @@ import {
85
101
  newDispatchIdentity,
86
102
  } from "./recovery";
87
103
  import { markInterrupted, listInflightRuns, clearInflightRun } from "./run-registry";
88
- import { acquireSlot, releaseSlot, updateStatus, updateProgressStatus } from "./concurrency";
104
+ import { acquireSlot, clearProgressLinger, releaseSlot, repaintStatus, stopProgressTicker } from "./concurrency";
89
105
  import { transcriptDisplayPath } from "./transcript-path";
90
106
  import {
91
107
  finalizeRunRecord,
@@ -137,6 +153,7 @@ import {
137
153
  claimTerminalNotice,
138
154
  resolveRunEntry,
139
155
  } from "./notify-completion";
156
+ import { isTransportRetryable, TRANSPORT_RETRY_TOAST } from "./transport-retry";
140
157
 
141
158
  // ---------------------------------------------------------------------------
142
159
  // Helpers
@@ -182,6 +199,81 @@ export function buildTemplateGuideline(templateSummary: string): string {
182
199
  return `Templates are file-backed task starters with \${param} slots. Built-in templates: ${templateSummary}. Custom templates are NOT listed here — inspect them via /brl-subagent templates before choosing one.`;
183
200
  }
184
201
 
202
+ /**
203
+ * Issue #354 review minor: the synchronous shutdown cleanup, extracted so the
204
+ * real body (not a hand-mirrored copy) is exercised by tests. Clears every
205
+ * session-bound live collection, resets the counters, and stops both footer
206
+ * timers. Ordering is significant: the ticker is stopped before the linger is
207
+ * cleared, and the maps are cleared before their guard claim set.
208
+ */
209
+ export function cleanupSessionState(state: SessionState): void {
210
+ // Clear all live subagent sessions
211
+ state.subagentSessions.clear();
212
+ // Drop pending finalize claims too (PR #71 review: the claim set must
213
+ // not outlive the map it guards — a fresh session could otherwise
214
+ // no-op on an id a stale claim still remembers).
215
+ state.resetLiveFinalizeClaims();
216
+ // Reset counters
217
+ state.activeSubagents = 0;
218
+ state.completedSubagents = 0;
219
+ state.failedSubagents = 0;
220
+ state.unseenSubagents = 0;
221
+ // Issue #354: the footer ticker must not outlive the session (it also
222
+ // drops the elapsed anchor, so a new session starts its own clock), and
223
+ // neither may the 3 s linger timer (F2) — it would repaint a dead pane.
224
+ stopProgressTicker(state);
225
+ clearProgressLinger(state);
226
+ // Clear pending queue
227
+ state.pendingQueue.length = 0;
228
+ }
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
+
185
277
  // ---------------------------------------------------------------------------
186
278
  // Extension entry point
187
279
  // ---------------------------------------------------------------------------
@@ -197,6 +289,87 @@ type _KnownDelegateKey = (typeof KNOWN_DELEGATE_KEYS extends Set<infer K> ? K :
197
289
  type _ExpectNever<T extends never> = T;
198
290
  type _DelegateParamCoverage = _ExpectNever<Exclude<_KnownDelegateKey, keyof DelegateTaskParams>>;
199
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
+
200
373
  export default function (pi: ExtensionAPI) {
201
374
  const log = createLogger("brl-subagent");
202
375
 
@@ -219,7 +392,10 @@ export default function (pi: ExtensionAPI) {
219
392
  // -------------------------------------------------------------------
220
393
 
221
394
  function applyConfig(ctx: ExtensionContext, message: string) {
222
- updateStatus(state, ctx);
395
+ // Issue #354: a config change mid-run must not blank the footer —
396
+ // repaintStatus renders the activity line while runs are active and
397
+ // falls back to the idle config line when none are.
398
+ repaintStatus(state, ctx);
223
399
  state.persistState(pi);
224
400
  ctx.ui.notify(message, "info");
225
401
  }
@@ -239,7 +415,7 @@ export default function (pi: ExtensionAPI) {
239
415
  getAllPresets(state.builtinPresets, state.customPresets),
240
416
  log,
241
417
  );
242
- updateStatus(state, ctx);
418
+ repaintStatus(state, ctx);
243
419
  state.persistState(pi);
244
420
  ctx.ui.notify("Subagent configuration reset", "info");
245
421
  }
@@ -248,73 +424,16 @@ export default function (pi: ExtensionAPI) {
248
424
  // Parameter resolution (extracted to src/params.ts — issue #59)
249
425
  // -------------------------------------------------------------------
250
426
 
251
- /** Parse "provider/model-id" into {provider, id}. Returns null on bad format. */
252
- function parseModelString(s: string): { provider: string; id: string } | null {
253
- const trimmed = s.trim();
254
- const idx = trimmed.indexOf("/");
255
- if (idx <= 0 || idx === trimmed.length - 1) return null;
256
- return { provider: trimmed.slice(0, idx), id: trimmed.slice(idx + 1) };
257
- }
258
-
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.
259
431
  function resolveSubagentModel(
260
432
  ctx: ExtensionContext,
261
433
  preset: SubagentPreset | undefined,
262
434
  perCallModel?: string, // NEW: top-level delegate_task model param (issue #96)
263
- ):
264
- | { ok: true; model: { provider: string; id: string } }
265
- | { ok: false; error: ToolResult<SubagentResult | undefined> } {
266
- // Precedence: per-call model > preset.model > state.config.model > conductor model
267
- let subagentModel: { provider: string; id: string } | undefined;
268
-
269
- if (perCallModel) {
270
- const parsed = parseModelString(perCallModel);
271
- if (!parsed) {
272
- log.warn("Model override is not a valid provider/model-id, falling back", { model: perCallModel });
273
- } else if (modelIsAvailable(ctx.modelRegistry, parsed)) {
274
- log.info("Using per-call model override", { model: perCallModel });
275
- return { ok: true, model: parsed };
276
- } else {
277
- log.warn("Model override unavailable, falling back", { model: perCallModel });
278
- }
279
- }
280
-
281
- if (preset?.model) {
282
- const parsed = parseModelString(preset.model);
283
- if (parsed && modelIsAvailable(ctx.modelRegistry, parsed)) {
284
- subagentModel = parsed;
285
- log.info("Using preset model", { preset: preset.name, model: preset.model });
286
- } else {
287
- // Fallback: preset model unavailable → configured model
288
- log.warn("Preset model unavailable, falling back to configured model", {
289
- preset: preset.name,
290
- model: preset.model,
291
- });
292
- }
293
- }
294
-
295
- if (!subagentModel) {
296
- subagentModel =
297
- state.config.model ||
298
- (ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined);
299
- }
300
-
301
- if (!subagentModel) {
302
- return {
303
- ok: false,
304
- error: {
305
- content: [
306
- {
307
- type: "text" as const,
308
- text: "No model available. Configure API keys first, then use /brl-subagent to set a model.",
309
- },
310
- ],
311
- details: undefined,
312
- isError: true,
313
- },
314
- };
315
- }
316
-
317
- return { ok: true, model: subagentModel };
435
+ ): SubagentModelResolution {
436
+ return resolveSubagentModelPrecedence({ state, ctx, log, preset, perCallModel });
318
437
  }
319
438
 
320
439
  // C3: Resolve a step's model override (step.model > global resolved model).
@@ -435,115 +554,22 @@ export default function (pi: ExtensionAPI) {
435
554
  // startedAt (captured once, at mode entry, not at completion).
436
555
  const chainModeStartedAt = new Date().toISOString();
437
556
 
438
- // R5: Check session cost limit before spawning
439
- 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,
440
565
  state,
441
566
  ctx,
442
567
  log,
568
+ label: "Chain",
443
569
  units: chainSteps.length,
444
- label: "Chain delegation",
445
570
  });
446
- if (costError) return costError;
447
-
448
- // Reject delegation if recursion depth exceeds configured max
449
- const currentDepth = getCurrentDepth();
450
- if (currentDepth >= state.config.maxSubagentDepth) {
451
- log.warn("Chain delegation rejected: max depth reached", {
452
- currentDepth,
453
- maxDepth: state.config.maxSubagentDepth,
454
- });
455
- return {
456
- content: [
457
- {
458
- type: "text" as const,
459
- text:
460
- `Cannot delegate further: subagent recursion depth limit reached ` +
461
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
462
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
463
- },
464
- ],
465
- details: undefined,
466
- isError: true,
467
- };
468
- }
469
-
470
- // Resolve global params once
471
- const globalParams = resolveSubagentParams(
472
- params as {
473
- task: string;
474
- label?: string;
475
- preset?: string;
476
- systemPrompt?: string;
477
- inheritSystemPrompt?: boolean;
478
- thinkingLevel?: string;
479
- outputFile?: string;
480
- timeout?: number;
481
- cwd?: string;
482
- tools?: string[];
483
- excludeTools?: string[];
484
- noBuiltinTools?: boolean;
485
- gitMode?: string;
486
- },
487
- state,
488
- ctx,
489
- log,
490
- );
491
-
492
- // Validate CWD once
493
- const cwdResult = validateCwd(globalParams.effectiveCwd, ctx.cwd);
494
- if (!cwdResult.ok) {
495
- return {
496
- content: [
497
- { type: "text" as const, text: `Invalid cwd: ${cwdResult.error}` },
498
- ],
499
- details: undefined,
500
- isError: true,
501
- };
502
- }
503
- const resolvedCwd = cwdResult.value;
504
-
505
- // Pre-flight checks — fail fast before consuming resources
506
- const pfResult = preflightCheck(resolvedCwd);
507
- if (!pfResult.ok) {
508
- log.warn("Chain pre-flight check failed", { error: pfResult.error });
509
- return {
510
- content: [
511
- {
512
- type: "text" as const,
513
- text: `Pre-flight check failed: ${pfResult.error}`,
514
- },
515
- ],
516
- details: undefined,
517
- isError: true,
518
- };
519
- }
520
-
521
- // H1: Pre-task validation at mode entry — deterministic check that
522
- // tools/thinking match the task (mirrors single/background modes, issue
523
- // #32). Chain top-level tasks are empty (modeCount forbids task+chain), so
524
- // keyword warnings skip on empty text and only the hard outputFile-vs-write
525
- // conflict applies (issue #34). The mode-level outputFile on globalParams is
526
- // the one validated here; every step's own cwd/outputFile/tools are
527
- // validated by the per-step pre-pass below (issue #222).
528
- const validation = validatePreTask({
529
- task: globalParams.task,
530
- toolOptions: globalParams.toolOptions,
531
- thinkingLevel: globalParams.thinkingLevel,
532
- gitMode: globalParams.resolvedGitMode,
533
- outputFile: globalParams.outputFile,
534
- });
535
- if (validation.warnings.length > 0) {
536
- log.warn("Chain pre-task validation warnings", { warnings: validation.warnings });
537
- }
538
- if (!validation.valid) {
539
- const errText = validation.errors.join("; ");
540
- log.warn("Chain pre-task validation failed", { errors: validation.errors });
541
- return {
542
- content: [{ type: "text" as const, text: errText }],
543
- details: undefined,
544
- isError: true,
545
- };
546
- }
571
+ if (!pro.ok) return pro.error;
572
+ const { globalParams, resolvedCwd, currentDepth } = pro;
547
573
 
548
574
  // Per-step pre-pass (issue #222): resolve + validate EVERY step before
549
575
  // any spawn, so a single bad step rejects the chain with nothing
@@ -553,72 +579,38 @@ export default function (pi: ExtensionAPI) {
553
579
  // step's output (only its TASK text consumes {previous}), so the pass
554
580
  // can run up front — and must, because discovering step 5's bad cwd
555
581
  // after four steps already ran would waste their whole budget.
556
- const stepCwds: string[] = [];
557
- const stepWarnings: string[] = [];
558
- for (let i = 0; i < chainSteps.length; i++) {
559
- const merged = mergeSubTaskParams(globalParams, chainSteps[i]);
560
- const stepPrefix = `Step ${i + 1} ("${displayTaskName(merged)}")`;
561
-
562
- const stepTargets = validateDelegationTargets({
563
- ctx,
564
- effectiveCwd: merged.effectiveCwd,
565
- outputFile: merged.outputFile,
566
- prefix: stepPrefix,
567
- });
568
- if (!stepTargets.ok) return stepTargets.error;
569
- stepCwds.push(stepTargets.cwd);
570
-
571
- const stepValidation = runPreTaskValidation({
572
- log,
573
- label: "Chain",
574
- 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)}")`,
575
593
  logContext: { step: i + 1 },
576
- preTask: {
577
- task: merged.task,
578
- toolOptions: merged.toolOptions,
579
- thinkingLevel: merged.thinkingLevel,
580
- gitMode: globalParams.resolvedGitMode,
581
- outputFile: merged.outputFile,
582
- force: params.force as boolean | undefined,
583
- },
584
- });
585
- if (stepValidation.error) return stepValidation.error;
586
- for (const w of stepValidation.warnings) stepWarnings.push(`${stepPrefix}: ${w}`);
587
- }
588
-
589
- // Resolve model once (per-call top-level model override beats preset)
590
- const modelResult = resolveSubagentModel(ctx, globalParams.resolvedPreset, params.model as string | undefined);
591
- if (!modelResult.ok) return modelResult.error;
592
- const subagentModel = modelResult.model;
593
-
594
- const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
595
- if (!modelStr || modelStr === "/") {
596
- log.warn("Model string is empty after resolution", { model: subagentModel });
597
- return {
598
- content: [
599
- {
600
- type: "text" as const,
601
- text:
602
- "Subagent model is not configured. " +
603
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
604
- },
605
- ],
606
- details: undefined,
607
- isError: true,
608
- };
609
- }
610
-
611
- // R1: Circuit breaker check — reject if circuit is open
612
- const circuitCheck = state.checkCircuit();
613
- if (circuitCheck.isOpen) {
614
- return {
615
- content: [
616
- { type: "text" as const, text: circuitCheck.message! },
617
- ],
618
- details: undefined,
619
- isError: true,
620
- };
621
- }
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;
622
614
 
623
615
  // Resolve priority (issue #114: no config knob — the call-level default)
624
616
  const chainPriority: Priority = (
@@ -694,10 +686,10 @@ export default function (pi: ExtensionAPI) {
694
686
  };
695
687
  // Issue #133: render the breakdown — the chain holds ONE mode-level
696
688
  // slot (acquired at mode start, released in the finally), so no
697
- // per-step acquire/release calls updateProgressStatus while the
689
+ // per-step acquire/release calls repaintStatus while the
698
690
  // mode context is set. Call it directly here (mirrors how the
699
691
  // graph path's per-node slot operations trigger the render).
700
- updateProgressStatus(state, ctx);
692
+ repaintStatus(state, ctx);
701
693
 
702
694
  // Emit initial progress for this step
703
695
  const modeInfo = describePromptMode(
@@ -785,17 +777,8 @@ export default function (pi: ExtensionAPI) {
785
777
  // shape finalizeRunRecord expects, errorCategory included).
786
778
  finalizeUnitRun(state, pi, ctx, run, result, log);
787
779
 
788
- // Fill SubTaskResult
789
- subTaskResult.exitCode = result.exitCode;
790
- subTaskResult.messages = result.messages;
791
- subTaskResult.stderr = result.stderr;
792
- subTaskResult.usage = result.usage;
793
- subTaskResult.model = result.model;
794
- subTaskResult.stopReason = result.stopReason;
795
- subTaskResult.errorMessage = result.errorMessage;
796
- subTaskResult.errorCategory = classifyError(result);
797
- subTaskResult.gitBranch = result.gitBranch;
798
- subTaskResult.gitDiff = result.gitDiff;
780
+ // Fill SubTaskResult (one shared field mapping — issue #376/D3).
781
+ Object.assign(subTaskResult, toSubTaskResult(result));
799
782
 
800
783
  chainResults.push(subTaskResult);
801
784
 
@@ -958,101 +941,22 @@ export default function (pi: ExtensionAPI) {
958
941
  ): Promise<ToolResult<SubagentResult | ParallelDetails | undefined>> {
959
942
  const taskList: SubTaskParams[] = params.tasks!;
960
943
 
961
- // R5: Check session cost limit before spawning
962
- 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,
963
952
  state,
964
953
  ctx,
965
- log,
966
- units: taskList.length,
967
- label: "Parallel delegation",
968
- });
969
- if (costError) return costError;
970
-
971
- // Reject delegation if recursion depth exceeds configured max
972
- const currentDepth = getCurrentDepth();
973
- if (currentDepth >= state.config.maxSubagentDepth) {
974
- log.warn("Parallel delegation rejected: max depth reached", {
975
- currentDepth,
976
- maxDepth: state.config.maxSubagentDepth,
977
- });
978
- return {
979
- content: [
980
- {
981
- type: "text" as const,
982
- text:
983
- `Cannot delegate further: subagent recursion depth limit reached ` +
984
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
985
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
986
- },
987
- ],
988
- details: undefined,
989
- isError: true,
990
- };
991
- }
992
-
993
- // Resolve global params once
994
- const globalParams = resolveSubagentParams(
995
- params as {
996
- task: string;
997
- label?: string;
998
- preset?: string;
999
- systemPrompt?: string;
1000
- inheritSystemPrompt?: boolean;
1001
- thinkingLevel?: string;
1002
- outputFile?: string;
1003
- timeout?: number;
1004
- cwd?: string;
1005
- tools?: string[];
1006
- excludeTools?: string[];
1007
- noBuiltinTools?: boolean;
1008
- gitMode?: string;
1009
- },
1010
- state,
1011
- ctx,
1012
- log,
1013
- );
1014
-
1015
- // Validate CWD once
1016
- const targets = validateDelegationTargets({ ctx, effectiveCwd: globalParams.effectiveCwd });
1017
- if (!targets.ok) return targets.error;
1018
- const resolvedCwd = targets.cwd;
1019
-
1020
- // Pre-flight checks — fail fast before consuming resources
1021
- const pfResult = preflightCheck(resolvedCwd);
1022
- if (!pfResult.ok) {
1023
- log.warn("Parallel pre-flight check failed", { error: pfResult.error });
1024
- return {
1025
- content: [
1026
- {
1027
- type: "text" as const,
1028
- text: `Pre-flight check failed: ${pfResult.error}`,
1029
- },
1030
- ],
1031
- details: undefined,
1032
- isError: true,
1033
- };
1034
- }
1035
-
1036
- // H1: Pre-task validation at mode entry — deterministic check that
1037
- // tools/thinking match the task (mirrors single/background modes, issue
1038
- // #32). Parallel top-level tasks are empty (modeCount forbids task+tasks),
1039
- // so keyword warnings skip on empty text and only the hard
1040
- // outputFile-vs-write conflict applies (issue #34). The mode-level
1041
- // outputFile on globalParams is the one validated here; every task's own
1042
- // cwd/outputFile/tools are validated by the per-task pre-pass below
1043
- // (issue #222).
1044
- const preTask = runPreTaskValidation({
1045
954
  log,
1046
955
  label: "Parallel",
1047
- preTask: {
1048
- task: globalParams.task,
1049
- toolOptions: globalParams.toolOptions,
1050
- thinkingLevel: globalParams.thinkingLevel,
1051
- gitMode: globalParams.resolvedGitMode,
1052
- outputFile: globalParams.outputFile,
1053
- },
956
+ units: taskList.length,
1054
957
  });
1055
- if (preTask.error) return preTask.error;
958
+ if (!pro.ok) return pro.error;
959
+ const { globalParams, resolvedCwd, currentDepth } = pro;
1056
960
 
1057
961
  // Per-task pre-pass (issue #220, extended by #222): validate EVERY task
1058
962
  // before any spawn, so a single bad task rejects the batch with nothing
@@ -1064,73 +968,38 @@ export default function (pi: ExtensionAPI) {
1064
968
  // mode-level cwd. Per-task warnings are prefixed with their unit and
1065
969
  // collected here to ride the final result. The mode-entry validation
1066
970
  // above stays for the mode-level outputFile (issue #34).
1067
- const taskWarnings: string[] = [];
1068
- // Parallel index → the task's own validated cwd (issue #222).
1069
- const taskCwds: string[] = [];
1070
- for (let i = 0; i < taskList.length; i++) {
1071
- const merged = mergeSubTaskParams(globalParams, taskList[i]);
1072
- const taskPrefix = `Task ${i + 1} ("${displayTaskName(merged)}")`;
1073
-
1074
- const taskTargets = validateDelegationTargets({
1075
- ctx,
1076
- effectiveCwd: merged.effectiveCwd,
1077
- outputFile: merged.outputFile,
1078
- prefix: taskPrefix,
1079
- });
1080
- if (!taskTargets.ok) return taskTargets.error;
1081
- taskCwds.push(taskTargets.cwd);
1082
-
1083
- const unitValidation = runPreTaskValidation({
1084
- log,
1085
- label: "Parallel",
1086
- 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)}")`,
1087
982
  logContext: { task: i + 1 },
1088
- preTask: {
1089
- task: merged.task,
1090
- toolOptions: merged.toolOptions,
1091
- thinkingLevel: merged.thinkingLevel,
1092
- gitMode: globalParams.resolvedGitMode,
1093
- outputFile: merged.outputFile,
1094
- force: params.force as boolean | undefined,
1095
- },
1096
- });
1097
- if (unitValidation.error) return unitValidation.error;
1098
- for (const w of unitValidation.warnings) taskWarnings.push(`${taskPrefix}: ${w}`);
1099
- }
1100
-
1101
- // Resolve model once (per-call top-level model override beats preset)
1102
- const modelResult = resolveSubagentModel(ctx, globalParams.resolvedPreset, params.model as string | undefined);
1103
- if (!modelResult.ok) return modelResult.error;
1104
- const subagentModel = modelResult.model;
1105
-
1106
- const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
1107
- if (!modelStr || modelStr === "/") {
1108
- log.warn("Model string is empty after resolution", { model: subagentModel });
1109
- return {
1110
- content: [
1111
- {
1112
- type: "text" as const,
1113
- text:
1114
- "Subagent model is not configured. " +
1115
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
1116
- },
1117
- ],
1118
- details: undefined,
1119
- isError: true,
1120
- };
1121
- }
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;
1122
989
 
1123
- // R1: Circuit breaker check — reject if circuit is open
1124
- const circuitCheck = state.checkCircuit();
1125
- if (circuitCheck.isOpen) {
1126
- return {
1127
- content: [
1128
- { type: "text" as const, text: circuitCheck.message! },
1129
- ],
1130
- details: undefined,
1131
- isError: true,
1132
- };
1133
- }
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;
1134
1003
 
1135
1004
  // Build base prompt once
1136
1005
  const basePrompt = ctx.getSystemPrompt();
@@ -1241,17 +1110,8 @@ export default function (pi: ExtensionAPI) {
1241
1110
  run.childMarker,
1242
1111
  );
1243
1112
 
1244
- // Fill SubTaskResult
1245
- subTaskResult.exitCode = result.exitCode;
1246
- subTaskResult.messages = result.messages;
1247
- subTaskResult.stderr = result.stderr;
1248
- subTaskResult.usage = result.usage;
1249
- subTaskResult.model = result.model;
1250
- subTaskResult.stopReason = result.stopReason;
1251
- subTaskResult.errorMessage = result.errorMessage;
1252
- subTaskResult.errorCategory = classifyError(result);
1253
- subTaskResult.gitBranch = result.gitBranch;
1254
- subTaskResult.gitDiff = result.gitDiff;
1113
+ // Fill SubTaskResult (one shared field mapping — issue #376/D3).
1114
+ Object.assign(subTaskResult, toSubTaskResult(result));
1255
1115
 
1256
1116
  results[index] = subTaskResult;
1257
1117
  completedCount++;
@@ -1433,166 +1293,43 @@ export default function (pi: ExtensionAPI) {
1433
1293
  // startedAt (captured once, at mode entry, not at completion).
1434
1294
  const graphModeStartedAt = new Date().toISOString();
1435
1295
 
1436
- // Validate graph
1437
- const errors = validateGraph(graphTasks);
1438
- if (errors.length > 0) {
1439
- return {
1440
- content: [
1441
- {
1442
- type: "text" as const,
1443
- text: `Graph validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`,
1444
- },
1445
- ],
1446
- details: undefined,
1447
- isError: true,
1448
- };
1449
- }
1450
-
1451
- // R5: Check session cost limit before spawning
1452
- 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,
1453
1303
  state,
1454
1304
  ctx,
1455
1305
  log,
1306
+ label: "Graph",
1456
1307
  units: graphTasks.length,
1457
- label: "Graph delegation",
1458
- });
1459
- if (costError) return costError;
1460
-
1461
- // Reject delegation if recursion depth exceeds configured max
1462
- const currentDepth = getCurrentDepth();
1463
- if (currentDepth >= state.config.maxSubagentDepth) {
1464
- log.warn("Graph delegation rejected: max depth reached", {
1465
- currentDepth,
1466
- maxDepth: state.config.maxSubagentDepth,
1467
- });
1468
- return {
1469
- content: [
1470
- {
1471
- type: "text" as const,
1472
- text:
1473
- `Cannot delegate further: subagent recursion depth limit reached ` +
1474
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
1475
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
1476
- },
1477
- ],
1478
- details: undefined,
1479
- isError: true,
1480
- };
1481
- }
1482
-
1483
- // Resolve global params once
1484
- const globalParams = resolveSubagentParams(
1485
- params as {
1486
- task: string;
1487
- label?: string;
1488
- preset?: string;
1489
- systemPrompt?: string;
1490
- inheritSystemPrompt?: boolean;
1491
- thinkingLevel?: string;
1492
- outputFile?: string;
1493
- timeout?: number;
1494
- cwd?: string;
1495
- tools?: string[];
1496
- excludeTools?: string[];
1497
- noBuiltinTools?: boolean;
1498
- gitMode?: string;
1499
- 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")}`);
1500
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({
1501
1324
  state,
1502
1325
  ctx,
1503
1326
  log,
1504
- );
1505
-
1506
- // Validate CWD once
1507
- const cwdResult = validateCwd(globalParams.effectiveCwd, ctx.cwd);
1508
- if (!cwdResult.ok) {
1509
- return {
1510
- content: [
1511
- { type: "text" as const, text: `Invalid cwd: ${cwdResult.error}` },
1512
- ],
1513
- details: undefined,
1514
- isError: true,
1515
- };
1516
- }
1517
- const resolvedCwd = cwdResult.value;
1518
-
1519
- // Pre-flight checks
1520
- const pfResult = preflightCheck(resolvedCwd);
1521
- if (!pfResult.ok) {
1522
- log.warn("Graph pre-flight check failed", { error: pfResult.error });
1523
- return {
1524
- content: [
1525
- {
1526
- type: "text" as const,
1527
- text: `Pre-flight check failed: ${pfResult.error}`,
1528
- },
1529
- ],
1530
- details: undefined,
1531
- isError: true,
1532
- };
1533
- }
1534
-
1535
- // H1: Pre-task validation at mode entry — deterministic check that
1536
- // tools/thinking match the task (mirrors single/background modes, issue
1537
- // #32). Graph top-level tasks are empty (modeCount forbids task+graph),
1538
- // so keyword warnings skip on empty text and only the hard
1539
- // outputFile-vs-write conflict applies (issue #34). The mode-level
1540
- // outputFile on globalParams is the one validated here; every node's own
1541
- // cwd/outputFile/tools are validated by the per-node pre-pass below
1542
- // (issue #222).
1543
- const validation = validatePreTask({
1544
- task: globalParams.task,
1545
- toolOptions: globalParams.toolOptions,
1546
- thinkingLevel: globalParams.thinkingLevel,
1547
- gitMode: globalParams.resolvedGitMode,
1548
- outputFile: globalParams.outputFile,
1327
+ preset: globalParams.resolvedPreset,
1328
+ perCallModel: params.model,
1549
1329
  });
1550
- if (validation.warnings.length > 0) {
1551
- log.warn("Graph pre-task validation warnings", { warnings: validation.warnings });
1552
- }
1553
- if (!validation.valid) {
1554
- const errText = validation.errors.join("; ");
1555
- log.warn("Graph pre-task validation failed", { errors: validation.errors });
1556
- return {
1557
- content: [{ type: "text" as const, text: errText }],
1558
- details: undefined,
1559
- isError: true,
1560
- };
1561
- }
1562
-
1563
- // Resolve model once (per-call top-level model override beats preset)
1564
- const modelResult = resolveSubagentModel(ctx, globalParams.resolvedPreset, params.model as string | undefined);
1565
- if (!modelResult.ok) return modelResult.error;
1566
- const subagentModel = modelResult.model;
1567
-
1568
- const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
1569
- if (!modelStr || modelStr === "/") {
1570
- log.warn("Model string is empty after resolution", { model: subagentModel });
1571
- return {
1572
- content: [
1573
- {
1574
- type: "text" as const,
1575
- text:
1576
- "Subagent model is not configured. " +
1577
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
1578
- },
1579
- ],
1580
- details: undefined,
1581
- isError: true,
1582
- };
1583
- }
1584
-
1585
- // R1: Circuit breaker check
1586
- const circuitCheck = state.checkCircuit();
1587
- if (circuitCheck.isOpen) {
1588
- return {
1589
- content: [
1590
- { type: "text" as const, text: circuitCheck.message! },
1591
- ],
1592
- details: undefined,
1593
- isError: true,
1594
- };
1595
- }
1330
+ if (!tail.ok) return tail.error;
1331
+ const subagentModel = tail.model;
1332
+ const modelStr = tail.modelStr;
1596
1333
 
1597
1334
  // Resolve priority — the FALLBACK for per-unit priority (issue #114): a
1598
1335
  // task-level priority on graph[] items wins per slot; this is the floor.
@@ -1630,57 +1367,30 @@ export default function (pi: ExtensionAPI) {
1630
1367
  // wording is still validated, and refusing to validate up front would
1631
1368
  // mean a bad node in the LAST wave is discovered after every earlier
1632
1369
  // wave already spent its budget.
1633
- const nodeCwds = new Map<string, string>();
1634
- const nodeWarnings: string[] = [];
1635
- for (const graphTask of graphTasks) {
1636
- const merged = mergeSubTaskParams(globalParams, {
1637
- task: graphTask.task,
1638
- label: graphTask.label,
1639
- model: graphTask.model,
1640
- thinkingLevel: graphTask.thinkingLevel,
1641
- priority: graphTask.priority,
1642
- cwd: graphTask.cwd,
1643
- timeout: graphTask.timeout,
1644
- outputFile: graphTask.outputFile,
1645
- tools: graphTask.tools,
1646
- excludeTools: graphTask.excludeTools,
1647
- noBuiltinTools: graphTask.noBuiltinTools,
1648
- systemPrompt: graphTask.systemPrompt,
1649
- inheritSystemPrompt: graphTask.inheritSystemPrompt,
1650
- });
1651
- const nodePrefix = `Node "${graphTask.id}"`;
1652
-
1653
- const nodeTargets = validateDelegationTargets({
1654
- ctx,
1655
- effectiveCwd: merged.effectiveCwd,
1656
- outputFile: merged.outputFile,
1657
- prefix: nodePrefix,
1658
- });
1659
- if (!nodeTargets.ok) return nodeTargets.error;
1660
- nodeCwds.set(graphTask.id, nodeTargets.cwd);
1661
-
1662
- const nodeValidation = runPreTaskValidation({
1663
- log,
1664
- label: "Graph",
1665
- prefix: nodePrefix,
1666
- logContext: { id: graphTask.id },
1667
- preTask: {
1668
- // Placeholder TOKENS stripped (issue #222 review): the rules
1669
- // read the declared string, so a `{<id>}` whose dependency id
1670
- // is a blocking keyword would block on a token, not on text
1671
- // the host wrote. The declared wording around it is unchanged
1672
- // and still validated.
1673
- task: merged.task.replace(GRAPH_OUTPUT_PLACEHOLDER_RE, " "),
1674
- toolOptions: merged.toolOptions,
1675
- thinkingLevel: merged.thinkingLevel,
1676
- gitMode: globalParams.resolvedGitMode,
1677
- outputFile: merged.outputFile,
1678
- force: params.force as boolean | undefined,
1679
- },
1680
- });
1681
- if (nodeValidation.error) return nodeValidation.error;
1682
- for (const w of nodeValidation.warnings) nodeWarnings.push(`${nodePrefix}: ${w}`);
1683
- }
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;
1684
1394
 
1685
1395
  // Build base prompt once
1686
1396
  const basePrompt = ctx.getSystemPrompt();
@@ -1736,21 +1446,7 @@ export default function (pi: ExtensionAPI) {
1736
1446
  // sibling node advances the counter (same-wave siblings run
1737
1447
  // concurrently, so the value must be pinned here).
1738
1448
  const globalNode = ++globalNodeCounter;
1739
- const subTaskParams: SubTaskParams = {
1740
- task: graphTask.task,
1741
- label: graphTask.label,
1742
- model: graphTask.model,
1743
- thinkingLevel: graphTask.thinkingLevel,
1744
- priority: graphTask.priority,
1745
- cwd: graphTask.cwd,
1746
- timeout: graphTask.timeout,
1747
- outputFile: graphTask.outputFile,
1748
- tools: graphTask.tools,
1749
- excludeTools: graphTask.excludeTools,
1750
- noBuiltinTools: graphTask.noBuiltinTools,
1751
- systemPrompt: graphTask.systemPrompt,
1752
- inheritSystemPrompt: graphTask.inheritSystemPrompt,
1753
- };
1449
+ const subTaskParams = graphTaskToSubTaskParams(graphTask);
1754
1450
 
1755
1451
  const merged = mergeSubTaskParams(globalParams, subTaskParams);
1756
1452
  // Issue #222: the node's OWN validated cwd (pre-pass);
@@ -1857,19 +1553,12 @@ export default function (pi: ExtensionAPI) {
1857
1553
  run.childMarker,
1858
1554
  );
1859
1555
 
1556
+ // One shared field mapping — issue #376/D3 (the graph literal was a
1557
+ // third copy of it).
1860
1558
  const subTaskResult: SubTaskResult = {
1861
1559
  task: merged.task,
1862
1560
  label: merged.label,
1863
- exitCode: result.exitCode,
1864
- messages: result.messages,
1865
- stderr: result.stderr,
1866
- usage: result.usage,
1867
- model: result.model,
1868
- stopReason: result.stopReason,
1869
- errorMessage: result.errorMessage,
1870
- errorCategory: classifyError(result),
1871
- gitBranch: result.gitBranch,
1872
- gitDiff: result.gitDiff,
1561
+ ...toSubTaskResult(result),
1873
1562
  };
1874
1563
 
1875
1564
  // Issue #133: finalize the per-node run entry — status, duration,
@@ -2045,26 +1734,7 @@ export default function (pi: ExtensionAPI) {
2045
1734
  if (costError) return costError;
2046
1735
 
2047
1736
  // Resolve global params once — same call shape as runParallelMode.
2048
- const globalParams = resolveSubagentParams(
2049
- params as {
2050
- task: string;
2051
- label?: string;
2052
- preset?: string;
2053
- systemPrompt?: string;
2054
- inheritSystemPrompt?: boolean;
2055
- thinkingLevel?: string;
2056
- outputFile?: string;
2057
- timeout?: number;
2058
- cwd?: string;
2059
- tools?: string[];
2060
- excludeTools?: string[];
2061
- noBuiltinTools?: boolean;
2062
- gitMode?: string;
2063
- },
2064
- state,
2065
- ctx,
2066
- log,
2067
- );
1737
+ const globalParams = resolveSubagentParams(params, state, ctx, log);
2068
1738
 
2069
1739
  // Resolve the global model once (per-call model beats preset/config).
2070
1740
  const globalModelResult = resolveSubagentModel(
@@ -2149,6 +1819,8 @@ export default function (pi: ExtensionAPI) {
2149
1819
  gitMode: globalParams.resolvedGitMode,
2150
1820
  outputFile: merged.outputFile,
2151
1821
  force: params.force as boolean | undefined,
1822
+ cwd: targets.cwd,
1823
+ noJev: params.noJev,
2152
1824
  },
2153
1825
  });
2154
1826
  if (preTask.error) return preTask.error;
@@ -2287,6 +1959,9 @@ export default function (pi: ExtensionAPI) {
2287
1959
  thinkingLevel: ThinkingLevel;
2288
1960
  priority?: string;
2289
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;
2290
1965
  cwd: string;
2291
1966
  toolOptions?: SubagentToolOptions;
2292
1967
  timeout?: number;
@@ -2319,6 +1994,7 @@ export default function (pi: ExtensionAPI) {
2319
1994
  // run entry + drill-in header carry it like foreground runs.
2320
1995
  priority: spawn.priority,
2321
1996
  systemPrompt: spawn.systemPrompt,
1997
+ resumeContext: spawn.resumeContext,
2322
1998
  cwd: spawn.cwd,
2323
1999
  toolOptions: spawn.toolOptions,
2324
2000
  timeout: spawn.timeout,
@@ -2362,7 +2038,7 @@ export default function (pi: ExtensionAPI) {
2362
2038
 
2363
2039
  // Update footer counters
2364
2040
  state.activeSubagents++;
2365
- updateProgressStatus(state, ctx);
2041
+ repaintStatus(state, ctx);
2366
2042
 
2367
2043
  let completed = false;
2368
2044
 
@@ -2394,7 +2070,7 @@ export default function (pi: ExtensionAPI) {
2394
2070
  if (state.activeSubagents < 0) state.activeSubagents = 0;
2395
2071
  }
2396
2072
  state.failedSubagents++;
2397
- updateProgressStatus(state, ctx);
2073
+ repaintStatus(state, ctx);
2398
2074
  sendCrashNotice(`Background agent "${agent.description}" crashed.`);
2399
2075
  return;
2400
2076
  }
@@ -2441,7 +2117,7 @@ export default function (pi: ExtensionAPI) {
2441
2117
 
2442
2118
  if (agent.status === 'failed') {
2443
2119
  state.failedSubagents++;
2444
- updateProgressStatus(state, ctx);
2120
+ repaintStatus(state, ctx);
2445
2121
  // Issue #315: the terminal wake (`subagent-completion`, emitted by
2446
2122
  // the session-manager settle) is the ONE notice for a failed run.
2447
2123
  // The status here was set by that settle, so the wake already
@@ -2449,11 +2125,11 @@ export default function (pi: ExtensionAPI) {
2449
2125
  } else if (agent.status === 'stopped') {
2450
2126
  // User-initiated stop (stop_subagent) or deadline abort
2451
2127
  // (timeout/deadline) — not a failure.
2452
- updateProgressStatus(state, ctx);
2128
+ repaintStatus(state, ctx);
2453
2129
  } else {
2454
2130
  state.completedSubagents++;
2455
2131
  state.unseenSubagents++;
2456
- updateProgressStatus(state, ctx);
2132
+ repaintStatus(state, ctx);
2457
2133
  }
2458
2134
  }
2459
2135
  } catch (err) {
@@ -2472,7 +2148,7 @@ export default function (pi: ExtensionAPI) {
2472
2148
  if (state.activeSubagents < 0) state.activeSubagents = 0;
2473
2149
  }
2474
2150
  state.failedSubagents++;
2475
- updateProgressStatus(state, ctx);
2151
+ repaintStatus(state, ctx);
2476
2152
  sendCrashNotice(`Background agent "${agent.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
2477
2153
  }
2478
2154
  }
@@ -2517,7 +2193,7 @@ export default function (pi: ExtensionAPI) {
2517
2193
  }
2518
2194
  // m6: deadline abort is a stop, not a completion — mirror the
2519
2195
  // W3/poller stopped path (no completedSubagents increment).
2520
- updateProgressStatus(state, ctx);
2196
+ repaintStatus(state, ctx);
2521
2197
  } catch (err) {
2522
2198
  // Defensive: never let the deadline timer throw uncaught — that would
2523
2199
  // skip finalizeLiveSubagent, the counter decrement, and the notification.
@@ -2543,7 +2219,7 @@ export default function (pi: ExtensionAPI) {
2543
2219
  if (state.activeSubagents < 0) state.activeSubagents = 0;
2544
2220
  }
2545
2221
  state.failedSubagents++;
2546
- updateProgressStatus(state, ctx);
2222
+ repaintStatus(state, ctx);
2547
2223
  }
2548
2224
  }
2549
2225
  }, hardCapMs);
@@ -2561,16 +2237,29 @@ export default function (pi: ExtensionAPI) {
2561
2237
  async function spawnBackgroundRun(
2562
2238
  pi: ExtensionAPI,
2563
2239
  ctx: ExtensionContext,
2564
- params: Omit<Parameters<typeof resolveSubagentParams>[0], "task"> & {
2565
- task?: string;
2566
- model?: string;
2567
- priority?: string;
2568
- },
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>,
2569
2249
  singleTask: string,
2570
2250
  // Option B U1: the spawn entry a retryRunId resolved to, so a retried
2571
2251
  // background run inherits dispatchId/resumeOf/attempt (record identity,
2572
2252
  // not a delegate param — D4).
2573
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,
2574
2263
  ): Promise<ToolResult<undefined>> {
2575
2264
  // Phase 6.5: Background execution — spawn session and return ID immediately.
2576
2265
  // Resolve the preset and its model BEFORE the background branch so the
@@ -2636,6 +2325,8 @@ export default function (pi: ExtensionAPI) {
2636
2325
  gitMode: bgResolved.resolvedGitMode,
2637
2326
  outputFile: bgResolvedOutputFile,
2638
2327
  force: params.force,
2328
+ cwd: targets.cwd,
2329
+ noJev: params.noJev,
2639
2330
  },
2640
2331
  });
2641
2332
  if (bgPreTask.error) return bgPreTask.error;
@@ -2654,7 +2345,12 @@ export default function (pi: ExtensionAPI) {
2654
2345
  // Option B U1: durability identity (retry inherits the original dispatch).
2655
2346
  const bgIdentity = newDispatchIdentity(retrySourceRun);
2656
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.
2657
2352
  task: singleTask,
2353
+ resumeContext: attemptContext,
2658
2354
  type: params.preset || 'general-purpose',
2659
2355
  description: params.label,
2660
2356
  model: bgModel,
@@ -2665,7 +2361,9 @@ export default function (pi: ExtensionAPI) {
2665
2361
  toolOptions: bgResolved.toolOptions,
2666
2362
  timeout: bgResolved.timeout,
2667
2363
  gitMode: bgResolved.resolvedGitMode,
2668
- originalParams: snapshotOriginalParams(params),
2364
+ originalParams: attemptContext
2365
+ ? { ...snapshotOriginalParams(params), task: singleTask }
2366
+ : snapshotOriginalParams(params),
2669
2367
  sanitizeCwd: bgResolved.effectiveCwd,
2670
2368
  dispatchId: bgIdentity.dispatchId,
2671
2369
  resumeOf: bgIdentity.resumeOf,
@@ -2822,8 +2520,8 @@ export default function (pi: ExtensionAPI) {
2822
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.`,
2823
2521
  buildTemplateGuideline(templateSummary),
2824
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.",
2825
- "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.",
2826
- "Set background: true to run the subagent in the background without blocking. The tool returns immediately with an agent ID. With tasks, background fans out: every task starts as its own background agent, the call returns one ID per task in task order, and the conductor is woken once per agent as each finishes; chain and graph cannot be combined with background (rejected). 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.",
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.",
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.",
2827
2525
  "",
2828
2526
  "## Conductor Guardrails",
2829
2527
  "",
@@ -3026,12 +2724,91 @@ export default function (pi: ExtensionAPI) {
3026
2724
  };
3027
2725
  }
3028
2726
 
2727
+ const dispatchShape: DispatchShape = isChain
2728
+ ? "chain"
2729
+ : isGraph
2730
+ ? "graph"
2731
+ : isParallel
2732
+ ? "parallel"
2733
+ : "single";
2734
+
2735
+ // Capture the caller's value BEFORE the default is recorded on
2736
+ // `params.background` below. The guard must judge what the caller
2737
+ // actually asked for; reading the recorded value would make it depend
2738
+ // on the default. Keeping the capture first makes that ordering
2739
+ // self-evident (issue #361 review).
2740
+ const explicitBackground = params.background;
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
+
3029
2804
  // background: true with chain/graph was silently ignored — the batch ran
3030
2805
  // foreground (blocking until every unit finished) while the caller believed
3031
2806
  // it was background. Both remain rejected loudly at dispatch validation;
3032
2807
  // tasks (parallel) fans out into independent background agents instead.
3033
- if (params.background && (isChain || isGraph)) {
3034
- const batchMode = isChain ? "chain" : "graph";
2808
+ // Only an EXPLICIT true trips this (issue #361): an omitted `background`
2809
+ // now defaults to foreground here rather than being rejected.
2810
+ if (shouldRejectBackgroundForBatch(dispatchShape, explicitBackground)) {
2811
+ const batchMode = dispatchShape === "chain" ? "chain" : "graph";
3035
2812
  return {
3036
2813
  content: [
3037
2814
  {
@@ -3044,6 +2821,24 @@ export default function (pi: ExtensionAPI) {
3044
2821
  };
3045
2822
  }
3046
2823
 
2824
+ // Issue #361: background is the CONDITIONAL default for the shapes that
2825
+ // can run unattended. Resolved ONCE per dispatch and reused by the
2826
+ // single and fan-out paths below, so the decision cannot drift between
2827
+ // them. The approval mode is the EFFECTIVE one (call param, else the
2828
+ // configured default — presets declare no approvalMode today) — the same
2829
+ // value the child will run with — so the default never routes a run into a
2830
+ // background context that would break or silently auto-approve it
2831
+ // ('always' has no dialog; 'writes' gates the diff on approval).
2832
+ const useBackground =
2833
+ params.background ??
2834
+ defaultBackgroundFor(dispatchShape, resolveEffectiveApprovalMode(params.approvalMode, state));
2835
+ // Record the EFFECTIVE value on the dispatch (a no-op when the caller was
2836
+ // explicit): a run started by the default must retry as what it actually
2837
+ // was instead of re-deriving the default, which may since have moved with
2838
+ // the config. Fan-out units still record no background of their own — a
2839
+ // unit retries as a single foreground run (issue #229), unaffected here.
2840
+ params.background ??= useBackground;
2841
+
3047
2842
  if (isChain) {
3048
2843
  if (params.chain!.length > MAX_CHAIN_STEPS) {
3049
2844
  return {
@@ -3073,7 +2868,7 @@ export default function (pi: ExtensionAPI) {
3073
2868
  isError: true,
3074
2869
  };
3075
2870
  }
3076
- if (params.background) return runBackgroundFanOut(pi, ctx, params, signal);
2871
+ if (useBackground) return runBackgroundFanOut(pi, ctx, params, signal);
3077
2872
  return runParallelMode(params, signal, onUpdate, ctx);
3078
2873
  }
3079
2874
 
@@ -3086,7 +2881,7 @@ export default function (pi: ExtensionAPI) {
3086
2881
  // boolean-array filter — assert, mirroring params.chain!/params.tasks! above.
3087
2882
  const singleTask = params.task!; // non-empty (sanitizer guarantees; isSingle confirms)
3088
2883
 
3089
- if (params.background) {
2884
+ if (useBackground) {
3090
2885
  return spawnBackgroundRun(pi, ctx, params, singleTask, retrySourceRun);
3091
2886
  }
3092
2887
 
@@ -3110,19 +2905,7 @@ export default function (pi: ExtensionAPI) {
3110
2905
  currentDepth,
3111
2906
  maxDepth: state.config.maxSubagentDepth,
3112
2907
  });
3113
- return {
3114
- content: [
3115
- {
3116
- type: "text" as const,
3117
- text:
3118
- `Cannot delegate further: subagent recursion depth limit reached ` +
3119
- `(depth ${currentDepth}/${state.config.maxSubagentDepth}). ` +
3120
- `Subagents can delegate up to ${state.config.maxSubagentDepth} levels deep (configurable via /brl-subagent depth). Complete the remaining work directly.`,
3121
- },
3122
- ],
3123
- details: undefined,
3124
- isError: true,
3125
- };
2908
+ return depthLimitRejection(currentDepth, state.config.maxSubagentDepth);
3126
2909
  }
3127
2910
 
3128
2911
  const {
@@ -3189,6 +2972,8 @@ export default function (pi: ExtensionAPI) {
3189
2972
  gitMode: resolvedGitMode,
3190
2973
  outputFile: resolvedOutputFile,
3191
2974
  force: params.force,
2975
+ cwd: resolvedCwd,
2976
+ noJev: params.noJev,
3192
2977
  });
3193
2978
  if (validation.warnings.length > 0) {
3194
2979
  log.warn("Pre-task validation warnings", { warnings: validation.warnings });
@@ -3218,18 +3003,7 @@ export default function (pi: ExtensionAPI) {
3218
3003
  const modelStr = `${subagentModel.provider}/${subagentModel.id}`.trim();
3219
3004
  if (!modelStr || modelStr === "/") {
3220
3005
  log.warn("Model string is empty after resolution", { model: subagentModel });
3221
- return {
3222
- content: [
3223
- {
3224
- type: "text" as const,
3225
- text:
3226
- "Subagent model is not configured. " +
3227
- "Use /brl-subagent to set a model, or ensure your current session has a valid model.",
3228
- },
3229
- ],
3230
- details: undefined,
3231
- isError: true,
3232
- };
3006
+ return modelNotConfiguredRejection();
3233
3007
  }
3234
3008
 
3235
3009
  // Create run record
@@ -3775,19 +3549,7 @@ export default function (pi: ExtensionAPI) {
3775
3549
  },
3776
3550
 
3777
3551
  renderCall(
3778
- args: {
3779
- task?: string;
3780
- label?: string;
3781
- systemPrompt?: string;
3782
- inheritSystemPrompt?: boolean;
3783
- thinkingLevel?: string;
3784
- outputFile?: string;
3785
- timeout?: number;
3786
- cwd?: string;
3787
- tools?: string[];
3788
- excludeTools?: string[];
3789
- noBuiltinTools?: boolean;
3790
- },
3552
+ args: DelegateTaskParams,
3791
3553
  theme: Theme,
3792
3554
  _context: unknown,
3793
3555
  ) {
@@ -3814,6 +3576,8 @@ export default function (pi: ExtensionAPI) {
3814
3576
  description: [
3815
3577
  "Check the status of a background agent and retrieve its result.",
3816
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.",
3817
3581
  "Returns the agent's status, result (if completed), and transcript path.",
3818
3582
  ].join(" "),
3819
3583
  parameters: Type.Object({
@@ -3827,14 +3591,64 @@ export default function (pi: ExtensionAPI) {
3827
3591
  ),
3828
3592
  }),
3829
3593
  execute: async (toolCallId, params) => {
3830
- const { getAgent } = await import('./session-manager');
3594
+ const { getAgent, resolveAgentId, findRetryLineage, isTerminalAgentStatus, RETRY_SCAN_WINDOW_MS, RETRY_SCAN_WINDOW_DAYS } = await import('./session-manager');
3831
3595
  const { getTranscript } = await import('./transcript');
3832
-
3833
- 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);
3834
3623
 
3835
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.`;
3836
3647
  return {
3837
- 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
+ }],
3838
3652
  details: undefined,
3839
3653
  isError: true,
3840
3654
  };
@@ -3852,6 +3666,22 @@ export default function (pi: ExtensionAPI) {
3852
3666
  if (agent.error) {
3853
3667
  resultText += `Error: ${agent.error}\n`;
3854
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
+ }
3855
3685
 
3856
3686
  if (agent.result) {
3857
3687
  resultText += `\nResult:\n`;
@@ -3878,7 +3708,7 @@ export default function (pi: ExtensionAPI) {
3878
3708
 
3879
3709
  // Include transcript if verbose
3880
3710
  if (params.verbose) {
3881
- const transcript = getTranscript(params.agent_id);
3711
+ const transcript = getTranscript(agentId);
3882
3712
  if (transcript.length > 0) {
3883
3713
  resultText += `\n\nTranscript (${transcript.length} entries):\n`;
3884
3714
  for (const entry of transcript.slice(-10)) { // Last 10 entries
@@ -3888,7 +3718,7 @@ export default function (pi: ExtensionAPI) {
3888
3718
  }
3889
3719
 
3890
3720
  // Include transcript path
3891
- resultText += `\nTranscript: ${transcriptDisplayPath(params.agent_id)}`;
3721
+ resultText += `\nTranscript: ${transcriptDisplayPath(agentId)}`;
3892
3722
 
3893
3723
  return {
3894
3724
  content: [{ type: "text" as const, text: resultText }],
@@ -4187,7 +4017,10 @@ export default function (pi: ExtensionAPI) {
4187
4017
  // run ONCE, at the next turn boundary (never mid-turn).
4188
4018
  await maybeSendRecoveryNotice(ctx);
4189
4019
 
4190
- updateStatus(state, ctx);
4020
+ // Issue #356: boot is a config-paint edge — route it through the same
4021
+ // chokepoint as every other footer repaint. With no runs in flight the
4022
+ // chokepoint draws the idle config line the old direct call painted.
4023
+ repaintStatus(state, ctx);
4191
4024
  });
4192
4025
 
4193
4026
  // F7: Clean up session-bound state on shutdown
@@ -4204,19 +4037,7 @@ export default function (pi: ExtensionAPI) {
4204
4037
  log.warn("Shutdown reap failed", { error: (err as Error).message });
4205
4038
  }
4206
4039
 
4207
- // Clear all live subagent sessions
4208
- state.subagentSessions.clear();
4209
- // Drop pending finalize claims too (PR #71 review: the claim set must
4210
- // not outlive the map it guards — a fresh session could otherwise
4211
- // no-op on an id a stale claim still remembers).
4212
- state.resetLiveFinalizeClaims();
4213
- // Reset counters
4214
- state.activeSubagents = 0;
4215
- state.completedSubagents = 0;
4216
- state.failedSubagents = 0;
4217
- state.unseenSubagents = 0;
4218
- // Clear pending queue
4219
- state.pendingQueue.length = 0;
4040
+ cleanupSessionState(state);
4220
4041
  // U3: a new session boot may notify again.
4221
4042
  recoveryNoticeDelivered = false;
4222
4043
  });
@@ -4247,6 +4068,76 @@ export default function (pi: ExtensionAPI) {
4247
4068
  });
4248
4069
  }
4249
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
+
4250
4141
  async function deliverCompletionAlert(event: SubagentEvent): Promise<void> {
4251
4142
  const id = event.agentId;
4252
4143
  if (!claimTerminalNotice(id)) return;
@@ -4258,6 +4149,14 @@ export default function (pi: ExtensionAPI) {
4258
4149
  if (!agent) return; // pruned or foreign id — nothing to notify
4259
4150
  const knob = state.config.completionNotify ?? "all";
4260
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
+ }
4261
4160
  const message = buildCompletionMessage(agent, run);
4262
4161
  // Issue #179 (D2): resolve delivery from the CLASSIFIED notification
4263
4162
  // status, not the raw agent status — otherwise a run whose completion