@adhdev/daemon-core 0.9.82-rc.42 → 0.9.82-rc.421

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 +141 -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 +63 -14
  74. package/dist/index.js +50038 -20126
  75. package/dist/index.js.map +1 -1
  76. package/dist/index.mjs +49631 -19875
  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 +164 -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 +447 -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 +208 -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 +14 -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 +428 -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 +527 -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 +678 -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 +998 -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 +142 -0
  255. package/src/commands/mesh-coordinator.ts +334 -124
  256. package/src/commands/router.ts +2669 -3246
  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 +469 -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 +188 -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 +1883 -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 +613 -102
  310. package/src/mesh/mesh-magi-status.ts +223 -0
  311. package/src/mesh/mesh-missions.ts +407 -0
  312. package/src/mesh/mesh-node-identity.ts +1887 -0
  313. package/src/mesh/mesh-queue-assignment.ts +1863 -0
  314. package/src/mesh/mesh-reconcile-loop.ts +1734 -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 +1836 -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 +1898 -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 +30 -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 +639 -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,998 @@
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
+ add_mesh_node: async (ctx: MedFamilyContext, args: any) => {
226
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
227
+ const workspace = typeof args?.workspace === 'string' ? args.workspace.trim() : '';
228
+ if (!meshId) return { success: false, error: 'meshId required' };
229
+ if (!workspace) return { success: false, error: 'workspace required' };
230
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node addition');
231
+ if (ownerFailure) return ownerFailure;
232
+ try {
233
+ const { addNode } = await import('../../config/mesh-config.js');
234
+ const providerPriority = Array.isArray(args?.providerPriority)
235
+ ? args.providerPriority.map((type: any) => typeof type === 'string' ? type.trim() : '').filter(Boolean)
236
+ : [];
237
+ const readOnly = args?.readOnly === true;
238
+ const providerRoles = normalizeProviderRoles(args?.providerRoles);
239
+ const policy = {
240
+ ...(readOnly ? { readOnly: true } : {}),
241
+ ...(providerPriority.length ? { providerPriority } : {}),
242
+ ...(providerRoles.length ? { providerRoles } : {}),
243
+ };
244
+ const role = normalizeMeshDaemonRole(args?.role);
245
+ const daemonId = typeof args?.daemonId === 'string' && args.daemonId.trim() ? args.daemonId.trim() : undefined;
246
+ const machineId = typeof args?.machineId === 'string' && args.machineId.trim() ? args.machineId.trim() : undefined;
247
+ const repoRoot = typeof args?.repoRoot === 'string' && args.repoRoot.trim() ? args.repoRoot.trim() : undefined;
248
+ const node = addNode(meshId, {
249
+ workspace,
250
+ ...(repoRoot ? { repoRoot } : {}),
251
+ ...(daemonId ? { daemonId } : {}),
252
+ ...(machineId ? { machineId } : {}),
253
+ ...(policy ? { policy } : {}),
254
+ ...(role ? { role } : {}),
255
+ });
256
+ if (!node) return { success: false, error: 'Mesh not found' };
257
+ // mesh_status hands back a coordinator-memory aggregate
258
+ // snapshot keyed on (meshId, queueRevision). Adding a
259
+ // node touches neither, so without an explicit cache
260
+ // bust the dashboard graph keeps rendering the pre-add
261
+ // node list (empty for a fresh mesh) even after the
262
+ // user clicks Refresh.
263
+ ctx.invalidateAggregateMeshStatus(meshId);
264
+ return { success: true, node };
265
+ } catch (e: any) {
266
+ return { success: false, error: e.message };
267
+ }
268
+ },
269
+
270
+ update_mesh_node: async (ctx: MedFamilyContext, args: any) => {
271
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
272
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
273
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
274
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node update');
275
+ if (ownerFailure) return ownerFailure;
276
+ try {
277
+ const { updateNode } = await import('../../config/mesh-config.js');
278
+ const policy = args?.policy && typeof args.policy === 'object' && !Array.isArray(args.policy)
279
+ ? { ...(args.policy as Record<string, unknown>) }
280
+ : {};
281
+ if (Array.isArray(args?.providerPriority)) {
282
+ const providerPriority = args.providerPriority
283
+ .map((type: any) => typeof type === 'string' ? type.trim() : '')
284
+ .filter(Boolean);
285
+ delete (policy as any).provider_priority;
286
+ if (providerPriority.length) {
287
+ (policy as any).providerPriority = providerPriority;
288
+ } else {
289
+ delete (policy as any).providerPriority;
290
+ }
291
+ }
292
+ // providerRoles: per-(node, provider) role label + maxParallel cap.
293
+ // Passing an explicit (possibly empty) array clears/replaces the
294
+ // declarations; omitting the arg leaves any value already on policy
295
+ // untouched (a full policy object passed by the caller still carries it).
296
+ if (Array.isArray(args?.providerRoles)) {
297
+ const providerRoles = normalizeProviderRoles(args.providerRoles);
298
+ if (providerRoles.length) {
299
+ (policy as any).providerRoles = providerRoles;
300
+ } else {
301
+ delete (policy as any).providerRoles;
302
+ }
303
+ }
304
+ const patch: Record<string, unknown> = { policy: policy as any };
305
+ if (typeof args?.systemPrompt === 'string') {
306
+ const trimmed = (args.systemPrompt as string).trim();
307
+ patch.systemPrompt = trimmed || undefined;
308
+ } else if (args?.systemPrompt === null) {
309
+ patch.systemPrompt = undefined;
310
+ }
311
+ const node = updateNode(meshId, nodeId, patch as any);
312
+ if (!node) return { success: false, error: 'Mesh node not found' };
313
+ // Provider priority / systemPrompt changes don't touch
314
+ // the queue revision, so without a manual bust the
315
+ // cached aggregate keeps surfacing pre-update values
316
+ // (priority chip, coordinator prompt preview, etc.).
317
+ ctx.invalidateAggregateMeshStatus(meshId);
318
+ return { success: true, node };
319
+ } catch (e: any) {
320
+ return { success: false, error: e.message };
321
+ }
322
+ },
323
+
324
+ cleanup_mesh_sessions: async (ctx: MedFamilyContext, args: any) => {
325
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
326
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
327
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
328
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node removal');
329
+ if (ownerFailure) return ownerFailure;
330
+ try {
331
+ // preferInline so inline-cache-only clone nodes resolve (matches owner check above).
332
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
333
+ const mesh = meshRecord?.mesh;
334
+ if (!mesh) return { success: false, error: 'Mesh not found' };
335
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
336
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
337
+ const mode = ctx.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
338
+ const sessionIds = Array.isArray(args?.sessionIds)
339
+ ? args.sessionIds.map((id: any) => typeof id === 'string' ? id.trim() : '').filter(Boolean)
340
+ : undefined;
341
+ const result = await ctx.cleanupMeshSessions({
342
+ meshId,
343
+ nodeId,
344
+ node,
345
+ mode,
346
+ sessionIds,
347
+ dryRun: args?.dryRun === true,
348
+ source: 'mesh_cleanup_sessions',
349
+ });
350
+ return result;
351
+ } catch (e: any) {
352
+ return { success: false, error: e.message };
353
+ }
354
+ },
355
+
356
+ remove_mesh_node: async (ctx: MedFamilyContext, args: any) => {
357
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
358
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
359
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
360
+ try {
361
+ // preferInline so removal can resolve inline-cache-only clone worktree nodes.
362
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
363
+ const mesh = meshRecord?.mesh;
364
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
365
+
366
+ // Guard: refuse to remove the coordinator's OWN local base node
367
+ // (same machine, NOT a worktree). Removing it breaks live mesh
368
+ // membership — the coordinator can no longer be reached and has
369
+ // to be restarted. Worktree clones are always safe to remove;
370
+ // only the non-worktree node bound to this daemon is protected.
371
+ // An explicit force:true overrides for intentional mesh teardown.
372
+ if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
373
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : '';
374
+ const nodeMachineId = readMeshNodeMachineId(node as Record<string, unknown>) || '';
375
+ const selfDaemonId = ctx.deps.statusInstanceId || '';
376
+ const selfMachineId = (() => { try { return loadConfig().machineId || ''; } catch { return ''; } })();
377
+ // Identity match is form-safe: a daemon answers to the same machine
378
+ // under interchangeable id forms (bare `mach_X`, cloud `daemon_mach_X`,
379
+ // standalone `standalone_mach_X`). statusInstanceId/loadConfig().machineId
380
+ // and the node's stored daemonId/machineId frequently hold DIFFERENT forms
381
+ // of the same machine, so a raw `===` would miss the self-match and let the
382
+ // coordinator delete its own live base node (the very accident this guard
383
+ // exists to prevent). daemonIdsEquivalent collapses every form to its
384
+ // machine core before comparing, so a same-machine match is caught
385
+ // regardless of which form each side carries. This only widens matches
386
+ // (every raw-`===` hit still matches) — fail-open → fail-closed.
387
+ const isCoordinatorBaseNode =
388
+ (!!selfDaemonId && (daemonIdsEquivalent(nodeDaemonId, selfDaemonId) || daemonIdsEquivalent(nodeMachineId, selfDaemonId)))
389
+ || (!!selfMachineId && (daemonIdsEquivalent(nodeDaemonId, selfMachineId) || daemonIdsEquivalent(nodeMachineId, selfMachineId)));
390
+ if (isCoordinatorBaseNode) {
391
+ return {
392
+ success: false,
393
+ removed: false,
394
+ code: 'mesh_remove_coordinator_base_node_protected',
395
+ error: `Refusing to remove the coordinator's own base node '${typeof node.workspace === 'string' ? node.workspace : nodeId}'. `
396
+ + `It is the local non-worktree node bound to this coordinator daemon; removing it breaks live mesh membership and forces a restart.`,
397
+ 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.',
398
+ };
399
+ }
400
+ }
401
+
402
+ // Default worktree session cleanup ON: when the caller OMITS a mode and the
403
+ // node is a local worktree, default to 'stop_and_delete' instead of the mesh
404
+ // policy ('preserve' by default). A worktree's chat session has no reason to
405
+ // outlive the worktree's node + directory + branch, and leaving it on
406
+ // 'preserve' is what orphaned chats after a worktree remove. An explicit mode
407
+ // (including an explicit 'preserve') is always honored — only the OMITTED case
408
+ // changes, and only for worktrees. Base nodes keep arg ?? policy ?? preserve.
409
+ const explicitCleanupMode = args?.sessionCleanupMode ?? args?.session_cleanup_mode;
410
+ const sessionCleanupMode = ctx.normalizeMeshSessionCleanupMode(
411
+ explicitCleanupMode
412
+ ?? (node?.isLocalWorktree === true ? 'stop_and_delete' : undefined)
413
+ ?? mesh?.policy?.sessionCleanupOnNodeRemove,
414
+ );
415
+ // Explicit sessionIds (e.g. supplied by refine auto-cleanup) bypass the
416
+ // workspace-only-match guard so a delegate session that lacks a
417
+ // meta.meshNodeId binding can still be stopped/deleted.
418
+ const explicitSessionIds = Array.isArray(args?.sessionIds)
419
+ ? (args.sessionIds as unknown[]).filter((v): v is string => typeof v === 'string' && v.trim().length > 0).map(v => v.trim())
420
+ : undefined;
421
+ // Precheck-first: for a LOCAL worktree removal, validate removability
422
+ // with a purely non-destructive precheck BEFORE touching the session.
423
+ // The session cleanup below is destructive and irreversible
424
+ // (stop_and_delete), so a refusal that fires only AFTER it — as the old
425
+ // ordering did when removeWorktree rejected a dirty worktree — orphaned
426
+ // the delegated session. Running the precheck here means a refusal
427
+ // (dirty worktree, missing/mismatched metadata, etc.) returns with the
428
+ // session left fully intact. Remote-forwarded worktrees are prechecked
429
+ // on the owning daemon (it runs this same handler), so we only gate the
430
+ // local case here. Success/skip cases return ok:true and fall through to
431
+ // the unchanged normal flow.
432
+ if (node?.isLocalWorktree) {
433
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
434
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
435
+ && !args?._meshDirectDispatch;
436
+ if (!isRemoteWorktree) {
437
+ const precheck = await ctx.precheckLocalWorktreeRemovable({ mesh, node, nodeId, force: args?.force === true });
438
+ if (precheck.ok === false) {
439
+ return {
440
+ success: false,
441
+ removed: false,
442
+ code: precheck.code,
443
+ error: precheck.error,
444
+ recoveryHint: precheck.recoveryHint,
445
+ // No sessionCleanup key: the session was deliberately NOT
446
+ // touched. worktreeCleanup mirrors the destructive path's
447
+ // refusal shape so existing callers see the same code.
448
+ worktreeCleanup: { success: false, code: precheck.code, error: precheck.error, recoveryHint: precheck.recoveryHint },
449
+ };
450
+ }
451
+ }
452
+ }
453
+
454
+ let sessionCleanup: Record<string, unknown> | undefined;
455
+ if (node && sessionCleanupMode !== 'preserve') {
456
+ sessionCleanup = await ctx.cleanupMeshSessions({
457
+ meshId,
458
+ nodeId,
459
+ node,
460
+ mode: sessionCleanupMode,
461
+ ...(explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {}),
462
+ source: 'mesh_remove_node',
463
+ });
464
+ if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
465
+ }
466
+
467
+ let worktreeCleanup: Record<string, unknown> | undefined;
468
+ if (node?.isLocalWorktree) {
469
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
470
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
471
+ // clean up locally, do not forward. Equivalent → local.
472
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
473
+ && !args?._meshDirectDispatch;
474
+ if (isRemoteWorktree) {
475
+ // Worktree lives on a different machine — ask that daemon to clean it up.
476
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
477
+ const forwarded = await ctx.deps.dispatchMeshCommand!(nodeDaemonId!, 'remove_mesh_node', {
478
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
479
+ _meshDirectDispatch: true,
480
+ });
481
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
482
+ }
483
+ const cleanupResult = await ctx.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
484
+ // De-gating: membership removal is NOT gated on the worktree
485
+ // directory actually being deleted. cleanupLocalWorktreeNode now
486
+ // returns success:true (with a residue flag) whenever the path is
487
+ // proven managed and the only remaining problem is leftover
488
+ // directory bytes (e.g. Windows EINVAL). A success:false here means
489
+ // a genuinely-unsafe condition — missing metadata, a non-managed /
490
+ // unexpected path, a branch mismatch, a dirty worktree, or an
491
+ // unverified force fallback — and those still block removal.
492
+ if (cleanupResult.success === false) {
493
+ return {
494
+ success: false,
495
+ removed: false,
496
+ code: cleanupResult.code,
497
+ error: cleanupResult.error,
498
+ recoveryHint: cleanupResult.recoveryHint,
499
+ ...(sessionCleanup ? { sessionCleanup } : {}),
500
+ worktreeCleanup: cleanupResult,
501
+ };
502
+ }
503
+ worktreeCleanup = cleanupResult;
504
+ }
505
+
506
+ let removed = false;
507
+ if (meshRecord?.inline) {
508
+ removed = ctx.removeInlineMeshNode(meshId, mesh, nodeId);
509
+ // Inline meshes share the same aggregate snapshot cache as
510
+ // local-config meshes; without this bust the removed node
511
+ // keeps showing up in the dashboard graph until the cache
512
+ // ages out on its own.
513
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
514
+ // Node was already absent from the inline mesh (e.g. removed by a
515
+ // prior refine cleanup). Treat as removed so caller gets removed:true.
516
+ if (!removed && !node) removed = true;
517
+ } else {
518
+ const { removeNode } = await import('../../config/mesh-config.js');
519
+ removed = removeNode(meshId, nodeId);
520
+ // Node already absent from config (e.g. removed by a prior refine
521
+ // cleanup after a successful Refinery merge). Treat as removed so
522
+ // the response is accurate.
523
+ if (!removed && !node) removed = true;
524
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
525
+ }
526
+
527
+ // Record in task ledger
528
+ if (removed) {
529
+ try {
530
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
531
+ appendLedgerEntry(meshId, {
532
+ kind: 'node_removed',
533
+ nodeId,
534
+ payload: {
535
+ worktree: !!node?.isLocalWorktree,
536
+ sessionCleanupMode,
537
+ workspace: typeof node?.workspace === 'string' ? node.workspace : undefined,
538
+ daemonId: typeof node?.daemonId === 'string' ? node.daemonId : undefined,
539
+ worktreeBranch: typeof node?.worktreeBranch === 'string' ? node.worktreeBranch : undefined,
540
+ worktreeCleanupFallback: typeof worktreeCleanup?.fallback === 'string' ? worktreeCleanup.fallback : undefined,
541
+ forced: worktreeCleanup?.forced === true ? true : undefined,
542
+ forceFallbackReason: typeof worktreeCleanup?.reason === 'string' ? worktreeCleanup.reason : undefined,
543
+ branchRefDeleted: typeof worktreeCleanup?.branchRefDeleted === 'boolean' ? worktreeCleanup.branchRefDeleted : undefined,
544
+ branchRefReason: typeof worktreeCleanup?.branchRefReason === 'string' ? worktreeCleanup.branchRefReason : undefined,
545
+ },
546
+ });
547
+ } catch { /* ledger append is best-effort */ }
548
+ }
549
+
550
+ // Surface leftover-directory residue at the top level so callers
551
+ // see the node was dropped from the mesh even though the worktree
552
+ // directory could not be fully removed (best-effort, non-gating).
553
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === 'string'
554
+ ? worktreeCleanup.residueWarning
555
+ : undefined;
556
+
557
+ // Surface a preserved-branch warning at the top level so callers see
558
+ // that the branch ref was intentionally NOT deleted (unmerged work is
559
+ // never silently dropped). When the branch ref WAS deleted, the nested
560
+ // worktreeCleanup.branchRefDeleted flag already records it.
561
+ const branchRefWarning = typeof worktreeCleanup?.branchRefWarning === 'string'
562
+ ? worktreeCleanup.branchRefWarning
563
+ : undefined;
564
+
565
+ // Orphan guard: if the session cleanup still left any LIVE session skipped
566
+ // (e.g. a future skip reason, or a workspace-only session on a base node),
567
+ // surface it at the top level so the caller knows a manual mesh_cleanup_sessions
568
+ // is still required for those sessionIds. Without this, a skipped-live session
569
+ // silently outlives a removed node (the very NODE-REMOVE-SESSION-ORPHAN bug).
570
+ const skippedLiveSessionIds = Array.isArray(sessionCleanup?.skippedLiveSessionIds)
571
+ ? (sessionCleanup!.skippedLiveSessionIds as unknown[]).filter((v): v is string => typeof v === 'string')
572
+ : [];
573
+ const orphanedSessionsRemaining = skippedLiveSessionIds.length > 0;
574
+ const orphanNextAction = orphanedSessionsRemaining
575
+ ? `Live session(s) [${skippedLiveSessionIds.join(', ')}] were skipped and still survive this node removal. `
576
+ + `Run mesh_cleanup_sessions with mode:'stop_and_delete' and sessionIds:[${skippedLiveSessionIds.map(id => `'${id}'`).join(', ')}] to release them.`
577
+ : undefined;
578
+ return {
579
+ success: true,
580
+ removed,
581
+ ...(residueWarning ? { residueWarning } : {}),
582
+ ...(branchRefWarning ? { branchRefWarning } : {}),
583
+ ...(sessionCleanup ? { sessionCleanup } : {}),
584
+ ...(worktreeCleanup ? { worktreeCleanup } : {}),
585
+ ...(orphanedSessionsRemaining
586
+ ? { orphanedSessionsRemaining: true, nextAction: orphanNextAction }
587
+ : {}),
588
+ };
589
+ } catch (e: any) {
590
+ return { success: false, error: e.message };
591
+ }
592
+ },
593
+
594
+ clone_mesh_node: async (ctx: MedFamilyContext, args: any) => {
595
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
596
+ const sourceNodeId = typeof args?.sourceNodeId === 'string' ? args.sourceNodeId.trim() : '';
597
+ const branch = typeof args?.branch === 'string' ? args.branch.trim() : '';
598
+ const baseBranch = typeof args?.baseBranch === 'string' ? args.baseBranch.trim() : undefined;
599
+ if (!meshId) return { success: false, error: 'meshId required' };
600
+ if (!sourceNodeId) return { success: false, error: 'sourceNodeId required' };
601
+ if (!branch) return { success: false, error: 'branch required' };
602
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'worktree clone');
603
+ if (ownerFailure) return ownerFailure;
604
+
605
+ try {
606
+ // Resolve with preferInline so the clone writes the new node into the
607
+ // same representation that get_mesh reads back. The MCP coordinator
608
+ // passes inlineMesh on every mesh command, so when it owns an inline
609
+ // mesh the membership read path (get_mesh, preferInline: true) returns
610
+ // the inline cache. Without preferInline here, clone could resolve to a
611
+ // local-config mesh and write the node only to config — leaving the
612
+ // inline cache (and therefore get_mesh / refreshMeshFromDaemon) without
613
+ // the node, so the new worktree node is never visible in live mesh
614
+ // membership even though worktree_bootstrap_complete fires.
615
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
616
+ const mesh = meshRecord?.mesh;
617
+ if (!mesh) return { success: false, error: 'Mesh not found' };
618
+
619
+ const sourceNode = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, sourceNodeId));
620
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
621
+
622
+ // Forward to the source node's daemon if it's on a different machine.
623
+ // _meshDirectDispatch prevents infinite re-forwarding when the stored daemonId
624
+ // uses a legacy format that doesn't match the receiving daemon's statusInstanceId.
625
+ const sourceDaemonId = typeof sourceNode.daemonId === 'string' ? sourceNode.daemonId.trim() : undefined;
626
+ // daemonIdsEquivalent: an equivalent-form source daemonId is this machine —
627
+ // clone locally, do not forward. Equivalent → local.
628
+ if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
629
+ && !args?._meshDirectDispatch) {
630
+ const forwarded = await ctx.deps.dispatchMeshCommand(sourceDaemonId, 'clone_mesh_node', {
631
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
632
+ _meshDirectDispatch: true,
633
+ });
634
+ // FALSE-BLOCKER-CLONE-QUEUE: open the transient grace window for the freshly
635
+ // cloned node on THIS coordinator daemon. The clone ran (and wrote the inline-
636
+ // cache node) on the remote source daemon; its inline entry has not propagated
637
+ // here yet, so a queue task pinned to it would transiently look like a permanent
638
+ // 'target_node_id_unmatched'. Recording its id marks the unmatch as transient.
639
+ const forwardedNodeId = (forwarded as { node?: { id?: unknown } } | null | undefined)?.node?.id;
640
+ if (typeof forwardedNodeId === 'string' && forwardedNodeId) noteRecentlyClonedNode(forwardedNodeId);
641
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
642
+ }
643
+
644
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
645
+ const { createWorktree } = await import('../../git/git-worktree.js');
646
+ const result = await createWorktree({
647
+ repoRoot,
648
+ branch,
649
+ baseBranch,
650
+ meshName: mesh.name,
651
+ });
652
+ if (result.baseSync?.warning) {
653
+ console.warn(`[mesh] clone_mesh_node base sync (${result.baseSync.action}): ${result.baseSync.warning}`);
654
+ } else if (result.baseSync && result.baseSync.action !== 'up_to_date') {
655
+ console.log(`[mesh] clone_mesh_node base sync: ${result.baseSync.action} (startRef=${result.baseSync.startRef})`);
656
+ }
657
+
658
+ let node: any;
659
+ if (meshRecord.inline) {
660
+ const { randomUUID } = await import('crypto');
661
+ node = {
662
+ id: `node_${randomUUID().replace(/-/g, '')}`,
663
+ workspace: result.worktreePath,
664
+ repoRoot: result.worktreePath,
665
+ daemonId: sourceNode.daemonId,
666
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
667
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
668
+ policy: { ...(sourceNode.policy || {}) },
669
+ isLocalWorktree: true,
670
+ worktreeBranch: result.branch,
671
+ clonedFromNodeId: sourceNodeId,
672
+ };
673
+ ctx.updateInlineMeshNode(meshId, mesh, node);
674
+ } else {
675
+ const { addNode } = await import('../../config/mesh-config.js');
676
+ node = addNode(meshId, {
677
+ workspace: result.worktreePath,
678
+ repoRoot: result.worktreePath,
679
+ daemonId: sourceNode.daemonId,
680
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
681
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
682
+ isLocalWorktree: true,
683
+ worktreeBranch: result.branch,
684
+ clonedFromNodeId: sourceNodeId,
685
+ policy: { ...(sourceNode.policy || {}) },
686
+ });
687
+ if (!node) return { success: false, error: 'Failed to register worktree node' };
688
+ // Also reconcile the freshly-registered node into any warmed inline
689
+ // cache for this mesh. get_mesh (preferInline: true) reads the inline
690
+ // cache first when one exists; if we only wrote to local config the
691
+ // node would be invisible to membership reads. updateInlineMeshNode is
692
+ // a no-op when no inline cache is present.
693
+ const inlineForReconcile = ctx.getCachedInlineMesh(meshId);
694
+ if (inlineForReconcile) ctx.updateInlineMeshNode(meshId, inlineForReconcile, node);
695
+ ctx.invalidateAggregateMeshStatus(meshId);
696
+ }
697
+
698
+ // FALSE-BLOCKER-CLONE-QUEUE: open the transient grace window for the freshly cloned
699
+ // node. A queue task pinned to it (target_node pin) enqueued before bootstrap
700
+ // completes / the inline-cache entry fully settles must be classified as a transient
701
+ // skip, not a permanent 'target_node_id_unmatched' actionable blocker.
702
+ if (typeof node?.id === 'string' && node.id) noteRecentlyClonedNode(node.id);
703
+
704
+ const persistWorktreeSetupState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
705
+ node.worktreeBootstrap = bootstrapState;
706
+ if (meshRecord.inline) {
707
+ ctx.updateInlineMeshNode(meshId, mesh, node);
708
+ return;
709
+ }
710
+ try {
711
+ const { updateNode } = await import('../../config/mesh-config.js');
712
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
713
+ ctx.invalidateAggregateMeshStatus(meshId);
714
+ } catch { /* bootstrap status persistence is best-effort */ }
715
+ };
716
+
717
+ const appendCloneLedger = async (initSubmodules: boolean, bootstrapState: WorktreeBootstrapState): Promise<void> => {
718
+ try {
719
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
720
+ appendLedgerEntry(meshId, {
721
+ kind: 'node_cloned',
722
+ nodeId: node.id,
723
+ payload: {
724
+ sourceNodeId,
725
+ branch: result.branch,
726
+ worktreePath: result.worktreePath,
727
+ submodulesInitialized: initSubmodules,
728
+ worktreeBootstrap: {
729
+ status: bootstrapState.status,
730
+ required: bootstrapState.required,
731
+ configSource: bootstrapState.configSource,
732
+ configSourceType: bootstrapState.configSourceType,
733
+ lastCommand: bootstrapState.lastCommand,
734
+ exitCode: bootstrapState.exitCode,
735
+ },
736
+ },
737
+ });
738
+ } catch { /* ledger append is best-effort */ }
739
+ };
740
+
741
+ const initSubmodules = (sourceNode.policy as any)?.initSubmodulesOnClone !== false;
742
+ // Read the worktree bootstrap config through the unified RepoSettings
743
+ // loader (file-separated `.adhdev/worktree_bootstrap.json`; machine-local
744
+ // inline seam honored). runMeshWorktreeBootstrap below re-loads it to run.
745
+ const loadedBootstrap = loadRepoSettings({ workspace: result.worktreePath, mesh }).worktreeBootstrap;
746
+ const runningBootstrapState: WorktreeBootstrapState = {
747
+ status: 'running',
748
+ required: loadedBootstrap.config?.required !== false,
749
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
750
+ configSourceType: loadedBootstrap.sourceType,
751
+ startedAt: new Date().toISOString(),
752
+ };
753
+ await persistWorktreeSetupState(runningBootstrapState);
754
+
755
+ const finishWorktreeSetup = async (): Promise<{ submodulesInitialized: boolean; bootstrapState: WorktreeBootstrapState }> => {
756
+ let submodulesInitialized = false;
757
+ if (initSubmodules) {
758
+ try {
759
+ const { runGit } = await import('../../git/git-executor.js');
760
+ await runGit(
761
+ { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
762
+ ['submodule', 'update', '--init', '--recursive'],
763
+ { timeoutMs: 120000 },
764
+ );
765
+ submodulesInitialized = true;
766
+
767
+ // Sync oss submodule to source node HEAD (best-effort)
768
+ const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
769
+ if (sourceWorkspace) {
770
+ try {
771
+ const { runGit: rg } = await import('../../git/git-executor.js');
772
+ const sourceCtx = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
773
+ const worktreeCtx = { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true };
774
+
775
+ // Read source node's oss submodule SHA
776
+ const sourceStatusOut = await rg(sourceCtx, ['submodule', 'status', 'oss'], { timeoutMs: 10000 });
777
+ const sourceStatusLine = (typeof sourceStatusOut === 'string' ? sourceStatusOut : (sourceStatusOut as any)?.stdout ?? '').trim();
778
+ const sourceShaMatch = sourceStatusLine.match(/^[+\- ]?([0-9a-f]{40})/);
779
+ const sourceSha = sourceShaMatch?.[1];
780
+
781
+ if (sourceSha) {
782
+ // Read worktree's current oss HEAD
783
+ const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
784
+ const worktreeOssHeadOut = await rg(ossCtx, ['rev-parse', 'HEAD'], { timeoutMs: 10000 });
785
+ const worktreeOssSha = (typeof worktreeOssHeadOut === 'string' ? worktreeOssHeadOut : (worktreeOssHeadOut as any)?.stdout ?? '').trim();
786
+
787
+ if (worktreeOssSha && worktreeOssSha !== sourceSha) {
788
+ // Bring the source node's oss HEAD into the worktree object DB so
789
+ // both SHAs are resolvable for the ancestry (rewind) guard below.
790
+ await rg(ossCtx, ['fetch', `${sourceWorkspace}/oss`, 'HEAD'], { timeoutMs: 60000 });
791
+
792
+ // Rewind guard: the worktree oss HEAD was just checked out from the
793
+ // FRESH (origin/main-derived) root base. Only advance to the source
794
+ // SHA when it is strictly newer — never rewind to a stale source.
795
+ let ossAction: OssCloneSyncAction;
796
+ try {
797
+ ossAction = await decideOssCloneSync(ossCtx, worktreeOssSha, sourceSha, rg);
798
+ } catch (decideErr: any) {
799
+ ossAction = 'skip_diverged';
800
+ console.warn(`[mesh] oss submodule sync guard could not resolve ancestry (kept fresh worktree HEAD): ${decideErr?.message ?? decideErr}`);
801
+ }
802
+
803
+ if (ossAction === 'advance') {
804
+ await rg(ossCtx, ['checkout', sourceSha], { timeoutMs: 10000 });
805
+ await rg(worktreeCtx, ['add', 'oss'], { timeoutMs: 10000 });
806
+ await rg(worktreeCtx, ['commit', '-m', 'chore: sync oss to source node HEAD on clone'], { timeoutMs: 10000 });
807
+ console.log(`[mesh] Advanced oss submodule to newer source HEAD ${sourceSha.slice(0, 8)} in worktree`);
808
+ } else if (ossAction === 'skip_rewind') {
809
+ 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`);
810
+ } else if (ossAction === 'skip_diverged') {
811
+ 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)`);
812
+ }
813
+ }
814
+ }
815
+ } catch (ossErr: any) {
816
+ console.warn('[mesh] oss submodule sync to source HEAD failed (best-effort):', ossErr.message);
817
+ }
818
+ }
819
+ } catch (subErr: any) {
820
+ // Submodule init is best-effort; don't fail the clone
821
+ console.warn('[mesh] Submodule init failed for worktree:', subErr.message);
822
+ }
823
+ }
824
+ const bootstrapState: WorktreeBootstrapState = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
825
+ await persistWorktreeSetupState(bootstrapState);
826
+ await appendCloneLedger(submodulesInitialized, bootstrapState);
827
+ return { submodulesInitialized, bootstrapState };
828
+ };
829
+
830
+ const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8000);
831
+ const setupWaitMs = Number.isFinite(requestedSetupWaitMs)
832
+ ? Math.min(Math.max(requestedSetupWaitMs, 0), 14000)
833
+ : 8000;
834
+ const setupPromise = finishWorktreeSetup();
835
+ const setupResult = await Promise.race([
836
+ setupPromise.then((value) => ({ completed: true as const, value })),
837
+ new Promise<{ completed: false }>((resolve) => setTimeout(() => resolve({ completed: false }), setupWaitMs)),
838
+ ]);
839
+
840
+ const emitBootstrapEvent = (eventStatus: 'bootstrap_complete' | 'bootstrap_failed', bootstrapState: WorktreeBootstrapState, startedAtMs: number, extraPayload?: Record<string, unknown>): void => {
841
+ try {
842
+ const durationMs = Date.now() - startedAtMs;
843
+ const event = `worktree_${eventStatus}` as const;
844
+ const metadataEvent = {
845
+ source: 'clone_mesh_node_bootstrap',
846
+ nodeId: node.id,
847
+ status: eventStatus,
848
+ worktreePath: result.worktreePath,
849
+ durationMs,
850
+ bootstrapStatus: bootstrapState.status,
851
+ ...(bootstrapState.error ? { error: bootstrapState.error } : {}),
852
+ ...(bootstrapState.exitCode !== undefined ? { exitCode: bootstrapState.exitCode } : {}),
853
+ ...(extraPayload || {}),
854
+ };
855
+ if (typeof ctx.deps.instanceManager?.getByCategory === 'function') {
856
+ const forwarded = handleMeshForwardEvent(
857
+ { instanceManager: ctx.deps.instanceManager } as any,
858
+ { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent },
859
+ );
860
+ if (forwarded?.success === true) return;
861
+ }
862
+ queuePendingMeshCoordinatorEvent({
863
+ event,
864
+ meshId,
865
+ nodeLabel: node.id,
866
+ nodeId: node.id,
867
+ workspace: result.worktreePath,
868
+ metadataEvent,
869
+ queuedAt: Date.now(),
870
+ });
871
+ } catch { /* event emission is best-effort */ }
872
+ };
873
+
874
+ const bootstrapStartedMs = Date.now();
875
+
876
+ if (!setupResult.completed) {
877
+ setupPromise
878
+ .then(({ bootstrapState }) => {
879
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
880
+ })
881
+ .catch((error: any) => {
882
+ const failedState: WorktreeBootstrapState = {
883
+ ...runningBootstrapState,
884
+ status: 'failed',
885
+ completedAt: new Date().toISOString(),
886
+ error: error?.message || String(error),
887
+ };
888
+ void persistWorktreeSetupState(failedState);
889
+ void appendCloneLedger(false, failedState);
890
+ emitBootstrapEvent('bootstrap_failed', failedState, bootstrapStartedMs, { error: error?.message || String(error) });
891
+ });
892
+ return {
893
+ success: true,
894
+ async: true,
895
+ status: 'accepted',
896
+ node,
897
+ worktreePath: result.worktreePath,
898
+ branch: result.branch,
899
+ ...(result.baseSync ? { baseSync: result.baseSync } : {}),
900
+ ...(result.baseSync?.warning ? { baseStaleWarning: result.baseSync.warning } : {}),
901
+ worktreeBootstrap: runningBootstrapState,
902
+ worktreeSetup: {
903
+ status: 'running',
904
+ setupWaitMs,
905
+ message: 'Worktree node is registered; submodule/bootstrap setup is continuing in the background.',
906
+ },
907
+ };
908
+ }
909
+
910
+ const { submodulesInitialized, bootstrapState } = setupResult.value;
911
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
912
+ return {
913
+ success: true,
914
+ node,
915
+ worktreePath: result.worktreePath,
916
+ branch: result.branch,
917
+ ...(result.baseSync ? { baseSync: result.baseSync } : {}),
918
+ ...(result.baseSync?.warning ? { baseStaleWarning: result.baseSync.warning } : {}),
919
+ submodulesInitialized,
920
+ worktreeBootstrap: bootstrapState,
921
+ };
922
+ } catch (e: any) {
923
+ return { success: false, error: e.message };
924
+ }
925
+ },
926
+
927
+ retry_mesh_node_bootstrap: async (ctx: MedFamilyContext, args: any) => {
928
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
929
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
930
+ if (!meshId) return { success: false, error: 'meshId required' };
931
+ if (!nodeId) return { success: false, error: 'nodeId required' };
932
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'bootstrap retry');
933
+ if (ownerFailure) return ownerFailure;
934
+
935
+ try {
936
+ // preferInline so bootstrap-retry can resolve inline-cache-only clone worktree nodes.
937
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
938
+ const mesh = meshRecord?.mesh;
939
+ if (!mesh) return { success: false, error: 'Mesh not found' };
940
+
941
+ const node = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
942
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
943
+ if (!node.isLocalWorktree) return { success: false, error: 'Node is not a local worktree node' };
944
+
945
+ // Bootstrap runs scripts in the worktree path — forward to the node's daemon if remote.
946
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
947
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
948
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
949
+ // bootstrap locally, do not forward. Equivalent → local.
950
+ if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
951
+ && !args?._meshDirectDispatch) {
952
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, 'retry_mesh_node_bootstrap', {
953
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
954
+ _meshDirectDispatch: true,
955
+ });
956
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
957
+ }
958
+
959
+ const currentBootstrap = node.worktreeBootstrap as WorktreeBootstrapState | undefined;
960
+ if (currentBootstrap?.status === 'running') {
961
+ return { success: false, error: 'Bootstrap is already running for this node' };
962
+ }
963
+
964
+ const worktreePath: string = node.workspace || node.repoRoot;
965
+ if (!worktreePath) return { success: false, error: 'Node has no workspace path' };
966
+
967
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
968
+ const runningState: WorktreeBootstrapState = {
969
+ status: 'running',
970
+ required: loadedBootstrap.config?.required !== false,
971
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
972
+ configSourceType: loadedBootstrap.sourceType,
973
+ startedAt: new Date().toISOString(),
974
+ };
975
+
976
+ const persistState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
977
+ node.worktreeBootstrap = bootstrapState;
978
+ if (meshRecord.inline) {
979
+ ctx.updateInlineMeshNode(meshId, mesh, node);
980
+ return;
981
+ }
982
+ try {
983
+ const { updateNode } = await import('../../config/mesh-config.js');
984
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
985
+ ctx.invalidateAggregateMeshStatus(meshId);
986
+ } catch { /* best-effort */ }
987
+ };
988
+
989
+ await persistState(runningState);
990
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
991
+ await persistState(bootstrapState);
992
+
993
+ return { success: true, bootstrapState };
994
+ } catch (e: any) {
995
+ return { success: false, error: e.message };
996
+ }
997
+ },
998
+ };