@adhdev/daemon-core 0.9.82-rc.43 → 0.9.82-rc.430

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