@henryqw/pi-subagent 27.13.1 → 27.14.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.
package/CONTEXT.md CHANGED
@@ -56,6 +56,9 @@ The guarded transfer of a validated integration generation into unchanged, clean
56
56
  **Release**:
57
57
  Main's explicit cleanup of an exact rejected worker or superseded generation after proving that it is no longer selected. Release does not discard dirty, conflicted, or uncertain work.
58
58
 
59
+ **Subagent Collection**:
60
+ Tab-only cleanup of verified completed workers. It preserves sessions, leases, worktrees, candidates, and recovery records. A workspace with more than 10 tabs triggers an automatic attempt; `/subagent prune` attempts it at any count. Live isolated revision workers are not completed resources.
61
+
59
62
  **Discard**:
60
63
  The user-confirmed deletion of owned isolated resources from `/subagent`, including committed, uncommitted, and ignored content. Unlike Release, only the user can trigger it.
61
64
 
package/README.md CHANGED
@@ -33,7 +33,7 @@ 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 | 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. |
36
+ | `/subagent prune` | command | Collect eligible completed worker tabs, then scan leftover branches and worktrees. Run it again when ready to review and confirm deletion. Requires a running Herdr server. Without an interactive user interface, collect tabs and report worktrees without deleting them. |
37
37
  | `/subagent prune cancel` | command | Cancel the scan, ready plan, or cleanup. An active removal step can finish; completed removals are not undone. |
38
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). |
39
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. |
@@ -271,7 +271,7 @@ The executor accepts concurrency, turn/token, idle/hard-runtime limits, and abor
271
271
 
272
272
  Private durable state lives under `config/pi-subagent/state/`. Isolated worker sessions use mode `0600` under `config/pi-subagent/leases/`; worker umask stays unchanged. Reads stop at 16 MiB. Larger sessions require inspection and cannot prove completion.
273
273
 
274
- Sessions are removed only after exact worker-tab cleanup. They can contain prompts and answers: do not share them. State v5 rejects v4 and older files without migration. Preserve old state and recover its work manually.
274
+ Sessions are removed only after exact worker-tab cleanup. Subagent Collection keeps them. They can contain prompts and answers: do not share them. State v5 rejects v4 and older files without migration. Preserve old state and recover its work manually.
275
275
 
276
276
  ## Limits and recovery
277
277
 
@@ -283,6 +283,20 @@ Unverified tab allocations retain evidence but offer no Close action. Reconcile
283
283
 
284
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).
285
285
 
286
+ ### Subagent Collection
287
+
288
+ Subagent Collection closes only verified completed worker tabs. It keeps saved sessions, process leases, worktrees, candidates, and recovery records. It never closes a workspace or its root tab.
289
+
290
+ Automatic collection checks each relevant workspace after direct `delegate_task` launches, after direct or isolated workflows finish, and when Main settles. More than 10 tabs in that workspace triggers collection. Ten is a trigger, not a maximum. Collection can close all eligible tabs, even after the count falls below 10. User tabs count toward the trigger but are never collection targets. There is no timer: changes from other clients wait for the next check.
291
+
292
+ Direct collection uses exact records on the current Pi session branch, in the current checkout and Herdr workspace. It requires the recorded final session turn. If the exact agent remains, it must be idle or done. Active local tasks, continued sessions, unverified allocations, and uncertain identities stay open. Pane absence and two empty process-lease scans must pass before an empty tab can close. Saved conversations remain available for `continueFrom`.
293
+
294
+ Isolated collection uses saved requests in the current checkout. It requires saved termination proof, then verifies agent and pane absence and two empty process-lease scans again. A live productive lease blocks collection. **Ready candidates keep their live workers because Main can still request a revision.** Workspaces, root tabs, orphaned requests, and requests in other checkouts stay unchanged. Use their existing recovery or cleanup actions.
295
+
296
+ Every `/subagent prune` call tries collection without the tab-count trigger, including calls while a worktree scan is busy. Collection runs before worktree review and does not require deletion approval. Collection failure does not prevent that review. Worktree and branch deletion still require the existing review and confirmation. `/subagent prune cancel` stops new collection steps; a dispatched close can finish.
297
+
298
+ ### Worktree pruning
299
+
286
300
  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
301
 
288
302
  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.
@@ -0,0 +1,4 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ /** A collection trigger, not a limit on tabs or workers. */
3
+ export declare const COLLECTION_TAB_TRIGGER = 10;
4
+ export declare function workspaceNeedsCollection(pi: Pick<ExtensionAPI, "exec">, cwd: string, workspaceId: string): Promise<boolean>;
@@ -0,0 +1,17 @@
1
+ import { createHerdrClient } from "@henryqw/pi-herdr";
2
+ /** A collection trigger, not a limit on tabs or workers. */
3
+ export const COLLECTION_TAB_TRIGGER = 10;
4
+ export async function workspaceNeedsCollection(pi, cwd, workspaceId) {
5
+ const response = await createHerdrClient(pi.exec.bind(pi)).json(["tab", "list", "--workspace", workspaceId], { cwd, timeout: 5_000 });
6
+ const result = response.result;
7
+ if (result?.type !== "tab_list" || !Array.isArray(result.tabs))
8
+ throw new Error("Malformed Herdr collection tab list.");
9
+ const ids = new Set();
10
+ for (const tab of result.tabs) {
11
+ if (!tab || tab.workspace_id !== workspaceId || typeof tab.tab_id !== "string" || !tab.tab_id || ids.has(tab.tab_id)) {
12
+ throw new Error("Herdr collection tab list has uncertain workspace or tab identity.");
13
+ }
14
+ ids.add(tab.tab_id);
15
+ }
16
+ return ids.size > COLLECTION_TAB_TRIGGER;
17
+ }
@@ -66,6 +66,8 @@ export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: s
66
66
  * A task result or Ctrl-C acknowledgement is not termination evidence.
67
67
  * `settledOnly` refuses to close a listed agent that is not idle or done. */
68
68
  stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, settledOnly?: boolean): Promise<void>;
69
+ /** Collection preserves the saved conversation and private lease for continuation and recovery. */
70
+ collect(tab: DirectTab, current: () => boolean): Promise<boolean>;
69
71
  /** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
70
72
  start(launch: ResolvedRoleLaunch & Pick<PreparedRoleLaunch, "tools">, name: string, label: string, task: string, signal: AbortSignal, onTab: (tab: DirectTab) => void, requireSuccess?: boolean, resume?: Pick<DirectTab, "sessionFile" | "leasePath">): Promise<DirectHandle>;
71
73
  };
@@ -351,6 +351,38 @@ export function createDirectHerdr(pi, cwd, idleMs) {
351
351
  }
352
352
  requireCurrent();
353
353
  },
354
+ /** Collection preserves the saved conversation and private lease for continuation and recovery. */
355
+ async collect(tab, current) {
356
+ if (tab.workspaceId !== workspaceId || tab.cwd !== workingDir || !current())
357
+ throw new Error("Direct collection scope changed.");
358
+ const before = await herdr.exec(["tab", "get", tab.tabId], options());
359
+ if (!before.killed && hasHerdrErrorCode(before, "tab_not_found"))
360
+ return false;
361
+ if (before.code !== 0 || before.killed)
362
+ throw new Error("Direct collection tab presence is uncertain.");
363
+ const original = object(result(JSON.parse(before.stdout), "tab_info").tab, "collection tab");
364
+ if (original.tab_id !== tab.tabId || original.workspace_id !== workspaceId || ![0, 1].includes(original.pane_count)) {
365
+ throw new Error("Direct collection tab identity or pane count changed.");
366
+ }
367
+ await assertSettledDirectSession(tab.sessionFile, tab.turn);
368
+ await this.stop(tab, current, true);
369
+ const response = await herdr.exec(["tab", "get", tab.tabId], options());
370
+ if (!response.killed && hasHerdrErrorCode(response, "tab_not_found"))
371
+ return true;
372
+ if (response.code !== 0 || response.killed)
373
+ throw new Error("Direct collection tab presence is uncertain.");
374
+ const saved = object(result(JSON.parse(response.stdout), "tab_info").tab, "collection tab");
375
+ if (saved.tab_id !== tab.tabId || saved.workspace_id !== workspaceId || saved.pane_count !== 0) {
376
+ throw new Error("Direct collection requires the exact empty worker tab.");
377
+ }
378
+ if (!current())
379
+ throw new Error("Direct collection scope changed.");
380
+ result(await herdr.json(["tab", "close", tab.tabId], options()), "ok");
381
+ const after = await herdr.exec(["tab", "get", tab.tabId], options());
382
+ if (after.killed || !hasHerdrErrorCode(after, "tab_not_found"))
383
+ throw new Error("Direct collection tab absence is unproved.");
384
+ return true;
385
+ },
354
386
  /** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
355
387
  async start(launch, name, label, task, signal, onTab, requireSuccess = false, resume) {
356
388
  const reader = directTaskReader(task, launch.tools);
@@ -101,6 +101,9 @@ export declare class HerdrHostRuntime implements HostRuntime {
101
101
  kind: HostCleanupKind;
102
102
  task: TaskRequest;
103
103
  attempt: TaskAttempt;
104
+ collection?: {
105
+ current(): boolean;
106
+ };
104
107
  }, context: OperationContext): Promise<{
105
108
  outcome: "completed" | "absent";
106
109
  } | {
@@ -687,6 +687,15 @@ export class HerdrHostRuntime {
687
687
  return { outcome: "blocked", failure: "Host cleanup requires exact worker termination or a definitive absent-agent allocation." };
688
688
  }
689
689
  try {
690
+ if (input.collection) {
691
+ if (!input.collection.current() || input.kind !== "worker_tab" || !terminationProven) {
692
+ throw new Error("Collection requires a current scope and a terminated worker tab.");
693
+ }
694
+ const proof = await this.reconcileWorkerTermination({ task: input.task, attempt: input.attempt,
695
+ workerId: input.attempt.termination.workerId, candidate: input.attempt.termination.candidate }, context);
696
+ if (proof.outcome !== "terminated")
697
+ throw new Error(proof.outcome === "unknown" ? proof.failure : "Worker is active; tab retained.");
698
+ }
690
699
  if (input.kind === "worker_tab") {
691
700
  const owned = ownedIntent(input.attempt, "worker_tab");
692
701
  const workspace = ownedIntent(input.attempt, "workspace");
@@ -724,6 +733,8 @@ export class HerdrHostRuntime {
724
733
  if (workspaceIsAbsent || tab.workspace_id !== workspaceId || tab.label !== allocation.label || tab.pane_count !== 0) {
725
734
  return { outcome: "blocked", failure: "The exact saved worker tab no longer matches its owned empty tab identity." };
726
735
  }
736
+ if (input.collection && !input.collection.current())
737
+ throw new Error("Collection scope changed; tab retained.");
727
738
  const closed = await this.herdr.exec(["tab", "close", tabId], this.processOptions(allocation.worktreeCwd, context, HERDR_OPERATION_CAP_MS));
728
739
  if (closed.code !== 0 || closed.killed)
729
740
  return { outcome: "blocked", failure: safeText(herdrCommandFailure(["tab", "close"], closed)) };
@@ -732,7 +743,8 @@ export class HerdrHostRuntime {
732
743
  return { outcome: "blocked", failure: "The exact saved worker tab still exists after close." };
733
744
  }
734
745
  }
735
- await this.removeLeaseArtifacts(allocation, input.attempt.correlationToken, paneId, tabId, context);
746
+ if (!input.collection)
747
+ await this.removeLeaseArtifacts(allocation, input.attempt.correlationToken, paneId, tabId, context);
736
748
  return tab ? { outcome: "completed" } : { outcome: "absent" };
737
749
  }
738
750
  const workerCleanup = input.attempt.cleanup.find((step) => step.kind === "worker_tab");
package/dist/runner.d.ts CHANGED
@@ -190,6 +190,10 @@ export interface HostRuntime {
190
190
  cleanupHost(input: {
191
191
  requestId: ExecuteRequest["id"];
192
192
  kind: HostCleanupKind;
193
+ /** Tab-only collection keeps all session and lease evidence. */
194
+ collection?: {
195
+ current(): boolean;
196
+ };
193
197
  task: TaskRequest;
194
198
  attempt: TaskAttempt;
195
199
  }, context: OperationContext): Promise<{
@@ -331,6 +335,8 @@ export declare class IsolatedRunner {
331
335
  invalidIds: string[];
332
336
  states: RunState[];
333
337
  }>;
338
+ /** Collect only already terminated worker tabs. Do not change saved state or candidate resources. */
339
+ collectTabs(root: string, eligible: (workspaceId: string) => Promise<boolean>, current: () => boolean): Promise<string[]>;
334
340
  /** True while a live productive run holds this root's lease; the lease does not name its request. */
335
341
  hasProductiveRunLease(root: string): Promise<boolean>;
336
342
  /** Classify orphaned work under the same repository lease as productive execution.
package/dist/runner.js CHANGED
@@ -641,6 +641,56 @@ export class IsolatedRunner {
641
641
  })),
642
642
  })) };
643
643
  }
644
+ /** Collect only already terminated worker tabs. Do not change saved state or candidate resources. */
645
+ async collectTabs(root, eligible, current) {
646
+ root = realpathSync.native(root);
647
+ const candidates = (states) => states.flatMap((state) => state.tasks.flatMap((task) => task.kind !== "changeset" ? []
648
+ : task.attempts.flatMap((attempt) => {
649
+ const workspace = allocationByKind(attempt, "workspace");
650
+ return attempt.termination?.status === "terminated" && workspace?.status === "owned" && workspace.workspaceId
651
+ && !attempt.cleanup.some((step) => step.kind === "worker_tab" && step.status === "completed")
652
+ ? [{ state, task, attempt, workspaceId: workspace.workspaceId }] : [];
653
+ })));
654
+ const listed = await this.listRequests(root);
655
+ const report = listed.invalidIds.map((id) => `Retained unreadable isolated request ${id}.`);
656
+ const workspaces = new Set();
657
+ for (const id of new Set(candidates(listed.states).map(({ workspaceId }) => workspaceId))) {
658
+ if (!current())
659
+ return report;
660
+ if (await eligible(id))
661
+ workspaces.add(id);
662
+ }
663
+ if (!workspaces.size || !current())
664
+ return report;
665
+ try {
666
+ return await this.withProductiveRun(root, async (lifecycle) => await this.store.withLock(root, async () => {
667
+ // Reload under the productive lease; the earlier inventory grants no mutation authority.
668
+ for (const { state, task, attempt, workspaceId } of candidates((await this.listRequests(root)).states)) {
669
+ if (!current())
670
+ return report;
671
+ if (!workspaces.has(workspaceId))
672
+ continue;
673
+ const scope = new DeadlineScope(this.coordinatorRuntime.now() + CLEANUP_SAFETY_BUDGET_MS, () => this.coordinatorRuntime.now());
674
+ try {
675
+ const result = await scope.call((context) => this.hostRuntime.cleanupHost({
676
+ requestId: state.request.id, kind: "worker_tab", task: changesetTaskRequest(state, task.taskId), attempt, collection: { current },
677
+ }, context));
678
+ if (result.outcome !== "absent")
679
+ report.push(`${state.request.id}/${task.taskId}/${attempt.number}: ${result.outcome === "blocked" ? `retained: ${result.failure}` : "worker tab collected"}.`);
680
+ }
681
+ finally {
682
+ scope.close();
683
+ }
684
+ }
685
+ return report;
686
+ }, { productiveRunLease: lifecycle.lease }));
687
+ }
688
+ catch (error) {
689
+ if (!(error instanceof ProductiveRunLeaseBusyError))
690
+ throw error;
691
+ return ["Isolated tabs retained: a productive run owns this checkout. Retry after it finishes."];
692
+ }
693
+ }
644
694
  /** True while a live productive run holds this root's lease; the lease does not name its request. */
645
695
  async hasProductiveRunLease(root) {
646
696
  return await this.store.hasProductiveRunLease(root);
@@ -418,9 +418,11 @@ The report lists removed, skipped, and failed resources. After complete cleanup,
418
418
 
419
419
  ### Prune leftover worktrees
420
420
 
421
+ Each `/subagent prune` call first runs [Subagent Collection](../README.md#subagent-collection), which closes only verified completed worker tabs and keeps their evidence. This separate action has no tab-count requirement and runs even if worktree review fails or has no candidates. It does not grant permission to delete worktrees or branches. A later cancellation does not reopen collected tabs.
422
+
421
423
  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
424
 
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.
425
+ 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 worktree operation. Tab collection remains independent. 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
426
 
425
427
  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
428
 
@@ -451,7 +453,7 @@ The list shows removable items first. The command never cuts a long list silentl
451
453
 
452
454
  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.
453
455
 
454
- Without interactive UI, the command waits for the scan and only reports. It never removes items in this mode.
456
+ Without an interactive user interface, the command still collects eligible tabs. It then waits for the worktree scan and reports its results. It never deletes worktrees or branches in this mode.
455
457
 
456
458
  A non-regular or unreadable state entry can block every item because its resource ownership is unknown. State files never change directly.
457
459
 
@@ -519,6 +519,7 @@ export interface IsolatedSurface {
519
519
  plan(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof formatExecutePlan>>;
520
520
  execute(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof toolResult>>;
521
521
  inventory(cwd: string, current?: () => boolean): Promise<IsolatedInventory>;
522
+ collectTabs(cwd: string, eligible: (workspaceId: string) => Promise<boolean>, current: () => boolean): Promise<string[]>;
522
523
  recover(cwd: string): Promise<string>;
523
524
  prunePlan(cwd: string, current?: () => boolean, progress?: PruneProgress): Promise<PrunePlan>;
524
525
  discardPlan(cwd: string, request: IsolatedRequest): Promise<DiscardPlan>;
@@ -537,6 +538,8 @@ export interface RegisterIsolatedOptions {
537
538
  /** Report new config issues, and throw when the config now blocks delegation, before each deferred Role launch. */
538
539
  beforeRoleLaunch?(ctx: ExtensionContext): void;
539
540
  componentsFactory?: CreateIsolatedComponents;
541
+ /** Notification after productive work releases its lease. */
542
+ onFinished?(ctx: ExtensionContext): void;
540
543
  }
541
544
 
542
545
  /** Register lifecycle surfaces; delegate_task remains the only start tool. */
@@ -725,6 +728,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
725
728
  return;
726
729
  }
727
730
  deliver("terminal", `${response.text}\n\nState: ${JSON.stringify(publicState(response.state, PUBLIC_EVIDENCE_MAX_BYTES))}`, response);
731
+ if (canDeliver()) options.onFinished?.(ctx);
728
732
  },
729
733
  (error: unknown) => {
730
734
  finish();
@@ -735,6 +739,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
735
739
  return;
736
740
  }
737
741
  deliver("terminal", `Pi Subagent ${id} stopped: ${boundedPublicText(error instanceof Error ? error.message : String(error))}. Use subagent_status to inspect the durable request before choosing an explicit recovery action.`);
742
+ if (canDeliver()) options.onFinished?.(ctx);
738
743
  },
739
744
  );
740
745
  const state = await durable;
@@ -852,6 +857,11 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
852
857
  const leaseLive = await getComponents().runner.hasProductiveRunLease(root);
853
858
  return { root, leaseLive, requests: [...requests, ...orphans.requests], invalidIds: [...new Set([...invalidIds, ...orphans.invalidIds])] };
854
859
  },
860
+ async collectTabs(cwd, eligible, current) {
861
+ const root = await lookupRoot(cwd);
862
+ requireCurrent(current);
863
+ return await getComponents().runner.collectTabs(root, eligible, () => current() && !sessionClosed);
864
+ },
855
865
  async recover(cwd) {
856
866
  const root = await lookupRoot(cwd);
857
867
  const { requests, invalidIds, leaseBusy } = await getComponents().runner.recoverRepository(root);
@@ -77,6 +77,8 @@ export interface SubagentCommandAdapter {
77
77
  stopDirect(task: DirectTask, entryId: string, current: () => boolean): Promise<string>;
78
78
  isolated(cwd: string, current: () => boolean): Promise<IsolatedInventory>;
79
79
  recover(cwd: string): Promise<string>;
80
+ /** Tab collection is independent of worktree deletion review and confirmation. */
81
+ collect(ctx: ExtensionContext, current: () => boolean): Promise<string>;
80
82
  /** Read-only review of pi-subagent worktrees and branches in the canonical repository. */
81
83
  prunePlan(cwd: string, current?: () => boolean, progress?: PruneProgress): Promise<PrunePlan>;
82
84
  discardPlan(cwd: string, request: IsolatedRequest): Promise<DiscardPlan>;
@@ -415,6 +417,7 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
415
417
  };
416
418
  let pruneJob: PruneJob | undefined;
417
419
  let generation = 0;
420
+ let collectionGeneration = 0;
418
421
  const clearPruneStatus = (job: PruneJob) => {
419
422
  if (job.indicator) job.ctx.ui.setStatus("subagent-prune", undefined);
420
423
  job.indicator = false;
@@ -476,11 +479,22 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
476
479
  const notify = (message: string) => ctx.hasUI ? ctx.ui.notify(message, "info") : deliver(ctx, textReport("info", message));
477
480
  if (pruneJob && !pruneJob.current()) cancelPrune(pruneJob);
478
481
  if (command === "prune cancel") {
482
+ collectionGeneration++;
479
483
  const job = pruneJob;
480
484
  if (job) cancelPrune(job);
481
485
  notify(job ? "Prune cancelled. An active step can finish; completed removals are not undone." : "No prune operation is active.");
482
486
  return;
483
487
  }
488
+ const collection = collectionGeneration;
489
+ const collectionCurrent = () => current() && collection === collectionGeneration;
490
+ try {
491
+ const report = await adapter.collect(ctx, collectionCurrent);
492
+ if (!collectionCurrent()) return;
493
+ deliver(ctx, textReport("info", report), "pi-subagent-collection");
494
+ } catch (error) {
495
+ if (!collectionCurrent()) return;
496
+ deliver(ctx, textReport("warning", `Subagent Collection failed: ${errorText(error)}. Worktree review remains separate.`));
497
+ }
484
498
  if (pruneJob && pruneJob.state.kind !== "ready") {
485
499
  notify(pruneJob.cancelled ? "Prune is stopping; wait for the active step." : `${pruneJob.status}. Use /subagent prune cancel to stop.`);
486
500
  return;
@@ -500,7 +514,7 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
500
514
  } else {
501
515
  job.state = { kind: "ready", plan };
502
516
  pruneStatus(job, "Prune ready · /subagent prune");
503
- ctx.ui.notify("Prune scan ready. Run /subagent prune to review it. No items were removed.", "info");
517
+ ctx.ui.notify("Prune scan ready. Run /subagent prune to review it. No worktrees or branches were removed.", "info");
504
518
  }
505
519
  } catch (error) {
506
520
  if (job.current() && !job.cancelled) deliver(ctx, textReport("error", `Prune scan failed: ${errorText(error)}`));
@@ -11,6 +11,7 @@ import { directRef, registerSubagentCommand, type DirectDisplay, type DirectTask
11
11
  import { MODEL_CLASS_GUIDANCE } from "./model-class-policy.ts";
12
12
  import { compactCost, compactTokens, ENTRY_STATUS_PRESENTATION, formatWorkflowResult, workerOutputForMain, type BackgroundWorkflowTransportDetails, type WorkflowTransportEntry } from "./result-transport.ts";
13
13
  import { checkoutNote, DelegateTaskParameters, identifyWorkflowEntries, parseDelegateTask, runForegroundWorkflow, snapshotCheckout, writesCheckout, type CheckoutSnapshot, type ParsedWorkflow, type WorkflowEntry } from "./workflow.ts";
14
+ import { workspaceNeedsCollection } from "../dist/collection.js";
14
15
  import { assertSettledDirectSession, createDirectHerdr, DirectAllocationError, directTaskReader, type DirectAllocation, type DirectHandle, type DirectTab, type DirectToolActivity, type DirectUsage } from "../dist/direct-herdr.js";
15
16
  import { materializeTransientLaunch } from "../dist/launch-runtime.js";
16
17
  const WIDGET_KEY = "subagent-status";
@@ -252,6 +253,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
252
253
  policy: initialPolicy,
253
254
  currentPolicy,
254
255
  beforeRoleLaunch,
256
+ onFinished: (ctx) => automaticCollection(ctx),
255
257
  });
256
258
  let directSequence = 0;
257
259
  const directTasks = new Map<string, {
@@ -269,6 +271,66 @@ export default function subagentExtension(pi: ExtensionAPI): void {
269
271
  && tab.paneId === saved.paneId && tab.sessionFile === saved.sessionFile;
270
272
  });
271
273
  let sessionEpoch = 0;
274
+ let collectionEpoch = 0;
275
+ let collecting: Promise<string[]> | undefined;
276
+ let pendingCollection: (() => void) | undefined;
277
+ pi.on("session_tree", () => { collectionEpoch++; });
278
+ const collectTabs = async (ctx: ExtensionContext, manual: boolean, current: () => boolean): Promise<string[]> => {
279
+ while (collecting) await collecting;
280
+ if (!current()) return [];
281
+ const work = async () => {
282
+ const report: string[] = [];
283
+ let triggered = manual;
284
+ const workspaces = new Map<string, Promise<boolean>>();
285
+ const eligible = (id: string) => {
286
+ if (!workspaces.has(id)) workspaces.set(id, manual ? Promise.resolve(true) : workspaceNeedsCollection(pi, ctx.cwd, id).then((due) => { triggered ||= due; return due; }));
287
+ return workspaces.get(id)!;
288
+ };
289
+ const records = ctx.sessionManager.getBranch().flatMap((entry) => entry.type === "custom" && entry.customType === DIRECT_TAB_TYPE
290
+ ? [entry.data as DirectTabRecord] : []);
291
+ const seen = new Set<string>();
292
+ for (const tab of records) {
293
+ if (!current()) break;
294
+ if (!tab.turn || !tab.workspaceId || !tab.cwd || seen.has(tab.tabId)) continue;
295
+ seen.add(tab.tabId);
296
+ const unowned = () => current() && !directTasks.has(tab.taskId)
297
+ && ![...directTasks.values()].some((task) => task.continues?.has(tab.sessionFile));
298
+ if (!unowned()) continue;
299
+ try {
300
+ if (!await eligible(tab.workspaceId) || !unowned()) continue;
301
+ const herdr = createDirectHerdr(pi, ctx.cwd, currentPolicy().childIdleMs);
302
+ if (await herdr.collect(tab as DirectTab, unowned)) report.push(`${tab.tabId}: direct worker tab collected.`);
303
+ } catch (error) { report.push(`${tab.tabId}: retained: ${boundedError(error).message}`); }
304
+ }
305
+ if (current()) {
306
+ try { report.push(...await isolatedSurface.collectTabs(ctx.cwd, eligible, current)); }
307
+ catch (error) { report.push(`Isolated tabs retained: ${boundedError(error).message}`); }
308
+ }
309
+ return triggered ? report : [];
310
+ };
311
+ collecting = work();
312
+ try { return await collecting; } finally {
313
+ collecting = undefined;
314
+ const pending = pendingCollection;
315
+ pendingCollection = undefined;
316
+ pending?.();
317
+ }
318
+ };
319
+ const automaticCollection = (ctx: ExtensionContext) => {
320
+ if (process.env.HERDR_ENV !== "1") return;
321
+ const epoch = sessionEpoch;
322
+ const tree = collectionEpoch;
323
+ const session = ctx.sessionManager.getSessionId();
324
+ const branch = ctx.sessionManager.getBranch().map((entry) => entry.id);
325
+ const existing = new Set(ctx.sessionManager.getEntries().map((entry) => entry.id));
326
+ const current = () => epoch === sessionEpoch && tree === collectionEpoch && session === ctx.sessionManager.getSessionId()
327
+ && branch.every((id, index) => ctx.sessionManager.getBranch()[index]?.id === id)
328
+ && ctx.sessionManager.getBranch().slice(branch.length).every((entry) => !existing.has(entry.id));
329
+ if (collecting) { pendingCollection = () => { if (current()) automaticCollection(ctx); }; return; }
330
+ void collectTabs(ctx, false, current).then((report) => {
331
+ if (current() && report.length && ctx.hasUI) ctx.ui.notify(capOutput(`Subagent Collection: closes only verified completed worker tabs.\n${report.join("\n")}`), "info");
332
+ }).catch((error) => { if (current() && ctx.hasUI) ctx.ui.notify(`Subagent Collection failed: ${boundedError(error).message}`, "warning"); });
333
+ };
272
334
  pi.events.on("pi-subagent:pending-result", (data) => {
273
335
  if (!data || typeof data !== "object" || !("sessionId" in data) || typeof data.sessionId !== "string"
274
336
  || !("pending" in data) || typeof data.pending !== "boolean") return;
@@ -353,6 +415,10 @@ export default function subagentExtension(pi: ExtensionAPI): void {
353
415
  await local.stopWorker.stop(entryId, current);
354
416
  return "Worker stopped; pane absence and empty lease scans proved. Other workers continue; Main receives one result when the workflow finishes.";
355
417
  },
418
+ async collect(ctx, current) {
419
+ const report = await collectTabs(ctx, true, current);
420
+ return capOutput(`Subagent Collection: closes only verified completed worker tabs.\n${report.length ? report.join("\n") : "No eligible tabs to close."}\nSessions, worktrees, candidates, and recovery evidence kept. Worktree deletion requires separate review and confirmation.`);
421
+ },
356
422
  isolated: isolatedSurface.inventory,
357
423
  recover: (cwd) => isolatedSurface.recover(cwd),
358
424
  prunePlan: (cwd, current, progress) => isolatedSurface.prunePlan(cwd, current, progress),
@@ -601,6 +667,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
601
667
  });
602
668
  pi.on("agent_settled", (_event, ctx) => {
603
669
  latestCtx = ctx;
670
+ automaticCollection(ctx);
604
671
  });
605
672
 
606
673
  const reportDirect = (
@@ -866,6 +933,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
866
933
  handles.push(handle);
867
934
  handleByEntry.set(entry.id, handle);
868
935
  if (widgetItems.has(entry.id)) tokenHandles.set(entry.id, handle);
936
+ if (launchEpoch === sessionEpoch) automaticCollection(ctx);
869
937
  return handle;
870
938
  };
871
939
  // The first tab is verified before returning a handle; subsequent independent
@@ -961,6 +1029,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
961
1029
  local.pendingResult = undefined;
962
1030
  if (!controller.signal.aborted) reportDirect(launchEpoch, taskId, ref, workflow.mode, [...states.values()], tabs, local.recovery);
963
1031
  resolveSettled();
1032
+ if (launchEpoch === sessionEpoch) automaticCollection(ctx);
964
1033
  }
965
1034
  })();
966
1035
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.13.1",
3
+ "version": "27.14.0",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",