@oyasmi/pipiclaw 0.9.5 → 0.9.6-beta.2

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 (345) hide show
  1. package/README.en.md +300 -142
  2. package/README.md +295 -140
  3. package/dist/agent/builtin-commands.d.ts +1 -1
  4. package/dist/agent/builtin-commands.js +1 -1
  5. package/dist/agent/channel-runner.d.ts +4 -3
  6. package/dist/agent/channel-runner.js +17 -28
  7. package/dist/agent/maintenance-context.js +2 -2
  8. package/dist/agent/prompt/builder.d.ts +1 -1
  9. package/dist/agent/prompt/builder.js +1 -1
  10. package/dist/agent/prompt/extension.d.ts +1 -1
  11. package/dist/agent/prompt/extension.js +1 -1
  12. package/dist/agent/prompt/manifest.d.ts +6 -1
  13. package/dist/agent/prompt/manifest.js +12 -5
  14. package/dist/agent/prompt/resources.d.ts +0 -3
  15. package/dist/agent/prompt/resources.js +0 -6
  16. package/dist/agent/prompt/sections.d.ts +2 -2
  17. package/dist/agent/prompt/sections.js +36 -26
  18. package/dist/agent/prompt/types.d.ts +3 -2
  19. package/dist/agent/runner-factory.js +1 -1
  20. package/dist/agent/session/command-extension.js +3 -1
  21. package/dist/agent/session/compaction-summary.js +3 -6
  22. package/dist/agent/session/compaction.d.ts +2 -0
  23. package/dist/agent/session/compaction.js +22 -14
  24. package/dist/agent/session/event-guards.d.ts +2 -1
  25. package/dist/agent/session/event-guards.js +6 -0
  26. package/dist/agent/session/model-selection.d.ts +2 -1
  27. package/dist/agent/session/model-selection.js +5 -5
  28. package/dist/agent/session/session-events.js +31 -4
  29. package/dist/agent/session/session-host.d.ts +5 -3
  30. package/dist/agent/session/session-host.js +20 -16
  31. package/dist/agent/status-render.js +3 -0
  32. package/dist/agent/stop-watchdog.js +5 -1
  33. package/dist/agent/turn/task-digest.d.ts +2 -5
  34. package/dist/agent/turn/task-digest.js +25 -45
  35. package/dist/agent/turn/turn-context.js +4 -6
  36. package/dist/agent/turn/turn-error.d.ts +1 -1
  37. package/dist/agent/turn/turn-error.js +9 -0
  38. package/dist/agent/turn/turn-pipeline.d.ts +10 -5
  39. package/dist/agent/turn/turn-pipeline.js +36 -7
  40. package/dist/agent/turn/turn-prompt.d.ts +2 -0
  41. package/dist/agent/turn/turn-prompt.js +2 -1
  42. package/dist/agent/turn/turn-recovery.js +4 -1
  43. package/dist/agent/turn/turn-state.d.ts +2 -0
  44. package/dist/agent/turn/turn-state.js +2 -1
  45. package/dist/agent/types.d.ts +23 -3
  46. package/dist/agent/types.js +2 -0
  47. package/dist/app/auth-command.d.ts +25 -0
  48. package/dist/app/auth-command.js +200 -67
  49. package/dist/app/home.d.ts +7 -8
  50. package/dist/app/home.js +143 -56
  51. package/dist/channel/attachments.d.ts +4 -0
  52. package/dist/channel/attachments.js +4 -0
  53. package/dist/channel/channel-context.d.ts +6 -0
  54. package/dist/channel/config.d.ts +3 -0
  55. package/dist/channel/config.js +11 -5
  56. package/dist/channel/store.d.ts +1 -1
  57. package/dist/commands/catalog.js +42 -10
  58. package/dist/commands/router.js +5 -1
  59. package/dist/desk/commands.d.ts +44 -5
  60. package/dist/desk/commands.js +162 -28
  61. package/dist/desk/paths.d.ts +6 -0
  62. package/dist/desk/paths.js +21 -1
  63. package/dist/desk/registry.d.ts +17 -2
  64. package/dist/desk/registry.js +122 -12
  65. package/dist/desk/types.d.ts +83 -1
  66. package/dist/dingtalk/bot.d.ts +1 -1
  67. package/dist/dingtalk/bot.js +4 -3
  68. package/dist/dingtalk/config.js +10 -10
  69. package/dist/dingtalk/delivery.js +15 -8
  70. package/dist/dingtalk/inbound-media.d.ts +36 -14
  71. package/dist/dingtalk/inbound-media.js +71 -12
  72. package/dist/dingtalk/inbound.d.ts +9 -2
  73. package/dist/dingtalk/inbound.js +17 -2
  74. package/dist/dingtalk/media.d.ts +4 -10
  75. package/dist/dingtalk/media.js +58 -32
  76. package/dist/events/commands.d.ts +2 -0
  77. package/dist/events/commands.js +13 -8
  78. package/dist/events/history.d.ts +9 -0
  79. package/dist/events/history.js +66 -0
  80. package/dist/events/parse.js +7 -3
  81. package/dist/events/types.d.ts +3 -0
  82. package/dist/events/watcher.d.ts +4 -8
  83. package/dist/events/watcher.js +53 -58
  84. package/dist/jobs/kill.d.ts +23 -0
  85. package/dist/jobs/kill.js +65 -0
  86. package/dist/jobs/manager.d.ts +19 -18
  87. package/dist/jobs/manager.js +36 -103
  88. package/dist/main.js +15 -3
  89. package/dist/memory/boundary-work.d.ts +2 -1
  90. package/dist/memory/boundary-work.js +1 -1
  91. package/dist/memory/lifecycle.d.ts +2 -1
  92. package/dist/memory/lifecycle.js +2 -2
  93. package/dist/memory/reflect-job.d.ts +2 -1
  94. package/dist/memory/reflect-job.js +1 -1
  95. package/dist/memory/reflect.d.ts +2 -1
  96. package/dist/memory/reflect.js +25 -4
  97. package/dist/memory/scheduler.d.ts +2 -1
  98. package/dist/memory/scheduler.js +1 -1
  99. package/dist/memory/session-corpus.d.ts +1 -1
  100. package/dist/memory/session-corpus.js +76 -1
  101. package/dist/memory/session-search.d.ts +2 -1
  102. package/dist/memory/session-search.js +14 -12
  103. package/dist/memory/sidecar-worker.d.ts +2 -1
  104. package/dist/memory/sidecar-worker.js +2 -4
  105. package/dist/memory/store.d.ts +2 -0
  106. package/dist/memory/store.js +19 -9
  107. package/dist/models/credential-work.d.ts +7 -0
  108. package/dist/models/credential-work.js +36 -0
  109. package/dist/models/login-ui.js +4 -4
  110. package/dist/models/provider-login.js +7 -6
  111. package/dist/models/requests.d.ts +8 -0
  112. package/dist/models/requests.js +69 -0
  113. package/dist/models/runtime.d.ts +3 -1
  114. package/dist/models/runtime.js +9 -2
  115. package/dist/playbooks/agent-delegation.md +20 -45
  116. package/dist/playbooks/background-jobs.md +1 -1
  117. package/dist/playbooks/catalog.js +1 -1
  118. package/dist/playbooks/delegation-inline.md +25 -0
  119. package/dist/playbooks/delegation-recovery.md +28 -0
  120. package/dist/playbooks/event-scheduling.md +18 -37
  121. package/dist/playbooks/event-sensors.md +26 -0
  122. package/dist/playbooks/event-task-template.md +22 -0
  123. package/dist/playbooks/learning-and-skills.md +26 -0
  124. package/dist/playbooks/memory-operations.md +36 -0
  125. package/dist/playbooks/outbound-media.md +2 -2
  126. package/dist/playbooks/runtime-files.md +29 -0
  127. package/dist/playbooks/runtime-operations.md +25 -0
  128. package/dist/playbooks/runtime-orientation.md +18 -53
  129. package/dist/playbooks/task-lead.md +22 -68
  130. package/dist/playbooks/task-manage.md +38 -0
  131. package/dist/playbooks/task-recovery.md +24 -0
  132. package/dist/playbooks/task-verify.md +22 -0
  133. package/dist/runtime/bootstrap.d.ts +10 -0
  134. package/dist/runtime/bootstrap.js +93 -29
  135. package/dist/runtime/daemon-lock.js +3 -3
  136. package/dist/runtime/desk-runtime.d.ts +40 -7
  137. package/dist/runtime/desk-runtime.js +330 -44
  138. package/dist/runtime/durable-dispatch.d.ts +14 -2
  139. package/dist/runtime/durable-dispatch.js +207 -65
  140. package/dist/runtime/ingress-busy.js +17 -8
  141. package/dist/runtime/ingress-commands.js +24 -4
  142. package/dist/runtime/ingress-deps.d.ts +4 -1
  143. package/dist/runtime/ingress.js +6 -1
  144. package/dist/runtime/request-execution.js +7 -6
  145. package/dist/runtime/shutdown.d.ts +4 -1
  146. package/dist/runtime/shutdown.js +88 -35
  147. package/dist/runtime/task-close.d.ts +1 -1
  148. package/dist/runtime/task-close.js +6 -3
  149. package/dist/runtime/task-control.d.ts +2 -3
  150. package/dist/runtime/task-control.js +38 -11
  151. package/dist/runtime/task-input.js +1 -1
  152. package/dist/runtime/task-lane-types.d.ts +12 -2
  153. package/dist/runtime/task-lane-types.js +9 -0
  154. package/dist/runtime/task-lane.d.ts +2 -0
  155. package/dist/runtime/task-lane.js +38 -20
  156. package/dist/runtime/task-step.d.ts +3 -3
  157. package/dist/runtime/task-step.js +34 -16
  158. package/dist/runtime/transports.js +6 -5
  159. package/dist/runtime/turn-run.js +103 -66
  160. package/dist/security/command-guard.d.ts +1 -1
  161. package/dist/security/command-guard.js +259 -314
  162. package/dist/security/path-guard.js +48 -7
  163. package/dist/security/shell-parse.d.ts +10 -0
  164. package/dist/security/shell-parse.js +224 -0
  165. package/dist/security/types.d.ts +2 -0
  166. package/dist/subagents/commands.d.ts +1 -1
  167. package/dist/subagents/commands.js +14 -5
  168. package/dist/subagents/completion-wake.js +6 -0
  169. package/dist/subagents/detached-discovery.d.ts +1 -1
  170. package/dist/subagents/discovery.d.ts +18 -199
  171. package/dist/subagents/discovery.js +35 -289
  172. package/dist/subagents/dispatch.d.ts +1 -2
  173. package/dist/subagents/dispatch.js +50 -29
  174. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  175. package/dist/subagents/external/antigravity-cli.js +517 -0
  176. package/dist/subagents/external/claude-code.js +8 -17
  177. package/dist/subagents/external/codex-cli.js +8 -18
  178. package/dist/subagents/external/cursor-cli.js +34 -31
  179. package/dist/subagents/external/dispatch.d.ts +21 -7
  180. package/dist/subagents/external/dispatch.js +146 -12
  181. package/dist/subagents/external/exec.js +3 -0
  182. package/dist/subagents/external/harness.d.ts +57 -33
  183. package/dist/subagents/external/harness.js +69 -40
  184. package/dist/subagents/external/reconciliation.js +1 -0
  185. package/dist/subagents/external/registry.js +4 -1
  186. package/dist/subagents/external/role-warnings.d.ts +4 -13
  187. package/dist/subagents/external/role-warnings.js +4 -28
  188. package/dist/subagents/external/run.d.ts +1 -2
  189. package/dist/subagents/external/run.js +16 -26
  190. package/dist/subagents/external/settlement.d.ts +2 -0
  191. package/dist/subagents/external/settlement.js +13 -3
  192. package/dist/subagents/format.d.ts +1 -1
  193. package/dist/subagents/format.js +1 -1
  194. package/dist/subagents/internal/outcome.d.ts +1 -2
  195. package/dist/subagents/internal/outcome.js +19 -12
  196. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  197. package/dist/subagents/internal/provider-retry.js +2 -4
  198. package/dist/subagents/internal/run.d.ts +2 -3
  199. package/dist/subagents/internal/run.js +27 -4
  200. package/dist/subagents/internal/state.d.ts +2 -5
  201. package/dist/subagents/internal/state.js +1 -2
  202. package/dist/subagents/internal/worker.d.ts +1 -2
  203. package/dist/subagents/internal/worker.js +20 -10
  204. package/dist/subagents/resolve.d.ts +56 -0
  205. package/dist/subagents/resolve.js +202 -0
  206. package/dist/subagents/result.d.ts +6 -4
  207. package/dist/subagents/result.js +39 -6
  208. package/dist/subagents/run-record.d.ts +54 -2
  209. package/dist/subagents/run-record.js +7 -0
  210. package/dist/subagents/runs.d.ts +6 -31
  211. package/dist/subagents/runs.js +26 -31
  212. package/dist/subagents/task-envelope.d.ts +1 -2
  213. package/dist/subagents/task-envelope.js +13 -4
  214. package/dist/subagents/task-settlement.js +1 -0
  215. package/dist/subagents/types.d.ts +105 -6
  216. package/dist/subagents/types.js +16 -1
  217. package/dist/subagents/workspace-lease.d.ts +41 -24
  218. package/dist/subagents/workspace-lease.js +159 -24
  219. package/dist/subagents/worktree.d.ts +52 -0
  220. package/dist/subagents/worktree.js +363 -0
  221. package/dist/tasks/archive.js +4 -0
  222. package/dist/tasks/brief.d.ts +5 -1
  223. package/dist/tasks/brief.js +19 -5
  224. package/dist/tasks/commands.d.ts +6 -1
  225. package/dist/tasks/commands.js +32 -7
  226. package/dist/tasks/control.d.ts +11 -0
  227. package/dist/tasks/delivery.d.ts +2 -0
  228. package/dist/tasks/delivery.js +141 -21
  229. package/dist/tasks/loop-log.d.ts +12 -0
  230. package/dist/tasks/loop-log.js +10 -1
  231. package/dist/tasks/receipts.d.ts +7 -3
  232. package/dist/tasks/receipts.js +34 -5
  233. package/dist/tools/bash.d.ts +3 -0
  234. package/dist/tools/bash.js +29 -15
  235. package/dist/tools/contract/presentation.js +7 -5
  236. package/dist/tools/edit-diff.d.ts +11 -0
  237. package/dist/tools/edit-diff.js +148 -0
  238. package/dist/tools/edit-match.d.ts +18 -0
  239. package/dist/tools/edit-match.js +242 -0
  240. package/dist/tools/edit.d.ts +10 -2
  241. package/dist/tools/edit.js +91 -361
  242. package/dist/tools/event-manage.d.ts +2 -1
  243. package/dist/tools/event-manage.js +46 -39
  244. package/dist/tools/file-observations.d.ts +9 -0
  245. package/dist/tools/file-observations.js +50 -0
  246. package/dist/tools/glob-match.d.ts +3 -1
  247. package/dist/tools/glob-match.js +40 -17
  248. package/dist/tools/glob.d.ts +1 -0
  249. package/dist/tools/glob.js +39 -19
  250. package/dist/tools/grep-command.d.ts +13 -0
  251. package/dist/tools/grep-command.js +77 -0
  252. package/dist/tools/grep.js +96 -201
  253. package/dist/tools/index.d.ts +6 -2
  254. package/dist/tools/index.js +9 -4
  255. package/dist/tools/job.js +12 -11
  256. package/dist/tools/read.d.ts +2 -0
  257. package/dist/tools/read.js +10 -2
  258. package/dist/tools/registry.d.ts +16 -11
  259. package/dist/tools/registry.js +32 -12
  260. package/dist/tools/send-media.js +9 -5
  261. package/dist/tools/session-search.d.ts +2 -1
  262. package/dist/tools/session-search.js +15 -5
  263. package/dist/tools/skill.js +13 -12
  264. package/dist/tools/subagent-manage.d.ts +1 -1
  265. package/dist/tools/subagent-manage.js +25 -152
  266. package/dist/tools/subagent.d.ts +24 -2
  267. package/dist/tools/subagent.js +24 -18
  268. package/dist/tools/task-manage/control-tools.js +1 -1
  269. package/dist/tools/task-manage/factory.d.ts +2 -2
  270. package/dist/tools/task-manage/factory.js +40 -4
  271. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  272. package/dist/tools/task-manage/lifecycle.js +56 -13
  273. package/dist/tools/task-manage/schema.d.ts +4 -1
  274. package/dist/tools/task-manage/schema.js +4 -1
  275. package/dist/tools/task-manage/shared.d.ts +1 -1
  276. package/dist/tools/task-manage/types.d.ts +5 -1
  277. package/dist/tools/write-content.d.ts +7 -1
  278. package/dist/tools/write-content.js +18 -6
  279. package/dist/tools/write.d.ts +3 -0
  280. package/dist/tools/write.js +6 -2
  281. package/dist/tui/cli.d.ts +6 -6
  282. package/dist/tui/cli.js +120 -28
  283. package/dist/tui/client.d.ts +7 -0
  284. package/dist/tui/client.js +67 -16
  285. package/dist/tui/frontend.d.ts +2 -0
  286. package/dist/tui/pitui-frontend.d.ts +4 -0
  287. package/dist/tui/pitui-frontend.js +27 -0
  288. package/dist/tui/render.d.ts +1 -0
  289. package/dist/tui/render.js +5 -0
  290. package/dist/tui/session.js +6 -0
  291. package/dist/usage/ledger.d.ts +1 -1
  292. package/dist/usage/render.js +1 -1
  293. package/dist/web/client.d.ts +1 -0
  294. package/dist/web/client.js +11 -0
  295. package/dist/web/fetch.js +6 -3
  296. package/dist/webapi/auth.d.ts +0 -3
  297. package/dist/webapi/auth.js +3 -7
  298. package/dist/webapi/config.js +17 -14
  299. package/dist/webapi/key-command.js +41 -41
  300. package/dist/webapi/response-state.d.ts +7 -1
  301. package/dist/webapi/response-state.js +166 -3
  302. package/dist/webapi/routes/websocket.js +24 -1
  303. package/dist/webapi/server.d.ts +3 -1
  304. package/dist/webapi/server.js +32 -1
  305. package/dist/webapi/service.js +8 -0
  306. package/dist/webapi/transport.d.ts +2 -0
  307. package/dist/webapi/transport.js +11 -1
  308. package/examples/sub-agents/README.md +43 -75
  309. package/examples/sub-agents/agy-main.md +21 -0
  310. package/examples/sub-agents/claude-high.md +21 -0
  311. package/examples/sub-agents/claude-main.md +21 -0
  312. package/examples/sub-agents/codex-flash.md +21 -0
  313. package/examples/sub-agents/codex-high.md +21 -0
  314. package/examples/sub-agents/codex-main.md +21 -0
  315. package/examples/sub-agents/codex-review.md +20 -0
  316. package/examples/sub-agents/cursor-high.md +20 -0
  317. package/examples/sub-agents/cursor-main.md +20 -0
  318. package/examples/sub-agents/glm-flash.md +21 -0
  319. package/examples/sub-agents/glm-high.md +21 -0
  320. package/examples/sub-agents/pi-scout.md +20 -0
  321. package/package.json +11 -12
  322. package/dist/agent/session/request-tools.d.ts +0 -3
  323. package/dist/agent/session/request-tools.js +0 -20
  324. package/dist/models/api-keys.d.ts +0 -11
  325. package/dist/models/api-keys.js +0 -22
  326. package/dist/playbooks/memory-and-learning.md +0 -55
  327. package/examples/sub-agents/agents/claude-high.md +0 -23
  328. package/examples/sub-agents/agents/claude-main.md +0 -23
  329. package/examples/sub-agents/agents/codex-flash.md +0 -23
  330. package/examples/sub-agents/agents/codex-high.md +0 -23
  331. package/examples/sub-agents/agents/codex-main.md +0 -23
  332. package/examples/sub-agents/agents/codex-review.md +0 -23
  333. package/examples/sub-agents/agents/cursor-high.md +0 -22
  334. package/examples/sub-agents/agents/cursor-main.md +0 -22
  335. package/examples/sub-agents/agents/glm-flash.md +0 -23
  336. package/examples/sub-agents/agents/glm-high.md +0 -23
  337. package/examples/sub-agents/agents/scout.md +0 -30
  338. package/examples/sub-agents/roles/builder-hard.md +0 -34
  339. package/examples/sub-agents/roles/builder.md +0 -34
  340. package/examples/sub-agents/roles/explorer.md +0 -39
  341. package/examples/sub-agents/roles/git-committer.md +0 -43
  342. package/examples/sub-agents/roles/planner.md +0 -33
  343. package/examples/sub-agents/roles/reviewer.md +0 -33
  344. package/examples/sub-agents/roles/verifier.md +0 -35
  345. package/examples/sub-agents/roles/worker.md +0 -34
@@ -1,59 +1,194 @@
1
- import { realpathSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { basename, dirname, normalize, resolve } from "node:path";
4
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
2
5
  import { withTrailingSlash } from "../shared/text-utils.js";
3
6
  const leases = new Map();
7
+ const cleanups = new Map();
8
+ const DESK_CONTROL_SUBDIRS = [
9
+ "tasks",
10
+ "subagent-artifacts",
11
+ "memory",
12
+ "journal",
13
+ "events",
14
+ "conversations",
15
+ "inbox",
16
+ "logs",
17
+ ".memory-work",
18
+ ".locks",
19
+ ];
20
+ const DESK_CONTROL_FILES = ["desk.json", "MEMORY.md"];
21
+ function holderMode(holder) {
22
+ return holder.mode ?? "write";
23
+ }
24
+ function crossesIsolatedBoundary(parent, child) {
25
+ const rel = child.slice(withTrailingSlash(parent).length);
26
+ return (rel.startsWith("subagent-artifacts/") ||
27
+ rel.includes("/subagent-artifacts/") ||
28
+ rel.startsWith(".git/pipiclaw-worktrees/") ||
29
+ rel.includes("/.git/pipiclaw-worktrees/") ||
30
+ rel.startsWith("pipiclaw-worktrees/") ||
31
+ rel.includes("/pipiclaw-worktrees/"));
32
+ }
4
33
  function pathsConflict(a, b) {
5
- return (a === b ||
6
- withTrailingSlash(a).startsWith(withTrailingSlash(b)) ||
7
- withTrailingSlash(b).startsWith(withTrailingSlash(a)));
34
+ if (a === b)
35
+ return true;
36
+ const aSlash = withTrailingSlash(a);
37
+ const bSlash = withTrailingSlash(b);
38
+ if (b.startsWith(aSlash))
39
+ return !crossesIsolatedBoundary(a, b);
40
+ if (a.startsWith(bSlash))
41
+ return !crossesIsolatedBoundary(b, a);
42
+ return false;
8
43
  }
9
- /** The stable lease key for a working directory: its realpath, so a symlink or `..` cannot dodge a conflict. */
10
- export function workspaceLeaseKey(workingDirectory) {
44
+ /**
45
+ * Resolve a directory or file path (including not-yet-created files for `write`) through symlinks
46
+ * so an alias or `..` segment cannot bypass an active checkout lease.
47
+ */
48
+ export function workspaceLeaseKey(targetPath) {
49
+ const normalized = normalize(targetPath);
11
50
  try {
12
- return realpathSync(workingDirectory);
51
+ return realpathSync(normalized);
13
52
  }
14
53
  catch {
15
- return workingDirectory;
54
+ const missingSegments = [];
55
+ let current = normalized;
56
+ while (!existsSync(current)) {
57
+ missingSegments.unshift(basename(current));
58
+ const parent = dirname(current);
59
+ if (parent === current)
60
+ return normalized;
61
+ current = parent;
62
+ }
63
+ try {
64
+ return resolve(realpathSync(current), ...missingSegments);
65
+ }
66
+ catch {
67
+ return normalized;
68
+ }
69
+ }
70
+ }
71
+ function isDeskControlPlanePath(resolvedTarget, deskDir) {
72
+ if (!deskDir)
73
+ return false;
74
+ const canonicalDesk = workspaceLeaseKey(deskDir);
75
+ for (const file of DESK_CONTROL_FILES) {
76
+ if (resolvedTarget === resolve(canonicalDesk, file))
77
+ return true;
78
+ }
79
+ for (const sub of DESK_CONTROL_SUBDIRS) {
80
+ const subRoot = resolve(canonicalDesk, sub);
81
+ if (resolvedTarget === subRoot || resolvedTarget.startsWith(withTrailingSlash(subRoot))) {
82
+ return true;
83
+ }
16
84
  }
85
+ return false;
17
86
  }
18
- function findConflict(leaseKey) {
19
- for (const [key, holder] of leases) {
87
+ function findConflict(leaseKey, requestedMode, excludeRunId) {
88
+ for (const [key, holder] of cleanups) {
20
89
  if (pathsConflict(key, leaseKey))
21
90
  return holder;
22
91
  }
92
+ for (const [key, holders] of leases) {
93
+ if (!pathsConflict(key, leaseKey))
94
+ continue;
95
+ for (const holder of holders.values()) {
96
+ if (excludeRunId && holder.runId === excludeRunId)
97
+ continue;
98
+ const mode = holderMode(holder);
99
+ if (requestedMode === "cleanup" ||
100
+ (requestedMode !== "use" && mode !== "use" && (requestedMode === "write" || mode === "write"))) {
101
+ return holder;
102
+ }
103
+ }
104
+ }
23
105
  return undefined;
24
106
  }
107
+ /**
108
+ * Atomically exclude every other directory user, then hold that exclusion across inspection and
109
+ * removal. A finished worker may clean up under its own still-held lease; never release that lease
110
+ * here — settlement remains the run manager's responsibility.
111
+ */
112
+ export async function withWorkspaceCleanupLease(workingDirectory, ownerRunId, cleanup) {
113
+ const key = workspaceLeaseKey(workingDirectory);
114
+ if (findConflict(key, "cleanup", ownerRunId))
115
+ return undefined;
116
+ cleanups.set(key, { runId: `cleanup-${randomUUID()}`, channelId: "runtime", workingDirectory, mode: "write" });
117
+ try {
118
+ return await cleanup();
119
+ }
120
+ finally {
121
+ cleanups.delete(key);
122
+ }
123
+ }
25
124
  export function acquireWorkspaceLease(holder) {
26
125
  const leaseKey = workspaceLeaseKey(holder.workingDirectory);
27
- const conflict = findConflict(leaseKey);
126
+ const mode = holderMode(holder);
127
+ const conflict = findConflict(leaseKey, mode, holder.runId);
28
128
  if (conflict) {
29
129
  return { ok: false, leaseKey, heldBy: conflict };
30
130
  }
31
- leases.set(leaseKey, holder);
131
+ let holders = leases.get(leaseKey);
132
+ if (!holders) {
133
+ holders = new Map();
134
+ leases.set(leaseKey, holders);
135
+ }
136
+ holders.set(holder.runId, { ...holder, mode });
32
137
  return { ok: true, leaseKey };
33
138
  }
34
139
  /**
35
- * Spec 042 D5: release only the caller's own lease. A blind `leases.delete(key)` let a restore
36
- * whose lease-rebuild failed (a real path — `realpath` can drift under a symlink swap) still
37
- * `settle()` and delete the *new* holder's lease for the same key, and a caller could otherwise
38
- * double-release harmlessly-in-appearance but incorrectly-in-general. `runId` must match the
39
- * current holder for the delete to happen; anything else (already released, held by someone else)
40
- * is a no-op rather than an assertion failure — callers already treat "did I ever hold it" as
41
- * something they cannot always know for certain (e.g. a settle() racing a lease rebuild).
140
+ * Spec 042 D5: release only the caller's own lease (`runId` must match). Shared read leases remove
141
+ * only their own entry and delete `leaseKey` once the last holder settles.
42
142
  */
43
143
  export function releaseWorkspaceLease(leaseKey, runId) {
44
144
  if (!leaseKey)
45
145
  return;
46
- const holder = leases.get(leaseKey);
47
- if (holder && holder.runId === runId) {
146
+ const holders = leases.get(leaseKey);
147
+ if (!holders)
148
+ return;
149
+ holders.delete(runId);
150
+ if (holders.size === 0) {
48
151
  leases.delete(leaseKey);
49
152
  }
50
153
  }
51
- /** Read-only check for a pre-flight gate (e.g. `purpose=verify`, D9) that must not itself take a lease. */
154
+ /** Read-only check for pre-flight gates (`purpose=verify`, D9): returns any overlapping *write* holder. */
52
155
  export function findWorkspaceLeaseHolder(workingDirectory) {
53
- return findConflict(workspaceLeaseKey(workingDirectory));
156
+ return findConflict(workspaceLeaseKey(workingDirectory), "read");
157
+ }
158
+ /**
159
+ * Check whether mutating (or reading) `targetPath` conflicts with an active delegation lease,
160
+ * ignoring `excludeRunId` (the worker's own run) and Pipiclaw's desk control-plane files (`tasks/`, etc.).
161
+ */
162
+ export function findConflictingWorkspaceLease(targetPath, options) {
163
+ const resolved = workspaceLeaseKey(targetPath);
164
+ if (isDeskControlPlanePath(resolved, options?.deskDir))
165
+ return undefined;
166
+ return findConflict(resolved, options?.mode ?? "write", options?.excludeRunId);
167
+ }
168
+ /**
169
+ * Guard for main-session and task-session `write`/`edit` tools (Direction 1.3): rejects mutations
170
+ * to a checkout currently locked by a write delegation or being inspected by a verification read lease.
171
+ */
172
+ export function assertPathWritableUnderLease(targetPath, options) {
173
+ const heldBy = findConflictingWorkspaceLease(targetPath, { mode: "write", ...options });
174
+ if (!heldBy)
175
+ return;
176
+ if (holderMode(heldBy) === "read") {
177
+ throw new RecoverableToolError(`Cannot modify "${targetPath}" while verification delegation ${heldBy.runId} holds a shared read lease on ` +
178
+ `"${heldBy.workingDirectory}" (channel ${heldBy.channelId}). Wait for verification to finish, cancel it ` +
179
+ "with subagent_run op=cancel, or delegate isolated edits with subagent worktree=true (or a separate `git worktree add` checkout).");
180
+ }
181
+ throw new RecoverableToolError(`Cannot modify "${targetPath}" while write delegation ${heldBy.runId} holds an exclusive write lease on ` +
182
+ `"${heldBy.workingDirectory}" (channel ${heldBy.channelId}). Wait for the delegation to finish, cancel it ` +
183
+ "with subagent_run op=cancel, or delegate isolated edits with subagent worktree=true (or a separate `git worktree add` checkout).");
54
184
  }
55
185
  export function formatWorkspaceLeaseConflict(heldBy) {
186
+ if (holderMode(heldBy) === "read") {
187
+ return (`Workspace "${heldBy.workingDirectory}" is currently held by a running verification delegation ` +
188
+ `(read lease, runId ${heldBy.runId}, channel ${heldBy.channelId}). Wait for verification to finish, ` +
189
+ "cancel it with subagent_run op=cancel, or isolate your write run with worktree=true (or a separate `git worktree add` checkout via workingDirectory).");
190
+ }
56
191
  return (`Workspace "${heldBy.workingDirectory}" is already held by a running write delegation ` +
57
192
  `(runId ${heldBy.runId}, channel ${heldBy.channelId}). Wait for it to finish, cancel it with ` +
58
- "subagent_run op=cancel, or use a separate `git worktree add` checkout via workingDirectory.");
193
+ "subagent_run op=cancel, or isolate your write run with worktree=true (or a separate `git worktree add` checkout via workingDirectory).");
59
194
  }
@@ -0,0 +1,52 @@
1
+ import type { RetainedWorktreeInfo } from "../tasks/control.js";
2
+ import { type ManagedWorktreeSummary, type RunRecord } from "./run-record.js";
3
+ export interface PreparedManagedWorktree {
4
+ workingDirectory: string;
5
+ worktreeRoot: string;
6
+ baseDir: string;
7
+ baseHead: string;
8
+ branch: string | null;
9
+ }
10
+ export type ReclaimWorktreeOutcome = {
11
+ status: "none";
12
+ } | {
13
+ status: "removed";
14
+ path: string;
15
+ branch: string | null;
16
+ } | {
17
+ status: "retained";
18
+ path: string;
19
+ branch: string | null;
20
+ headSha: string;
21
+ reason: RetainedWorktreeInfo["reason"];
22
+ };
23
+ /**
24
+ * Create an isolated Git worktree at `<gitCommonDir>/pipiclaw-worktrees/<runId>` (`.git/pipiclaw-worktrees/<runId>`)
25
+ * on branch `pipiclaw/<runId>` (falling back to detached HEAD only on ref collision) so concurrent write
26
+ * delegations never collide on the main checkout.
27
+ */
28
+ export declare function prepareManagedWorktree(baseWorkingDir: string, artifactDir: string, runId: string): Promise<PreparedManagedWorktree>;
29
+ /** Propagate `.worktree.json` to a resumed `follow_up` run's artifact directory so settlement tracks it. */
30
+ export declare function copyManagedWorktreeMeta(sourceArtifactDir: string, targetArtifactDir: string): Promise<boolean>;
31
+ /** Read structured `branch`, `headSha`, and `changedFiles` state of a managed worktree without mutating it. */
32
+ export declare function inspectManagedWorktree(artifactDir: string): Promise<ManagedWorktreeSummary | undefined>;
33
+ /**
34
+ * Inspect a runtime-managed worktree upon run settlement/cancel and auto-remove it immediately when
35
+ * unchanged (no commits beyond `baseHead` and no uncommitted/untracked files). Worktrees with commits
36
+ * or dirty edits stay on disk so the parent session/task can verify and merge them.
37
+ */
38
+ export declare function settleManagedWorktree(artifactDir: string, precomputed?: ManagedWorktreeSummary, ownerRunId?: string): Promise<ManagedWorktreeSummary | undefined>;
39
+ export declare function cleanupManagedWorktreeIfUnchanged(artifactDir: string): Promise<void>;
40
+ /**
41
+ * Reclaim a settled run's managed worktree when its parent task closes or its retention window expires:
42
+ * - Clean and either unchanged (`headSha === baseHead`) or merged into `repoRoot`'s `HEAD` -> `git worktree remove`.
43
+ * - Dirty working tree or unmerged commits -> preserved on disk and reported back to the caller.
44
+ */
45
+ export declare function reclaimManagedWorktree(artifactDir: string): Promise<ReclaimWorktreeOutcome>;
46
+ /**
47
+ * Reclaim all managed worktrees bound to `taskId` when the task closes. Clean/merged worktrees are
48
+ * removed automatically; dirty or unmerged worktrees stay on disk and are returned for user notice.
49
+ */
50
+ export declare function reclaimTaskManagedWorktrees(runs: Iterable<RunRecord>, taskId: string, onUpdated?: (record: RunRecord) => Promise<void> | void): Promise<RetainedWorktreeInfo[]>;
51
+ /** Periodic GC helper for standalone/expired runs past `WORKTREE_RETENTION_MS`. */
52
+ export declare function sweepExpiredRunWorktree(record: RunRecord, now: number, persist: (record: RunRecord) => Promise<void>): Promise<void>;
@@ -0,0 +1,363 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
4
+ import { dirname, join, relative, resolve } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import * as log from "../log.js";
7
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
8
+ import { errorMessage } from "../shared/text-utils.js";
9
+ import { isTerminal, WORKTREE_RETENTION_MS } from "./run-record.js";
10
+ import { withWorkspaceCleanupLease } from "./workspace-lease.js";
11
+ const execFileAsync = promisify(execFile);
12
+ const GIT_WORKTREE_TIMEOUT_MS = 15_000;
13
+ const WORKTREE_META_FILENAME = ".worktree.json";
14
+ const CHANGED_FILES_CAP = 100;
15
+ function safeRunSegment(value) {
16
+ return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
17
+ }
18
+ async function runGitRaw(cwd, args) {
19
+ const { stdout } = await execFileAsync("git", ["-C", cwd, ...args], {
20
+ maxBuffer: 4 * 1024 * 1024,
21
+ timeout: GIT_WORKTREE_TIMEOUT_MS,
22
+ });
23
+ return stdout;
24
+ }
25
+ async function runGit(cwd, args) {
26
+ return (await runGitRaw(cwd, args)).trim();
27
+ }
28
+ async function readWorktreeMeta(artifactDir) {
29
+ try {
30
+ return JSON.parse(await readFile(join(artifactDir, WORKTREE_META_FILENAME), "utf-8"));
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
36
+ async function removeWorktreeDirectory(meta) {
37
+ // Git must get the final veto if files changed after inspection or the worktree is locked.
38
+ // Never bypass that refusal with --force or a recursive filesystem delete.
39
+ await runGit(meta.repoRoot, ["worktree", "remove", meta.worktreeRoot]);
40
+ }
41
+ async function deleteBranchIfAtBase(meta) {
42
+ if (!meta.createdBranch)
43
+ return;
44
+ const branchSha = await runGit(meta.repoRoot, ["rev-parse", "--verify", `refs/heads/${meta.createdBranch}`]).catch(() => undefined);
45
+ if (branchSha && branchSha === meta.baseHead) {
46
+ await runGit(meta.repoRoot, ["branch", "-D", meta.createdBranch]).catch(() => undefined);
47
+ }
48
+ }
49
+ async function deleteBranchIfMerged(meta) {
50
+ if (!meta.createdBranch)
51
+ return;
52
+ const branchSha = await runGit(meta.repoRoot, ["rev-parse", "--verify", `refs/heads/${meta.createdBranch}`]).catch(() => undefined);
53
+ if (!branchSha)
54
+ return;
55
+ if (branchSha === meta.baseHead) {
56
+ await runGit(meta.repoRoot, ["branch", "-D", meta.createdBranch]).catch(() => undefined);
57
+ return;
58
+ }
59
+ await runGit(meta.repoRoot, ["branch", "-d", meta.createdBranch]).catch(() => undefined);
60
+ }
61
+ /**
62
+ * Create an isolated Git worktree at `<gitCommonDir>/pipiclaw-worktrees/<runId>` (`.git/pipiclaw-worktrees/<runId>`)
63
+ * on branch `pipiclaw/<runId>` (falling back to detached HEAD only on ref collision) so concurrent write
64
+ * delegations never collide on the main checkout.
65
+ */
66
+ export async function prepareManagedWorktree(baseWorkingDir, artifactDir, runId) {
67
+ let repoRoot;
68
+ let gitCommonDir;
69
+ let baseHead;
70
+ try {
71
+ repoRoot = realpathSync(await runGit(baseWorkingDir, ["rev-parse", "--show-toplevel"]));
72
+ const rawCommonDir = await runGit(baseWorkingDir, ["rev-parse", "--git-common-dir"]);
73
+ gitCommonDir = realpathSync(resolve(baseWorkingDir, rawCommonDir));
74
+ baseHead = await runGit(repoRoot, ["rev-parse", "--verify", "HEAD"]);
75
+ }
76
+ catch {
77
+ throw new RecoverableToolError(`Cannot create worktree from "${baseWorkingDir}": it is not inside a Git repository with an existing commit. Omit worktree=true or pass a Git checkout in workingDirectory.`);
78
+ }
79
+ const canonicalBase = realpathSync(baseWorkingDir);
80
+ const subdir = relative(repoRoot, canonicalBase);
81
+ const safeId = safeRunSegment(runId);
82
+ const worktreeRoot = join(gitCommonDir, "pipiclaw-worktrees", safeId);
83
+ const candidateBranch = `pipiclaw/${safeId}`;
84
+ await mkdir(dirname(worktreeRoot), { recursive: true });
85
+ let createdBranch = candidateBranch;
86
+ try {
87
+ await runGit(repoRoot, ["worktree", "add", "-B", candidateBranch, worktreeRoot, baseHead]);
88
+ }
89
+ catch {
90
+ createdBranch = null;
91
+ try {
92
+ await runGit(repoRoot, ["worktree", "add", "--detach", worktreeRoot, baseHead]);
93
+ }
94
+ catch (error) {
95
+ const detail = error instanceof Error ? error.message : String(error);
96
+ throw new RecoverableToolError(`Failed to create managed Git worktree at "${worktreeRoot}": ${detail}. Omit worktree=true or pass an existing checkout via workingDirectory.`);
97
+ }
98
+ }
99
+ const canonicalWorktreeRoot = realpathSync(worktreeRoot);
100
+ const workingDirectory = realpathSync(subdir ? join(canonicalWorktreeRoot, subdir) : canonicalWorktreeRoot);
101
+ const meta = {
102
+ repoRoot,
103
+ gitCommonDir,
104
+ baseHead,
105
+ worktreeRoot: canonicalWorktreeRoot,
106
+ workingDirectory,
107
+ createdBranch,
108
+ };
109
+ await mkdir(artifactDir, { recursive: true });
110
+ await writeFile(join(artifactDir, WORKTREE_META_FILENAME), JSON.stringify(meta), "utf-8");
111
+ return {
112
+ workingDirectory,
113
+ worktreeRoot: canonicalWorktreeRoot,
114
+ baseDir: canonicalBase,
115
+ baseHead,
116
+ branch: createdBranch,
117
+ };
118
+ }
119
+ /** Propagate `.worktree.json` to a resumed `follow_up` run's artifact directory so settlement tracks it. */
120
+ export async function copyManagedWorktreeMeta(sourceArtifactDir, targetArtifactDir) {
121
+ const meta = await readWorktreeMeta(sourceArtifactDir);
122
+ if (!meta)
123
+ return false;
124
+ await mkdir(targetArtifactDir, { recursive: true });
125
+ await writeFile(join(targetArtifactDir, WORKTREE_META_FILENAME), JSON.stringify(meta), "utf-8");
126
+ return true;
127
+ }
128
+ /** Read structured `branch`, `headSha`, and `changedFiles` state of a managed worktree without mutating it. */
129
+ export async function inspectManagedWorktree(artifactDir) {
130
+ const meta = await readWorktreeMeta(artifactDir);
131
+ if (!meta)
132
+ return undefined;
133
+ if (!existsSync(meta.worktreeRoot)) {
134
+ return {
135
+ path: meta.worktreeRoot,
136
+ baseHead: meta.baseHead,
137
+ branch: null,
138
+ headSha: meta.baseHead,
139
+ changedFiles: [],
140
+ dirty: false,
141
+ cleaned: true,
142
+ };
143
+ }
144
+ try {
145
+ const [headSha, branch, statusText, diffOut, untrackedOut] = await Promise.all([
146
+ runGit(meta.worktreeRoot, ["rev-parse", "--verify", "HEAD"]),
147
+ runGit(meta.worktreeRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]).then((name) => name || null, () => null),
148
+ runGit(meta.worktreeRoot, ["status", "--porcelain=v1", "--untracked-files=all"]),
149
+ runGitRaw(meta.worktreeRoot, ["diff", "--name-only", "-z", meta.baseHead]).catch(() => ""),
150
+ runGitRaw(meta.worktreeRoot, ["ls-files", "--others", "--exclude-standard", "-z"]).catch(() => ""),
151
+ ]);
152
+ const seen = new Set();
153
+ for (const raw of [...diffOut.split("\0"), ...untrackedOut.split("\0")]) {
154
+ if (raw)
155
+ seen.add(raw);
156
+ }
157
+ return {
158
+ path: meta.worktreeRoot,
159
+ baseHead: meta.baseHead,
160
+ branch,
161
+ headSha,
162
+ changedFiles: Array.from(seen).slice(0, CHANGED_FILES_CAP),
163
+ dirty: statusText.length > 0,
164
+ cleaned: false,
165
+ };
166
+ }
167
+ catch (error) {
168
+ log.logWarn("subagent.worktree.inspect_failed", "Managed worktree inspection failed", {
169
+ reason: errorMessage(error),
170
+ fields: { path: meta.worktreeRoot },
171
+ });
172
+ return undefined;
173
+ }
174
+ }
175
+ /**
176
+ * Inspect a runtime-managed worktree upon run settlement/cancel and auto-remove it immediately when
177
+ * unchanged (no commits beyond `baseHead` and no uncommitted/untracked files). Worktrees with commits
178
+ * or dirty edits stay on disk so the parent session/task can verify and merge them.
179
+ */
180
+ export async function settleManagedWorktree(artifactDir, precomputed, ownerRunId) {
181
+ const metaPath = join(artifactDir, WORKTREE_META_FILENAME);
182
+ if (precomputed) {
183
+ if (precomputed.cleaned)
184
+ await unlink(metaPath).catch(() => undefined);
185
+ return precomputed;
186
+ }
187
+ const meta = await readWorktreeMeta(artifactDir);
188
+ if (!meta)
189
+ return undefined;
190
+ return withWorkspaceCleanupLease(meta.worktreeRoot, ownerRunId, async () => {
191
+ const summary = await inspectManagedWorktree(artifactDir);
192
+ if (!summary)
193
+ return undefined;
194
+ if (!summary.dirty && summary.headSha === meta.baseHead) {
195
+ try {
196
+ if (!summary.cleaned)
197
+ await removeWorktreeDirectory(meta);
198
+ }
199
+ catch {
200
+ return summary;
201
+ }
202
+ await deleteBranchIfAtBase(meta);
203
+ await unlink(metaPath).catch(() => undefined);
204
+ return { ...summary, cleaned: true };
205
+ }
206
+ return summary;
207
+ });
208
+ }
209
+ export async function cleanupManagedWorktreeIfUnchanged(artifactDir) {
210
+ await settleManagedWorktree(artifactDir);
211
+ }
212
+ /**
213
+ * Reclaim a settled run's managed worktree when its parent task closes or its retention window expires:
214
+ * - Clean and either unchanged (`headSha === baseHead`) or merged into `repoRoot`'s `HEAD` -> `git worktree remove`.
215
+ * - Dirty working tree or unmerged commits -> preserved on disk and reported back to the caller.
216
+ */
217
+ export async function reclaimManagedWorktree(artifactDir) {
218
+ const meta = await readWorktreeMeta(artifactDir);
219
+ if (!meta)
220
+ return { status: "none" };
221
+ const outcome = await withWorkspaceCleanupLease(meta.worktreeRoot, undefined, () => reclaimWorktree(meta, artifactDir));
222
+ return (outcome ?? {
223
+ status: "retained",
224
+ path: meta.worktreeRoot,
225
+ branch: meta.createdBranch,
226
+ headSha: meta.baseHead,
227
+ reason: "busy",
228
+ });
229
+ }
230
+ async function reclaimWorktree(meta, artifactDir) {
231
+ const metaPath = join(artifactDir, WORKTREE_META_FILENAME);
232
+ if (!existsSync(meta.worktreeRoot)) {
233
+ await runGit(meta.repoRoot, ["worktree", "prune"]).catch(() => undefined);
234
+ await deleteBranchIfMerged(meta);
235
+ await unlink(metaPath).catch(() => undefined);
236
+ return { status: "removed", path: meta.worktreeRoot, branch: meta.createdBranch };
237
+ }
238
+ let headSha;
239
+ let branch;
240
+ let statusText;
241
+ try {
242
+ [headSha, branch, statusText] = await Promise.all([
243
+ runGit(meta.worktreeRoot, ["rev-parse", "--verify", "HEAD"]),
244
+ runGit(meta.worktreeRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]).then((name) => name || null, () => null),
245
+ runGit(meta.worktreeRoot, ["status", "--porcelain=v1", "--untracked-files=all"]),
246
+ ]);
247
+ }
248
+ catch {
249
+ return {
250
+ status: "retained",
251
+ path: meta.worktreeRoot,
252
+ branch: meta.createdBranch,
253
+ headSha: meta.baseHead,
254
+ reason: "unavailable",
255
+ };
256
+ }
257
+ if (statusText.length > 0) {
258
+ return {
259
+ status: "retained",
260
+ path: meta.worktreeRoot,
261
+ branch,
262
+ headSha,
263
+ reason: "dirty",
264
+ };
265
+ }
266
+ if (headSha !== meta.baseHead) {
267
+ const merged = await runGit(meta.repoRoot, ["merge-base", "--is-ancestor", headSha, "HEAD"]).then(() => true, () => false);
268
+ if (!merged) {
269
+ return {
270
+ status: "retained",
271
+ path: meta.worktreeRoot,
272
+ branch,
273
+ headSha,
274
+ reason: "unmerged",
275
+ };
276
+ }
277
+ }
278
+ try {
279
+ await removeWorktreeDirectory(meta);
280
+ }
281
+ catch {
282
+ return { status: "retained", path: meta.worktreeRoot, branch, headSha, reason: "unavailable" };
283
+ }
284
+ await deleteBranchIfMerged(meta);
285
+ await unlink(metaPath).catch(() => undefined);
286
+ return { status: "removed", path: meta.worktreeRoot, branch };
287
+ }
288
+ /**
289
+ * Reclaim all managed worktrees bound to `taskId` when the task closes. Clean/merged worktrees are
290
+ * removed automatically; dirty or unmerged worktrees stay on disk and are returned for user notice.
291
+ */
292
+ export async function reclaimTaskManagedWorktrees(runs, taskId, onUpdated) {
293
+ const byPath = new Map();
294
+ const unindexed = [];
295
+ for (const record of runs) {
296
+ if (record.taskId !== taskId || !isTerminal(record.status))
297
+ continue;
298
+ if (record.worktree?.cleaned)
299
+ continue;
300
+ const key = record.worktree?.path;
301
+ if (key) {
302
+ const group = byPath.get(key) ?? [];
303
+ group.push(record);
304
+ byPath.set(key, group);
305
+ }
306
+ else {
307
+ unindexed.push(record);
308
+ }
309
+ }
310
+ const retained = [];
311
+ const groups = [...byPath.values(), ...unindexed.map((record) => [record])];
312
+ for (const group of groups) {
313
+ const latest = group.reduce((a, b) => ((b.finishedAt ?? b.startedAt) >= (a.finishedAt ?? a.startedAt) ? b : a));
314
+ const outcome = await reclaimManagedWorktree(latest.artifactDir).catch(() => ({ status: "none" }));
315
+ if (outcome.status === "removed") {
316
+ for (const record of group) {
317
+ if (record !== latest) {
318
+ await unlink(join(record.artifactDir, WORKTREE_META_FILENAME)).catch(() => undefined);
319
+ }
320
+ if (record.worktree && !record.worktree.cleaned) {
321
+ record.worktree = { ...record.worktree, cleaned: true };
322
+ await onUpdated?.(record);
323
+ }
324
+ }
325
+ }
326
+ else if (outcome.status === "retained") {
327
+ retained.push({
328
+ runId: latest.runId,
329
+ path: outcome.path,
330
+ branch: outcome.branch,
331
+ headSha: outcome.headSha,
332
+ reason: outcome.reason,
333
+ });
334
+ }
335
+ }
336
+ return retained;
337
+ }
338
+ /** Periodic GC helper for standalone/expired runs past `WORKTREE_RETENTION_MS`. */
339
+ export async function sweepExpiredRunWorktree(record, now, persist) {
340
+ if (!record.settledAt || now - record.settledAt < WORKTREE_RETENTION_MS)
341
+ return;
342
+ if (record.worktree?.cleaned)
343
+ return;
344
+ const outcome = await reclaimManagedWorktree(record.artifactDir).catch(() => ({ status: "none" }));
345
+ if (outcome.status === "removed" && record.worktree) {
346
+ record.worktree = { ...record.worktree, cleaned: true };
347
+ await persist(record);
348
+ }
349
+ else if (outcome.status === "retained" && outcome.reason !== "busy" && !record.worktreeRetainWarned) {
350
+ record.worktreeRetainWarned = true;
351
+ await persist(record);
352
+ log.logWarn("subagent.worktree.retained", "Managed worktree retained on expiry", {
353
+ channelId: record.channelId,
354
+ reason: outcome.reason,
355
+ fields: {
356
+ runId: record.runId,
357
+ path: outcome.path,
358
+ branch: outcome.branch ?? "detached",
359
+ headSha: outcome.headSha,
360
+ },
361
+ });
362
+ }
363
+ }
@@ -7,7 +7,9 @@ import { writeFileAtomically } from "../shared/atomic-file.js";
7
7
  import { errorMessage } from "../shared/text-utils.js";
8
8
  import { isPlainObject } from "../shared/type-guards.js";
9
9
  import { normalizeTaskId, renderTaskDocument } from "./contract.js";
10
+ import { closeTaskLogAppender } from "./loop-log.js";
10
11
  import { withTaskMutation } from "./mutation-lock.js";
12
+ import { taskSessionPath } from "./session-path.js";
11
13
  const SUFFIXES = ["", ".1", ".2"];
12
14
  /** A current-format crash-recovery record, removed only after publication and source cleanup. */
13
15
  export function taskArchiveCommitPath(deskDir, id) {
@@ -77,8 +79,10 @@ async function finishCommit(deskDir, commit) {
77
79
  await writeFileAtomically(target, commit.contract);
78
80
  // Keep the active contract until every archive file is durable. It is the lane's visible handle
79
81
  // throughout cleanup; the commit independently covers a crash after that handle is removed.
82
+ await closeTaskLogAppender(deskDir, commit.id).catch(() => undefined);
80
83
  for (const { suffix } of commit.logs)
81
84
  await rm(join(tasks, `${commit.id}.jsonl${suffix}`), { force: true });
85
+ await rm(taskSessionPath(deskDir, commit.id), { force: true });
82
86
  await rm(join(tasks, `${commit.id}.md`), { force: true });
83
87
  await syncDirectory(tasks);
84
88
  await rm(taskArchiveCommitPath(deskDir, commit.id), { force: true });
@@ -31,7 +31,11 @@ export interface TaskBriefInput {
31
31
  }
32
32
  export interface TaskBrief {
33
33
  text: string;
34
- contractSha: string;
34
+ contract: {
35
+ tag: string;
36
+ text: string;
37
+ path: string;
38
+ };
35
39
  }
36
40
  /** The `<task_inputs>` block body, or `undefined` when nothing new arrived. Executor output is data, not instruction. */
37
41
  export declare function renderTaskInputs(records: readonly TaskLogRecord[], inputs: readonly TaskInputRecord[]): string | undefined;