brl-subagent 2.9.0 → 2.9.2

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.
@@ -0,0 +1,383 @@
1
+ // Purpose: The durable "retry armed" marker for the background transport auto-retry (issue #616).
2
+ /**
3
+ * Issue #616 (Q3) — the ARMED-RETRY marker.
4
+ *
5
+ * The background transport auto-retry has an unaddressable window: the retry
6
+ * attempt's id is minted inside `spawnBackgroundSession` and its agent record +
7
+ * registry entry only land several statements later. Between the two, nothing
8
+ * durable says the retry exists, so a `stop_subagent` aimed at the dispatch
9
+ * finds a dead attempt 1 and truthfully-but-uselessly reports "stopped" while
10
+ * the retry is being started.
11
+ *
12
+ * This module closes that window with a marker that is an **intent, not a run**:
13
+ *
14
+ * - it is written by `scheduleTransportRetry` BEFORE the spawn
15
+ * (`armRetry`), naming the SOURCE run it replaces and the attempt it will
16
+ * become;
17
+ * - a stop of that dispatch sets `cancelRequested` (`cancelArmedRetry`);
18
+ * - the spawn honours it at its pre-prompt gate
19
+ * (`isRetryCancelRequested` → settle `stopped`, never prompt) and clears it
20
+ * once the retry is durable (`clearArmedRetry`).
21
+ *
22
+ * WHY NOT A FIELD ON THE EXISTING REGISTRY ENTRY: the retry's entry does not
23
+ * exist yet inside the window — that IS the window. The marker therefore hangs
24
+ * off the one id that does exist, the source run.
25
+ *
26
+ * WHY A SUBDIRECTORY (`.pi/run-registry/armed/`): every run-shaped reader —
27
+ * `listInflightRuns` (and therefore the boot scan), run history, the monitor —
28
+ * enumerates `*.json` files directly in the registry directory. A nested
29
+ * directory is invisible to all of them by construction, which is what keeps an
30
+ * INTENT from rendering as a RUN ROW. (`src/__tests__/stop-subagent-lineage.test.ts`
31
+ * pins that: arming produces no registry entry and no run record.)
32
+ *
33
+ * Writes are atomic (temp + rename) and owner-only (0o600), mirroring the
34
+ * registry's own discipline. Every reader is total: a missing, unreadable or
35
+ * malformed marker reads as "nothing armed" and never throws — the failure mode
36
+ * is the pre-#616 window, not a broken stop.
37
+ *
38
+ * THE AGE RULE (review 624 r2, B1): **age may reclaim an INTENT, never a
39
+ * CANCEL.** An UNCLAIMED marker past `ARMED_RETRY_STALE_MS` is crash residue and
40
+ * is reclaimed on read (and by the boot sweep); a marker whose
41
+ * `cancelRequested === true` is NEVER stale and is never unlinked by age, in any
42
+ * reader. The stretch between the arm and the pre-prompt gate is NOT bounded —
43
+ * the spawn waits in the process-wide spawn queue, and a `gitMode: 'branch'`
44
+ * retry waits on another run's repository lock, bound only by that run's
45
+ * lifetime — so a cancel can still have its gate coming arbitrarily far away.
46
+ * Reclaiming it on age would silently lose a live stop, which is the failure this
47
+ * issue exists to prevent.
48
+ *
49
+ * THE ACCEPTED RESIDUAL (stated, not papered over): a cancel whose spawn never
50
+ * materialises — the process died after the cancel write, before the gate — stays
51
+ * on disk forever, and every later stop of that dispatch keeps the "not claimed
52
+ * quiescent" disclosure. A permanent false NOT-QUIESCENT is acceptable; a false
53
+ * QUIESCENT is the bug this issue exists for.
54
+ */
55
+
56
+ import * as fs from 'node:fs';
57
+ import * as path from 'node:path';
58
+
59
+ import { writeFileAtomicSync } from './atomic-write';
60
+ import { registryDir } from './run-registry';
61
+ import { assertSafeAgentId } from './sanitize';
62
+ import { ensureOwnerOnlyDir } from './store-permissions';
63
+
64
+ /** The armed retry's cause. Only the automatic transport retry is ever armed. */
65
+ export type ArmedRetryCause = 'transport';
66
+
67
+ /**
68
+ * Issue #616 / review 624 (B1) — the RE-ARM BOUND.
69
+ *
70
+ * The ONE thing this bound decides is whether a SECOND arm for the same source
71
+ * may inherit a cancel from the previous one. Inside it, a re-arm PRESERVES the
72
+ * cancel (a second `scheduleTransportRetry` must not un-cancel a stop that
73
+ * already reached the dispatch). Beyond it the previous arm describes a spawn
74
+ * that never made it (the process died between arm and gate), so a cancel on it
75
+ * belongs to a spawn that is gone — preserving it would let a phantom kill the
76
+ * retry this arm is about to start.
77
+ *
78
+ * It is NOT a staleness bound: no reader reclaims a marker on this age, and age
79
+ * never reclaims a cancel at all (see `ARMED_RETRY_STALE_MS`).
80
+ */
81
+ export const ARMED_RETRY_SPAWN_BOUND_MS = 120_000;
82
+
83
+ /**
84
+ * Issue #616 / review 624 (B1) — the UNCLAIMED-MARKER STALE BOUND.
85
+ *
86
+ * Nothing clears a marker when the process dies between the arm write and the
87
+ * spawn, and no run-shaped reader enumerates `armed/` (that is what keeps an
88
+ * intent from rendering as a run row), so without an age rule a phantom marker
89
+ * makes every later stop of that dispatch print "Cancelled transport retry …"
90
+ * for a retry that will never exist, and suppress the universal claim forever.
91
+ *
92
+ * AGE RECLAIMS AN INTENT, NEVER A CANCEL. This bound applies ONLY to a marker
93
+ * with no `cancelRequested` (see the module header). A CANCELLED marker is never
94
+ * stale at any age — in the gate, in the stop's cancel, and in the boot sweep —
95
+ * because its gate can still be an unbounded wait away.
96
+ *
97
+ * THE ACCEPTED RESIDUAL: a cancel whose spawn never materialises stays on disk
98
+ * indefinitely and keeps its dispatch's "not claimed quiescent" disclosure. The
99
+ * safe direction is deliberate: a false not-quiescent is survivable, a false
100
+ * quiescent is not.
101
+ */
102
+ export const ARMED_RETRY_STALE_MS = 600_000;
103
+
104
+ /** One durable "a transport retry is being started for this run" intent. */
105
+ export interface ArmedRetry {
106
+ /** The SOURCE run id — the attempt a stop of the dispatch resolves to. */
107
+ parentId: string;
108
+ /** The attempt number the retry will carry (`sourceAttempt + 1`). */
109
+ attempt: number;
110
+ cause: ArmedRetryCause;
111
+ /** ISO stamp of the arm write (diagnostics and ordering). */
112
+ armedAt: string;
113
+ /** Set by a stop that reached the dispatch while the retry was unspawned. */
114
+ cancelRequested?: boolean;
115
+ /** ISO stamp of that cancel. */
116
+ cancelRequestedAt?: string;
117
+ }
118
+
119
+ /** The marker subdirectory, resolved against the CURRENT registry dir per call. */
120
+ function armedDir(): string {
121
+ return path.join(registryDir(), 'armed');
122
+ }
123
+
124
+ /** `<registry>/armed/<parentId>.json`, or `null` for an unusable id. */
125
+ function armedPath(parentId: string): string | null {
126
+ try {
127
+ assertSafeAgentId(parentId);
128
+ } catch {
129
+ return null;
130
+ }
131
+ return path.join(armedDir(), `${parentId}.json`);
132
+ }
133
+
134
+ function isArmedRetry(value: unknown): value is ArmedRetry {
135
+ if (!value || typeof value !== 'object') return false;
136
+ const v = value as Record<string, unknown>;
137
+ if (typeof v.parentId !== 'string' || v.parentId === '') return false;
138
+ if (typeof v.attempt !== 'number' || !Number.isFinite(v.attempt) || v.attempt < 1) return false;
139
+ if (v.cause !== 'transport') return false;
140
+ if (typeof v.armedAt !== 'string' || v.armedAt === '') return false;
141
+ if (v.cancelRequested !== undefined && typeof v.cancelRequested !== 'boolean') return false;
142
+ if (v.cancelRequestedAt !== undefined && typeof v.cancelRequestedAt !== 'string') return false;
143
+ return true;
144
+ }
145
+
146
+ function writeArmed(retry: ArmedRetry): boolean {
147
+ const file = armedPath(retry.parentId);
148
+ if (!file) return false;
149
+ try {
150
+ ensureOwnerOnlyDir(armedDir());
151
+ writeFileAtomicSync(file, JSON.stringify(retry, null, 2));
152
+ return true;
153
+ } catch {
154
+ // Best-effort by contract: a marker that cannot be written leaves the
155
+ // pre-#616 window, which is strictly better than refusing the retry.
156
+ return false;
157
+ }
158
+ }
159
+
160
+ /** The marker's age in ms, or `null` when its stamp cannot be read. */
161
+ function armedAgeMs(retry: ArmedRetry): number | null {
162
+ const armedAt = Date.parse(retry.armedAt);
163
+ if (!Number.isFinite(armedAt)) return null;
164
+ return Date.now() - armedAt;
165
+ }
166
+
167
+ /**
168
+ * Is this marker an unclaimed intent old enough to be crash residue?
169
+ *
170
+ * RULE (1), review 624 r2: a CANCEL is never stale — its spawn's gate can still
171
+ * be waiting behind the spawn queue or another run's repository lock, so an age
172
+ * bound would silently drop a live stop. Only an UNCLAIMED marker is judged, and
173
+ * only by age.
174
+ *
175
+ * TOTAL and CHEAP: one parse of a stamp already in memory. An unjudgeable stamp
176
+ * (a rolled-back clock, a corrupt `armedAt`) is NOT stale — the conservative
177
+ * side is to honour an intent we cannot date (review 624, N-r2-4).
178
+ */
179
+ function isStaleArmedRetry(retry: ArmedRetry): boolean {
180
+ if (retry.cancelRequested === true) return false;
181
+ const age = armedAgeMs(retry);
182
+ if (age === null) return false;
183
+ return age > ARMED_RETRY_STALE_MS;
184
+ }
185
+
186
+ /** Unlink a marker file. Best-effort: a failed unlink leaves it readable. */
187
+ function reclaimArmed(file: string): boolean {
188
+ try {
189
+ fs.unlinkSync(file);
190
+ return true;
191
+ } catch {
192
+ // ENOENT (already gone) and EACCES (cannot reclaim) both leave a marker that
193
+ // the next read judges stale again — no state is corrupted by failing here.
194
+ return false;
195
+ }
196
+ }
197
+
198
+ /** Read one marker. Total: absent/unreadable/malformed all read as `null`. */
199
+ export function readArmedRetry(parentId: string): ArmedRetry | null {
200
+ const file = armedPath(parentId);
201
+ if (!file) return null;
202
+ let parsed: unknown;
203
+ try {
204
+ parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
205
+ } catch {
206
+ return null;
207
+ }
208
+ if (!isArmedRetry(parsed)) return null;
209
+ // The id in the FILE must be the id we asked about: a mismatched marker is
210
+ // not this run's intent.
211
+ if (parsed.parentId !== parentId) return null;
212
+ // Review 624 (B1): reclaim on read. A stale marker must not be honoured by
213
+ // ANY reader — the gate, the cancel and the stop report all come through here.
214
+ // A cancel is never stale (rule 1), so this can only drop an unclaimed intent.
215
+ if (isStaleArmedRetry(parsed)) {
216
+ reclaimArmed(file);
217
+ return null;
218
+ }
219
+ return parsed;
220
+ }
221
+
222
+ /**
223
+ * Arm `attempt` for `parentId`. Idempotent WITHIN THE RE-ARM BOUND: re-arming an
224
+ * already-armed retry refreshes the stamp but PRESERVES a cancel that is already
225
+ * requested (a second arming must not un-cancel a stop that already reached it).
226
+ *
227
+ * BEYOND the re-arm bound the previous marker cannot be about this spawn: it
228
+ * outlived an arm whose spawn never reached the gate (the process died), so a
229
+ * cancel on it describes a spawn that is gone. Preserving it would let a phantom
230
+ * kill THIS retry at the gate, so the arm starts fresh instead (review 624, B1).
231
+ *
232
+ * An age that CANNOT be judged is IN-WINDOW (review 624, N-r2-4): honour the
233
+ * cancel rather than discard one that every other reader would still honour.
234
+ */
235
+ export function armRetry(input: {
236
+ parentId: string;
237
+ attempt: number;
238
+ armedAt: string;
239
+ }): boolean {
240
+ const existing = readArmedRetry(input.parentId);
241
+ const age = existing ? armedAgeMs(existing) : null;
242
+ const inSpawnWindow = age === null || age <= ARMED_RETRY_SPAWN_BOUND_MS;
243
+ if (existing && existing.attempt === input.attempt && inSpawnWindow) {
244
+ return writeArmed({ ...existing, armedAt: input.armedAt });
245
+ }
246
+ return writeArmed({
247
+ parentId: input.parentId,
248
+ attempt: input.attempt,
249
+ cause: 'transport',
250
+ armedAt: input.armedAt,
251
+ });
252
+ }
253
+
254
+ /**
255
+ * What a stop's cancel attempt did. Three outcomes, not two, because the caller
256
+ * must distinguish "the retry has not spawned yet" (`cancelled`) from "the
257
+ * marker was already gone because the retry became durable" (`gone` — worth ONE
258
+ * lineage re-read, since the retry is now a normal record) from "the marker is
259
+ * there and could not be written" (`failed` — the retry may still prompt, which
260
+ * is an error the caller must report).
261
+ */
262
+ export type CancelOutcome = 'cancelled' | 'gone' | 'failed';
263
+
264
+ /** Request the cancel on an armed retry. Never throws. */
265
+ export function cancelArmedRetry(parentId: string, attempt: number): CancelOutcome {
266
+ // Reclaim-on-read applies here too (B1): an unclaimed marker past the stale
267
+ // bound is `gone` for every attempt, and is unlinked rather than left to
268
+ // mislead the next reader. A CANCEL is never stale (rule 1).
269
+ const existing = readArmedRetry(parentId);
270
+ // A marker for a DIFFERENT attempt is not this retry's intent: treat it as
271
+ // gone for this attempt (the gate compares attempts too, so no cancel leaks).
272
+ if (!existing || existing.attempt !== attempt) return 'gone';
273
+ const cancelled: ArmedRetry = {
274
+ ...existing,
275
+ cancelRequested: true,
276
+ cancelRequestedAt: new Date().toISOString(),
277
+ };
278
+ return writeArmed(cancelled) ? 'cancelled' : 'failed';
279
+ }
280
+
281
+ /**
282
+ * The PRE-PROMPT gate (issue #616's Q3 seam): has a stop cancelled the retry
283
+ * that is about to prompt? Total — an unreadable marker answers `false`, which
284
+ * degrades to the pre-#616 behaviour rather than blocking a legitimate retry.
285
+ */
286
+ export function isRetryCancelRequested(parentId: string, attempt: number): boolean {
287
+ const armed = readArmedRetry(parentId);
288
+ return !!armed && armed.attempt === attempt && armed.cancelRequested === true;
289
+ }
290
+
291
+ /** Drop the marker for `parentId` when it names `attempt`. True when none is left. */
292
+ export function clearArmedRetry(parentId: string, attempt?: number): boolean {
293
+ const file = armedPath(parentId);
294
+ if (!file) return true;
295
+ const existing = readArmedRetry(parentId);
296
+ if (existing && attempt !== undefined && existing.attempt !== attempt) return false;
297
+ try {
298
+ fs.unlinkSync(file);
299
+ return true;
300
+ } catch (err) {
301
+ // Only ENOENT proves the desired end state (the same rule
302
+ // `clearInflightRun` follows).
303
+ return (err as NodeJS.ErrnoException).code === 'ENOENT';
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Is this file NOT a marker for the name it sits under? Total, and never throws.
309
+ *
310
+ * A file that cannot be parsed, does not have the marker shape, or names a
311
+ * different `parentId` can never be returned by `readArmedRetry(fileParentId)`:
312
+ * the path is derived from the id and the read additionally requires the parsed
313
+ * id to match. An UNREADABLE file (EACCES, a race with the unlink) is NOT orphan
314
+ * evidence — the sweep leaves what it cannot judge to the next boot.
315
+ */
316
+ function isOrphanMarkerFile(fileParentId: string, file: string): boolean {
317
+ let text: string;
318
+ try {
319
+ text = fs.readFileSync(file, 'utf-8');
320
+ } catch {
321
+ return false;
322
+ }
323
+ let parsed: unknown;
324
+ try {
325
+ parsed = JSON.parse(text);
326
+ } catch {
327
+ return true;
328
+ }
329
+ return !isArmedRetry(parsed) || parsed.parentId !== fileParentId;
330
+ }
331
+
332
+ /**
333
+ * Issue #616 / review 624 (B1) — the BOOT SWEEP.
334
+ *
335
+ * Nothing outside a marker's own lifecycle clears it, so a process death between
336
+ * the arm write and the spawn leaves a file that every later stop of that
337
+ * dispatch would read as an armed retry. The readers already reclaim what they
338
+ * touch; this reclaims what no reader will touch for a while, so a stale intent
339
+ * does not sit on disk until the dispatch is stopped again.
340
+ *
341
+ * Cheap by construction: one `readdir` of a directory that holds at most one
342
+ * marker per in-flight retry, and the same total read every other caller uses.
343
+ *
344
+ * TWO KINDS OF RESIDUE (review 624 r2, N-r2-2):
345
+ *
346
+ * - a MARKER whose own read judges it stale — reclaimed by the read itself;
347
+ * - a FILE that is not a marker for the name it sits under (its `parentId`
348
+ * names another run, or it does not parse into a marker at all). Every
349
+ * reader is keyed by `parentId` and rejects the mismatch, so nothing can
350
+ * ever consume it — it is rubbish that would otherwise be re-scanned on
351
+ * every boot. Unlinking it drops no cancel any reader could honour.
352
+ *
353
+ * RULE (1) IS OBEYED: a well-formed, correctly-named marker with
354
+ * `cancelRequested === true` is never reclaimed here at any age — its gate may
355
+ * still be an unbounded wait away (see the module header).
356
+ */
357
+ export function sweepStaleArmedRetries(): {
358
+ scanned: number;
359
+ reclaimed: number;
360
+ } {
361
+ let files: string[];
362
+ try {
363
+ files = fs.readdirSync(armedDir());
364
+ } catch {
365
+ return { scanned: 0, reclaimed: 0 };
366
+ }
367
+ let scanned = 0;
368
+ let reclaimed = 0;
369
+ for (const file of files) {
370
+ if (!file.endsWith('.json')) continue;
371
+ const parentId = file.slice(0, -'.json'.length);
372
+ const full = path.join(armedDir(), file);
373
+ scanned += 1;
374
+ if (isOrphanMarkerFile(parentId, full)) {
375
+ if (reclaimArmed(full)) reclaimed += 1;
376
+ continue;
377
+ }
378
+ if (readArmedRetry(parentId) === null && !fs.existsSync(full)) {
379
+ reclaimed += 1;
380
+ }
381
+ }
382
+ return { scanned, reclaimed };
383
+ }
@@ -32,18 +32,61 @@
32
32
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
33
33
  import * as fs from "node:fs";
34
34
  import * as path from "node:path";
35
- import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES, type ProcessOwner, type RecoveryMode, type SubagentRun } from "./types";
35
+ import {
36
+ CUSTOM_ENTRY_TYPES,
37
+ RECOVERY_MODES,
38
+ RETRY_CAUSES,
39
+ type ProcessOwner,
40
+ type RecoveryMode,
41
+ type RetryCause,
42
+ type SubagentRun,
43
+ } from "./types";
36
44
  import { assertSafeAgentId } from "./sanitize";
37
45
  import { ensureOwnerOnlyDir } from "./store-permissions";
38
46
 
39
47
  /** Which execution path owns an in-flight run (drives the boot scan's mark). */
40
48
  export type InflightRunKind = "foreground" | "unit" | "background";
41
49
 
50
+ /**
51
+ * The terminal status a `recordFlipPending` marker names (issue #546). This is
52
+ * the AGENT-record vocabulary, not the run record's: a settled `done` run maps to
53
+ * `completed` on the record. Only `failed` is written today (the pre-start path is
54
+ * the one writer), and both values are validated on read.
55
+ */
56
+ export type RecordFlipStatus = "failed" | "completed";
57
+
58
+ /**
59
+ * Issue #546: the terminal status the dispatch was about to write onto its
60
+ * agent record. Written into the registry entry BEFORE that entry is retired,
61
+ * because retirement is an unlink — after it there is nothing left for a fresh
62
+ * process to find, and the crash residue is a `running` agent record that no
63
+ * boot scan can source a candidate for. The record flip ends the marker's
64
+ * useful life: the entry is retired only once the flip is durable, so a marker
65
+ * that outlives its entry means the flip did not land.
66
+ *
67
+ * Read fail-open: a marker that fails validation is dropped (normalizeEnrichment),
68
+ * which degrades to the pre-#546 behaviour rather than inventing a flip.
69
+ */
70
+ export interface RecordFlipPending {
71
+ status: RecordFlipStatus;
72
+ /** The error the flip was going to stamp (already sanitised by the caller). */
73
+ error?: string;
74
+ /** ISO stamp of the marker write (diagnostics only; ordering is the entry's). */
75
+ at: string;
76
+ }
77
+
42
78
  /** The durable per-run registry entry (one small JSON file per run id). */
43
79
  export interface InflightRun {
44
80
  id: string;
45
81
  dispatchId?: string;
46
82
  attempt?: number;
83
+ /**
84
+ * Issue #616: why this attempt exists (`transport` auto-retry vs a manual
85
+ * `retryRunId` retry). Mirrored from the run record so a stop that must
86
+ * resolve a retry from the registry alone (no agent record yet) can still
87
+ * scope itself. Absent = unknown, never `transport`.
88
+ */
89
+ retryCause?: RetryCause;
47
90
  kind: InflightRunKind;
48
91
  owner?: ProcessOwner;
49
92
  childMarker?: string;
@@ -63,6 +106,12 @@ export interface InflightRun {
63
106
  // run record, so a post-crash retry restores the same 17-field shape a
64
107
  // same-session retry does (including `force`; decision 2026-10-11).
65
108
  originalParams?: SubagentRun["originalParams"];
109
+ /**
110
+ * Issue #546: the terminal flip this process had not yet written when it
111
+ * died. Absent on every terminal entry the live path retires normally; present
112
+ * only between the terminal run-entry write and the agent-record flip.
113
+ */
114
+ recordFlipPending?: RecordFlipPending;
66
115
  /**
67
116
  * Issue #447: the acceptance marker, mirrored from the run record.
68
117
  * `null` = tracked but never accepted (never reached `session.prompt()`),
@@ -80,6 +129,7 @@ export interface InflightRunInput {
80
129
  id: string;
81
130
  dispatchId?: string;
82
131
  attempt?: number;
132
+ retryCause?: RetryCause;
83
133
  kind: InflightRunKind;
84
134
  owner?: ProcessOwner;
85
135
  childMarker?: string;
@@ -90,6 +140,8 @@ export interface InflightRunInput {
90
140
  thinkingLevel?: string;
91
141
  originalParams?: SubagentRun["originalParams"];
92
142
  acceptedAt?: string | null;
143
+ /** Issue #546: a marker to write, or `null` to clear one (never `undefined`-clobbered). */
144
+ recordFlipPending?: RecordFlipPending | null;
93
145
  startedAt: string;
94
146
  cwd?: string;
95
147
  }
@@ -150,6 +202,20 @@ function isInflightRun(value: unknown): value is InflightRun {
150
202
  return v.kind === "foreground" || v.kind === "unit" || v.kind === "background";
151
203
  }
152
204
 
205
+ /** True when `value` is a well-formed `recordFlipPending` marker. */
206
+ function normalizeRecordFlipPending(value: unknown): RecordFlipPending | null {
207
+ if (!value || typeof value !== "object") return null;
208
+ const v = value as Record<string, unknown>;
209
+ if (v.status !== "failed" && v.status !== "completed") return null;
210
+ if (typeof v.at !== "string" || v.at === "") return null;
211
+ if (v.error !== undefined && typeof v.error !== "string") return null;
212
+ return {
213
+ status: v.status,
214
+ ...(typeof v.error === "string" ? { error: v.error } : {}),
215
+ at: v.at,
216
+ };
217
+ }
218
+
153
219
  /**
154
220
  * Normalize the additive enrichment fields leniently. A wrong-typed field
155
221
  * degrades to ABSENT on the parsed entry; the entry itself is never rejected
@@ -168,6 +234,13 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
168
234
  } else {
169
235
  delete entry.originalParams;
170
236
  }
237
+ // Issue #616: same lenient rule — a cause we cannot trust is DROPPED (absent ⇒
238
+ // unknown ⇒ never auto-stopped), never coerced to the stop-scoped value.
239
+ if (typeof raw.retryCause === "string" && (RETRY_CAUSES as readonly string[]).includes(raw.retryCause)) {
240
+ entry.retryCause = raw.retryCause as RetryCause;
241
+ } else {
242
+ delete entry.retryCause;
243
+ }
171
244
  // Issue #447: keep the tri-state intact and treat anything else as LEGACY
172
245
  // (absent) rather than inventing a fourth state. A mistyped marker must
173
246
  // never downgrade a real run into the never-started class.
@@ -176,6 +249,13 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
176
249
  } else {
177
250
  delete entry.acceptedAt;
178
251
  }
252
+ // Issue #546: same lenient rule as the fields above — a mistyped marker is
253
+ // dropped, never invented. Dropping it degrades to the pre-#546 residue (a
254
+ // stale `running` record), which is strictly safer than flipping a record on
255
+ // a marker we cannot trust.
256
+ const flip = normalizeRecordFlipPending(raw.recordFlipPending);
257
+ if (flip) entry.recordFlipPending = flip;
258
+ else delete entry.recordFlipPending;
179
259
  return entry;
180
260
  }
181
261
 
@@ -210,6 +290,7 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
210
290
  const next: InflightRun = { ...base, id: input.id, kind: input.kind };
211
291
  if (input.dispatchId !== undefined) next.dispatchId = input.dispatchId;
212
292
  if (input.attempt !== undefined) next.attempt = input.attempt;
293
+ if (input.retryCause !== undefined) next.retryCause = input.retryCause;
213
294
  if (input.recoveryPosture !== undefined) next.recoveryPosture = input.recoveryPosture;
214
295
  if (input.owner !== undefined) next.owner = input.owner;
215
296
  if (input.childMarker !== undefined) next.childMarker = input.childMarker;
@@ -223,6 +304,10 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
223
304
  // Issue #447: `null` MUST copy (it is the never-started sentinel); only
224
305
  // `undefined` is skipped, so a refresh without the marker cannot erase it.
225
306
  if (input.acceptedAt !== undefined) next.acceptedAt = input.acceptedAt;
307
+ // Issue #546: `null` is the explicit CLEAR (mirroring `acceptedAt`); only
308
+ // `undefined` is skipped, so a refresh cannot erase a live marker.
309
+ if (input.recordFlipPending === null) delete next.recordFlipPending;
310
+ else if (input.recordFlipPending !== undefined) next.recordFlipPending = input.recordFlipPending;
226
311
  return next;
227
312
  }
228
313
 
@@ -257,14 +342,36 @@ export function updateInflightRun(input: InflightRunInput): boolean {
257
342
  return writeAtomic(file, mergeInput(existing, input));
258
343
  }
259
344
 
260
- /** Remove an entry (terminal finalize). Missing file is a no-op. */
261
- export function clearInflightRun(id: string): void {
345
+ /**
346
+ * Remove an entry (terminal finalize). Missing file is a no-op.
347
+ *
348
+ * Issue #546 (major 4): returns whether the DESIRED END STATE holds — `true`
349
+ * when the file is gone (unlinked now, or never there), `false` when it still
350
+ * exists after the attempt (`EACCES`/`EPERM`/`EBUSY`, or a racing writer that
351
+ * re-created it). Existing callers ignore the value; the boot applier does not:
352
+ * an unverified retirement would report a settled marker while the marker is
353
+ * still on disk, so `false` is counted as a flip failure and the entry is kept.
354
+ */
355
+ export function clearInflightRun(id: string): boolean {
262
356
  const file = resolvePath(id);
263
- if (!file) return;
357
+ if (!file) return true; // nothing addressable to remove
264
358
  try {
265
359
  fs.unlinkSync(file);
266
- } catch {
267
- // Already cleared (or never registered) — the desired end state.
360
+ return true;
361
+ } catch (err) {
362
+ // Only ENOENT proves the desired end state. Any OTHER error (EACCES on the
363
+ // file or on an untraversable parent, EPERM, EBUSY, EROFS) does not — an
364
+ // `existsSync` here returns false for both "gone" and "cannot look", which
365
+ // is how a failed unlink was reported as a settlement (r2 major 1).
366
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return true;
367
+ try {
368
+ fs.statSync(file);
369
+ return false; // confirmed: the entry is still there
370
+ } catch (statErr) {
371
+ // An untraversable parent is UNCERTAIN, not absent: fail closed so the
372
+ // caller keeps the marker for a boot that can actually look.
373
+ return (statErr as NodeJS.ErrnoException).code === "ENOENT";
374
+ }
268
375
  }
269
376
  }
270
377
 
@@ -308,6 +415,30 @@ export function markInterrupted(id: string, interruptedAt: string): boolean {
308
415
  }
309
416
  }
310
417
 
418
+ /**
419
+ * Issue #546: write the terminal-flip marker onto an EXISTING entry — the call
420
+ * that has to happen before the entry is retired, because retirement is an
421
+ * unlink and the marker must survive it.
422
+ *
423
+ * Idempotent and total, with the same contract as `markInterrupted`: a missing
424
+ * entry, an id that fails the write guard, or a failed write returns `false` and
425
+ * never throws (a throwing pre-start cleanup would replace the caller's original
426
+ * spawn error). `false` is the only truthful signal, so callers must not assume
427
+ * the marker landed.
428
+ */
429
+ export function markRecordFlipPending(id: string, flip: RecordFlipPending): boolean {
430
+ try {
431
+ const file = resolvePath(id);
432
+ if (!file) return false;
433
+ const existing = readEntry(file);
434
+ if (!existing) return false;
435
+ if (existing.recordFlipPending) return true;
436
+ return writeAtomic(file, { ...existing, recordFlipPending: flip });
437
+ } catch {
438
+ return false;
439
+ }
440
+ }
441
+
311
442
  // ---------------------------------------------------------------------------
312
443
  // The persistence choke point
313
444
  // ---------------------------------------------------------------------------
@@ -318,6 +449,7 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
318
449
  id: run.id,
319
450
  dispatchId: run.dispatchId,
320
451
  attempt: run.attempt,
452
+ retryCause: run.retryCause,
321
453
  kind,
322
454
  recoveryPosture: run.recoveryPosture,
323
455
  owner: run.owner,
@@ -342,9 +474,26 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
342
474
  * registry and ignore it. A `running` write without a kind is a refresh with
343
475
  * nothing to register — the boot scan's mark is a separate `markInterrupted`.
344
476
  */
345
- export function persistRunRecord(pi: ExtensionAPI, run: SubagentRun, kind?: InflightRunKind): void {
477
+ export interface PersistRunRecordOptions {
478
+ /**
479
+ * Issue #546: leave the registry entry in place and make the CALLER its owner
480
+ * (it retires with `clearInflightRun` once the agent-record flip is durable).
481
+ * Retirement-before-append is what makes a crash inside this function leave a
482
+ * residue no boot scan can source a candidate for; the pre-start terminal path
483
+ * is the one caller that must not take it, and it is the only caller that
484
+ * passes this flag. Every other writer keeps the historical order.
485
+ */
486
+ deferRetire?: boolean;
487
+ }
488
+
489
+ export function persistRunRecord(
490
+ pi: ExtensionAPI,
491
+ run: SubagentRun,
492
+ kind?: InflightRunKind,
493
+ options?: PersistRunRecordOptions,
494
+ ): void {
346
495
  if (run.status !== "running") {
347
- clearInflightRun(run.id);
496
+ if (!options?.deferRetire) clearInflightRun(run.id);
348
497
  } else if (kind) {
349
498
  registerInflightRun(toRegistryInput(run, kind));
350
499
  }
package/src/schema.ts CHANGED
@@ -128,8 +128,10 @@ export const delegateTaskParamsSchema = Type.Object({
128
128
  Type.Number({
129
129
  description:
130
130
  "Maximum time in milliseconds the subagent is allowed to run. " +
131
- "If exceeded, the subagent is killed and an error is returned. " +
132
- "Background runs default to a 30-minute deadline when no timeout is given; an explicit timeout is honored as given (30 minutes is a default, not a ceiling). A raw value ≥ 2^31-1 normalizes to the default.",
131
+ "A **background** run with no valid timeout (none passed, or normalized away) gets the 30-minute default deadline; a **foreground** run has no default. " +
132
+ "An explicit **positive** timeout is honored as given, except values that normalize to no timeout (a raw value `≥ 2^31-1` or a nonpositive value; a background run then gets the 30-minute default, a foreground run has none) and the opt-in `processChecks` high/xhigh foreground switch, which may drop an explicit timeout. " +
133
+ "**Foreground expiry** kills the process (SIGTERM, 5s grace, then SIGKILL); the expired attempt's result is a timeout error, and with `retryOnTimeout: true` the tool may retry automatically and return the later result. " +
134
+ "**Background expiry** requests a cooperative abort — a prompt that ignores it keeps running; the run's **timeout snapshot** (`failed`/`timeout`) is written at expiry, and a later settle **amends** that record (never re-classifies it).",
133
135
  }),
134
136
  ),
135
137
  cwd: Type.Optional(