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
package/src/preflight.ts CHANGED
@@ -1,16 +1,34 @@
1
- // Purpose: Pre-spawn environment checks: pi binary, temp-dir writability, cwd readability.
1
+ // Purpose: Pre-spawn environment checks: pi binary, scratch-root writability, cwd readability.
2
2
  /**
3
3
  * brl-subagent — Pre-flight Checks (R3)
4
4
  *
5
5
  * Validates the execution environment before spawning a subagent.
6
- * Checks: pi binary availability, temp directory writability,
7
- * and project cwd readability.
6
+ * Checks: pi binary availability, **shipped scratch-root** writability (issue
7
+ * #511, U4 — the last probe of a system-temp path), and project cwd
8
+ * readability.
9
+ *
10
+ * THE THIRD CHECK IS AN EARLY WARNING, NOT THE AUTHORITY. It resolves the same
11
+ * root the spawn uses and proves a file can be created where the root lives or
12
+ * would be created; `prepareRunScratch` then re-resolves, re-validates the chain
13
+ * and creates `<root>/runs/<id>` at 0700 on every spawn. This check exists so a
14
+ * human learns before the dispatch does — never as the only place a bad root is
15
+ * caught.
16
+ *
17
+ * LIMITS, stated rather than implied: the probe CREATES nothing durable — a
18
+ * missing root stays missing (the spawn creates it), so a probe that passes on
19
+ * a writable ancestor says "the root can be created here", not "the root is
20
+ * sound"; a process killed between the write and the unlink leaves one 0600
21
+ * `.brl-preflight-probe-<pid>-<n>` file in the root or its nearest existing
22
+ * ancestor, recognisable and inert (nothing reads it, and no validation looks
23
+ * at it); and no system-temp
24
+ * path is probed, used as a fallback, or advised in a message any more
25
+ * (`src/__tests__/no-temp-paths` is the guard).
8
26
  */
9
27
 
10
28
  import * as fs from "node:fs";
11
- import * as os from "node:os";
12
29
  import * as path from "node:path";
13
30
  import { getPiInvocation } from "./runner";
31
+ import { FILE_MODE, resolveRoot, type RootOptions } from "./scratch-root";
14
32
 
15
33
  // ---------------------------------------------------------------------------
16
34
  // Types
@@ -18,6 +36,16 @@ import { getPiInvocation } from "./runner";
18
36
 
19
37
  export type PreflightResult = { ok: true } | { ok: false; error: string };
20
38
 
39
+ /** What a caller may inject. Production passes nothing. */
40
+ export interface PreflightOptions {
41
+ /**
42
+ * Root-resolution inputs (U1's seam), injected by tests only — `home` is the
43
+ * one that moves the layout. Production lets `resolveRoot` read the real
44
+ * environment.
45
+ */
46
+ root?: RootOptions;
47
+ }
48
+
21
49
  // ---------------------------------------------------------------------------
22
50
  // Checks
23
51
  // ---------------------------------------------------------------------------
@@ -117,24 +145,103 @@ function checkCwdReadable(cwd: string): PreflightResult {
117
145
  return { ok: true };
118
146
  }
119
147
 
148
+ /** The probe's one name, so a leftover from a killed process is recognisable as ours. */
149
+ const PROBE_PREFIX = ".brl-preflight-probe";
150
+
151
+ /**
152
+ * A per-process sequence, appended to the probe's name.
153
+ *
154
+ * The pid alone is not enough: `preflightCheck` runs BEFORE the concurrency slot
155
+ * is taken, so two overlapping dispatches in one process can probe at the same
156
+ * moment — and both would then write and unlink the SAME path, letting one
157
+ * call's unlink make the other report "not writable" for a directory that is
158
+ * perfectly writable. A distinct name per call removes the race without a lock.
159
+ */
160
+ let probeSequence = 0;
161
+
162
+ /**
163
+ * The probe's filename for THIS call: prefix, pid and a per-call sequence.
164
+ * Exported so a test can pin the part that matters — two calls must not share a
165
+ * name, because a pid-only name is exactly the race above.
166
+ */
167
+ export function nextProbeName(): string {
168
+ probeSequence += 1;
169
+ return `${PROBE_PREFIX}-${process.pid}-${probeSequence}`;
170
+ }
171
+
172
+ /**
173
+ * The nearest ancestor of `target` that exists — the directory a root that is
174
+ * not there yet would be CREATED in, and therefore the one that must be
175
+ * writable.
176
+ *
177
+ * `access` rather than `existsSync`: a directory we may not even look at is not
178
+ * a directory we can create in, and treating it as "missing" would walk past it
179
+ * and blame the wrong path. `dirname` is separator-agnostic and terminates at
180
+ * the filesystem root, which is returned as-is when nothing above exists.
181
+ */
182
+ function nearestExistingAncestor(target: string): string {
183
+ let current = target;
184
+ for (;;) {
185
+ try {
186
+ fs.accessSync(current, fs.constants.F_OK);
187
+ return current;
188
+ } catch {
189
+ const parent = path.dirname(current);
190
+ if (parent === current) return current;
191
+ current = parent;
192
+ }
193
+ }
194
+ }
195
+
120
196
  /**
121
- * Verify the system temp directory is writable by creating and
122
- * removing a small temporary file.
197
+ * Verify the shipped scratch root is writable, by creating and removing a
198
+ * 0600 probe file (issue #511, U4 — the replacement for the `os.tmpdir()`
199
+ * probe).
200
+ *
201
+ * WHERE it lands: inside the root when the root exists, otherwise in its
202
+ * nearest existing ancestor, because that is where the root would be created.
203
+ * A missing root is NOT a failure — the spawn creates it at 0700.
204
+ *
205
+ * WHERE the root comes from: `resolveRoot` (U1) with this module's injected
206
+ * inputs. PRODUCTION passes none, so the resolver reads the real environment;
207
+ * TESTS inject `{ home }`, the one input that moves the layout, which is why no
208
+ * test here reads or writes the developer's real cache root. There is
209
+ * deliberately NO module-level test redirect (the pattern `scratch-spawn.ts`
210
+ * uses): a global setup file that imported this module would load it BEFORE a
211
+ * suite registers `vi.mock("../runner")`, leaving this module bound to the real
212
+ * runner and silently defeating every suite whose preflight is supposed to see a
213
+ * mocked binary. The injected seam has no such ordering hazard.
214
+ *
215
+ * A refusal names the RESOLVED root, not the probe directory alone, so the line
216
+ * a human reads is the path the spawn would use. There is no "set TMPDIR"
217
+ * advice here: that advice belonged to the temp-dir probe this replaces, and the
218
+ * root is not configurable by an environment variable.
123
219
  */
124
- function checkTempWritable(): PreflightResult {
125
- const tmpDir = os.tmpdir();
126
- const testFile = path.join(tmpDir, `.brl-subagent-pcheck-${process.pid}`);
220
+ function checkScratchRootWritable(options: PreflightOptions): PreflightResult {
221
+ const resolved = resolveRoot(options.root);
222
+ if (!resolved.ok) {
223
+ // A resolver refusal (no home, a root that is a symlink, a foreign owner, a
224
+ // writable ancestor, a mode that is not 0700) IS a preflight failure, and
225
+ // the resolver's code travels with it: one taxonomy, no re-wording.
226
+ return {
227
+ ok: false,
228
+ error: `Scratch root could not be resolved (${resolved.code}): ${resolved.message}`,
229
+ };
230
+ }
231
+
232
+ const probeDir = nearestExistingAncestor(resolved.root);
233
+ const probeFile = path.join(probeDir, nextProbeName());
127
234
 
128
235
  try {
129
- fs.writeFileSync(testFile, "ok", { encoding: "utf-8", mode: 0o600 });
130
- fs.unlinkSync(testFile);
236
+ fs.writeFileSync(probeFile, "ok", { encoding: "utf-8", mode: FILE_MODE });
237
+ fs.unlinkSync(probeFile);
131
238
  return { ok: true };
132
239
  } catch (err) {
133
240
  const message = err instanceof Error ? err.message : String(err);
134
241
  return {
135
242
  ok: false,
136
- error: `System temp directory (${tmpDir}) is not writable: ${message}. ` +
137
- "Set TMPDIR or TEMP to a writable directory.",
243
+ error: `Scratch root (${resolved.root}) is not writable: ${message}. ` +
244
+ `brl-subagent banks each run's progress under this root, so ${probeDir} must be writable by you.`,
138
245
  };
139
246
  }
140
247
  }
@@ -152,15 +259,15 @@ function checkTempWritable(): PreflightResult {
152
259
  * Call this BEFORE acquiring a concurrency slot to avoid wasting
153
260
  * resources on a doomed spawn.
154
261
  */
155
- export function preflightCheck(cwd: string): PreflightResult {
262
+ export function preflightCheck(cwd: string, options: PreflightOptions = {}): PreflightResult {
156
263
  const piResult = checkPiBinary();
157
264
  if (!piResult.ok) return piResult;
158
265
 
159
266
  const cwdResult = checkCwdReadable(cwd);
160
267
  if (!cwdResult.ok) return cwdResult;
161
268
 
162
- const tempResult = checkTempWritable();
163
- if (!tempResult.ok) return tempResult;
269
+ const scratchResult = checkScratchRootWritable(options);
270
+ if (!scratchResult.ok) return scratchResult;
164
271
 
165
272
  return { ok: true };
166
273
  }
package/src/prelude.ts CHANGED
@@ -45,10 +45,20 @@
45
45
  * extra log fields.
46
46
  */
47
47
 
48
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
49
- import type { ApprovalMode, GitMode, SubagentPreset, SubagentToolOptions, ThinkingLevel, ToolResult } from "./types";
50
- import type { SessionState } from "./state";
51
48
  import type { Logger } from "./logging";
49
+ import type { SessionState } from "./state";
50
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
51
+ import {
52
+ approvalBlocksBackground,
53
+ isThinkingLevel,
54
+ THINKING_LEVELS,
55
+ type ApprovalMode,
56
+ type GitMode,
57
+ type SubagentPreset,
58
+ type SubagentToolOptions,
59
+ type ThinkingLevel,
60
+ type ToolResult,
61
+ } from "./types";
52
62
  import { validateCwd, validateOutputFile } from "./sanitize";
53
63
  import { validatePreTask, type ValidateConfig } from "./validate";
54
64
  import { modelIsAvailable, parseModelString } from "./model-availability";
@@ -89,6 +99,62 @@ export function modelNotConfiguredRejection(): ToolResult<undefined> {
89
99
  );
90
100
  }
91
101
 
102
+ // ── Gate 0: a DECLARED thinking level (issue #443) ──────────────────────
103
+
104
+ /**
105
+ * Render a declared value for the rejection text. A string is quoted as JSON so
106
+ * an empty/whitespace value is VISIBLE (`""` vs `" high"`); anything else
107
+ * arrives only from a programmatic caller (the schema declares a string), so it
108
+ * is rendered as JSON and falls back to `String` for the values JSON rejects
109
+ * (a `BigInt` throws, a symbol stringifies to `undefined`).
110
+ */
111
+ function renderDeclaredThinkingLevel(value: unknown): string {
112
+ try {
113
+ return JSON.stringify(value) ?? String(value);
114
+ } catch {
115
+ return String(value);
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Reject an unsupported DECLARED thinking level before it reaches resolution
121
+ * (issue #443). Returns `undefined` when the value is usable.
122
+ *
123
+ * This is the runtime guard; the schema's `enum` is only the first line of
124
+ * defence, because pi validates raw TOOL ARGUMENTS. Every other route to a
125
+ * launch — a preset object injected in memory (the file tier has its own
126
+ * validator, `getPreset` does not re-check), a value restored by `retryRunId`,
127
+ * the transport auto-retry's rebuilt params, a per-unit declaration — reaches
128
+ * `resolveSubagentParams` without passing through the schema at all.
129
+ *
130
+ * The guard must run before resolution: `resolveThinkingLevel` erases an
131
+ * unknown value to `undefined`, which then survives every later check
132
+ * (`resolveSubagentParams` returns a level, it cannot report a failure) and
133
+ * reaches the child as `--thinking undefined`, where pi warns and runs at its
134
+ * own default — the configured cap silently bypassed.
135
+ *
136
+ * Deliberately NOT rejected: `undefined`/`null` (omitted) and `""`. Both are
137
+ * existing, meaningful declarations — top level `""` means "use the configured
138
+ * maximum", per unit `""` means "inherit the global level" — so the empty
139
+ * string keeps its meaning rather than becoming an error.
140
+ *
141
+ * `prefix` names the unit a per-unit declaration came from, matching the other
142
+ * unit-prefixed rejections (`Task 2 ("two"): …`).
143
+ */
144
+ export function invalidThinkingLevelRejection(
145
+ declared: unknown,
146
+ prefix?: string,
147
+ ): ToolResult<undefined> | undefined {
148
+ // Omitted, or the preserved empty-string declaration: not a level to judge.
149
+ if (declared === undefined || declared === null || declared === "") return undefined;
150
+ if (isThinkingLevel(declared)) return undefined;
151
+ return rejection(
152
+ `${prefix ? `${prefix}: ` : ""}Invalid thinkingLevel ${renderDeclaredThinkingLevel(declared)}. ` +
153
+ `Valid levels: ${THINKING_LEVELS.join(", ")} — matched exactly, so "High" and " high" are rejected too. ` +
154
+ `Omit thinkingLevel, or pass "", to use the configured maximum.`,
155
+ );
156
+ }
157
+
92
158
  // ── Gate 1: session cost ────────────────────────────────────────────────
93
159
 
94
160
  /**
@@ -142,7 +208,7 @@ export function gateSessionCost(input: {
142
208
  export function rejectApprovalAlwaysInBackground(
143
209
  approvalMode: ApprovalMode,
144
210
  ): ToolResult<undefined> | undefined {
145
- if (approvalMode !== "always") return undefined;
211
+ if (!approvalBlocksBackground(approvalMode)) return undefined;
146
212
  return rejection(
147
213
  `Cannot spawn background agent with approvalMode 'always': background agents run unattended ` +
148
214
  `and cannot present the approval dialog. Use approvalMode 'auto' (default) or 'writes'.`,
@@ -251,7 +317,7 @@ export function runPreTaskValidation(input: {
251
317
 
252
318
  /**
253
319
  * A merged per-unit source, structurally (mergeSubTaskParams lives in
254
- * index.ts and is passed in by the handler). These are the fields the
320
+ * unit-params.ts and is passed in by the handler). These are the fields the
255
321
  * pre-pass reads; the handler's own type is preserved through the generic
256
322
  * `M` so it can build its mode-specific unit records from the result.
257
323
  */
@@ -310,6 +376,15 @@ export interface UnitPrePassInput<U, M extends UnitPrePassSource> {
310
376
  * silence the check for a batch while appearing to pass it for the call.
311
377
  */
312
378
  noJev?: string;
379
+ /**
380
+ * The unit's DECLARED thinkingLevel, read from the unit itself (issue #443).
381
+ * Required, so a new caller cannot silently skip the check: the merged value
382
+ * cannot be judged — `merge` has already resolved it, and an unknown
383
+ * declaration comes back as `undefined` (the erasure this guard exists for).
384
+ * `""` and an omitted declaration are NOT rejected here: they mean "inherit
385
+ * the global level", which `merge` applies.
386
+ */
387
+ declaredThinkingLevel: (unit: U) => unknown;
313
388
  }
314
389
 
315
390
  export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
@@ -318,7 +393,8 @@ export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
318
393
 
319
394
  /**
320
395
  * The per-unit pre-pass shared by chain, parallel and graph: for EVERY unit,
321
- * merge → validate cwd/outputFile → H1 → collect `${prefix}: ${warning}`.
396
+ * declared-level guard → merge → validate cwd/outputFile → H1 → collect
397
+ * `${prefix}: ${warning}`.
322
398
  *
323
399
  * This is a helper each handler CALLS at its own position; it is deliberately
324
400
  * not a hook the mode prologue invokes — the three modes run it at different
@@ -331,7 +407,7 @@ export type UnitPrePassOutcome<U, M extends UnitPrePassSource> =
331
407
  export function validateUnitPrePass<U, M extends UnitPrePassSource>(
332
408
  input: UnitPrePassInput<U, M>,
333
409
  ): UnitPrePassOutcome<U, M> {
334
- const { units, merge, describe, label, gitMode, ctx, log, force, noJev } = input;
410
+ const { units, merge, describe, label, gitMode, ctx, log, force, noJev, declaredThinkingLevel } = input;
335
411
  const validated: Array<ValidatedUnit<U, M>> = [];
336
412
  const warnings: string[] = [];
337
413
 
@@ -340,6 +416,15 @@ export function validateUnitPrePass<U, M extends UnitPrePassSource>(
340
416
  const merged = merge(unit, i);
341
417
  const display = describe(unit, merged, i);
342
418
 
419
+ // Issue #443: the DECLARED per-unit level, before `merged.thinkingLevel`
420
+ // (already resolved, so an unknown value is indistinguishable from
421
+ // omitted) could hide it.
422
+ const thinkingError = invalidThinkingLevelRejection(
423
+ declaredThinkingLevel(unit),
424
+ display.prefix,
425
+ );
426
+ if (thinkingError) return { ok: false, error: thinkingError };
427
+
343
428
  const targets = validateDelegationTargets({
344
429
  ctx,
345
430
  effectiveCwd: merged.effectiveCwd,
package/src/presets.ts CHANGED
@@ -7,12 +7,11 @@
7
7
  * Custom presets are stored in session state.
8
8
  */
9
9
 
10
+ import type { Logger } from "./logging";
10
11
  import * as fs from "node:fs";
11
12
  import * as path from "node:path";
12
- import type { SubagentPreset, ThinkingLevel } from "./types";
13
- import { THINKING_LEVELS } from "./types";
14
- import type { Logger } from "./logging";
15
- import { loadMarkdownRecords } from "./loader";
13
+ import { THINKING_LEVELS, type SubagentPreset, type ThinkingLevel } from "./types";
14
+ import { applyFrontmatterMappers, loadMarkdownRecords, type FrontmatterFieldMapper, type FrontmatterMapContext } from "./loader";
16
15
 
17
16
  // `parseFrontmatter` moved to loader.ts when the four loader copies collapsed
18
17
  // into one walk (issue #380). Re-exported so the existing import sites keep
@@ -24,8 +23,8 @@ export { parseFrontmatter } from "./loader";
24
23
  // ---------------------------------------------------------------------------
25
24
 
26
25
  /**
27
- * Validate that a parsed preset has the required name field
28
- * and its thinkingLevel (if set) is a valid value.
26
+ * Validate that a parsed preset has the required name field, its thinkingLevel
27
+ * (if set) is a valid value, and its outputFile (if set) is a string.
29
28
  * Returns validation errors, or empty array if valid.
30
29
  */
31
30
  export function validatePreset(meta: Record<string, unknown>, fileName: string): string[] {
@@ -64,9 +63,87 @@ export function validatePreset(meta: Record<string, unknown>, fileName: string):
64
63
  }
65
64
  }
66
65
 
66
+ // outputFile is MAPPED (#436), so a non-string here would reach the resolved
67
+ // params as a broken path — refuse it at load, like thinkingLevel above.
68
+ if (meta.outputFile !== undefined && typeof meta.outputFile !== "string") {
69
+ errors.push(
70
+ `Preset "${meta.name}" (${fileName}): outputFile must be a string, got "${String(meta.outputFile)}".`,
71
+ );
72
+ }
73
+
67
74
  return errors;
68
75
  }
69
76
 
77
+ // ---------------------------------------------------------------------------
78
+ // Frontmatter → SubagentPreset mapping
79
+ // ---------------------------------------------------------------------------
80
+
81
+ /**
82
+ * Preset fields that are DELIBERATELY not mapped from frontmatter. This is the
83
+ * only sanctioned escape hatch from the parity pin below — every entry must
84
+ * name its reason.
85
+ *
86
+ * `timeout` (ADR 0022 §6): `resolveSubagentParams` merges
87
+ * `params.timeout ?? preset?.timeout`, so a preset-supplied deadline would
88
+ * silently re-merge the value the dispatch pre-flight's `drop-timeout` arm
89
+ * believes it dropped, and `THINKING_TIMEOUT_DROP_NOTICE`'s "no clock kills it"
90
+ * sentence would become false — with no other test failing. Mapping it requires
91
+ * re-deriving that arm first (issue #431).
92
+ */
93
+ type OmittedPresetField = "timeout";
94
+
95
+ /**
96
+ * Compile-time pin on the allowlist being EXACTLY `"timeout"` (#436 review
97
+ * nit): the `satisfies` below only notices a field that is missing from the
98
+ * table, so adding a new field to BOTH `SubagentPreset` and this union used to
99
+ * compile cleanly — the reviewed bypass. A tuple-wrapped union extends a
100
+ * one-element tuple only when it is that member, so a second entry turns this
101
+ * into `never` and the assignment under it fails with TS2322.
102
+ */
103
+ type OmittedMustStayTimeout = [OmittedPresetField] extends ["timeout"] ? true : never;
104
+
105
+ /** Kept live by the export; its only job is to fail `tsc` when the pin flips. */
106
+ export const PRESET_OMIT_PIN: OmittedMustStayTimeout = true;
107
+
108
+ /** Every preset field that frontmatter MUST be able to populate (issue #436). */
109
+ type MappedPresetField = Exclude<keyof SubagentPreset, OmittedPresetField>;
110
+
111
+ /**
112
+ * Per-key return types: the mapper for `outputFile` must return
113
+ * `SubagentPreset["outputFile"]` (a string | undefined), so a mapper that
114
+ * returns `42` — previously blessed by the `unknown` value type plus the
115
+ * assembly cast — is now a compile error at the row.
116
+ */
117
+ type PresetFieldMappers = {
118
+ [K in MappedPresetField]: FrontmatterFieldMapper<SubagentPreset[K]>;
119
+ };
120
+
121
+ /**
122
+ * THE declaration of which frontmatter keys reach a `SubagentPreset` — one
123
+ * table, so a field cannot be declared in the type and forgotten here.
124
+ *
125
+ * `satisfies PresetFieldMappers` is the parity pin: adding a field to
126
+ * `SubagentPreset` without a mapper is a COMPILE error (the record is missing a
127
+ * key), a mapper for a field the type no longer declares is an excess-property
128
+ * error, and a mapper returning the wrong field type is a third. Before #436
129
+ * the object was a hand-written literal, so a declared field (`outputFile`)
130
+ * could be dropped in total silence.
131
+ */
132
+ const PRESET_FIELD_MAPPERS = {
133
+ name: (_meta, ctx) => ctx.name,
134
+ description: (meta) => (meta.description as string) || undefined,
135
+ systemPrompt: (_meta, ctx) => ctx.body || undefined,
136
+ thinkingLevel: (meta) => (meta.thinkingLevel as string) || undefined,
137
+ model: (meta) => (meta.model as string) || undefined,
138
+ inheritSystemPrompt: (meta) => (meta.inheritSystemPrompt === "false" ? false : undefined),
139
+ outputFile: (meta) => (meta.outputFile as string) || undefined,
140
+ tools: (meta) => (Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined),
141
+ excludeTools: (meta) =>
142
+ Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
143
+ noBuiltinTools: (meta) => (meta.noBuiltinTools === "true" ? true : undefined),
144
+ promptGuideline: (meta) => (meta.promptGuideline as string) || undefined,
145
+ } satisfies PresetFieldMappers;
146
+
70
147
  // ---------------------------------------------------------------------------
71
148
  // Loading
72
149
  // ---------------------------------------------------------------------------
@@ -80,18 +157,8 @@ function presetFromFrontmatter(
80
157
  body: string,
81
158
  name: string,
82
159
  ): 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
- };
160
+ const ctx: FrontmatterMapContext = { name, body };
161
+ return applyFrontmatterMappers<SubagentPreset>(PRESET_FIELD_MAPPERS, meta, ctx);
95
162
  }
96
163
 
97
164
  /**
package/src/proc.ts CHANGED
@@ -18,12 +18,11 @@
18
18
  * that platform guard without mocking `node:fs` module-wide.
19
19
  */
20
20
 
21
+ import type { RecoveryDeps } from "./recovery-engine";
21
22
  import * as fs from "node:fs";
22
23
  import * as path from "node:path";
23
- import type { ProcessOwner } from "./types";
24
- import { SIGKILL_GRACE_MS, SIGKILL_POLL_MS } from "./types";
24
+ import { SIGKILL_GRACE_MS, SIGKILL_POLL_MS, type ProcessOwner } from "./types";
25
25
  import { CHILD_MARKER_ENV_KEY } from "./sanitize";
26
- import type { RecoveryDeps } from "./recovery-engine";
27
26
  import { supportsProcessGroupKill } from "./kill-escalation";
28
27
 
29
28
  const PROC_ROOT = "/proc";
@@ -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
@@ -23,10 +23,10 @@
23
23
  * every pid, wait one grace window, SIGKILL any survivor.
24
24
  */
25
25
 
26
+ import type { Logger } from "./logging";
26
27
  import type { ProcessOwner, SubagentRun } from "./types";
27
28
  import { resolveTerminalRunEntry } from "./state";
28
29
  import { escalateKill, processTarget, type SignalGuard, type SignalPhase } from "./kill-escalation";
29
- import type { Logger } from "./logging";
30
30
 
31
31
  // ---------------------------------------------------------------------------
32
32
  // Dependency injection surface
@@ -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]));
@@ -28,8 +28,7 @@
28
28
  */
29
29
 
30
30
  import { listInflightRuns, type InflightRun, type InflightRunKind } from "./run-registry";
31
- import type { SubagentRun } from "./types";
32
- import { isInterruptedRun, runRecoveryPosture, type RecoveryMode } from "./types";
31
+ import { isInterruptedRun, runRecoveryPosture, type RecoveryMode, type SubagentRun } from "./types";
33
32
  import { resolveTerminalRunEntry } from "./state";
34
33
  import { sortNewestFirst } from "./history";
35
34
  import { claimTerminalNotice, type DeliveryResolution } from "./notify-completion";