@fitlab-ai/agent-infra 0.9.13 → 0.9.15

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 (428) hide show
  1. package/README.md +10 -0
  2. package/README.zh-CN.md +10 -0
  3. package/bin/cli.ts +26 -9
  4. package/bin/internal-cli.sh +45 -0
  5. package/dist/bin/cli.js +173 -157
  6. package/dist/bin/internal-cli.js +126 -42
  7. package/dist/lib/agent-client.js +5 -0
  8. package/dist/lib/agent-clients/adapters/codex-lifecycle/capability-store.js +165 -27
  9. package/dist/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.js +3 -2
  10. package/dist/lib/defaults.json +103 -103
  11. package/dist/lib/fs/durable-write.js +37 -0
  12. package/dist/lib/fs/file-lock.js +111 -0
  13. package/dist/lib/host-control/audit.js +19 -0
  14. package/dist/lib/host-control/client.js +142 -0
  15. package/dist/lib/host-control/command.js +49 -0
  16. package/dist/lib/host-control/path.js +160 -0
  17. package/dist/lib/host-control/secure-fs.js +140 -0
  18. package/dist/lib/host-control/server.js +159 -0
  19. package/dist/lib/host-control/service.js +112 -0
  20. package/dist/lib/init.js +11 -2
  21. package/dist/lib/internal/agent-client.js +5 -2
  22. package/dist/lib/internal/cli-route-inventory.js +154 -0
  23. package/dist/lib/internal/codex-lifecycle.js +15 -12
  24. package/dist/lib/internal/codex-sandbox-controller.js +8 -2
  25. package/dist/lib/internal/demo-promotion.js +322 -0
  26. package/dist/lib/internal/demo-transcript.js +454 -0
  27. package/dist/lib/internal/git-workflow.js +10 -6
  28. package/dist/lib/internal/host-control.js +28 -0
  29. package/dist/lib/internal/manual-validation.js +322 -0
  30. package/dist/lib/internal/platform-checks.js +16 -4
  31. package/dist/lib/internal/platform-comment.js +16 -4
  32. package/dist/lib/internal/platform-context.js +4 -1
  33. package/dist/lib/internal/platform-issue.js +12 -4
  34. package/dist/lib/internal/platform-metadata.js +88 -0
  35. package/dist/lib/internal/platform-pr-review.js +16 -3
  36. package/dist/lib/internal/platform-pr.js +42 -14
  37. package/dist/lib/internal/platform-release-notes.js +6 -3
  38. package/dist/lib/internal/platform-security.js +93 -0
  39. package/dist/lib/internal/pr-review-grade.js +14 -3
  40. package/dist/lib/internal/release-workflow.js +82 -89
  41. package/dist/lib/internal/sandbox-control.js +171 -7
  42. package/dist/lib/internal/task-activity.js +13 -4
  43. package/dist/lib/internal/task-artifact.js +19 -107
  44. package/dist/lib/internal/task-context.js +4 -1
  45. package/dist/lib/internal/task-create.js +48 -14
  46. package/dist/lib/internal/task-delivery.js +4 -1
  47. package/dist/lib/internal/task-event.js +38 -35
  48. package/dist/lib/internal/task-finalization.js +4 -1
  49. package/dist/lib/internal/task-invalidation.js +4 -1
  50. package/dist/lib/internal/task-ledger.js +12 -1
  51. package/dist/lib/internal/task-lifecycle.js +4 -1
  52. package/dist/lib/internal/task-operation-registry.js +519 -0
  53. package/dist/lib/internal/task-orchestration.js +12 -0
  54. package/dist/lib/internal/task-override.js +10 -3
  55. package/dist/lib/internal/task-qualification.js +90 -0
  56. package/dist/lib/internal/task-review.js +10 -52
  57. package/dist/lib/internal/task-short-id.js +11 -1
  58. package/dist/lib/internal/task-snapshot.js +4 -1
  59. package/dist/lib/internal/task-validate.js +37 -12
  60. package/dist/lib/internal/task-verify.js +5 -1
  61. package/dist/lib/internal/task-warning.js +8 -1
  62. package/dist/lib/owned-path.js +33 -0
  63. package/dist/lib/platform/check-status.js +11 -0
  64. package/dist/lib/platform/comment-safety.js +229 -0
  65. package/dist/lib/platform/completion-backfill.js +1 -1
  66. package/dist/lib/platform/github-data.js +241 -0
  67. package/dist/lib/platform/github-provider.js +248 -26
  68. package/dist/lib/platform/issue-comments.js +146 -34
  69. package/dist/lib/platform/issues.js +1 -179
  70. package/dist/lib/platform/pr-change-report.js +6 -12
  71. package/dist/lib/platform/pr-checks.js +12 -65
  72. package/dist/lib/platform/pr-summary.js +83 -10
  73. package/dist/lib/platform/provider-contract.d.ts +67 -1
  74. package/dist/lib/platform/provider-contract.js +6 -2
  75. package/dist/lib/platform/provider-validation.js +76 -3
  76. package/dist/lib/platform/pull-requests.js +117 -275
  77. package/dist/lib/platform/repository-metadata.js +377 -0
  78. package/dist/lib/platform/security-alerts.js +155 -0
  79. package/dist/lib/platform/snapshots.js +2 -0
  80. package/dist/lib/platform/verification-sync.js +154 -162
  81. package/dist/lib/process-data/index.js +7 -0
  82. package/dist/lib/release/workflow.js +1 -1
  83. package/dist/lib/run/index.js +5 -0
  84. package/dist/lib/sandbox/commands/control-status.js +22 -0
  85. package/dist/lib/sandbox/commands/create.js +39 -8
  86. package/dist/lib/sandbox/commands/ls.js +5 -0
  87. package/dist/lib/sandbox/commands/rm.js +3 -807
  88. package/dist/lib/sandbox/commands/show.js +16 -0
  89. package/dist/lib/sandbox/control/audit.js +203 -0
  90. package/dist/lib/sandbox/control/client.js +125 -12
  91. package/dist/lib/sandbox/control/completed-reentry.js +85 -0
  92. package/dist/lib/sandbox/control/container-identity.js +28 -31
  93. package/dist/lib/sandbox/control/executor.js +233 -34
  94. package/dist/lib/sandbox/control/finalization-response.js +27 -0
  95. package/dist/lib/sandbox/control/identity-sentinel.js +107 -0
  96. package/dist/lib/sandbox/control/lifecycle.js +656 -128
  97. package/dist/lib/sandbox/control/native-file-lock.js +85 -0
  98. package/dist/lib/sandbox/control/protocol.js +55 -4
  99. package/dist/lib/sandbox/control/server.js +720 -79
  100. package/dist/lib/sandbox/control/state.js +63 -3
  101. package/dist/lib/sandbox/control/task-view.js +183 -0
  102. package/dist/lib/sandbox/control/task-workflow.js +74 -0
  103. package/dist/lib/sandbox/control/workflow-executor.js +99 -0
  104. package/dist/lib/sandbox/engines/authority.js +289 -0
  105. package/dist/lib/sandbox/engines/docker-exact-discovery.js +97 -0
  106. package/dist/lib/sandbox/index.js +7 -2
  107. package/dist/lib/sandbox/recovery.js +49 -5
  108. package/dist/lib/sandbox/removal.js +1717 -0
  109. package/dist/lib/sandbox/task-cleanup.js +217 -0
  110. package/dist/lib/sandbox/workspace-view.js +15 -15
  111. package/dist/lib/sandbox/worktree-safety.js +4 -1
  112. package/dist/lib/server/index.js +8 -0
  113. package/dist/lib/task/activity-intent.js +2 -1
  114. package/dist/lib/task/activity-log.js +30 -24
  115. package/dist/lib/task/artifact-command.js +101 -0
  116. package/dist/lib/task/artifact-lifecycle.js +71 -40
  117. package/dist/lib/task/artifact-name.js +36 -0
  118. package/dist/lib/task/artifact-operations.js +474 -0
  119. package/dist/lib/task/artifact-receipts.js +3 -15
  120. package/dist/lib/task/artifact-repair-intent.js +130 -0
  121. package/dist/lib/task/artifact-schema.js +127 -0
  122. package/dist/lib/task/capabilities.js +83 -19
  123. package/dist/lib/task/codex-orchestration.js +71 -25
  124. package/dist/lib/task/commit-identity.js +28 -0
  125. package/dist/lib/task/commit-operation.js +2 -16
  126. package/dist/lib/task/control-authority.js +375 -5
  127. package/dist/lib/task/control-recovery.js +128 -0
  128. package/dist/lib/task/create-service.js +103 -4
  129. package/dist/lib/task/create.js +80 -2
  130. package/dist/lib/task/decision-details.js +2 -46
  131. package/dist/lib/task/events.js +306 -76
  132. package/dist/lib/task/finalization-state.js +9 -0
  133. package/dist/lib/task/human-override.js +3 -6
  134. package/dist/lib/task/implementation-inputs.js +3 -3
  135. package/dist/lib/task/index.js +11 -3
  136. package/dist/lib/task/intermediate-cleanup.js +383 -0
  137. package/dist/lib/task/invalidation.js +18 -65
  138. package/dist/lib/task/ledger-intents.js +7 -22
  139. package/dist/lib/task/ledger.js +1 -3
  140. package/dist/lib/task/lifecycle.js +19 -1
  141. package/dist/lib/task/local-artifact-finalization.js +190 -290
  142. package/dist/lib/task/manual-validation-completion.js +26 -0
  143. package/dist/lib/task/manual-validation-evidence.js +130 -0
  144. package/dist/lib/task/manual-validation-receipt.js +101 -0
  145. package/dist/lib/task/manual-validation-shared.js +40 -0
  146. package/dist/lib/task/manual-validation-transaction.js +243 -0
  147. package/dist/lib/task/markdown.js +47 -0
  148. package/dist/lib/task/orchestration.js +206 -69
  149. package/dist/lib/task/qualification-audit.js +476 -0
  150. package/dist/lib/task/qualification-confirmation.js +109 -0
  151. package/dist/lib/task/qualification-intents.js +148 -0
  152. package/dist/lib/task/review-artifacts.js +23 -40
  153. package/dist/lib/task/review-command.js +25 -0
  154. package/dist/lib/task/review-finalization.js +146 -97
  155. package/dist/lib/task/review-fingerprint.js +2 -2
  156. package/dist/lib/task/sections.js +34 -54
  157. package/dist/lib/task/verification-config.js +11 -0
  158. package/dist/lib/task/verification-engine.js +170 -327
  159. package/dist/lib/task/verification.js +1 -1
  160. package/dist/lib/task/workflow-command.js +17 -0
  161. package/dist/lib/task/workflow-warning-intents.js +0 -16
  162. package/dist/lib/task/workflow-warnings.js +28 -2
  163. package/dist/lib/update.js +2 -0
  164. package/dist/lifecycle-build-manifest.json +3 -3
  165. package/lib/agent-client.ts +9 -0
  166. package/lib/agent-clients/adapters/codex-lifecycle/capability-store.ts +223 -33
  167. package/lib/agent-clients/adapters/codex-lifecycle/sandbox-controller.ts +3 -2
  168. package/lib/fs/durable-write.ts +29 -0
  169. package/lib/fs/file-lock.ts +113 -0
  170. package/lib/host-control/audit.ts +22 -0
  171. package/lib/host-control/client.ts +172 -0
  172. package/lib/host-control/command.ts +60 -0
  173. package/lib/host-control/path.ts +167 -0
  174. package/lib/host-control/secure-fs.ts +135 -0
  175. package/lib/host-control/server.ts +180 -0
  176. package/lib/host-control/service.ts +133 -0
  177. package/lib/init.ts +15 -2
  178. package/lib/internal/agent-client.ts +4 -2
  179. package/lib/internal/cli-route-inventory.ts +142 -0
  180. package/lib/internal/codex-lifecycle.ts +14 -12
  181. package/lib/internal/codex-sandbox-controller.ts +7 -2
  182. package/lib/internal/demo-promotion.ts +354 -0
  183. package/lib/internal/demo-transcript.ts +419 -0
  184. package/lib/internal/git-workflow.ts +9 -6
  185. package/lib/internal/host-control.ts +28 -0
  186. package/lib/internal/manual-validation.ts +306 -0
  187. package/lib/internal/platform-checks.ts +12 -4
  188. package/lib/internal/platform-comment.ts +12 -4
  189. package/lib/internal/platform-context.ts +3 -1
  190. package/lib/internal/platform-issue.ts +11 -4
  191. package/lib/internal/platform-metadata.ts +70 -0
  192. package/lib/internal/platform-pr-review.ts +14 -3
  193. package/lib/internal/platform-pr.ts +38 -14
  194. package/lib/internal/platform-release-notes.ts +5 -3
  195. package/lib/internal/platform-security.ts +83 -0
  196. package/lib/internal/pr-review-grade.ts +10 -3
  197. package/lib/internal/release-workflow.ts +91 -87
  198. package/lib/internal/sandbox-control.ts +181 -6
  199. package/lib/internal/task-activity.ts +12 -4
  200. package/lib/internal/task-artifact.ts +15 -79
  201. package/lib/internal/task-context.ts +3 -1
  202. package/lib/internal/task-create.ts +76 -15
  203. package/lib/internal/task-delivery.ts +3 -1
  204. package/lib/internal/task-event.ts +21 -10
  205. package/lib/internal/task-finalization.ts +3 -1
  206. package/lib/internal/task-invalidation.ts +3 -1
  207. package/lib/internal/task-ledger.ts +11 -1
  208. package/lib/internal/task-lifecycle.ts +3 -1
  209. package/lib/internal/task-operation-registry.ts +590 -0
  210. package/lib/internal/task-orchestration.ts +12 -0
  211. package/lib/internal/task-override.ts +9 -3
  212. package/lib/internal/task-qualification.ts +61 -0
  213. package/lib/internal/task-review.ts +7 -50
  214. package/lib/internal/task-short-id.ts +10 -1
  215. package/lib/internal/task-snapshot.ts +3 -1
  216. package/lib/internal/task-validate.ts +32 -12
  217. package/lib/internal/task-verify.ts +4 -1
  218. package/lib/internal/task-warning.ts +7 -1
  219. package/lib/owned-path.ts +26 -0
  220. package/lib/platform/check-status.ts +9 -0
  221. package/lib/platform/comment-safety.ts +255 -0
  222. package/lib/platform/completion-backfill.ts +1 -1
  223. package/lib/platform/github-data.ts +322 -0
  224. package/lib/platform/github-provider.ts +244 -27
  225. package/lib/platform/issue-comments.ts +159 -35
  226. package/lib/platform/issues.ts +4 -245
  227. package/lib/platform/pr-change-report.ts +6 -12
  228. package/lib/platform/pr-checks.ts +13 -77
  229. package/lib/platform/pr-summary.ts +88 -11
  230. package/lib/platform/provider-contract.ts +78 -3
  231. package/lib/platform/provider-validation.ts +85 -3
  232. package/lib/platform/pull-requests.ts +129 -348
  233. package/lib/platform/repository-metadata.ts +453 -0
  234. package/lib/platform/security-alerts.ts +191 -0
  235. package/lib/platform/snapshots.ts +53 -0
  236. package/lib/platform/verification-sync.ts +171 -177
  237. package/lib/process-data/index.ts +7 -0
  238. package/lib/release/workflow.ts +3 -3
  239. package/lib/run/index.ts +5 -0
  240. package/lib/sandbox/commands/control-status.ts +26 -0
  241. package/lib/sandbox/commands/create.ts +53 -12
  242. package/lib/sandbox/commands/ls.ts +7 -0
  243. package/lib/sandbox/commands/rm.ts +3 -996
  244. package/lib/sandbox/commands/show.ts +16 -0
  245. package/lib/sandbox/control/audit.ts +253 -0
  246. package/lib/sandbox/control/client.ts +150 -13
  247. package/lib/sandbox/control/completed-reentry.ts +98 -0
  248. package/lib/sandbox/control/container-identity.ts +27 -43
  249. package/lib/sandbox/control/executor.ts +262 -37
  250. package/lib/sandbox/control/finalization-response.ts +29 -0
  251. package/lib/sandbox/control/identity-sentinel.ts +137 -0
  252. package/lib/sandbox/control/lifecycle.ts +672 -18
  253. package/lib/sandbox/control/native-file-lock.ts +108 -0
  254. package/lib/sandbox/control/protocol.ts +80 -8
  255. package/lib/sandbox/control/server.ts +779 -82
  256. package/lib/sandbox/control/state.ts +84 -3
  257. package/lib/sandbox/control/task-view.ts +240 -0
  258. package/lib/sandbox/control/task-workflow.ts +95 -0
  259. package/lib/sandbox/control/workflow-executor.ts +102 -0
  260. package/lib/sandbox/engines/authority.ts +365 -0
  261. package/lib/sandbox/engines/docker-exact-discovery.ts +132 -0
  262. package/lib/sandbox/index.ts +9 -2
  263. package/lib/sandbox/recovery.ts +49 -6
  264. package/lib/sandbox/removal.ts +2144 -0
  265. package/lib/sandbox/task-cleanup.ts +209 -0
  266. package/lib/sandbox/workspace-view.ts +26 -18
  267. package/lib/sandbox/worktree-safety.ts +4 -1
  268. package/lib/server/index.ts +10 -0
  269. package/lib/task/activity-intent.ts +2 -2
  270. package/lib/task/activity-log.ts +27 -19
  271. package/lib/task/artifact-command.ts +104 -0
  272. package/lib/task/artifact-lifecycle.ts +66 -39
  273. package/lib/task/artifact-name.ts +55 -0
  274. package/lib/task/artifact-operations.ts +580 -0
  275. package/lib/task/artifact-receipts.ts +3 -14
  276. package/lib/task/artifact-repair-intent.ts +152 -0
  277. package/lib/task/artifact-schema.ts +163 -0
  278. package/lib/task/capabilities.ts +82 -22
  279. package/lib/task/codex-orchestration.ts +85 -24
  280. package/lib/task/commit-identity.ts +31 -0
  281. package/lib/task/commit-operation.ts +2 -16
  282. package/lib/task/control-authority.ts +513 -6
  283. package/lib/task/control-recovery.ts +174 -0
  284. package/lib/task/create-service.ts +131 -6
  285. package/lib/task/create.ts +83 -1
  286. package/lib/task/decision-details.ts +3 -71
  287. package/lib/task/events.ts +292 -75
  288. package/lib/task/finalization-state.ts +11 -0
  289. package/lib/task/human-override.ts +3 -8
  290. package/lib/task/implementation-inputs.ts +3 -3
  291. package/lib/task/index.ts +16 -3
  292. package/lib/task/intermediate-cleanup.ts +455 -0
  293. package/lib/task/invalidation.ts +18 -62
  294. package/lib/task/ledger-intents.ts +7 -24
  295. package/lib/task/ledger.ts +1 -3
  296. package/lib/task/lifecycle.ts +17 -1
  297. package/lib/task/local-artifact-finalization.ts +223 -388
  298. package/lib/task/manual-validation-completion.ts +40 -0
  299. package/lib/task/manual-validation-evidence.ts +209 -0
  300. package/lib/task/manual-validation-receipt.ts +152 -0
  301. package/lib/task/manual-validation-shared.ts +50 -0
  302. package/lib/task/manual-validation-transaction.ts +304 -0
  303. package/lib/task/markdown.ts +70 -0
  304. package/lib/task/orchestration.ts +191 -68
  305. package/lib/task/qualification-audit.ts +588 -0
  306. package/lib/task/qualification-confirmation.ts +117 -0
  307. package/lib/task/qualification-intents.ts +150 -0
  308. package/lib/task/review-artifacts.ts +21 -41
  309. package/lib/task/review-command.ts +23 -0
  310. package/lib/task/review-finalization.ts +154 -153
  311. package/lib/task/review-fingerprint.ts +2 -2
  312. package/lib/task/sections.ts +33 -52
  313. package/lib/task/verification-config.ts +12 -0
  314. package/lib/task/verification-engine.ts +165 -370
  315. package/lib/task/verification-types.ts +17 -0
  316. package/lib/task/verification.ts +1 -1
  317. package/lib/task/workflow-command.ts +18 -0
  318. package/lib/task/workflow-warning-intents.ts +0 -13
  319. package/lib/task/workflow-warnings.ts +21 -2
  320. package/lib/update.ts +6 -0
  321. package/package.json +7 -2
  322. package/templates/.agents/hooks/lifecycle-delegation.js +6 -6
  323. package/templates/.agents/rules/README.en.md +2 -0
  324. package/templates/.agents/rules/README.zh-CN.md +2 -0
  325. package/templates/.agents/rules/decision-qualification.en.md +22 -0
  326. package/templates/.agents/rules/decision-qualification.zh-CN.md +22 -0
  327. package/templates/.agents/rules/evidence-reporting.en.md +28 -0
  328. package/templates/.agents/rules/evidence-reporting.zh-CN.md +28 -0
  329. package/templates/.agents/rules/label-milestone-setup.en.md +7 -7
  330. package/templates/.agents/rules/label-milestone-setup.zh-CN.md +7 -7
  331. package/templates/.agents/rules/local-artifact-repair.en.md +5 -1
  332. package/templates/.agents/rules/local-artifact-repair.zh-CN.md +5 -1
  333. package/templates/.agents/rules/security-alerts.en.md +8 -8
  334. package/templates/.agents/rules/security-alerts.zh-CN.md +8 -8
  335. package/templates/.agents/rules/testing-discipline.en.md +2 -0
  336. package/templates/.agents/rules/testing-discipline.zh-CN.md +2 -0
  337. package/templates/.agents/scripts/package.json +3 -0
  338. package/templates/.agents/skills/analyze-task/SKILL.en.md +15 -2
  339. package/templates/.agents/skills/analyze-task/SKILL.zh-CN.md +19 -2
  340. package/templates/.agents/skills/analyze-task/config/verify.en.json +1 -12
  341. package/templates/.agents/skills/analyze-task/config/verify.zh-CN.json +1 -12
  342. package/templates/.agents/skills/close-codescan/SKILL.en.md +2 -2
  343. package/templates/.agents/skills/close-codescan/SKILL.zh-CN.md +2 -2
  344. package/templates/.agents/skills/close-dependabot/SKILL.en.md +2 -2
  345. package/templates/.agents/skills/close-dependabot/SKILL.zh-CN.md +2 -2
  346. package/templates/.agents/skills/code-task/SKILL.en.md +14 -1
  347. package/templates/.agents/skills/code-task/SKILL.zh-CN.md +14 -1
  348. package/templates/.agents/skills/code-task/config/verify.en.json +5 -14
  349. package/templates/.agents/skills/code-task/config/verify.zh-CN.json +5 -14
  350. package/templates/.agents/skills/code-task/reference/code-rules.en.md +5 -4
  351. package/templates/.agents/skills/code-task/reference/code-rules.zh-CN.md +5 -4
  352. package/templates/.agents/skills/code-task/reference/dual-mode.en.md +1 -1
  353. package/templates/.agents/skills/code-task/reference/dual-mode.zh-CN.md +1 -1
  354. package/templates/.agents/skills/code-task/reference/fix-mode.en.md +3 -1
  355. package/templates/.agents/skills/code-task/reference/fix-mode.zh-CN.md +3 -1
  356. package/templates/.agents/skills/code-task/reference/report-template.en.md +42 -15
  357. package/templates/.agents/skills/code-task/reference/report-template.zh-CN.md +39 -12
  358. package/templates/.agents/skills/complete-manual-validation/SKILL.en.md +37 -21
  359. package/templates/.agents/skills/complete-manual-validation/SKILL.zh-CN.md +37 -21
  360. package/templates/.agents/skills/complete-manual-validation/config/verify.en.json +1 -1
  361. package/templates/.agents/skills/complete-manual-validation/config/verify.zh-CN.json +1 -1
  362. package/templates/.agents/skills/complete-manual-validation/reference/report-template.en.md +4 -0
  363. package/templates/.agents/skills/complete-manual-validation/reference/report-template.zh-CN.md +4 -0
  364. package/templates/.agents/skills/complete-manual-validation/reference/summary-update.en.md +16 -7
  365. package/templates/.agents/skills/complete-manual-validation/reference/summary-update.zh-CN.md +16 -7
  366. package/templates/.agents/skills/complete-task/SKILL.en.md +10 -23
  367. package/templates/.agents/skills/complete-task/SKILL.zh-CN.md +10 -23
  368. package/templates/.agents/skills/create-task/SKILL.en.md +8 -0
  369. package/templates/.agents/skills/create-task/SKILL.zh-CN.md +7 -0
  370. package/templates/.agents/skills/import-codescan/SKILL.en.md +1 -1
  371. package/templates/.agents/skills/import-codescan/SKILL.zh-CN.md +1 -1
  372. package/templates/.agents/skills/import-dependabot/SKILL.en.md +1 -1
  373. package/templates/.agents/skills/import-dependabot/SKILL.zh-CN.md +1 -1
  374. package/templates/.agents/skills/init-labels/SKILL.en.md +8 -8
  375. package/templates/.agents/skills/init-labels/SKILL.zh-CN.md +8 -8
  376. package/templates/.agents/skills/init-milestones/SKILL.en.md +9 -11
  377. package/templates/.agents/skills/init-milestones/SKILL.zh-CN.md +9 -11
  378. package/templates/.agents/skills/plan-task/SKILL.en.md +14 -1
  379. package/templates/.agents/skills/plan-task/SKILL.zh-CN.md +16 -1
  380. package/templates/.agents/skills/plan-task/config/verify.en.json +4 -14
  381. package/templates/.agents/skills/plan-task/config/verify.zh-CN.json +4 -14
  382. package/templates/.agents/skills/release/SKILL.en.md +7 -3
  383. package/templates/.agents/skills/release/SKILL.zh-CN.md +7 -3
  384. package/templates/.agents/skills/review-analysis/SKILL.en.md +14 -1
  385. package/templates/.agents/skills/review-analysis/SKILL.zh-CN.md +14 -1
  386. package/templates/.agents/skills/review-analysis/config/verify.en.json +1 -18
  387. package/templates/.agents/skills/review-analysis/config/verify.zh-CN.json +1 -18
  388. package/templates/.agents/skills/review-analysis/reference/report-template.en.md +50 -23
  389. package/templates/.agents/skills/review-analysis/reference/report-template.zh-CN.md +45 -18
  390. package/templates/.agents/skills/review-code/SKILL.en.md +14 -1
  391. package/templates/.agents/skills/review-code/SKILL.zh-CN.md +14 -1
  392. package/templates/.agents/skills/review-code/config/verify.en.json +1 -23
  393. package/templates/.agents/skills/review-code/config/verify.zh-CN.json +1 -23
  394. package/templates/.agents/skills/review-code/reference/report-template.en.md +49 -22
  395. package/templates/.agents/skills/review-code/reference/report-template.zh-CN.md +45 -18
  396. package/templates/.agents/skills/review-plan/SKILL.en.md +14 -1
  397. package/templates/.agents/skills/review-plan/SKILL.zh-CN.md +14 -1
  398. package/templates/.agents/skills/review-plan/config/verify.en.json +1 -18
  399. package/templates/.agents/skills/review-plan/config/verify.zh-CN.json +1 -18
  400. package/templates/.agents/skills/review-plan/reference/report-template.en.md +49 -22
  401. package/templates/.agents/skills/review-plan/reference/report-template.zh-CN.md +45 -18
  402. package/templates/.agents/skills/review-pr/SKILL.en.md +5 -1
  403. package/templates/.agents/skills/review-pr/SKILL.zh-CN.md +5 -1
  404. package/templates/.agents/skills/review-pr/reference/report-template.en.md +4 -3
  405. package/templates/.agents/skills/review-pr/reference/report-template.zh-CN.md +4 -3
  406. package/templates/.agents/skills/run-manual-validation/SKILL.en.md +25 -4
  407. package/templates/.agents/skills/run-manual-validation/SKILL.zh-CN.md +25 -4
  408. package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.en.md +4 -1
  409. package/templates/.agents/skills/run-manual-validation/reference/discovery-and-execution.zh-CN.md +4 -1
  410. package/templates/.agents/skills/run-manual-validation/reference/report-template.en.md +5 -1
  411. package/templates/.agents/skills/run-manual-validation/reference/report-template.zh-CN.md +5 -1
  412. package/templates/.agents/skills/run-task/SKILL.en.md +1 -1
  413. package/templates/.agents/skills/run-task/SKILL.zh-CN.md +1 -1
  414. package/templates/.agents/skills/test/SKILL.en.md +29 -7
  415. package/templates/.agents/skills/test/SKILL.zh-CN.md +29 -7
  416. package/templates/.agents/skills/update-agent-infra/scripts/sync-templates.js +14 -0
  417. package/templates/.agents/templates/task.en.md +6 -0
  418. package/templates/.agents/templates/task.zh-CN.md +6 -0
  419. package/templates/.claude/commands/run-manual-validation.en.md +1 -1
  420. package/templates/.claude/commands/run-manual-validation.zh-CN.md +1 -1
  421. package/dist/lib/platform/adapters.js +0 -56
  422. package/lib/platform/adapters.ts +0 -197
  423. package/templates/.agents/scripts/security-alerts.github.sh +0 -151
  424. package/templates/.agents/scripts/security-alerts.sh +0 -31
  425. package/templates/.agents/skills/init-labels/scripts/init-labels.github.sh +0 -146
  426. package/templates/.agents/skills/init-labels/scripts/init-labels.sh +0 -32
  427. package/templates/.agents/skills/init-milestones/scripts/init-milestones.github.sh +0 -294
  428. package/templates/.agents/skills/init-milestones/scripts/init-milestones.sh +0 -6
@@ -0,0 +1,1717 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import * as p from '@clack/prompts';
5
+ import pc from 'picocolors';
6
+ import { assertValidBranchName, containerNameCandidates, sandboxBranchLabel, sandboxLabel, sandboxTaskIdLabel, sandboxWorkspaceModeLabel, shareBranchDir, shellConfigDirCandidates, worktreeDirCandidates } from './constants.js';
7
+ import { ENGINES, detectEngine, engineDisplayName, isManagedEngine, stopManagedVm } from './engine.js';
8
+ import { pruneSandboxDanglingImages } from './image-prune.js';
9
+ import { assertManagedPath, removeManagedDir, removeWorktreeDir } from './managed-fs.js';
10
+ import { run, runEngine, runOk, runOkEngine, runSafe, runSafeEngine } from './shell.js';
11
+ import { parseSandboxWorkspaceIdentity, resolveSandboxCleanupTarget, sameSandboxWorkspaceIdentity } from './workspace-identity.js';
12
+ import { sandboxControlPaths, sandboxWorkspaceViewPaths } from './workspace-view.js';
13
+ import { advanceSandboxRemovalJournalToPhase, advanceSandboxRemovalJournalPhase, claimSandboxRemovalJournal, clearSandboxRemovalJournalRecord, isDefaultSandboxRemovalJournal, listSandboxRemovalJournals, removeSandboxControlRoot, readSandboxControlManifest, sandboxRemovalPhaseIndex } from './control/lifecycle.js';
14
+ import { inspectSandboxControlContainer } from './control/container-identity.js';
15
+ import { commandForSandboxAuthority } from './engines/authority.js';
16
+ import { acquireSandboxResourceLock } from './control/native-file-lock.js';
17
+ import { toolConfigDirCandidates, toolProjectDirCandidates } from './tools.js';
18
+ import { getProcessStartTime } from '../server/process-state.js';
19
+ import { fetchSandboxRows } from './commands/list-running.js';
20
+ import { formatIntermediateCleanupReport, cleanupIntermediateUnderRemovalCoordinator, protectIntermediateCleanupReport, mergeIntermediateCleanupReports, scanIntermediateCleanup } from '../task/intermediate-cleanup.js';
21
+ import { createSandboxControlBindingEvidence } from './task-cleanup.js';
22
+ import { withRepositoryMutationLock, withTaskExecutionLock } from '../task/task-execution-lock.js';
23
+ import { createCleanPermit, createDiscardPermit, formatWorktreeSnapshot, inspectRecoveredWorktree, inspectWorktrees, verifyWorktreePermit } from './worktree-safety.js';
24
+ function projectToolDirs(config, tools) {
25
+ return tools.flatMap((tool) => toolProjectDirCandidates(tool, config.project));
26
+ }
27
+ function isMissingPathError(error) {
28
+ return Boolean(error && typeof error === 'object' && 'code' in error
29
+ && error.code === 'ENOENT');
30
+ }
31
+ function canonicalPath(input) {
32
+ try {
33
+ return fs.realpathSync.native(input);
34
+ }
35
+ catch {
36
+ return path.resolve(input);
37
+ }
38
+ }
39
+ function isMissingTaskRecordError(error) {
40
+ return error instanceof Error && /^Task not found: TASK-\d{8}-\d{6}$/.test(error.message);
41
+ }
42
+ function digestCleanupValue(value) {
43
+ return createHash('sha256').update(JSON.stringify(value)).digest('hex');
44
+ }
45
+ function removalTargetDigest(config, target) {
46
+ return digestCleanupValue({
47
+ project: config.project,
48
+ branch: target.effectiveBranch,
49
+ workspace: target.workspace,
50
+ controlRoots: target.controlRoots.map((candidate) => path.resolve(candidate)),
51
+ workspaceViewRoots: target.workspaceViewRoots.map((candidate) => path.resolve(candidate)),
52
+ managedPathCandidates: (target.managedPathCandidates ?? []).map((candidate) => path.resolve(candidate)).sort()
53
+ });
54
+ }
55
+ function removalPermitDigest(permits) {
56
+ return digestCleanupValue([...permits.entries()]
57
+ .map(([worktree, permit]) => [path.resolve(worktree), permit.mode, permit.snapshot.identity])
58
+ .sort(([left], [right]) => String(left).localeCompare(String(right))));
59
+ }
60
+ function removalPermitCommits(permits) {
61
+ return [...permits.entries()]
62
+ .map(([worktree, permit]) => ({
63
+ path: path.resolve(worktree),
64
+ mode: permit.mode,
65
+ snapshot: permit.snapshot
66
+ }))
67
+ .sort((left, right) => left.path.localeCompare(right.path));
68
+ }
69
+ function removalTargetCommit(config, target, permits, removeWorktree, removeBranch, removeShare) {
70
+ return {
71
+ branch: target.effectiveBranch,
72
+ project: config.project,
73
+ controlRoot: path.resolve(target.controlRoots[0] ?? path.join(config.controlBase, config.project)),
74
+ targetDigest: removalTargetDigest(config, target),
75
+ permitDigest: removalPermitDigest(permits),
76
+ removeWorktree,
77
+ removeBranch,
78
+ removeShare,
79
+ worktreePaths: target.existingWorktrees.map((candidate) => path.resolve(candidate)).sort(),
80
+ workspaceViewPaths: target.workspaceViewRoots.map((candidate) => path.resolve(candidate)).sort(),
81
+ toolPaths: target.toolCandidates.flatMap(({ candidates }) => candidates.map((candidate) => path.resolve(candidate))).sort(),
82
+ shellPaths: shellConfigDirCandidates(config, target.effectiveBranch).map((candidate) => path.resolve(candidate)).sort(),
83
+ sharePath: path.resolve(shareBranchDir(config, target.effectiveBranch)),
84
+ permits: removalPermitCommits(permits)
85
+ };
86
+ }
87
+ function assertRemovalSelectionMatches(expected, actual) {
88
+ const normalize = (value) => ({
89
+ ...value,
90
+ controlRoot: '',
91
+ permits: value.permits
92
+ });
93
+ if (JSON.stringify(normalize(expected)) !== JSON.stringify(normalize(actual))) {
94
+ throw new Error('SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH');
95
+ }
96
+ }
97
+ function advanceRemovalJournals(project, target, targetDigest, phase, resourceLocks) {
98
+ return listSandboxRemovalJournals({ branch: target.effectiveBranch, project, targetDigest }).map((journal) => {
99
+ if (sandboxRemovalPhaseIndex(journal.phase) >= sandboxRemovalPhaseIndex(phase))
100
+ return journal;
101
+ const lock = resourceLocks.get(journal.target.controlRoot);
102
+ if (!lock)
103
+ throw new Error('SANDBOX_CONTROL_REMOVAL_LOCK_MISMATCH');
104
+ return advanceSandboxRemovalJournalToPhase(journal, phase, lock);
105
+ });
106
+ }
107
+ function prepareRemovalAction(project, target, targetDigest, startPhase, completedPhase, resourceLocks) {
108
+ const journals = listSandboxRemovalJournals({
109
+ branch: target.effectiveBranch,
110
+ project,
111
+ targetDigest
112
+ });
113
+ const startIndex = sandboxRemovalPhaseIndex(startPhase);
114
+ const completedIndex = sandboxRemovalPhaseIndex(completedPhase);
115
+ const shouldRun = journals.length === 0
116
+ || journals.some((journal) => sandboxRemovalPhaseIndex(journal.phase) < completedIndex);
117
+ const recovering = journals.some((journal) => {
118
+ const index = sandboxRemovalPhaseIndex(journal.phase);
119
+ return index >= startIndex && index < completedIndex;
120
+ });
121
+ advanceRemovalJournals(project, target, targetDigest, startPhase, resourceLocks);
122
+ return { run: shouldRun, recovering };
123
+ }
124
+ function assertRemovalPathsAbsent(paths) {
125
+ const remaining = paths.filter((candidate) => fs.existsSync(candidate));
126
+ if (remaining.length > 0) {
127
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${remaining[0]}`);
128
+ }
129
+ }
130
+ function assertBranchRemovalIdentity(config, branch, permits) {
131
+ if (!runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', `refs/heads/${branch}`]))
132
+ return;
133
+ const expectedHeads = new Set([...permits.values()]
134
+ .filter((permit) => permit.snapshot.branch === branch)
135
+ .map((permit) => permit.snapshot.head));
136
+ if (expectedHeads.size === 0) {
137
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
138
+ }
139
+ const actualHead = runSafe('git', ['-C', config.repoRoot, 'rev-parse', `refs/heads/${branch}`]);
140
+ if (!expectedHeads.has(actualHead)) {
141
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
142
+ }
143
+ }
144
+ function removalTombstonePath(targetDigest, kind, source) {
145
+ const sourceDigest = createHash('sha256')
146
+ .update(`${kind}\0${path.resolve(source)}`)
147
+ .digest('hex')
148
+ .slice(0, 24);
149
+ return path.join(path.dirname(path.resolve(source)), `.agent-infra-removal-${targetDigest.slice(0, 16)}-${kind}-${sourceDigest}`);
150
+ }
151
+ const REMOVAL_TOMBSTONE_MARKER = '.agent-infra-removal-ownership.json';
152
+ const REMOVAL_TOMBSTONE_PAYLOAD = 'payload';
153
+ function removalSourceClaimPath(source, ownership) {
154
+ const claimDigest = createHash('sha256')
155
+ .update(JSON.stringify(ownership))
156
+ .digest('hex')
157
+ .slice(0, 24);
158
+ return path.join(source, `.agent-infra-removal-source-${claimDigest}.json`);
159
+ }
160
+ function removalSourceIdentity(source) {
161
+ const stat = fs.lstatSync(source, { bigint: true });
162
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev === 0n || stat.ino === 0n) {
163
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
164
+ }
165
+ return { dev: String(stat.dev), ino: String(stat.ino) };
166
+ }
167
+ function sameRemovalSourceIdentity(left, right) {
168
+ return left.dev === right.dev && left.ino === right.ino;
169
+ }
170
+ function removalSourceClaimMatches(source, ownership, identity) {
171
+ try {
172
+ const claimPath = removalSourceClaimPath(source, ownership);
173
+ const claimStat = fs.lstatSync(claimPath);
174
+ if (!claimStat.isFile() || claimStat.isSymbolicLink())
175
+ return false;
176
+ const record = JSON.parse(fs.readFileSync(claimPath, 'utf8'));
177
+ return record.version === ownership.version
178
+ && record.targetDigest === ownership.targetDigest
179
+ && record.permitDigest === ownership.permitDigest
180
+ && record.kind === ownership.kind
181
+ && typeof record.source === 'string'
182
+ && path.resolve(record.source) === path.resolve(ownership.source)
183
+ && record.sourceIdentity?.dev === identity.dev
184
+ && record.sourceIdentity?.ino === identity.ino;
185
+ }
186
+ catch {
187
+ return false;
188
+ }
189
+ }
190
+ function isOwnedRemovalSourceClaim(source, ownership) {
191
+ try {
192
+ const claimPath = removalSourceClaimPath(source, ownership);
193
+ const claimStat = fs.lstatSync(claimPath);
194
+ if (!claimStat.isFile() || claimStat.isSymbolicLink())
195
+ return false;
196
+ const record = JSON.parse(fs.readFileSync(claimPath, 'utf8'));
197
+ return record.version === ownership.version
198
+ && record.targetDigest === ownership.targetDigest
199
+ && record.permitDigest === ownership.permitDigest
200
+ && record.kind === ownership.kind
201
+ && typeof record.source === 'string'
202
+ && path.resolve(record.source) === path.resolve(ownership.source);
203
+ }
204
+ catch {
205
+ return false;
206
+ }
207
+ }
208
+ function removeOwnedSourceClaim(source, ownership) {
209
+ try {
210
+ const claimPath = removalSourceClaimPath(source, ownership);
211
+ if (isOwnedRemovalSourceClaim(source, ownership))
212
+ fs.unlinkSync(claimPath);
213
+ }
214
+ catch {
215
+ // Preserve the source when the claim cannot be revalidated.
216
+ }
217
+ }
218
+ function readRemovalTombstoneRecord(root, tombstone) {
219
+ assertManagedPath(root, tombstone);
220
+ try {
221
+ const tombstoneStat = fs.lstatSync(tombstone);
222
+ const markerStat = fs.lstatSync(removalTombstoneMarker(tombstone));
223
+ if (!tombstoneStat.isDirectory() || tombstoneStat.isSymbolicLink()
224
+ || !markerStat.isFile() || markerStat.isSymbolicLink())
225
+ return null;
226
+ const record = JSON.parse(fs.readFileSync(removalTombstoneMarker(tombstone), 'utf8'));
227
+ if (record.version !== 1
228
+ || typeof record.targetDigest !== 'string'
229
+ || typeof record.permitDigest !== 'string'
230
+ || typeof record.kind !== 'string'
231
+ || typeof record.source !== 'string'
232
+ || record.sourceIdentity?.dev === undefined
233
+ || record.sourceIdentity.ino === undefined)
234
+ return null;
235
+ return record;
236
+ }
237
+ catch {
238
+ return null;
239
+ }
240
+ }
241
+ function removalTombstonePayload(tombstone) {
242
+ return path.join(tombstone, REMOVAL_TOMBSTONE_PAYLOAD);
243
+ }
244
+ function removalTombstoneMarker(tombstone) {
245
+ return path.join(tombstone, REMOVAL_TOMBSTONE_MARKER);
246
+ }
247
+ function isOwnedRemovalTombstone(root, tombstone, ownership) {
248
+ const record = readRemovalTombstoneRecord(root, tombstone);
249
+ return record !== null
250
+ && record.version === 1
251
+ && record.targetDigest === ownership.targetDigest
252
+ && record.permitDigest === ownership.permitDigest
253
+ && record.kind === ownership.kind
254
+ && typeof record.source === 'string'
255
+ && path.resolve(record.source) === path.resolve(ownership.source);
256
+ }
257
+ function isOwnedRemovalPayload(root, tombstone, ownership) {
258
+ const record = readRemovalTombstoneRecord(root, tombstone);
259
+ if (!record || record.targetDigest !== ownership.targetDigest
260
+ || record.permitDigest !== ownership.permitDigest
261
+ || record.kind !== ownership.kind
262
+ || path.resolve(record.source) !== path.resolve(ownership.source))
263
+ return false;
264
+ try {
265
+ const payload = removalTombstonePayload(tombstone);
266
+ const payloadIdentity = removalSourceIdentity(payload);
267
+ return sameRemovalSourceIdentity(payloadIdentity, record.sourceIdentity)
268
+ && removalSourceClaimMatches(payload, ownership, record.sourceIdentity);
269
+ }
270
+ catch {
271
+ return false;
272
+ }
273
+ }
274
+ function assertOwnedRemovalTombstone(root, tombstone, ownership) {
275
+ if (!isOwnedRemovalTombstone(root, tombstone, ownership)) {
276
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${ownership.source}`);
277
+ }
278
+ }
279
+ function shouldStageManagedRemoval(source, tombstone, recovering) {
280
+ return fs.existsSync(source) || (recovering && fs.existsSync(tombstone));
281
+ }
282
+ function stageManagedRemoval(root, source, tombstone, recovering, ownership) {
283
+ assertManagedPath(root, source);
284
+ assertManagedPath(root, tombstone);
285
+ const sourceExists = fs.existsSync(source);
286
+ const tombstoneExists = fs.existsSync(tombstone);
287
+ if (tombstoneExists) {
288
+ assertOwnedRemovalTombstone(root, tombstone, ownership);
289
+ if (sourceExists) {
290
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
291
+ }
292
+ if (recovering) {
293
+ if (!isOwnedRemovalPayload(root, tombstone, ownership)) {
294
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
295
+ }
296
+ return;
297
+ }
298
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
299
+ }
300
+ if (recovering) {
301
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${source}`);
302
+ }
303
+ if (!sourceExists)
304
+ return;
305
+ // The operator authorizes cleanup of this managed target after execution stops.
306
+ // Path checks detect conflicts; they do not provide an atomic source-instance move.
307
+ const expectedIdentity = removalSourceIdentity(source);
308
+ const claimPath = removalSourceClaimPath(source, ownership);
309
+ try {
310
+ fs.writeFileSync(claimPath, `${JSON.stringify({ ...ownership, sourceIdentity: expectedIdentity })}\n`, {
311
+ encoding: 'utf8',
312
+ mode: 0o600,
313
+ flag: 'wx'
314
+ });
315
+ }
316
+ catch {
317
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
318
+ }
319
+ if (!sameRemovalSourceIdentity(expectedIdentity, removalSourceIdentity(source))) {
320
+ removeOwnedSourceClaim(source, ownership);
321
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
322
+ }
323
+ let moved = false;
324
+ try {
325
+ fs.mkdirSync(tombstone, { mode: 0o700 });
326
+ fs.writeFileSync(removalTombstoneMarker(tombstone), `${JSON.stringify({ ...ownership, sourceIdentity: expectedIdentity })}\n`, {
327
+ encoding: 'utf8',
328
+ mode: 0o600,
329
+ flag: 'wx'
330
+ });
331
+ fs.renameSync(source, removalTombstonePayload(tombstone));
332
+ moved = true;
333
+ if (!isOwnedRemovalPayload(root, tombstone, ownership)) {
334
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
335
+ }
336
+ }
337
+ catch (error) {
338
+ if (!moved)
339
+ removeOwnedSourceClaim(source, ownership);
340
+ throw error;
341
+ }
342
+ }
343
+ function cleanupManagedTombstones(root, targetDigest, permitDigest, kind, sources) {
344
+ for (const source of sources) {
345
+ const tombstone = removalTombstonePath(targetDigest, kind, source);
346
+ if (!fs.existsSync(tombstone))
347
+ continue;
348
+ const ownership = { version: 1, targetDigest, permitDigest, kind, source };
349
+ if (!isOwnedRemovalTombstone(root, tombstone, ownership))
350
+ continue;
351
+ if (!isOwnedRemovalPayload(root, tombstone, ownership)) {
352
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${source}`);
353
+ }
354
+ removeManagedDir(root, tombstone);
355
+ }
356
+ }
357
+ function branchRemovalTombstoneRef(targetDigest) {
358
+ return `refs/agent-infra/sandbox-removal/${targetDigest}/branch`;
359
+ }
360
+ function branchPermitHead(branch, permits) {
361
+ const heads = new Set([...permits.values()]
362
+ .filter((permit) => permit.snapshot.branch === branch)
363
+ .map((permit) => permit.snapshot.head));
364
+ return heads.size === 1 ? [...heads][0] : null;
365
+ }
366
+ function stageBranchRemoval(config, branch, targetDigest, permits, recovering) {
367
+ const expectedHead = branchPermitHead(branch, permits);
368
+ if (!expectedHead)
369
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
370
+ const branchName = `refs/heads/${branch}`;
371
+ const tombstone = branchRemovalTombstoneRef(targetDigest);
372
+ const branchExists = runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', branchName]);
373
+ const tombstoneExists = runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', tombstone]);
374
+ if (branchExists && tombstoneExists) {
375
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
376
+ }
377
+ if (recovering) {
378
+ if (branchExists && !tombstoneExists) {
379
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${branch}`);
380
+ }
381
+ if (tombstoneExists && runSafe('git', ['-C', config.repoRoot, 'rev-parse', tombstone]) !== expectedHead) {
382
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
383
+ }
384
+ return;
385
+ }
386
+ if (!branchExists)
387
+ return;
388
+ assertBranchRemovalIdentity(config, branch, permits);
389
+ const actualHead = runSafe('git', ['-C', config.repoRoot, 'rev-parse', branchName]);
390
+ if (!runOk('git', ['-C', config.repoRoot, 'update-ref', tombstone, actualHead, '0'.repeat(40)])) {
391
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
392
+ }
393
+ if (!runOk('git', ['-C', config.repoRoot, 'update-ref', '-d', branchName, actualHead])) {
394
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
395
+ }
396
+ }
397
+ function cleanupBranchTombstone(config, branch, targetDigest, permits) {
398
+ const tombstone = branchRemovalTombstoneRef(targetDigest);
399
+ if (!runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', tombstone]))
400
+ return;
401
+ const expectedHead = branchPermitHead(branch, permits);
402
+ if (!expectedHead || runSafe('git', ['-C', config.repoRoot, 'rev-parse', tombstone]) !== expectedHead) {
403
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
404
+ }
405
+ if (!runOk('git', ['-C', config.repoRoot, 'update-ref', '-d', tombstone, expectedHead])) {
406
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${branch}`);
407
+ }
408
+ }
409
+ function worktreeRegistration(config, worktree) {
410
+ const lines = runSafe('git', ['-C', config.repoRoot, 'worktree', 'list', '--porcelain']).split('\n');
411
+ let current = null;
412
+ const flush = () => {
413
+ if (!current || path.resolve(current.path) !== path.resolve(worktree))
414
+ return null;
415
+ return { head: current.head, branch: current.branch };
416
+ };
417
+ for (const line of lines) {
418
+ if (line.startsWith('worktree ')) {
419
+ const previous = flush();
420
+ if (previous)
421
+ return previous;
422
+ current = { path: line.slice('worktree '.length), head: '', branch: null };
423
+ }
424
+ else if (current && line.startsWith('HEAD ')) {
425
+ current.head = line.slice('HEAD '.length);
426
+ }
427
+ else if (current && line.startsWith('branch ')) {
428
+ current.branch = line.slice('branch '.length);
429
+ }
430
+ }
431
+ return flush();
432
+ }
433
+ function assertWorktreeRegistrationIdentity(config, worktree, permit) {
434
+ const registration = worktreeRegistration(config, worktree);
435
+ if (!registration)
436
+ return;
437
+ if (registration.head !== permit.snapshot.head
438
+ || registration.branch !== `refs/heads/${permit.snapshot.branch}`) {
439
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${worktree}`);
440
+ }
441
+ }
442
+ function pruneWorktreeRegistration(config, worktree) {
443
+ runSafe('git', ['-C', config.repoRoot, 'worktree', 'prune']);
444
+ if (worktreeRegistration(config, worktree)) {
445
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${worktree}`);
446
+ }
447
+ }
448
+ function stageWorktreeRemoval(config, worktree, permit, tombstone, recovering, ownership) {
449
+ assertManagedPath(config.worktreeBase, worktree);
450
+ assertManagedPath(config.worktreeBase, tombstone);
451
+ const worktreeExists = fs.existsSync(worktree);
452
+ const tombstoneExists = fs.existsSync(tombstone);
453
+ if (worktreeExists || !recovering)
454
+ verifyWorktreePermit(permit);
455
+ if (recovering) {
456
+ if (worktreeExists || !tombstoneExists) {
457
+ if (worktreeExists && tombstoneExists) {
458
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${worktree}`);
459
+ }
460
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_ACTION_OUTCOME_UNKNOWN: ${worktree}`);
461
+ }
462
+ assertOwnedRemovalTombstone(config.worktreeBase, tombstone, ownership);
463
+ assertWorktreeRegistrationIdentity(config, worktree, permit);
464
+ pruneWorktreeRegistration(config, worktree);
465
+ return;
466
+ }
467
+ if (!worktreeExists)
468
+ return;
469
+ stageManagedRemoval(config.worktreeBase, worktree, tombstone, false, ownership);
470
+ pruneWorktreeRegistration(config, worktree);
471
+ }
472
+ function cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest) {
473
+ const journals = listSandboxRemovalJournals({
474
+ branch: target.effectiveBranch,
475
+ project: config.project,
476
+ targetDigest
477
+ });
478
+ if (journals.length === 0)
479
+ return;
480
+ const completed = (phase) => journals.every((journal) => (sandboxRemovalPhaseIndex(journal.phase) >= sandboxRemovalPhaseIndex(phase)));
481
+ if (completed('workspace-removed')) {
482
+ cleanupManagedTombstones(config.workspaceViewBase, targetDigest, committedTarget.permitDigest, 'workspace', target.workspaceViewRoots);
483
+ cleanupManagedTombstones(path.join(config.controlBase, config.project), targetDigest, committedTarget.permitDigest, 'workspace', target.controlRoots);
484
+ cleanupManagedTombstones(config.worktreeBase, targetDigest, committedTarget.permitDigest, 'worktree', committedTarget.worktreePaths);
485
+ }
486
+ if (completed('branch-removed')) {
487
+ cleanupBranchTombstone(config, target.effectiveBranch, targetDigest, new Map(committedTarget.permits.map((permit) => [path.resolve(permit.path), {
488
+ mode: permit.mode,
489
+ snapshot: permit.snapshot
490
+ }])));
491
+ }
492
+ if (completed('tool-removed')) {
493
+ cleanupManagedTombstones(config.home, targetDigest, committedTarget.permitDigest, 'tool', committedTarget.toolPaths);
494
+ }
495
+ if (completed('shell-removed')) {
496
+ cleanupManagedTombstones(config.shellConfigBase, targetDigest, committedTarget.permitDigest, 'shell', committedTarget.shellPaths);
497
+ }
498
+ if (completed('share-removed')) {
499
+ cleanupManagedTombstones(config.shareBase, targetDigest, committedTarget.permitDigest, 'share', [committedTarget.sharePath]);
500
+ }
501
+ }
502
+ function removalActionPaths(target, config, phase) {
503
+ if (phase === 'workspace-removed') {
504
+ return [...target.workspaceViewRoots, ...target.controlRoots];
505
+ }
506
+ if (phase === 'tool-removed') {
507
+ return target.toolCandidates.flatMap(({ candidates }) => candidates);
508
+ }
509
+ if (phase === 'shell-removed') {
510
+ return shellConfigDirCandidates(config, target.effectiveBranch);
511
+ }
512
+ if (phase === 'share-removed') {
513
+ return [shareBranchDir(config, target.effectiveBranch)];
514
+ }
515
+ return [];
516
+ }
517
+ function permitsFromJournal(journals, target, expectedTargetDigest) {
518
+ const permits = new Map();
519
+ for (const journal of journals) {
520
+ if (journal.target.targetDigest !== expectedTargetDigest)
521
+ continue;
522
+ if (journal.target.branch !== target.effectiveBranch) {
523
+ throw new Error('SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH');
524
+ }
525
+ for (const entry of journal.target.permits) {
526
+ if (path.resolve(entry.path) !== path.resolve(entry.snapshot.worktree)) {
527
+ throw new Error('SANDBOX_CONTROL_REMOVAL_PERMIT_MISMATCH');
528
+ }
529
+ permits.set(path.resolve(entry.path), {
530
+ mode: entry.mode,
531
+ snapshot: entry.snapshot
532
+ });
533
+ }
534
+ }
535
+ return permits;
536
+ }
537
+ export function sandboxManagedPathKey(candidate, platform = process.platform, resolveExistingPath = (resolved) => fs.realpathSync.native(resolved)) {
538
+ const resolved = path.resolve(candidate);
539
+ let identity = resolved;
540
+ try {
541
+ identity = resolveExistingPath(resolved);
542
+ }
543
+ catch (error) {
544
+ if (!isMissingPathError(error)) {
545
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: unable to determine managed path identity for '${resolved}'`);
546
+ }
547
+ }
548
+ return platform === 'win32' ? identity.toLowerCase() : identity;
549
+ }
550
+ function projectSandboxControlRoots(config) {
551
+ const projectRoot = path.join(config.controlBase, config.project);
552
+ let containers;
553
+ try {
554
+ containers = fs.readdirSync(projectRoot, { withFileTypes: true });
555
+ }
556
+ catch (error) {
557
+ if (isMissingPathError(error))
558
+ return [];
559
+ throw error;
560
+ }
561
+ return containers
562
+ .filter((container) => container.isDirectory())
563
+ .flatMap((container) => {
564
+ const containerRoot = path.join(projectRoot, container.name);
565
+ const identities = fs.readdirSync(containerRoot, { withFileTypes: true });
566
+ return identities
567
+ .filter((identity) => identity.isDirectory())
568
+ .map((identity) => path.join(containerRoot, identity.name));
569
+ });
570
+ }
571
+ function projectSandboxControlBindingEvidence(config, controlRoots = projectSandboxControlRoots(config), removalJournals = listSandboxRemovalJournals({ project: config.project })) {
572
+ return createSandboxControlBindingEvidence(config.repoRoot, controlRoots, removalJournals);
573
+ }
574
+ // Reasons that mean "intentionally preserved", not "cleanup is unsafe". A task
575
+ // that is still active keeps its auxiliary intents by design, so preserving
576
+ // them must not make its sandbox unremovable. Every other protected reason
577
+ // signals tampering or an unreadable path and still blocks, as does any
578
+ // failure, so unknown reasons stay fail-closed.
579
+ const REMOVAL_PRESERVED_REASONS = new Set([
580
+ 'TASK_STATE_PROTECTED',
581
+ 'TASK_NOT_FOUND',
582
+ 'LFAI_STATE_PROTECTED',
583
+ 'LFAI_RETRY_OR_WARNING_OPEN',
584
+ 'FINALIZATION_RECEIPT_MISSING',
585
+ 'FINALIZATION_RECEIPT_PENDING',
586
+ 'AUXILIARY_ROOT_NOT_EMPTY'
587
+ ]);
588
+ function assertIntermediateCleanupPreflight(report) {
589
+ const blockers = report.items.filter((candidate) => candidate.disposition === 'failed'
590
+ || (candidate.disposition === 'protected' && !REMOVAL_PRESERVED_REASONS.has(candidate.reason)));
591
+ if (blockers.length === 0)
592
+ return;
593
+ throw new Error([
594
+ 'SANDBOX_AUXILIARY_PREFLIGHT_FAILED:',
595
+ ...blockers.map((candidate) => (`${candidate.kind} ${candidate.path} (${candidate.taskId ?? 'unbound'}; ${candidate.reason})`))
596
+ ].join('\n'));
597
+ }
598
+ function recoveryContexts(config, target, worktrees) {
599
+ const candidates = worktreeDirCandidates(config, target.effectiveBranch).map((candidate) => path.resolve(candidate));
600
+ const existingCandidates = candidates.filter((candidate) => fs.existsSync(candidate));
601
+ if (existingCandidates.length !== 1)
602
+ return new Map();
603
+ const contexts = new Map();
604
+ for (const worktree of worktrees) {
605
+ const resolvedWorktree = path.resolve(worktree);
606
+ if (resolvedWorktree !== existingCandidates[0])
607
+ continue;
608
+ for (const root of target.controlRoots.filter((candidate) => fs.existsSync(candidate))) {
609
+ assertLegacyCandidateEvidence(root, config.controlBase, config, target.effectiveBranch, target.matchedContainers);
610
+ assertControlRootMatchesTarget(root, target.effectiveBranch, target.workspace);
611
+ }
612
+ contexts.set(resolvedWorktree, {
613
+ repoRoot: config.repoRoot,
614
+ worktreeBase: config.worktreeBase,
615
+ branch: target.effectiveBranch,
616
+ identitySource: target.workspace.mode,
617
+ taskId: target.workspace.mode === 'task-bound' ? target.workspace.taskId : null
618
+ });
619
+ }
620
+ return contexts;
621
+ }
622
+ function resolveRmTarget(config, tools, cleanupTarget, options = {}) {
623
+ assertValidBranchName(cleanupTarget.branch);
624
+ const engine = detectEngine(config);
625
+ const branch = cleanupTarget.branch;
626
+ const effectiveBranch = branch;
627
+ const worktreeCandidates = worktreeDirCandidates(config, branch);
628
+ const toolCandidates = tools.map((tool) => ({
629
+ tool,
630
+ candidates: toolConfigDirCandidates(tool, config.project, branch)
631
+ }));
632
+ const shellCandidates = shellConfigDirCandidates(config, branch);
633
+ const existing = runEngine(engine, 'docker', ['ps', '-a', '--format', '{{.Names}}']).split('\n').filter(Boolean);
634
+ const matchedContainers = options.discoveredContainers
635
+ ? options.discoveredContainers.map((container) => {
636
+ if (!existing.includes(container)) {
637
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: discovered container '${container}' is no longer present`);
638
+ }
639
+ return container;
640
+ })
641
+ : containerNameCandidates(config, branch).filter((name) => existing.includes(name));
642
+ const workspace = cleanupTarget.workspace;
643
+ const identities = [workspace];
644
+ const containers = options.discoveredContainers
645
+ ? matchedContainers
646
+ : [...new Set([...containerNameCandidates(config, effectiveBranch), ...matchedContainers])];
647
+ const controlRoots = containers.flatMap((container) => identities.map((identity) => sandboxControlPaths({
648
+ base: config.controlBase, project: config.project, container, identity
649
+ }).root));
650
+ const workspaceViewRoots = containers.flatMap((container) => identities.map((identity) => sandboxWorkspaceViewPaths({
651
+ base: config.workspaceViewBase, project: config.project, container, identity
652
+ }).root));
653
+ const managedPathCandidates = [...new Set([
654
+ ...worktreeCandidates,
655
+ ...toolCandidates.flatMap(({ candidates }) => candidates),
656
+ ...shellCandidates,
657
+ shareBranchDir(config, branch),
658
+ ...controlRoots,
659
+ ...workspaceViewRoots
660
+ ].map((candidate) => path.resolve(candidate)))];
661
+ return {
662
+ branch,
663
+ effectiveBranch,
664
+ engine,
665
+ matchedContainers,
666
+ existingWorktrees: worktreeCandidates.filter((candidate) => fs.existsSync(candidate)),
667
+ toolCandidates,
668
+ managedPathCandidates,
669
+ workspace,
670
+ controlRoots: [...new Set(controlRoots)],
671
+ workspaceViewRoots: [...new Set(workspaceViewRoots)]
672
+ };
673
+ }
674
+ function inspectNamedContainerIdentity(target, container) {
675
+ const raw = runSafeEngine(target.engine, 'docker', [
676
+ 'inspect', '--format', '{{json .}}', container
677
+ ]).trim();
678
+ let parsed;
679
+ try {
680
+ parsed = JSON.parse(raw);
681
+ }
682
+ catch {
683
+ throw new Error(`SANDBOX_WORKSPACE_IDENTITY_UNKNOWN: container '${container}' inspection is invalid`);
684
+ }
685
+ const value = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
686
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
687
+ throw new Error(`SANDBOX_WORKSPACE_IDENTITY_UNKNOWN: container '${container}' inspection is incomplete`);
688
+ }
689
+ const candidate = value;
690
+ if (typeof candidate.Id !== 'string' || !candidate.Id
691
+ || !candidate.Config?.Labels || typeof candidate.Config.Labels !== 'object'
692
+ || Array.isArray(candidate.Config.Labels)
693
+ || Object.values(candidate.Config.Labels).some((value) => typeof value !== 'string')) {
694
+ throw new Error(`SANDBOX_WORKSPACE_IDENTITY_UNKNOWN: container '${container}' inspection is incomplete`);
695
+ }
696
+ return { id: candidate.Id, labels: candidate.Config.Labels };
697
+ }
698
+ function assertMatchedContainerIdentities(config, target) {
699
+ const current = new Map();
700
+ for (const container of target.matchedContainers) {
701
+ const observation = inspectNamedContainerIdentity(target, container);
702
+ const stringLabels = observation.labels;
703
+ const branch = stringLabels[sandboxBranchLabel(config)];
704
+ if (branch !== target.branch) {
705
+ throw new Error(`SANDBOX_WORKSPACE_IDENTITY_CONFLICT: container '${container}' branch is ${JSON.stringify(branch ?? null)}, `
706
+ + `but this request is ${JSON.stringify(target.branch)}`);
707
+ }
708
+ const identity = parseSandboxWorkspaceIdentity(stringLabels, {
709
+ mode: sandboxWorkspaceModeLabel(config),
710
+ taskId: sandboxTaskIdLabel(config)
711
+ });
712
+ if (identity.mode === 'legacy-invalid' || !sameSandboxWorkspaceIdentity(identity, target.workspace)) {
713
+ const existingDescription = identity.mode === 'task-bound'
714
+ ? `task-bound:${identity.taskId}`
715
+ : identity.mode;
716
+ const requestedDescription = target.workspace.mode === 'task-bound'
717
+ ? `task-bound:${target.workspace.taskId}`
718
+ : target.workspace.mode;
719
+ throw new Error(`SANDBOX_WORKSPACE_IDENTITY_CONFLICT: container '${container}' is ${existingDescription}, `
720
+ + `but this request is ${requestedDescription}`);
721
+ }
722
+ current.set(container, observation);
723
+ }
724
+ return current;
725
+ }
726
+ function controlRootContainer(config, root) {
727
+ const relative = path.relative(path.join(config.controlBase, config.project), root);
728
+ const [container, identity, ...extra] = relative.split(path.sep);
729
+ if (!container || !identity || extra.length > 0) {
730
+ throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_INVALID: ${root}`);
731
+ }
732
+ return container;
733
+ }
734
+ function assertControlRootMatchesTarget(root, effectiveBranch, workspace) {
735
+ const manifestPath = path.join(root, 'manifest.json');
736
+ if (!fs.existsSync(manifestPath)) {
737
+ if (workspace.mode === 'task-bound') {
738
+ throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: ${root}`);
739
+ }
740
+ return;
741
+ }
742
+ const manifest = readSandboxControlManifest(manifestPath);
743
+ const identityMatches = workspace.mode === 'task-bound'
744
+ ? manifest.mode === 'task-bound' && manifest.taskId === workspace.taskId
745
+ : manifest.mode === 'branch-only';
746
+ if (manifest.branch !== effectiveBranch || !identityMatches) {
747
+ throw new Error(`SANDBOX_CONTROL_TARGET_MISMATCH: ${root}`);
748
+ }
749
+ }
750
+ function preflightRmTarget(config, target) {
751
+ const current = assertMatchedContainerIdentities(config, target);
752
+ const manifests = [];
753
+ for (const root of target.controlRoots.filter((candidate) => fs.existsSync(candidate))) {
754
+ assertLegacyCandidateEvidence(root, config.controlBase, config, target.effectiveBranch, target.matchedContainers);
755
+ assertControlRootMatchesTarget(root, target.effectiveBranch, target.workspace);
756
+ const manifestPath = path.join(root, 'manifest.json');
757
+ if (!fs.existsSync(manifestPath))
758
+ continue;
759
+ const manifest = readSandboxControlManifest(manifestPath);
760
+ const rootContainer = controlRootContainer(config, root);
761
+ if (manifest.container !== rootContainer) {
762
+ throw new Error(`SANDBOX_CONTROL_TARGET_MISMATCH: ${root}`);
763
+ }
764
+ const observed = current.get(manifest.container);
765
+ if (observed && (observed.id !== manifest.containerIdentity.id
766
+ || Object.entries(manifest.containerIdentity.labels).some(([key, value]) => observed.labels[key] !== value))) {
767
+ throw new Error(`SANDBOX_CONTROL_TARGET_MISMATCH: ${root}`);
768
+ }
769
+ manifests.push(manifest);
770
+ }
771
+ if (target.workspace.mode !== 'task-bound')
772
+ return;
773
+ const matched = new Set(target.matchedContainers);
774
+ const manifestContainers = manifests.map((manifest) => manifest.container);
775
+ if (matched.size > 0 && manifestContainers.some((container) => !matched.has(container))) {
776
+ throw new Error('SANDBOX_CONTROL_TARGET_MISMATCH: manifest container is outside the cleanup target');
777
+ }
778
+ for (const container of matched) {
779
+ const matches = manifests.filter((manifest) => manifest.container === container);
780
+ if (matches.length !== 1) {
781
+ throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: container '${container}'`);
782
+ }
783
+ }
784
+ if (matched.size === 0 && manifests.length > 0) {
785
+ const supported = new Set(containerNameCandidates(config, target.effectiveBranch));
786
+ if (manifests.some((manifest) => !supported.has(manifest.container))) {
787
+ throw new Error('SANDBOX_CONTROL_TARGET_MISMATCH: manifest container is outside the cleanup target');
788
+ }
789
+ }
790
+ }
791
+ function assertCleanupGroupPathsDoNotOverlap(groups, protectedTargets = []) {
792
+ const owners = new Map();
793
+ const addOwner = (branch, candidates) => {
794
+ for (const candidate of candidates) {
795
+ const key = sandboxManagedPathKey(candidate);
796
+ const existingBranch = owners.get(key);
797
+ if (existingBranch && existingBranch !== branch) {
798
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: managed path '${candidate}' is shared by branches `
799
+ + `${JSON.stringify(existingBranch)} and ${JSON.stringify(branch)}`);
800
+ }
801
+ owners.set(key, branch);
802
+ }
803
+ };
804
+ for (const group of groups) {
805
+ addOwner(group.cleanupTarget.branch, group.target.managedPathCandidates ?? []);
806
+ }
807
+ for (const target of protectedTargets) {
808
+ addOwner(target.branch, target.managedPathCandidates);
809
+ }
810
+ }
811
+ function assertWorktreeBranchesMatchGroups(groups, inspections) {
812
+ const byPath = new Map(inspections.flatMap((inspection) => inspection.status === 'failed'
813
+ ? []
814
+ : [[sandboxManagedPathKey(inspection.snapshot.worktree), inspection.snapshot.branch]]));
815
+ for (const group of groups) {
816
+ for (const worktree of group.target.existingWorktrees) {
817
+ const registeredBranch = byPath.get(sandboxManagedPathKey(worktree));
818
+ if (registeredBranch && registeredBranch !== group.cleanupTarget.branch) {
819
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: worktree '${worktree}' is registered to branch `
820
+ + `${JSON.stringify(registeredBranch)}, but cleanup targets ${JSON.stringify(group.cleanupTarget.branch)}`);
821
+ }
822
+ }
823
+ }
824
+ }
825
+ function assertLegacyCandidateEvidence(candidate, base, config, effectiveBranch, matchedContainers) {
826
+ const relative = path.relative(path.join(base, config.project), candidate);
827
+ const [container, identity] = relative.split(path.sep);
828
+ const [canonical, legacy] = containerNameCandidates(config, effectiveBranch);
829
+ if (!container || !identity || legacy === canonical || container !== legacy || matchedContainers.includes(container))
830
+ return;
831
+ const manifestPath = path.join(config.controlBase, config.project, container, identity, 'manifest.json');
832
+ if (!fs.existsSync(manifestPath)) {
833
+ throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: ${candidate}`);
834
+ }
835
+ }
836
+ function assertRemoved(target, label) {
837
+ if (fs.existsSync(target))
838
+ throw new Error(`${label} still exists after removal: ${target}`);
839
+ }
840
+ function removeEmptyManagedParent(base, directory) {
841
+ const parent = path.dirname(directory);
842
+ if (path.resolve(parent) === path.resolve(base))
843
+ return;
844
+ assertManagedPath(base, parent);
845
+ try {
846
+ fs.rmdirSync(parent);
847
+ }
848
+ catch (error) {
849
+ if (['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code ?? ''))
850
+ return;
851
+ throw error;
852
+ }
853
+ assertRemoved(parent, 'Empty sandbox container directory');
854
+ }
855
+ async function removeExactSandboxContainer(engine, manifest, timeoutMs) {
856
+ const deadlineAt = Date.now() + timeoutMs;
857
+ const remaining = () => Math.max(1, deadlineAt - Date.now());
858
+ const inspect = () => inspectSandboxControlContainer(manifest, { timeoutMs: remaining() });
859
+ const runAuthorityCommand = (args) => {
860
+ const command = manifest.authorityEvidence
861
+ ? commandForSandboxAuthority(manifest.authorityEvidence, 'docker', args)
862
+ : null;
863
+ return command ? runOk(command.cmd, command.args, { timeout: remaining() })
864
+ : runOkEngine(engine, 'docker', args, { timeout: remaining() });
865
+ };
866
+ const before = await inspect();
867
+ if (before.state === 'unknown')
868
+ throw new Error(`SANDBOX_CONTROL_CONTAINER_UNKNOWN: ${before.reason}`);
869
+ if (before.state === 'absent')
870
+ return;
871
+ if (before.running && !runAuthorityCommand(['stop', '--timeout', '1', manifest.containerIdentity.id])) {
872
+ const afterStop = await inspect();
873
+ if (afterStop.state !== 'absent' && afterStop.state !== 'found') {
874
+ throw new Error(`SANDBOX_CONTROL_CONTAINER_UNKNOWN: ${afterStop.reason}`);
875
+ }
876
+ if (afterStop.state === 'found' && afterStop.running) {
877
+ throw new Error(`Failed to stop sandbox container: ${manifest.containerIdentity.id}`);
878
+ }
879
+ }
880
+ const afterStop = await inspect();
881
+ if (afterStop.state === 'unknown')
882
+ throw new Error(`SANDBOX_CONTROL_CONTAINER_UNKNOWN: ${afterStop.reason}`);
883
+ if (afterStop.state === 'found' && !runAuthorityCommand(['rm', manifest.containerIdentity.id])) {
884
+ const afterRemove = await inspect();
885
+ if (afterRemove.state !== 'absent') {
886
+ throw new Error(`Failed to remove sandbox container: ${manifest.containerIdentity.id}`);
887
+ }
888
+ }
889
+ }
890
+ async function removeProjectControlRoots(config, engine, options = {}) {
891
+ const containers = new Set();
892
+ const projectRoot = path.join(config.controlBase, config.project);
893
+ if (!fs.existsSync(projectRoot))
894
+ return containers;
895
+ assertManagedPath(config.controlBase, projectRoot);
896
+ const projectStat = fs.lstatSync(projectRoot);
897
+ if (!projectStat.isDirectory() || projectStat.isSymbolicLink())
898
+ throw new Error('SANDBOX_CONTROL_CHANNEL_INVALID');
899
+ for (const root of projectSandboxControlRoots(config)) {
900
+ const manifestPath = path.join(root, 'manifest.json');
901
+ if (!fs.existsSync(manifestPath))
902
+ throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: ${root}`);
903
+ const manifest = readSandboxControlManifest(manifestPath);
904
+ containers.add(manifest.container);
905
+ await removeSandboxControlRoot(root, {
906
+ inspectContainer: (timeoutMs) => inspectSandboxControlContainer(manifest, { timeoutMs }),
907
+ removeContainer: (timeoutMs) => removeExactSandboxContainer(engine, manifest, timeoutMs),
908
+ ...(options.retainRemovalJournal ? { retainRemovalJournal: true } : {})
909
+ });
910
+ }
911
+ return containers;
912
+ }
913
+ function completePurgeRemovalJournals(config) {
914
+ const projectRoot = path.resolve(config.controlBase, config.project);
915
+ const projectJournals = listSandboxRemovalJournals({ project: config.project }).filter((journal) => {
916
+ const relativeRoot = path.relative(projectRoot, path.resolve(journal.target.controlRoot));
917
+ return relativeRoot !== '' && relativeRoot !== '..'
918
+ && !relativeRoot.startsWith(`..${path.sep}`) && !path.isAbsolute(relativeRoot);
919
+ });
920
+ if (projectJournals.some((journal) => !isDefaultSandboxRemovalJournal(journal))) {
921
+ throw new Error('SANDBOX_CONTROL_REMOVE_RECOVERY_PENDING');
922
+ }
923
+ for (const journal of projectJournals) {
924
+ const resourceLock = acquireSandboxResourceLock(`${journal.engine}:${journal.containerId}`, {
925
+ lockDomain: journal.lockDomain
926
+ });
927
+ try {
928
+ let current = journal;
929
+ const currentProcessStartTime = getProcessStartTime(process.pid);
930
+ const ownedByCurrentProcess = currentProcessStartTime !== null
931
+ && current.owner.pid === process.pid
932
+ && current.owner.startTime === currentProcessStartTime;
933
+ if (!ownedByCurrentProcess) {
934
+ current = claimSandboxRemovalJournal(current, { resourceLock });
935
+ }
936
+ advanceSandboxRemovalJournalToPhase(current, 'completed', resourceLock);
937
+ }
938
+ finally {
939
+ resourceLock.release();
940
+ }
941
+ }
942
+ }
943
+ function inspectionBlockers(inspections) {
944
+ return inspections.filter((inspection) => inspection.status !== 'clean');
945
+ }
946
+ function blockerMessage(blockers) {
947
+ return blockers.map((blocker) => {
948
+ if (blocker.status === 'failed')
949
+ return `${JSON.stringify(blocker.worktree)}: ${blocker.message}`;
950
+ return `${formatWorktreeSnapshot(blocker.snapshot)}\n Action: commit, stash, clean, or remove this sandbox interactively.`;
951
+ }).join('\n');
952
+ }
953
+ function cleanPermits(inspections) {
954
+ const permits = new Map();
955
+ for (const inspection of inspections) {
956
+ if (inspection.status === 'clean')
957
+ permits.set(inspection.snapshot.worktree, createCleanPermit(inspection.snapshot));
958
+ }
959
+ return permits;
960
+ }
961
+ async function authorizeWorktrees(worktrees, { allowDirtyDiscard, assumeYes }, { interactive = Boolean(process.stdin.isTTY), confirm = p.confirm, isCancel = p.isCancel, recovery = new Map() } = {}) {
962
+ const inspections = worktrees.map((worktree) => {
963
+ const inspection = inspectWorktrees([worktree])[0];
964
+ const context = recovery.get(path.resolve(worktree));
965
+ return inspection.status === 'failed' && context
966
+ ? inspectRecoveredWorktree(worktree, context)
967
+ : inspection;
968
+ });
969
+ const failures = inspections.filter((inspection) => inspection.status === 'failed');
970
+ if (failures.length > 0)
971
+ throw new Error(`Unable to inspect worktree(s):\n${blockerMessage(failures)}`);
972
+ const permits = cleanPermits(inspections);
973
+ for (const inspection of inspections) {
974
+ if (inspection.status !== 'dirty')
975
+ continue;
976
+ if (!allowDirtyDiscard || assumeYes || !interactive) {
977
+ throw new Error(`Refusing to remove dirty worktree(s):\n${blockerMessage([inspection])}`);
978
+ }
979
+ p.log.warn(formatWorktreeSnapshot(inspection.snapshot));
980
+ const confirmed = await confirm({
981
+ message: 'Discard this worktree and all its uncommitted changes, including later changes?',
982
+ initialValue: false
983
+ });
984
+ if (isCancel(confirmed) || !confirmed)
985
+ throw new Error('Dirty worktree removal cancelled; nothing was deleted');
986
+ permits.set(inspection.snapshot.worktree, createDiscardPermit(inspection.snapshot));
987
+ }
988
+ return permits;
989
+ }
990
+ async function runRmOneUnderRepositoryLock(config, tools, branch, options = {}) {
991
+ const target = options.target ?? resolveRmTarget(config, tools, options.cleanupTarget ?? resolveSandboxCleanupTarget(branch, config.repoRoot));
992
+ const taskId = target.workspace.mode === 'task-bound' ? target.workspace.taskId : null;
993
+ const execute = () => rmOneCore(config, tools, branch, { ...options, target });
994
+ return taskId
995
+ ? withTaskExecutionLock(config.repoRoot, taskId, 'sandbox-removal', execute)
996
+ : execute();
997
+ }
998
+ async function rmOne(config, tools, branch, options = {}) {
999
+ await withRepositoryMutationLock(config.repoRoot, () => runRmOneUnderRepositoryLock(config, tools, branch, options));
1000
+ }
1001
+ async function rmOneCore(config, tools, branch, options = {}) {
1002
+ const target = options.target ?? resolveRmTarget(config, tools, options.cleanupTarget ?? resolveSandboxCleanupTarget(branch, config.repoRoot));
1003
+ const { effectiveBranch, engine, matchedContainers, existingWorktrees, toolCandidates } = target;
1004
+ const { workspace, controlRoots, workspaceViewRoots } = target;
1005
+ preflightRmTarget(config, target);
1006
+ const auxiliaryTaskId = workspace.mode === 'task-bound' ? workspace.taskId : null;
1007
+ if (auxiliaryTaskId) {
1008
+ const targetJournals = listSandboxRemovalJournals({
1009
+ branch: effectiveBranch,
1010
+ project: config.project,
1011
+ targetDigest: removalTargetDigest(config, target)
1012
+ });
1013
+ assertIntermediateCleanupPreflight(scanIntermediateCleanup(config.repoRoot, {
1014
+ preflight: true,
1015
+ taskIds: [auxiliaryTaskId],
1016
+ controlBindingEvidence: projectSandboxControlBindingEvidence(config, controlRoots, targetJournals)
1017
+ }));
1018
+ }
1019
+ const confirm = options.prompt?.confirm ?? p.confirm;
1020
+ const isCancel = options.prompt?.isCancel ?? p.isCancel;
1021
+ if (!options.quiet) {
1022
+ p.intro(pc.cyan(`Removing sandbox for ${branch}`));
1023
+ }
1024
+ const targetDigest = removalTargetDigest(config, target);
1025
+ const existingJournals = listSandboxRemovalJournals({
1026
+ branch: effectiveBranch,
1027
+ project: config.project,
1028
+ targetDigest
1029
+ });
1030
+ const persistedTarget = existingJournals[0]?.target;
1031
+ for (const journal of existingJournals) {
1032
+ if (!persistedTarget)
1033
+ break;
1034
+ assertRemovalSelectionMatches(persistedTarget, journal.target);
1035
+ }
1036
+ const recovery = options.permits
1037
+ ? new Map()
1038
+ : recoveryContexts(config, target, existingWorktrees);
1039
+ const journalPermits = options.permits ? new Map()
1040
+ : permitsFromJournal(existingJournals, target, targetDigest);
1041
+ const permits = options.permits
1042
+ ? new Map(options.permits)
1043
+ : journalPermits.size > 0
1044
+ ? journalPermits
1045
+ : await authorizeWorktrees(existingWorktrees, {
1046
+ allowDirtyDiscard: options.allowDirtyDiscard ?? true,
1047
+ assumeYes: Boolean(options.assumeYes)
1048
+ }, {
1049
+ ...options.prompt,
1050
+ interactive: options.interactive ?? Boolean(process.stdin.isTTY),
1051
+ recovery
1052
+ });
1053
+ for (const worktree of existingWorktrees) {
1054
+ const permit = permits.get(path.resolve(worktree));
1055
+ if (!permit)
1056
+ throw new Error(`Missing worktree removal permit: ${worktree}`);
1057
+ const worktreeTombstone = removalTombstonePath(targetDigest, 'worktree', worktree);
1058
+ const workspacePhasePending = existingJournals.some((journal) => (sandboxRemovalPhaseIndex(journal.phase) < sandboxRemovalPhaseIndex('workspace-removed')));
1059
+ if (fs.existsSync(worktree)
1060
+ || (workspacePhasePending
1061
+ && !isOwnedRemovalTombstone(config.worktreeBase, worktreeTombstone, {
1062
+ version: 1,
1063
+ targetDigest,
1064
+ permitDigest: removalPermitDigest(permits),
1065
+ kind: 'worktree',
1066
+ source: worktree
1067
+ }))) {
1068
+ verifyWorktreePermit(permit);
1069
+ }
1070
+ }
1071
+ const recoveredRemovalChoice = persistedTarget;
1072
+ const shouldRemoveWorktree = recoveredRemovalChoice
1073
+ ? recoveredRemovalChoice.removeWorktree
1074
+ : existingWorktrees.length === 0
1075
+ ? false
1076
+ : options.assumeYes
1077
+ ? true
1078
+ : await confirm({
1079
+ message: `Remove worktree(s): ${existingWorktrees.join(', ')}?`,
1080
+ initialValue: true
1081
+ });
1082
+ if (isCancel(shouldRemoveWorktree)) {
1083
+ p.outro('Cancelled');
1084
+ return null;
1085
+ }
1086
+ const shouldDeleteBranch = recoveredRemovalChoice
1087
+ ? recoveredRemovalChoice.removeBranch
1088
+ : shouldRemoveWorktree && existingWorktrees.length > 0
1089
+ ? options.assumeYes
1090
+ ? true
1091
+ : await confirm({
1092
+ message: `Also delete local branch '${effectiveBranch}'?`,
1093
+ initialValue: true
1094
+ })
1095
+ : false;
1096
+ if (isCancel(shouldDeleteBranch)) {
1097
+ p.outro('Cancelled');
1098
+ return null;
1099
+ }
1100
+ const sharePath = path.resolve(shareBranchDir(config, effectiveBranch));
1101
+ const shouldRemoveShare = recoveredRemovalChoice
1102
+ ? recoveredRemovalChoice.removeShare
1103
+ : fs.existsSync(sharePath)
1104
+ ? options.assumeYes
1105
+ ? true
1106
+ : await confirm({
1107
+ message: `Remove share dir for branch '${effectiveBranch}' (${sharePath})?`,
1108
+ initialValue: true
1109
+ })
1110
+ : false;
1111
+ if (isCancel(shouldRemoveShare)) {
1112
+ p.outro('Cancelled');
1113
+ return null;
1114
+ }
1115
+ const committedTarget = persistedTarget
1116
+ ? {
1117
+ ...persistedTarget,
1118
+ permitDigest: removalPermitDigest(permits),
1119
+ permits: removalPermitCommits(permits)
1120
+ }
1121
+ : removalTargetCommit(config, target, permits, Boolean(shouldRemoveWorktree), Boolean(shouldDeleteBranch), Boolean(shouldRemoveShare));
1122
+ if (persistedTarget)
1123
+ assertRemovalSelectionMatches(persistedTarget, committedTarget);
1124
+ const coordinatedManifests = controlRoots
1125
+ .filter((candidate) => fs.existsSync(candidate))
1126
+ .flatMap((root) => {
1127
+ const manifestPath = path.join(root, 'manifest.json');
1128
+ return fs.existsSync(manifestPath)
1129
+ ? [[root, readSandboxControlManifest(manifestPath), fs.readFileSync(manifestPath, 'utf8')]]
1130
+ : [];
1131
+ });
1132
+ const resourceLocks = new Map();
1133
+ const recoveredContainerNames = new Set();
1134
+ try {
1135
+ for (const [root, manifest] of [...coordinatedManifests].sort(([left], [right]) => left.localeCompare(right))) {
1136
+ resourceLocks.set(root, acquireSandboxResourceLock(`${manifest.engine}:${manifest.containerIdentity.id}`, { lockDomain: manifest.authorityEvidence.lockDomain }));
1137
+ }
1138
+ for (const journal of existingJournals.filter((candidate) => !fs.existsSync(candidate.target.controlRoot))) {
1139
+ if (!target.controlRoots.some((root) => path.resolve(root) === path.resolve(journal.target.controlRoot))) {
1140
+ throw new Error('SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH');
1141
+ }
1142
+ assertRemovalSelectionMatches(committedTarget, journal.target);
1143
+ if (journal.target.permitDigest !== removalPermitDigest(permits)) {
1144
+ throw new Error('SANDBOX_CONTROL_REMOVAL_PERMIT_MISMATCH');
1145
+ }
1146
+ const lock = acquireSandboxResourceLock(`${journal.engine}:${journal.containerId}`, {
1147
+ lockDomain: journal.lockDomain
1148
+ });
1149
+ resourceLocks.set(journal.target.controlRoot, lock);
1150
+ const current = listSandboxRemovalJournals({
1151
+ branch: journal.target.branch,
1152
+ project: journal.target.project,
1153
+ targetDigest: journal.target.targetDigest
1154
+ }).find((candidate) => candidate.carrierIdentityDigest === journal.carrierIdentityDigest);
1155
+ if (!current || current.revision !== journal.revision || current.handoffId !== journal.handoffId) {
1156
+ throw new Error('SANDBOX_CONTROL_REMOVAL_JOURNAL_REVISION_MISMATCH');
1157
+ }
1158
+ const claimed = claimSandboxRemovalJournal(current, { resourceLock: lock });
1159
+ if (!['carrier-finalizing', 'carrier-removed', 'workspace-finalizing', 'workspace-removed',
1160
+ 'branch-finalizing', 'branch-removed', 'tool-finalizing', 'tool-removed',
1161
+ 'shell-finalizing', 'shell-removed', 'share-finalizing', 'share-removed', 'completed']
1162
+ .includes(claimed.phase)) {
1163
+ throw new Error('SANDBOX_CONTROL_REMOVE_RECOVERY_PENDING');
1164
+ }
1165
+ const recovered = claimed.phase === 'carrier-finalizing'
1166
+ ? advanceSandboxRemovalJournalPhase(claimed, 'carrier-removed', { resourceLock: lock })
1167
+ : claimed;
1168
+ recoveredContainerNames.add(controlRootContainer(config, journal.target.controlRoot));
1169
+ }
1170
+ cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
1171
+ preflightRmTarget(config, target);
1172
+ const coordinatedContainers = new Set(recoveredContainerNames);
1173
+ for (const root of controlRoots.filter((candidate) => fs.existsSync(candidate))) {
1174
+ assertLegacyCandidateEvidence(root, config.controlBase, config, effectiveBranch, matchedContainers);
1175
+ assertControlRootMatchesTarget(root, effectiveBranch, workspace);
1176
+ const manifestPath = path.join(root, 'manifest.json');
1177
+ if (!fs.existsSync(manifestPath))
1178
+ continue;
1179
+ const currentRaw = fs.readFileSync(manifestPath, 'utf8');
1180
+ const manifest = readSandboxControlManifest(manifestPath);
1181
+ const initial = coordinatedManifests.find(([candidate]) => candidate === root);
1182
+ if (!initial || currentRaw !== initial[2])
1183
+ throw new Error('SANDBOX_CONTROL_MANIFEST_CHANGED');
1184
+ coordinatedContainers.add(manifest.container);
1185
+ await removeSandboxControlRoot(root, {
1186
+ inspectContainer: (timeoutMs) => inspectSandboxControlContainer(manifest, { timeoutMs }),
1187
+ removeContainer: (timeoutMs) => removeExactSandboxContainer(engine, manifest, timeoutMs),
1188
+ resourceLock: resourceLocks.get(root),
1189
+ retainRemovalJournal: true,
1190
+ removalTarget: { ...committedTarget, controlRoot: path.resolve(root) }
1191
+ });
1192
+ removeEmptyManagedParent(path.join(config.controlBase, config.project), root);
1193
+ }
1194
+ if ([...recoveredContainerNames].some((name) => matchedContainers.includes(name))) {
1195
+ throw new Error('SANDBOX_CONTROL_CONTAINER_REAPPEARED');
1196
+ }
1197
+ const uncoordinatedContainers = matchedContainers.filter((name) => !coordinatedContainers.has(name));
1198
+ if (uncoordinatedContainers.length > 0) {
1199
+ if (workspace.mode === 'task-bound') {
1200
+ throw new Error(`SANDBOX_CONTROL_TARGET_EVIDENCE_MISSING: container '${uncoordinatedContainers[0]}'`);
1201
+ }
1202
+ const spinner = p.spinner();
1203
+ spinner.start(`Stopping container(s): ${uncoordinatedContainers.join(', ')}`);
1204
+ for (const name of uncoordinatedContainers) {
1205
+ if (!runOkEngine(engine, 'docker', ['stop', name]))
1206
+ throw new Error(`Failed to stop sandbox container: ${name}`);
1207
+ if (!runOkEngine(engine, 'docker', ['rm', name]))
1208
+ throw new Error(`Failed to remove sandbox container: ${name}`);
1209
+ }
1210
+ const remaining = runEngine(engine, 'docker', ['ps', '-a', '--format', '{{.Names}}']).split('\n').filter(Boolean);
1211
+ const leftovers = uncoordinatedContainers.filter((name) => remaining.includes(name));
1212
+ if (leftovers.length > 0)
1213
+ throw new Error(`Sandbox container(s) still exist after removal: ${leftovers.join(', ')}`);
1214
+ spinner.stop(pc.green(`Removed container(s): ${uncoordinatedContainers.join(', ')}`));
1215
+ }
1216
+ else {
1217
+ p.log.warn(`No sandbox container found for '${branch}'`);
1218
+ }
1219
+ const runWorkspaceCleanup = prepareRemovalAction(config.project, target, targetDigest, 'workspace-finalizing', 'workspace-removed', resourceLocks);
1220
+ if (runWorkspaceCleanup.run) {
1221
+ for (const [roots, base, label] of [
1222
+ [workspaceViewRoots, path.join(config.workspaceViewBase, config.project), 'Workspace view'],
1223
+ [controlRoots, path.join(config.controlBase, config.project), 'Control channel']
1224
+ ]) {
1225
+ for (const directory of roots.filter((candidate) => shouldStageManagedRemoval(candidate, removalTombstonePath(targetDigest, 'workspace', candidate), runWorkspaceCleanup.recovering))) {
1226
+ assertLegacyCandidateEvidence(directory, base === path.join(config.controlBase, config.project)
1227
+ ? config.controlBase : config.workspaceViewBase, config, effectiveBranch, matchedContainers);
1228
+ stageManagedRemoval(base, directory, removalTombstonePath(targetDigest, 'workspace', directory), runWorkspaceCleanup.recovering, {
1229
+ version: 1,
1230
+ targetDigest,
1231
+ permitDigest: committedTarget.permitDigest,
1232
+ kind: 'workspace',
1233
+ source: directory
1234
+ });
1235
+ if (!options.quiet)
1236
+ p.log.success(`${label} removed: ${directory}`);
1237
+ }
1238
+ }
1239
+ if (shouldRemoveWorktree) {
1240
+ for (const worktree of existingWorktrees) {
1241
+ const permit = permits.get(path.resolve(worktree));
1242
+ if (!permit)
1243
+ throw new Error(`Missing worktree removal permit: ${worktree}`);
1244
+ stageWorktreeRemoval(config, worktree, permit, removalTombstonePath(targetDigest, 'worktree', worktree), runWorkspaceCleanup.recovering, {
1245
+ version: 1,
1246
+ targetDigest,
1247
+ permitDigest: committedTarget.permitDigest,
1248
+ kind: 'worktree',
1249
+ source: worktree
1250
+ });
1251
+ }
1252
+ }
1253
+ }
1254
+ else {
1255
+ assertRemovalPathsAbsent([
1256
+ ...removalActionPaths(target, config, 'workspace-removed'),
1257
+ ...(shouldRemoveWorktree ? existingWorktrees : [])
1258
+ ]);
1259
+ }
1260
+ advanceRemovalJournals(config.project, target, targetDigest, 'workspace-removed', resourceLocks);
1261
+ cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
1262
+ for (const [roots, base] of [
1263
+ [workspaceViewRoots, path.join(config.workspaceViewBase, config.project)],
1264
+ [controlRoots, path.join(config.controlBase, config.project)]
1265
+ ]) {
1266
+ for (const directory of roots) {
1267
+ if (!fs.existsSync(directory))
1268
+ removeEmptyManagedParent(base, directory);
1269
+ }
1270
+ }
1271
+ const runBranchCleanup = prepareRemovalAction(config.project, target, targetDigest, 'branch-finalizing', 'branch-removed', resourceLocks);
1272
+ if (runBranchCleanup.run) {
1273
+ if (shouldRemoveWorktree && shouldDeleteBranch) {
1274
+ stageBranchRemoval(config, effectiveBranch, targetDigest, permits, runBranchCleanup.recovering);
1275
+ }
1276
+ }
1277
+ else if (shouldRemoveWorktree && shouldDeleteBranch
1278
+ && runOk('git', ['-C', config.repoRoot, 'show-ref', '--verify', `refs/heads/${effectiveBranch}`])) {
1279
+ throw new Error(`SANDBOX_CONTROL_REMOVAL_TARGET_MISMATCH: ${effectiveBranch}`);
1280
+ }
1281
+ advanceRemovalJournals(config.project, target, targetDigest, 'branch-removed', resourceLocks);
1282
+ cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
1283
+ const directoryStages = [
1284
+ { kind: 'tool', entries: toolCandidates.flatMap(({ tool, candidates }) => candidates.map((dir) => ({ dir, base: tool.sandboxBase, label: tool.name + ' state' }))) },
1285
+ { kind: 'shell', entries: shellConfigDirCandidates(config, effectiveBranch)
1286
+ .map((dir) => ({ dir, base: config.shellConfigBase, label: 'Shell config' })) },
1287
+ { kind: 'share', entries: shouldRemoveShare
1288
+ ? [{ dir: sharePath, base: config.shareBase, label: 'Share dir' }] : [] }
1289
+ ];
1290
+ for (const { kind, entries } of directoryStages) {
1291
+ const completedPhase = `${kind}-removed`;
1292
+ const action = prepareRemovalAction(config.project, target, targetDigest, `${kind}-finalizing`, completedPhase, resourceLocks);
1293
+ if (action.run) {
1294
+ for (const { dir, base, label } of entries) {
1295
+ const tombstone = removalTombstonePath(targetDigest, kind, dir);
1296
+ if (!shouldStageManagedRemoval(dir, tombstone, action.recovering))
1297
+ continue;
1298
+ stageManagedRemoval(base, dir, tombstone, action.recovering, {
1299
+ version: 1, targetDigest, permitDigest: committedTarget.permitDigest, kind, source: dir
1300
+ });
1301
+ p.log.success(`${label} removed: ${dir}`);
1302
+ }
1303
+ }
1304
+ else if (kind !== 'share' || shouldRemoveShare) {
1305
+ assertRemovalPathsAbsent(removalActionPaths(target, config, completedPhase));
1306
+ }
1307
+ advanceRemovalJournals(config.project, target, targetDigest, completedPhase, resourceLocks);
1308
+ cleanupCompletedRemovalArtifacts(config, target, committedTarget, targetDigest);
1309
+ }
1310
+ advanceRemovalJournals(config.project, target, targetDigest, 'completed', resourceLocks);
1311
+ let auxiliaryReport = null;
1312
+ if (auxiliaryTaskId) {
1313
+ const finalControlBindingEvidence = projectSandboxControlBindingEvidence(config, controlRoots, listSandboxRemovalJournals({ branch: effectiveBranch, project: config.project, targetDigest }));
1314
+ const report = cleanupIntermediateUnderRemovalCoordinator(config.repoRoot, {
1315
+ taskIds: [auxiliaryTaskId],
1316
+ controlBindingEvidence: finalControlBindingEvidence,
1317
+ lockedTaskIds: new Set([auxiliaryTaskId])
1318
+ });
1319
+ auxiliaryReport = report;
1320
+ if (!options.quiet) {
1321
+ for (const line of formatIntermediateCleanupReport(report))
1322
+ p.log.message(line);
1323
+ }
1324
+ if (!report.remaining.some((item) => item.taskId === auxiliaryTaskId)) {
1325
+ for (const journal of listSandboxRemovalJournals({
1326
+ branch: effectiveBranch,
1327
+ project: config.project,
1328
+ targetDigest
1329
+ }))
1330
+ clearSandboxRemovalJournalRecord(journal);
1331
+ }
1332
+ }
1333
+ else {
1334
+ for (const journal of listSandboxRemovalJournals({
1335
+ branch: effectiveBranch,
1336
+ project: config.project,
1337
+ targetDigest
1338
+ }))
1339
+ clearSandboxRemovalJournalRecord(journal);
1340
+ }
1341
+ if (!options.quiet)
1342
+ p.outro(pc.green('Sandbox removed'));
1343
+ return auxiliaryReport;
1344
+ }
1345
+ finally {
1346
+ for (const lock of [...resourceLocks.values()].reverse())
1347
+ lock.release();
1348
+ }
1349
+ }
1350
+ async function rmPurge(config, tools, prompt = {}) {
1351
+ return withRepositoryMutationLock(config.repoRoot, () => rmPurgeCore(config, tools, prompt));
1352
+ }
1353
+ async function rmPurgeCore(config, tools, prompt = {}) {
1354
+ const engine = detectEngine(config);
1355
+ const confirm = prompt.confirm ?? p.confirm;
1356
+ const isCancel = prompt.isCancel ?? p.isCancel;
1357
+ p.intro(pc.cyan(`Removing all sandboxes for ${config.project}`));
1358
+ const worktrees = fs.existsSync(config.worktreeBase)
1359
+ ? fs.readdirSync(config.worktreeBase)
1360
+ .map((entry) => path.join(config.worktreeBase, entry))
1361
+ .filter((entry) => {
1362
+ try {
1363
+ return fs.statSync(entry).isDirectory();
1364
+ }
1365
+ catch {
1366
+ return false;
1367
+ }
1368
+ })
1369
+ : [];
1370
+ const inspections = inspectWorktrees(worktrees);
1371
+ const blockers = inspectionBlockers(inspections);
1372
+ if (blockers.length > 0) {
1373
+ throw new Error(`Refusing to purge because worktree preflight found blocker(s):\n${blockerMessage(blockers)}`);
1374
+ }
1375
+ const permits = cleanPermits(inspections);
1376
+ assertIntermediateCleanupPreflight(scanIntermediateCleanup(config.repoRoot, {
1377
+ preflight: true,
1378
+ controlBindingEvidence: projectSandboxControlBindingEvidence(config)
1379
+ }));
1380
+ const coordinatedContainers = await removeProjectControlRoots(config, engine, {
1381
+ retainRemovalJournal: true
1382
+ });
1383
+ const containers = runEngine(engine, 'docker', [
1384
+ 'ps',
1385
+ '-a',
1386
+ '--filter',
1387
+ `label=${sandboxLabel(config)}`,
1388
+ '--format',
1389
+ '{{.Names}}'
1390
+ ]);
1391
+ const uncoordinatedContainers = containers.split('\n').filter((name) => name && !coordinatedContainers.has(name));
1392
+ if (uncoordinatedContainers.length > 0) {
1393
+ const spinner = p.spinner();
1394
+ spinner.start('Stopping project sandbox containers...');
1395
+ for (const name of uncoordinatedContainers) {
1396
+ if (!runOkEngine(engine, 'docker', ['stop', name]))
1397
+ throw new Error(`Failed to stop sandbox container: ${name}`);
1398
+ if (!runOkEngine(engine, 'docker', ['rm', name]))
1399
+ throw new Error(`Failed to remove sandbox container: ${name}`);
1400
+ }
1401
+ const remaining = runEngine(engine, 'docker', [
1402
+ 'ps', '-a', '--filter', `label=${sandboxLabel(config)}`, '--format', '{{.Names}}'
1403
+ ]);
1404
+ const leftovers = remaining.split('\n').filter((name) => name && !coordinatedContainers.has(name));
1405
+ if (leftovers.length > 0)
1406
+ throw new Error(`Project sandbox container(s) still exist after removal: ${leftovers.join(', ')}`);
1407
+ spinner.stop(pc.green('Project sandbox containers removed'));
1408
+ }
1409
+ else {
1410
+ p.log.warn('No project sandbox containers found');
1411
+ }
1412
+ if (worktrees.length > 0) {
1413
+ const shouldRemoveWorktrees = await confirm({
1414
+ message: `Remove all worktrees in ${config.worktreeBase}?`,
1415
+ initialValue: true
1416
+ });
1417
+ if (!isCancel(shouldRemoveWorktrees) && shouldRemoveWorktrees) {
1418
+ for (const dir of worktrees) {
1419
+ const permit = permits.get(path.resolve(dir));
1420
+ if (!permit)
1421
+ throw new Error(`Missing worktree removal permit: ${dir}`);
1422
+ removeWorktreeDir(config.repoRoot, config.worktreeBase, dir, permit, {
1423
+ allowRegisteredPathFallback: engine === ENGINES.WSL2
1424
+ });
1425
+ assertRemoved(dir, 'Worktree');
1426
+ }
1427
+ runSafe('git', ['-C', config.repoRoot, 'worktree', 'prune']);
1428
+ const registered = new Set(runSafe('git', ['-C', config.repoRoot, 'worktree', 'list', '--porcelain'])
1429
+ .split('\n').filter((line) => line.startsWith('worktree ')).map((line) => path.resolve(line.slice(9))));
1430
+ const leftovers = worktrees.filter((dir) => registered.has(path.resolve(dir)));
1431
+ if (leftovers.length > 0)
1432
+ throw new Error(`Worktree(s) still registered after removal: ${leftovers.join(', ')}`);
1433
+ }
1434
+ }
1435
+ for (const dir of projectToolDirs(config, tools)) {
1436
+ if (fs.existsSync(dir)) {
1437
+ removeManagedDir(path.dirname(dir), dir);
1438
+ assertRemoved(dir, 'Tool state');
1439
+ p.log.success(`Removed tool state: ${dir}`);
1440
+ }
1441
+ }
1442
+ if (fs.existsSync(config.shellConfigBase) && fs.readdirSync(config.shellConfigBase).length > 0) {
1443
+ const shouldRemoveShellConfigs = await confirm({
1444
+ message: `Remove all shell config dirs in ${config.shellConfigBase}?`,
1445
+ initialValue: true
1446
+ });
1447
+ if (!isCancel(shouldRemoveShellConfigs) && shouldRemoveShellConfigs) {
1448
+ for (const entry of fs.readdirSync(config.shellConfigBase)) {
1449
+ const dir = path.join(config.shellConfigBase, entry);
1450
+ removeManagedDir(config.shellConfigBase, dir);
1451
+ assertRemoved(dir, 'Shell config');
1452
+ }
1453
+ p.log.success(`Project shell config dirs removed: ${config.shellConfigBase}`);
1454
+ }
1455
+ }
1456
+ if (fs.existsSync(config.shareBase) && fs.readdirSync(config.shareBase).length > 0) {
1457
+ const shouldRemoveAllShares = await confirm({
1458
+ message: `Remove all share dirs for project (${config.shareBase})?`,
1459
+ initialValue: true
1460
+ });
1461
+ if (!isCancel(shouldRemoveAllShares) && shouldRemoveAllShares) {
1462
+ removeManagedDir(path.dirname(config.shareBase), config.shareBase);
1463
+ assertRemoved(config.shareBase, 'Project share dir');
1464
+ p.log.success(`Project share dirs removed: ${config.shareBase}`);
1465
+ }
1466
+ }
1467
+ for (const [base, label] of [
1468
+ [config.workspaceViewBase, 'workspace views'],
1469
+ [config.controlBase, 'control channels']
1470
+ ]) {
1471
+ const projectDir = path.join(base, config.project);
1472
+ if (fs.existsSync(projectDir)) {
1473
+ removeManagedDir(base, projectDir);
1474
+ assertRemoved(projectDir, `Project ${label}`);
1475
+ p.log.success(`Removed project ${label}: ${projectDir}`);
1476
+ }
1477
+ }
1478
+ const shouldRemoveImage = await confirm({
1479
+ message: `Remove image ${config.imageName}?`,
1480
+ initialValue: false
1481
+ });
1482
+ if (!isCancel(shouldRemoveImage) && shouldRemoveImage) {
1483
+ runSafeEngine(engine, 'docker', ['rmi', config.imageName]);
1484
+ }
1485
+ pruneSandboxDanglingImages(config, engine);
1486
+ const cleanupPurgeAuxiliary = () => {
1487
+ const report = cleanupIntermediateUnderRemovalCoordinator(config.repoRoot, {
1488
+ controlBindingEvidence: projectSandboxControlBindingEvidence(config)
1489
+ });
1490
+ for (const line of formatIntermediateCleanupReport(report))
1491
+ p.log.message(line);
1492
+ if (!report.remaining.some((item) => item.taskId !== null)) {
1493
+ for (const journal of listSandboxRemovalJournals({ project: config.project })) {
1494
+ if (journal.phase === 'completed')
1495
+ clearSandboxRemovalJournalRecord(journal);
1496
+ }
1497
+ }
1498
+ };
1499
+ if (isManagedEngine(engine)) {
1500
+ if (engine === ENGINES.WSL2) {
1501
+ completePurgeRemovalJournals(config);
1502
+ cleanupPurgeAuxiliary();
1503
+ p.log.warn('Windows uses Docker Desktop with WSL2. Stop it from Docker Desktop or run "wsl --shutdown" manually.');
1504
+ p.outro(pc.green('All project sandboxes removed'));
1505
+ return;
1506
+ }
1507
+ const name = engineDisplayName(engine);
1508
+ const shouldStopVm = await confirm({
1509
+ message: `Stop ${name} VM?`,
1510
+ initialValue: false
1511
+ });
1512
+ if (!isCancel(shouldStopVm) && shouldStopVm) {
1513
+ stopManagedVm(config);
1514
+ }
1515
+ }
1516
+ completePurgeRemovalJournals(config);
1517
+ cleanupPurgeAuxiliary();
1518
+ p.outro(pc.green('All project sandboxes removed'));
1519
+ }
1520
+ async function rmUnbound(config, tools, options) {
1521
+ return withRepositoryMutationLock(config.repoRoot, () => rmUnboundCore(config, tools, options));
1522
+ }
1523
+ async function rmUnboundCore(config, tools, options) {
1524
+ const engine = detectEngine(config);
1525
+ const controlBindingEvidence = projectSandboxControlBindingEvidence(config);
1526
+ const { running, nonRunning } = fetchSandboxRows(engine, sandboxLabel(config), sandboxBranchLabel(config), { mode: sandboxWorkspaceModeLabel(config), taskId: sandboxTaskIdLabel(config) });
1527
+ const rows = [...running, ...nonRunning];
1528
+ p.intro(pc.cyan(`Removing sandboxes not bound to an active task for ${config.project}`));
1529
+ const intermediatePreview = scanIntermediateCleanup(config.repoRoot, { controlBindingEvidence });
1530
+ const candidates = [];
1531
+ const protectedCandidates = [];
1532
+ for (const row of rows) {
1533
+ if (!row.branch || !row.workspaceMode || row.workspaceMode === 'legacy-invalid') {
1534
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: container '${row.name}' has incomplete workspace identity`);
1535
+ }
1536
+ if (row.workspaceMode === 'task-bound') {
1537
+ if (!row.taskId) {
1538
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: container '${row.name}' has no task id`);
1539
+ }
1540
+ try {
1541
+ const cleanupTarget = resolveSandboxCleanupTarget(row.taskId, config.repoRoot, { allowProtected: true });
1542
+ if (cleanupTarget.branch !== row.branch
1543
+ || cleanupTarget.workspace.mode !== 'task-bound'
1544
+ || cleanupTarget.workspace.taskId !== row.taskId) {
1545
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: container '${row.name}' task identity conflicts with task.md`);
1546
+ }
1547
+ candidates.push({ row, cleanupTarget });
1548
+ }
1549
+ catch (error) {
1550
+ if (!isMissingTaskRecordError(error))
1551
+ throw error;
1552
+ protectedCandidates.push({
1553
+ row,
1554
+ branch: row.branch,
1555
+ identity: `task-bound:${row.taskId}`,
1556
+ reason: 'TASK_NOT_FOUND'
1557
+ });
1558
+ }
1559
+ continue;
1560
+ }
1561
+ candidates.push({
1562
+ row,
1563
+ cleanupTarget: {
1564
+ requestedRef: row.branch,
1565
+ branch: row.branch,
1566
+ workspace: { mode: 'branch-only' },
1567
+ taskState: 'branch-only'
1568
+ }
1569
+ });
1570
+ }
1571
+ const branchIdentities = new Map();
1572
+ const groupedCandidates = new Map();
1573
+ for (const candidate of protectedCandidates) {
1574
+ const existingIdentity = branchIdentities.get(candidate.branch);
1575
+ if (existingIdentity && existingIdentity !== candidate.identity) {
1576
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: branch '${candidate.branch}' has conflicting workspace identities`);
1577
+ }
1578
+ branchIdentities.set(candidate.branch, candidate.identity);
1579
+ }
1580
+ for (const candidate of candidates) {
1581
+ const identity = candidate.cleanupTarget.workspace.mode === 'task-bound'
1582
+ ? `task-bound:${candidate.cleanupTarget.workspace.taskId}`
1583
+ : 'branch-only';
1584
+ const existingIdentity = branchIdentities.get(candidate.cleanupTarget.branch);
1585
+ if (existingIdentity && existingIdentity !== identity) {
1586
+ throw new Error(`SANDBOX_CLEANUP_BATCH_PREFLIGHT_FAILED: branch '${candidate.cleanupTarget.branch}' has conflicting workspace identities`);
1587
+ }
1588
+ branchIdentities.set(candidate.cleanupTarget.branch, identity);
1589
+ const groupKey = `${candidate.cleanupTarget.branch}\0${identity}`;
1590
+ const group = groupedCandidates.get(groupKey) ?? [];
1591
+ group.push(candidate);
1592
+ groupedCandidates.set(groupKey, group);
1593
+ }
1594
+ const groups = [...groupedCandidates.values()].map((groupCandidates) => {
1595
+ const cleanupTarget = groupCandidates[0].cleanupTarget;
1596
+ const target = resolveRmTarget(config, tools, cleanupTarget, {
1597
+ discoveredContainers: groupCandidates.map(({ row }) => row.name)
1598
+ });
1599
+ preflightRmTarget(config, target);
1600
+ return { candidates: groupCandidates, cleanupTarget, target };
1601
+ });
1602
+ const protectedTargets = protectedCandidates.map(({ row, branch }) => {
1603
+ const target = resolveRmTarget(config, tools, {
1604
+ requestedRef: branch,
1605
+ branch,
1606
+ workspace: { mode: 'task-bound', taskId: row.taskId },
1607
+ taskState: 'completed'
1608
+ }, { discoveredContainers: [row.name] });
1609
+ return { branch, managedPathCandidates: target.managedPathCandidates ?? [] };
1610
+ });
1611
+ assertCleanupGroupPathsDoNotOverlap(groups, protectedTargets);
1612
+ const removableGroups = groups.filter(({ cleanupTarget }) => cleanupTarget.taskState === 'completed' || cleanupTarget.taskState === 'branch-only');
1613
+ const rowTaskIds = new Set(groups.flatMap(({ cleanupTarget }) => (cleanupTarget.workspace.mode === 'task-bound' ? [cleanupTarget.workspace.taskId] : [])));
1614
+ const cleanupOnlyTaskIds = new Set(intermediatePreview.items
1615
+ .filter((candidate) => candidate.disposition === 'planned' && candidate.taskId !== null && !rowTaskIds.has(candidate.taskId))
1616
+ .map((candidate) => candidate.taskId));
1617
+ const removable = removableGroups.flatMap(({ candidates: groupCandidates }) => groupCandidates);
1618
+ for (const { candidates: groupCandidates, cleanupTarget } of groups.filter(({ cleanupTarget }) => cleanupTarget.taskState !== 'completed' && cleanupTarget.taskState !== 'branch-only')) {
1619
+ for (const { row } of groupCandidates) {
1620
+ p.log.message(`Skipped protected sandbox ${row.name} (${cleanupTarget.taskState})`);
1621
+ }
1622
+ }
1623
+ for (const { row, reason } of protectedCandidates) {
1624
+ p.log.message(`Skipped protected sandbox ${row.name} (${reason})`);
1625
+ }
1626
+ for (const line of formatIntermediateCleanupReport(intermediatePreview))
1627
+ p.log.message(line);
1628
+ const hasAuxiliaryWork = intermediatePreview.items.some((candidate) => candidate.disposition === 'planned');
1629
+ if (removableGroups.length === 0 && !hasAuxiliaryWork) {
1630
+ p.outro('No removable sandboxes: every container is bound to a protected task (or none exist)');
1631
+ return;
1632
+ }
1633
+ const inspections = inspectWorktrees(removableGroups.flatMap(({ target }) => target.existingWorktrees));
1634
+ assertWorktreeBranchesMatchGroups(removableGroups, inspections);
1635
+ const blockers = inspectionBlockers(inspections);
1636
+ const permits = cleanPermits(inspections);
1637
+ for (const { row } of removable) {
1638
+ p.log.message(`${row.name} ${row.branch}`);
1639
+ }
1640
+ if (blockers.length > 0)
1641
+ p.log.error(blockerMessage(blockers));
1642
+ if (options.dryRun) {
1643
+ p.outro(`Dry run: ${removable.length} sandbox(es) inspected, nothing deleted`);
1644
+ return;
1645
+ }
1646
+ if (blockers.length > 0) {
1647
+ throw new Error(`Refusing batch removal because worktree preflight found blocker(s):\n${blockerMessage(blockers)}`);
1648
+ }
1649
+ if (!options.assumeYes && !process.stdin.isTTY) {
1650
+ throw new Error('Refusing to remove sandboxes without confirmation in a non-interactive shell; pass --yes to proceed.');
1651
+ }
1652
+ const failures = [];
1653
+ const actualReports = [];
1654
+ let failedRows = 0;
1655
+ for (const group of removableGroups) {
1656
+ try {
1657
+ const report = await runRmOneUnderRepositoryLock(config, tools, group.cleanupTarget.branch, {
1658
+ assumeYes: options.assumeYes,
1659
+ quiet: true,
1660
+ target: group.target,
1661
+ cleanupTarget: group.cleanupTarget,
1662
+ permits,
1663
+ allowDirtyDiscard: false
1664
+ });
1665
+ if (report)
1666
+ actualReports.push(report);
1667
+ }
1668
+ catch (error) {
1669
+ failedRows += group.candidates.length;
1670
+ failures.push({ branch: group.cleanupTarget.branch, message: error instanceof Error ? error.message : String(error) });
1671
+ const taskId = group.cleanupTarget.workspace.mode === 'task-bound'
1672
+ ? group.cleanupTarget.workspace.taskId
1673
+ : null;
1674
+ if (taskId) {
1675
+ const failedReport = cleanupIntermediateUnderRemovalCoordinator(config.repoRoot, {
1676
+ dryRun: true,
1677
+ taskIds: [taskId],
1678
+ controlBindingEvidence
1679
+ });
1680
+ actualReports.push(protectIntermediateCleanupReport(failedReport, 'SANDBOX_ROW_REMOVAL_FAILED'));
1681
+ }
1682
+ }
1683
+ }
1684
+ const auxiliaryTaskIds = [...cleanupOnlyTaskIds].sort();
1685
+ const finalControlBindingEvidence = projectSandboxControlBindingEvidence(config);
1686
+ const cleanupOnlyReport = cleanupIntermediateUnderRemovalCoordinator(config.repoRoot, {
1687
+ taskIds: auxiliaryTaskIds,
1688
+ controlBindingEvidence: finalControlBindingEvidence
1689
+ });
1690
+ actualReports.push(cleanupOnlyReport);
1691
+ const intermediateReport = mergeIntermediateCleanupReports(actualReports);
1692
+ for (const line of formatIntermediateCleanupReport(intermediateReport))
1693
+ p.log.message(line);
1694
+ if (cleanupOnlyReport.remaining.every((item) => item.taskId === null)) {
1695
+ for (const taskId of auxiliaryTaskIds) {
1696
+ let branch;
1697
+ try {
1698
+ branch = resolveSandboxCleanupTarget(taskId, config.repoRoot, { allowProtected: true }).branch;
1699
+ }
1700
+ catch {
1701
+ continue;
1702
+ }
1703
+ for (const journal of listSandboxRemovalJournals({ project: config.project, branch })) {
1704
+ clearSandboxRemovalJournalRecord(journal);
1705
+ }
1706
+ }
1707
+ }
1708
+ if (failures.length > 0) {
1709
+ for (const failure of failures) {
1710
+ p.log.error(`Failed to remove '${failure.branch}': ${failure.message}`);
1711
+ }
1712
+ throw new Error(`Removed ${removable.length - failedRows}/${removable.length} sandbox(es); ${failures.length} failed`);
1713
+ }
1714
+ p.outro(pc.green(`Removed ${removable.length} sandbox(es)`));
1715
+ }
1716
+ export { authorizeWorktrees, rmOne, rmPurge, rmUnbound };
1717
+ //# sourceMappingURL=removal.js.map