brl-subagent 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENT.md +3 -3
  2. package/README.md +18 -10
  3. package/package.json +6 -5
  4. package/src/agent-tools.ts +332 -0
  5. package/src/background-pipeline.ts +1025 -0
  6. package/src/boot-recovery.ts +313 -0
  7. package/src/commands.ts +137 -0
  8. package/src/concurrency.ts +26 -5
  9. package/src/delegate-handler.ts +2261 -0
  10. package/src/engineering-bar.ts +69 -0
  11. package/src/event-bus.ts +10 -0
  12. package/src/git.ts +274 -5
  13. package/src/headstate.ts +471 -0
  14. package/src/history.ts +21 -3
  15. package/src/index.ts +127 -3943
  16. package/src/kill-escalation.ts +87 -7
  17. package/src/loader.ts +47 -1
  18. package/src/logging.ts +1 -1
  19. package/src/mode-prologue.ts +4 -10
  20. package/src/mode-runners.ts +1575 -0
  21. package/src/notify-completion.ts +180 -12
  22. package/src/params.ts +211 -37
  23. package/src/preflight.ts +123 -16
  24. package/src/prelude.ts +92 -7
  25. package/src/presets.ts +85 -18
  26. package/src/proc.ts +2 -3
  27. package/src/project-flags.ts +3 -3
  28. package/src/recovery-engine.ts +11 -1
  29. package/src/recovery-surface.ts +1 -2
  30. package/src/recovery.ts +155 -20
  31. package/src/reports.ts +1 -7
  32. package/src/run-registry.ts +22 -3
  33. package/src/runner.ts +80 -21
  34. package/src/runtime.ts +50 -0
  35. package/src/sanitize.ts +20 -2
  36. package/src/scheduler.ts +1 -2
  37. package/src/schema.ts +37 -7
  38. package/src/scratch-root.ts +909 -0
  39. package/src/scratch-spawn.ts +256 -0
  40. package/src/session-manager.ts +854 -200
  41. package/src/state.ts +130 -30
  42. package/src/templates.ts +42 -17
  43. package/src/terminal-notifier.ts +405 -0
  44. package/src/transcript.ts +1 -1
  45. package/src/tui-format.ts +177 -7
  46. package/src/tui.ts +115 -57
  47. package/src/types.ts +206 -5
  48. package/src/unit-params.ts +113 -0
  49. package/src/unit-run.ts +45 -16
  50. package/src/validate.ts +89 -11
  51. package/src/worktree-report.ts +142 -0
@@ -0,0 +1,471 @@
1
+ // Purpose: Durable per-repository head state (ADR 0026): the record a branch run writes before its branch exists, the guarded boot reconciliation, and the age sweep.
2
+ /**
3
+ * Issue #466 — the durable head state, and the one boot step allowed to move git.
4
+ *
5
+ * A branch-mode run creates `brl-subagent-<8hex>` and, before this module, the
6
+ * starting HEAD lived only in a local variable: a crash left the tree on the
7
+ * orphan branch with nothing durable naming the base, and the next dispatch read
8
+ * the orphan as its own base (its diff window then started at the orphan's tip).
9
+ * ADR 0026 fixes that with ONE small record per repository, at
10
+ * `.pi/head-state/<sha256(repoRoot)[0:16]>.json`, written BEFORE the branch
11
+ * exists so a crash inside `createWorkBranch` is recoverable.
12
+ *
13
+ * Three parts, in the order the boot uses them:
14
+ * 1. the store — `writeHeadState` / `readHeadState` / `clearHeadState` /
15
+ * `listHeadStates`, atomic (temp + rename) and owner-only, keyed by the
16
+ * resolved repository root (never `process.cwd()`: a run dispatched with
17
+ * `cwd` inside another repo must record THAT repo);
18
+ * 2. `reconcileHeadStates` — the policy table of dossier §4, executed in its
19
+ * fixed order: parse → root resolves → owner PROVABLY dead → HEAD is
20
+ * EXACTLY the recorded work branch → (unborn HEAD restores, before the
21
+ * dirty row) → tree clean → restore, verify, clear. Any other row leaves
22
+ * the tree alone, keeps the record, and names what it could not repair.
23
+ * It touches git ONLY through injected deps, so all seven verdicts are
24
+ * unit-testable without a repository;
25
+ * 3. `buildHeadStateNotice` + `sweepHeadStates` — one message at the next turn
26
+ * boundary (D5: silence is not a verdict), and 30-day housekeeping for a
27
+ * record whose repository is gone (precedent: `cleanupTempDirs`).
28
+ *
29
+ * What this module must NEVER do (ADR 0026 D3): delete a work branch, force a
30
+ * checkout, or reset a tree. After a crash the work branch is the ONLY copy of
31
+ * the run's work — the diff was captured in memory and lost — so the repair
32
+ * restores the recorded base and keeps the branch.
33
+ */
34
+
35
+ import type { HeadState } from "./git";
36
+ import type { OwnerState } from "./recovery-engine";
37
+ import type { ProcessOwner } from "./types";
38
+ import { createHash } from "node:crypto";
39
+ import { existsSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
40
+ import { basename, join, resolve } from "node:path";
41
+ import { ensureOwnerOnlyDir } from "./store-permissions";
42
+
43
+ /** On-disk record version. A record with any other value is `skip-record`. */
44
+ export const HEAD_STATE_VERSION = 1;
45
+
46
+ /** Housekeeping age for a record whose repository no longer resolves. */
47
+ export const HEAD_STATE_SWEEP_AGE_MS = 30 * 24 * 60 * 60 * 1000;
48
+
49
+ /** Custom-entry type of the one-per-boot head-state notice. */
50
+ export const HEAD_STATE_NOTICE_CUSTOM_TYPE = "subagent-head-state";
51
+
52
+ /**
53
+ * The durable record. `base` is the verbatim `getHeadState` capture, so the
54
+ * repair replays the recorded branch or detached sha — the policy never
55
+ * CHOOSES a branch.
56
+ */
57
+ export interface HeadStateRecord {
58
+ version: number;
59
+ /** Canonical absolute repository root: the record's identity. */
60
+ repoRoot: string;
61
+ /** The agent id, so the notice names the interrupted run's owner. */
62
+ runId: string;
63
+ kind: "background" | "foreground";
64
+ base: HeadState;
65
+ /** Known BEFORE the branch exists (hence `newWorkBranchName` at the caller). */
66
+ workBranch: string;
67
+ owner: ProcessOwner;
68
+ createdAt: string;
69
+ }
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Storage location + keying
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /** Store directory, cwd-relative like the agent store (`.pi/subagents`). */
76
+ let HEAD_STATE_DIR = ".pi/head-state";
77
+
78
+ /** TEST-ONLY: point the store at an alternate directory (mirrors `__setRegistryDir`). */
79
+ export function __setHeadStateDir(dir: string): void {
80
+ HEAD_STATE_DIR = dir;
81
+ }
82
+
83
+ /** The active store directory. */
84
+ export function headStateDir(): string {
85
+ return HEAD_STATE_DIR;
86
+ }
87
+
88
+ /**
89
+ * The record path for a repository. The key is `sha256(root)[0:16]` — one file
90
+ * per repository, which is sufficient because `gitBranchLocks` already
91
+ * serializes the whole branch lifecycle per repo root.
92
+ */
93
+ export function headStatePath(repoRoot: string): string {
94
+ const key = createHash("sha256").update(resolve(repoRoot)).digest("hex").slice(0, 16);
95
+ return join(HEAD_STATE_DIR, `${key}.json`);
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // Shape + IO
100
+ // ---------------------------------------------------------------------------
101
+
102
+ /** True when `value` is a record this code can act on (row 1 of the table). */
103
+ function isHeadStateRecord(value: unknown): value is HeadStateRecord {
104
+ if (!value || typeof value !== "object") return false;
105
+ const v = value as Record<string, unknown>;
106
+ if (v.version !== HEAD_STATE_VERSION) return false;
107
+ if (typeof v.repoRoot !== "string" || typeof v.runId !== "string") return false;
108
+ if (typeof v.workBranch !== "string" || typeof v.createdAt !== "string") return false;
109
+ if (v.kind !== "background" && v.kind !== "foreground") return false;
110
+ const base = v.base as Record<string, unknown> | undefined;
111
+ if (!base || typeof base !== "object") return false;
112
+ if (typeof base.sha !== "string" || typeof base.branch !== "string") return false;
113
+ if (typeof base.detached !== "boolean") return false;
114
+ const owner = v.owner as Record<string, unknown> | undefined;
115
+ if (!owner || typeof owner !== "object") return false;
116
+ return typeof owner.pid === "number" && typeof owner.start === "string";
117
+ }
118
+
119
+ /** A record read: absent and corrupt are DISTINCT (L1 warns, absent is silent). */
120
+ export type HeadStateRead =
121
+ | { state: "ok"; record: HeadStateRecord }
122
+ | { state: "absent" }
123
+ | { state: "corrupt" };
124
+
125
+ /** One enumerated state file and what it parsed to. */
126
+ export interface HeadStateEntry {
127
+ file: string;
128
+ read: HeadStateRead;
129
+ }
130
+
131
+ function readStateFile(file: string): HeadStateRead {
132
+ let text: string;
133
+ try {
134
+ text = readFileSync(file, "utf-8");
135
+ } catch {
136
+ // Present-but-unreadable is a record we cannot trust, not an absent one.
137
+ return existsSync(file) ? { state: "corrupt" } : { state: "absent" };
138
+ }
139
+ try {
140
+ const parsed: unknown = JSON.parse(text);
141
+ return isHeadStateRecord(parsed) ? { state: "ok", record: parsed } : { state: "corrupt" };
142
+ } catch {
143
+ return { state: "corrupt" };
144
+ }
145
+ }
146
+
147
+ /** Read the record for one repository. Never throws. */
148
+ export function readHeadState(repoRoot: string): HeadStateRead {
149
+ return readStateFile(headStatePath(repoRoot));
150
+ }
151
+
152
+ /**
153
+ * Write (or replace) a repository's record. Atomic — temp file in the same
154
+ * directory, then `rename` — and owner-only, so a reader never sees a torn
155
+ * record. Best-effort: returns false rather than throwing, because it runs in
156
+ * the spawn's critical section where a store failure must not refuse the run.
157
+ */
158
+ export function writeHeadState(record: HeadStateRecord): boolean {
159
+ const file = headStatePath(record.repoRoot);
160
+ try {
161
+ ensureOwnerOnlyDir(HEAD_STATE_DIR);
162
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
163
+ writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: "utf-8", mode: 0o600 });
164
+ renameSync(tmp, file);
165
+ return true;
166
+ } catch {
167
+ return false;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Remove a repository's record. Only ever called where the tree is VERIFIED off
173
+ * the work branch (or nothing was created) — a missing file is a no-op.
174
+ */
175
+ export function clearHeadState(repoRoot: string): void {
176
+ try {
177
+ unlinkSync(headStatePath(repoRoot));
178
+ } catch {
179
+ // Already cleared (or never written) — the desired end state.
180
+ }
181
+ }
182
+
183
+ /** Every state file in the store, parse result included (tolerant scan). */
184
+ export function listHeadStateEntries(): HeadStateEntry[] {
185
+ let names: string[];
186
+ try {
187
+ names = readdirSync(HEAD_STATE_DIR).sort();
188
+ } catch {
189
+ return [];
190
+ }
191
+ const entries: HeadStateEntry[] = [];
192
+ for (const name of names) {
193
+ if (!name.endsWith(".json")) continue;
194
+ const file = join(HEAD_STATE_DIR, name);
195
+ entries.push({ file, read: readStateFile(file) });
196
+ }
197
+ return entries;
198
+ }
199
+
200
+ /** Every parseable record; [] when the store is absent. */
201
+ export function listHeadStates(): HeadStateRecord[] {
202
+ const records: HeadStateRecord[] = [];
203
+ for (const entry of listHeadStateEntries()) {
204
+ if (entry.read.state === "ok") records.push(entry.read.record);
205
+ }
206
+ return records;
207
+ }
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // The boot reconciliation (dossier §4's table, in its fixed order)
211
+ // ---------------------------------------------------------------------------
212
+
213
+ /** The git/process surface the table reads (injected: no repository needed to test it). */
214
+ export interface HeadStateDeps {
215
+ /** Resolved repository root for a path, or undefined when it is gone/not a repo. */
216
+ getRepoRoot(dir: string): string | undefined;
217
+ /** Owner liveness; only "dead" may be acted on. */
218
+ classifyOwner(owner: ProcessOwner): OwnerState;
219
+ /** HEAD's branch (undefined when detached) and whether it has a commit yet. */
220
+ getHeadBranch(cwd: string): { branch: string | undefined; unborn: boolean };
221
+ /** The settled path's own restore primitive — no forcing, no resetting. */
222
+ restoreHead(cwd: string, base: HeadState): { ok: true } | { ok: false; error: string };
223
+ hasUncommittedChanges(cwd: string): boolean;
224
+ /** Optional: present work branches, for the leaked-orphan count in the notice. */
225
+ listWorkBranches?(cwd: string): string[];
226
+ }
227
+
228
+ /** One row's verdict, using the dossier's names. */
229
+ export type HeadStateVerdict =
230
+ /** Repaired: the base was restored and the work branch kept. */
231
+ | "restore"
232
+ /** Repaired from an unborn HEAD (the branch had been deleted while checked out). */
233
+ | "no-branch"
234
+ /** HEAD is not on the recorded branch: nothing to repair, the record is cleared. */
235
+ | "already-off"
236
+ /** Left alone; a human must finish (dirty tree, or an unexpected failure). */
237
+ | "needs-manual"
238
+ /** `restoreHead` failed or did not land: the record is KEPT for the next boot. */
239
+ | "restore-failed"
240
+ /** Unparseable/unversioned record: no git command runs, the record is kept. */
241
+ | "skip-record"
242
+ /** The record's repository no longer resolves: kept (may be unmounted). */
243
+ | "skip-missing"
244
+ /** The owner is not provably dead: untouched, and NOT refused. */
245
+ | "skip-owner";
246
+
247
+ /** What the boot decided about one record, and everything the user may need. */
248
+ export interface HeadStateOutcome {
249
+ verdict: HeadStateVerdict;
250
+ repoRoot?: string;
251
+ workBranch?: string;
252
+ base?: HeadState;
253
+ /** A restore error, or why the tree needs a human. */
254
+ detail?: string;
255
+ /** `brl-subagent-*` branches still present, when more than the recorded one. */
256
+ orphans?: number;
257
+ }
258
+
259
+ function countOrphans(deps: HeadStateDeps, cwd: string): number | undefined {
260
+ if (!deps.listWorkBranches) return undefined;
261
+ try {
262
+ const count = deps.listWorkBranches(cwd).length;
263
+ return count > 1 ? count : undefined;
264
+ } catch {
265
+ return undefined;
266
+ }
267
+ }
268
+
269
+ /** One record through the table. Throws only on an unexpected dep failure. */
270
+ function reconcileEntry(entry: HeadStateEntry, deps: HeadStateDeps): HeadStateOutcome {
271
+ if (entry.read.state !== "ok") {
272
+ // Row 1 — no `version`: not written by this code, so its `base` cannot be
273
+ // trusted. Fail closed by NOT ACTING (never by refusing the repository).
274
+ return { verdict: "skip-record", detail: entry.file };
275
+ }
276
+ const record = entry.read.record;
277
+ const identity = { repoRoot: record.repoRoot, workBranch: record.workBranch, base: record.base };
278
+ // Row 2 — the repository may be temporarily unmounted: keep, never delete.
279
+ const repoRoot = deps.getRepoRoot(record.repoRoot);
280
+ if (!repoRoot) return { ...identity, verdict: "skip-missing" };
281
+ const orphans = countOrphans(deps, repoRoot);
282
+ // Row 3 — ONLY a provably dead owner may be repaired. A live one belongs to
283
+ // another process (or the #465 case) and is not refused here either.
284
+ if (deps.classifyOwner(record.owner) !== "dead") return { ...identity, verdict: "skip-owner" };
285
+ const head = deps.getHeadBranch(repoRoot);
286
+ // Row 4 — HEAD must be EXACTLY the recorded work branch. A tree moved by hand
287
+ // is never switched: the policy replays a recorded base, it never chooses one.
288
+ if (head.branch !== record.workBranch) {
289
+ clearHeadState(record.repoRoot);
290
+ return { ...identity, verdict: "already-off" };
291
+ }
292
+ // Row 5 — the branch was deleted while checked out (unborn HEAD). It is a
293
+ // REPAIR row, not a refusal: `git checkout <base>` works there, and `status`
294
+ // reads dirty for the wrong reason — so this row precedes the dirty check.
295
+ if (!head.unborn && deps.hasUncommittedChanges(repoRoot)) {
296
+ // Row 6 — the interrupted run's uncommitted work is the only copy: leave.
297
+ return { ...identity, verdict: "needs-manual", detail: "uncommitted changes in the working tree", orphans };
298
+ }
299
+ // Row 7 — restore the RECORDED base (never a guessed branch), verify, clear.
300
+ const restored = deps.restoreHead(repoRoot, record.base);
301
+ if (!restored.ok) {
302
+ return { ...identity, verdict: "restore-failed", detail: restored.error, orphans };
303
+ }
304
+ const landed = deps.getHeadBranch(repoRoot);
305
+ const wanted = record.base.detached ? undefined : record.base.branch;
306
+ if (landed.branch !== wanted) {
307
+ return {
308
+ ...identity,
309
+ verdict: "restore-failed",
310
+ detail: `restore did not land on ${wanted ?? "the recorded detached HEAD"}`,
311
+ orphans,
312
+ };
313
+ }
314
+ clearHeadState(record.repoRoot);
315
+ return { ...identity, verdict: head.unborn ? "no-branch" : "restore", orphans };
316
+ }
317
+
318
+ /**
319
+ * Run the table over EVERY record in the store (not just this cwd's repository:
320
+ * the payload carries the absolute root, so a boot started in repo A repairs
321
+ * repo B). Each record is isolated: one unreadable repository can never abort
322
+ * the rest of the boot.
323
+ */
324
+ export function reconcileHeadStates(deps: HeadStateDeps): HeadStateOutcome[] {
325
+ const outcomes: HeadStateOutcome[] = [];
326
+ for (const entry of listHeadStateEntries()) {
327
+ try {
328
+ outcomes.push(reconcileEntry(entry, deps));
329
+ } catch (err) {
330
+ // A dep threw mid-table (the repository vanished under us): keep the
331
+ // record and NAME it — silence is not a verdict (D5).
332
+ outcomes.push({
333
+ verdict: "needs-manual",
334
+ detail: err instanceof Error ? err.message : String(err),
335
+ });
336
+ }
337
+ }
338
+ return outcomes;
339
+ }
340
+
341
+ /** The verdicts the user is told about (the rest are log-level detail). */
342
+ export function isReportable(outcome: HeadStateOutcome): boolean {
343
+ return outcome.verdict !== "already-off" && outcome.verdict !== "skip-owner";
344
+ }
345
+
346
+ // ---------------------------------------------------------------------------
347
+ // The notice (one nextTurn message) + the sweep
348
+ // ---------------------------------------------------------------------------
349
+
350
+ /** The recorded base, as a human names it. */
351
+ function baseLabel(base: HeadState | undefined): string {
352
+ if (!base) return "the recorded base";
353
+ return base.detached ? `detached ${base.sha.slice(0, 8)}` : base.branch;
354
+ }
355
+
356
+ /** The exact command that returns the tree to the recorded base (§6). */
357
+ function baseCheckoutCommand(base: HeadState | undefined): string {
358
+ if (!base) return "git checkout <base-branch>";
359
+ return base.detached ? `git checkout --detach ${base.sha}` : `git checkout ${base.branch}`;
360
+ }
361
+
362
+ function describeOutcome(outcome: HeadStateOutcome): string[] {
363
+ const repo = outcome.repoRoot ? basename(outcome.repoRoot) : "an unknown repository";
364
+ const work = outcome.workBranch ?? "the work branch";
365
+ const base = baseLabel(outcome.base);
366
+ const orphanNote = outcome.orphans
367
+ ? `\n ${outcome.orphans} brl-subagent-* branches exist; none is deleted at boot \u2014 their diffs were never captured, so a human decides.`
368
+ : "";
369
+ switch (outcome.verdict) {
370
+ case "restore":
371
+ case "no-branch": {
372
+ const how =
373
+ outcome.verdict === "no-branch"
374
+ ? "its branch had been deleted while checked out"
375
+ : "an interrupted run left the tree on it";
376
+ return [
377
+ ` \u2022 ${repo} \u00b7 RESTORED ${base} \u00b7 ${work} was KEPT with the run's commits (${how}).${orphanNote}`,
378
+ ];
379
+ }
380
+ case "needs-manual":
381
+ case "restore-failed":
382
+ return [
383
+ ` \u2022 ${repo} \u00b7 NEEDS A MANUAL REPAIR \u00b7 ${base} could not be restored (${outcome.detail ?? "unknown reason"}).`,
384
+ ` The tree is still on ${work}. Inspect it with \`git status\`, then:`,
385
+ ` git stash push -u -m "brl-subagent interrupted work"`,
386
+ ` ${baseCheckoutCommand(outcome.base)}`,
387
+ ` Keep ${work} until its work is reviewed — it is the only copy.${orphanNote}`,
388
+ ];
389
+ case "skip-record":
390
+ return [
391
+ ` \u2022 an unreadable head-state record was left in place (${outcome.detail ?? "unknown file"}).`,
392
+ ` No git command was run. If a branch run was interrupted, restore the base by hand: \`git status\`, then \`git checkout <base-branch>\`.`,
393
+ ];
394
+ case "skip-missing":
395
+ return [
396
+ ` \u2022 ${repo} \u00b7 SKIPPED \u00b7 its repository no longer resolves (${outcome.repoRoot}).`,
397
+ ` The record was kept; it is swept after ${Math.round(HEAD_STATE_SWEEP_AGE_MS / 86_400_000)} days.`,
398
+ ];
399
+ default:
400
+ return [];
401
+ }
402
+ }
403
+
404
+ /**
405
+ * PURE builder — the ONE turn-boundary message for the boot's head-state work.
406
+ * Returns undefined when there is nothing the user must act on or know about,
407
+ * so the caller can skip `sendMessage` entirely.
408
+ */
409
+ export function buildHeadStateNotice(
410
+ outcomes: HeadStateOutcome[],
411
+ ): { customType: string; content: string; display: boolean; details: Record<string, unknown> } | undefined {
412
+ const reportable = outcomes.filter(isReportable);
413
+ if (reportable.length === 0) return undefined;
414
+ const lines = reportable.flatMap(describeOutcome);
415
+ const content =
416
+ `Branch isolation left state that this boot had to look at (${reportable.length}):\n\n` +
417
+ `${lines.join("\n")}\n\n` +
418
+ `ADR 0026: the boot restores the recorded base only when the owning process is provably dead, ` +
419
+ `HEAD is exactly the recorded work branch, and the working tree is clean. Anything else is left alone ` +
420
+ `and named here.`;
421
+ return {
422
+ customType: HEAD_STATE_NOTICE_CUSTOM_TYPE,
423
+ content,
424
+ display: true,
425
+ details: { count: reportable.length, verdicts: reportable.map((o) => o.verdict) },
426
+ };
427
+ }
428
+
429
+ /** Options for `sweepHeadStates`. */
430
+ export interface HeadStateSweepOptions {
431
+ /** Age past which an unreachable record is housekeeping (default 30 days). */
432
+ maxAgeMs?: number;
433
+ /** Injectable clock (tests). */
434
+ now?: number;
435
+ /**
436
+ * True when the record's repository no longer resolves. Injected because this
437
+ * module never runs git — and because it is what keeps the sweep honest: a
438
+ * LIVE repository's record is never swept, however old it is.
439
+ */
440
+ repoGone(record: HeadStateRecord): boolean;
441
+ }
442
+
443
+ /**
444
+ * Bounded, boot-time housekeeping (precedent: `cleanupTempDirs`): delete the
445
+ * records that can never be acted on — the repository is gone, or the file
446
+ * cannot be parsed (it names no repository, so it is judged by its own age).
447
+ * Returns the number removed. Never throws.
448
+ */
449
+ export function sweepHeadStates(options: HeadStateSweepOptions): number {
450
+ const maxAgeMs = options.maxAgeMs ?? HEAD_STATE_SWEEP_AGE_MS;
451
+ const now = options.now ?? Date.now();
452
+ let removed = 0;
453
+ for (const entry of listHeadStateEntries()) {
454
+ try {
455
+ if (entry.read.state === "ok") {
456
+ const age = now - Date.parse(entry.read.record.createdAt);
457
+ // NaN (a bad timestamp) is NOT old: keep it, never sweep on a parse failure.
458
+ if (!(age > maxAgeMs) || !options.repoGone(entry.read.record)) continue;
459
+ } else if (entry.read.state === "corrupt") {
460
+ if (!(now - statSync(entry.file).mtimeMs > maxAgeMs)) continue;
461
+ } else {
462
+ continue;
463
+ }
464
+ unlinkSync(entry.file);
465
+ removed++;
466
+ } catch {
467
+ // A record that vanished mid-scan is already the desired end state.
468
+ }
469
+ }
470
+ return removed;
471
+ }
package/src/history.ts CHANGED
@@ -6,11 +6,22 @@
6
6
  * and duration formatting.
7
7
  */
8
8
 
9
- import type { SubagentRun, SubagentResult } from "./types";
10
- import { isSubagentError, getFinalOutput, isSubagentRunShape, classifyError, coherentFailureReason, CUSTOM_ENTRY_TYPES, MAX_RUN_HISTORY_ENTRIES, DEFAULT_OUTPUT_CAP_BYTES } from "./types";
9
+ import type { ExtensionContext, SessionManager } from "@earendil-works/pi-coding-agent";
10
+ import {
11
+ isSubagentError,
12
+ getFinalOutput,
13
+ isSubagentRunShape,
14
+ classifyError,
15
+ coherentFailureReason,
16
+ CUSTOM_ENTRY_TYPES,
17
+ MAX_RUN_HISTORY_ENTRIES,
18
+ DEFAULT_OUTPUT_CAP_BYTES,
19
+ type SubagentRun,
20
+ type SubagentResult,
21
+ } from "./types";
11
22
  import { isOutputTruncated } from "./sanitize";
23
+ import { markSettled } from "./scratch-spawn";
12
24
  import { transcriptDisplayPath } from "./transcript-path";
13
- import type { ExtensionContext, SessionManager } from "@earendil-works/pi-coding-agent";
14
25
 
15
26
  // ---------------------------------------------------------------------------
16
27
  // Run pruning — R2: Disk usage policy
@@ -129,6 +140,13 @@ export function finalizeRunRecord(
129
140
  : result.stopReason;
130
141
  run.outputSummary = finalOutput.slice(0, 200);
131
142
  run.fullOutput = finalOutput || undefined;
143
+ // Issue #511 (U2): settling includes the scratch directory's `.done` marker,
144
+ // and this is the ONE function every foreground terminal path calls — the
145
+ // success, failure, crash and pre-start-rejection arms all land here — so the
146
+ // marker cannot be forgotten by a future caller. Best-effort by contract:
147
+ // `markSettled` logs a failure and never throws, and it is a no-op for a run
148
+ // with no scratch directory to mark.
149
+ markSettled(run);
132
150
  }
133
151
 
134
152
  // ---------------------------------------------------------------------------