synabun 2.3.1 → 2.4.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 (356) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +169 -0
  4. package/browser-extension/engine.js +477 -0
  5. package/browser-extension/icons/icon-128.png +0 -0
  6. package/browser-extension/icons/icon-16.png +0 -0
  7. package/browser-extension/icons/icon-32.png +0 -0
  8. package/browser-extension/icons/icon-48.png +0 -0
  9. package/browser-extension/icons/status-off-16.png +0 -0
  10. package/browser-extension/icons/status-off-32.png +0 -0
  11. package/browser-extension/icons/status-off-48.png +0 -0
  12. package/browser-extension/icons/status-on-16.png +0 -0
  13. package/browser-extension/icons/status-on-32.png +0 -0
  14. package/browser-extension/icons/status-on-48.png +0 -0
  15. package/browser-extension/manifest.json +56 -0
  16. package/browser-extension/popup-strings.js +244 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +165 -0
  19. package/browser-extension/popup.html +105 -0
  20. package/browser-extension/popup.js +347 -0
  21. package/browser-extension/protocol.js +226 -0
  22. package/browser-extension/service-worker.js +267 -0
  23. package/browser-extension/setup-content.js +36 -0
  24. package/browser-extension/tokens.css +326 -0
  25. package/docs/browser-extension-bridge.md +84 -0
  26. package/docs/whatsapp.md +1 -1
  27. package/mcp-server/dist/http.d.ts +2 -0
  28. package/mcp-server/dist/http.d.ts.map +1 -1
  29. package/mcp-server/dist/http.js +9 -1
  30. package/mcp-server/dist/http.js.map +1 -1
  31. package/mcp-server/dist/index.d.ts +11 -0
  32. package/mcp-server/dist/index.d.ts.map +1 -1
  33. package/mcp-server/dist/index.js +38 -3
  34. package/mcp-server/dist/index.js.map +1 -1
  35. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  36. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  38. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  39. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  40. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  41. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +94 -3
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +168 -23
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/team-context.d.ts +18 -0
  47. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  48. package/mcp-server/dist/services/team-context.js +29 -0
  49. package/mcp-server/dist/services/team-context.js.map +1 -0
  50. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  51. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  52. package/mcp-server/dist/services/tool-catalog.js +22 -6
  53. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  54. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  55. package/mcp-server/dist/services/tool-list.js +4 -0
  56. package/mcp-server/dist/services/tool-list.js.map +1 -1
  57. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  58. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.js +18 -1
  60. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  61. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  62. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/agent-definition.js +483 -0
  64. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  65. package/mcp-server/dist/tools/agents.d.ts +91 -9
  66. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  67. package/mcp-server/dist/tools/agents.js +161 -20
  68. package/mcp-server/dist/tools/agents.js.map +1 -1
  69. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  70. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  72. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  73. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  74. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.js +283 -2
  76. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  77. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  78. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.js +22 -5
  80. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  81. package/mcp-server/dist/tools/team.d.ts +32 -0
  82. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  83. package/mcp-server/dist/tools/team.js +87 -0
  84. package/mcp-server/dist/tools/team.js.map +1 -0
  85. package/mcp-server/package-lock.json +2 -2
  86. package/mcp-server/package.json +1 -1
  87. package/mcp-server/src/http.ts +9 -1
  88. package/mcp-server/src/index.ts +34 -4
  89. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  90. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  91. package/mcp-server/src/services/neural-interface.ts +190 -29
  92. package/mcp-server/src/services/team-context.ts +27 -0
  93. package/mcp-server/src/services/tool-catalog.ts +26 -8
  94. package/mcp-server/src/services/tool-list.ts +4 -0
  95. package/mcp-server/src/services/tool-runtime.ts +21 -2
  96. package/mcp-server/src/tools/agent-definition.ts +458 -0
  97. package/mcp-server/src/tools/agents.ts +175 -19
  98. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  99. package/mcp-server/src/tools/git-tools.ts +249 -3
  100. package/mcp-server/src/tools/morelogin.ts +20 -5
  101. package/mcp-server/src/tools/team.ts +97 -0
  102. package/neural-interface/i18n/en.json +1117 -47
  103. package/neural-interface/i18n/pt-BR.json +1117 -47
  104. package/neural-interface/lib/account-usage.js +1 -1
  105. package/neural-interface/lib/agents/density.js +101 -0
  106. package/neural-interface/lib/agents/forge-host.js +223 -0
  107. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  108. package/neural-interface/lib/agents/native-export.js +365 -0
  109. package/neural-interface/lib/agents/registry.js +840 -0
  110. package/neural-interface/lib/agents/resolve.js +544 -0
  111. package/neural-interface/lib/agents/schema.js +642 -0
  112. package/neural-interface/lib/agents/split.js +37 -0
  113. package/neural-interface/lib/agents-studio-api.js +591 -0
  114. package/neural-interface/lib/assistant-api.js +76 -7
  115. package/neural-interface/lib/assistant-catalog.js +2 -0
  116. package/neural-interface/lib/assistant-continuity.js +49 -0
  117. package/neural-interface/lib/assistant-dispatch.js +229 -102
  118. package/neural-interface/lib/assistant-persona.js +105 -8
  119. package/neural-interface/lib/assistant-route-gate.js +24 -9
  120. package/neural-interface/lib/assistant-router.js +384 -42
  121. package/neural-interface/lib/assistant-run-tail.js +151 -0
  122. package/neural-interface/lib/assistant-run-wait.js +183 -0
  123. package/neural-interface/lib/assistant-runtime.js +440 -93
  124. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  125. package/neural-interface/lib/assistant-usage.js +3 -2
  126. package/neural-interface/lib/automation-approval.js +2 -2
  127. package/neural-interface/lib/browser-close-evidence.js +80 -0
  128. package/neural-interface/lib/browser-default.js +210 -0
  129. package/neural-interface/lib/browser-extension-adapter.js +255 -0
  130. package/neural-interface/lib/browser-extension-bridge.js +418 -0
  131. package/neural-interface/lib/browser-extension-folder.js +116 -0
  132. package/neural-interface/lib/browser-extension-setup.js +140 -0
  133. package/neural-interface/lib/browser-profile-choices.js +3 -3
  134. package/neural-interface/lib/browser-tool-policy.js +1 -1
  135. package/neural-interface/lib/claude-account-links.js +301 -0
  136. package/neural-interface/lib/claude-accounts.js +45 -20
  137. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  138. package/neural-interface/lib/claude-model-catalog.js +6 -0
  139. package/neural-interface/lib/claude-panel-session.js +33 -0
  140. package/neural-interface/lib/codex-accounts.js +67 -24
  141. package/neural-interface/lib/coordination/README.md +384 -0
  142. package/neural-interface/lib/coordination/service.js +563 -0
  143. package/neural-interface/lib/coordination/store.js +1138 -0
  144. package/neural-interface/lib/db.js +22 -1
  145. package/neural-interface/lib/effort-levels.js +10 -1
  146. package/neural-interface/lib/memory-list-page.js +49 -0
  147. package/neural-interface/lib/memory-list-stamp.js +60 -0
  148. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  149. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  150. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  151. package/neural-interface/lib/morelogin.js +194 -8
  152. package/neural-interface/lib/native-loop-runtime.js +20 -0
  153. package/neural-interface/lib/opencode-build-preflight.js +16 -1
  154. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  155. package/neural-interface/lib/opencode-serve-records.js +14 -9
  156. package/neural-interface/lib/page-session.js +1 -1
  157. package/neural-interface/lib/peer-identity.js +60 -21
  158. package/neural-interface/lib/process-identity.js +68 -7
  159. package/neural-interface/lib/request-gate.js +3 -0
  160. package/neural-interface/lib/screenshot-location.js +33 -0
  161. package/neural-interface/lib/skills/creation.js +1 -1
  162. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  163. package/neural-interface/lib/studio-attention.js +56 -0
  164. package/neural-interface/lib/teams/README.md +382 -0
  165. package/neural-interface/lib/teams/api.js +287 -0
  166. package/neural-interface/lib/teams/brief.js +185 -0
  167. package/neural-interface/lib/teams/claims.js +315 -0
  168. package/neural-interface/lib/teams/git.js +293 -0
  169. package/neural-interface/lib/teams/index.js +122 -0
  170. package/neural-interface/lib/teams/integration.js +580 -0
  171. package/neural-interface/lib/teams/landing.js +184 -0
  172. package/neural-interface/lib/teams/recovery.js +256 -0
  173. package/neural-interface/lib/teams/scheduler.js +1474 -0
  174. package/neural-interface/lib/teams/schema.js +559 -0
  175. package/neural-interface/lib/teams/state.js +181 -0
  176. package/neural-interface/lib/teams/test-runner.js +86 -0
  177. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  178. package/neural-interface/lib/teams/worktrees.js +757 -0
  179. package/neural-interface/lib/tool-permission-choices.js +226 -0
  180. package/neural-interface/lib/whatsapp/cards.js +24 -10
  181. package/neural-interface/lib/worker-confinement.js +206 -6
  182. package/neural-interface/package-lock.json +2 -2
  183. package/neural-interface/package.json +1 -1
  184. package/neural-interface/public/extension-setup.html +107 -0
  185. package/neural-interface/public/index.html +52 -12
  186. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  187. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  188. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  189. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  190. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  191. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  192. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  193. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  194. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  195. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  196. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  197. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  198. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  199. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  200. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  201. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  202. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  203. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  204. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  205. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  206. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  207. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  208. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  209. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  210. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  211. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  212. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  213. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  214. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  215. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  216. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  217. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  218. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  219. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  220. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  221. package/neural-interface/public/shared/assistant/asst-render.js +36 -6
  222. package/neural-interface/public/shared/assistant/asst-route.js +78 -12
  223. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  224. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  225. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  226. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  229. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  230. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  231. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  232. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  233. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  234. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  235. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  236. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  237. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  238. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  239. package/neural-interface/public/shared/code-copy.js +120 -0
  240. package/neural-interface/public/shared/constants.js +7 -0
  241. package/neural-interface/public/shared/context-menu-model.js +1 -0
  242. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  243. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  244. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  245. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  246. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  247. package/neural-interface/public/shared/dom-morph.js +124 -0
  248. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  249. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  250. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  251. package/neural-interface/public/shared/html-shell.js +33 -4
  252. package/neural-interface/public/shared/i18n.js +14 -1
  253. package/neural-interface/public/shared/idle-queue.js +78 -0
  254. package/neural-interface/public/shared/iface-config.js +227 -0
  255. package/neural-interface/public/shared/lazy-module.js +108 -0
  256. package/neural-interface/public/shared/memory-list.js +117 -0
  257. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  258. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  259. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  260. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  261. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  269. package/neural-interface/public/shared/schedules-view.js +2 -2
  270. package/neural-interface/public/shared/session-project-items.js +11 -0
  271. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  272. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  273. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  274. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  275. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  276. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  277. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  278. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  279. package/neural-interface/public/shared/storage.js +6 -1
  280. package/neural-interface/public/shared/studio-attention.js +83 -0
  281. package/neural-interface/public/shared/styles.css +682 -50
  282. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  283. package/neural-interface/public/shared/transcript-rows.js +334 -0
  284. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  285. package/neural-interface/public/shared/ui-agents.js +97 -0
  286. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  287. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  288. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  289. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  290. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  291. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  292. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  293. package/neural-interface/public/shared/ui-games.js +1 -1
  294. package/neural-interface/public/shared/ui-loading.js +12 -1
  295. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  296. package/neural-interface/public/shared/ui-menubar.js +23 -0
  297. package/neural-interface/public/shared/ui-native-loop-router.js +1 -1
  298. package/neural-interface/public/shared/ui-navbar.js +15 -9
  299. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  300. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  301. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  302. package/neural-interface/public/shared/ui-sessions.js +3 -3
  303. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  304. package/neural-interface/public/shared/ui-settings.js +355 -400
  305. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  306. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  307. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  308. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  309. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  310. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  311. package/neural-interface/public/shared/ui-sync.js +5 -0
  312. package/neural-interface/public/shared/ui-terminal.js +13 -9
  313. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  314. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  315. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  316. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  317. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  318. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  319. package/neural-interface/public/shared/window-keys.js +71 -0
  320. package/neural-interface/public/variant/2d/main.js +2 -0
  321. package/neural-interface/public/variant/3d/app.js +620 -0
  322. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  323. package/neural-interface/public/variant/3d/main.js +21 -544
  324. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  325. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  326. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  327. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  328. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  329. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  330. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  331. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  332. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  333. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  334. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  335. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  336. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  337. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  338. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  339. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  340. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  341. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  342. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  343. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  346. package/neural-interface/scripts/boot-graph.mjs +270 -0
  347. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  348. package/neural-interface/server.js +1050 -140
  349. package/npm-shrinkwrap.json +2 -2
  350. package/package.json +3 -1
  351. package/skills/agent-forge/SKILL.md +182 -0
  352. package/skills/agent-forge/evals/evals.json +56 -0
  353. package/skills/agent-forge/references/definition-fields.md +61 -0
  354. package/skills/agent-forge/references/examples.md +105 -0
  355. package/skills/agent-forge/references/instructions.md +51 -0
  356. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -0,0 +1,757 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Teams: managed worktrees
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // A team works in worktrees SynaBun makes and removes, never in the user's checkout and never on the user's branch
6
+ // (owner decision, 2026-11-15). For a plan (lib/teams/schema.js):
7
+ //
8
+ // <project>/.worktrees/<team>/<slice> branch synabun/<team>/<slice> one per slice
9
+ // <project>/.worktrees/<team>/integration branch synabun/<team>/integration where finished slices are joined
10
+ //
11
+ // all cut from one pinned commit: the plan's base, which is the project's HEAD when the team is created unless the
12
+ // plan names one. The user's uncommitted files are not in any of them (a worktree is a checkout of a commit), and
13
+ // nothing here writes the user's checkout, index, stash or branch. `.worktrees/` is added to the repository's own
14
+ // `.git/info/exclude` when the project does not ignore it yet, never to `.gitignore`.
15
+ //
16
+ // What is refused, with a code, changing nothing:
17
+ // NOT_A_GIT_REPOSITORY / PROJECT_NOT_REPO_ROOT / NO_COMMITS the project is not a repository's root with a commit
18
+ // INVALID_PLAN the plan does not pass validateTeamPlan (`errors` lists why)
19
+ // TEAM_EXISTS the team's folder, one of its branches, a worktree registered under its folder or a
20
+ // journal entry is already there. `.worktrees/` also holds worktrees people make by hand
21
+ // (`.worktrees/agents-system`): a team never takes such a name.
22
+ //
23
+ // Removal is conservative. `remove(teamId)` works after a landing, or with `discard: true`; either way a worktree
24
+ // with uncommitted changes and a branch with commits that are nowhere else stay, and are reported, unless
25
+ // `force: true`. What is removed is written to the journal with the commit each branch pointed at.
26
+ //
27
+ // Dependencies are not installed per worktree: `setup` is a step the caller supplies (default: none).
28
+ // `cloneNodeModules()` is one: a copy-on-write clone of the project's ignored node_modules folders, where the file
29
+ // system can clone. Changing dependencies (lockfiles, and with them the manifests) is the lockfile-owner slice's.
30
+
31
+ import { execFile } from 'node:child_process';
32
+ import { appendFileSync, constants as FS, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, statfsSync } from 'node:fs';
33
+ import { copyFile, cp, rm } from 'node:fs/promises';
34
+ import { dirname, isAbsolute, join, posix, resolve } from 'node:path';
35
+ import { promisify } from 'node:util';
36
+ import {
37
+ INTEGRATION_SLICE_ID, WORKTREES_DIR, branchName, integrationBranchName, isTeamSlug, normalizeRelPath, normalizeTeamPlan,
38
+ parseWorktreePath, validateTeamPlan, worktreePath, worktreesRoot,
39
+ } from './schema.js';
40
+ import { gitSaid, line, nulList, parseStatus, parseWorktreeList } from './git.js';
41
+ import { TERMINAL_TEAM_STATES, planPieces, planSlice, refuse, sliceState } from './state.js';
42
+
43
+ const execFileAsync = promisify(execFile);
44
+ const realOf = (path) => { try { return realpathSync(path); } catch { return resolve(path); } };
45
+ const isDirectory = (path) => { try { return lstatSync(path).isDirectory(); } catch { return false; } };
46
+ const present = (path) => { try { lstatSync(path); return true; } catch { return false; } };
47
+
48
+ /** The key under which everything that changes a repository's worktrees and branches takes its turn. */
49
+ export const repoLockKey = (projectPath) => `repo:${realOf(projectPath)}`;
50
+
51
+ /** Slice states from which a slice can be given to a worker for the first time. */
52
+ const FRESH_SLICE_STATES = new Set(['planned', 'pending', 'blocked']);
53
+ /** Slice states from which a worker can be sent back to a slice it already worked. */
54
+ const REWORK_SLICE_STATES = new Set(['running', 'done', 'rejected', 'conflict', 'tests-failed']);
55
+
56
+ // ── asking git ───────────────────────────────────────────────────────────────
57
+
58
+ /** The commit a revision names, or null. */
59
+ export async function commitOf(git, cwd, revision) {
60
+ return line(await git(['rev-parse', '--verify', '--quiet', `${revision}^{commit}`], { cwd })) || null;
61
+ }
62
+
63
+ /** Does this branch exist? */
64
+ export async function branchExists(git, cwd, branch) {
65
+ return (await git(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], { cwd })).ok;
66
+ }
67
+
68
+ /**
69
+ * The branch a folder is on, when the folder is a worktree of its own: git's top level for it is the folder itself.
70
+ * Null for a folder that is not one (git asked inside a plain folder answers for the repository around it, which
71
+ * here is the user's checkout: nothing a team does may be aimed at it by such an answer), and for a detached HEAD.
72
+ */
73
+ export async function branchAt(git, path) {
74
+ if (!isDirectory(path)) return null;
75
+ const top = line(await git(['rev-parse', '--show-toplevel'], { cwd: path }));
76
+ if (!top || realOf(top) !== realOf(path)) return null;
77
+ return line(await git(['symbolic-ref', '--short', '-q', 'HEAD'], { cwd: path })) || null;
78
+ }
79
+
80
+ /** Every worktree the repository knows. */
81
+ export async function listWorktrees(git, cwd) {
82
+ const result = await git(['worktree', 'list', '--porcelain'], { cwd });
83
+ return result.ok ? parseWorktreeList(result.stdout) : [];
84
+ }
85
+
86
+ /** The uncommitted changes of a checkout: `{ path, index, worktree, from? }` each (untracked files one by one). */
87
+ export async function changesOf(git, cwd) {
88
+ const result = await git(['status', '--porcelain=v1', '-z', '--untracked-files=all'], { cwd });
89
+ return result.ok ? parseStatus(result.stdout) : null;
90
+ }
91
+
92
+ /** `[ahead, behind]` of `head` against `other`, or null. */
93
+ async function aheadBehind(git, cwd, other, head) {
94
+ const result = await git(['rev-list', '--left-right', '--count', `${other}...${head}`], { cwd });
95
+ const match = /^(\d+)\s+(\d+)/.exec(result.stdout || '');
96
+ return result.ok && match ? { ahead: Number(match[2]), behind: Number(match[1]) } : null;
97
+ }
98
+
99
+ /** How many commits of `limit..head` have no equal change in `upstream` (git cherry's `+` lines). */
100
+ async function commitsOnlyIn(git, cwd, upstream, head, limit) {
101
+ if (!head || head === limit) return 0;
102
+ const result = await git(['cherry', upstream, head, limit], { cwd });
103
+ if (!result.ok) return -1;
104
+ return result.stdout.split('\n').filter((each) => each.startsWith('+ ')).length;
105
+ }
106
+
107
+ /**
108
+ * Is `branch` merged into `target`, for a guarded cleanup? SynaBun joins slices on the integration branch by
109
+ * cherry-pick, so a slice branch's own commits are usually not ancestors of the target, only copies of them are.
110
+ *
111
+ * - `via: 'ancestor'`: the branch's head is an ancestor of the target (deleted with `git branch -d`).
112
+ * - `via: 'patch-equivalent'`: every commit the branch has beyond `base` that the target cannot reach has a
113
+ * patch-equivalent commit the target reaches (`git cherry <target> <branch> <base>` prints no `+` line), and none of
114
+ * them is a merge commit (deleted by compare-and-swap on `head`, never by `branch -D`).
115
+ * - Otherwise `ok: false`, with the commits that have no equivalent in `commits`. A merge commit the target cannot
116
+ * reach is always one of them: it has no single patch to compare, and `git cherry` passes over merges in silence.
117
+ *
118
+ * @returns {Promise<{ ok: boolean, branch: string, head: string|null, via: 'ancestor'|'patch-equivalent'|null,
119
+ * commits: string[], detail: string }>}
120
+ */
121
+ export async function mergedInto(git, cwd, branch, target, base) {
122
+ const out = (ok, head, via, commits, detail) => ({ ok, branch, head, via, commits, detail: `${branch}: ${detail}` });
123
+ if (!target) return out(false, null, null, [], 'no landing target is recorded');
124
+ const head = await commitOf(git, cwd, `refs/heads/${branch}`);
125
+ const targetHead = await commitOf(git, cwd, `refs/heads/${target}`);
126
+ if (!head) return out(false, null, null, [], 'the branch is not there');
127
+ if (!targetHead) return out(false, head, null, [], `the landing target ${target} is not there`);
128
+ if ((await git(['merge-base', '--is-ancestor', head, targetHead], { cwd })).ok) return out(true, head, 'ancestor', [], `ancestor of ${target}`);
129
+ const limit = base && await commitOf(git, cwd, base);
130
+ if (!limit) return out(false, head, null, [], `not an ancestor of ${target}, and the team's base commit is not there to compare from`);
131
+ const merges = await git(['rev-list', '--merges', head, '--not', targetHead, limit], { cwd });
132
+ const cherry = await git(['cherry', targetHead, head, limit], { cwd });
133
+ if (!merges.ok || !cherry.ok) return out(false, head, null, [], `not an ancestor of ${target}, and git could not compare it (${gitSaid(merges.ok ? cherry : merges)})`);
134
+ const mergeCommits = merges.stdout.split('\n').map((each) => each.trim()).filter(Boolean);
135
+ const missing = cherry.stdout.split('\n').filter((each) => each.startsWith('+ ')).map((each) => each.slice(2).trim().split(/\s/)[0]);
136
+ const commits = [...new Set([...missing, ...mergeCommits])];
137
+ if (!commits.length) return out(true, head, 'patch-equivalent', [], `every commit has a patch-equivalent commit in ${target}`);
138
+ const parts = [];
139
+ if (missing.length) parts.push(`${missing.length} commit${missing.length === 1 ? ' has' : 's have'} no patch-equivalent commit in ${target}: ${missing.join(', ')}`);
140
+ if (mergeCommits.length) parts.push(`${mergeCommits.length} merge commit${mergeCommits.length === 1 ? ' is' : 's are'} not reachable from ${target}: ${mergeCommits.join(', ')}`);
141
+ return out(false, head, null, commits, `not merged into ${target}: ${parts.join('; ')}`);
142
+ }
143
+
144
+ /**
145
+ * The project as a repository: its HEAD and branch. A refusal for a folder that is not the root of a repository
146
+ * with a commit.
147
+ */
148
+ export async function repositoryOf(git, projectPath) {
149
+ if (typeof projectPath !== 'string' || !isAbsolute(projectPath)) return refuse('INVALID_PLAN', 'projectPath must be an absolute path.');
150
+ if (!isDirectory(projectPath)) return refuse('PROJECT_NOT_FOUND', `${projectPath} is not a folder.`);
151
+ const inside = await git(['rev-parse', '--is-inside-work-tree'], { cwd: projectPath });
152
+ if (!inside.ok || line(inside) !== 'true') return refuse('NOT_A_GIT_REPOSITORY', `${projectPath} is not a git repository: a team needs one, because every worker gets a worktree of it. Run "git init" and commit first, or give the task to one worker.`);
153
+ const top = line(await git(['rev-parse', '--show-toplevel'], { cwd: projectPath }));
154
+ if (!top || realOf(top) !== realOf(projectPath)) return refuse('PROJECT_NOT_REPO_ROOT', `${projectPath} is inside the repository ${top || '(unknown)'}, not its root: a team's worktrees are made for the repository's root folder.`, { repositoryRoot: top || null });
155
+ const head = await commitOf(git, projectPath, 'HEAD');
156
+ if (!head) return refuse('NO_COMMITS', `${projectPath} has no commit yet: a team starts from a commit. Commit something first.`);
157
+ const branch = line(await git(['symbolic-ref', '--short', '-q', 'HEAD'], { cwd: projectPath })) || null;
158
+ return { ok: true, top, head, branch };
159
+ }
160
+
161
+ /** Make sure the project ignores `.worktrees/`: through `.git/info/exclude`, and only when nothing ignores it yet. */
162
+ export async function ensureWorktreesExcluded(git, projectPath) {
163
+ const probe = await git(['check-ignore', '-q', '--no-index', '--', `${WORKTREES_DIR}/probe`], { cwd: projectPath });
164
+ if (probe.status === 0) return { added: false };
165
+ const where = line(await git(['rev-parse', '--git-path', 'info/exclude'], { cwd: projectPath }));
166
+ if (!where) return { added: false, error: 'the repository\'s exclude file could not be found' };
167
+ const file = isAbsolute(where) ? where : resolve(projectPath, where);
168
+ mkdirSync(dirname(file), { recursive: true });
169
+ const before = existsSync(file) ? readFileSync(file, 'utf8') : '';
170
+ appendFileSync(file, `${before && !before.endsWith('\n') ? '\n' : ''}${WORKTREES_DIR}/\n`);
171
+ return { added: true, file };
172
+ }
173
+
174
+ // ── dependency setup ─────────────────────────────────────────────────────────
175
+
176
+ /**
177
+ * A dependency setup step: clone the project's node_modules folders into a worktree, copy-on-write, so a worker
178
+ * can run the project without an install. Only folders git ignores, only where the file system can clone (APFS,
179
+ * Btrfs, XFS with reflinks): anywhere else nothing is copied and the answer says so.
180
+ *
181
+ * @param {object} [options]
182
+ * @param {string[]} [options.paths] project-relative folders to clone. Default: the `node_modules` beside every
183
+ * tracked `package.json`.
184
+ * @param {number} [options.limit] at most this many folders (default 40)
185
+ * @returns {(context: { projectPath: string, worktree: string, teamId: string, sliceId: string, git: Function }) =>
186
+ * Promise<{ cloned: { path: string, ok: boolean, reason?: string }[] }>}
187
+ */
188
+ export function cloneNodeModules({ paths = null, limit = 40 } = {}) {
189
+ return async function setup({ projectPath, worktree, git }) {
190
+ let list = Array.isArray(paths) ? paths : null;
191
+ if (!list) {
192
+ const tracked = await git(['ls-files', '-z', '--', 'package.json', '*/package.json'], { cwd: projectPath });
193
+ list = nulList(tracked.stdout).map((file) => posix.join(posix.dirname(file), 'node_modules'));
194
+ }
195
+ const cloned = [];
196
+ let supported = null;
197
+ for (const raw of [...new Set(list)].slice(0, Math.max(0, limit))) {
198
+ const rel = normalizeRelPath(raw);
199
+ if (rel === null) { cloned.push({ path: String(raw), ok: false, reason: 'not_inside_project' }); continue; }
200
+ const from = join(projectPath, rel);
201
+ const to = join(worktree, rel);
202
+ if (!isDirectory(from) || present(to)) continue;
203
+ // Never a folder the project tracks: that one is in the worktree already, from the commit.
204
+ if ((await git(['check-ignore', '-q', '--', rel], { cwd: projectPath })).status !== 0) { cloned.push({ path: rel, ok: false, reason: 'not_ignored' }); continue; }
205
+ if (supported === null) supported = await canClone(projectPath, worktree);
206
+ if (!supported) { cloned.push({ path: rel, ok: false, reason: 'clone_not_supported' }); continue; }
207
+ try {
208
+ mkdirSync(dirname(to), { recursive: true });
209
+ await cloneFolder(from, to);
210
+ cloned.push({ path: rel, ok: true });
211
+ } catch (error) {
212
+ await rm(to, { recursive: true, force: true }).catch(() => {});
213
+ cloned.push({ path: rel, ok: false, reason: error?.code || error?.message || 'failed' });
214
+ }
215
+ }
216
+ return { cloned };
217
+ };
218
+ }
219
+
220
+ /** What statfs answers as the type of an APFS volume on macOS (the one file system there that clones). */
221
+ const APFS_TYPE = 0x1a;
222
+
223
+ /**
224
+ * Can a file of the project be cloned (copy-on-write) into the worktree? On macOS: both on one APFS volume (`cp -c`
225
+ * copies in full where it cannot clone, and Node's forced clone is not implemented there, so the file system is
226
+ * asked for its type). Elsewhere: asked by cloning one small file, which fails where the file system cannot.
227
+ */
228
+ async function canClone(projectPath, worktree) {
229
+ try {
230
+ if (lstatSync(projectPath).dev !== lstatSync(worktree).dev) return false;
231
+ if (process.platform === 'darwin') return statfsSync(worktree).type === APFS_TYPE;
232
+ } catch {
233
+ return false;
234
+ }
235
+ const probe = join(worktree, `.synabun-clone-probe-${process.pid}`);
236
+ try {
237
+ const source = [join(projectPath, 'package.json'), ...readdirSync(projectPath).map((name) => join(projectPath, name))].find((path) => { try { return lstatSync(path).isFile(); } catch { return false; } });
238
+ if (!source) return false;
239
+ await copyFile(source, probe, FS.COPYFILE_FICLONE_FORCE);
240
+ return true;
241
+ } catch {
242
+ return false;
243
+ } finally {
244
+ await rm(probe, { force: true }).catch(() => {});
245
+ }
246
+ }
247
+
248
+ async function cloneFolder(from, to) {
249
+ if (process.platform === 'darwin') { await execFileAsync('cp', ['-c', '-R', from, to], { maxBuffer: 4 * 1024 * 1024 }); return; }
250
+ if (process.platform === 'linux') { await execFileAsync('cp', ['-R', '--reflink=always', from, to], { maxBuffer: 4 * 1024 * 1024 }); return; }
251
+ await cp(from, to, { recursive: true, mode: FS.COPYFILE_FICLONE_FORCE, verbatimSymlinks: true, errorOnExist: true, force: false });
252
+ }
253
+
254
+ // ── the module ───────────────────────────────────────────────────────────────
255
+
256
+ /**
257
+ * @param {object} deps
258
+ * @param {object} deps.state createTeamState(...) of lib/teams/state.js
259
+ * @param {Function} deps.git createGitRunner(...) of lib/teams/git.js
260
+ * @param {object} deps.locks createLocks() of lib/teams/git.js
261
+ * @param {Function} [deps.setup] the default dependency setup step (`create`'s `setup` option overrides it)
262
+ * @param {() => number} [deps.now]
263
+ * @param {(tag: string, detail: any) => void} [deps.log]
264
+ */
265
+ export function createTeamWorktrees({ state, git, locks, setup: defaultSetup = null, now = Date.now, log = () => {} } = {}) {
266
+ const repoKey = repoLockKey;
267
+ const piecesOf = (plan) => [...plan.slices.map((slice) => slice.id), ...(plan.readOnly ? [] : [INTEGRATION_SLICE_ID])];
268
+ const placeOf = (plan, sliceId) => ({ sliceId, path: worktreePath(plan.projectPath, plan.teamId, sliceId), branch: branchName(plan.teamId, sliceId) });
269
+
270
+ /** What already stands in a new team's way: its folder, its branches, worktrees registered under its folder. */
271
+ async function collisions(plan) {
272
+ const found = [];
273
+ const folder = join(worktreesRoot(plan.projectPath), plan.teamId);
274
+ if (present(folder)) found.push({ kind: 'folder', path: folder });
275
+ const refs = await git(['for-each-ref', '--format=%(refname:short)', `refs/heads/${branchName(plan.teamId, 'x').slice(0, -1)}`], { cwd: plan.projectPath });
276
+ for (const branch of (refs.stdout || '').split('\n').map((each) => each.trim()).filter(Boolean)) found.push({ kind: 'branch', branch });
277
+ // A branch named like the folder a team's branches need (`synabun`, `synabun/<team>`) blocks them all.
278
+ for (const blocker of [branchName(plan.teamId, 'x').split('/')[0], branchName(plan.teamId, 'x').split('/').slice(0, 2).join('/')]) {
279
+ if (await branchExists(git, plan.projectPath, blocker)) found.push({ kind: 'branch', branch: blocker });
280
+ }
281
+ const real = realOf(folder);
282
+ for (const entry of await listWorktrees(git, plan.projectPath)) {
283
+ const at = resolve(entry.path);
284
+ if (at === folder || at.startsWith(`${folder}/`) || at === real || at.startsWith(`${real}/`)) found.push({ kind: 'worktree', path: entry.path });
285
+ }
286
+ return found;
287
+ }
288
+
289
+ /** Make the worktrees and branches of a plan that are not there yet. Answers what it made, or the failure. */
290
+ async function materialize(plan) {
291
+ const made = [];
292
+ for (const sliceId of piecesOf(plan)) {
293
+ const { path, branch } = placeOf(plan, sliceId);
294
+ const hasBranch = await branchExists(git, plan.projectPath, branch);
295
+ const result = await git(['worktree', 'add', '-q', ...(hasBranch ? [path, branch] : ['-b', branch, path, plan.baseCommit])], { cwd: plan.projectPath });
296
+ if (!result.ok) return { ok: false, made, failed: { sliceId, path, branch, error: gitSaid(result) } };
297
+ made.push({ sliceId, path, branch, madeBranch: !hasBranch });
298
+ }
299
+ return { ok: true, made };
300
+ }
301
+
302
+ /** Take back what a failed creation made: worktrees, and branches that still point at the base. */
303
+ async function unmake(plan, made) {
304
+ for (const piece of made) {
305
+ await git(['worktree', 'remove', '--force', piece.path], { cwd: plan.projectPath });
306
+ if (present(piece.path)) rmSync(piece.path, { recursive: true, force: true });
307
+ if (piece.madeBranch && await commitOf(git, plan.projectPath, `refs/heads/${piece.branch}`) === plan.baseCommit) await git(['branch', '-D', piece.branch], { cwd: plan.projectPath });
308
+ }
309
+ await git(['worktree', 'prune'], { cwd: plan.projectPath });
310
+ const folder = join(worktreesRoot(plan.projectPath), plan.teamId);
311
+ try { rmdirSync(folder); } catch { /* something is still in it: it stays */ }
312
+ }
313
+
314
+ async function runSetup(plan, setup) {
315
+ if (typeof setup !== 'function') return [];
316
+ const out = [];
317
+ for (const sliceId of piecesOf(plan)) {
318
+ const { path } = placeOf(plan, sliceId);
319
+ try {
320
+ const result = await setup({ projectPath: plan.projectPath, worktree: path, teamId: plan.teamId, sliceId, git });
321
+ out.push({ sliceId, ok: true, ...(result && typeof result === 'object' ? result : {}) });
322
+ } catch (error) {
323
+ log('teams:setup-failed', { teamId: plan.teamId, sliceId, error: error?.message || String(error) });
324
+ out.push({ sliceId, ok: false, error: error?.message || String(error) });
325
+ }
326
+ }
327
+ return out;
328
+ }
329
+
330
+ /**
331
+ * Create a team: pin the base, make every slice's worktree and branch and the integration ones, record it.
332
+ *
333
+ * @param {object} input a team plan (lib/teams/schema.js). `baseCommit` may be left out: the project's HEAD is
334
+ * pinned then. One it names must be a commit of the repository.
335
+ * @param {object} [options]
336
+ * @param {string} [options.density] the session's Agent density: the cap on slices (validateTeamPlan)
337
+ * @param {number} [options.maxSlices] the cap as a number
338
+ * @param {string|string[]} [options.testCommand] what `integrate` runs on each integration commit
339
+ * @param {Function|null} [options.setup] the dependency setup step for this team (null: none)
340
+ * @param {string} [options.createdBy] who asked (a session id, for the record)
341
+ * @returns {Promise<{ ok: true, team: object, setup: object[], excluded: object } | { ok: false, code: string, message: string }>}
342
+ */
343
+ async function create(input, { density = null, maxSlices = null, testCommand = null, setup = undefined, createdBy = null } = {}) {
344
+ const draft = normalizeTeamPlan(input);
345
+ const repo = await repositoryOf(git, draft.projectPath);
346
+ if (!repo.ok) return repo;
347
+ let baseCommit = repo.head;
348
+ if (draft.baseCommit) {
349
+ baseCommit = await commitOf(git, draft.projectPath, draft.baseCommit);
350
+ if (!baseCommit || baseCommit !== draft.baseCommit) return refuse('BASE_NOT_FOUND', `${draft.baseCommit} is not a commit of this repository.`);
351
+ }
352
+ const checked = validateTeamPlan({ ...(input && typeof input === 'object' ? input : {}), baseCommit }, { density, maxSlices });
353
+ if (!checked.ok) return refuse('INVALID_PLAN', `The plan is not valid: ${checked.errors[0].message}`, { errors: checked.errors });
354
+ const plan = checked.value;
355
+ const command = plan.readOnly ? null : testCommandOf(testCommand);
356
+ if (command === false) return refuse('INVALID_TEST_COMMAND', 'testCommand is a command line (text) or a list of arguments.');
357
+
358
+ return locks.run(repoKey(plan.projectPath), async () => {
359
+ if (state.record(plan.teamId)) return refuse('TEAM_EXISTS', `A team named "${plan.teamId}" is already recorded. Pick another team id, or remove that team first.`, { existing: [{ kind: 'journal', teamId: plan.teamId }] });
360
+ const existing = await collisions(plan);
361
+ if (existing.length) {
362
+ const what = existing.map((each) => each.path || each.branch).join(', ');
363
+ return refuse('TEAM_EXISTS', `"${plan.teamId}" is taken in this project (${what}). ${WORKTREES_DIR}/ also holds worktrees made by hand: pick another team id.`, { existing });
364
+ }
365
+ const excluded = await ensureWorktreesExcluded(git, plan.projectPath);
366
+ const pieces = planPieces(plan);
367
+ state.writeTeam(plan.teamId, 'creating', {
368
+ plan: pieces.team, baseBranch: repo.branch, headAtCreate: repo.head, testCommand: command, createdBy: typeof createdBy === 'string' ? createdBy : null,
369
+ integration: { head: plan.baseCommit, lastGood: plan.baseCommit, tests: null },
370
+ });
371
+ for (const piece of pieces.slices) {
372
+ state.writeSlice(plan.teamId, piece.id, 'planned', { task: piece.task });
373
+ state.writeSlice(plan.teamId, piece.id, 'pending', { ownedPaths: piece.ownedPaths, ...placeOf(plan, piece.id), startCommit: plan.baseCommit });
374
+ }
375
+ const built = await materialize(plan);
376
+ if (!built.ok) {
377
+ await unmake(plan, built.made);
378
+ state.writeTeam(plan.teamId, 'failed', { error: built.failed, failedAt: now() });
379
+ return refuse('WORKTREE_FAILED', `The worktree of "${built.failed.sliceId}" could not be made: ${built.failed.error}. Nothing of the team is left.`, { failed: built.failed });
380
+ }
381
+ const prepared = await runSetup(plan, plan.readOnly ? null : setup === undefined ? defaultSetup : setup);
382
+ state.writeTeam(plan.teamId, 'planned', { worktrees: built.made.map(({ sliceId, path, branch }) => ({ sliceId, path, branch })) });
383
+ return { ok: true, team: state.record(plan.teamId), setup: prepared, excluded };
384
+ });
385
+ }
386
+
387
+ /** A team's record (lib/teams/state.js), or null. */
388
+ const get = (teamId) => (isTeamSlug(teamId) ? state.record(teamId) : null);
389
+
390
+ /**
391
+ * The teams the journal knows, oldest first.
392
+ * @param {{ projectPath?: string, states?: string[], includeRemoved?: boolean }} [query]
393
+ */
394
+ function list({ projectPath = null, states = null, includeRemoved = true } = {}) {
395
+ const wanted = projectPath ? realOf(projectPath) : null;
396
+ const out = [];
397
+ for (const entry of state.teams(states ? { states } : {})) {
398
+ const record = state.record(entry.teamId);
399
+ if (!record) continue;
400
+ if (wanted && realOf(record.projectPath) !== wanted) continue;
401
+ if (!includeRemoved && record.removed) continue;
402
+ out.push({
403
+ teamId: record.teamId, state: record.state, projectPath: record.projectPath, baseCommit: record.baseCommit, baseBranch: record.baseBranch,
404
+ integrationBranch: record.plan.readOnly ? null : integrationBranchName(record.teamId), removed: record.removed,
405
+ slices: record.plan.slices.map((slice) => ({ id: slice.id, title: slice.title, state: sliceState(record, slice.id), dependsOn: slice.dependsOn })),
406
+ createdAt: record.createdAt, updatedAt: record.updatedAt,
407
+ });
408
+ }
409
+ return out;
410
+ }
411
+
412
+ /** One worktree of a team as it is now: there or not, its branch and head, how far it is from the base, what is uncommitted. */
413
+ async function pieceInfo(record, sliceId, registered = null) {
414
+ const { path, branch } = placeOf(record.plan, sliceId);
415
+ const known = registered || await listWorktrees(git, record.projectPath);
416
+ const entry = known.find((each) => realOf(each.path) === realOf(path)) || null;
417
+ const exists = isDirectory(path);
418
+ const head = await commitOf(git, record.projectPath, `refs/heads/${branch}`);
419
+ const info = { sliceId, path, branch, exists, registered: !!entry, branchExists: !!head, head, checkedOut: entry?.branch || null, onBranch: entry?.branch === branch, dirty: null, changes: [], base: null, lastCommit: null };
420
+ if (exists && entry) {
421
+ const changes = await changesOf(git, path);
422
+ info.changes = changes || [];
423
+ info.dirty = changes === null ? null : changes.length;
424
+ }
425
+ if (head) {
426
+ info.base = await aheadBehind(git, record.projectPath, record.baseCommit, head);
427
+ const last = await git(['log', '-1', '--format=%H%x00%s%x00%cI', head], { cwd: record.projectPath });
428
+ const [sha, subject, date] = (last.stdout || '').trim().split('\0');
429
+ if (last.ok && sha) info.lastCommit = { sha, subject: subject || '', date: date || null };
430
+ }
431
+ return info;
432
+ }
433
+
434
+ /**
435
+ * A team as it stands on disk and in git: every slice's worktree and branch (ahead / behind the base and the
436
+ * integration branch, uncommitted files, last commit), the integration branch, and the user's branch.
437
+ */
438
+ async function inspect(teamId) {
439
+ const record = get(teamId);
440
+ if (!record) return refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is recorded.`);
441
+ const registered = isDirectory(record.projectPath) ? await listWorktrees(git, record.projectPath) : [];
442
+ const integration = record.plan.readOnly ? {} : await pieceInfo(record, INTEGRATION_SLICE_ID, registered);
443
+ const slices = [];
444
+ for (const slice of record.plan.slices) {
445
+ const info = await pieceInfo(record, slice.id, registered);
446
+ const own = record.slices[slice.id] || {};
447
+ slices.push({
448
+ ...info, id: slice.id, title: slice.title, state: sliceState(record, slice.id), dependsOn: slice.dependsOn, ownedPaths: slice.ownedPaths,
449
+ runId: own.runId || null, startCommit: own.startCommit || record.baseCommit,
450
+ integration: info.head && integration.head ? await aheadBehind(git, record.projectPath, integration.head, info.head) : null,
451
+ unintegrated: info.head && integration.head ? await commitsOnlyIn(git, record.projectPath, integration.head, info.head, record.baseCommit) : null,
452
+ });
453
+ }
454
+ const target = record.landed?.targetBranch || record.baseBranch || null;
455
+ const targetHead = target ? await commitOf(git, record.projectPath, `refs/heads/${target}`) : null;
456
+ return {
457
+ ok: true, teamId, state: record.state, projectPath: record.projectPath, baseCommit: record.baseCommit, baseBranch: record.baseBranch,
458
+ removed: record.removed, testCommand: record.testCommand, slices,
459
+ integration: {
460
+ ...integration, recordedHead: record.integration.head, lastGood: record.integration.lastGood, tests: record.integration.tests,
461
+ moved: !!integration.head && integration.head !== record.integration.head,
462
+ },
463
+ target: target ? {
464
+ branch: target, head: targetHead, exists: !!targetHead,
465
+ fastForward: !!(targetHead && integration.head) && (await git(['merge-base', '--is-ancestor', targetHead, integration.head], { cwd: record.projectPath })).ok,
466
+ landed: record.state === 'merged',
467
+ } : null,
468
+ landed: record.landed || null,
469
+ };
470
+ }
471
+
472
+ /**
473
+ * Give a slice to a worker: check that what it waits for is joined, bring a slice with dependencies up to the
474
+ * integration branch (its dependencies' work is there), and record the commit its own work starts from.
475
+ * A slice sent back to work (after a conflict, a rejection, failed tests) keeps its worktree as it is.
476
+ *
477
+ * @returns {Promise<{ ok: true, sliceId: string, worktree: string, branch: string, startCommit: string, rework: boolean } | { ok: false, code: string }>}
478
+ */
479
+ async function startSlice(teamId, sliceId, { runId = null } = {}) {
480
+ const record = get(teamId);
481
+ if (!record) return refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is recorded.`);
482
+ const slice = planSlice(record, sliceId);
483
+ if (!slice) return refuse('SLICE_NOT_FOUND', `Team "${teamId}" has no slice "${sliceId}".`);
484
+ if (TERMINAL_TEAM_STATES.includes(record.state) || record.state === 'creating' || record.removed) return refuse('TEAM_NOT_ACTIVE', `Team "${teamId}" is ${record.removed ? 'removed' : record.state}: no slice of it can start.`, { state: record.state });
485
+ const current = sliceState(record, sliceId);
486
+ const rework = REWORK_SLICE_STATES.has(current);
487
+ if (!rework && !FRESH_SLICE_STATES.has(current)) return refuse('SLICE_NOT_STARTABLE', `Slice "${sliceId}" is ${current}: it cannot be started.`, { state: current });
488
+ const waiting = slice.dependsOn.filter((dep) => sliceState(record, dep) !== 'integrated');
489
+ if (waiting.length) return refuse('DEPENDENCIES_NOT_INTEGRATED', `Slice "${sliceId}" waits for ${waiting.join(', ')}: a slice starts once the slices it depends on are joined on the integration branch.`, { waiting });
490
+ const { path, branch } = placeOf(record.plan, sliceId);
491
+ return locks.run(`slice:${teamId}/${sliceId}`, async () => {
492
+ if (!isDirectory(path)) return refuse('SLICE_WORKTREE_MISSING', `The worktree of slice "${sliceId}" is not there (${path}). Run recover() first.`, { path });
493
+ const on = await branchAt(git, path);
494
+ if (on !== branch) return refuse('SLICE_BRANCH_MOVED', `The worktree of slice "${sliceId}" is on ${on || 'no branch'}, not on ${branch}.`, { path, branch, on: on || null });
495
+ let startCommit = record.slices[sliceId]?.startCommit || record.baseCommit;
496
+ if (!rework) {
497
+ const head = await commitOf(git, path, 'HEAD');
498
+ const integration = await commitOf(git, record.projectPath, `refs/heads/${integrationBranchName(teamId)}`);
499
+ if (slice.dependsOn.length && integration && integration !== head) {
500
+ // Its dependencies' work is on the integration branch: the slice starts from there. Nothing of its own
501
+ // is in the worktree yet, so this is a plain fast-forward.
502
+ const moved = await git(['merge', '--ff-only', '-q', integration], { cwd: path });
503
+ if (!moved.ok) return refuse('SLICE_NOT_FAST_FORWARD', `Slice "${sliceId}" could not be brought up to the integration branch: ${gitSaid(moved)}`, { path });
504
+ }
505
+ startCommit = await commitOf(git, path, 'HEAD') || head;
506
+ }
507
+ state.writeSlice(teamId, sliceId, 'running', { startCommit, startedAt: now(), ...(rework ? { rework: true } : {}) }, runId);
508
+ if (record.state === 'planned' || record.state === 'ready') state.writeTeam(teamId, 'running', {});
509
+ return { ok: true, sliceId, worktree: path, branch, startCommit, rework };
510
+ });
511
+ }
512
+
513
+ /** A read-only worker has ended. Preserve any changed checkout or commit, including ignored files. */
514
+ async function finishReadOnlySlice(teamId, sliceId, { failed = false } = {}) {
515
+ const record = get(teamId);
516
+ if (!record?.plan.readOnly) return refuse('TEAM_NOT_READ_ONLY', 'This operation is for read-only workers.');
517
+ if (!planSlice(record, sliceId)) return refuse('SLICE_NOT_FOUND', `Unknown slice ${sliceId}.`);
518
+ return locks.run(repoKey(record.projectPath), async () => {
519
+ const info = await pieceInfo(record, sliceId);
520
+ let kept = null;
521
+ if (info.exists || info.registered || info.branchExists) {
522
+ const status = info.exists && info.registered && info.onBranch
523
+ ? await git(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--ignored=matching'], { cwd: info.path }) : null;
524
+ const changes = status?.ok ? parseStatus(status.stdout) : null;
525
+ if (!changes) kept = { ...info, reason: 'worktree_not_verified' };
526
+ else if (changes.length || info.head !== record.baseCommit) kept = { sliceId, path: info.path, branch: info.branch, head: info.head,
527
+ reason: changes.length ? 'uncommitted_changes' : 'worker_commits', files: changes.map(c => c.path), baseCommit: record.baseCommit };
528
+ else {
529
+ // Without --force: a concurrent change must make removal fail, never erase work.
530
+ const gone = await git(['worktree', 'remove', info.path], { cwd: record.projectPath });
531
+ if (!gone.ok) kept = { sliceId, path: info.path, branch: info.branch, reason: 'worktree_not_removed', error: gitSaid(gone) };
532
+ else {
533
+ const removed = await git(['branch', '-D', info.branch], { cwd: record.projectPath });
534
+ if (!removed.ok) kept = { sliceId, path: info.path, branch: info.branch, reason: 'branch_not_removed', error: gitSaid(removed) };
535
+ }
536
+ }
537
+ }
538
+ const cleanup = { removed: !kept, kept, path: info.path, branch: info.branch };
539
+ state.writeSlice(teamId, sliceId, failed ? 'failed' : 'completed', { cleanup, endedAt: now() });
540
+ const fresh = get(teamId);
541
+ const ended = fresh.plan.slices.every(s => fresh.slices[s.id]?.cleanup);
542
+ if (ended) {
543
+ const clean = fresh.plan.slices.every(s => fresh.slices[s.id]?.cleanup.removed);
544
+ state.writeTeam(teamId, 'completed', { removed: clean });
545
+ if (clean) { try { rmdirSync(join(worktreesRoot(record.projectPath), teamId)); } catch {} }
546
+ }
547
+ return { ok: true, ...cleanup };
548
+ });
549
+ }
550
+
551
+ /**
552
+ * Remove a team's worktrees and branches. Only after a landing, or with `discard: true`. A worktree with
553
+ * uncommitted changes and a branch whose commits are nowhere else are kept and reported, unless `force: true`.
554
+ *
555
+ * @returns {Promise<{ ok: true, complete: boolean, removed: object[], kept: object[] } | { ok: false, code: string }>}
556
+ */
557
+ async function remove(teamId, { discard = false, force = false, guarded = false, checkOnly = false } = {}) {
558
+ const record = get(teamId);
559
+ if (!record) return refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is recorded.`);
560
+ if (guarded && record.plan.readOnly) return refuse('TEAM_NOT_LANDED', 'Read-only teams cannot land.', { checks: [{ name: 'landed', ok: false, detail: 'Read-only team' }] });
561
+ if (record.plan.readOnly) {
562
+ const removed = [], kept = [];
563
+ for (const slice of record.plan.slices) {
564
+ const out = await finishReadOnlySlice(teamId, slice.id, { failed: record.slices[slice.id]?.state === 'failed' });
565
+ if (!out.ok) return out;
566
+ if (out.kept) kept.push(out.kept);
567
+ else removed.push({ sliceId: slice.id, path: out.path, branch: out.branch });
568
+ }
569
+ return { ok: true, complete: !kept.length, removed, kept };
570
+ }
571
+ if (record.state === 'integrating' || record.state === 'landing' || record.state === 'creating') return refuse('TEAM_NEEDS_RECOVERY', `Team "${teamId}" is recorded as ${record.state}: run recover() before removing it.`, { state: record.state });
572
+ const landed = record.state === 'merged';
573
+ if (!landed && !discard && !record.plan.readOnly && !checkOnly) return refuse('TEAM_NOT_LANDED', `Team "${teamId}" has not landed: its result is on ${integrationBranchName(teamId)}. Land it first, or pass discard: true to give its work up.`, { state: record.state });
574
+ if (!isDirectory(record.projectPath)) return refuse('PROJECT_NOT_FOUND', `${record.projectPath} is not a folder.`);
575
+
576
+ return locks.run(repoKey(record.projectPath), async () => {
577
+ if (guarded) {
578
+ const checks = [];
579
+ const items = piecesOf(record.plan).map(sliceId => ({ sliceId, path: worktreePath(record.projectPath, teamId, sliceId), branch: sliceId === INTEGRATION_SLICE_ID ? integrationBranchName(teamId) : branchName(teamId, sliceId) }));
580
+ const registered = await listWorktrees(git, record.projectPath);
581
+ const target = record.landed?.targetBranch;
582
+ for (const item of items) {
583
+ let linked = false;
584
+ try { linked = lstatSync(join(item.path, '.git')).isFile() && !lstatSync(item.path).isSymbolicLink(); } catch {}
585
+ const valid = linked && await branchAt(git, item.path) === item.branch && registered.some(w => realOf(w.path) === realOf(item.path) && w.branch === item.branch && !w.locked) && registered.every(w => w.branch !== item.branch || realOf(w.path) === realOf(item.path));
586
+ checks.push({ name: 'clean', ok: !!valid, detail: `${item.path}: ${valid ? 'linked worktree verified' : 'not an unlocked linked worktree on its expected branch'}` });
587
+ if (valid) {
588
+ const changes = await changesOf(git, item.path);
589
+ checks.push({ name: 'clean', ok: changes !== null && changes.length === 0, detail: `${item.path}: ${changes === null ? 'status unavailable' : changes.map(c => c.path).join(', ') || 'clean'}` });
590
+ }
591
+ // Merged: an ancestor of the target, or every commit beyond the base patch-equivalent to one in it
592
+ // (mergedInto). The head it checked is the one the deletion compares against.
593
+ const merged = await mergedInto(git, record.projectPath, item.branch, target, record.baseCommit);
594
+ item.head = merged.head;
595
+ item.via = merged.via;
596
+ checks.push({ name: 'merged', ok: merged.ok, detail: merged.detail, branch: item.branch, head: merged.head, via: merged.via, commits: merged.commits });
597
+ }
598
+ // branch -d checks the configured upstream, or HEAD when none exists.
599
+ // Verify that criterion too for the ancestors it deletes, so a different target checkout cannot cause
600
+ // partial removal. A patch-equivalent branch is deleted by compare-and-swap, which asks neither.
601
+ for (const item of items.filter((each) => each.via === 'ancestor')) {
602
+ const upstream = line(await git(['rev-parse', '--abbrev-ref', `${item.branch}@{upstream}`], { cwd: record.projectPath })) || 'HEAD';
603
+ const safe = (await git(['merge-base', '--is-ancestor', item.head, upstream], { cwd: record.projectPath })).ok;
604
+ checks.push({ name: 'merged', ok: safe, detail: `${item.branch}: safe branch -d against ${upstream}` });
605
+ }
606
+ const failed = checks.find(c => !c.ok);
607
+ if (failed) return refuse(failed.name === 'merged' ? 'BRANCH_NOT_MERGED' : 'WORKTREE_DIRTY', failed.detail, { checks });
608
+ if (checkOnly) return { ok: true, checks };
609
+ // All checks precede all mutations. The branches are settled first, in one atomic ref transaction: every
610
+ // ancestor is verified at the head that was checked, and every patch-equivalent branch is deleted only if it
611
+ // is still at that head (`git branch -d` refuses those, and `-D` is never used). Such a branch is checked
612
+ // out in its worktree, so that worktree's HEAD is detached at the same commit first (no file or index
613
+ // changes); a failed transaction puts every HEAD back and removes nothing.
614
+ const cwd = record.projectPath;
615
+ const equivalent = items.filter((each) => each.via === 'patch-equivalent');
616
+ const detached = [];
617
+ const reattach = async () => {
618
+ const failures = [];
619
+ for (const item of detached.splice(0)) {
620
+ const back = await git(['symbolic-ref', '-m', 'SynaBun cleanup refused', 'HEAD', `refs/heads/${item.branch}`], { cwd: item.path });
621
+ if (!back.ok) failures.push(`${item.path}: ${gitSaid(back)}`);
622
+ }
623
+ return failures;
624
+ };
625
+ for (const item of equivalent) {
626
+ const detach = await git(['update-ref', '--no-deref', '-m', 'SynaBun cleanup', 'HEAD', item.head], { cwd: item.path });
627
+ if (!detach.ok) {
628
+ const failures = await reattach();
629
+ if (failures.length) throw new Error(`Cleanup interrupted: ${failures.join('; ')}`);
630
+ return refuse('WORKTREE_DIRTY', `${item.path}: could not be detached for the branch deletion (${gitSaid(detach)}). Nothing was removed.`, { checks });
631
+ }
632
+ detached.push(item);
633
+ }
634
+ const transaction = [
635
+ ...items.filter((each) => each.via === 'ancestor').map((each) => `verify refs/heads/${each.branch} ${each.head}`),
636
+ ...equivalent.map((each) => `delete refs/heads/${each.branch} ${each.head}`),
637
+ ].join('\n') + '\n';
638
+ const settled = await git(['update-ref', '-m', 'SynaBun cleanup', '--stdin'], { cwd, input: transaction });
639
+ if (!settled.ok) {
640
+ const failures = await reattach();
641
+ if (failures.length) throw new Error(`Cleanup interrupted: ${gitSaid(settled)}; ${failures.join('; ')}`);
642
+ const moved = [];
643
+ for (const item of items) {
644
+ const current = await commitOf(git, cwd, `refs/heads/${item.branch}`);
645
+ if (current !== item.head) moved.push(`${item.branch} (checked at ${item.head}, now ${current || 'gone'})`);
646
+ }
647
+ return refuse('BRANCH_MOVED', `${moved.length ? `${moved.join(', ')} moved` : 'A team branch changed'} between the merged check and the deletion (${gitSaid(settled)}). Nothing was removed.`, { checks, moved });
648
+ }
649
+ const removed = [];
650
+ for (const item of items) {
651
+ const gone = await git(['worktree', 'remove', item.path], { cwd });
652
+ if (!gone.ok) throw new Error(`Cleanup interrupted: ${gitSaid(gone)}`);
653
+ if (item.via === 'ancestor') {
654
+ const deleted = await git(['branch', '-d', item.branch], { cwd });
655
+ if (!deleted.ok) throw new Error(`Cleanup interrupted: ${gitSaid(deleted)}`);
656
+ }
657
+ removed.push({ sliceId: item.sliceId, path: item.path, branch: item.branch });
658
+ }
659
+ const pruned = await git(['worktree', 'prune'], { cwd: record.projectPath });
660
+ if (!pruned.ok) throw new Error(`Cleanup prune failed: ${gitSaid(pruned)}`);
661
+ try { rmdirSync(join(worktreesRoot(record.projectPath), teamId)); } catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTEMPTY') throw error; }
662
+ state.writeTeam(teamId, 'merged', { removed: true, removal: { at: now(), force: false, removed, kept: [] } });
663
+ return { ok: true, complete: true, removed, checks };
664
+ }
665
+ const registered = await listWorktrees(git, record.projectPath);
666
+ const integration = record.plan.readOnly ? {} : await pieceInfo(record, INTEGRATION_SLICE_ID, registered);
667
+ const target = record.landed?.targetBranch || record.baseBranch || null;
668
+ const targetHead = (target && await commitOf(git, record.projectPath, `refs/heads/${target}`)) || record.baseCommit;
669
+ // What a slice's commits are measured against: once landed, the integration branch (what is there landed
670
+ // with it); otherwise the user's branch, where nothing of the team is.
671
+ const upstream = landed && integration.head ? integration.head : targetHead;
672
+ const removed = [];
673
+ const kept = [];
674
+ const order = piecesOf(record.plan);
675
+ for (const sliceId of order) {
676
+ const info = sliceId === INTEGRATION_SLICE_ID ? integration : await pieceInfo(record, sliceId, registered);
677
+ if (!info.exists && !info.registered && !info.branchExists) continue;
678
+ const uncommitted = sliceId === INTEGRATION_SLICE_ID ? [] : info.changes.map((change) => change.path);
679
+ const only = info.head
680
+ ? (sliceId === INTEGRATION_SLICE_ID
681
+ ? Number(line(await git(['rev-list', '--count', `${targetHead}..${info.head}`], { cwd: record.projectPath })) || 0)
682
+ : await commitsOnlyIn(git, record.projectPath, upstream, info.head, record.baseCommit))
683
+ : 0;
684
+ // A folder that is there but is no worktree of the repository: what is in it is unknown, so it stays.
685
+ if (!force && info.exists && !info.registered) {
686
+ kept.push({ sliceId, path: info.path, branch: info.branch, head: info.head, reason: 'folder_is_not_a_worktree', files: [], commits: 0 });
687
+ continue;
688
+ }
689
+ if (!force && (uncommitted.length || only !== 0)) {
690
+ kept.push({
691
+ sliceId, path: info.path, branch: info.branch, head: info.head,
692
+ reason: uncommitted.length ? 'uncommitted_changes' : 'unintegrated_commits',
693
+ files: uncommitted.slice(0, 50), commits: Math.max(only, 0),
694
+ });
695
+ continue;
696
+ }
697
+ if (info.registered || info.exists) {
698
+ const gone = await git(['worktree', 'remove', '--force', info.path], { cwd: record.projectPath });
699
+ if (!gone.ok && present(info.path)) {
700
+ if (info.registered) { kept.push({ sliceId, path: info.path, branch: info.branch, head: info.head, reason: 'worktree_not_removed', error: gitSaid(gone) }); continue; }
701
+ rmSync(info.path, { recursive: true, force: true });
702
+ }
703
+ }
704
+ await git(['worktree', 'prune'], { cwd: record.projectPath });
705
+ if (info.branchExists) {
706
+ const deleted = await git(['branch', '-D', info.branch], { cwd: record.projectPath });
707
+ if (!deleted.ok) { kept.push({ sliceId, path: info.path, branch: info.branch, head: info.head, reason: 'branch_not_removed', error: gitSaid(deleted) }); continue; }
708
+ }
709
+ removed.push({ sliceId, path: info.path, branch: info.branch, head: info.head });
710
+ }
711
+ const folder = join(worktreesRoot(record.projectPath), teamId);
712
+ let folderRemoved = false;
713
+ try { rmdirSync(folder); folderRemoved = true; } catch { folderRemoved = !present(folder); }
714
+ const complete = kept.length === 0;
715
+ state.writeTeam(teamId, landed ? 'merged' : 'cancelled', {
716
+ removed: complete, removal: { at: now(), discard: !landed, force: !!force, removed, kept },
717
+ });
718
+ for (const slice of record.plan.slices) {
719
+ if (!landed && removed.some((each) => each.sliceId === slice.id) && sliceState(record, slice.id) !== 'integrated') state.writeSlice(teamId, slice.id, 'cancelled', { discarded: true });
720
+ }
721
+ return { ok: true, complete, landed, removed, kept, folderRemoved };
722
+ });
723
+ }
724
+
725
+ /**
726
+ * Clear what is stale in a project: worktree registrations whose folder is gone (`git worktree prune`) and the
727
+ * empty folders of teams the journal knows. A folder somebody made by hand is never touched.
728
+ */
729
+ async function prune({ projectPath } = {}) {
730
+ const repo = await repositoryOf(git, projectPath);
731
+ if (!repo.ok) return repo;
732
+ return locks.run(repoKey(projectPath), async () => {
733
+ const before = await listWorktrees(git, projectPath);
734
+ const stale = before.filter((entry) => entry.prunable || !present(entry.path)).map((entry) => ({ path: entry.path, branch: entry.branch, team: parseWorktreePath(projectPath, resolve(entry.path)) }));
735
+ const result = await git(['worktree', 'prune'], { cwd: projectPath });
736
+ const folders = [];
737
+ const root = worktreesRoot(projectPath);
738
+ let names = [];
739
+ try { names = readdirSync(root); } catch { names = []; }
740
+ for (const name of names) {
741
+ if (!isTeamSlug(name) || !state.record(name)) continue;
742
+ try { rmdirSync(join(root, name)); folders.push(join(root, name)); } catch { /* not empty: a team's worktrees are in it */ }
743
+ }
744
+ return { ok: result.ok, pruned: stale, folders, ...(result.ok ? {} : { error: gitSaid(result) }) };
745
+ });
746
+ }
747
+
748
+ return { create, get, list, inspect, startSlice, finishReadOnlySlice, remove, prune, materialize, unmake, pieceInfo, placeOf, collisions };
749
+ }
750
+
751
+ /** A test command as it is stored: text, a list of arguments, or null. `false` for anything else. */
752
+ export function testCommandOf(value) {
753
+ if (value === null || value === undefined || value === '') return null;
754
+ if (typeof value === 'string') return value.trim().length && value.length <= 4000 ? value.trim() : false;
755
+ if (Array.isArray(value) && value.length && value.length <= 200 && value.every((arg) => typeof arg === 'string' && arg.length <= 4000) && value[0]) return [...value];
756
+ return false;
757
+ }