@xzzpig/pi-subagents 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
- import type { BeforeProviderRequestEvent, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import type { BeforeAgentStartEvent, BeforeProviderRequestEvent, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
5
  import { registerNativeSupervisorClient } from "../../intercom/native-supervisor-channel.ts";
6
6
  import { permissionDecision } from "./permissions.ts";
7
7
  import type { SteerRequest } from "../background/control-channel.ts";
@@ -198,16 +198,16 @@ export function stripSubagentOrchestrationSkill(prompt: string): string {
198
198
 
199
199
  function stripChildBoundaryInstructions(prompt: string): string {
200
200
  let rewritten = prompt;
201
- for (const boundary of [CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS, CHILD_FANOUT_BOUNDARY_INSTRUCTIONS]) {
202
- rewritten = rewritten.split(boundary).join("");
201
+ for (const instructions of [CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS, CHILD_FANOUT_BOUNDARY_INSTRUCTIONS, STRUCTURED_OUTPUT_INSTRUCTIONS]) {
202
+ rewritten = rewritten.split(`\n\n${instructions}`).join("").split(instructions).join("");
203
203
  }
204
204
  return rewritten.replace(/^(?:[ \t]*\r?\n)+/, "");
205
205
  }
206
206
 
207
- export function rewriteSubagentPrompt(
208
- prompt: string,
209
- options: { inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean; fanoutChild?: boolean; structuredOutput?: boolean },
210
- ): string {
207
+ type InheritedPromptOptions = { inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean };
208
+ type ChildBoundaryOptions = { fanoutChild?: boolean; structuredOutput?: boolean };
209
+
210
+ function stripInheritedPromptText(prompt: string, options: InheritedPromptOptions): string {
211
211
  let rewritten = prompt;
212
212
  if (!options.inheritProjectContext) {
213
213
  rewritten = stripProjectContext(rewritten);
@@ -218,11 +218,41 @@ export function rewriteSubagentPrompt(
218
218
  if (!options.inheritSkills) {
219
219
  rewritten = stripInheritedSkills(rewritten);
220
220
  }
221
- rewritten = stripSubagentOrchestrationSkill(rewritten);
222
- rewritten = stripChildBoundaryInstructions(rewritten);
221
+ return stripChildBoundaryInstructions(stripSubagentOrchestrationSkill(rewritten));
222
+ }
223
+
224
+ function appendChildBoundary(prompt: string, options: ChildBoundaryOptions): string {
223
225
  const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;
224
226
  const structured = options.structuredOutput ? `\n\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : "";
225
- return `${boundary}${structured}\n\n${rewritten}`;
227
+ // Pi's base prompt stays first so providers that recognize it by its opening still do.
228
+ return `${stripChildBoundaryInstructions(prompt)}\n\n${boundary}${structured}`;
229
+ }
230
+
231
+ export function rewriteSubagentPrompt(prompt: string, options: InheritedPromptOptions & ChildBoundaryOptions): string {
232
+ return appendChildBoundary(stripInheritedPromptText(prompt, options), options);
233
+ }
234
+
235
+ /** In place, so later handlers and the final render never see the removed context. */
236
+ function filterChildPromptOptions(options: BeforeAgentStartEvent["systemPromptOptions"], inherited: InheritedPromptOptions): void {
237
+ if (!inherited.inheritProjectContext) options.contextFiles = [];
238
+ else if (!inherited.inheritGlobalContext) options.contextFiles = options.contextFiles.filter((file) => !isGlobalContextFile(file.path));
239
+ options.skills = inherited.inheritSkills ? options.skills.filter((skill) => skill.name !== "pi-subagents") : [];
240
+ // Role prompts can embed context, skill catalogs, or an earlier child's boundary as text.
241
+ if (options.customPrompt) options.customPrompt = stripInheritedPromptText(options.customPrompt, inherited);
242
+ if (options.appendSystemPrompt) options.appendSystemPrompt = stripInheritedPromptText(options.appendSystemPrompt, inherited);
243
+ }
244
+
245
+ function rewritesChildPrompt(config: ChildRuntimeConfig): boolean {
246
+ return config.inheritProjectContext !== undefined || config.inheritGlobalContext !== undefined || config.inheritSkills !== undefined || Boolean(config.fanoutChild);
247
+ }
248
+
249
+ /** Installed after every other extension: a returned prompt freezes out sections added after it. */
250
+ export function registerSubagentPromptBoundary(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
251
+ if (!rewritesChildPrompt(config)) return;
252
+ pi.on("before_agent_start", (event) => {
253
+ const finalized = appendChildBoundary(event.systemPrompt, { fanoutChild: config.fanoutChild, structuredOutput: Boolean(config.structuredOutput) });
254
+ return finalized === event.systemPrompt ? undefined : { systemPrompt: finalized };
255
+ });
226
256
  }
227
257
 
228
258
  function isParentOnlySubagentMessage(message: unknown): boolean {
@@ -267,17 +297,22 @@ export function rewriteForkCacheProviderRequest(event: BeforeProviderRequestEven
267
297
  return { ...payload, prompt_cache_key: key };
268
298
  }
269
299
 
270
- function portableToolId(id: string): string {
300
+ function portableToolId(id: string, preserveBoundedCompositeToolIds = false): string {
271
301
  if (PORTABLE_TOOL_ID_PATTERN.test(id) && id.length <= MAX_PORTABLE_TOOL_ID_LENGTH) return id;
302
+ // Codex splits call_id|item_id on replay; each wire ID must remain portable and bounded.
303
+ if (preserveBoundedCompositeToolIds) {
304
+ const parts = id.split("|");
305
+ if (parts.length === 2 && parts.every((part) => PORTABLE_TOOL_ID_PATTERN.test(part) && part.length <= MAX_PORTABLE_TOOL_ID_LENGTH)) return id;
306
+ }
272
307
  const encoded = `tool_${Buffer.from(id).toString("base64url") || "empty"}`;
273
308
  if (encoded.length <= MAX_PORTABLE_TOOL_ID_LENGTH) return encoded;
274
309
  return `tool_${createHash("sha256").update(id).digest("base64url")}`;
275
310
  }
276
311
 
277
- function sanitizeToolHistoryMessage(message: unknown): unknown {
312
+ function sanitizeToolHistoryMessage(message: unknown, preserveBoundedCompositeToolIds = false): unknown {
278
313
  const m = message as { role?: string; content?: unknown; toolCallId?: unknown };
279
314
  if (m?.role === "toolResult" && typeof m.toolCallId === "string") {
280
- const toolCallId = portableToolId(m.toolCallId);
315
+ const toolCallId = portableToolId(m.toolCallId, preserveBoundedCompositeToolIds);
281
316
  return toolCallId === m.toolCallId ? message : { ...m, toolCallId };
282
317
  }
283
318
  if (m?.role !== "assistant" || !Array.isArray(m.content)) return message;
@@ -285,7 +320,7 @@ function sanitizeToolHistoryMessage(message: unknown): unknown {
285
320
  const content = m.content.map((block) => {
286
321
  const b = block as { type?: string; id?: unknown };
287
322
  if (b?.type !== "toolCall" || typeof b.id !== "string") return block;
288
- const id = portableToolId(b.id);
323
+ const id = portableToolId(b.id, preserveBoundedCompositeToolIds);
289
324
  if (id === b.id) return block;
290
325
  changed = true;
291
326
  return { ...b, id };
@@ -302,7 +337,7 @@ function stripAssistantSubagentToolCallBlocks(message: unknown): unknown | undef
302
337
  return { ...m, content: filteredContent };
303
338
  }
304
339
 
305
- export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean; preserveFanoutToolHistory?: boolean } = {}): unknown[] {
340
+ export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean; preserveBoundedCompositeToolIds?: boolean; preserveFanoutToolHistory?: boolean } = {}): unknown[] {
306
341
  const preserveCurrentFanoutToolHistory = options.preserveFanoutToolHistory === true;
307
342
  const sanitizeToolIds = options.sanitizeToolIds ?? true;
308
343
  let changed = false;
@@ -317,7 +352,7 @@ export function stripParentOnlySubagentMessages(messages: unknown[], options: {
317
352
  changed = true;
318
353
  continue;
319
354
  }
320
- const sanitized = sanitizeToolIds ? sanitizeToolHistoryMessage(stripped) : stripped;
355
+ const sanitized = sanitizeToolIds ? sanitizeToolHistoryMessage(stripped, options.preserveBoundedCompositeToolIds === true) : stripped;
321
356
  if (stripped !== message || sanitized !== stripped) changed = true;
322
357
  filtered.push(sanitized);
323
358
  }
@@ -524,6 +559,7 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
524
559
  if (!event || typeof event !== "object" || !("messages" in event) || !Array.isArray(event.messages)) return undefined;
525
560
  const messages = stripParentOnlySubagentMessages(event.messages, {
526
561
  sanitizeToolIds: !COMPOSITE_TOOL_ID_APIS.has(ctx?.model?.api ?? ""),
562
+ preserveBoundedCompositeToolIds: ctx?.model?.api === "openai-codex-responses",
527
563
  preserveFanoutToolHistory: config.fanoutChild,
528
564
  });
529
565
  if (messages === event.messages) return undefined;
@@ -551,19 +587,12 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config?:
551
587
  pi.setSessionName(childSessionName);
552
588
  }
553
589
 
554
- const { inheritProjectContext, inheritGlobalContext, inheritSkills } = config;
555
- const fanoutChild = config.fanoutChild;
556
- let rewritten = event.systemPrompt;
557
- if (inheritProjectContext !== undefined || inheritGlobalContext !== undefined || inheritSkills !== undefined || fanoutChild) {
558
- rewritten = rewriteSubagentPrompt(event.systemPrompt, {
559
- inheritProjectContext: inheritProjectContext ?? true,
560
- inheritGlobalContext: inheritGlobalContext ?? true,
561
- inheritSkills: inheritSkills ?? true,
562
- fanoutChild,
563
- structuredOutput: Boolean(config.structuredOutput),
564
- });
565
- }
566
- if (rewritten === event.systemPrompt) return;
567
- return { systemPrompt: rewritten };
590
+ // Filter the inputs instead of returning a prompt; the boundary hook appends the boundary last.
591
+ if (!rewritesChildPrompt(config)) return;
592
+ filterChildPromptOptions((event as BeforeAgentStartEvent).systemPromptOptions, {
593
+ inheritProjectContext: config.inheritProjectContext ?? true,
594
+ inheritGlobalContext: config.inheritGlobalContext ?? true,
595
+ inheritSkills: config.inheritSkills ?? true,
596
+ });
568
597
  });
569
598
  }
@@ -13,6 +13,6 @@ export function workflowAsyncChildSteeringGuidance(status: AsyncStatus, state?:
13
13
  if (ids.size === 0) return [];
14
14
  return [
15
15
  "Async children recorded as running; direct steering rechecks controls. Choose an exact child ID (queued does not mean consumed):",
16
- ...[...ids].map((id) => ` subagent({ action: "steer", id: "${id}", mode: "follow_up", message: "..." })`),
16
+ ...[...ids].map((id) => ` subagent({ action: "steer", id: "${id}", message: "...", options: { mode: "follow_up" } })`),
17
17
  ];
18
18
  }
@@ -0,0 +1,160 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawnSync } from "node:child_process";
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import { writePrivateAtomicJson } from "../../shared/atomic-json.ts";
6
+ import { readParallelHandoffManifest } from "./parallel-handoff.ts";
7
+ import { buildWorktreeCleanupPlan, isRegisteredCleanupWorktree, resolveCleanupRepoRoot, samePath, worktreeCleanupContentPayload, worktreeCleanupPlanPath, WORKTREE_CLEANUP_PLAN_TTL_MS, type BuildWorktreeCleanupPlanInput, type WorktreeCleanupPlan, type WorktreeCleanupPlanEntry } from "./worktree-cleanup-plan.ts";
8
+ import { withHandoffWriteLock, withRepositoryWorktreeLock } from "./worktree-lock.ts";
9
+ import { withWorktreeTransaction } from "./worktree.ts";
10
+
11
+ export type CleanupReceipt = {
12
+ version: 1; planId: string; repoRoot: string; contentHash: string;
13
+ state: "applying" | "complete" | "partial";
14
+ startedAt: number; completedAt?: number; error?: string;
15
+ entries: Array<{ path: string; branch: string; state: "removing" | "removed" | "kept" | "failed"; reason: string }>;
16
+ };
17
+
18
+ function assertContainedRealPath(repoRoot: string, candidate: string, create = false): void {
19
+ const relative = path.relative(repoRoot, candidate);
20
+ if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) throw new Error("Cleanup evidence must be inside the selected repository.");
21
+ let current = repoRoot;
22
+ for (const segment of relative.split(path.sep)) {
23
+ current = path.join(current, segment);
24
+ if (!fs.existsSync(current) && create) fs.mkdirSync(current, { mode: 0o700 });
25
+ const stat = fs.lstatSync(current);
26
+ if (stat.isSymbolicLink()) throw new Error(`Cleanup evidence cannot use a symlink: ${current}`);
27
+ }
28
+ }
29
+
30
+ export function loadReviewedCleanupPlan(repo: string, planId: string, now = Date.now()): WorktreeCleanupPlan {
31
+ const repoRoot = resolveCleanupRepoRoot(repo);
32
+ const file = worktreeCleanupPlanPath(repoRoot, planId);
33
+ assertContainedRealPath(repoRoot, file);
34
+ const stat = fs.statSync(file);
35
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024) throw new Error("Cleanup plan is not a bounded regular file.");
36
+ const plan = JSON.parse(fs.readFileSync(file, "utf-8")) as WorktreeCleanupPlan;
37
+ if (plan.version !== 1 || plan.planId !== planId || plan.repoRoot !== repoRoot || !Number.isFinite(plan.createdAt) || !Number.isFinite(plan.expiresAt) || plan.createdAt > now || (plan.expiresAt <= now && !fs.existsSync(file.replace(/\.json$/, ".claim"))) || plan.expiresAt - plan.createdAt !== WORKTREE_CLEANUP_PLAN_TTL_MS) throw new Error("Cleanup plan is invalid, expired, or belongs to another repository.");
38
+ if (!Array.isArray(plan.entries) || plan.entries.length > 512 || !Array.isArray(plan.baseDirs) || plan.baseDirs.length !== 1 || !plan.baseDirs.every((item) => typeof item === "string" && path.isAbsolute(item)) || !Array.isArray(plan.metadataPaths) || !plan.metadataPaths.every((item) => typeof item === "string" && path.isAbsolute(item)) || !Array.isArray(plan.pruneCandidates)) throw new Error("Cleanup plan has invalid inventory fields.");
39
+ const paths = new Set<string>();
40
+ for (const entry of plan.entries) {
41
+ if (!entry || typeof entry.path !== "string" || !path.isAbsolute(entry.path) || typeof entry.branch !== "string" || !["remove", "keep", "unknown"].includes(entry.decision) || !entry.preconditions || entry.preconditions.path !== entry.path || entry.preconditions.branch !== entry.branch || !Array.isArray(entry.reasons) || !entry.reasons.every((reason) => typeof reason === "string") || paths.has(entry.path)) throw new Error("Cleanup plan has invalid or duplicate entries.");
42
+ paths.add(entry.path);
43
+ }
44
+ const hash = createHash("sha256").update(JSON.stringify(worktreeCleanupContentPayload(plan))).digest("hex");
45
+ if (plan.contentHash !== hash) throw new Error("Cleanup plan content hash does not match; create and review a fresh plan.");
46
+ return plan;
47
+ }
48
+
49
+ function recordRemoval(entry: WorktreeCleanupPlanEntry): void {
50
+ const manifest = readParallelHandoffManifest(entry.handoffPath!);
51
+ if (!manifest || manifest.runId !== entry.runId) throw new Error("Handoff ownership changed before recording removal.");
52
+ const tasks = manifest.groups.flatMap((group) => group.cleanup.tasks).filter((task) => task.index === entry.taskIndex && samePath(path.resolve(path.dirname(entry.handoffPath!), task.path), entry.path) && task.branch === entry.branch);
53
+ if (tasks.length !== 1) throw new Error("Handoff task no longer identifies exactly one removed worktree.");
54
+ if (tasks[0]!.worktreeRemoved) return;
55
+ tasks[0]!.worktreeRemoved = true;
56
+ tasks[0]!.branchRemoved = false;
57
+ tasks[0]!.preserved = true;
58
+ tasks[0]!.reason = "reviewed cleanup removed worktree; local branch retained";
59
+ manifest.updatedAt = Date.now();
60
+ writePrivateAtomicJson(entry.handoffPath!, manifest);
61
+ }
62
+
63
+ export async function applyReviewedCleanupPlan(input: {
64
+ repo: string; planId: string; authorized: boolean; signal?: AbortSignal;
65
+ foregroundRunOwnership?: BuildWorktreeCleanupPlanInput["foregroundRunOwnership"];
66
+ /** Internal retention seam: shrink the reviewed batch while holding the repository lock. */
67
+ select?: (plan: WorktreeCleanupPlan) => Set<string>;
68
+ }): Promise<{ receipt: CleanupReceipt; receiptPath: string; reused: boolean }> {
69
+ if (!input.authorized) throw new Error("Worktree cleanup requires discardWorktree authorization.");
70
+ return withWorktreeTransaction(() => withRepositoryWorktreeLock(input.repo, async () => {
71
+ const plan = loadReviewedCleanupPlan(input.repo, input.planId);
72
+ const claimPath = worktreeCleanupPlanPath(plan.repoRoot, plan.planId).replace(/\.json$/, ".claim");
73
+ const receiptPath = path.join(claimPath, "receipt.json");
74
+ assertContainedRealPath(plan.repoRoot, path.dirname(claimPath));
75
+ try { fs.mkdirSync(claimPath, { mode: 0o700 }); }
76
+ catch (error) {
77
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
78
+ assertContainedRealPath(plan.repoRoot, receiptPath);
79
+ // A claimed plan is never destructively replayed, even after interruption.
80
+ const receipt = JSON.parse(fs.readFileSync(receiptPath, "utf-8")) as CleanupReceipt;
81
+ if (receipt.version !== 1 || receipt.planId !== plan.planId || receipt.repoRoot !== plan.repoRoot || receipt.contentHash !== plan.contentHash || !Array.isArray(receipt.entries) || !["applying", "complete", "partial"].includes(receipt.state)) throw new Error("Claimed cleanup plan has an invalid receipt; inspect it before creating a fresh plan.");
82
+ // Reconcile only a journaled attempt whose directory and Git registration
83
+ // are both gone. A recreated path is never changed or removed on replay.
84
+ for (const entry of plan.entries.filter((entry) => receipt.state !== "complete" && entry.decision === "remove" && receipt.entries.some((item) => (item?.state === "removing" || item?.state === "removed") && item.path === entry.path && item.branch === entry.branch))) {
85
+ await new Promise<void>((resolve) => setImmediate(resolve));
86
+ input.signal?.throwIfAborted();
87
+ try { fs.lstatSync(entry.path); continue; }
88
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
89
+ if (!isRegisteredCleanupWorktree(plan.repoRoot, entry.path) && entry.handoffPath) {
90
+ const item = receipt.entries.find((item) => item.path === entry.path && item.branch === entry.branch)!;
91
+ if (item.state === "removing") {
92
+ item.state = "removed";
93
+ item.reason = "interrupted removal reconciled; local branch retained";
94
+ writePrivateAtomicJson(receiptPath, receipt);
95
+ }
96
+ withHandoffWriteLock(entry.handoffPath, () => recordRemoval(entry));
97
+ }
98
+ }
99
+ return { receipt, receiptPath, reused: true };
100
+ }
101
+ const receipt: CleanupReceipt = { version: 1, planId: plan.planId, repoRoot: plan.repoRoot, contentHash: plan.contentHash, state: "applying", startedAt: Date.now(), entries: [] };
102
+ writePrivateAtomicJson(receiptPath, receipt);
103
+ try {
104
+ const selected = input.select?.(plan);
105
+ for (const entry of plan.entries.filter((item) => item.decision === "remove")) {
106
+ await new Promise<void>((resolve) => setImmediate(resolve));
107
+ input.signal?.throwIfAborted();
108
+ if (selected && !selected.has(entry.path)) {
109
+ receipt.entries.push({ path: entry.path, branch: entry.branch, state: "kept", reason: "outside the current retention excess" });
110
+ } else {
111
+ try {
112
+ if (!entry.handoffPath) throw new Error("Reviewed entry has no handoff ownership.");
113
+ withHandoffWriteLock(entry.handoffPath, () => {
114
+ const manifest = readParallelHandoffManifest(entry.handoffPath!);
115
+ if (!manifest || manifest.runId !== entry.runId) throw new Error("Handoff ownership changed before cleanup validation.");
116
+ const fresh = buildWorktreeCleanupPlan({ repo: plan.repoRoot, candidatePaths: [entry.path], handoffPaths: plan.metadataPaths, worktreeBaseDir: path.dirname(plan.baseDirs[0]!), foregroundRunOwnership: input.foregroundRunOwnership });
117
+ const candidate = fresh.entries.find((item) => item.path === entry.path);
118
+ if (fresh.warnings?.some((warning) => /capped|failed to inspect/.test(warning)) || !candidate || candidate.decision !== "remove" || candidate.handoffPath !== entry.handoffPath || candidate.runId !== entry.runId || candidate.taskIndex !== entry.taskIndex || candidate.patchPath !== entry.patchPath || JSON.stringify(candidate.preconditions) !== JSON.stringify(entry.preconditions)) {
119
+ receipt.entries.push({ path: entry.path, branch: entry.branch, state: "kept", reason: candidate?.reasons.join("; ") || "reviewed ownership or Git facts changed" });
120
+ return;
121
+ }
122
+ input.signal?.throwIfAborted();
123
+ const journalEntry: CleanupReceipt["entries"][number] = { path: entry.path, branch: entry.branch, state: "removing", reason: "removal prepared; outcome not yet recorded" };
124
+ receipt.entries.push(journalEntry);
125
+ writePrivateAtomicJson(receiptPath, receipt); // Admit the attempt before Git can remove anything.
126
+ const removed = spawnSync("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
127
+ if (removed.status !== 0) throw new Error(removed.error?.message || removed.stderr.trim() || "git worktree remove failed");
128
+ journalEntry.state = "removed";
129
+ journalEntry.reason = "worktree removed; local branch retained";
130
+ writePrivateAtomicJson(receiptPath, receipt); // Evidence precedes secondary manifest bookkeeping.
131
+ recordRemoval(entry);
132
+ });
133
+ } catch (error) {
134
+ const reason = error instanceof Error ? error.message : String(error);
135
+ const removed = receipt.entries.find((item) => item.path === entry.path && item.state === "removed");
136
+ if (removed) { removed.reason += `; removal bookkeeping failed: ${reason}`; receipt.error = reason; }
137
+ else {
138
+ const pending = receipt.entries.find((item) => item.path === entry.path && item.state === "removing");
139
+ if (pending) { pending.reason += `; operation failed: ${reason}`; receipt.error = reason; }
140
+ else receipt.entries.push({ path: entry.path, branch: entry.branch, state: "failed", reason });
141
+ }
142
+ }
143
+ }
144
+ writePrivateAtomicJson(receiptPath, receipt);
145
+ }
146
+ receipt.state = !receipt.error && receipt.entries.every((entry) => entry.state === "removed") ? "complete" : "partial";
147
+ } catch (error) {
148
+ receipt.state = "partial";
149
+ receipt.error = error instanceof Error ? error.message : String(error);
150
+ }
151
+ receipt.completedAt = Date.now();
152
+ writePrivateAtomicJson(receiptPath, receipt);
153
+ return { receipt, receiptPath, reused: false };
154
+ }, { signal: input.signal }));
155
+ }
156
+
157
+ export function formatCleanupReceipt(result: { receipt: CleanupReceipt; receiptPath: string; reused: boolean }): string {
158
+ const { receipt } = result;
159
+ return [`Worktree cleanup ${receipt.planId}: ${receipt.state}${result.reused ? " (previous receipt; plan not replayed)" : ""}`, "Local branches retained.", ...receipt.entries.map((entry) => `- ${entry.path}: ${entry.state}; ${entry.reason}`), ...(receipt.error ? [receipt.error] : []), `Receipt: ${result.receiptPath}`].join("\n");
160
+ }
@@ -14,7 +14,7 @@ import type {
14
14
  ParallelHandoffManifest,
15
15
  } from "../../shared/types.ts";
16
16
  import { getAgentDir } from "../../shared/utils.ts";
17
- import { isTerminalParallelHandoffChildStatus } from "./parallel-handoff.ts";
17
+ import { isTerminalParallelHandoffChildStatus, readParallelHandoffManifest } from "./parallel-handoff.ts";
18
18
  import { MACHINE_DIFF_OPTIONS, validateWorktreePatchRepresentsCurrentWorktree } from "./worktree.ts";
19
19
 
20
20
  export const WORKTREE_CLEANUP_PLAN_VERSION = 1 as const;
@@ -72,6 +72,8 @@ export interface WorktreeCleanupPlan {
72
72
 
73
73
  export interface BuildWorktreeCleanupPlanInput {
74
74
  repo: string;
75
+ /** Internal maintenance seam: inspect only these paths with the same safety predicates. */
76
+ candidatePaths?: string[];
75
77
  handoffPath?: string;
76
78
  /** Internal test and migration seam for explicitly supplied handoff records. */
77
79
  handoffPaths?: string[];
@@ -99,6 +101,7 @@ interface GitWorktreeRecord {
99
101
  head: string;
100
102
  branch?: string;
101
103
  prunable?: string;
104
+ locked?: boolean;
102
105
  }
103
106
 
104
107
  interface ManifestMetadataRecord {
@@ -194,16 +197,16 @@ function comparablePath(candidate: string): string {
194
197
  return process.platform === "win32" ? normalized.toLowerCase() : normalized;
195
198
  }
196
199
 
197
- function samePath(left: string, right: string): boolean {
200
+ export function samePath(left: string, right: string): boolean {
198
201
  if (comparablePath(left) === comparablePath(right)) return true;
199
202
  if (process.platform !== "win32") return false;
200
203
  // Git for Windows and Node can spell the same temp directory with different
201
204
  // drive/short-name aliases. The directory identity is the final bounded
202
205
  // fallback; never accept aliases when the filesystem cannot prove identity.
203
206
  try {
204
- const leftStat = fs.statSync(left);
205
- const rightStat = fs.statSync(right);
206
- return leftStat.dev !== 0 && leftStat.ino !== 0 && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
207
+ const leftStat = fs.statSync(left, { bigint: true });
208
+ const rightStat = fs.statSync(right, { bigint: true });
209
+ return leftStat.dev !== 0n && leftStat.ino !== 0n && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
207
210
  } catch {
208
211
  return false;
209
212
  }
@@ -239,7 +242,7 @@ function validatePlanId(planId: string): string {
239
242
  return planId;
240
243
  }
241
244
 
242
- function resolveRepoRoot(repo: string): string {
245
+ export function resolveCleanupRepoRoot(repo: string): string {
243
246
  const requested = path.resolve(repo);
244
247
  const toplevel = runGitChecked(requested, ["rev-parse", "--show-toplevel"]);
245
248
  return realpathExisting(toplevel);
@@ -288,6 +291,7 @@ export function parseGitWorktreeList(raw: string): GitWorktreeRecord[] {
288
291
  if (line.startsWith("HEAD ")) current.head = line.slice("HEAD ".length).trim();
289
292
  else if (line.startsWith("branch refs/heads/")) current.branch = line.slice("branch refs/heads/".length).trim();
290
293
  else if (line === "detached") delete current.branch;
294
+ else if (line === "locked" || line.startsWith("locked ")) current.locked = true;
291
295
  else if (line.startsWith("prunable ")) current.prunable = line.slice("prunable ".length).trim();
292
296
  }
293
297
  flush();
@@ -300,6 +304,10 @@ function listGitWorktrees(repoRoot: string): GitWorktreeRecord[] {
300
304
  return parseGitWorktreeList(result.stdout);
301
305
  }
302
306
 
307
+ export function isRegisteredCleanupWorktree(repoRoot: string, candidate: string): boolean {
308
+ return listGitWorktrees(repoRoot).some((tree) => samePath(tree.path, candidate));
309
+ }
310
+
303
311
  function readJsonFile(filePath: string): unknown {
304
312
  return JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
305
313
  }
@@ -313,11 +321,11 @@ function readManifest(manifestPath: string): ManifestReadResult {
313
321
  const stat = fs.lstatSync(manifestPath);
314
322
  if (stat.isSymbolicLink() || !stat.isFile()) return { error: `parallel handoff manifest is not a regular file: ${manifestPath}` };
315
323
  if (stat.size > MAX_METADATA_FILE_BYTES) return { error: `parallel handoff manifest exceeds the ${MAX_METADATA_FILE_BYTES}-byte limit: ${manifestPath}` };
316
- const parsed = readJsonFile(manifestPath);
317
- if (!isRecord(parsed) || parsed.version !== 1 || !Array.isArray(parsed.groups)) {
324
+ const parsed = readParallelHandoffManifest(manifestPath);
325
+ if (!parsed) {
318
326
  return { error: `invalid parallel handoff manifest version or groups: ${manifestPath}` };
319
327
  }
320
- return { manifest: parsed as unknown as ParallelHandoffManifest };
328
+ return { manifest: parsed };
321
329
  } catch (error) {
322
330
  const code = error && typeof error === "object" && "code" in error ? (error as NodeJS.ErrnoException).code : undefined;
323
331
  if (code === "ENOENT") return { error: `parallel handoff manifest not found: ${manifestPath}` };
@@ -423,11 +431,10 @@ function loadMetadata(input: BuildWorktreeCleanupPlanInput, repoRoot: string): {
423
431
  const discovered = discoverHandoffPaths(repoRoot, input);
424
432
  const records: ManifestMetadataRecord[] = [];
425
433
  const warnings = [...discovered.warnings];
426
- const explicitPath = input.handoffPath ? path.isAbsolute(input.handoffPath) ? path.resolve(input.handoffPath) : path.resolve(repoRoot, input.handoffPath) : undefined;
427
434
  for (const manifestPath of discovered.paths) {
428
435
  const result = readManifest(manifestPath);
429
436
  if (!result.manifest) {
430
- if (explicitPath && comparablePath(manifestPath) === comparablePath(explicitPath)) warnings.push(result.error!);
437
+ warnings.push(result.error!);
431
438
  continue;
432
439
  }
433
440
  const manifestRoot = resolveExistingPath(manifestPath);
@@ -526,7 +533,7 @@ function buildEntryBase(input: {
526
533
  metadata?: ManifestMetadataRecord;
527
534
  targetHead: string;
528
535
  }): WorktreeCleanupPlanEntry {
529
- const recordedBaseDir = path.dirname(input.path);
536
+ const recordedBaseDir = input.metadata?.task.recordedBaseDir;
530
537
  const patchPath = input.metadata ? metadataPatchPath(input.metadata) : undefined;
531
538
  return {
532
539
  path: input.path,
@@ -544,7 +551,7 @@ function buildEntryBase(input: {
544
551
  branch: input.branch,
545
552
  ...(input.git?.head ? { worktreeHead: input.git.head } : {}),
546
553
  ...(input.metadata?.group.baseCommit ? { baseCommit: input.metadata.group.baseCommit } : {}),
547
- recordedBaseDir,
554
+ ...(recordedBaseDir ? { recordedBaseDir } : {}),
548
555
  targetRef: input.targetHead,
549
556
  },
550
557
  };
@@ -626,8 +633,14 @@ function buildManagedEntry(input: {
626
633
  const extensionsDir = path.join(getAgentDir(), "extensions");
627
634
  if (pathInside(extensionsDir, pathInspection.realpath)) return blockedEntry(entry, "ineligible", "keep", `worktree real path is inside Pi extensions directory '${extensionsDir}'`);
628
635
  if (input.containmentInvalid || !pathInside(baseDir, pathInspection.realpath, true)) return blockedEntry(entry, "ineligible", "keep", `worktree real path is outside configured base directory '${baseDir}'`);
636
+ const recordedBaseDir = record.task.recordedBaseDir;
637
+ if (typeof recordedBaseDir !== "string" || !path.isAbsolute(recordedBaseDir)) return blockedEntry(entry, "unknown", "keep", "handoff metadata has no creation-time base directory proof");
638
+ // Compare the saved canonical string, without following a newly replaced ancestor.
639
+ const creationRelative = path.relative(recordedBaseDir, pathInspection.realpath);
640
+ if (!creationRelative || creationRelative === ".." || creationRelative.startsWith(`..${path.sep}`) || path.isAbsolute(creationRelative)) return blockedEntry(entry, "ineligible", "keep", `worktree real path is outside its creation-time recorded base directory '${recordedBaseDir}'`);
629
641
 
630
642
  if (rootPath === comparablePath(pathInspection.realpath)) return blockedEntry(entry, "ineligible", "keep", "worktree is the repository root");
643
+ if (git.locked) return blockedEntry(entry, "ineligible", "keep", "Git worktree is locked");
631
644
  if (!git.branch) return blockedEntry(entry, "unknown", "unknown", "detached worktrees have no metadata-recorded branch");
632
645
  if (record.task.branch !== git.branch) return blockedEntry(entry, "unknown", "unknown", `metadata branch '${record.task.branch}' does not match Git branch '${git.branch}'`);
633
646
  if (record.task.worktreeRemoved) return blockedEntry(entry, "stale", "unknown", "handoff metadata already records this worktree as removed");
@@ -646,6 +659,9 @@ function buildManagedEntry(input: {
646
659
  return blockedEntry(entry, "ineligible", "keep", "metadata-recorded branch is checked out at the repository root");
647
660
  }
648
661
 
662
+ const retainedSession = record.child.sessionPath ?? record.status?.steps?.[record.child.index]?.sessionFile ?? record.status?.sessionFile;
663
+ if (typeof retainedSession === "string" && retainedSession.trim()) return blockedEntry(entry, "ineligible", "keep", "retained child resume still has a recorded session dependency");
664
+
649
665
  const runState = inspectRunState(record, input.now, foregroundRunOwnership);
650
666
  if (runState.kind === "unknown") return blockedEntry(entry, "unknown", "unknown", runState.reason ?? "owning run state is unknown");
651
667
  if (runState.kind === "active") return blockedEntry(entry, "active", "keep", runState.reason ?? "owning run is active");
@@ -668,6 +684,10 @@ function buildManagedEntry(input: {
668
684
  entry.preconditions.statusDigest = status.digest;
669
685
  if (status.output && status.output.trim()) return blockedEntry(entry, "dirty", "keep", "worktree has uncommitted or untracked changes");
670
686
 
687
+ const ignored = runGit(worktreePath, ["ls-files", "--others", "--ignored", "--exclude-standard", "-z"]);
688
+ if (ignored.status !== 0) return blockedEntry(entry, "unknown", "unknown", `ignored-file inspection failed: ${gitFailure(ignored, "git ls-files")}`);
689
+ if (ignored.stdout) return blockedEntry(entry, "ineligible", "keep", "worktree contains ignored files; cleanup preserves them");
690
+
671
691
  const diff = runGit(worktreePath, ["diff", "--quiet", ...MACHINE_DIFF_OPTIONS, resolvedBase.value, "--"]);
672
692
  if (diff.status !== 0 && diff.status !== 1) return blockedEntry(entry, "unknown", "unknown", `git diff safety check failed: ${gitFailure(diff, "git diff")}`);
673
693
  const ancestor = runGit(repoRoot, ["merge-base", "--is-ancestor", git.head, targetHead]);
@@ -704,7 +724,7 @@ function buildManagedEntry(input: {
704
724
 
705
725
  entry.state = "safe";
706
726
  entry.decision = "remove";
707
- entry.willDeleteBranch = branchTipIsAncestor;
727
+ entry.willDeleteBranch = false;
708
728
  entry.reasons.push("extension-owned metadata, terminal run, contained clean worktree, and local divergence checks passed");
709
729
  if (!branchTipIsAncestor) entry.reasons.push("local branch tip is not an ancestor of target HEAD; future apply must retain the branch");
710
730
  return entry;
@@ -723,7 +743,7 @@ function buildMissingMetadataEntry(input: { record: ManifestMetadataRecord; targ
723
743
  return blockedEntry(entry, "stale", "unknown", "handoff metadata records a worktree that is not present in Git worktree state");
724
744
  }
725
745
 
726
- function contentPayload(plan: Omit<WorktreeCleanupPlan, "contentHash" | "planId" | "createdAt" | "expiresAt">): unknown {
746
+ export function worktreeCleanupContentPayload(plan: Omit<WorktreeCleanupPlan, "contentHash" | "planId" | "createdAt" | "expiresAt">): unknown {
727
747
  return {
728
748
  version: plan.version,
729
749
  repoRoot: plan.repoRoot,
@@ -741,7 +761,7 @@ function stableEntrySort(left: WorktreeCleanupPlanEntry, right: WorktreeCleanupP
741
761
 
742
762
  export function buildWorktreeCleanupPlan(input: BuildWorktreeCleanupPlanInput): WorktreeCleanupPlan {
743
763
  if (typeof input.repo !== "string" || !input.repo.trim()) throw new Error("worktree cleanup plan requires a repository path");
744
- const repoRoot = resolveRepoRoot(input.repo);
764
+ const repoRoot = resolveCleanupRepoRoot(input.repo);
745
765
  const now = input.now ?? Date.now();
746
766
  if (!Number.isFinite(now)) throw new Error("worktree cleanup plan timestamp must be finite");
747
767
  const baseDir = resolveCleanupBaseDir(repoRoot, input.worktreeBaseDir);
@@ -762,6 +782,7 @@ export function buildWorktreeCleanupPlan(input: BuildWorktreeCleanupPlanInput):
762
782
  const entries: WorktreeCleanupPlanEntry[] = [];
763
783
  const matchedMetadataRecords = new Set<ManifestMetadataRecord>();
764
784
  for (const git of linkedGit) {
785
+ if (input.candidatePaths && !input.candidatePaths.some((candidate) => samePath(candidate, git.path))) continue;
765
786
  const records = metadataByPath.get(comparablePath(git.path)) ?? (git.branch
766
787
  ? metadata.records.filter((record) => record.task.branch === git.branch && samePath(metadataRecordPath(record), git.path))
767
788
  : []);
@@ -807,7 +828,7 @@ export function buildWorktreeCleanupPlan(input: BuildWorktreeCleanupPlanInput):
807
828
  pruneCandidates,
808
829
  ...(warnings.length ? { warnings: [...new Set(warnings)].sort() } : {}),
809
830
  };
810
- const contentHash = sha256(JSON.stringify(contentPayload(basePlan)));
831
+ const contentHash = sha256(JSON.stringify(worktreeCleanupContentPayload(basePlan)));
811
832
  const planId = validatePlanId(input.planId ?? randomUUID());
812
833
  return {
813
834
  ...basePlan,
@@ -837,7 +858,7 @@ function formatPlanEntry(entry: WorktreeCleanupPlanEntry): string {
837
858
  export function formatWorktreeCleanupPlan(created: CreatedWorktreeCleanupPlan): string {
838
859
  const { plan, planPath } = created;
839
860
  const removable = plan.entries.filter((entry) => entry.decision === "remove");
840
- const branches = removable.filter((entry) => entry.willDeleteBranch === true);
861
+
841
862
  const kept = plan.entries.filter((entry) => entry.decision === "keep");
842
863
  const unknown = plan.entries.filter((entry) => entry.decision === "unknown");
843
864
  const section = (title: string, entries: WorktreeCleanupPlanEntry[], empty: string): string[] => [
@@ -852,7 +873,7 @@ export function formatWorktreeCleanupPlan(created: CreatedWorktreeCleanupPlan):
852
873
  "",
853
874
  ...section("Will remove", removable, "none"),
854
875
  "",
855
- ...section("Will delete local branches", branches, "none (plan-only mode; no branch will be deleted)"),
876
+ "Local branches: all retained, including after apply.",
856
877
  "",
857
878
  ...section("Will keep, with reasons", kept, "none"),
858
879
  "",
@@ -864,6 +885,7 @@ export function formatWorktreeCleanupPlan(created: CreatedWorktreeCleanupPlan):
864
885
  "",
865
886
  `Plan saved: ${planPath}`,
866
887
  "Plan-only mode: no worktrees or branches were removed.",
888
+ `Apply this reviewed plan: subagent({ action: "worktree.cleanup", options: { mode: "apply", repo: ${JSON.stringify(plan.repoRoot)}, planId: ${JSON.stringify(plan.planId)} } })`,
867
889
  ];
868
890
  return lines.join("\n");
869
891
  }
@@ -0,0 +1,29 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { tryLease } from "../../shared/file-lease.ts";
5
+
6
+ export function withHandoffWriteLock<T>(manifestPath: string, action: () => T): T {
7
+ const requested = path.resolve(manifestPath);
8
+ fs.mkdirSync(path.dirname(requested), { recursive: true });
9
+ const absolute = path.join(fs.realpathSync.native(path.dirname(requested)), path.basename(requested));
10
+ const release = tryLease(`${absolute}.write-lock`);
11
+ if (!release) throw new Error(`Handoff is being updated or cleaned: ${absolute}. Retry after the current operation completes.`);
12
+ try { return action(); } finally { release(); }
13
+ }
14
+
15
+ export async function withRepositoryWorktreeLock<T>(repo: string, action: () => T | Promise<T>, options: { signal?: AbortSignal; waitMs?: number } = {}): Promise<T> {
16
+ const git = spawnSync("git", ["-C", repo, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf-8", windowsHide: true });
17
+ if (git.status !== 0) throw new Error(git.error?.message || git.stderr.trim() || "Cannot resolve Git common directory.");
18
+ const lockPath = path.join(fs.realpathSync(git.stdout.trim()), "pi-subagents-worktree.lock");
19
+ const deadline = Date.now() + (options.waitMs ?? 2_000);
20
+ while (true) {
21
+ options.signal?.throwIfAborted();
22
+ const release = tryLease(lockPath);
23
+ if (release) {
24
+ try { return await action(); } finally { release(); }
25
+ }
26
+ if (Date.now() >= deadline) throw new Error("Repository worktree maintenance is busy; retry later.");
27
+ await new Promise<void>((resolve) => setTimeout(resolve, 25));
28
+ }
29
+ }