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/params.ts CHANGED
@@ -24,7 +24,7 @@ import type {
24
24
  SnapshotParams,
25
25
  DelegateTaskParams,
26
26
  } from "./types";
27
- import { resolveThinkingLevel } from "./types";
27
+ import { approvalBlocksBackground, declaredThinkingLevel, resolveThinkingLevel } from "./types";
28
28
  import { getAllPresets, getPreset } from "./presets";
29
29
  import { classifyTask } from "./router";
30
30
  import { normalizeTimeout } from "./validate";
@@ -199,48 +199,106 @@ export const THINKING_SWITCH_NOTICE =
199
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
200
 
201
201
  /** The pre-flight's verdict for one dispatch. */
202
- export type ThinkingDispatchSwitch = "switch" | "forced" | "none";
202
+ export type ThinkingDispatchSwitch = "switch" | "drop-timeout" | "forced" | "none";
203
203
 
204
204
  /**
205
- * Issue #412 (rule 2: "no deadline ⇒ durable path") — should the pre-flight
206
- * change this dispatch's shape?
205
+ * The notice the dispatch emits on the SECOND arm (issue #431): the run was
206
+ * going to be killed by its own explicit foreground timeout, but its approval
207
+ * mode makes a background run impossible (or it never asked for one), so the
208
+ * deadline is dropped and the shape stays foreground.
209
+ *
210
+ * Deliberately NOT `THINKING_SWITCH_NOTICE`: that text says "the run is now
211
+ * background", which is a lie on this arm. The trade-off (no clock on a hung
212
+ * child) is stated rather than hidden — a dropped deadline removes the only
213
+ * bound the runner had.
214
+ */
215
+ export const THINKING_TIMEOUT_DROP_NOTICE =
216
+ "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. " +
217
+ "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. " +
218
+ "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.";
219
+
220
+ /**
221
+ * Issue #412 (rule 2: "no deadline ⇒ durable path") — what should the
222
+ * pre-flight do with this dispatch?
207
223
  *
208
224
  * The 2026-10-31 incident: a plan critique ran foreground under a 15-minute
209
225
  * timeout, was killed at ~14 minutes ("almost done"), and lost everything —
210
226
  * the background re-run then cost another 17 minutes. The decision was
211
227
  * conductor discretion; this predicate makes the durable shape the only one
212
- * for the runs where losing the context is expensive:
228
+ * for the runs where losing the context is expensive.
229
+ *
230
+ * One rule, two arms — the run must not be killable by its own deadline:
213
231
  *
214
232
  * processChecks (the project opted into OUR process — issue #415)
215
233
  * + thinkingLevel high|xhigh
216
- * + background EXPLICITLY false (the caller asked for foreground)
217
234
  * + an explicit timeout (the deadline that would kill it)
218
- * → switch to background and drop the timeout.
235
+ * + an effective FOREGROUND shape
236
+ *
237
+ * → "switch": move to background and drop the timeout (the 30-minute
238
+ * background default applies) — used when a background run is possible.
239
+ * → "drop-timeout": keep foreground and drop the timeout (a foreground
240
+ * run has no default deadline since #423) — used when it is not:
241
+ * · `background: false` + effective `always`: switching there would be
242
+ * REJECTED (no dialog in background), and a pre-flight must never
243
+ * turn a valid dispatch into an error (#433);
244
+ * · `background` omitted where the #361 default resolved FOREGROUND
245
+ * (effective `writes`/`always`): the default already judged the
246
+ * approval mode, so the deadline is all that is left to remove.
219
247
  *
220
248
  * Deliberately exempt:
221
249
  * - `processChecks: false` — this is a CONDUCTOR decision rule, not product
222
250
  * behavior. A user's explicit foreground timeout is usually a budget cap,
223
251
  * 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
252
+ * The umbrella flag (ADR 0019) is what makes the pre-flight opt-in; the
225
253
  * 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.
254
+ * - `chain`/`graph` — an uncapped batch multiplies a hang across N units and
255
+ * has no per-unit pre-flight (#434); the exemption is about the BATCH now,
256
+ * not about `background: true` being rejected (which motivated it for the
257
+ * switch arm only).
258
+ * - an explicit `background: true` — the caller asked for background; there
259
+ * is no foreground deadline to lose.
260
+ * - an omitted `background` whose effective shape is background (`auto`) —
261
+ * the #361 default already chose the durable shape.
262
+ * - no explicit timeout — there is no deadline to drop.
234
263
  * - `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.
264
+ * caller can tell "kept by request" from "never applied". `force` carries
265
+ * no reason field (ADR 0007): the dispatch text is the reason.
266
+ * PRECEDENCE: force maps `switch`/`drop-timeout` → `forced`; an arm that
267
+ * computes `none` stays `none` REGARDLESS of force — there is nothing to
268
+ * override, and the call site's "foreground forced" log line must never
269
+ * print for a run that is already background.
270
+ *
271
+ * The omitted-background arm keys on the EFFECTIVE SHAPE via
272
+ * `defaultBackgroundFor`, never on a re-spelled mode list — the same helper the
273
+ * #361 default uses, so the two cannot disagree. `effectiveApprovalMode` is
274
+ * resolved by `resolveEffectiveApprovalMode(params.approvalMode, state)` at the
275
+ * call site, never read from the raw call param: a config-tier mode must reach
276
+ * this predicate, and the `always` guard goes through `approvalBlocksBackground`
277
+ * — the same helper the background gates reject with.
278
+ *
279
+ * INVARIANT (MAJ-7): "drop the timeout" is `params.timeout = undefined`, which
280
+ * `resolveSubagentParams` merges as `params.timeout ?? preset?.timeout`. The
281
+ * drop arm's no-deadline guarantee therefore holds ONLY because no preset can
282
+ * carry a `timeout` at runtime (`presetFromFrontmatter` maps none, so
283
+ * `SubagentPreset.timeout` is dead). If preset timeouts ever map, the drop
284
+ * silently re-merges one, no test fails, and the notice becomes a lie — merge
285
+ * or skip the preset value here first.
238
286
  *
239
287
  * `thinkingLevel` is the DECLARED level (per-call, else the named preset's),
240
288
  * not the capped one: `maxThinkingLevel` defaults to `off` for an unconfigured
241
289
  * session, so applying the cap here would disable the pre-flight exactly where
242
290
  * nobody configured anything — the drift this rule exists to remove.
243
291
  */
292
+ /**
293
+ * #434 review (DRY): the two levels the pre-flight treats as "high thinking".
294
+ * ONE member test, used by the dispatch predicate and by its unit projection —
295
+ * the literal pair is shared core, not a documented divergence, and U10 pins
296
+ * that the two predicates agree on the same declared pair.
297
+ */
298
+ export function isHighDeclaredLevel(level: ThinkingLevel | string | undefined): boolean {
299
+ return level === "high" || level === "xhigh";
300
+ }
301
+
244
302
  export function resolveThinkingDispatchSwitch(input: {
245
303
  processChecks: boolean;
246
304
  thinkingLevel: ThinkingLevel | undefined;
@@ -248,13 +306,124 @@ export function resolveThinkingDispatchSwitch(input: {
248
306
  timeout: number | undefined;
249
307
  force: boolean | undefined;
250
308
  shape: DispatchShape;
309
+ /** The mode the child will actually run with (call param, else config). */
310
+ effectiveApprovalMode: ApprovalMode;
251
311
  }): ThinkingDispatchSwitch {
252
312
  if (!input.processChecks) return "none";
253
313
  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";
314
+ if (!isHighDeclaredLevel(input.thinkingLevel)) return "none";
256
315
  if (input.timeout === undefined) return "none";
257
- return input.force === true ? "forced" : "switch";
316
+ const base: ThinkingDispatchSwitch =
317
+ input.explicitBackground === true
318
+ ? "none"
319
+ : input.explicitBackground === false
320
+ ? approvalBlocksBackground(input.effectiveApprovalMode)
321
+ ? "drop-timeout"
322
+ : "switch"
323
+ : defaultBackgroundFor(input.shape, input.effectiveApprovalMode)
324
+ ? "none"
325
+ : "drop-timeout";
326
+ if (base === "none") return "none";
327
+ return input.force === true ? "forced" : base;
328
+ }
329
+
330
+ /**
331
+ * The notice a batch dispatch emits when the UNIT projection of the same rule
332
+ * (issue #434) removes a unit's own declared deadline.
333
+ *
334
+ * Emitted at most once per dispatch, at the first affected unit's run — so the
335
+ * wording deliberately claims NO completeness: it names that one unit and says
336
+ * when the others are judged. A unit cancelled before its run is never named,
337
+ * and a unit whose own declaration is not eligible gets no line at all.
338
+ *
339
+ * Deliberately NOT `THINKING_TIMEOUT_DROP_NOTICE`: that text reasons about the
340
+ * DISPATCH's effective approval mode, which says nothing about a unit that
341
+ * declared its own pair inside a batch the caller already shaped.
342
+ */
343
+ export const THINKING_UNIT_TIMEOUT_DROP_NOTICE =
344
+ "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. " +
345
+ "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. " +
346
+ "Pass force: true to keep the units' declared timeouts.";
347
+
348
+ /**
349
+ * Whether a UNIT runs foreground or background — the unit's own shape, which
350
+ * decides whether its declared deadline is a foreground hazard at all (issue
351
+ * #434).
352
+ *
353
+ * Background units are excluded by construction: a `tasks` fan-out spawns its
354
+ * units as detached background agents, where the deadline is the legitimate
355
+ * 30-minute budget and dropping it would REMOVE a bound instead of adding
356
+ * durability. Chain/graph units are always foreground (an explicit
357
+ * `background: true` batch is rejected at dispatch).
358
+ */
359
+ export type UnitShape = "foreground" | "background";
360
+
361
+ /**
362
+ * Issue #434 — the UNIT projection of `resolveThinkingDispatchSwitch`.
363
+ *
364
+ * The dispatch rule only judges the DISPATCH-level pair (`params.thinkingLevel`
365
+ * + `params.timeout`). Batch units carry their own (`schema.ts`
366
+ * `STEP_HEAD_FIELDS`/`STEP_THINKING_LEVEL_FIELD`/`STEP_TAIL_FIELDS`) and
367
+ * `mergeSubTaskParams` lets the unit win per field, so a unit declaring
368
+ * `thinkingLevel: "high"` + `timeout: 600000` under no top-level pair
369
+ * reproduced the 2026-11-06 incident for that unit alone: the dispatch
370
+ * predicate exits early on `params.timeout === undefined`.
371
+ *
372
+ * Only ONE arm is available per unit — a unit cannot become its own background
373
+ * dispatch (it is one spawn inside a batch the caller already shaped), so the
374
+ * projection answers a boolean and never re-states the switch/drop-timeout
375
+ * approval arms that decide a DISPATCH's shape.
376
+ *
377
+ * Eligible when ALL hold:
378
+ *
379
+ * 1. `processChecks` — threaded from `execute` so a unit is judged by the
380
+ * same project opt-in as its dispatch. NEVER re-read at the unit site: a
381
+ * relative `params.cwd` re-read (against the process cwd instead of
382
+ * `ctx.cwd`) measured `false` where the dispatch resolved `true`.
383
+ * 2. `force !== true` — the override reaches units too; it is the caller's
384
+ * statement that the declared pair is intentional.
385
+ * 3. the unit's EFFECTIVE DECLARED level is high/xhigh: its own declaration,
386
+ * else the dispatch's declared level, which the unit inherits. NOT
387
+ * `merged.thinkingLevel`: that value is CAPPED, and the default cap is
388
+ * `off`, so judging it would silently disable this guard exactly where
389
+ * nobody configured anything — the same drift #443 removed one level up.
390
+ * 4. the MERGED timeout is defined and `> 0`. Only a positive timeout arms a
391
+ * foreground timer (`runner.ts`: `if (timeout && timeout > 0)`), and
392
+ * `mergeSubTaskParams` merges with `??`, so a declared `timeout: 0`
393
+ * OVERRIDES an inherited timeout and arms nothing — never eligible.
394
+ * 5. the unit DECLARES the pair — a non-empty `thinkingLevel`, or `timeout`
395
+ * present (a `0` included: it is a declaration, it just never arms a
396
+ * timer). This is the #434/#431 boundary: a unit that declares NEITHER
397
+ * and inherits the dispatch's pair was already judged at dispatch level,
398
+ * including the chain/graph exemption — so inherited pairs stay exempt
399
+ * (pinned, not accidental) while unit-declared ones do not.
400
+ * 6. the unit's shape is FOREGROUND (`unitShape`, passed explicitly so the
401
+ * exclusion is visible at the call site).
402
+ *
403
+ * The caller applies the effect — `merged.timeout = undefined` — before the
404
+ * unit's run record is created, so the retry snapshot records an absent
405
+ * deadline instead of restoring the cap (ADR 0009).
406
+ */
407
+ export function shouldDropUnitTimeout(input: {
408
+ processChecks: boolean;
409
+ force: boolean | undefined;
410
+ /** The DISPATCH's declared level, threaded from `execute` (clause 3). */
411
+ dispatchDeclaredLevel: ThinkingLevel | undefined;
412
+ unitShape: UnitShape;
413
+ /** The unit's OWN declaration: `""`/`undefined` both mean "inherit". */
414
+ declaredLevel: ThinkingLevel | "" | undefined;
415
+ /** The unit's OWN timeout declaration (`undefined` = inherit). */
416
+ declaredTimeout: number | undefined;
417
+ /** `mergeSubTaskParams`' result: the deadline the unit would actually run with. */
418
+ mergedTimeout: number | undefined;
419
+ }): boolean {
420
+ if (!input.processChecks) return false;
421
+ if (input.force === true) return false;
422
+ if (input.unitShape !== "foreground") return false;
423
+ const effectiveDeclaredLevel = input.declaredLevel || input.dispatchDeclaredLevel;
424
+ if (!isHighDeclaredLevel(effectiveDeclaredLevel)) return false;
425
+ if (input.mergedTimeout === undefined || input.mergedTimeout <= 0) return false;
426
+ return Boolean(input.declaredLevel) || input.declaredTimeout !== undefined;
258
427
  }
259
428
 
260
429
  /**
@@ -369,9 +538,13 @@ export function resolveSubagentParams(
369
538
  : undefined;
370
539
  const autoRoutedPreset = wasAutoRouted ? preset : undefined;
371
540
 
372
- const mergedThinkingLevel =
373
- (params.thinkingLevel as ThinkingLevel | undefined) ??
374
- (preset?.thinkingLevel as ThinkingLevel | undefined);
541
+ // The DECLARED level (per-call, else the selected preset's) — read through the
542
+ // shared helper so both dispatch guards (issue #443) judge exactly the value
543
+ // this merge resolves, not a second interpretation of it.
544
+ const mergedThinkingLevel = declaredThinkingLevel(
545
+ params.thinkingLevel,
546
+ preset?.thinkingLevel,
547
+ ) as ThinkingLevel | undefined;
375
548
  const mergedSystemPrompt = params.systemPrompt ?? preset?.systemPrompt;
376
549
  const mergedInheritSP = params.inheritSystemPrompt ?? preset?.inheritSystemPrompt;
377
550
  const mergedOutputFile = params.outputFile ?? preset?.outputFile;
package/src/prelude.ts CHANGED
@@ -47,6 +47,7 @@
47
47
 
48
48
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
49
49
  import type { ApprovalMode, GitMode, SubagentPreset, SubagentToolOptions, ThinkingLevel, ToolResult } from "./types";
50
+ import { approvalBlocksBackground, isThinkingLevel, THINKING_LEVELS } from "./types";
50
51
  import type { SessionState } from "./state";
51
52
  import type { Logger } from "./logging";
52
53
  import { validateCwd, validateOutputFile } from "./sanitize";
@@ -89,6 +90,62 @@ export function modelNotConfiguredRejection(): ToolResult<undefined> {
89
90
  );
90
91
  }
91
92
 
93
+ // ── Gate 0: a DECLARED thinking level (issue #443) ──────────────────────
94
+
95
+ /**
96
+ * Render a declared value for the rejection text. A string is quoted as JSON so
97
+ * an empty/whitespace value is VISIBLE (`""` vs `" high"`); anything else
98
+ * arrives only from a programmatic caller (the schema declares a string), so it
99
+ * is rendered as JSON and falls back to `String` for the values JSON rejects
100
+ * (a `BigInt` throws, a symbol stringifies to `undefined`).
101
+ */
102
+ function renderDeclaredThinkingLevel(value: unknown): string {
103
+ try {
104
+ return JSON.stringify(value) ?? String(value);
105
+ } catch {
106
+ return String(value);
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Reject an unsupported DECLARED thinking level before it reaches resolution
112
+ * (issue #443). Returns `undefined` when the value is usable.
113
+ *
114
+ * This is the runtime guard; the schema's `enum` is only the first line of
115
+ * defence, because pi validates raw TOOL ARGUMENTS. Every other route to a
116
+ * launch — a preset object injected in memory (the file tier has its own
117
+ * validator, `getPreset` does not re-check), a value restored by `retryRunId`,
118
+ * the transport auto-retry's rebuilt params, a per-unit declaration — reaches
119
+ * `resolveSubagentParams` without passing through the schema at all.
120
+ *
121
+ * The guard must run before resolution: `resolveThinkingLevel` erases an
122
+ * unknown value to `undefined`, which then survives every later check
123
+ * (`resolveSubagentParams` returns a level, it cannot report a failure) and
124
+ * reaches the child as `--thinking undefined`, where pi warns and runs at its
125
+ * own default — the configured cap silently bypassed.
126
+ *
127
+ * Deliberately NOT rejected: `undefined`/`null` (omitted) and `""`. Both are
128
+ * existing, meaningful declarations — top level `""` means "use the configured
129
+ * maximum", per unit `""` means "inherit the global level" — so the empty
130
+ * string keeps its meaning rather than becoming an error.
131
+ *
132
+ * `prefix` names the unit a per-unit declaration came from, matching the other
133
+ * unit-prefixed rejections (`Task 2 ("two"): …`).
134
+ */
135
+ export function invalidThinkingLevelRejection(
136
+ declared: unknown,
137
+ prefix?: string,
138
+ ): ToolResult<undefined> | undefined {
139
+ // Omitted, or the preserved empty-string declaration: not a level to judge.
140
+ if (declared === undefined || declared === null || declared === "") return undefined;
141
+ if (isThinkingLevel(declared)) return undefined;
142
+ return rejection(
143
+ `${prefix ? `${prefix}: ` : ""}Invalid thinkingLevel ${renderDeclaredThinkingLevel(declared)}. ` +
144
+ `Valid levels: ${THINKING_LEVELS.join(", ")} — matched exactly, so "High" and " high" are rejected too. ` +
145
+ `Omit thinkingLevel, or pass "", to use the configured maximum.`,
146
+ );
147
+ }
148
+
92
149
  // ── Gate 1: session cost ────────────────────────────────────────────────
93
150
 
94
151
  /**
@@ -142,7 +199,7 @@ export function gateSessionCost(input: {
142
199
  export function rejectApprovalAlwaysInBackground(
143
200
  approvalMode: ApprovalMode,
144
201
  ): ToolResult<undefined> | undefined {
145
- if (approvalMode !== "always") return undefined;
202
+ if (!approvalBlocksBackground(approvalMode)) return undefined;
146
203
  return rejection(
147
204
  `Cannot spawn background agent with approvalMode 'always': background agents run unattended ` +
148
205
  `and cannot present the approval dialog. Use approvalMode 'auto' (default) or 'writes'.`,
@@ -310,6 +367,15 @@ export interface UnitPrePassInput<U, M extends UnitPrePassSource> {
310
367
  * silence the check for a batch while appearing to pass it for the call.
311
368
  */
312
369
  noJev?: string;
370
+ /**
371
+ * The unit's DECLARED thinkingLevel, read from the unit itself (issue #443).
372
+ * Required, so a new caller cannot silently skip the check: the merged value
373
+ * cannot be judged — `merge` has already resolved it, and an unknown
374
+ * declaration comes back as `undefined` (the erasure this guard exists for).
375
+ * `""` and an omitted declaration are NOT rejected here: they mean "inherit
376
+ * the global level", which `merge` applies.
377
+ */
378
+ declaredThinkingLevel: (unit: U) => unknown;
313
379
  }
314
380
 
315
381
  export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
@@ -318,7 +384,8 @@ export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
318
384
 
319
385
  /**
320
386
  * The per-unit pre-pass shared by chain, parallel and graph: for EVERY unit,
321
- * merge → validate cwd/outputFile → H1 → collect `${prefix}: ${warning}`.
387
+ * declared-level guard → merge → validate cwd/outputFile → H1 → collect
388
+ * `${prefix}: ${warning}`.
322
389
  *
323
390
  * This is a helper each handler CALLS at its own position; it is deliberately
324
391
  * not a hook the mode prologue invokes — the three modes run it at different
@@ -331,7 +398,7 @@ export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
331
398
  export function validateUnitPrePass<U, M extends UnitPrePassSource>(
332
399
  input: UnitPrePassInput<U, M>,
333
400
  ): UnitPrePassOutcome<U, M> {
334
- const { units, merge, describe, label, gitMode, ctx, log, force, noJev } = input;
401
+ const { units, merge, describe, label, gitMode, ctx, log, force, noJev, declaredThinkingLevel } = input;
335
402
  const validated: Array<ValidatedUnit<U, M>> = [];
336
403
  const warnings: string[] = [];
337
404
 
@@ -340,6 +407,15 @@ export function validateUnitPrePass<U, M extends UnitPrePassSource>(
340
407
  const merged = merge(unit, i);
341
408
  const display = describe(unit, merged, i);
342
409
 
410
+ // Issue #443: the DECLARED per-unit level, before `merged.thinkingLevel`
411
+ // (already resolved, so an unknown value is indistinguishable from
412
+ // omitted) could hide it.
413
+ const thinkingError = invalidThinkingLevelRejection(
414
+ declaredThinkingLevel(unit),
415
+ display.prefix,
416
+ );
417
+ if (thinkingError) return { ok: false, error: thinkingError };
418
+
343
419
  const targets = validateDelegationTargets({
344
420
  ctx,
345
421
  effectiveCwd: merged.effectiveCwd,
package/src/presets.ts CHANGED
@@ -12,7 +12,8 @@ import * as path from "node:path";
12
12
  import type { SubagentPreset, ThinkingLevel } from "./types";
13
13
  import { THINKING_LEVELS } from "./types";
14
14
  import type { Logger } from "./logging";
15
- import { loadMarkdownRecords } from "./loader";
15
+ import { applyFrontmatterMappers, loadMarkdownRecords } from "./loader";
16
+ import type { FrontmatterFieldMapper, FrontmatterMapContext } from "./loader";
16
17
 
17
18
  // `parseFrontmatter` moved to loader.ts when the four loader copies collapsed
18
19
  // into one walk (issue #380). Re-exported so the existing import sites keep
@@ -24,8 +25,8 @@ export { parseFrontmatter } from "./loader";
24
25
  // ---------------------------------------------------------------------------
25
26
 
26
27
  /**
27
- * Validate that a parsed preset has the required name field
28
- * and its thinkingLevel (if set) is a valid value.
28
+ * Validate that a parsed preset has the required name field, its thinkingLevel
29
+ * (if set) is a valid value, and its outputFile (if set) is a string.
29
30
  * Returns validation errors, or empty array if valid.
30
31
  */
31
32
  export function validatePreset(meta: Record<string, unknown>, fileName: string): string[] {
@@ -64,9 +65,87 @@ export function validatePreset(meta: Record<string, unknown>, fileName: string):
64
65
  }
65
66
  }
66
67
 
68
+ // outputFile is MAPPED (#436), so a non-string here would reach the resolved
69
+ // params as a broken path — refuse it at load, like thinkingLevel above.
70
+ if (meta.outputFile !== undefined && typeof meta.outputFile !== "string") {
71
+ errors.push(
72
+ `Preset "${meta.name}" (${fileName}): outputFile must be a string, got "${String(meta.outputFile)}".`,
73
+ );
74
+ }
75
+
67
76
  return errors;
68
77
  }
69
78
 
79
+ // ---------------------------------------------------------------------------
80
+ // Frontmatter → SubagentPreset mapping
81
+ // ---------------------------------------------------------------------------
82
+
83
+ /**
84
+ * Preset fields that are DELIBERATELY not mapped from frontmatter. This is the
85
+ * only sanctioned escape hatch from the parity pin below — every entry must
86
+ * name its reason.
87
+ *
88
+ * `timeout` (ADR 0022 §6): `resolveSubagentParams` merges
89
+ * `params.timeout ?? preset?.timeout`, so a preset-supplied deadline would
90
+ * silently re-merge the value the dispatch pre-flight's `drop-timeout` arm
91
+ * believes it dropped, and `THINKING_TIMEOUT_DROP_NOTICE`'s "no clock kills it"
92
+ * sentence would become false — with no other test failing. Mapping it requires
93
+ * re-deriving that arm first (issue #431).
94
+ */
95
+ type OmittedPresetField = "timeout";
96
+
97
+ /**
98
+ * Compile-time pin on the allowlist being EXACTLY `"timeout"` (#436 review
99
+ * nit): the `satisfies` below only notices a field that is missing from the
100
+ * table, so adding a new field to BOTH `SubagentPreset` and this union used to
101
+ * compile cleanly — the reviewed bypass. A tuple-wrapped union extends a
102
+ * one-element tuple only when it is that member, so a second entry turns this
103
+ * into `never` and the assignment under it fails with TS2322.
104
+ */
105
+ type OmittedMustStayTimeout = [OmittedPresetField] extends ["timeout"] ? true : never;
106
+
107
+ /** Kept live by the export; its only job is to fail `tsc` when the pin flips. */
108
+ export const PRESET_OMIT_PIN: OmittedMustStayTimeout = true;
109
+
110
+ /** Every preset field that frontmatter MUST be able to populate (issue #436). */
111
+ type MappedPresetField = Exclude<keyof SubagentPreset, OmittedPresetField>;
112
+
113
+ /**
114
+ * Per-key return types: the mapper for `outputFile` must return
115
+ * `SubagentPreset["outputFile"]` (a string | undefined), so a mapper that
116
+ * returns `42` — previously blessed by the `unknown` value type plus the
117
+ * assembly cast — is now a compile error at the row.
118
+ */
119
+ type PresetFieldMappers = {
120
+ [K in MappedPresetField]: FrontmatterFieldMapper<SubagentPreset[K]>;
121
+ };
122
+
123
+ /**
124
+ * THE declaration of which frontmatter keys reach a `SubagentPreset` — one
125
+ * table, so a field cannot be declared in the type and forgotten here.
126
+ *
127
+ * `satisfies PresetFieldMappers` is the parity pin: adding a field to
128
+ * `SubagentPreset` without a mapper is a COMPILE error (the record is missing a
129
+ * key), a mapper for a field the type no longer declares is an excess-property
130
+ * error, and a mapper returning the wrong field type is a third. Before #436
131
+ * the object was a hand-written literal, so a declared field (`outputFile`)
132
+ * could be dropped in total silence.
133
+ */
134
+ const PRESET_FIELD_MAPPERS = {
135
+ name: (_meta, ctx) => ctx.name,
136
+ description: (meta) => (meta.description as string) || undefined,
137
+ systemPrompt: (_meta, ctx) => ctx.body || undefined,
138
+ thinkingLevel: (meta) => (meta.thinkingLevel as string) || undefined,
139
+ model: (meta) => (meta.model as string) || undefined,
140
+ inheritSystemPrompt: (meta) => (meta.inheritSystemPrompt === "false" ? false : undefined),
141
+ outputFile: (meta) => (meta.outputFile as string) || undefined,
142
+ tools: (meta) => (Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined),
143
+ excludeTools: (meta) =>
144
+ Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
145
+ noBuiltinTools: (meta) => (meta.noBuiltinTools === "true" ? true : undefined),
146
+ promptGuideline: (meta) => (meta.promptGuideline as string) || undefined,
147
+ } satisfies PresetFieldMappers;
148
+
70
149
  // ---------------------------------------------------------------------------
71
150
  // Loading
72
151
  // ---------------------------------------------------------------------------
@@ -80,18 +159,8 @@ function presetFromFrontmatter(
80
159
  body: string,
81
160
  name: string,
82
161
  ): SubagentPreset {
83
- return {
84
- name,
85
- description: (meta.description as string) || undefined,
86
- systemPrompt: body || undefined,
87
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
88
- model: (meta.model as string) || undefined,
89
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
90
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
91
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
92
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
93
- promptGuideline: (meta.promptGuideline as string) || undefined,
94
- };
162
+ const ctx: FrontmatterMapContext = { name, body };
163
+ return applyFrontmatterMappers<SubagentPreset>(PRESET_FIELD_MAPPERS, meta, ctx);
95
164
  }
96
165
 
97
166
  /**
@@ -3,9 +3,9 @@
3
3
  * The umbrella project-local flag: `{"brl-subagent": {"processChecks": true}}`.
4
4
  *
5
5
  * `processChecks` gates OUR process mechanisms — the Jev dispatch-line check
6
- * (#407/#412) and rule 2's durable-shape auto-switch (#412). It replaces the
7
- * merged-but-unreleased `requireJevLine`: one flag, one reader, no per-rule
8
- * fields.
6
+ * (#407/#412), rule 2's durable-shape auto-switch (#412), and the
7
+ * engineering-bar injection (#421). It replaces the merged-but-unreleased
8
+ * `requireJevLine`: one flag, one reader, no per-rule fields.
9
9
  *
10
10
  * Why one reader (issue #415): the shape rule shipped GLOBAL, so a user's
11
11
  * explicit `background: false` + timeout was overridden by our conductor
@@ -88,6 +88,13 @@ export interface RecoveryDeps {
88
88
  * the historical wait-the-full-grace-once shape.
89
89
  */
90
90
  pollMs?: number;
91
+ /**
92
+ * #455: bounded post-SIGKILL confirmation window (ms) threaded into
93
+ * `escalateKill` — the reap does not classify a pid it just SIGKILLed as a
94
+ * survivor until this window expires. Omitted → `escalateKill`'s default
95
+ * (100 ms); `0` restores the legacy single-sample classification.
96
+ */
97
+ drainMs?: number;
91
98
  }
92
99
 
93
100
  /** Which persisted store a candidate record came from. */
@@ -291,6 +298,9 @@ export async function reapPids(
291
298
  graceMs: deps.graceMs,
292
299
  pollMs: deps.pollMs,
293
300
  sleep: deps.sleep,
301
+ // #455: the survivors below are pids, not samples — a SIGKILL that has not
302
+ // landed yet must not be reported as a surviving orphan.
303
+ drainMs: deps.drainMs,
294
304
  });
295
305
  const survivedSet = new Set(survivors);
296
306
  return unique.filter((_, index) => survivedSet.has(targets[index]));