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

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 +66 -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 +53556 -19074
  82. package/dist/index.js.map +1 -1
  83. package/dist/index.mjs +53380 -19063
  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 +1309 -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,1309 @@
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, normalizeCapabilityTags } = 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) {
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
+ }
590
+ // NODE-SLOTS-REMOTE-WRITE: updateNode reads ONLY this daemon's local
591
+ // meshes.json. When update_mesh_node is forwarded to a node's home-daemon
592
+ // that has no local config entry for a coordinator-owned mesh (a remote
593
+ // member daemon, or a cloud coordinator that holds the mesh solely in its
594
+ // inline cache), updateNode returns undefined and the write failed with
595
+ // "Mesh node not found" — even though the coordinator attached the mesh
596
+ // snapshot as inlineMesh and the read paths (get_mesh / dry-run / list)
597
+ // resolve it fine via getMeshForCommand's inline fallback. Mirror those
598
+ // read paths here: resolve the mesh from the inline cache and apply the
599
+ // same field semantics as updateNode, persisting to the inline cache.
600
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
601
+ const mesh = meshRecord?.mesh;
602
+ if (!mesh) return { success: false, error: 'Mesh not found' };
603
+ const inlineNode = Array.isArray(mesh.nodes)
604
+ ? mesh.nodes.find((n: any) => meshNodeIdMatches(n, nodeId))
605
+ : undefined;
606
+ if (!inlineNode) return { success: false, error: 'Mesh node not found' };
607
+ // Apply the SAME field semantics updateNode uses so the inline write and a
608
+ // local-config write are indistinguishable: shallow-merge policy, honor an
609
+ // explicit systemPrompt clear, replace/normalize capability tags.
610
+ inlineNode.policy = {
611
+ ...(inlineNode.policy && typeof inlineNode.policy === 'object' && !Array.isArray(inlineNode.policy)
612
+ ? inlineNode.policy as Record<string, unknown>
613
+ : {}),
614
+ ...(patch.policy as Record<string, unknown>),
615
+ };
616
+ if (Object.prototype.hasOwnProperty.call(patch, 'systemPrompt')) {
617
+ const sp = (patch as any).systemPrompt;
618
+ if (typeof sp === 'string' && sp.trim()) inlineNode.systemPrompt = sp;
619
+ else delete inlineNode.systemPrompt;
620
+ }
621
+ if (Object.prototype.hasOwnProperty.call(patch, 'capabilities')) {
622
+ const tags = normalizeCapabilityTags((patch as any).capabilities);
623
+ if (tags && tags.length) inlineNode.capabilities = tags;
624
+ else delete inlineNode.capabilities;
625
+ }
626
+ // updateInlineMeshNode canonicalizes node identity, persists the mutated
627
+ // mesh back to the inline cache, and busts the aggregate-status cache.
628
+ ctx.updateInlineMeshNode(meshId, mesh, inlineNode);
629
+ return { success: true, node: inlineNode };
630
+ } catch (e: any) {
631
+ return { success: false, error: e.message };
632
+ }
633
+ },
634
+
635
+ cleanup_mesh_sessions: async (ctx: MedFamilyContext, args: any) => {
636
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
637
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
638
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
639
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node removal');
640
+ if (ownerFailure) return ownerFailure;
641
+ try {
642
+ // preferInline so inline-cache-only clone nodes resolve (matches owner check above).
643
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
644
+ const mesh = meshRecord?.mesh;
645
+ if (!mesh) return { success: false, error: 'Mesh not found' };
646
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
647
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
648
+ const mode = ctx.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
649
+ const sessionIds = Array.isArray(args?.sessionIds)
650
+ ? args.sessionIds.map((id: any) => typeof id === 'string' ? id.trim() : '').filter(Boolean)
651
+ : undefined;
652
+ // MAGI post-review auto-cleanup routes through this same command with
653
+ // source:'magi_session_cleanup' and a per-session autoLaunchedForQueueTaskId
654
+ // map, which gates cleanup to sessions THIS fan-out actually auto-launched.
655
+ const source = args?.source === 'magi_session_cleanup' ? 'magi_session_cleanup' : 'mesh_cleanup_sessions';
656
+ const requireAutoLaunchedForTaskIds = (args?.requireAutoLaunchedForTaskIds
657
+ && typeof args.requireAutoLaunchedForTaskIds === 'object'
658
+ && !Array.isArray(args.requireAutoLaunchedForTaskIds))
659
+ ? args.requireAutoLaunchedForTaskIds as Record<string, string>
660
+ : undefined;
661
+ // Opt-in orphan reclaim (SESSION-ACCUMULATION-LEAK). The live-node id set
662
+ // is the CURRENT mesh membership; a matched live session bound to a node
663
+ // still in this set is an active sibling and is never reclaimed. Only when
664
+ // the caller passes reclaimOrphans:true does the router loosen the
665
+ // shared-daemon guard for workspace-only / dead-node-bound live sessions.
666
+ const reclaimOrphans = args?.reclaimOrphans === true;
667
+ const liveMeshNodeIds = Array.isArray(mesh?.nodes)
668
+ ? mesh.nodes.map((n: any) => normalizeMeshNodeId(n)).filter(Boolean) as string[]
669
+ : [];
670
+ const result = await ctx.cleanupMeshSessions({
671
+ meshId,
672
+ nodeId,
673
+ node,
674
+ mode,
675
+ sessionIds,
676
+ dryRun: args?.dryRun === true,
677
+ source,
678
+ requireAutoLaunchedForTaskIds,
679
+ reclaimOrphans,
680
+ liveMeshNodeIds,
681
+ });
682
+ return result;
683
+ } catch (e: any) {
684
+ return { success: false, error: e.message };
685
+ }
686
+ },
687
+
688
+ remove_mesh_node: async (ctx: MedFamilyContext, args: any) => {
689
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
690
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
691
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
692
+ try {
693
+ // preferInline so removal can resolve inline-cache-only clone worktree nodes.
694
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
695
+ const mesh = meshRecord?.mesh;
696
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
697
+
698
+ // Guard: refuse to remove the coordinator's OWN local base node
699
+ // (same machine, NOT a worktree). Removing it breaks live mesh
700
+ // membership — the coordinator can no longer be reached and has
701
+ // to be restarted. Worktree clones are always safe to remove;
702
+ // only the non-worktree node bound to this daemon is protected.
703
+ // An explicit force:true overrides for intentional mesh teardown.
704
+ if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
705
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : '';
706
+ const nodeMachineId = readMeshNodeMachineId(node as Record<string, unknown>) || '';
707
+ const selfDaemonId = ctx.deps.statusInstanceId || '';
708
+ const selfMachineId = (() => { try { return loadConfig().machineId || ''; } catch { return ''; } })();
709
+ // Identity match is form-safe: a daemon answers to the same machine
710
+ // under interchangeable id forms (bare `mach_X`, cloud `daemon_mach_X`,
711
+ // standalone `standalone_mach_X`). statusInstanceId/loadConfig().machineId
712
+ // and the node's stored daemonId/machineId frequently hold DIFFERENT forms
713
+ // of the same machine, so a raw `===` would miss the self-match and let the
714
+ // coordinator delete its own live base node (the very accident this guard
715
+ // exists to prevent). daemonIdsEquivalent collapses every form to its
716
+ // machine core before comparing, so a same-machine match is caught
717
+ // regardless of which form each side carries. This only widens matches
718
+ // (every raw-`===` hit still matches) — fail-open → fail-closed.
719
+ const isCoordinatorBaseNode =
720
+ (!!selfDaemonId && (daemonIdsEquivalent(nodeDaemonId, selfDaemonId) || daemonIdsEquivalent(nodeMachineId, selfDaemonId)))
721
+ || (!!selfMachineId && (daemonIdsEquivalent(nodeDaemonId, selfMachineId) || daemonIdsEquivalent(nodeMachineId, selfMachineId)));
722
+ if (isCoordinatorBaseNode) {
723
+ return {
724
+ success: false,
725
+ removed: false,
726
+ code: 'mesh_remove_coordinator_base_node_protected',
727
+ error: `Refusing to remove the coordinator's own base node '${typeof node.workspace === 'string' ? node.workspace : nodeId}'. `
728
+ + `It is the local non-worktree node bound to this coordinator daemon; removing it breaks live mesh membership and forces a restart.`,
729
+ 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.',
730
+ };
731
+ }
732
+ }
733
+
734
+ // Default worktree session cleanup ON: when the caller OMITS a mode and the
735
+ // node is a local worktree, default to 'stop_and_delete' instead of the mesh
736
+ // policy ('preserve' by default). A worktree's chat session has no reason to
737
+ // outlive the worktree's node + directory + branch, and leaving it on
738
+ // 'preserve' is what orphaned chats after a worktree remove. An explicit mode
739
+ // (including an explicit 'preserve') is always honored — only the OMITTED case
740
+ // changes, and only for worktrees. Base nodes keep arg ?? policy ?? preserve.
741
+ const explicitCleanupMode = args?.sessionCleanupMode ?? args?.session_cleanup_mode;
742
+ const sessionCleanupMode = ctx.normalizeMeshSessionCleanupMode(
743
+ explicitCleanupMode
744
+ ?? (node?.isLocalWorktree === true ? 'stop_and_delete' : undefined)
745
+ ?? mesh?.policy?.sessionCleanupOnNodeRemove,
746
+ );
747
+ // Explicit sessionIds (e.g. supplied by refine auto-cleanup) bypass the
748
+ // workspace-only-match guard so a delegate session that lacks a
749
+ // meta.meshNodeId binding can still be stopped/deleted.
750
+ const explicitSessionIds = Array.isArray(args?.sessionIds)
751
+ ? (args.sessionIds as unknown[]).filter((v): v is string => typeof v === 'string' && v.trim().length > 0).map(v => v.trim())
752
+ : undefined;
753
+ // Precheck-first: for a LOCAL worktree removal, validate removability
754
+ // with a purely non-destructive precheck BEFORE touching the session.
755
+ // The session cleanup below is destructive and irreversible
756
+ // (stop_and_delete), so a refusal that fires only AFTER it — as the old
757
+ // ordering did when removeWorktree rejected a dirty worktree — orphaned
758
+ // the delegated session. Running the precheck here means a refusal
759
+ // (dirty worktree, missing/mismatched metadata, etc.) returns with the
760
+ // session left fully intact. Remote-forwarded worktrees are prechecked
761
+ // on the owning daemon (it runs this same handler), so we only gate the
762
+ // local case here. Success/skip cases return ok:true and fall through to
763
+ // the unchanged normal flow.
764
+ if (node?.isLocalWorktree) {
765
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
766
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
767
+ && !args?._meshDirectDispatch;
768
+ if (!isRemoteWorktree) {
769
+ const precheck = await ctx.precheckLocalWorktreeRemovable({ mesh, node, nodeId, force: args?.force === true });
770
+ if (precheck.ok === false) {
771
+ return {
772
+ success: false,
773
+ removed: false,
774
+ code: precheck.code,
775
+ error: precheck.error,
776
+ recoveryHint: precheck.recoveryHint,
777
+ // No sessionCleanup key: the session was deliberately NOT
778
+ // touched. worktreeCleanup mirrors the destructive path's
779
+ // refusal shape so existing callers see the same code.
780
+ worktreeCleanup: { success: false, code: precheck.code, error: precheck.error, recoveryHint: precheck.recoveryHint },
781
+ };
782
+ }
783
+ }
784
+ }
785
+
786
+ let sessionCleanup: Record<string, unknown> | undefined;
787
+ if (node && sessionCleanupMode !== 'preserve') {
788
+ sessionCleanup = await ctx.cleanupMeshSessions({
789
+ meshId,
790
+ nodeId,
791
+ node,
792
+ mode: sessionCleanupMode,
793
+ ...(explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {}),
794
+ source: 'mesh_remove_node',
795
+ });
796
+ if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
797
+ }
798
+
799
+ let worktreeCleanup: Record<string, unknown> | undefined;
800
+ if (node?.isLocalWorktree) {
801
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
802
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
803
+ // clean up locally, do not forward. Equivalent → local.
804
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
805
+ && !args?._meshDirectDispatch;
806
+ if (isRemoteWorktree) {
807
+ // Worktree lives on a different machine — ask that daemon to clean it up.
808
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
809
+ const forwarded = await ctx.deps.dispatchMeshCommand!(nodeDaemonId!, 'remove_mesh_node', {
810
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
811
+ _meshDirectDispatch: true,
812
+ });
813
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
814
+ }
815
+ const cleanupResult = await ctx.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
816
+ // De-gating: membership removal is NOT gated on the worktree
817
+ // directory actually being deleted. cleanupLocalWorktreeNode now
818
+ // returns success:true (with a residue flag) whenever the path is
819
+ // proven managed and the only remaining problem is leftover
820
+ // directory bytes (e.g. Windows EINVAL). A success:false here means
821
+ // a genuinely-unsafe condition — missing metadata, a non-managed /
822
+ // unexpected path, a branch mismatch, a dirty worktree, or an
823
+ // unverified force fallback — and those still block removal.
824
+ if (cleanupResult.success === false) {
825
+ return {
826
+ success: false,
827
+ removed: false,
828
+ code: cleanupResult.code,
829
+ error: cleanupResult.error,
830
+ recoveryHint: cleanupResult.recoveryHint,
831
+ ...(sessionCleanup ? { sessionCleanup } : {}),
832
+ worktreeCleanup: cleanupResult,
833
+ };
834
+ }
835
+ worktreeCleanup = cleanupResult;
836
+ }
837
+
838
+ let removed = false;
839
+ if (meshRecord?.inline) {
840
+ removed = ctx.removeInlineMeshNode(meshId, mesh, nodeId);
841
+ // Inline meshes share the same aggregate snapshot cache as
842
+ // local-config meshes; without this bust the removed node
843
+ // keeps showing up in the dashboard graph until the cache
844
+ // ages out on its own.
845
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
846
+ // MESH-INLINE-NODE-RESURRECTION: removeInlineMeshNode only mutates
847
+ // the in-memory inlineMeshCache + tombstones — it does NOT touch
848
+ // the file-backed config (meshes.json). When the SAME node also
849
+ // lives in meshes.json (a worktree node that was persisted to the
850
+ // file config, then resolved through the inline cache on removal),
851
+ // the file record survives. On daemon restart the in-memory
852
+ // tombstone is lost, getMesh falls back to the file config, and
853
+ // mesh-status renders the dead node again. So a node present in
854
+ // BOTH the inline cache AND meshes.json must be spliced+saved from
855
+ // the file config here too. Pure-inline meshes (no matching file
856
+ // mesh/node) are untouched — getMesh returns undefined and we skip.
857
+ try {
858
+ const { getMesh, removeNode } = await import('../../config/mesh-config.js');
859
+ const fileMesh = getMesh(meshId);
860
+ const fileNode = fileMesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
861
+ if (fileNode?.id) {
862
+ const fileRemoved = removeNode(meshId, fileNode.id);
863
+ if (fileRemoved) {
864
+ removed = true;
865
+ ctx.invalidateAggregateMeshStatus(meshId);
866
+ }
867
+ }
868
+ } catch { /* file config absent / unreadable — inline-only mesh, nothing to durably delete */ }
869
+ // Node was already absent from the inline mesh (e.g. removed by a
870
+ // prior refine cleanup). Treat as removed so caller gets removed:true.
871
+ if (!removed && !node) removed = true;
872
+ } else {
873
+ const { removeNode } = await import('../../config/mesh-config.js');
874
+ removed = removeNode(meshId, nodeId);
875
+ // Node already absent from config (e.g. removed by a prior refine
876
+ // cleanup after a successful Refinery merge). Treat as removed so
877
+ // the response is accurate.
878
+ if (!removed && !node) removed = true;
879
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
880
+ }
881
+
882
+ // Record in task ledger
883
+ if (removed) {
884
+ try {
885
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
886
+ appendLedgerEntry(meshId, {
887
+ kind: 'node_removed',
888
+ nodeId,
889
+ payload: {
890
+ worktree: !!node?.isLocalWorktree,
891
+ sessionCleanupMode,
892
+ workspace: typeof node?.workspace === 'string' ? node.workspace : undefined,
893
+ daemonId: typeof node?.daemonId === 'string' ? node.daemonId : undefined,
894
+ worktreeBranch: typeof node?.worktreeBranch === 'string' ? node.worktreeBranch : undefined,
895
+ worktreeCleanupFallback: typeof worktreeCleanup?.fallback === 'string' ? worktreeCleanup.fallback : undefined,
896
+ forced: worktreeCleanup?.forced === true ? true : undefined,
897
+ forceFallbackReason: typeof worktreeCleanup?.reason === 'string' ? worktreeCleanup.reason : undefined,
898
+ branchRefDeleted: typeof worktreeCleanup?.branchRefDeleted === 'boolean' ? worktreeCleanup.branchRefDeleted : undefined,
899
+ branchRefReason: typeof worktreeCleanup?.branchRefReason === 'string' ? worktreeCleanup.branchRefReason : undefined,
900
+ },
901
+ });
902
+ } catch { /* ledger append is best-effort */ }
903
+ }
904
+
905
+ // Surface leftover-directory residue at the top level so callers
906
+ // see the node was dropped from the mesh even though the worktree
907
+ // directory could not be fully removed (best-effort, non-gating).
908
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === 'string'
909
+ ? worktreeCleanup.residueWarning
910
+ : undefined;
911
+
912
+ // Surface a preserved-branch warning at the top level so callers see
913
+ // that the branch ref was intentionally NOT deleted (unmerged work is
914
+ // never silently dropped). When the branch ref WAS deleted, the nested
915
+ // worktreeCleanup.branchRefDeleted flag already records it.
916
+ const branchRefWarning = typeof worktreeCleanup?.branchRefWarning === 'string'
917
+ ? worktreeCleanup.branchRefWarning
918
+ : undefined;
919
+
920
+ // Orphan guard: if the session cleanup still left any LIVE session skipped
921
+ // (e.g. a future skip reason, or a workspace-only session on a base node),
922
+ // surface it at the top level so the caller knows a manual mesh_cleanup_sessions
923
+ // is still required for those sessionIds. Without this, a skipped-live session
924
+ // silently outlives a removed node (the very NODE-REMOVE-SESSION-ORPHAN bug).
925
+ const skippedLiveSessionIds = Array.isArray(sessionCleanup?.skippedLiveSessionIds)
926
+ ? (sessionCleanup!.skippedLiveSessionIds as unknown[]).filter((v): v is string => typeof v === 'string')
927
+ : [];
928
+ const orphanedSessionsRemaining = skippedLiveSessionIds.length > 0;
929
+ const orphanNextAction = orphanedSessionsRemaining
930
+ ? `Live session(s) [${skippedLiveSessionIds.join(', ')}] were skipped and still survive this node removal. `
931
+ + `Run mesh_cleanup_sessions with mode:'stop_and_delete' and sessionIds:[${skippedLiveSessionIds.map(id => `'${id}'`).join(', ')}] to release them.`
932
+ : undefined;
933
+ return {
934
+ success: true,
935
+ removed,
936
+ ...(residueWarning ? { residueWarning } : {}),
937
+ ...(branchRefWarning ? { branchRefWarning } : {}),
938
+ ...(sessionCleanup ? { sessionCleanup } : {}),
939
+ ...(worktreeCleanup ? { worktreeCleanup } : {}),
940
+ ...(orphanedSessionsRemaining
941
+ ? { orphanedSessionsRemaining: true, nextAction: orphanNextAction }
942
+ : {}),
943
+ };
944
+ } catch (e: any) {
945
+ return { success: false, error: e.message };
946
+ }
947
+ },
948
+
949
+ clone_mesh_node: async (ctx: MedFamilyContext, args: any) => {
950
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
951
+ const sourceNodeId = typeof args?.sourceNodeId === 'string' ? args.sourceNodeId.trim() : '';
952
+ const branch = typeof args?.branch === 'string' ? args.branch.trim() : '';
953
+ const baseBranch = typeof args?.baseBranch === 'string' ? args.baseBranch.trim() : undefined;
954
+ if (!meshId) return { success: false, error: 'meshId required' };
955
+ if (!sourceNodeId) return { success: false, error: 'sourceNodeId required' };
956
+ if (!branch) return { success: false, error: 'branch required' };
957
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'worktree clone');
958
+ if (ownerFailure) return ownerFailure;
959
+
960
+ try {
961
+ // Resolve with preferInline so the clone writes the new node into the
962
+ // same representation that get_mesh reads back. The MCP coordinator
963
+ // passes inlineMesh on every mesh command, so when it owns an inline
964
+ // mesh the membership read path (get_mesh, preferInline: true) returns
965
+ // the inline cache. Without preferInline here, clone could resolve to a
966
+ // local-config mesh and write the node only to config — leaving the
967
+ // inline cache (and therefore get_mesh / refreshMeshFromDaemon) without
968
+ // the node, so the new worktree node is never visible in live mesh
969
+ // membership even though worktree_bootstrap_complete fires.
970
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
971
+ const mesh = meshRecord?.mesh;
972
+ if (!mesh) return { success: false, error: 'Mesh not found' };
973
+
974
+ const sourceNode = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, sourceNodeId));
975
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
976
+
977
+ // Forward to the source node's daemon if it's on a different machine.
978
+ // _meshDirectDispatch prevents infinite re-forwarding when the stored daemonId
979
+ // uses a legacy format that doesn't match the receiving daemon's statusInstanceId.
980
+ const sourceDaemonId = typeof sourceNode.daemonId === 'string' ? sourceNode.daemonId.trim() : undefined;
981
+ // daemonIdsEquivalent: an equivalent-form source daemonId is this machine —
982
+ // clone locally, do not forward. Equivalent → local.
983
+ if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
984
+ && !args?._meshDirectDispatch) {
985
+ const forwarded = await ctx.deps.dispatchMeshCommand(sourceDaemonId, 'clone_mesh_node', {
986
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
987
+ _meshDirectDispatch: true,
988
+ });
989
+ // FALSE-BLOCKER-CLONE-QUEUE: open the transient grace window for the freshly
990
+ // cloned node on THIS coordinator daemon. The clone ran (and wrote the inline-
991
+ // cache node) on the remote source daemon; its inline entry has not propagated
992
+ // here yet, so a queue task pinned to it would transiently look like a permanent
993
+ // 'target_node_id_unmatched'. Recording its id marks the unmatch as transient.
994
+ const forwardedNodeId = (forwarded as { node?: { id?: unknown } } | null | undefined)?.node?.id;
995
+ if (typeof forwardedNodeId === 'string' && forwardedNodeId) noteRecentlyClonedNode(forwardedNodeId);
996
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
997
+ }
998
+
999
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
1000
+ const { createWorktree } = await import('../../git/git-worktree.js');
1001
+ const result = await createWorktree({
1002
+ repoRoot,
1003
+ branch,
1004
+ baseBranch,
1005
+ meshName: mesh.name,
1006
+ });
1007
+ if (result.baseSync?.warning) {
1008
+ console.warn(`[mesh] clone_mesh_node base sync (${result.baseSync.action}): ${result.baseSync.warning}`);
1009
+ } else if (result.baseSync && result.baseSync.action !== 'up_to_date') {
1010
+ console.log(`[mesh] clone_mesh_node base sync: ${result.baseSync.action} (startRef=${result.baseSync.startRef})`);
1011
+ }
1012
+
1013
+ let node: any;
1014
+ if (meshRecord.inline) {
1015
+ const { randomUUID } = await import('crypto');
1016
+ node = {
1017
+ id: `node_${randomUUID().replace(/-/g, '')}`,
1018
+ workspace: result.worktreePath,
1019
+ repoRoot: result.worktreePath,
1020
+ daemonId: sourceNode.daemonId,
1021
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
1022
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
1023
+ policy: { ...(sourceNode.policy || {}) },
1024
+ isLocalWorktree: true,
1025
+ worktreeBranch: result.branch,
1026
+ clonedFromNodeId: sourceNodeId,
1027
+ };
1028
+ ctx.updateInlineMeshNode(meshId, mesh, node);
1029
+ } else {
1030
+ const { addNode } = await import('../../config/mesh-config.js');
1031
+ node = addNode(meshId, {
1032
+ workspace: result.worktreePath,
1033
+ repoRoot: result.worktreePath,
1034
+ daemonId: sourceNode.daemonId,
1035
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
1036
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
1037
+ isLocalWorktree: true,
1038
+ worktreeBranch: result.branch,
1039
+ clonedFromNodeId: sourceNodeId,
1040
+ policy: { ...(sourceNode.policy || {}) },
1041
+ });
1042
+ if (!node) return { success: false, error: 'Failed to register worktree node' };
1043
+ // Also reconcile the freshly-registered node into any warmed inline
1044
+ // cache for this mesh. get_mesh (preferInline: true) reads the inline
1045
+ // cache first when one exists; if we only wrote to local config the
1046
+ // node would be invisible to membership reads. updateInlineMeshNode is
1047
+ // a no-op when no inline cache is present.
1048
+ const inlineForReconcile = ctx.getCachedInlineMesh(meshId);
1049
+ if (inlineForReconcile) ctx.updateInlineMeshNode(meshId, inlineForReconcile, node);
1050
+ ctx.invalidateAggregateMeshStatus(meshId);
1051
+ }
1052
+
1053
+ // FALSE-BLOCKER-CLONE-QUEUE: open the transient grace window for the freshly cloned
1054
+ // node. A queue task pinned to it (target_node pin) enqueued before bootstrap
1055
+ // completes / the inline-cache entry fully settles must be classified as a transient
1056
+ // skip, not a permanent 'target_node_id_unmatched' actionable blocker.
1057
+ if (typeof node?.id === 'string' && node.id) noteRecentlyClonedNode(node.id);
1058
+
1059
+ const persistWorktreeSetupState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
1060
+ node.worktreeBootstrap = bootstrapState;
1061
+ if (meshRecord.inline) {
1062
+ ctx.updateInlineMeshNode(meshId, mesh, node);
1063
+ return;
1064
+ }
1065
+ try {
1066
+ const { updateNode } = await import('../../config/mesh-config.js');
1067
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
1068
+ ctx.invalidateAggregateMeshStatus(meshId);
1069
+ } catch { /* bootstrap status persistence is best-effort */ }
1070
+ };
1071
+
1072
+ const appendCloneLedger = async (initSubmodules: boolean, bootstrapState: WorktreeBootstrapState): Promise<void> => {
1073
+ try {
1074
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
1075
+ appendLedgerEntry(meshId, {
1076
+ kind: 'node_cloned',
1077
+ nodeId: node.id,
1078
+ payload: {
1079
+ sourceNodeId,
1080
+ branch: result.branch,
1081
+ worktreePath: result.worktreePath,
1082
+ submodulesInitialized: initSubmodules,
1083
+ worktreeBootstrap: {
1084
+ status: bootstrapState.status,
1085
+ required: bootstrapState.required,
1086
+ configSource: bootstrapState.configSource,
1087
+ configSourceType: bootstrapState.configSourceType,
1088
+ lastCommand: bootstrapState.lastCommand,
1089
+ exitCode: bootstrapState.exitCode,
1090
+ },
1091
+ },
1092
+ });
1093
+ } catch { /* ledger append is best-effort */ }
1094
+ };
1095
+
1096
+ const initSubmodules = (sourceNode.policy as any)?.initSubmodulesOnClone !== false;
1097
+ // Read the worktree bootstrap config through the unified RepoSettings
1098
+ // loader (file-separated `.adhdev/worktree_bootstrap.json`; machine-local
1099
+ // inline seam honored). runMeshWorktreeBootstrap below re-loads it to run.
1100
+ const loadedBootstrap = loadRepoSettings({ workspace: result.worktreePath, mesh }).worktreeBootstrap;
1101
+ const runningBootstrapState: WorktreeBootstrapState = {
1102
+ status: 'running',
1103
+ required: loadedBootstrap.config?.required !== false,
1104
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
1105
+ configSourceType: loadedBootstrap.sourceType,
1106
+ startedAt: new Date().toISOString(),
1107
+ };
1108
+ await persistWorktreeSetupState(runningBootstrapState);
1109
+
1110
+ const finishWorktreeSetup = async (): Promise<{ submodulesInitialized: boolean; bootstrapState: WorktreeBootstrapState }> => {
1111
+ let submodulesInitialized = false;
1112
+ if (initSubmodules) {
1113
+ try {
1114
+ const { runGit } = await import('../../git/git-executor.js');
1115
+ await runGit(
1116
+ { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
1117
+ ['submodule', 'update', '--init', '--recursive'],
1118
+ { timeoutMs: 120000 },
1119
+ );
1120
+ submodulesInitialized = true;
1121
+
1122
+ // Sync every registered submodule to the clone source node's
1123
+ // working HEAD (best-effort, generic over .gitmodules — no
1124
+ // hardcoded 'oss'; the rewind guard is applied per submodule).
1125
+ const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
1126
+ if (sourceWorkspace) {
1127
+ const { runGit: rg } = await import('../../git/git-executor.js');
1128
+ await syncClonedWorktreeSubmodules(result.worktreePath, sourceWorkspace, rg);
1129
+ }
1130
+ } catch (subErr: any) {
1131
+ // Submodule init is best-effort; don't fail the clone
1132
+ console.warn('[mesh] Submodule init failed for worktree:', subErr.message);
1133
+ }
1134
+ }
1135
+ const bootstrapState: WorktreeBootstrapState = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
1136
+ await persistWorktreeSetupState(bootstrapState);
1137
+ await appendCloneLedger(submodulesInitialized, bootstrapState);
1138
+ return { submodulesInitialized, bootstrapState };
1139
+ };
1140
+
1141
+ const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8000);
1142
+ const setupWaitMs = Number.isFinite(requestedSetupWaitMs)
1143
+ ? Math.min(Math.max(requestedSetupWaitMs, 0), 14000)
1144
+ : 8000;
1145
+ const setupPromise = finishWorktreeSetup();
1146
+ const setupResult = await Promise.race([
1147
+ setupPromise.then((value) => ({ completed: true as const, value })),
1148
+ new Promise<{ completed: false }>((resolve) => setTimeout(() => resolve({ completed: false }), setupWaitMs)),
1149
+ ]);
1150
+
1151
+ const emitBootstrapEvent = (eventStatus: 'bootstrap_complete' | 'bootstrap_failed', bootstrapState: WorktreeBootstrapState, startedAtMs: number, extraPayload?: Record<string, unknown>): void => {
1152
+ try {
1153
+ const durationMs = Date.now() - startedAtMs;
1154
+ const event = `worktree_${eventStatus}` as const;
1155
+ const metadataEvent = {
1156
+ source: 'clone_mesh_node_bootstrap',
1157
+ nodeId: node.id,
1158
+ status: eventStatus,
1159
+ worktreePath: result.worktreePath,
1160
+ durationMs,
1161
+ bootstrapStatus: bootstrapState.status,
1162
+ ...(bootstrapState.error ? { error: bootstrapState.error } : {}),
1163
+ ...(bootstrapState.exitCode !== undefined ? { exitCode: bootstrapState.exitCode } : {}),
1164
+ ...(extraPayload || {}),
1165
+ };
1166
+ if (typeof ctx.deps.instanceManager?.getByCategory === 'function') {
1167
+ const forwarded = handleMeshForwardEvent(
1168
+ { instanceManager: ctx.deps.instanceManager } as any,
1169
+ { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent },
1170
+ );
1171
+ if (forwarded?.success === true) return;
1172
+ }
1173
+ queuePendingMeshCoordinatorEvent({
1174
+ event,
1175
+ meshId,
1176
+ nodeLabel: node.id,
1177
+ nodeId: node.id,
1178
+ workspace: result.worktreePath,
1179
+ metadataEvent,
1180
+ queuedAt: Date.now(),
1181
+ });
1182
+ } catch { /* event emission is best-effort */ }
1183
+ };
1184
+
1185
+ const bootstrapStartedMs = Date.now();
1186
+
1187
+ if (!setupResult.completed) {
1188
+ setupPromise
1189
+ .then(({ bootstrapState }) => {
1190
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
1191
+ })
1192
+ .catch((error: any) => {
1193
+ const failedState: WorktreeBootstrapState = {
1194
+ ...runningBootstrapState,
1195
+ status: 'failed',
1196
+ completedAt: new Date().toISOString(),
1197
+ error: error?.message || String(error),
1198
+ };
1199
+ void persistWorktreeSetupState(failedState);
1200
+ void appendCloneLedger(false, failedState);
1201
+ emitBootstrapEvent('bootstrap_failed', failedState, bootstrapStartedMs, { error: error?.message || String(error) });
1202
+ });
1203
+ return {
1204
+ success: true,
1205
+ async: true,
1206
+ status: 'accepted',
1207
+ node,
1208
+ worktreePath: result.worktreePath,
1209
+ branch: result.branch,
1210
+ ...(result.baseSync ? { baseSync: result.baseSync } : {}),
1211
+ ...(result.baseSync?.warning ? { baseStaleWarning: result.baseSync.warning } : {}),
1212
+ worktreeBootstrap: runningBootstrapState,
1213
+ worktreeSetup: {
1214
+ status: 'running',
1215
+ setupWaitMs,
1216
+ message: 'Worktree node is registered; submodule/bootstrap setup is continuing in the background.',
1217
+ },
1218
+ };
1219
+ }
1220
+
1221
+ const { submodulesInitialized, bootstrapState } = setupResult.value;
1222
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
1223
+ return {
1224
+ success: true,
1225
+ node,
1226
+ worktreePath: result.worktreePath,
1227
+ branch: result.branch,
1228
+ ...(result.baseSync ? { baseSync: result.baseSync } : {}),
1229
+ ...(result.baseSync?.warning ? { baseStaleWarning: result.baseSync.warning } : {}),
1230
+ submodulesInitialized,
1231
+ worktreeBootstrap: bootstrapState,
1232
+ };
1233
+ } catch (e: any) {
1234
+ return { success: false, error: e.message };
1235
+ }
1236
+ },
1237
+
1238
+ retry_mesh_node_bootstrap: async (ctx: MedFamilyContext, args: any) => {
1239
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
1240
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
1241
+ if (!meshId) return { success: false, error: 'meshId required' };
1242
+ if (!nodeId) return { success: false, error: 'nodeId required' };
1243
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'bootstrap retry');
1244
+ if (ownerFailure) return ownerFailure;
1245
+
1246
+ try {
1247
+ // preferInline so bootstrap-retry can resolve inline-cache-only clone worktree nodes.
1248
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
1249
+ const mesh = meshRecord?.mesh;
1250
+ if (!mesh) return { success: false, error: 'Mesh not found' };
1251
+
1252
+ const node = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
1253
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
1254
+ if (!node.isLocalWorktree) return { success: false, error: 'Node is not a local worktree node' };
1255
+
1256
+ // Bootstrap runs scripts in the worktree path — forward to the node's daemon if remote.
1257
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
1258
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
1259
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
1260
+ // bootstrap locally, do not forward. Equivalent → local.
1261
+ if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
1262
+ && !args?._meshDirectDispatch) {
1263
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, 'retry_mesh_node_bootstrap', {
1264
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
1265
+ _meshDirectDispatch: true,
1266
+ });
1267
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
1268
+ }
1269
+
1270
+ const currentBootstrap = node.worktreeBootstrap as WorktreeBootstrapState | undefined;
1271
+ if (currentBootstrap?.status === 'running') {
1272
+ return { success: false, error: 'Bootstrap is already running for this node' };
1273
+ }
1274
+
1275
+ const worktreePath: string = node.workspace || node.repoRoot;
1276
+ if (!worktreePath) return { success: false, error: 'Node has no workspace path' };
1277
+
1278
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
1279
+ const runningState: WorktreeBootstrapState = {
1280
+ status: 'running',
1281
+ required: loadedBootstrap.config?.required !== false,
1282
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
1283
+ configSourceType: loadedBootstrap.sourceType,
1284
+ startedAt: new Date().toISOString(),
1285
+ };
1286
+
1287
+ const persistState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
1288
+ node.worktreeBootstrap = bootstrapState;
1289
+ if (meshRecord.inline) {
1290
+ ctx.updateInlineMeshNode(meshId, mesh, node);
1291
+ return;
1292
+ }
1293
+ try {
1294
+ const { updateNode } = await import('../../config/mesh-config.js');
1295
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
1296
+ ctx.invalidateAggregateMeshStatus(meshId);
1297
+ } catch { /* best-effort */ }
1298
+ };
1299
+
1300
+ await persistState(runningState);
1301
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
1302
+ await persistState(bootstrapState);
1303
+
1304
+ return { success: true, bootstrapState };
1305
+ } catch (e: any) {
1306
+ return { success: false, error: e.message };
1307
+ }
1308
+ },
1309
+ };