pi-goal-delegate 0.1.0 → 0.3.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/src/registry.ts CHANGED
@@ -14,6 +14,8 @@
14
14
  import { closeSync, openSync, readdirSync, realpathSync, unlinkSync, writeSync } from "node:fs";
15
15
  import { resolve } from "node:path";
16
16
  import {
17
+ attenuationRefusal,
18
+ COMPLETION_MESSAGE_LIMIT,
17
19
  DEFAULT_MAX_COST_USD,
18
20
  DEFAULT_MAX_LIVE,
19
21
  formatDuration,
@@ -21,6 +23,7 @@ import {
21
23
  isFailure,
22
24
  isTerminal,
23
25
  MAX_MAX_LIVE,
26
+ MAX_WAIT_MS,
24
27
  shortGoal,
25
28
  type ContainmentVerdict,
26
29
  type RunProgress,
@@ -75,6 +78,11 @@ export interface RegistryHost {
75
78
  thinking: string;
76
79
  parentModel?: string;
77
80
  activeTools: readonly string[];
81
+ /** Ambient delegation-tree limits when this registry lives inside a child. */
82
+ depth?: number;
83
+ maxDepth?: number;
84
+ deadline?: number;
85
+ maxCostUsd?: number;
78
86
  /** Inject a message that participates in the model's context. */
79
87
  deliver: (message: { content: string; summary: string; runIds: string[] }) => void;
80
88
  /** Redraw the footer for one registry. Called on settle, so no status goes stale. */
@@ -94,6 +102,8 @@ export interface StartOptions {
94
102
  scope?: "session" | "workspace";
95
103
  isolated?: boolean;
96
104
  inlineSettleMs?: number;
105
+ /** Aborts only the inline wait; the admitted run continues in the background. */
106
+ signal?: AbortSignal;
97
107
  /** A command the parent runs to prove a `complete` verdict. */
98
108
  verify?: { command: string };
99
109
  /** A run id or child session to continue instead of starting cold. */
@@ -102,8 +112,11 @@ export interface StartOptions {
102
112
  worktree?: boolean;
103
113
  /** Cumulative spend cap in USD. Defaults to PI_DELEGATE_MAX_COST_USD. */
104
114
  maxCostUsd?: number;
115
+ resultSchema?: Record<string, unknown>;
116
+ /** Maximum absolute delegation depth for the new run tree. */
117
+ maxDepth?: number;
105
118
  /** TUI hook: called when live progress changes. */
106
- onProgress?: (progress: RunProgress, status: RunStatus) => void;
119
+ onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void;
107
120
  }
108
121
 
109
122
  export interface AwaitOptions {
@@ -111,6 +124,13 @@ export interface AwaitOptions {
111
124
  mode?: "all" | "any";
112
125
  waitMs?: number;
113
126
  signal?: AbortSignal;
127
+ /**
128
+ * Whether this call reports the settles it returns.
129
+ *
130
+ * Reporting a settle and announcing it are one event or the other, never
131
+ * both, so the caller that is told is the caller that claims. Default true.
132
+ */
133
+ claim?: boolean;
114
134
  }
115
135
 
116
136
  export interface AwaitResult {
@@ -152,7 +172,6 @@ function combineContainment(outcomes: readonly RunOutcome[]): ContainmentVerdict
152
172
 
153
173
  const DELIVERY_WINDOW_MS = 150;
154
174
  const DEFAULT_WAIT_MS = 30_000;
155
- const MAX_WAIT_MS = 50_000;
156
175
  /** Retention runs at most this often, so a burst of settles is one scan. */
157
176
  const PRUNE_INTERVAL_MS = 5 * 60_000;
158
177
 
@@ -263,6 +282,8 @@ export function holderAlive(holder: ClaimHolder): boolean {
263
282
 
264
283
  export class RunRegistry {
265
284
  private readonly handles = new Map<string, RunHandle>();
285
+ /** Starts admitted synchronously but not yet registered as handles. */
286
+ private reserved = 0;
266
287
  private readonly claims = new Map<string, number>();
267
288
  private readonly held = new Map<string, RunOutcome>();
268
289
  private queue: RunOutcome[] = [];
@@ -313,10 +334,35 @@ export class RunRegistry {
313
334
  * environment per call, so a host can raise it without a reload.
314
335
  */
315
336
  async start(options: StartOptions): Promise<RunHandle> {
337
+ const inheritedMaxDepth = this.host.maxDepth ?? 0;
338
+ const requestedMaxDepth = options.maxDepth ?? inheritedMaxDepth;
339
+ const spendCap = options.maxCostUsd ?? (this.host.depth !== undefined ? (this.host.maxCostUsd ?? 0) : maxCostUsd());
340
+ const refusal = attenuationRefusal(this.host, { maxDepth: requestedMaxDepth, maxCostUsd: spendCap });
341
+ if (refusal) throw new Error(refusal);
342
+ options = { ...options, maxDepth: requestedMaxDepth, maxCostUsd: spendCap };
316
343
  const live = maxLive();
317
- if (this.runningCount >= live) {
344
+ if (this.runningCount + this.reserved >= live) {
318
345
  throw new Error(this.admissionRefusal(live));
319
346
  }
347
+ this.reserved += 1;
348
+ // The reservation covers the window between the gate and the handle
349
+ // appearing in `handles`. Once it appears, `runningCount` counts the run:
350
+ // holding both would charge one run two slots for its whole inline window
351
+ // and refuse a start the limit still allows.
352
+ let reserved = true;
353
+ const releaseReservation = () => {
354
+ if (!reserved) return;
355
+ reserved = false;
356
+ this.reserved -= 1;
357
+ };
358
+ try {
359
+ return await this.startReserved(options, releaseReservation);
360
+ } finally {
361
+ releaseReservation();
362
+ }
363
+ }
364
+
365
+ private async startReserved(options: StartOptions, releaseReservation: () => void): Promise<RunHandle> {
320
366
  const onProgress = options.onProgress;
321
367
  const request: StartRequest = {
322
368
  goal: options.goal,
@@ -325,6 +371,10 @@ export class RunRegistry {
325
371
  maxTurns: options.maxTurns,
326
372
  timeoutMinutes: options.timeoutMinutes,
327
373
  maxCostUsd: options.maxCostUsd ?? maxCostUsd(),
374
+ resultSchema: options.resultSchema,
375
+ depth: (this.host.depth ?? -1) + 1,
376
+ maxDepth: options.maxDepth ?? 0,
377
+ parentDeadline: this.host.deadline,
328
378
  verify: options.verify,
329
379
  resumeFrom: options.resumeFrom,
330
380
  worktree: options.worktree,
@@ -338,9 +388,10 @@ export class RunRegistry {
338
388
  sessionId: this.host.sessionId,
339
389
  isolated: options.isolated,
340
390
  inlineSettleMs: options.inlineSettleMs,
391
+ signal: options.signal,
341
392
  parentActiveTools: this.host.activeTools,
342
- onProgress: (progress, status) => {
343
- onProgress?.(progress, status);
393
+ onProgress: (progress, status, runId) => {
394
+ onProgress?.(progress, status, runId);
344
395
  },
345
396
  onSettle: (outcome) => this.onSettle(outcome),
346
397
  onAdmitted: (handle) => {
@@ -349,11 +400,16 @@ export class RunRegistry {
349
400
  // bounded inline window is still open.
350
401
  this.handles.set(handle.runId, handle);
351
402
  this.claim([handle.runId]);
403
+ // Admitted is now counted by `runningCount`.
404
+ releaseReservation();
352
405
  },
353
406
  };
354
407
  const handle = await startRun(request);
355
408
  this.handles.set(handle.runId, handle);
356
- if (handle.outcome?.settledInline) this.consume([handle.runId]);
409
+ // A codemode deadline can discard this nested return value even when the
410
+ // child settled while the wait was aborting. Leave that settle for the
411
+ // completion channel: a possible redelivery is recoverable, a lost one is not.
412
+ if (handle.outcome && !options.signal?.aborted) this.consume([handle.runId]);
357
413
  this.release([handle.runId]);
358
414
  return handle;
359
415
  }
@@ -560,31 +616,44 @@ export class RunRegistry {
560
616
  return;
561
617
  }
562
618
  for (const outcome of pending) this.delivered.add(outcome.runId);
563
- const lines: string[] = [];
564
- for (const outcome of pending) {
565
- const usage = formatUsage(outcome.usage);
566
- const head = [
567
- outcome.runId,
568
- outcome.status,
569
- `${outcome.turns} turns`,
570
- formatDuration(outcome.durationMs),
571
- usage,
572
- ].filter(Boolean).join(" · ");
573
- lines.push(`- ${head}`);
574
- lines.push(` goal: ${shortGoal(outcome.goal, 100)}`);
575
- if (outcome.summary) lines.push(` result: ${shortGoal(outcome.summary, 400)}`);
576
- if (outcome.evidence) lines.push(` evidence: ${shortGoal(outcome.evidence, 400)}`);
577
- }
578
- const content = [
619
+ const runIds = pending.map((outcome) => outcome.runId);
620
+ const detailed = [
579
621
  "# Delegation settled",
580
622
  "",
581
- ...lines,
582
- "",
583
- `Call delegate_await({ runIds: [${pending.map((outcome) => JSON.stringify(outcome.runId)).join(", ")}] }) for the full outcome, or read the run record under ${delegateRoot()}.`,
584
- ].join("\n");
623
+ ...pending.map((outcome) => `## ${outcome.runId}\n${formatOutcome(outcome)}`),
624
+ ].join("\n\n");
625
+ let content = detailed;
626
+ if (detailed.length > COMPLETION_MESSAGE_LIMIT) {
627
+ const lines: string[] = [];
628
+ for (const outcome of pending) {
629
+ const usage = formatUsage(outcome.usage);
630
+ const head = [
631
+ outcome.runId,
632
+ outcome.status,
633
+ `${outcome.turns} turns`,
634
+ formatDuration(outcome.durationMs),
635
+ usage,
636
+ ].filter(Boolean).join(" · ");
637
+ lines.push(`- ${head}`);
638
+ lines.push(` goal: ${shortGoal(outcome.goal, 100)}`);
639
+ // `summary` and `result` are different fields: a structured result
640
+ // exists when the run carried a schema, and labelling the child's
641
+ // prose as `result` made the two look interchangeable.
642
+ if (outcome.summary) lines.push(` summary: ${shortGoal(outcome.summary, 400)}`);
643
+ if (outcome.evidence) lines.push(` evidence: ${shortGoal(outcome.evidence, 400)}`);
644
+ if (outcome.needs) lines.push(` needs: ${shortGoal(outcome.needs, 400)}`);
645
+ }
646
+ content = [
647
+ "# Delegation settled",
648
+ "",
649
+ ...lines,
650
+ "",
651
+ `Call delegate_status({ runIds: [${runIds.map((runId) => JSON.stringify(runId)).join(", ")}] }) for the full outcome, or read the run record under ${delegateRoot()}.`,
652
+ ].join("\n");
653
+ }
585
654
  const summary = pending.map((outcome) => `${outcome.runId}:${outcome.status}`).join(", ");
586
655
  try {
587
- this.host.deliver({ content, summary, runIds: pending.map((outcome) => outcome.runId) });
656
+ this.host.deliver({ content, summary, runIds });
588
657
  } catch {
589
658
  // The session may be shutting down; the record stays on disk.
590
659
  }
@@ -643,6 +712,13 @@ export class RunRegistry {
643
712
  }
644
713
  }
645
714
 
715
+ /** The run ids that are still live, in start order. */
716
+ liveIds(): string[] {
717
+ return this.list()
718
+ .filter((handle) => !isTerminal(handle.status))
719
+ .map((handle) => handle.runId);
720
+ }
721
+
646
722
  /**
647
723
  * Wait for runs, bounded by waitMs. A wait never cancels a run.
648
724
  *
@@ -687,7 +763,10 @@ export class RunRegistry {
687
763
  const handle = this.handles.get(id);
688
764
  if (handle) stillRunning.push(liveOutcome(handle));
689
765
  }
690
- if (!options.signal?.aborted) this.consume(settledIds);
766
+ // Consume exactly what an active caller receives. An aborted codemode
767
+ // script discards nested return values, so its outcomes must go back to
768
+ // the completion channel even when the abort raced the settle.
769
+ if (options.claim !== false && !options.signal?.aborted) this.consume(settledIds);
691
770
  const result: AwaitResult = {
692
771
  settled: mode === "any" ? outcomes.length > 0 : outcomes.length === known.length,
693
772
  timedOutWaiting,
@@ -697,7 +776,7 @@ export class RunRegistry {
697
776
  };
698
777
  if (expired) {
699
778
  result.note =
700
- "The wait ended at waitMs; nothing was cancelled. A delegation takes minutes: end the turn and let the completion message wake you, or wait again.";
779
+ "The wait ended at waitMs; nothing was cancelled. Call delegate_status again with a larger waitMs (and a codemode timeout_ms above it), or yield the turn (via goal_wait if Goal mode is active) so the delegate-completion message wakes you.";
701
780
  } else if (aborted) {
702
781
  result.note = "The wait was cancelled; the delegation itself is untouched and still running.";
703
782
  }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * result-schema.ts - the contract for a child's structured result.
3
+ *
4
+ * A `resultSchema` is enforced by the child at `delegate_complete`. Two failures
5
+ * are worth separating there, because they need different repairs:
6
+ *
7
+ * - the value does not satisfy the schema: the child rewrites the value;
8
+ * - the schema itself is unusable - a dangling `$ref`, a reference into a
9
+ * document this package cannot reach, a shape TypeBox cannot evaluate: no
10
+ * value can satisfy it. The child can never complete, and every
11
+ * retry spends budget on a dead end. That case is caught at admission, in the
12
+ * parent, where the caller can still fix the contract.
13
+ */
14
+
15
+ import { Value } from "typebox/value";
16
+
17
+ /**
18
+ * Whether a local JSON pointer inside the schema document resolves.
19
+ *
20
+ * The answer is a boolean because that is the only question the audit asks. The
21
+ * value a pointer names is a schema fragment of no fixed type, and handing it
22
+ * back would invite callers to interpret a document nothing has validated.
23
+ *
24
+ * The fragment of `#/a/b` is `/a/b`, not `a/b`: the leading slash is part of
25
+ * the pointer, and treating the fragment as the pointer resolves every ref to
26
+ * the empty top-level key.
27
+ */
28
+ function resolves(schema: unknown, fragment: string): boolean {
29
+ if (fragment === "") return true;
30
+ if (!fragment.startsWith("/")) return false;
31
+ let cursor: unknown = schema;
32
+ for (const token of fragment.slice(1).split("/")) {
33
+ let key: string;
34
+ try {
35
+ key = decodeURIComponent(token).replaceAll("~1", "/").replaceAll("~0", "~");
36
+ } catch {
37
+ // A malformed percent escape names no member of any document. It is an
38
+ // unresolved pointer, not a crash inside the caller's argument check.
39
+ return false;
40
+ }
41
+ if (typeof cursor !== "object" || cursor === null) return false;
42
+ // Own properties only. A plain index read resolves `#/toString` through the
43
+ // prototype chain, so the audit admitted a schema the validator rejects for
44
+ // every value - the exact trap this audit exists to refuse.
45
+ if (!Object.hasOwn(cursor, key)) return false;
46
+ cursor = (cursor as Record<string, unknown>)[key];
47
+ if (cursor === undefined) return false;
48
+ }
49
+ return true;
50
+ }
51
+
52
+ /** `$ref` values this package cannot resolve, split by the reason. */
53
+ interface RefAudit {
54
+ /** Local pointers that name nothing in this document. */
55
+ dangling: string[];
56
+ /** References into another document, for which this package has no resolver. */
57
+ external: string[];
58
+ }
59
+
60
+ function auditRefs(schema: unknown): RefAudit {
61
+ const dangling = new Set<string>();
62
+ const external = new Set<string>();
63
+ const visit = (node: unknown): void => {
64
+ if (Array.isArray(node)) {
65
+ for (const item of node) visit(item);
66
+ return;
67
+ }
68
+ if (typeof node !== "object" || node === null) return;
69
+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
70
+ if (key === "$ref" && typeof value === "string") {
71
+ if (!value.startsWith("#")) {
72
+ // `other.json#/t` and `https://.../t` name a document nothing here
73
+ // loads. TypeBox answers false for every value rather than throwing,
74
+ // so a sample could never expose it: the audit has to say the name.
75
+ external.add(value);
76
+ continue;
77
+ }
78
+ // `#` is the whole document; `#name` is an anchor, not a pointer, and
79
+ // is left to the validator rather than judged here.
80
+ const fragment = value.slice(1);
81
+ if (fragment !== "" && fragment.startsWith("/") && !resolves(schema, fragment)) dangling.add(value);
82
+ continue;
83
+ }
84
+ visit(value);
85
+ }
86
+ };
87
+ visit(schema);
88
+ return { dangling: [...dangling], external: [...external] };
89
+ }
90
+
91
+ /** Values every JSON document can be classified against, for a liveness probe. */
92
+ const SAMPLES: readonly unknown[] = [null, {}, [], "", 0, true];
93
+
94
+ /**
95
+ * Why a schema cannot be used at all, or undefined when it is worth admitting.
96
+ *
97
+ * `Value.Check` answers false for a value that does not match, which is the
98
+ * right answer. A `$ref` that resolves nowhere makes it answer false for *every*
99
+ * value: TypeBox fails closed, and a completion contract that fails closed on
100
+ * purpose on nothing is a trap rather than a gate.
101
+ */
102
+ export function auditResultSchema(schema: Record<string, unknown>): string | undefined {
103
+ const { dangling, external } = auditRefs(schema);
104
+ if (dangling.length > 0) {
105
+ return `resultSchema has an unresolved $ref (${dangling.slice(0, 3).join(", ")}), so no result could ever satisfy it.`;
106
+ }
107
+ if (external.length > 0) {
108
+ return `resultSchema has a $ref into another document (${external.slice(0, 3).join(", ")}), which cannot be resolved here, so no result could ever satisfy it.`;
109
+ }
110
+ try {
111
+ for (const sample of SAMPLES) Value.Check(schema as never, sample);
112
+ } catch (error) {
113
+ return `resultSchema cannot be evaluated: ${String(error).slice(0, 300)}`;
114
+ }
115
+ return undefined;
116
+ }
117
+
118
+ /**
119
+ * A bounded, actionable account of why a value failed its schema.
120
+ *
121
+ * "Does not satisfy the schema" is a dead end for a child that cannot see which
122
+ * field is wrong. The instance path and the reason are both in the validator's
123
+ * own error list, so the repair is one call away instead of a guess.
124
+ */
125
+ export function describeSchemaErrors(schema: Record<string, unknown>, value: unknown, limit = 4): string {
126
+ interface SchemaError {
127
+ instancePath?: string;
128
+ message?: string;
129
+ }
130
+ let errors: SchemaError[];
131
+ try {
132
+ // SAFETY: the validator returns records described by its own public type;
133
+ // this function reads exactly two documented fields from each of them, and
134
+ // nothing else about the record is part of the contract here.
135
+ errors = Value.Errors(schema as never, value) as unknown as SchemaError[];
136
+ } catch (error) {
137
+ return `The schema itself could not be evaluated: ${String(error).slice(0, 300)}`;
138
+ }
139
+ const lines = errors.slice(0, limit).map((error) => `${error.instancePath || "/"}: ${error.message ?? "invalid"}`);
140
+ if (lines.length === 0) return "The value does not satisfy the result schema.";
141
+ const more = errors.length > lines.length ? ` (and ${errors.length - lines.length} more)` : "";
142
+ return `${lines.join("; ")}${more}`;
143
+ }
package/src/retention.ts CHANGED
@@ -24,6 +24,7 @@ import { existsSync, lstatSync, readdirSync, rmSync, statSync } from "node:fs";
24
24
  import { join, resolve } from "node:path";
25
25
  import { identityAlive, type ProcessIdentity } from "./identity.ts";
26
26
  import { delegateRoot, isRunId, readJson, value } from "./spawn.ts";
27
+ import { removeWorktree, type WorktreeRef } from "./worktree.ts";
27
28
 
28
29
  const KEEP_ENV = "PI_DELEGATE_MAX_RUNS";
29
30
  const AGE_ENV = "PI_DELEGATE_RETENTION_DAYS";
@@ -108,7 +109,7 @@ interface MetaShape {
108
109
  }
109
110
 
110
111
  interface OutcomeShape {
111
- worktree?: { path?: string };
112
+ worktree?: WorktreeRef;
112
113
  }
113
114
 
114
115
  /** True when the directory is a run record this extension may consider. */
@@ -222,62 +223,126 @@ function planRemovals(candidates: Candidate[], policy: RetentionPolicy, liveByte
222
223
  return removable;
223
224
  }
224
225
 
226
+ /** The plan one pass of the policy produces, before anything is deleted. */
227
+ interface Scan {
228
+ root: string;
229
+ policy: RetentionPolicy;
230
+ candidates: Candidate[];
231
+ live: string[];
232
+ liveBytes: number;
233
+ totalBytes: number;
234
+ removable: Set<string>;
235
+ }
236
+
225
237
  /**
226
- * Remove expired and surplus run records. Best effort: a directory that cannot
227
- * be read or removed stays, and the next pass tries again.
238
+ * Read the record root and compute what the policy would do.
239
+ *
240
+ * Shared by the prune and by the report, so "what the next prune removes" and
241
+ * "what this prune removed" cannot disagree: a caller that only reports is
242
+ * looking at the same computation the deleting pass runs.
228
243
  */
229
- export function pruneRunRecords(options: PruneOptions = {}): PruneResult {
244
+ function scan(options: PruneOptions): Scan {
230
245
  const now = options.now ?? Date.now();
231
- const policy = retentionPolicy();
232
- const keepRuns = Math.max(0, options.keepRuns ?? policy.keepRuns);
233
- const maxAgeDays = Math.max(0, options.maxAgeDays ?? policy.maxAgeDays);
234
- const maxBytes = Math.max(0, options.maxBytes ?? policy.maxBytes);
235
- const root = options.root ?? delegateRoot();
236
- const result: PruneResult = {
237
- scanned: 0,
238
- removed: [],
239
- live: [],
240
- kept: 0,
241
- bytesFreed: 0,
242
- bytesScanned: 0,
246
+ const read = retentionPolicy();
247
+ const policy: RetentionPolicy = {
248
+ keepRuns: Math.max(0, options.keepRuns ?? read.keepRuns),
249
+ maxAgeDays: Math.max(0, options.maxAgeDays ?? read.maxAgeDays),
250
+ maxBytes: Math.max(0, options.maxBytes ?? read.maxBytes),
243
251
  };
252
+ const root = options.root ?? delegateRoot();
253
+ const candidates: Candidate[] = [];
254
+ const live: string[] = [];
255
+ let liveBytes = 0;
244
256
 
245
257
  let names: string[];
246
258
  try {
247
259
  names = readdirSync(root);
248
260
  } catch {
249
- return result;
261
+ return { root, policy, candidates, live, liveBytes: 0, totalBytes: 0, removable: new Set() };
250
262
  }
251
263
 
252
- const candidates: Candidate[] = [];
253
- let liveBytes = 0;
254
264
  for (const name of names) {
255
265
  const record = isRunRecord(root, name);
256
266
  if (!record) continue;
257
- result.scanned += 1;
258
267
  const classified = classify(record, name, now, options.isLive);
259
268
  if (classified === "live") {
260
- result.live.push(name);
269
+ live.push(name);
261
270
  // A live record still occupies disk, so it counts toward the total even
262
271
  // though no rule may remove it.
263
272
  liveBytes += recordBytes(record.dir);
264
273
  continue;
265
274
  }
266
- result.bytesScanned += classified.bytes;
267
275
  candidates.push(classified);
268
276
  }
269
- result.bytesScanned += liveBytes;
270
277
 
271
278
  // Oldest first: the age rule, the count cap and the size cap all want that order.
272
279
  candidates.sort((left, right) => right.ageMs - left.ageMs);
273
- const removable = planRemovals(candidates, { keepRuns, maxAgeDays, maxBytes }, liveBytes);
280
+ const removable = planRemovals(candidates, policy, liveBytes);
281
+ const totalBytes = liveBytes + candidates.reduce((sum, candidate) => sum + candidate.bytes, 0);
282
+ return { root, policy, candidates, live, liveBytes, totalBytes, removable };
283
+ }
274
284
 
275
- for (const candidate of candidates) {
276
- if (!removable.has(candidate.runId)) {
285
+ export interface RetentionScan {
286
+ /** The record root that was read. */
287
+ root: string;
288
+ /** The policy the scan applied. */
289
+ policy: RetentionPolicy;
290
+ /** Run records this extension owns. */
291
+ total: number;
292
+ /** Run ids that can still produce a verdict, so no rule may remove them. */
293
+ live: string[];
294
+ /** Bytes held by every record. */
295
+ bytes: number;
296
+ /** Run ids the next prune would remove. */
297
+ removable: string[];
298
+ /** Age of the oldest record, or undefined when there is none. */
299
+ oldestAgeMs?: number;
300
+ }
301
+
302
+ /**
303
+ * What the next prune would do, without doing it.
304
+ *
305
+ * Retention used to be observable only through its own deletions: a session
306
+ * learned that a record was old enough by finding it gone. This answers the same
307
+ * question before the answer is permanent.
308
+ */
309
+ export function scanRetention(options: PruneOptions = {}): RetentionScan {
310
+ const plan = scan(options);
311
+ return {
312
+ root: plan.root,
313
+ policy: plan.policy,
314
+ total: plan.candidates.length + plan.live.length,
315
+ live: plan.live,
316
+ bytes: plan.totalBytes,
317
+ removable: plan.candidates.filter((candidate) => plan.removable.has(candidate.runId)).map((candidate) => candidate.runId),
318
+ // Candidates are ordered oldest first, so the head is the oldest.
319
+ oldestAgeMs: plan.candidates[0]?.ageMs,
320
+ };
321
+ }
322
+
323
+ /**
324
+ * Remove expired and surplus run records. Best effort: a directory that cannot
325
+ * be read or removed stays, and the next pass tries again.
326
+ */
327
+ export function pruneRunRecords(options: PruneOptions = {}): PruneResult {
328
+ const plan = scan(options);
329
+ const result: PruneResult = {
330
+ scanned: plan.candidates.length + plan.live.length,
331
+ removed: [],
332
+ live: plan.live,
333
+ kept: 0,
334
+ bytesFreed: 0,
335
+ bytesScanned: plan.totalBytes,
336
+ };
337
+ for (const candidate of plan.candidates) {
338
+ if (!plan.removable.has(candidate.runId)) {
339
+ result.kept += 1;
340
+ continue;
341
+ }
342
+ if (!releaseWorktree(plan.root, candidate.dir)) {
277
343
  result.kept += 1;
278
344
  continue;
279
345
  }
280
- releaseWorktree(root, candidate.dir);
281
346
  try {
282
347
  rmSync(candidate.dir, { recursive: true, force: true });
283
348
  result.removed.push(candidate.runId);
@@ -296,18 +361,51 @@ export function pruneRunRecords(options: PruneOptions = {}): PruneResult {
296
361
  * other leaves an orphan directory that `git worktree list` reports forever. A
297
362
  * path outside the record root is left alone: it is not ours to delete.
298
363
  */
299
- function releaseWorktree(root: string, dir: string): void {
300
- const outcome = value(readJson<OutcomeShape>(join(dir, "outcome.json")));
301
- const path = outcome?.worktree?.path;
302
- if (!path) return;
364
+ function releaseWorktree(root: string, dir: string): boolean {
365
+ const worktree = recordWorktree(dir);
366
+ const path = worktree?.path;
367
+ if (!path) return true;
303
368
  const worktreeRoot = resolve(root, "worktrees");
304
369
  const resolved = resolve(path);
305
- if (!resolved.startsWith(worktreeRoot + "/") && resolved !== worktreeRoot) return;
370
+ if (!resolved.startsWith(worktreeRoot + "/") && resolved !== worktreeRoot) return true;
371
+ if (!existsSync(resolved)) return true;
372
+ if (worktreeReferencedElsewhere(root, resolved, dir)) return true;
373
+ if (!worktree.repo || !worktree.branch) return false;
374
+ // A dirty tree, a missing repository, or a git failure all preserve both the
375
+ // checkout and its record. The only removal path is git's own clean-tree check.
376
+ return removeWorktree(worktree);
377
+ }
378
+
379
+ /**
380
+ * The checkout a record points at, from whichever file still has it.
381
+ *
382
+ * A run killed before it settled never wrote outcome.json, so spec.json is the
383
+ * only record of the checkout this process created. Reading outcome.json alone
384
+ * deleted that record and orphaned the checkout in `git worktree list` forever,
385
+ * taking the only pointer to any unmerged work with it.
386
+ */
387
+ function recordWorktree(dir: string): WorktreeRef | undefined {
388
+ const outcome = value(readJson<OutcomeShape>(join(dir, "outcome.json")));
389
+ if (outcome?.worktree) return outcome.worktree;
390
+ const spec = value(readJson<{ worktree?: WorktreeRef }>(join(dir, "spec.json")));
391
+ return spec?.worktree;
392
+ }
393
+
394
+ function worktreeReferencedElsewhere(root: string, path: string, excludedDir: string): boolean {
395
+ let names: string[];
306
396
  try {
307
- rmSync(resolved, { recursive: true, force: true });
397
+ names = readdirSync(root);
308
398
  } catch {
309
- // a checkout that cannot be removed is a directory, not a pruning failure
399
+ return true;
400
+ }
401
+ for (const name of names) {
402
+ if (!isRunId(name)) continue;
403
+ const dir = join(root, name);
404
+ if (dir === excludedDir) continue;
405
+ const worktree = recordWorktree(dir);
406
+ if (worktree?.path && resolve(worktree.path) === path) return true;
310
407
  }
408
+ return false;
311
409
  }
312
410
 
313
411
  /** Total bytes a record directory holds, for a caller that wants to report it. */