@adhdev/daemon-core 0.9.82-rc.38 → 0.9.82-rc.381

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 (414) 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 +55 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +121 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +63 -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 +14 -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 +7 -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 +15 -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 +60 -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 +2 -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 +116 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +227 -2
  56. package/dist/commands/upgrade-helper.d.ts +41 -1
  57. package/dist/config/chat-history.d.ts +9 -0
  58. package/dist/config/config.d.ts +5 -0
  59. package/dist/config/mesh-config.d.ts +77 -1
  60. package/dist/daemon/dev-server.d.ts +0 -2
  61. package/dist/detection/ide-detector.d.ts +13 -0
  62. package/dist/detection/win32-ide-version.d.ts +37 -0
  63. package/dist/git/change-impact-config.d.ts +159 -0
  64. package/dist/git/git-commands.d.ts +11 -1
  65. package/dist/git/git-diff.d.ts +6 -0
  66. package/dist/git/git-executor.d.ts +11 -0
  67. package/dist/git/git-status.d.ts +23 -0
  68. package/dist/git/git-types.d.ts +2 -50
  69. package/dist/git/index.d.ts +2 -0
  70. package/dist/index.d.ts +57 -13
  71. package/dist/index.js +47417 -19860
  72. package/dist/index.js.map +1 -1
  73. package/dist/index.mjs +45865 -18449
  74. package/dist/index.mjs.map +1 -1
  75. package/dist/installer.d.ts +1 -4
  76. package/dist/ipc/local-ipc-server.d.ts +91 -0
  77. package/dist/launch.d.ts +1 -1
  78. package/dist/logging/async-batch-writer.d.ts +10 -0
  79. package/dist/logging/log-redactor.d.ts +24 -0
  80. package/dist/logging/log-tail-reader.d.ts +81 -0
  81. package/dist/logging/logger.d.ts +1 -1
  82. package/dist/mesh/contracts.d.ts +164 -0
  83. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  84. package/dist/mesh/coordinator-registry.d.ts +59 -0
  85. package/dist/mesh/mesh-active-work.d.ts +174 -0
  86. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  87. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  88. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  89. package/dist/mesh/mesh-event-forwarding.d.ts +18 -0
  90. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  91. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  92. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  93. package/dist/mesh/mesh-events-stale.d.ts +52 -0
  94. package/dist/mesh/mesh-events-utils.d.ts +64 -0
  95. package/dist/mesh/mesh-events.d.ts +6 -49
  96. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  97. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  98. package/dist/mesh/mesh-init.d.ts +86 -0
  99. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  100. package/dist/mesh/mesh-ledger.d.ts +77 -1
  101. package/dist/mesh/mesh-missions.d.ts +164 -0
  102. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  103. package/dist/mesh/mesh-queue-assignment.d.ts +86 -0
  104. package/dist/mesh/mesh-reconcile-loop.d.ts +8 -0
  105. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  106. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  107. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  108. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  109. package/dist/mesh/mesh-routing.d.ts +70 -0
  110. package/dist/mesh/mesh-runtime-store.d.ts +439 -0
  111. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  112. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  113. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  114. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  115. package/dist/mesh/mesh-work-queue.d.ts +247 -5
  116. package/dist/mesh/preview-freshness.d.ts +18 -0
  117. package/dist/mesh/refine-config.d.ts +216 -0
  118. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  119. package/dist/providers/acp-provider-instance.d.ts +5 -0
  120. package/dist/providers/approval-utils.d.ts +20 -0
  121. package/dist/providers/chat-message-normalization.d.ts +13 -1
  122. package/dist/providers/cli-provider-instance.d.ts +111 -3
  123. package/dist/providers/contracts.d.ts +139 -6
  124. package/dist/providers/external-sources.d.ts +71 -0
  125. package/dist/providers/manual-attendance.d.ts +63 -0
  126. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  127. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  128. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  129. package/dist/providers/native-history/constants.d.ts +12 -0
  130. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  131. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  132. package/dist/providers/native-history/index.d.ts +13 -0
  133. package/dist/providers/provider-instance-manager.d.ts +14 -0
  134. package/dist/providers/provider-instance.d.ts +23 -1
  135. package/dist/providers/provider-loader.d.ts +26 -4
  136. package/dist/providers/provider-trust.d.ts +31 -0
  137. package/dist/providers/read-chat-contract.d.ts +29 -0
  138. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  139. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  140. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  141. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  142. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  143. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  144. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  145. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  146. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  147. package/dist/providers/sdk/v1/index.d.ts +30 -0
  148. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  149. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  150. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  151. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  152. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  153. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  154. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  155. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  156. package/dist/providers/spec/adapter.d.ts +91 -0
  157. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  158. package/dist/providers/spec/evaluator.d.ts +45 -0
  159. package/dist/providers/spec/fsm-driver.d.ts +397 -0
  160. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  161. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  162. package/dist/providers/spec/fsm-types.d.ts +174 -0
  163. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  164. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  165. package/dist/providers/spec/route.d.ts +4 -0
  166. package/dist/providers/spec/types.d.ts +222 -0
  167. package/dist/providers/status-monitor.d.ts +7 -7
  168. package/dist/providers/transcript-v2.d.ts +176 -0
  169. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  170. package/dist/providers/working-dir.d.ts +17 -0
  171. package/dist/repo-mesh-types.d.ts +376 -13
  172. package/dist/runtime-defaults.d.ts +2 -0
  173. package/dist/sessions/registry.d.ts +6 -0
  174. package/dist/shared-types-extra.d.ts +2 -4
  175. package/dist/shared-types.d.ts +59 -2
  176. package/dist/status/normalize.d.ts +1 -1
  177. package/dist/status/normalize.js +1 -0
  178. package/dist/status/normalize.js.map +1 -1
  179. package/dist/status/normalize.mjs +1 -0
  180. package/dist/status/normalize.mjs.map +1 -1
  181. package/dist/status/reporter.d.ts +2 -0
  182. package/dist/status/snapshot.d.ts +26 -0
  183. package/dist/system/hash.d.ts +8 -0
  184. package/dist/system/load-better-sqlite3.d.ts +21 -0
  185. package/dist/types.d.ts +5 -0
  186. package/package.json +7 -3
  187. package/src/agent-stream/poller.ts +2 -3
  188. package/src/agent-stream/provider-adapter.ts +1 -1
  189. package/src/boot/daemon-lifecycle.ts +63 -12
  190. package/src/boot/process-hardening.ts +89 -0
  191. package/src/build-info.ts +73 -0
  192. package/src/chat/source-machine.ts +534 -0
  193. package/src/chat/source-resolver.ts +0 -0
  194. package/src/chat/subscription-updates.ts +20 -1
  195. package/src/cli-adapter-types.d.ts +1 -0
  196. package/src/cli-adapter-types.ts +56 -2
  197. package/src/cli-adapters/cli-script-runner.ts +421 -0
  198. package/src/cli-adapters/cli-state-engine.ts +1221 -0
  199. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  200. package/src/cli-adapters/provider-cli-adapter.ts +836 -1141
  201. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  202. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  203. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  204. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  205. package/src/cli-adapters/provider-cli-shared.ts +110 -11
  206. package/src/cli-adapters/pty-transport.ts +2 -1
  207. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  208. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  209. package/src/cli-adapters/resolve-executable.ts +90 -0
  210. package/src/cli-adapters/session-host-transport.ts +2 -1
  211. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  212. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  213. package/src/cli-adapters/terminal-screen.ts +16 -81
  214. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  215. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  216. package/src/commands/chat-commands-read.ts +2327 -0
  217. package/src/commands/chat-commands-scope.ts +54 -0
  218. package/src/commands/chat-commands-shared.ts +114 -0
  219. package/src/commands/chat-commands-write.ts +880 -0
  220. package/src/commands/chat-commands.ts +19 -1841
  221. package/src/commands/cli-manager.ts +513 -26
  222. package/src/commands/handler.ts +841 -2
  223. package/src/commands/high-family/index.ts +28 -0
  224. package/src/commands/high-family/mesh-coordinator-launch.ts +657 -0
  225. package/src/commands/high-family/mesh-events.ts +47 -0
  226. package/src/commands/high-family/mesh-status.ts +642 -0
  227. package/src/commands/high-family/types.ts +76 -0
  228. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  229. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  230. package/src/commands/low-family/diagnostics.ts +57 -0
  231. package/src/commands/low-family/index.ts +37 -0
  232. package/src/commands/low-family/mesh-ledger.ts +62 -0
  233. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  234. package/src/commands/low-family/notification.ts +116 -0
  235. package/src/commands/low-family/refine-config.ts +106 -0
  236. package/src/commands/low-family/session-host.ts +274 -0
  237. package/src/commands/low-family/spec-providerdev.ts +217 -0
  238. package/src/commands/low-family/status-meta.ts +112 -0
  239. package/src/commands/low-family/types.ts +39 -0
  240. package/src/commands/med-family/cli-agent.ts +230 -0
  241. package/src/commands/med-family/fast-forward.ts +230 -0
  242. package/src/commands/med-family/ide.ts +163 -0
  243. package/src/commands/med-family/index.ts +37 -0
  244. package/src/commands/med-family/mesh-crud.ts +825 -0
  245. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  246. package/src/commands/med-family/mesh-queue.ts +131 -0
  247. package/src/commands/med-family/mesh-restart.ts +92 -0
  248. package/src/commands/med-family/types.ts +120 -0
  249. package/src/commands/mesh-coordinator.ts +334 -124
  250. package/src/commands/router.ts +2395 -3206
  251. package/src/commands/stream-commands.ts +8 -0
  252. package/src/commands/upgrade-helper.ts +310 -45
  253. package/src/config/chat-history.ts +483 -24
  254. package/src/config/config.ts +12 -0
  255. package/src/config/mesh-config.ts +353 -22
  256. package/src/config/recent-activity.ts +8 -2
  257. package/src/daemon/dev-auto-implement.ts +3 -2
  258. package/src/daemon/dev-cli-debug.ts +10 -1
  259. package/src/daemon/dev-server.ts +0 -541
  260. package/src/detection/cli-detector.ts +28 -9
  261. package/src/detection/ide-detector.ts +55 -16
  262. package/src/detection/win32-ide-version.ts +106 -0
  263. package/src/git/change-impact-config.ts +354 -0
  264. package/src/git/git-commands.ts +55 -14
  265. package/src/git/git-diff.ts +81 -11
  266. package/src/git/git-executor.ts +12 -0
  267. package/src/git/git-status.ts +574 -43
  268. package/src/git/git-types.ts +14 -62
  269. package/src/git/git-worktree.ts +8 -1
  270. package/src/git/index.ts +16 -0
  271. package/src/index.ts +171 -12
  272. package/src/installer.d.ts +1 -1
  273. package/src/installer.ts +8 -6
  274. package/src/ipc/local-ipc-server.ts +278 -0
  275. package/src/launch.d.ts +1 -1
  276. package/src/launch.ts +37 -28
  277. package/src/logging/async-batch-writer.ts +55 -0
  278. package/src/logging/command-log.ts +7 -5
  279. package/src/logging/log-redactor.ts +100 -0
  280. package/src/logging/log-tail-reader.ts +341 -0
  281. package/src/logging/logger.ts +14 -7
  282. package/src/mesh/contracts.ts +338 -0
  283. package/src/mesh/coordinator-prompt.ts +381 -33
  284. package/src/mesh/coordinator-registry.ts +121 -0
  285. package/src/mesh/mesh-active-work.ts +645 -0
  286. package/src/mesh/mesh-coordinator-config.ts +97 -0
  287. package/src/mesh/mesh-delivery-policy.ts +315 -0
  288. package/src/mesh/mesh-event-classify.ts +51 -0
  289. package/src/mesh/mesh-event-forwarding.ts +1575 -0
  290. package/src/mesh/mesh-event-trace.ts +67 -0
  291. package/src/mesh/mesh-events-coordinator.ts +30 -0
  292. package/src/mesh/mesh-events-pending.ts +590 -0
  293. package/src/mesh/mesh-events-stale.ts +363 -0
  294. package/src/mesh/mesh-events-utils.ts +425 -0
  295. package/src/mesh/mesh-events.ts +30 -1035
  296. package/src/mesh/mesh-fast-forward.ts +839 -0
  297. package/src/mesh/mesh-host-ownership.ts +73 -0
  298. package/src/mesh/mesh-init.ts +260 -0
  299. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  300. package/src/mesh/mesh-ledger.ts +596 -102
  301. package/src/mesh/mesh-missions.ts +322 -0
  302. package/src/mesh/mesh-node-identity.ts +1887 -0
  303. package/src/mesh/mesh-queue-assignment.ts +1491 -0
  304. package/src/mesh/mesh-reconcile-loop.ts +1332 -0
  305. package/src/mesh/mesh-refine-batch.ts +197 -0
  306. package/src/mesh/mesh-refine-gates.ts +1652 -0
  307. package/src/mesh/mesh-refine-status.ts +231 -0
  308. package/src/mesh/mesh-review-inbox.ts +307 -0
  309. package/src/mesh/mesh-routing.ts +291 -0
  310. package/src/mesh/mesh-runtime-store.ts +1708 -0
  311. package/src/mesh/mesh-scheduling-runtime.ts +199 -0
  312. package/src/mesh/mesh-task-stats.ts +161 -0
  313. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  314. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  315. package/src/mesh/mesh-work-queue.ts +997 -141
  316. package/src/mesh/preview-freshness.ts +118 -0
  317. package/src/mesh/refine-config.ts +423 -0
  318. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  319. package/src/providers/acp-provider-instance.ts +43 -10
  320. package/src/providers/approval-utils.d.ts +5 -0
  321. package/src/providers/approval-utils.ts +57 -5
  322. package/src/providers/chat-message-normalization.ts +46 -6
  323. package/src/providers/cli-provider-instance.ts +1416 -101
  324. package/src/providers/contracts.d.ts +55 -0
  325. package/src/providers/contracts.ts +150 -6
  326. package/src/providers/extension-provider-instance.ts +12 -7
  327. package/src/providers/external-sources.ts +218 -0
  328. package/src/providers/ide-provider-instance.ts +35 -12
  329. package/src/providers/manual-attendance.ts +85 -0
  330. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  331. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  332. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  333. package/src/providers/native-history/constants.ts +19 -0
  334. package/src/providers/native-history/dispatcher.ts +339 -0
  335. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  336. package/src/providers/native-history/index.ts +30 -0
  337. package/src/providers/provider-instance-manager.ts +30 -0
  338. package/src/providers/provider-instance.ts +19 -1
  339. package/src/providers/provider-loader.ts +668 -50
  340. package/src/providers/provider-schema.ts +87 -14
  341. package/src/providers/provider-trust.ts +114 -0
  342. package/src/providers/read-chat-contract.ts +76 -16
  343. package/src/providers/sdk/README.md +49 -0
  344. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  345. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  346. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  347. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  348. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  349. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  350. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  351. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  352. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  353. package/src/providers/sdk/v1/index.ts +152 -0
  354. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  355. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  356. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  357. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  358. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  359. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  360. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  361. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  362. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  363. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  364. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  365. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  366. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  367. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  368. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  369. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  370. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  374. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  375. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  376. package/src/providers/sdk/v1/validators/index.ts +19 -0
  377. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  378. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  379. package/src/providers/spec/adapter.ts +235 -0
  380. package/src/providers/spec/cli-adapter.ts +1051 -0
  381. package/src/providers/spec/evaluator.ts +407 -0
  382. package/src/providers/spec/fsm-driver.ts +1292 -0
  383. package/src/providers/spec/fsm-evaluator.ts +272 -0
  384. package/src/providers/spec/fsm-loader.ts +120 -0
  385. package/src/providers/spec/fsm-types.ts +273 -0
  386. package/src/providers/spec/native-history-executor.ts +1128 -0
  387. package/src/providers/spec/pre-launch-trust.ts +104 -0
  388. package/src/providers/spec/route.ts +51 -0
  389. package/src/providers/spec/types.ts +262 -0
  390. package/src/providers/status-monitor.d.ts +7 -7
  391. package/src/providers/status-monitor.ts +37 -22
  392. package/src/providers/transcript-v2.ts +567 -0
  393. package/src/providers/types/interactive-prompt.ts +536 -0
  394. package/src/providers/version-archive.ts +64 -24
  395. package/src/providers/working-dir.ts +23 -0
  396. package/src/repo-mesh-types.ts +542 -14
  397. package/src/runtime-defaults.ts +39 -0
  398. package/src/sessions/registry.ts +6 -0
  399. package/src/shared-types-extra.ts +2 -4
  400. package/src/shared-types.d.ts +8 -0
  401. package/src/shared-types.ts +64 -1
  402. package/src/status/builders.ts +26 -6
  403. package/src/status/normalize.ts +2 -0
  404. package/src/status/reporter.ts +19 -1
  405. package/src/status/snapshot.ts +95 -26
  406. package/src/system/hash.ts +23 -0
  407. package/src/system/host-memory.ts +29 -12
  408. package/src/system/load-better-sqlite3.ts +68 -0
  409. package/src/types.ts +5 -0
  410. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  411. package/dist/mesh/mesh-sync.d.ts +0 -53
  412. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  413. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  414. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,825 @@
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 } from '@adhdev/mesh-shared';
13
+ import { resolveMeshHostStatus, normalizeMeshDaemonRole } from '../../mesh/mesh-host-ownership.js';
14
+ import {
15
+ loadMeshWorktreeBootstrapConfig,
16
+ runMeshWorktreeBootstrap,
17
+ type WorktreeBootstrapState,
18
+ } from '../../mesh/worktree-bootstrap-config.js';
19
+ import { handleMeshForwardEvent, queuePendingMeshCoordinatorEvent } from '../../mesh/mesh-events.js';
20
+ import { loadConfig } from '../../config/config.js';
21
+ import {
22
+ hydrateInlineMeshDirectTruth,
23
+ normalizeProviderRoles,
24
+ readMeshNodeMachineId,
25
+ } from '../router.js';
26
+ import type { CommandRouterResult } from '../router.js';
27
+ import type { MedFamilyContext, MedFamilyHandler } from './types.js';
28
+
29
+ export const meshCrudHandlers: Record<string, MedFamilyHandler> = {
30
+ list_meshes: async (_ctx: MedFamilyContext, _args: any) => {
31
+ try {
32
+ const { listMeshes } = await import('../../config/mesh-config.js');
33
+ return { success: true, meshes: listMeshes() };
34
+ } catch (e: any) {
35
+ return { success: false, error: e.message };
36
+ }
37
+ },
38
+
39
+ get_mesh: async (ctx: MedFamilyContext, args: any) => {
40
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
41
+ if (!meshId) return { success: false, error: 'meshId required' };
42
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
43
+ if (!meshRecord?.mesh) return { success: false, error: 'Mesh not found' };
44
+
45
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
46
+ // Only an explicit refresh fans out a blocking peer probe.
47
+ // Default loads are satisfied from held standing-state git truth.
48
+ const probeRemotePeers = args?.refresh === true || args?.forceRefresh === true;
49
+ const directTruth = await hydrateInlineMeshDirectTruth({
50
+ mesh: meshRecord.mesh,
51
+ meshSource: meshRecord.source,
52
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
53
+ getMeshPeerConnectionStatus: ctx.deps.getMeshPeerConnectionStatus,
54
+ statusInstanceId: ctx.deps.statusInstanceId,
55
+ localMachineId: loadConfig().machineId || '',
56
+ probeRemotePeers,
57
+ probeCache: ctx.meshGitProbeCache,
58
+ });
59
+ const directTruthSatisfied = meshRecord.source !== 'inline_bootstrap' || directTruth.directEvidenceCount > 0;
60
+ const sourceOfTruth = {
61
+ membership: meshRecord.source === 'inline_cache'
62
+ ? 'coordinator_inline_mesh_cache'
63
+ : meshRecord.source === 'local_config'
64
+ ? 'local_mesh_config'
65
+ : 'inline_bootstrap_snapshot',
66
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
67
+ directPeerTruth: {
68
+ required: requireDirectPeerTruth,
69
+ satisfied: directTruthSatisfied,
70
+ directEvidenceCount: directTruth.directEvidenceCount,
71
+ localConfirmedCount: directTruth.localConfirmedCount,
72
+ peerAttemptedCount: directTruth.peerAttemptedCount,
73
+ peerConfirmedCount: directTruth.peerConfirmedCount,
74
+ unavailableNodeIds: directTruth.unavailableNodeIds,
75
+ },
76
+ };
77
+ if (requireDirectPeerTruth && !directTruthSatisfied) {
78
+ return {
79
+ success: false,
80
+ code: 'mesh_direct_peer_truth_unavailable',
81
+ error: 'Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.',
82
+ sourceOfTruth,
83
+ };
84
+ }
85
+ return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
86
+ },
87
+
88
+ create_mesh: async (_ctx: MedFamilyContext, args: any) => {
89
+ const name = typeof args?.name === 'string' ? args.name.trim() : '';
90
+ const repoIdentity = typeof args?.repoIdentity === 'string' ? args.repoIdentity.trim() : '';
91
+ const repoRemoteUrl = typeof args?.repoRemoteUrl === 'string' ? args.repoRemoteUrl.trim() : undefined;
92
+ const defaultBranch = typeof args?.defaultBranch === 'string' ? args.defaultBranch.trim() : undefined;
93
+ if (!name) return { success: false, error: 'name required' };
94
+ try {
95
+ const { createMesh } = await import('../../config/mesh-config.js');
96
+ const meshHost = args?.meshHost && typeof args.meshHost === 'object' && !Array.isArray(args.meshHost)
97
+ ? args.meshHost
98
+ : undefined;
99
+ const mesh = createMesh({ name, repoIdentity, repoRemoteUrl, defaultBranch, policy: args?.policy, meshHost });
100
+ return { success: true, mesh };
101
+ } catch (e: any) {
102
+ return { success: false, error: e.message };
103
+ }
104
+ },
105
+
106
+ update_mesh: async (ctx: MedFamilyContext, args: any) => {
107
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
108
+ if (!meshId) return { success: false, error: 'meshId required' };
109
+ try {
110
+ const { updateMesh } = await import('../../config/mesh-config.js');
111
+ const patch: Record<string, unknown> = {};
112
+ if (typeof args?.name === 'string') patch.name = args.name;
113
+ if (typeof args?.defaultBranch === 'string') patch.defaultBranch = args.defaultBranch;
114
+ if (args?.policy && typeof args.policy === 'object' && !Array.isArray(args.policy)) patch.policy = args.policy;
115
+ if (args?.coordinator && typeof args.coordinator === 'object' && !Array.isArray(args.coordinator)) patch.coordinator = args.coordinator;
116
+ if (args?.meshHost && typeof args.meshHost === 'object' && !Array.isArray(args.meshHost)) patch.meshHost = args.meshHost;
117
+ if (!Object.keys(patch).length) return { success: false, error: 'No updates provided' };
118
+ const mesh = updateMesh(meshId, patch as any);
119
+ if (!mesh) return { success: false, error: 'Mesh not found' };
120
+ ctx.inlineMeshCache.set(meshId, mesh);
121
+ ctx.invalidateAggregateMeshStatus(meshId);
122
+ return { success: true, mesh };
123
+ } catch (e: any) {
124
+ return { success: false, error: e.message };
125
+ }
126
+ },
127
+
128
+ delete_mesh: async (_ctx: MedFamilyContext, args: any) => {
129
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
130
+ if (!meshId) return { success: false, error: 'meshId required' };
131
+ try {
132
+ const { deleteMesh } = await import('../../config/mesh-config.js');
133
+ const deleted = deleteMesh(meshId);
134
+ return { success: true, deleted };
135
+ } catch (e: any) {
136
+ return { success: false, error: e.message };
137
+ }
138
+ },
139
+
140
+ add_mesh_node: async (ctx: MedFamilyContext, args: any) => {
141
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
142
+ const workspace = typeof args?.workspace === 'string' ? args.workspace.trim() : '';
143
+ if (!meshId) return { success: false, error: 'meshId required' };
144
+ if (!workspace) return { success: false, error: 'workspace required' };
145
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node addition');
146
+ if (ownerFailure) return ownerFailure;
147
+ try {
148
+ const { addNode } = await import('../../config/mesh-config.js');
149
+ const providerPriority = Array.isArray(args?.providerPriority)
150
+ ? args.providerPriority.map((type: any) => typeof type === 'string' ? type.trim() : '').filter(Boolean)
151
+ : [];
152
+ const readOnly = args?.readOnly === true;
153
+ const providerRoles = normalizeProviderRoles(args?.providerRoles);
154
+ const policy = {
155
+ ...(readOnly ? { readOnly: true } : {}),
156
+ ...(providerPriority.length ? { providerPriority } : {}),
157
+ ...(providerRoles.length ? { providerRoles } : {}),
158
+ };
159
+ const role = normalizeMeshDaemonRole(args?.role);
160
+ const daemonId = typeof args?.daemonId === 'string' && args.daemonId.trim() ? args.daemonId.trim() : undefined;
161
+ const machineId = typeof args?.machineId === 'string' && args.machineId.trim() ? args.machineId.trim() : undefined;
162
+ const repoRoot = typeof args?.repoRoot === 'string' && args.repoRoot.trim() ? args.repoRoot.trim() : undefined;
163
+ const node = addNode(meshId, {
164
+ workspace,
165
+ ...(repoRoot ? { repoRoot } : {}),
166
+ ...(daemonId ? { daemonId } : {}),
167
+ ...(machineId ? { machineId } : {}),
168
+ ...(policy ? { policy } : {}),
169
+ ...(role ? { role } : {}),
170
+ });
171
+ if (!node) return { success: false, error: 'Mesh not found' };
172
+ // mesh_status hands back a coordinator-memory aggregate
173
+ // snapshot keyed on (meshId, queueRevision). Adding a
174
+ // node touches neither, so without an explicit cache
175
+ // bust the dashboard graph keeps rendering the pre-add
176
+ // node list (empty for a fresh mesh) even after the
177
+ // user clicks Refresh.
178
+ ctx.invalidateAggregateMeshStatus(meshId);
179
+ return { success: true, node };
180
+ } catch (e: any) {
181
+ return { success: false, error: e.message };
182
+ }
183
+ },
184
+
185
+ update_mesh_node: async (ctx: MedFamilyContext, args: any) => {
186
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
187
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
188
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
189
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node update');
190
+ if (ownerFailure) return ownerFailure;
191
+ try {
192
+ const { updateNode } = await import('../../config/mesh-config.js');
193
+ const policy = args?.policy && typeof args.policy === 'object' && !Array.isArray(args.policy)
194
+ ? { ...(args.policy as Record<string, unknown>) }
195
+ : {};
196
+ if (Array.isArray(args?.providerPriority)) {
197
+ const providerPriority = args.providerPriority
198
+ .map((type: any) => typeof type === 'string' ? type.trim() : '')
199
+ .filter(Boolean);
200
+ delete (policy as any).provider_priority;
201
+ if (providerPriority.length) {
202
+ (policy as any).providerPriority = providerPriority;
203
+ } else {
204
+ delete (policy as any).providerPriority;
205
+ }
206
+ }
207
+ // providerRoles: per-(node, provider) role label + maxParallel cap.
208
+ // Passing an explicit (possibly empty) array clears/replaces the
209
+ // declarations; omitting the arg leaves any value already on policy
210
+ // untouched (a full policy object passed by the caller still carries it).
211
+ if (Array.isArray(args?.providerRoles)) {
212
+ const providerRoles = normalizeProviderRoles(args.providerRoles);
213
+ if (providerRoles.length) {
214
+ (policy as any).providerRoles = providerRoles;
215
+ } else {
216
+ delete (policy as any).providerRoles;
217
+ }
218
+ }
219
+ const patch: Record<string, unknown> = { policy: policy as any };
220
+ if (typeof args?.systemPrompt === 'string') {
221
+ const trimmed = (args.systemPrompt as string).trim();
222
+ patch.systemPrompt = trimmed || undefined;
223
+ } else if (args?.systemPrompt === null) {
224
+ patch.systemPrompt = undefined;
225
+ }
226
+ const node = updateNode(meshId, nodeId, patch as any);
227
+ if (!node) return { success: false, error: 'Mesh node not found' };
228
+ // Provider priority / systemPrompt changes don't touch
229
+ // the queue revision, so without a manual bust the
230
+ // cached aggregate keeps surfacing pre-update values
231
+ // (priority chip, coordinator prompt preview, etc.).
232
+ ctx.invalidateAggregateMeshStatus(meshId);
233
+ return { success: true, node };
234
+ } catch (e: any) {
235
+ return { success: false, error: e.message };
236
+ }
237
+ },
238
+
239
+ cleanup_mesh_sessions: async (ctx: MedFamilyContext, args: any) => {
240
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
241
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
242
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
243
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node removal');
244
+ if (ownerFailure) return ownerFailure;
245
+ try {
246
+ // preferInline so inline-cache-only clone nodes resolve (matches owner check above).
247
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
248
+ const mesh = meshRecord?.mesh;
249
+ if (!mesh) return { success: false, error: 'Mesh not found' };
250
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
251
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
252
+ const mode = ctx.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
253
+ const sessionIds = Array.isArray(args?.sessionIds)
254
+ ? args.sessionIds.map((id: any) => typeof id === 'string' ? id.trim() : '').filter(Boolean)
255
+ : undefined;
256
+ const result = await ctx.cleanupMeshSessions({
257
+ meshId,
258
+ nodeId,
259
+ node,
260
+ mode,
261
+ sessionIds,
262
+ dryRun: args?.dryRun === true,
263
+ source: 'mesh_cleanup_sessions',
264
+ });
265
+ return result;
266
+ } catch (e: any) {
267
+ return { success: false, error: e.message };
268
+ }
269
+ },
270
+
271
+ remove_mesh_node: async (ctx: MedFamilyContext, args: any) => {
272
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
273
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
274
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
275
+ try {
276
+ // preferInline so removal can resolve inline-cache-only clone worktree nodes.
277
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
278
+ const mesh = meshRecord?.mesh;
279
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
280
+
281
+ // Guard: refuse to remove the coordinator's OWN local base node
282
+ // (same machine, NOT a worktree). Removing it breaks live mesh
283
+ // membership — the coordinator can no longer be reached and has
284
+ // to be restarted. Worktree clones are always safe to remove;
285
+ // only the non-worktree node bound to this daemon is protected.
286
+ // An explicit force:true overrides for intentional mesh teardown.
287
+ if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
288
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : '';
289
+ const nodeMachineId = readMeshNodeMachineId(node as Record<string, unknown>) || '';
290
+ const selfDaemonId = ctx.deps.statusInstanceId || '';
291
+ const selfMachineId = (() => { try { return loadConfig().machineId || ''; } catch { return ''; } })();
292
+ // Identity match is form-safe: a daemon answers to the same machine
293
+ // under interchangeable id forms (bare `mach_X`, cloud `daemon_mach_X`,
294
+ // standalone `standalone_mach_X`). statusInstanceId/loadConfig().machineId
295
+ // and the node's stored daemonId/machineId frequently hold DIFFERENT forms
296
+ // of the same machine, so a raw `===` would miss the self-match and let the
297
+ // coordinator delete its own live base node (the very accident this guard
298
+ // exists to prevent). daemonIdsEquivalent collapses every form to its
299
+ // machine core before comparing, so a same-machine match is caught
300
+ // regardless of which form each side carries. This only widens matches
301
+ // (every raw-`===` hit still matches) — fail-open → fail-closed.
302
+ const isCoordinatorBaseNode =
303
+ (!!selfDaemonId && (daemonIdsEquivalent(nodeDaemonId, selfDaemonId) || daemonIdsEquivalent(nodeMachineId, selfDaemonId)))
304
+ || (!!selfMachineId && (daemonIdsEquivalent(nodeDaemonId, selfMachineId) || daemonIdsEquivalent(nodeMachineId, selfMachineId)));
305
+ if (isCoordinatorBaseNode) {
306
+ return {
307
+ success: false,
308
+ removed: false,
309
+ code: 'mesh_remove_coordinator_base_node_protected',
310
+ error: `Refusing to remove the coordinator's own base node '${typeof node.workspace === 'string' ? node.workspace : nodeId}'. `
311
+ + `It is the local non-worktree node bound to this coordinator daemon; removing it breaks live mesh membership and forces a restart.`,
312
+ 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.',
313
+ };
314
+ }
315
+ }
316
+
317
+ // Default worktree session cleanup ON: when the caller OMITS a mode and the
318
+ // node is a local worktree, default to 'stop_and_delete' instead of the mesh
319
+ // policy ('preserve' by default). A worktree's chat session has no reason to
320
+ // outlive the worktree's node + directory + branch, and leaving it on
321
+ // 'preserve' is what orphaned chats after a worktree remove. An explicit mode
322
+ // (including an explicit 'preserve') is always honored — only the OMITTED case
323
+ // changes, and only for worktrees. Base nodes keep arg ?? policy ?? preserve.
324
+ const explicitCleanupMode = args?.sessionCleanupMode ?? args?.session_cleanup_mode;
325
+ const sessionCleanupMode = ctx.normalizeMeshSessionCleanupMode(
326
+ explicitCleanupMode
327
+ ?? (node?.isLocalWorktree === true ? 'stop_and_delete' : undefined)
328
+ ?? mesh?.policy?.sessionCleanupOnNodeRemove,
329
+ );
330
+ // Explicit sessionIds (e.g. supplied by refine auto-cleanup) bypass the
331
+ // workspace-only-match guard so a delegate session that lacks a
332
+ // meta.meshNodeId binding can still be stopped/deleted.
333
+ const explicitSessionIds = Array.isArray(args?.sessionIds)
334
+ ? (args.sessionIds as unknown[]).filter((v): v is string => typeof v === 'string' && v.trim().length > 0).map(v => v.trim())
335
+ : undefined;
336
+ let sessionCleanup: Record<string, unknown> | undefined;
337
+ if (node && sessionCleanupMode !== 'preserve') {
338
+ sessionCleanup = await ctx.cleanupMeshSessions({
339
+ meshId,
340
+ nodeId,
341
+ node,
342
+ mode: sessionCleanupMode,
343
+ ...(explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {}),
344
+ source: 'mesh_remove_node',
345
+ });
346
+ if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
347
+ }
348
+
349
+ let worktreeCleanup: Record<string, unknown> | undefined;
350
+ if (node?.isLocalWorktree) {
351
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
352
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
353
+ // clean up locally, do not forward. Equivalent → local.
354
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
355
+ && !args?._meshDirectDispatch;
356
+ if (isRemoteWorktree) {
357
+ // Worktree lives on a different machine — ask that daemon to clean it up.
358
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
359
+ const forwarded = await ctx.deps.dispatchMeshCommand!(nodeDaemonId!, 'remove_mesh_node', {
360
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
361
+ _meshDirectDispatch: true,
362
+ });
363
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
364
+ }
365
+ const cleanupResult = await ctx.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
366
+ // De-gating: membership removal is NOT gated on the worktree
367
+ // directory actually being deleted. cleanupLocalWorktreeNode now
368
+ // returns success:true (with a residue flag) whenever the path is
369
+ // proven managed and the only remaining problem is leftover
370
+ // directory bytes (e.g. Windows EINVAL). A success:false here means
371
+ // a genuinely-unsafe condition — missing metadata, a non-managed /
372
+ // unexpected path, a branch mismatch, a dirty worktree, or an
373
+ // unverified force fallback — and those still block removal.
374
+ if (cleanupResult.success === false) {
375
+ return {
376
+ success: false,
377
+ removed: false,
378
+ code: cleanupResult.code,
379
+ error: cleanupResult.error,
380
+ recoveryHint: cleanupResult.recoveryHint,
381
+ ...(sessionCleanup ? { sessionCleanup } : {}),
382
+ worktreeCleanup: cleanupResult,
383
+ };
384
+ }
385
+ worktreeCleanup = cleanupResult;
386
+ }
387
+
388
+ let removed = false;
389
+ if (meshRecord?.inline) {
390
+ removed = ctx.removeInlineMeshNode(meshId, mesh, nodeId);
391
+ // Inline meshes share the same aggregate snapshot cache as
392
+ // local-config meshes; without this bust the removed node
393
+ // keeps showing up in the dashboard graph until the cache
394
+ // ages out on its own.
395
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
396
+ // Node was already absent from the inline mesh (e.g. removed by a
397
+ // prior refine cleanup). Treat as removed so caller gets removed:true.
398
+ if (!removed && !node) removed = true;
399
+ } else {
400
+ const { removeNode } = await import('../../config/mesh-config.js');
401
+ removed = removeNode(meshId, nodeId);
402
+ // Node already absent from config (e.g. removed by a prior refine
403
+ // cleanup after a successful Refinery merge). Treat as removed so
404
+ // the response is accurate.
405
+ if (!removed && !node) removed = true;
406
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
407
+ }
408
+
409
+ // Record in task ledger
410
+ if (removed) {
411
+ try {
412
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
413
+ appendLedgerEntry(meshId, {
414
+ kind: 'node_removed',
415
+ nodeId,
416
+ payload: {
417
+ worktree: !!node?.isLocalWorktree,
418
+ sessionCleanupMode,
419
+ workspace: typeof node?.workspace === 'string' ? node.workspace : undefined,
420
+ daemonId: typeof node?.daemonId === 'string' ? node.daemonId : undefined,
421
+ worktreeBranch: typeof node?.worktreeBranch === 'string' ? node.worktreeBranch : undefined,
422
+ worktreeCleanupFallback: typeof worktreeCleanup?.fallback === 'string' ? worktreeCleanup.fallback : undefined,
423
+ forced: worktreeCleanup?.forced === true ? true : undefined,
424
+ forceFallbackReason: typeof worktreeCleanup?.reason === 'string' ? worktreeCleanup.reason : undefined,
425
+ },
426
+ });
427
+ } catch { /* ledger append is best-effort */ }
428
+ }
429
+
430
+ // Surface leftover-directory residue at the top level so callers
431
+ // see the node was dropped from the mesh even though the worktree
432
+ // directory could not be fully removed (best-effort, non-gating).
433
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === 'string'
434
+ ? worktreeCleanup.residueWarning
435
+ : undefined;
436
+
437
+ // Orphan guard: if the session cleanup still left any LIVE session skipped
438
+ // (e.g. a future skip reason, or a workspace-only session on a base node),
439
+ // surface it at the top level so the caller knows a manual mesh_cleanup_sessions
440
+ // is still required for those sessionIds. Without this, a skipped-live session
441
+ // silently outlives a removed node (the very NODE-REMOVE-SESSION-ORPHAN bug).
442
+ const skippedLiveSessionIds = Array.isArray(sessionCleanup?.skippedLiveSessionIds)
443
+ ? (sessionCleanup!.skippedLiveSessionIds as unknown[]).filter((v): v is string => typeof v === 'string')
444
+ : [];
445
+ const orphanedSessionsRemaining = skippedLiveSessionIds.length > 0;
446
+ const orphanNextAction = orphanedSessionsRemaining
447
+ ? `Live session(s) [${skippedLiveSessionIds.join(', ')}] were skipped and still survive this node removal. `
448
+ + `Run mesh_cleanup_sessions with mode:'stop_and_delete' and sessionIds:[${skippedLiveSessionIds.map(id => `'${id}'`).join(', ')}] to release them.`
449
+ : undefined;
450
+ return {
451
+ success: true,
452
+ removed,
453
+ ...(residueWarning ? { residueWarning } : {}),
454
+ ...(sessionCleanup ? { sessionCleanup } : {}),
455
+ ...(worktreeCleanup ? { worktreeCleanup } : {}),
456
+ ...(orphanedSessionsRemaining
457
+ ? { orphanedSessionsRemaining: true, nextAction: orphanNextAction }
458
+ : {}),
459
+ };
460
+ } catch (e: any) {
461
+ return { success: false, error: e.message };
462
+ }
463
+ },
464
+
465
+ clone_mesh_node: async (ctx: MedFamilyContext, args: any) => {
466
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
467
+ const sourceNodeId = typeof args?.sourceNodeId === 'string' ? args.sourceNodeId.trim() : '';
468
+ const branch = typeof args?.branch === 'string' ? args.branch.trim() : '';
469
+ const baseBranch = typeof args?.baseBranch === 'string' ? args.baseBranch.trim() : undefined;
470
+ if (!meshId) return { success: false, error: 'meshId required' };
471
+ if (!sourceNodeId) return { success: false, error: 'sourceNodeId required' };
472
+ if (!branch) return { success: false, error: 'branch required' };
473
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'worktree clone');
474
+ if (ownerFailure) return ownerFailure;
475
+
476
+ try {
477
+ // Resolve with preferInline so the clone writes the new node into the
478
+ // same representation that get_mesh reads back. The MCP coordinator
479
+ // passes inlineMesh on every mesh command, so when it owns an inline
480
+ // mesh the membership read path (get_mesh, preferInline: true) returns
481
+ // the inline cache. Without preferInline here, clone could resolve to a
482
+ // local-config mesh and write the node only to config — leaving the
483
+ // inline cache (and therefore get_mesh / refreshMeshFromDaemon) without
484
+ // the node, so the new worktree node is never visible in live mesh
485
+ // membership even though worktree_bootstrap_complete fires.
486
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
487
+ const mesh = meshRecord?.mesh;
488
+ if (!mesh) return { success: false, error: 'Mesh not found' };
489
+
490
+ const sourceNode = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, sourceNodeId));
491
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
492
+
493
+ // Forward to the source node's daemon if it's on a different machine.
494
+ // _meshDirectDispatch prevents infinite re-forwarding when the stored daemonId
495
+ // uses a legacy format that doesn't match the receiving daemon's statusInstanceId.
496
+ const sourceDaemonId = typeof sourceNode.daemonId === 'string' ? sourceNode.daemonId.trim() : undefined;
497
+ // daemonIdsEquivalent: an equivalent-form source daemonId is this machine —
498
+ // clone locally, do not forward. Equivalent → local.
499
+ if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
500
+ && !args?._meshDirectDispatch) {
501
+ const forwarded = await ctx.deps.dispatchMeshCommand(sourceDaemonId, 'clone_mesh_node', {
502
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
503
+ _meshDirectDispatch: true,
504
+ });
505
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
506
+ }
507
+
508
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
509
+ const { createWorktree } = await import('../../git/git-worktree.js');
510
+ const result = await createWorktree({
511
+ repoRoot,
512
+ branch,
513
+ baseBranch,
514
+ meshName: mesh.name,
515
+ });
516
+
517
+ let node: any;
518
+ if (meshRecord.inline) {
519
+ const { randomUUID } = await import('crypto');
520
+ node = {
521
+ id: `node_${randomUUID().replace(/-/g, '')}`,
522
+ workspace: result.worktreePath,
523
+ repoRoot: result.worktreePath,
524
+ daemonId: sourceNode.daemonId,
525
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
526
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
527
+ policy: { ...(sourceNode.policy || {}) },
528
+ isLocalWorktree: true,
529
+ worktreeBranch: result.branch,
530
+ clonedFromNodeId: sourceNodeId,
531
+ };
532
+ ctx.updateInlineMeshNode(meshId, mesh, node);
533
+ } else {
534
+ const { addNode } = await import('../../config/mesh-config.js');
535
+ node = addNode(meshId, {
536
+ workspace: result.worktreePath,
537
+ repoRoot: result.worktreePath,
538
+ daemonId: sourceNode.daemonId,
539
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
540
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
541
+ isLocalWorktree: true,
542
+ worktreeBranch: result.branch,
543
+ clonedFromNodeId: sourceNodeId,
544
+ policy: { ...(sourceNode.policy || {}) },
545
+ });
546
+ if (!node) return { success: false, error: 'Failed to register worktree node' };
547
+ // Also reconcile the freshly-registered node into any warmed inline
548
+ // cache for this mesh. get_mesh (preferInline: true) reads the inline
549
+ // cache first when one exists; if we only wrote to local config the
550
+ // node would be invisible to membership reads. updateInlineMeshNode is
551
+ // a no-op when no inline cache is present.
552
+ const inlineForReconcile = ctx.getCachedInlineMesh(meshId);
553
+ if (inlineForReconcile) ctx.updateInlineMeshNode(meshId, inlineForReconcile, node);
554
+ ctx.invalidateAggregateMeshStatus(meshId);
555
+ }
556
+
557
+ const persistWorktreeSetupState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
558
+ node.worktreeBootstrap = bootstrapState;
559
+ if (meshRecord.inline) {
560
+ ctx.updateInlineMeshNode(meshId, mesh, node);
561
+ return;
562
+ }
563
+ try {
564
+ const { updateNode } = await import('../../config/mesh-config.js');
565
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
566
+ ctx.invalidateAggregateMeshStatus(meshId);
567
+ } catch { /* bootstrap status persistence is best-effort */ }
568
+ };
569
+
570
+ const appendCloneLedger = async (initSubmodules: boolean, bootstrapState: WorktreeBootstrapState): Promise<void> => {
571
+ try {
572
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
573
+ appendLedgerEntry(meshId, {
574
+ kind: 'node_cloned',
575
+ nodeId: node.id,
576
+ payload: {
577
+ sourceNodeId,
578
+ branch: result.branch,
579
+ worktreePath: result.worktreePath,
580
+ submodulesInitialized: initSubmodules,
581
+ worktreeBootstrap: {
582
+ status: bootstrapState.status,
583
+ required: bootstrapState.required,
584
+ configSource: bootstrapState.configSource,
585
+ configSourceType: bootstrapState.configSourceType,
586
+ lastCommand: bootstrapState.lastCommand,
587
+ exitCode: bootstrapState.exitCode,
588
+ },
589
+ },
590
+ });
591
+ } catch { /* ledger append is best-effort */ }
592
+ };
593
+
594
+ const initSubmodules = (sourceNode.policy as any)?.initSubmodulesOnClone !== false;
595
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
596
+ const runningBootstrapState: WorktreeBootstrapState = {
597
+ status: 'running',
598
+ required: loadedBootstrap.config?.required !== false,
599
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
600
+ configSourceType: loadedBootstrap.sourceType,
601
+ startedAt: new Date().toISOString(),
602
+ };
603
+ await persistWorktreeSetupState(runningBootstrapState);
604
+
605
+ const finishWorktreeSetup = async (): Promise<{ submodulesInitialized: boolean; bootstrapState: WorktreeBootstrapState }> => {
606
+ let submodulesInitialized = false;
607
+ if (initSubmodules) {
608
+ try {
609
+ const { runGit } = await import('../../git/git-executor.js');
610
+ await runGit(
611
+ { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
612
+ ['submodule', 'update', '--init', '--recursive'],
613
+ { timeoutMs: 120000 },
614
+ );
615
+ submodulesInitialized = true;
616
+
617
+ // Sync oss submodule to source node HEAD (best-effort)
618
+ const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
619
+ if (sourceWorkspace) {
620
+ try {
621
+ const { runGit: rg } = await import('../../git/git-executor.js');
622
+ const sourceCtx = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
623
+ const worktreeCtx = { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true };
624
+
625
+ // Read source node's oss submodule SHA
626
+ const sourceStatusOut = await rg(sourceCtx, ['submodule', 'status', 'oss'], { timeoutMs: 10000 });
627
+ const sourceStatusLine = (typeof sourceStatusOut === 'string' ? sourceStatusOut : (sourceStatusOut as any)?.stdout ?? '').trim();
628
+ const sourceShaMatch = sourceStatusLine.match(/^[+\- ]?([0-9a-f]{40})/);
629
+ const sourceSha = sourceShaMatch?.[1];
630
+
631
+ if (sourceSha) {
632
+ // Read worktree's current oss HEAD
633
+ const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
634
+ const worktreeOssHeadOut = await rg(ossCtx, ['rev-parse', 'HEAD'], { timeoutMs: 10000 });
635
+ const worktreeOssSha = (typeof worktreeOssHeadOut === 'string' ? worktreeOssHeadOut : (worktreeOssHeadOut as any)?.stdout ?? '').trim();
636
+
637
+ if (worktreeOssSha !== sourceSha) {
638
+ // Fetch target SHA from source node's oss directory
639
+ await rg(ossCtx, ['fetch', `${sourceWorkspace}/oss`, 'HEAD'], { timeoutMs: 60000 });
640
+ await rg(ossCtx, ['checkout', sourceSha], { timeoutMs: 10000 });
641
+ await rg(worktreeCtx, ['add', 'oss'], { timeoutMs: 10000 });
642
+ await rg(worktreeCtx, ['commit', '-m', 'chore: sync oss to source node HEAD on clone'], { timeoutMs: 10000 });
643
+ console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
644
+ }
645
+ }
646
+ } catch (ossErr: any) {
647
+ console.warn('[mesh] oss submodule sync to source HEAD failed (best-effort):', ossErr.message);
648
+ }
649
+ }
650
+ } catch (subErr: any) {
651
+ // Submodule init is best-effort; don't fail the clone
652
+ console.warn('[mesh] Submodule init failed for worktree:', subErr.message);
653
+ }
654
+ }
655
+ const bootstrapState: WorktreeBootstrapState = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
656
+ await persistWorktreeSetupState(bootstrapState);
657
+ await appendCloneLedger(submodulesInitialized, bootstrapState);
658
+ return { submodulesInitialized, bootstrapState };
659
+ };
660
+
661
+ const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8000);
662
+ const setupWaitMs = Number.isFinite(requestedSetupWaitMs)
663
+ ? Math.min(Math.max(requestedSetupWaitMs, 0), 14000)
664
+ : 8000;
665
+ const setupPromise = finishWorktreeSetup();
666
+ const setupResult = await Promise.race([
667
+ setupPromise.then((value) => ({ completed: true as const, value })),
668
+ new Promise<{ completed: false }>((resolve) => setTimeout(() => resolve({ completed: false }), setupWaitMs)),
669
+ ]);
670
+
671
+ const emitBootstrapEvent = (eventStatus: 'bootstrap_complete' | 'bootstrap_failed', bootstrapState: WorktreeBootstrapState, startedAtMs: number, extraPayload?: Record<string, unknown>): void => {
672
+ try {
673
+ const durationMs = Date.now() - startedAtMs;
674
+ const event = `worktree_${eventStatus}` as const;
675
+ const metadataEvent = {
676
+ source: 'clone_mesh_node_bootstrap',
677
+ nodeId: node.id,
678
+ status: eventStatus,
679
+ worktreePath: result.worktreePath,
680
+ durationMs,
681
+ bootstrapStatus: bootstrapState.status,
682
+ ...(bootstrapState.error ? { error: bootstrapState.error } : {}),
683
+ ...(bootstrapState.exitCode !== undefined ? { exitCode: bootstrapState.exitCode } : {}),
684
+ ...(extraPayload || {}),
685
+ };
686
+ if (typeof ctx.deps.instanceManager?.getByCategory === 'function') {
687
+ const forwarded = handleMeshForwardEvent(
688
+ { instanceManager: ctx.deps.instanceManager } as any,
689
+ { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent },
690
+ );
691
+ if (forwarded?.success === true) return;
692
+ }
693
+ queuePendingMeshCoordinatorEvent({
694
+ event,
695
+ meshId,
696
+ nodeLabel: node.id,
697
+ nodeId: node.id,
698
+ workspace: result.worktreePath,
699
+ metadataEvent,
700
+ queuedAt: Date.now(),
701
+ });
702
+ } catch { /* event emission is best-effort */ }
703
+ };
704
+
705
+ const bootstrapStartedMs = Date.now();
706
+
707
+ if (!setupResult.completed) {
708
+ setupPromise
709
+ .then(({ bootstrapState }) => {
710
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
711
+ })
712
+ .catch((error: any) => {
713
+ const failedState: WorktreeBootstrapState = {
714
+ ...runningBootstrapState,
715
+ status: 'failed',
716
+ completedAt: new Date().toISOString(),
717
+ error: error?.message || String(error),
718
+ };
719
+ void persistWorktreeSetupState(failedState);
720
+ void appendCloneLedger(false, failedState);
721
+ emitBootstrapEvent('bootstrap_failed', failedState, bootstrapStartedMs, { error: error?.message || String(error) });
722
+ });
723
+ return {
724
+ success: true,
725
+ async: true,
726
+ status: 'accepted',
727
+ node,
728
+ worktreePath: result.worktreePath,
729
+ branch: result.branch,
730
+ worktreeBootstrap: runningBootstrapState,
731
+ worktreeSetup: {
732
+ status: 'running',
733
+ setupWaitMs,
734
+ message: 'Worktree node is registered; submodule/bootstrap setup is continuing in the background.',
735
+ },
736
+ };
737
+ }
738
+
739
+ const { submodulesInitialized, bootstrapState } = setupResult.value;
740
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
741
+ return {
742
+ success: true,
743
+ node,
744
+ worktreePath: result.worktreePath,
745
+ branch: result.branch,
746
+ submodulesInitialized,
747
+ worktreeBootstrap: bootstrapState,
748
+ };
749
+ } catch (e: any) {
750
+ return { success: false, error: e.message };
751
+ }
752
+ },
753
+
754
+ retry_mesh_node_bootstrap: async (ctx: MedFamilyContext, args: any) => {
755
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
756
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
757
+ if (!meshId) return { success: false, error: 'meshId required' };
758
+ if (!nodeId) return { success: false, error: 'nodeId required' };
759
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'bootstrap retry');
760
+ if (ownerFailure) return ownerFailure;
761
+
762
+ try {
763
+ // preferInline so bootstrap-retry can resolve inline-cache-only clone worktree nodes.
764
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
765
+ const mesh = meshRecord?.mesh;
766
+ if (!mesh) return { success: false, error: 'Mesh not found' };
767
+
768
+ const node = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
769
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
770
+ if (!node.isLocalWorktree) return { success: false, error: 'Node is not a local worktree node' };
771
+
772
+ // Bootstrap runs scripts in the worktree path — forward to the node's daemon if remote.
773
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
774
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
775
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
776
+ // bootstrap locally, do not forward. Equivalent → local.
777
+ if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
778
+ && !args?._meshDirectDispatch) {
779
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, 'retry_mesh_node_bootstrap', {
780
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
781
+ _meshDirectDispatch: true,
782
+ });
783
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
784
+ }
785
+
786
+ const currentBootstrap = node.worktreeBootstrap as WorktreeBootstrapState | undefined;
787
+ if (currentBootstrap?.status === 'running') {
788
+ return { success: false, error: 'Bootstrap is already running for this node' };
789
+ }
790
+
791
+ const worktreePath: string = node.workspace || node.repoRoot;
792
+ if (!worktreePath) return { success: false, error: 'Node has no workspace path' };
793
+
794
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
795
+ const runningState: WorktreeBootstrapState = {
796
+ status: 'running',
797
+ required: loadedBootstrap.config?.required !== false,
798
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
799
+ configSourceType: loadedBootstrap.sourceType,
800
+ startedAt: new Date().toISOString(),
801
+ };
802
+
803
+ const persistState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
804
+ node.worktreeBootstrap = bootstrapState;
805
+ if (meshRecord.inline) {
806
+ ctx.updateInlineMeshNode(meshId, mesh, node);
807
+ return;
808
+ }
809
+ try {
810
+ const { updateNode } = await import('../../config/mesh-config.js');
811
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
812
+ ctx.invalidateAggregateMeshStatus(meshId);
813
+ } catch { /* best-effort */ }
814
+ };
815
+
816
+ await persistState(runningState);
817
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
818
+ await persistState(bootstrapState);
819
+
820
+ return { success: true, bootstrapState };
821
+ } catch (e: any) {
822
+ return { success: false, error: e.message };
823
+ }
824
+ },
825
+ };