brl-subagent 2.7.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 (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  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 +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
@@ -17,16 +17,18 @@
17
17
  * controls the WAKE (D2). D1: failed/stopped → "steer", completed → "followUp".
18
18
  */
19
19
 
20
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
21
- import type {
22
- BackgroundAgent,
23
- SubagentRun,
24
- CompletionNotifyMode,
25
- AgentStatus,
26
- } from "./types";
20
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
27
21
  import { truncateTail } from "./transcript-tail";
28
22
  import { formatRunDuration } from "./history";
29
- import { classifyTerminalOutcome } from "./types";
23
+ import { formatBudgetDuration } from "./tui-format";
24
+ import {
25
+ classifyTerminalOutcome,
26
+ type BackgroundAgent,
27
+ type BackgroundAgentIdentity,
28
+ type SubagentRun,
29
+ type CompletionNotifyMode,
30
+ type AgentStatus,
31
+ } from "./types";
30
32
  import { resolveTerminalRunEntry } from "./state";
31
33
 
32
34
  /** Terminal statuses the completion message can carry. */
@@ -59,7 +61,11 @@ export interface DeliveryResolution {
59
61
  triggerTurn: boolean;
60
62
  }
61
63
 
62
- /** Default dedupe cap: the set is simply cleared when it exceeds this. */
64
+ /**
65
+ * Default dedupe cap. The set stays bounded by evicting its oldest entry when it
66
+ * exceeds this — never the whole set (issue #440: a clear-all forgot the id it had
67
+ * just claimed, so that id could be delivered twice).
68
+ */
63
69
  const DEDUPE_CAP = 200;
64
70
 
65
71
  /**
@@ -114,6 +120,49 @@ function buildSummaryLine(
114
120
  return line;
115
121
  }
116
122
 
123
+ /**
124
+ * The ONE timeout predicate (issue #423): a run hit its deadline when the
125
+ * classified category says so or the agent's error is the deadline stamp. The
126
+ * wake, the result renderer and the budget line all read it, so the two
127
+ * exhaustion surfaces cannot disagree.
128
+ */
129
+ export function isTimeoutEvidence(agent: BackgroundAgent, run?: SubagentRun): boolean {
130
+ const category = run?.errorCategory ?? run?.originalParams?.errorCategory;
131
+ return category === "timeout" || /^Timed out/.test(agent.error ?? "");
132
+ }
133
+
134
+ /**
135
+ * One line stating a run's budget (issue #423). PURE. Returns undefined when the
136
+ * record carries no budget — an old record written before `timeoutMs` existed
137
+ * has nothing to state, so no line is better than an invented 30 m.
138
+ *
139
+ * Shapes:
140
+ * - timeout: `Budget: 30m (exhausted)`
141
+ * - otherwise `Budget: 30m — 4m 12s used, 25m 48s left`
142
+ *
143
+ * `status` guards the exhausted form: a run classified `completed` never claims
144
+ * to have exhausted its budget (the evidence predicate alone would otherwise be
145
+ * enough to downgrade a late-but-successful settle). `run` is optional because
146
+ * the result path (`get_subagent_result`) has only the agent record; both read
147
+ * the SAME predicate.
148
+ */
149
+ export function formatBudgetLine(
150
+ agent: BackgroundAgent,
151
+ status: CompletionStatus | undefined,
152
+ run: SubagentRun | undefined,
153
+ now: number = Date.now(),
154
+ ): string | undefined {
155
+ if (agent.timeoutMs === undefined) return undefined;
156
+ const budget = formatBudgetDuration(agent.timeoutMs);
157
+ if (status !== "completed" && isTimeoutEvidence(agent, run)) {
158
+ return `Budget: ${budget} (exhausted)`;
159
+ }
160
+ const endMs = agent.completedAt ?? now;
161
+ const usedMs = Math.max(0, endMs - agent.startedAt);
162
+ const remainingMs = Math.max(0, agent.startedAt + agent.timeoutMs - endMs);
163
+ return `Budget: ${budget} — ${formatBudgetDuration(usedMs)} used, ${formatBudgetDuration(remainingMs)} left`;
164
+ }
165
+
117
166
  /**
118
167
  * PURE builder — no pi SDK, no side effects, never throws. Returns the
119
168
  * sendMessage payload shape per D3.
@@ -169,6 +218,13 @@ export function buildCompletionMessage(
169
218
  : stored;
170
219
  const tail = truncateTail(body, 15);
171
220
  const parts = [summary];
221
+ // Issue #423: the budget rides its own part, and ONLY on a failed/stopped
222
+ // wake — a completed run's message is unchanged (the human reads the budget
223
+ // when something went wrong, not on every success).
224
+ if (status !== "completed") {
225
+ const budgetLine = formatBudgetLine(agent, status, run);
226
+ if (budgetLine) parts.push(budgetLine);
227
+ }
172
228
  if (headline) parts.push(headline);
173
229
  if (tail) parts.push(tail);
174
230
  parts.push(COMPLETION_DIRECTIVE);
@@ -190,6 +246,33 @@ export function buildCompletionMessage(
190
246
  return { customType: "subagent-completion", content, display: true, details };
191
247
  }
192
248
 
249
+ /**
250
+ * Issue #474: insert the worktree-state block into a settled-failure wake, as
251
+ * its own part and BEFORE the closing directive.
252
+ *
253
+ * PURE — it takes the already-rendered block and never probes git: the builder's
254
+ * contract is "no side effects", and the probe is a subprocess. The caller
255
+ * renders the block (`describeWorktreeState`) and gates on the CLASSIFIED
256
+ * status.
257
+ *
258
+ * The directive is matched at the END (`endsWith`), never as the first
259
+ * occurrence: an agent's own tail can quote the directive text, and splitting
260
+ * there would drop everything after the quote. A shape that does not end with
261
+ * the directive keeps the block by appending it — a missing report is the one
262
+ * outcome this function must not produce.
263
+ */
264
+ export function withWorktreeState(
265
+ message: CompletionMessagePayload,
266
+ worktreeState: string,
267
+ ): CompletionMessagePayload {
268
+ if (!worktreeState) return message;
269
+ const suffix = `\n\n${COMPLETION_DIRECTIVE}`;
270
+ const content = message.content.endsWith(suffix)
271
+ ? `${message.content.slice(0, -suffix.length)}\n\n${worktreeState}${suffix}`
272
+ : `${message.content}\n\n${worktreeState}`;
273
+ return { ...message, content };
274
+ }
275
+
193
276
  /**
194
277
  * D1 + D2 matrix — the only knob-dependent logic. Delivery is always-on
195
278
  * (minimum `nextTurn`); the knob controls the WAKE (triggerTurn).
@@ -209,13 +292,20 @@ export function resolveDelivery(
209
292
 
210
293
  /**
211
294
  * Dedupe guard — first terminal event per id wins. Returns true when the event
212
- * should be delivered, false when it is a duplicate. Capped simply (W1): the
213
- * set is cleared when it exceeds the cap.
295
+ * should be delivered, false when it is a duplicate. Retention is bounded (W1):
296
+ * once the set exceeds the cap its OLDEST entry is evicted (a `Set` iterates in
297
+ * insertion order, so that is exact). The id just claimed is the newest entry, so
298
+ * its own call evicts an EARLIER id — not the set, and not that claim. A clear-all
299
+ * forgot the claim entirely, so the very next duplicate was delivered twice (#440).
214
300
  */
215
301
  export function markTerminalSeen(seen: Set<string>, id: string, cap = DEDUPE_CAP): boolean {
302
+ cap = Math.max(cap, 1); // a cap below 1 evicts the claim just made — retention must keep it
216
303
  if (seen.has(id)) return false;
217
304
  seen.add(id);
218
- if (seen.size > cap) seen.clear();
305
+ if (seen.size > cap) {
306
+ const oldest = seen.values().next().value;
307
+ if (oldest !== undefined) seen.delete(oldest);
308
+ }
219
309
  return true;
220
310
  }
221
311
 
@@ -254,3 +344,81 @@ export function sendCompletionNotification(
254
344
  ): void {
255
345
  pi.sendMessage(message, { deliverAs: delivery.deliverAs, triggerTurn: delivery.triggerTurn });
256
346
  }
347
+
348
+ // ---------------------------------------------------------------------------
349
+ // Started-but-degraded monitoring advisory (issue #439)
350
+ //
351
+ // A background spawn whose tail faulted is a STARTED run whose monitoring is
352
+ // degraded — never a failed spawn. The conductor learns that from the spawn
353
+ // result's paragraph; the user learns it from this advisory. The advisory is
354
+ // deliberately NOT a terminal notice and never takes the terminal claim: the
355
+ // run is live, and its genuine completion notice must still be delivered later
356
+ // (the resolved contract on the issue). A run that emits the advisory and then
357
+ // never delivers a terminal notice (no listener at settle time) degrades to
358
+ // "advisory only" — a stated limitation, not a silent one.
359
+ // ---------------------------------------------------------------------------
360
+
361
+ /** The advisory's custom message type. NOT a terminal notice type. */
362
+ export const MONITORING_DEGRADED_CUSTOM_TYPE = "subagent-monitoring-degraded";
363
+
364
+ /** The user-facing half of the advisory (the footer/toast line). */
365
+ export const MONITORING_DEGRADED_TOAST = "Background agent started — monitoring degraded";
366
+
367
+ /**
368
+ * The conductor-facing paragraph a STARTED-but-degraded spawn result carries.
369
+ * Built from the identity record only — never from a property read on the live
370
+ * agent (see the boundary statement in `startBackgroundAgent`). EMPTY when the
371
+ * tail attached fully: callers append it unconditionally.
372
+ */
373
+ export function buildMonitoringDegradedParagraph(
374
+ unit: Pick<BackgroundAgentIdentity, "id" | "label">,
375
+ tailFailures: string[],
376
+ ): string {
377
+ if (tailFailures.length === 0) return "";
378
+ const name = unit.label ? `"${unit.label}" ` : "";
379
+ return (
380
+ `\n\nMonitoring degraded: ${name}started, but its live monitoring could not be attached (${tailFailures.join("; ")}). ` +
381
+ `Do not re-dispatch — the run is live; retrieve with get_subagent_result({ agent_id: "${unit.id}" }).`
382
+ );
383
+ }
384
+
385
+ /** The advisory's message body — the same facts, phrased for the user's screen. */
386
+ export function buildMonitoringDegradedAdvisory(
387
+ unit: Pick<BackgroundAgentIdentity, "id" | "label">,
388
+ tailFailures: string[],
389
+ ): string {
390
+ if (tailFailures.length === 0) return "";
391
+ const name = unit.label ? ` "${unit.label}"` : "";
392
+ return (
393
+ `Background agent${name} started, but its monitoring is degraded (${tailFailures.join("; ")}). ` +
394
+ `The run is live — do not re-dispatch it; retrieve with get_subagent_result({ agent_id: "${unit.id}" }).`
395
+ );
396
+ }
397
+
398
+ /**
399
+ * Emit the advisory on both channels, each in its own try: a throwing
400
+ * `sendMessage` must not swallow the footer line, and a missing UI must not
401
+ * swallow the message. Best-effort by design — this is the report of a
402
+ * degraded path and cannot itself fail the spawn.
403
+ */
404
+ export function sendMonitoringDegradedAdvisory(
405
+ pi: ExtensionAPI,
406
+ ctx: Pick<ExtensionContext, "ui">,
407
+ identity: BackgroundAgentIdentity,
408
+ tailFailures: string[],
409
+ ): void {
410
+ try {
411
+ pi.sendMessage(
412
+ {
413
+ customType: MONITORING_DEGRADED_CUSTOM_TYPE,
414
+ content: buildMonitoringDegradedAdvisory(identity, tailFailures),
415
+ display: true,
416
+ details: { agentId: identity.id, tailFailures },
417
+ },
418
+ { deliverAs: "followUp" },
419
+ );
420
+ } catch { /* best-effort */ }
421
+ try {
422
+ ctx.ui.notify(MONITORING_DEGRADED_TOAST, "warning");
423
+ } catch { /* best-effort */ }
424
+ }
package/src/params.ts CHANGED
@@ -12,24 +12,25 @@
12
12
  * drive the REAL function (no more silent test drift).
13
13
  */
14
14
 
15
+ import type { Logger } from "./logging";
16
+ import type { SessionState } from "./state";
15
17
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
16
-
17
- import type {
18
- ThinkingLevel,
19
- SubagentPreset,
20
- GitMode,
21
- ApprovalMode,
22
- SubagentToolOptions,
23
- ResolvedParams,
24
- SnapshotParams,
25
- DelegateTaskParams,
18
+ import {
19
+ approvalBlocksBackground,
20
+ declaredThinkingLevel,
21
+ resolveThinkingLevel,
22
+ type ThinkingLevel,
23
+ type SubagentPreset,
24
+ type GitMode,
25
+ type ApprovalMode,
26
+ type SubagentToolOptions,
27
+ type ResolvedParams,
28
+ type SnapshotParams,
29
+ type DelegateTaskParams,
26
30
  } from "./types";
27
- import { resolveThinkingLevel } from "./types";
28
31
  import { getAllPresets, getPreset } from "./presets";
29
32
  import { classifyTask } from "./router";
30
33
  import { normalizeTimeout } from "./validate";
31
- import type { SessionState } from "./state";
32
- import type { Logger } from "./logging";
33
34
 
34
35
  // ---------------------------------------------------------------------------
35
36
  // delegate_task known keys (issue #99)
@@ -199,48 +200,106 @@ export const THINKING_SWITCH_NOTICE =
199
200
  "The run is now background; the conductor is woken on terminal state. Pass force: true to keep it foreground (state the reason in the task text).";
200
201
 
201
202
  /** The pre-flight's verdict for one dispatch. */
202
- export type ThinkingDispatchSwitch = "switch" | "forced" | "none";
203
+ export type ThinkingDispatchSwitch = "switch" | "drop-timeout" | "forced" | "none";
204
+
205
+ /**
206
+ * The notice the dispatch emits on the SECOND arm (issue #431): the run was
207
+ * going to be killed by its own explicit foreground timeout, but its approval
208
+ * mode makes a background run impossible (or it never asked for one), so the
209
+ * deadline is dropped and the shape stays foreground.
210
+ *
211
+ * Deliberately NOT `THINKING_SWITCH_NOTICE`: that text says "the run is now
212
+ * background", which is a lie on this arm. The trade-off (no clock on a hung
213
+ * child) is stated rather than hidden — a dropped deadline removes the only
214
+ * bound the runner had.
215
+ */
216
+ export const THINKING_TIMEOUT_DROP_NOTICE =
217
+ "Dispatch pre-flight (no deadline means the durable path): a high/xhigh-thinking run carried an explicit timeout, but its effective approval mode needs the interactive approval dialog — a background run would be rejected ('always') or would silently auto-approve ('writes'), so the shape cannot move. " +
218
+ "The explicit timeout was dropped and the run stays FOREGROUND: foreground runs have no default deadline, so no clock kills it, and the conductor's call blocks until the child settles. " +
219
+ "The trade-off is explicit — a dropped deadline also removes the only clock on a child that hangs. Pass force: true to keep the explicit timeout.";
203
220
 
204
221
  /**
205
- * Issue #412 (rule 2: "no deadline ⇒ durable path") — should the pre-flight
206
- * change this dispatch's shape?
222
+ * Issue #412 (rule 2: "no deadline ⇒ durable path") — what should the
223
+ * pre-flight do with this dispatch?
207
224
  *
208
225
  * The 2026-10-31 incident: a plan critique ran foreground under a 15-minute
209
226
  * timeout, was killed at ~14 minutes ("almost done"), and lost everything —
210
227
  * the background re-run then cost another 17 minutes. The decision was
211
228
  * conductor discretion; this predicate makes the durable shape the only one
212
- * for the runs where losing the context is expensive:
229
+ * for the runs where losing the context is expensive.
230
+ *
231
+ * One rule, two arms — the run must not be killable by its own deadline:
213
232
  *
214
233
  * processChecks (the project opted into OUR process — issue #415)
215
234
  * + thinkingLevel high|xhigh
216
- * + background EXPLICITLY false (the caller asked for foreground)
217
235
  * + an explicit timeout (the deadline that would kill it)
218
- * → switch to background and drop the timeout.
236
+ * + an effective FOREGROUND shape
237
+ *
238
+ * → "switch": move to background and drop the timeout (the 30-minute
239
+ * background default applies) — used when a background run is possible.
240
+ * → "drop-timeout": keep foreground and drop the timeout (a foreground
241
+ * run has no default deadline since #423) — used when it is not:
242
+ * · `background: false` + effective `always`: switching there would be
243
+ * REJECTED (no dialog in background), and a pre-flight must never
244
+ * turn a valid dispatch into an error (#433);
245
+ * · `background` omitted where the #361 default resolved FOREGROUND
246
+ * (effective `writes`/`always`): the default already judged the
247
+ * approval mode, so the deadline is all that is left to remove.
219
248
  *
220
249
  * Deliberately exempt:
221
250
  * - `processChecks: false` — this is a CONDUCTOR decision rule, not product
222
251
  * behavior. A user's explicit foreground timeout is usually a budget cap,
223
252
  * so overriding it could triple time and cost against their instruction.
224
- * The umbrella flag (ADR 0019) is what makes the switch opt-in; the
253
+ * The umbrella flag (ADR 0019) is what makes the pre-flight opt-in; the
225
254
  * predicate has no global mode.
226
- * - `chain`/`graph` — they block by definition and `background: true` is
227
- * rejected at dispatch; the decision cannot apply to them.
228
- * - an omitted `background` — the #361 default already decided, and it knows
229
- * about approval modes (a `writes`/`always` run must stay in front of the
230
- * user); second-guessing it here would silently move a gated run into a
231
- * context with no approval dialog.
232
- * - no explicit timeout — there is no deadline to lose; the background
233
- * default is a deadline too, so switching would not make the run safer.
255
+ * - `chain`/`graph` — an uncapped batch multiplies a hang across N units and
256
+ * has no per-unit pre-flight (#434); the exemption is about the BATCH now,
257
+ * not about `background: true` being rejected (which motivated it for the
258
+ * switch arm only).
259
+ * - an explicit `background: true` — the caller asked for background; there
260
+ * is no foreground deadline to lose.
261
+ * - an omitted `background` whose effective shape is background (`auto`) —
262
+ * the #361 default already chose the durable shape.
263
+ * - no explicit timeout — there is no deadline to drop.
234
264
  * - `force: true` — the override, reported as `forced` (not `none`) so the
235
- * caller can tell "kept foreground by request" from "never applied".
236
- * `force` carries no reason field (ADR 0007): the dispatch text is the
237
- * reason.
265
+ * caller can tell "kept by request" from "never applied". `force` carries
266
+ * no reason field (ADR 0007): the dispatch text is the reason.
267
+ * PRECEDENCE: force maps `switch`/`drop-timeout` → `forced`; an arm that
268
+ * computes `none` stays `none` REGARDLESS of force — there is nothing to
269
+ * override, and the call site's "foreground forced" log line must never
270
+ * print for a run that is already background.
271
+ *
272
+ * The omitted-background arm keys on the EFFECTIVE SHAPE via
273
+ * `defaultBackgroundFor`, never on a re-spelled mode list — the same helper the
274
+ * #361 default uses, so the two cannot disagree. `effectiveApprovalMode` is
275
+ * resolved by `resolveEffectiveApprovalMode(params.approvalMode, state)` at the
276
+ * call site, never read from the raw call param: a config-tier mode must reach
277
+ * this predicate, and the `always` guard goes through `approvalBlocksBackground`
278
+ * — the same helper the background gates reject with.
279
+ *
280
+ * INVARIANT (MAJ-7): "drop the timeout" is `params.timeout = undefined`, which
281
+ * `resolveSubagentParams` merges as `params.timeout ?? preset?.timeout`. The
282
+ * drop arm's no-deadline guarantee therefore holds ONLY because no preset can
283
+ * carry a `timeout` at runtime (`presetFromFrontmatter` maps none, so
284
+ * `SubagentPreset.timeout` is dead). If preset timeouts ever map, the drop
285
+ * silently re-merges one, no test fails, and the notice becomes a lie — merge
286
+ * or skip the preset value here first.
238
287
  *
239
288
  * `thinkingLevel` is the DECLARED level (per-call, else the named preset's),
240
289
  * not the capped one: `maxThinkingLevel` defaults to `off` for an unconfigured
241
290
  * session, so applying the cap here would disable the pre-flight exactly where
242
291
  * nobody configured anything — the drift this rule exists to remove.
243
292
  */
293
+ /**
294
+ * #434 review (DRY): the two levels the pre-flight treats as "high thinking".
295
+ * ONE member test, used by the dispatch predicate and by its unit projection —
296
+ * the literal pair is shared core, not a documented divergence, and U10 pins
297
+ * that the two predicates agree on the same declared pair.
298
+ */
299
+ export function isHighDeclaredLevel(level: ThinkingLevel | string | undefined): boolean {
300
+ return level === "high" || level === "xhigh";
301
+ }
302
+
244
303
  export function resolveThinkingDispatchSwitch(input: {
245
304
  processChecks: boolean;
246
305
  thinkingLevel: ThinkingLevel | undefined;
@@ -248,13 +307,124 @@ export function resolveThinkingDispatchSwitch(input: {
248
307
  timeout: number | undefined;
249
308
  force: boolean | undefined;
250
309
  shape: DispatchShape;
310
+ /** The mode the child will actually run with (call param, else config). */
311
+ effectiveApprovalMode: ApprovalMode;
251
312
  }): ThinkingDispatchSwitch {
252
313
  if (!input.processChecks) return "none";
253
314
  if (input.shape === "chain" || input.shape === "graph") return "none";
254
- if (input.thinkingLevel !== "high" && input.thinkingLevel !== "xhigh") return "none";
255
- if (input.explicitBackground !== false) return "none";
315
+ if (!isHighDeclaredLevel(input.thinkingLevel)) return "none";
256
316
  if (input.timeout === undefined) return "none";
257
- return input.force === true ? "forced" : "switch";
317
+ const base: ThinkingDispatchSwitch =
318
+ input.explicitBackground === true
319
+ ? "none"
320
+ : input.explicitBackground === false
321
+ ? approvalBlocksBackground(input.effectiveApprovalMode)
322
+ ? "drop-timeout"
323
+ : "switch"
324
+ : defaultBackgroundFor(input.shape, input.effectiveApprovalMode)
325
+ ? "none"
326
+ : "drop-timeout";
327
+ if (base === "none") return "none";
328
+ return input.force === true ? "forced" : base;
329
+ }
330
+
331
+ /**
332
+ * The notice a batch dispatch emits when the UNIT projection of the same rule
333
+ * (issue #434) removes a unit's own declared deadline.
334
+ *
335
+ * Emitted at most once per dispatch, at the first affected unit's run — so the
336
+ * wording deliberately claims NO completeness: it names that one unit and says
337
+ * when the others are judged. A unit cancelled before its run is never named,
338
+ * and a unit whose own declaration is not eligible gets no line at all.
339
+ *
340
+ * Deliberately NOT `THINKING_TIMEOUT_DROP_NOTICE`: that text reasons about the
341
+ * DISPATCH's effective approval mode, which says nothing about a unit that
342
+ * declared its own pair inside a batch the caller already shaped.
343
+ */
344
+ export const THINKING_UNIT_TIMEOUT_DROP_NOTICE =
345
+ "Dispatch pre-flight (no deadline means the durable path): a batch unit declares its own high/xhigh thinking level with an explicit timeout, so that unit's timeout is dropped and it runs FOREGROUND — a foreground run has no default deadline, so no clock kills it. " +
346
+ "Only the unit this notice is attached to is reported here; the other units are judged when each reaches its run, so a unit that has not started yet is not covered. " +
347
+ "Pass force: true to keep the units' declared timeouts.";
348
+
349
+ /**
350
+ * Whether a UNIT runs foreground or background — the unit's own shape, which
351
+ * decides whether its declared deadline is a foreground hazard at all (issue
352
+ * #434).
353
+ *
354
+ * Background units are excluded by construction: a `tasks` fan-out spawns its
355
+ * units as detached background agents, where the deadline is the legitimate
356
+ * 30-minute budget and dropping it would REMOVE a bound instead of adding
357
+ * durability. Chain/graph units are always foreground (an explicit
358
+ * `background: true` batch is rejected at dispatch).
359
+ */
360
+ export type UnitShape = "foreground" | "background";
361
+
362
+ /**
363
+ * Issue #434 — the UNIT projection of `resolveThinkingDispatchSwitch`.
364
+ *
365
+ * The dispatch rule only judges the DISPATCH-level pair (`params.thinkingLevel`
366
+ * + `params.timeout`). Batch units carry their own (`schema.ts`
367
+ * `STEP_HEAD_FIELDS`/`STEP_THINKING_LEVEL_FIELD`/`STEP_TAIL_FIELDS`) and
368
+ * `mergeSubTaskParams` lets the unit win per field, so a unit declaring
369
+ * `thinkingLevel: "high"` + `timeout: 600000` under no top-level pair
370
+ * reproduced the 2026-11-06 incident for that unit alone: the dispatch
371
+ * predicate exits early on `params.timeout === undefined`.
372
+ *
373
+ * Only ONE arm is available per unit — a unit cannot become its own background
374
+ * dispatch (it is one spawn inside a batch the caller already shaped), so the
375
+ * projection answers a boolean and never re-states the switch/drop-timeout
376
+ * approval arms that decide a DISPATCH's shape.
377
+ *
378
+ * Eligible when ALL hold:
379
+ *
380
+ * 1. `processChecks` — threaded from `execute` so a unit is judged by the
381
+ * same project opt-in as its dispatch. NEVER re-read at the unit site: a
382
+ * relative `params.cwd` re-read (against the process cwd instead of
383
+ * `ctx.cwd`) measured `false` where the dispatch resolved `true`.
384
+ * 2. `force !== true` — the override reaches units too; it is the caller's
385
+ * statement that the declared pair is intentional.
386
+ * 3. the unit's EFFECTIVE DECLARED level is high/xhigh: its own declaration,
387
+ * else the dispatch's declared level, which the unit inherits. NOT
388
+ * `merged.thinkingLevel`: that value is CAPPED, and the default cap is
389
+ * `off`, so judging it would silently disable this guard exactly where
390
+ * nobody configured anything — the same drift #443 removed one level up.
391
+ * 4. the MERGED timeout is defined and `> 0`. Only a positive timeout arms a
392
+ * foreground timer (`runner.ts`: `if (timeout && timeout > 0)`), and
393
+ * `mergeSubTaskParams` merges with `??`, so a declared `timeout: 0`
394
+ * OVERRIDES an inherited timeout and arms nothing — never eligible.
395
+ * 5. the unit DECLARES the pair — a non-empty `thinkingLevel`, or `timeout`
396
+ * present (a `0` included: it is a declaration, it just never arms a
397
+ * timer). This is the #434/#431 boundary: a unit that declares NEITHER
398
+ * and inherits the dispatch's pair was already judged at dispatch level,
399
+ * including the chain/graph exemption — so inherited pairs stay exempt
400
+ * (pinned, not accidental) while unit-declared ones do not.
401
+ * 6. the unit's shape is FOREGROUND (`unitShape`, passed explicitly so the
402
+ * exclusion is visible at the call site).
403
+ *
404
+ * The caller applies the effect — `merged.timeout = undefined` — before the
405
+ * unit's run record is created, so the retry snapshot records an absent
406
+ * deadline instead of restoring the cap (ADR 0009).
407
+ */
408
+ export function shouldDropUnitTimeout(input: {
409
+ processChecks: boolean;
410
+ force: boolean | undefined;
411
+ /** The DISPATCH's declared level, threaded from `execute` (clause 3). */
412
+ dispatchDeclaredLevel: ThinkingLevel | undefined;
413
+ unitShape: UnitShape;
414
+ /** The unit's OWN declaration: `""`/`undefined` both mean "inherit". */
415
+ declaredLevel: ThinkingLevel | "" | undefined;
416
+ /** The unit's OWN timeout declaration (`undefined` = inherit). */
417
+ declaredTimeout: number | undefined;
418
+ /** `mergeSubTaskParams`' result: the deadline the unit would actually run with. */
419
+ mergedTimeout: number | undefined;
420
+ }): boolean {
421
+ if (!input.processChecks) return false;
422
+ if (input.force === true) return false;
423
+ if (input.unitShape !== "foreground") return false;
424
+ const effectiveDeclaredLevel = input.declaredLevel || input.dispatchDeclaredLevel;
425
+ if (!isHighDeclaredLevel(effectiveDeclaredLevel)) return false;
426
+ if (input.mergedTimeout === undefined || input.mergedTimeout <= 0) return false;
427
+ return Boolean(input.declaredLevel) || input.declaredTimeout !== undefined;
258
428
  }
259
429
 
260
430
  /**
@@ -369,9 +539,13 @@ export function resolveSubagentParams(
369
539
  : undefined;
370
540
  const autoRoutedPreset = wasAutoRouted ? preset : undefined;
371
541
 
372
- const mergedThinkingLevel =
373
- (params.thinkingLevel as ThinkingLevel | undefined) ??
374
- (preset?.thinkingLevel as ThinkingLevel | undefined);
542
+ // The DECLARED level (per-call, else the selected preset's) — read through the
543
+ // shared helper so both dispatch guards (issue #443) judge exactly the value
544
+ // this merge resolves, not a second interpretation of it.
545
+ const mergedThinkingLevel = declaredThinkingLevel(
546
+ params.thinkingLevel,
547
+ preset?.thinkingLevel,
548
+ ) as ThinkingLevel | undefined;
375
549
  const mergedSystemPrompt = params.systemPrompt ?? preset?.systemPrompt;
376
550
  const mergedInheritSP = params.inheritSystemPrompt ?? preset?.inheritSystemPrompt;
377
551
  const mergedOutputFile = params.outputFile ?? preset?.outputFile;