brl-subagent 2.8.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.
- package/AGENT.md +17 -2
- package/README.md +3 -3
- package/package.json +6 -5
- package/src/agent-tools.ts +332 -0
- package/src/background-pipeline.ts +1025 -0
- package/src/boot-recovery.ts +360 -0
- package/src/commands.ts +137 -0
- package/src/concurrency.ts +3 -5
- package/src/delegate-handler.ts +2261 -0
- package/src/engineering-bar.ts +1 -1
- package/src/git.ts +220 -8
- package/src/headstate.ts +3 -3
- package/src/history.ts +21 -3
- package/src/index.ts +109 -4473
- package/src/loader.ts +1 -1
- package/src/logging.ts +67 -4
- package/src/mode-prologue.ts +4 -10
- package/src/mode-runners.ts +1575 -0
- package/src/notify-completion.ts +35 -8
- package/src/params.ts +14 -13
- package/src/preflight.ts +123 -16
- package/src/prelude.ts +14 -5
- package/src/presets.ts +3 -5
- package/src/proc.ts +2 -3
- package/src/recovery-engine.ts +1 -1
- package/src/recovery-surface.ts +1 -2
- package/src/recovery.ts +238 -10
- package/src/reports.ts +1 -7
- package/src/run-registry.ts +133 -10
- package/src/runner.ts +47 -18
- package/src/runtime.ts +50 -0
- package/src/sanitize.ts +20 -2
- package/src/scheduler.ts +1 -2
- package/src/schema.ts +4 -2
- package/src/scratch-root.ts +909 -0
- package/src/scratch-spawn.ts +256 -0
- package/src/session-manager.ts +587 -81
- package/src/state.ts +12 -14
- package/src/templates.ts +3 -5
- package/src/terminal-notifier.ts +405 -0
- package/src/transcript.ts +1 -1
- package/src/tui-format.ts +3 -1
- package/src/tui.ts +46 -36
- package/src/types.ts +29 -3
- package/src/unit-params.ts +113 -0
- package/src/unit-run.ts +35 -15
- package/src/validate.ts +28 -9
- package/src/worktree-report.ts +142 -0
package/src/recovery.ts
CHANGED
|
@@ -31,13 +31,12 @@
|
|
|
31
31
|
* ownership cannot be verified.
|
|
32
32
|
*/
|
|
33
33
|
|
|
34
|
-
import {
|
|
34
|
+
import type { Logger } from "./logging";
|
|
35
|
+
import { listInflightRuns, type InflightRun, type RecordFlipStatus } from "./run-registry";
|
|
35
36
|
import { assertSafeAgentId } from "./sanitize";
|
|
36
37
|
import { isProcAvailable, defaultRecoveryDeps } from "./proc";
|
|
37
38
|
import { decideRecovery, classifyOwner, reapPids, type RecoveryDeps, type RecoveryRecord } from "./recovery-engine";
|
|
38
|
-
import type
|
|
39
|
-
import type { SubagentRun } from "./types";
|
|
40
|
-
import { PROMPT_NEVER_ISSUED_MESSAGE } from "./types";
|
|
39
|
+
import { PROMPT_NEVER_ISSUED_MESSAGE, type SubagentRun } from "./types";
|
|
41
40
|
|
|
42
41
|
// Re-export the pure engine and the production wiring so existing importers
|
|
43
42
|
// (`index.ts`, the recovery/registry suites) keep their single entry point.
|
|
@@ -71,6 +70,21 @@ export interface BootScanSummary {
|
|
|
71
70
|
* write is warned — either way the entry stays out of the interrupted class.
|
|
72
71
|
*/
|
|
73
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;
|
|
74
88
|
}
|
|
75
89
|
|
|
76
90
|
/** The all-zero summary (a skipped scan / an empty registry). */
|
|
@@ -86,6 +100,9 @@ export function emptyBootScanSummary(): BootScanSummary {
|
|
|
86
100
|
skippedNoOwner: 0,
|
|
87
101
|
skippedUnsafeIds: 0,
|
|
88
102
|
neverStarted: 0,
|
|
103
|
+
flipRepaired: 0,
|
|
104
|
+
flipRetired: 0,
|
|
105
|
+
flipFailures: 0,
|
|
89
106
|
};
|
|
90
107
|
}
|
|
91
108
|
|
|
@@ -282,6 +299,39 @@ export function neverStartedRunRecord(
|
|
|
282
299
|
};
|
|
283
300
|
}
|
|
284
301
|
|
|
302
|
+
/** What the boot verdict hands the caller: which record to flip, to what. */
|
|
303
|
+
export interface RecordFlipVerdict {
|
|
304
|
+
id: string;
|
|
305
|
+
status: RecordFlipStatus;
|
|
306
|
+
error?: string;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Issue #546 (major 4): what the applier's unit of work did. `'repaired'` = the
|
|
311
|
+
* record was rewritten and the store says terminal; `'retired'` = no rewrite was
|
|
312
|
+
* needed (the record was already terminal or absent) and only the entry was
|
|
313
|
+
* retired; `false` = NOT settled (unreadable record, a failed record write, or a
|
|
314
|
+
* failed unlink) — the scan keeps the marker and counts `flipFailures`.
|
|
315
|
+
*
|
|
316
|
+
* The applier reports the outcome instead of the scan inferring it from its own
|
|
317
|
+
* earlier decision: under the two-boot race the second boot's applier sees a
|
|
318
|
+
* terminal record and retires, and the ledger must say `retired` (not a second
|
|
319
|
+
* repair) without the scan having to re-read anything.
|
|
320
|
+
*/
|
|
321
|
+
export type RecordFlipOutcome = "repaired" | "retired" | false;
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Issue #546 (major 2/3): the disk-only, TRI-STATE read of one agent record,
|
|
325
|
+
* taken immediately before the flip verdict. `exists: false` is CONFIRMED
|
|
326
|
+
* ABSENCE (nothing durable can go stale ⇒ the marker may retire); `exists: true`
|
|
327
|
+
* with `record: null` is PRESENT-BUT-UNREADABLE/CORRUPT (we know nothing ⇒ hold,
|
|
328
|
+
* keep the marker); a record is the state the decision is made on.
|
|
329
|
+
*/
|
|
330
|
+
export interface FreshAgentRecord {
|
|
331
|
+
record: PersistedAgentLike | null;
|
|
332
|
+
exists: boolean;
|
|
333
|
+
}
|
|
334
|
+
|
|
285
335
|
export interface RegistryScanOptions {
|
|
286
336
|
deps: RecoveryDeps;
|
|
287
337
|
/**
|
|
@@ -302,6 +352,24 @@ export interface RegistryScanOptions {
|
|
|
302
352
|
* entry so a registry without an agent file is still marked, not skipped.
|
|
303
353
|
*/
|
|
304
354
|
readAgentRecord?(id: string): PersistedAgentLike | null;
|
|
355
|
+
/**
|
|
356
|
+
* Issue #546: apply a persisted `recordFlipPending` marker to that run's agent
|
|
357
|
+
* record AND retire the registry entry (the two writes belong together: the
|
|
358
|
+
* entry is the marker, so it may die only with the flip). Returns the outcome
|
|
359
|
+
* the ledger counts; `false` (a failed record write OR a failed unlink) keeps
|
|
360
|
+
* the entry, so the marker survives to the next boot. Idempotent by contract:
|
|
361
|
+
* an already-terminal record is not rewritten and emits no event.
|
|
362
|
+
* Absent ⇒ the marker is left untouched (no write, no retirement).
|
|
363
|
+
*/
|
|
364
|
+
applyRecordFlip?(verdict: RecordFlipVerdict): RecordFlipOutcome;
|
|
365
|
+
/**
|
|
366
|
+
* Issue #546 (major 3): a DISK read of the one agent record, taken just before
|
|
367
|
+
* the verdict — never the scanner's earlier snapshot, which is memory-first
|
|
368
|
+
* (`getAgent`) and may be stale. Wired together with `applyRecordFlip`; when
|
|
369
|
+
* either is absent the marker branch holds (fail-closed): a marker is never
|
|
370
|
+
* retired on a state we did not just read.
|
|
371
|
+
*/
|
|
372
|
+
readFreshAgentRecord?(id: string): FreshAgentRecord;
|
|
305
373
|
now?: () => Date;
|
|
306
374
|
log?: Pick<Logger, "debug" | "info" | "warn">;
|
|
307
375
|
}
|
|
@@ -319,6 +387,53 @@ export interface RegistryScanOptions {
|
|
|
319
387
|
* invisible here — consistent with the maintained `no-owner` policy (don't act
|
|
320
388
|
* on what we cannot verify).
|
|
321
389
|
*/
|
|
390
|
+
/**
|
|
391
|
+
* Issue #447 / #546: the one ownership rule both pre-verdict paths share — a
|
|
392
|
+
* record may be acted on ONLY when its owner is provably dead. A live owner may
|
|
393
|
+
* still be inside its own pre-start window (the git-branch lock, a slow
|
|
394
|
+
* transcript start, the microseconds between the marker write and its flip) and
|
|
395
|
+
* is about to finish the job itself; an owner we cannot verify is never acted on
|
|
396
|
+
* (`classifyOwner` returns "unverifiable" without /proc).
|
|
397
|
+
*/
|
|
398
|
+
function ownerProvablyDead(owner: RecoveryRecord["owner"], deps: RecoveryDeps): boolean {
|
|
399
|
+
if (!owner || !Number.isInteger(owner.pid) || owner.pid <= 0) return false;
|
|
400
|
+
return classifyOwner(owner, deps) === "dead";
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Issue #546: the verdict for an entry that carries a `recordFlipPending`
|
|
405
|
+
* marker. Three outcomes plus one hold:
|
|
406
|
+
*
|
|
407
|
+
* - record already terminal, or CONFIRMED ABSENT → the flip landed (or nothing
|
|
408
|
+
* durable exists) and only the retirement was lost: retire only
|
|
409
|
+
* (`flipRetired`);
|
|
410
|
+
* - record still `running` and the owner provably dead → apply the flip and
|
|
411
|
+
* retire (`flipRepaired`);
|
|
412
|
+
* - record present but UNREADABLE/corrupt → HOLD: we cannot tell whether a
|
|
413
|
+
* `running` record is still there, so the marker must survive (major 2);
|
|
414
|
+
* - record still `running` but the owner live/unverifiable → HOLD, write
|
|
415
|
+
* nothing, and skip ordinary recovery for this entry (`continue`).
|
|
416
|
+
*
|
|
417
|
+
* `fresh` is a DISK read taken by the caller immediately before this call
|
|
418
|
+
* (major 3), not the scanner's snapshot.
|
|
419
|
+
*/
|
|
420
|
+
function recordFlipDecision(
|
|
421
|
+
entry: InflightRun,
|
|
422
|
+
fresh: FreshAgentRecord,
|
|
423
|
+
deps: RecoveryDeps,
|
|
424
|
+
): "repaired" | "retired" | "held" | "unreadable" {
|
|
425
|
+
// Major 2: absence and unreadability are OPPOSITE verdicts. A confirmed
|
|
426
|
+
// absence may retire the marker (nothing durable can go stale); a file that
|
|
427
|
+
// exists but cannot be parsed keeps it (we know nothing, and retiring would
|
|
428
|
+
// strand a possibly still-`running` record). `unreadable` is its own verdict
|
|
429
|
+
// so the ledger can count it as a failed settlement instead of a silent hold.
|
|
430
|
+
if (!fresh.exists) return "retired";
|
|
431
|
+
if (!fresh.record) return "unreadable";
|
|
432
|
+
if (fresh.record.status !== "running") return "retired";
|
|
433
|
+
const owner = fresh.record.owner ?? entry.owner;
|
|
434
|
+
return ownerProvablyDead(owner, deps) ? "repaired" : "held";
|
|
435
|
+
}
|
|
436
|
+
|
|
322
437
|
export async function recoverInflightRuns(options: RegistryScanOptions): Promise<BootScanSummary> {
|
|
323
438
|
// Issue #304 read/write asymmetry, fail-closed: `listInflightRuns` accepts
|
|
324
439
|
// any string id, but every write (and `markInterrupted`) resolves through
|
|
@@ -348,11 +463,120 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
348
463
|
// is nothing to reap, nothing to interrupt, and nothing to retry. It is
|
|
349
464
|
// finalized `failed` below instead of being handed to the decision engine.
|
|
350
465
|
const neverStarted: InflightRun[] = [];
|
|
466
|
+
// Issue #546: the counters for the marker verdict (a marker is not a
|
|
467
|
+
// candidate; it is a repair).
|
|
468
|
+
let flipRepaired = 0;
|
|
469
|
+
let flipRetired = 0;
|
|
470
|
+
let flipFailures = 0;
|
|
351
471
|
for (const entry of addressable) {
|
|
352
472
|
const isBackground = entry.kind === "background";
|
|
353
473
|
// Only a background entry has an agent record to enrich from (and to drop
|
|
354
474
|
// a stale entry by); the read is that ONE file, never the whole store.
|
|
355
475
|
const agent = isBackground ? (options.readAgentRecord?.(entry.id) ?? null) : null;
|
|
476
|
+
// Issue #546: a marker means the terminal run-entry write was ATTEMPTED and
|
|
477
|
+
// the agent-record flip was not seen through. Settle it BEFORE the
|
|
478
|
+
// terminal-record drop below — that drop's whole job is to swallow a stale
|
|
479
|
+
// entry, and swallowing a marker would leave exactly the zombie row this
|
|
480
|
+
// issue is about. A marker is not gated by `recovery` (a repair is not an
|
|
481
|
+
// offer) and not by `acceptedAt` (the marker already names the terminal
|
|
482
|
+
// status, which supersedes the never-started class).
|
|
483
|
+
if (entry.recordFlipPending) {
|
|
484
|
+
if (!options.applyRecordFlip || !options.readFreshAgentRecord) {
|
|
485
|
+
// HOLD — and skip ordinary recovery for this entry. A half-wired
|
|
486
|
+
// applier cannot settle the marker, but falling through is worse than
|
|
487
|
+
// doing nothing: the never-started finalizer would retire a marker
|
|
488
|
+
// over a record that is still `running`, and the interrupted mark
|
|
489
|
+
// would stamp a dispatch whose terminal run entry is already
|
|
490
|
+
// written (r2 major 2). Entry and marker stay byte-identical for
|
|
491
|
+
// the next fully wired boot.
|
|
492
|
+
options.log?.debug("Recovery: held a record-flip marker (applier or fresh-record reader not wired)", {
|
|
493
|
+
id: entry.id,
|
|
494
|
+
kind: entry.kind,
|
|
495
|
+
});
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
{
|
|
499
|
+
// Issue #546 (major 3): the pre-flip read is taken HERE, after the
|
|
500
|
+
// candidate loop and immediately before the verdict — so a boot that
|
|
501
|
+
// begins after another finished sees the terminal record and retires
|
|
502
|
+
// without rewriting. Two boots that BOTH read here before either
|
|
503
|
+
// writes are the stated limit (see the spec's narrowed guarantee).
|
|
504
|
+
const fresh = options.readFreshAgentRecord(entry.id);
|
|
505
|
+
const decision = recordFlipDecision(entry, fresh, options.deps);
|
|
506
|
+
if (decision === "unreadable") {
|
|
507
|
+
// Major 2: the record exists but cannot be parsed, so we cannot
|
|
508
|
+
// tell whether it is still `running`. The marker is KEPT and the
|
|
509
|
+
// settlement is counted failed (never silently dropped).
|
|
510
|
+
flipFailures++;
|
|
511
|
+
options.log?.warn("Recovery: could not read the agent record for a record-flip marker — the marker is kept", {
|
|
512
|
+
id: entry.id,
|
|
513
|
+
kind: entry.kind,
|
|
514
|
+
});
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (decision === "held") {
|
|
518
|
+
// NOT a candidate either: the owner may be about to land this flip
|
|
519
|
+
// itself, and the "don't act on what we cannot verify" policy applies
|
|
520
|
+
// (neverStarted's no-owner rule). A marker is never offered as an
|
|
521
|
+
// interrupted run — that would offer a retry for a run that already
|
|
522
|
+
// wrote its terminal entry.
|
|
523
|
+
options.log?.debug("Recovery: held a record-flip marker whose owner is live or unverifiable", {
|
|
524
|
+
id: entry.id,
|
|
525
|
+
kind: entry.kind,
|
|
526
|
+
});
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
{
|
|
530
|
+
// The APPLIER's outcome is the ledger, not the decision taken above:
|
|
531
|
+
// under the two-boot race the second applier can find the record
|
|
532
|
+
// already terminal and retire — that is a `retired`, not a second
|
|
533
|
+
// `repaired`.
|
|
534
|
+
let outcome: RecordFlipOutcome = false;
|
|
535
|
+
try {
|
|
536
|
+
outcome = options.applyRecordFlip({
|
|
537
|
+
id: entry.id,
|
|
538
|
+
status: entry.recordFlipPending.status,
|
|
539
|
+
...(entry.recordFlipPending.error !== undefined
|
|
540
|
+
? { error: entry.recordFlipPending.error }
|
|
541
|
+
: {}),
|
|
542
|
+
});
|
|
543
|
+
} catch (err) {
|
|
544
|
+
// Best-effort, exactly like the mark and never-started paths: a
|
|
545
|
+
// failed repair must not abort the scan for the other candidates.
|
|
546
|
+
options.log?.warn("Recovery: record-flip repair threw", {
|
|
547
|
+
id: entry.id,
|
|
548
|
+
error: (err as Error).message,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
if (outcome === false) {
|
|
552
|
+
flipFailures++;
|
|
553
|
+
options.log?.warn("Recovery: record-flip settlement did not land — the marker is kept", {
|
|
554
|
+
id: entry.id,
|
|
555
|
+
kind: entry.kind,
|
|
556
|
+
status: entry.recordFlipPending.status,
|
|
557
|
+
decision,
|
|
558
|
+
});
|
|
559
|
+
} else if (outcome === "repaired") {
|
|
560
|
+
flipRepaired++;
|
|
561
|
+
options.log?.info("Recovery: repaired a record whose terminal flip was lost", {
|
|
562
|
+
id: entry.id,
|
|
563
|
+
kind: entry.kind,
|
|
564
|
+
status: entry.recordFlipPending.status,
|
|
565
|
+
});
|
|
566
|
+
} else {
|
|
567
|
+
flipRetired++;
|
|
568
|
+
options.log?.debug("Recovery: retired a record-flip marker whose flip had landed", {
|
|
569
|
+
id: entry.id,
|
|
570
|
+
kind: entry.kind,
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
// A landed settlement retires the entry (the applier does it) and a
|
|
574
|
+
// kept marker must not be re-read as an ordinary candidate — either
|
|
575
|
+
// way this entry's scan is over.
|
|
576
|
+
continue;
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
356
580
|
if (agent && agent.status !== "running") continue;
|
|
357
581
|
// Issue #447: ONE tri-state read for both kinds, so the `null` rule cannot
|
|
358
582
|
// drift between the background and run branches.
|
|
@@ -390,12 +614,7 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
390
614
|
// terminal record the run's real terminal entry could not outrank (the
|
|
391
615
|
// store keeps the earlier entry, and readers prefer the LAST one). No owner or
|
|
392
616
|
// an unverifiable one ⇒ no write, exactly as for the mark path.
|
|
393
|
-
const
|
|
394
|
-
const ownerDead =
|
|
395
|
-
!!owner &&
|
|
396
|
-
Number.isInteger(owner.pid) &&
|
|
397
|
-
owner.pid > 0 &&
|
|
398
|
-
classifyOwner(owner, options.deps) === "dead";
|
|
617
|
+
const ownerDead = ownerProvablyDead(entry.owner, options.deps);
|
|
399
618
|
if (!ownerDead) {
|
|
400
619
|
options.log?.debug("Recovery: left a never-started dispatch with a live/unverified owner", {
|
|
401
620
|
id: entry.id,
|
|
@@ -435,6 +654,9 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
435
654
|
});
|
|
436
655
|
summary.skippedUnsafeIds = unsafeIds.length;
|
|
437
656
|
summary.neverStarted = settledNeverStarted;
|
|
657
|
+
summary.flipRepaired = flipRepaired;
|
|
658
|
+
summary.flipRetired = flipRetired;
|
|
659
|
+
summary.flipFailures = flipFailures;
|
|
438
660
|
return summary;
|
|
439
661
|
}
|
|
440
662
|
|
|
@@ -450,6 +672,10 @@ export interface ProductionRecoveryOptions {
|
|
|
450
672
|
/** Issue #447: persist the terminal record of a never-started dispatch. */
|
|
451
673
|
finalizeNeverStarted?(run: SubagentRun, reason: string): boolean | void;
|
|
452
674
|
readAgentRecord?(id: string): PersistedAgentLike | null;
|
|
675
|
+
/** Issue #546: apply a persisted record-flip marker (flip + retire). */
|
|
676
|
+
applyRecordFlip?(verdict: RecordFlipVerdict): RecordFlipOutcome;
|
|
677
|
+
/** Issue #546: the disk read the flip verdict is made on. */
|
|
678
|
+
readFreshAgentRecord?(id: string): FreshAgentRecord;
|
|
453
679
|
now?: () => Date;
|
|
454
680
|
log?: Pick<Logger, "debug" | "info" | "warn">;
|
|
455
681
|
}
|
|
@@ -473,6 +699,8 @@ export async function recoverProduction(options: ProductionRecoveryOptions): Pro
|
|
|
473
699
|
mark: options.mark,
|
|
474
700
|
finalizeNeverStarted: options.finalizeNeverStarted,
|
|
475
701
|
readAgentRecord: options.readAgentRecord,
|
|
702
|
+
applyRecordFlip: options.applyRecordFlip,
|
|
703
|
+
readFreshAgentRecord: options.readFreshAgentRecord,
|
|
476
704
|
now: options.now,
|
|
477
705
|
log: options.log,
|
|
478
706
|
});
|
package/src/reports.ts
CHANGED
|
@@ -6,13 +6,7 @@
|
|
|
6
6
|
* and what secrets may have been accessed.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import type {
|
|
10
|
-
SubagentRun,
|
|
11
|
-
FileAccessReport,
|
|
12
|
-
SecretsExposureEntry,
|
|
13
|
-
SecretsExposureReport,
|
|
14
|
-
ComplianceSummary,
|
|
15
|
-
} from "./types";
|
|
9
|
+
import type { SubagentRun, FileAccessReport, SecretsExposureEntry, SecretsExposureReport, ComplianceSummary } from "./types";
|
|
16
10
|
import { computeSLAMetrics } from "./metrics";
|
|
17
11
|
|
|
18
12
|
// ---------------------------------------------------------------------------
|
package/src/run-registry.ts
CHANGED
|
@@ -29,17 +29,44 @@
|
|
|
29
29
|
* agent store's F6 discipline.
|
|
30
30
|
*/
|
|
31
31
|
|
|
32
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
32
33
|
import * as fs from "node:fs";
|
|
33
34
|
import * as path from "node:path";
|
|
34
|
-
import type
|
|
35
|
-
import type { ProcessOwner, RecoveryMode, SubagentRun } from "./types";
|
|
36
|
-
import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES } from "./types";
|
|
35
|
+
import { CUSTOM_ENTRY_TYPES, RECOVERY_MODES, type ProcessOwner, type RecoveryMode, type SubagentRun } from "./types";
|
|
37
36
|
import { assertSafeAgentId } from "./sanitize";
|
|
38
37
|
import { ensureOwnerOnlyDir } from "./store-permissions";
|
|
39
38
|
|
|
40
39
|
/** Which execution path owns an in-flight run (drives the boot scan's mark). */
|
|
41
40
|
export type InflightRunKind = "foreground" | "unit" | "background";
|
|
42
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
|
+
|
|
43
70
|
/** The durable per-run registry entry (one small JSON file per run id). */
|
|
44
71
|
export interface InflightRun {
|
|
45
72
|
id: string;
|
|
@@ -64,6 +91,12 @@ export interface InflightRun {
|
|
|
64
91
|
// run record, so a post-crash retry restores the same 17-field shape a
|
|
65
92
|
// same-session retry does (including `force`; decision 2026-10-11).
|
|
66
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;
|
|
67
100
|
/**
|
|
68
101
|
* Issue #447: the acceptance marker, mirrored from the run record.
|
|
69
102
|
* `null` = tracked but never accepted (never reached `session.prompt()`),
|
|
@@ -91,6 +124,8 @@ export interface InflightRunInput {
|
|
|
91
124
|
thinkingLevel?: string;
|
|
92
125
|
originalParams?: SubagentRun["originalParams"];
|
|
93
126
|
acceptedAt?: string | null;
|
|
127
|
+
/** Issue #546: a marker to write, or `null` to clear one (never `undefined`-clobbered). */
|
|
128
|
+
recordFlipPending?: RecordFlipPending | null;
|
|
94
129
|
startedAt: string;
|
|
95
130
|
cwd?: string;
|
|
96
131
|
}
|
|
@@ -151,6 +186,20 @@ function isInflightRun(value: unknown): value is InflightRun {
|
|
|
151
186
|
return v.kind === "foreground" || v.kind === "unit" || v.kind === "background";
|
|
152
187
|
}
|
|
153
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
|
+
|
|
154
203
|
/**
|
|
155
204
|
* Normalize the additive enrichment fields leniently. A wrong-typed field
|
|
156
205
|
* degrades to ABSENT on the parsed entry; the entry itself is never rejected
|
|
@@ -177,6 +226,13 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
|
|
|
177
226
|
} else {
|
|
178
227
|
delete entry.acceptedAt;
|
|
179
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;
|
|
180
236
|
return entry;
|
|
181
237
|
}
|
|
182
238
|
|
|
@@ -224,6 +280,10 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
|
|
|
224
280
|
// Issue #447: `null` MUST copy (it is the never-started sentinel); only
|
|
225
281
|
// `undefined` is skipped, so a refresh without the marker cannot erase it.
|
|
226
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;
|
|
227
287
|
return next;
|
|
228
288
|
}
|
|
229
289
|
|
|
@@ -258,14 +318,36 @@ export function updateInflightRun(input: InflightRunInput): boolean {
|
|
|
258
318
|
return writeAtomic(file, mergeInput(existing, input));
|
|
259
319
|
}
|
|
260
320
|
|
|
261
|
-
/**
|
|
262
|
-
|
|
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 {
|
|
263
332
|
const file = resolvePath(id);
|
|
264
|
-
if (!file) return;
|
|
333
|
+
if (!file) return true; // nothing addressable to remove
|
|
265
334
|
try {
|
|
266
335
|
fs.unlinkSync(file);
|
|
267
|
-
|
|
268
|
-
|
|
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
|
+
}
|
|
269
351
|
}
|
|
270
352
|
}
|
|
271
353
|
|
|
@@ -309,6 +391,30 @@ export function markInterrupted(id: string, interruptedAt: string): boolean {
|
|
|
309
391
|
}
|
|
310
392
|
}
|
|
311
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
|
+
|
|
312
418
|
// ---------------------------------------------------------------------------
|
|
313
419
|
// The persistence choke point
|
|
314
420
|
// ---------------------------------------------------------------------------
|
|
@@ -343,9 +449,26 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
|
|
|
343
449
|
* registry and ignore it. A `running` write without a kind is a refresh with
|
|
344
450
|
* nothing to register — the boot scan's mark is a separate `markInterrupted`.
|
|
345
451
|
*/
|
|
346
|
-
export
|
|
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 {
|
|
347
470
|
if (run.status !== "running") {
|
|
348
|
-
clearInflightRun(run.id);
|
|
471
|
+
if (!options?.deferRetire) clearInflightRun(run.id);
|
|
349
472
|
} else if (kind) {
|
|
350
473
|
registerInflightRun(toRegistryInput(run, kind));
|
|
351
474
|
}
|
package/src/runner.ts
CHANGED
|
@@ -10,19 +10,13 @@
|
|
|
10
10
|
* - Temp file management
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import {
|
|
14
|
-
import type {
|
|
13
|
+
import type { TranscriptMessage, TranscriptContentBlock, TranscriptToolCallBlock } from "./transcript-tail";
|
|
14
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
15
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
15
16
|
import * as fs from "node:fs";
|
|
16
17
|
import * as path from "node:path";
|
|
17
|
-
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
18
18
|
import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
19
19
|
import { wrapTask } from "./prompt";
|
|
20
|
-
import type {
|
|
21
|
-
SubagentResult,
|
|
22
|
-
SubagentToolOptions,
|
|
23
|
-
UsageStats,
|
|
24
|
-
ThinkingLevel,
|
|
25
|
-
} from "./types";
|
|
26
20
|
import {
|
|
27
21
|
EMPTY_USAGE,
|
|
28
22
|
SIGKILL_GRACE_MS,
|
|
@@ -33,6 +27,10 @@ import {
|
|
|
33
27
|
classifyError,
|
|
34
28
|
SUBAGENT_ABORTED_MESSAGE,
|
|
35
29
|
SUBAGENT_SIGNAL_KILLED_MESSAGE,
|
|
30
|
+
type SubagentResult,
|
|
31
|
+
type SubagentToolOptions,
|
|
32
|
+
type UsageStats,
|
|
33
|
+
type ThinkingLevel,
|
|
36
34
|
} from "./types";
|
|
37
35
|
import {
|
|
38
36
|
escalateKill,
|
|
@@ -45,16 +43,10 @@ import {
|
|
|
45
43
|
} from "./kill-escalation";
|
|
46
44
|
import { findByMarker, pidAlive, pidHasMarker, pidGone, groupHasMembers, killProcessGroup } from "./proc";
|
|
47
45
|
import { getSafeEnv, DEPTH_ENV_KEY, CHILD_MARKER_ENV_KEY, sanitizeErrorMessage } from "./sanitize";
|
|
48
|
-
import { createLogger } from "./logging";
|
|
49
|
-
import type { Logger } from "./logging";
|
|
46
|
+
import { createLogger, type Logger } from "./logging";
|
|
50
47
|
import { buildEngineeringBarSection } from "./engineering-bar";
|
|
51
|
-
import
|
|
52
|
-
import { extractMessages, formatPendingMessages } from "./messaging";
|
|
53
|
-
import type {
|
|
54
|
-
TranscriptMessage,
|
|
55
|
-
TranscriptContentBlock,
|
|
56
|
-
TranscriptToolCallBlock,
|
|
57
|
-
} from "./transcript-tail";
|
|
48
|
+
import { SCRATCH_ENV_KEY, prepareRunScratch } from "./scratch-spawn";
|
|
49
|
+
import { extractMessages, formatPendingMessages, type Intercom } from "./messaging";
|
|
58
50
|
|
|
59
51
|
/**
|
|
60
52
|
* The logger for diagnostics a CALLER did not instrument. `runSubagent`'s `log`
|
|
@@ -1084,7 +1076,39 @@ export async function runSubagent(
|
|
|
1084
1076
|
intercom?: Intercom,
|
|
1085
1077
|
subagentId?: string,
|
|
1086
1078
|
childMarker?: string,
|
|
1079
|
+
/**
|
|
1080
|
+
* Issue #511 (U2): this run's id — the record id the caller already persisted
|
|
1081
|
+
* (`run.id`), and the name of its scratch directory (`<root>/runs/<id>`).
|
|
1082
|
+
*
|
|
1083
|
+
* Supplied by every DISPATCH call site (single, chain, parallel, graph — and
|
|
1084
|
+
* the timeout retry re-enters this function with the same id). It is optional
|
|
1085
|
+
* only so the non-dispatch callers and the unit tests need not own a scratch
|
|
1086
|
+
* root: absent means "no scratch directory for this spawn", which is a hole
|
|
1087
|
+
* `scratch-spawn.test.ts` closes by asserting each dispatch site passes one.
|
|
1088
|
+
*/
|
|
1089
|
+
runId?: string,
|
|
1087
1090
|
): Promise<SubagentResult> {
|
|
1091
|
+
// Issue #511 (U2): resolve the scratch root, create this run's directory and
|
|
1092
|
+
// admit `BRL_SCRATCH` into the child's environment — HERE, at the one
|
|
1093
|
+
// foreground spawn seam every caller shares, BEFORE any side effect of the
|
|
1094
|
+
// spawn (no temp system-prompt file, no process). A refusal is named and
|
|
1095
|
+
// pre-spawn: the caller's ordinary failure path reports it and no child
|
|
1096
|
+
// starts.
|
|
1097
|
+
const scratch = runId === undefined ? undefined : prepareRunScratch(runId, { log });
|
|
1098
|
+
if (scratch !== undefined && !scratch.ok) {
|
|
1099
|
+
return {
|
|
1100
|
+
messages: [],
|
|
1101
|
+
usage: { ...EMPTY_USAGE },
|
|
1102
|
+
exitCode: 1,
|
|
1103
|
+
stderr: scratch.message,
|
|
1104
|
+
errorMessage: `scratch root unavailable (${scratch.code}): ${scratch.message}`,
|
|
1105
|
+
// An environment refusal is not a provider or tool failure; "crash" is
|
|
1106
|
+
// the closed taxonomy's bucket for "the child never got to run" (the
|
|
1107
|
+
// named code in the message is the actionable half).
|
|
1108
|
+
errorCategory: "crash",
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1088
1112
|
// E10: Inject pending intercom messages into the task prompt
|
|
1089
1113
|
if (intercom && subagentId && intercom.hasMessages(subagentId)) {
|
|
1090
1114
|
const pending = intercom.receiveAndClear(subagentId);
|
|
@@ -1148,6 +1172,11 @@ ${msgBlock}`;
|
|
|
1148
1172
|
// Option B U1: stamp the per-run marker so boot recovery can discover
|
|
1149
1173
|
// this child by scanning /proc/*/environ after a conductor crash.
|
|
1150
1174
|
if (childMarker) envOverrides[CHILD_MARKER_ENV_KEY] = childMarker;
|
|
1175
|
+
// Issue #511 (U2): the run's scratch directory, as an OVERRIDE (applied
|
|
1176
|
+
// last by `getSafeEnv`) and never as an allowlisted key: a `BRL_SCRATCH`
|
|
1177
|
+
// inherited from the parent process must be replaced, and a grandchild
|
|
1178
|
+
// must resolve its own run rather than inherit this one.
|
|
1179
|
+
if (scratch) envOverrides[SCRATCH_ENV_KEY] = scratch.runDir;
|
|
1151
1180
|
const hasEnvOverrides = Object.keys(envOverrides).length > 0;
|
|
1152
1181
|
const proc = spawn(invocation.command, invocation.args, {
|
|
1153
1182
|
cwd,
|