@temmo/cli 0.0.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (445) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +16 -0
  3. package/.codex-plugin/plugin.json +30 -0
  4. package/.cursor-plugin/plugin.json +22 -0
  5. package/.mcp.json +18 -0
  6. package/LICENSE +202 -0
  7. package/README.md +82 -2
  8. package/THIRD_PARTY_NOTICES +32 -0
  9. package/commands/afk.md +17 -0
  10. package/deploy/build-ui.mjs +65 -0
  11. package/deploy/claude/README.md +16 -0
  12. package/deploy/claude/auto-mode.json +31 -0
  13. package/deploy/postgres/compose.yaml +26 -0
  14. package/deploy/temmo-runner.service +24 -0
  15. package/deploy/verify-ui.mjs +15 -0
  16. package/harness-core/README.md +27 -0
  17. package/harness-core/bin/harness.mjs +17 -0
  18. package/harness-core/package.json +10 -0
  19. package/harness-core/stage.mjs +108 -0
  20. package/harness-core/stages/commit.md +7 -0
  21. package/harness-core/stages/pr.md +7 -0
  22. package/harness-core/stages/push.md +7 -0
  23. package/hooks/codex-hooks.json +14 -0
  24. package/hooks/cursor-hooks.json +17 -0
  25. package/hooks/hooks.json +27 -0
  26. package/lib/acp/permission.js +72 -0
  27. package/lib/acp/sessionConfig.js +109 -0
  28. package/lib/activity.js +244 -0
  29. package/lib/agent-guard.js +72 -0
  30. package/lib/agents-route.js +55 -0
  31. package/lib/agents.js +213 -0
  32. package/lib/agui.js +255 -0
  33. package/lib/alerts.js +36 -0
  34. package/lib/analyze-otlp.js +46 -0
  35. package/lib/analyze-run-code.js +397 -0
  36. package/lib/analyze-sources.js +372 -0
  37. package/lib/approval-card.js +54 -0
  38. package/lib/approval-cli.js +53 -0
  39. package/lib/approval-request.js +81 -0
  40. package/lib/approval-signer.js +48 -0
  41. package/lib/approvals.js +295 -0
  42. package/lib/attachment-cache.js +236 -0
  43. package/lib/attachment.js +63 -0
  44. package/lib/blocked.js +20 -0
  45. package/lib/build-review.js +90 -0
  46. package/lib/builder/cli.js +90 -0
  47. package/lib/builder/policy.js +176 -0
  48. package/lib/builder/recover.js +189 -0
  49. package/lib/builder/run.js +240 -0
  50. package/lib/builder/settle.js +198 -0
  51. package/lib/builder/stage.js +240 -0
  52. package/lib/builder/state.js +73 -0
  53. package/lib/builder/supervisor.js +289 -0
  54. package/lib/builder-clean.js +223 -0
  55. package/lib/builder-code.cjs +67 -0
  56. package/lib/builder.js +9 -0
  57. package/lib/bus-postgres.js +281 -0
  58. package/lib/bus.js +349 -0
  59. package/lib/catalog/author.js +278 -0
  60. package/lib/catalog/dot.js +426 -0
  61. package/lib/catalog/pattern-model.js +193 -0
  62. package/lib/catalog/patterns.js +324 -0
  63. package/lib/catalog/projects.js +83 -0
  64. package/lib/catalog/records.js +2 -0
  65. package/lib/catalog/roster.js +70 -0
  66. package/lib/catalog/team-files.js +49 -0
  67. package/lib/catalog/teams.js +109 -0
  68. package/lib/claude-socket.js +333 -0
  69. package/lib/cli.js +741 -0
  70. package/lib/code-mode.js +45 -0
  71. package/lib/code-read-policy.yaml +9 -0
  72. package/lib/code-run.js +461 -0
  73. package/lib/codex-compact.js +141 -0
  74. package/lib/compaction.js +21 -0
  75. package/lib/config.js +424 -0
  76. package/lib/cursor-trace.js +248 -0
  77. package/lib/deep-link.js +20 -0
  78. package/lib/deliver-push.js +120 -0
  79. package/lib/delivery.js +28 -0
  80. package/lib/deploy-tree.js +227 -0
  81. package/lib/durable.js +404 -0
  82. package/lib/factory-tick.js +32 -0
  83. package/lib/family.js +63 -0
  84. package/lib/fetch-origin.js +53 -0
  85. package/lib/format.js +133 -0
  86. package/lib/harness-surface-cli.js +153 -0
  87. package/lib/harness-surface.js +486 -0
  88. package/lib/harness.js +271 -0
  89. package/lib/hook.mjs +291 -0
  90. package/lib/idle.js +40 -0
  91. package/lib/install-cursor.js +115 -0
  92. package/lib/install-opencode.js +105 -0
  93. package/lib/job.js +82 -0
  94. package/lib/land-cli.js +319 -0
  95. package/lib/land-member.js +64 -0
  96. package/lib/land.js +320 -0
  97. package/lib/lessons.js +223 -0
  98. package/lib/limit-alert.js +423 -0
  99. package/lib/limits.js +284 -0
  100. package/lib/machine-prompt.js +19 -0
  101. package/lib/merge-sweep.js +149 -0
  102. package/lib/messaging.js +1002 -0
  103. package/lib/mission-cli.js +103 -0
  104. package/lib/mission.js +241 -0
  105. package/lib/mode.js +215 -0
  106. package/lib/models.js +114 -0
  107. package/lib/names.js +86 -0
  108. package/lib/opencode-api.js +57 -0
  109. package/lib/opencode-plugin.mjs +313 -0
  110. package/lib/operator-token.js +78 -0
  111. package/lib/operator.js +187 -0
  112. package/lib/pad-activity.js +143 -0
  113. package/lib/pad-fresh.js +44 -0
  114. package/lib/pad.js +198 -0
  115. package/lib/pattern-cli.js +120 -0
  116. package/lib/pattern-compiler.js +68 -0
  117. package/lib/pattern-runs.js +795 -0
  118. package/lib/pattern-stall.js +58 -0
  119. package/lib/pattern-tick.js +45 -0
  120. package/lib/pattern-workflow.js +69 -0
  121. package/lib/pi-extension.mjs +98 -0
  122. package/lib/pi.js +57 -0
  123. package/lib/plugin-copy.js +76 -0
  124. package/lib/pm-review.js +32 -0
  125. package/lib/pm-workspace.js +87 -0
  126. package/lib/postgres.js +115 -0
  127. package/lib/pr-card.js +34 -0
  128. package/lib/probe.js +295 -0
  129. package/lib/process.js +67 -0
  130. package/lib/project-pause.js +23 -0
  131. package/lib/prune.js +793 -0
  132. package/lib/questions.js +250 -0
  133. package/lib/receipts.js +63 -0
  134. package/lib/reflect.js +962 -0
  135. package/lib/rename-migration.js +118 -0
  136. package/lib/run-terminal.js +437 -0
  137. package/lib/runner-request.js +33 -0
  138. package/lib/sandbox-app.js +120 -0
  139. package/lib/sandbox-claims.js +258 -0
  140. package/lib/sandbox-cli.js +188 -0
  141. package/lib/sandbox-hosts-cli.js +68 -0
  142. package/lib/sandbox-hosts.js +94 -0
  143. package/lib/sandbox-pr.js +102 -0
  144. package/lib/sandbox-proposal.js +367 -0
  145. package/lib/sandbox-tools.js +143 -0
  146. package/lib/sandbox.js +501 -0
  147. package/lib/schedule-session.js +68 -0
  148. package/lib/session-activity.js +67 -0
  149. package/lib/session-events.js +94 -0
  150. package/lib/sessions/control.js +244 -0
  151. package/lib/sessions/git-refs.js +265 -0
  152. package/lib/sessions/launch.js +359 -0
  153. package/lib/sessions/registry.js +450 -0
  154. package/lib/sessions/scope.js +111 -0
  155. package/lib/setup.js +377 -0
  156. package/lib/signed-approval.js +225 -0
  157. package/lib/slash.js +167 -0
  158. package/lib/spawn-cli.js +45 -0
  159. package/lib/spawn.js +107 -0
  160. package/lib/start-limit.js +58 -0
  161. package/lib/state.js +24 -0
  162. package/lib/stop.js +308 -0
  163. package/lib/store-read.js +62 -0
  164. package/lib/store.js +252 -0
  165. package/lib/subagent-guard.js +240 -0
  166. package/lib/surfaces/channel-post.js +43 -0
  167. package/lib/surfaces/instructions.js +15 -0
  168. package/lib/surfaces/mcp-reload.js +144 -0
  169. package/lib/surfaces/ops.js +629 -0
  170. package/lib/surfaces/render-mcp.js +33 -0
  171. package/lib/surfaces/run-terminal-ops.js +40 -0
  172. package/lib/surfaces/sandbox-ops.js +36 -0
  173. package/lib/surfaces/schema.js +7 -0
  174. package/lib/surfaces/task-view.js +90 -0
  175. package/lib/surfaces/types.js +4 -0
  176. package/lib/task-cli.js +274 -0
  177. package/lib/task-order.js +34 -0
  178. package/lib/task-order.mjs +2 -0
  179. package/lib/task-route.js +125 -0
  180. package/lib/tasks.js +631 -0
  181. package/lib/team-permission.js +34 -0
  182. package/lib/team-templates/blitz/team.dot +9 -0
  183. package/lib/team-templates/factory/team.dot +26 -0
  184. package/lib/team-templates/feature/team.dot +14 -0
  185. package/lib/team-templates/fix-and-review/team.dot +12 -0
  186. package/lib/team-templates/product/team.dot +16 -0
  187. package/lib/team-templates/release/team.dot +7 -0
  188. package/lib/team-templates/review/team.dot +6 -0
  189. package/lib/terminal-draft.js +42 -0
  190. package/lib/thread-branch.js +82 -0
  191. package/lib/thread-channel-store.js +181 -0
  192. package/lib/thread-channels.js +116 -0
  193. package/lib/thread-listening.js +20 -0
  194. package/lib/thread-routes.js +91 -0
  195. package/lib/threads.js +441 -0
  196. package/lib/tool-api.js +33 -0
  197. package/lib/transcript.js +98 -0
  198. package/lib/ui-build-output.js +19 -0
  199. package/lib/ui-capabilities.js +90 -0
  200. package/lib/usage.js +182 -0
  201. package/lib/vendor/mcp-sdk.d.mts +4 -0
  202. package/lib/vendor/mcp-sdk.mjs +17046 -0
  203. package/lib/waiter.js +127 -0
  204. package/lib/workflows.js +546 -0
  205. package/lib/worktree-setup.js +86 -0
  206. package/package.json +112 -1
  207. package/runner/adapters/claude.js +465 -0
  208. package/runner/adapters/cli-sandbox.js +277 -0
  209. package/runner/adapters/codex.js +675 -0
  210. package/runner/adapters/cursor.mjs +937 -0
  211. package/runner/adapters/fake.js +119 -0
  212. package/runner/adapters/opencode-sandbox.js +370 -0
  213. package/runner/adapters/opencode.js +486 -0
  214. package/runner/adapters/pi-sandbox.js +134 -0
  215. package/runner/adapters/pi.js +364 -0
  216. package/runner/client.js +40 -0
  217. package/runner/contract.js +129 -0
  218. package/runner/control.js +178 -0
  219. package/runner/delivery.js +184 -0
  220. package/runner/factory-tick.mjs +10 -0
  221. package/runner/lock.js +41 -0
  222. package/runner/main.mjs +118 -0
  223. package/runner/pattern-tick.mjs +16 -0
  224. package/runner/publish.js +113 -0
  225. package/runner/runner.js +2612 -0
  226. package/runner/sandbox-run.mjs +239 -0
  227. package/runner/schedules.js +294 -0
  228. package/runner/task-wake.js +59 -0
  229. package/scripts/ai-collab +3 -0
  230. package/scripts/ai-collab-bus.mjs +4 -0
  231. package/scripts/ai-collab-code-mcp.mjs +3 -0
  232. package/scripts/ai-collab-hook +3 -0
  233. package/scripts/ai-collab-hook.mjs +3 -0
  234. package/scripts/ai-collab-mcp-tools.mjs +2 -0
  235. package/scripts/ai-collab-mcp.mjs +3 -0
  236. package/scripts/ai-collab.mjs +3 -0
  237. package/scripts/install-cursor.mjs +11 -0
  238. package/scripts/install-opencode.mjs +10 -0
  239. package/scripts/temmo +3 -0
  240. package/scripts/temmo-bus.mjs +151 -0
  241. package/scripts/temmo-code-mcp.mjs +63 -0
  242. package/scripts/temmo-hook +3 -0
  243. package/scripts/temmo-hook.mjs +201 -0
  244. package/scripts/temmo-mcp-tools.mjs +22 -0
  245. package/scripts/temmo-mcp.mjs +27 -0
  246. package/scripts/temmo.mjs +4 -0
  247. package/skills/antislop/SKILL.md +701 -0
  248. package/skills/antislop/VERSION +1 -0
  249. package/skills/antislop-code/SKILL.md +128 -0
  250. package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
  251. package/skills/antislop-human/SKILL.md +204 -0
  252. package/skills/antislop-human/contrast-check.py +168 -0
  253. package/skills/antislop-human/contrast-mcp.py +125 -0
  254. package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
  255. package/skills/antislop-human/references/WCAG.md +127 -0
  256. package/skills/antislop-layoutmobile/SKILL.md +170 -0
  257. package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
  258. package/skills/antislop-ui/SKILL.md +351 -0
  259. package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
  260. package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
  261. package/skills/harness-surface/SKILL.md +42 -0
  262. package/skills/land/SKILL.md +32 -0
  263. package/skills/memory-file/SKILL.md +39 -0
  264. package/skills/temmo/SKILL.md +101 -0
  265. package/skills/temmo/references/role-programs.md +47 -0
  266. package/skills/ui-sdk/SKILL.md +56 -0
  267. package/skills/ui-sdk/references/agent-ready.md +136 -0
  268. package/skills/ui-sdk/references/build-interface.md +187 -0
  269. package/skills/ui-sdk/references/create-component.md +88 -0
  270. package/skills/ui-sdk/references/patterns.md +246 -0
  271. package/skills/ui-sdk/references/styles.md +66 -0
  272. package/skills/ui-sdk/references/testing.md +172 -0
  273. package/skills/ui-sdk/references/web-components.md +78 -0
  274. package/tools/screen-state.mjs +119 -0
  275. package/tools/smoke-ui.mjs +540 -0
  276. package/web/app/activity.jsx +251 -0
  277. package/web/app/agent-mark.tsx +43 -0
  278. package/web/app/alert-level.jsx +16 -0
  279. package/web/app/api/[action]/route.js +8 -0
  280. package/web/app/api/auth/[step]/route.js +12 -0
  281. package/web/app/api/events/route.js +8 -0
  282. package/web/app/api/file/[name]/route.js +8 -0
  283. package/web/app/api/land/route.js +12 -0
  284. package/web/app/api/lessons/route.js +8 -0
  285. package/web/app/api/push/key/route.js +8 -0
  286. package/web/app/api/push/subscribe/route.js +12 -0
  287. package/web/app/api/push/test/route.js +8 -0
  288. package/web/app/api/refs/route.js +8 -0
  289. package/web/app/api/review-diff/route.js +8 -0
  290. package/web/app/api/schedules/route.js +8 -0
  291. package/web/app/api/thread-diff/route.js +8 -0
  292. package/web/app/api/version/route.js +6 -0
  293. package/web/app/cards.jsx +189 -0
  294. package/web/app/chat-api.js +82 -0
  295. package/web/app/chat-composer.jsx +313 -0
  296. package/web/app/chat-console.jsx +691 -0
  297. package/web/app/chat-image.tsx +61 -0
  298. package/web/app/chat-message.jsx +122 -0
  299. package/web/app/chat-shared.jsx +59 -0
  300. package/web/app/chat-sidebar.jsx +25 -0
  301. package/web/app/chat-stream.js +127 -0
  302. package/web/app/chat.jsx +31 -0
  303. package/web/app/compactions.jsx +57 -0
  304. package/web/app/composer-actions.tsx +87 -0
  305. package/web/app/decisions.jsx +53 -0
  306. package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
  307. package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
  308. package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
  309. package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
  310. package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
  311. package/web/app/globals.css +199 -0
  312. package/web/app/home.jsx +246 -0
  313. package/web/app/icon.svg +1 -0
  314. package/web/app/land-panel.jsx +63 -0
  315. package/web/app/land-reviews.jsx +20 -0
  316. package/web/app/layout.jsx +17 -0
  317. package/web/app/lessons.tsx +76 -0
  318. package/web/app/logo.tsx +13 -0
  319. package/web/app/logos.jsx +16 -0
  320. package/web/app/manifest.js +8 -0
  321. package/web/app/mode-menu.tsx +46 -0
  322. package/web/app/new-session.jsx +275 -0
  323. package/web/app/notify.jsx +180 -0
  324. package/web/app/outcomes.tsx +94 -0
  325. package/web/app/page.jsx +9 -0
  326. package/web/app/pattern-graph.jsx +75 -0
  327. package/web/app/patterns-page.jsx +293 -0
  328. package/web/app/phone-nav.tsx +36 -0
  329. package/web/app/progress-feed.tsx +33 -0
  330. package/web/app/providers.tsx +27 -0
  331. package/web/app/quote.jsx +15 -0
  332. package/web/app/run-card.tsx +200 -0
  333. package/web/app/run-requests.tsx +148 -0
  334. package/web/app/scheduled.jsx +105 -0
  335. package/web/app/session-panel.tsx +174 -0
  336. package/web/app/session-toolbar.tsx +180 -0
  337. package/web/app/shadcn.css +638 -0
  338. package/web/app/shipped.jsx +49 -0
  339. package/web/app/subagent-runs.jsx +31 -0
  340. package/web/app/task-graph.jsx +67 -0
  341. package/web/app/tasks-strip.tsx +36 -0
  342. package/web/app/tasks.jsx +375 -0
  343. package/web/app/team-author.jsx +145 -0
  344. package/web/app/team-editor.jsx +88 -0
  345. package/web/app/thread-agents.tsx +32 -0
  346. package/web/app/thread-place.tsx +9 -0
  347. package/web/app/thread-sessions.tsx +149 -0
  348. package/web/app/thread-sidebar.tsx +418 -0
  349. package/web/app/thread-switcher.tsx +27 -0
  350. package/web/app/tool-diff.jsx +94 -0
  351. package/web/components/a2ui/controls.jsx +36 -0
  352. package/web/components/a2ui/option-picker.jsx +23 -0
  353. package/web/components/a2ui/script.tsx +121 -0
  354. package/web/components/a2ui/surface.jsx +81 -0
  355. package/web/components/chat/thread.jsx +50 -0
  356. package/web/components/script-text.tsx +42 -0
  357. package/web/components/ui/avatar.jsx +115 -0
  358. package/web/components/ui/badge.jsx +47 -0
  359. package/web/components/ui/button.jsx +63 -0
  360. package/web/components/ui/chat-container.jsx +52 -0
  361. package/web/components/ui/choice-list.tsx +72 -0
  362. package/web/components/ui/code-block.jsx +60 -0
  363. package/web/components/ui/copy-button.tsx +41 -0
  364. package/web/components/ui/dropdown-menu.jsx +257 -0
  365. package/web/components/ui/markdown.jsx +84 -0
  366. package/web/components/ui/message.jsx +28 -0
  367. package/web/components/ui/popover.jsx +33 -0
  368. package/web/components/ui/scroll-button.jsx +34 -0
  369. package/web/components/ui/select.jsx +189 -0
  370. package/web/components/ui/sheet.jsx +152 -0
  371. package/web/components/ui/sonner.jsx +10 -0
  372. package/web/components/ui/tabs.jsx +88 -0
  373. package/web/components/ui/textarea.jsx +20 -0
  374. package/web/components/ui/tooltip.jsx +56 -0
  375. package/web/components.json +24 -0
  376. package/web/instrumentation.js +8 -0
  377. package/web/lib/a2ui-catalog.js +34 -0
  378. package/web/lib/a2ui-pr.js +76 -0
  379. package/web/lib/a2ui-run-catalog.js +18 -0
  380. package/web/lib/a2ui-run.js +93 -0
  381. package/web/lib/a2ui.js +262 -0
  382. package/web/lib/activity-rows.js +275 -0
  383. package/web/lib/agent-detail.js +5 -0
  384. package/web/lib/alert-level.js +44 -0
  385. package/web/lib/approval-mode.js +22 -0
  386. package/web/lib/chat-turns.js +174 -0
  387. package/web/lib/child-subagents.js +16 -0
  388. package/web/lib/compaction-view.js +48 -0
  389. package/web/lib/composer-actions.js +40 -0
  390. package/web/lib/context-view.js +57 -0
  391. package/web/lib/fuzzy.js +26 -0
  392. package/web/lib/highlight.js +44 -0
  393. package/web/lib/lessons-view.js +23 -0
  394. package/web/lib/mentions.js +16 -0
  395. package/web/lib/message-routing.js +105 -0
  396. package/web/lib/new-session.js +85 -0
  397. package/web/lib/operator-messages.js +28 -0
  398. package/web/lib/pattern-graph.js +165 -0
  399. package/web/lib/pattern-view.js +33 -0
  400. package/web/lib/pending-summary.js +18 -0
  401. package/web/lib/permission-modes.js +30 -0
  402. package/web/lib/project-feed.js +107 -0
  403. package/web/lib/quote.js +7 -0
  404. package/web/lib/reply-quote.js +31 -0
  405. package/web/lib/scheduled.js +79 -0
  406. package/web/lib/selection.js +110 -0
  407. package/web/lib/send-confirmation.js +22 -0
  408. package/web/lib/session-dead.js +10 -0
  409. package/web/lib/session-state.js +132 -0
  410. package/web/lib/sidebar.js +15 -0
  411. package/web/lib/slash-commands.js +164 -0
  412. package/web/lib/start-default.js +35 -0
  413. package/web/lib/start-mode.js +35 -0
  414. package/web/lib/stream-views.js +49 -0
  415. package/web/lib/subagent-state.js +20 -0
  416. package/web/lib/task-board.js +54 -0
  417. package/web/lib/task-graph.js +183 -0
  418. package/web/lib/task-tags.js +41 -0
  419. package/web/lib/team-editor.js +10 -0
  420. package/web/lib/thread-groups.js +86 -0
  421. package/web/lib/threads.js +28 -0
  422. package/web/lib/tool-diff.js +273 -0
  423. package/web/lib/ui-events.js +58 -0
  424. package/web/lib/utils.js +5 -0
  425. package/web/lib/view-memory.js +25 -0
  426. package/web/next.config.mjs +37 -0
  427. package/web/postcss.config.mjs +1 -0
  428. package/web/proxy.js +25 -0
  429. package/web/public/sw.js +39 -0
  430. package/web/server/auth.js +178 -0
  431. package/web/server/dispatch.js +293 -0
  432. package/web/server/history.js +56 -0
  433. package/web/server/hosted.js +58 -0
  434. package/web/server/hub.js +126 -0
  435. package/web/server/instance.js +5 -0
  436. package/web/server/land-reviews.js +64 -0
  437. package/web/server/push.js +148 -0
  438. package/web/server/run-terminal.js +79 -0
  439. package/web/server/schedules.js +38 -0
  440. package/web/server/shipped.js +51 -0
  441. package/web/server/task-board.js +71 -0
  442. package/web/server/threads.js +209 -0
  443. package/web/server/ui.js +2937 -0
  444. package/web/tsconfig.base.json +16 -0
  445. package/web/tsconfig.json +9 -0
package/lib/prune.js ADDED
@@ -0,0 +1,793 @@
1
+ /** `temmo prune`: reclaim disk from settled builder copies and git worktrees; keeps every commit reachable. */
2
+ import { execFile } from "node:child_process";
3
+ import { parseArgs } from "node:util";
4
+ import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { builderPaths, FINAL_PHASES, LIVE_STATES } from "./builder/state.js";
7
+ import { unitState } from "./builder/supervisor.js";
8
+ import { PROTECTED_CHECKOUTS } from "./builder-clean.js";
9
+ import { stateDir } from "./config.js";
10
+ import { sessionRecords } from "./sessions/registry.js";
11
+ import { commitIdentity } from "./sandbox.js";
12
+ import { projectRoot } from "./sessions/launch.js";
13
+ import { parseWorktreeList } from "./sessions/git-refs.js";
14
+ import { openTasks, TaskNotFoundError } from "./tasks.js";
15
+ export { parseWorktreeList };
16
+ export const ARCHIVE_NS = "refs/ai-collab/archive";
17
+ export const LOG_CAP_BYTES = 1024 * 1024;
18
+ const MIN_CUTOFF_MS = 24 * 3_600_000;
19
+ const MIN_MERGED_CUTOFF_MS = 30 * 60_000;
20
+ const DEFAULT_MERGED_CUTOFF = "1h";
21
+ const SCAN_MAX_ENTRIES = 50_000;
22
+ const SCAN_SKIP = new Set([".git", "node_modules"]);
23
+ const ALLOWED_IGNORED = [/(^|\/)node_modules(\/|$)/, /(^|\/)\.next[^/]*(\/|$)/, /(^|\/)dist(\/|$)/, /^web\/next-env\.d\.ts$/];
24
+ const CARGO_TARGET = /^target(\/|$)/;
25
+ const LOCK_REASON = "temmo prune";
26
+ // oxlint-disable-next-line quality/no-known-value-widening -- looked up by a runtime age unit
27
+ const AGE_UNITS = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };
28
+ const GIT_ENV_KEYS = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_PREFIX"];
29
+ const GIT_TIMEOUT_MS = 120_000;
30
+ const GIT_MAX_BUFFER = 64 * 1024 * 1024;
31
+ const GH_TIMEOUT_MS = 60_000;
32
+ const GH_PR_LIMIT = "1000";
33
+ const USAGE = "usage: temmo prune [--apply] [--older-than 7d] [--merged-older-than 1h] [--repo <path>]... [--json]"
34
+ + " (cutoff at least 24h, merged cutoff at least 30m)";
35
+ /** Milliseconds for "7d", "24h", "30m" or "45s"; null for anything else. */
36
+ export function parseAge(text) {
37
+ const match = /^(\d+)([smhd])$/.exec(text ?? "");
38
+ return match ? Number(match[1]) * AGE_UNITS[match[2]] : null;
39
+ }
40
+ /** Flags for prune, or null for an unknown flag, a bad age, a cutoff under 24h, or a merged cutoff under 30m. */
41
+ export function parsePruneArgs(argv) {
42
+ let flags;
43
+ try {
44
+ ({ values: flags } = parseArgs({ args: argv, strict: true, options: {
45
+ apply: { type: "boolean", default: false }, json: { type: "boolean", default: false }, "older-than": { type: "string", default: "7d" },
46
+ "merged-older-than": { type: "string", default: DEFAULT_MERGED_CUTOFF }, repo: { type: "string", multiple: true, default: [] },
47
+ } }));
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ const { apply, json, "older-than": olderThan, "merged-older-than": mergedOlderThan, repo: repos } = flags;
53
+ const olderThanMs = parseAge(olderThan);
54
+ const mergedOlderThanMs = parseAge(mergedOlderThan);
55
+ if (olderThanMs === null || olderThanMs < MIN_CUTOFF_MS)
56
+ return null;
57
+ if (mergedOlderThanMs === null || mergedOlderThanMs < MIN_MERGED_CUTOFF_MS)
58
+ return null;
59
+ return { apply, json, olderThan, olderThanMs, mergedOlderThan, mergedOlderThanMs, repos };
60
+ }
61
+ /** Bytes of disk the tree at `target` uses; an inode counts once. */
62
+ export function treeBytes(target, seen = new Set()) {
63
+ let info;
64
+ try {
65
+ info = lstatSync(target);
66
+ }
67
+ catch {
68
+ return 0;
69
+ }
70
+ const key = `${info.dev}:${info.ino}`;
71
+ if (seen.has(key))
72
+ return 0;
73
+ seen.add(key);
74
+ let total = info.blocks * 512;
75
+ if (info.isDirectory() && !info.isSymbolicLink()) {
76
+ for (const name of readdirSync(target))
77
+ total += treeBytes(path.join(target, name), seen);
78
+ }
79
+ return total;
80
+ }
81
+ /** Working directories of the processes in /proc; an unreadable cwd is not counted. */
82
+ export function readLiveCwds(proc = "/proc") {
83
+ let pids;
84
+ try {
85
+ pids = readdirSync(proc).filter((pid) => /^\d+$/.test(pid));
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ const cwds = [];
91
+ for (const pid of pids) {
92
+ try {
93
+ cwds.push(readlinkSync(path.join(proc, pid, "cwd")));
94
+ }
95
+ catch { /* exited, kernel thread, or not readable */ }
96
+ }
97
+ return cwds;
98
+ }
99
+ /** True when `wtPath` is the project checkout or a protected checkout, not a path inside one. */
100
+ export function isProtectedCheckout(wtPath, root) {
101
+ const real = (p) => { try {
102
+ return realpathSync(p);
103
+ }
104
+ catch {
105
+ return path.resolve(p);
106
+ } };
107
+ const target = real(wtPath);
108
+ return [root, ...PROTECTED_CHECKOUTS].some((base) => real(base) === target);
109
+ }
110
+ /** Bulky copies in one builder dir: clone, staged trees (with tools), sandbox downloads, and logs over the cap. */
111
+ export function builderBulkTargets(dir) {
112
+ const targets = [];
113
+ for (const name of readdirSync(dir)) {
114
+ const full = path.join(dir, name);
115
+ if (name === "back")
116
+ targets.push({ kind: "clone", path: full });
117
+ else if (name === "stage")
118
+ targets.push({ kind: "staged", path: full });
119
+ else if (name.startsWith("download-"))
120
+ targets.push({ kind: "downloads", path: full });
121
+ else if (name.endsWith(".log")) {
122
+ const info = lstatSync(full);
123
+ if (info.isFile() && info.size > LOG_CAP_BYTES)
124
+ targets.push({ kind: "logs", path: full });
125
+ }
126
+ }
127
+ return targets;
128
+ }
129
+ /** Newest file mtime under `root`, skipping node_modules, .next and the `skip` paths; Infinity when the scan hits its entry cap. */
130
+ export function newestFileMs(root, maxEntries = SCAN_MAX_ENTRIES, skip = []) {
131
+ let newest = 0;
132
+ let seen = 0;
133
+ const stack = [root];
134
+ while (stack.length) {
135
+ const dir = stack.pop();
136
+ let names;
137
+ try {
138
+ names = readdirSync(dir);
139
+ }
140
+ catch {
141
+ continue;
142
+ }
143
+ for (const name of names) {
144
+ if (SCAN_SKIP.has(name) || name.startsWith(".next"))
145
+ continue;
146
+ seen += 1;
147
+ if (seen > maxEntries)
148
+ return Infinity;
149
+ const full = path.join(dir, name);
150
+ if (skip.includes(full))
151
+ continue;
152
+ let info;
153
+ try {
154
+ info = lstatSync(full);
155
+ }
156
+ catch {
157
+ continue;
158
+ }
159
+ if (info.isDirectory())
160
+ stack.push(full);
161
+ else
162
+ newest = Math.max(newest, info.mtimeMs);
163
+ }
164
+ }
165
+ return newest;
166
+ }
167
+ /** True when an ignored path is one a rebuild recreates: node_modules, .next* and dist anywhere, web/next-env.d.ts, and top-level target/ in a Cargo worktree. */
168
+ export function isAllowedIgnored(file, { cargo = false } = {}) {
169
+ return ALLOWED_IGNORED.some((pattern) => pattern.test(file)) || (cargo && CARGO_TARGET.test(file));
170
+ }
171
+ /** Decide one worktree from its facts; a merged worktree waits only for `mergedCutoffMs`. Pure: no I/O. */
172
+ export function worktreeDecision(f, cutoffMs, mergedCutoffMs = cutoffMs) {
173
+ const keep = (reason) => ({ action: "keep", reason, archive: null });
174
+ if (f.main)
175
+ return keep("main worktree");
176
+ if (f.protected)
177
+ return keep("protected checkout");
178
+ if (f.locked)
179
+ return keep("locked");
180
+ if (f.nested)
181
+ return keep(`contains another worktree: ${f.nested}`);
182
+ if (f.error)
183
+ return keep(`unreadable: ${f.error}`);
184
+ if (f.dirty > 0)
185
+ return keep(`dirty: ${f.dirty} changed or untracked file(s)`);
186
+ if (f.ignoredBad?.length)
187
+ return keep(`ignored outside allowlist: ${f.ignoredBad[0]}`);
188
+ if (f.inUse)
189
+ return keep("in use: a live process has its cwd inside");
190
+ if (f.builderOpen)
191
+ return keep("builder task open");
192
+ if (f.lastActivityMs >= (f.merged ? Math.max(cutoffMs, mergedCutoffMs) : cutoffMs))
193
+ return keep(f.merged ? "merged, newer than merged cutoff" : "newer than cutoff");
194
+ if (f.detached && f.archiveSha && f.archiveSha !== f.head)
195
+ return keep("archive ref points elsewhere");
196
+ const archive = f.detached && !f.archiveSha ? { ref: f.archiveRef, sha: f.head } : null;
197
+ const reason = f.detached ? "detached" : f.merged ? "merged" : "clean";
198
+ const decision = { action: f.prunable ? "prune" : "remove", reason: f.prunable ? "directory missing" : reason, archive };
199
+ if (f.reflogOnly?.length)
200
+ decision.reflog = f.reflogOnly.map((sha) => ({ ref: `${f.archiveRef}-reflog/${sha}`, sha }));
201
+ return decision;
202
+ }
203
+ /** Decide one builder dir from its facts. Pure: no I/O. */
204
+ export function builderDecision(f, cutoffMs) {
205
+ const keep = (reason) => ({ action: "keep", reason, archive: null });
206
+ if (f.error)
207
+ return keep(`unreadable: ${f.error}`);
208
+ if (!FINAL_PHASES.includes(f.phase))
209
+ return keep(`unsettled: ${f.phase}`);
210
+ if (LIVE_STATES.includes(f.unitActive) || f.unitActive === "unknown")
211
+ return keep(`unit ${f.unitActive}`);
212
+ if (f.pidAlive)
213
+ return keep("process alive");
214
+ if (f.taskOpen)
215
+ return keep("task open");
216
+ if (f.mtimeMs >= cutoffMs)
217
+ return keep("newer than cutoff");
218
+ let archive = null;
219
+ if (f.backExists) {
220
+ if (!f.root)
221
+ return keep("unpreserved commits: no project root");
222
+ if (f.archiveDiverged)
223
+ return keep("archive ref differs from clone");
224
+ if (f.backIgnoredBad?.length)
225
+ return keep(`ignored outside node_modules: ${f.backIgnoredBad[0]}`);
226
+ archive = { id: f.id, backRepo: f.backRepo };
227
+ }
228
+ else if (f.commits > 0 && !f.landed && !f.archiveHead) {
229
+ return keep("unpreserved commits: no clone");
230
+ }
231
+ if (f.bytes === 0 && !archive)
232
+ return keep("nothing to reclaim");
233
+ return { action: "remove", reason: f.phase, archive };
234
+ }
235
+ function gitEnv(env) {
236
+ const next = { ...env };
237
+ for (const key of GIT_ENV_KEYS)
238
+ delete next[key];
239
+ return next;
240
+ }
241
+ function runGit(cwd, args, env) {
242
+ return new Promise((resolve, reject) => {
243
+ execFile("git", ["-C", cwd, ...args], { env: gitEnv(env), timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout, stderr) => {
244
+ if (error) {
245
+ reject(Object.assign(error, { stderr }));
246
+ return;
247
+ }
248
+ resolve(stdout);
249
+ });
250
+ });
251
+ }
252
+ async function revParse(cwd, ref, env) {
253
+ try {
254
+ return (await runGit(cwd, ["rev-parse", "--verify", "--quiet", ref], env)).trim() || null;
255
+ }
256
+ catch {
257
+ return null;
258
+ }
259
+ }
260
+ async function isAncestor(cwd, older, newer, env) {
261
+ try {
262
+ await runGit(cwd, ["merge-base", "--is-ancestor", older, newer], env);
263
+ return true;
264
+ }
265
+ catch {
266
+ return false;
267
+ }
268
+ }
269
+ function isAlive(pid) {
270
+ try {
271
+ process.kill(pid, 0);
272
+ }
273
+ catch (error) {
274
+ return error.code !== "ESRCH";
275
+ }
276
+ return true;
277
+ }
278
+ function oneLine(text) {
279
+ return String(text).replace(/\s+/g, " ").trim();
280
+ }
281
+ function builderIds(root) {
282
+ if (!existsSync(root))
283
+ return [];
284
+ return readdirSync(root).filter((id) => {
285
+ if (id === "." || id === ".." || id !== path.basename(id) || id.includes("\0"))
286
+ return false;
287
+ try {
288
+ return lstatSync(path.join(root, id)).isDirectory();
289
+ }
290
+ catch {
291
+ return false;
292
+ }
293
+ });
294
+ }
295
+ /** True while a builder's task is open: unknown tasks are closed, an unreadable store is open. */
296
+ export function taskIsOpen(state, env) {
297
+ if (typeof state.task !== "string" || typeof state.project !== "string")
298
+ return false;
299
+ try {
300
+ const task = openTasks(state.project, env).get(state.task);
301
+ return task.status !== "done";
302
+ }
303
+ catch (error) {
304
+ return !(error instanceof TaskNotFoundError);
305
+ }
306
+ }
307
+ // Where node_modules sits at the worktree top: "link", "dir", "file" or "none".
308
+ function nodeModulesKind(wtPath) {
309
+ try {
310
+ const info = lstatSync(path.join(wtPath, "node_modules"));
311
+ if (info.isSymbolicLink())
312
+ return "link";
313
+ return info.isDirectory() ? "dir" : "file";
314
+ }
315
+ catch {
316
+ return "none";
317
+ }
318
+ }
319
+ /** Reads a builder's state and facts. Pure apart from the reads. */
320
+ async function gatherBuilder(id, ctx) {
321
+ const { env } = ctx;
322
+ const paths = builderPaths(id, env);
323
+ const f = { id, error: "", phase: "", commits: 0, landed: false, root: null, mtimeMs: 0, unitActive: "", pidAlive: false,
324
+ taskOpen: false, bulk: [], bytes: 0, worktree: "", backExists: false, backRepo: "", backSha: null, archiveHead: null, archiveDiverged: false };
325
+ let state;
326
+ try {
327
+ state = JSON.parse(readFileSync(paths.state, "utf8"));
328
+ f.mtimeMs = statSync(paths.state).mtimeMs;
329
+ }
330
+ catch {
331
+ f.error = "state.json unreadable";
332
+ return f;
333
+ }
334
+ f.phase = state.phase;
335
+ f.commits = state.commits ?? 0;
336
+ f.landed = Boolean(state.landed);
337
+ f.root = typeof state.root === "string" ? state.root : null;
338
+ f.worktree = typeof state.worktree === "string" ? state.worktree : "";
339
+ f.unitActive = await unitState(paths.unit, env);
340
+ f.pidAlive = Number.isSafeInteger(state.pid) && state.pid > 0 && isAlive(state.pid);
341
+ f.taskOpen = ctx.taskOpen(state);
342
+ f.bulk = builderBulkTargets(paths.dir).map((target) => ({ ...target, bytes: treeBytes(target.path) }));
343
+ f.bytes = f.bulk.reduce((sum, target) => sum + target.bytes, 0);
344
+ if (f.worktree) {
345
+ f.backRepo = path.join(paths.dir, "back", path.basename(f.worktree));
346
+ f.backExists = existsSync(path.join(f.backRepo, ".git"));
347
+ }
348
+ if (f.backExists) {
349
+ try {
350
+ const lines = (await runGit(f.backRepo, ["--no-optional-locks", "status", "--porcelain", "--untracked-files=all", "--ignored=matching"], env))
351
+ .split("\n").filter(Boolean);
352
+ f.backIgnoredBad = lines.filter((line) => line.startsWith("!! ")).map((line) => line.slice(3))
353
+ .filter((file) => !/^node_modules(\/|$)/.test(file));
354
+ }
355
+ catch (error) {
356
+ f.error = oneLine(error.stderr || error.message);
357
+ }
358
+ }
359
+ if (f.backExists && f.root) {
360
+ f.backSha = await revParse(f.backRepo, "HEAD", env);
361
+ f.archiveHead = await revParse(f.root, `${ARCHIVE_NS}/${id}/HEAD`, env);
362
+ f.archiveDiverged = Boolean(f.archiveHead && f.backSha && !(await isAncestor(f.root, f.archiveHead, f.backSha, env)));
363
+ }
364
+ else if (f.root) {
365
+ f.archiveHead = await revParse(f.root, `${ARCHIVE_NS}/${id}/HEAD`, env);
366
+ }
367
+ return f;
368
+ }
369
+ /** Tips of the worktree's HEAD reflog commits (other than HEAD) that no ref reaches; archiving the tips keeps every such commit. */
370
+ async function reflogOnlyCommits(root, admin, head, env) {
371
+ if (!admin)
372
+ return [];
373
+ const log = path.join(admin, "logs", "HEAD");
374
+ if (!existsSync(log))
375
+ return [];
376
+ const shas = new Set();
377
+ for (const line of readFileSync(log, "utf8").split("\n")) {
378
+ const match = /^([0-9a-f]{40}) ([0-9a-f]{40}) /.exec(line);
379
+ if (match)
380
+ shas.add(match[2]);
381
+ }
382
+ shas.delete(head);
383
+ shas.delete("0".repeat(40));
384
+ if (!shas.size)
385
+ return [];
386
+ const unreachable = new Set((await runGit(root, ["rev-list", ...shas, "--not", "--all"], env)).split("\n").filter(Boolean));
387
+ const entries = [...shas].filter((sha) => unreachable.has(sha));
388
+ if (!entries.length)
389
+ return [];
390
+ return (await runGit(root, ["merge-base", "--independent", ...entries], env)).split("\n").filter(Boolean);
391
+ }
392
+ /** True when `head` is in `mainSha`: an ancestor, every commit patch-equivalent, or the tip of a merged PR for `branch`. */
393
+ async function isMerged(root, head, branch, ctx) {
394
+ if (!ctx.mainSha || !head)
395
+ return false;
396
+ if (await isAncestor(root, head, ctx.mainSha, ctx.env))
397
+ return true;
398
+ let cherry = [];
399
+ try {
400
+ cherry = (await runGit(root, ["cherry", ctx.mainSha, head], ctx.env)).split("\n").filter(Boolean);
401
+ }
402
+ catch { /* fall through to the PR signal */ }
403
+ if (cherry.length && cherry.every((line) => line.startsWith("- ")))
404
+ return true;
405
+ const name = branch?.replace(/^refs\/heads\//, "");
406
+ return Boolean(name && ctx.mergedPrs?.get(name)?.has(head));
407
+ }
408
+ /** Fetches origin and returns the sha of its default branch; null when there is no origin or the fetch fails. */
409
+ export async function fetchMainSha(root, env) {
410
+ try {
411
+ await runGit(root, ["remote", "get-url", "origin"], env);
412
+ await runGit(root, ["fetch", "--quiet", "origin"], env);
413
+ }
414
+ catch {
415
+ return null;
416
+ }
417
+ let ref = "refs/remotes/origin/main";
418
+ try {
419
+ ref = (await runGit(root, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"], env)).trim() || ref;
420
+ }
421
+ catch { /* no origin/HEAD: use origin/main */ }
422
+ return revParse(root, `${ref}^{commit}`, env);
423
+ }
424
+ /** Merged PR heads from `gh`; null when gh is missing, unauthenticated, or the repo is not on GitHub. */
425
+ export function mergedPrHeads(root, env) {
426
+ const args = ["pr", "list", "--state", "merged", "--limit", GH_PR_LIMIT, "--json", "headRefName,headRefOid"];
427
+ return new Promise((resolve) => {
428
+ execFile("gh", args, { cwd: root, env: gitEnv(env), timeout: GH_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, (error, stdout) => {
429
+ if (error)
430
+ return resolve(null);
431
+ try {
432
+ const heads = new Map();
433
+ for (const pr of JSON.parse(stdout)) {
434
+ heads.set(pr.headRefName, (heads.get(pr.headRefName) ?? new Set()).add(pr.headRefOid));
435
+ }
436
+ resolve(heads);
437
+ }
438
+ catch {
439
+ resolve(null);
440
+ }
441
+ });
442
+ });
443
+ }
444
+ async function adminDirOf(wt, root, env) {
445
+ if (wt.prunable) {
446
+ const common = (await runGit(root, ["rev-parse", "--git-common-dir"], env)).trim();
447
+ return path.join(path.resolve(root, common), "worktrees", path.basename(wt.path));
448
+ }
449
+ try {
450
+ return (await runGit(wt.path, ["rev-parse", "--absolute-git-dir"], env)).trim();
451
+ }
452
+ catch {
453
+ return null;
454
+ }
455
+ }
456
+ // The top-level target/ of a Cargo worktree, as a scan skip list.
457
+ function cargoTarget(wtPath) {
458
+ return existsSync(path.join(wtPath, "Cargo.toml")) ? [path.join(wtPath, "target")] : [];
459
+ }
460
+ // Newest of: HEAD commit, directory and file mtimes, index, HEAD reflog, and any session seen inside.
461
+ async function activityMs(wt, admin, ctx) {
462
+ const times = [0];
463
+ if (wt.head) {
464
+ try {
465
+ times.push(Number((await runGit(ctx.root, ["log", "-1", "--format=%ct", wt.head], ctx.env)).trim() || 0) * 1000);
466
+ }
467
+ catch {
468
+ times.push(Infinity);
469
+ }
470
+ }
471
+ if (existsSync(wt.path))
472
+ times.push(statSync(wt.path).mtimeMs, newestFileMs(wt.path, SCAN_MAX_ENTRIES, cargoTarget(wt.path)));
473
+ if (admin && existsSync(path.join(admin, "index")))
474
+ times.push(statSync(path.join(admin, "index")).mtimeMs);
475
+ if (admin && existsSync(path.join(admin, "logs", "HEAD"))) {
476
+ for (const match of readFileSync(path.join(admin, "logs", "HEAD"), "utf8").matchAll(/ (\d{9,11}) [+-]\d{4}\t/g))
477
+ times.push(Number(match[1]) * 1000);
478
+ }
479
+ for (const session of ctx.sessions()) {
480
+ if (session.unreadable)
481
+ times.push(Infinity);
482
+ const inside = session.cwd === wt.path || session.cwd?.startsWith(wt.path + path.sep);
483
+ if (inside)
484
+ times.push(session.live ? Infinity : session.seenAt ?? Infinity);
485
+ }
486
+ return Math.max(...times);
487
+ }
488
+ /** Reads one worktree's facts. Pure apart from the reads. */
489
+ async function gatherWorktree(wt, index, worktrees, ctx) {
490
+ const { env, root } = ctx;
491
+ const f = { main: index === 0, protected: isProtectedCheckout(wt.path, root), locked: wt.locked, prunable: wt.prunable,
492
+ detached: wt.detached, head: wt.head, path: wt.path, error: "", dirty: 0, ignoredBad: [], reflogOnly: [], inUse: false,
493
+ builderOpen: ctx.builderWorktrees.has(wt.path), nested: "", lastActivityMs: Infinity,
494
+ archiveRef: `${ARCHIVE_NS}/wt-${path.basename(wt.path)}`, archiveSha: null };
495
+ f.nested = worktrees.filter((other) => other.path !== wt.path && other.path.startsWith(wt.path + path.sep))
496
+ .map((other) => path.basename(other.path))[0] ?? "";
497
+ if (f.main)
498
+ return f;
499
+ const cwds = ctx.liveCwds();
500
+ f.inUse = cwds.some((cwd) => cwd === wt.path || cwd.startsWith(wt.path + path.sep));
501
+ const admin = await adminDirOf(wt, root, env);
502
+ try {
503
+ if (!wt.prunable) {
504
+ const lines = (await runGit(wt.path, ["--no-optional-locks", "status", "--porcelain", "--untracked-files=all", "--ignored=matching"], env))
505
+ .split("\n").filter(Boolean);
506
+ const ignored = lines.filter((line) => line.startsWith("!! ")).map((line) => line.slice(3));
507
+ const tracked = lines.filter((line) => !line.startsWith("!! "));
508
+ const linkOnly = nodeModulesKind(wt.path) === "link" && tracked.filter((line) => line === "?? node_modules").length === 1;
509
+ f.dirty = tracked.length - (linkOnly ? 1 : 0);
510
+ const cargo = existsSync(path.join(wt.path, "Cargo.toml"));
511
+ f.ignoredBad = ignored.filter((file) => !isAllowedIgnored(file, { cargo }));
512
+ }
513
+ f.reflogOnly = await reflogOnlyCommits(root, admin, wt.head, env);
514
+ f.lastActivityMs = await activityMs(wt, admin, ctx);
515
+ f.merged = await isMerged(root, wt.head, wt.branch, ctx);
516
+ }
517
+ catch (error) {
518
+ f.error = oneLine(error.stderr || error.message);
519
+ }
520
+ if (wt.detached)
521
+ f.archiveSha = await revParse(root, f.archiveRef, env);
522
+ return f;
523
+ }
524
+ // Archives a builder's clone: commits uncommitted work, then copies every branch and HEAD into the project repo.
525
+ async function archiveBuilder(archive, ctx) {
526
+ const ref = `${ARCHIVE_NS}/${archive.id}`;
527
+ if ((await runGit(archive.backRepo, ["status", "--porcelain"], ctx.env)).trim()) {
528
+ await runGit(archive.backRepo, ["add", "-A", "--", ".", ":!node_modules"], ctx.env);
529
+ const identity = await commitIdentity({ git: (repo, args) => runGit(repo, args, ctx.env), repo: archive.backRepo });
530
+ await runGit(archive.backRepo, [...identity, "-c", "core.hooksPath=/dev/null", "commit", "-q", "-m", "prune: archive uncommitted work"], ctx.env);
531
+ }
532
+ const sha = (await runGit(archive.backRepo, ["rev-parse", "HEAD"], ctx.env)).trim();
533
+ const refspecs = [`refs/heads/*:${ref}/heads/*`, `refs/tags/*:${ref}/tags/*`, `HEAD:${ref}/HEAD`];
534
+ if (await revParse(archive.backRepo, "refs/stash", ctx.env))
535
+ refspecs.push(`refs/stash:${ref}/stash`);
536
+ await runGit(ctx.root, ["fetch", "--quiet", "--no-tags", archive.backRepo, ...refspecs], ctx.env);
537
+ if (await revParse(ctx.root, `${ref}/HEAD`, ctx.env) !== sha)
538
+ throw new Error(`could not verify ${ref}/HEAD`);
539
+ return { ref: `${ref}/HEAD`, sha };
540
+ }
541
+ async function setRef(root, ref, sha, env) {
542
+ await runGit(root, ["update-ref", ref, sha], env);
543
+ if (await revParse(root, ref, env) !== sha)
544
+ throw new Error(`could not verify ${ref}`);
545
+ }
546
+ function removeTargets(dir, targets) {
547
+ for (const target of targets) {
548
+ if (path.dirname(target.path) !== dir)
549
+ throw new Error(`refusing to remove ${target.path}`);
550
+ rmSync(target.path, { recursive: true, force: true });
551
+ }
552
+ }
553
+ // Removes the worktree. A refused removal unlinks only its node_modules symlink, then retries; a failed retry restores the link.
554
+ async function removeWorktree(root, wtPath, env) {
555
+ try {
556
+ await runGit(root, ["worktree", "remove", wtPath], env);
557
+ }
558
+ catch (error) {
559
+ const link = path.join(wtPath, "node_modules");
560
+ if (nodeModulesKind(wtPath) !== "link")
561
+ throw error;
562
+ const target = readlinkSync(link);
563
+ unlinkSync(link);
564
+ try {
565
+ await runGit(root, ["worktree", "remove", wtPath], env);
566
+ }
567
+ catch (retryError) {
568
+ symlinkSync(target, link);
569
+ throw retryError;
570
+ }
571
+ }
572
+ }
573
+ function addCategory(categories, kind, bytes) {
574
+ const entry = categories[kind] ?? { count: 0, bytes: 0 };
575
+ categories[kind] = { count: entry.count + 1, bytes: entry.bytes + bytes };
576
+ }
577
+ /** Plan (and with `apply`, carry out) the prune for one repo and, unless `builders` is false, its builder state. */
578
+ export async function pruneRepo({ env, root, olderThanMs, mergedOlderThanMs = parseAge(DEFAULT_MERGED_CUTOFF), apply, now = Date.now(), cwds = readLiveCwds, sessions = () => [], taskOpen = (state) => taskIsOpen(state, env), builders: withBuilders = true }) {
579
+ if (olderThanMs < MIN_CUTOFF_MS)
580
+ throw new Error("cutoff must be at least 24h");
581
+ if (mergedOlderThanMs < MIN_MERGED_CUTOFF_MS)
582
+ throw new Error("merged cutoff must be at least 30m");
583
+ const cutoffMs = now - olderThanMs;
584
+ const mergedCutoffMs = now - mergedOlderThanMs;
585
+ const liveCwds = () => (typeof cwds === "function" ? cwds() : cwds);
586
+ const ctx = { env, root, liveCwds, sessions, taskOpen, builderWorktrees: new Set(), mainSha: null, mergedPrs: null };
587
+ const summary = { mode: apply ? "apply" : "dry-run", cutoff: new Date(cutoffMs).toISOString(),
588
+ mergedCutoff: new Date(mergedCutoffMs).toISOString(), mergedBase: {}, reclaimedBytes: 0,
589
+ categories: {}, builders: [], worktrees: [], archives: [], skipped: [], skipReasons: {} };
590
+ const skip = (kind, key, reason) => summary.skipped.push({ kind, key, reason });
591
+ const buildersRoot = path.join(stateDir(env), "builders");
592
+ const builders = [];
593
+ for (const id of withBuilders ? builderIds(buildersRoot) : [])
594
+ builders.push(await gatherBuilder(id, ctx));
595
+ ctx.builderWorktrees = new Set(builders.filter((f) => f.taskOpen && f.worktree).map((f) => f.worktree));
596
+ for (const f of builders) {
597
+ const decision = builderDecision(f, cutoffMs);
598
+ if (decision.action === "keep") {
599
+ skip("builder", f.id, decision.reason);
600
+ continue;
601
+ }
602
+ let current = f;
603
+ let archived = null;
604
+ try {
605
+ if (apply) {
606
+ current = await gatherBuilder(f.id, ctx);
607
+ const again = builderDecision(current, cutoffMs);
608
+ if (again.action !== "remove") {
609
+ skip("builder", f.id, again.reason);
610
+ continue;
611
+ }
612
+ if (again.archive)
613
+ archived = await archiveBuilder(again.archive, ctx);
614
+ removeTargets(builderPaths(f.id, env).dir, current.bulk);
615
+ }
616
+ else if (decision.archive) {
617
+ archived = { ref: `${ARCHIVE_NS}/${f.id}/HEAD`, sha: f.backSha };
618
+ }
619
+ }
620
+ catch (error) {
621
+ skip("builder", f.id, `remove failed: ${oneLine(error.message)}`);
622
+ continue;
623
+ }
624
+ if (archived)
625
+ summary.archives.push({ ref: archived.ref, sha: archived.sha, source: f.id });
626
+ for (const target of current.bulk)
627
+ addCategory(summary.categories, target.kind, target.bytes);
628
+ summary.builders.push({ id: f.id, phase: f.phase, bytes: f.bytes, targets: f.bulk.map((t) => t.kind) });
629
+ summary.reclaimedBytes += f.bytes;
630
+ }
631
+ ctx.mainSha = await fetchMainSha(root, env);
632
+ if (ctx.mainSha)
633
+ ctx.mergedPrs = await mergedPrHeads(root, env);
634
+ summary.mergedBase[root] = ctx.mainSha;
635
+ const worktrees = parseWorktreeList(await runGit(root, ["worktree", "list", "--porcelain"], env));
636
+ const keptPrunable = [];
637
+ for (const [index, wt] of worktrees.entries()) {
638
+ const f = await gatherWorktree(wt, index, worktrees, ctx);
639
+ const decision = worktreeDecision(f, cutoffMs, mergedCutoffMs);
640
+ if (decision.action === "keep") {
641
+ skip("worktree", wt.path, decision.reason);
642
+ if (wt.prunable && !wt.locked)
643
+ keptPrunable.push(wt.path);
644
+ continue;
645
+ }
646
+ const bytes = existsSync(wt.path) ? treeBytes(wt.path) : 0;
647
+ let final = decision;
648
+ try {
649
+ if (apply && decision.action === "remove") {
650
+ const verdict = await lockedRecheck(wt, index, worktrees, ctx, cutoffMs, mergedCutoffMs);
651
+ if (verdict.action !== "remove") {
652
+ skip("worktree", wt.path, verdict.reason);
653
+ continue;
654
+ }
655
+ final = verdict;
656
+ await removeWorktree(root, wt.path, env);
657
+ }
658
+ else if (apply) {
659
+ for (const ref of archivesOf(decision))
660
+ await setRef(root, ref.ref, ref.sha, env);
661
+ }
662
+ }
663
+ catch (error) {
664
+ skip("worktree", wt.path, `remove failed: ${oneLine(error.stderr || error.message)}`);
665
+ continue;
666
+ }
667
+ for (const ref of archivesOf(final))
668
+ summary.archives.push({ ref: ref.ref, sha: ref.sha, source: wt.path });
669
+ if (decision.action === "remove")
670
+ addCategory(summary.categories, "worktrees", bytes);
671
+ summary.worktrees.push({ path: wt.path, branch: wt.branch, detached: wt.detached, bytes: decision.action === "remove" ? bytes : 0, action: decision.action });
672
+ summary.reclaimedBytes += decision.action === "remove" ? bytes : 0;
673
+ }
674
+ if (apply)
675
+ await pruneEntries(root, keptPrunable, env);
676
+ for (const item of summary.skipped) {
677
+ const key = item.reason.split(":")[0];
678
+ summary.skipReasons[key] = (summary.skipReasons[key] ?? 0) + 1;
679
+ }
680
+ return summary;
681
+ }
682
+ // The detached HEAD archive and the reflog archives a decision writes before removal.
683
+ function archivesOf(decision) {
684
+ return [...(decision.archive ? [decision.archive] : []), ...(decision.reflog ?? [])];
685
+ }
686
+ // Re-reads every rule under a lock and writes the archives; the lock is released on every path, including a failed archive.
687
+ async function lockedRecheck(wt, index, worktrees, ctx, cutoffMs, mergedCutoffMs) {
688
+ const { env, root } = ctx;
689
+ await runGit(root, ["worktree", "lock", "--reason", LOCK_REASON, wt.path], env);
690
+ let verdict;
691
+ try {
692
+ verdict = worktreeDecision(await gatherWorktree(wt, index, worktrees, ctx), cutoffMs, mergedCutoffMs);
693
+ if (verdict.action === "remove")
694
+ for (const ref of archivesOf(verdict))
695
+ await setRef(root, ref.ref, ref.sha, env);
696
+ }
697
+ finally {
698
+ await runGit(root, ["worktree", "unlock", wt.path], env);
699
+ }
700
+ return verdict;
701
+ }
702
+ // Removes the admin entries of missing worktrees that were chosen; locks the kept ones so git leaves them.
703
+ async function pruneEntries(root, keptPrunable, env) {
704
+ for (const kept of keptPrunable)
705
+ await runGit(root, ["worktree", "lock", "--reason", LOCK_REASON, kept], env);
706
+ await runGit(root, ["worktree", "prune"], env);
707
+ for (const kept of keptPrunable)
708
+ await runGit(root, ["worktree", "unlock", kept], env);
709
+ }
710
+ function formatBytes(bytes) {
711
+ if (bytes >= 1e9)
712
+ return `${(bytes / 1e9).toFixed(2)} GB`;
713
+ if (bytes >= 1e6)
714
+ return `${(bytes / 1e6).toFixed(2)} MB`;
715
+ return `${bytes} B`;
716
+ }
717
+ /** One line for logs and schedule records: mode, bytes, counts, and the three most common skip reasons. */
718
+ export function summaryLine(summary) {
719
+ const mode = summary.mode === "apply" ? "applied" : "dry run";
720
+ const verb = summary.mode === "apply" ? "reclaimed" : "reclaimable";
721
+ const categories = Object.entries(summary.categories).map(([kind, entry]) => `${kind} ${entry.count}`).join(", ");
722
+ const top = Object.entries(summary.skipReasons).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([reason, count]) => `${reason} ${count}`).join(", ");
723
+ const removed = summary.worktrees.filter((w) => w.action === "remove").length;
724
+ return `prune ${mode}: ${verb} ${formatBytes(summary.reclaimedBytes)}; builders ${summary.builders.length}`
725
+ + `${categories ? ` (${categories})` : ""}; worktrees ${removed}; archives ${summary.archives.length}`
726
+ + `; skipped ${summary.skipped.length}${top ? ` (${top})` : ""}`;
727
+ }
728
+ /** Human-readable report for `prune`. */
729
+ export function renderPrune(summary) {
730
+ const lines = [
731
+ summary.mode === "apply" ? "prune: applied" : "prune: dry run, nothing deleted (pass --apply to delete)",
732
+ `cutoff ${summary.cutoff}`,
733
+ `builders: ${summary.builders.length} to prune`,
734
+ ];
735
+ for (const [kind, entry] of Object.entries(summary.categories))
736
+ lines.push(` ${kind}: ${entry.count} (${formatBytes(entry.bytes)})`);
737
+ lines.push(`worktrees: ${summary.worktrees.filter((w) => w.action === "remove").length} to remove`);
738
+ lines.push(`archive refs: ${summary.archives.length}`);
739
+ lines.push(`reclaimable: ${formatBytes(summary.reclaimedBytes)}`);
740
+ lines.push(`skipped: ${summary.skipped.length}`);
741
+ for (const [reason, count] of Object.entries(summary.skipReasons))
742
+ lines.push(` ${reason}: ${count}`);
743
+ for (const item of summary.skipped)
744
+ lines.push(` ${item.kind} ${item.key}: ${item.reason}`);
745
+ return `${lines.join("\n")}\n`;
746
+ }
747
+ /** Adds `next` into `into`: totals, categories, skip reasons and lists. */
748
+ export function mergeSummaries(into, next) {
749
+ into.reclaimedBytes += next.reclaimedBytes;
750
+ for (const [kind, entry] of Object.entries(next.categories)) {
751
+ const have = into.categories[kind] ?? { count: 0, bytes: 0 };
752
+ into.categories[kind] = { count: have.count + entry.count, bytes: have.bytes + entry.bytes };
753
+ }
754
+ for (const [reason, count] of Object.entries(next.skipReasons))
755
+ into.skipReasons[reason] = (into.skipReasons[reason] ?? 0) + count;
756
+ Object.assign(into.mergedBase, next.mergedBase);
757
+ into.builders.push(...next.builders);
758
+ into.worktrees.push(...next.worktrees);
759
+ into.archives.push(...next.archives);
760
+ into.skipped.push(...next.skipped);
761
+ return into;
762
+ }
763
+ /** `temmo prune [--apply] [--older-than 7d] [--merged-older-than 1h] [--repo <path>]... [--json]`. */
764
+ export async function prune(argv, { env, cfg, out, err }) {
765
+ const flags = parsePruneArgs(argv);
766
+ if (!flags) {
767
+ err.write(`temmo: ${USAGE}\n`);
768
+ return 2;
769
+ }
770
+ try {
771
+ const root = projectRoot(cfg.project, env);
772
+ const base = { env, olderThanMs: flags.olderThanMs, mergedOlderThanMs: flags.mergedOlderThanMs, apply: flags.apply, sessions: () => sessionRecords(cfg) };
773
+ const summary = await pruneRepo({ ...base, root });
774
+ for (const repo of new Set(flags.repos.map((p) => path.resolve(p)))) {
775
+ if (isProtectedCheckout(repo, root))
776
+ continue;
777
+ try {
778
+ mergeSummaries(summary, await pruneRepo({ ...base, root: repo, builders: false }));
779
+ }
780
+ catch (error) {
781
+ summary.skipped.push({ kind: "repo", key: repo, reason: `unreadable: ${oneLine(error.stderr || error.message)}` });
782
+ summary.skipReasons.unreadable = (summary.skipReasons.unreadable ?? 0) + 1;
783
+ }
784
+ }
785
+ out.write(flags.json ? `${JSON.stringify(summary, null, 2)}\n` : renderPrune(summary));
786
+ err.write(`${summaryLine(summary)}\n`);
787
+ return 0;
788
+ }
789
+ catch (error) {
790
+ err.write(`temmo: prune: ${error.message}\n`);
791
+ return 1;
792
+ }
793
+ }