brl-subagent 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/loader.ts ADDED
@@ -0,0 +1,178 @@
1
+ // Purpose: Shared markdown-tier loader — scan dirs for `.md`, parse frontmatter, validate, map to a typed record.
2
+ /**
3
+ * brl-subagent — Markdown tier loader
4
+ *
5
+ * Presets and task templates are both FILE-BACKED tiers: a directory of `.md`
6
+ * files with YAML frontmatter is listed, filtered to `.md`, read, parsed,
7
+ * validated, and normalised into a family-specific record. Before issue #380
8
+ * that pipeline was written four times (builtin presets, custom presets,
9
+ * custom templates, builtin templates) with only the record shape, the
10
+ * validator, and the log wording differing (D6 in the smell audit).
11
+ *
12
+ * This module owns the common steps once. The two families keep their own
13
+ * record types and mappers — `loadMarkdownRecords` is generic over the record
14
+ * and takes the family-specific mapping as `spec.map`, so presets stay presets
15
+ * and templates stay templates while the walk is single-source.
16
+ *
17
+ * Behaviour preserved from the four copies:
18
+ * - non-`.md` entries are ignored; a directory named `*.md` surfaces as a
19
+ * read failure (warn) instead of aborting the scan;
20
+ * - an unreadable directory is skipped (`onMissingDir` lets the builtin tiers
21
+ * log the info line, custom tiers stay silent);
22
+ * - a validation error warns once per error and skips the file;
23
+ * - a per-file read/parse/map throw warns and continues;
24
+ * - dedupe by name is opt-in (`dedupeByName`) and first-occurrence-wins,
25
+ * which is how PROJECT > USER precedence is enforced.
26
+ */
27
+
28
+ import * as fs from "node:fs";
29
+ import * as path from "node:path";
30
+ import type { Logger } from "./logging";
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Frontmatter parsing
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Parse YAML frontmatter from a markdown file.
38
+ * Returns metadata key-value pairs and the body content.
39
+ */
40
+ export function parseFrontmatter(content: string): { meta: Record<string, unknown>; body: string } {
41
+ const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
42
+ if (!match) return { meta: {}, body: content };
43
+
44
+ const meta: Record<string, unknown> = {};
45
+ const lines = match[1].split("\n");
46
+ let currentKey = "";
47
+ let currentArray: string[] | null = null;
48
+
49
+ for (const line of lines) {
50
+ // Array item: starts with "- "
51
+ if (line.match(/^\s+-\s+/)) {
52
+ if (currentArray !== null) {
53
+ currentArray.push(line.replace(/^\s+-\s+/, "").trim());
54
+ }
55
+ continue;
56
+ }
57
+
58
+ // End of array if we were in one
59
+ if (currentArray !== null) {
60
+ meta[currentKey] = currentArray;
61
+ currentArray = null;
62
+ }
63
+
64
+ // Key-value pair
65
+ const kvMatch = line.match(/^(\w+):\s*(.*)$/);
66
+ if (kvMatch) {
67
+ const key = kvMatch[1];
68
+ const value = kvMatch[2].trim();
69
+ // Check if next line starts an array
70
+ if (value === "") {
71
+ currentKey = key;
72
+ currentArray = [];
73
+ } else {
74
+ // Strip quotes if present
75
+ meta[key] = value.replace(/^["']|["']$/g, "");
76
+ }
77
+ }
78
+ }
79
+ // Close any pending array
80
+ if (currentArray !== null) {
81
+ meta[currentKey] = currentArray;
82
+ }
83
+
84
+ return { meta, body: match[2].trim() };
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // Tier loading
89
+ // ---------------------------------------------------------------------------
90
+
91
+ /** Log wording for one tier — the only part of the walk that is family-specific. */
92
+ export interface LoaderMessages {
93
+ /** Warn message for a file skipped by `validate` or `bodyError`. */
94
+ invalid: string;
95
+ /** Warn message for a file that threw while being read, parsed, or mapped. */
96
+ readFailed: string;
97
+ }
98
+
99
+ /** Everything one tier needs: where to scan, how to validate, how to build the record. */
100
+ export interface MarkdownTierSpec<T> {
101
+ /** Directories to scan, in precedence order (first occurrence of a name wins). */
102
+ dirs: readonly string[];
103
+ /** Frontmatter validator; a non-empty result skips the file (one warn per error). */
104
+ validate: (meta: Record<string, unknown>, fileName: string) => string[];
105
+ /** Family-specific record construction from validated frontmatter, body, and name. */
106
+ map: (meta: Record<string, unknown>, body: string, name: string) => T;
107
+ /** Log wording for this tier. */
108
+ messages: LoaderMessages;
109
+ /** Logger for the warn/info lines; omitted → silent. */
110
+ log?: Logger;
111
+ /** Skip a second occurrence of an already-seen name (PROJECT > USER precedence). */
112
+ dedupeByName?: boolean;
113
+ /** Extra skip check after `validate`; a returned error string warns and skips. */
114
+ bodyError?: (meta: Record<string, unknown>, body: string) => string | null;
115
+ /** Called when a directory cannot be read (missing dir). Custom tiers stay silent. */
116
+ onMissingDir?: (dir: string) => void;
117
+ }
118
+
119
+ /**
120
+ * Load every record of one markdown tier: walk `spec.dirs` in order, and for
121
+ * each `.md` file parse frontmatter, validate, check the optional body guard,
122
+ * dedupe by name when asked, then map into the family-specific record.
123
+ *
124
+ * Never throws for a bad file or a missing directory — those are warnings (or
125
+ * silence), matching the four hand-written loaders this replaces.
126
+ */
127
+ export function loadMarkdownRecords<T>(spec: MarkdownTierSpec<T>): T[] {
128
+ const records: T[] = [];
129
+ const seenNames = new Set<string>();
130
+
131
+ for (const dir of spec.dirs) {
132
+ let files: string[];
133
+ try {
134
+ files = fs.readdirSync(dir);
135
+ } catch {
136
+ // Directory doesn't exist or can't be read — no records from this tier.
137
+ spec.onMissingDir?.(dir);
138
+ continue;
139
+ }
140
+
141
+ for (const file of files) {
142
+ if (!file.endsWith(".md")) continue;
143
+
144
+ try {
145
+ const content = fs.readFileSync(path.join(dir, file), "utf-8");
146
+ const { meta, body } = parseFrontmatter(content);
147
+
148
+ const errors = spec.validate(meta, file);
149
+ if (errors.length > 0) {
150
+ for (const err of errors) {
151
+ spec.log?.warn(spec.messages.invalid, { file, error: err });
152
+ }
153
+ continue;
154
+ }
155
+
156
+ const bodyError = spec.bodyError?.(meta, body) ?? null;
157
+ if (bodyError !== null) {
158
+ spec.log?.warn(spec.messages.invalid, { file, error: bodyError });
159
+ continue;
160
+ }
161
+
162
+ // Both validators reject a missing/non-string name, so it is a string here.
163
+ const name = meta.name as string;
164
+ if (spec.dedupeByName) {
165
+ // First occurrence (highest-precedence dir) wins; later ones are skipped.
166
+ if (seenNames.has(name)) continue;
167
+ seenNames.add(name);
168
+ }
169
+
170
+ records.push(spec.map(meta, body, name));
171
+ } catch (err) {
172
+ spec.log?.warn(spec.messages.readFailed, { file, error: (err as Error).message });
173
+ }
174
+ }
175
+ }
176
+
177
+ return records;
178
+ }
@@ -0,0 +1,169 @@
1
+ // Purpose: The batch-mode prologue (cost → depth → resolve → targets → preflight → H1), one call per foreground batch handler.
2
+ /**
3
+ * Batch-mode prologue (issue #379, the D1 cluster).
4
+ *
5
+ * `runChainMode`, `runParallelMode` and `runGraphMode` open with the SAME six
6
+ * gates in the SAME order:
7
+ *
8
+ * [graph only: DAG validation] → cost → depth → resolve params
9
+ * → mode-level target validation → pre-flight → H1
10
+ *
11
+ * That sequence used to be copied into each handler (~110 lines × 3). This
12
+ * module owns it once. The per-mode differences are parameters, not forks:
13
+ *
14
+ * - `label` — the warning/log lead: "Chain" → "Chain delegation" (cost
15
+ * and depth logs), "Chain pre-flight check failed", "Chain
16
+ * pre-task validation warnings/failed";
17
+ * - `units` — the cost estimate's multiplier (IN2: the declared unit
18
+ * count for chain/parallel/graph — never a wave count);
19
+ * - `beforeCost` — graph's DAG validation, the ONE hook that must run before
20
+ * the cost gate (IN1 boundary: a malformed graph is rejected
21
+ * before the session spends anything).
22
+ *
23
+ * Deliberately NOT here:
24
+ *
25
+ * - the per-unit pre-pass (`validateUnitPrePass`, prelude.ts) — each handler
26
+ * CALLS it at its own position, because that position is part of the
27
+ * contract (IN8: chain/parallel before model resolution, graph after the
28
+ * circuit check and the topological sort);
29
+ * - the model tail (`resolveModeModel`, prelude.ts) — same reason: graph
30
+ * resolves the model before its per-node pass, chain/parallel after;
31
+ * - the single foreground path and the two background paths — they are a
32
+ * different gate sequence (design note §2.1; IN1/IN3/IN6), so forcing
33
+ * them through this skeleton would normalise their order.
34
+ *
35
+ * The gate functions are imported from `prelude.ts` (not re-implemented), so
36
+ * the existing suite's call-through wrappers still observe each gate at the
37
+ * same point in the sequence.
38
+ */
39
+
40
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
41
+ import type { ToolResult } from "./types";
42
+ import type { SessionState } from "./state";
43
+ import type { Logger } from "./logging";
44
+ import { resolveSubagentParams, type ResolveInputParams } from "./params";
45
+ import { getCurrentDepth } from "./sanitize";
46
+ import { preflightCheck } from "./preflight";
47
+ import {
48
+ depthLimitRejection,
49
+ gateSessionCost,
50
+ rejection,
51
+ runPreTaskValidation,
52
+ validateDelegationTargets,
53
+ } from "./prelude";
54
+
55
+ /** The params object the shared resolver consumes (`ResolveInputParams`,
56
+ * params.ts) — the same type the background and single paths pass. */
57
+ export interface ModePrologueInput {
58
+ /**
59
+ * `noJev` is carried alongside the resolution inputs rather than inside
60
+ * `ResolveInputParams`: resolution never reads it, but the mode-level H1
61
+ * gate forwards it as the call's stated bypass (issue #412).
62
+ */
63
+ params: ResolveInputParams & { noJev?: string };
64
+ state: SessionState;
65
+ ctx: ExtensionContext;
66
+ log: Logger;
67
+ /** Mode name, used as the warning/log lead: "Chain" | "Parallel" | "Graph". */
68
+ label: string;
69
+ /** Units this dispatch would spawn — the cost estimate's multiplier (IN2). */
70
+ units: number;
71
+ /**
72
+ * Mode-specific validation that MUST run before the cost gate. Graph uses
73
+ * it for `validateGraph`; chain/parallel pass nothing. Returns the
74
+ * rejection to surface, or `undefined` when the mode's precondition holds.
75
+ */
76
+ beforeCost?: () => ToolResult<undefined> | undefined;
77
+ }
78
+
79
+ /** The resolved dispatch the handlers build on (IN4: resolved exactly once). */
80
+ export type ModeGlobalParams = ReturnType<typeof resolveSubagentParams>;
81
+
82
+ export type ModePrologueOutcome =
83
+ | { ok: false; error: ToolResult<undefined> }
84
+ | {
85
+ ok: true;
86
+ globalParams: ModeGlobalParams;
87
+ resolvedCwd: string;
88
+ /** The depth the depth gate measured — every unit spawns at `+ 1`. */
89
+ currentDepth: number;
90
+ };
91
+
92
+ /**
93
+ * Run the batch-mode prologue. Returns the resolved params + validated cwd on
94
+ * success, or the first gate's rejection in the verbatim wording the suites
95
+ * pin. Gate order is the invariant (IN1/IN3/IN4/IN5/IN6/IN7): `beforeCost` →
96
+ * cost → depth → resolve → targets → preflight → H1.
97
+ */
98
+ export function runModePrologue(input: ModePrologueInput): ModePrologueOutcome {
99
+ const { params, state, ctx, log, label, units, beforeCost } = input;
100
+
101
+ // 0. Mode precondition (graph: DAG validation) — before the cost gate.
102
+ const preCost = beforeCost?.();
103
+ if (preCost) return { ok: false, error: preCost };
104
+
105
+ // 1. Session cost gate (R5) — the first gate of every batch mode.
106
+ const costError = gateSessionCost({
107
+ state,
108
+ ctx,
109
+ log,
110
+ units,
111
+ label: `${label} delegation`,
112
+ });
113
+ if (costError) return { ok: false, error: costError };
114
+
115
+ // 2. Recursion depth gate (IN3) — absent from the background paths by
116
+ // design (they spawn in-process SDK sessions, which do not stamp the
117
+ // depth env key); pinning the asymmetry, not "fixing" it here.
118
+ const currentDepth = getCurrentDepth();
119
+ if (currentDepth >= state.config.maxSubagentDepth) {
120
+ log.warn(`${label} delegation rejected: max depth reached`, {
121
+ currentDepth,
122
+ maxDepth: state.config.maxSubagentDepth,
123
+ });
124
+ return {
125
+ ok: false,
126
+ error: depthLimitRejection(currentDepth, state.config.maxSubagentDepth),
127
+ };
128
+ }
129
+
130
+ // 3. Resolve the global params exactly once (IN4).
131
+ const globalParams = resolveSubagentParams(params, state, ctx, log);
132
+
133
+ // 4. Mode-level target validation — cwd only. Every unit's own outputFile
134
+ // is validated by the per-unit pre-pass (IN5); the message bytes are
135
+ // identical to the inline spelling this replaced.
136
+ const targets = validateDelegationTargets({ ctx, effectiveCwd: globalParams.effectiveCwd });
137
+ if (!targets.ok) return { ok: false, error: targets.error };
138
+
139
+ // 5. Pre-flight checks — fail fast before consuming resources (IN6).
140
+ const pfResult = preflightCheck(targets.cwd);
141
+ if (!pfResult.ok) {
142
+ log.warn(`${label} pre-flight check failed`, { error: pfResult.error });
143
+ return { ok: false, error: rejection(`Pre-flight check failed: ${pfResult.error}`) };
144
+ }
145
+
146
+ // 6. H1 at mode entry — mode-level params only, never prefixed and never
147
+ // carrying `force` (IN7). Warnings are logged, not surfaced: the result
148
+ // warnings come from the per-unit passes.
149
+ const preTask = runPreTaskValidation({
150
+ log,
151
+ label,
152
+ preTask: {
153
+ task: globalParams.task,
154
+ toolOptions: globalParams.toolOptions,
155
+ thinkingLevel: globalParams.thinkingLevel,
156
+ gitMode: globalParams.resolvedGitMode,
157
+ outputFile: globalParams.outputFile,
158
+ // Issue #412: the project-local Jev-line check keys on the DISPATCH
159
+ // cwd (the project whose manifest opts in), and `noJev` is the
160
+ // call-level stated bypass — the mode-level task text is the caller's
161
+ // own, so it is checked and bypassable exactly like a single task.
162
+ cwd: targets.cwd,
163
+ noJev: params.noJev,
164
+ },
165
+ });
166
+ if (preTask.error) return { ok: false, error: preTask.error };
167
+
168
+ return { ok: true, globalParams, resolvedCwd: targets.cwd, currentDepth };
169
+ }
@@ -1,4 +1,4 @@
1
- // Purpose: Auth-aware model availability: distinguishes catalog presence from configured provider auth.
1
+ // Purpose: Model identity + auth-aware availability: parse a provider/model-id string and check catalog presence plus configured provider auth.
2
2
  /**
3
3
  * Auth-aware model availability check (issue #4).
4
4
  *
@@ -23,6 +23,18 @@ export interface ModelLike {
23
23
  id: string;
24
24
  }
25
25
 
26
+ /**
27
+ * Parse a `provider/model-id` string. Returns null on anything that is not
28
+ * exactly one non-empty provider and one non-empty id (no provider-only or
29
+ * trailing-slash values).
30
+ */
31
+ export function parseModelString(s: string): { provider: string; id: string } | null {
32
+ const trimmed = s.trim();
33
+ const idx = trimmed.indexOf("/");
34
+ if (idx <= 0 || idx === trimmed.length - 1) return null;
35
+ return { provider: trimmed.slice(0, idx), id: trimmed.slice(idx + 1) };
36
+ }
37
+
26
38
  export interface ProviderAuthStatusLike {
27
39
  configured?: boolean;
28
40
  source?: string;
package/src/params.ts CHANGED
@@ -21,6 +21,8 @@ import type {
21
21
  ApprovalMode,
22
22
  SubagentToolOptions,
23
23
  ResolvedParams,
24
+ SnapshotParams,
25
+ DelegateTaskParams,
24
26
  } from "./types";
25
27
  import { resolveThinkingLevel } from "./types";
26
28
  import { getAllPresets, getPreset } from "./presets";
@@ -50,7 +52,7 @@ export const KNOWN_DELEGATE_KEYS = new Set([
50
52
  "outputFile", "label", "model", "timeout", "cwd", "tools",
51
53
  "excludeTools", "noBuiltinTools", "preset", "template", "params",
52
54
  "retryRunId", "gitMode", "retryOnTimeout", "approvalMode", "background",
53
- "priority", "chain", "tasks", "graph", "force",
55
+ "priority", "chain", "tasks", "graph", "force", "noJev",
54
56
  ] as const);
55
57
 
56
58
  /**
@@ -82,25 +84,12 @@ export function findUnknownParams(
82
84
  * resolveRetryParams rebuilds a fresh literal and a key missing here is both
83
85
  * unrestored AND discarded when passed explicitly on a retry call. Records
84
86
  * written before this change simply lack the keys (additive, undefined-safe).
87
+ *
88
+ * Issue #381 (audit D5): the 16-field shape is declared once, as
89
+ * `SnapshotParams` in types.ts, and shared with `SubagentRun["originalParams"]`;
90
+ * this signature previously carried its own copy of the literal.
85
91
  */
86
- export function snapshotOriginalParams(params: {
87
- systemPrompt?: string;
88
- inheritSystemPrompt?: boolean;
89
- model?: string;
90
- thinkingLevel?: string;
91
- priority?: string;
92
- outputFile?: string;
93
- timeout?: number;
94
- cwd?: string;
95
- tools?: string[];
96
- excludeTools?: string[];
97
- noBuiltinTools?: boolean;
98
- preset?: string;
99
- background?: boolean;
100
- gitMode?: string;
101
- approvalMode?: string;
102
- force?: boolean;
103
- }): Record<string, unknown> {
92
+ export function snapshotOriginalParams(params: SnapshotParams): Record<string, unknown> {
104
93
  return {
105
94
  systemPrompt: params.systemPrompt,
106
95
  inheritSystemPrompt: params.inheritSystemPrompt,
@@ -192,30 +181,164 @@ export function defaultBackgroundFor(
192
181
  return effectiveApprovalMode === "auto";
193
182
  }
194
183
 
184
+ // ---------------------------------------------------------------------------
185
+ // The thinking-level dispatch-shape pre-flight (issue #412, rule 2)
186
+ // ---------------------------------------------------------------------------
187
+
188
+ /**
189
+ * The notice the dispatch emits when it auto-switches the shape. The text
190
+ * states the TRUE tool fact (why the shape matters), because that is the only
191
+ * thing that makes the switch acceptable to the conductor that asked for
192
+ * foreground: a foreground run has no transcript to resume, so a timeout there
193
+ * loses the work, while a background run keeps its session and is retried on a
194
+ * transport error.
195
+ */
196
+ export const THINKING_SWITCH_NOTICE =
197
+ "Dispatch pre-flight (no deadline means the durable path): a high/xhigh-thinking run was dispatched FOREGROUND with an explicit timeout. " +
198
+ "The explicit timeout was dropped — foreground runs persist nothing, so a timeout there loses the run's whole context, while the 30-minute background deadline applies instead. " +
199
+ "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
+ /** The pre-flight's verdict for one dispatch. */
202
+ export type ThinkingDispatchSwitch = "switch" | "forced" | "none";
203
+
204
+ /**
205
+ * Issue #412 (rule 2: "no deadline ⇒ durable path") — should the pre-flight
206
+ * change this dispatch's shape?
207
+ *
208
+ * The 2026-10-31 incident: a plan critique ran foreground under a 15-minute
209
+ * timeout, was killed at ~14 minutes ("almost done"), and lost everything —
210
+ * the background re-run then cost another 17 minutes. The decision was
211
+ * conductor discretion; this predicate makes the durable shape the only one
212
+ * for the runs where losing the context is expensive:
213
+ *
214
+ * processChecks (the project opted into OUR process — issue #415)
215
+ * + thinkingLevel high|xhigh
216
+ * + background EXPLICITLY false (the caller asked for foreground)
217
+ * + an explicit timeout (the deadline that would kill it)
218
+ * → switch to background and drop the timeout.
219
+ *
220
+ * Deliberately exempt:
221
+ * - `processChecks: false` — this is a CONDUCTOR decision rule, not product
222
+ * behavior. A user's explicit foreground timeout is usually a budget cap,
223
+ * 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
225
+ * 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.
234
+ * - `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.
238
+ *
239
+ * `thinkingLevel` is the DECLARED level (per-call, else the named preset's),
240
+ * not the capped one: `maxThinkingLevel` defaults to `off` for an unconfigured
241
+ * session, so applying the cap here would disable the pre-flight exactly where
242
+ * nobody configured anything — the drift this rule exists to remove.
243
+ */
244
+ export function resolveThinkingDispatchSwitch(input: {
245
+ processChecks: boolean;
246
+ thinkingLevel: ThinkingLevel | undefined;
247
+ explicitBackground: boolean | undefined;
248
+ timeout: number | undefined;
249
+ force: boolean | undefined;
250
+ shape: DispatchShape;
251
+ }): ThinkingDispatchSwitch {
252
+ if (!input.processChecks) return "none";
253
+ 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";
256
+ if (input.timeout === undefined) return "none";
257
+ return input.force === true ? "forced" : "switch";
258
+ }
259
+
260
+ /**
261
+ * The resolver's input: the dispatch-param fields resolution actually reads,
262
+ * derived from the registered schema (issue #379) instead of re-spelled here.
263
+ *
264
+ * `task` is OPTIONAL because the schema says so (`chain`/`tasks`/`graph`
265
+ * dispatches carry no mode-level task) — batch call sites therefore pass the
266
+ * registered params object through unchanged. The four `params as {…}`
267
+ * assertions this replaces existed only to claim a `task` the schema never
268
+ * required. `resolveSubagentParams` defaults it with `?? ""`, which every
269
+ * reader of the field treats like `undefined` (see the `task` line below).
270
+ *
271
+ * Compile-time coverage of this key list is ratcheted in index.ts
272
+ * (`_ResolveInputCoverage`) — a schema field the resolver forgets is silent at
273
+ * runtime, so only the compiler can catch it.
274
+ */
275
+ export type ResolveInputParams = Pick<
276
+ DelegateTaskParams,
277
+ | "task"
278
+ | "label"
279
+ | "preset"
280
+ | "systemPrompt"
281
+ | "inheritSystemPrompt"
282
+ | "thinkingLevel"
283
+ | "outputFile"
284
+ | "timeout"
285
+ | "cwd"
286
+ | "tools"
287
+ | "excludeTools"
288
+ | "noBuiltinTools"
289
+ | "gitMode"
290
+ | "approvalMode"
291
+ | "template"
292
+ // Capability-block override: carried here so the validation call sites
293
+ // (which receive the resolved params) can forward it to validatePreTask.
294
+ // Resolution itself ignores it.
295
+ | "force"
296
+ >;
297
+
298
+ /**
299
+ * Issue #412: resolve the preset a dispatch will actually run with, INCLUDING
300
+ * the auto-route decision. Extracted from `resolveSubagentParams` so the
301
+ * dispatch pre-flight can ask "what thinking level will this run have?"
302
+ * without re-spelling the routing condition — a second copy of that condition
303
+ * is exactly the silent drift `_ResolveInputCoverage` and the KNOWN_DELEGATE_KEYS
304
+ * ratchet exist to prevent.
305
+ *
306
+ * `name` is what the caller asked for (or the routed match); `preset` is the
307
+ * resolved record, `undefined` when neither exists. `autoRouted` distinguishes
308
+ * a routed match from an explicit request (the caller logs the evidence).
309
+ */
310
+ export function resolveDispatchPreset(
311
+ params: Pick<
312
+ ResolveInputParams,
313
+ "preset" | "template" | "tools" | "excludeTools" | "noBuiltinTools" | "task"
314
+ >,
315
+ state: Pick<SessionState, "builtinPresets" | "customPresets">,
316
+ ): { name?: string; preset?: SubagentPreset; autoRouted: boolean; keyword?: string } {
317
+ if (params.preset) {
318
+ return { name: params.preset, preset: getPreset(params.preset, state.builtinPresets, state.customPresets), autoRouted: false };
319
+ }
320
+ // E2: an explicit template or tool preference is intent that must win over
321
+ // keyword routing (issue #57) — unchanged from the resolver's rule.
322
+ const hasExplicitToolPreference =
323
+ params.tools !== undefined ||
324
+ params.excludeTools !== undefined ||
325
+ params.noBuiltinTools !== undefined;
326
+ if (params.template || hasExplicitToolPreference) return { autoRouted: false };
327
+ const matched = classifyTask(
328
+ params.task ?? "",
329
+ getAllPresets(state.builtinPresets, state.customPresets),
330
+ );
331
+ if (!matched) return { autoRouted: false };
332
+ return {
333
+ name: matched.preset,
334
+ preset: getPreset(matched.preset, state.builtinPresets, state.customPresets),
335
+ autoRouted: true,
336
+ keyword: matched.keyword,
337
+ };
338
+ }
339
+
195
340
  export function resolveSubagentParams(
196
- params: {
197
- task: string;
198
- label?: string;
199
- preset?: string;
200
- systemPrompt?: string;
201
- inheritSystemPrompt?: boolean;
202
- thinkingLevel?: string;
203
- outputFile?: string;
204
- timeout?: number;
205
- cwd?: string;
206
- tools?: string[];
207
- excludeTools?: string[];
208
- noBuiltinTools?: boolean;
209
- gitMode?: string;
210
- approvalMode?: string;
211
- template?: string;
212
- /**
213
- * Capability-block override: carried here so the validation call sites
214
- * (which receive the resolved params) can forward it to validatePreTask.
215
- * Resolution itself ignores it.
216
- */
217
- force?: boolean;
218
- },
341
+ params: ResolveInputParams,
219
342
  state: SessionState,
220
343
  ctx: ExtensionContext,
221
344
  log: Logger,
@@ -229,25 +352,16 @@ export function resolveSubagentParams(
229
352
  autoRouteKeyword?: string;
230
353
  } {
231
354
  // E2: Auto-route to best preset only when the conductor expressed NO
232
- // explicit preference — an explicit preset, template, or tool
233
- // parameters (tools/excludeTools/noBuiltinTools) all count as intent
234
- // that must win over keyword-based routing (issue #57).
235
- let resolvedPreset = params.preset;
236
- let wasAutoRouted = false;
237
- let routeKeyword: string | undefined;
238
- const hasExplicitToolPreference =
239
- params.tools !== undefined ||
240
- params.excludeTools !== undefined ||
241
- params.noBuiltinTools !== undefined;
242
- if (!resolvedPreset && !params.template && !hasExplicitToolPreference) {
243
- const allPresets = getAllPresets(state.builtinPresets, state.customPresets);
244
- const matched = classifyTask(params.task, allPresets);
245
- if (matched) {
246
- resolvedPreset = matched.preset;
247
- wasAutoRouted = true;
248
- routeKeyword = matched.keyword;
249
- log.info("Auto-routed task to preset", { preset: matched.preset, keyword: matched.keyword });
250
- }
355
+ // explicit preference — an explicit preset, template, or tool parameters
356
+ // (tools/excludeTools/noBuiltinTools) all count as intent that must win over
357
+ // keyword-based routing (issue #57). The rule lives in `resolveDispatchPreset`
358
+ // so the dispatch pre-flight (#412) resolves the SAME preset this merge does.
359
+ const routed = resolveDispatchPreset(params, state);
360
+ const resolvedPreset = routed.name;
361
+ const wasAutoRouted = routed.autoRouted;
362
+ const routeKeyword = routed.keyword;
363
+ if (wasAutoRouted) {
364
+ log.info("Auto-routed task to preset", { preset: resolvedPreset, keyword: routeKeyword });
251
365
  }
252
366
 
253
367
  const preset = resolvedPreset
@@ -301,7 +415,10 @@ export function resolveSubagentParams(
301
415
  : undefined;
302
416
 
303
417
  return {
304
- task: params.task,
418
+ // "" ≡ undefined at all three readers of the field: mergeSubTaskParams
419
+ // (`subTask.task || globalParams.task`), validatePreTask
420
+ // (`config.task || ''`) and classifyTask (`if (!task …)`).
421
+ task: params.task ?? "",
305
422
  label: params.label?.trim() || undefined,
306
423
  inheritSP: mergedInheritSP !== false,
307
424
  customSP: mergedSystemPrompt,