brl-subagent 2.9.0 → 2.9.1

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.
@@ -39,6 +39,34 @@ import { ensureOwnerOnlyDir } from "./store-permissions";
39
39
  /** Which execution path owns an in-flight run (drives the boot scan's mark). */
40
40
  export type InflightRunKind = "foreground" | "unit" | "background";
41
41
 
42
+ /**
43
+ * The terminal status a `recordFlipPending` marker names (issue #546). This is
44
+ * the AGENT-record vocabulary, not the run record's: a settled `done` run maps to
45
+ * `completed` on the record. Only `failed` is written today (the pre-start path is
46
+ * the one writer), and both values are validated on read.
47
+ */
48
+ export type RecordFlipStatus = "failed" | "completed";
49
+
50
+ /**
51
+ * Issue #546: the terminal status the dispatch was about to write onto its
52
+ * agent record. Written into the registry entry BEFORE that entry is retired,
53
+ * because retirement is an unlink — after it there is nothing left for a fresh
54
+ * process to find, and the crash residue is a `running` agent record that no
55
+ * boot scan can source a candidate for. The record flip ends the marker's
56
+ * useful life: the entry is retired only once the flip is durable, so a marker
57
+ * that outlives its entry means the flip did not land.
58
+ *
59
+ * Read fail-open: a marker that fails validation is dropped (normalizeEnrichment),
60
+ * which degrades to the pre-#546 behaviour rather than inventing a flip.
61
+ */
62
+ export interface RecordFlipPending {
63
+ status: RecordFlipStatus;
64
+ /** The error the flip was going to stamp (already sanitised by the caller). */
65
+ error?: string;
66
+ /** ISO stamp of the marker write (diagnostics only; ordering is the entry's). */
67
+ at: string;
68
+ }
69
+
42
70
  /** The durable per-run registry entry (one small JSON file per run id). */
43
71
  export interface InflightRun {
44
72
  id: string;
@@ -63,6 +91,12 @@ export interface InflightRun {
63
91
  // run record, so a post-crash retry restores the same 17-field shape a
64
92
  // same-session retry does (including `force`; decision 2026-10-11).
65
93
  originalParams?: SubagentRun["originalParams"];
94
+ /**
95
+ * Issue #546: the terminal flip this process had not yet written when it
96
+ * died. Absent on every terminal entry the live path retires normally; present
97
+ * only between the terminal run-entry write and the agent-record flip.
98
+ */
99
+ recordFlipPending?: RecordFlipPending;
66
100
  /**
67
101
  * Issue #447: the acceptance marker, mirrored from the run record.
68
102
  * `null` = tracked but never accepted (never reached `session.prompt()`),
@@ -90,6 +124,8 @@ export interface InflightRunInput {
90
124
  thinkingLevel?: string;
91
125
  originalParams?: SubagentRun["originalParams"];
92
126
  acceptedAt?: string | null;
127
+ /** Issue #546: a marker to write, or `null` to clear one (never `undefined`-clobbered). */
128
+ recordFlipPending?: RecordFlipPending | null;
93
129
  startedAt: string;
94
130
  cwd?: string;
95
131
  }
@@ -150,6 +186,20 @@ function isInflightRun(value: unknown): value is InflightRun {
150
186
  return v.kind === "foreground" || v.kind === "unit" || v.kind === "background";
151
187
  }
152
188
 
189
+ /** True when `value` is a well-formed `recordFlipPending` marker. */
190
+ function normalizeRecordFlipPending(value: unknown): RecordFlipPending | null {
191
+ if (!value || typeof value !== "object") return null;
192
+ const v = value as Record<string, unknown>;
193
+ if (v.status !== "failed" && v.status !== "completed") return null;
194
+ if (typeof v.at !== "string" || v.at === "") return null;
195
+ if (v.error !== undefined && typeof v.error !== "string") return null;
196
+ return {
197
+ status: v.status,
198
+ ...(typeof v.error === "string" ? { error: v.error } : {}),
199
+ at: v.at,
200
+ };
201
+ }
202
+
153
203
  /**
154
204
  * Normalize the additive enrichment fields leniently. A wrong-typed field
155
205
  * degrades to ABSENT on the parsed entry; the entry itself is never rejected
@@ -176,6 +226,13 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
176
226
  } else {
177
227
  delete entry.acceptedAt;
178
228
  }
229
+ // Issue #546: same lenient rule as the fields above — a mistyped marker is
230
+ // dropped, never invented. Dropping it degrades to the pre-#546 residue (a
231
+ // stale `running` record), which is strictly safer than flipping a record on
232
+ // a marker we cannot trust.
233
+ const flip = normalizeRecordFlipPending(raw.recordFlipPending);
234
+ if (flip) entry.recordFlipPending = flip;
235
+ else delete entry.recordFlipPending;
179
236
  return entry;
180
237
  }
181
238
 
@@ -223,6 +280,10 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
223
280
  // Issue #447: `null` MUST copy (it is the never-started sentinel); only
224
281
  // `undefined` is skipped, so a refresh without the marker cannot erase it.
225
282
  if (input.acceptedAt !== undefined) next.acceptedAt = input.acceptedAt;
283
+ // Issue #546: `null` is the explicit CLEAR (mirroring `acceptedAt`); only
284
+ // `undefined` is skipped, so a refresh cannot erase a live marker.
285
+ if (input.recordFlipPending === null) delete next.recordFlipPending;
286
+ else if (input.recordFlipPending !== undefined) next.recordFlipPending = input.recordFlipPending;
226
287
  return next;
227
288
  }
228
289
 
@@ -257,14 +318,36 @@ export function updateInflightRun(input: InflightRunInput): boolean {
257
318
  return writeAtomic(file, mergeInput(existing, input));
258
319
  }
259
320
 
260
- /** Remove an entry (terminal finalize). Missing file is a no-op. */
261
- export function clearInflightRun(id: string): void {
321
+ /**
322
+ * Remove an entry (terminal finalize). Missing file is a no-op.
323
+ *
324
+ * Issue #546 (major 4): returns whether the DESIRED END STATE holds — `true`
325
+ * when the file is gone (unlinked now, or never there), `false` when it still
326
+ * exists after the attempt (`EACCES`/`EPERM`/`EBUSY`, or a racing writer that
327
+ * re-created it). Existing callers ignore the value; the boot applier does not:
328
+ * an unverified retirement would report a settled marker while the marker is
329
+ * still on disk, so `false` is counted as a flip failure and the entry is kept.
330
+ */
331
+ export function clearInflightRun(id: string): boolean {
262
332
  const file = resolvePath(id);
263
- if (!file) return;
333
+ if (!file) return true; // nothing addressable to remove
264
334
  try {
265
335
  fs.unlinkSync(file);
266
- } catch {
267
- // Already cleared (or never registered) — the desired end state.
336
+ return true;
337
+ } catch (err) {
338
+ // Only ENOENT proves the desired end state. Any OTHER error (EACCES on the
339
+ // file or on an untraversable parent, EPERM, EBUSY, EROFS) does not — an
340
+ // `existsSync` here returns false for both "gone" and "cannot look", which
341
+ // is how a failed unlink was reported as a settlement (r2 major 1).
342
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return true;
343
+ try {
344
+ fs.statSync(file);
345
+ return false; // confirmed: the entry is still there
346
+ } catch (statErr) {
347
+ // An untraversable parent is UNCERTAIN, not absent: fail closed so the
348
+ // caller keeps the marker for a boot that can actually look.
349
+ return (statErr as NodeJS.ErrnoException).code === "ENOENT";
350
+ }
268
351
  }
269
352
  }
270
353
 
@@ -308,6 +391,30 @@ export function markInterrupted(id: string, interruptedAt: string): boolean {
308
391
  }
309
392
  }
310
393
 
394
+ /**
395
+ * Issue #546: write the terminal-flip marker onto an EXISTING entry — the call
396
+ * that has to happen before the entry is retired, because retirement is an
397
+ * unlink and the marker must survive it.
398
+ *
399
+ * Idempotent and total, with the same contract as `markInterrupted`: a missing
400
+ * entry, an id that fails the write guard, or a failed write returns `false` and
401
+ * never throws (a throwing pre-start cleanup would replace the caller's original
402
+ * spawn error). `false` is the only truthful signal, so callers must not assume
403
+ * the marker landed.
404
+ */
405
+ export function markRecordFlipPending(id: string, flip: RecordFlipPending): boolean {
406
+ try {
407
+ const file = resolvePath(id);
408
+ if (!file) return false;
409
+ const existing = readEntry(file);
410
+ if (!existing) return false;
411
+ if (existing.recordFlipPending) return true;
412
+ return writeAtomic(file, { ...existing, recordFlipPending: flip });
413
+ } catch {
414
+ return false;
415
+ }
416
+ }
417
+
311
418
  // ---------------------------------------------------------------------------
312
419
  // The persistence choke point
313
420
  // ---------------------------------------------------------------------------
@@ -342,9 +449,26 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
342
449
  * registry and ignore it. A `running` write without a kind is a refresh with
343
450
  * nothing to register — the boot scan's mark is a separate `markInterrupted`.
344
451
  */
345
- export function persistRunRecord(pi: ExtensionAPI, run: SubagentRun, kind?: InflightRunKind): void {
452
+ export interface PersistRunRecordOptions {
453
+ /**
454
+ * Issue #546: leave the registry entry in place and make the CALLER its owner
455
+ * (it retires with `clearInflightRun` once the agent-record flip is durable).
456
+ * Retirement-before-append is what makes a crash inside this function leave a
457
+ * residue no boot scan can source a candidate for; the pre-start terminal path
458
+ * is the one caller that must not take it, and it is the only caller that
459
+ * passes this flag. Every other writer keeps the historical order.
460
+ */
461
+ deferRetire?: boolean;
462
+ }
463
+
464
+ export function persistRunRecord(
465
+ pi: ExtensionAPI,
466
+ run: SubagentRun,
467
+ kind?: InflightRunKind,
468
+ options?: PersistRunRecordOptions,
469
+ ): void {
346
470
  if (run.status !== "running") {
347
- clearInflightRun(run.id);
471
+ if (!options?.deferRetire) clearInflightRun(run.id);
348
472
  } else if (kind) {
349
473
  registerInflightRun(toRegistryInput(run, kind));
350
474
  }
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(