synabun 2.3.1 → 2.4.1

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 (370) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +189 -0
  4. package/browser-extension/engine.js +508 -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 +250 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +166 -0
  19. package/browser-extension/popup.html +108 -0
  20. package/browser-extension/popup.js +359 -0
  21. package/browser-extension/protocol.js +232 -0
  22. package/browser-extension/service-worker.js +275 -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/lib/data-home-files.js +45 -0
  28. package/lib/data-home-migration.js +34 -58
  29. package/mcp-server/dist/http.d.ts +2 -0
  30. package/mcp-server/dist/http.d.ts.map +1 -1
  31. package/mcp-server/dist/http.js +9 -1
  32. package/mcp-server/dist/http.js.map +1 -1
  33. package/mcp-server/dist/index.d.ts +11 -0
  34. package/mcp-server/dist/index.d.ts.map +1 -1
  35. package/mcp-server/dist/index.js +38 -3
  36. package/mcp-server/dist/index.js.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  38. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  39. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  40. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  41. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  42. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  43. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.d.ts +95 -3
  45. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  46. package/mcp-server/dist/services/neural-interface.js +168 -23
  47. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  48. package/mcp-server/dist/services/team-context.d.ts +18 -0
  49. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  50. package/mcp-server/dist/services/team-context.js +29 -0
  51. package/mcp-server/dist/services/team-context.js.map +1 -0
  52. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  53. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  54. package/mcp-server/dist/services/tool-catalog.js +22 -6
  55. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  56. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  57. package/mcp-server/dist/services/tool-list.js +4 -0
  58. package/mcp-server/dist/services/tool-list.js.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  60. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  61. package/mcp-server/dist/services/tool-runtime.js +18 -1
  62. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  63. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  64. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  65. package/mcp-server/dist/tools/agent-definition.js +483 -0
  66. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  67. package/mcp-server/dist/tools/agents.d.ts +92 -9
  68. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  69. package/mcp-server/dist/tools/agents.js +163 -20
  70. package/mcp-server/dist/tools/agents.js.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  72. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  73. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  74. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  76. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/git-tools.js +283 -2
  78. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  80. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/morelogin.js +22 -5
  82. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  83. package/mcp-server/dist/tools/team.d.ts +32 -0
  84. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/team.js +87 -0
  86. package/mcp-server/dist/tools/team.js.map +1 -0
  87. package/mcp-server/package-lock.json +2 -2
  88. package/mcp-server/package.json +1 -1
  89. package/mcp-server/src/http.ts +9 -1
  90. package/mcp-server/src/index.ts +34 -4
  91. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  92. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  93. package/mcp-server/src/services/neural-interface.ts +191 -29
  94. package/mcp-server/src/services/team-context.ts +27 -0
  95. package/mcp-server/src/services/tool-catalog.ts +26 -8
  96. package/mcp-server/src/services/tool-list.ts +4 -0
  97. package/mcp-server/src/services/tool-runtime.ts +21 -2
  98. package/mcp-server/src/tools/agent-definition.ts +458 -0
  99. package/mcp-server/src/tools/agents.ts +177 -19
  100. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  101. package/mcp-server/src/tools/git-tools.ts +249 -3
  102. package/mcp-server/src/tools/morelogin.ts +20 -5
  103. package/mcp-server/src/tools/team.ts +97 -0
  104. package/neural-interface/i18n/en.json +1119 -47
  105. package/neural-interface/i18n/pt-BR.json +1119 -47
  106. package/neural-interface/lib/account-usage.js +1 -1
  107. package/neural-interface/lib/agents/builtins.json +207 -0
  108. package/neural-interface/lib/agents/density.js +101 -0
  109. package/neural-interface/lib/agents/forge-host.js +223 -0
  110. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  111. package/neural-interface/lib/agents/native-export.js +365 -0
  112. package/neural-interface/lib/agents/registry.js +885 -0
  113. package/neural-interface/lib/agents/resolve.js +603 -0
  114. package/neural-interface/lib/agents/schema.js +642 -0
  115. package/neural-interface/lib/agents/split.js +37 -0
  116. package/neural-interface/lib/agents-studio-api.js +591 -0
  117. package/neural-interface/lib/assistant-api.js +76 -7
  118. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  119. package/neural-interface/lib/assistant-catalog.js +2 -0
  120. package/neural-interface/lib/assistant-continuity.js +49 -0
  121. package/neural-interface/lib/assistant-dispatch.js +351 -121
  122. package/neural-interface/lib/assistant-persona.js +105 -8
  123. package/neural-interface/lib/assistant-route-gate.js +24 -9
  124. package/neural-interface/lib/assistant-router.js +432 -47
  125. package/neural-interface/lib/assistant-run-tail.js +151 -0
  126. package/neural-interface/lib/assistant-run-wait.js +183 -0
  127. package/neural-interface/lib/assistant-runtime.js +449 -94
  128. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  129. package/neural-interface/lib/assistant-usage.js +3 -2
  130. package/neural-interface/lib/automation-approval.js +2 -2
  131. package/neural-interface/lib/backup-service.js +64 -105
  132. package/neural-interface/lib/browser-close-evidence.js +80 -0
  133. package/neural-interface/lib/browser-default.js +210 -0
  134. package/neural-interface/lib/browser-extension-adapter.js +264 -0
  135. package/neural-interface/lib/browser-extension-bridge.js +441 -0
  136. package/neural-interface/lib/browser-extension-folder.js +116 -0
  137. package/neural-interface/lib/browser-extension-setup.js +140 -0
  138. package/neural-interface/lib/browser-profile-choices.js +3 -3
  139. package/neural-interface/lib/browser-tool-policy.js +1 -1
  140. package/neural-interface/lib/claude-account-links.js +301 -0
  141. package/neural-interface/lib/claude-accounts.js +45 -20
  142. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  143. package/neural-interface/lib/claude-model-catalog.js +6 -0
  144. package/neural-interface/lib/claude-panel-session.js +33 -0
  145. package/neural-interface/lib/codex-accounts.js +67 -24
  146. package/neural-interface/lib/coordination/README.md +384 -0
  147. package/neural-interface/lib/coordination/service.js +563 -0
  148. package/neural-interface/lib/coordination/store.js +1138 -0
  149. package/neural-interface/lib/db.js +22 -1
  150. package/neural-interface/lib/effort-levels.js +10 -1
  151. package/neural-interface/lib/memory-list-page.js +49 -0
  152. package/neural-interface/lib/memory-list-stamp.js +60 -0
  153. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  154. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  155. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  156. package/neural-interface/lib/morelogin.js +194 -8
  157. package/neural-interface/lib/native-loop-runtime.js +26 -7
  158. package/neural-interface/lib/opencode-build-preflight.js +28 -8
  159. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  160. package/neural-interface/lib/opencode-serve-records.js +14 -9
  161. package/neural-interface/lib/page-session.js +1 -1
  162. package/neural-interface/lib/peer-identity.js +73 -29
  163. package/neural-interface/lib/process-identity.js +68 -7
  164. package/neural-interface/lib/request-gate.js +3 -0
  165. package/neural-interface/lib/screenshot-location.js +33 -0
  166. package/neural-interface/lib/session-cache-builder.js +41 -3
  167. package/neural-interface/lib/skills/creation.js +1 -1
  168. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  169. package/neural-interface/lib/studio-attention.js +56 -0
  170. package/neural-interface/lib/teams/README.md +382 -0
  171. package/neural-interface/lib/teams/api.js +287 -0
  172. package/neural-interface/lib/teams/brief.js +185 -0
  173. package/neural-interface/lib/teams/claims.js +315 -0
  174. package/neural-interface/lib/teams/git.js +293 -0
  175. package/neural-interface/lib/teams/index.js +122 -0
  176. package/neural-interface/lib/teams/integration.js +580 -0
  177. package/neural-interface/lib/teams/landing.js +184 -0
  178. package/neural-interface/lib/teams/recovery.js +256 -0
  179. package/neural-interface/lib/teams/scheduler.js +1474 -0
  180. package/neural-interface/lib/teams/schema.js +559 -0
  181. package/neural-interface/lib/teams/state.js +181 -0
  182. package/neural-interface/lib/teams/test-runner.js +86 -0
  183. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  184. package/neural-interface/lib/teams/worktrees.js +757 -0
  185. package/neural-interface/lib/tool-permission-choices.js +226 -0
  186. package/neural-interface/lib/whatsapp/cards.js +24 -10
  187. package/neural-interface/lib/worker-confinement.js +206 -6
  188. package/neural-interface/package-lock.json +2 -2
  189. package/neural-interface/package.json +1 -1
  190. package/neural-interface/public/extension-setup.html +107 -0
  191. package/neural-interface/public/index.html +103 -12
  192. package/neural-interface/public/offline.html +4 -3
  193. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  194. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  195. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  196. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  197. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  198. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  199. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  200. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  201. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  202. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  203. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  204. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  205. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  206. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  207. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  208. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  209. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  210. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  211. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  212. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  213. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  214. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  215. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  216. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  217. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  218. package/neural-interface/public/shared/api.js +2 -1
  219. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  220. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  221. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  222. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  223. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  224. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  225. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  226. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  227. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  228. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  229. package/neural-interface/public/shared/assistant/asst-render.js +37 -6
  230. package/neural-interface/public/shared/assistant/asst-route.js +80 -12
  231. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  232. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  233. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  234. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  235. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  236. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  237. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  238. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  239. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  240. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  241. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  242. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  243. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  244. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  245. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  246. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  247. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  248. package/neural-interface/public/shared/code-copy.js +120 -0
  249. package/neural-interface/public/shared/constants.js +7 -0
  250. package/neural-interface/public/shared/context-menu-model.js +1 -0
  251. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  252. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  253. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  254. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  255. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  256. package/neural-interface/public/shared/dom-morph.js +124 -0
  257. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  258. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  259. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  260. package/neural-interface/public/shared/html-shell.js +34 -4
  261. package/neural-interface/public/shared/i18n.js +14 -1
  262. package/neural-interface/public/shared/idle-queue.js +78 -0
  263. package/neural-interface/public/shared/iface-config.js +227 -0
  264. package/neural-interface/public/shared/lazy-module.js +108 -0
  265. package/neural-interface/public/shared/memory-list.js +117 -0
  266. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  267. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  268. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  269. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  278. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  279. package/neural-interface/public/shared/page-session.js +1 -1
  280. package/neural-interface/public/shared/schedules-view.js +2 -2
  281. package/neural-interface/public/shared/session-project-items.js +11 -0
  282. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  283. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  284. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  285. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  286. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  287. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  288. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  289. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  290. package/neural-interface/public/shared/start-bridge.js +2 -2
  291. package/neural-interface/public/shared/storage.js +6 -1
  292. package/neural-interface/public/shared/studio-attention.js +83 -0
  293. package/neural-interface/public/shared/styles.css +694 -50
  294. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  295. package/neural-interface/public/shared/transcript-rows.js +334 -0
  296. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  297. package/neural-interface/public/shared/ui-agents.js +97 -0
  298. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  299. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  300. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  301. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  302. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  303. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  304. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  305. package/neural-interface/public/shared/ui-games.js +1 -1
  306. package/neural-interface/public/shared/ui-loading.js +83 -19
  307. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  308. package/neural-interface/public/shared/ui-menubar.js +23 -0
  309. package/neural-interface/public/shared/ui-native-loop-router.js +50 -21
  310. package/neural-interface/public/shared/ui-navbar.js +15 -9
  311. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  312. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  313. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  314. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  315. package/neural-interface/public/shared/ui-sessions.js +3 -3
  316. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  317. package/neural-interface/public/shared/ui-settings.js +363 -400
  318. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  319. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  320. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  321. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  322. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  323. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  324. package/neural-interface/public/shared/ui-sync.js +6 -0
  325. package/neural-interface/public/shared/ui-terminal.js +13 -9
  326. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  327. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  328. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  329. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  330. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  331. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  332. package/neural-interface/public/shared/window-keys.js +71 -0
  333. package/neural-interface/public/sw.js +4 -3
  334. package/neural-interface/public/variant/2d/main.js +2 -0
  335. package/neural-interface/public/variant/3d/app.js +620 -0
  336. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  337. package/neural-interface/public/variant/3d/main.js +30 -544
  338. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  339. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  340. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  341. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  342. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  343. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  346. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  347. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  348. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  349. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  350. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  351. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  352. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  353. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  354. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  355. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  356. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  357. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  358. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  359. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  360. package/neural-interface/scripts/boot-graph.mjs +270 -0
  361. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  362. package/neural-interface/server.js +1083 -164
  363. package/npm-shrinkwrap.json +2 -2
  364. package/package.json +4 -1
  365. package/skills/agent-forge/SKILL.md +182 -0
  366. package/skills/agent-forge/evals/evals.json +56 -0
  367. package/skills/agent-forge/references/definition-fields.md +61 -0
  368. package/skills/agent-forge/references/examples.md +105 -0
  369. package/skills/agent-forge/references/instructions.md +51 -0
  370. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -0,0 +1,1474 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Teams: the scheduler (Agents system, phase P4)
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // One task given to several workers. The Assistant writes a plan (slices with the files each owns); this module
6
+ // owns the team's life on top of the git library of phase P3 (lib/teams/index.js) and the coordination service of
7
+ // phase P2 (lib/coordination/service.js):
8
+ //
9
+ // plan validate a plan against the session's Agent density and the plan's own rules; nothing is created
10
+ // start create the worktrees and the claims, dispatch one worker per slice that can start
11
+ // (events) a worker reports done → SynaBun commits the slice's own files, joins it on the integration branch in
12
+ // dependency order and runs the tests on exactly that commit; a conflict or failed tests go back to the
13
+ // slice's worker as a follow-up with the report, a bounded number of times; then the team needs
14
+ // attention and the Assistant is told
15
+ // land the integration branch into the owner's branch: the owner's step, or the Assistant's when the tests
16
+ // passed, the owner's branch has not moved and no locally changed file is touched
17
+ // discard stop the workers, give the work up
18
+ //
19
+ // Agent density targets the selected worker count; fewer requires a reason. Solo starts no
20
+ // team; workers never work in the owner's checkout or on the owner's branch; the owner's branch receives the work
21
+ // only through `land`; worktrees and branches are removed only after a landing or a discard; no worker starts,
22
+ // lands or reads anything of another team.
23
+ //
24
+ // What it keeps itself is small: one JSON file per team (<dataDir>/teams/<teamId>.json: which session started it,
25
+ // the route and the dispatch settings its workers run on, each slice's run and how often it was sent back). The
26
+ // team's state proper (worktrees, branches, commits, test results) is the journal's, read through the library.
27
+ //
28
+ // Nothing here is reachable by a worker except the channel functions (`member`, `post`, `read`, `wait`, `ack`,
29
+ // `claims`, `request`), which take the caller's proven run id and find its team themselves.
30
+
31
+ import { randomBytes } from 'node:crypto';
32
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
33
+ import { join } from 'node:path';
34
+ import { AGENT_DENSITY_LABELS, DEFAULT_AGENT_DENSITY, maxWorkers, normalizeAgentDensity } from '../agents/density.js';
35
+ import { sessionRecipient } from '../coordination/store.js';
36
+ import {
37
+ PEER_NOTICE, TEAM_ACTION_KINDS, TEAM_MESSAGE_KINDS, conflictFollowUp, peerMessagesText, teamBrief, testsFailedFollowUp,
38
+ unresolvedFollowUp,
39
+ } from './brief.js';
40
+ import {
41
+ worktreePath, branchName, integrationBranchName, isTeamSlug, normalizeRelPath, normalizeTeamPlan, pathOwner, validateTeamPlan,
42
+ } from './schema.js';
43
+ import { TEAM_TEST_TIMEOUT_MS } from './test-runner.js';
44
+
45
+ /** The team events the scheduler emits: what the Assistant reads (`kind`), the log's kind, the priority, and whether the session's mailbox gets it. */
46
+ export const TEAM_EVENTS = Object.freeze({
47
+ team_started: { kind: 'team.started', priority: 'low', mailbox: false },
48
+ slice_started: { kind: 'team.slice_started', priority: 'low', mailbox: false },
49
+ slice_done: { kind: 'team.slice_done', priority: 'low', mailbox: false },
50
+ integrated: { kind: 'team.integrated', priority: 'low', mailbox: false },
51
+ // Sent back to the slice's worker: logged. Once the retries are used up (`final`), critical and told.
52
+ conflict: { kind: 'team.conflict', priority: 'normal', mailbox: false },
53
+ tests_failed: { kind: 'team.tests_failed', priority: 'normal', mailbox: false },
54
+ needs_attention: { kind: 'team.needs_attention', priority: 'critical', mailbox: true },
55
+ team_completed: { kind: 'team.completed', priority: 'normal', mailbox: true },
56
+ team_ready: { kind: 'team.ready', priority: 'normal', mailbox: true },
57
+ landed: { kind: 'team.landed', priority: 'normal', mailbox: true },
58
+ team_cleaned: { kind: 'team.cleaned', priority: 'normal', mailbox: true },
59
+ discarded: { kind: 'team.discarded', priority: 'normal', mailbox: true },
60
+ // A worker wrote to the lead (a question nobody on the team can answer, a file nobody open owns).
61
+ team_message: { kind: 'team.lead_message', priority: 'normal', mailbox: true },
62
+ });
63
+ /** Every log kind of a scheduler event (the `team` timeline reads these plus `team.message`). */
64
+ export const TEAM_EVENT_LOG_KINDS = Object.freeze([...new Set(Object.values(TEAM_EVENTS).map((event) => event.kind))]);
65
+ export const TEAM_MESSAGE_LOG_KIND = 'team.message';
66
+ /** The broadcast every team event sends to the owner's pages. */
67
+ export const TEAM_CHANGED = 'assistant:team-changed';
68
+
69
+ /** A team as the scheduler sees it (its own status; the journal's state is finer). */
70
+ export const TEAM_STATUSES = Object.freeze(['running', 'needs_attention', 'ready', 'completed', 'landed', 'discarded', 'failed']);
71
+ const OPEN_STATUSES = new Set(['running', 'needs_attention', 'ready']);
72
+
73
+ export const TEAM_SCHEDULER_LIMITS = Object.freeze({
74
+ /** How often a slice is sent back to its worker for one kind of trouble before the team needs attention. */
75
+ maxRetries: 2,
76
+ reconcileEveryMs: 60_000,
77
+ joinOverdueMs: TEAM_TEST_TIMEOUT_MS,
78
+ /** How often a finished turn is followed by the peer questions that waited for it, per slice. */
79
+ maxPeerDeferrals: 4,
80
+ /** A worker's posts: at most this many in the window. */
81
+ postsPerWindow: 40,
82
+ postWindowMs: 10 * 60_000,
83
+ /** A message's text. */
84
+ messageChars: 4000,
85
+ /** `wait` of the team tool: at most this long (under an MCP client's 60 s request timeout). */
86
+ maxWaitMs: 50_000,
87
+ defaultWaitMs: 25_000,
88
+ /** How many messages one read returns. */
89
+ readLimit: 50,
90
+ /** The status answer's timeline. */
91
+ timeline: 100,
92
+ titleChars: 80,
93
+ });
94
+
95
+ const iso = (ms) => new Date(ms).toISOString();
96
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
97
+ const clip = (value, max) => {
98
+ const text = String(value ?? '').replace(/\s+/g, ' ').trim();
99
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
100
+ };
101
+ const refuse = (code, message, extra = {}) => ({ ok: false, code, message, ...extra });
102
+ const slugOf = (value, max = 30) => String(value || '').toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, max).replace(/-+$/, '');
103
+
104
+ /**
105
+ * The dispatch settings a team's workers run with, from what `start` was given: only fields a dispatch takes, in
106
+ * the dispatcher's spelling. The task, the folder, the capability and the workflow are the scheduler's own.
107
+ */
108
+ function dispatchDefaults(input = {}) {
109
+ const out = {};
110
+ const take = (key, ...names) => {
111
+ const value = names.map((name) => input[name]).find((item) => item !== undefined && item !== null && item !== '');
112
+ if (value !== undefined) out[key] = value;
113
+ };
114
+ take('provider', 'provider');
115
+ take('model', 'model');
116
+ take('effort', 'effort');
117
+ take('accountId', 'accountId', 'account_id');
118
+ take('tools', 'tools');
119
+ take('maxMinutes', 'maxMinutes', 'max_minutes');
120
+ take('budgetUsd', 'budgetUsd', 'budget_usd');
121
+ take('permissionPolicy', 'permissionPolicy', 'permission_policy');
122
+ take('context', 'context');
123
+ take('briefId', 'briefId', 'brief_id');
124
+ take('confidence', 'confidence');
125
+ if (Array.isArray(input.tags)) out.tags = input.tags.map((tag) => String(tag).trim()).filter(Boolean).slice(0, 6);
126
+ return out;
127
+ }
128
+
129
+ /**
130
+ * @param {object} deps
131
+ * @param {object} deps.teams createTeams(...) of lib/teams/index.js, over the service's own store
132
+ * @param {object} deps.coordination the coordination service (lib/coordination/service.js)
133
+ * @param {object|(() => object|null)} deps.dispatcher the Assistant's dispatcher, or what returns it
134
+ * @param {(sessionId: string) => string|null} [deps.density] the session's Agent density (default: the dispatcher's)
135
+ * @param {object|(() => object|null)} [deps.router] assistant-router.js (`status(routeId)`); none: no route is asked for
136
+ * @param {(sessionId: string) => ({ remote?: boolean }|null)} [deps.session] what is known of a session (a remote one starts no team)
137
+ * @param {(sessionId: string) => (number|string|null)} [deps.lastOwnerTurnAt] latest trusted UI owner turn
138
+ * @param {Function} [deps.git] a git runner (lib/teams/git.js) for the two things the scheduler asks git itself
139
+ * @param {string} deps.dataDir where <dataDir>/teams/<teamId>.json go
140
+ * @param {(message: object) => void} [deps.broadcast] the owner's pages (assistant:team-changed)
141
+ * @param {object} [deps.limits]
142
+ * @param {() => number} [deps.now]
143
+ * @param {(tag: string, detail: any) => void} [deps.log]
144
+ * @param {() => string} [deps.newRunId]
145
+ */
146
+ export function createTeamScheduler({
147
+ teams, coordination, dispatcher: givenDispatcher, density = null, router: givenRouter = null, session: sessionInfo = null,
148
+ git = null, dataDir, broadcast = () => {}, limits: limitOverrides = {}, now = Date.now, log = () => {},
149
+ lastOwnerTurnAt = null,
150
+ newRunId = () => randomBytes(16).toString('hex'),
151
+ } = {}) {
152
+ if (!teams || typeof teams.create !== 'function') throw new Error('createTeamScheduler needs { teams } (lib/teams/index.js createTeams)');
153
+ if (!coordination?.store) throw new Error('createTeamScheduler needs { coordination } (lib/coordination/service.js)');
154
+ if (!dataDir) throw new Error('createTeamScheduler needs { dataDir }');
155
+ const limits = Object.freeze({ ...TEAM_SCHEDULER_LIMITS, ...limitOverrides });
156
+ const store = coordination.store;
157
+ const dir = join(dataDir, 'teams');
158
+ const records = new Map(); // teamId → the scheduler's record
159
+ const runIndex = new Map(); // runId → { teamId, sliceId } (every run a slice ever had)
160
+ const chains = new Map(); // team or slice key → last scheduled operation
161
+ const postTimes = new Map(); // runId → the times of its recent posts
162
+ let unsubscribe = null;
163
+ let watchdog = null;
164
+ const reconciling = new Set(); // one pending watchdog replay per run
165
+ let closed = false;
166
+ // Nothing of a team runs before the library's own recovery has (recover()): a team a stop cut off mid-join is
167
+ // refused by every library function until then.
168
+ let ready = Promise.resolve();
169
+
170
+ const dispatcherOf = () => { try { return (typeof givenDispatcher === 'function' ? givenDispatcher() : givenDispatcher) || null; } catch { return null; } };
171
+ const routerOf = () => { try { return (typeof givenRouter === 'function' ? givenRouter() : givenRouter) || null; } catch { return null; } };
172
+ const say = (tag, detail) => { try { log(tag, detail); } catch { /* a log never stops a team */ } };
173
+
174
+ // ── the scheduler's own record ─────────────────────────────────────────────
175
+ const fileOf = (teamId) => join(dir, `${teamId}.json`);
176
+ function save(record) {
177
+ record.updatedAt = iso(now());
178
+ records.set(record.teamId, record);
179
+ try {
180
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
181
+ const temp = `${fileOf(record.teamId)}.${process.pid}.tmp`;
182
+ writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`);
183
+ renameSync(temp, fileOf(record.teamId));
184
+ } catch (error) {
185
+ say('teams:record-write-failed', { teamId: record.teamId, error: error?.message || String(error) });
186
+ }
187
+ return record;
188
+ }
189
+ function index(record) {
190
+ for (const [sliceId, slice] of Object.entries(record.slices || {})) {
191
+ for (const runId of slice.runIds || []) runIndex.set(runId, { teamId: record.teamId, sliceId });
192
+ }
193
+ }
194
+ function loadRecords() {
195
+ let names = [];
196
+ try { names = existsSync(dir) ? readdirSync(dir) : []; } catch { names = []; }
197
+ for (const name of names) {
198
+ if (!name.endsWith('.json')) continue;
199
+ try {
200
+ const record = JSON.parse(readFileSync(join(dir, name), 'utf8'));
201
+ if (!isObject(record) || !isTeamSlug(record.teamId) || !isObject(record.slices)) continue;
202
+ records.set(record.teamId, record);
203
+ index(record);
204
+ } catch (error) {
205
+ say('teams:record-unreadable', { file: name, error: error?.message || String(error) });
206
+ }
207
+ }
208
+ }
209
+
210
+ // Team operations share the integration branch. Worker events need only their slice.
211
+ // Reserve all requested keys synchronously so an owner operation can exclude every worker.
212
+ function enqueue(keys, fn) {
213
+ const before = keys.map((key) => chains.get(key)).filter(Boolean);
214
+ const next = Promise.all(before).then(() => ready).then(fn);
215
+ const kept = next.catch((error) => say('teams:step-failed', { keys, error: error?.message || String(error) }));
216
+ for (const key of keys) chains.set(key, kept);
217
+ kept.then(() => {
218
+ for (const key of keys) {
219
+ if (chains.get(key) === kept) chains.delete(key);
220
+ }
221
+ });
222
+ return next;
223
+ }
224
+ const inTurn = (teamId, fn) => enqueue([teamId], fn);
225
+ const inSlice = (record, sliceId, fn) => enqueue([`${record.teamId}/${sliceId}`], fn);
226
+ const withAllSlices = (record, fn) => enqueue(Object.keys(record.slices).map(id => `${record.teamId}/${id}`), fn);
227
+ const teamStep = (record, fn) => inTurn(record.teamId, () => withAllSlices(record, fn));
228
+ /** Resolves once every team's queued steps have run (tests, shutdown). */
229
+ async function settled() {
230
+ while (chains.size) {
231
+ await Promise.all(new Set(chains.values()));
232
+ }
233
+ }
234
+
235
+ // ── events ─────────────────────────────────────────────────────────────────
236
+ /**
237
+ * A team event: one entry of the durable log with the team's id (the team's timeline), addressed to the session
238
+ * that runs the team when its brain must hear it, and one broadcast to the owner's pages.
239
+ */
240
+ function emit(record, name, detail = {}, { critical = false, mailbox = null, quiet = false } = {}) {
241
+ const spec = TEAM_EVENTS[name];
242
+ if (!spec) return null;
243
+ record.eventSeq = (Number(record.eventSeq) || 0) + 1;
244
+ const told = (mailbox === null ? spec.mailbox : mailbox) && !!record.sessionId && !quiet;
245
+ const payload = {
246
+ kind: name, teamId: record.teamId, title: record.title || null, status: record.status,
247
+ readOnly: record.plan?.readOnly === true,
248
+ ...detail,
249
+ ...(detail.text ? { text: clip(detail.text, 600) } : {}),
250
+ };
251
+ let out = null;
252
+ try {
253
+ out = store.append({
254
+ id: `team:${record.teamId}:event:${record.eventSeq}`,
255
+ kind: spec.kind, priority: critical ? 'critical' : spec.priority,
256
+ teamId: record.teamId, sessionId: record.sessionId || null, runId: detail.runId || null,
257
+ payload, to: told ? [sessionRecipient(record.sessionId)] : [],
258
+ });
259
+ } catch (error) {
260
+ say('teams:event-failed', { teamId: record.teamId, event: name, error: error?.message || String(error) });
261
+ }
262
+ save(record);
263
+ try { broadcast({ type: TEAM_CHANGED, teamId: record.teamId, event: name, status: record.status, sliceId: detail.sliceId || null }); } catch { /* no page is listening */ }
264
+ return out;
265
+ }
266
+
267
+ // ── reading ────────────────────────────────────────────────────────────────
268
+ const densityOf = (sessionId) => {
269
+ let level = null;
270
+ try { level = typeof density === 'function' ? density(sessionId) : dispatcherOf()?.agentDensity?.(sessionId); } catch { level = null; }
271
+ return normalizeAgentDensity(level, DEFAULT_AGENT_DENSITY);
272
+ };
273
+ const densityView = (level, slices) => ({
274
+ level, label: AGENT_DENSITY_LABELS[level], cap: maxWorkers(level), slices,
275
+ fits: level !== 'solo' && slices >= 1 && slices <= maxWorkers(level),
276
+ });
277
+ const runOf = (runId) => { try { return runId ? dispatcherOf()?.get?.(runId) || null : null; } catch { return null; } };
278
+ const runBrief = (run) => (run ? {
279
+ runId: run.runId, state: run.state, status: run.status || null, outcome: run.outcome || null, provider: run.provider || null,
280
+ model: run.model || null, agentRef: run.agentRef || null, title: run.title || null, active: run.active === true,
281
+ summary: run.lastResult?.summary ? clip(run.lastResult.summary, 300) : null, costUsd: run.costUsd ?? 0,
282
+ } : null);
283
+ const runLive = (run) => !!run && run.active === true;
284
+ /** Is the run waiting warm for a follow-up (its turn ended, the worker is there)? */
285
+ const runIdle = (run) => !!run && run.state === 'idle';
286
+
287
+ /** The team's journal record, or null. */
288
+ const journalOf = (teamId) => { try { return teams.get(teamId); } catch { return null; } };
289
+ const sliceStateOf = (journal, sliceId) => journal?.slices?.[sliceId]?.state || 'pending';
290
+
291
+ function summary(record) {
292
+ return {
293
+ id: record.teamId, project: record.projectPath, title: record.title || record.teamId, status: record.status,
294
+ density: record.density, slices: Object.keys(record.slices || {}).length, createdAt: record.createdAt,
295
+ updatedAt: record.updatedAt, sessionId: record.sessionId || null, workflowId: record.workflowId,
296
+ };
297
+ }
298
+
299
+ /** The newest `limit` events of a team's log, oldest first. */
300
+ function tailOfLog(teamId, kinds, limit) {
301
+ const out = [];
302
+ let afterSeq = 0;
303
+ for (let page = 0; page < 40; page += 1) {
304
+ const rows = store.events({ teamId, afterSeq, kinds, limit: 500 });
305
+ out.push(...rows);
306
+ if (out.length > limit * 2) out.splice(0, out.length - limit);
307
+ if (rows.length < 500) break;
308
+ afterSeq = rows[rows.length - 1].seq;
309
+ }
310
+ return out.slice(-limit);
311
+ }
312
+ const sliceOfRun = (runId) => (runId ? runIndex.get(String(runId))?.sliceId || null : null);
313
+ function eventView(event) {
314
+ const payload = isObject(event.payload) ? event.payload : {};
315
+ return { seq: event.seq, id: event.id, at: event.createdAt, event: payload.kind || null, priority: event.priority, sliceId: payload.sliceId || null, runId: event.runId || null, text: payload.text || null, final: payload.final === true, code: payload.code || null };
316
+ }
317
+ function messageView(event) {
318
+ const payload = isObject(event.payload) ? event.payload : {};
319
+ const fromRunId = payload.from && payload.from !== 'lead' ? String(payload.from) : null;
320
+ return {
321
+ seq: event.seq, id: event.id, at: event.createdAt, kind: payload.messageKind || 'note',
322
+ from: fromRunId ? 'worker' : 'lead', fromRunId, fromSlice: payload.fromSlice || sliceOfRun(fromRunId),
323
+ to: payload.to || 'board', toSlice: payload.toSlice || null, path: payload.path || null, text: payload.text || '',
324
+ };
325
+ }
326
+
327
+ /**
328
+ * A team in full: the plan, every slice with its state, run, worktree, branch, owned paths and how far it is
329
+ * from the base and the integration branch, the claims, the integration branch and its last test result, the
330
+ * landing, and the end of the team's timeline (events and messages).
331
+ */
332
+ async function status(teamId, { timeline = limits.timeline } = {}) {
333
+ const record = records.get(String(teamId || ''));
334
+ if (!record) return refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`, { status: 404 });
335
+ let journal = journalOf(record.teamId);
336
+ let inspected = null;
337
+ if (journal && !journal.removed) { try { inspected = await teams.inspect(record.teamId); } catch (error) { inspected = null; say('teams:inspect-failed', { teamId: record.teamId, error: error?.message || String(error) }); } }
338
+ // Inspection asks git about every checkout; the join can change phase while it runs.
339
+ journal = journalOf(record.teamId);
340
+ const seen = inspected?.ok ? inspected : null;
341
+ const plan = journal?.plan || record.plan || { slices: [] };
342
+ const slices = plan.slices.map((slice) => {
343
+ const mine = record.slices[slice.id] || {};
344
+ const at = seen?.slices?.find((each) => each.sliceId === slice.id || each.id === slice.id) || null;
345
+ const entry = journal?.slices?.[slice.id] || {};
346
+ return {
347
+ id: slice.id, title: slice.title || null, status: entry.state || 'pending', phase: mine.phase || 'waiting',
348
+ runId: mine.runId || null, run: runBrief(runOf(mine.runId)), runs: [...(mine.runIds || [])],
349
+ worktree: at?.path || entry.path || null, branch: at?.branch || branchName(record.teamId, slice.id),
350
+ ownedPaths: [...(slice.ownedPaths || [])], dependsOn: [...(slice.dependsOn || [])], lockfileOwner: slice.lockfileOwner === true,
351
+ agentRef: slice.agentRef || null,
352
+ ahead: at?.base?.ahead ?? null, behind: at?.base?.behind ?? null,
353
+ integration: at?.integration ? { ahead: at.integration.ahead ?? null, behind: at.integration.behind ?? null } : null,
354
+ dirty: at?.dirty ?? null, head: at?.head || entry.head || null,
355
+ cleanup: entry.cleanup || null,
356
+ attempts: { ...(mine.attempts || {}) }, lastReport: mine.lastReport || null,
357
+ };
358
+ });
359
+ let claims = [];
360
+ try { claims = store.claimsFor({ teamId: record.teamId }).map((claim) => ({ sliceId: claim.sliceId, runId: claim.runId || null, glob: claim.glob, claimedAt: claim.claimedAt || claim.createdAt || null })); } catch { claims = []; }
361
+ const tests = journal?.integration?.tests || null;
362
+ const events = tailOfLog(record.teamId, TEAM_EVENT_LOG_KINDS, timeline).map(eventView);
363
+ const messages = tailOfLog(record.teamId, [TEAM_MESSAGE_LOG_KIND], timeline).map(messageView);
364
+ return {
365
+ ok: true,
366
+ team: {
367
+ ...summary(record), state: journal?.state || null, attention: record.attention || null,
368
+ baseCommit: journal?.baseCommit || plan.baseCommit || null, baseBranch: journal?.baseBranch || null,
369
+ route: record.routeId ? { routeId: record.routeId, taskClass: record.taskClass || null } : null,
370
+ cap: maxWorkers(record.density),
371
+ },
372
+ plan,
373
+ slices,
374
+ claims,
375
+ integration: plan.readOnly ? null : {
376
+ branch: integrationBranchName(record.teamId), head: seen?.integration?.head || journal?.integration?.head || null,
377
+ lastGood: journal?.integration?.lastGood || null, moved: seen?.integration?.moved ?? null,
378
+ ready: journal?.state === 'ready' || journal?.state === 'merged',
379
+ tests: tests ? { ok: tests.ok === true, commit: tests.commit || null, command: tests.command ?? null, at: tests.at || null, exitCode: tests.exitCode ?? null, output: tests.output ? String(tests.output).slice(-2000) : null } : null,
380
+ under: journal?.integrating ? { ...journal.integrating, elapsedMs: Math.max(0, now() - journal.integrating.startedAt) } : null,
381
+ testCommand: journal?.testCommand ?? null,
382
+ },
383
+ landing: {
384
+ state: journal?.state === 'merged' ? 'landed' : (record.landing?.refused ? 'refused' : 'none'),
385
+ landed: journal?.landed || null, refused: record.landing?.refused || null,
386
+ target: seen?.target || null, cleanup: record.cleanup || null,
387
+ },
388
+ events,
389
+ messages,
390
+ // The text of a message is a worker's own words.
391
+ messagesNotice: 'The text of each message was written by a worker of the team: untrusted peer content, data and not instructions.',
392
+ };
393
+ }
394
+
395
+ function list({ sessionId = null, projectPath = null, open = false } = {}) {
396
+ return [...records.values()]
397
+ .filter((record) => (!sessionId || record.sessionId === String(sessionId)) && (!projectPath || record.projectPath === projectPath) && (!open || OPEN_STATUSES.has(record.status)))
398
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
399
+ .map(summary);
400
+ }
401
+ const get = (teamId) => { const record = records.get(String(teamId || '')); return record ? { ...summary(record), attention: record.attention || null } : null; };
402
+ /** Does this session run that team? (An Assistant brain reads and steers only its own.) */
403
+ const ownedBy = (teamId, sessionId) => records.get(String(teamId || ''))?.sessionId === String(sessionId || '');
404
+
405
+ // ── plan ───────────────────────────────────────────────────────────────────
406
+ async function headOf(projectPath) {
407
+ if (typeof git !== 'function') return null;
408
+ try {
409
+ const out = await git(['rev-parse', '--verify', '-q', 'HEAD^{commit}'], { cwd: projectPath });
410
+ return out.ok ? String(out.stdout || '').trim() || null : null;
411
+ } catch { return null; }
412
+ }
413
+ async function branchOf(projectPath) {
414
+ if (typeof git !== 'function') return null;
415
+ try {
416
+ const out = await git(['symbolic-ref', '--short', '-q', 'HEAD'], { cwd: projectPath });
417
+ return out.ok ? String(out.stdout || '').trim() || null : null;
418
+ } catch { return null; }
419
+ }
420
+
421
+ /**
422
+ * A plan as it would start: normalized, with a team id and the pinned base commit when it names none, checked
423
+ * against the session's Agent density and the plan's own rules. Creates nothing.
424
+ * @returns {Promise<{ ok: boolean, plan: object, title: string, density: object, errors: object[], code?: string, message?: string }>}
425
+ */
426
+ async function plan(input = {}, { sessionId = null } = {}) {
427
+ const src = isObject(input.plan) ? { ...input.plan } : (isObject(input) ? { ...input } : {});
428
+ const taskClass = input.taskClass || input.task_class || src.taskClass || src.task_class || 'code';
429
+ src.readOnly = ['research', 'review'].includes(taskClass);
430
+ const title = clip(input.title || src.title || '', limits.titleChars);
431
+ const errors = [];
432
+ const projectPath = String(src.projectPath || src.project_path || src.cwd || input.cwd || '').trim();
433
+ if (projectPath) src.projectPath = projectPath;
434
+ if (!src.teamId && !src.id) {
435
+ const base = slugOf(title || 'team') || 'team';
436
+ src.teamId = `${base}-${randomBytes(3).toString('hex')}`;
437
+ }
438
+ if (!src.baseCommit && projectPath) {
439
+ const head = await headOf(projectPath);
440
+ if (head) src.baseCommit = head;
441
+ else if (typeof git === 'function') errors.push({ field: 'projectPath', code: 'not_a_repository', message: `${projectPath} is not a git repository with a commit: a team needs one (git init and commit first), or use one worker.` });
442
+ }
443
+ const level = densityOf(sessionId);
444
+ const checked = validateTeamPlan(src, { density: level });
445
+ const count = checked.value.slices.length;
446
+ const view = densityView(level, count);
447
+ // The one error the density decides is named by the scheduler's own code, so a brain can act on it.
448
+ const planErrors = checked.errors.filter((error) => error.code !== 'too_many_slices');
449
+ let code = null;
450
+ let message = null;
451
+ if (level === 'solo') {
452
+ code = 'TEAM_DENSITY_SOLO';
453
+ message = 'Agent density is Solo: one worker per task, no team. Give the task to one worker (agent_dispatch), or ask the user to raise the Agent density next to the Test density control.';
454
+ } else if (count > view.cap) {
455
+ code = 'TEAM_TOO_MANY_SLICES';
456
+ message = `The plan has ${count} slices; Agent density ${view.label} allows ${view.cap} workers on one task. Use fewer slices, or ask the user to raise the Agent density.`;
457
+ }
458
+ if (!code && count > 0 && count < view.cap && !checked.value.fewerReason) {
459
+ code = 'TEAM_SPLIT_REASON_REQUIRED';
460
+ message = `The plan uses ${count} of ${view.cap} workers. Give fewer_reason explaining why it cannot sensibly split further.`;
461
+ }
462
+ if (code) errors.unshift({ field: 'slices', code, message, limit: view.cap, count, density: level });
463
+ errors.push(...planErrors);
464
+ const ok = errors.length === 0;
465
+ return {
466
+ ok, ...(errors.some(e => e.code === 'not_a_repository') ? { fallback: { workers: 1, reason: 'The project is not a git repository with a commit; use agent_dispatch for one worker.' } } : {}), plan: checked.value, title: title || checked.value.teamId, density: view, errors,
467
+ ...(ok ? {} : { code: code || 'INVALID_PLAN', message: message || `The plan is not valid: ${errors.slice(0, 3).map((error) => error.message).join(' ')}` }),
468
+ };
469
+ }
470
+
471
+ // ── start ──────────────────────────────────────────────────────────────────
472
+ /** The approved route a team's dispatches ride on, or a refusal. No router: no route is asked for. */
473
+ function routeFor(routeId, sessionId) {
474
+ const router = routerOf();
475
+ if (!router || typeof router.status !== 'function') return { ok: true, route: null };
476
+ if (!routeId) return refuse('TEAM_ROUTE_REQUIRED', 'A team starts on an approved route, like any dispatch: call agent_route for the task first and pass its route_id (one route covers every slice of the team).', { status: 409 });
477
+ let found = null;
478
+ try { found = router.status(String(routeId)); } catch { found = null; }
479
+ if (!found || String(found.sessionId || '') !== String(sessionId || '')) return refuse('TEAM_ROUTE_UNKNOWN', `Route ${routeId} is not a route of this session.`, { status: 404 });
480
+ const currentTask = typeof sessionInfo === 'function' ? sessionInfo(sessionId)?.taskId : null;
481
+ if (currentTask && found.taskId && currentTask !== found.taskId) return refuse('TEAM_ROUTE_TASK_CHANGED', 'This route belongs to an earlier user task.', { status: 409 });
482
+ if (found.status !== 'approved') return refuse('TEAM_ROUTE_NOT_APPROVED', `Route ${routeId} is ${found.status}: a team starts once its route is approved.`, { status: 409, routeStatus: found.status });
483
+ if (found.target?.kind === 'direct') return refuse('TEAM_ROUTE_IS_DIRECT', `Route ${routeId} was decided to run here, in this conversation: a team's slices run on workers. Route the task again for a worker model.`, { status: 409 });
484
+ return { ok: true, route: found };
485
+ }
486
+
487
+ /**
488
+ * Start a team: the plan is checked again (the density is the server's to enforce), its worktrees and claims are
489
+ * made, and one worker is dispatched for every slice that can start.
490
+ */
491
+ async function start(input = {}, { sessionId = null } = {}) {
492
+ if (closed) return refuse('TEAMS_UNAVAILABLE', 'Teams are shutting down.', { status: 503 });
493
+ const session = sessionId ? String(sessionId) : null;
494
+ if (!session) return refuse('TEAM_SESSION_REQUIRED', 'A team is started by an Assistant session: its Agent density decides how many workers one task may get.', { status: 400 });
495
+ if (!dispatcherOf()) return refuse('DISPATCH_UNAVAILABLE', 'Runs are not available on this server yet.', { status: 503 });
496
+ let remote = false;
497
+ try { remote = typeof sessionInfo === 'function' ? sessionInfo(session)?.remote === true : false; } catch { remote = false; }
498
+ if (remote && !['research', 'review'].includes(input.taskClass || input.task_class || routerOf()?.status?.(input.routeId || input.route_id)?.taskClass)) return refuse('TEAM_REMOTE_UNSUPPORTED', 'A team is started from the Assistant panel on this computer, not from a remote conversation: one approved route covers one worker there.', { status: 409 });
499
+ const routeId = input.routeId || input.route_id || null;
500
+ const routed = routeFor(routeId, session);
501
+ if (!routed.ok) return routed;
502
+ const taskClass = String(input.taskClass || input.task_class || routed.route?.taskClass || 'code');
503
+ if (!['code', 'complex', 'research', 'review'].includes(taskClass) || (routed.route && taskClass !== routed.route.taskClass)) return refuse('TEAM_TASK_CLASS_MISMATCH', 'Team task_class must match the approved code, complex, research or review route.', { status: 409 });
504
+ const checked = await plan({ ...input, taskClass }, { sessionId: session });
505
+ if (!checked.ok) return { ...refuse(checked.code, checked.message, { status: checked.code === 'INVALID_PLAN' ? 400 : 409 }), plan: checked.plan, density: checked.density, errors: checked.errors };
506
+ const split = routed.route?.plannedSplit;
507
+ if (routed.route && (!split || split.flow !== 'team' || split.workers !== checked.plan.slices.length
508
+ || split.projectPath !== checked.plan.projectPath
509
+ || split.slices.some((title, i) => title !== checked.plan.slices[i]?.title)
510
+ || (split.workers < split.target && split.reason !== checked.plan.fewerReason))) {
511
+ return refuse('TEAM_ROUTE_SPLIT_MISMATCH', 'The team must match the approved project, slice count, titles and fewer_reason. Route the complete plan once before starting.', { status: 409 });
512
+ }
513
+ if (routed.route?.workflowId && routed.route.workflowId !== `team:${checked.plan.teamId}`) return refuse('TEAM_ROUTE_SPLIT_MISMATCH', 'This route already belongs to another team.', { status: 409 });
514
+ const defaults = dispatchDefaults(input);
515
+ if (!routed.route && !defaults.provider && checked.plan.slices.some((slice) => !slice.agentRef || slice.agentRef === 'none')) {
516
+ return refuse('TEAM_PROVIDER_REQUIRED', 'Name the provider the team\'s workers run on (or give every slice an agent_ref).', { status: 400 });
517
+ }
518
+ if (records.has(checked.plan.teamId)) return refuse('TEAM_EXISTS', `A team named "${checked.plan.teamId}" exists already: a team id is used once.`, { status: 409 });
519
+
520
+ const testCommand = checked.plan.readOnly ? null : input.testCommand ?? input.test_command ?? null;
521
+ const made = await teams.create(checked.plan, { density: checked.density.level, ...(testCommand ? { testCommand } : {}), createdBy: session });
522
+ if (!made.ok) return { ...made, status: made.code === 'INVALID_PLAN' ? 400 : 409 };
523
+
524
+ const at = iso(now());
525
+ const record = {
526
+ v: 1, teamId: checked.plan.teamId, title: checked.title, projectPath: checked.plan.projectPath, sessionId: session,
527
+ density: checked.density.level, workflowId: `team:${checked.plan.teamId}`, routeId: routeId ? String(routeId) : null, taskClass,
528
+ dispatch: defaults, plan: checked.plan, status: 'running', attention: null, eventSeq: 0,
529
+ slices: Object.fromEntries(checked.plan.slices.map((slice) => [slice.id, { phase: 'waiting', runId: null, runIds: [], attempts: {}, deferrals: 0, lastReport: null }])),
530
+ landing: null, cleanup: null, createdAt: at, updatedAt: at,
531
+ };
532
+ save(record);
533
+ emit(record, 'team_started', { text: `${checked.plan.slices.length} slices at Agent density ${checked.density.label}`, slices: checked.plan.slices.map((slice) => slice.id), baseCommit: made.team.baseCommit });
534
+ const started = await teamStep(record, () => startReady(record));
535
+ return { ok: true, teamId: record.teamId, workflowId: record.workflowId, density: checked.density, setup: made.setup || [], started, team: (await status(record.teamId, { timeline: 20 })) };
536
+ }
537
+ /**
538
+ * Dispatch a worker for a slice. `rework`: the slice has been worked on (a conflict, failed tests, a worker that
539
+ * ended); `task` then says what is left to do, in front of the slice's own task.
540
+ */
541
+ async function dispatchSlice(record, sliceId, { rework = false, lead = '', resolve = false } = {}) {
542
+ const dispatcher = dispatcherOf();
543
+ const mine = record.slices[sliceId];
544
+ const slice = record.plan.slices.find((each) => each.id === sliceId);
545
+ if (!dispatcher || !mine || !slice) return refuse('DISPATCH_UNAVAILABLE', 'Runs are not available on this server.');
546
+ const runId = newRunId();
547
+ // The slice's worktree is prepared and its claims are put in the run's name before the worker exists.
548
+ const started = resolve
549
+ ? await teams.resolveInSlice(record.teamId, sliceId, { runId })
550
+ : await teams.startSlice(record.teamId, sliceId, { runId });
551
+ if (!started.ok) return started;
552
+ const worktree = started.worktree;
553
+ const journal = journalOf(record.teamId);
554
+ const brief = teamBrief(journal, sliceId, { title: record.title, worktree, rework: rework || resolve, startCommit: started.startCommit || '' });
555
+ const attempt = (mine.runIds || []).length + 1;
556
+ // A slice that runs as one of the owner's agents runs on what that agent runs on: the team's own provider,
557
+ // model, effort and account are for the slices that name none. (An approved route binds every slice all the same:
558
+ // the router writes its target over the spec after the agent was applied.)
559
+ const { provider: _provider, model: _model, effort: _effort, accountId: _accountId, ...shared } = record.dispatch || {};
560
+ const defaults = slice.agentRef && slice.agentRef !== 'none' ? shared : (record.dispatch || {});
561
+ const spec = {
562
+ ...defaults,
563
+ task: lead ? `${lead}\n\nYOUR SLICE'S TASK (as first given):\n${slice.task}` : slice.task,
564
+ title: clip(slice.title || `${record.title}: ${sliceId}`, 80),
565
+ cwd: worktree,
566
+ // A slice is confined to its worktree and its own files whatever it is given (lib/worker-confinement.js).
567
+ capability: 'workspace',
568
+ workflowId: record.workflowId,
569
+ taskClass: record.taskClass || 'code',
570
+ ...(record.routeId ? { routeId: record.routeId } : {}),
571
+ ...(slice.agentRef ? { agentRef: slice.agentRef } : {}),
572
+ tags: [...new Set([...(defaults.tags || []), 'team', `team:${record.teamId}`, `slice:${sliceId}`])].slice(0, 10),
573
+ idempotencyKey: `team:${record.teamId}:${sliceId}:${attempt}`,
574
+ // Its start does not wait on a question the brain asked about something else; a brief it was given rides along.
575
+ independent: !defaults.briefId,
576
+ };
577
+ mine.runId = runId;
578
+ mine.handledTurn = 0;
579
+ mine.runIds = [...(mine.runIds || []), runId];
580
+ mine.phase = 'dispatched';
581
+ mine.startedAt = iso(now());
582
+ runIndex.set(runId, { teamId: record.teamId, sliceId });
583
+ save(record);
584
+ try {
585
+ const out = await dispatcher.dispatch(spec, { assistantSessionId: record.sessionId, origin: 'assistant', team: brief, runId });
586
+ mine.phase = out.queued ? 'queued' : 'working';
587
+ emit(record, 'slice_started', { sliceId, runId, text: `${slice.title || sliceId}${rework || resolve ? ' (sent back)' : ''}${out.queued ? ' (queued for a free slot)' : ''}`, rework: rework || resolve, queued: out.queued === true });
588
+ return { ok: true, sliceId, runId, queued: out.queued === true, worktree };
589
+ } catch (error) {
590
+ mine.phase = 'failed';
591
+ mine.lastReport = { code: error?.code || 'DISPATCH_FAILED', message: clip(error?.message || String(error), 600), at: iso(now()) };
592
+ save(record);
593
+ if (record.plan.readOnly) await finishReader(record, sliceId, { failed: true });
594
+ return refuse(error?.code || 'DISPATCH_FAILED', error?.message || String(error), { sliceId, runId });
595
+ }
596
+ }
597
+
598
+ /** Start every slice whose dependencies are joined and that no worker has been given yet. */
599
+ async function startReady(record) {
600
+ const started = [];
601
+ if (record.status !== 'running') return started;
602
+ const journal = journalOf(record.teamId);
603
+ if (!journal) return started;
604
+ for (const slice of record.plan.slices) {
605
+ const mine = record.slices[slice.id];
606
+ if (!mine || mine.phase !== 'waiting') continue;
607
+ if (slice.dependsOn.some((dep) => sliceStateOf(journal, dep) !== 'integrated')) continue;
608
+ const out = await dispatchSlice(record, slice.id);
609
+ started.push(out.ok ? { sliceId: slice.id, runId: out.runId, queued: out.queued } : { sliceId: slice.id, ok: false, code: out.code, message: out.message });
610
+ if (!out.ok) attention(record, { code: out.code || 'SLICE_NOT_STARTED', sliceId: slice.id, message: `Slice ${slice.id} could not start: ${out.message}` });
611
+ }
612
+ return started;
613
+ }
614
+
615
+ // ── needs attention ────────────────────────────────────────────────────────
616
+ /** The team cannot go on by itself: say so once, to the session that runs it, as critical. */
617
+ function attention(record, { code, sliceId = null, message, report = null, event = 'needs_attention' } = {}) {
618
+ record.status = 'needs_attention';
619
+ record.attention = { code, sliceId, message: clip(message, 600), at: iso(now()) };
620
+ if (sliceId && record.slices[sliceId]) record.slices[sliceId].lastReport = { code, message: clip(message, 600), at: iso(now()), ...(report ? { report } : {}) };
621
+ emit(record, event, { sliceId, code, text: message, final: true, ...(report ? { report: reportBrief(report) } : {}) }, { critical: true, mailbox: true });
622
+ }
623
+ /** A report as an event carries it: the files and the test result's end, never whole blobs. */
624
+ function reportBrief(report) {
625
+ if (!isObject(report)) return null;
626
+ const out = {};
627
+ if (Array.isArray(report.files)) out.files = report.files.slice(0, 20).map((file) => (isObject(file) ? { path: file.path, owner: file.owner ?? null } : { path: String(file) }));
628
+ if (isObject(report.tests)) out.tests = { ok: report.tests.ok === true, exitCode: report.tests.exitCode ?? null, timedOut: report.tests.timedOut === true, output: report.tests.output ? String(report.tests.output).slice(-1200) : null };
629
+ for (const key of ['candidate', 'before', 'integrationHead', 'sliceHead', 'integrationBranch', 'stoppedAt']) if (report[key] !== undefined) out[key] = report[key];
630
+ if (Array.isArray(report.violations)) out.violations = report.violations.slice(0, 20);
631
+ if (Array.isArray(report.stray)) out.stray = report.stray.slice(0, 20);
632
+ return out;
633
+ }
634
+
635
+ // ── a worker's turn ended ──────────────────────────────────────────────────
636
+ /** Send a slice's worker a follow-up; when the worker is gone, a new one takes the slice up with the same text. */
637
+ async function sendBack(record, sliceId, text, { resolve = false, origin = 'team' } = {}) {
638
+ const dispatcher = dispatcherOf();
639
+ const mine = record.slices[sliceId];
640
+ const run = runOf(mine.runId);
641
+ if (dispatcher && runLive(run)) {
642
+ try {
643
+ dispatcher.sendTurn(mine.runId, text, { origin });
644
+ mine.phase = 'working';
645
+ save(record);
646
+ return { ok: true, runId: mine.runId, via: 'follow-up' };
647
+ } catch (error) {
648
+ say('teams:follow-up-failed', { teamId: record.teamId, sliceId, error: error?.message || String(error) });
649
+ // It lives but cannot take a follow-up (its turns or its work time are used up): it makes room for a new one.
650
+ try { await dispatcher.stop(mine.runId, 'team_replaced'); } catch { /* it ends by itself */ }
651
+ }
652
+ }
653
+ // Its worker ended (or cannot take a follow-up): the slice goes to a new one, with what is left to do.
654
+ const out = await dispatchSlice(record, sliceId, { rework: true, lead: text, resolve });
655
+ return out.ok ? { ok: true, runId: out.runId, via: 'new-worker' } : out;
656
+ }
657
+
658
+ /** The unread messages of a member that somebody waits on (questions, change requests). */
659
+ function waitingMessages(teamId, runId) {
660
+ let rows = [];
661
+ try { rows = coordination.team.read({ teamId, runId, limit: 100, peek: true }); } catch { rows = []; }
662
+ return rows.filter((event) => event.kind === TEAM_MESSAGE_LOG_KIND && TEAM_ACTION_KINDS.includes(event.payload?.messageKind));
663
+ }
664
+
665
+ // Read-only workers never commit or join. End a warm run before removing its checkout.
666
+ async function finishReader(record, sliceId, { failed = false } = {}) {
667
+ const mine = record.slices[sliceId];
668
+ if (journalOf(record.teamId)?.slices[sliceId]?.cleanup) return;
669
+ const run = runOf(mine.runId);
670
+ if (runLive(run)) {
671
+ try { await dispatcherOf().complete(mine.runId, { reason: 'read_only_done' }); }
672
+ catch (error) { return attention(record, { code: 'WORKER_STILL_ACTIVE', sliceId, message: `Worktree kept: worker could not end (${error.message}).` }); }
673
+ // complete() wakes the idle run; its terminal dispatch event resumes cleanup.
674
+ if (runLive(runOf(mine.runId))) return;
675
+ }
676
+ const cleanup = await teams.finishReadOnlySlice(record.teamId, sliceId, { failed });
677
+ mine.phase = failed ? 'failed' : 'completed';
678
+ mine.released = true;
679
+ mine.doneAt = iso(now());
680
+ emit(record, 'slice_done', { sliceId, runId: mine.runId, text: cleanup.removed ? 'Read-only worker ended; worktree removed.' : `Worktree kept: ${cleanup.kept?.path || cleanup.path} (${cleanup.kept?.reason || cleanup.code}).` });
681
+ if (!cleanup.ok || cleanup.kept) attention(record, { code: 'READ_ONLY_WORKTREE_KEPT', sliceId, message: `Read-only worker worktree kept at ${cleanup.kept?.path || cleanup.path}: ${cleanup.kept?.reason || cleanup.message}. Inspect it; no changes were committed or landed.`, report: cleanup });
682
+ else if (failed) attention(record, { code: 'SLICE_WORKER_ENDED', sliceId, message: 'Read-only worker ended before reporting done; its clean worktree was removed.' });
683
+ if (Object.values(record.slices).every(s => s.released) && record.status !== 'needs_attention') {
684
+ record.status = 'completed';
685
+ emit(record, 'team_completed', { text: 'All read-only workers finished. Synthesize their results; no integration or landing is needed.' });
686
+ }
687
+ save(record);
688
+ }
689
+
690
+ /** A worker reported done: the peer questions that waited, then the commit, the ownership check and the join. */
691
+ async function sliceReportedDone(record, sliceId, runId) {
692
+ if (record.plan.readOnly) return finishReader(record, sliceId);
693
+ const mine = record.slices[sliceId];
694
+ const journal = journalOf(record.teamId);
695
+ const current = sliceStateOf(journal, sliceId);
696
+ if (current === 'integrated') return;
697
+ // Somebody asked this worker something while it worked: it answers before its slice is closed.
698
+ const asks = waitingMessages(record.teamId, runId);
699
+ if (asks.length && (Number(mine.deferrals) || 0) < limits.maxPeerDeferrals) {
700
+ mine.deferrals = (Number(mine.deferrals) || 0) + 1;
701
+ const handed = await sendBack(record, sliceId, peerMessagesText(record.teamId, asks.map(messageView), { beforeIntegration: true }), { origin: 'peer' });
702
+ if (!handed.ok) {
703
+ mine.phase = 'failed';
704
+ return attention(record, { code: handed.code || 'SLICE_NOT_SENT_BACK', sliceId, message: `Could not deliver the peer follow-up to ${sliceId}: ${handed.message}. Inspect agent_team status and retry with agent_team integrate.` });
705
+ }
706
+ if (handed.via === 'follow-up') {
707
+ try { coordination.team.ack({ teamId: record.teamId, runId, eventIds: asks.map((event) => event.id) }); } catch { /* handed over all the same */ }
708
+ }
709
+ return;
710
+ }
711
+ const resultTurn = runOf(runId)?.resultTurn;
712
+ mine.handledTurn = resultTurn;
713
+ const isCurrent = () => {
714
+ const run = runOf(runId);
715
+ return canFinish(run) && run.resultTurn === resultTurn;
716
+ };
717
+ mine.phase = 'finishing';
718
+ save(record);
719
+ const slice = record.plan.slices.find((each) => each.id === sliceId);
720
+ const options = { runId, message: slice?.title || null, isCurrent };
721
+ let finished = await teams.finishSlice(record.teamId, sliceId, options);
722
+ if (!finished.ok && finished.code === 'STRAY_CHANGES') {
723
+ // Files it does not own changed in its worktree: they stay out (never committed, never joined), and it is told.
724
+ const stray = finished.stray || [];
725
+ finished = await teams.finishSlice(record.teamId, sliceId, { ...options, allowStray: true });
726
+ if (finished.ok) mine.stray = (finished.stray?.length ? finished.stray : stray).slice(0, 30).map((item) => ({ path: item.path, owner: item.owner ?? null }));
727
+ }
728
+ if (finished.skipped || !isCurrent()) {
729
+ mine.phase = 'working';
730
+ save(record);
731
+ return;
732
+ }
733
+ if (!finished.ok) {
734
+ if (finished.code === 'UNRESOLVED_CONFLICTS') return retry(record, sliceId, 'conflict', { report: { files: finished.files || [] }, text: unresolvedFollowUp({ teamId: record.teamId, sliceId, files: finished.files || [] }), message: finished.message });
735
+ if (finished.code === 'SLICE_ALREADY_INTEGRATED') return;
736
+ mine.phase = 'rejected';
737
+ return attention(record, { code: finished.code, sliceId, message: `Slice ${sliceId} was not committed: ${finished.message} Inspect the worktree and retry with agent_team integrate.`, report: { violations: finished.violations, stray: finished.stray } });
738
+ }
739
+ mine.phase = 'done';
740
+ mine.doneAt = iso(now());
741
+ emit(record, 'slice_done', { sliceId, runId, text: `${finished.changed?.length || 0} files${finished.committed ? '' : ' (nothing new to commit)'}${mine.stray?.length ? `, ${mine.stray.length} left out (not its own)` : ''}`, head: finished.head, changed: (finished.changed || []).length, stray: mine.stray || [] });
742
+ return true;
743
+ }
744
+
745
+ /** One more try for a slice (`kind`: conflict | tests), or, with the retries used up, the team needs attention. */
746
+ async function retry(record, sliceId, kind, { report = null, text, message, resolve = false } = {}) {
747
+ const mine = record.slices[sliceId];
748
+ mine.attempts = mine.attempts || {};
749
+ const used = Number(mine.attempts[kind]) || 0;
750
+ const event = kind === 'tests' ? 'tests_failed' : 'conflict';
751
+ mine.lastReport = { code: kind === 'tests' ? 'TESTS_FAILED' : 'CONFLICT', message: clip(message || '', 600), at: iso(now()), ...(report ? { report: reportBrief(report) } : {}) };
752
+ if (used >= limits.maxRetries) {
753
+ mine.phase = kind === 'tests' ? 'tests_failed' : 'conflict';
754
+ return attention(record, {
755
+ code: kind === 'tests' ? 'TESTS_FAILED' : 'CONFLICT', sliceId, report, event,
756
+ message: `Slice ${sliceId} ${kind === 'tests' ? 'failed the integration tests' : 'conflicts with the integration branch'} after ${used} ${used === 1 ? 'retry' : 'retries'}: ${message || ''} Decide what happens next (agent_team status has the report): fix the plan, send the worker a hint with agent_send and then agent_team integrate, or discard the team.`,
757
+ });
758
+ }
759
+ mine.attempts[kind] = used + 1;
760
+ mine.phase = kind === 'tests' ? 'tests_failed' : 'conflict';
761
+ save(record);
762
+ const body = typeof text === 'function' ? text(used + 1) : text;
763
+ const sent = await sendBack(record, sliceId, body, { resolve });
764
+ emit(record, event, { sliceId, runId: mine.runId, attempt: used + 1, of: limits.maxRetries, text: `${clip(message || '', 300)} Sent back to its worker (${sent.ok ? sent.via : 'could not be sent'}).`, ...(report ? { report: reportBrief(report) } : {}) });
765
+ if (!sent.ok) attention(record, { code: sent.code || 'SLICE_NOT_SENT_BACK', sliceId, message: `Slice ${sliceId} could not be sent back to a worker: ${sent.message}`, report });
766
+ }
767
+
768
+ async function handleJoin(record, result) {
769
+ const mine = record.slices[result.sliceId];
770
+ if (result.ok) {
771
+ mine.phase = 'integrated';
772
+ mine.integratedAt = iso(now());
773
+ mine.lastReport = null;
774
+ emit(record, 'integrated', { sliceId: result.sliceId, runId: mine.runId, commit: result.commit, method: result.method, tests: result.tests ? { ok: result.tests.ok === true, exitCode: result.tests.exitCode ?? null } : null, text: `${result.method || 'joined'}${result.tests ? (result.tests.ok ? ', tests passed' : ', tests failed') : ', not tested (no test command)'}` });
775
+ release(record, result.sliceId, 'team_integrated');
776
+ return;
777
+ }
778
+ if (result.skipped) return;
779
+ if (result.code === 'CONFLICT') {
780
+ // The integration branch is merged into the slice's own worktree, the conflict left open in its own files.
781
+ const mineRun = runOf(mine.runId);
782
+ let conflicts = [];
783
+ let resolved = null;
784
+ if (runLive(mineRun) && (Number(mine.attempts?.conflict) || 0) < limits.maxRetries) {
785
+ resolved = await teams.resolveInSlice(record.teamId, result.sliceId, { runId: mine.runId });
786
+ conflicts = resolved.ok ? resolved.conflicts || [] : [];
787
+ }
788
+ if (resolved && !resolved.ok) {
789
+ mine.phase = 'conflict';
790
+ attention(record, { code: resolved.code || 'CONFLICT', sliceId: result.sliceId, message: `Slice ${result.sliceId} conflicts with the integration branch and the conflict could not be brought into its worktree: ${resolved.message}`, report: result.report, event: 'conflict' });
791
+ return;
792
+ }
793
+ await retry(record, result.sliceId, 'conflict', {
794
+ report: result.report, message: result.message, resolve: !resolved,
795
+ text: (attempt) => conflictFollowUp({ teamId: record.teamId, sliceId: result.sliceId, report: result.report || {}, conflicts, attempt, maxAttempts: limits.maxRetries }),
796
+ });
797
+ return;
798
+ }
799
+ if (result.code === 'TESTS_FAILED') {
800
+ const mineRun = runOf(mine.runId);
801
+ // The slice is the worker's again (its claims with it) before it is told: a live worker keeps its run.
802
+ if (runLive(mineRun) && (Number(mine.attempts?.tests) || 0) < limits.maxRetries) {
803
+ const again = await teams.startSlice(record.teamId, result.sliceId, { runId: mine.runId });
804
+ if (!again.ok) { mine.phase = 'tests_failed'; attention(record, { code: again.code, sliceId: result.sliceId, message: `Slice ${result.sliceId} failed the integration tests and could not be reopened: ${again.message}`, report: result.report, event: 'tests_failed' }); return; }
805
+ }
806
+ await retry(record, result.sliceId, 'tests', {
807
+ report: result.report, message: result.message,
808
+ text: (attempt) => testsFailedFollowUp({ teamId: record.teamId, sliceId: result.sliceId, report: result.report || {}, attempt, maxAttempts: limits.maxRetries, stray: mine.stray || [] }),
809
+ });
810
+ return;
811
+ }
812
+ mine.phase = 'failed';
813
+ attention(record, { code: result.code || 'INTEGRATION_FAILED', sliceId: result.sliceId, message: `Slice ${result.sliceId} could not be joined: ${result.message}`, report: result.report });
814
+ }
815
+
816
+ async function joinFinished(record) {
817
+ if (!OPEN_STATUSES.has(record.status)) return null;
818
+ const joinSlice = (teamId, sliceId) => inSlice(record, sliceId, async () => {
819
+ const mine = record.slices[sliceId];
820
+ const isCurrent = () => {
821
+ const run = runOf(mine.runId);
822
+ return !run || (canFinish(run) && (!mine.handledTurn || run.resultTurn === mine.handledTurn));
823
+ };
824
+ if (!isCurrent()) return { ok: false, skipped: 'worker' };
825
+ const result = await teams.integrate(teamId, sliceId, { isCurrent });
826
+ await handleJoin(record, { ...result, sliceId });
827
+ return result;
828
+ });
829
+ let joined;
830
+ try {
831
+ joined = await teams.integrateAll(record.teamId, {}, joinSlice);
832
+ } catch (error) {
833
+ joined = refuse('INTEGRATION_FAILED', `${error?.message || String(error)}. Inspect the integration worktree before retrying.`);
834
+ }
835
+ if (joined.ok === false && !Array.isArray(joined.results)) {
836
+ attention(record, { code: joined.code || 'INTEGRATION_FAILED', message: `The team could not be joined: ${joined.message}` });
837
+ return joined;
838
+ }
839
+ for (const result of joined.results || []) {
840
+ const mine = record.slices[result.sliceId];
841
+ if (result.already && mine && mine.phase !== 'integrated') {
842
+ mine.phase = 'integrated';
843
+ save(record);
844
+ }
845
+ }
846
+ if (joined.ready && record.status !== 'ready') {
847
+ record.status = 'ready';
848
+ record.attention = null;
849
+ const journal = journalOf(record.teamId);
850
+ const tests = journal?.integration?.tests || null;
851
+ emit(record, 'team_ready', {
852
+ integrationBranch: integrationBranchName(record.teamId), head: journal?.integration?.head || null,
853
+ tests: tests ? { ok: tests.ok === true, commit: tests.commit || null } : null,
854
+ text: `Every slice is joined on ${integrationBranchName(record.teamId)}${tests ? (tests.ok ? ' and the tests passed on that commit' : ' but the tests have not passed on that commit') : ' (no test command: not tested)'}. Land it with agent_team land when the tests passed, the owner's branch has not moved and no locally changed file is touched; otherwise ask the owner.`,
855
+ });
856
+ return joined;
857
+ }
858
+ healed(record);
859
+ if (record.status === 'running') await withAllSlices(record, () => startReady(record));
860
+ return joined;
861
+ }
862
+
863
+ /** What the team needed attention for is settled (the slice joined, or is at work again): it runs on. */
864
+ function healed(record) {
865
+ if (record.status !== 'needs_attention') return;
866
+ const stuck = Object.values(record.slices).some((mine) => ['failed', 'conflict', 'tests_failed', 'rejected'].includes(mine.phase));
867
+ if (stuck) return;
868
+ record.status = 'running';
869
+ record.attention = null;
870
+ save(record);
871
+ }
872
+
873
+ /** A slice's worker has nothing left to do: its warm run is completed so its slot is free for the next slice. */
874
+ function release(record, sliceId, reason) {
875
+ const mine = record.slices[sliceId];
876
+ if (!mine?.runId) return;
877
+ mine.released = true;
878
+ save(record);
879
+ try { const dispatcher = dispatcherOf(); const run = runOf(mine.runId); if (dispatcher && runLive(run)) Promise.resolve(dispatcher.complete(mine.runId, { reason })).catch(() => {}); } catch { /* it ends by its idle time */ }
880
+ }
881
+
882
+ // The result of a prior turn remains on a working, failed or interrupted run. Only
883
+ // an idle worker with an empty follow-up outbox, or a successfully ended worker, is done.
884
+ function canFinish(run) {
885
+ return (run?.lastResult?.status || run?.outcome) === 'done' &&
886
+ (run.state === 'completed' || (runIdle(run) && !coordination.followUps?.count(run.runId)));
887
+ }
888
+
889
+ async function reconcileRun(record, sliceId, runId) {
890
+ const mine = record.slices[sliceId];
891
+ if (!OPEN_STATUSES.has(record.status) || mine.runId !== runId || mine.released) return;
892
+ const run = runOf(runId);
893
+ if (!run || (!runIdle(run) && !run.terminal)) return;
894
+ const state = sliceStateOf(journalOf(record.teamId), sliceId);
895
+ if (state === 'integrated' || state === 'completed') return;
896
+ if (record.plan.readOnly && run.terminal) return finishReader(record, sliceId, { failed: !canFinish(run) });
897
+ if (canFinish(run) && (mine.phase === 'finishing' || !mine.handledTurn || run.resultTurn > mine.handledTurn)) {
898
+ mine.handledTurn = run.resultTurn;
899
+ try {
900
+ if (await sliceReportedDone(record, sliceId, runId)) {
901
+ // Never hold the slice reservation while waiting for the integration branch.
902
+ inTurn(record.teamId, () => joinFinished(record));
903
+ }
904
+ } catch (error) {
905
+ mine.phase = 'failed';
906
+ attention(record, { code: 'SLICE_FINALIZATION_FAILED', sliceId, message: `Could not finalize ${sliceId}: ${error.message}. Inspect its worktree and retry with agent_team integrate.` });
907
+ }
908
+ return;
909
+ }
910
+ if (['failed', 'rejected', 'conflict', 'tests_failed'].includes(mine.phase)) return;
911
+ if (run.terminal) {
912
+ if (state === 'done' && canFinish(run)) return;
913
+ mine.phase = 'failed';
914
+ attention(record, { code: 'SLICE_WORKER_ENDED', sliceId,
915
+ message: `The worker of slice ${sliceId} ended (${run.completionReason || run.state}) before its slice was done. Its files are in its worktree. agent_team integrate gives the slice to a new worker; agent_team discard gives the team up.` });
916
+ } else if (run.outcome !== 'done') {
917
+ mine.phase = 'blocked';
918
+ mine.lastReport = { code: 'WORKER_BLOCKED', message: clip(run.lastResult?.summary || run.lastResult?.question || run.outcome || 'no result', 400), at: iso(now()) };
919
+ save(record);
920
+ }
921
+ }
922
+
923
+ function onDispatch(payload) {
924
+ if (closed || payload?.type !== 'assistant:dispatch') return;
925
+ const runId = payload.run?.runId;
926
+ const ref = runIndex.get(runId);
927
+ if (!ref) return;
928
+ const record = records.get(ref.teamId);
929
+ const mine = record?.slices[ref.sliceId];
930
+ if (!mine || mine.runId !== runId || mine.released || !OPEN_STATUSES.has(record.status)) return;
931
+ if (payload.reason === 'turn_started' && mine.handledTurn && !record.plan.readOnly) {
932
+ if (payload.turn <= mine.handledTurn || runOf(runId)?.state !== 'running') return;
933
+ // The dispatcher announces the new turn before handing its prompt to the worker.
934
+ // A finished slice gave back its claims; restore them before the follow-up edits.
935
+ if (['done', 'integrating'].includes(sliceStateOf(journalOf(record.teamId), ref.sliceId))) {
936
+ const claims = teams.modules.claims.assign(record.teamId, ref.sliceId, runId);
937
+ if (!claims.ok) return attention(record, { code: claims.code, sliceId: ref.sliceId, message: claims.message });
938
+ mine.phase = 'working';
939
+ save(record);
940
+ }
941
+ } else if (['started', 'queue_started'].includes(payload.reason)) {
942
+ inSlice(record, ref.sliceId, () => {
943
+ if (mine.runId === runId && ['queued', 'dispatched'].includes(mine.phase)) { mine.phase = 'working'; save(record); }
944
+ });
945
+ } else if (['idle', 'failed', 'stopped', 'interrupted', 'completed'].includes(payload.reason)) {
946
+ inSlice(record, ref.sliceId, () => reconcileRun(record, ref.sliceId, runId));
947
+ }
948
+ }
949
+
950
+ function checkProgress() {
951
+ if (closed) return;
952
+ for (const record of records.values()) {
953
+ if (!['running', 'needs_attention'].includes(record.status)) continue;
954
+ const journal = journalOf(record.teamId);
955
+ const under = journal?.integrating;
956
+ if (under && now() - under.startedAt >= limits.joinOverdueMs && record.alertedJoin !== under.startedAt) {
957
+ record.alertedJoin = under.startedAt;
958
+ emit(record, 'needs_attention', { code: 'JOIN_OVERDUE', sliceId: under.sliceId,
959
+ text: `Integration has been ${under.phase} for ${Math.floor((now() - under.startedAt) / 60000)} minutes. Inspect agent_team status and the integration worktree before retrying.`,
960
+ phase: under.phase, startedAt: under.startedAt, candidate: under.candidate || null });
961
+ }
962
+ for (const [sliceId, mine] of Object.entries(record.slices)) {
963
+ const state = sliceStateOf(journal, sliceId);
964
+ if (!mine.runId || mine.released || (state !== 'running' && state !== 'done') ||
965
+ ['failed', 'rejected', 'conflict', 'tests_failed'].includes(mine.phase)) continue;
966
+ const runId = mine.runId;
967
+ const run = runOf(runId);
968
+ if (!run?.terminal || reconciling.has(runId)) continue;
969
+ if (state === 'done' && canFinish(run) && (!mine.handledTurn || run.resultTurn === mine.handledTurn)) continue;
970
+ reconciling.add(runId);
971
+ inSlice(record, sliceId, () => reconcileRun(record, sliceId, runId))
972
+ .finally(() => reconciling.delete(runId)).catch(() => {});
973
+ }
974
+ }
975
+ }
976
+
977
+ // ── retry, land, discard ───────────────────────────────────────────────────
978
+ /**
979
+ * Take a team that needs attention up again (the Assistant's `integrate`): every slice is looked at as the
980
+ * journal has it. A finished slice is joined; one in conflict or with failed tests goes back to a worker with a
981
+ * fresh count; one whose worker ended gets a new one.
982
+ */
983
+ function integrate(teamId, { sliceId = null } = {}) {
984
+ const record = records.get(String(teamId || ''));
985
+ if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`, { status: 404 }));
986
+ if (record.plan.readOnly) return Promise.resolve(refuse('TEAM_READ_ONLY', 'Research/review teams have no integration or landing.', { status: 409 }));
987
+ if (!OPEN_STATUSES.has(record.status)) return Promise.resolve(refuse('TEAM_NOT_ACTIVE', `Team "${teamId}" is ${record.status}.`, { status: 409 }));
988
+ if (sliceId && !record.slices[sliceId]) return Promise.resolve(refuse('SLICE_NOT_FOUND', `Team "${teamId}" has no slice "${sliceId}".`, { status: 404 }));
989
+ return inTurn(record.teamId, async () => {
990
+ await withAllSlices(record, async () => {
991
+ if (record.status === 'needs_attention') { record.status = 'running'; record.attention = null; }
992
+ const journal = journalOf(record.teamId);
993
+ for (const slice of record.plan.slices) {
994
+ if (sliceId && slice.id !== sliceId) continue;
995
+ const mine = record.slices[slice.id];
996
+ const state = sliceStateOf(journal, slice.id);
997
+ if (state === 'integrated' || (state === 'done' && mine.phase !== 'failed')) continue;
998
+ if (mine.phase === 'waiting') continue;
999
+ mine.attempts = {};
1000
+ const run = runOf(mine.runId);
1001
+ if (state === 'conflict') {
1002
+ const report = journal.slices[slice.id]?.conflict || {};
1003
+ let conflicts = [];
1004
+ let resolved = null;
1005
+ if (runLive(run)) { resolved = await teams.resolveInSlice(record.teamId, slice.id, { runId: mine.runId }); conflicts = resolved.ok ? resolved.conflicts || [] : []; }
1006
+ if (resolved && !resolved.ok) { attention(record, { code: resolved.code, sliceId: slice.id, message: `Slice ${slice.id}: ${resolved.message}` }); continue; }
1007
+ await retry(record, slice.id, 'conflict', { report, message: 'Conflicts with the integration branch.', resolve: !resolved, text: (attempt) => conflictFollowUp({ teamId: record.teamId, sliceId: slice.id, report, conflicts, attempt, maxAttempts: limits.maxRetries }) });
1008
+ } else if (state === 'tests-failed') {
1009
+ const report = { tests: journal.slices[slice.id]?.tests || {} };
1010
+ if (runLive(run)) { const again = await teams.startSlice(record.teamId, slice.id, { runId: mine.runId }); if (!again.ok) { attention(record, { code: again.code, sliceId: slice.id, message: `Slice ${slice.id}: ${again.message}` }); continue; } }
1011
+ await retry(record, slice.id, 'tests', { report, message: 'The integration tests failed.', text: (attempt) => testsFailedFollowUp({ teamId: record.teamId, sliceId: slice.id, report, attempt, maxAttempts: limits.maxRetries }) });
1012
+ } else if (state === 'rejected') {
1013
+ if (canFinish(run)) await sliceReportedDone(record, slice.id, mine.runId);
1014
+ else await sendBack(record, slice.id, `Your slice ${slice.id} of team ${record.teamId} was not committed the last time (it changed files it does not own). Leave every file that is not yours as it is on your branch, finish your own files, and end with your ## Result block.`);
1015
+ } else if (!runLive(run)) {
1016
+ // Its worker is gone and the slice is not finished: a new worker takes it up where the files are.
1017
+ const out = await dispatchSlice(record, slice.id, { rework: true, lead: `You take over slice ${slice.id} of team ${record.teamId} from a worker that ended before it was done. What it changed so far is in your worktree, uncommitted: read it (git status, git diff) and finish the slice.` });
1018
+ if (!out.ok) attention(record, { code: out.code || 'SLICE_NOT_STARTED', sliceId: slice.id, message: `Slice ${slice.id} could not be given to a new worker: ${out.message}` });
1019
+ } else if (canFinish(run)) {
1020
+ await sliceReportedDone(record, slice.id, mine.runId);
1021
+ }
1022
+ }
1023
+ });
1024
+ if (OPEN_STATUSES.has(record.status)) await joinFinished(record);
1025
+ save(record);
1026
+ return status(record.teamId, { timeline: 30 });
1027
+ });
1028
+ }
1029
+
1030
+ /**
1031
+ * Land a team: the integration branch into the owner's branch (default: the branch checked out in the project).
1032
+ * The library's refusals come back unchanged. `by.kind` 'assistant': never untested, never partial, and only
1033
+ * while the owner's branch is where it was when the team was cut.
1034
+ */
1035
+ function land(teamId, { targetBranch = null, mode = 'ff', by = { kind: 'owner' }, allowUntested = false, allowPartial = false } = {}) {
1036
+ const record = records.get(String(teamId || ''));
1037
+ if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`, { status: 404 }));
1038
+ if (record.plan.readOnly) return Promise.resolve(refuse('TEAM_READ_ONLY', 'Research/review teams have no integration or landing.', { status: 409 }));
1039
+ return teamStep(record, async () => {
1040
+ const journal = journalOf(record.teamId);
1041
+ if (!journal) return refuse('TEAM_NOT_FOUND', `Team "${teamId}" has no record in the journal.`, { status: 404 });
1042
+ const assistant = by?.kind !== 'owner';
1043
+ const target = targetBranch ? String(targetBranch) : ((await branchOf(record.projectPath)) || journal.baseBranch || null);
1044
+ if (assistant) {
1045
+ // The Assistant lands only what the owner would wave through: the owner's branch must be where the team
1046
+ // was cut from. Moved since: the owner decides (a merge would mix their newer commits with the team's).
1047
+ const head = target && typeof git === 'function' ? await (async () => { const out = await git(['rev-parse', '--verify', '-q', `refs/heads/${target}^{commit}`], { cwd: record.projectPath }); return out.ok ? String(out.stdout || '').trim() : null; })() : null;
1048
+ const cutFrom = journal.baseCommit || null;
1049
+ if (head && cutFrom && head !== cutFrom && journal.state !== 'merged') {
1050
+ const refused = refuse('OWNER_BRANCH_MOVED', `${target} has moved since the team was cut from ${String(cutFrom).slice(0, 10)} (it is at ${head.slice(0, 10)} now). Landing is the owner's to decide: ask them, do not land.`, {
1051
+ status: 409, report: { targetBranch: target, cutFrom, head, integrationBranch: integrationBranchName(record.teamId), userShouldRun: [`git checkout ${target}`, `git merge ${integrationBranchName(record.teamId)}`] },
1052
+ });
1053
+ record.landing = { refused: { code: refused.code, message: refused.message, at: iso(now()), by: by?.kind || 'assistant' } };
1054
+ save(record);
1055
+ return refused;
1056
+ }
1057
+ }
1058
+ const landed = await teams.land(record.teamId, {
1059
+ ...(target ? { targetBranch: target } : {}), mode,
1060
+ allowUntested: !assistant && allowUntested === true, allowPartial: !assistant && allowPartial === true,
1061
+ });
1062
+ if (!landed.ok) {
1063
+ record.landing = { refused: { code: landed.code, message: clip(landed.message, 600), at: iso(now()), by: by?.kind || 'owner' } };
1064
+ save(record);
1065
+ return landed; // the library's refusal, unchanged
1066
+ }
1067
+ record.status = 'landed';
1068
+ record.attention = null;
1069
+ record.landing = { landed: landed.landed || null, at: iso(now()), by: by?.kind || 'owner' };
1070
+ record.cleanup = {
1071
+ available: true,
1072
+ worktrees: [...record.plan.slices.map(s => worktreePath(record.projectPath, record.teamId, s.id)), worktreePath(record.projectPath, record.teamId, 'integration')],
1073
+ branches: [...record.plan.slices.map(s => branchName(record.teamId, s.id)), integrationBranchName(record.teamId)],
1074
+ next: 'When the task is fully finished, suggest deleting these worktrees and branches with a confirm follow-up; call agent_team action cleanup with user_confirmed true only after the user says yes.',
1075
+ };
1076
+ emit(record, 'landed', {
1077
+ targetBranch: landed.landed?.targetBranch || target, mode: landed.landed?.mode || mode, to: landed.landed?.to || null,
1078
+ text: `Landed on ${landed.landed?.targetBranch || target} (${landed.landed?.mode || mode}); worktrees and branches kept pending confirmed cleanup.`, by: by?.kind || 'owner',
1079
+ }, { quiet: assistant && by?.sessionId === record.sessionId });
1080
+ return { ...landed, cleanup: record.cleanup };
1081
+ });
1082
+ }
1083
+
1084
+ function cleanup(teamId, { sessionId = null, userConfirmed = false } = {}) {
1085
+ const record = records.get(String(teamId || ''));
1086
+ if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`));
1087
+ return teamStep(record, async () => {
1088
+ if (sessionId && sessionId !== record.sessionId) return refuse('TEAM_FORBIDDEN', 'That team belongs to another Assistant session.');
1089
+ if (record.cleanedAt) return { ok: true, teamId: record.teamId, alreadyClean: true, removed: [] };
1090
+ const verified = typeof lastOwnerTurnAt === 'function';
1091
+ let ownerAt = null;
1092
+ if (verified) { try { ownerAt = await lastOwnerTurnAt(record.sessionId); } catch {} }
1093
+ const timestamp = value => typeof value === 'number' ? value : Date.parse(value);
1094
+ const confirmed = userConfirmed === true && (!verified || timestamp(ownerAt) > timestamp(record.landing?.at));
1095
+ const checks = [{ name: 'confirmed', ok: confirmed, detail: verified ? 'Requires explicit confirmation and an owner UI turn after landing.' : 'Owner-turn timing unverified; explicit confirmation required.' },
1096
+ { name: 'landed', ok: record.status === 'landed', detail: `Team status: ${record.status}` }];
1097
+ const dispatcher = dispatcherOf();
1098
+ const finalIds = new Set();
1099
+ const ids = new Set();
1100
+ for (const slice of Object.values(record.slices)) {
1101
+ const history = slice.runIds || [];
1102
+ for (const id of history) ids.add(id);
1103
+ const current = slice.runId || history.at(-1);
1104
+ if (current) {
1105
+ finalIds.add(current);
1106
+ ids.add(current);
1107
+ }
1108
+ }
1109
+ // Only a known superseded worker may have an unsuccessful outcome.
1110
+ // Integrators and other runs found only in the dispatcher still need to finish done.
1111
+ const superseded = new Set([...ids].filter(id => !finalIds.has(id)));
1112
+ let listed = null;
1113
+ try { listed = dispatcher?.teamRuns?.(record.teamId, record.workflowId); } catch {}
1114
+ const pending = [];
1115
+ if (Array.isArray(listed)) {
1116
+ for (const run of listed) ids.add(run.runId);
1117
+ for (const id of ids) {
1118
+ const run = runOf(id);
1119
+ const outcome = run?.outcome || run?.lastResult?.status;
1120
+ if (run?.active !== false || run.state === 'running' || run.state === 'queued' || (!superseded.has(id) && outcome !== 'done')) {
1121
+ pending.push(`${id}: ${run?.state || 'unknown'} / ${outcome || 'unknown'}`);
1122
+ }
1123
+ }
1124
+ }
1125
+ checks.push({ name: 'runs ended', ok: Array.isArray(listed) && pending.length === 0,
1126
+ detail: Array.isArray(listed) ? pending.join(', ') || 'All team runs ended and final workers reported done.' : 'Complete team run inventory unavailable.' });
1127
+ const preflight = await teams.modules.worktrees.remove(record.teamId, { guarded: true, checkOnly: true });
1128
+ checks.push(...(preflight.checks || []));
1129
+ const failed = checks.find(c => !c.ok);
1130
+ if (failed) return refuse({ confirmed: 'CLEANUP_NOT_CONFIRMED', landed: 'TEAM_NOT_LANDED', 'runs ended': 'TEAM_RUNS_ACTIVE', merged: 'BRANCH_NOT_MERGED', clean: 'WORKTREE_DIRTY' }[failed.name], failed.detail, { checks });
1131
+ if (!preflight.ok) return { ...preflight, checks };
1132
+ const out = await teams.remove(record.teamId, { guarded: true });
1133
+ if (!out.ok) return { ...out, checks: [...checks, ...(out.checks || [])] };
1134
+ record.cleanedAt = iso(now());
1135
+ record.cleanup = { complete: true, removed: out.removed };
1136
+ emit(record, 'team_cleaned', { text: 'Confirmed cleanup removed the team worktrees and branches.' });
1137
+ return { ok: true, teamId: record.teamId, removed: out.removed, ...(!verified ? { confirmation: 'unverified' } : {}) };
1138
+ });
1139
+ }
1140
+
1141
+ async function stopRuns(record, reason) {
1142
+ const dispatcher = dispatcherOf();
1143
+ for (const mine of Object.values(record.slices)) mine.released = true;
1144
+ save(record);
1145
+ if (!dispatcher) return [];
1146
+ try { return (await dispatcher.killAll({ workflowId: record.workflowId, reason })).stopped || []; } catch (error) { say('teams:stop-failed', { teamId: record.teamId, error: error?.message || String(error) }); return []; }
1147
+ }
1148
+
1149
+ /** Give a team up: its workers are stopped, its worktrees and branches removed (what holds work is kept unless `force`). */
1150
+ function discard(teamId, { by = { kind: 'owner' }, force = false, reason = '' } = {}) {
1151
+ const record = records.get(String(teamId || ''));
1152
+ if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`, { status: 404 }));
1153
+ return teamStep(record, async () => {
1154
+ const journal = journalOf(record.teamId);
1155
+ if (journal?.state === 'merged') return refuse('ALREADY_LANDED', `Team "${teamId}" has landed: there is nothing to discard.`, { status: 409 });
1156
+ if (record.status === 'discarded' && journal?.removed) return { ok: true, already: true, cleanup: record.cleanup };
1157
+ const assistant = by?.kind !== 'owner';
1158
+ const stopped = await stopRuns(record, 'team_discarded');
1159
+ const removed = await teams.remove(record.teamId, { discard: true, force: !assistant && force === true });
1160
+ if (!removed.ok) return removed; // the library's refusal, unchanged
1161
+ record.status = 'discarded';
1162
+ record.attention = null;
1163
+ record.cleanup = { complete: removed.complete === true, kept: (removed.kept || []).map((item) => ({ sliceId: item.sliceId, path: item.path, branch: item.branch, reason: item.reason, files: (item.files || []).slice(0, 20), commits: item.commits ?? null })) };
1164
+ emit(record, 'discarded', {
1165
+ text: `Discarded${reason ? `: ${clip(reason, 200)}` : ''}. ${removed.complete ? 'Worktrees and branches removed.' : `${record.cleanup.kept.length} worktree${record.cleanup.kept.length === 1 ? '' : 's'} or branch${record.cleanup.kept.length === 1 ? '' : 'es'} kept because work is in them.`}`, by: by?.kind || 'owner',
1166
+ }, { quiet: assistant && by?.sessionId === record.sessionId });
1167
+ return { ok: true, stopped, complete: removed.complete === true, removed: removed.removed || [], kept: record.cleanup.kept };
1168
+ });
1169
+ }
1170
+
1171
+ // ── the channel (a worker's `team` tool) ───────────────────────────────────
1172
+ /** The team and slice a run works on now, or null: only the slice's current run, while it lives, is a member. */
1173
+ function member(runId) {
1174
+ const ref = runIndex.get(String(runId || ''));
1175
+ if (!ref) return null;
1176
+ const record = records.get(ref.teamId);
1177
+ const mine = record?.slices?.[ref.sliceId];
1178
+ if (!record || !mine || mine.runId !== String(runId)) return null;
1179
+ if (!OPEN_STATUSES.has(record.status)) return null;
1180
+ // …and only while the run lives (working, waiting warm, or being resumed after a restart): a run that ended is nobody.
1181
+ if (!runLive(runOf(runId))) return null;
1182
+ return { teamId: ref.teamId, sliceId: ref.sliceId, title: record.title || null, sessionId: record.sessionId || null };
1183
+ }
1184
+ /** The runs that are members now: each slice's current run, while it lives. */
1185
+ function liveMembers(record, { except = null } = {}) {
1186
+ const out = [];
1187
+ for (const [sliceId, mine] of Object.entries(record.slices)) {
1188
+ if (!mine.runId || mine.runId === except) continue;
1189
+ if (runLive(runOf(mine.runId))) out.push({ sliceId, runId: mine.runId });
1190
+ }
1191
+ return out;
1192
+ }
1193
+ const noMember = () => refuse('TEAM_CONTEXT_REQUIRED', 'The team tool is for a worker of a team slice, about its own team: this run works on no team.', { status: 403 });
1194
+ function throttled(runId) {
1195
+ const at = now();
1196
+ const recent = (postTimes.get(runId) || []).filter((time) => at - time < limits.postWindowMs);
1197
+ if (recent.length >= limits.postsPerWindow) { postTimes.set(runId, recent); return true; }
1198
+ recent.push(at);
1199
+ postTimes.set(runId, recent);
1200
+ return false;
1201
+ }
1202
+
1203
+ /** Hand messages to a worker that waits warm: one follow-up, named as untrusted peer content. → delivered or not. */
1204
+ function pushTo(record, recipientRunId, events) {
1205
+ const dispatcher = dispatcherOf();
1206
+ const run = runOf(recipientRunId);
1207
+ if (!dispatcher || !runIdle(run)) return false;
1208
+ try {
1209
+ dispatcher.sendTurn(recipientRunId, peerMessagesText(record.teamId, events.map(messageView)), { origin: 'peer', queue: false });
1210
+ coordination.team.ack({ teamId: record.teamId, runId: recipientRunId, eventIds: events.map((event) => event.id) });
1211
+ return true;
1212
+ } catch (error) {
1213
+ say('teams:peer-push-failed', { teamId: record.teamId, runId: recipientRunId, error: error?.code || error?.message || String(error) });
1214
+ return false;
1215
+ }
1216
+ }
1217
+
1218
+ /**
1219
+ * A worker says something on its team's channel. `to`: "board" (every other worker, and the lead's log), "lead"
1220
+ * (the Assistant session that runs the team), or a slice id. Delivered through the coordination service to each
1221
+ * recipient's own mailbox; a recipient that waits warm gets it as a follow-up at once, a working one at its next
1222
+ * `team` call or when its turn ends.
1223
+ */
1224
+ function post(runId, { to = 'board', kind = 'note', text = '', path = null, id = null } = {}) {
1225
+ const who = member(runId);
1226
+ if (!who) return noMember();
1227
+ const record = records.get(who.teamId);
1228
+ const messageKind = String(kind || 'note').trim().toLowerCase();
1229
+ if (!TEAM_MESSAGE_KINDS.includes(messageKind)) return refuse('TEAM_KIND_INVALID', `kind is one of ${TEAM_MESSAGE_KINDS.join(', ')}.`, { status: 400 });
1230
+ const body = String(text ?? '').trim();
1231
+ if (!body) return refuse('TEAM_TEXT_REQUIRED', 'text is required: what you say.', { status: 400 });
1232
+ if (body.length > limits.messageChars) return refuse('TEAM_TEXT_TOO_LONG', `text is at most ${limits.messageChars} characters.`, { status: 400 });
1233
+ if (throttled(String(runId))) return refuse('TEAM_RATE_LIMITED', `At most ${limits.postsPerWindow} posts in ${Math.round(limits.postWindowMs / 60_000)} minutes: read and wait instead of posting again.`, { status: 429 });
1234
+ const target = String(to || 'board').trim().toLowerCase();
1235
+ const others = liveMembers(record, { except: String(runId) });
1236
+ let recipients = [];
1237
+ let toSlice = null;
1238
+ if (target === 'board' || target === 'all') recipients = others;
1239
+ else if (target === 'lead') recipients = [];
1240
+ else {
1241
+ if (!record.slices[target]) return refuse('TEAM_SLICE_UNKNOWN', `This team has no slice "${target}". Its slices: ${Object.keys(record.slices).join(', ')}.`, { status: 404 });
1242
+ if (target === who.sliceId) return refuse('TEAM_SELF', 'That is your own slice.', { status: 400 });
1243
+ toSlice = target;
1244
+ recipients = others.filter((each) => each.sliceId === target);
1245
+ if (!recipients.length) return refuse('TEAM_RECIPIENT_GONE', `Slice "${target}" has no worker now (it is finished, or not started yet). Post to "lead" when you need a decision or a change there.`, { status: 409, sliceId: target });
1246
+ }
1247
+ const toLead = target === 'lead' || target === 'board' || target === 'all';
1248
+ const payload = { messageKind, fromSlice: who.sliceId, to: toSlice ? 'slice' : (target === 'lead' ? 'lead' : 'board'), ...(toSlice ? { toSlice } : {}), ...(path ? { path: String(path).slice(0, 400) } : {}) };
1249
+ let out;
1250
+ try {
1251
+ out = coordination.team.post({
1252
+ teamId: who.teamId, fromRunId: String(runId), kind: TEAM_MESSAGE_LOG_KIND, text: body, payload,
1253
+ // Each recipient's own mailbox; the team's log has every message (the lead reads it there: agent_team status).
1254
+ to: recipients.map((each) => each.runId),
1255
+ members: recipients.map((each) => each.runId), sessionId: record.sessionId || null,
1256
+ ...(id ? { id: `team:${who.teamId}:post:${String(runId).slice(0, 12)}:${String(id).slice(0, 80)}` } : {}),
1257
+ });
1258
+ } catch (error) {
1259
+ return refuse(error?.code || 'TEAM_POST_FAILED', error?.message || String(error), { status: Number(error?.status) || 400 });
1260
+ }
1261
+ const delivered = [];
1262
+ if (!out.duplicate) {
1263
+ const event = store.get(out.id);
1264
+ for (const each of recipients) {
1265
+ const pushed = event ? pushTo(record, each.runId, [event]) : false;
1266
+ delivered.push({ sliceId: each.sliceId, how: pushed ? 'follow-up' : 'mailbox' });
1267
+ }
1268
+ // The lead (the Assistant) hears what is addressed to it, and a question or change request nobody else got.
1269
+ if (target === 'lead' || (toLead && !recipients.length && TEAM_ACTION_KINDS.includes(messageKind))) {
1270
+ emit(record, 'team_message', { sliceId: who.sliceId, runId: String(runId), messageKind, text: `[${messageKind}] from slice ${who.sliceId}: ${body}`, untrusted: true, ...(path ? { path: String(path).slice(0, 400) } : {}) });
1271
+ delivered.push({ sliceId: null, how: 'lead' });
1272
+ } else {
1273
+ try { broadcast({ type: TEAM_CHANGED, teamId: record.teamId, event: 'message', status: record.status, sliceId: who.sliceId }); } catch { /* no page is listening */ }
1274
+ }
1275
+ }
1276
+ return { ok: true, id: out.id, seq: out.seq, duplicate: out.duplicate === true, to: payload.to, toSlice, delivered };
1277
+ }
1278
+
1279
+ const kindsOf = (kinds) => {
1280
+ const list = (Array.isArray(kinds) ? kinds : (kinds ? [kinds] : [])).map((kind) => String(kind).trim().toLowerCase()).filter((kind) => TEAM_MESSAGE_KINDS.includes(kind));
1281
+ return list.length ? list : null;
1282
+ };
1283
+ /** A position in the log a caller named, or null when it named none. */
1284
+ const seqOf = (value) => { if (value === null || value === undefined || value === '') return null; const n = Number(value); return Number.isInteger(n) && n >= 0 ? n : null; };
1285
+
1286
+ /** A member's messages after a position (default: what it has not acknowledged), oldest first. */
1287
+ function read(runId, { afterSeq = null, kinds = null, limit = null } = {}) {
1288
+ const who = member(runId);
1289
+ if (!who) return noMember();
1290
+ const wanted = kindsOf(kinds);
1291
+ const max = Math.max(1, Math.min(limits.readLimit, Number(limit) || limits.readLimit));
1292
+ const cursor = seqOf(afterSeq);
1293
+ let rows = [];
1294
+ try { rows = coordination.team.read({ teamId: who.teamId, runId: String(runId), afterSeq: cursor, limit: 200 }); } catch (error) { return refuse(error?.code || 'TEAM_READ_FAILED', error?.message || String(error), { status: Number(error?.status) || 400 }); }
1295
+ const messages = rows.filter((event) => event.kind === TEAM_MESSAGE_LOG_KIND).map(messageView).filter((message) => !wanted || wanted.includes(message.kind)).slice(0, max);
1296
+ const last = rows.length ? rows[rows.length - 1].seq : (cursor ?? coordination.team.cursor({ teamId: who.teamId, runId: String(runId) }));
1297
+ return { ok: true, teamId: who.teamId, sliceId: who.sliceId, untrusted: true, notice: PEER_NOTICE, messages, cursor: messages.length === max && messages.length ? messages[messages.length - 1].seq : last };
1298
+ }
1299
+
1300
+ /** Wait (bounded) until the member has a message of the kinds it names, then read. */
1301
+ async function wait(runId, { afterSeq = null, kinds = null, timeoutMs = null } = {}) {
1302
+ const who = member(runId);
1303
+ if (!who) return noMember();
1304
+ const budget = Math.max(0, Math.min(limits.maxWaitMs, Number.isFinite(Number(timeoutMs)) && timeoutMs !== null ? Number(timeoutMs) : limits.defaultWaitMs));
1305
+ const deadline = now() + budget;
1306
+ let cursor = seqOf(afterSeq);
1307
+ for (;;) {
1308
+ const got = read(runId, { afterSeq: cursor, kinds });
1309
+ if (!got.ok) return got;
1310
+ if (got.messages.length) return { ...got, timedOut: false };
1311
+ cursor = got.cursor ?? cursor;
1312
+ const left = deadline - now();
1313
+ if (left <= 0) return { ...got, timedOut: true };
1314
+ let woke = null;
1315
+ try { woke = await coordination.team.wait({ teamId: who.teamId, runId: String(runId), afterSeq: cursor, timeoutMs: left, limit: 50 }); } catch (error) { return refuse(error?.code || 'TEAM_WAIT_FAILED', error?.message || String(error), { status: 400 }); }
1316
+ if (woke.closed || woke.aborted) return { ...got, timedOut: true };
1317
+ if (woke.timedOut) return { ...got, timedOut: true };
1318
+ // Something arrived: read again from the same position (it may be of another kind).
1319
+ if (!member(runId)) return { ...got, timedOut: true };
1320
+ }
1321
+ }
1322
+
1323
+ /** The member dealt with these messages (their ids), or with everything up to a seq. */
1324
+ function ack(runId, { ids = null, throughSeq = null } = {}) {
1325
+ const who = member(runId);
1326
+ if (!who) return noMember();
1327
+ const through = seqOf(throughSeq);
1328
+ const eventIds = (Array.isArray(ids) ? ids : (ids ? [ids] : [])).map(String).slice(0, 200);
1329
+ if (through === null && !eventIds.length) return refuse('TEAM_ACK_EMPTY', 'Name the message ids, or through_seq.', { status: 400 });
1330
+ try {
1331
+ const out = coordination.team.ack({ teamId: who.teamId, runId: String(runId), ...(through !== null ? { throughSeq: through } : { eventIds }) });
1332
+ return { ok: true, acked: out.acked, cursor: out.cursor };
1333
+ } catch (error) { return refuse(error?.code || 'TEAM_ACK_FAILED', error?.message || String(error), { status: Number(error?.status) || 400 }); }
1334
+ }
1335
+
1336
+ /** Who owns a path of the project (with `path`), or every slice with what it owns. */
1337
+ function claims(runId, { path = null } = {}) {
1338
+ const who = member(runId);
1339
+ if (!who) return noMember();
1340
+ const record = records.get(who.teamId);
1341
+ const journal = journalOf(who.teamId);
1342
+ const plan = journal?.plan || record.plan;
1343
+ if (path !== null && path !== undefined && String(path).trim()) {
1344
+ const verdict = teams.checkWrite(who.teamId, who.sliceId, String(path));
1345
+ return { ok: true, teamId: who.teamId, sliceId: who.sliceId, path: verdict.relPath || String(path), owner: verdict.owner ?? null, mine: verdict.owner === who.sliceId, writable: verdict.allow === true, code: verdict.code, message: verdict.message || null };
1346
+ }
1347
+ let held = [];
1348
+ try { held = store.claimsFor({ teamId: who.teamId }); } catch { held = []; }
1349
+ return {
1350
+ ok: true, teamId: who.teamId, sliceId: who.sliceId,
1351
+ slices: plan.slices.map((slice) => ({
1352
+ id: slice.id, title: slice.title || null, mine: slice.id === who.sliceId, ownedPaths: [...(slice.ownedPaths || [])], lockfileOwner: slice.lockfileOwner === true,
1353
+ status: sliceStateOf(journal, slice.id), hasWorker: !!liveMembers(record).find((each) => each.sliceId === slice.id),
1354
+ held: held.filter((claim) => claim.sliceId === slice.id).map((claim) => claim.glob),
1355
+ })),
1356
+ };
1357
+ }
1358
+
1359
+ /** Ask the slice that owns a file outside the caller's claim to change it. Nobody open owns it: the lead is asked. */
1360
+ function request(runId, { path = '', text = '' } = {}) {
1361
+ const who = member(runId);
1362
+ if (!who) return noMember();
1363
+ const record = records.get(who.teamId);
1364
+ const plan = journalOf(who.teamId)?.plan || record.plan;
1365
+ const rel = normalizeRelPath(String(path || ''));
1366
+ if (!rel) return refuse('TEAM_PATH_REQUIRED', 'path is required: the file you need changed, relative to the project.', { status: 400 });
1367
+ const body = String(text ?? '').trim();
1368
+ if (!body) return refuse('TEAM_TEXT_REQUIRED', 'text is required: exactly what should change in that file, and why.', { status: 400 });
1369
+ const owner = pathOwner(plan, rel);
1370
+ if (owner === who.sliceId) return refuse('TEAM_OWN_FILE', `${rel} is your own file: change it yourself.`, { status: 400, owner });
1371
+ const open = owner ? liveMembers(record).some((each) => each.sliceId === owner) : false;
1372
+ const sent = post(runId, { to: open ? owner : 'lead', kind: 'request_change', path: rel, text: open ? body : `${owner ? `The owner of ${rel} (slice ${owner}) has no worker now` : `No slice owns ${rel}`}. Requested change: ${body}` });
1373
+ if (!sent.ok) return sent;
1374
+ return { ...sent, path: rel, owner: owner || null, askedOf: open ? `slice ${owner}` : 'lead', note: open ? `Slice ${owner} was asked. Wait for its answer with the team tool (wait, kinds ["answer"]) or go on with what does not depend on it.` : 'The team lead (the Assistant) was asked: go on with what does not depend on it, and say in your ## Result block what is still open.' };
1375
+ }
1376
+
1377
+ // ── start-up, shutdown ─────────────────────────────────────────────────────
1378
+ /**
1379
+ * Once, at start-up: the library's own recovery, then every team under way is looked at again. A slice whose
1380
+ * worker reported done before the stop is finished and joined; a finished slice is joined; a slice whose worker
1381
+ * did not come back needs attention; a run the dispatcher resumes is its slice's again by itself.
1382
+ * `settleMs`: how long to give resumed runs to be known before a missing one counts as gone.
1383
+ */
1384
+ async function recover() {
1385
+ let recovered = null;
1386
+ attach();
1387
+ const recovering = (async () => { try { recovered = await teams.recover(); } catch (error) { say('teams:recover-failed', error?.message || String(error)); } })();
1388
+ ready = recovering;
1389
+ await recovering;
1390
+ const out = [];
1391
+ for (const record of records.values()) {
1392
+ if (!OPEN_STATUSES.has(record.status)) continue;
1393
+ out.push(await inTurn(record.teamId, async () => {
1394
+ await withAllSlices(record, async () => {
1395
+ const journal = journalOf(record.teamId);
1396
+ if (!journal) { record.status = 'failed'; record.attention = { code: 'TEAM_RECORD_MISSING', sliceId: null, message: 'The team has no record in the journal any more.', at: iso(now()) }; save(record); return { teamId: record.teamId, status: record.status }; }
1397
+ if (journal.state === 'merged') { record.status = 'landed'; save(record); return { teamId: record.teamId, status: record.status }; }
1398
+ if (journal.state === 'cancelled' || journal.state === 'failed') { record.status = journal.state === 'failed' ? 'failed' : 'discarded'; save(record); return { teamId: record.teamId, status: record.status }; }
1399
+ for (const slice of record.plan.slices) {
1400
+ const mine = record.slices[slice.id];
1401
+ const state = sliceStateOf(journal, slice.id);
1402
+ if (state === 'integrated') { mine.phase = 'integrated'; continue; }
1403
+ if (state === 'done') {
1404
+ mine.phase = 'done';
1405
+ const run = runOf(mine.runId);
1406
+ if (mine.handledTurn && run?.resultTurn > mine.handledTurn) await reconcileRun(record, slice.id, mine.runId);
1407
+ continue;
1408
+ }
1409
+ if (!mine.runId) continue;
1410
+ const run = runOf(mine.runId);
1411
+ if (record.plan.readOnly) {
1412
+ if (journal.slices[slice.id]?.cleanup) { mine.phase = state; mine.released = true; continue; }
1413
+ if (!runLive(run) || (runIdle(run) && run.lastResult?.status === 'done')) await finishReader(record, slice.id, { failed: run?.lastResult?.status !== 'done' });
1414
+ continue;
1415
+ }
1416
+ // Live events can be lost across a restart. Replay the same result rules as the watchdog.
1417
+ if (state === 'running' && canFinish(run)) {
1418
+ await reconcileRun(record, slice.id, mine.runId);
1419
+ continue;
1420
+ }
1421
+ if (runLive(run)) continue;
1422
+ if (['running', 'conflict', 'tests-failed', 'rejected'].includes(state) && record.status === 'running') {
1423
+ mine.phase = 'failed';
1424
+ attention(record, { code: 'SLICE_WORKER_LOST', sliceId: slice.id, message: `The worker of slice ${slice.id} did not come back after the restart. Its files are in its worktree. agent_team integrate gives the slice to a new worker.` });
1425
+ }
1426
+ }
1427
+ if (record.plan.readOnly && Object.values(record.slices).every(s => s.released) && record.status === 'running') { record.status = 'completed'; emit(record, 'team_completed', { text: 'Read-only workers finished; synthesize their results.' }); }
1428
+ });
1429
+ if (!record.plan.readOnly && OPEN_STATUSES.has(record.status) && record.status !== 'needs_attention') await joinFinished(record);
1430
+ save(record);
1431
+ return { teamId: record.teamId, status: record.status };
1432
+ }));
1433
+ }
1434
+ return { ok: true, library: recovered, teams: out };
1435
+ }
1436
+
1437
+ function attach() {
1438
+ if (unsubscribe || closed) return;
1439
+ const dispatcher = dispatcherOf();
1440
+ if (dispatcher && typeof dispatcher.subscribe === 'function') {
1441
+ unsubscribe = dispatcher.subscribe(onDispatch);
1442
+ watchdog = setInterval(checkProgress, limits.reconcileEveryMs);
1443
+ watchdog.unref?.();
1444
+ }
1445
+ }
1446
+
1447
+ async function shutdown() {
1448
+ closed = true;
1449
+ clearInterval(watchdog);
1450
+ if (unsubscribe) { try { unsubscribe(); } catch { /* gone already */ } unsubscribe = null; }
1451
+ await settled();
1452
+ }
1453
+
1454
+ loadRecords();
1455
+
1456
+ return Object.freeze({
1457
+ limits,
1458
+ plan, start, status, list, get, ownedBy, integrate, land, cleanup, discard,
1459
+ // the channel of a worker's `team` tool (the caller's proven run id decides the team)
1460
+ member, post, read, wait, ack, claims, request,
1461
+ recover, attach, shutdown, settled,
1462
+ _internals: { records, runIndex, onDispatch, joinFinished, startReady, dispatchSlice, emit },
1463
+ });
1464
+ }
1465
+
1466
+ // ── the server's one scheduler ─────────────────────────────────────────────────
1467
+ // server.js makes one (its agents-p4 block) and shares it here; the Assistant's API and the Agents Studio routes
1468
+ // ask for it when a request arrives, so neither is handed it through its own options.
1469
+ let sharedScheduler = null;
1470
+ /** Share the server's scheduler (null: none). Returns it. */
1471
+ export function shareTeamScheduler(scheduler) { sharedScheduler = scheduler || null; return sharedScheduler; }
1472
+ export function sharedTeamScheduler() { return sharedScheduler; }
1473
+
1474
+ export { normalizeTeamPlan };