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.
package/src/recovery.ts CHANGED
@@ -32,7 +32,7 @@
32
32
  */
33
33
 
34
34
  import type { Logger } from "./logging";
35
- import { listInflightRuns, type InflightRun } from "./run-registry";
35
+ import { listInflightRuns, type InflightRun, type RecordFlipStatus } from "./run-registry";
36
36
  import { assertSafeAgentId } from "./sanitize";
37
37
  import { isProcAvailable, defaultRecoveryDeps } from "./proc";
38
38
  import { decideRecovery, classifyOwner, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
@@ -70,6 +70,30 @@ export interface BootScanSummary {
70
70
  * write is warned — either way the entry stays out of the interrupted class.
71
71
  */
72
72
  neverStarted: number;
73
+ /**
74
+ * Issue #546: entries carrying a `recordFlipPending` marker whose agent record
75
+ * was still `running` with a provably dead owner — the flip was APPLIED and the
76
+ * entry retired, so a `running` record that no boot scan could otherwise see is
77
+ * terminal after this boot.
78
+ */
79
+ flipRepaired: number;
80
+ /**
81
+ * Issue #546: markers whose record was ALREADY terminal (or absent) — the flip
82
+ * landed and only the retirement was lost. The entry is retired; nothing is
83
+ * rewritten and no terminal event is re-emitted.
84
+ */
85
+ flipRetired: number;
86
+ /** Issue #546: flips decided but whose durable write did NOT land (#304 rule). */
87
+ flipFailures: number;
88
+ /**
89
+ * Issue #554: the CORRUPT subset of `flipFailures` — the record was present
90
+ * and its bytes were read, but `JSON.parse` rejected them. An ADDITIONAL
91
+ * count, never a replacement: `flipFailures` keeps its meaning (a failed
92
+ * settlement) so #546's H2c and every other marker case stay valid. The
93
+ * operator's distinction is "repair the file" (corrupt) vs "fix permissions"
94
+ * (unreadable, the rest of `flipFailures`).
95
+ */
96
+ flipCorrupt: number;
73
97
  }
74
98
 
75
99
  /** The all-zero summary (a skipped scan / an empty registry). */
@@ -85,6 +109,10 @@ export function emptyBootScanSummary(): BootScanSummary {
85
109
  skippedNoOwner: 0,
86
110
  skippedUnsafeIds: 0,
87
111
  neverStarted: 0,
112
+ flipRepaired: 0,
113
+ flipRetired: 0,
114
+ flipFailures: 0,
115
+ flipCorrupt: 0,
88
116
  };
89
117
  }
90
118
 
@@ -281,6 +309,49 @@ export function neverStartedRunRecord(
281
309
  };
282
310
  }
283
311
 
312
+ /** What the boot verdict hands the caller: which record to flip, to what. */
313
+ export interface RecordFlipVerdict {
314
+ id: string;
315
+ status: RecordFlipStatus;
316
+ error?: string;
317
+ }
318
+
319
+ /**
320
+ * Issue #546 (major 4): what the applier's unit of work did. `'repaired'` = the
321
+ * record was rewritten and the store says terminal; `'retired'` = no rewrite was
322
+ * needed (the record was already terminal or absent) and only the entry was
323
+ * retired; `false` = NOT settled (unreadable record, a failed record write, or a
324
+ * failed unlink) — the scan keeps the marker and counts `flipFailures`.
325
+ *
326
+ * The applier reports the outcome instead of the scan inferring it from its own
327
+ * earlier decision: under the two-boot race the second boot's applier sees a
328
+ * terminal record and retires, and the ledger must say `retired` (not a second
329
+ * repair) without the scan having to re-read anything.
330
+ */
331
+ export type RecordFlipOutcome = "repaired" | "retired" | false;
332
+
333
+ /**
334
+ * Issue #546 (major 2/3): the disk-only, TRI-STATE read of one agent record,
335
+ * taken immediately before the flip verdict. `exists: false` is CONFIRMED
336
+ * ABSENCE (nothing durable can go stale ⇒ the marker may retire); `exists: true`
337
+ * with `record: null` is PRESENT-BUT-UNREADABLE/CORRUPT (we know nothing ⇒ hold,
338
+ * keep the marker); a record is the state the decision is made on.
339
+ */
340
+ export interface FreshAgentRecord {
341
+ record: PersistedAgentLike | null;
342
+ exists: boolean;
343
+ /**
344
+ * Issue #554: WHY there is no record when `exists` is true — `"corrupt"`
345
+ * (the file read, but JSON.parse rejected it) vs `"unreadable"` (stat/read
346
+ * failed). Optional so a caller that only knows the tri-state (a test seam)
347
+ * stays valid; the boot ledger counts the corrupt subset by name.
348
+ */
349
+ reason?: AgentRecordFailureReason;
350
+ }
351
+
352
+ /** Issue #554: the two named record-read failures. */
353
+ export type AgentRecordFailureReason = "corrupt" | "unreadable";
354
+
284
355
  export interface RegistryScanOptions {
285
356
  deps: RecoveryDeps;
286
357
  /**
@@ -301,6 +372,24 @@ export interface RegistryScanOptions {
301
372
  * entry so a registry without an agent file is still marked, not skipped.
302
373
  */
303
374
  readAgentRecord?(id: string): PersistedAgentLike | null;
375
+ /**
376
+ * Issue #546: apply a persisted `recordFlipPending` marker to that run's agent
377
+ * record AND retire the registry entry (the two writes belong together: the
378
+ * entry is the marker, so it may die only with the flip). Returns the outcome
379
+ * the ledger counts; `false` (a failed record write OR a failed unlink) keeps
380
+ * the entry, so the marker survives to the next boot. Idempotent by contract:
381
+ * an already-terminal record is not rewritten and emits no event.
382
+ * Absent ⇒ the marker is left untouched (no write, no retirement).
383
+ */
384
+ applyRecordFlip?(verdict: RecordFlipVerdict): RecordFlipOutcome;
385
+ /**
386
+ * Issue #546 (major 3): a DISK read of the one agent record, taken just before
387
+ * the verdict — never the scanner's earlier snapshot, which is memory-first
388
+ * (`getAgent`) and may be stale. Wired together with `applyRecordFlip`; when
389
+ * either is absent the marker branch holds (fail-closed): a marker is never
390
+ * retired on a state we did not just read.
391
+ */
392
+ readFreshAgentRecord?(id: string): FreshAgentRecord;
304
393
  now?: () => Date;
305
394
  log?: Pick<Logger, "debug" | "info" | "warn">;
306
395
  }
@@ -318,6 +407,53 @@ export interface RegistryScanOptions {
318
407
  * invisible here — consistent with the maintained `no-owner` policy (don't act
319
408
  * on what we cannot verify).
320
409
  */
410
+ /**
411
+ * Issue #447 / #546: the one ownership rule both pre-verdict paths share — a
412
+ * record may be acted on ONLY when its owner is provably dead. A live owner may
413
+ * still be inside its own pre-start window (the git-branch lock, a slow
414
+ * transcript start, the microseconds between the marker write and its flip) and
415
+ * is about to finish the job itself; an owner we cannot verify is never acted on
416
+ * (`classifyOwner` returns "unverifiable" without /proc).
417
+ */
418
+ function ownerProvablyDead(owner: RecoveryRecord["owner"], deps: RecoveryDeps): boolean {
419
+ if (!owner || !Number.isInteger(owner.pid) || owner.pid <= 0) return false;
420
+ return classifyOwner(owner, deps) === "dead";
421
+ }
422
+
423
+ /**
424
+ * Issue #546: the verdict for an entry that carries a `recordFlipPending`
425
+ * marker. Three outcomes plus one hold:
426
+ *
427
+ * - record already terminal, or CONFIRMED ABSENT → the flip landed (or nothing
428
+ * durable exists) and only the retirement was lost: retire only
429
+ * (`flipRetired`);
430
+ * - record still `running` and the owner provably dead → apply the flip and
431
+ * retire (`flipRepaired`);
432
+ * - record present but UNREADABLE/corrupt → HOLD: we cannot tell whether a
433
+ * `running` record is still there, so the marker must survive (major 2);
434
+ * - record still `running` but the owner live/unverifiable → HOLD, write
435
+ * nothing, and skip ordinary recovery for this entry (`continue`).
436
+ *
437
+ * `fresh` is a DISK read taken by the caller immediately before this call
438
+ * (major 3), not the scanner's snapshot.
439
+ */
440
+ function recordFlipDecision(
441
+ entry: InflightRun,
442
+ fresh: FreshAgentRecord,
443
+ deps: RecoveryDeps,
444
+ ): "repaired" | "retired" | "held" | "unreadable" {
445
+ // Major 2: absence and unreadability are OPPOSITE verdicts. A confirmed
446
+ // absence may retire the marker (nothing durable can go stale); a file that
447
+ // exists but cannot be parsed keeps it (we know nothing, and retiring would
448
+ // strand a possibly still-`running` record). `unreadable` is its own verdict
449
+ // so the ledger can count it as a failed settlement instead of a silent hold.
450
+ if (!fresh.exists) return "retired";
451
+ if (!fresh.record) return "unreadable";
452
+ if (fresh.record.status !== "running") return "retired";
453
+ const owner = fresh.record.owner ?? entry.owner;
454
+ return ownerProvablyDead(owner, deps) ? "repaired" : "held";
455
+ }
456
+
321
457
  export async function recoverInflightRuns(options: RegistryScanOptions): Promise<BootScanSummary> {
322
458
  // Issue #304 read/write asymmetry, fail-closed: `listInflightRuns` accepts
323
459
  // any string id, but every write (and `markInterrupted`) resolves through
@@ -347,11 +483,128 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
347
483
  // is nothing to reap, nothing to interrupt, and nothing to retry. It is
348
484
  // finalized `failed` below instead of being handed to the decision engine.
349
485
  const neverStarted: InflightRun[] = [];
486
+ // Issue #546: the counters for the marker verdict (a marker is not a
487
+ // candidate; it is a repair).
488
+ let flipRepaired = 0;
489
+ let flipRetired = 0;
490
+ let flipFailures = 0;
491
+ // Issue #554: the corrupt SUBSET of the failures above — counted beside it,
492
+ // never instead of it.
493
+ let flipCorrupt = 0;
350
494
  for (const entry of addressable) {
351
495
  const isBackground = entry.kind === "background";
352
496
  // Only a background entry has an agent record to enrich from (and to drop
353
497
  // a stale entry by); the read is that ONE file, never the whole store.
354
498
  const agent = isBackground ? (options.readAgentRecord?.(entry.id) ?? null) : null;
499
+ // Issue #546: a marker means the terminal run-entry write was ATTEMPTED and
500
+ // the agent-record flip was not seen through. Settle it BEFORE the
501
+ // terminal-record drop below — that drop's whole job is to swallow a stale
502
+ // entry, and swallowing a marker would leave exactly the zombie row this
503
+ // issue is about. A marker is not gated by `recovery` (a repair is not an
504
+ // offer) and not by `acceptedAt` (the marker already names the terminal
505
+ // status, which supersedes the never-started class).
506
+ if (entry.recordFlipPending) {
507
+ if (!options.applyRecordFlip || !options.readFreshAgentRecord) {
508
+ // HOLD — and skip ordinary recovery for this entry. A half-wired
509
+ // applier cannot settle the marker, but falling through is worse than
510
+ // doing nothing: the never-started finalizer would retire a marker
511
+ // over a record that is still `running`, and the interrupted mark
512
+ // would stamp a dispatch whose terminal run entry is already
513
+ // written (r2 major 2). Entry and marker stay byte-identical for
514
+ // the next fully wired boot.
515
+ options.log?.debug("Recovery: held a record-flip marker (applier or fresh-record reader not wired)", {
516
+ id: entry.id,
517
+ kind: entry.kind,
518
+ });
519
+ continue;
520
+ }
521
+ {
522
+ // Issue #546 (major 3): the pre-flip read is taken HERE, after the
523
+ // candidate loop and immediately before the verdict — so a boot that
524
+ // begins after another finished sees the terminal record and retires
525
+ // without rewriting. Two boots that BOTH read here before either
526
+ // writes are the stated limit (see the spec's narrowed guarantee).
527
+ const fresh = options.readFreshAgentRecord(entry.id);
528
+ const decision = recordFlipDecision(entry, fresh, options.deps);
529
+ if (decision === "unreadable") {
530
+ // Major 2: the record exists but cannot be parsed, so we cannot
531
+ // tell whether it is still `running`. The marker is KEPT and the
532
+ // settlement is counted failed (never silently dropped).
533
+ flipFailures++;
534
+ // Issue #554: name the corrupt subset — the record read fine but
535
+ // its JSON did not parse. The decision and the kept marker are
536
+ // unchanged; only the ledger gains the finer distinction.
537
+ if (fresh.reason === "corrupt") flipCorrupt++;
538
+ options.log?.warn("Recovery: could not read the agent record for a record-flip marker — the marker is kept", {
539
+ id: entry.id,
540
+ kind: entry.kind,
541
+ ...(fresh.reason ? { reason: fresh.reason } : {}),
542
+ });
543
+ continue;
544
+ }
545
+ if (decision === "held") {
546
+ // NOT a candidate either: the owner may be about to land this flip
547
+ // itself, and the "don't act on what we cannot verify" policy applies
548
+ // (neverStarted's no-owner rule). A marker is never offered as an
549
+ // interrupted run — that would offer a retry for a run that already
550
+ // wrote its terminal entry.
551
+ options.log?.debug("Recovery: held a record-flip marker whose owner is live or unverifiable", {
552
+ id: entry.id,
553
+ kind: entry.kind,
554
+ });
555
+ continue;
556
+ }
557
+ {
558
+ // The APPLIER's outcome is the ledger, not the decision taken above:
559
+ // under the two-boot race the second applier can find the record
560
+ // already terminal and retire — that is a `retired`, not a second
561
+ // `repaired`.
562
+ let outcome: RecordFlipOutcome = false;
563
+ try {
564
+ outcome = options.applyRecordFlip({
565
+ id: entry.id,
566
+ status: entry.recordFlipPending.status,
567
+ ...(entry.recordFlipPending.error !== undefined
568
+ ? { error: entry.recordFlipPending.error }
569
+ : {}),
570
+ });
571
+ } catch (err) {
572
+ // Best-effort, exactly like the mark and never-started paths: a
573
+ // failed repair must not abort the scan for the other candidates.
574
+ options.log?.warn("Recovery: record-flip repair threw", {
575
+ id: entry.id,
576
+ error: (err as Error).message,
577
+ });
578
+ }
579
+ if (outcome === false) {
580
+ flipFailures++;
581
+ options.log?.warn("Recovery: record-flip settlement did not land — the marker is kept", {
582
+ id: entry.id,
583
+ kind: entry.kind,
584
+ status: entry.recordFlipPending.status,
585
+ decision,
586
+ });
587
+ } else if (outcome === "repaired") {
588
+ flipRepaired++;
589
+ options.log?.info("Recovery: repaired a record whose terminal flip was lost", {
590
+ id: entry.id,
591
+ kind: entry.kind,
592
+ status: entry.recordFlipPending.status,
593
+ });
594
+ } else {
595
+ flipRetired++;
596
+ options.log?.debug("Recovery: retired a record-flip marker whose flip had landed", {
597
+ id: entry.id,
598
+ kind: entry.kind,
599
+ });
600
+ }
601
+ // A landed settlement retires the entry (the applier does it) and a
602
+ // kept marker must not be re-read as an ordinary candidate — either
603
+ // way this entry's scan is over.
604
+ continue;
605
+ }
606
+ }
607
+ }
355
608
  if (agent && agent.status !== "running") continue;
356
609
  // Issue #447: ONE tri-state read for both kinds, so the `null` rule cannot
357
610
  // drift between the background and run branches.
@@ -389,12 +642,7 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
389
642
  // terminal record the run's real terminal entry could not outrank (the
390
643
  // store keeps the earlier entry, and readers prefer the LAST one). No owner or
391
644
  // an unverifiable one ⇒ no write, exactly as for the mark path.
392
- const owner = entry.owner;
393
- const ownerDead =
394
- !!owner &&
395
- Number.isInteger(owner.pid) &&
396
- owner.pid > 0 &&
397
- classifyOwner(owner, options.deps) === "dead";
645
+ const ownerDead = ownerProvablyDead(entry.owner, options.deps);
398
646
  if (!ownerDead) {
399
647
  options.log?.debug("Recovery: left a never-started dispatch with a live/unverified owner", {
400
648
  id: entry.id,
@@ -434,6 +682,10 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
434
682
  });
435
683
  summary.skippedUnsafeIds = unsafeIds.length;
436
684
  summary.neverStarted = settledNeverStarted;
685
+ summary.flipRepaired = flipRepaired;
686
+ summary.flipRetired = flipRetired;
687
+ summary.flipFailures = flipFailures;
688
+ summary.flipCorrupt = flipCorrupt;
437
689
  return summary;
438
690
  }
439
691
 
@@ -449,6 +701,10 @@ export interface ProductionRecoveryOptions {
449
701
  /** Issue #447: persist the terminal record of a never-started dispatch. */
450
702
  finalizeNeverStarted?(run: SubagentRun, reason: string): boolean | void;
451
703
  readAgentRecord?(id: string): PersistedAgentLike | null;
704
+ /** Issue #546: apply a persisted record-flip marker (flip + retire). */
705
+ applyRecordFlip?(verdict: RecordFlipVerdict): RecordFlipOutcome;
706
+ /** Issue #546: the disk read the flip verdict is made on. */
707
+ readFreshAgentRecord?(id: string): FreshAgentRecord;
452
708
  now?: () => Date;
453
709
  log?: Pick<Logger, "debug" | "info" | "warn">;
454
710
  }
@@ -472,6 +728,8 @@ export async function recoverProduction(options: ProductionRecoveryOptions): Pro
472
728
  mark: options.mark,
473
729
  finalizeNeverStarted: options.finalizeNeverStarted,
474
730
  readAgentRecord: options.readAgentRecord,
731
+ applyRecordFlip: options.applyRecordFlip,
732
+ readFreshAgentRecord: options.readFreshAgentRecord,
475
733
  now: options.now,
476
734
  log: options.log,
477
735
  });