@henryqw/pi-subagent 27.12.0 → 27.13.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/README.md CHANGED
@@ -33,7 +33,8 @@ Commands, prompts, and UI are for you. Tools and the packaged skill are for Main
33
33
  | --- | --- | --- |
34
34
  | `/subagent` | command | Browse direct and isolated work, including requests whose parent checkout was removed. Stop direct workers, inspect isolated work, send follow-ups, or delete owned isolated worktrees after confirmation. **Select multiple…** applies one action to many rows. Without interactive UI, only reports. |
35
35
  | `/subagent roles` | command | List Role sources, resources, resolved model and thinking level, route errors, and file errors. Read-only; requires no Herdr pane. |
36
- | `/subagent prune` | command | Review remaining worker and integration branches and worktrees. Select the items to remove; merged items are selected first. Some blocked items can also be selected, after a separate confirmation. Requires a running Herdr server; without interactive UI, only reports. |
36
+ | `/subagent prune` | command | Start a background scan of leftover branches and worktrees. Run it again when ready to review and confirm removal. While busy, show progress. Requires a running Herdr server; without interactive UI, wait for the scan and only report. |
37
+ | `/subagent prune cancel` | command | Cancel the scan, ready plan, or cleanup. An active removal step can finish; completed removals are not undone. |
37
38
  | `/review [target] [focus]` | prompt | Tell Main to review a change with parallel `reviewer` tasks and give one ship verdict. See [Review a change](#review-a-change). |
38
39
  | `/subagent recover` | command | Classify interrupted isolated work in the canonical repository. Send Main request IDs, blockers, and next actions. Requires no UI or Herdr pane. |
39
40
  | `delegate_task` | tool | Start authorized shared-checkout work or a durable isolated checked graph. With `dryRun: true`, check the request and show the resolved plan without a launch. |
@@ -282,6 +283,10 @@ Unverified tab allocations retain evidence but offer no Close action. Reconcile
282
283
 
283
284
  After coordinator interruption, restart Pi and run `/subagent recover` in the canonical repository. Use `subagent_status` for exact evidence; never take over a live productive lease or replay uncertain prompts, merges, or promotion. See [Recover after interruption](./docs/orchestration.md#recover-after-interruption) and [Recovery and state](./docs/orchestration.md#recovery-and-state).
284
285
 
285
- Run `/subagent prune` for leftovers; merged items are selected first. Removing a checkout deletes its ignored files only after a separate confirmation naming those entries. If you select an item that an unfinished request owns, the command closes and deletes that whole request after its review and confirmation. **If you select unowned work with unique commits or changes, a separate confirmation permits its permanent deletion.** Uncertain resources, such as locked checkouts or checkouts that other Herdr panes use, cannot be selected. See [Prune leftover worktrees](./docs/orchestration.md#prune-leftover-worktrees) before removal.
286
+ Run `/subagent prune` to scan leftovers in the background. It inspects at most four candidates at once and never inspects the same checkout twice at once. When notified, run the command again to review the plan; no dialog opens automatically. All reviews and confirmations stay in the foreground. Confirmed cleanup runs in the background and removes items one at a time with fresh safety checks.
287
+
288
+ Use `/subagent prune cancel` to stop new removal steps. An active step can finish, and the report includes completed steps. Repeated commands while busy show progress, not another scan. A session or branch change, reload, or shutdown cancels the operation and clears its progress. Old plans and results do not appear in the new context.
289
+
290
+ In the review, merged items are selected first. Removing a checkout deletes its ignored files only after a separate confirmation naming those entries. If you select an item that an unfinished request owns, the command closes and deletes that whole request after its review and confirmation. **If you select unowned work with unique commits or changes, a separate confirmation permits its permanent deletion.** Uncertain resources, such as locked checkouts or checkouts that other Herdr panes use, cannot be selected. See [Prune leftover worktrees](./docs/orchestration.md#prune-leftover-worktrees) before removal.
286
291
 
287
292
  For aborted requests with retained resources, inspect status, resolve blockers, and repeat `subagent_abort` to reconcile cleanup without replaying work. Release rejected candidates and superseded generations explicitly. The extension never pushes, opens pull requests, publishes, deploys, or silently falls back to Main. It force-deletes recoverable work only after the user confirms **Close and delete worktrees (discard work)** in `/subagent` or a force removal in `/subagent prune`.
@@ -1,5 +1,5 @@
1
1
  export declare const DISPLAY_TEXT_CONTRACT: {
2
2
  readonly controlRanges: "\\u0000-\\u001F\\u007F-\\u009F";
3
- readonly pattern: "^(?![\\s\\S]*[\\u0000-\\u001F\\u007F-\\u009F])[\\s\\S]+$";
3
+ readonly pattern: "^[^\\u0000-\\u001F\\u007F-\\u009F]+$";
4
4
  };
5
5
  export declare function hasDisplayControlCharacters(value: string): boolean;
@@ -1,7 +1,7 @@
1
1
  const C0_C1_CONTROL_RANGES = "\\u0000-\\u001F\\u007F-\\u009F";
2
2
  export const DISPLAY_TEXT_CONTRACT = {
3
3
  controlRanges: C0_C1_CONTROL_RANGES,
4
- pattern: `^(?![\\s\\S]*[${C0_C1_CONTROL_RANGES}])[\\s\\S]+$`,
4
+ pattern: `^[^${C0_C1_CONTROL_RANGES}]+$`,
5
5
  };
6
6
  const DISPLAY_TEXT_CONTROL_PATTERN = new RegExp(`[${DISPLAY_TEXT_CONTRACT.controlRanges}]`, "u");
7
7
  export function hasDisplayControlCharacters(value) {
package/dist/prune.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type GitRunner } from "./git-process.ts";
2
+ export type PruneProgress = (completed: number, total: number) => void;
2
3
  /** Blockers that a separately confirmed force removal of an unowned item may override; every other kind is hard. */
3
4
  export declare const FORCEABLE_PRUNE_BLOCKERS: readonly ["unmerged", "changes", "operation", "submodules"];
4
5
  export type PruneBlockerKind = typeof FORCEABLE_PRUNE_BLOCKERS[number] | "owner" | "lease" | "hard";
@@ -49,8 +50,9 @@ export interface PruneGuards {
49
50
  paneId: string;
50
51
  cwds: readonly string[];
51
52
  }[]>;
52
- /** The confirming session still owns the command; checked immediately before each removal step. */
53
+ /** The command is not cancelled and its session is current; checked before each candidate and removal step. */
53
54
  current?(): boolean;
55
+ progress?: PruneProgress;
54
56
  }
55
57
  export type PruneRemoval = {
56
58
  outcome: "removed" | "skipped" | "failed";
@@ -70,9 +72,8 @@ export declare function inspectPruneCandidates(root: string, mainCwd: string, gu
70
72
  * Re-verify each reviewed prunable item immediately before removing its checkout, then delete its
71
73
  * branch only at the reviewed tip. Ignored entries are deleted only when `allowIgnored` and all of
72
74
  * them were in the review. With `force`, a reviewed forceable item is removed with `--force` while
73
- * every fresh blocker is forceable and of a reviewed kind. Returns the repository checkouts that still exist.
75
+ * every fresh blocker is forceable and of a reviewed kind. Cancellation keeps completed outcomes.
74
76
  */
75
77
  export declare function removePruneCandidates(root: string, mainCwd: string, reviewed: readonly PruneItem[], allowIgnored: boolean, force: boolean, guards: PruneGuards, run?: GitRunner): Promise<{
76
78
  removals: PruneRemoval[];
77
- checkouts: string[];
78
79
  }>;
package/dist/prune.js CHANGED
@@ -5,6 +5,7 @@ import { runGit } from "./git-process.js";
5
5
  import { runProcess } from "./process.js";
6
6
  import { inspectWorktreeDirty, OWNED_BRANCH_PATTERN, WORKTREES_DIRNAME } from "./worktree.js";
7
7
  const HERDR_TIMEOUT_MS = 30_000;
8
+ const INSPECTION_CONCURRENCY = 4;
8
9
  const IN_PROGRESS_MARKERS = ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "REBASE_HEAD", "BISECT_LOG", "rebase-merge", "rebase-apply", "sequencer"];
9
10
  /** Blockers that a separately confirmed force removal of an unowned item may override; every other kind is hard. */
10
11
  export const FORCEABLE_PRUNE_BLOCKERS = ["unmerged", "changes", "operation", "submodules"];
@@ -58,12 +59,16 @@ async function snapshot(root, mainCwd, run) {
58
59
  }
59
60
  return { primary: checkouts[0].path, checkouts, branches, targets };
60
61
  }
62
+ function candidateCheckout(snap, branch) {
63
+ const ownedPath = join(snap.primary, WORKTREES_DIRNAME, basename(branch));
64
+ // A detached or switched owned checkout no longer names the branch; find it by its owned path too.
65
+ return snap.checkouts.find((item) => item.branch === branch) ?? snap.checkouts.find((item) => item.path === ownedPath);
66
+ }
61
67
  async function classify(snap, branch, mainCwd, ownership, panes, run, root) {
62
68
  const tip = snap.branches.get(branch);
63
69
  const name = basename(branch);
64
70
  const ownedPath = join(snap.primary, WORKTREES_DIRNAME, name);
65
- // A detached or switched owned checkout no longer names the branch; find it by its owned path too.
66
- const checkout = snap.checkouts.find((item) => item.branch === branch) ?? snap.checkouts.find((item) => item.path === ownedPath);
71
+ const checkout = candidateCheckout(snap, branch);
67
72
  const blockers = [];
68
73
  const block = (kind, text) => blockers.push({ kind, text });
69
74
  if (checkout && checkout.branch !== branch)
@@ -146,9 +151,42 @@ async function evidence(root, mainCwd, guards, run) {
146
151
  /** Read-only review of every pi-subagent worker or integration branch and its checkout. */
147
152
  export async function inspectPruneCandidates(root, mainCwd, guards, run = runGit) {
148
153
  const { snap, ownership, panes } = await evidence(root, mainCwd, guards, run);
149
- const items = [];
150
- for (const branch of [...snap.branches.keys()].sort())
151
- items.push(await classify(snap, branch, mainCwd, ownership, panes, run, root));
154
+ const branches = [...snap.branches.keys()].sort();
155
+ const groups = new Map();
156
+ for (const [index, branch] of branches.entries()) {
157
+ const checkout = candidateCheckout(snap, branch);
158
+ // Git inspection refreshes the index. Aliases and owned-path fallbacks must share one worker.
159
+ const key = checkout && !checkout.missing && existsSync(checkout.path) ? realpathSync.native(checkout.path) : branch;
160
+ const group = groups.get(key) ?? [];
161
+ group.push(index);
162
+ groups.set(key, group);
163
+ }
164
+ const pending = [...groups.values()];
165
+ const items = new Array(branches.length);
166
+ let next = 0, completed = 0, failed = false;
167
+ guards.progress?.(0, branches.length);
168
+ const workers = await Promise.allSettled(Array.from({ length: Math.min(INSPECTION_CONCURRENCY, pending.length) }, async () => {
169
+ try {
170
+ while (next < pending.length && !failed) {
171
+ for (const index of pending[next++]) {
172
+ if (failed)
173
+ return;
174
+ if (guards.current && !guards.current())
175
+ throw new Error("Prune scan cancelled or session changed.");
176
+ items[index] = await classify(snap, branches[index], mainCwd, ownership, panes, run, root);
177
+ guards.progress?.(++completed, branches.length);
178
+ }
179
+ }
180
+ }
181
+ catch (error) {
182
+ failed = true;
183
+ throw error;
184
+ }
185
+ }));
186
+ // Do not release this scan while another worker can still inspect an index.
187
+ for (const worker of workers)
188
+ if (worker.status === "rejected")
189
+ throw worker.reason;
152
190
  return items;
153
191
  }
154
192
  async function removeOne(root, mainCwd, reviewed, allowIgnored, force, guards, run) {
@@ -170,7 +208,7 @@ async function removeOne(root, mainCwd, reviewed, allowIgnored, force, guards, r
170
208
  const stale = () => guards.current !== undefined && !guards.current();
171
209
  if (fresh.path) {
172
210
  if (stale())
173
- return skip("session or branch changed before removal; reopen /subagent prune");
211
+ return skip("prune cancelled or session or branch changed before removal; reopen /subagent prune");
174
212
  // Git removes ignored content without --force; the checks above approved it. Force also deletes reviewed changes.
175
213
  const removed = await run(["worktree", "remove", ...(forced ? ["--force"] : []), fresh.path], root);
176
214
  if (removed.code !== 0)
@@ -179,27 +217,37 @@ async function removeOne(root, mainCwd, reviewed, allowIgnored, force, guards, r
179
217
  return fail("git worktree remove succeeded but the checkout remains");
180
218
  }
181
219
  if (stale())
182
- return skip(`${fresh.path ? "checkout removed; " : ""}session or branch changed before branch deletion; branch kept`);
183
- const deleted = await run(["update-ref", "-d", `refs/heads/${reviewed.branch}`, reviewed.tip], root);
184
- if (deleted.code !== 0)
185
- return fail(`${fresh.path ? "checkout removed; " : ""}branch kept: ${deleted.stderr.trim().slice(0, 200)}`);
186
- return { outcome: "removed", item: reviewed, reason: fresh.reason };
220
+ return skip(`${fresh.path ? "checkout removed; " : ""}prune cancelled or session or branch changed before branch deletion; branch kept`);
221
+ try {
222
+ const deleted = await run(["update-ref", "-d", `refs/heads/${reviewed.branch}`, reviewed.tip], root);
223
+ if (deleted.code !== 0)
224
+ return fail(`${fresh.path ? "checkout removed; " : ""}branch kept: ${deleted.stderr.trim().slice(0, 200)}`);
225
+ return { outcome: "removed", item: reviewed, reason: fresh.reason };
226
+ }
227
+ catch (error) {
228
+ return fail(`${fresh.path ? "checkout removed; " : ""}branch deletion not verified: ${String(error).slice(0, 200)}`);
229
+ }
187
230
  }
188
231
  /**
189
232
  * Re-verify each reviewed prunable item immediately before removing its checkout, then delete its
190
233
  * branch only at the reviewed tip. Ignored entries are deleted only when `allowIgnored` and all of
191
234
  * them were in the review. With `force`, a reviewed forceable item is removed with `--force` while
192
- * every fresh blocker is forceable and of a reviewed kind. Returns the repository checkouts that still exist.
235
+ * every fresh blocker is forceable and of a reviewed kind. Cancellation keeps completed outcomes.
193
236
  */
194
237
  export async function removePruneCandidates(root, mainCwd, reviewed, allowIgnored, force, guards, run = runGit) {
195
238
  const removals = [];
239
+ guards.progress?.(0, reviewed.length);
196
240
  for (const item of reviewed) {
197
- try {
198
- removals.push(await removeOne(root, mainCwd, item, allowIgnored, force, guards, run));
199
- }
200
- catch (error) {
201
- removals.push({ outcome: "failed", item, reason: (error instanceof Error ? error.message : String(error)).slice(0, 300) });
202
- }
241
+ if (guards.current && !guards.current())
242
+ removals.push({ outcome: "skipped", item, reason: "prune cancelled or session changed before removal; reopen /subagent prune" });
243
+ else
244
+ try {
245
+ removals.push(await removeOne(root, mainCwd, item, allowIgnored, force, guards, run));
246
+ }
247
+ catch (error) {
248
+ removals.push({ outcome: "failed", item, reason: (error instanceof Error ? error.message : String(error)).slice(0, 300) });
249
+ }
250
+ guards.progress?.(removals.length, reviewed.length);
203
251
  }
204
- return { removals, checkouts: existing(await snapshot(root, mainCwd, run)) };
252
+ return { removals };
205
253
  }
package/dist/runner.d.ts CHANGED
@@ -344,8 +344,6 @@ export declare class IsolatedRunner {
344
344
  * A non-terminal state owns every resource name its saved text mentions; an unreadable state owns every
345
345
  * name its raw text mentions, or every name when unreadable. */
346
346
  pruneOwnership(checkouts: readonly string[]): Promise<PruneOwnership>;
347
- /** After pruning, reconcile aborted requests that recorded a removed resource through the guarded abort path. */
348
- reconcilePrunedAborts(checkouts: readonly string[], names: readonly string[]): Promise<string[]>;
349
347
  canFollowup(root: string, requestId: string, taskId: string): boolean;
350
348
  drainFollowups(root: string, requestId: string, taskId: string): string[];
351
349
  queueFollowup(root: string, requestId: string, taskId: string, instruction: string): string;
package/dist/runner.js CHANGED
@@ -714,30 +714,6 @@ export class IsolatedRunner {
714
714
  return { ...(lease ? { lease } : {}), owners: (name) => owners.filter(({ text }) => text === undefined || text.includes(name))
715
715
  .map(({ label, request }) => ({ label, ...(request ? { request } : {}) })) };
716
716
  }
717
- /** After pruning, reconcile aborted requests that recorded a removed resource through the guarded abort path. */
718
- async reconcilePrunedAborts(checkouts, names) {
719
- const lines = [];
720
- for (const checkout of checkouts) {
721
- const root = realpathSync.native(checkout);
722
- const { requests, states } = await this.listRequests(root);
723
- for (const [index, state] of states.entries()) {
724
- const id = state.request.id;
725
- const text = JSON.stringify(state);
726
- if (requests[index].status !== "aborted · retained" || !names.some((name) => text.includes(name)))
727
- continue;
728
- try {
729
- await this.abort(id, root);
730
- const after = (await this.listRequests(root)).requests.find((request) => request.id === id);
731
- lines.push(after?.status === "aborted" ? `Reconciled cleanup of aborted request ${id}.`
732
- : `Aborted request ${id} still has pending cleanup; inspect subagent_status.`);
733
- }
734
- catch (error) {
735
- lines.push(`Aborted request ${id} could not be reconciled: ${errorText(error)}`);
736
- }
737
- }
738
- }
739
- return lines;
740
- }
741
717
  canFollowup(root, requestId, taskId) {
742
718
  const active = this.activeControl(realpathSync.native(root), requestId, taskId);
743
719
  return active !== undefined && active.task.status === "working" && !active.control.isSealed;
@@ -1856,7 +1832,7 @@ export class IsolatedRunner {
1856
1832
  delete generation.review;
1857
1833
  }
1858
1834
  await handle.save();
1859
- await this.closeDiscardResource(handle, resource, verify);
1835
+ await this.closeDiscardResource(handle, resource, verify, checked.current);
1860
1836
  });
1861
1837
  for (const candidate of state.integration.candidates) {
1862
1838
  const task = changesetTaskState(state, candidate.taskId);
@@ -1874,10 +1850,10 @@ export class IsolatedRunner {
1874
1850
  return removals;
1875
1851
  });
1876
1852
  }
1877
- async terminateAbortedAttempt(handle, task, attempt, signal, deadline = this.coordinatorRuntime.now() + TERMINATION_SAFETY_BUDGET_MS) {
1853
+ async terminateAbortedAttempt(handle, task, attempt, signal, deadline = this.coordinatorRuntime.now() + TERMINATION_SAFETY_BUDGET_MS, current) {
1878
1854
  if (!allocationByKind(attempt, "agent")?.agentName || attempt.termination?.status === "terminated")
1879
1855
  return;
1880
- await this.proveTermination(handle, task, attempt, this.terminationCandidate(attempt), async () => await handle.save(), signal, deadline);
1856
+ await this.proveTermination(handle, task, attempt, this.terminationCandidate(attempt), async () => await handle.save(), signal, deadline, current);
1881
1857
  }
1882
1858
  async cleanupAbortedHost(handle, task, attempt, kind, scope) {
1883
1859
  const result = await scope.call((context) => this.hostRuntime.cleanupHost({
@@ -1886,12 +1862,12 @@ export class IsolatedRunner {
1886
1862
  if (result.outcome === "blocked")
1887
1863
  throw new Error(result.failure);
1888
1864
  }
1889
- async closeDiscardResource(handle, resource, verify) {
1865
+ async closeDiscardResource(handle, resource, verify, current) {
1890
1866
  const { task, attempt } = resource;
1891
1867
  if (!task || !attempt)
1892
1868
  return;
1893
1869
  await verify();
1894
- await this.terminateAbortedAttempt(handle, task, attempt);
1870
+ await this.terminateAbortedAttempt(handle, task, attempt, undefined, undefined, current);
1895
1871
  if (allocationByKind(attempt, "agent") && attempt.termination?.status !== "terminated")
1896
1872
  throw new Error("Worker termination remains unproved.");
1897
1873
  const scope = new DeadlineScope(this.coordinatorRuntime.now() + CLEANUP_SAFETY_BUDGET_MS, () => this.coordinatorRuntime.now());
@@ -2746,7 +2722,7 @@ export class IsolatedRunner {
2746
2722
  * Proves exact worker termination without replay. Reconciliation records a worker that is already gone;
2747
2723
  * only an observed live worker without saved termination intent is closed.
2748
2724
  */
2749
- async proveTermination(handle, task, attempt, candidate, save, signal, deadline = this.coordinatorRuntime.now() + TERMINATION_SAFETY_BUDGET_MS) {
2725
+ async proveTermination(handle, task, attempt, candidate, save, signal, deadline = this.coordinatorRuntime.now() + TERMINATION_SAFETY_BUDGET_MS, current) {
2750
2726
  if (attempt.termination?.status === "terminated")
2751
2727
  return;
2752
2728
  const workerId = attempt.termination?.workerId ?? allocationByKind(attempt, "agent")?.agentName;
@@ -2758,8 +2734,15 @@ export class IsolatedRunner {
2758
2734
  try {
2759
2735
  let result = await safety.call((context) => this.hostRuntime.reconcileWorkerTermination(input, context));
2760
2736
  if (result.outcome === "active" && !attempt.termination) {
2737
+ if (current && !current())
2738
+ throw new Error("Session changed; reopen /subagent.");
2761
2739
  attempt.termination = { status: "terminating", workerId, candidate: input.candidate };
2762
2740
  await save(); // Intent before the exact pane close.
2741
+ if (current && !current()) {
2742
+ // No close started. Clear this intent so a later discard can try again.
2743
+ delete attempt.termination;
2744
+ throw new Error("Session changed; reopen /subagent.");
2745
+ }
2763
2746
  result = await safety.call((context) => this.hostRuntime.terminateWorker(input, context));
2764
2747
  }
2765
2748
  if (result.outcome !== "terminated") {
@@ -418,7 +418,15 @@ The report lists removed, skipped, and failed resources. After complete cleanup,
418
418
 
419
419
  ### Prune leftover worktrees
420
420
 
421
- Run `/subagent prune` to clean up leftover worker and integration checkouts under `.worktrees/`. Their branches have the name `pi-subagent/subagent-<name>-<24hex>`, or the saved legacy name `pi-subagent/subagent-<24hex>`. The command also cleans up such branches that have no checkout. The review starts with the number of removable and blocked items. It groups the items by the exact reason that the command can remove them, or by their exact blockers, and shows each reason once. Under each reason, it shows the readable name, if present, and the first 8 characters of the identity suffix. The command can remove an item only when all of these conditions are true:
421
+ Run `/subagent prune` to scan leftover worker and integration checkouts under `.worktrees/`. In interactive mode, the command starts a background scan, shows progress, and returns without waiting. It inspects at most four candidates at once. Candidates that share one checkout, including path aliases, are inspected one at a time. The results stay sorted and include every blocker.
422
+
423
+ When the scan is ready, the command sends a notification. It does not open a dialog. Run `/subagent prune` again to review that plan. Repeated commands during a scan, review, or cleanup show its status; they do not start another operation. All selection and confirmation dialogs stay in the foreground, including the review of whole owning requests. After confirmation, cleanup runs in the background. It removes items one at a time and reports removed, skipped, and failed items.
424
+
425
+ Use `/subagent prune cancel` to cancel a scan, ready plan, or cleanup. Cancellation stops new removal steps. An active step can finish; completed removals are not undone. The final cleanup report includes completed steps and partial removal, such as a removed checkout whose branch was kept. Wait for the active step to finish before starting another scan.
426
+
427
+ Each operation belongs to its launching session and branch generation. A session or branch change, reload, or shutdown cancels it and clears progress. Old plans, notifications, and reports are not delivered to the new context. Runtime shutdown waits for active background steps to finish, so a replacement runtime cannot inspect the same index at the same time. Plans are not saved across reloads.
428
+
429
+ Candidate branches have the name `pi-subagent/subagent-<name>-<24hex>`, or the saved legacy name `pi-subagent/subagent-<24hex>`. The command also cleans up such branches that have no checkout. The review starts with the number of removable and blocked items. It groups the items by the exact reason that the command can remove them, or by their exact blockers, and shows each reason once. Under each reason, it shows the readable name, if present, and the first 8 characters of the identity suffix. The command can remove an item only when all of these conditions are true:
422
430
 
423
431
  - Its branch tip is already in Main's HEAD or in the local `origin` default-branch ref. The command does not fetch.
424
432
  - Its checkout has no tracked or untracked changes. No merge, rebase, cherry-pick, revert, or bisect is in progress.
@@ -441,9 +449,9 @@ If a top-level ignored entry is new or changed, the command skips the checkout.
441
449
 
442
450
  The list shows removable items first. The command never cuts a long list silently. The list ends with `+N more not shown`, where `N` counts items, and the command does not remove the items that it did not show in that run. Run `/subagent prune` again to review them.
443
451
 
444
- The command checks each item again immediately before removal and skips an item that changed. If the session or branch changes during removal, the command skips the remaining steps. The command deletes a branch only if the branch still points at the reviewed tip. Then the command reconciles each aborted request that recorded a removed resource. It uses the same guarded path as a repeated `subagent_abort`, so the cleanup of that request no longer shows as pending.
452
+ The command checks each item again immediately before removal and skips an item that changed. It checks ownership, the productive lease, Herdr panes, checkout state, the branch tip, ignored entries, and the launching session. The command deletes a branch only if it still points at the reviewed tip. It does not run automatic request-abort cleanup, because that separate workflow can remove other resources. If an aborted request still shows retained resources, inspect `subagent_status` and repeat `subagent_abort` to reconcile its saved cleanup state.
445
453
 
446
- The report lists removed, skipped, and failed items, and each request that the command could not reconcile. Without interactive UI, the command only reports.
454
+ Without interactive UI, the command waits for the scan and only reports. It never removes items in this mode.
447
455
 
448
456
  A non-regular or unreadable state entry can block every item because its resource ownership is unknown. State files never change directly.
449
457
 
@@ -12,7 +12,7 @@ import {
12
12
  type DirectProcessRunner,
13
13
  } from "../dist/git-runtime.js";
14
14
  import { HerdrHostRuntime } from "../dist/herdr-runtime.js";
15
- import { inspectPruneCandidates, listHerdrPanes, removePruneCandidates, type PruneGuards, type PruneItem } from "../dist/prune.js";
15
+ import { inspectPruneCandidates, listHerdrPanes, removePruneCandidates, type PruneGuards, type PruneItem, type PruneProgress } from "../dist/prune.js";
16
16
  import { runProcess as directRunProcess } from "../dist/process.js";
17
17
  import { RoleLaunchRuntime, type LaunchRuntimeOptions } from "../dist/launch-runtime.js";
18
18
  import { IsolatedRunner, nextIntegrationAction, type ExecutePlan, type OperationContext, type RunResponse } from "../dist/runner.js";
@@ -520,10 +520,10 @@ export interface IsolatedSurface {
520
520
  execute(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof toolResult>>;
521
521
  inventory(cwd: string, current?: () => boolean): Promise<IsolatedInventory>;
522
522
  recover(cwd: string): Promise<string>;
523
- prunePlan(cwd: string): Promise<PrunePlan>;
523
+ prunePlan(cwd: string, current?: () => boolean, progress?: PruneProgress): Promise<PrunePlan>;
524
524
  discardPlan(cwd: string, request: IsolatedRequest): Promise<DiscardPlan>;
525
525
  discard(cwd: string, plan: DiscardPlan, current: () => boolean): Promise<CleanupReport>;
526
- prune(cwd: string, items: readonly PruneItem[], allowIgnored: boolean, force: boolean, current: () => boolean): Promise<CleanupReport>;
526
+ prune(cwd: string, items: readonly PruneItem[], allowIgnored: boolean, force: boolean, current: () => boolean, progress?: PruneProgress): Promise<CleanupReport>;
527
527
  inspect(root: string, requestId: string): Promise<readonly string[]>;
528
528
  canFollowup(root: string, requestId: string, taskId: string): boolean;
529
529
  enqueue(root: string, requestId: string, taskId: string, text: string, current: () => boolean): string;
@@ -549,6 +549,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
549
549
  const stateListeners = new Set<(state: RunState) => void>();
550
550
  const activeJobs = new Set<AbortController>();
551
551
  const jobOwners = new Map<string, { canDeliver(): boolean; pendingResult(): boolean }>();
552
+ const discardDeliveries = new Map<string, () => boolean>();
552
553
  let sessionEpoch = 0;
553
554
  let sessionClosed = false;
554
555
 
@@ -570,8 +571,10 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
570
571
  onStateSaved: (state) => {
571
572
  savedRevision += 1;
572
573
  for (const listener of stateListeners) listener(state);
573
- const owner = jobOwners.get(`${state.root}\0${state.request.id}`);
574
- if (!sessionClosed && (owner === undefined || owner.canDeliver())) {
574
+ const key = `${state.root}\0${state.request.id}`;
575
+ const owner = jobOwners.get(key);
576
+ const discardCurrent = discardDeliveries.get(key);
577
+ if (!sessionClosed && (owner === undefined || owner.canDeliver()) && (discardCurrent === undefined || discardCurrent())) {
575
578
  updateWorkspaceWidgetSafely(latestContext(), state, workspaceRowsByRequest);
576
579
  }
577
580
  },
@@ -888,32 +891,39 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
888
891
  },
889
892
  async discard(cwd, plan, current) {
890
893
  requireCurrent(current);
891
- const removals = await getComponents().runner.discard(cwd, plan, {
892
- panes: () => listHerdrPanes(cwd), current: () => current() && !sessionClosed,
893
- blocked: async () => jobOwners.has(`${plan.root}\0${plan.requestId}`) ? "A local job is active for this request." : undefined,
894
- });
895
- const count = (outcome: string) => removals.filter((item) => item.outcome === outcome).length;
896
- return { failed: count("failed"), skipped: count("skipped"), text: boundedReport([`Close and delete ${plan.requestId}:`,
897
- ...removals.map((item) => `${item.outcome}: ${item.key}: ${item.reason}`),
898
- ], "removal report lines omitted; reopen /subagent to inspect retained resources.") };
894
+ const key = `${plan.root}\0${plan.requestId}`;
895
+ const epoch = sessionEpoch;
896
+ const canDeliver = () => current() && !sessionClosed && sessionEpoch === epoch;
897
+ discardDeliveries.set(key, canDeliver);
898
+ try {
899
+ const removals = await getComponents().runner.discard(cwd, plan, {
900
+ panes: () => listHerdrPanes(cwd), current: canDeliver,
901
+ blocked: async () => jobOwners.has(key) ? "A local job is active for this request." : undefined,
902
+ });
903
+ const count = (outcome: string) => removals.filter((item) => item.outcome === outcome).length;
904
+ return { failed: count("failed"), skipped: count("skipped"), text: boundedReport([`Close and delete ${plan.requestId}:`,
905
+ ...removals.map((item) => `${item.outcome}: ${item.key}: ${item.reason}`),
906
+ ], "removal report lines omitted; reopen /subagent to inspect retained resources.") };
907
+ } finally {
908
+ if (discardDeliveries.get(key) === canDeliver) discardDeliveries.delete(key);
909
+ }
899
910
  },
900
- async prunePlan(cwd) {
911
+ async prunePlan(cwd, current, progress) {
901
912
  const root = await lookupRoot(cwd);
902
- return { root, items: await inspectPruneCandidates(root, cwd, pruneGuards(root)) };
913
+ return { root, items: await inspectPruneCandidates(root, cwd, { ...pruneGuards(root), current, progress }) };
903
914
  },
904
- async prune(cwd, items, allowIgnored, force, current) {
915
+ async prune(cwd, items, allowIgnored, force, current, progress) {
905
916
  requireCurrent(current);
906
917
  const root = await lookupRoot(cwd);
907
- const { removals, checkouts } = await removePruneCandidates(root, cwd, items, allowIgnored, force,
908
- { ...pruneGuards(root), current: () => current() && !sessionClosed });
918
+ const { removals } = await removePruneCandidates(root, cwd, items, allowIgnored, force,
919
+ { ...pruneGuards(root), current: () => current() && !sessionClosed, progress });
909
920
  const removed = removals.filter(({ outcome }) => outcome === "removed");
910
- const reconciled = removed.length
911
- ? await getComponents().runner.reconcilePrunedAborts(checkouts, removed.map(({ item }) => basename(item.branch))) : [];
912
921
  const count = (outcome: string) => removals.filter((item) => item.outcome === outcome).length;
913
- return { failed: count("failed"), skipped: count("skipped"), text: boundedReport([
914
- `Pi Subagent prune in ${root}: ${removed.length} removed, ${count("skipped")} skipped, ${count("failed")} failed.`,
922
+ const failed = count("failed");
923
+ return { failed, skipped: count("skipped"), text: boundedReport([
924
+ `Pi Subagent prune in ${root}: ${removed.length} removed, ${count("skipped")} skipped, ${failed} failed.`,
915
925
  ...removals.map(({ outcome, item, reason }) => `${outcome}: ${item.path ?? "(no checkout)"} · ${item.branch} · ${reason}`),
916
- ...reconciled,
926
+ ...(removed.length ? ["If an aborted request still shows retained resources, inspect subagent_status and repeat subagent_abort to reconcile cleanup."] : []),
917
927
  ], "prune report lines omitted.") };
918
928
  },
919
929
  async inspect(root, requestId) {
@@ -1,7 +1,7 @@
1
1
  import { getMarkdownTheme, getSelectListTheme, keyHint, keyText, type ExtensionAPI, type ExtensionContext, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import { Box, Markdown, SelectList, Spacer, Text, truncateToWidth } from "@earendil-works/pi-tui";
3
3
  import type { DiscardPlan } from "../dist/discard.js";
4
- import type { PruneItem } from "../dist/prune.js";
4
+ import type { PruneItem, PruneProgress } from "../dist/prune.js";
5
5
  import { TERMINAL_RUN_STATUSES } from "../dist/schema.js";
6
6
  import { compactCost } from "./result-transport.ts";
7
7
 
@@ -78,11 +78,11 @@ export interface SubagentCommandAdapter {
78
78
  isolated(cwd: string, current: () => boolean): Promise<IsolatedInventory>;
79
79
  recover(cwd: string): Promise<string>;
80
80
  /** Read-only review of pi-subagent worktrees and branches in the canonical repository. */
81
- prunePlan(cwd: string): Promise<PrunePlan>;
81
+ prunePlan(cwd: string, current?: () => boolean, progress?: PruneProgress): Promise<PrunePlan>;
82
82
  discardPlan(cwd: string, request: IsolatedRequest): Promise<DiscardPlan>;
83
83
  discard(cwd: string, plan: DiscardPlan, current: () => boolean): Promise<CleanupReport>;
84
84
  /** Re-verify and remove reviewed prunable items, and with `force` reviewed forceable items; returns a bounded report. */
85
- prune(cwd: string, items: readonly PruneItem[], allowIgnored: boolean, force: boolean, current: () => boolean): Promise<CleanupReport>;
85
+ prune(cwd: string, items: readonly PruneItem[], allowIgnored: boolean, force: boolean, current: () => boolean, progress?: PruneProgress): Promise<CleanupReport>;
86
86
  /** Read-only Role catalog report with routes and per-file load errors. */
87
87
  roles(ctx: ExtensionContext): RolesReport;
88
88
  inspectInTab(root: string, requestId: string, ctx: ExtensionContext, current: () => boolean): Promise<{ ref: string; tabId: string; name: string; sessionFile: string }>;
@@ -396,7 +396,8 @@ const pruneLabel = (item: PruneItem) => item.override === "discard"
396
396
  ? [`${shortId(item)} · delete whole request ${item.owner!.id} (${item.owner!.status})`, ...item.blockers.filter(({ kind }) => kind !== "owner").map(({ text }) => text)].join(" · ")
397
397
  : `${shortId(item)} · ${item.prunable ? "" : "force · "}${item.reason}`;
398
398
 
399
- export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentCommandAdapter): void {
399
+ /** Returns the shutdown wait; call it after the runtime has invalidated its other task owners. */
400
+ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentCommandAdapter): () => Promise<void> | undefined {
400
401
  pi.registerEntryRenderer<Report>(REPORT_ENTRY, (entry, _options, theme) => entry.data && reportComponent(entry.data, theme, 1));
401
402
  pi.registerMessageRenderer(RECOVERY_MESSAGE, (message, { outputPad }, theme) => reportComponent(textReport("info", typeof message.content === "string"
402
403
  ? message.content : message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n"), "Recovery report"), theme, outputPad));
@@ -407,11 +408,43 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
407
408
  if (ctx.hasUI) ctx.ui.notify(text, LEVEL[report.tone]);
408
409
  else pi.sendMessage({ customType, content: text, display: true });
409
410
  };
411
+ type PruneJob = {
412
+ ctx: ExtensionContext; current: () => boolean; cancelled: boolean; status: string; indicator: boolean;
413
+ settled?: Promise<void>;
414
+ state: { kind: "scanning" | "reviewing" | "removing" } | { kind: "ready"; plan: PrunePlan };
415
+ };
416
+ let pruneJob: PruneJob | undefined;
417
+ let generation = 0;
418
+ const clearPruneStatus = (job: PruneJob) => {
419
+ if (job.indicator) job.ctx.ui.setStatus("subagent-prune", undefined);
420
+ job.indicator = false;
421
+ };
422
+ const clearPrune = (job: PruneJob) => {
423
+ if (pruneJob !== job) return;
424
+ clearPruneStatus(job);
425
+ pruneJob = undefined;
426
+ };
427
+ const pruneStatus = (job: PruneJob, status: string) => {
428
+ job.status = status;
429
+ if (job.current() && !job.cancelled && job.ctx.hasUI) {
430
+ job.indicator = true;
431
+ job.ctx.ui.setStatus("subagent-prune", `● ${status}`);
432
+ }
433
+ };
434
+ const cancelPrune = (job: PruneJob) => {
435
+ job.cancelled = true;
436
+ clearPruneStatus(job);
437
+ if (job.state.kind === "ready") clearPrune(job);
438
+ };
439
+ const invalidatePrune = () => { generation++; if (pruneJob) cancelPrune(pruneJob); };
440
+ pi.on("session_start", invalidatePrune);
441
+ pi.on("session_shutdown", invalidatePrune);
442
+ pi.on("session_tree", invalidatePrune);
410
443
  pi.registerCommand("subagent", {
411
- description: "Inspect direct and isolated work, list Roles with /subagent roles, recover orphaned isolated requests with /subagent recover, or remove merged leftover worktrees with /subagent prune",
444
+ description: "Inspect direct and isolated work, list Roles with /subagent roles, recover with /subagent recover, or scan/review leftovers with /subagent prune (stop with /subagent prune cancel)",
412
445
  handler: async (args, ctx) => {
413
446
  const command = args.trim();
414
- if (command && !["prune", "recover", "roles"].includes(command)) throw new Error("Usage: /subagent [prune|recover|roles]");
447
+ if (command && !["prune", "prune cancel", "recover", "roles"].includes(command)) throw new Error("Usage: /subagent [prune [cancel]|recover|roles]");
415
448
  if (command === "roles") {
416
449
  deliver(ctx, rolesReport(adapter.roles(ctx)), "pi-subagent-roles");
417
450
  return;
@@ -425,8 +458,9 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
425
458
  // already existed when it opened must not retarget its pending actions.
426
459
  const existing = new Set(manager.getEntries().map((entry) => entry.id));
427
460
  const epoch = adapter.epoch();
428
- const current = () => {
429
- if (adapter.epoch() !== epoch || manager.getSessionId() !== session || manager.getSessionFile() !== file) return false;
461
+ const launched = generation;
462
+ let current = () => {
463
+ if (generation !== launched || adapter.epoch() !== epoch || manager.getSessionId() !== session || manager.getSessionFile() !== file) return false;
430
464
  const now = manager.getBranch();
431
465
  return now.length >= branch.length && branch.every((id, index) => now[index]?.id === id)
432
466
  && now.slice(branch.length).every((entry) => !existing.has(entry.id));
@@ -438,36 +472,82 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
438
472
  { triggerTurn: true, deliverAs: "followUp" });
439
473
  return;
440
474
  }
475
+ if (command === "prune" || command === "prune cancel") {
476
+ const notify = (message: string) => ctx.hasUI ? ctx.ui.notify(message, "info") : deliver(ctx, textReport("info", message));
477
+ if (pruneJob && !pruneJob.current()) cancelPrune(pruneJob);
478
+ if (command === "prune cancel") {
479
+ const job = pruneJob;
480
+ if (job) cancelPrune(job);
481
+ notify(job ? "Prune cancelled. An active step can finish; completed removals are not undone." : "No prune operation is active.");
482
+ return;
483
+ }
484
+ if (pruneJob && pruneJob.state.kind !== "ready") {
485
+ notify(pruneJob.cancelled ? "Prune is stopping; wait for the active step." : `${pruneJob.status}. Use /subagent prune cancel to stop.`);
486
+ return;
487
+ }
488
+ if (!pruneJob) {
489
+ const job: PruneJob = { ctx, current, cancelled: false, indicator: false, status: "Prune scan starting", state: { kind: "scanning" } };
490
+ pruneJob = job;
491
+ pruneStatus(job, job.status);
492
+ const scan = async () => {
493
+ try {
494
+ const plan = await adapter.prunePlan(ctx.cwd, () => job.current() && !job.cancelled,
495
+ (done, total) => pruneStatus(job, `Prune scan ${done}/${total}`));
496
+ if (!job.current() || job.cancelled) return;
497
+ if (!ctx.hasUI) {
498
+ const reviewed = pruneReview(plan);
499
+ deliver(ctx, { ...reviewed.report, sections: [...reviewed.report.sections, { rows: [{ text: "Report only: removal requires interactive confirmation." }] }] }, "pi-subagent-prune");
500
+ } else {
501
+ job.state = { kind: "ready", plan };
502
+ pruneStatus(job, "Prune ready · /subagent prune");
503
+ ctx.ui.notify("Prune scan ready. Run /subagent prune to review it. No items were removed.", "info");
504
+ }
505
+ } catch (error) {
506
+ if (job.current() && !job.cancelled) deliver(ctx, textReport("error", `Prune scan failed: ${errorText(error)}`));
507
+ } finally { if (job.state.kind !== "ready") clearPrune(job); }
508
+ };
509
+ job.settled = scan();
510
+ if (ctx.hasUI) ctx.ui.notify("Prune scan started. Use /subagent prune cancel to stop.", "info");
511
+ else await job.settled;
512
+ return;
513
+ }
514
+ const job = pruneJob;
515
+ current = () => job.current() && !job.cancelled;
516
+ }
441
517
  const valid = () => {
442
518
  if (current()) return true;
443
- ctx.ui.notify("Session or branch changed; reopen /subagent in the current context.", "warning");
519
+ ctx.ui.notify("Cancelled or session or branch changed; reopen /subagent in the current context.", "warning");
444
520
  return false;
445
521
  };
446
522
  /** Review each request's discard plan, then one confirmation covers every shown unblocked group.
447
- * `whole` states that a request is deleted although only some of its resources were selected. Returns false when stale. */
448
- const discardRequests = async (requests: readonly IsolatedRequest[], whole = false): Promise<boolean> => {
523
+ * `whole` states that a request is deleted although only some of its resources were selected. Returns undefined when stale. */
524
+ const reviewDiscardRequests = async (requests: readonly IsolatedRequest[], whole = false): Promise<DiscardPlan[] | undefined> => {
449
525
  const plans: DiscardPlan[] = [];
450
526
  for (const request of requests) {
451
527
  try {
452
528
  const plan = await adapter.discardPlan(ctx.cwd, request);
453
529
  const reviewed = discardReview(plan);
454
- if (!valid()) return false;
530
+ if (!valid()) return;
455
531
  deliver(ctx, reviewed.report);
456
532
  const items = reviewed.shown.filter((item) => !item.blockers.length);
457
533
  if (items.length) plans.push({ ...plan, items });
458
534
  } catch (error) {
459
- if (!valid()) return false;
535
+ if (!valid()) return;
460
536
  ctx.ui.notify(`Close and delete failed for ${request.id}: ${errorText(error)}`, "error");
461
537
  }
462
538
  }
463
- if (!plans.length) return true;
539
+ if (!plans.length) return plans;
464
540
  const groups = plans.reduce((sum, plan) => sum + plan.items.length, 0);
465
541
  const confirmed = await ctx.ui.confirm("Close and delete worktrees (discard work)", clean(`${whole
466
542
  ? `This closes and deletes each whole owning request (${plans.map(({ requestId }) => requestId).join(", ")}), not only the selected worktrees. ` : ""}`
467
543
  + `Stop the listed workers and delete the ${groups} unblocked resource group(s) shown above${plans.length > 1 ? ` across ${plans.length} requests` : ""}? Committed, uncommitted, and ignored content in the listed checkouts is permanently deleted. Their listed branches, Herdr tabs, and workspaces are removed. Items not shown or blocked are kept.`,
468
544
  PRUNE_IGNORED_CONFIRM_CODE_POINTS));
469
- if (!valid()) return false;
470
- if (!confirmed) return true;
545
+ if (!valid()) return;
546
+ return confirmed ? plans : [];
547
+ };
548
+ const discardRequests = async (requests: readonly IsolatedRequest[], whole = false): Promise<boolean> => {
549
+ const plans = await reviewDiscardRequests(requests, whole);
550
+ if (!plans) return false;
471
551
  for (const plan of plans) {
472
552
  try {
473
553
  const report = await adapter.discard(ctx.cwd, plan, current);
@@ -480,55 +560,68 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
480
560
  }
481
561
  return true;
482
562
  };
483
- if (command === "prune") {
484
- const plan = await adapter.prunePlan(ctx.cwd);
485
- const reviewed = pruneReview(plan);
486
- if (!ctx.hasUI) {
487
- deliver(ctx, { ...reviewed.report, sections: [...reviewed.report.sections, { rows: [{ text: "Report only: removal requires interactive confirmation." }] }] }, "pi-subagent-prune");
563
+ if (command === "prune" && pruneJob?.state.kind === "ready") {
564
+ const job = pruneJob;
565
+ const reviewed = pruneReview(pruneJob.state.plan);
566
+ job.state = { kind: "reviewing" };
567
+ pruneStatus(job, "Prune review");
568
+ try {
569
+ if (!valid()) return;
570
+ deliver(ctx, reviewed.report);
571
+ const options = reviewed.shown.filter((item) => item.prunable || item.override);
572
+ if (!options.length) return;
573
+ // Continue confirms prunable items; each is re-verified first. Blocked items need their own confirmation below.
574
+ const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item), value: item })),
575
+ options.filter((item) => item.prunable), valid);
576
+ if (!picked?.length) return;
577
+ const forceable = picked.filter((item) => item.override === "force");
578
+ const forceList = fitItems(`Force remove ${forceable.length} blocked item(s)? This permanently deletes their unique commits, tracked and untracked changes, in-progress Git operations, and initialized submodules, as listed. Each is re-verified first and kept if a new kind of blocker appears:`,
579
+ forceable, (item) => `${shortId(item)}: ${item.reason}`, PRUNE_IGNORED_CONFIRM_CODE_POINTS);
580
+ const force = forceList.shown.length > 0 && await ctx.ui.confirm("Force remove blocked worktrees",
581
+ clean(forceList.text.replace(`Force remove ${forceable.length} blocked`, `Force remove ${forceList.shown.length} blocked`), PRUNE_IGNORED_CONFIRM_CODE_POINTS, true));
582
+ if (!valid()) return;
583
+ if (forceable.length && !force) ctx.ui.notify(`Kept ${forceable.length} blocked item(s); force removal was not approved.`, "info");
584
+ const prunable = [...picked.filter((item) => item.prunable), ...force ? forceList.shown : []];
585
+ const ignored = prunable.filter((item) => item.ignored.length);
586
+ // The header uses the full count's width so the shown count always fits.
587
+ const ignoredList = fitItems(`Also remove ${ignored.length} checkout(s) with ignored files? This permanently deletes these ignored entries and everything inside them:`,
588
+ // Approval names every ignored entry; a checkout whose full list does not fit is left out of this run.
589
+ ignored, (item) => clean(`${item.path}: ${item.ignored.join(", ")}`, Number.MAX_SAFE_INTEGER), PRUNE_IGNORED_CONFIRM_CODE_POINTS);
590
+ const approvable = ignoredList.shown;
591
+ const allowIgnored = approvable.length > 0 && await ctx.ui.confirm("Delete ignored content",
592
+ clean(ignoredList.text.replace(`Also remove ${ignored.length} checkout(s)`, `Also remove ${approvable.length} checkout(s)`), PRUNE_IGNORED_CONFIRM_CODE_POINTS, true));
593
+ if (!valid()) return;
594
+ const kept = ignored.length - (allowIgnored ? approvable.length : 0);
595
+ if (kept) ctx.ui.notify(`Kept ${kept} checkout(s) with ignored content; their deletion was not approved.`, "info");
596
+ const selected = prunable.filter((item) => !item.ignored.length || (allowIgnored && approvable.includes(item)));
597
+ // Finish every dialog in the foreground, including whole-request discard review.
598
+ const owners = new Map(picked.flatMap((item) => item.override === "discard" ? [[`${item.owner!.directory}\0${item.owner!.id}`, item.owner!] as const] : []));
599
+ const plans = await reviewDiscardRequests([...owners.values()].map((owner) => ({ ...owner, tasks: [] })), true);
600
+ if (!plans || !valid() || (!selected.length && !plans.length)) return;
601
+ job.state = { kind: "removing" };
602
+ pruneStatus(job, "Prune cleanup starting");
603
+ const cleanup = async () => {
604
+ try {
605
+ if (selected.length && current()) {
606
+ const report = await adapter.prune(ctx.cwd, selected, allowIgnored, force, current,
607
+ (done, total) => pruneStatus(job, `Prune cleanup ${done}/${total}`));
608
+ if (job.current()) deliver(ctx, cleanupReport(report));
609
+ }
610
+ for (const [index, plan] of plans.entries()) {
611
+ if (!current()) break;
612
+ pruneStatus(job, `Prune discard ${index + 1}/${plans.length}`);
613
+ const report = await adapter.discard(ctx.cwd, plan, current);
614
+ if (job.current()) deliver(ctx, cleanupReport(report));
615
+ }
616
+ if (job.current()) ctx.ui.notify(job.cancelled ? "Prune stopped. See cleanup reports for completed steps; unstarted items were kept."
617
+ : "Prune cleanup finished. See cleanup reports for removed, skipped, and failed items.", "info");
618
+ } catch (error) {
619
+ if (job.current()) deliver(ctx, textReport("error", `Prune cleanup failed: ${errorText(error)}. The active step can have changed resources. Earlier reports still apply; inspect /subagent before retrying.`));
620
+ } finally { clearPrune(job); }
621
+ };
622
+ job.settled = cleanup();
488
623
  return;
489
- }
490
- if (!valid()) return;
491
- deliver(ctx, reviewed.report);
492
- const options = reviewed.shown.filter((item) => item.prunable || item.override);
493
- if (!options.length) return;
494
- // Continue confirms prunable items; each is re-verified first. Blocked items need their own confirmation below.
495
- const picked = await chooseMany(ctx, "Prune subagent worktrees · prunable items are selected", options.map((item) => ({ label: pruneLabel(item), value: item })),
496
- options.filter((item) => item.prunable), valid);
497
- if (!picked?.length) return;
498
- const forceable = picked.filter((item) => item.override === "force");
499
- const forceList = fitItems(`Force remove ${forceable.length} blocked item(s)? This permanently deletes their unique commits, tracked and untracked changes, in-progress Git operations, and initialized submodules, as listed. Each is re-verified first and kept if a new kind of blocker appears:`,
500
- forceable, (item) => `${shortId(item)}: ${item.reason}`, PRUNE_IGNORED_CONFIRM_CODE_POINTS);
501
- const force = forceList.shown.length > 0 && await ctx.ui.confirm("Force remove blocked worktrees",
502
- clean(forceList.text.replace(`Force remove ${forceable.length} blocked`, `Force remove ${forceList.shown.length} blocked`), PRUNE_IGNORED_CONFIRM_CODE_POINTS, true));
503
- if (!valid()) return;
504
- if (forceable.length && !force) ctx.ui.notify(`Kept ${forceable.length} blocked item(s); force removal was not approved.`, "info");
505
- const prunable = [...picked.filter((item) => item.prunable), ...force ? forceList.shown : []];
506
- const ignored = prunable.filter((item) => item.ignored.length);
507
- // The header uses the full count's width so the shown count always fits.
508
- const ignoredList = fitItems(`Also remove ${ignored.length} checkout(s) with ignored files? This permanently deletes these ignored entries and everything inside them:`,
509
- // Approval names every ignored entry; a checkout whose full list does not fit is left out of this run.
510
- ignored, (item) => clean(`${item.path}: ${item.ignored.join(", ")}`, Number.MAX_SAFE_INTEGER), PRUNE_IGNORED_CONFIRM_CODE_POINTS);
511
- const approvable = ignoredList.shown;
512
- const allowIgnored = approvable.length > 0 && await ctx.ui.confirm("Delete ignored content",
513
- clean(ignoredList.text.replace(`Also remove ${ignored.length} checkout(s)`, `Also remove ${approvable.length} checkout(s)`), PRUNE_IGNORED_CONFIRM_CODE_POINTS, true));
514
- if (!valid()) return;
515
- const kept = ignored.length - (allowIgnored ? approvable.length : 0);
516
- if (kept) ctx.ui.notify(`Kept ${kept} checkout(s) with ignored content; their deletion was not approved.`, "info");
517
- const selected = prunable.filter((item) => !item.ignored.length || (allowIgnored && approvable.includes(item)));
518
- if (selected.length) {
519
- try {
520
- const report = await adapter.prune(ctx.cwd, selected, allowIgnored, force, current);
521
- if (!valid()) return;
522
- deliver(ctx, cleanupReport(report));
523
- } catch (error) {
524
- if (!valid()) return;
525
- ctx.ui.notify(`Prune failed: ${errorText(error)}`, "error");
526
- }
527
- }
528
- // Discard owns request-owned items: it closes the request's own workers and panes, then removes its resources.
529
- const owners = new Map(picked.flatMap((item) => item.override === "discard" ? [[`${item.owner!.directory}\0${item.owner!.id}`, item.owner!] as const] : []));
530
- await discardRequests([...owners.values()].map((owner) => ({ ...owner, tasks: [] })), true);
531
- return;
624
+ } finally { if (job.state.kind === "reviewing") clearPrune(job); }
532
625
  }
533
626
  if (!ctx.hasUI) {
534
627
  const inventory = await adapter.isolated(ctx.cwd, current);
@@ -696,4 +789,6 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
696
789
  }
697
790
  },
698
791
  });
792
+ // A replacement runtime must not inspect an index while this runtime still owns it.
793
+ return () => pruneJob?.settled;
699
794
  }
@@ -292,7 +292,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
292
292
  };
293
293
  // The in-memory counter also covers launches that have not saved a record yet.
294
294
  const nextWorkflow = (ctx: ExtensionContext) => (directWorkflow = Math.max(directWorkflow, ...savedWorkflows(ctx).keys()) + 1);
295
- registerSubagentCommand(pi, {
295
+ const settlePrune = registerSubagentCommand(pi, {
296
296
  direct(ctx): DirectTask[] {
297
297
  const grouped = new Map<string, DirectTask & { workers: DirectDisplay[]; tabs: Array<DirectTask["tabs"][number]> }>();
298
298
  // Delivered results carry measured costs; running or undelivered workflows show none.
@@ -355,10 +355,10 @@ export default function subagentExtension(pi: ExtensionAPI): void {
355
355
  },
356
356
  isolated: isolatedSurface.inventory,
357
357
  recover: (cwd) => isolatedSurface.recover(cwd),
358
- prunePlan: (cwd) => isolatedSurface.prunePlan(cwd),
358
+ prunePlan: (cwd, current, progress) => isolatedSurface.prunePlan(cwd, current, progress),
359
359
  discardPlan: (cwd, request) => isolatedSurface.discardPlan(cwd, request),
360
360
  discard: (cwd, plan, current) => isolatedSurface.discard(cwd, plan, current),
361
- prune: (cwd, items, allowIgnored, force, current) => isolatedSurface.prune(cwd, items, allowIgnored, force, current),
361
+ prune: (cwd, items, allowIgnored, force, current, progress) => isolatedSurface.prune(cwd, items, allowIgnored, force, current, progress),
362
362
  async inspectInTab(root, id, ctx, current) {
363
363
  const notices = await isolatedSurface.inspect(root, id);
364
364
  if (!current()) throw new Error("Session or branch changed before status inspection.");
@@ -584,6 +584,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
584
584
  await Promise.allSettled(handles.map((handle) => handle.cancel()));
585
585
  }
586
586
  await Promise.allSettled(tasks.map(({ settled }) => settled));
587
+ await settlePrune();
587
588
  // Unproved workers keep their local ownership and admission across a session switch.
588
589
  });
589
590
  // btw-style context refresh: model_select carries the new model on the event,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.12.0",
3
+ "version": "27.13.1",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",