brl-subagent 2.8.0 → 2.9.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.
Files changed (47) hide show
  1. package/AGENT.md +1 -1
  2. package/README.md +3 -3
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +3 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +1 -1
  11. package/src/git.ts +220 -8
  12. package/src/headstate.ts +3 -3
  13. package/src/history.ts +21 -3
  14. package/src/index.ts +109 -4473
  15. package/src/loader.ts +1 -1
  16. package/src/logging.ts +1 -1
  17. package/src/mode-prologue.ts +4 -10
  18. package/src/mode-runners.ts +1575 -0
  19. package/src/notify-completion.ts +35 -8
  20. package/src/params.ts +14 -13
  21. package/src/preflight.ts +123 -16
  22. package/src/prelude.ts +14 -5
  23. package/src/presets.ts +3 -5
  24. package/src/proc.ts +2 -3
  25. package/src/recovery-engine.ts +1 -1
  26. package/src/recovery-surface.ts +1 -2
  27. package/src/recovery.ts +2 -3
  28. package/src/reports.ts +1 -7
  29. package/src/run-registry.ts +2 -3
  30. package/src/runner.ts +47 -18
  31. package/src/runtime.ts +50 -0
  32. package/src/sanitize.ts +20 -2
  33. package/src/scheduler.ts +1 -2
  34. package/src/scratch-root.ts +909 -0
  35. package/src/scratch-spawn.ts +256 -0
  36. package/src/session-manager.ts +75 -7
  37. package/src/state.ts +12 -14
  38. package/src/templates.ts +3 -5
  39. package/src/terminal-notifier.ts +405 -0
  40. package/src/transcript.ts +1 -1
  41. package/src/tui-format.ts +3 -1
  42. package/src/tui.ts +42 -32
  43. package/src/types.ts +29 -3
  44. package/src/unit-params.ts +113 -0
  45. package/src/unit-run.ts +35 -15
  46. package/src/validate.ts +2 -3
  47. package/src/worktree-report.ts +142 -0
@@ -0,0 +1,1025 @@
1
+ // Purpose: The background pipeline — the fan-out handler, the shared spawn tail and the single-background spawn — built over one runtime context.
2
+ /**
3
+ * brl-subagent — the background pipeline (cycle S3, ADR 0027 D3/D6)
4
+ *
5
+ * `runBackgroundFanOut`, `startBackgroundAgent` and `spawnBackgroundRun` used to
6
+ * be closures inside `src/index.ts`'s default export: ~830 lines of the
7
+ * composition root that owned the background lifecycle (spawns, session refs,
8
+ * live records, abort/settle). They move here verbatim.
9
+ *
10
+ * D3: this module may import the `src/*.ts` modules it needs, and NOT the
11
+ * composition root — `architecture-rules` forbids a non-entry module importing
12
+ * `index.ts`. The three bindings the moved bodies read from their old closure
13
+ * (`pi`, `log`, `state`) arrive as the `RuntimeContext` argument, and the three
14
+ * capabilities the moved bodies cannot reach from here arrive as `deps`:
15
+ *
16
+ * - `loadSessionManager` is the seam ADR 0027 D3 forces. `startBackgroundAgent`
17
+ * awaits `spawnBackgroundSession`, `setAgentFinalOutput` and
18
+ * `extractFinalOutput` — session-manager LIFECYCLE MUTATORS, which
19
+ * `architecture-rules` ("non-entry modules take only the reader API") forbids
20
+ * a non-entry module to import. The thunk is awaited at the ORIGINAL
21
+ * statement position, so the lazy-load timing and the rejection path that the
22
+ * two callers already translate into their own failure shape are unchanged.
23
+ * - `resolveStepModel` and `applyUnitShapeGuard` live in `mode-runners.ts` (S2)
24
+ * and the fan-out's per-task pre-pass/spawn loop calls both.
25
+ *
26
+ * `deps` carries FUNCTION fields only; no data (ADR 0027 F2), and the context is
27
+ * exactly the three fields `runtime.ts` declares — a fourth would mean the split
28
+ * is wrong (ADR 0027 F1), not that this interface should widen.
29
+ *
30
+ * The move is verbatim. `createBackgroundPipeline` destructures its context on
31
+ * its first lines and the bodies carry their original indentation, so a body line
32
+ * that differs from 156d238 is a bug in this commit, not a refactor. The three
33
+ * deliberate non-verbatim edits are named in the PR: the retired
34
+ * `resolveSubagentModel` wrapper (explicit `resolveSubagentModelPrecedence`
35
+ * arguments), the loader thunk, and the spawn request shape lifted to
36
+ * `BackgroundAgentSpawnRequest` so the returned interface reuses it instead of
37
+ * restating 25 lines.
38
+ */
39
+
40
+ import type { BatchGuardContext } from "./mode-runners";
41
+ import type { RuntimeContext } from "./runtime";
42
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
43
+ import { repaintStatus } from "./concurrency";
44
+ import { resolveRetryParams } from "./history";
45
+ import { buildMonitoringDegradedParagraph, claimTerminalNotice, sendMonitoringDegradedAdvisory } from "./notify-completion";
46
+ import { resolveDispatchPreset, resolveSubagentParams, snapshotOriginalParams } from "./params";
47
+ import {
48
+ formatValidationWarnings,
49
+ gateSessionCost,
50
+ invalidThinkingLevelRejection,
51
+ rejectApprovalAlwaysInBackground,
52
+ resolveSubagentModelPrecedence,
53
+ runPreTaskValidation,
54
+ validateDelegationTargets,
55
+ } from "./prelude";
56
+ import { formatPresetRestriction, formatToolRestriction } from "./presets";
57
+ import { buildSubagentPrompt } from "./prompt";
58
+ import { newDispatchIdentity } from "./recovery";
59
+ import { clearInflightRun } from "./run-registry";
60
+ import { sanitizeErrorMessage } from "./sanitize";
61
+ import {
62
+ declaredThinkingLevel,
63
+ type BackgroundAgent,
64
+ type BackgroundAgentIdentity,
65
+ type BackgroundAgentSpawnResult,
66
+ type DelegateTaskParams,
67
+ type GitMode,
68
+ type RecoveryMode,
69
+ type SubagentResult,
70
+ type SubagentRun,
71
+ type SubagentToolOptions,
72
+ type SubTaskParams,
73
+ type ThinkingLevel,
74
+ type ToolResult,
75
+ } from "./types";
76
+ import { displayTaskName, mergeSubTaskParams, type MergedSubTaskParams } from "./unit-params";
77
+
78
+ /**
79
+ * The session-manager lifecycle mutators `startBackgroundAgent` needs, named
80
+ * through the module's own types rather than restated (a signature drift there
81
+ * is a compile error here). Never imported: the composition root passes them in
82
+ * through `loadSessionManager`, which is the one place allowed to reach them.
83
+ */
84
+ export interface SessionManagerSpawnDeps {
85
+ spawnBackgroundSession: (typeof import("./session-manager"))["spawnBackgroundSession"];
86
+ setAgentFinalOutput: (typeof import("./session-manager"))["setAgentFinalOutput"];
87
+ extractFinalOutput: (typeof import("./session-manager"))["extractFinalOutput"];
88
+ }
89
+
90
+ /**
91
+ * The capabilities the moved bodies cannot reach from this module: the lazy
92
+ * session-manager load, and the two unit helpers `mode-runners.ts` owns (S2).
93
+ * Function fields only — no data crosses this seam (ADR 0027 F2).
94
+ */
95
+ export interface BackgroundPipelineDeps {
96
+ /**
97
+ * Injected so this module never imports session-manager's lifecycle
98
+ * mutators. Called at the top of `startBackgroundAgent` and awaited there, so
99
+ * a rejected load rejects that function — the two callers classify it.
100
+ */
101
+ loadSessionManager: () => Promise<SessionManagerSpawnDeps>;
102
+ /** C3: per-unit model override (step.model > global resolved model). */
103
+ resolveStepModel: (
104
+ ctx: ExtensionContext,
105
+ stepModel: string | undefined,
106
+ globalModel: { provider: string; id: string },
107
+ ) => { provider: string; id: string };
108
+ /** Issue #434: the dispatch pre-flight's unit projection. */
109
+ applyUnitShapeGuard: (
110
+ ctx: ExtensionContext,
111
+ guard: BatchGuardContext,
112
+ step: SubTaskParams,
113
+ merged: MergedSubTaskParams,
114
+ ) => void;
115
+ }
116
+
117
+ /**
118
+ * `startBackgroundAgent`'s request. Named at module scope because the returned
119
+ * interface declares the same function: one shape, declared once.
120
+ */
121
+ interface BackgroundAgentSpawnRequest {
122
+ task: string;
123
+ type?: string;
124
+ description?: string;
125
+ model?: string;
126
+ thinkingLevel: ThinkingLevel;
127
+ priority?: string;
128
+ systemPrompt: string;
129
+ /** Issue #411: conductor-authored resume context for an auto-retry,
130
+ * delivered on the system-prompt side (never inside the task fence). */
131
+ resumeContext?: string;
132
+ cwd: string;
133
+ toolOptions?: SubagentToolOptions;
134
+ timeout?: number;
135
+ gitMode: GitMode;
136
+ originalParams?: SubagentRun["originalParams"];
137
+ /** cwd used to redact paths from crash notifications. */
138
+ sanitizeCwd: string;
139
+ // Option B U1: durability identity threaded onto the background records.
140
+ dispatchId?: string;
141
+ resumeOf?: string;
142
+ attempt?: number;
143
+ // Option B U3 (D4): recovery posture snapshot for the background run.
144
+ recoveryPosture?: RecoveryMode;
145
+ }
146
+
147
+ /**
148
+ * The three functions `createBackgroundPipeline` hands the composition root.
149
+ * Declared once as the module's public contract rather than inferred: the return
150
+ * statement is checked against it, so a signature that drifts is a compile error
151
+ * here instead of a surprise at the `execute` call site.
152
+ */
153
+ interface BackgroundPipeline {
154
+ runBackgroundFanOut: (
155
+ pi: ExtensionAPI,
156
+ ctx: ExtensionContext,
157
+ params: DelegateTaskParams,
158
+ signal: AbortSignal | undefined,
159
+ guard: BatchGuardContext,
160
+ ) => Promise<ToolResult<SubagentResult | undefined>>;
161
+ startBackgroundAgent: (
162
+ pi: ExtensionAPI,
163
+ ctx: ExtensionContext,
164
+ spawn: BackgroundAgentSpawnRequest,
165
+ ) => Promise<BackgroundAgentSpawnResult>;
166
+ spawnBackgroundRun: (
167
+ pi: ExtensionAPI,
168
+ ctx: ExtensionContext,
169
+ params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
170
+ singleTask: string,
171
+ retrySourceRun?: SubagentRun,
172
+ attemptContext?: string,
173
+ ) => Promise<ToolResult<undefined>>;
174
+ }
175
+
176
+ /**
177
+ * Build the background pipeline over one runtime context (ADR 0027 D1/D3).
178
+ *
179
+ * The two destructures are the whole point of the wrapper: they re-create, as
180
+ * locals, the names the bodies read from their old closure, so every moved
181
+ * statement stays byte-identical. `pi` is NOT among them — all three moved
182
+ * bodies take it as a parameter, so the composition root supplies it exactly
183
+ * where it did before and a destructured `pi` would be a dead binding.
184
+ *
185
+ * Nothing else is captured: the factory allocates no state of its own, so two
186
+ * contexts produce two independent pipelines over two independent stores (the
187
+ * S3 boundary test pins that).
188
+ */
189
+ export function createBackgroundPipeline(
190
+ rt: RuntimeContext,
191
+ deps: BackgroundPipelineDeps,
192
+ ): BackgroundPipeline {
193
+ const { log, state } = rt;
194
+ const { resolveStepModel, applyUnitShapeGuard } = deps;
195
+
196
+ // -------------------------------------------------------------------
197
+ // runBackgroundFanOut — background fan-out for tasks mode.
198
+ // Resolves + validates the WHOLE batch up front (no spawn on any
199
+ // failure), then spawns the tasks sequentially, in task order, through the
200
+ // shared startBackgroundAgent tail, and returns immediately with their ids.
201
+ // Foreground-only gates (preflight, circuit breaker, recursion depth) are
202
+ // deliberately skipped — the single-background path skips them too.
203
+ // -------------------------------------------------------------------
204
+
205
+ async function runBackgroundFanOut(
206
+ pi: ExtensionAPI,
207
+ ctx: ExtensionContext,
208
+ params: DelegateTaskParams,
209
+ signal: AbortSignal | undefined,
210
+ guard: BatchGuardContext,
211
+ ): Promise<ToolResult<SubagentResult | undefined>> {
212
+ const taskList: SubTaskParams[] = params.tasks!;
213
+
214
+ // Session cost limit gates the WHOLE batch before any spawn — same
215
+ // estimate/limit logic as runParallelMode, scaled by task count.
216
+ const costError = gateSessionCost({
217
+ state,
218
+ ctx,
219
+ log,
220
+ units: taskList.length,
221
+ label: "Background fan-out",
222
+ });
223
+ if (costError) return costError;
224
+
225
+ // Resolve global params once — same call shape as runParallelMode.
226
+ const globalParams = resolveSubagentParams(params, state, ctx, log);
227
+
228
+ // Resolve the global model once (per-call model beats preset/config).
229
+ // ADR 0027 (S3): the retired `resolveSubagentModel` wrapper called the
230
+ // precedence chain with a positional (ctx, presets, per-call) shape; the
231
+ // call is spelled out here so this module depends on the chain directly.
232
+ const globalModelResult = resolveSubagentModelPrecedence({
233
+ state,
234
+ ctx,
235
+ log,
236
+ preset: globalParams.resolvedPreset,
237
+ perCallModel: params.model as string | undefined,
238
+ });
239
+ if (!globalModelResult.ok) return globalModelResult.error;
240
+ const globalModel = globalModelResult.model;
241
+
242
+ // Same rejection as the single-background path: approvalMode 'always'
243
+ // cannot work in background — there is no interactive dialog to approve
244
+ // the diff, for any of the N agents.
245
+ const approvalError = rejectApprovalAlwaysInBackground(globalParams.resolvedApprovalMode);
246
+ if (approvalError) return approvalError;
247
+ // W5 parity with the single-background path: 'writes' silently
248
+ // auto-approves in background — warn once so the caller knows none of
249
+ // the N agents' diffs will be gated on approval.
250
+ if (globalParams.resolvedApprovalMode === 'writes') {
251
+ log.warn("Background fan-out spawned with approvalMode 'writes' — auto-approving (no dialog in background)", {
252
+ tasks: taskList.length,
253
+ });
254
+ }
255
+
256
+ // gitMode 'branch' is rejected for the whole batch: the per-repository
257
+ // git lock is awaited inside the first spawn and held until that agent
258
+ // settles, so same-repository branch-mode spawns would serialize and
259
+ // block this call for the whole chain. The rule is blanket (not
260
+ // per-repository-checked) because the lock is keyed by the resolved
261
+ // repository root: units in different directories of one repo share the
262
+ // working tree and contend for the same lock.
263
+ if (globalParams.resolvedGitMode === 'branch') {
264
+ return {
265
+ content: [{ type: "text" as const, text:
266
+ `Cannot start ${taskList.length} background agents with gitMode 'branch': the per-repository git lock ` +
267
+ `is awaited by the first spawn and held until that agent settles, so same-repository branch-mode ` +
268
+ `spawns would serialize and block this call for the whole chain. Background fan-out therefore ` +
269
+ `rejects gitMode 'branch' for all tasks in this version. Use gitMode 'none' for the batch, or ` +
270
+ `dispatch each unit as a separate single-task background call.`
271
+ }],
272
+ details: undefined,
273
+ isError: true,
274
+ };
275
+ }
276
+
277
+ // Per-task pre-pass: resolve + validate EVERYTHING before any spawn, so a
278
+ // single bad task rejects the whole batch with nothing started.
279
+ type FanOutTask = {
280
+ merged: MergedSubTaskParams;
281
+ model: { provider: string; id: string };
282
+ cwd: string;
283
+ outputFile: string | undefined;
284
+ };
285
+
286
+ const fanOutTasks: FanOutTask[] = [];
287
+ // C: per-task warnings collect here to ride the immediate spawn result.
288
+ const taskWarnings: string[] = [];
289
+ for (let i = 0; i < taskList.length; i++) {
290
+ const merged = mergeSubTaskParams(globalParams, taskList[i], state.config.maxThinkingLevel);
291
+ const name = displayTaskName(merged);
292
+ const taskPrefix = `Task ${i + 1} ("${name}")`;
293
+ // Issue #443: the DECLARED per-task level — `merged.thinkingLevel` is
294
+ // already resolved, so an unknown declaration is indistinguishable from
295
+ // an omitted one by the time the spawn pass reads it. Checked here, in
296
+ // the all-before-any-spawn pass, so a bad SECOND task rejects the whole
297
+ // batch with nothing started.
298
+ const declaredThinkingError = invalidThinkingLevelRejection(
299
+ taskList[i].thinkingLevel,
300
+ taskPrefix,
301
+ );
302
+ if (declaredThinkingError) return declaredThinkingError;
303
+ // Per-task model override wins; the global model is the fallback.
304
+ const stepModel = resolveStepModel(ctx, merged.model, globalModel);
305
+
306
+ const targets = validateDelegationTargets({
307
+ ctx,
308
+ effectiveCwd: merged.effectiveCwd,
309
+ outputFile: merged.outputFile,
310
+ prefix: taskPrefix,
311
+ });
312
+ if (!targets.ok) return targets.error;
313
+
314
+ const preTask = runPreTaskValidation({
315
+ log,
316
+ label: "Background fan-out",
317
+ prefix: taskPrefix,
318
+ logContext: { task: i + 1 },
319
+ preTask: {
320
+ task: merged.task,
321
+ toolOptions: merged.toolOptions,
322
+ thinkingLevel: merged.thinkingLevel,
323
+ gitMode: globalParams.resolvedGitMode,
324
+ outputFile: merged.outputFile,
325
+ force: params.force as boolean | undefined,
326
+ cwd: targets.cwd,
327
+ noJev: params.noJev,
328
+ },
329
+ });
330
+ if (preTask.error) return preTask.error;
331
+ for (const w of preTask.warnings) taskWarnings.push(`${taskPrefix}: ${w}`);
332
+
333
+ fanOutTasks.push({ merged, model: stepModel, cwd: targets.cwd, outputFile: targets.outputFile });
334
+ }
335
+
336
+ // Spawn pass — sequential, in task order, through the shared tail.
337
+ // Issue #439: a unit's report is built from its plain identity record plus
338
+ // its own containment ledger, so a degraded unit is still reported as
339
+ // STARTED — including when a LATER unit fails or the batch is cancelled.
340
+ const started: Array<{ id: string; label?: string; tailFailures: string[] }> = [];
341
+ const startedIdsText = (): string => started.map((s) => s.id).join(", ");
342
+ /** The degraded paragraph for every unit whose monitoring did not attach. */
343
+ const degradedReport = (): string =>
344
+ started
345
+ .filter((s) => s.tailFailures.length > 0)
346
+ .map((s) => buildMonitoringDegradedParagraph(s, s.tailFailures))
347
+ .join("");
348
+
349
+ for (let i = 0; i < fanOutTasks.length; i++) {
350
+ if (signal?.aborted) {
351
+ if (started.length === 0) {
352
+ return {
353
+ content: [{ type: "text" as const, text: `Background fan-out cancelled before any agent started.` }],
354
+ details: undefined,
355
+ isError: true,
356
+ };
357
+ }
358
+ return {
359
+ content: [{ type: "text" as const, text:
360
+ `Background fan-out cancelled after starting ${started.length} of ${fanOutTasks.length} agents ` +
361
+ `(${startedIdsText()}) — they are detached and will still wake you.` +
362
+ degradedReport()
363
+ }],
364
+ details: undefined,
365
+ isError: true,
366
+ };
367
+ }
368
+
369
+ const { merged, model, cwd, outputFile } = fanOutTasks[i];
370
+ // Issue #434: called with the dispatch's `unitShape`, which is
371
+ // "background" here — a detached unit's deadline is the legitimate
372
+ // 30-minute budget, so nothing is dropped and no unit notice is ever
373
+ // emitted on this path. The call is here (not omitted) so the exclusion
374
+ // is visible at the spawn site instead of hidden in a never-taken branch.
375
+ applyUnitShapeGuard(ctx, guard, taskList[i], merged);
376
+ const name = displayTaskName(merged);
377
+ const subagentPrompt = buildSubagentPrompt(
378
+ ctx.getSystemPrompt(),
379
+ merged.inheritSP,
380
+ merged.customSP,
381
+ outputFile,
382
+ merged.toolOptions?.tools,
383
+ globalParams.resolvedPreset?.promptGuideline,
384
+ );
385
+ const unitPriority = merged.priority ?? (params.priority as string | undefined);
386
+
387
+ let spawned: BackgroundAgentSpawnResult;
388
+ try {
389
+ spawned = await startBackgroundAgent(pi, ctx, {
390
+ task: merged.task,
391
+ type: (params.preset as string | undefined) || 'general-purpose',
392
+ description: merged.label,
393
+ model: `${model.provider}/${model.id}`,
394
+ thinkingLevel: merged.thinkingLevel,
395
+ priority: unitPriority,
396
+ systemPrompt: subagentPrompt,
397
+ cwd,
398
+ toolOptions: merged.toolOptions,
399
+ timeout: merged.timeout,
400
+ gitMode: globalParams.resolvedGitMode,
401
+ // Retry parity with createUnitRun: snapshot this unit's resolved
402
+ // values so a retry restores them. The execution-shape fields
403
+ // (background/gitMode/approvalMode/force) are deliberately NOT
404
+ // passed here — a fan-out unit is spec'd to retry as a single
405
+ // run, so it must not inherit this spawn's background-ness.
406
+ // Same omission in unit-run.ts's createUnitRun.
407
+ originalParams: snapshotOriginalParams({
408
+ systemPrompt: merged.customSP,
409
+ inheritSystemPrompt: merged.inheritSP,
410
+ model: merged.model,
411
+ thinkingLevel: merged.thinkingLevel,
412
+ priority: unitPriority,
413
+ outputFile: merged.outputFile,
414
+ timeout: merged.timeout,
415
+ cwd: merged.effectiveCwd,
416
+ tools: merged.toolOptions?.tools,
417
+ excludeTools: merged.toolOptions?.excludeTools,
418
+ noBuiltinTools: merged.toolOptions?.noBuiltinTools,
419
+ preset: globalParams.resolvedPreset?.name,
420
+ }),
421
+ sanitizeCwd: merged.effectiveCwd,
422
+ recoveryPosture: state.config.recovery,
423
+ });
424
+ } catch (err) {
425
+ const message = sanitizeErrorMessage(
426
+ err instanceof Error ? err.message : String(err),
427
+ merged.effectiveCwd,
428
+ );
429
+ log.error("Background fan-out spawn failed", { task: i + 1, error: message });
430
+ const alreadyStarted = started.length > 0
431
+ ? `\n\nAlready started: ${startedIdsText()} — they are detached and will still wake you.`
432
+ : "";
433
+ return {
434
+ content: [{ type: "text" as const, text:
435
+ `Failed to spawn background agent for Task ${i + 1} ("${name}"): ${message}` + alreadyStarted +
436
+ // A degraded EARLIER unit is still a started run: its report must
437
+ // survive this later unit's failure.
438
+ degradedReport()
439
+ }],
440
+ details: undefined,
441
+ isError: true,
442
+ };
443
+ }
444
+ started.push({ id: spawned.identity.id, label: merged.label, tailFailures: spawned.tailFailures });
445
+ }
446
+
447
+ // Text-only result: ids in task order + the wake hint. C: per-task
448
+ // validation warnings ride the immediate SPAWN result (prefixed with
449
+ // their task) so the conductor can stop/re-dispatch in the same turn.
450
+ // Issue #439: a unit whose monitoring did not attach is still reported
451
+ // STARTED, with its own degraded paragraph — `isError` stays false.
452
+ const lines = started
453
+ .map((s, i) => `${i + 1}. ${s.label ? `"${s.label}" ` : ""}— ${s.id}`)
454
+ .join("\n");
455
+ return {
456
+ content: [{ type: "text" as const, text:
457
+ `Background agents started: ${started.length}\n\n` +
458
+ `${lines}\n\n` +
459
+ `You'll be woken with a completion message as each finishes; use get_subagent_result({ agent_id }) for retrieval and stall checks.` +
460
+ formatValidationWarnings(taskWarnings) +
461
+ degradedReport()
462
+ }],
463
+ details: undefined,
464
+ };
465
+ }
466
+
467
+ // -------------------------------------------------------------------
468
+ // startBackgroundAgent — the shared background-spawn tail.
469
+ // Used by BOTH spawnBackgroundRun (single task) and runBackgroundFanOut
470
+ // (tasks fan-out): the session-manager import, the spawn call, live-monitor
471
+ // registration, footer counters, the 2s progress poller and the default
472
+ // deadline timer live here exactly once. Callers keep their own prelude,
473
+ // checks, validations and result formatting. THROWS only on spawn failure —
474
+ // callers translate THAT into their own failure shape. Everything after the
475
+ // spawn is contained (issue #439): it returns `{ agent, identity,
476
+ // tailFailures }`, and a non-empty `tailFailures` is a STARTED run with
477
+ // degraded monitoring, never a failed spawn.
478
+ // -------------------------------------------------------------------
479
+
480
+ async function startBackgroundAgent(
481
+ pi: ExtensionAPI,
482
+ ctx: ExtensionContext,
483
+ spawn: BackgroundAgentSpawnRequest,
484
+ ): Promise<BackgroundAgentSpawnResult> {
485
+ // ADR 0027 D3: the lifecycle mutators arrive through the injected loader
486
+ // thunk, not a module import. Awaited at the ORIGINAL statement position so
487
+ // the import stays lazy and its rejection keeps its timing: a rejected load
488
+ // rejects THIS function, and both callers translate that into their own
489
+ // failure shape (see their catches).
490
+ const { spawnBackgroundSession, setAgentFinalOutput, extractFinalOutput } = await deps.loadSessionManager();
491
+ // Issue #31 (PR #76 review, DRY): extract final output from a
492
+ // possibly-released ref — the poller may observe a terminal agent
493
+ // whose ref was already nulled by the settlement path.
494
+ const extractAgentFinalOutput = (a: BackgroundAgent): string =>
495
+ extractFinalOutput(a._sessionRef ?? { messages: [] });
496
+
497
+ const agent = await spawnBackgroundSession(pi, ctx, {
498
+ task: spawn.task,
499
+ type: spawn.type,
500
+ description: spawn.description,
501
+ model: spawn.model,
502
+ thinkingLevel: spawn.thinkingLevel,
503
+ // Issue #114: per-unit priority rides the spawn so the background
504
+ // run entry + drill-in header carry it like foreground runs.
505
+ priority: spawn.priority,
506
+ systemPrompt: spawn.systemPrompt,
507
+ resumeContext: spawn.resumeContext,
508
+ cwd: spawn.cwd,
509
+ toolOptions: spawn.toolOptions,
510
+ // Issue #453: the deadline rides the spawn's own timer (one owner). The
511
+ // caller passes the budget only — no ownership flag, no timer of its own.
512
+ timeout: spawn.timeout,
513
+ gitMode: spawn.gitMode,
514
+ // Issue #98/#108: snapshotOriginalParams is the single source of truth
515
+ // for the caller params a later retry restores.
516
+ originalParams: spawn.originalParams,
517
+ // Option B U1: durability identity for the agent record + run entry.
518
+ dispatchId: spawn.dispatchId,
519
+ resumeOf: spawn.resumeOf,
520
+ attempt: spawn.attempt,
521
+ // Option B U3 (D4): recovery posture snapshot for the background run.
522
+ recoveryPosture: spawn.recoveryPosture,
523
+ });
524
+
525
+ // -----------------------------------------------------------------
526
+ // Post-spawn containment (issue #439).
527
+ //
528
+ // The session EXISTS from here on: the run is live and will wake the
529
+ // conductor however this tail behaves. A fault in the tail must therefore
530
+ // classify the run as STARTED with degraded monitoring — never as a failed
531
+ // spawn. Before this containment an escaping throw reached the callers'
532
+ // catch, which said "Failed to spawn background agent" while the agent was
533
+ // running, and the transport retry read that as "did not start".
534
+ //
535
+ // Boundary statement (falsifiable). Two different records, and only one of
536
+ // them is read here:
537
+ // - `identity` below is a plain record THIS module constructs. Reading its
538
+ // properties cannot throw; only a monkey-patched accessor could, and this
539
+ // module never installs one. A fault that wants to reach the degraded
540
+ // report must therefore be injected at a STATEMENT (a throwing
541
+ // registerLiveSubagent, a throwing scheduler, a rejecting spawn), which is
542
+ // what the #439 tests do.
543
+ // - `agent` (the live record from the spawn) is read ONLY by the identity
544
+ // capture immediately below and by the poller's terminal-state guard;
545
+ // every later statement reads `identity` and the captured
546
+ // primitives instead. The capture itself sits before the outer try, so a
547
+ // getter-backed `agent` (which the production spawn cannot produce but an
548
+ // injected one can) would still escape to the caller's catch — that is the
549
+ // one unpinned read, stated rather than claimed away (2026-11-07 review).
550
+ // The callers format their results from `identity` alone, so an
551
+ // adversarial accessor on the live record cannot reach the report text.
552
+ // If a future change makes `identity` a proxy or getter-backed, this boundary
553
+ // is void: the failing test is the one asserting a started run never reports
554
+ // "Failed to spawn".
555
+ //
556
+ // Two independently contained groups record into `tailFailures` — G1
557
+ // bookkeeping, G2 poller — so a fault in one never skips the other. The
558
+ // deadline is NOT one of them (issue #453): it is the spawn's, armed before
559
+ // the spawn returned, so no statement here can leave a run unbounded. An
560
+ // outer catch backstops the ledger itself, and the degraded result is
561
+ // assembled from `identity` only.
562
+ // -----------------------------------------------------------------
563
+ const identity: BackgroundAgentIdentity = {
564
+ id: agent.id,
565
+ label: spawn.description,
566
+ description: agent.description,
567
+ task: agent.task,
568
+ status: agent.status,
569
+ model: agent.model,
570
+ };
571
+
572
+ const tailFailures: string[] = [];
573
+ /** Record a contained fault. The text reaches the conductor and the user: sanitize. */
574
+ const recordTailFailure = (group: string, err: unknown): void => {
575
+ tailFailures.push(
576
+ `${group}: ${sanitizeErrorMessage(err instanceof Error ? err.message : String(err), spawn.sanitizeCwd)}`,
577
+ );
578
+ };
579
+
580
+ let pollInterval: ReturnType<typeof setInterval> | undefined;
581
+ /** G1 completed the counter increment — the ONLY runs that may decrement. */
582
+ let countedForThisRun = false;
583
+ let completed = false;
584
+
585
+ /** Stop the live-poll. The deadline is NOT the caller's to stop (issue #453). */
586
+ const stopTailPolling = (): void => {
587
+ if (pollInterval !== undefined) clearInterval(pollInterval);
588
+ };
589
+
590
+ /**
591
+ * Release this run's live counter — the ONE decrement shape for all five
592
+ * poller/deadline sites. Gated on `countedForThisRun` AND on the finalize
593
+ * claim: a run that never incremented (G1 failed before it) must not
594
+ * decrement, and a run the stale sweep already finalized had its decrement
595
+ * taken there (PR #71 review). The first gate is what keeps the ordering in
596
+ * G1 honest — without it, a row registered before the increment let the
597
+ * sweep's decrement land on a SIBLING's count.
598
+ *
599
+ * Belt-and-braces, stated as such (2026-11-07 review): with the current
600
+ * increment-first order in G1, `countedForThisRun` is always true by the time
601
+ * any callback can call this, so removing the flag alone changes nothing and
602
+ * no test pins it (an extra removal mutant survived). It is kept because the
603
+ * ORDERING is the real invariant: when the row is registered before the
604
+ * increment, the flag is the only thing standing between a settle and a
605
+ * sibling's count — M8 (reorder G1) fails T2b exactly because of it.
606
+ *
607
+ * Stated limit: the decrement is only reachable from a monitor that a run
608
+ * owns. If G1 AND G2 BOTH fail for the same run (counted, no row, no poller)
609
+ * nothing can release its count, so the footer's active count stays one high
610
+ * for the session. That is the honest reading — the run is real and
611
+ * unmonitored — and the alternative (releasing from a group that never
612
+ * attached) is how a sibling's count gets stolen.
613
+ *
614
+ * Issue #453: the deadline used to be a third releaser. It is not any more
615
+ * and does not need to be — the poller sees the spawn's `stopped` +
616
+ * `completedAt` on its next tick and releases there, which is exactly how an
617
+ * explicit-timeout run has always been released.
618
+ */
619
+ const releaseLiveCount = (): void => {
620
+ if (!countedForThisRun) return;
621
+ if (!state.finalizeLiveSubagent(identity.id)) return;
622
+ state.activeSubagents--;
623
+ if (state.activeSubagents < 0) state.activeSubagents = 0;
624
+ };
625
+
626
+ // Issue #318 (from #316 review): the two poller crash sites share one
627
+ // claimed notification envelope. Content is the only variable; the
628
+ // claim guard, display, details and deliverAs live here once.
629
+ // Issue #439: best-effort — the claim and the send sit in their own try, so
630
+ // neither a throwing claim nor a throwing send can turn a crash notice into
631
+ // a fault on the run's reporting path.
632
+ const sendCrashNotice = (content: string): void => {
633
+ try {
634
+ if (!claimTerminalNotice(identity.id)) return;
635
+ } catch {
636
+ return;
637
+ }
638
+ try {
639
+ pi.sendMessage({
640
+ customType: "subagent-notification",
641
+ content,
642
+ display: true,
643
+ details: { agentId: identity.id }
644
+ }, { deliverAs: "followUp" });
645
+ } catch { /* best-effort */ }
646
+ };
647
+
648
+ try {
649
+ // ---- G1: bookkeeping ------------------------------------------
650
+ // Ordering (issue #439, measured): counter FIRST, then the live row,
651
+ // then the repaint. A row therefore always implies a counted run, so the
652
+ // stale sweep's decrement can only release this run's own count.
653
+ try {
654
+ state.activeSubagents++;
655
+ countedForThisRun = true;
656
+ state.registerLiveSubagent(identity.id, {
657
+ id: identity.id,
658
+ label: identity.description,
659
+ task: identity.task,
660
+ model: identity.model,
661
+ thinkingLevel: agent.thinkingLevel,
662
+ priority: agent.priority,
663
+ startedAt: agent.startedAt,
664
+ // Issue #423: the persisted EFFECTIVE budget, anchored on the record's
665
+ // own start clock — the same clock the deadline timers use.
666
+ ...(agent.timeoutMs !== undefined
667
+ ? { deadlineAt: agent.startedAt + agent.timeoutMs }
668
+ : {}),
669
+ ctx,
670
+ });
671
+ repaintStatus(state, ctx);
672
+ } catch (err) {
673
+ recordTailFailure("live-monitor bookkeeping", err);
674
+ }
675
+
676
+ // ---- G2: live progress poller --------------------------------
677
+ // Issue #453: this poller is the CLEANUP OWNER for a deadline stop. The
678
+ // spawn's timer sets `status: 'stopped'` + `completedAt` (via
679
+ // updateAgentStatus) and aborts; on its next tick the poller below sees
680
+ // the terminal record and does every caller-owned step — output capture,
681
+ // the finalize claim, the counter decrement, the repaint — then stops
682
+ // itself. Nothing here arms or clears a deadline.
683
+ try {
684
+ pollInterval = setInterval(() => {
685
+ try {
686
+ if (completed) return;
687
+
688
+ const session = agent._sessionRef;
689
+ // Issue #31: a nulled ref on a TERMINAL agent is expected (the
690
+ // settlement path releases the ref) — fall through to finalize
691
+ // below instead of treating it as a crash. A nulled ref on a
692
+ // live agent is still a crash.
693
+ if (!session && !agent.completedAt) {
694
+ // Session ref not available — session may have crashed.
695
+ // Defensive: the ref is assigned synchronously before the poller starts
696
+ // and is never nulled, so this is mostly unreachable — but keep the
697
+ // bookkeeping safe regardless.
698
+ completed = true;
699
+ stopTailPolling();
700
+ // Capture whatever output exists (may be empty — fine).
701
+ setAgentFinalOutput(identity.id, state.subagentSessions.get(identity.id)?.liveOutput ?? '');
702
+ releaseLiveCount();
703
+ state.failedSubagents++;
704
+ repaintStatus(state, ctx);
705
+ sendCrashNotice(`Background agent "${identity.description}" crashed.`);
706
+ return;
707
+ }
708
+
709
+ // While running, update the live monitor.
710
+ // Once completedAt is set, skip straight to finalize below.
711
+ // Issue #31: past the guard above, the only nulled-ref path left is a
712
+ // TERMINAL agent (settlement releases the ref), so a live agent always
713
+ // has its session — the guard already returned on the live-nulled-ref
714
+ // crash path. The compiler can't correlate the two checks, so assert it.
715
+ if (!agent.completedAt) {
716
+ const finalOutput = extractFinalOutput(session!);
717
+
718
+ try {
719
+ const stats = session!.getSessionStats();
720
+ state.updateLiveSubagent(identity.id, finalOutput, stats.tokens.input, stats.tokens.output);
721
+ } catch {
722
+ state.updateLiveSubagent(identity.id, finalOutput, 0, 0);
723
+ }
724
+ }
725
+
726
+ // Authoritative completion: the prompt promise settled — status and
727
+ // completedAt are set by .then()/.catch() in spawnBackgroundSession.
728
+ // Do NOT rely on !session.isStreaming: it is false during prompt()
729
+ // preflight (auth check, model resolution) and for failed starts.
730
+ if (agent.completedAt) {
731
+ completed = true;
732
+ stopTailPolling();
733
+
734
+ // Issue #31: prefer the output already captured at settlement;
735
+ // the ref may already be nulled on terminal agents, so never
736
+ // overwrite with empty and stay null-safe.
737
+ const finalOutput = agent.finalOutput ?? extractAgentFinalOutput(agent);
738
+ setAgentFinalOutput(identity.id, finalOutput);
739
+
740
+ releaseLiveCount();
741
+
742
+ if (agent.status === 'failed') {
743
+ state.failedSubagents++;
744
+ repaintStatus(state, ctx);
745
+ // Issue #315: the terminal wake (`subagent-completion`, emitted by
746
+ // the session-manager settle) is the ONE notice for a failed run.
747
+ // The status here was set by that settle, so the wake already
748
+ // delivered — this legacy poller notice would duplicate it.
749
+ } else if (agent.status === 'stopped') {
750
+ // User-initiated stop (stop_subagent) or deadline abort
751
+ // (timeout/deadline) — not a failure.
752
+ repaintStatus(state, ctx);
753
+ } else {
754
+ state.completedSubagents++;
755
+ state.unseenSubagents++;
756
+ repaintStatus(state, ctx);
757
+ }
758
+ }
759
+ } catch (err) {
760
+ if (!completed) {
761
+ completed = true;
762
+ stopTailPolling();
763
+ try {
764
+ setAgentFinalOutput(identity.id, extractAgentFinalOutput(agent));
765
+ } catch { /* ignore */ }
766
+ releaseLiveCount();
767
+ state.failedSubagents++;
768
+ repaintStatus(state, ctx);
769
+ sendCrashNotice(`Background agent "${identity.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
770
+ }
771
+ }
772
+ }, 2000);
773
+ } catch (err) {
774
+ recordTailFailure("progress polling", err);
775
+ }
776
+
777
+ try {
778
+ log.info("Background agent spawned", { agentId: identity.id, task: spawn.task, model: identity.model });
779
+ } catch (err) {
780
+ recordTailFailure("spawn log", err);
781
+ }
782
+ } catch (err) {
783
+ // Backstop: the groups above swallow their own faults, so this can only
784
+ // see a fault in the ledger machinery itself. The degraded result below is
785
+ // assembled from `identity` — never from a property read on `agent`.
786
+ recordTailFailure("spawn tail", err);
787
+ }
788
+
789
+ if (tailFailures.length > 0) {
790
+ // ONE advisory per run, after aggregation. It is NOT a terminal notice
791
+ // and never takes the terminal claim (issue #439 contract): the run's
792
+ // genuine completion notice is still delivered when it settles.
793
+ // 2026-11-07 review: this call is INSIDE the outer containment, not after
794
+ // it — the advisory's own dispatch surfaces are contained too, and the
795
+ // inner per-channel tries in `sendMonitoringDegradedAdvisory` cover the
796
+ // case where one channel throws (so one failure cannot lose both).
797
+ try {
798
+ sendMonitoringDegradedAdvisory(pi, ctx, identity, tailFailures);
799
+ } catch (err) {
800
+ recordTailFailure("monitoring advisory", err);
801
+ }
802
+ }
803
+
804
+ return { agent, identity, tailFailures };
805
+ }
806
+
807
+ // -------------------------------------------------------------------
808
+ // spawnBackgroundRun — Phase 6.5 background spawn, extracted verbatim
809
+ // from execute() (#198 phase 1) so a later phase can fan out N runs.
810
+ // -------------------------------------------------------------------
811
+
812
+ async function spawnBackgroundRun(
813
+ pi: ExtensionAPI,
814
+ ctx: ExtensionContext,
815
+ /**
816
+ * Two shapes, both passed WITHOUT an assertion (issue #379):
817
+ * - `DelegateTaskParams` — a fresh dispatch, schema-validated;
818
+ * - the `resolveRetryParams` bag — rebuilt from a run record, whose
819
+ * `priority` is the unvalidated persisted string. It is the only field
820
+ * the two shapes disagree on, and claiming the recorded value was
821
+ * schema-validated would be a lie: records are read back from disk.
822
+ */
823
+ params: (DelegateTaskParams & { noJev?: string }) | ReturnType<typeof resolveRetryParams>,
824
+ singleTask: string,
825
+ // Option B U1: the spawn entry a retryRunId resolved to, so a retried
826
+ // background run inherits dispatchId/resumeOf/attempt (record identity,
827
+ // not a delegate param — D4).
828
+ retrySourceRun?: SubagentRun,
829
+ /**
830
+ * Issue #401/#411: the resume preamble for a TRANSPORT auto-retry. It rides
831
+ * the child's system prompt only (as a `<resume-context>` section) — never
832
+ * inside the `<task>` fence. `resolveSubagentParams`, every gate and every
833
+ * H1 check above still see `singleTask` (which stays byte-identical to the
834
+ * recorded original), so routing, capability warnings and pre-flight checks
835
+ * cannot be steered by the preamble's wording.
836
+ */
837
+ attemptContext?: string,
838
+ ): Promise<ToolResult<undefined>> {
839
+ // Issue #443: the DECLARED level, guarded before `bgResolved` clamps it.
840
+ // This is the seam for the TRANSPORT auto-retry (`scheduleTransportRetry`
841
+ // re-enters here with `resolveRetryParams`' rebuilt bag and never passes
842
+ // through `execute`), and the reason a restored record carrying an unknown
843
+ // level cannot launch a session at pi's default. A rejection here surfaces
844
+ // as the ORIGINAL failure's notice — the caller reports it unchanged.
845
+ const bgDeclaredThinkingLevel = declaredThinkingLevel(
846
+ params.thinkingLevel,
847
+ resolveDispatchPreset({ ...params, task: singleTask }, state).preset?.thinkingLevel,
848
+ );
849
+ const bgDeclaredThinkingError = invalidThinkingLevelRejection(bgDeclaredThinkingLevel);
850
+ if (bgDeclaredThinkingError) return bgDeclaredThinkingError;
851
+
852
+ // Phase 6.5: Background execution — spawn session and return ID immediately.
853
+ // Resolve the preset and its model BEFORE the background branch so the
854
+ // preset's model (and system prompt) are honored in background mode.
855
+ const bgResolved = resolveSubagentParams({ ...params, task: singleTask }, state, ctx, log);
856
+ const {
857
+ resolvedPreset: bgResolvedPreset,
858
+ autoRoutedPreset: bgAutoRoutedPreset,
859
+ autoRouteKeyword: bgAutoRouteKeyword,
860
+ } = bgResolved;
861
+ // ADR 0027 (S3): explicit argument mapping — the same three inputs the
862
+ // retired wrapper forwarded, plus the context bindings it captured.
863
+ const bgModelResult = resolveSubagentModelPrecedence({
864
+ state,
865
+ ctx,
866
+ log,
867
+ preset: bgResolvedPreset,
868
+ perCallModel: params.model,
869
+ });
870
+ const bgModel = bgModelResult.ok
871
+ ? `${bgModelResult.model.provider}/${bgModelResult.model.id}`
872
+ : undefined;
873
+
874
+ try {
875
+ // W5 (issue #28): approvalMode 'always' cannot work in background —
876
+ // there is no interactive dialog to approve the diff. Reject loudly
877
+ // instead of silently running unattended with write access.
878
+ const approvalError = rejectApprovalAlwaysInBackground(bgResolved.resolvedApprovalMode);
879
+ if (approvalError) return approvalError;
880
+ // W5: 'writes' in background silently auto-approves — warn once so the
881
+ // caller knows the diff will NOT be gated on approval.
882
+ if (bgResolved.resolvedApprovalMode === 'writes') {
883
+ log.warn("Background agent spawned with approvalMode 'writes' — auto-approving (no dialog in background)", {
884
+ task: params.task,
885
+ });
886
+ }
887
+
888
+ // W6 (issue #28): session cost limit must gate background spawns too —
889
+ // the R5 check after the background branch never runs for them.
890
+ // Same estimate/limit logic as single mode.
891
+ const costError = gateSessionCost({
892
+ state,
893
+ ctx,
894
+ log,
895
+ units: 1,
896
+ label: "Background delegation",
897
+ });
898
+ if (costError) return costError;
899
+
900
+ // F1: Validate cwd + outputFile the same way foreground single mode does —
901
+ // an unvalidated outputFile would reach the prompt and could steer the
902
+ // background agent's write tool outside the project root.
903
+ const targets = validateDelegationTargets({
904
+ ctx,
905
+ effectiveCwd: bgResolved.effectiveCwd,
906
+ outputFile: bgResolved.outputFile,
907
+ });
908
+ if (!targets.ok) return targets.error;
909
+ const bgResolvedOutputFile = targets.outputFile;
910
+
911
+ // C: H1 validation for background mode — reject capability blocks and
912
+ // outputFile-vs-write conflicts before spawning (same as single mode;
913
+ // `force` honors the same override foreground does).
914
+ const bgPreTask = runPreTaskValidation({
915
+ log,
916
+ label: "Background",
917
+ preTask: {
918
+ task: singleTask,
919
+ toolOptions: bgResolved.toolOptions,
920
+ thinkingLevel: bgResolved.thinkingLevel,
921
+ gitMode: bgResolved.resolvedGitMode,
922
+ outputFile: bgResolvedOutputFile,
923
+ force: params.force,
924
+ cwd: targets.cwd,
925
+ noJev: params.noJev,
926
+ },
927
+ });
928
+ if (bgPreTask.error) return bgPreTask.error;
929
+
930
+ // Build the full prompt the same way foreground single mode does:
931
+ // base prompt (optionally inherited) + custom prompt + preset guidance.
932
+ const bgPrompt = buildSubagentPrompt(
933
+ ctx.getSystemPrompt(),
934
+ bgResolved.inheritSP,
935
+ bgResolved.customSP,
936
+ bgResolvedOutputFile,
937
+ bgResolved.toolOptions?.tools,
938
+ bgResolvedPreset?.promptGuideline,
939
+ );
940
+
941
+ // Option B U1: durability identity (retry inherits the original dispatch).
942
+ const bgIdentity = newDispatchIdentity(retrySourceRun);
943
+ const spawned = await startBackgroundAgent(pi, ctx, {
944
+ // Issue #411: the preamble rides the system-prompt side
945
+ // (`resumeContext`), never the task. The task stays the recorded
946
+ // original, and the snapshot keeps it too, so a later retry of this
947
+ // retry resolves from the un-prefixed text and never compounds.
948
+ task: singleTask,
949
+ resumeContext: attemptContext,
950
+ type: params.preset || 'general-purpose',
951
+ description: params.label,
952
+ model: bgModel,
953
+ thinkingLevel: bgResolved.thinkingLevel,
954
+ priority: params.priority,
955
+ systemPrompt: bgPrompt,
956
+ cwd: targets.cwd,
957
+ toolOptions: bgResolved.toolOptions,
958
+ timeout: bgResolved.timeout,
959
+ gitMode: bgResolved.resolvedGitMode,
960
+ originalParams: attemptContext
961
+ ? { ...snapshotOriginalParams(params), task: singleTask }
962
+ : snapshotOriginalParams(params),
963
+ sanitizeCwd: bgResolved.effectiveCwd,
964
+ dispatchId: bgIdentity.dispatchId,
965
+ resumeOf: bgIdentity.resumeOf,
966
+ attempt: bgIdentity.attempt,
967
+ recoveryPosture: state.config.recovery,
968
+ });
969
+
970
+ // Retire-on-retry (O3 fold, decision 2026-10-11): the source interrupted
971
+ // registry entry is superseded once the new background run is actually
972
+ // spawned (a throwing spawn is caught below and leaves the source intact
973
+ // and retryable).
974
+ if (retrySourceRun) clearInflightRun(retrySourceRun.id);
975
+
976
+ // B2: Surface auto-route decisions in background spawn result too —
977
+ // preset name + matched-keyword evidence + restriction, derived from
978
+ // the RESOLVED toolOptions (reflects per-call overrides).
979
+ const bgAutoRouteNote = bgAutoRoutedPreset
980
+ ? `\n\n[auto-routed to preset '${bgAutoRoutedPreset.name}'${bgAutoRouteKeyword ? ` (matched keyword '${bgAutoRouteKeyword}')` : ""} — ${bgResolved.toolOptions ? formatToolRestriction(bgResolved.toolOptions) : formatPresetRestriction(bgAutoRoutedPreset)}]`
981
+ : "";
982
+
983
+ // Issue #439: everything the result states comes from `identity`, the plain
984
+ // record captured at spawn time — never a property read on the live agent.
985
+ // A non-empty `tailFailures` is a STARTED run with degraded monitoring, so
986
+ // this stays a success (`isError` false) with the degraded paragraph;
987
+ // the transport retry reads `isError` as "did not start" and must not see
988
+ // a started run here.
989
+ return {
990
+ content: [{
991
+ type: "text" as const,
992
+ text: `Background agent started: ${spawned.identity.id}\n\n` +
993
+ `Description: ${spawned.identity.description}\n` +
994
+ `Task: ${spawned.identity.task}\n` +
995
+ `Status: ${spawned.identity.status}\n\n` +
996
+ `You'll be woken with a completion message when it finishes; use get_subagent_result({ agent_id: "${spawned.identity.id}" }) for retrieval and stall checks.` +
997
+ bgAutoRouteNote +
998
+ // C: warnings ride the immediate SPAWN result so the conductor
999
+ // can stop/re-dispatch in the same turn.
1000
+ formatValidationWarnings(bgPreTask.warnings) +
1001
+ buildMonitoringDegradedParagraph(spawned.identity, spawned.tailFailures),
1002
+ }],
1003
+ details: undefined,
1004
+ isError: false,
1005
+ };
1006
+ } catch (err) {
1007
+ // Issue #439: this catch is reachable ONLY for a pre-spawn gate or a
1008
+ // rejected `spawnBackgroundSession`. Everything after a successful spawn
1009
+ // is contained in `startBackgroundAgent` — a run that started never lands
1010
+ // here, so the wording below can never describe a live run.
1011
+ const message = sanitizeErrorMessage(
1012
+ err instanceof Error ? err.message : String(err),
1013
+ bgResolved.effectiveCwd,
1014
+ );
1015
+ log.error("Failed to spawn background agent", { error: message });
1016
+ return {
1017
+ content: [{ type: "text" as const, text: `Failed to spawn background agent: ${message}` }],
1018
+ details: undefined,
1019
+ isError: true,
1020
+ };
1021
+ }
1022
+ }
1023
+
1024
+ return { runBackgroundFanOut, startBackgroundAgent, spawnBackgroundRun };
1025
+ }