@adhdev/daemon-core 0.9.82-rc.49 → 0.9.82-rc.490

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 (473) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +9 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +220 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +137 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +69 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +23 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +71 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +64 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +48 -0
  50. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  51. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  52. package/dist/commands/med-family/mesh-restart.d.ts +2 -0
  53. package/dist/commands/med-family/types.d.ts +152 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router-aggregate-status.d.ts +24 -0
  56. package/dist/commands/router-mesh-session-owner.d.ts +59 -0
  57. package/dist/commands/router-refine.d.ts +151 -0
  58. package/dist/commands/router-worktree-cleanup.d.ts +133 -0
  59. package/dist/commands/router.d.ts +203 -15
  60. package/dist/commands/upgrade-helper.d.ts +41 -1
  61. package/dist/config/chat-history.d.ts +11 -0
  62. package/dist/config/config.d.ts +19 -0
  63. package/dist/config/mesh-config.d.ts +65 -0
  64. package/dist/config/mesh-json-config.d.ts +199 -0
  65. package/dist/config/registry-resolver.d.ts +54 -0
  66. package/dist/config/repo-settings.d.ts +77 -0
  67. package/dist/config/state-store.d.ts +30 -0
  68. package/dist/daemon/dev-server.d.ts +0 -2
  69. package/dist/detection/cli-detector.d.ts +17 -0
  70. package/dist/detection/ide-detector.d.ts +13 -0
  71. package/dist/detection/win32-ide-version.d.ts +37 -0
  72. package/dist/git/change-impact-config.d.ts +159 -0
  73. package/dist/git/git-commands.d.ts +26 -2
  74. package/dist/git/git-diff.d.ts +6 -0
  75. package/dist/git/git-executor.d.ts +11 -0
  76. package/dist/git/git-status.d.ts +80 -0
  77. package/dist/git/git-types.d.ts +2 -50
  78. package/dist/git/git-worktree.d.ts +71 -1
  79. package/dist/git/index.d.ts +3 -1
  80. package/dist/index.d.ts +70 -17
  81. package/dist/index.js +53532 -19073
  82. package/dist/index.js.map +1 -1
  83. package/dist/index.mjs +53283 -18989
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/installer.d.ts +1 -4
  86. package/dist/ipc/local-ipc-server.d.ts +91 -0
  87. package/dist/launch.d.ts +1 -1
  88. package/dist/logging/async-batch-writer.d.ts +10 -0
  89. package/dist/logging/debug-config.d.ts +16 -0
  90. package/dist/logging/log-redactor.d.ts +24 -0
  91. package/dist/logging/log-tail-reader.d.ts +81 -0
  92. package/dist/logging/logger.d.ts +1 -1
  93. package/dist/mesh/contracts.d.ts +256 -0
  94. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  95. package/dist/mesh/coordinator-registry.d.ts +59 -0
  96. package/dist/mesh/mesh-active-work.d.ts +203 -0
  97. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  98. package/dist/mesh/mesh-completion-synthesis.d.ts +4 -0
  99. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  100. package/dist/mesh/mesh-delivery-policy.d.ts +104 -0
  101. package/dist/mesh/mesh-event-classify.d.ts +7 -0
  102. package/dist/mesh/mesh-event-forwarding.d.ts +58 -0
  103. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  104. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  105. package/dist/mesh/mesh-events-pending.d.ts +258 -0
  106. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  107. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  108. package/dist/mesh/mesh-events.d.ts +6 -49
  109. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  110. package/dist/mesh/mesh-host-ownership.d.ts +21 -1
  111. package/dist/mesh/mesh-init.d.ts +128 -0
  112. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  113. package/dist/mesh/mesh-ledger.d.ts +139 -1
  114. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  115. package/dist/mesh/mesh-missions.d.ts +281 -0
  116. package/dist/mesh/mesh-node-identity.d.ts +310 -0
  117. package/dist/mesh/mesh-queue-assignment.d.ts +162 -0
  118. package/dist/mesh/mesh-reconcile-acked-hold.d.ts +17 -0
  119. package/dist/mesh/mesh-reconcile-config.d.ts +6 -0
  120. package/dist/mesh/mesh-reconcile-identity.d.ts +6 -0
  121. package/dist/mesh/mesh-reconcile-loop.d.ts +84 -0
  122. package/dist/mesh/mesh-reconcile-v2-backstop.d.ts +16 -0
  123. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  124. package/dist/mesh/mesh-refine-gates.d.ts +457 -0
  125. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  126. package/dist/mesh/mesh-remote-event-pull.d.ts +15 -0
  127. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  128. package/dist/mesh/mesh-routing.d.ts +70 -0
  129. package/dist/mesh/mesh-runtime-store.d.ts +567 -0
  130. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  131. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  132. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  133. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +34 -0
  134. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  135. package/dist/mesh/mesh-work-queue.d.ts +392 -1
  136. package/dist/mesh/preview-freshness.d.ts +28 -0
  137. package/dist/mesh/refine-config.d.ts +97 -0
  138. package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
  139. package/dist/providers/acp-provider-instance.d.ts +5 -0
  140. package/dist/providers/approval-utils.d.ts +46 -0
  141. package/dist/providers/chat-message-normalization.d.ts +58 -1
  142. package/dist/providers/cli-provider-effect-format.d.ts +30 -0
  143. package/dist/providers/cli-provider-history-dedup.d.ts +17 -0
  144. package/dist/providers/cli-provider-input-prompt.d.ts +12 -0
  145. package/dist/providers/cli-provider-instance-types.d.ts +45 -0
  146. package/dist/providers/cli-provider-instance.d.ts +426 -30
  147. package/dist/providers/cli-provider-status-helpers.d.ts +46 -0
  148. package/dist/providers/cli-provider-transcript-merge.d.ts +7 -0
  149. package/dist/providers/contracts.d.ts +196 -6
  150. package/dist/providers/external-sources.d.ts +71 -0
  151. package/dist/providers/manual-attendance.d.ts +79 -0
  152. package/dist/providers/native-history/antigravity-claim-registry.d.ts +39 -0
  153. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
  154. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  155. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  156. package/dist/providers/native-history/constants.d.ts +12 -0
  157. package/dist/providers/native-history/dispatcher.d.ts +44 -0
  158. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  159. package/dist/providers/native-history/index.d.ts +13 -0
  160. package/dist/providers/provider-instance-manager.d.ts +30 -0
  161. package/dist/providers/provider-instance.d.ts +31 -1
  162. package/dist/providers/provider-loader.d.ts +42 -5
  163. package/dist/providers/provider-trust.d.ts +31 -0
  164. package/dist/providers/read-chat-contract.d.ts +29 -0
  165. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  166. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  167. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  168. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  169. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  170. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  171. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  172. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  173. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  174. package/dist/providers/sdk/v1/index.d.ts +30 -0
  175. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  176. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  177. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  178. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  179. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  180. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  181. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  182. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  183. package/dist/providers/spec/adapter.d.ts +98 -0
  184. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  185. package/dist/providers/spec/evaluator.d.ts +45 -0
  186. package/dist/providers/spec/fsm-driver.d.ts +449 -0
  187. package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
  188. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  189. package/dist/providers/spec/fsm-types.d.ts +202 -0
  190. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  191. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  192. package/dist/providers/spec/route.d.ts +4 -0
  193. package/dist/providers/spec/types.d.ts +244 -0
  194. package/dist/providers/status-monitor.d.ts +7 -7
  195. package/dist/providers/transcript-v2.d.ts +176 -0
  196. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  197. package/dist/providers/working-dir.d.ts +17 -0
  198. package/dist/repo-mesh-types.d.ts +616 -12
  199. package/dist/runtime-defaults.d.ts +2 -0
  200. package/dist/session-host/managed-host.d.ts +64 -0
  201. package/dist/session-host/runtime-surface.d.ts +10 -16
  202. package/dist/sessions/registry.d.ts +26 -0
  203. package/dist/shared-types-extra.d.ts +2 -4
  204. package/dist/shared-types.d.ts +110 -55
  205. package/dist/status/chat-tail-hot-sessions.d.ts +40 -0
  206. package/dist/status/normalize.d.ts +1 -1
  207. package/dist/status/normalize.js +1 -0
  208. package/dist/status/normalize.js.map +1 -1
  209. package/dist/status/normalize.mjs +1 -0
  210. package/dist/status/normalize.mjs.map +1 -1
  211. package/dist/status/reporter.d.ts +2 -0
  212. package/dist/status/snapshot.d.ts +27 -0
  213. package/dist/system/hash.d.ts +8 -0
  214. package/dist/system/load-better-sqlite3.d.ts +21 -0
  215. package/dist/types.d.ts +20 -6
  216. package/package.json +11 -4
  217. package/src/agent-stream/poller.ts +2 -3
  218. package/src/agent-stream/provider-adapter.ts +1 -1
  219. package/src/boot/daemon-lifecycle.ts +80 -14
  220. package/src/boot/process-hardening.ts +89 -0
  221. package/src/build-info.ts +73 -0
  222. package/src/chat/source-machine.ts +534 -0
  223. package/src/chat/source-resolver.ts +0 -0
  224. package/src/chat/subscription-updates.ts +20 -1
  225. package/src/cli-adapter-types.d.ts +3 -1
  226. package/src/cli-adapter-types.ts +68 -2
  227. package/src/cli-adapters/cli-script-runner.ts +421 -0
  228. package/src/cli-adapters/cli-state-engine.ts +1282 -0
  229. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  230. package/src/cli-adapters/provider-cli-adapter.ts +1048 -1143
  231. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  232. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  233. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  234. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  235. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  236. package/src/cli-adapters/pty-transport.ts +2 -1
  237. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  238. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  239. package/src/cli-adapters/resolve-executable.ts +204 -0
  240. package/src/cli-adapters/session-host-transport.ts +2 -1
  241. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  242. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  243. package/src/cli-adapters/terminal-screen.ts +16 -81
  244. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  245. package/src/commands/chat-commands-read.ts +2788 -0
  246. package/src/commands/chat-commands-scope.ts +54 -0
  247. package/src/commands/chat-commands-shared.ts +114 -0
  248. package/src/commands/chat-commands-write.ts +891 -0
  249. package/src/commands/chat-commands.ts +19 -1841
  250. package/src/commands/cli-manager.d.ts +2 -0
  251. package/src/commands/cli-manager.ts +724 -27
  252. package/src/commands/handler.ts +865 -2
  253. package/src/commands/high-family/index.ts +28 -0
  254. package/src/commands/high-family/mesh-coordinator-launch.ts +696 -0
  255. package/src/commands/high-family/mesh-events.ts +102 -0
  256. package/src/commands/high-family/mesh-status.ts +857 -0
  257. package/src/commands/high-family/types.ts +80 -0
  258. package/src/commands/low-family/coordinator-prompt.ts +125 -0
  259. package/src/commands/low-family/daemon-lifecycle.ts +120 -0
  260. package/src/commands/low-family/diagnostics.ts +57 -0
  261. package/src/commands/low-family/index.ts +37 -0
  262. package/src/commands/low-family/mesh-ledger.ts +62 -0
  263. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  264. package/src/commands/low-family/notification.ts +116 -0
  265. package/src/commands/low-family/refine-config.ts +106 -0
  266. package/src/commands/low-family/session-host.ts +282 -0
  267. package/src/commands/low-family/spec-providerdev.ts +217 -0
  268. package/src/commands/low-family/status-meta.ts +112 -0
  269. package/src/commands/low-family/types.ts +39 -0
  270. package/src/commands/med-family/cli-agent.ts +270 -0
  271. package/src/commands/med-family/fast-forward.ts +230 -0
  272. package/src/commands/med-family/ide.ts +163 -0
  273. package/src/commands/med-family/index.ts +37 -0
  274. package/src/commands/med-family/mesh-crud.ts +1268 -0
  275. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  276. package/src/commands/med-family/mesh-queue.ts +167 -0
  277. package/src/commands/med-family/mesh-restart.ts +92 -0
  278. package/src/commands/med-family/types.ts +153 -0
  279. package/src/commands/mesh-coordinator.ts +334 -124
  280. package/src/commands/router-aggregate-status.ts +209 -0
  281. package/src/commands/router-mesh-session-owner.ts +114 -0
  282. package/src/commands/router-refine.ts +1794 -0
  283. package/src/commands/router-worktree-cleanup.ts +870 -0
  284. package/src/commands/router.ts +567 -4149
  285. package/src/commands/stream-commands.ts +8 -0
  286. package/src/commands/upgrade-helper.ts +310 -45
  287. package/src/config/chat-history.ts +517 -24
  288. package/src/config/config.ts +30 -0
  289. package/src/config/mesh-config.ts +300 -24
  290. package/src/config/mesh-json-config.ts +376 -0
  291. package/src/config/recent-activity.ts +8 -2
  292. package/src/config/registry-resolver.ts +100 -0
  293. package/src/config/repo-settings.ts +111 -0
  294. package/src/config/state-store.ts +55 -0
  295. package/src/daemon/dev-auto-implement.ts +3 -2
  296. package/src/daemon/dev-cli-debug.ts +10 -1
  297. package/src/daemon/dev-server.ts +0 -541
  298. package/src/detection/cli-detector.ts +94 -9
  299. package/src/detection/ide-detector.ts +55 -16
  300. package/src/detection/win32-ide-version.ts +106 -0
  301. package/src/git/change-impact-config.ts +354 -0
  302. package/src/git/git-commands.ts +112 -16
  303. package/src/git/git-diff.ts +81 -11
  304. package/src/git/git-executor.ts +12 -0
  305. package/src/git/git-status.ts +822 -48
  306. package/src/git/git-types.ts +14 -62
  307. package/src/git/git-worktree.ts +261 -4
  308. package/src/git/index.ts +17 -0
  309. package/src/index.ts +190 -13
  310. package/src/installer.d.ts +1 -1
  311. package/src/installer.ts +8 -6
  312. package/src/ipc/local-ipc-server.ts +278 -0
  313. package/src/launch.d.ts +1 -1
  314. package/src/launch.ts +37 -28
  315. package/src/logging/async-batch-writer.ts +55 -0
  316. package/src/logging/command-log.ts +7 -5
  317. package/src/logging/debug-config.ts +25 -0
  318. package/src/logging/debug-trace.ts +7 -2
  319. package/src/logging/log-redactor.ts +100 -0
  320. package/src/logging/log-tail-reader.ts +341 -0
  321. package/src/logging/logger.ts +14 -7
  322. package/src/mesh/contracts.ts +510 -0
  323. package/src/mesh/coordinator-prompt.ts +627 -34
  324. package/src/mesh/coordinator-registry.ts +121 -0
  325. package/src/mesh/mesh-active-work.ts +706 -0
  326. package/src/mesh/mesh-clone-grace.ts +68 -0
  327. package/src/mesh/mesh-completion-synthesis.ts +416 -0
  328. package/src/mesh/mesh-coordinator-config.ts +97 -0
  329. package/src/mesh/mesh-delivery-policy.ts +284 -0
  330. package/src/mesh/mesh-event-classify.ts +78 -0
  331. package/src/mesh/mesh-event-forwarding.ts +2030 -0
  332. package/src/mesh/mesh-event-trace.ts +67 -0
  333. package/src/mesh/mesh-events-coordinator.ts +32 -0
  334. package/src/mesh/mesh-events-pending.ts +1548 -0
  335. package/src/mesh/mesh-events-stale.ts +452 -0
  336. package/src/mesh/mesh-events-utils.ts +443 -0
  337. package/src/mesh/mesh-events.ts +43 -1035
  338. package/src/mesh/mesh-fast-forward.ts +856 -0
  339. package/src/mesh/mesh-host-ownership.ts +41 -3
  340. package/src/mesh/mesh-init.ts +350 -0
  341. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  342. package/src/mesh/mesh-ledger.ts +897 -102
  343. package/src/mesh/mesh-magi-status.ts +223 -0
  344. package/src/mesh/mesh-missions.ts +695 -0
  345. package/src/mesh/mesh-node-identity.ts +2065 -0
  346. package/src/mesh/mesh-queue-assignment.ts +2498 -0
  347. package/src/mesh/mesh-reconcile-acked-hold.ts +230 -0
  348. package/src/mesh/mesh-reconcile-config.ts +66 -0
  349. package/src/mesh/mesh-reconcile-identity.ts +103 -0
  350. package/src/mesh/mesh-reconcile-loop.ts +1696 -0
  351. package/src/mesh/mesh-reconcile-v2-backstop.ts +62 -0
  352. package/src/mesh/mesh-refine-batch.ts +205 -0
  353. package/src/mesh/mesh-refine-gates.ts +1792 -0
  354. package/src/mesh/mesh-refine-status.ts +231 -0
  355. package/src/mesh/mesh-remote-event-pull.ts +279 -0
  356. package/src/mesh/mesh-review-inbox.ts +308 -0
  357. package/src/mesh/mesh-routing.ts +291 -0
  358. package/src/mesh/mesh-runtime-store.ts +2292 -0
  359. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  360. package/src/mesh/mesh-task-inflight.ts +70 -0
  361. package/src/mesh/mesh-task-stats.ts +161 -0
  362. package/src/mesh/mesh-unresolved-forward-outbox.ts +215 -0
  363. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  364. package/src/mesh/mesh-work-queue.ts +1489 -145
  365. package/src/mesh/preview-freshness.ts +163 -0
  366. package/src/mesh/refine-config.ts +129 -12
  367. package/src/mesh/worktree-bootstrap-config.ts +599 -0
  368. package/src/providers/acp-provider-instance.ts +43 -10
  369. package/src/providers/approval-utils.d.ts +5 -0
  370. package/src/providers/approval-utils.ts +100 -6
  371. package/src/providers/chat-message-normalization.ts +126 -4
  372. package/src/providers/cli-provider-effect-format.ts +53 -0
  373. package/src/providers/cli-provider-history-dedup.ts +75 -0
  374. package/src/providers/cli-provider-input-prompt.ts +133 -0
  375. package/src/providers/cli-provider-instance-types.ts +131 -0
  376. package/src/providers/cli-provider-instance.ts +2771 -499
  377. package/src/providers/cli-provider-status-helpers.ts +123 -0
  378. package/src/providers/cli-provider-transcript-merge.ts +114 -0
  379. package/src/providers/contracts.d.ts +55 -0
  380. package/src/providers/contracts.ts +207 -6
  381. package/src/providers/extension-provider-instance.ts +12 -7
  382. package/src/providers/external-sources.ts +218 -0
  383. package/src/providers/ide-provider-instance.ts +35 -12
  384. package/src/providers/manual-attendance.ts +105 -0
  385. package/src/providers/native-history/antigravity-claim-registry.ts +138 -0
  386. package/src/providers/native-history/antigravity-cli-transcript.ts +1275 -0
  387. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  388. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  389. package/src/providers/native-history/constants.ts +19 -0
  390. package/src/providers/native-history/dispatcher.ts +617 -0
  391. package/src/providers/native-history/hermes-cli-transcript.ts +312 -0
  392. package/src/providers/native-history/index.ts +30 -0
  393. package/src/providers/provider-instance-manager.ts +71 -0
  394. package/src/providers/provider-instance.ts +24 -1
  395. package/src/providers/provider-loader.ts +700 -55
  396. package/src/providers/provider-schema.ts +93 -14
  397. package/src/providers/provider-trust.ts +114 -0
  398. package/src/providers/read-chat-contract.ts +76 -16
  399. package/src/providers/sdk/README.md +49 -0
  400. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  401. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  402. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  403. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
  404. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  405. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  406. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  407. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  408. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  409. package/src/providers/sdk/v1/index.ts +152 -0
  410. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  411. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  412. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  413. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +538 -0
  414. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  415. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  416. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  417. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  418. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  419. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  420. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  421. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  422. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  423. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  424. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  425. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  426. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  427. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  428. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  429. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  430. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  431. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  432. package/src/providers/sdk/v1/validators/index.ts +19 -0
  433. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  434. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  435. package/src/providers/spec/adapter.ts +246 -0
  436. package/src/providers/spec/cli-adapter.ts +1064 -0
  437. package/src/providers/spec/evaluator.ts +407 -0
  438. package/src/providers/spec/fsm-driver.ts +1528 -0
  439. package/src/providers/spec/fsm-evaluator.ts +290 -0
  440. package/src/providers/spec/fsm-loader.ts +128 -0
  441. package/src/providers/spec/fsm-types.ts +301 -0
  442. package/src/providers/spec/native-history-executor.ts +1241 -0
  443. package/src/providers/spec/pre-launch-trust.ts +104 -0
  444. package/src/providers/spec/route.ts +51 -0
  445. package/src/providers/spec/types.ts +284 -0
  446. package/src/providers/status-monitor.d.ts +7 -7
  447. package/src/providers/status-monitor.ts +37 -22
  448. package/src/providers/transcript-v2.ts +567 -0
  449. package/src/providers/types/interactive-prompt.ts +536 -0
  450. package/src/providers/version-archive.ts +64 -24
  451. package/src/providers/working-dir.ts +23 -0
  452. package/src/repo-mesh-types.ts +861 -14
  453. package/src/runtime-defaults.ts +39 -0
  454. package/src/session-host/managed-host.ts +218 -0
  455. package/src/session-host/runtime-surface.ts +20 -80
  456. package/src/sessions/registry.ts +44 -0
  457. package/src/shared-types-extra.ts +2 -4
  458. package/src/shared-types.d.ts +8 -0
  459. package/src/shared-types.ts +148 -55
  460. package/src/status/builders.ts +69 -6
  461. package/src/status/chat-tail-hot-sessions.ts +117 -2
  462. package/src/status/normalize.ts +2 -0
  463. package/src/status/reporter.ts +19 -1
  464. package/src/status/snapshot.ts +100 -27
  465. package/src/system/hash.ts +23 -0
  466. package/src/system/host-memory.ts +29 -12
  467. package/src/system/load-better-sqlite3.ts +68 -0
  468. package/src/types.ts +26 -6
  469. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  470. package/dist/mesh/mesh-sync.d.ts +0 -53
  471. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  472. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  473. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1268 @@
1
+ /**
2
+ * RF-ROUTER MED family — mesh CRUD + node CRUD commands.
3
+ *
4
+ * Mesh records (list/get/create/update/delete_mesh) and node lifecycle
5
+ * (add/update/remove/clone_mesh_node, cleanup_mesh_sessions,
6
+ * retry_mesh_node_bootstrap). get_mesh hydrates direct git truth; the mutating
7
+ * node commands gate on the Mesh Host owner check and bust the aggregate-status
8
+ * cache; clone/remove/retry forward to the owning daemon for remote worktrees.
9
+ * Extracted verbatim from executeDaemonCommand; the inline-cache, session/worktree
10
+ * cleanup and aggregate-status collaborators come from ctx.
11
+ */
12
+ import { daemonIdsEquivalent, meshNodeIdMatches, normalizeMeshNodeId } from '@adhdev/mesh-shared';
13
+ import { resolveMeshHostStatus, normalizeMeshDaemonRole } from '../../mesh/mesh-host-ownership.js';
14
+ import {
15
+ getRegisteredSubmodulePaths,
16
+ loadMeshWorktreeBootstrapConfig,
17
+ runMeshWorktreeBootstrap,
18
+ type WorktreeBootstrapState,
19
+ } from '../../mesh/worktree-bootstrap-config.js';
20
+ import { loadRepoSettings } from '../../config/repo-settings.js';
21
+ import { handleMeshForwardEvent, queuePendingMeshCoordinatorEvent } from '../../mesh/mesh-events.js';
22
+ import { noteRecentlyClonedNode } from '../../mesh/mesh-clone-grace.js';
23
+ import { loadConfig } from '../../config/config.js';
24
+ import {
25
+ hydrateInlineMeshDirectTruth,
26
+ normalizeProviderRoles,
27
+ readMeshNodeMachineId,
28
+ } from '../router.js';
29
+ import type { CommandRouterResult } from '../router.js';
30
+ import type { GitRepoIdentity } from '../../git/git-types.js';
31
+ import type { MedFamilyContext, MedFamilyHandler } from './types.js';
32
+
33
+ /**
34
+ * Decision for syncing a freshly-cloned worktree's `oss` submodule to its clone
35
+ * source node, applying resolveWorktreeBaseStartPoint's origin-tip-priority
36
+ * policy to the submodule.
37
+ *
38
+ * On clone, `submodule update --init` checks the worktree's `oss` out at the
39
+ * gitlink recorded in the FRESH root base — which the root base-stale fix
40
+ * branches from origin/main, so it is the up-to-date origin tip. The clone
41
+ * source node's *working* `oss` SHA can lag that tip. The original sync blindly
42
+ * checked out the source SHA whenever it merely differed, which REWINDS the
43
+ * submodule back onto the stale source and re-introduces staleness.
44
+ *
45
+ * Guard policy (never rewind, mirror the base-start-point resolver):
46
+ * - source SHA == worktree SHA → `noop`
47
+ * - source SHA is an ancestor of worktree → `skip_rewind` (source is behind; keep fresh tip)
48
+ * - worktree SHA is an ancestor of source → `advance` (source strictly newer; safe fast-forward)
49
+ * - neither is an ancestor (diverged) → `skip_diverged` (keep fresh tip; coordinator reconciles)
50
+ *
51
+ * Both SHAs must already be resolvable in `ossCtx` (the caller fetches the
52
+ * source SHA first). A non-1 git exit (unresolvable SHA / real failure) is
53
+ * rethrown so the caller can fall back to keeping the fresh worktree HEAD.
54
+ */
55
+ export type OssCloneSyncAction = 'noop' | 'advance' | 'skip_rewind' | 'skip_diverged';
56
+
57
+ export async function decideOssCloneSync(
58
+ ossCtx: GitRepoIdentity,
59
+ worktreeOssSha: string,
60
+ sourceSha: string,
61
+ rg: (ctx: GitRepoIdentity, argv: string[], opts?: { timeoutMs?: number }) => Promise<unknown>,
62
+ ): Promise<OssCloneSyncAction> {
63
+ if (!worktreeOssSha || !sourceSha || worktreeOssSha === sourceSha) return 'noop';
64
+
65
+ const isAncestor = async (ancestor: string, descendant: string): Promise<boolean> => {
66
+ try {
67
+ await rg(ossCtx, ['merge-base', '--is-ancestor', ancestor, descendant], { timeoutMs: 10000 });
68
+ return true;
69
+ } catch (err: any) {
70
+ // `merge-base --is-ancestor` exits 1 for a clean "not an ancestor".
71
+ // Any other exit (128 = unresolvable commit, etc.) is a real failure.
72
+ if (err?.exitCode === 1 || err?.code === 1) return false;
73
+ throw err;
74
+ }
75
+ };
76
+
77
+ // Source is an ancestor of the fresh worktree tip → checking it out rewinds.
78
+ if (await isAncestor(sourceSha, worktreeOssSha)) return 'skip_rewind';
79
+ // Worktree tip is an ancestor of source → source is strictly newer → safe FF.
80
+ if (await isAncestor(worktreeOssSha, sourceSha)) return 'advance';
81
+ // Neither is an ancestor → diverged → keep the fresh worktree HEAD.
82
+ return 'skip_diverged';
83
+ }
84
+
85
+ /**
86
+ * Sync every registered submodule of a freshly-cloned worktree to its clone source
87
+ * node's working submodule HEAD, applying decideOssCloneSync's origin-tip-priority
88
+ * rewind guard per submodule.
89
+ *
90
+ * Generic over the submodule set: the paths come from `.gitmodules` via
91
+ * getRegisteredSubmodulePaths, so this operates identically over EVERY registered
92
+ * submodule (oss, adhdev-providers, …) instead of a hardcoded 'oss' literal. In a
93
+ * repo whose only synced submodule is `oss` the emitted git commands are byte-identical
94
+ * to the original oss-only path.
95
+ *
96
+ * Best-effort by design: a failure on one submodule is logged and skipped; it never
97
+ * blocks the other submodules or the clone. A submodule is only ever advanced to a
98
+ * STRICTLY-NEWER source SHA — the fresh (origin/main-derived) worktree tip is never
99
+ * rewound onto a behind/diverged source.
100
+ */
101
+ export async function syncClonedWorktreeSubmodules(
102
+ worktreePath: string,
103
+ sourceWorkspace: string,
104
+ rg: (ctx: GitRepoIdentity, argv: string[], opts?: { timeoutMs?: number }) => Promise<unknown>,
105
+ ): Promise<void> {
106
+ const submodulePaths = getRegisteredSubmodulePaths(worktreePath);
107
+ if (submodulePaths.size === 0) return;
108
+
109
+ const sourceCtx: GitRepoIdentity = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
110
+ const worktreeCtx: GitRepoIdentity = { workspace: worktreePath, repoRoot: worktreePath, isGitRepo: true };
111
+ const readStdout = (out: unknown): string =>
112
+ (typeof out === 'string' ? out : (out as any)?.stdout ?? '').trim();
113
+
114
+ for (const submodulePath of submodulePaths) {
115
+ try {
116
+ // Read the source node's working submodule SHA.
117
+ const sourceStatusOut = await rg(sourceCtx, ['submodule', 'status', submodulePath], { timeoutMs: 10000 });
118
+ const sourceSha = readStdout(sourceStatusOut).match(/^[+\- ]?([0-9a-f]{40})/)?.[1];
119
+ if (!sourceSha) continue;
120
+
121
+ // Read the worktree's freshly-checked-out submodule HEAD.
122
+ const subCtx: GitRepoIdentity = {
123
+ workspace: `${worktreePath}/${submodulePath}`,
124
+ repoRoot: `${worktreePath}/${submodulePath}`,
125
+ isGitRepo: true,
126
+ };
127
+ const worktreeSubSha = readStdout(await rg(subCtx, ['rev-parse', 'HEAD'], { timeoutMs: 10000 }));
128
+ if (!worktreeSubSha || worktreeSubSha === sourceSha) continue;
129
+
130
+ // Bring the source node's submodule HEAD into the worktree submodule object
131
+ // DB so both SHAs are resolvable for the ancestry (rewind) guard below.
132
+ await rg(subCtx, ['fetch', `${sourceWorkspace}/${submodulePath}`, 'HEAD'], { timeoutMs: 60000 });
133
+
134
+ // Rewind guard: the worktree submodule HEAD was just checked out from the
135
+ // FRESH (origin/main-derived) root base. Only advance to the source SHA when
136
+ // it is strictly newer — never rewind to a stale source.
137
+ let action: OssCloneSyncAction;
138
+ try {
139
+ action = await decideOssCloneSync(subCtx, worktreeSubSha, sourceSha, rg);
140
+ } catch (decideErr: any) {
141
+ action = 'skip_diverged';
142
+ console.warn(`[mesh] ${submodulePath} submodule sync guard could not resolve ancestry (kept fresh worktree HEAD): ${decideErr?.message ?? decideErr}`);
143
+ }
144
+
145
+ if (action === 'advance') {
146
+ await rg(subCtx, ['checkout', sourceSha], { timeoutMs: 10000 });
147
+ await rg(worktreeCtx, ['add', submodulePath], { timeoutMs: 10000 });
148
+ await rg(worktreeCtx, ['commit', '-m', `chore: sync ${submodulePath} to source node HEAD on clone`], { timeoutMs: 10000 });
149
+ console.log(`[mesh] Advanced ${submodulePath} submodule to newer source HEAD ${sourceSha.slice(0, 8)} in worktree`);
150
+ } else if (action === 'skip_rewind') {
151
+ console.warn(`[mesh] Skipped ${submodulePath} submodule rewind on clone: source node ${submodulePath} ${sourceSha.slice(0, 8)} is an ancestor of the fresh worktree ${submodulePath} ${worktreeSubSha.slice(0, 8)} — kept fresher worktree HEAD`);
152
+ } else if (action === 'skip_diverged') {
153
+ console.warn(`[mesh] Skipped ${submodulePath} submodule sync on clone: source node ${submodulePath} ${sourceSha.slice(0, 8)} diverged from the fresh worktree ${submodulePath} ${worktreeSubSha.slice(0, 8)} — kept worktree HEAD (coordinator reconciles)`);
154
+ }
155
+ } catch (subErr: any) {
156
+ // Per-submodule best-effort: never let one submodule's failure block the rest.
157
+ console.warn(`[mesh] ${submodulePath} submodule sync to source HEAD failed (best-effort):`, subErr?.message ?? subErr);
158
+ }
159
+ }
160
+ }
161
+
162
+ export const meshCrudHandlers: Record<string, MedFamilyHandler> = {
163
+ list_meshes: async (ctx: MedFamilyContext, _args: any) => {
164
+ try {
165
+ const { listMeshes } = await import('../../config/mesh-config.js');
166
+ const meshes = listMeshes();
167
+ // HOST-MISSEED-CLOUD-SURFACE: surface the SAME resolved host pin that
168
+ // mesh_status synthesizes (resolveMeshHostStatus) onto each list entry's
169
+ // meshHost. The cloud dashboard's host banner reads hostPinned from the
170
+ // list_meshes payload (selectedMesh.meshHost), NOT from mesh_status — so
171
+ // without this a host mesh whose hostDaemonId was never persisted shows
172
+ // 'no host yet' even though the daemon resolves this daemon as host.
173
+ // resolveMeshHostStatus only synthesizes localDaemonId for role:'host'
174
+ // (member meshes keep hostDaemonId undefined), so member meshes are not
175
+ // polluted. localDaemonId mirrors mesh-status.ts; when absent, the resolver
176
+ // falls back to the raw persisted meshHost.
177
+ const localDaemonId = ctx?.deps?.statusInstanceId;
178
+ const meshesWithHost = Array.isArray(meshes)
179
+ ? meshes.map((mesh: any) => {
180
+ try {
181
+ return { ...mesh, meshHost: resolveMeshHostStatus(mesh, { localDaemonId }) };
182
+ } catch {
183
+ // Resolver failure on a single mesh must not drop the whole list.
184
+ return mesh;
185
+ }
186
+ })
187
+ : meshes;
188
+ return { success: true, meshes: meshesWithHost };
189
+ } catch (e: any) {
190
+ return { success: false, error: e.message };
191
+ }
192
+ },
193
+
194
+ get_mesh: async (ctx: MedFamilyContext, args: any) => {
195
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
196
+ if (!meshId) return { success: false, error: 'meshId required' };
197
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
198
+ if (!meshRecord?.mesh) return { success: false, error: 'Mesh not found' };
199
+
200
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
201
+ // Only an explicit refresh fans out a blocking peer probe.
202
+ // Default loads are satisfied from held standing-state git truth.
203
+ const probeRemotePeers = args?.refresh === true || args?.forceRefresh === true;
204
+ const directTruth = await hydrateInlineMeshDirectTruth({
205
+ mesh: meshRecord.mesh,
206
+ meshSource: meshRecord.source,
207
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
208
+ getMeshPeerConnectionStatus: ctx.deps.getMeshPeerConnectionStatus,
209
+ statusInstanceId: ctx.deps.statusInstanceId,
210
+ localMachineId: loadConfig().machineId || '',
211
+ probeRemotePeers,
212
+ probeCache: ctx.meshGitProbeCache,
213
+ });
214
+ const directTruthSatisfied = meshRecord.source !== 'inline_bootstrap' || directTruth.directEvidenceCount > 0;
215
+ const sourceOfTruth = {
216
+ membership: meshRecord.source === 'inline_cache'
217
+ ? 'coordinator_inline_mesh_cache'
218
+ : meshRecord.source === 'local_config'
219
+ ? 'local_mesh_config'
220
+ : 'inline_bootstrap_snapshot',
221
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
222
+ directPeerTruth: {
223
+ required: requireDirectPeerTruth,
224
+ satisfied: directTruthSatisfied,
225
+ directEvidenceCount: directTruth.directEvidenceCount,
226
+ localConfirmedCount: directTruth.localConfirmedCount,
227
+ peerAttemptedCount: directTruth.peerAttemptedCount,
228
+ peerConfirmedCount: directTruth.peerConfirmedCount,
229
+ unavailableNodeIds: directTruth.unavailableNodeIds,
230
+ },
231
+ };
232
+ if (requireDirectPeerTruth && !directTruthSatisfied) {
233
+ return {
234
+ success: false,
235
+ code: 'mesh_direct_peer_truth_unavailable',
236
+ error: 'Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.',
237
+ sourceOfTruth,
238
+ };
239
+ }
240
+ return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
241
+ },
242
+
243
+ create_mesh: async (_ctx: MedFamilyContext, args: any) => {
244
+ const name = typeof args?.name === 'string' ? args.name.trim() : '';
245
+ const repoIdentity = typeof args?.repoIdentity === 'string' ? args.repoIdentity.trim() : '';
246
+ const repoRemoteUrl = typeof args?.repoRemoteUrl === 'string' ? args.repoRemoteUrl.trim() : undefined;
247
+ const defaultBranch = typeof args?.defaultBranch === 'string' ? args.defaultBranch.trim() : undefined;
248
+ if (!name) return { success: false, error: 'name required' };
249
+ try {
250
+ const { createMesh } = await import('../../config/mesh-config.js');
251
+ const meshHost = args?.meshHost && typeof args.meshHost === 'object' && !Array.isArray(args.meshHost)
252
+ ? args.meshHost
253
+ : undefined;
254
+ const mesh = createMesh({ name, repoIdentity, repoRemoteUrl, defaultBranch, policy: args?.policy, meshHost });
255
+ return { success: true, mesh };
256
+ } catch (e: any) {
257
+ return { success: false, error: e.message };
258
+ }
259
+ },
260
+
261
+ update_mesh: async (ctx: MedFamilyContext, args: any) => {
262
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
263
+ if (!meshId) return { success: false, error: 'meshId required' };
264
+ try {
265
+ const { updateMesh } = await import('../../config/mesh-config.js');
266
+ const patch: Record<string, unknown> = {};
267
+ if (typeof args?.name === 'string') patch.name = args.name;
268
+ if (typeof args?.defaultBranch === 'string') patch.defaultBranch = args.defaultBranch;
269
+ if (args?.policy && typeof args.policy === 'object' && !Array.isArray(args.policy)) patch.policy = args.policy;
270
+ if (args?.coordinator && typeof args.coordinator === 'object' && !Array.isArray(args.coordinator)) patch.coordinator = args.coordinator;
271
+ if (args?.meshHost && typeof args.meshHost === 'object' && !Array.isArray(args.meshHost)) patch.meshHost = args.meshHost;
272
+ if (!Object.keys(patch).length) return { success: false, error: 'No updates provided' };
273
+ const mesh = updateMesh(meshId, patch as any);
274
+ if (!mesh) return { success: false, error: 'Mesh not found' };
275
+ ctx.inlineMeshCache.set(meshId, mesh);
276
+ ctx.invalidateAggregateMeshStatus(meshId);
277
+ return { success: true, mesh };
278
+ } catch (e: any) {
279
+ return { success: false, error: e.message };
280
+ }
281
+ },
282
+
283
+ // OPSRULES — emit a `.adhdev/mesh.json` DRAFT from the machine-local mesh
284
+ // entry. This is an export scaffold for the operator to review and commit to
285
+ // the repo, NOT an automatic data migration: nothing is written to disk and
286
+ // meshes.json is untouched. The returned `scaffold` (object) + `scaffoldJson`
287
+ // (2-space text) capture the coordinator prompt override/append (policy is
288
+ // machine-local and is intentionally NOT exported into mesh.json).
289
+ export_mesh_json_config: async (_ctx: MedFamilyContext, args: any) => {
290
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
291
+ if (!meshId) return { success: false, error: 'meshId required' };
292
+ try {
293
+ const { getMesh } = await import('../../config/mesh-config.js');
294
+ const mesh = getMesh(meshId);
295
+ if (!mesh) return { success: false, error: 'Mesh not found' };
296
+ const { buildMeshJsonConfigScaffold, serializeMeshJsonConfigScaffold, MESH_JSON_CONFIG_LOCATIONS } =
297
+ await import('../../config/mesh-json-config.js');
298
+ const scaffold = buildMeshJsonConfigScaffold(mesh);
299
+ const scaffoldJson = serializeMeshJsonConfigScaffold(scaffold);
300
+ return {
301
+ success: true,
302
+ meshId,
303
+ suggestedPath: MESH_JSON_CONFIG_LOCATIONS[0],
304
+ scaffold,
305
+ scaffoldJson,
306
+ note: 'Draft only — review and commit to the repo at the suggested path. Nothing was written; meshes.json is unchanged (local-wins).',
307
+ };
308
+ } catch (e: any) {
309
+ return { success: false, error: e.message };
310
+ }
311
+ },
312
+
313
+ // Gated WRITE path for `.adhdev/mesh.json` — the sibling of export_mesh_json_config
314
+ // (which only DRAFTS). Same write/overwrite/dry-run contract as mesh_init's config
315
+ // writer: defaults to dry-run (no write), never clobbers an existing repo mesh.json
316
+ // unless overwrite=true, and validates the scaffold before persisting. The scaffold
317
+ // is built from the machine-local mesh entry (coordinator prompt override/append);
318
+ // policy/operating-notes are intentionally NOT exported (see buildMeshJsonConfigScaffold).
319
+ write_mesh_json_config: async (_ctx: MedFamilyContext, args: any) => {
320
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
321
+ if (!meshId) return { success: false, error: 'meshId required' };
322
+ const workspace = typeof args?.workspace === 'string' && args.workspace.trim() ? args.workspace.trim() : process.cwd();
323
+ const write = args?.write === true;
324
+ const overwrite = args?.overwrite === true;
325
+ try {
326
+ const { getMesh } = await import('../../config/mesh-config.js');
327
+ const mesh = getMesh(meshId);
328
+ if (!mesh) return { success: false, error: 'Mesh not found' };
329
+ const {
330
+ buildMeshJsonConfigScaffold,
331
+ serializeMeshJsonConfigScaffold,
332
+ loadRepoMeshJsonConfig,
333
+ normalizeRepoMeshDeclarativeConfig,
334
+ MESH_JSON_CONFIG_LOCATIONS,
335
+ } = await import('../../config/mesh-json-config.js');
336
+ const { mkdirSync, writeFileSync } = await import('fs');
337
+ const { dirname, join } = await import('path');
338
+
339
+ const scaffold = buildMeshJsonConfigScaffold(mesh);
340
+ const scaffoldJson = serializeMeshJsonConfigScaffold(scaffold);
341
+ const relativePath = MESH_JSON_CONFIG_LOCATIONS[0];
342
+ const absolutePath = join(workspace, relativePath);
343
+
344
+ // Validate before we ever touch disk — never write an unusable mesh.json.
345
+ const validation = normalizeRepoMeshDeclarativeConfig(scaffold);
346
+ if (!validation.valid) {
347
+ return { success: false, meshId, error: `invalid mesh.json scaffold: ${validation.errors.join('; ')}` };
348
+ }
349
+
350
+ // existing-wins: a repo mesh.json already present is kept unless overwrite=true.
351
+ const existing = loadRepoMeshJsonConfig(workspace);
352
+ const existingPresent = existing.sourceType === 'repo_file' || existing.sourceType === 'invalid';
353
+ if (existingPresent && !overwrite) {
354
+ return {
355
+ success: true,
356
+ meshId,
357
+ written: false,
358
+ dryRun: !write,
359
+ skippedReason: 'already_exists',
360
+ path: absolutePath,
361
+ relativePath,
362
+ existing: existing.config,
363
+ existingSourceType: existing.sourceType,
364
+ scaffold,
365
+ scaffoldJson,
366
+ note: 'A repo mesh.json already exists — kept as-is. Re-run with overwrite=true to replace it (this silently drops operator hand-edits, so present a current-vs-suggested diff first).',
367
+ };
368
+ }
369
+
370
+ if (!write) {
371
+ return {
372
+ success: true,
373
+ meshId,
374
+ written: false,
375
+ dryRun: true,
376
+ path: absolutePath,
377
+ relativePath,
378
+ scaffold,
379
+ scaffoldJson,
380
+ note: 'Dry-run: nothing written. Re-run with write=true to persist to the repo (commit target). meshes.json is untouched.',
381
+ };
382
+ }
383
+
384
+ mkdirSync(dirname(absolutePath), { recursive: true });
385
+ writeFileSync(absolutePath, `${scaffoldJson}\n`, 'utf-8');
386
+ return {
387
+ success: true,
388
+ meshId,
389
+ written: true,
390
+ dryRun: false,
391
+ path: absolutePath,
392
+ relativePath,
393
+ scaffold,
394
+ scaffoldJson,
395
+ note: 'Wrote .adhdev/mesh.json (repo commit target). Commit it to the repo; meshes.json (machine-local) is unchanged.',
396
+ };
397
+ } catch (e: any) {
398
+ return { success: false, error: e.message };
399
+ }
400
+ },
401
+
402
+ delete_mesh: async (_ctx: MedFamilyContext, args: any) => {
403
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
404
+ if (!meshId) return { success: false, error: 'meshId required' };
405
+ try {
406
+ const { deleteMesh } = await import('../../config/mesh-config.js');
407
+ const deleted = deleteMesh(meshId);
408
+ return { success: true, deleted };
409
+ } catch (e: any) {
410
+ return { success: false, error: e.message };
411
+ }
412
+ },
413
+
414
+ // ─── MAGI kind → panel bindings (MAGI-KIND-PANEL, machine-local config) ───
415
+ // Per-task_kind slot lists in ~/.adhdev/meshes.json `magiKindPanels` — the SOLE
416
+ // MAGI panel-resolution surface (the former named-panel magi_panel_* handlers were
417
+ // removed). Owner-only gating: intentionally NOT listed in
418
+ // canPeerUsePrivilegedShareCommand (daemon-cloud data-channel-router), so a peer
419
+ // holding ANY share permission hits its `default → false` branch — identical
420
+ // owner-only gating to create_mesh / update_mesh / list_meshes. A trusted peer (no
421
+ // permission = the owner) passes the top `!permission → true` guard. set/remove are
422
+ // WRITE commands; list is read-only. normalizeMagiSlots (inside setMagiKindPanel)
423
+ // surfaces invalid_magi_kind_panel: … messages verbatim for the editor.
424
+ magi_kind_panel_list: async (_ctx: MedFamilyContext, _args: any) => {
425
+ try {
426
+ const { listMagiKindPanels } = await import('../../config/mesh-config.js');
427
+ return { success: true, kindPanels: listMagiKindPanels() };
428
+ } catch (e: any) {
429
+ return { success: false, error: e.message };
430
+ }
431
+ },
432
+
433
+ magi_kind_panel_set: async (_ctx: MedFamilyContext, args: any) => {
434
+ const kind = typeof args?.kind === 'string' ? args.kind.trim() : '';
435
+ if (!kind) return { success: false, error: 'invalid_magi_kind_panel: task_kind is required' };
436
+ try {
437
+ const { setMagiKindPanel } = await import('../../config/mesh-config.js');
438
+ // normalizeMagiTaskKindKey + normalizeMagiSlots (inside setMagiKindPanel)
439
+ // validate the kind and each slot (provider required; model/nodeId optional;
440
+ // replica counts clamped). Structured errors flow back as `error`.
441
+ const slots = setMagiKindPanel(kind, args?.slots);
442
+ return { success: true, kind, slots };
443
+ } catch (e: any) {
444
+ return { success: false, error: e.message };
445
+ }
446
+ },
447
+
448
+ magi_kind_panel_remove: async (_ctx: MedFamilyContext, args: any) => {
449
+ const kind = typeof args?.kind === 'string' ? args.kind.trim() : '';
450
+ if (!kind) return { success: false, error: 'invalid_magi_kind_panel: task_kind is required' };
451
+ try {
452
+ const { removeMagiKindPanel } = await import('../../config/mesh-config.js');
453
+ const removed = removeMagiKindPanel(kind);
454
+ return { success: true, removed };
455
+ } catch (e: any) {
456
+ return { success: false, error: e.message };
457
+ }
458
+ },
459
+
460
+ // ─── Brain routing: per-difficulty brain presets (machine-local) ───
461
+ // getDifficultyBrains returns the seeded defaults when nothing is configured,
462
+ // so the editor always shows a usable mapping. set replaces the whole map.
463
+ difficulty_brains_get: async (_ctx: MedFamilyContext, _args: any) => {
464
+ try {
465
+ const { getDifficultyBrains } = await import('../../config/mesh-config.js');
466
+ return { success: true, difficultyBrains: getDifficultyBrains() };
467
+ } catch (e: any) {
468
+ return { success: false, error: e.message };
469
+ }
470
+ },
471
+
472
+ difficulty_brains_set: async (_ctx: MedFamilyContext, args: any) => {
473
+ try {
474
+ const { setDifficultyBrains } = await import('../../config/mesh-config.js');
475
+ // normalizeDifficultyBrainMap (inside setDifficultyBrains) drops unknown
476
+ // keys and empty slots. An empty result clears the override → defaults.
477
+ const difficultyBrains = setDifficultyBrains(args?.difficultyBrains);
478
+ return { success: true, difficultyBrains };
479
+ } catch (e: any) {
480
+ return { success: false, error: e.message };
481
+ }
482
+ },
483
+
484
+ add_mesh_node: async (ctx: MedFamilyContext, args: any) => {
485
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
486
+ const workspace = typeof args?.workspace === 'string' ? args.workspace.trim() : '';
487
+ if (!meshId) return { success: false, error: 'meshId required' };
488
+ if (!workspace) return { success: false, error: 'workspace required' };
489
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node addition');
490
+ if (ownerFailure) return ownerFailure;
491
+ try {
492
+ const { addNode } = await import('../../config/mesh-config.js');
493
+ const providerPriority = Array.isArray(args?.providerPriority)
494
+ ? args.providerPriority.map((type: any) => typeof type === 'string' ? type.trim() : '').filter(Boolean)
495
+ : [];
496
+ const readOnly = args?.readOnly === true;
497
+ const providerRoles = normalizeProviderRoles(args?.providerRoles);
498
+ const policy = {
499
+ ...(readOnly ? { readOnly: true } : {}),
500
+ ...(providerPriority.length ? { providerPriority } : {}),
501
+ ...(providerRoles.length ? { providerRoles } : {}),
502
+ };
503
+ const role = normalizeMeshDaemonRole(args?.role);
504
+ const daemonId = typeof args?.daemonId === 'string' && args.daemonId.trim() ? args.daemonId.trim() : undefined;
505
+ const machineId = typeof args?.machineId === 'string' && args.machineId.trim() ? args.machineId.trim() : undefined;
506
+ const repoRoot = typeof args?.repoRoot === 'string' && args.repoRoot.trim() ? args.repoRoot.trim() : undefined;
507
+ const capabilities = Array.isArray(args?.capabilities)
508
+ ? args.capabilities.map((t: any) => typeof t === 'string' ? t.trim() : '').filter(Boolean)
509
+ : undefined;
510
+ const node = addNode(meshId, {
511
+ workspace,
512
+ ...(repoRoot ? { repoRoot } : {}),
513
+ ...(daemonId ? { daemonId } : {}),
514
+ ...(machineId ? { machineId } : {}),
515
+ ...(policy ? { policy } : {}),
516
+ ...(role ? { role } : {}),
517
+ ...(capabilities && capabilities.length ? { capabilities } : {}),
518
+ });
519
+ if (!node) return { success: false, error: 'Mesh not found' };
520
+ // mesh_status hands back a coordinator-memory aggregate
521
+ // snapshot keyed on (meshId, queueRevision). Adding a
522
+ // node touches neither, so without an explicit cache
523
+ // bust the dashboard graph keeps rendering the pre-add
524
+ // node list (empty for a fresh mesh) even after the
525
+ // user clicks Refresh.
526
+ ctx.invalidateAggregateMeshStatus(meshId);
527
+ return { success: true, node };
528
+ } catch (e: any) {
529
+ return { success: false, error: e.message };
530
+ }
531
+ },
532
+
533
+ update_mesh_node: async (ctx: MedFamilyContext, args: any) => {
534
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
535
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
536
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
537
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node update');
538
+ if (ownerFailure) return ownerFailure;
539
+ try {
540
+ const { updateNode } = await import('../../config/mesh-config.js');
541
+ const policy = args?.policy && typeof args.policy === 'object' && !Array.isArray(args.policy)
542
+ ? { ...(args.policy as Record<string, unknown>) }
543
+ : {};
544
+ if (Array.isArray(args?.providerPriority)) {
545
+ const providerPriority = args.providerPriority
546
+ .map((type: any) => typeof type === 'string' ? type.trim() : '')
547
+ .filter(Boolean);
548
+ delete (policy as any).provider_priority;
549
+ if (providerPriority.length) {
550
+ (policy as any).providerPriority = providerPriority;
551
+ } else {
552
+ delete (policy as any).providerPriority;
553
+ }
554
+ }
555
+ // providerRoles: per-(node, provider) role label + maxParallel cap.
556
+ // Passing an explicit (possibly empty) array clears/replaces the
557
+ // declarations; omitting the arg leaves any value already on policy
558
+ // untouched (a full policy object passed by the caller still carries it).
559
+ if (Array.isArray(args?.providerRoles)) {
560
+ const providerRoles = normalizeProviderRoles(args.providerRoles);
561
+ if (providerRoles.length) {
562
+ (policy as any).providerRoles = providerRoles;
563
+ } else {
564
+ delete (policy as any).providerRoles;
565
+ }
566
+ }
567
+ const patch: Record<string, unknown> = { policy: policy as any };
568
+ if (typeof args?.systemPrompt === 'string') {
569
+ const trimmed = (args.systemPrompt as string).trim();
570
+ patch.systemPrompt = trimmed || undefined;
571
+ } else if (args?.systemPrompt === null) {
572
+ patch.systemPrompt = undefined;
573
+ }
574
+ // Operator custom capability tags. An explicit (possibly empty) array
575
+ // replaces them; omitting the arg leaves existing tags untouched.
576
+ if (Array.isArray(args?.capabilities)) {
577
+ patch.capabilities = args.capabilities
578
+ .map((t: any) => typeof t === 'string' ? t.trim() : '')
579
+ .filter(Boolean);
580
+ }
581
+ const node = updateNode(meshId, nodeId, patch as any);
582
+ if (!node) return { success: false, error: 'Mesh node not found' };
583
+ // Provider priority / systemPrompt changes don't touch
584
+ // the queue revision, so without a manual bust the
585
+ // cached aggregate keeps surfacing pre-update values
586
+ // (priority chip, coordinator prompt preview, etc.).
587
+ ctx.invalidateAggregateMeshStatus(meshId);
588
+ return { success: true, node };
589
+ } catch (e: any) {
590
+ return { success: false, error: e.message };
591
+ }
592
+ },
593
+
594
+ cleanup_mesh_sessions: async (ctx: MedFamilyContext, args: any) => {
595
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
596
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
597
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
598
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node removal');
599
+ if (ownerFailure) return ownerFailure;
600
+ try {
601
+ // preferInline so inline-cache-only clone nodes resolve (matches owner check above).
602
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
603
+ const mesh = meshRecord?.mesh;
604
+ if (!mesh) return { success: false, error: 'Mesh not found' };
605
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
606
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
607
+ const mode = ctx.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
608
+ const sessionIds = Array.isArray(args?.sessionIds)
609
+ ? args.sessionIds.map((id: any) => typeof id === 'string' ? id.trim() : '').filter(Boolean)
610
+ : undefined;
611
+ // MAGI post-review auto-cleanup routes through this same command with
612
+ // source:'magi_session_cleanup' and a per-session autoLaunchedForQueueTaskId
613
+ // map, which gates cleanup to sessions THIS fan-out actually auto-launched.
614
+ const source = args?.source === 'magi_session_cleanup' ? 'magi_session_cleanup' : 'mesh_cleanup_sessions';
615
+ const requireAutoLaunchedForTaskIds = (args?.requireAutoLaunchedForTaskIds
616
+ && typeof args.requireAutoLaunchedForTaskIds === 'object'
617
+ && !Array.isArray(args.requireAutoLaunchedForTaskIds))
618
+ ? args.requireAutoLaunchedForTaskIds as Record<string, string>
619
+ : undefined;
620
+ // Opt-in orphan reclaim (SESSION-ACCUMULATION-LEAK). The live-node id set
621
+ // is the CURRENT mesh membership; a matched live session bound to a node
622
+ // still in this set is an active sibling and is never reclaimed. Only when
623
+ // the caller passes reclaimOrphans:true does the router loosen the
624
+ // shared-daemon guard for workspace-only / dead-node-bound live sessions.
625
+ const reclaimOrphans = args?.reclaimOrphans === true;
626
+ const liveMeshNodeIds = Array.isArray(mesh?.nodes)
627
+ ? mesh.nodes.map((n: any) => normalizeMeshNodeId(n)).filter(Boolean) as string[]
628
+ : [];
629
+ const result = await ctx.cleanupMeshSessions({
630
+ meshId,
631
+ nodeId,
632
+ node,
633
+ mode,
634
+ sessionIds,
635
+ dryRun: args?.dryRun === true,
636
+ source,
637
+ requireAutoLaunchedForTaskIds,
638
+ reclaimOrphans,
639
+ liveMeshNodeIds,
640
+ });
641
+ return result;
642
+ } catch (e: any) {
643
+ return { success: false, error: e.message };
644
+ }
645
+ },
646
+
647
+ remove_mesh_node: async (ctx: MedFamilyContext, args: any) => {
648
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
649
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
650
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
651
+ try {
652
+ // preferInline so removal can resolve inline-cache-only clone worktree nodes.
653
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
654
+ const mesh = meshRecord?.mesh;
655
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
656
+
657
+ // Guard: refuse to remove the coordinator's OWN local base node
658
+ // (same machine, NOT a worktree). Removing it breaks live mesh
659
+ // membership — the coordinator can no longer be reached and has
660
+ // to be restarted. Worktree clones are always safe to remove;
661
+ // only the non-worktree node bound to this daemon is protected.
662
+ // An explicit force:true overrides for intentional mesh teardown.
663
+ if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
664
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : '';
665
+ const nodeMachineId = readMeshNodeMachineId(node as Record<string, unknown>) || '';
666
+ const selfDaemonId = ctx.deps.statusInstanceId || '';
667
+ const selfMachineId = (() => { try { return loadConfig().machineId || ''; } catch { return ''; } })();
668
+ // Identity match is form-safe: a daemon answers to the same machine
669
+ // under interchangeable id forms (bare `mach_X`, cloud `daemon_mach_X`,
670
+ // standalone `standalone_mach_X`). statusInstanceId/loadConfig().machineId
671
+ // and the node's stored daemonId/machineId frequently hold DIFFERENT forms
672
+ // of the same machine, so a raw `===` would miss the self-match and let the
673
+ // coordinator delete its own live base node (the very accident this guard
674
+ // exists to prevent). daemonIdsEquivalent collapses every form to its
675
+ // machine core before comparing, so a same-machine match is caught
676
+ // regardless of which form each side carries. This only widens matches
677
+ // (every raw-`===` hit still matches) — fail-open → fail-closed.
678
+ const isCoordinatorBaseNode =
679
+ (!!selfDaemonId && (daemonIdsEquivalent(nodeDaemonId, selfDaemonId) || daemonIdsEquivalent(nodeMachineId, selfDaemonId)))
680
+ || (!!selfMachineId && (daemonIdsEquivalent(nodeDaemonId, selfMachineId) || daemonIdsEquivalent(nodeMachineId, selfMachineId)));
681
+ if (isCoordinatorBaseNode) {
682
+ return {
683
+ success: false,
684
+ removed: false,
685
+ code: 'mesh_remove_coordinator_base_node_protected',
686
+ error: `Refusing to remove the coordinator's own base node '${typeof node.workspace === 'string' ? node.workspace : nodeId}'. `
687
+ + `It is the local non-worktree node bound to this coordinator daemon; removing it breaks live mesh membership and forces a restart.`,
688
+ recoveryHint: 'Remove worktree clone nodes instead, or pass force:true only if you are intentionally tearing down this mesh and accept that the coordinator must be re-registered/restarted.',
689
+ };
690
+ }
691
+ }
692
+
693
+ // Default worktree session cleanup ON: when the caller OMITS a mode and the
694
+ // node is a local worktree, default to 'stop_and_delete' instead of the mesh
695
+ // policy ('preserve' by default). A worktree's chat session has no reason to
696
+ // outlive the worktree's node + directory + branch, and leaving it on
697
+ // 'preserve' is what orphaned chats after a worktree remove. An explicit mode
698
+ // (including an explicit 'preserve') is always honored — only the OMITTED case
699
+ // changes, and only for worktrees. Base nodes keep arg ?? policy ?? preserve.
700
+ const explicitCleanupMode = args?.sessionCleanupMode ?? args?.session_cleanup_mode;
701
+ const sessionCleanupMode = ctx.normalizeMeshSessionCleanupMode(
702
+ explicitCleanupMode
703
+ ?? (node?.isLocalWorktree === true ? 'stop_and_delete' : undefined)
704
+ ?? mesh?.policy?.sessionCleanupOnNodeRemove,
705
+ );
706
+ // Explicit sessionIds (e.g. supplied by refine auto-cleanup) bypass the
707
+ // workspace-only-match guard so a delegate session that lacks a
708
+ // meta.meshNodeId binding can still be stopped/deleted.
709
+ const explicitSessionIds = Array.isArray(args?.sessionIds)
710
+ ? (args.sessionIds as unknown[]).filter((v): v is string => typeof v === 'string' && v.trim().length > 0).map(v => v.trim())
711
+ : undefined;
712
+ // Precheck-first: for a LOCAL worktree removal, validate removability
713
+ // with a purely non-destructive precheck BEFORE touching the session.
714
+ // The session cleanup below is destructive and irreversible
715
+ // (stop_and_delete), so a refusal that fires only AFTER it — as the old
716
+ // ordering did when removeWorktree rejected a dirty worktree — orphaned
717
+ // the delegated session. Running the precheck here means a refusal
718
+ // (dirty worktree, missing/mismatched metadata, etc.) returns with the
719
+ // session left fully intact. Remote-forwarded worktrees are prechecked
720
+ // on the owning daemon (it runs this same handler), so we only gate the
721
+ // local case here. Success/skip cases return ok:true and fall through to
722
+ // the unchanged normal flow.
723
+ if (node?.isLocalWorktree) {
724
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
725
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
726
+ && !args?._meshDirectDispatch;
727
+ if (!isRemoteWorktree) {
728
+ const precheck = await ctx.precheckLocalWorktreeRemovable({ mesh, node, nodeId, force: args?.force === true });
729
+ if (precheck.ok === false) {
730
+ return {
731
+ success: false,
732
+ removed: false,
733
+ code: precheck.code,
734
+ error: precheck.error,
735
+ recoveryHint: precheck.recoveryHint,
736
+ // No sessionCleanup key: the session was deliberately NOT
737
+ // touched. worktreeCleanup mirrors the destructive path's
738
+ // refusal shape so existing callers see the same code.
739
+ worktreeCleanup: { success: false, code: precheck.code, error: precheck.error, recoveryHint: precheck.recoveryHint },
740
+ };
741
+ }
742
+ }
743
+ }
744
+
745
+ let sessionCleanup: Record<string, unknown> | undefined;
746
+ if (node && sessionCleanupMode !== 'preserve') {
747
+ sessionCleanup = await ctx.cleanupMeshSessions({
748
+ meshId,
749
+ nodeId,
750
+ node,
751
+ mode: sessionCleanupMode,
752
+ ...(explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {}),
753
+ source: 'mesh_remove_node',
754
+ });
755
+ if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
756
+ }
757
+
758
+ let worktreeCleanup: Record<string, unknown> | undefined;
759
+ if (node?.isLocalWorktree) {
760
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
761
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
762
+ // clean up locally, do not forward. Equivalent → local.
763
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
764
+ && !args?._meshDirectDispatch;
765
+ if (isRemoteWorktree) {
766
+ // Worktree lives on a different machine — ask that daemon to clean it up.
767
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
768
+ const forwarded = await ctx.deps.dispatchMeshCommand!(nodeDaemonId!, 'remove_mesh_node', {
769
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
770
+ _meshDirectDispatch: true,
771
+ });
772
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
773
+ }
774
+ const cleanupResult = await ctx.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
775
+ // De-gating: membership removal is NOT gated on the worktree
776
+ // directory actually being deleted. cleanupLocalWorktreeNode now
777
+ // returns success:true (with a residue flag) whenever the path is
778
+ // proven managed and the only remaining problem is leftover
779
+ // directory bytes (e.g. Windows EINVAL). A success:false here means
780
+ // a genuinely-unsafe condition — missing metadata, a non-managed /
781
+ // unexpected path, a branch mismatch, a dirty worktree, or an
782
+ // unverified force fallback — and those still block removal.
783
+ if (cleanupResult.success === false) {
784
+ return {
785
+ success: false,
786
+ removed: false,
787
+ code: cleanupResult.code,
788
+ error: cleanupResult.error,
789
+ recoveryHint: cleanupResult.recoveryHint,
790
+ ...(sessionCleanup ? { sessionCleanup } : {}),
791
+ worktreeCleanup: cleanupResult,
792
+ };
793
+ }
794
+ worktreeCleanup = cleanupResult;
795
+ }
796
+
797
+ let removed = false;
798
+ if (meshRecord?.inline) {
799
+ removed = ctx.removeInlineMeshNode(meshId, mesh, nodeId);
800
+ // Inline meshes share the same aggregate snapshot cache as
801
+ // local-config meshes; without this bust the removed node
802
+ // keeps showing up in the dashboard graph until the cache
803
+ // ages out on its own.
804
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
805
+ // MESH-INLINE-NODE-RESURRECTION: removeInlineMeshNode only mutates
806
+ // the in-memory inlineMeshCache + tombstones — it does NOT touch
807
+ // the file-backed config (meshes.json). When the SAME node also
808
+ // lives in meshes.json (a worktree node that was persisted to the
809
+ // file config, then resolved through the inline cache on removal),
810
+ // the file record survives. On daemon restart the in-memory
811
+ // tombstone is lost, getMesh falls back to the file config, and
812
+ // mesh-status renders the dead node again. So a node present in
813
+ // BOTH the inline cache AND meshes.json must be spliced+saved from
814
+ // the file config here too. Pure-inline meshes (no matching file
815
+ // mesh/node) are untouched — getMesh returns undefined and we skip.
816
+ try {
817
+ const { getMesh, removeNode } = await import('../../config/mesh-config.js');
818
+ const fileMesh = getMesh(meshId);
819
+ const fileNode = fileMesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
820
+ if (fileNode?.id) {
821
+ const fileRemoved = removeNode(meshId, fileNode.id);
822
+ if (fileRemoved) {
823
+ removed = true;
824
+ ctx.invalidateAggregateMeshStatus(meshId);
825
+ }
826
+ }
827
+ } catch { /* file config absent / unreadable — inline-only mesh, nothing to durably delete */ }
828
+ // Node was already absent from the inline mesh (e.g. removed by a
829
+ // prior refine cleanup). Treat as removed so caller gets removed:true.
830
+ if (!removed && !node) removed = true;
831
+ } else {
832
+ const { removeNode } = await import('../../config/mesh-config.js');
833
+ removed = removeNode(meshId, nodeId);
834
+ // Node already absent from config (e.g. removed by a prior refine
835
+ // cleanup after a successful Refinery merge). Treat as removed so
836
+ // the response is accurate.
837
+ if (!removed && !node) removed = true;
838
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
839
+ }
840
+
841
+ // Record in task ledger
842
+ if (removed) {
843
+ try {
844
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
845
+ appendLedgerEntry(meshId, {
846
+ kind: 'node_removed',
847
+ nodeId,
848
+ payload: {
849
+ worktree: !!node?.isLocalWorktree,
850
+ sessionCleanupMode,
851
+ workspace: typeof node?.workspace === 'string' ? node.workspace : undefined,
852
+ daemonId: typeof node?.daemonId === 'string' ? node.daemonId : undefined,
853
+ worktreeBranch: typeof node?.worktreeBranch === 'string' ? node.worktreeBranch : undefined,
854
+ worktreeCleanupFallback: typeof worktreeCleanup?.fallback === 'string' ? worktreeCleanup.fallback : undefined,
855
+ forced: worktreeCleanup?.forced === true ? true : undefined,
856
+ forceFallbackReason: typeof worktreeCleanup?.reason === 'string' ? worktreeCleanup.reason : undefined,
857
+ branchRefDeleted: typeof worktreeCleanup?.branchRefDeleted === 'boolean' ? worktreeCleanup.branchRefDeleted : undefined,
858
+ branchRefReason: typeof worktreeCleanup?.branchRefReason === 'string' ? worktreeCleanup.branchRefReason : undefined,
859
+ },
860
+ });
861
+ } catch { /* ledger append is best-effort */ }
862
+ }
863
+
864
+ // Surface leftover-directory residue at the top level so callers
865
+ // see the node was dropped from the mesh even though the worktree
866
+ // directory could not be fully removed (best-effort, non-gating).
867
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === 'string'
868
+ ? worktreeCleanup.residueWarning
869
+ : undefined;
870
+
871
+ // Surface a preserved-branch warning at the top level so callers see
872
+ // that the branch ref was intentionally NOT deleted (unmerged work is
873
+ // never silently dropped). When the branch ref WAS deleted, the nested
874
+ // worktreeCleanup.branchRefDeleted flag already records it.
875
+ const branchRefWarning = typeof worktreeCleanup?.branchRefWarning === 'string'
876
+ ? worktreeCleanup.branchRefWarning
877
+ : undefined;
878
+
879
+ // Orphan guard: if the session cleanup still left any LIVE session skipped
880
+ // (e.g. a future skip reason, or a workspace-only session on a base node),
881
+ // surface it at the top level so the caller knows a manual mesh_cleanup_sessions
882
+ // is still required for those sessionIds. Without this, a skipped-live session
883
+ // silently outlives a removed node (the very NODE-REMOVE-SESSION-ORPHAN bug).
884
+ const skippedLiveSessionIds = Array.isArray(sessionCleanup?.skippedLiveSessionIds)
885
+ ? (sessionCleanup!.skippedLiveSessionIds as unknown[]).filter((v): v is string => typeof v === 'string')
886
+ : [];
887
+ const orphanedSessionsRemaining = skippedLiveSessionIds.length > 0;
888
+ const orphanNextAction = orphanedSessionsRemaining
889
+ ? `Live session(s) [${skippedLiveSessionIds.join(', ')}] were skipped and still survive this node removal. `
890
+ + `Run mesh_cleanup_sessions with mode:'stop_and_delete' and sessionIds:[${skippedLiveSessionIds.map(id => `'${id}'`).join(', ')}] to release them.`
891
+ : undefined;
892
+ return {
893
+ success: true,
894
+ removed,
895
+ ...(residueWarning ? { residueWarning } : {}),
896
+ ...(branchRefWarning ? { branchRefWarning } : {}),
897
+ ...(sessionCleanup ? { sessionCleanup } : {}),
898
+ ...(worktreeCleanup ? { worktreeCleanup } : {}),
899
+ ...(orphanedSessionsRemaining
900
+ ? { orphanedSessionsRemaining: true, nextAction: orphanNextAction }
901
+ : {}),
902
+ };
903
+ } catch (e: any) {
904
+ return { success: false, error: e.message };
905
+ }
906
+ },
907
+
908
+ clone_mesh_node: async (ctx: MedFamilyContext, args: any) => {
909
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
910
+ const sourceNodeId = typeof args?.sourceNodeId === 'string' ? args.sourceNodeId.trim() : '';
911
+ const branch = typeof args?.branch === 'string' ? args.branch.trim() : '';
912
+ const baseBranch = typeof args?.baseBranch === 'string' ? args.baseBranch.trim() : undefined;
913
+ if (!meshId) return { success: false, error: 'meshId required' };
914
+ if (!sourceNodeId) return { success: false, error: 'sourceNodeId required' };
915
+ if (!branch) return { success: false, error: 'branch required' };
916
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'worktree clone');
917
+ if (ownerFailure) return ownerFailure;
918
+
919
+ try {
920
+ // Resolve with preferInline so the clone writes the new node into the
921
+ // same representation that get_mesh reads back. The MCP coordinator
922
+ // passes inlineMesh on every mesh command, so when it owns an inline
923
+ // mesh the membership read path (get_mesh, preferInline: true) returns
924
+ // the inline cache. Without preferInline here, clone could resolve to a
925
+ // local-config mesh and write the node only to config — leaving the
926
+ // inline cache (and therefore get_mesh / refreshMeshFromDaemon) without
927
+ // the node, so the new worktree node is never visible in live mesh
928
+ // membership even though worktree_bootstrap_complete fires.
929
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
930
+ const mesh = meshRecord?.mesh;
931
+ if (!mesh) return { success: false, error: 'Mesh not found' };
932
+
933
+ const sourceNode = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, sourceNodeId));
934
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
935
+
936
+ // Forward to the source node's daemon if it's on a different machine.
937
+ // _meshDirectDispatch prevents infinite re-forwarding when the stored daemonId
938
+ // uses a legacy format that doesn't match the receiving daemon's statusInstanceId.
939
+ const sourceDaemonId = typeof sourceNode.daemonId === 'string' ? sourceNode.daemonId.trim() : undefined;
940
+ // daemonIdsEquivalent: an equivalent-form source daemonId is this machine —
941
+ // clone locally, do not forward. Equivalent → local.
942
+ if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
943
+ && !args?._meshDirectDispatch) {
944
+ const forwarded = await ctx.deps.dispatchMeshCommand(sourceDaemonId, 'clone_mesh_node', {
945
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
946
+ _meshDirectDispatch: true,
947
+ });
948
+ // FALSE-BLOCKER-CLONE-QUEUE: open the transient grace window for the freshly
949
+ // cloned node on THIS coordinator daemon. The clone ran (and wrote the inline-
950
+ // cache node) on the remote source daemon; its inline entry has not propagated
951
+ // here yet, so a queue task pinned to it would transiently look like a permanent
952
+ // 'target_node_id_unmatched'. Recording its id marks the unmatch as transient.
953
+ const forwardedNodeId = (forwarded as { node?: { id?: unknown } } | null | undefined)?.node?.id;
954
+ if (typeof forwardedNodeId === 'string' && forwardedNodeId) noteRecentlyClonedNode(forwardedNodeId);
955
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
956
+ }
957
+
958
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
959
+ const { createWorktree } = await import('../../git/git-worktree.js');
960
+ const result = await createWorktree({
961
+ repoRoot,
962
+ branch,
963
+ baseBranch,
964
+ meshName: mesh.name,
965
+ });
966
+ if (result.baseSync?.warning) {
967
+ console.warn(`[mesh] clone_mesh_node base sync (${result.baseSync.action}): ${result.baseSync.warning}`);
968
+ } else if (result.baseSync && result.baseSync.action !== 'up_to_date') {
969
+ console.log(`[mesh] clone_mesh_node base sync: ${result.baseSync.action} (startRef=${result.baseSync.startRef})`);
970
+ }
971
+
972
+ let node: any;
973
+ if (meshRecord.inline) {
974
+ const { randomUUID } = await import('crypto');
975
+ node = {
976
+ id: `node_${randomUUID().replace(/-/g, '')}`,
977
+ workspace: result.worktreePath,
978
+ repoRoot: result.worktreePath,
979
+ daemonId: sourceNode.daemonId,
980
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
981
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
982
+ policy: { ...(sourceNode.policy || {}) },
983
+ isLocalWorktree: true,
984
+ worktreeBranch: result.branch,
985
+ clonedFromNodeId: sourceNodeId,
986
+ };
987
+ ctx.updateInlineMeshNode(meshId, mesh, node);
988
+ } else {
989
+ const { addNode } = await import('../../config/mesh-config.js');
990
+ node = addNode(meshId, {
991
+ workspace: result.worktreePath,
992
+ repoRoot: result.worktreePath,
993
+ daemonId: sourceNode.daemonId,
994
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
995
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
996
+ isLocalWorktree: true,
997
+ worktreeBranch: result.branch,
998
+ clonedFromNodeId: sourceNodeId,
999
+ policy: { ...(sourceNode.policy || {}) },
1000
+ });
1001
+ if (!node) return { success: false, error: 'Failed to register worktree node' };
1002
+ // Also reconcile the freshly-registered node into any warmed inline
1003
+ // cache for this mesh. get_mesh (preferInline: true) reads the inline
1004
+ // cache first when one exists; if we only wrote to local config the
1005
+ // node would be invisible to membership reads. updateInlineMeshNode is
1006
+ // a no-op when no inline cache is present.
1007
+ const inlineForReconcile = ctx.getCachedInlineMesh(meshId);
1008
+ if (inlineForReconcile) ctx.updateInlineMeshNode(meshId, inlineForReconcile, node);
1009
+ ctx.invalidateAggregateMeshStatus(meshId);
1010
+ }
1011
+
1012
+ // FALSE-BLOCKER-CLONE-QUEUE: open the transient grace window for the freshly cloned
1013
+ // node. A queue task pinned to it (target_node pin) enqueued before bootstrap
1014
+ // completes / the inline-cache entry fully settles must be classified as a transient
1015
+ // skip, not a permanent 'target_node_id_unmatched' actionable blocker.
1016
+ if (typeof node?.id === 'string' && node.id) noteRecentlyClonedNode(node.id);
1017
+
1018
+ const persistWorktreeSetupState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
1019
+ node.worktreeBootstrap = bootstrapState;
1020
+ if (meshRecord.inline) {
1021
+ ctx.updateInlineMeshNode(meshId, mesh, node);
1022
+ return;
1023
+ }
1024
+ try {
1025
+ const { updateNode } = await import('../../config/mesh-config.js');
1026
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
1027
+ ctx.invalidateAggregateMeshStatus(meshId);
1028
+ } catch { /* bootstrap status persistence is best-effort */ }
1029
+ };
1030
+
1031
+ const appendCloneLedger = async (initSubmodules: boolean, bootstrapState: WorktreeBootstrapState): Promise<void> => {
1032
+ try {
1033
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
1034
+ appendLedgerEntry(meshId, {
1035
+ kind: 'node_cloned',
1036
+ nodeId: node.id,
1037
+ payload: {
1038
+ sourceNodeId,
1039
+ branch: result.branch,
1040
+ worktreePath: result.worktreePath,
1041
+ submodulesInitialized: initSubmodules,
1042
+ worktreeBootstrap: {
1043
+ status: bootstrapState.status,
1044
+ required: bootstrapState.required,
1045
+ configSource: bootstrapState.configSource,
1046
+ configSourceType: bootstrapState.configSourceType,
1047
+ lastCommand: bootstrapState.lastCommand,
1048
+ exitCode: bootstrapState.exitCode,
1049
+ },
1050
+ },
1051
+ });
1052
+ } catch { /* ledger append is best-effort */ }
1053
+ };
1054
+
1055
+ const initSubmodules = (sourceNode.policy as any)?.initSubmodulesOnClone !== false;
1056
+ // Read the worktree bootstrap config through the unified RepoSettings
1057
+ // loader (file-separated `.adhdev/worktree_bootstrap.json`; machine-local
1058
+ // inline seam honored). runMeshWorktreeBootstrap below re-loads it to run.
1059
+ const loadedBootstrap = loadRepoSettings({ workspace: result.worktreePath, mesh }).worktreeBootstrap;
1060
+ const runningBootstrapState: WorktreeBootstrapState = {
1061
+ status: 'running',
1062
+ required: loadedBootstrap.config?.required !== false,
1063
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
1064
+ configSourceType: loadedBootstrap.sourceType,
1065
+ startedAt: new Date().toISOString(),
1066
+ };
1067
+ await persistWorktreeSetupState(runningBootstrapState);
1068
+
1069
+ const finishWorktreeSetup = async (): Promise<{ submodulesInitialized: boolean; bootstrapState: WorktreeBootstrapState }> => {
1070
+ let submodulesInitialized = false;
1071
+ if (initSubmodules) {
1072
+ try {
1073
+ const { runGit } = await import('../../git/git-executor.js');
1074
+ await runGit(
1075
+ { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
1076
+ ['submodule', 'update', '--init', '--recursive'],
1077
+ { timeoutMs: 120000 },
1078
+ );
1079
+ submodulesInitialized = true;
1080
+
1081
+ // Sync every registered submodule to the clone source node's
1082
+ // working HEAD (best-effort, generic over .gitmodules — no
1083
+ // hardcoded 'oss'; the rewind guard is applied per submodule).
1084
+ const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
1085
+ if (sourceWorkspace) {
1086
+ const { runGit: rg } = await import('../../git/git-executor.js');
1087
+ await syncClonedWorktreeSubmodules(result.worktreePath, sourceWorkspace, rg);
1088
+ }
1089
+ } catch (subErr: any) {
1090
+ // Submodule init is best-effort; don't fail the clone
1091
+ console.warn('[mesh] Submodule init failed for worktree:', subErr.message);
1092
+ }
1093
+ }
1094
+ const bootstrapState: WorktreeBootstrapState = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
1095
+ await persistWorktreeSetupState(bootstrapState);
1096
+ await appendCloneLedger(submodulesInitialized, bootstrapState);
1097
+ return { submodulesInitialized, bootstrapState };
1098
+ };
1099
+
1100
+ const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8000);
1101
+ const setupWaitMs = Number.isFinite(requestedSetupWaitMs)
1102
+ ? Math.min(Math.max(requestedSetupWaitMs, 0), 14000)
1103
+ : 8000;
1104
+ const setupPromise = finishWorktreeSetup();
1105
+ const setupResult = await Promise.race([
1106
+ setupPromise.then((value) => ({ completed: true as const, value })),
1107
+ new Promise<{ completed: false }>((resolve) => setTimeout(() => resolve({ completed: false }), setupWaitMs)),
1108
+ ]);
1109
+
1110
+ const emitBootstrapEvent = (eventStatus: 'bootstrap_complete' | 'bootstrap_failed', bootstrapState: WorktreeBootstrapState, startedAtMs: number, extraPayload?: Record<string, unknown>): void => {
1111
+ try {
1112
+ const durationMs = Date.now() - startedAtMs;
1113
+ const event = `worktree_${eventStatus}` as const;
1114
+ const metadataEvent = {
1115
+ source: 'clone_mesh_node_bootstrap',
1116
+ nodeId: node.id,
1117
+ status: eventStatus,
1118
+ worktreePath: result.worktreePath,
1119
+ durationMs,
1120
+ bootstrapStatus: bootstrapState.status,
1121
+ ...(bootstrapState.error ? { error: bootstrapState.error } : {}),
1122
+ ...(bootstrapState.exitCode !== undefined ? { exitCode: bootstrapState.exitCode } : {}),
1123
+ ...(extraPayload || {}),
1124
+ };
1125
+ if (typeof ctx.deps.instanceManager?.getByCategory === 'function') {
1126
+ const forwarded = handleMeshForwardEvent(
1127
+ { instanceManager: ctx.deps.instanceManager } as any,
1128
+ { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent },
1129
+ );
1130
+ if (forwarded?.success === true) return;
1131
+ }
1132
+ queuePendingMeshCoordinatorEvent({
1133
+ event,
1134
+ meshId,
1135
+ nodeLabel: node.id,
1136
+ nodeId: node.id,
1137
+ workspace: result.worktreePath,
1138
+ metadataEvent,
1139
+ queuedAt: Date.now(),
1140
+ });
1141
+ } catch { /* event emission is best-effort */ }
1142
+ };
1143
+
1144
+ const bootstrapStartedMs = Date.now();
1145
+
1146
+ if (!setupResult.completed) {
1147
+ setupPromise
1148
+ .then(({ bootstrapState }) => {
1149
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
1150
+ })
1151
+ .catch((error: any) => {
1152
+ const failedState: WorktreeBootstrapState = {
1153
+ ...runningBootstrapState,
1154
+ status: 'failed',
1155
+ completedAt: new Date().toISOString(),
1156
+ error: error?.message || String(error),
1157
+ };
1158
+ void persistWorktreeSetupState(failedState);
1159
+ void appendCloneLedger(false, failedState);
1160
+ emitBootstrapEvent('bootstrap_failed', failedState, bootstrapStartedMs, { error: error?.message || String(error) });
1161
+ });
1162
+ return {
1163
+ success: true,
1164
+ async: true,
1165
+ status: 'accepted',
1166
+ node,
1167
+ worktreePath: result.worktreePath,
1168
+ branch: result.branch,
1169
+ ...(result.baseSync ? { baseSync: result.baseSync } : {}),
1170
+ ...(result.baseSync?.warning ? { baseStaleWarning: result.baseSync.warning } : {}),
1171
+ worktreeBootstrap: runningBootstrapState,
1172
+ worktreeSetup: {
1173
+ status: 'running',
1174
+ setupWaitMs,
1175
+ message: 'Worktree node is registered; submodule/bootstrap setup is continuing in the background.',
1176
+ },
1177
+ };
1178
+ }
1179
+
1180
+ const { submodulesInitialized, bootstrapState } = setupResult.value;
1181
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
1182
+ return {
1183
+ success: true,
1184
+ node,
1185
+ worktreePath: result.worktreePath,
1186
+ branch: result.branch,
1187
+ ...(result.baseSync ? { baseSync: result.baseSync } : {}),
1188
+ ...(result.baseSync?.warning ? { baseStaleWarning: result.baseSync.warning } : {}),
1189
+ submodulesInitialized,
1190
+ worktreeBootstrap: bootstrapState,
1191
+ };
1192
+ } catch (e: any) {
1193
+ return { success: false, error: e.message };
1194
+ }
1195
+ },
1196
+
1197
+ retry_mesh_node_bootstrap: async (ctx: MedFamilyContext, args: any) => {
1198
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
1199
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
1200
+ if (!meshId) return { success: false, error: 'meshId required' };
1201
+ if (!nodeId) return { success: false, error: 'nodeId required' };
1202
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'bootstrap retry');
1203
+ if (ownerFailure) return ownerFailure;
1204
+
1205
+ try {
1206
+ // preferInline so bootstrap-retry can resolve inline-cache-only clone worktree nodes.
1207
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
1208
+ const mesh = meshRecord?.mesh;
1209
+ if (!mesh) return { success: false, error: 'Mesh not found' };
1210
+
1211
+ const node = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
1212
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
1213
+ if (!node.isLocalWorktree) return { success: false, error: 'Node is not a local worktree node' };
1214
+
1215
+ // Bootstrap runs scripts in the worktree path — forward to the node's daemon if remote.
1216
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
1217
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
1218
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
1219
+ // bootstrap locally, do not forward. Equivalent → local.
1220
+ if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
1221
+ && !args?._meshDirectDispatch) {
1222
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, 'retry_mesh_node_bootstrap', {
1223
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
1224
+ _meshDirectDispatch: true,
1225
+ });
1226
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
1227
+ }
1228
+
1229
+ const currentBootstrap = node.worktreeBootstrap as WorktreeBootstrapState | undefined;
1230
+ if (currentBootstrap?.status === 'running') {
1231
+ return { success: false, error: 'Bootstrap is already running for this node' };
1232
+ }
1233
+
1234
+ const worktreePath: string = node.workspace || node.repoRoot;
1235
+ if (!worktreePath) return { success: false, error: 'Node has no workspace path' };
1236
+
1237
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
1238
+ const runningState: WorktreeBootstrapState = {
1239
+ status: 'running',
1240
+ required: loadedBootstrap.config?.required !== false,
1241
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
1242
+ configSourceType: loadedBootstrap.sourceType,
1243
+ startedAt: new Date().toISOString(),
1244
+ };
1245
+
1246
+ const persistState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
1247
+ node.worktreeBootstrap = bootstrapState;
1248
+ if (meshRecord.inline) {
1249
+ ctx.updateInlineMeshNode(meshId, mesh, node);
1250
+ return;
1251
+ }
1252
+ try {
1253
+ const { updateNode } = await import('../../config/mesh-config.js');
1254
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
1255
+ ctx.invalidateAggregateMeshStatus(meshId);
1256
+ } catch { /* best-effort */ }
1257
+ };
1258
+
1259
+ await persistState(runningState);
1260
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
1261
+ await persistState(bootstrapState);
1262
+
1263
+ return { success: true, bootstrapState };
1264
+ } catch (e: any) {
1265
+ return { success: false, error: e.message };
1266
+ }
1267
+ },
1268
+ };