brl-subagent 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -36,8 +36,10 @@ import type {
36
36
  TaskTemplate,
37
37
  ToolResult,
38
38
  SubagentEvent,
39
+ SubagentEventListener,
39
40
  } from "./types";
40
41
  import {
42
+ declaredThinkingLevel,
41
43
  resolveThinkingLevel,
42
44
  EMPTY_USAGE,
43
45
  getFinalOutput,
@@ -52,6 +54,8 @@ import {
52
54
  DEFAULT_PRIORITY,
53
55
  type GitMode,
54
56
  type BackgroundAgent,
57
+ type BackgroundAgentIdentity,
58
+ type BackgroundAgentSpawnResult,
55
59
  type RecoveryMode,
56
60
  } from "./types";
57
61
  import { validateGraph, topologicalSort } from "./scheduler";
@@ -63,18 +67,22 @@ import { sanitizeTask, validateCwd, validateOutputFile, stripAnsi, capOutput, ge
63
67
  import {
64
68
  hasUncommittedChanges,
65
69
  createWorkBranch,
70
+ newWorkBranchName,
66
71
  captureDiff,
67
72
  getHeadState,
73
+ getHeadBranch,
74
+ getRepoRoot,
75
+ listWorkBranches,
68
76
  restoreHead,
69
77
  deleteBranch,
70
78
  mergeWorkBranch,
71
79
  type HeadState,
72
80
  } from "./git";
73
81
  import { preflightCheck } from "./preflight";
74
- import { depthLimitRejection, formatValidationWarnings, gateSessionCost, modelNotConfiguredRejection, rejectApprovalAlwaysInBackground, rejection, resolveModeModel, resolveSubagentModelPrecedence, runPreTaskValidation, validateDelegationTargets, validateUnitPrePass, type SubagentModelResolution } from "./prelude";
82
+ import { depthLimitRejection, formatValidationWarnings, gateSessionCost, invalidThinkingLevelRejection, modelNotConfiguredRejection, rejectApprovalAlwaysInBackground, rejection, resolveModeModel, resolveSubagentModelPrecedence, runPreTaskValidation, validateDelegationTargets, validateUnitPrePass, type SubagentModelResolution } from "./prelude";
75
83
  import { loadBuiltinPresets, loadCustomPresets, getAllPresets, writePresetFile, formatPresetRestriction, formatToolRestriction } from "./presets";
76
84
  import { modelIsAvailable, parseModelString } from "./model-availability";
77
- import { validatePreTask, diagnoseFailure, DEFAULT_BACKGROUND_DEADLINE_MS } from "./validate";
85
+ import { validatePreTask, diagnoseFailure } from "./validate";
78
86
  import {
79
87
  defaultBackgroundFor,
80
88
  findUnknownParams,
@@ -83,11 +91,15 @@ import {
83
91
  resolveEffectiveApprovalMode,
84
92
  resolveSubagentParams,
85
93
  resolveThinkingDispatchSwitch,
94
+ shouldDropUnitTimeout,
86
95
  shouldRejectBackgroundForBatch,
87
96
  snapshotOriginalParams,
88
97
  THINKING_SWITCH_NOTICE,
98
+ THINKING_TIMEOUT_DROP_NOTICE,
99
+ THINKING_UNIT_TIMEOUT_DROP_NOTICE,
89
100
  type DispatchShape,
90
101
  type ResolveInputParams,
102
+ type UnitShape,
91
103
  } from "./params";
92
104
  import { delegateTaskParamsSchema } from "./schema";
93
105
  import { readProcessChecks } from "./project-flags";
@@ -99,7 +111,19 @@ import {
99
111
  recoverProduction,
100
112
  currentProcessOwner,
101
113
  newDispatchIdentity,
114
+ classifyOwner,
115
+ defaultRecoveryDeps,
102
116
  } from "./recovery";
117
+ import {
118
+ buildHeadStateNotice,
119
+ reconcileHeadStates,
120
+ sweepHeadStates,
121
+ writeHeadState,
122
+ clearHeadState,
123
+ HEAD_STATE_VERSION,
124
+ type HeadStateDeps,
125
+ type HeadStateOutcome,
126
+ } from "./headstate";
103
127
  import { markInterrupted, listInflightRuns, clearInflightRun } from "./run-registry";
104
128
  import { acquireSlot, clearProgressLinger, releaseSlot, repaintStatus, stopProgressTicker } from "./concurrency";
105
129
  import { transcriptDisplayPath } from "./transcript-path";
@@ -148,10 +172,14 @@ import { Intercom } from "./messaging";
148
172
  import * as eventBus from "./event-bus";
149
173
  import {
150
174
  buildCompletionMessage,
175
+ formatBudgetLine,
176
+ normalizeCompletionStatus,
151
177
  resolveDelivery,
152
178
  sendCompletionNotification,
153
179
  claimTerminalNotice,
154
180
  resolveRunEntry,
181
+ buildMonitoringDegradedParagraph,
182
+ sendMonitoringDegradedAdvisory,
155
183
  } from "./notify-completion";
156
184
  import { isTransportRetryable, TRANSPORT_RETRY_TOAST } from "./transport-retry";
157
185
 
@@ -331,6 +359,38 @@ function graphTaskToSubTaskParams(node: GraphTask): SubTaskParams {
331
359
  return subTask;
332
360
  }
333
361
 
362
+ /**
363
+ * Issue #434: what every unit of ONE dispatch needs from the dispatch-level
364
+ * pre-flight — threaded from `execute` into the four batch handlers, never
365
+ * re-derived at a unit site.
366
+ *
367
+ * - `processChecks` is the project opt-in `execute` already resolved from the
368
+ * dispatch's OWN cwd. Re-reading it per unit (from a relative
369
+ * `params.cwd`) judges a different directory than the dispatch did.
370
+ * - `dispatchDeclaredLevel` is the declared (uncapped) level the dispatch arm
371
+ * judged, so a unit that declares only a `timeout` is still judged against
372
+ * the thinking level it actually inherits.
373
+ * - `force` and `unitShape` are the dispatch-level facts the unit projection
374
+ * asks for; `params` is in scope at every unit site, so passing them here is
375
+ * what keeps the predicate's inputs in ONE place.
376
+ * - `noticeEmitted` is the one-shot flag on this shared object (all handlers
377
+ * received the same reference): the unit projection emits AT MOST one
378
+ * additional notice per dispatch, and a dispatch-arm notice starts it true
379
+ * (the drop still happens — the deadline is the hazard, the notice is the
380
+ * report). A flag on the shared context, not a boolean copy, because the
381
+ * first unit to reach its run is whichever won the slot, not the first in
382
+ * the array.
383
+ */
384
+ interface BatchGuardContext {
385
+ processChecks: boolean;
386
+ dispatchDeclaredLevel: ThinkingLevel | undefined;
387
+ /** The dispatch's `force` — the override applies to every unit of it. */
388
+ force: boolean | undefined;
389
+ unitShape: UnitShape;
390
+ /** True once any notice for this dispatch went out — mutated at the unit site. */
391
+ noticeEmitted: boolean;
392
+ }
393
+
334
394
  /**
335
395
  * Issue #376 (audit D3): the one `SubagentResult` → `SubTaskResult` field
336
396
  * mapping, shared by every dispatch mode (chain, parallel, graph). The ten
@@ -377,7 +437,7 @@ export default function (pi: ExtensionAPI) {
377
437
  let state = createSessionState(log);
378
438
 
379
439
  // Issue #147: the completion-push subscriber needs the session context to
380
- // resolve the run entry (state.getRunEntries(ctx)). The event-bus listener
440
+ // resolve the run entry (state.getLogicalRunEntries(ctx)). The event-bus listener
381
441
  // receives no ctx, so capture it in session_start where it is available.
382
442
  let sessionCtx: ExtensionContext | undefined;
383
443
 
@@ -538,6 +598,74 @@ export default function (pi: ExtensionAPI) {
538
598
  merged.label ??
539
599
  (merged.task.length > 60 ? `${merged.task.slice(0, 57)}...` : merged.task);
540
600
 
601
+ /**
602
+ * Issue #434: apply the dispatch pre-flight's UNIT projection to one merged
603
+ * unit — `merged.timeout = undefined` before the unit's run record exists, so
604
+ * the retry snapshot records an absent deadline (ADR 0009) and no
605
+ * `createUnitRun`/`startBackgroundAgent` ever sees it. The decision itself
606
+ * lives in `shouldDropUnitTimeout` (params.ts): re-stating the condition here
607
+ * is the drift #361's resolver extraction exists to prevent.
608
+ *
609
+ * EVERY input is threaded (`ctx`'s guard) or the unit's own declaration
610
+ * (`step`) — the unit site reads no config, no manifest and no cap of its
611
+ * own. `merged.thinkingLevel` is deliberately not an input: it is the capped
612
+ * level, and the default cap would silently disable the guard.
613
+ *
614
+ * Emission discipline (issue #434 [c2]): called from the unit's dispatch
615
+ * point, AFTER its slot is held and immediately BEFORE its run — a pre-pass
616
+ * would announce a unit that a cancellation can still skip. At most ONE
617
+ * notice per dispatch: a dispatch-arm notice suppresses this one entirely
618
+ * (the drop still happens — the deadline is the hazard, the notice is the
619
+ * report), and the first unit to reach its run claims it.
620
+ */
621
+ function applyUnitShapeGuard(
622
+ ctx: ExtensionContext,
623
+ guard: BatchGuardContext,
624
+ step: SubTaskParams,
625
+ merged: ReturnType<typeof mergeSubTaskParams>,
626
+ ): void {
627
+ const shouldDrop = shouldDropUnitTimeout({
628
+ processChecks: guard.processChecks,
629
+ force: guard.force,
630
+ dispatchDeclaredLevel: guard.dispatchDeclaredLevel,
631
+ unitShape: guard.unitShape,
632
+ declaredLevel: step.thinkingLevel as ThinkingLevel | "" | undefined,
633
+ declaredTimeout: step.timeout,
634
+ mergedTimeout: merged.timeout,
635
+ });
636
+ if (!shouldDrop) return;
637
+
638
+ const previousTimeout = merged.timeout;
639
+ const unit = displayTaskName(merged);
640
+ const effectiveLevel = step.thinkingLevel || guard.dispatchDeclaredLevel;
641
+ // The drop precedes `createUnitRun`: that is what makes the recorded
642
+ // `originalParams.timeout` absent, so a retry re-derives instead of
643
+ // restoring the cap (ADR 0009). A drop after it passes every
644
+ // runner-argument assertion and still restores the deadline on retry.
645
+ merged.timeout = undefined;
646
+ log.info("Dispatch pre-flight: unit-declared timeout dropped, unit stays foreground", {
647
+ unit,
648
+ thinkingLevel: effectiveLevel,
649
+ previousTimeout,
650
+ });
651
+ if (!guard.noticeEmitted) {
652
+ guard.noticeEmitted = true;
653
+ pi.sendMessage({
654
+ customType: "delegate-notification",
655
+ content: THINKING_UNIT_TIMEOUT_DROP_NOTICE,
656
+ display: true,
657
+ details: {
658
+ unit,
659
+ thinkingLevel: effectiveLevel,
660
+ // The ACTUAL ms value, mirroring the dispatch drop arm: the
661
+ // friction log needs the number to tell a budget cap from a clock.
662
+ previousTimeout,
663
+ },
664
+ }, { deliverAs: "followUp" });
665
+ ctx.ui.notify(THINKING_UNIT_TIMEOUT_DROP_NOTICE, "warning");
666
+ }
667
+ }
668
+
541
669
  // -------------------------------------------------------------------
542
670
  // P1: runChainMode
543
671
  // -------------------------------------------------------------------
@@ -547,6 +675,7 @@ export default function (pi: ExtensionAPI) {
547
675
  signal: AbortSignal | undefined,
548
676
  onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
549
677
  ctx: ExtensionContext,
678
+ guard: BatchGuardContext,
550
679
  ): Promise<ToolResult<SubagentResult | ChainDetails | undefined>> {
551
680
  const chainSteps: SubTaskParams[] = params.chain!;
552
681
 
@@ -587,6 +716,8 @@ export default function (pi: ExtensionAPI) {
587
716
  log,
588
717
  force: params.force as boolean | undefined,
589
718
  noJev: params.noJev,
719
+ // Issue #443: the DECLARED per-step level (the merged one is resolved).
720
+ declaredThinkingLevel: (step) => step.thinkingLevel,
590
721
  merge: (step) => mergeSubTaskParams(globalParams, step),
591
722
  describe: (_step, merged, i) => ({
592
723
  prefix: `Step ${i + 1} ("${displayTaskName(merged)}")`,
@@ -647,6 +778,12 @@ export default function (pi: ExtensionAPI) {
647
778
  // Merge params for this step
648
779
  const merged = mergeSubTaskParams(globalParams, step);
649
780
 
781
+ // Issue #434: the unit projection of the dispatch pre-flight (#412/#431).
782
+ // A chain holds its ONE mode-level slot across the whole loop, so the
783
+ // slot is already held here; the drop lands BEFORE `createUnitRun`
784
+ // below, or the retry snapshot would restore the deadline (ADR 0009).
785
+ applyUnitShapeGuard(ctx, guard, step, merged);
786
+
650
787
  // C3: Resolve this step's model override (step.model > global resolved model)
651
788
  const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
652
789
 
@@ -727,7 +864,7 @@ export default function (pi: ExtensionAPI) {
727
864
  // parallel mode's issue #119 registration). Fall back to
728
865
  // "Step N" when the step carries no label (liveRowName would
729
866
  // otherwise show the truncated task).
730
- registerLiveRun(state, run, ctx, merged.label ?? `Step ${i + 1}`);
867
+ registerLiveRun(state, run, ctx, merged.label ?? `Step ${i + 1}`, merged.timeout);
731
868
 
732
869
  // Wrap onUpdate so the live monitor sees per-step progress
733
870
  // (mirrors parallel mode's taskOnUpdate).
@@ -938,6 +1075,7 @@ export default function (pi: ExtensionAPI) {
938
1075
  signal: AbortSignal | undefined,
939
1076
  onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
940
1077
  ctx: ExtensionContext,
1078
+ guard: BatchGuardContext,
941
1079
  ): Promise<ToolResult<SubagentResult | ParallelDetails | undefined>> {
942
1080
  const taskList: SubTaskParams[] = params.tasks!;
943
1081
 
@@ -976,6 +1114,8 @@ export default function (pi: ExtensionAPI) {
976
1114
  log,
977
1115
  force: params.force as boolean | undefined,
978
1116
  noJev: params.noJev,
1117
+ // Issue #443: the DECLARED per-task level (the merged one is resolved).
1118
+ declaredThinkingLevel: (task) => task.thinkingLevel,
979
1119
  merge: (task) => mergeSubTaskParams(globalParams, task),
980
1120
  describe: (_task, merged, i) => ({
981
1121
  prefix: `Task ${i + 1} ("${displayTaskName(merged)}")`,
@@ -1018,6 +1158,14 @@ export default function (pi: ExtensionAPI) {
1018
1158
  unitCwd: string,
1019
1159
  ): Promise<boolean> => {
1020
1160
 
1161
+ // Issue #434: the unit projection of the dispatch pre-flight. Applied
1162
+ // HERE, not in the launcher's pre-merge: the launcher awaits
1163
+ // `acquireSlot` and only then calls this, so a unit cancelled while
1164
+ // waiting for its slot is never announced (and never dropped). The
1165
+ // drop still precedes `createUnitRun` below, so the retry snapshot
1166
+ // records an absent deadline rather than restoring the cap.
1167
+ applyUnitShapeGuard(ctx, guard, taskList[index], merged);
1168
+
1021
1169
  // C3: Resolve this step's model override (step.model > global resolved model)
1022
1170
  const stepModel = resolveStepModel(ctx, merged.model, subagentModel);
1023
1171
 
@@ -1055,8 +1203,9 @@ export default function (pi: ExtensionAPI) {
1055
1203
  pruneHistoryIfNeeded(state, ctx, log);
1056
1204
 
1057
1205
  // Register for live monitor — parallel subtasks now appear in the
1058
- // drill-in with their per-unit priority (issue #119).
1059
- registerLiveRun(state, run, ctx);
1206
+ // drill-in with their per-unit priority (issue #119). The merged
1207
+ // timeout rides along as the display deadline (issue #423).
1208
+ registerLiveRun(state, run, ctx, undefined, merged.timeout);
1060
1209
 
1061
1210
  log.debug("Parallel subtask run registered", { runId, index });
1062
1211
 
@@ -1286,6 +1435,7 @@ export default function (pi: ExtensionAPI) {
1286
1435
  signal: AbortSignal | undefined,
1287
1436
  onUpdate: AgentToolUpdateCallback<DelegateTaskDetails> | undefined,
1288
1437
  ctx: ExtensionContext,
1438
+ guard: BatchGuardContext,
1289
1439
  ): Promise<ToolResult<SubagentResult | GraphDetails | undefined>> {
1290
1440
  const graphTasks: GraphTask[] = params.graph!;
1291
1441
 
@@ -1375,6 +1525,8 @@ export default function (pi: ExtensionAPI) {
1375
1525
  log,
1376
1526
  force: params.force as boolean | undefined,
1377
1527
  noJev: params.noJev,
1528
+ // Issue #443: the DECLARED per-node level (the merged one is resolved).
1529
+ declaredThinkingLevel: (node) => node.thinkingLevel,
1378
1530
  merge: (node) => mergeSubTaskParams(globalParams, graphTaskToSubTaskParams(node)),
1379
1531
  describe: (node, merged) => ({
1380
1532
  prefix: `Node "${node.id}"`,
@@ -1496,6 +1648,12 @@ export default function (pi: ExtensionAPI) {
1496
1648
  const subagentId = graphTask.id;
1497
1649
  intercom.register(subagentId);
1498
1650
 
1651
+ // Issue #434: the unit projection of the dispatch pre-flight, applied
1652
+ // after this node's slot is held (a node cancelled above never
1653
+ // reaches here) and BEFORE `createUnitRun` below, so the retry
1654
+ // snapshot records the dropped deadline (ADR 0009).
1655
+ applyUnitShapeGuard(ctx, guard, subTaskParams, merged);
1656
+
1499
1657
  // Issue #133: status-bar breakdown — the node's dispatch-wide
1500
1658
  // position (globalNode, not the wave-local nodeIndex) so a later
1501
1659
  // wave reports its true global ordinal.
@@ -1525,7 +1683,8 @@ export default function (pi: ExtensionAPI) {
1525
1683
  // is host-global, so raw graph-task ids would collide across
1526
1684
  // concurrent graph runs (the intercom namespace is per-run and
1527
1685
  // stays untouched).
1528
- registerLiveRun(state, run, ctx);
1686
+ // Issue #423: the merged timeout rides along as the display deadline.
1687
+ registerLiveRun(state, run, ctx, undefined, merged.timeout);
1529
1688
 
1530
1689
  let nodeSuccess = false;
1531
1690
  try {
@@ -1719,6 +1878,7 @@ export default function (pi: ExtensionAPI) {
1719
1878
  ctx: ExtensionContext,
1720
1879
  params: DelegateTaskParams,
1721
1880
  signal: AbortSignal | undefined,
1881
+ guard: BatchGuardContext,
1722
1882
  ): Promise<ToolResult<SubagentResult | undefined>> {
1723
1883
  const taskList: SubTaskParams[] = params.tasks!;
1724
1884
 
@@ -1796,6 +1956,16 @@ export default function (pi: ExtensionAPI) {
1796
1956
  const merged = mergeSubTaskParams(globalParams, taskList[i]);
1797
1957
  const name = displayTaskName(merged);
1798
1958
  const taskPrefix = `Task ${i + 1} ("${name}")`;
1959
+ // Issue #443: the DECLARED per-task level — `merged.thinkingLevel` is
1960
+ // already resolved, so an unknown declaration is indistinguishable from
1961
+ // an omitted one by the time the spawn pass reads it. Checked here, in
1962
+ // the all-before-any-spawn pass, so a bad SECOND task rejects the whole
1963
+ // batch with nothing started.
1964
+ const declaredThinkingError = invalidThinkingLevelRejection(
1965
+ taskList[i].thinkingLevel,
1966
+ taskPrefix,
1967
+ );
1968
+ if (declaredThinkingError) return declaredThinkingError;
1799
1969
  // Per-task model override wins; the global model is the fallback.
1800
1970
  const stepModel = resolveStepModel(ctx, merged.model, globalModel);
1801
1971
 
@@ -1830,8 +2000,17 @@ export default function (pi: ExtensionAPI) {
1830
2000
  }
1831
2001
 
1832
2002
  // Spawn pass — sequential, in task order, through the shared tail.
1833
- const started: Array<{ id: string; label?: string }> = [];
2003
+ // Issue #439: a unit's report is built from its plain identity record plus
2004
+ // its own containment ledger, so a degraded unit is still reported as
2005
+ // STARTED — including when a LATER unit fails or the batch is cancelled.
2006
+ const started: Array<{ id: string; label?: string; tailFailures: string[] }> = [];
1834
2007
  const startedIdsText = (): string => started.map((s) => s.id).join(", ");
2008
+ /** The degraded paragraph for every unit whose monitoring did not attach. */
2009
+ const degradedReport = (): string =>
2010
+ started
2011
+ .filter((s) => s.tailFailures.length > 0)
2012
+ .map((s) => buildMonitoringDegradedParagraph(s, s.tailFailures))
2013
+ .join("");
1835
2014
 
1836
2015
  for (let i = 0; i < fanOutTasks.length; i++) {
1837
2016
  if (signal?.aborted) {
@@ -1845,7 +2024,8 @@ export default function (pi: ExtensionAPI) {
1845
2024
  return {
1846
2025
  content: [{ type: "text" as const, text:
1847
2026
  `Background fan-out cancelled after starting ${started.length} of ${fanOutTasks.length} agents ` +
1848
- `(${startedIdsText()}) — they are detached and will still wake you.`
2027
+ `(${startedIdsText()}) — they are detached and will still wake you.` +
2028
+ degradedReport()
1849
2029
  }],
1850
2030
  details: undefined,
1851
2031
  isError: true,
@@ -1853,6 +2033,12 @@ export default function (pi: ExtensionAPI) {
1853
2033
  }
1854
2034
 
1855
2035
  const { merged, model, cwd, outputFile } = fanOutTasks[i];
2036
+ // Issue #434: called with the dispatch's `unitShape`, which is
2037
+ // "background" here — a detached unit's deadline is the legitimate
2038
+ // 30-minute budget, so nothing is dropped and no unit notice is ever
2039
+ // emitted on this path. The call is here (not omitted) so the exclusion
2040
+ // is visible at the spawn site instead of hidden in a never-taken branch.
2041
+ applyUnitShapeGuard(ctx, guard, taskList[i], merged);
1856
2042
  const name = displayTaskName(merged);
1857
2043
  const subagentPrompt = buildSubagentPrompt(
1858
2044
  ctx.getSystemPrompt(),
@@ -1864,9 +2050,9 @@ export default function (pi: ExtensionAPI) {
1864
2050
  );
1865
2051
  const unitPriority = merged.priority ?? (params.priority as string | undefined);
1866
2052
 
1867
- let agent: BackgroundAgent;
2053
+ let spawned: BackgroundAgentSpawnResult;
1868
2054
  try {
1869
- agent = await startBackgroundAgent(pi, ctx, {
2055
+ spawned = await startBackgroundAgent(pi, ctx, {
1870
2056
  task: merged.task,
1871
2057
  type: (params.preset as string | undefined) || 'general-purpose',
1872
2058
  description: merged.label,
@@ -1912,18 +2098,23 @@ export default function (pi: ExtensionAPI) {
1912
2098
  : "";
1913
2099
  return {
1914
2100
  content: [{ type: "text" as const, text:
1915
- `Failed to spawn background agent for Task ${i + 1} ("${name}"): ${message}` + alreadyStarted
2101
+ `Failed to spawn background agent for Task ${i + 1} ("${name}"): ${message}` + alreadyStarted +
2102
+ // A degraded EARLIER unit is still a started run: its report must
2103
+ // survive this later unit's failure.
2104
+ degradedReport()
1916
2105
  }],
1917
2106
  details: undefined,
1918
2107
  isError: true,
1919
2108
  };
1920
2109
  }
1921
- started.push({ id: agent.id, label: merged.label });
2110
+ started.push({ id: spawned.identity.id, label: merged.label, tailFailures: spawned.tailFailures });
1922
2111
  }
1923
2112
 
1924
2113
  // Text-only result: ids in task order + the wake hint. C: per-task
1925
2114
  // validation warnings ride the immediate SPAWN result (prefixed with
1926
2115
  // their task) so the conductor can stop/re-dispatch in the same turn.
2116
+ // Issue #439: a unit whose monitoring did not attach is still reported
2117
+ // STARTED, with its own degraded paragraph — `isError` stays false.
1927
2118
  const lines = started
1928
2119
  .map((s, i) => `${i + 1}. ${s.label ? `"${s.label}" ` : ""}— ${s.id}`)
1929
2120
  .join("\n");
@@ -1932,7 +2123,8 @@ export default function (pi: ExtensionAPI) {
1932
2123
  `Background agents started: ${started.length}\n\n` +
1933
2124
  `${lines}\n\n` +
1934
2125
  `You'll be woken with a completion message as each finishes; use get_subagent_result({ agent_id }) for retrieval and stall checks.` +
1935
- formatValidationWarnings(taskWarnings)
2126
+ formatValidationWarnings(taskWarnings) +
2127
+ degradedReport()
1936
2128
  }],
1937
2129
  details: undefined,
1938
2130
  };
@@ -1944,8 +2136,11 @@ export default function (pi: ExtensionAPI) {
1944
2136
  // (tasks fan-out): the session-manager import, the spawn call, live-monitor
1945
2137
  // registration, footer counters, the 2s progress poller and the default
1946
2138
  // deadline timer live here exactly once. Callers keep their own prelude,
1947
- // checks, validations and result formatting. THROWS on spawn failure —
1948
- // callers translate the error into their own result shape.
2139
+ // checks, validations and result formatting. THROWS only on spawn failure —
2140
+ // callers translate THAT into their own failure shape. Everything after the
2141
+ // spawn is contained (issue #439): it returns `{ agent, identity,
2142
+ // tailFailures }`, and a non-empty `tailFailures` is a STARTED run with
2143
+ // degraded monitoring, never a failed spawn.
1949
2144
  // -------------------------------------------------------------------
1950
2145
 
1951
2146
  async function startBackgroundAgent(
@@ -1976,8 +2171,8 @@ export default function (pi: ExtensionAPI) {
1976
2171
  // Option B U3 (D4): recovery posture snapshot for the background run.
1977
2172
  recoveryPosture?: RecoveryMode;
1978
2173
  },
1979
- ): Promise<BackgroundAgent> {
1980
- const { spawnBackgroundSession, setAgentFinalOutput, extractFinalOutput, updateAgentStatus } = await import('./session-manager');
2174
+ ): Promise<BackgroundAgentSpawnResult> {
2175
+ const { spawnBackgroundSession, setAgentFinalOutput, extractFinalOutput } = await import('./session-manager');
1981
2176
  // Issue #31 (PR #76 review, DRY): extract final output from a
1982
2177
  // possibly-released ref — the poller may observe a terminal agent
1983
2178
  // whose ref was already nulled by the settlement path.
@@ -1997,6 +2192,8 @@ export default function (pi: ExtensionAPI) {
1997
2192
  resumeContext: spawn.resumeContext,
1998
2193
  cwd: spawn.cwd,
1999
2194
  toolOptions: spawn.toolOptions,
2195
+ // Issue #453: the deadline rides the spawn's own timer (one owner). The
2196
+ // caller passes the budget only — no ownership flag, no timer of its own.
2000
2197
  timeout: spawn.timeout,
2001
2198
  gitMode: spawn.gitMode,
2002
2199
  // Issue #98/#108: snapshotOriginalParams is the single source of truth
@@ -2010,223 +2207,286 @@ export default function (pi: ExtensionAPI) {
2010
2207
  recoveryPosture: spawn.recoveryPosture,
2011
2208
  });
2012
2209
 
2210
+ // -----------------------------------------------------------------
2211
+ // Post-spawn containment (issue #439).
2212
+ //
2213
+ // The session EXISTS from here on: the run is live and will wake the
2214
+ // conductor however this tail behaves. A fault in the tail must therefore
2215
+ // classify the run as STARTED with degraded monitoring — never as a failed
2216
+ // spawn. Before this containment an escaping throw reached the callers'
2217
+ // catch, which said "Failed to spawn background agent" while the agent was
2218
+ // running, and the transport retry read that as "did not start".
2219
+ //
2220
+ // Boundary statement (falsifiable). Two different records, and only one of
2221
+ // them is read here:
2222
+ // - `identity` below is a plain record THIS module constructs. Reading its
2223
+ // properties cannot throw; only a monkey-patched accessor could, and this
2224
+ // module never installs one. A fault that wants to reach the degraded
2225
+ // report must therefore be injected at a STATEMENT (a throwing
2226
+ // registerLiveSubagent, a throwing scheduler, a rejecting spawn), which is
2227
+ // what the #439 tests do.
2228
+ // - `agent` (the live record from the spawn) is read ONLY by the identity
2229
+ // capture immediately below and by the poller's terminal-state guard;
2230
+ // every later statement reads `identity` and the captured
2231
+ // primitives instead. The capture itself sits before the outer try, so a
2232
+ // getter-backed `agent` (which the production spawn cannot produce but an
2233
+ // injected one can) would still escape to the caller's catch — that is the
2234
+ // one unpinned read, stated rather than claimed away (2026-11-07 review).
2235
+ // The callers format their results from `identity` alone, so an
2236
+ // adversarial accessor on the live record cannot reach the report text.
2237
+ // If a future change makes `identity` a proxy or getter-backed, this boundary
2238
+ // is void: the failing test is the one asserting a started run never reports
2239
+ // "Failed to spawn".
2240
+ //
2241
+ // Two independently contained groups record into `tailFailures` — G1
2242
+ // bookkeeping, G2 poller — so a fault in one never skips the other. The
2243
+ // deadline is NOT one of them (issue #453): it is the spawn's, armed before
2244
+ // the spawn returned, so no statement here can leave a run unbounded. An
2245
+ // outer catch backstops the ledger itself, and the degraded result is
2246
+ // assembled from `identity` only.
2247
+ // -----------------------------------------------------------------
2248
+ const identity: BackgroundAgentIdentity = {
2249
+ id: agent.id,
2250
+ label: spawn.description,
2251
+ description: agent.description,
2252
+ task: agent.task,
2253
+ status: agent.status,
2254
+ model: agent.model,
2255
+ };
2256
+
2257
+ const tailFailures: string[] = [];
2258
+ /** Record a contained fault. The text reaches the conductor and the user: sanitize. */
2259
+ const recordTailFailure = (group: string, err: unknown): void => {
2260
+ tailFailures.push(
2261
+ `${group}: ${sanitizeErrorMessage(err instanceof Error ? err.message : String(err), spawn.sanitizeCwd)}`,
2262
+ );
2263
+ };
2264
+
2265
+ let pollInterval: ReturnType<typeof setInterval> | undefined;
2266
+ /** G1 completed the counter increment — the ONLY runs that may decrement. */
2267
+ let countedForThisRun = false;
2268
+ let completed = false;
2269
+
2270
+ /** Stop the live-poll. The deadline is NOT the caller's to stop (issue #453). */
2271
+ const stopTailPolling = (): void => {
2272
+ if (pollInterval !== undefined) clearInterval(pollInterval);
2273
+ };
2274
+
2275
+ /**
2276
+ * Release this run's live counter — the ONE decrement shape for all five
2277
+ * poller/deadline sites. Gated on `countedForThisRun` AND on the finalize
2278
+ * claim: a run that never incremented (G1 failed before it) must not
2279
+ * decrement, and a run the stale sweep already finalized had its decrement
2280
+ * taken there (PR #71 review). The first gate is what keeps the ordering in
2281
+ * G1 honest — without it, a row registered before the increment let the
2282
+ * sweep's decrement land on a SIBLING's count.
2283
+ *
2284
+ * Belt-and-braces, stated as such (2026-11-07 review): with the current
2285
+ * increment-first order in G1, `countedForThisRun` is always true by the time
2286
+ * any callback can call this, so removing the flag alone changes nothing and
2287
+ * no test pins it (an extra removal mutant survived). It is kept because the
2288
+ * ORDERING is the real invariant: when the row is registered before the
2289
+ * increment, the flag is the only thing standing between a settle and a
2290
+ * sibling's count — M8 (reorder G1) fails T2b exactly because of it.
2291
+ *
2292
+ * Stated limit: the decrement is only reachable from a monitor that a run
2293
+ * owns. If G1 AND G2 BOTH fail for the same run (counted, no row, no poller)
2294
+ * nothing can release its count, so the footer's active count stays one high
2295
+ * for the session. That is the honest reading — the run is real and
2296
+ * unmonitored — and the alternative (releasing from a group that never
2297
+ * attached) is how a sibling's count gets stolen.
2298
+ *
2299
+ * Issue #453: the deadline used to be a third releaser. It is not any more
2300
+ * and does not need to be — the poller sees the spawn's `stopped` +
2301
+ * `completedAt` on its next tick and releases there, which is exactly how an
2302
+ * explicit-timeout run has always been released.
2303
+ */
2304
+ const releaseLiveCount = (): void => {
2305
+ if (!countedForThisRun) return;
2306
+ if (!state.finalizeLiveSubagent(identity.id)) return;
2307
+ state.activeSubagents--;
2308
+ if (state.activeSubagents < 0) state.activeSubagents = 0;
2309
+ };
2310
+
2013
2311
  // Issue #318 (from #316 review): the two poller crash sites share one
2014
2312
  // claimed notification envelope. Content is the only variable; the
2015
2313
  // claim guard, display, details and deliverAs live here once.
2314
+ // Issue #439: best-effort — the claim and the send sit in their own try, so
2315
+ // neither a throwing claim nor a throwing send can turn a crash notice into
2316
+ // a fault on the run's reporting path.
2016
2317
  const sendCrashNotice = (content: string): void => {
2017
- if (claimTerminalNotice(agent.id)) {
2318
+ try {
2319
+ if (!claimTerminalNotice(identity.id)) return;
2320
+ } catch {
2321
+ return;
2322
+ }
2323
+ try {
2018
2324
  pi.sendMessage({
2019
2325
  customType: "subagent-notification",
2020
2326
  content,
2021
2327
  display: true,
2022
- details: { agentId: agent.id }
2328
+ details: { agentId: identity.id }
2023
2329
  }, { deliverAs: "followUp" });
2024
- }
2330
+ } catch { /* best-effort */ }
2025
2331
  };
2026
2332
 
2027
- // Register for live monitor
2028
- state.registerLiveSubagent(agent.id, {
2029
- id: agent.id,
2030
- label: agent.description,
2031
- task: agent.task,
2032
- model: agent.model,
2033
- thinkingLevel: agent.thinkingLevel,
2034
- priority: agent.priority,
2035
- startedAt: agent.startedAt,
2036
- ctx,
2037
- });
2038
-
2039
- // Update footer counters
2040
- state.activeSubagents++;
2041
- repaintStatus(state, ctx);
2333
+ try {
2334
+ // ---- G1: bookkeeping ------------------------------------------
2335
+ // Ordering (issue #439, measured): counter FIRST, then the live row,
2336
+ // then the repaint. A row therefore always implies a counted run, so the
2337
+ // stale sweep's decrement can only release this run's own count.
2338
+ try {
2339
+ state.activeSubagents++;
2340
+ countedForThisRun = true;
2341
+ state.registerLiveSubagent(identity.id, {
2342
+ id: identity.id,
2343
+ label: identity.description,
2344
+ task: identity.task,
2345
+ model: identity.model,
2346
+ thinkingLevel: agent.thinkingLevel,
2347
+ priority: agent.priority,
2348
+ startedAt: agent.startedAt,
2349
+ // Issue #423: the persisted EFFECTIVE budget, anchored on the record's
2350
+ // own start clock — the same clock the deadline timers use.
2351
+ ...(agent.timeoutMs !== undefined
2352
+ ? { deadlineAt: agent.startedAt + agent.timeoutMs }
2353
+ : {}),
2354
+ ctx,
2355
+ });
2356
+ repaintStatus(state, ctx);
2357
+ } catch (err) {
2358
+ recordTailFailure("live-monitor bookkeeping", err);
2359
+ }
2042
2360
 
2043
- let completed = false;
2044
-
2045
- // Poll for live progress
2046
- const pollInterval = setInterval(() => {
2361
+ // ---- G2: live progress poller --------------------------------
2362
+ // Issue #453: this poller is the CLEANUP OWNER for a deadline stop. The
2363
+ // spawn's timer sets `status: 'stopped'` + `completedAt` (via
2364
+ // updateAgentStatus) and aborts; on its next tick the poller below sees
2365
+ // the terminal record and does every caller-owned step — output capture,
2366
+ // the finalize claim, the counter decrement, the repaint — then stops
2367
+ // itself. Nothing here arms or clears a deadline.
2047
2368
  try {
2048
- if (completed) return;
2049
-
2050
- const session = agent._sessionRef;
2051
- // Issue #31: a nulled ref on a TERMINAL agent is expected (the
2052
- // settlement path releases the ref) — fall through to finalize
2053
- // below instead of treating it as a crash. A nulled ref on a
2054
- // live agent is still a crash.
2055
- if (!session && !agent.completedAt) {
2056
- // Session ref not available — session may have crashed.
2057
- // Defensive: the ref is assigned synchronously before the poller starts
2058
- // and is never nulled, so this is mostly unreachable — but keep the
2059
- // bookkeeping safe regardless.
2060
- completed = true;
2061
- clearInterval(pollInterval);
2062
- clearTimeout(hardCapHandle);
2063
- // Capture whatever output exists (may be empty — fine).
2064
- setAgentFinalOutput(agent.id, state.subagentSessions.get(agent.id)?.liveOutput ?? '');
2065
- // Gate the counter on the finalize claim: if the
2066
- // stale sweep already finalized this entry, the
2067
- // decrement happened there (PR #71 review).
2068
- if (state.finalizeLiveSubagent(agent.id)) {
2069
- state.activeSubagents--;
2070
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2071
- }
2072
- state.failedSubagents++;
2073
- repaintStatus(state, ctx);
2074
- sendCrashNotice(`Background agent "${agent.description}" crashed.`);
2075
- return;
2076
- }
2077
-
2078
- // While running, update the live monitor.
2079
- // Once completedAt is set, skip straight to finalize below.
2080
- // Issue #31: past the guard above, the only nulled-ref path left is a
2081
- // TERMINAL agent (settlement releases the ref), so a live agent always
2082
- // has its session — the guard already returned on the live-nulled-ref
2083
- // crash path. The compiler can't correlate the two checks, so assert it.
2084
- if (!agent.completedAt) {
2085
- const finalOutput = extractFinalOutput(session!);
2086
-
2369
+ pollInterval = setInterval(() => {
2087
2370
  try {
2088
- const stats = session!.getSessionStats();
2089
- state.updateLiveSubagent(agent.id, finalOutput, stats.tokens.input, stats.tokens.output);
2090
- } catch {
2091
- state.updateLiveSubagent(agent.id, finalOutput, 0, 0);
2092
- }
2093
- }
2094
-
2095
- // Authoritative completion: the prompt promise settled — status and
2096
- // completedAt are set by .then()/.catch() in spawnBackgroundSession.
2097
- // Do NOT rely on !session.isStreaming: it is false during prompt()
2098
- // preflight (auth check, model resolution) and for failed starts.
2099
- if (agent.completedAt) {
2100
- completed = true;
2101
- clearInterval(pollInterval);
2102
- clearTimeout(hardCapHandle);
2103
-
2104
- // Issue #31: prefer the output already captured at settlement;
2105
- // the ref may already be nulled on terminal agents, so never
2106
- // overwrite with empty and stay null-safe.
2107
- const finalOutput = agent.finalOutput ?? extractAgentFinalOutput(agent);
2108
- setAgentFinalOutput(agent.id, finalOutput);
2109
-
2110
- // Gate the counter on the finalize claim: if the
2111
- // stale sweep already finalized this entry, the
2112
- // decrement happened there (PR #71 review).
2113
- if (state.finalizeLiveSubagent(agent.id)) {
2114
- state.activeSubagents--;
2115
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2116
- }
2117
-
2118
- if (agent.status === 'failed') {
2119
- state.failedSubagents++;
2120
- repaintStatus(state, ctx);
2121
- // Issue #315: the terminal wake (`subagent-completion`, emitted by
2122
- // the session-manager settle) is the ONE notice for a failed run.
2123
- // The status here was set by that settle, so the wake already
2124
- // delivered — this legacy poller notice would duplicate it.
2125
- } else if (agent.status === 'stopped') {
2126
- // User-initiated stop (stop_subagent) or deadline abort
2127
- // (timeout/deadline) — not a failure.
2128
- repaintStatus(state, ctx);
2129
- } else {
2130
- state.completedSubagents++;
2131
- state.unseenSubagents++;
2132
- repaintStatus(state, ctx);
2371
+ if (completed) return;
2372
+
2373
+ const session = agent._sessionRef;
2374
+ // Issue #31: a nulled ref on a TERMINAL agent is expected (the
2375
+ // settlement path releases the ref) — fall through to finalize
2376
+ // below instead of treating it as a crash. A nulled ref on a
2377
+ // live agent is still a crash.
2378
+ if (!session && !agent.completedAt) {
2379
+ // Session ref not available — session may have crashed.
2380
+ // Defensive: the ref is assigned synchronously before the poller starts
2381
+ // and is never nulled, so this is mostly unreachable — but keep the
2382
+ // bookkeeping safe regardless.
2383
+ completed = true;
2384
+ stopTailPolling();
2385
+ // Capture whatever output exists (may be empty — fine).
2386
+ setAgentFinalOutput(identity.id, state.subagentSessions.get(identity.id)?.liveOutput ?? '');
2387
+ releaseLiveCount();
2388
+ state.failedSubagents++;
2389
+ repaintStatus(state, ctx);
2390
+ sendCrashNotice(`Background agent "${identity.description}" crashed.`);
2391
+ return;
2392
+ }
2393
+
2394
+ // While running, update the live monitor.
2395
+ // Once completedAt is set, skip straight to finalize below.
2396
+ // Issue #31: past the guard above, the only nulled-ref path left is a
2397
+ // TERMINAL agent (settlement releases the ref), so a live agent always
2398
+ // has its session — the guard already returned on the live-nulled-ref
2399
+ // crash path. The compiler can't correlate the two checks, so assert it.
2400
+ if (!agent.completedAt) {
2401
+ const finalOutput = extractFinalOutput(session!);
2402
+
2403
+ try {
2404
+ const stats = session!.getSessionStats();
2405
+ state.updateLiveSubagent(identity.id, finalOutput, stats.tokens.input, stats.tokens.output);
2406
+ } catch {
2407
+ state.updateLiveSubagent(identity.id, finalOutput, 0, 0);
2408
+ }
2409
+ }
2410
+
2411
+ // Authoritative completion: the prompt promise settled — status and
2412
+ // completedAt are set by .then()/.catch() in spawnBackgroundSession.
2413
+ // Do NOT rely on !session.isStreaming: it is false during prompt()
2414
+ // preflight (auth check, model resolution) and for failed starts.
2415
+ if (agent.completedAt) {
2416
+ completed = true;
2417
+ stopTailPolling();
2418
+
2419
+ // Issue #31: prefer the output already captured at settlement;
2420
+ // the ref may already be nulled on terminal agents, so never
2421
+ // overwrite with empty and stay null-safe.
2422
+ const finalOutput = agent.finalOutput ?? extractAgentFinalOutput(agent);
2423
+ setAgentFinalOutput(identity.id, finalOutput);
2424
+
2425
+ releaseLiveCount();
2426
+
2427
+ if (agent.status === 'failed') {
2428
+ state.failedSubagents++;
2429
+ repaintStatus(state, ctx);
2430
+ // Issue #315: the terminal wake (`subagent-completion`, emitted by
2431
+ // the session-manager settle) is the ONE notice for a failed run.
2432
+ // The status here was set by that settle, so the wake already
2433
+ // delivered — this legacy poller notice would duplicate it.
2434
+ } else if (agent.status === 'stopped') {
2435
+ // User-initiated stop (stop_subagent) or deadline abort
2436
+ // (timeout/deadline) — not a failure.
2437
+ repaintStatus(state, ctx);
2438
+ } else {
2439
+ state.completedSubagents++;
2440
+ state.unseenSubagents++;
2441
+ repaintStatus(state, ctx);
2442
+ }
2443
+ }
2444
+ } catch (err) {
2445
+ if (!completed) {
2446
+ completed = true;
2447
+ stopTailPolling();
2448
+ try {
2449
+ setAgentFinalOutput(identity.id, extractAgentFinalOutput(agent));
2450
+ } catch { /* ignore */ }
2451
+ releaseLiveCount();
2452
+ state.failedSubagents++;
2453
+ repaintStatus(state, ctx);
2454
+ sendCrashNotice(`Background agent "${identity.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
2455
+ }
2133
2456
  }
2134
- }
2457
+ }, 2000);
2135
2458
  } catch (err) {
2136
- if (!completed) {
2137
- completed = true;
2138
- clearInterval(pollInterval);
2139
- clearTimeout(hardCapHandle);
2140
- try {
2141
- setAgentFinalOutput(agent.id, extractAgentFinalOutput(agent));
2142
- } catch { /* ignore */ }
2143
- // Gate the counter on the finalize claim: if the
2144
- // stale sweep already finalized this entry, the
2145
- // decrement happened there (PR #71 review).
2146
- if (state.finalizeLiveSubagent(agent.id)) {
2147
- state.activeSubagents--;
2148
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2149
- }
2150
- state.failedSubagents++;
2151
- repaintStatus(state, ctx);
2152
- sendCrashNotice(`Background agent "${agent.description}" crashed: ${sanitizeErrorMessage((err as Error).message, spawn.sanitizeCwd)}`);
2153
- }
2459
+ recordTailFailure("progress polling", err);
2154
2460
  }
2155
- }, 2000);
2156
-
2157
- // Default deadline: stop polling AND abort the session after the
2158
- // deadline. W2 (issue #28): previously this only stopped the poller —
2159
- // the pi session kept running forever (orphaned). Now it pre-sets
2160
- // 'stopped' (so the .then keeps it, per W1) and aborts the session.
2161
- // Issue #240: an explicit per-agent timeout is HONORED verbatim; this
2162
- // deadline DEFAULTS to 30m only when no timeout is given. It is a
2163
- // default, not a ceiling. Issue #244: exactly ONE deadline timer per
2164
- // run — an explicit timeout is owned by the session-manager W3 timer,
2165
- // so this index timer arms ONLY on the no-timeout path, mirroring
2166
- // spawnBackgroundSession's `params.timeout && params.timeout > 0` guard
2167
- // (with no timeout, it owns the 30m default, #28).
2168
- const hasExplicitDeadline = spawn.timeout !== undefined && spawn.timeout > 0;
2169
- const hardCapMs = spawn.timeout ?? DEFAULT_BACKGROUND_DEADLINE_MS;
2170
- const hardCapHandle: ReturnType<typeof setTimeout> | undefined =
2171
- hasExplicitDeadline ? undefined : setTimeout(() => {
2172
- if (!completed && !agent.completedAt) {
2173
- try {
2174
- completed = true;
2175
- clearInterval(pollInterval);
2176
- // Pre-set stopped BEFORE aborting so the .then in
2177
- // spawnBackgroundSession keeps the stopped state.
2178
- updateAgentStatus(agent.id, 'stopped', `Timed out (${hardCapMs}ms deadline)`);
2179
- agent._sessionRef?.abort().catch(() => {
2180
- // Abort may reject if the session is mid-dispose;
2181
- // the status flip above is already recorded.
2182
- });
2183
- // Capture whatever final output exists in the session
2184
- const hardCapSession = agent._sessionRef;
2185
- const hardCapFinalOutput = hardCapSession ? extractFinalOutput(hardCapSession) : '';
2186
- setAgentFinalOutput(agent.id, hardCapFinalOutput);
2187
- // Gate the counter on the finalize claim: if the
2188
- // stale sweep already finalized this entry, the
2189
- // decrement happened there (PR #71 review).
2190
- if (state.finalizeLiveSubagent(agent.id)) {
2191
- state.activeSubagents--;
2192
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2193
- }
2194
- // m6: deadline abort is a stop, not a completion — mirror the
2195
- // W3/poller stopped path (no completedSubagents increment).
2196
- repaintStatus(state, ctx);
2197
- } catch (err) {
2198
- // Defensive: never let the deadline timer throw uncaught — that would
2199
- // skip finalizeLiveSubagent, the counter decrement, and the notification.
2200
- // Do all fallible work first (output capture), then mutate counters,
2201
- // then notify — a throw mid-path can't double-fire mutations.
2202
- completed = true;
2203
- clearInterval(pollInterval);
2204
- // m3: the try may have thrown BEFORE updateAgentStatus ran (e.g.
2205
- // persistAgent fs failure) — leave the record terminal so
2206
- // get_subagent_result doesn't report 'running' and the W3 timer
2207
- // guard (!agent.completedAt) can't re-fire later.
2208
- try {
2209
- updateAgentStatus(agent.id, 'stopped', `Timed out (${hardCapMs}ms deadline)`);
2210
- } catch { /* ignore */ }
2211
- try {
2212
- setAgentFinalOutput(agent.id, extractAgentFinalOutput(agent));
2213
- } catch { /* ignore */ }
2214
- // Gate the counter on the finalize claim: if the
2215
- // stale sweep already finalized this entry, the
2216
- // decrement happened there (PR #71 review).
2217
- if (state.finalizeLiveSubagent(agent.id)) {
2218
- state.activeSubagents--;
2219
- if (state.activeSubagents < 0) state.activeSubagents = 0;
2220
- }
2221
- state.failedSubagents++;
2222
- repaintStatus(state, ctx);
2223
- }
2461
+
2462
+ try {
2463
+ log.info("Background agent spawned", { agentId: identity.id, task: spawn.task, model: identity.model });
2464
+ } catch (err) {
2465
+ recordTailFailure("spawn log", err);
2224
2466
  }
2225
- }, hardCapMs);
2226
-
2227
- log.info("Background agent spawned", { agentId: agent.id, task: spawn.task, model: agent.model });
2467
+ } catch (err) {
2468
+ // Backstop: the groups above swallow their own faults, so this can only
2469
+ // see a fault in the ledger machinery itself. The degraded result below is
2470
+ // assembled from `identity` — never from a property read on `agent`.
2471
+ recordTailFailure("spawn tail", err);
2472
+ }
2473
+
2474
+ if (tailFailures.length > 0) {
2475
+ // ONE advisory per run, after aggregation. It is NOT a terminal notice
2476
+ // and never takes the terminal claim (issue #439 contract): the run's
2477
+ // genuine completion notice is still delivered when it settles.
2478
+ // 2026-11-07 review: this call is INSIDE the outer containment, not after
2479
+ // it — the advisory's own dispatch surfaces are contained too, and the
2480
+ // inner per-channel tries in `sendMonitoringDegradedAdvisory` cover the
2481
+ // case where one channel throws (so one failure cannot lose both).
2482
+ try {
2483
+ sendMonitoringDegradedAdvisory(pi, ctx, identity, tailFailures);
2484
+ } catch (err) {
2485
+ recordTailFailure("monitoring advisory", err);
2486
+ }
2487
+ }
2228
2488
 
2229
- return agent;
2489
+ return { agent, identity, tailFailures };
2230
2490
  }
2231
2491
 
2232
2492
  // -------------------------------------------------------------------
@@ -2261,6 +2521,19 @@ export default function (pi: ExtensionAPI) {
2261
2521
  */
2262
2522
  attemptContext?: string,
2263
2523
  ): Promise<ToolResult<undefined>> {
2524
+ // Issue #443: the DECLARED level, guarded before `bgResolved` clamps it.
2525
+ // This is the seam for the TRANSPORT auto-retry (`scheduleTransportRetry`
2526
+ // re-enters here with `resolveRetryParams`' rebuilt bag and never passes
2527
+ // through `execute`), and the reason a restored record carrying an unknown
2528
+ // level cannot launch a session at pi's default. A rejection here surfaces
2529
+ // as the ORIGINAL failure's notice — the caller reports it unchanged.
2530
+ const bgDeclaredThinkingLevel = declaredThinkingLevel(
2531
+ params.thinkingLevel,
2532
+ resolveDispatchPreset({ ...params, task: singleTask }, state).preset?.thinkingLevel,
2533
+ );
2534
+ const bgDeclaredThinkingError = invalidThinkingLevelRejection(bgDeclaredThinkingLevel);
2535
+ if (bgDeclaredThinkingError) return bgDeclaredThinkingError;
2536
+
2264
2537
  // Phase 6.5: Background execution — spawn session and return ID immediately.
2265
2538
  // Resolve the preset and its model BEFORE the background branch so the
2266
2539
  // preset's model (and system prompt) are honored in background mode.
@@ -2344,7 +2617,7 @@ export default function (pi: ExtensionAPI) {
2344
2617
 
2345
2618
  // Option B U1: durability identity (retry inherits the original dispatch).
2346
2619
  const bgIdentity = newDispatchIdentity(retrySourceRun);
2347
- const agent = await startBackgroundAgent(pi, ctx, {
2620
+ const spawned = await startBackgroundAgent(pi, ctx, {
2348
2621
  // Issue #411: the preamble rides the system-prompt side
2349
2622
  // (`resumeContext`), never the task. The task stays the recorded
2350
2623
  // original, and the snapshot keeps it too, so a later retry of this
@@ -2384,22 +2657,34 @@ export default function (pi: ExtensionAPI) {
2384
2657
  ? `\n\n[auto-routed to preset '${bgAutoRoutedPreset.name}'${bgAutoRouteKeyword ? ` (matched keyword '${bgAutoRouteKeyword}')` : ""} — ${bgResolved.toolOptions ? formatToolRestriction(bgResolved.toolOptions) : formatPresetRestriction(bgAutoRoutedPreset)}]`
2385
2658
  : "";
2386
2659
 
2660
+ // Issue #439: everything the result states comes from `identity`, the plain
2661
+ // record captured at spawn time — never a property read on the live agent.
2662
+ // A non-empty `tailFailures` is a STARTED run with degraded monitoring, so
2663
+ // this stays a success (`isError` false) with the degraded paragraph;
2664
+ // the transport retry reads `isError` as "did not start" and must not see
2665
+ // a started run here.
2387
2666
  return {
2388
2667
  content: [{
2389
2668
  type: "text" as const,
2390
- text: `Background agent started: ${agent.id}\n\n` +
2391
- `Description: ${agent.description}\n` +
2392
- `Task: ${agent.task}\n` +
2393
- `Status: ${agent.status}\n\n` +
2394
- `You'll be woken with a completion message when it finishes; use get_subagent_result({ agent_id: "${agent.id}" }) for retrieval and stall checks.` +
2669
+ text: `Background agent started: ${spawned.identity.id}\n\n` +
2670
+ `Description: ${spawned.identity.description}\n` +
2671
+ `Task: ${spawned.identity.task}\n` +
2672
+ `Status: ${spawned.identity.status}\n\n` +
2673
+ `You'll be woken with a completion message when it finishes; use get_subagent_result({ agent_id: "${spawned.identity.id}" }) for retrieval and stall checks.` +
2395
2674
  bgAutoRouteNote +
2396
2675
  // C: warnings ride the immediate SPAWN result so the conductor
2397
2676
  // can stop/re-dispatch in the same turn.
2398
- formatValidationWarnings(bgPreTask.warnings),
2677
+ formatValidationWarnings(bgPreTask.warnings) +
2678
+ buildMonitoringDegradedParagraph(spawned.identity, spawned.tailFailures),
2399
2679
  }],
2400
2680
  details: undefined,
2681
+ isError: false,
2401
2682
  };
2402
2683
  } catch (err) {
2684
+ // Issue #439: this catch is reachable ONLY for a pre-spawn gate or a
2685
+ // rejected `spawnBackgroundSession`. Everything after a successful spawn
2686
+ // is contained in `startBackgroundAgent` — a run that started never lands
2687
+ // here, so the wording below can never describe a live run.
2403
2688
  const message = sanitizeErrorMessage(
2404
2689
  err instanceof Error ? err.message : String(err),
2405
2690
  bgResolved.effectiveCwd,
@@ -2765,15 +3050,37 @@ export default function (pi: ExtensionAPI) {
2765
3050
  // caller declared no level, so the pre-flight resolves the SAME preset
2766
3051
  // the merge below will (one rule, `resolveDispatchPreset`).
2767
3052
  const declaredPresetForSwitch = resolveDispatchPreset(params, state).preset;
3053
+ // Issue #443: guard the EFFECTIVE DECLARED level here — the per-call value
3054
+ // or the selected preset's (named, or auto-routed by the line above) —
3055
+ // BEFORE `resolveSubagentParams` clamps it. `params.thinkingLevel` is
3056
+ // already the post-template, post-`retryRunId` value by this point, so a
3057
+ // level restored from a run record is judged too; a preset object injected
3058
+ // in memory never passed a schema or the preset-file validator, so this
3059
+ // is its only check. Everything below runs through this one seam: the
3060
+ // single, background, chain, parallel and graph handlers are all reached
3061
+ // from here, and the per-unit declarations are guarded by the pre-passes.
3062
+ const effectiveDeclaredThinkingLevel = declaredThinkingLevel(
3063
+ params.thinkingLevel,
3064
+ declaredPresetForSwitch?.thinkingLevel,
3065
+ );
3066
+ const declaredThinkingError = invalidThinkingLevelRejection(effectiveDeclaredThinkingLevel);
3067
+ if (declaredThinkingError) return declaredThinkingError;
3068
+ // The EFFECTIVE approval mode (call param, else the configured default) —
3069
+ // the same resolver `resolveSubagentParams` and the #361 default use, so the
3070
+ // pre-flight cannot judge a mode the child will not run with. Reading
3071
+ // `params.approvalMode` raw here would miss a config-tier mode entirely.
3072
+ const effectiveApprovalModeForSwitch = resolveEffectiveApprovalMode(
3073
+ params.approvalMode,
3074
+ state,
3075
+ );
2768
3076
  const thinkingSwitch = resolveThinkingDispatchSwitch({
2769
3077
  processChecks,
2770
- thinkingLevel: (params.thinkingLevel ?? declaredPresetForSwitch?.thinkingLevel) as
2771
- | ThinkingLevel
2772
- | undefined,
3078
+ thinkingLevel: effectiveDeclaredThinkingLevel as ThinkingLevel | undefined,
2773
3079
  explicitBackground,
2774
3080
  timeout: params.timeout,
2775
3081
  force: params.force,
2776
3082
  shape: dispatchShape,
3083
+ effectiveApprovalMode: effectiveApprovalModeForSwitch,
2777
3084
  });
2778
3085
  if (thinkingSwitch === "switch") {
2779
3086
  params.background = true;
@@ -2792,6 +3099,34 @@ export default function (pi: ExtensionAPI) {
2792
3099
  details: { thinkingLevel: params.thinkingLevel, previousTimeout: "dropped" },
2793
3100
  }, { deliverAs: "followUp" });
2794
3101
  ctx.ui.notify(THINKING_SWITCH_NOTICE, "warning");
3102
+ } else if (thinkingSwitch === "drop-timeout") {
3103
+ // Issue #431 — the second arm: the shape cannot move (an effective
3104
+ // 'always'/'writes' run needs the interactive gate, and switching an
3105
+ // explicit-foreground 'always' dispatch would be REJECTED — #433), so
3106
+ // the only thing the pre-flight can remove is the deadline. Clearing it
3107
+ // HERE, before `snapshotOriginalParams` records the run (:3035
3108
+ // foreground, :2374 background), is what makes a retry re-derive an
3109
+ // absent deadline instead of restoring the cap (ADR 0009).
3110
+ const previousTimeout = params.timeout;
3111
+ params.timeout = undefined;
3112
+ log.info("Dispatch pre-flight: high-thinking foreground timeout dropped, shape kept", {
3113
+ thinkingLevel: params.thinkingLevel,
3114
+ previousTimeout,
3115
+ effectiveApprovalMode: effectiveApprovalModeForSwitch,
3116
+ });
3117
+ pi.sendMessage({
3118
+ customType: "delegate-notification",
3119
+ content: THINKING_TIMEOUT_DROP_NOTICE,
3120
+ display: true,
3121
+ details: {
3122
+ thinkingLevel: params.thinkingLevel,
3123
+ // The ACTUAL ms value, not "dropped": the friction log needs the
3124
+ // number to tell a budget cap from a tight clock.
3125
+ previousTimeout,
3126
+ effectiveApprovalMode: effectiveApprovalModeForSwitch,
3127
+ },
3128
+ }, { deliverAs: "followUp" });
3129
+ ctx.ui.notify(THINKING_TIMEOUT_DROP_NOTICE, "warning");
2795
3130
  } else if (thinkingSwitch === "forced") {
2796
3131
  // The override is recorded, not silent: the dispatch text is the reason
2797
3132
  // (`force` has no reason field — ADR 0007's contract stays unchanged).
@@ -2839,6 +3174,26 @@ export default function (pi: ExtensionAPI) {
2839
3174
  // unit retries as a single foreground run (issue #229), unaffected here.
2840
3175
  params.background ??= useBackground;
2841
3176
 
3177
+ // Issue #434: the unit projection's inputs, resolved ONCE here so no
3178
+ // unit site can re-derive them (a relative `params.cwd` re-read of the
3179
+ // manifest measured `false` where this resolution measured `true`).
3180
+ // `noticeEmitted` starts true when the DISPATCH arm announced its own
3181
+ // change: the drop still reaches every eligible unit, but the dispatch
3182
+ // already spoke, and a second notice would double-report one decision.
3183
+ // (`forced` emits nothing — the caller asked for the explicit pair, so
3184
+ // there is nothing to announce and no arm acted.)
3185
+ const batchGuard: BatchGuardContext = {
3186
+ processChecks,
3187
+ dispatchDeclaredLevel: effectiveDeclaredThinkingLevel as ThinkingLevel | undefined,
3188
+ force: params.force as boolean | undefined,
3189
+ // A `tasks` fan-out spawns detached background units (their deadline is
3190
+ // the legitimate budget); every other batch handler runs its units
3191
+ // foreground. Chain/graph can never be background: an explicit
3192
+ // `background: true` batch was rejected above.
3193
+ unitShape: isParallel && useBackground ? "background" : "foreground",
3194
+ noticeEmitted: thinkingSwitch === "switch" || thinkingSwitch === "drop-timeout",
3195
+ };
3196
+
2842
3197
  if (isChain) {
2843
3198
  if (params.chain!.length > MAX_CHAIN_STEPS) {
2844
3199
  return {
@@ -2852,7 +3207,7 @@ export default function (pi: ExtensionAPI) {
2852
3207
  isError: true,
2853
3208
  };
2854
3209
  }
2855
- return runChainMode(params, signal, onUpdate, ctx);
3210
+ return runChainMode(params, signal, onUpdate, ctx, batchGuard);
2856
3211
  }
2857
3212
 
2858
3213
  if (isParallel) {
@@ -2868,12 +3223,12 @@ export default function (pi: ExtensionAPI) {
2868
3223
  isError: true,
2869
3224
  };
2870
3225
  }
2871
- if (useBackground) return runBackgroundFanOut(pi, ctx, params, signal);
2872
- return runParallelMode(params, signal, onUpdate, ctx);
3226
+ if (useBackground) return runBackgroundFanOut(pi, ctx, params, signal, batchGuard);
3227
+ return runParallelMode(params, signal, onUpdate, ctx, batchGuard);
2873
3228
  }
2874
3229
 
2875
3230
  if (isGraph) {
2876
- return runGraphMode(params, signal, onUpdate, ctx);
3231
+ return runGraphMode(params, signal, onUpdate, ctx, batchGuard);
2877
3232
  }
2878
3233
 
2879
3234
  // Single mode: isSingle is true (modeCount===1, none of chain/parallel/graph),
@@ -3038,11 +3393,23 @@ export default function (pi: ExtensionAPI) {
3038
3393
  pruneHistoryIfNeeded(state, ctx, log);
3039
3394
 
3040
3395
  // Register for live monitor
3041
- registerLiveRun(state, run, ctx);
3396
+ // Issue #423: the merged timeout is the display deadline (absent → no
3397
+ // deadline; a foreground run has no 30m default).
3398
+ registerLiveRun(state, run, ctx, undefined, timeout);
3042
3399
 
3043
3400
  // P3: Git integration — set up work branch if gitMode is "branch"
3044
3401
  let headState: HeadState | undefined;
3045
3402
  let workBranchName: string | undefined;
3403
+ // Issue #466 (ADR 0026 D6): the foreground path creates the same work
3404
+ // branch with the same crash exposure, so it writes and clears the same
3405
+ // durable record — with `kind: "foreground"`, so "no record" means "no
3406
+ // orphan" for every branch run, not just background ones.
3407
+ let headStateRoot: string | undefined;
3408
+ const clearForegroundHeadState = (): void => {
3409
+ if (!headStateRoot) return;
3410
+ clearHeadState(headStateRoot);
3411
+ headStateRoot = undefined;
3412
+ };
3046
3413
  if (resolvedGitMode === "branch") {
3047
3414
  try {
3048
3415
  headState = getHeadState(resolvedCwd);
@@ -3053,9 +3420,27 @@ export default function (pi: ExtensionAPI) {
3053
3420
  });
3054
3421
  }
3055
3422
 
3056
- const branchResult = createWorkBranch(resolvedCwd, headState.sha);
3423
+ // Written BEFORE the branch exists (D1): the name must be minted here.
3424
+ headStateRoot = getRepoRoot(resolvedCwd) ?? resolvedCwd;
3425
+ workBranchName = newWorkBranchName();
3426
+ if (!writeHeadState({
3427
+ version: HEAD_STATE_VERSION,
3428
+ repoRoot: headStateRoot,
3429
+ runId: run.id,
3430
+ kind: "foreground",
3431
+ base: headState,
3432
+ workBranch: workBranchName,
3433
+ owner: currentProcessOwner(),
3434
+ createdAt: new Date().toISOString(),
3435
+ })) {
3436
+ log.warn("headState record could not be written — an interrupted run will name no base", {
3437
+ runId: run.id,
3438
+ workBranch: workBranchName,
3439
+ });
3440
+ }
3441
+
3442
+ const branchResult = createWorkBranch(resolvedCwd, headState.sha, workBranchName);
3057
3443
  if (branchResult.ok) {
3058
- workBranchName = branchResult.branch;
3059
3444
  log.info("Created work branch for subagent", {
3060
3445
  branch: workBranchName,
3061
3446
  base: headState.branch,
@@ -3064,12 +3449,16 @@ export default function (pi: ExtensionAPI) {
3064
3449
  log.error("Failed to create work branch, falling back to 'none'", {
3065
3450
  error: branchResult.error,
3066
3451
  });
3452
+ // Nothing was created: nothing to repair.
3453
+ clearForegroundHeadState();
3067
3454
  headState = undefined;
3455
+ workBranchName = undefined;
3068
3456
  }
3069
3457
  } catch (err) {
3070
3458
  log.warn("Not a git repository or git error; falling back to gitMode 'none'", {
3071
3459
  error: (err as Error).message,
3072
3460
  });
3461
+ clearForegroundHeadState();
3073
3462
  headState = undefined;
3074
3463
  workBranchName = undefined;
3075
3464
  }
@@ -3088,6 +3477,9 @@ export default function (pi: ExtensionAPI) {
3088
3477
  branch: headState.branch,
3089
3478
  detached: headState.detached,
3090
3479
  });
3480
+ // Issue #466: verified off the work branch — the record is done.
3481
+ // A FAILED restore keeps it: the base lives only in the record.
3482
+ clearForegroundHeadState();
3091
3483
  } else {
3092
3484
  log.warn("Failed to restore original HEAD during cleanup", {
3093
3485
  branch: headState.branch,
@@ -3252,6 +3644,12 @@ export default function (pi: ExtensionAPI) {
3252
3644
  result.errorMessage?.includes("timed out")
3253
3645
  ) {
3254
3646
  log.info("Auto-retrying after timeout", { runId });
3647
+ // Issue #423: the retry restarts the clock, so its display deadline is
3648
+ // re-anchored on it (the same clock `startedAt` carries). Registering
3649
+ // also clears the finalize claim, so the row is live again.
3650
+ const retryStartedAt = Date.now();
3651
+ const retryDeadlineAt =
3652
+ timeout && timeout > 0 ? retryStartedAt + timeout : undefined;
3255
3653
  state.registerLiveSubagent(runId, {
3256
3654
  id: runId,
3257
3655
  label,
@@ -3259,7 +3657,8 @@ export default function (pi: ExtensionAPI) {
3259
3657
  model: run.model,
3260
3658
  thinkingLevel,
3261
3659
  priority: params.priority,
3262
- startedAt: Date.now(),
3660
+ startedAt: retryStartedAt,
3661
+ ...(retryDeadlineAt !== undefined ? { deadlineAt: retryDeadlineAt } : {}),
3263
3662
  ctx,
3264
3663
  });
3265
3664
 
@@ -3320,6 +3719,9 @@ export default function (pi: ExtensionAPI) {
3320
3719
  branch: headState.branch,
3321
3720
  detached: headState.detached,
3322
3721
  });
3722
+ // Issue #466: the tree is verified off the work branch, so the
3723
+ // durable record has nothing left to repair.
3724
+ clearForegroundHeadState();
3323
3725
 
3324
3726
  // P4: Change approval workflow — let user review the diff
3325
3727
  const diffContent = (result.gitDiff ?? "").trim();
@@ -3423,7 +3825,7 @@ export default function (pi: ExtensionAPI) {
3423
3825
 
3424
3826
  // E4: SLA tracking — compute metrics if enabled
3425
3827
  if (state.config.slaTrackingEnabled) {
3426
- const recentRuns = state.getRunEntries(ctx).slice(0, state.config.slaWindowSize);
3828
+ const recentRuns = state.getLogicalRunEntries(ctx).slice(0, state.config.slaWindowSize);
3427
3829
  const metrics = computeSLAMetrics(recentRuns);
3428
3830
  log.info("SLA metrics computed", {
3429
3831
  totalRuns: metrics.totalRuns,
@@ -3662,6 +4064,17 @@ export default function (pi: ExtensionAPI) {
3662
4064
  resultText += `Completed: ${new Date(agent.completedAt).toISOString()}\n`;
3663
4065
  resultText += `Duration: ${agent.completedAt - agent.startedAt}ms\n`;
3664
4066
  }
4067
+
4068
+ // Issue #423: the budget the run actually ran under — from the PERSISTED
4069
+ // record, so it survives the closure that armed the timer. The result
4070
+ // path has no run entry to consult, so the timeout evidence is the
4071
+ // agent's own error stamp (one shared predicate owns both paths).
4072
+ const budgetLine = formatBudgetLine(
4073
+ agent,
4074
+ normalizeCompletionStatus(agent.status),
4075
+ undefined,
4076
+ );
4077
+ if (budgetLine) resultText += `${budgetLine}\n`;
3665
4078
 
3666
4079
  if (agent.error) {
3667
4080
  resultText += `Error: ${agent.error}\n`;
@@ -3870,18 +4283,96 @@ export default function (pi: ExtensionAPI) {
3870
4283
  if (record.kind === "agent") markAgentInterrupted(record.id, interruptedAt);
3871
4284
  return durable;
3872
4285
  },
4286
+ // Issue #447: a dispatch whose acceptance marker is still `null` never
4287
+ // reached `session.prompt()`. It is finalized `failed` here — a
4288
+ // terminal write, so `persistRunRecord` retires the registry entry in
4289
+ // the same call and no interrupted/retry surface can pick it up.
4290
+ finalizeNeverStarted: (run) => {
4291
+ state.persistRun(pi, run);
4292
+ },
3873
4293
  });
3874
4294
  // Report the scan whenever it did anything durable OR attempted a mark
3875
4295
  // that failed — a failure-only boot must not be silent (issue #304).
3876
4296
  if (summary.marked > 0 || summary.markFailures > 0) {
3877
4297
  log.warn("Boot recovery marked interrupted runs", { ...summary });
3878
4298
  }
4299
+ // Issue #447: never-started dispatches are finalized, not marked — a
4300
+ // separate line so the two outcomes cannot be read as one another.
4301
+ if (summary.neverStarted > 0) {
4302
+ log.info("Boot recovery finalized never-started dispatches", {
4303
+ count: summary.neverStarted,
4304
+ });
4305
+ }
3879
4306
  } catch (err) {
3880
4307
  // Recovery is best-effort hygiene — it must never break session start.
3881
4308
  log.warn("Boot recovery scan failed", { error: (err as Error).message });
3882
4309
  }
3883
4310
  }
3884
4311
 
4312
+ /**
4313
+ * Issue #466 (ADR 0026 D2): the git/process surface the head-state table
4314
+ * reads, wired once so the boot step and its tests cannot drift apart.
4315
+ */
4316
+ function headStateDeps(): HeadStateDeps {
4317
+ const procDeps = defaultRecoveryDeps();
4318
+ return {
4319
+ getRepoRoot,
4320
+ classifyOwner: (owner) => classifyOwner(owner, procDeps),
4321
+ getHeadBranch,
4322
+ restoreHead,
4323
+ hasUncommittedChanges,
4324
+ listWorkBranches,
4325
+ };
4326
+ }
4327
+
4328
+ /**
4329
+ * Issue #466: the boot's ONE git-mutating step, between the scan (which only
4330
+ * marks records) and the notices. Best-effort like the scan — a failing store
4331
+ * must never break session start — but every record still ends in exactly one
4332
+ * LOGGED verdict (D5: silence is not a verdict).
4333
+ *
4334
+ * The repair itself is NEVER gated by `config.recovery`: a tree left on a dead
4335
+ * run's branch is a correctness problem, not a recovery offer. Only the notice
4336
+ * below is gated.
4337
+ */
4338
+ function reconcileHeadStatesAtBoot(): HeadStateOutcome[] {
4339
+ try {
4340
+ const outcomes = reconcileHeadStates(headStateDeps());
4341
+ for (const outcome of outcomes) {
4342
+ log.info("Boot head-state verdict", { ...outcome });
4343
+ }
4344
+ // Housekeeping, never part of the repair contract: only a record whose
4345
+ // repository no longer resolves (or that cannot be parsed) is swept, so
4346
+ // a live orphan's base is never deleted by age.
4347
+ const swept = sweepHeadStates({
4348
+ repoGone: (record) => getRepoRoot(record.repoRoot) === undefined,
4349
+ });
4350
+ if (swept > 0) log.info("Swept stale head-state records", { count: swept });
4351
+ return outcomes;
4352
+ } catch (err) {
4353
+ log.warn("Boot head-state reconciliation failed", { error: (err as Error).message });
4354
+ return [];
4355
+ }
4356
+ }
4357
+
4358
+ /**
4359
+ * Issue #466 (D5): the repair and the needs-manual verdict reach the user
4360
+ * once, on the same `nextTurn` channel as the recovery notice, and are gated
4361
+ * by `config.recovery !== "off"` like every other boot surface.
4362
+ */
4363
+ function maybeSendHeadStateNotice(outcomes: HeadStateOutcome[]): void {
4364
+ if (state.config.recovery === "off") return;
4365
+ const notice = buildHeadStateNotice(outcomes);
4366
+ if (!notice) return;
4367
+ try {
4368
+ pi.sendMessage(notice, resolveRecoveryNoticeDelivery());
4369
+ log.info("Head-state notice delivered", { count: notice.details.count });
4370
+ } catch (err) {
4371
+ // The notice is best-effort — it must never break session start.
4372
+ log.warn("Head-state notice failed", { error: (err as Error).message });
4373
+ }
4374
+ }
4375
+
3885
4376
  /**
3886
4377
  * Option B U3 Fix A: the recovery visibility bridge, wired for the two
3887
4378
  * extension consumers that resolve a run id (the retryRunId branch and the
@@ -3895,7 +4386,7 @@ export default function (pi: ExtensionAPI) {
3895
4386
  ctx: ExtensionContext,
3896
4387
  getAgent: RecoveryAgentLookup,
3897
4388
  ): SubagentRun[] {
3898
- return visibleRunEntriesForSession(state.getRunEntries(ctx), getAgent);
4389
+ return visibleRunEntriesForSession(state.getLogicalRunEntries(ctx), getAgent);
3899
4390
  }
3900
4391
 
3901
4392
  /**
@@ -4013,10 +4504,18 @@ export default function (pi: ExtensionAPI) {
4013
4504
  // records interrupted BEFORE anything else touches their worktrees.
4014
4505
  await performBootRecovery();
4015
4506
 
4507
+ // Issue #466 (ADR 0026 D2/D5): reconcile the durable head-state records —
4508
+ // the ONE step allowed to move git at boot, and only for a record whose
4509
+ // owner it has proved dead.
4510
+ const headStateOutcomes = reconcileHeadStatesAtBoot();
4511
+
4016
4512
  // Option B U3 (D2): after the scan, surface every unresolved interrupted
4017
4513
  // run ONCE, at the next turn boundary (never mid-turn).
4018
4514
  await maybeSendRecoveryNotice(ctx);
4019
4515
 
4516
+ // Issue #466: the head-state verdicts ride the same nextTurn channel.
4517
+ maybeSendHeadStateNotice(headStateOutcomes);
4518
+
4020
4519
  // Issue #356: boot is a config-paint edge — route it through the same
4021
4520
  // chokepoint as every other footer repaint. With no runs in flight the
4022
4521
  // chokepoint draws the idle config line the old direct call painted.
@@ -4025,6 +4524,17 @@ export default function (pi: ExtensionAPI) {
4025
4524
 
4026
4525
  // F7: Clean up session-bound state on shutdown
4027
4526
  pi.on("session_shutdown", async (_event, _ctx) => {
4527
+ // Issue #437: release THIS runtime's terminal subscribers FIRST — before
4528
+ // any await or fallible cleanup. A clean replacement (/new, /resume,
4529
+ // /fork, /reload, quit) tears this runtime down and loads a new factory
4530
+ // instance; the old listeners used to survive and win the shared terminal
4531
+ // claim for the NEW session's run, delivering (or throwing) through dead
4532
+ // pi/ctx handles. Only our three exact identities are removed, and the
4533
+ // release is idempotent, so other subscribers and a later runtime are
4534
+ // untouched. `releaseTerminalSubscriptions` is a hoisted declaration
4535
+ // below (the subscription block is registered after this handler).
4536
+ releaseTerminalSubscriptions();
4537
+
4028
4538
  log.info("Session shutting down", {
4029
4539
  activeSubagents: state.activeSubagents,
4030
4540
  });
@@ -4062,10 +4572,41 @@ export default function (pi: ExtensionAPI) {
4062
4572
  // the point; details are best-effort — the notification must never throw or
4063
4573
  // block on their absence.
4064
4574
  const terminalTypes = ["subagent:completed", "subagent:failed", "subagent:stopped"] as const;
4575
+
4576
+ // Issue #437: keep the EXACT listener references this factory instance owns.
4577
+ // Anonymous subscriptions could never be released, so a shut-down runtime's
4578
+ // listeners stayed on the shared bus forever. Ownership is per factory
4579
+ // invocation: the array and the released flag are this runtime's alone, so a
4580
+ // replacement's listeners are never in the removal set.
4581
+ const terminalSubscriptions: Array<{
4582
+ type: (typeof terminalTypes)[number];
4583
+ listener: SubagentEventListener;
4584
+ }> = [];
4585
+ let terminalSubscriptionsReleased = false;
4586
+
4587
+ /**
4588
+ * Issue #437: unsubscribe exactly the listeners registered above.
4589
+ *
4590
+ * Idempotent — a repeated/double `session_shutdown` (or a late one after the
4591
+ * replacement runtime is already live) is a no-op. Synchronous, so it can run
4592
+ * as the first statement of `session_shutdown`, before any await or fallible
4593
+ * cleanup. Never touches another subscriber or another runtime's listeners.
4594
+ */
4595
+ function releaseTerminalSubscriptions(): void {
4596
+ if (terminalSubscriptionsReleased) return;
4597
+ terminalSubscriptionsReleased = true;
4598
+ for (const { type, listener } of terminalSubscriptions) {
4599
+ eventBus.off(type, listener);
4600
+ }
4601
+ terminalSubscriptions.length = 0;
4602
+ }
4603
+
4065
4604
  for (const type of terminalTypes) {
4066
- eventBus.on(type, (event) => {
4605
+ const listener: SubagentEventListener = (event) => {
4067
4606
  void deliverCompletionAlert(event);
4068
- });
4607
+ };
4608
+ terminalSubscriptions.push({ type, listener });
4609
+ eventBus.on(type, listener);
4069
4610
  }
4070
4611
 
4071
4612
  /**
@@ -4086,6 +4627,13 @@ export default function (pi: ExtensionAPI) {
4086
4627
  * the source run's completion notice, because the retry's own terminal settle
4087
4628
  * is the wake. A gate rejection or a throwing spawn returns FALSE and the
4088
4629
  * caller reports the original failure exactly as before (no silent drop).
4630
+ *
4631
+ * Issue #439: this reads only `isError`, and a retry whose post-spawn tail
4632
+ * faulted is still a SUCCESSFUL spawn (`isError: false`, degraded monitoring).
4633
+ * It therefore returns TRUE for it: the source notice stays suppressed and the
4634
+ * degraded advisory is the signal that the retry started with degraded
4635
+ * monitoring. Reading a contained tail failure as "did not start" would
4636
+ * surface the source failure for a run that is live.
4089
4637
  */
4090
4638
  async function scheduleTransportRetry(
4091
4639
  ctx: ExtensionContext,
@@ -4148,7 +4696,7 @@ export default function (pi: ExtensionAPI) {
4148
4696
  const agent = getAgent(id);
4149
4697
  if (!agent) return; // pruned or foreign id — nothing to notify
4150
4698
  const knob = state.config.completionNotify ?? "all";
4151
- const run = resolveRunEntry(state.getRunEntries(ctx), id);
4699
+ const run = resolveRunEntry(state.getLogicalRunEntries(ctx), id);
4152
4700
  // Issue #365: a transport-class background failure is re-dispatched once
4153
4701
  // and the source notice is suppressed (the retry's settle is the wake).
4154
4702
  // Every other terminal type — and every non-retryable failure — keeps the