brl-subagent 2.6.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/presets.ts CHANGED
@@ -12,69 +12,21 @@ 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 { applyFrontmatterMappers, loadMarkdownRecords } from "./loader";
16
+ import type { FrontmatterFieldMapper, FrontmatterMapContext } from "./loader";
15
17
 
16
- // ---------------------------------------------------------------------------
17
- // Frontmatter parsing
18
- // ---------------------------------------------------------------------------
19
-
20
- /**
21
- * Parse YAML frontmatter from a markdown file.
22
- * Returns metadata key-value pairs and the body content.
23
- */
24
- export function parseFrontmatter(content: string): { meta: Record<string, unknown>; body: string } {
25
- const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
26
- if (!match) return { meta: {}, body: content };
27
-
28
- const meta: Record<string, unknown> = {};
29
- const lines = match[1].split("\n");
30
- let currentKey = "";
31
- let currentArray: string[] | null = null;
32
-
33
- for (const line of lines) {
34
- // Array item: starts with "- "
35
- if (line.match(/^\s+-\s+/)) {
36
- if (currentArray !== null) {
37
- currentArray.push(line.replace(/^\s+-\s+/, "").trim());
38
- }
39
- continue;
40
- }
41
-
42
- // End of array if we were in one
43
- if (currentArray !== null) {
44
- meta[currentKey] = currentArray;
45
- currentArray = null;
46
- }
47
-
48
- // Key-value pair
49
- const kvMatch = line.match(/^(\w+):\s*(.*)$/);
50
- if (kvMatch) {
51
- const key = kvMatch[1];
52
- const value = kvMatch[2].trim();
53
- // Check if next line starts an array
54
- if (value === "") {
55
- currentKey = key;
56
- currentArray = [];
57
- } else {
58
- // Strip quotes if present
59
- meta[key] = value.replace(/^["']|["']$/g, "");
60
- }
61
- }
62
- }
63
- // Close any pending array
64
- if (currentArray !== null) {
65
- meta[currentKey] = currentArray;
66
- }
67
-
68
- return { meta, body: match[2].trim() };
69
- }
18
+ // `parseFrontmatter` moved to loader.ts when the four loader copies collapsed
19
+ // into one walk (issue #380). Re-exported so the existing import sites keep
20
+ // working unchanged.
21
+ export { parseFrontmatter } from "./loader";
70
22
 
71
23
  // ---------------------------------------------------------------------------
72
24
  // Preset validation
73
25
  // ---------------------------------------------------------------------------
74
26
 
75
27
  /**
76
- * Validate that a parsed preset has the required name field
77
- * 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.
78
30
  * Returns validation errors, or empty array if valid.
79
31
  */
80
32
  export function validatePreset(meta: Record<string, unknown>, fileName: string): string[] {
@@ -113,61 +65,122 @@ export function validatePreset(meta: Record<string, unknown>, fileName: string):
113
65
  }
114
66
  }
115
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
+
116
76
  return errors;
117
77
  }
118
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
+
119
149
  // ---------------------------------------------------------------------------
120
150
  // Loading
121
151
  // ---------------------------------------------------------------------------
122
152
 
153
+ /**
154
+ * Normalise validated preset frontmatter into a SubagentPreset. Shared by both
155
+ * preset tiers — the file walk and validation live in loadMarkdownRecords.
156
+ */
157
+ function presetFromFrontmatter(
158
+ meta: Record<string, unknown>,
159
+ body: string,
160
+ name: string,
161
+ ): SubagentPreset {
162
+ const ctx: FrontmatterMapContext = { name, body };
163
+ return applyFrontmatterMappers<SubagentPreset>(PRESET_FIELD_MAPPERS, meta, ctx);
164
+ }
165
+
123
166
  /**
124
167
  * Load built-in presets from a directory of markdown files.
125
168
  * Files must have YAML frontmatter with at least a `name` field.
126
169
  * Invalid files are skipped with log warnings.
127
170
  */
128
171
  export function loadBuiltinPresets(presetsDir: string, log?: Logger): SubagentPreset[] {
129
- const presets: SubagentPreset[] = [];
130
-
131
- try {
132
- const files = fs.readdirSync(presetsDir);
133
- for (const file of files) {
134
- if (!file.endsWith(".md")) continue;
135
-
136
- try {
137
- const filePath = path.join(presetsDir, file);
138
- const content = fs.readFileSync(filePath, "utf-8");
139
- const { meta, body } = parseFrontmatter(content);
140
-
141
- const errors = validatePreset(meta, file);
142
- if (errors.length > 0) {
143
- for (const err of errors) {
144
- log?.warn("Preset validation failed", { file, error: err });
145
- }
146
- continue;
147
- }
148
-
149
- const name = meta.name as string;
150
-
151
- presets.push({
152
- name,
153
- description: (meta.description as string) || undefined,
154
- systemPrompt: body || undefined,
155
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
156
- model: (meta.model as string) || undefined,
157
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
158
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
159
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
160
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
161
- promptGuideline: (meta.promptGuideline as string) || undefined,
162
- });
163
- } catch (err) {
164
- log?.warn("Failed to load preset file", { file, error: (err as Error).message });
165
- }
166
- }
167
- } catch {
168
- // Presets directory doesn't exist or can't be read — no built-in presets
169
- log?.info("No built-in presets directory found", { dir: presetsDir });
170
- }
172
+ const presets = loadMarkdownRecords<SubagentPreset>({
173
+ dirs: [presetsDir],
174
+ validate: validatePreset,
175
+ map: presetFromFrontmatter,
176
+ log,
177
+ messages: {
178
+ invalid: "Preset validation failed",
179
+ readFailed: "Failed to load preset file",
180
+ },
181
+ // Built-in presets directory doesn't exist or can't be read — no built-in presets
182
+ onMissingDir: (dir) => log?.info("No built-in presets directory found", { dir }),
183
+ });
171
184
 
172
185
  // Validate all loaded presets
173
186
  const validationErrors = validateAllPresets(presets);
@@ -195,60 +208,24 @@ export function loadBuiltinPresets(presetsDir: string, log?: Logger): SubagentPr
195
208
  * 2. ~/.pi/agent/brl-subagent/presets/ (global)
196
209
  */
197
210
  export function loadCustomPresets(cwd: string, log?: Logger): SubagentPreset[] {
198
- const presets: SubagentPreset[] = [];
199
- const seenNames = new Set<string>();
200
211
  const homedir = process.env.HOME || process.env.USERPROFILE || "";
201
212
 
202
- const dirs = [
203
- path.join(cwd, ".pi", "brl-subagent", "presets"),
204
- path.join(homedir, ".pi", "agent", "brl-subagent", "presets"),
205
- ];
206
-
207
- for (const dir of dirs) {
208
- try {
209
- const files = fs.readdirSync(dir);
210
- for (const file of files) {
211
- if (!file.endsWith(".md")) continue;
212
- try {
213
- const filePath = path.join(dir, file);
214
- const content = fs.readFileSync(filePath, "utf-8");
215
- const { meta, body } = parseFrontmatter(content);
216
-
217
- const errors = validatePreset(meta, file);
218
- if (errors.length > 0) {
219
- for (const err of errors) {
220
- log?.warn("Custom preset validation failed", { file, error: err });
221
- }
222
- continue;
223
- }
224
-
225
- const name = meta.name as string;
226
- // Dedup by name: the first occurrence (project-local, scanned
227
- // first) wins; user-global duplicates are skipped.
228
- if (seenNames.has(name)) continue;
229
- seenNames.add(name);
230
- presets.push({
231
- name,
232
- description: (meta.description as string) || undefined,
233
- systemPrompt: body || undefined,
234
- thinkingLevel: (meta.thinkingLevel as string) || undefined,
235
- model: (meta.model as string) || undefined,
236
- inheritSystemPrompt: meta.inheritSystemPrompt === "false" ? false : undefined,
237
- tools: Array.isArray(meta.tools) ? (meta.tools as string[]) : undefined,
238
- excludeTools: Array.isArray(meta.excludeTools) ? (meta.excludeTools as string[]) : undefined,
239
- noBuiltinTools: meta.noBuiltinTools === "true" ? true : undefined,
240
- promptGuideline: (meta.promptGuideline as string) || undefined,
241
- });
242
- } catch (err) {
243
- log?.warn("Failed to load custom preset file", { file, error: (err as Error).message });
244
- }
245
- }
246
- } catch {
247
- // Directory doesn't exist — that's fine, no custom presets
248
- }
249
- }
250
-
251
- return presets;
213
+ return loadMarkdownRecords<SubagentPreset>({
214
+ dirs: [
215
+ path.join(cwd, ".pi", "brl-subagent", "presets"),
216
+ path.join(homedir, ".pi", "agent", "brl-subagent", "presets"),
217
+ ],
218
+ validate: validatePreset,
219
+ map: presetFromFrontmatter,
220
+ // Dedup by name: the first occurrence (project-local, scanned first) wins.
221
+ dedupeByName: true,
222
+ log,
223
+ messages: {
224
+ invalid: "Custom preset validation failed",
225
+ readFailed: "Failed to load custom preset file",
226
+ },
227
+ // A missing directory is fine — no custom presets in that tier.
228
+ });
252
229
  }
253
230
 
254
231
  // ---------------------------------------------------------------------------
@@ -0,0 +1,58 @@
1
+ // Purpose: The single reader for the project-local `brl-subagent` umbrella flags (issue #415).
2
+ /**
3
+ * The umbrella project-local flag: `{"brl-subagent": {"processChecks": true}}`.
4
+ *
5
+ * `processChecks` gates OUR process mechanisms — the Jev dispatch-line check
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
+ *
10
+ * Why one reader (issue #415): the shape rule shipped GLOBAL, so a user's
11
+ * explicit `background: false` + timeout was overridden by our conductor
12
+ * decision rule. A conductor rule is not product behavior. Scoping both
13
+ * mechanisms behind one project-local opt-in keeps a user's dispatch exactly as
14
+ * they asked for it, and this module is the only place the manifest field is
15
+ * read (the ratchet in `project-flags.test.ts` fails a second reader).
16
+ *
17
+ * FAIL-OPEN is the product contract: a missing, unreadable or malformed
18
+ * `package.json` means `false`. A project's packaging mistake must never reject
19
+ * a user's dispatch or reshape it.
20
+ *
21
+ * The manifest read is the project's OWN `package.json` — tracked, so it exists
22
+ * in every worktree (worktrees share the repo's manifest), unlike a gitignored
23
+ * marker under `.pi/`.
24
+ */
25
+
26
+ import { readFileSync } from "node:fs";
27
+ import { join } from "node:path";
28
+
29
+ /**
30
+ * The fields this module is allowed to read from the `brl-subagent` section.
31
+ * A third field is a new mechanism, and a new mechanism needs its own ADR and
32
+ * its own line in this whitelist (the ratchet enforces both directions).
33
+ */
34
+ export const PROCESS_CHECK_KEYS = ["processChecks"] as const;
35
+
36
+ /**
37
+ * Whether the project at `cwd` opted into our process checks. Fail-open in
38
+ * every failure mode: no cwd, no manifest, unreadable manifest, malformed JSON,
39
+ * a non-object section, or a non-boolean field all read as `false`.
40
+ */
41
+ export function readProcessChecks(cwd: string | undefined): boolean {
42
+ if (cwd === undefined || cwd === "") return false;
43
+ try {
44
+ const manifest = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8")) as {
45
+ "brl-subagent"?: { processChecks?: unknown };
46
+ };
47
+ return manifest?.["brl-subagent"]?.processChecks === true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * The validation seam's name for the same read (`validatePreTask` asks "is the
55
+ * check enabled for this project?"). One implementation: this is an alias, not
56
+ * a second reader.
57
+ */
58
+ export const isProcessChecksEnabled = readProcessChecks;
@@ -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]));
package/src/recovery.ts CHANGED
@@ -34,8 +34,10 @@
34
34
  import { listInflightRuns, type InflightRun } from "./run-registry";
35
35
  import { assertSafeAgentId } from "./sanitize";
36
36
  import { isProcAvailable, defaultRecoveryDeps } from "./proc";
37
- import { decideRecovery, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
37
+ import { decideRecovery, classifyOwner, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
38
38
  import type { Logger } from "./logging";
39
+ import type { SubagentRun } from "./types";
40
+ import { PROMPT_NEVER_ISSUED_MESSAGE } from "./types";
39
41
 
40
42
  // Re-export the pure engine and the production wiring so existing importers
41
43
  // (`index.ts`, the recovery/registry suites) keep their single entry point.
@@ -61,6 +63,14 @@ export interface BootScanSummary {
61
63
  skippedNoOwner: number;
62
64
  /** Registry entries skipped fail-closed because their id failed the write guard. */
63
65
  skippedUnsafeIds: number;
66
+ /**
67
+ * Issue #447: registry entries classified NEVER STARTED (`acceptedAt:
68
+ * null`) and settled `failed` instead of being offered as an interrupted,
69
+ * retryable run. Counted per FINALIZE attempt: an entry held back because its
70
+ * owner is still live (or unverifiable) is not counted, and a failed terminal
71
+ * write is warned — either way the entry stays out of the interrupted class.
72
+ */
73
+ neverStarted: number;
64
74
  }
65
75
 
66
76
  /** The all-zero summary (a skipped scan / an empty registry). */
@@ -75,6 +85,7 @@ export function emptyBootScanSummary(): BootScanSummary {
75
85
  skippedUnverifiable: 0,
76
86
  skippedNoOwner: 0,
77
87
  skippedUnsafeIds: 0,
88
+ neverStarted: 0,
78
89
  };
79
90
  }
80
91
 
@@ -211,10 +222,66 @@ export async function runBootScan(options: BootScanOptions): Promise<BootScanSum
211
222
  export interface PersistedAgentLike {
212
223
  status: string;
213
224
  interruptedAt?: string;
225
+ /**
226
+ * Issue #447: the acceptance marker, when the record carries one. Only the
227
+ * registry entry and the run entry write it today; this read keeps a record
228
+ * that DOES carry it authoritative (the entry is the fallback, not the
229
+ * override) — see `acceptanceState`.
230
+ */
231
+ acceptedAt?: string | null;
214
232
  owner?: RecoveryRecord["owner"];
215
233
  childMarker?: string;
216
234
  }
217
235
 
236
+ /**
237
+ * Issue #447: the tri-state read of the acceptance marker. `undefined` is the
238
+ * LEGACY/untracked state, and it must stay distinguishable from `null` (never
239
+ * started) — which is why this is an explicit `!== undefined` probe and never
240
+ * `??` (`null ?? agent` would silently reclassify every never-started entry as
241
+ * accepted and bring the false positive straight back).
242
+ */
243
+ function acceptanceState(
244
+ entry: InflightRun,
245
+ agent: PersistedAgentLike | null,
246
+ ): string | null | undefined {
247
+ if (entry.acceptedAt !== undefined) return entry.acceptedAt;
248
+ return agent?.acceptedAt;
249
+ }
250
+
251
+ /**
252
+ * The terminal `failed` record written for a dispatch that never reached the
253
+ * prompt: the durable summary the entry already holds, stamped with the honest
254
+ * reason. Projected here (next to the classification that decides it) so the
255
+ * caller only has to persist what it is handed. Deliberately does NOT carry
256
+ * `interruptedAt` — a never-started run is not an interrupted run, and the
257
+ * recovery surface keys on that mark alone.
258
+ */
259
+ export function neverStartedRunRecord(
260
+ entry: InflightRun,
261
+ finishedAt: string,
262
+ reason: string = PROMPT_NEVER_ISSUED_MESSAGE,
263
+ ): SubagentRun {
264
+ return {
265
+ id: entry.id,
266
+ task: entry.task ?? "",
267
+ ...(entry.label !== undefined ? { label: entry.label } : {}),
268
+ ...(entry.dispatchId !== undefined ? { dispatchId: entry.dispatchId } : {}),
269
+ ...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),
270
+ status: "failed",
271
+ model: entry.model ?? "unknown",
272
+ thinkingLevel: entry.thinkingLevel ?? "unknown",
273
+ startedAt: entry.startedAt,
274
+ finishedAt,
275
+ errorCategory: "unknown",
276
+ errorMessage: reason,
277
+ ...(entry.recoveryPosture !== undefined ? { recoveryPosture: entry.recoveryPosture } : {}),
278
+ ...(entry.originalParams !== undefined ? { originalParams: entry.originalParams } : {}),
279
+ // The marker stays `null` on the terminal record: this run never accepted
280
+ // the prompt, and the record must not claim otherwise after the fact.
281
+ acceptedAt: null,
282
+ };
283
+ }
284
+
218
285
  export interface RegistryScanOptions {
219
286
  deps: RecoveryDeps;
220
287
  /**
@@ -222,6 +289,13 @@ export interface RegistryScanOptions {
222
289
  * background). Returns `false` when the durable write did not land.
223
290
  */
224
291
  mark(record: RecoveryRecord, interruptedAt: string): boolean | void;
292
+ /**
293
+ * Issue #447: persist the terminal record of a dispatch that never reached
294
+ * the prompt (`acceptedAt: null`). Absent ⇒ the entry is left untouched —
295
+ * it is still never offered as interrupted, so the fail-closed direction is
296
+ * "no write", never "offer a retry".
297
+ */
298
+ finalizeNeverStarted?(run: SubagentRun, reason: string): boolean | void;
225
299
  /**
226
300
  * Read ONE background run's agent record by id (never the whole store).
227
301
  * Returns null when the record is absent; absent defaults to an in-flight
@@ -269,31 +343,89 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
269
343
  }
270
344
 
271
345
  const records: RecoveryRecord[] = [];
346
+ // Issue #447: `acceptedAt: null` = tracked but the prompt was never issued.
347
+ // Such an entry is NOT a recovery candidate: nothing was started, so there
348
+ // is nothing to reap, nothing to interrupt, and nothing to retry. It is
349
+ // finalized `failed` below instead of being handed to the decision engine.
350
+ const neverStarted: InflightRun[] = [];
272
351
  for (const entry of addressable) {
273
- if (entry.kind === "background") {
274
- const agent = options.readAgentRecord?.(entry.id) ?? null;
275
- if (agent && agent.status !== "running") continue;
276
- records.push({
352
+ const isBackground = entry.kind === "background";
353
+ // Only a background entry has an agent record to enrich from (and to drop
354
+ // a stale entry by); the read is that ONE file, never the whole store.
355
+ const agent = isBackground ? (options.readAgentRecord?.(entry.id) ?? null) : null;
356
+ if (agent && agent.status !== "running") continue;
357
+ // Issue #447: ONE tri-state read for both kinds, so the `null` rule cannot
358
+ // drift between the background and run branches.
359
+ if (acceptanceState(entry, agent) === null) {
360
+ neverStarted.push(entry);
361
+ continue;
362
+ }
363
+ records.push({
364
+ id: entry.id,
365
+ kind: isBackground ? "agent" : "run",
366
+ status: "running",
367
+ interruptedAt: agent?.interruptedAt ?? entry.interruptedAt,
368
+ owner: agent?.owner ?? entry.owner,
369
+ childMarker: agent?.childMarker ?? entry.childMarker,
370
+ source: entry,
371
+ });
372
+ }
373
+
374
+ const now = options.now?.() ?? new Date();
375
+ /** Entries this scan actually SETTLED (see `BootScanSummary.neverStarted`). */
376
+ let settledNeverStarted = 0;
377
+ for (const entry of neverStarted) {
378
+ if (!options.finalizeNeverStarted) {
379
+ options.log?.debug("Recovery: left a never-started dispatch untouched (no finalizer wired)", {
277
380
  id: entry.id,
278
- kind: "agent",
279
- status: "running",
280
- interruptedAt: agent?.interruptedAt ?? entry.interruptedAt,
281
- owner: agent?.owner ?? entry.owner,
282
- childMarker: agent?.childMarker ?? entry.childMarker,
283
- source: entry,
381
+ kind: entry.kind,
284
382
  });
285
- } else {
286
- records.push({
383
+ continue;
384
+ }
385
+ // A never-started entry is acted on ONLY when its owner is provably dead,
386
+ // the same ownership rule the decision engine applies before it marks
387
+ // anything. A LIVE owner may still be inside its own pre-start window (the
388
+ // git-branch lock, a slow transcript start) and will write its acceptance
389
+ // marker momentarily — finalizing it here would stamp a false `failed`
390
+ // terminal record the run's real terminal entry could not outrank (the
391
+ // store keeps the earlier entry, and readers prefer the LAST one). No owner or
392
+ // an unverifiable one ⇒ no write, exactly as for the mark path.
393
+ const owner = entry.owner;
394
+ const ownerDead =
395
+ !!owner &&
396
+ Number.isInteger(owner.pid) &&
397
+ owner.pid > 0 &&
398
+ classifyOwner(owner, options.deps) === "dead";
399
+ if (!ownerDead) {
400
+ options.log?.debug("Recovery: left a never-started dispatch with a live/unverified owner", {
287
401
  id: entry.id,
288
- kind: "run",
289
- status: "running",
290
- interruptedAt: entry.interruptedAt,
291
- owner: entry.owner,
292
- childMarker: entry.childMarker,
293
- source: entry,
402
+ kind: entry.kind,
403
+ });
404
+ continue;
405
+ }
406
+ settledNeverStarted++;
407
+ try {
408
+ options.finalizeNeverStarted(
409
+ neverStartedRunRecord(entry, now.toISOString()),
410
+ PROMPT_NEVER_ISSUED_MESSAGE,
411
+ );
412
+ options.log?.info("Recovery: finalized a never-started dispatch as failed", {
413
+ id: entry.id,
414
+ kind: entry.kind,
415
+ });
416
+ } catch (err) {
417
+ // Best-effort, exactly like the mark path: a failed finalize must not
418
+ // abort the scan for the OTHER candidates. The registry entry is cleared
419
+ // before the append lands (`persistRunRecord`), so the residue is gone
420
+ // even when the terminal entry cannot be written.
421
+ options.log?.warn("Recovery: never-started finalize failed", {
422
+ id: entry.id,
423
+ kind: entry.kind,
424
+ error: (err as Error).message,
294
425
  });
295
426
  }
296
427
  }
428
+
297
429
  const summary = await runBootScan({
298
430
  records,
299
431
  deps: options.deps,
@@ -302,6 +434,7 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
302
434
  log: options.log,
303
435
  });
304
436
  summary.skippedUnsafeIds = unsafeIds.length;
437
+ summary.neverStarted = settledNeverStarted;
305
438
  return summary;
306
439
  }
307
440
 
@@ -314,6 +447,8 @@ export interface ProductionRecoveryOptions {
314
447
  deps?: RecoveryDeps;
315
448
  /** Persist the D3 mark for this record; `false` = the durable write failed. */
316
449
  mark(record: RecoveryRecord, interruptedAt: string): boolean | void;
450
+ /** Issue #447: persist the terminal record of a never-started dispatch. */
451
+ finalizeNeverStarted?(run: SubagentRun, reason: string): boolean | void;
317
452
  readAgentRecord?(id: string): PersistedAgentLike | null;
318
453
  now?: () => Date;
319
454
  log?: Pick<Logger, "debug" | "info" | "warn">;
@@ -336,6 +471,7 @@ export async function recoverProduction(options: ProductionRecoveryOptions): Pro
336
471
  return recoverInflightRuns({
337
472
  deps: options.deps ?? defaultRecoveryDeps(),
338
473
  mark: options.mark,
474
+ finalizeNeverStarted: options.finalizeNeverStarted,
339
475
  readAgentRecord: options.readAgentRecord,
340
476
  now: options.now,
341
477
  log: options.log,