@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,1887 @@
1
+ /**
2
+ * Mesh node-identity & git-freshness helpers
3
+ *
4
+ * Extracted from commands/router.ts (behavior-preserving move). Contains:
5
+ * - daemon-id / machine-id / hostname normalization + canonicalization
6
+ * - inline-mesh node identity reconciliation and transient-state handling
7
+ * - git-status normalization, branch-convergence, and freshness/staleness derivation
8
+ * - the direct git-probe cache and remote git-status probe machinery
9
+ *
10
+ * router.ts re-exports every public symbol from here so existing import paths
11
+ * (e.g. `from '.../commands/router.js'`) keep working.
12
+ */
13
+
14
+ import type { ProviderLoader } from '../providers/provider-loader.js';
15
+ import { detectCLI } from '../detection/cli-detector.js';
16
+ import { getGitRepoStatus } from '../git/git-status.js';
17
+ import { normalizeGitStatus as sharedNormalizeGitStatus, pickBestTransitGitStatus as sharedPickBestTransitGitStatus, summarizeGitShape as sharedSummarizeGitShape, normalizeMeshNodeId, daemonIdsEquivalent, meshWorkspacesEquivalent } from '@adhdev/mesh-shared';
18
+ import { LOG } from '../logging/logger.js';
19
+ import { getSessionHostSurfaceKind } from '../session-host/runtime-surface.js';
20
+ import { awaitWithWarmupDeadline, resolveWarmupDeadlineOpts } from '../mesh/mesh-warmup-deadline.js';
21
+ import * as fs from 'fs';
22
+ import { workingDirBasename } from '../providers/working-dir.js';
23
+ import { readMeshTimeoutEnvMs, MESH_CONNECT_TIMEOUT_MS } from '../runtime-defaults.js';
24
+
25
+ export function readProviderPriorityFromPolicy(policy: unknown): string[] {
26
+ const record = policy && typeof policy === 'object' && !Array.isArray(policy)
27
+ ? policy as Record<string, unknown>
28
+ : {};
29
+ const raw = record.providerPriority;
30
+ if (!Array.isArray(raw)) return [];
31
+ const seen = new Set<string>();
32
+ return raw
33
+ .map(type => typeof type === 'string' ? type.trim() : '')
34
+ .filter(Boolean)
35
+ .filter(type => {
36
+ if (seen.has(type)) return false;
37
+ seen.add(type);
38
+ return true;
39
+ });
40
+ }
41
+
42
+ /**
43
+ * Normalize a providerRoles array (RepoMeshNodePolicy.providerRoles) from raw
44
+ * tool args. Each entry binds a providerType to an optional `maxParallel` cap.
45
+ * Entries without a usable providerType are dropped; the last entry wins on
46
+ * duplicate providerType. Returns [] when no valid entries — callers then omit
47
+ * the field entirely (full backward compat). Routing is governed by required_tags;
48
+ * any legacy `role` field on the input is ignored.
49
+ */
50
+ export function normalizeProviderRoles(value: unknown): Array<{ providerType: string; maxParallel?: number }> {
51
+ if (!Array.isArray(value)) return [];
52
+ const byType = new Map<string, { providerType: string; maxParallel?: number }>();
53
+ for (const raw of value) {
54
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue;
55
+ const rec = raw as Record<string, unknown>;
56
+ const providerType = typeof rec.providerType === 'string' ? rec.providerType.trim() : '';
57
+ if (!providerType) continue;
58
+ const entry: { providerType: string; maxParallel?: number } = { providerType };
59
+ const maxParallel = Number(rec.maxParallel);
60
+ if (Number.isFinite(maxParallel) && maxParallel >= 0) entry.maxParallel = Math.floor(maxParallel);
61
+ byType.set(providerType.toLowerCase(), entry);
62
+ }
63
+ return [...byType.values()];
64
+ }
65
+
66
+ export function readObjectRecord(value: unknown): Record<string, any> {
67
+ return value && typeof value === 'object' && !Array.isArray(value)
68
+ ? value as Record<string, any>
69
+ : {};
70
+ }
71
+
72
+ export function readStringValue(...values: unknown[]): string | undefined {
73
+ for (const value of values) {
74
+ if (typeof value === 'string' && value.trim()) return value.trim();
75
+ }
76
+ return undefined;
77
+ }
78
+
79
+ function readNumberValue(...values: unknown[]): number | undefined {
80
+ for (const value of values) {
81
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
82
+ }
83
+ return undefined;
84
+ }
85
+
86
+ export function readBooleanValue(...values: unknown[]): boolean | undefined {
87
+ for (const value of values) {
88
+ if (typeof value === 'boolean') return value;
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ // summarizeRepoMeshDebugGit was a hand-synced copy of the cloud git-shape
94
+ // summarizer; both now call shared summarizeGitShape (@adhdev/mesh-shared).
95
+
96
+ export function summarizeRepoMeshStatusDebug(status: any): Record<string, unknown> {
97
+ const nodes = Array.isArray(status?.nodes) ? status.nodes : [];
98
+ return {
99
+ success: status?.success,
100
+ meshId: readStringValue(status?.meshId, status?.mesh_id) ?? null,
101
+ refreshedAt: readStringValue(status?.refreshedAt, status?.refreshed_at) ?? null,
102
+ sourceOfTruth: status?.sourceOfTruth ?? null,
103
+ branchConvergenceSummary: status?.branchConvergenceSummary ?? status?.branch_convergence_summary ?? null,
104
+ nodeCount: nodes.length,
105
+ nodes: nodes.map((node: any) => ({
106
+ // Status emits the id under `nodeId` (3-way input absorbed). The
107
+ // inline cache keeps `id` and `nodeId` equal, so this serialized form
108
+ // round-trips back through the cache without flipping shape.
109
+ nodeId: normalizeMeshNodeId(node) ?? null,
110
+ daemonId: readStringValue(node?.daemonId, node?.daemon_id) ?? null,
111
+ workspace: readStringValue(node?.workspace, node?.git?.workspace) ?? null,
112
+ health: readStringValue(node?.health) ?? null,
113
+ machineStatus: readStringValue(node?.machineStatus, node?.machine_status) ?? null,
114
+ connection: node?.connection && typeof node.connection === 'object' ? {
115
+ state: readStringValue(node.connection.state) ?? null,
116
+ transport: readStringValue(node.connection.transport) ?? null,
117
+ source: readStringValue(node.connection.source) ?? null,
118
+ reported: readBooleanValue(node.connection.reported) ?? null,
119
+ } : null,
120
+ gitProbePending: node?.gitProbePending === true,
121
+ launchReady: node?.launchReady === true,
122
+ git: sharedSummarizeGitShape(node?.git),
123
+ branchConvergence: node?.branchConvergence ?? node?.branch_convergence ?? null,
124
+ })),
125
+ };
126
+ }
127
+
128
+ export function logRepoMeshStatusDebug(event: string, fields: Record<string, unknown>): void {
129
+ try {
130
+ LOG.info('MeshStatusDebug', `[RepoMeshStatusDebug] ${JSON.stringify({ event, ...fields })}`);
131
+ } catch {
132
+ LOG.info('MeshStatusDebug', `[RepoMeshStatusDebug] ${event}`);
133
+ }
134
+ }
135
+
136
+ // joinRepoPath + readGitSubmodules moved to @adhdev/mesh-shared (readGitSubmodules)
137
+ // — used via sharedNormalizeGitStatus / sharedPickBestTransitGitStatus below.
138
+
139
+ export function buildMeshNodeDisplayLabel(node: Record<string, unknown>, nodeId: string, providerPriority: string[]): string {
140
+ const explicit = readStringValue(node.machineLabel, node.machine_label, node.machineNickname, node.machine_nickname, node.alias);
141
+ if (explicit) return explicit;
142
+ const workspace = readStringValue(node.workspace, node.repoRoot, node.repo_root);
143
+ // Use the OS-agnostic basename: a workspace reported by a Windows node
144
+ // (`D:\gh\adhdev-cloud`) must still collapse to its trailing segment even when
145
+ // this coordinator's own `path.basename` is POSIX-only and would not split `\`.
146
+ const workspaceName = workspace ? workingDirBasename(workspace) : undefined;
147
+ const host = readStringValue(node.machineName, node.machine_name, node.hostname, node.host, node.daemonId, node.daemon_id, node.machineId, node.machine_id);
148
+ const provider = providerPriority[0] || (Array.isArray(node.providers) ? readStringValue(...node.providers) : undefined);
149
+ const parts = [workspaceName, host, provider].filter(Boolean);
150
+ if (parts.length > 0) return parts.join(' · ');
151
+ return nodeId || 'unidentified mesh node';
152
+ }
153
+
154
+ function normalizeMeshHostname(value: unknown): string | undefined {
155
+ const hostname = readStringValue(value);
156
+ if (!hostname) return undefined;
157
+ return hostname.toLowerCase().replace(/\.$/, '');
158
+ }
159
+
160
+ export function readMeshNodeMachineId(node: Record<string, unknown>): string | undefined {
161
+ return readStringValue(
162
+ node.machineId,
163
+ node.machine_id,
164
+ readObjectRecord(node.machine)?.id,
165
+ readObjectRecord(node.machine)?.machineId,
166
+ readObjectRecord(node.lastProbe)?.machineId,
167
+ readObjectRecord(node.last_probe)?.machine_id,
168
+ readObjectRecord(readObjectRecord(node.lastProbe)?.machine)?.id,
169
+ readObjectRecord(readObjectRecord(node.lastProbe)?.machine)?.machineId,
170
+ readObjectRecord(readObjectRecord(node.last_probe)?.machine)?.id,
171
+ readObjectRecord(readObjectRecord(node.last_probe)?.machine)?.machine_id,
172
+ );
173
+ }
174
+
175
+ export function readMeshNodeDaemonId(node: Record<string, unknown>): string | undefined {
176
+ return readStringValue(
177
+ node.daemonId,
178
+ node.daemon_id,
179
+ readObjectRecord(node.machine)?.daemonId,
180
+ readObjectRecord(node.machine)?.daemon_id,
181
+ readObjectRecord(node.lastProbe)?.daemonId,
182
+ readObjectRecord(node.last_probe)?.daemon_id,
183
+ readObjectRecord(readObjectRecord(node.lastProbe)?.machine)?.daemonId,
184
+ readObjectRecord(readObjectRecord(node.lastProbe)?.machine)?.daemon_id,
185
+ readObjectRecord(readObjectRecord(node.last_probe)?.machine)?.daemonId,
186
+ readObjectRecord(readObjectRecord(node.last_probe)?.machine)?.daemon_id,
187
+ );
188
+ }
189
+
190
+ export function readMeshNodeHostname(node: Record<string, unknown>): string | undefined {
191
+ return readStringValue(
192
+ node.hostname,
193
+ node.host,
194
+ node.machineHostname,
195
+ node.machine_hostname,
196
+ readObjectRecord(node.machine)?.hostname,
197
+ readObjectRecord(node.machine)?.host,
198
+ readObjectRecord(node.lastProbe)?.hostname,
199
+ readObjectRecord(node.last_probe)?.hostname,
200
+ readObjectRecord(readObjectRecord(node.lastProbe)?.machine)?.hostname,
201
+ readObjectRecord(readObjectRecord(node.last_probe)?.machine)?.hostname,
202
+ );
203
+ }
204
+
205
+ function readMeshNodeDisplayMachineName(node: Record<string, unknown>): string | undefined {
206
+ return readStringValue(
207
+ node.machineName,
208
+ node.machine_name,
209
+ node.machineLabel,
210
+ node.machine_label,
211
+ node.machineNickname,
212
+ node.machine_nickname,
213
+ node.alias,
214
+ readObjectRecord(node.machine)?.name,
215
+ readObjectRecord(node.machine)?.displayName,
216
+ readObjectRecord(node.machine)?.display_name,
217
+ readObjectRecord(node.lastProbe)?.machineName,
218
+ readObjectRecord(node.last_probe)?.machine_name,
219
+ readObjectRecord(readObjectRecord(node.lastProbe)?.machine)?.name,
220
+ readObjectRecord(readObjectRecord(node.last_probe)?.machine)?.name,
221
+ readMeshNodeHostname(node),
222
+ );
223
+ }
224
+
225
+ function compactMeshIdentityEvidence(value: string | undefined): string | undefined {
226
+ if (!value) return undefined;
227
+ return value.length > 24 ? `${value.slice(0, 12)}…${value.slice(-8)}` : value;
228
+ }
229
+
230
+ export function buildMeshNodeMachineIdentity(node: Record<string, unknown>, opts: {
231
+ localMachineId?: string;
232
+ localDaemonId?: string;
233
+ coordinatorHostname?: string;
234
+ isSelfNode?: boolean;
235
+ }): Record<string, unknown> {
236
+ const machineId = readMeshNodeMachineId(node);
237
+ const daemonId = readMeshNodeDaemonId(node);
238
+ const hostname = readMeshNodeHostname(node);
239
+ const machineName = readMeshNodeDisplayMachineName(node);
240
+ const coordinatorHostname = readStringValue(opts.coordinatorHostname);
241
+ const machineIdMatches = Boolean(opts.localMachineId && machineId && opts.localMachineId === machineId);
242
+ const daemonIdMatches = Boolean(opts.localDaemonId && daemonId && daemonIdsEquivalent(opts.localDaemonId, daemonId));
243
+ const hostnameMatches = Boolean(
244
+ normalizeMeshHostname(hostname)
245
+ && normalizeMeshHostname(coordinatorHostname)
246
+ && normalizeMeshHostname(hostname) === normalizeMeshHostname(coordinatorHostname),
247
+ );
248
+ const sameMachine = opts.isSelfNode === true || machineIdMatches || daemonIdMatches || hostnameMatches;
249
+ const evidence: string[] = [];
250
+ for (const [label, value] of [['machineName', machineName], ['hostname', hostname], ['machineId', machineId], ['daemonId', daemonId]] as const) {
251
+ const compact = compactMeshIdentityEvidence(value);
252
+ if (compact) evidence.push(`${label}:${compact}`);
253
+ }
254
+ const locality = sameMachine ? 'same_machine' : (evidence.length > 0 ? 'remote_known' : 'remote_or_unknown');
255
+ const localityReason = sameMachine
256
+ ? (machineIdMatches ? 'matched coordinator machine id'
257
+ : daemonIdMatches ? 'matched coordinator daemon id'
258
+ : hostnameMatches ? 'matched coordinator hostname'
259
+ : 'selected coordinator node')
260
+ : evidence.length > 0
261
+ ? `known remote/other machine identity; no local coordinator match (${evidence.join(', ')})`
262
+ : 'no useful machine identity evidence available';
263
+ return {
264
+ daemonId,
265
+ machineId,
266
+ hostname,
267
+ machineName,
268
+ displayName: machineName || hostname || daemonId || machineId,
269
+ coordinatorHostname,
270
+ sameMachine,
271
+ locality,
272
+ localityReason,
273
+ identityEvidence: evidence,
274
+ };
275
+ }
276
+
277
+ // normalizeInlineMeshGitStatus / scoreInlineMeshGitStatus /
278
+ // buildInlineMeshTransitGitStatus were the standalone-side copies of the cloud
279
+ // transit git normalizers. They now delegate to @adhdev/mesh-shared so the two
280
+ // transports can no longer drift (e.g. on the submodule drop / evidence rules).
281
+
282
+ function normalizeInlineMeshGitStatus(
283
+ status: Record<string, unknown>,
284
+ node: any,
285
+ options?: { lastCheckedAt?: number },
286
+ ): Record<string, unknown> | undefined {
287
+ return sharedNormalizeGitStatus(status, readObjectRecord(node), options) as Record<string, unknown> | undefined;
288
+ }
289
+
290
+ export function buildInlineMeshTransitGitStatus(node: any): Record<string, unknown> | undefined {
291
+ return sharedPickBestTransitGitStatus(readObjectRecord(node), { lastCheckedAt: Date.now() }) as Record<string, unknown> | undefined;
292
+ }
293
+
294
+ export function shouldRefreshStalePendingAggregate(snapshot: any, options?: { requireDirectPeerTruth?: boolean }): boolean {
295
+ if (options?.requireDirectPeerTruth !== true || !Array.isArray(snapshot?.nodes)) return false;
296
+ return snapshot.nodes.some((node: any) => {
297
+ if (node?.gitProbePending !== true) return false;
298
+ const git = readObjectRecord(node?.git);
299
+ return !readBooleanValue(git.isGitRepo) && !readStringValue(git.branch, git.headCommit, git.upstream);
300
+ });
301
+ }
302
+
303
+ export function buildLivePeerGitConnection(connection: Record<string, unknown>, timestamp = new Date().toISOString()): Record<string, unknown> {
304
+ const source = readStringValue(connection.source);
305
+ const transport = readStringValue(connection.transport);
306
+ return {
307
+ ...connection,
308
+ perspective: readStringValue(connection.perspective) ?? 'selected_coordinator',
309
+ source: source && source !== 'not_reported' ? source : 'mesh_peer_status',
310
+ state: 'connected',
311
+ transport: transport && transport !== 'unknown' ? transport : 'direct',
312
+ reported: true,
313
+ reason: 'Live peer git snapshot reported by the selected coordinator.',
314
+ lastStateChangeAt: readStringValue(connection.lastStateChangeAt) ?? timestamp,
315
+ };
316
+ }
317
+
318
+ export function recordInlineMeshDirectGitTruth(
319
+ node: any,
320
+ git: Record<string, unknown>,
321
+ source: 'selected_coordinator_local_git' | 'selected_coordinator_mesh_p2p_git',
322
+ ): { reporterPlatform: string | null; reporterArch: string | null } {
323
+ if (!node || typeof node !== 'object' || Array.isArray(node)) {
324
+ return { reporterPlatform: null, reporterArch: null };
325
+ }
326
+ const checkedAt = readNumberValue(git.lastCheckedAt) ?? Date.now();
327
+ const updatedAt = new Date(checkedAt).toISOString();
328
+ const nextGit: Record<string, unknown> = {
329
+ ...git,
330
+ lastCheckedAt: checkedAt,
331
+ };
332
+ node.lastGit = {
333
+ source,
334
+ checkedAt,
335
+ status: nextGit,
336
+ };
337
+ node.last_git = node.lastGit;
338
+ node.machineStatus = 'online';
339
+ node.updatedAt = updatedAt;
340
+ node.lastSeenAt = updatedAt;
341
+ const repoRoot = readStringValue(nextGit.repoRoot);
342
+ if (repoRoot && !readStringValue(node.repoRoot)) node.repoRoot = repoRoot;
343
+ // Self-heal per-node platform/arch from the live probe. For a remote member
344
+ // this is the platform the member daemon reported in its git_status envelope
345
+ // (threaded through as reporter*); for the local coordinator's own / worktree
346
+ // nodes the git was computed locally (source 'selected_coordinator_local_git'
347
+ // ⇒ the workspace lives on THIS machine), so process.platform/process.arch is
348
+ // the correct value. Stamp into userOverrides — the exact fields
349
+ // buildMeshNodeCapabilityTags reads — only when absent, so an operator's
350
+ // explicit override is preserved and the value is corrected once per reconnect
351
+ // without any migration.
352
+ const isLocalSource = source === 'selected_coordinator_local_git';
353
+ const reporterPlatform = readStringValue(git.reporterPlatform) ?? (isLocalSource ? process.platform : null);
354
+ const reporterArch = readStringValue(git.reporterArch) ?? (isLocalSource ? process.arch : null);
355
+ stampNodeReporterPlatform(node, reporterPlatform, reporterArch);
356
+ // Mirror onto the in-memory node's dedicated reporter fields too (distinct
357
+ // from userOverrides). For a local_config mesh the caller also persists these
358
+ // to meshes.json via updateNode so the value survives a coordinator restart;
359
+ // for an inline/cache mesh this keeps the runtime object self-consistent.
360
+ if (reporterPlatform) node.reportedPlatform = reporterPlatform;
361
+ if (reporterArch) node.reportedArch = reporterArch;
362
+ return { reporterPlatform, reporterArch };
363
+ }
364
+
365
+ /**
366
+ * Fill node.userOverrides.platform/arch from a live report, but never overwrite a
367
+ * value that is already present (an operator override or an earlier report). Used
368
+ * by both the remote-member probe path and the local self-stamp path so the
369
+ * coordinator advertises each node's real OS instead of falling back to the
370
+ * coordinator's own process.platform.
371
+ */
372
+ function stampNodeReporterPlatform(node: any, platform: string | null, arch: string | null): void {
373
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return;
374
+ if (!platform && !arch) return;
375
+ const overrides = (node.userOverrides && typeof node.userOverrides === 'object' && !Array.isArray(node.userOverrides))
376
+ ? node.userOverrides as Record<string, unknown>
377
+ : {};
378
+ let changed = false;
379
+ if (platform && !readStringValue(overrides.platform)) { overrides.platform = platform; changed = true; }
380
+ if (arch && !readStringValue(overrides.arch)) { overrides.arch = arch; changed = true; }
381
+ if (changed) node.userOverrides = overrides;
382
+ }
383
+
384
+ /**
385
+ * Persist the live self-reported platform/arch onto the local meshes.json node
386
+ * record so capability-tag os=/arch= self-heals across coordinator restarts.
387
+ *
388
+ * The in-memory stamp done by recordInlineMeshDirectGitTruth lives on the
389
+ * mesh_status assembly object and is discarded after the response; only a
390
+ * `local_config` mesh has a backing meshes.json node to write through to. Inline
391
+ * cache/bootstrap meshes have no local node to update, so we no-op for them.
392
+ * Fire-and-forget (same pattern as the worktreeBootstrap writer) — a persistence
393
+ * failure must never block the status response.
394
+ */
395
+ export function persistNodeReporterPlatform(
396
+ meshSource: 'inline_cache' | 'inline_bootstrap' | 'local_config',
397
+ mesh: any,
398
+ nodeId: string | undefined,
399
+ reporter: { reporterPlatform: string | null; reporterArch: string | null },
400
+ ): void {
401
+ if (meshSource !== 'local_config') return;
402
+ const meshId = readStringValue(mesh?.id);
403
+ if (!meshId || !nodeId) return;
404
+ const reportedPlatform = reporter.reporterPlatform ?? undefined;
405
+ const reportedArch = reporter.reporterArch ?? undefined;
406
+ if (!reportedPlatform && !reportedArch) return;
407
+ void import('../config/mesh-config.js')
408
+ .then(({ updateNode }) => updateNode(meshId, nodeId, { reportedPlatform, reportedArch }))
409
+ .catch(() => { /* best-effort self-heal; never block status assembly */ });
410
+ }
411
+
412
+ function buildCachedInlineMeshGitStatus(node: any): Record<string, unknown> | undefined {
413
+ const liveGit = buildInlineMeshTransitGitStatus(node);
414
+ if (liveGit) return liveGit;
415
+
416
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
417
+ const cachedGit = readObjectRecord(cachedStatus.git);
418
+ if (!Object.keys(cachedGit).length) return undefined;
419
+ return normalizeInlineMeshGitStatus(cachedGit, node);
420
+ }
421
+
422
+ function shouldDiscardCachedInlineMeshStatus(node: any): boolean {
423
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
424
+ if (!Object.keys(cachedStatus).length) return false;
425
+ const cachedGit = readObjectRecord(cachedStatus.git);
426
+ const workspaceError = readStringValue(cachedStatus.error, node?.error);
427
+ if (workspaceError && /workspace must be an existing directory/i.test(workspaceError)) return true;
428
+ const isGitRepo = readBooleanValue(cachedGit.isGitRepo);
429
+ const branch = readStringValue(cachedGit.branch);
430
+ const headCommit = readStringValue(cachedGit.headCommit);
431
+ return isGitRepo === false && !branch && !headCommit;
432
+ }
433
+
434
+ function stripInlineMeshTransientNodeState(node: any): any {
435
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return node;
436
+ const {
437
+ cachedStatus,
438
+ lastGit: _lastGit,
439
+ last_git: _lastGitLegacy,
440
+ lastProbe: _lastProbe,
441
+ last_probe: _lastProbeLegacy,
442
+ error: _error,
443
+ health: _health,
444
+ machineStatus: _machineStatus,
445
+ lastSeenAt: _lastSeenAt,
446
+ last_seen_at: _lastSeenAtLegacy,
447
+ updatedAt: _updatedAt,
448
+ updated_at: _updatedAtLegacy,
449
+ activeSession: _activeSession,
450
+ active_session: _activeSessionLegacy,
451
+ activeSessionId: _activeSessionId,
452
+ active_session_id: _activeSessionIdLegacy,
453
+ sessionId: _sessionId,
454
+ session_id: _sessionIdLegacy,
455
+ providerType: _providerType,
456
+ provider_type: _providerTypeLegacy,
457
+ ...rest
458
+ } = node as Record<string, unknown>;
459
+ if (cachedStatus && !shouldDiscardCachedInlineMeshStatus(node)) {
460
+ return { ...rest, cachedStatus };
461
+ }
462
+ return rest;
463
+ }
464
+
465
+ function hasInlineMeshTransientNodeState(node: any): boolean {
466
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return false;
467
+ return 'cachedStatus' in node
468
+ || 'lastGit' in node
469
+ || 'last_git' in node
470
+ || 'lastProbe' in node
471
+ || 'last_probe' in node
472
+ || 'error' in node
473
+ || 'health' in node
474
+ || 'machineStatus' in node
475
+ || 'lastSeenAt' in node
476
+ || 'last_seen_at' in node
477
+ || 'updatedAt' in node
478
+ || 'updated_at' in node
479
+ || 'activeSession' in node
480
+ || 'active_session' in node
481
+ || 'activeSessionId' in node
482
+ || 'active_session_id' in node
483
+ || 'sessionId' in node
484
+ || 'session_id' in node
485
+ || 'providerType' in node
486
+ || 'provider_type' in node;
487
+ }
488
+
489
+ export function inlineMeshCarriesTransientNodeTruth(inlineMesh: any): boolean {
490
+ if (!inlineMesh || typeof inlineMesh !== 'object' || Array.isArray(inlineMesh)) return false;
491
+ if (!Array.isArray(inlineMesh.nodes) || inlineMesh.nodes.length === 0) return false;
492
+ return inlineMesh.nodes.some((node: any) => hasInlineMeshTransientNodeState(node));
493
+ }
494
+
495
+ export function readInlineMeshNodeId(node: any): string {
496
+ // 3-way (id / nodeId / node_id) via the shared normalizer. The old 2-way
497
+ // `id ?? nodeId` dropped the SQLite `node_id` form, so an inline-cached node
498
+ // that arrived in that form failed to reconcile against its cached twin.
499
+ return normalizeMeshNodeId(node) ?? '';
500
+ }
501
+
502
+ // A local worktree node whose workspace directory has been deleted from disk.
503
+ // The worktree was removed (or the machine pruned it) but the node still lingers
504
+ // in the inline mesh cache. Such a node has no live truth to confirm and must
505
+ // never be probed or counted toward direct-peer-truth — doing so blocks the
506
+ // graph with a permanent `direct_peer_truth_unavailable`. Deliberately narrow:
507
+ // it only fires for `isLocalWorktree === true` nodes with a recorded workspace
508
+ // that does not exist. Remote nodes and nodes whose workspace is present on disk
509
+ // are never matched, so a slow remote peer is still classified unavailable.
510
+ export function isDeadLocalWorktreeNode(node: any): boolean {
511
+ if (node?.isLocalWorktree !== true) return false;
512
+ const workspace = readStringValue(node?.workspace);
513
+ if (!workspace) return false;
514
+ return !fs.existsSync(workspace);
515
+ }
516
+
517
+ // Boundary normalization: reconcile a node's identity so `id` and `nodeId` both
518
+ // carry the same canonical value (any incoming form — id / nodeId / node_id — is
519
+ // absorbed by normalizeMeshNodeId, and the SQLite `node_id` leak is dropped).
520
+ // See foldMeshNodeIdentityToCanonical for why both fields are kept equal rather
521
+ // than collapsing to one. The rewrite is shallow (other runtime fields are
522
+ // preserved); records that already agree are returned unchanged so
523
+ // identity-equality fast paths hold.
524
+ export function foldMeshNodeIdentityToCanonical(node: any): any {
525
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return node;
526
+ const canonical = normalizeMeshNodeId(node);
527
+ if (canonical === undefined) return node;
528
+ // Save-boundary identity folding, applied IN PLACE. We DUAL-WRITE both `id`
529
+ // and `nodeId` to the single canonical value (and drop the SQLite `node_id`
530
+ // leak), rather than collapsing to one field. Two halves of the system read
531
+ // different field names: the mesh_status serializer emits `nodeId`, while the
532
+ // worktree clone path and get_mesh membership consumers read `node.id`.
533
+ // Folding to ONE form would break whichever side reads the other. Keeping
534
+ // both fields equal makes every reader correct AND makes the
535
+ // snapshot→cache→reconcile→snapshot round-trip form-stable (no field ever
536
+ // flips, because both always agree). Mutating in place (not returning a new
537
+ // object) preserves the cached node-object identity that callers warming an
538
+ // inline mesh from an already-shared snapshot rely on.
539
+ if (node.id === canonical && node.nodeId === canonical && node.node_id === undefined) return node;
540
+ node.id = canonical;
541
+ node.nodeId = canonical;
542
+ if ('node_id' in node) delete node.node_id;
543
+ return node;
544
+ }
545
+
546
+ export function normalizeInlineMeshNodeIdentity(inlineMesh: any): any {
547
+ if (!inlineMesh || typeof inlineMesh !== 'object' || Array.isArray(inlineMesh)) return inlineMesh;
548
+ if (!Array.isArray(inlineMesh.nodes) || inlineMesh.nodes.length === 0) return inlineMesh;
549
+ // Fold each node IN PLACE so the mesh object and its nodes array keep their
550
+ // identity — sanitizeInlineMesh and the cache-sharing callers depend on
551
+ // unchanged inputs returning the same reference.
552
+ for (const node of inlineMesh.nodes) foldMeshNodeIdentityToCanonical(node);
553
+ return inlineMesh;
554
+ }
555
+
556
+ export function sanitizeInlineMesh(inlineMesh: any): any {
557
+ if (!inlineMesh || typeof inlineMesh !== 'object' || Array.isArray(inlineMesh)) return inlineMesh;
558
+ if (!Array.isArray(inlineMesh.nodes)) return inlineMesh;
559
+ let changed = false;
560
+ const nodes = inlineMesh.nodes.map((node: any) => {
561
+ if (!hasInlineMeshTransientNodeState(node)) return node;
562
+ changed = true;
563
+ return stripInlineMeshTransientNodeState(node);
564
+ });
565
+ if (!changed) return inlineMesh;
566
+ return {
567
+ ...inlineMesh,
568
+ nodes,
569
+ };
570
+ }
571
+
572
+ export function reconcileInlineMeshCache(cached: any, incoming: any): any {
573
+ if (!cached || typeof cached !== 'object' || Array.isArray(cached)) return incoming;
574
+ if (!incoming || typeof incoming !== 'object' || Array.isArray(incoming)) return cached;
575
+ const cachedNodes = Array.isArray(cached.nodes) ? cached.nodes : [];
576
+ const incomingNodes = Array.isArray(incoming.nodes) ? incoming.nodes : [];
577
+ if (!cachedNodes.length || !incomingNodes.length) return { ...cached, ...incoming };
578
+
579
+ const cachedUpdatedAt = Date.parse(readStringValue(cached.updatedAt, cached.updated_at) || '');
580
+ const incomingUpdatedAt = Date.parse(readStringValue(incoming.updatedAt, incoming.updated_at) || '');
581
+ const preserveCachedMembership = Number.isFinite(cachedUpdatedAt)
582
+ && (!Number.isFinite(incomingUpdatedAt) || cachedUpdatedAt > incomingUpdatedAt);
583
+
584
+ const cachedById = new Map<string, any>();
585
+ for (const node of cachedNodes) {
586
+ const nodeId = readInlineMeshNodeId(node);
587
+ if (nodeId) cachedById.set(nodeId, node);
588
+ }
589
+
590
+ const mergedIncomingIds = new Set<string>();
591
+ const nodes = incomingNodes.map((incomingNode: any) => {
592
+ const nodeId = readInlineMeshNodeId(incomingNode);
593
+ const cachedNode = nodeId ? cachedById.get(nodeId) : undefined;
594
+ if (!cachedNode && preserveCachedMembership) return null;
595
+ if (nodeId) mergedIncomingIds.add(nodeId);
596
+ if (!cachedNode) return incomingNode;
597
+ if (hasInlineMeshTransientNodeState(incomingNode)) {
598
+ return { ...cachedNode, ...incomingNode };
599
+ }
600
+ return { ...stripInlineMeshTransientNodeState(cachedNode), ...incomingNode };
601
+ }).filter(Boolean);
602
+
603
+ // When the cached membership is authoritative (newer than the incoming
604
+ // snapshot), nodes that exist only in the cache must survive reconciliation.
605
+ // A freshly cloned worktree node lives only in the coordinator's cache until
606
+ // the next snapshot catches up; iterating incomingNodes alone would silently
607
+ // drop it, making the node invisible to get_mesh / membership reads even
608
+ // though worktree_bootstrap_complete already fired.
609
+ if (preserveCachedMembership) {
610
+ for (const cachedNode of cachedNodes) {
611
+ const nodeId = readInlineMeshNodeId(cachedNode);
612
+ if (nodeId && !mergedIncomingIds.has(nodeId)) {
613
+ nodes.push(cachedNode);
614
+ }
615
+ }
616
+ }
617
+
618
+ return {
619
+ ...cached,
620
+ ...incoming,
621
+ nodes,
622
+ };
623
+ }
624
+
625
+ function hasGitWorktreeChanges(git: Record<string, unknown> | null | undefined): boolean {
626
+ return countGitWorktreeChanges(git) > 0;
627
+ }
628
+
629
+ function countGitWorktreeChanges(git: Record<string, unknown> | null | undefined): number {
630
+ if (!git) return 0;
631
+ return Number(git.staged || 0)
632
+ + Number(git.modified || 0)
633
+ + Number(git.untracked || 0)
634
+ + Number(git.deleted || 0)
635
+ + Number(git.renamed || 0);
636
+ }
637
+
638
+ function getGitSubmoduleDriftState(git: Record<string, unknown> | null | undefined): { dirty: boolean; outOfSync: boolean } {
639
+ const submodules = Array.isArray(git?.submodules) ? git.submodules : [];
640
+ let dirty = false;
641
+ let outOfSync = false;
642
+ for (const entry of submodules) {
643
+ const submodule = readObjectRecord(entry);
644
+ if (readBooleanValue(submodule.dirty) === true) dirty = true;
645
+ if (readBooleanValue(submodule.outOfSync) === true || !!readStringValue(submodule.error)) outOfSync = true;
646
+ }
647
+ return { dirty, outOfSync };
648
+ }
649
+
650
+ function isInlineMeshAutoFastForwardEligible(git: Record<string, unknown> | null | undefined): boolean {
651
+ if (!git) return false;
652
+ if (readBooleanValue(git.isGitRepo) !== true) return false;
653
+ if (!readStringValue(git.branch)) return false;
654
+ if (!readStringValue(git.upstream)) return false;
655
+ const upstreamStatus = readStringValue(git.upstreamStatus, git.upstream_status);
656
+ if (upstreamStatus !== 'fresh') return false;
657
+ if ((readNumberValue(git.ahead) ?? 0) !== 0) return false;
658
+ if ((readNumberValue(git.behind) ?? 0) <= 0) return false;
659
+ const hasConflicts = readBooleanValue(git.hasConflicts)
660
+ ?? (Array.isArray(git.conflictFiles) && git.conflictFiles.length > 0);
661
+ if (hasConflicts) return false;
662
+ if ((readNumberValue(git.stashCount, git.stash_count) ?? 0) > 0) return false;
663
+ const submoduleDrift = getGitSubmoduleDriftState(git);
664
+ if (submoduleDrift.dirty || submoduleDrift.outOfSync) return false;
665
+ const dirty = readBooleanValue(git.dirty) ?? (countGitWorktreeChanges(git) > 0);
666
+ return dirty !== true && countGitWorktreeChanges(git) === 0;
667
+ }
668
+
669
+ export function deriveMeshNodeHealthFromGit(git: Record<string, unknown> | null | undefined): 'online' | 'dirty' | 'degraded' {
670
+ if (!git || readBooleanValue(git.isGitRepo) === false) return 'degraded';
671
+ const branch = readStringValue(git.branch);
672
+ if (!branch) return 'degraded';
673
+ const submoduleDrift = getGitSubmoduleDriftState(git);
674
+ if (submoduleDrift.outOfSync) return 'degraded';
675
+ if (submoduleDrift.dirty || hasGitWorktreeChanges(git)) return 'dirty';
676
+ return 'online';
677
+ }
678
+
679
+ function readMeshNodeLabel(status: Record<string, unknown>, node: any): string {
680
+ return readStringValue(status.nodeId, normalizeMeshNodeId(node)) ?? 'unknown';
681
+ }
682
+
683
+ function buildInlineMeshBranchConvergence(args: {
684
+ mesh: any;
685
+ node: any;
686
+ status: Record<string, unknown>;
687
+ }): Record<string, unknown> {
688
+ const git = readObjectRecord(args.status.git);
689
+ const nodeLabel = readMeshNodeLabel(args.status, args.node);
690
+ const defaultBranch = readStringValue(args.mesh?.defaultBranch) ?? 'main';
691
+ const branch = readStringValue(git.branch, args.node?.worktreeBranch) ?? null;
692
+ const upstream = readStringValue(git.upstream) ?? null;
693
+ const upstreamStatus = readStringValue(git.upstreamStatus, git.upstream_status)
694
+ ?? (upstream ? 'unchecked' : 'no_upstream');
695
+ const ahead = readNumberValue(git.ahead) ?? 0;
696
+ const behind = readNumberValue(git.behind) ?? 0;
697
+ const uncommittedChanges = countGitWorktreeChanges(git);
698
+ const hasConflicts = readBooleanValue(git.hasConflicts)
699
+ ?? (Array.isArray(git.conflictFiles) && git.conflictFiles.length > 0);
700
+ const base = {
701
+ defaultBranch,
702
+ branch,
703
+ upstream,
704
+ upstreamStatus,
705
+ ahead,
706
+ behind,
707
+ isWorktree: args.node?.isLocalWorktree === true || args.status.isLocalWorktree === true,
708
+ isDefaultBranch: branch === defaultBranch,
709
+ };
710
+
711
+ if (readBooleanValue(git.isGitRepo) !== true) {
712
+ return {
713
+ ...base,
714
+ status: 'blocked_review',
715
+ needsConvergence: true,
716
+ reason: 'git_status_unavailable',
717
+ nextStep: `Resolve git status for node '${nodeLabel}' before marking the task complete.`,
718
+ };
719
+ }
720
+
721
+ if (!branch) {
722
+ return {
723
+ ...base,
724
+ status: 'blocked_review',
725
+ needsConvergence: true,
726
+ reason: 'branch_unknown',
727
+ nextStep: `Inspect node '${nodeLabel}' git branch before deciding whether it is merged to ${defaultBranch}.`,
728
+ };
729
+ }
730
+
731
+ if (hasConflicts || uncommittedChanges > 0) {
732
+ return {
733
+ ...base,
734
+ status: 'not_mergeable',
735
+ needsConvergence: true,
736
+ reason: hasConflicts ? 'conflicts_present' : 'dirty_workspace',
737
+ nextStep: `Commit, checkpoint, or resolve node '${nodeLabel}' before any main convergence step.`,
738
+ };
739
+ }
740
+
741
+ if (branch === defaultBranch) {
742
+ if (upstream && upstreamStatus !== 'fresh') {
743
+ return {
744
+ ...base,
745
+ status: 'blocked_review',
746
+ needsConvergence: true,
747
+ reason: 'default_branch_upstream_unverified',
748
+ nextStep: `Refresh ${defaultBranch}'s upstream refs or resolve the fetch failure before declaring convergence complete for node '${nodeLabel}'.`,
749
+ };
750
+ }
751
+ if (ahead > 0 || behind > 0) {
752
+ return {
753
+ ...base,
754
+ status: 'blocked_review',
755
+ needsConvergence: true,
756
+ reason: 'default_branch_not_even_with_upstream',
757
+ nextStep: `Bring ${defaultBranch} even with its upstream before declaring convergence complete.`,
758
+ };
759
+ }
760
+ return {
761
+ ...base,
762
+ status: 'merged_to_main',
763
+ needsConvergence: false,
764
+ reason: 'clean_default_branch',
765
+ nextStep: null,
766
+ };
767
+ }
768
+
769
+ if (args.node?.isLocalWorktree === true || args.status.isLocalWorktree === true) {
770
+ return {
771
+ ...base,
772
+ status: 'cleanup_candidate',
773
+ needsConvergence: true,
774
+ reason: 'clean_non_default_worktree_branch',
775
+ nextStep: `Run mesh_refine_node(node_id: "${nodeLabel}") or explicitly classify this worktree as blocked_review/not_mergeable before ending the task.`,
776
+ };
777
+ }
778
+
779
+ if (upstream && upstreamStatus !== 'fresh') {
780
+ return {
781
+ ...base,
782
+ status: 'blocked_review',
783
+ needsConvergence: true,
784
+ reason: 'feature_branch_upstream_unverified',
785
+ nextStep: `Refresh branch '${branch}' upstream refs or resolve the fetch failure before deciding whether it is ready to merge into ${defaultBranch}.`,
786
+ };
787
+ }
788
+
789
+ if (!upstream || ahead > 0 || behind > 0) {
790
+ return {
791
+ ...base,
792
+ status: 'blocked_review',
793
+ needsConvergence: true,
794
+ reason: !upstream ? 'feature_branch_missing_upstream' : 'feature_branch_not_even_with_upstream',
795
+ nextStep: `Push or reconcile branch '${branch}', then merge it into ${defaultBranch} or mark it not_mergeable with a reason.`,
796
+ };
797
+ }
798
+
799
+ return {
800
+ ...base,
801
+ status: 'pushed_feature_branch_needs_merge',
802
+ needsConvergence: true,
803
+ reason: 'clean_non_default_branch',
804
+ nextStep: `Review and merge branch '${branch}' into ${defaultBranch}; do not report the task as fully complete while it remains off main.`,
805
+ };
806
+ }
807
+
808
+ export function applyInlineMeshBranchConvergence(mesh: any, node: any, status: Record<string, unknown>): void {
809
+ const git = readObjectRecord(status.git);
810
+ if (Object.keys(git).length === 0 && !status.gitProbePending) return;
811
+ const uncommittedChanges = countGitWorktreeChanges(git);
812
+ status.isDirty = uncommittedChanges > 0;
813
+ status.uncommittedChanges = uncommittedChanges;
814
+ status.branchConvergence = buildInlineMeshBranchConvergence({ mesh, node, status });
815
+ status.autoFastForwardEligible = isInlineMeshAutoFastForwardEligible(git);
816
+ if (status.autoFastForwardEligible) {
817
+ status.suggestedAction = 'auto_fast_forward';
818
+ } else {
819
+ delete status.suggestedAction;
820
+ }
821
+ }
822
+
823
+ export function summarizeInlineMeshBranchConvergence(nodes: Array<Record<string, unknown>>): Record<string, unknown> {
824
+ const followUps = nodes
825
+ .filter(node => {
826
+ if (readObjectRecord(node.branchConvergence).needsConvergence !== true) return false;
827
+ const workspace = typeof node.workspace === 'string' ? node.workspace : '';
828
+ if (workspace && !fs.existsSync(workspace)) return false;
829
+ return true;
830
+ })
831
+ .map(node => {
832
+ const convergence = readObjectRecord(node.branchConvergence);
833
+ return {
834
+ nodeId: node.nodeId,
835
+ workspace: node.workspace,
836
+ branch: convergence.branch,
837
+ status: convergence.status,
838
+ reason: convergence.reason,
839
+ nextStep: convergence.nextStep,
840
+ };
841
+ });
842
+
843
+ return {
844
+ needsFollowUp: followUps.length > 0,
845
+ unresolvedCount: followUps.length,
846
+ requiredFinalStates: ['merged_to_main', 'pushed_feature_branch_needs_merge', 'blocked_review', 'cleanup_candidate', 'not_mergeable'],
847
+ followUps,
848
+ };
849
+ }
850
+
851
+ export function readCachedInlineMeshActiveSessions(node: any): string[] {
852
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
853
+ const activeSession = readObjectRecord(cachedStatus.activeSession);
854
+ const fallbackSession = Object.keys(activeSession).length
855
+ ? activeSession
856
+ : readObjectRecord(node?.activeSession ?? node?.active_session);
857
+ const sessionId = readStringValue(fallbackSession.id, fallbackSession.sessionId, fallbackSession.session_id, node?.activeSessionId, node?.active_session_id, node?.sessionId, node?.session_id);
858
+ return sessionId ? [sessionId] : [];
859
+ }
860
+
861
+ /**
862
+ * Wider session-ownership scan used ONLY by resolveRemoteMeshSessionOwnerDaemonId: collect
863
+ * EVERY session id a mesh node currently hosts. readCachedInlineMeshActiveSessions above only
864
+ * surfaces the node's single primary session (cachedStatus.activeSession) — other consumers
865
+ * depend on that one-session semantics, so it is left untouched. A worker hosting more than one
866
+ * session exposes its non-primary sessions only through the plural live-session arrays the
867
+ * coordinator carries: status.activeSessions / activeSessionDetails (built from live records on
868
+ * the aggregate snapshot, see get_mesh_status), or a worker's merged session report. A
869
+ * controlbar/modal command (invoke_provider_script / resolve_action / set_mode / …) targeting a
870
+ * non-primary remote session resolves its owner daemon only when those plural shapes are scanned
871
+ * too. Mirrors sessionStatusFromNodes' shape tolerance (mesh-active-work.ts): plural arrays of
872
+ * string ids OR objects keyed by id/sessionId/session_id/runtimeSessionId/instanceId, on both
873
+ * camelCase and snake_case, at the node root and under cachedStatus / lastProbe.
874
+ */
875
+ export function collectMeshNodeHostedSessionIds(node: any): Set<string> {
876
+ const ids = new Set<string>();
877
+ for (const id of readCachedInlineMeshActiveSessions(node)) ids.add(id);
878
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
879
+ for (const value of [
880
+ node?.activeSessions,
881
+ node?.active_sessions,
882
+ node?.activeSessionDetails,
883
+ node?.active_session_details,
884
+ node?.sessions,
885
+ node?.sessionDetails,
886
+ node?.session_details,
887
+ readObjectRecord(node?.lastProbe).sessions,
888
+ readObjectRecord(node?.last_probe).sessions,
889
+ cachedStatus.activeSessions,
890
+ cachedStatus.active_sessions,
891
+ cachedStatus.activeSessionDetails,
892
+ cachedStatus.active_session_details,
893
+ cachedStatus.sessions,
894
+ ]) {
895
+ if (!Array.isArray(value)) continue;
896
+ for (const item of value) {
897
+ if (typeof item === 'string') {
898
+ const id = readStringValue(item);
899
+ if (id) ids.add(id);
900
+ continue;
901
+ }
902
+ const record = readObjectRecord(item);
903
+ const id = readStringValue(record.id, record.sessionId, record.session_id, record.runtimeSessionId, record.instanceId);
904
+ if (id) ids.add(id);
905
+ }
906
+ }
907
+ return ids;
908
+ }
909
+
910
+ /**
911
+ * Resolve the owning-node attribution for a mesh node record so a coordinator can
912
+ * stamp the TRUE owner onto a synthetic session entry instead of letting the
913
+ * dashboard fall back to the coordinator's own daemonId. Returns whichever of the
914
+ * owning node's `daemonId` / display machine name could be read from the node's
915
+ * (possibly multi-serialization-path) shape; both may be undefined for a node that
916
+ * never carried machine identity.
917
+ */
918
+ export function resolveMeshNodeAttribution(node: unknown): { daemonId?: string; machineName?: string } {
919
+ const record = readObjectRecord(node);
920
+ return {
921
+ daemonId: readMeshNodeDaemonId(record),
922
+ machineName: readMeshNodeDisplayMachineName(record),
923
+ };
924
+ }
925
+
926
+ export function readCachedInlineMeshActiveSessionDetails(node: any): Array<Record<string, unknown>> {
927
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
928
+ const activeSession = readObjectRecord(cachedStatus.activeSession);
929
+ const fallbackSession = Object.keys(activeSession).length
930
+ ? activeSession
931
+ : readObjectRecord(node?.activeSession ?? node?.active_session);
932
+ const sessionId = readStringValue(
933
+ fallbackSession.id,
934
+ fallbackSession.sessionId,
935
+ fallbackSession.session_id,
936
+ node?.activeSessionId,
937
+ node?.active_session_id,
938
+ node?.sessionId,
939
+ node?.session_id,
940
+ );
941
+ if (!sessionId) return [];
942
+ return [{
943
+ sessionId,
944
+ providerType: readStringValue(
945
+ fallbackSession.providerType,
946
+ fallbackSession.provider_type,
947
+ fallbackSession.cliType,
948
+ fallbackSession.cli_type,
949
+ fallbackSession.provider,
950
+ node?.providerType,
951
+ node?.provider_type,
952
+ ),
953
+ state: readStringValue(fallbackSession.status, fallbackSession.state, fallbackSession.lifecycle),
954
+ chatStatus: readStringValue(fallbackSession.chatStatus, fallbackSession.chat_status),
955
+ lifecycle: readStringValue(fallbackSession.lifecycle),
956
+ title: readStringValue(fallbackSession.title, fallbackSession.displayName, fallbackSession.display_name) ?? null,
957
+ workspace: readStringValue(fallbackSession.workspace, node?.workspace) ?? null,
958
+ role: readStringValue(fallbackSession.role) ?? null,
959
+ isSelfCoordinator: fallbackSession.isSelfCoordinator === true || fallbackSession.is_self_coordinator === true,
960
+ createdAt: readStringValue(fallbackSession.createdAt, fallbackSession.created_at) ?? null,
961
+ startedAt: readStringValue(fallbackSession.startedAt, fallbackSession.started_at) ?? null,
962
+ lastActivityAt: readStringValue(fallbackSession.lastActivityAt, fallbackSession.last_activity_at) ?? null,
963
+ recoveryState: readStringValue(fallbackSession.recoveryState, fallbackSession.recovery_state) ?? null,
964
+ // [T2] Carry the worker-computed last-message preview through the cached inline-mesh
965
+ // active-session entry. The worker's get_status_metadata slim now ships these
966
+ // (mesh-tools.ts), and this is the surface the coordinator's inbox-preview path reads
967
+ // (buildDaemonMetadataUpdateForSubscription → stampLocalAssistantPreviewOnCachedEntry).
968
+ // Without carrying them here, the coordinator could only derive the preview from a live
969
+ // in-process instance it doesn't host for a remote worker, so the inbox stuck on the
970
+ // dispatched user task. Only present when the worker reported them.
971
+ ...(readStringValue(fallbackSession.lastMessagePreview, fallbackSession.last_message_preview)
972
+ ? { lastMessagePreview: readStringValue(fallbackSession.lastMessagePreview, fallbackSession.last_message_preview) } : {}),
973
+ ...(readStringValue(fallbackSession.lastMessageRole, fallbackSession.last_message_role)
974
+ ? { lastMessageRole: readStringValue(fallbackSession.lastMessageRole, fallbackSession.last_message_role) } : {}),
975
+ ...(readNumberValue(fallbackSession.lastMessageAt, fallbackSession.last_message_at) !== undefined
976
+ ? { lastMessageAt: readNumberValue(fallbackSession.lastMessageAt, fallbackSession.last_message_at) } : {}),
977
+ isCached: true,
978
+ }];
979
+ }
980
+
981
+ function readLiveMeshSessionState(record: any): string | undefined {
982
+ return readStringValue(
983
+ record?.meta?.sessionStatus,
984
+ record?.meta?.status,
985
+ record?.meta?.providerStatus,
986
+ record?.status,
987
+ record?.state,
988
+ record?.lifecycle,
989
+ );
990
+ }
991
+
992
+ function toIsoTimestamp(value: unknown): string | null {
993
+ if (typeof value === 'number' && Number.isFinite(value)) return new Date(value).toISOString();
994
+ const stringValue = readStringValue(value);
995
+ return stringValue || null;
996
+ }
997
+
998
+ function synthesizeMeshNodeFreshnessFromConnection(status: Record<string, unknown>): void {
999
+ const connection = readObjectRecord(status.connection);
1000
+ const connectionFreshAt = toIsoTimestamp(connection.lastCommandAt ?? connection.lastConnectedAt ?? connection.lastStateChangeAt);
1001
+ const git = readObjectRecord(status.git);
1002
+ const gitCheckedAt = toIsoTimestamp(git.lastCheckedAt);
1003
+ if (!status.lastSeenAt && connectionFreshAt) status.lastSeenAt = connectionFreshAt;
1004
+ if (!status.updatedAt && (gitCheckedAt || connectionFreshAt)) {
1005
+ status.updatedAt = gitCheckedAt ?? connectionFreshAt;
1006
+ }
1007
+ }
1008
+
1009
+ /**
1010
+ * Transient per-node marker the mesh_status render loop stamps onto a node
1011
+ * `status` at the two sites that obtain git truth from a FRESH probe this call
1012
+ * (a successful local `getGitRepoStatus`, or a successful P2P `git_status`
1013
+ * round-trip). finalizeMeshNodeStatus consumes and deletes it. Held/standing
1014
+ * truth (node.lastGit / cachedStatus / inline transit) is deliberately NOT
1015
+ * stamped — its absence is exactly how the freshness marker tells "live" apart
1016
+ * from "cached". Internal only; never serialized in the response.
1017
+ */
1018
+ export const MESH_NODE_LIVE_TRUTH_MARKER = '__liveTruthProbed';
1019
+
1020
+ type MeshNodeDataSource =
1021
+ | 'self' // the selected coordinator's own node — local truth
1022
+ | 'live' // git/session truth confirmed by a fresh probe THIS call
1023
+ | 'cached' // rendered from held standing truth (possibly old — see staleness)
1024
+ | 'pending' // reachable/known but no probe attempted yet (default load)
1025
+ | 'unreachable' // peer could not be reached (P2P probe failed / not connected, no held truth)
1026
+ | 'empty' // reachable but genuinely no session + git data
1027
+ | 'unconfigured'; // node has no daemonId, so transport truth cannot be reported
1028
+
1029
+ type MeshNodeStaleness = 'fresh' | 'recent' | 'stale' | 'unknown';
1030
+
1031
+ // Staleness buckets (ms). Held/cached truth younger than FRESH reads as fresh,
1032
+ // younger than RECENT as recent, older as stale. Kept coarse on purpose — the
1033
+ // coordinator only needs "just-now / minutes-old / old", not millisecond precision.
1034
+ const MESH_FRESHNESS_FRESH_MS = 30_000;
1035
+ const MESH_FRESHNESS_RECENT_MS = 300_000;
1036
+
1037
+ function classifyMeshNodeStaleness(dataSource: MeshNodeDataSource, ageMs: number | null): MeshNodeStaleness {
1038
+ if (dataSource === 'self' || dataSource === 'live') return 'fresh';
1039
+ if (ageMs === null) return 'unknown';
1040
+ if (ageMs < MESH_FRESHNESS_FRESH_MS) return 'fresh';
1041
+ if (ageMs < MESH_FRESHNESS_RECENT_MS) return 'recent';
1042
+ return 'stale';
1043
+ }
1044
+
1045
+ /**
1046
+ * Build the additive per-node `dataFreshness` marker. This NEVER mutates any
1047
+ * existing field — it only adds an explicit, machine-readable answer to the
1048
+ * question the legacy fields blurred: is this node's data live (just probed),
1049
+ * cached (held truth, maybe old), or absent because the peer was unreachable?
1050
+ *
1051
+ * The crucial separation: an UNREACHABLE peer (P2P probe failed / not connected)
1052
+ * is no longer indistinguishable from an idle/EMPTY node. Both used to render as
1053
+ * `health:'unknown'` with no sessions; now `dataFreshness.dataSource` and
1054
+ * `reachable` tell them apart so a coordinator never reads a dead peer as "online
1055
+ * but doing nothing".
1056
+ */
1057
+ export function buildMeshNodeDataFreshness(args: {
1058
+ status: Record<string, unknown>;
1059
+ node?: any;
1060
+ isSelfNode: boolean;
1061
+ daemonId?: string;
1062
+ /** True when this node was stamped with a fresh live git probe this call. */
1063
+ liveTruthProbed: boolean;
1064
+ /** True when direct-peer-truth accounting classified this node unavailable. */
1065
+ directTruthUnavailable?: boolean;
1066
+ now?: () => number;
1067
+ }): Record<string, unknown> {
1068
+ const { status, node, isSelfNode, daemonId, liveTruthProbed, directTruthUnavailable } = args;
1069
+ const now = args.now ?? Date.now;
1070
+ const connection = readObjectRecord(status.connection);
1071
+ const connectionState = readStringValue(connection.state);
1072
+ const git = readObjectRecord(status.git);
1073
+ const hasGit = readBooleanValue(git.isGitRepo) === true
1074
+ || !!readStringValue(git.branch, git.headCommit, git.head, git.upstream);
1075
+ const connectionFreshAt = toIsoTimestamp(connection.lastCommandAt ?? connection.lastConnectedAt ?? connection.lastStateChangeAt);
1076
+ // Provenance-aware probe time. A FRESH probe this call writes a genuine
1077
+ // git.lastCheckedAt, so trust it for live nodes. Held/standing truth, however,
1078
+ // is re-normalized through pickBestTransitGitStatus which stamps lastCheckedAt
1079
+ // with Date.now() on assembly (git-normalize.ts) — so status.git.lastCheckedAt
1080
+ // would falsely read fresh. For cached nodes prefer the authentic peer-reported
1081
+ // check time persisted on node.lastGit.checkedAt / cachedStatus, so a genuinely
1082
+ // old cache is correctly reported stale.
1083
+ const liveGitCheckedAt = liveTruthProbed ? toIsoTimestamp(git.lastCheckedAt) : null;
1084
+ const heldGit = readObjectRecord(node?.lastGit ?? node?.last_git);
1085
+ const heldCheckedAt = toIsoTimestamp(heldGit.checkedAt ?? heldGit.checked_at);
1086
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
1087
+ const cachedGitCheckedAt = toIsoTimestamp(readObjectRecord(cachedStatus.git).lastCheckedAt);
1088
+ const lastProbeAt = liveGitCheckedAt
1089
+ ?? heldCheckedAt
1090
+ ?? cachedGitCheckedAt
1091
+ ?? toIsoTimestamp(git.lastCheckedAt)
1092
+ ?? connectionFreshAt
1093
+ ?? toIsoTimestamp(status.updatedAt)
1094
+ ?? toIsoTimestamp(status.lastSeenAt);
1095
+
1096
+ // connectionReachable: true (connected) / false (terminally down) / null (unknown,
1097
+ // not yet reported) — used so a cached/pending node carries the coordinator's last
1098
+ // known transport state rather than guessing.
1099
+ const connectionReachable: boolean | null = connectionState === 'connected'
1100
+ ? true
1101
+ : (!connectionState || connectionState === 'unknown' || connectionState === 'connecting')
1102
+ ? (connectionState === 'connecting' ? true : null)
1103
+ : false;
1104
+
1105
+ let dataSource: MeshNodeDataSource;
1106
+ let reachable: boolean | null;
1107
+ if (isSelfNode) {
1108
+ dataSource = 'self';
1109
+ reachable = true;
1110
+ } else if (liveTruthProbed) {
1111
+ dataSource = 'live';
1112
+ reachable = true;
1113
+ } else if (readBooleanValue(status.gitProbePending) === true) {
1114
+ dataSource = 'pending';
1115
+ reachable = connectionReachable;
1116
+ } else if (directTruthUnavailable) {
1117
+ dataSource = 'unreachable';
1118
+ reachable = false;
1119
+ } else if (hasGit) {
1120
+ dataSource = 'cached';
1121
+ reachable = connectionReachable;
1122
+ } else if (!daemonId) {
1123
+ dataSource = 'unconfigured';
1124
+ reachable = null;
1125
+ } else if (connectionState === 'connected') {
1126
+ dataSource = 'empty';
1127
+ reachable = true;
1128
+ } else {
1129
+ dataSource = 'unreachable';
1130
+ reachable = false;
1131
+ }
1132
+
1133
+ const probeOk = dataSource === 'live' || dataSource === 'self';
1134
+ let ageMs: number | null = null;
1135
+ if (lastProbeAt) {
1136
+ const parsed = Date.parse(lastProbeAt);
1137
+ if (Number.isFinite(parsed)) ageMs = Math.max(0, now() - parsed);
1138
+ }
1139
+ const staleness = classifyMeshNodeStaleness(dataSource, ageMs);
1140
+
1141
+ return {
1142
+ dataSource,
1143
+ probeOk,
1144
+ reachable,
1145
+ lastProbeAt: lastProbeAt ?? null,
1146
+ ageMs,
1147
+ staleness,
1148
+ };
1149
+ }
1150
+
1151
+ /**
1152
+ * Canonical live-probe → freshness adapter. The coordinator-facing mesh_status
1153
+ * (mcp-server `meshStatus`) builds each node entry from a SINGLE fresh git_status
1154
+ * probe that either returns (live truth) or throws (peer unreachable). It used to
1155
+ * hand-reconstruct the freshness INPUT inline — a synthetic `{ git, connection }`
1156
+ * status plus the directTruthUnavailable/liveTruthProbed wiring — which is exactly
1157
+ * how a field added to `buildMeshNodeDataFreshness`'s input contract ends up "wired
1158
+ * on the daemon surface, null on the coordinator surface" (the rc.371
1159
+ * null-everywhere regression). Routing every live-probe surface through this one
1160
+ * adapter keeps the marker derivation canonical: there is a SINGLE place that turns
1161
+ * a probe outcome into freshness args, so the two mesh_status surfaces cannot drift.
1162
+ *
1163
+ * `liveTruthProbed` true → the probe returned (live/self truth); false → it threw,
1164
+ * so a configured peer is unreachable while an unconfigured node (no daemonId) falls
1165
+ * through to the classifier's `unconfigured` branch.
1166
+ */
1167
+ export function buildMeshNodeProbeFreshness(args: {
1168
+ /** The git snapshot this probe stamped on the node entry (entry.git). */
1169
+ git: unknown;
1170
+ /** True when the fresh git_status probe RETURNED (live truth); false when it threw. */
1171
+ liveTruthProbed: boolean;
1172
+ isSelfNode: boolean;
1173
+ /** The node's resolved daemonId; absent → unconfigured node. */
1174
+ daemonId?: string;
1175
+ /** The mesh node record, for held-git fallback when the probe did not return live. */
1176
+ node?: any;
1177
+ now?: () => number;
1178
+ }): Record<string, unknown> {
1179
+ const { git, liveTruthProbed, isSelfNode, daemonId, node, now } = args;
1180
+ const status: Record<string, unknown> = {
1181
+ git,
1182
+ connection: { state: liveTruthProbed ? 'connected' : 'disconnected' },
1183
+ };
1184
+ if (liveTruthProbed) status[MESH_NODE_LIVE_TRUTH_MARKER] = true;
1185
+ return buildMeshNodeDataFreshness({
1186
+ status,
1187
+ node,
1188
+ isSelfNode,
1189
+ daemonId,
1190
+ liveTruthProbed,
1191
+ directTruthUnavailable: !liveTruthProbed && !!daemonId,
1192
+ now,
1193
+ });
1194
+ }
1195
+
1196
+ export function finalizeMeshNodeStatus(args: {
1197
+ status: Record<string, unknown>;
1198
+ node: any;
1199
+ daemonId?: string;
1200
+ isSelfNode: boolean;
1201
+ /** True when direct-peer-truth accounting classified this node unavailable. */
1202
+ directTruthUnavailable?: boolean;
1203
+ }): void {
1204
+ const { status, node, daemonId, isSelfNode, directTruthUnavailable } = args;
1205
+ if (!readStringValue(status.machineStatus)) {
1206
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
1207
+ const machineStatus = readStringValue(cachedStatus.machineStatus, cachedStatus.machine_status, node?.machineStatus);
1208
+ if (machineStatus) status.machineStatus = machineStatus;
1209
+ }
1210
+ synthesizeMeshNodeFreshnessFromConnection(status);
1211
+ // Stamp the additive freshness/reachability marker before any early return so
1212
+ // every node — including bootstrap-blocked ones — carries it. Consume and drop
1213
+ // the transient live-probe marker so it never leaks into the response.
1214
+ const liveTruthProbed = readBooleanValue(status[MESH_NODE_LIVE_TRUTH_MARKER]) === true;
1215
+ delete status[MESH_NODE_LIVE_TRUTH_MARKER];
1216
+ status.dataFreshness = buildMeshNodeDataFreshness({
1217
+ status,
1218
+ node,
1219
+ isSelfNode,
1220
+ daemonId,
1221
+ liveTruthProbed,
1222
+ directTruthUnavailable,
1223
+ });
1224
+ const bootstrap = readObjectRecord(node?.worktreeBootstrap);
1225
+ if (node?.isLocalWorktree && readStringValue(bootstrap.status)) {
1226
+ status.worktreeBootstrap = bootstrap;
1227
+ if (bootstrap.status === 'failed' && bootstrap.required !== false) {
1228
+ status.launchReady = false;
1229
+ status.launchBlockedReason = 'worktree_bootstrap_failed';
1230
+ status.launchBlockedMessage = readStringValue(bootstrap.error)
1231
+ || 'Required worktree bootstrap failed; resolve it before launching an agent into this node.';
1232
+ status.recoveryHint = 'Run retry_mesh_node_bootstrap to retry';
1233
+ return;
1234
+ }
1235
+ if (bootstrap.status === 'running' && bootstrap.required !== false) {
1236
+ status.launchReady = false;
1237
+ status.launchBlockedReason = 'worktree_bootstrap_running';
1238
+ status.launchBlockedMessage = 'Required worktree bootstrap is still running; wait for it to finish before launching an agent into this node.';
1239
+ return;
1240
+ }
1241
+ }
1242
+ const connectionState = readStringValue(readObjectRecord(status.connection).state);
1243
+ status.launchReady = !!daemonId && (
1244
+ readStringValue(status.machineStatus) === 'online'
1245
+ || connectionState === 'connected'
1246
+ || isSelfNode
1247
+ );
1248
+ }
1249
+
1250
+
1251
+ // Direct-peer git_status probe timeout for the dashboard's requireDirectPeerTruth
1252
+ // bootstrap. The previous hard-coded 8s/12s were shorter than the real P2P
1253
+ // round-trip to slow (often TURN-relayed) peers, so such a node was permanently
1254
+ // marked unavailable and blocked the whole mesh graph. Default raised to 25s
1255
+ // (still under the P2P REQUEST_TIMEOUT of 30s) and made env-overridable.
1256
+ export const MESH_DIRECT_PROBE_TIMEOUT_MS = readMeshTimeoutEnvMs('MESH_DIRECT_PROBE_TIMEOUT_MS', 25_000);
1257
+ export const MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS = readMeshTimeoutEnvMs('MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS', 25_000);
1258
+ // Cold-open warmup budget for the FIRST direct-peer probe to a peer whose mesh
1259
+ // DataChannel is not open yet. A fresh cross-machine, TURN-relayed handshake
1260
+ // (ICE gather + TURN allocation + DTLS across two residential networks) routinely
1261
+ // needs many seconds. Charging that warmup against the response deadline
1262
+ // (MESH_DIRECT_PROBE_TIMEOUT_MS) made the very first git_status to a cold peer
1263
+ // false-timeout, after which the warm retry — reusing the now-open channel —
1264
+ // succeeded: the classic cold-open signature. This budget bounds ONLY the
1265
+ // "channel not open yet" phase; once the channel opens the response deadline
1266
+ // governs the round trip. A genuine connect failure still rejects immediately —
1267
+ // the mesh manager fails the peer the instant its PeerConnection state goes
1268
+ // terminal, and isMeshConnectionDefinitivelyDown pre-gates an already-dead peer —
1269
+ // so this never masks a real failure for the whole window; it only grants a
1270
+ // still-handshaking peer the time it legitimately needs. Matches the daemon-cloud
1271
+ // DaemonMeshManager CONNECT_TIMEOUT_MS (45s). Env-overridable for very slow links.
1272
+ // Re-exported from the unified MESH_CONNECT_TIMEOUT_MS (runtime-defaults) so this
1273
+ // probe path and the coordinator's remote task-dispatch path share ONE
1274
+ // env-overridable connect budget instead of silently diverging when the env is set.
1275
+ export const MESH_DIRECT_PROBE_CONNECT_TIMEOUT_MS = MESH_CONNECT_TIMEOUT_MS;
1276
+ // How long a successful per-peer git_status probe stays fresh enough to be
1277
+ // reused instead of issuing another blocking `refreshUpstream:true` fan-out.
1278
+ // A slow (TURN-relayed) peer's probe can take 9-23s, and the dashboard's
1279
+ // auto-retry loop re-fires every few seconds; without this gate every retry
1280
+ // would start a brand new probe storm to the same peer. Within this window the
1281
+ // last successful result is reused so a refresh quiesces instead of looping.
1282
+ // Min-clamped to 1s by readMeshTimeoutEnvMs; raise via env for very slow peers.
1283
+ export const MESH_DIRECT_PROBE_REUSE_MS = readMeshTimeoutEnvMs('MESH_DIRECT_PROBE_REUSE_MS', 12_000);
1284
+
1285
+ /**
1286
+ * De-duplicates and rate-limits per-peer git_status probes so a single mesh
1287
+ * refresh — or a burst of refreshes from the dashboard auto-retry loop — cannot
1288
+ * launch a storm of concurrent/back-to-back `refreshUpstream:true` commands to
1289
+ * the same slow peer.
1290
+ *
1291
+ * Two gates, both keyed by `daemonId::workspace`:
1292
+ * - In-flight dedup: a second probe for a key with a probe already running
1293
+ * shares (awaits) the in-flight promise instead of issuing a second command.
1294
+ * - Recently-probed reuse: a successful probe younger than `reuseMs` is reused
1295
+ * verbatim instead of issuing a fresh probe. Failures are NOT cached (so a
1296
+ * transient timeout doesn't pin a peer to "no truth" for the whole window).
1297
+ *
1298
+ * Lives on the router instance so the gate spans separate mesh_status calls,
1299
+ * which is exactly where the refresh storm happens.
1300
+ */
1301
+ export class MeshGitProbeCache {
1302
+ private inflight = new Map<string, Promise<Record<string, unknown> | null>>();
1303
+ private recent = new Map<string, { at: number; value: Record<string, unknown> }>();
1304
+
1305
+ constructor(private readonly reuseMs: number, private readonly now: () => number = Date.now) {}
1306
+
1307
+ private key(daemonId: string, workspace: string): string {
1308
+ return `${daemonId}::${workspace}`;
1309
+ }
1310
+
1311
+ /**
1312
+ * Run `probe` for this peer, but reuse a fresh recent result or an in-flight
1313
+ * probe for the same key when one is available. `probe` is only invoked when
1314
+ * neither gate is satisfied.
1315
+ */
1316
+ async probe(
1317
+ daemonId: string,
1318
+ workspace: string,
1319
+ probe: () => Promise<Record<string, unknown> | null>,
1320
+ ): Promise<Record<string, unknown> | null> {
1321
+ const key = this.key(daemonId, workspace);
1322
+ const cached = this.recent.get(key);
1323
+ if (cached && this.now() - cached.at < this.reuseMs) {
1324
+ return cached.value;
1325
+ }
1326
+ const existing = this.inflight.get(key);
1327
+ if (existing) return existing;
1328
+ const pending = (async () => {
1329
+ const result = await probe();
1330
+ if (result) this.recent.set(key, { at: this.now(), value: result });
1331
+ return result;
1332
+ })();
1333
+ this.inflight.set(key, pending);
1334
+ try {
1335
+ return await pending;
1336
+ } finally {
1337
+ // Only clear the slot if it is still ours — a later overlapping call
1338
+ // would have reused this very promise, so it is safe to delete here.
1339
+ if (this.inflight.get(key) === pending) this.inflight.delete(key);
1340
+ }
1341
+ }
1342
+ }
1343
+
1344
+ // The warmup-aware deadline now lives in the dependency-free mesh leaf so BOTH the
1345
+ // dashboard git_status probe (here) and the general task-dispatch path
1346
+ // (mesh/mesh-events-coordinator.ts) can share it without an import cycle. Re-exported
1347
+ // for the existing `from '../commands/router.js'` callers/tests.
1348
+ export { awaitWithWarmupDeadline };
1349
+
1350
+ async function probeRemoteMeshGitStatus(args: {
1351
+ dispatchMeshCommand?: (daemonId: string, cmd: string, args: Record<string, unknown>) => Promise<unknown>;
1352
+ daemonId: string;
1353
+ workspace: string;
1354
+ // Response deadline — applies only once the peer's DataChannel is open (warm).
1355
+ responseTimeoutMs: number;
1356
+ // Cold-open warmup budget — applies only while the channel is still opening.
1357
+ connectTimeoutMs: number;
1358
+ // Live peer connection snapshot getter; lets the deadline tell "still warming
1359
+ // up" apart from "warm but slow". Absent → degrade conservatively (fail-loud,
1360
+ // combined connect+response window) rather than silently assuming "always warm"
1361
+ // — see resolveWarmupDeadlineOpts.
1362
+ getConnection?: (daemonId: string) => Record<string, unknown> | null;
1363
+ }): Promise<Record<string, unknown> | null> {
1364
+ if (!args.dispatchMeshCommand) return null;
1365
+ // Fire the dispatch first — this is what drives the mesh manager to ensure /
1366
+ // open the peer connection. The warmup-aware deadline then charges the
1367
+ // cold-open handshake to the connect budget and only the warm round trip to
1368
+ // the response budget, so the first probe to a cold peer is no longer
1369
+ // false-timed-out before its channel has even opened.
1370
+ const dispatch = args.dispatchMeshCommand(args.daemonId, 'git_status', { workspace: args.workspace, refreshUpstream: true });
1371
+ // A missing connection getter no longer silently becomes `() => true`
1372
+ // ("always warm") — that charged a still-opening channel against the response
1373
+ // budget and re-introduced the cold-open false-timeout. resolveWarmupDeadlineOpts
1374
+ // warns once per peer and grants the combined budget instead.
1375
+ const remoteResult = await awaitWithWarmupDeadline(dispatch, resolveWarmupDeadlineOpts({
1376
+ getConnection: args.getConnection,
1377
+ daemonId: args.daemonId,
1378
+ connectTimeoutMs: args.connectTimeoutMs,
1379
+ responseTimeoutMs: args.responseTimeoutMs,
1380
+ onMissingGetter: warnMeshWarmupGetterMissingOnce,
1381
+ })) as any;
1382
+ const remoteGit = remoteResult?.status ?? remoteResult?.git ?? remoteResult;
1383
+ if (!remoteGit || typeof remoteGit !== 'object' || typeof remoteGit.isGitRepo !== 'boolean') return null;
1384
+ // The member daemon stamps its own platform/arch onto the git_status result
1385
+ // envelope (see git-commands.ts). Reflect them onto the returned git object
1386
+ // under non-colliding reporter* keys so recordInlineMeshDirectGitTruth can
1387
+ // persist them to node.userOverrides without touching the git status shape.
1388
+ const reporterPlatform = readStringValue(remoteResult?.reporterPlatform);
1389
+ const reporterArch = readStringValue(remoteResult?.reporterArch);
1390
+ const git = remoteGit as Record<string, unknown>;
1391
+ if (reporterPlatform) git.reporterPlatform = reporterPlatform;
1392
+ if (reporterArch) git.reporterArch = reporterArch;
1393
+ return git;
1394
+ }
1395
+
1396
+ /** Number of bounded retries after the initial direct-peer git probe attempt. */
1397
+ const MESH_DIRECT_PROBE_MAX_RETRIES = 2;
1398
+
1399
+ function readMeshConnectionState(connection: Record<string, unknown> | null | undefined): string | undefined {
1400
+ return readStringValue((connection as any)?.state);
1401
+ }
1402
+
1403
+ // Fail-loud (but throttled) trace for the degraded-warmup case: a direct-peer mesh
1404
+ // dispatch ran with NO live connection getter wired. This is a misconfiguration in a
1405
+ // P2P-capable daemon (the getter should be present), and the old `() => true`
1406
+ // fallback hid it while silently re-introducing the cold-open false-timeout. Warn
1407
+ // once per peer so the degrade is visible without flooding the log on every probe.
1408
+ const meshWarmupGetterMissingWarned = new Set<string>();
1409
+ function warnMeshWarmupGetterMissingOnce(daemonId: string): void {
1410
+ if (meshWarmupGetterMissingWarned.has(daemonId)) return;
1411
+ meshWarmupGetterMissingWarned.add(daemonId);
1412
+ LOG.warn('Mesh', `Mesh peer connection getter unavailable for ${String(daemonId).slice(0, 12)}; warmup deadline degraded to the combined connect+response window (cannot observe DataChannel open). This avoids a cold-open false-timeout but loses warm/cold precision — wire getMeshPeerConnectionStatus on this daemon.`);
1413
+ }
1414
+
1415
+ /**
1416
+ * Connection states that mean the peer is definitively NOT reachable right now —
1417
+ * an offline machine (no peer entry at all) or a transport that has dropped
1418
+ * (failed/closed/disconnected). Probing such a peer would just burn the full
1419
+ * MESH_DIRECT_PROBE_TIMEOUT_MS window before timing out, so the cold-open of the
1420
+ * mesh graph stalls 25s behind one powered-off node. `connecting` is deliberately
1421
+ * NOT here: a peer mid-handshake may complete during the probe window, so it still
1422
+ * gets its attempt. Held standing git truth is consulted by the caller BEFORE this
1423
+ * runs, so the invariant "connected+held is never unavailable" is untouched — this
1424
+ * only short-circuits a peer that has no usable transport to probe over.
1425
+ */
1426
+ function isMeshConnectionDefinitivelyDown(
1427
+ connection: Record<string, unknown> | null | undefined,
1428
+ ): boolean {
1429
+ if (!connection) return true;
1430
+ const state = readMeshConnectionState(connection);
1431
+ return state === 'failed' || state === 'closed' || state === 'disconnected';
1432
+ }
1433
+
1434
+ /**
1435
+ * Probe a remote peer's git_status with a bounded retry budget, but only while
1436
+ * the peer is reported `connected`. A single slow (often TURN-relayed) peer can
1437
+ * exceed one probe window; retrying — with the connection re-checked before each
1438
+ * attempt so we abandon a peer that dropped — recovers it without blocking the
1439
+ * mesh forever. Shared by the bootstrap hydrate path and the per-node render
1440
+ * path so both treat a connected-but-slow peer identically.
1441
+ *
1442
+ * Returns the git status on success, or null if every attempt failed/timed out
1443
+ * (caller decides how to classify). `getConnection` is consulted before each
1444
+ * attempt; a non-`connected` state short-circuits the retry loop (the very first
1445
+ * attempt always runs so a missing connection getter still gets one try).
1446
+ */
1447
+ export async function probeRemoteMeshGitStatusWithRetry(args: {
1448
+ dispatchMeshCommand?: (daemonId: string, cmd: string, args: Record<string, unknown>) => Promise<unknown>;
1449
+ daemonId: string;
1450
+ workspace: string;
1451
+ timeoutMs: number;
1452
+ /** Per-attempt timeout for retries (attempts > 0); defaults to timeoutMs. */
1453
+ retryTimeoutMs?: number;
1454
+ /** Cold-open warmup budget per attempt; defaults to MESH_DIRECT_PROBE_CONNECT_TIMEOUT_MS. */
1455
+ connectTimeoutMs?: number;
1456
+ getConnection?: (daemonId: string) => Record<string, unknown> | null;
1457
+ onConnection?: (connection: Record<string, unknown>) => void;
1458
+ }): Promise<Record<string, unknown> | null> {
1459
+ // Fast-fail an offline / dropped peer BEFORE the first attempt. Previously the
1460
+ // liveness re-check only ran *between* attempts, so a powered-off node still ate
1461
+ // the full first MESH_DIRECT_PROBE_TIMEOUT_MS (25s) window — stalling the mesh
1462
+ // graph cold-open behind one dead machine. If a connection getter is wired and
1463
+ // it reports the peer as definitively down (no peer entry / failed / closed /
1464
+ // disconnected), skip straight to "no truth" instead of awaiting a 25s timeout.
1465
+ // A `connecting` peer still gets its attempt (it may complete mid-probe). No
1466
+ // onConnection side effect here: this is a pure liveness gate, and the caller's
1467
+ // own connection read already seeds status.connection — only the between-attempt
1468
+ // path needs to surface a freshly-observed connection.
1469
+ if (args.getConnection && isMeshConnectionDefinitivelyDown(args.getConnection(args.daemonId))) {
1470
+ return null;
1471
+ }
1472
+ for (let attempt = 0; attempt <= MESH_DIRECT_PROBE_MAX_RETRIES; attempt += 1) {
1473
+ if (attempt > 0) {
1474
+ // Re-check liveness before spending another probe window; a peer that
1475
+ // dropped between attempts is not worth retrying.
1476
+ const connection = args.getConnection?.(args.daemonId);
1477
+ if (args.getConnection && readMeshConnectionState(connection) !== 'connected') break;
1478
+ if (connection) args.onConnection?.(connection);
1479
+ // Exponential backoff: 250ms, 500ms before attempts 1 and 2.
1480
+ await new Promise(resolve => setTimeout(resolve, 250 * 2 ** (attempt - 1)));
1481
+ }
1482
+ try {
1483
+ const remoteGit = await probeRemoteMeshGitStatus({
1484
+ dispatchMeshCommand: args.dispatchMeshCommand,
1485
+ daemonId: args.daemonId,
1486
+ workspace: args.workspace,
1487
+ responseTimeoutMs: attempt === 0 ? args.timeoutMs : (args.retryTimeoutMs ?? args.timeoutMs),
1488
+ connectTimeoutMs: args.connectTimeoutMs ?? MESH_DIRECT_PROBE_CONNECT_TIMEOUT_MS,
1489
+ getConnection: args.getConnection,
1490
+ });
1491
+ if (remoteGit) return remoteGit;
1492
+ } catch {
1493
+ // Timed out or P2P error — fall through to the next bounded attempt.
1494
+ }
1495
+ }
1496
+ return null;
1497
+ }
1498
+
1499
+ export async function hydrateInlineMeshDirectTruth(args: {
1500
+ mesh: any;
1501
+ meshSource: 'inline_cache' | 'inline_bootstrap' | 'local_config';
1502
+ dispatchMeshCommand?: (daemonId: string, cmd: string, args: Record<string, unknown>) => Promise<unknown>;
1503
+ getMeshPeerConnectionStatus?: (daemonId: string) => Record<string, unknown> | null;
1504
+ statusInstanceId?: string;
1505
+ localMachineId?: string;
1506
+ // Standing-state model: the default (non-refresh) bootstrap load must NOT
1507
+ // fan out a blocking git_status probe to every peer — a single slow
1508
+ // (TURN-relayed) peer would time out and mark the whole mesh unavailable,
1509
+ // blocking the graph. When false, a non-local node is satisfied from its
1510
+ // held standing git truth (lastGit / cachedStatus reflected via mesh
1511
+ // events) and is never pushed to unavailableNodeIds merely because no live
1512
+ // probe was attempted. Only an explicit refresh (probeRemotePeers=true)
1513
+ // performs the fan-out and classifies an unreachable peer as unavailable.
1514
+ probeRemotePeers: boolean;
1515
+ // Optional shared probe cache: dedups concurrent probes and reuses a
1516
+ // recently-probed peer's result instead of re-issuing a blocking
1517
+ // refreshUpstream probe within the reuse window.
1518
+ probeCache?: MeshGitProbeCache;
1519
+ }): Promise<{
1520
+ directEvidenceCount: number;
1521
+ localConfirmedCount: number;
1522
+ peerAttemptedCount: number;
1523
+ peerConfirmedCount: number;
1524
+ standingEvidenceCount: number;
1525
+ unavailableNodeIds: string[];
1526
+ deadNodeIds: string[];
1527
+ }> {
1528
+ const nodes = Array.isArray(args.mesh?.nodes) ? args.mesh.nodes : [];
1529
+ if (!nodes.length) {
1530
+ return {
1531
+ directEvidenceCount: 0,
1532
+ localConfirmedCount: 0,
1533
+ peerAttemptedCount: 0,
1534
+ peerConfirmedCount: 0,
1535
+ standingEvidenceCount: 0,
1536
+ unavailableNodeIds: [],
1537
+ deadNodeIds: [],
1538
+ };
1539
+ }
1540
+
1541
+ const selectedCoordinatorNodeId = readStringValue(
1542
+ args.mesh?.coordinator?.preferredNodeId,
1543
+ nodes[0]?.id,
1544
+ nodes[0]?.nodeId,
1545
+ );
1546
+
1547
+ let localConfirmedCount = 0;
1548
+ let peerAttemptedCount = 0;
1549
+ let peerConfirmedCount = 0;
1550
+ let standingEvidenceCount = 0;
1551
+ const unavailableNodeIds: string[] = [];
1552
+ const deadNodeIds: string[] = [];
1553
+
1554
+ for (const [nodeIndex, node] of nodes.entries()) {
1555
+ const nodeId = normalizeMeshNodeId(node) || `node_${nodeIndex}`;
1556
+ const workspace = readStringValue(node?.workspace);
1557
+ const daemonId = readStringValue(node?.daemonId);
1558
+ const isSelfNode = Boolean(
1559
+ nodeId && selectedCoordinatorNodeId && nodeId === selectedCoordinatorNodeId,
1560
+ ) || Boolean(
1561
+ daemonId && (daemonIdsEquivalent(daemonId, args.localMachineId) || daemonIdsEquivalent(daemonId, args.statusInstanceId)),
1562
+ ) || Boolean(args.meshSource !== 'local_config' && nodeIndex === 0);
1563
+
1564
+ // A dead local worktree owned by this coordinator (isLocalWorktree, the
1565
+ // node's daemon is us, workspace path gone) has no live truth and cannot
1566
+ // be probed — the directory it would self-probe no longer exists. Exclude
1567
+ // it entirely from direct-peer-truth accounting: do not probe it, do not
1568
+ // attempt it, do not push it to unavailableNodeIds (which would otherwise
1569
+ // wedge the graph in a permanent direct_peer_truth_unavailable). This is
1570
+ // strictly self + isLocalWorktree + absent-path; remote peers and nodes
1571
+ // whose workspace still exists are unaffected and stay classifiable.
1572
+ const isSelfDaemonNode = Boolean(
1573
+ daemonId && (daemonIdsEquivalent(daemonId, args.localMachineId) || daemonIdsEquivalent(daemonId, args.statusInstanceId)),
1574
+ );
1575
+ if ((isSelfNode || isSelfDaemonNode) && isDeadLocalWorktreeNode(node)) {
1576
+ deadNodeIds.push(nodeId);
1577
+ continue;
1578
+ }
1579
+
1580
+ if (!workspace) {
1581
+ if (!isSelfNode && daemonId) unavailableNodeIds.push(nodeId);
1582
+ continue;
1583
+ }
1584
+
1585
+ if (fs.existsSync(workspace)) {
1586
+ try {
1587
+ const localGit = await getGitRepoStatus(workspace, { timeoutMs: 10_000, refreshUpstream: true });
1588
+ if (localGit?.isGitRepo) {
1589
+ const reporter = recordInlineMeshDirectGitTruth(node, localGit as unknown as Record<string, unknown>, 'selected_coordinator_local_git');
1590
+ persistNodeReporterPlatform(args.meshSource, args.mesh, nodeId, reporter);
1591
+ localConfirmedCount += 1;
1592
+ continue;
1593
+ }
1594
+ } catch {
1595
+ // Fall through to remote classification.
1596
+ }
1597
+ }
1598
+
1599
+ // Standing-state first: a non-local peer's held git truth (reflected
1600
+ // from its self-emitted mesh events into node.lastGit / cachedStatus)
1601
+ // counts as direct evidence without any probe. On the default load this
1602
+ // is the ONLY thing we consult — no fan-out, so one slow peer can't
1603
+ // block the bootstrap.
1604
+ const standingGit = buildInlineMeshTransitGitStatus(node);
1605
+ if (standingGit) {
1606
+ standingEvidenceCount += 1;
1607
+ continue;
1608
+ }
1609
+
1610
+ if (!args.probeRemotePeers) {
1611
+ // Default (non-refresh) load: a peer with no held truth yet is left
1612
+ // pending (the per-node loop marks it gitProbePending and the graph
1613
+ // shows setup inventory for it). It is NOT unavailable — the graph
1614
+ // must still render. An explicit refresh will fan out and freshen it.
1615
+ continue;
1616
+ }
1617
+
1618
+ if (!daemonId || !args.dispatchMeshCommand) {
1619
+ if (!isSelfNode) unavailableNodeIds.push(nodeId);
1620
+ continue;
1621
+ }
1622
+
1623
+ peerAttemptedCount += 1;
1624
+ // Bounded retry, gated on the peer staying `connected`: a slow
1625
+ // (TURN-relayed) peer that just exceeds one probe window is recovered
1626
+ // instead of being hard-failed. The connection is re-checked before each
1627
+ // retry so a peer that actually dropped is abandoned promptly. Routed
1628
+ // through the shared probe cache so a refresh burst reuses a recent
1629
+ // result / shares an in-flight probe instead of storming the peer.
1630
+ const runProbe = () => probeRemoteMeshGitStatusWithRetry({
1631
+ dispatchMeshCommand: args.dispatchMeshCommand,
1632
+ daemonId,
1633
+ workspace,
1634
+ timeoutMs: MESH_DIRECT_PROBE_TIMEOUT_MS,
1635
+ retryTimeoutMs: MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS,
1636
+ connectTimeoutMs: MESH_DIRECT_PROBE_CONNECT_TIMEOUT_MS,
1637
+ getConnection: args.getMeshPeerConnectionStatus,
1638
+ });
1639
+ const remoteGit = args.probeCache
1640
+ ? await args.probeCache.probe(daemonId, workspace, runProbe)
1641
+ : await runProbe();
1642
+ if (remoteGit) {
1643
+ const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, 'selected_coordinator_mesh_p2p_git');
1644
+ persistNodeReporterPlatform(args.meshSource, args.mesh, nodeId, reporter);
1645
+ peerConfirmedCount += 1;
1646
+ continue;
1647
+ }
1648
+
1649
+ // Invariant: a connected peer that still holds standing git truth is
1650
+ // never classified unavailable (standingGit short-circuited above, so by
1651
+ // here there is no held truth). Only push to unavailable when the peer is
1652
+ // not currently connected, or it is connected but every bounded probe
1653
+ // failed — that is the genuine "connected, no truth, retries exhausted"
1654
+ // case that drives the explicit-refresh hard-fail.
1655
+ unavailableNodeIds.push(nodeId);
1656
+ }
1657
+
1658
+ return {
1659
+ directEvidenceCount: localConfirmedCount + peerConfirmedCount + standingEvidenceCount,
1660
+ localConfirmedCount,
1661
+ peerAttemptedCount,
1662
+ peerConfirmedCount,
1663
+ standingEvidenceCount,
1664
+ unavailableNodeIds,
1665
+ deadNodeIds,
1666
+ };
1667
+ }
1668
+
1669
+ export function summarizeMeshSessionRecord(record: any): Record<string, unknown> {
1670
+ const meta = readObjectRecord(record?.meta);
1671
+ const isSelfCoordinator = Boolean(readStringValue(meta.meshCoordinatorFor));
1672
+ const chatStatus = readStringValue(record?.chatStatus, record?.activeChat?.status, meta.chatStatus, meta.sessionStatus);
1673
+ const state = readLiveMeshSessionState(record);
1674
+ const statusNote = isSelfCoordinator && (!chatStatus || chatStatus === 'idle' || state === 'idle')
1675
+ ? 'Coordinator self status is sampled from the session host and may read idle while the coordinator is generating this response.'
1676
+ : null;
1677
+ return {
1678
+ sessionId: readStringValue(record?.sessionId) || 'unknown',
1679
+ providerType: readStringValue(record?.providerType),
1680
+ state,
1681
+ chatStatus,
1682
+ lifecycle: readStringValue(record?.lifecycle),
1683
+ surfaceKind: getSessionHostSurfaceKind(record as any),
1684
+ recoveryState: readStringValue(meta.runtimeRecoveryState) ?? null,
1685
+ workspace: readStringValue(record?.workspace) ?? null,
1686
+ title: readStringValue(record?.displayName, record?.workspaceLabel) ?? null,
1687
+ role: isSelfCoordinator ? 'coordinator' : readStringValue(meta.meshRole, meta.role) ?? null,
1688
+ isSelfCoordinator,
1689
+ statusNote,
1690
+ createdAt: toIsoTimestamp(record?.createdAt ?? record?.created_at),
1691
+ startedAt: toIsoTimestamp(record?.startedAt ?? record?.started_at ?? record?.spawnedAtMs ?? record?.spawned_at_ms),
1692
+ lastActivityAt: toIsoTimestamp(record?.updatedAt ?? record?.lastActivityAt ?? record?.last_activity_at),
1693
+ isCached: false,
1694
+ };
1695
+ }
1696
+
1697
+ function liveSessionRecordMatchesMeshNode(record: any, meshId: string, nodeId: string, nodeWorkspace = '', nodeIsMissingLocalWorktree = false): boolean {
1698
+ const recordNodeId = readStringValue(record?.meta?.meshNodeId);
1699
+ if (!recordNodeId || recordNodeId !== nodeId) return false;
1700
+ if (nodeIsMissingLocalWorktree) return false;
1701
+ const recordWorkspace = readStringValue(record?.workspace);
1702
+ // Normalized compare (shared WTCLAIM rule): a base node and a co-located worktree
1703
+ // clone differ ONLY by workspace root, so a separator/case-skewed exact compare
1704
+ // could wrongly keep a sibling worktree's session attached to this node.
1705
+ if (nodeWorkspace && recordWorkspace && !meshWorkspacesEquivalent(recordWorkspace, nodeWorkspace)) return false;
1706
+ const recordMeshId = readStringValue(record?.meta?.meshNodeFor);
1707
+ return !recordMeshId || recordMeshId === meshId;
1708
+ }
1709
+
1710
+ function liveSessionRecordMatchesMeshWorkspace(record: any, meshId: string, workspace: string): boolean {
1711
+ const recordWorkspace = readStringValue(record?.workspace);
1712
+ if (!recordWorkspace || !workspace || !meshWorkspacesEquivalent(recordWorkspace, workspace)) return false;
1713
+
1714
+ const recordMeshId = readStringValue(record?.meta?.meshNodeFor);
1715
+ if (recordMeshId) return recordMeshId === meshId;
1716
+
1717
+ return record?.meta?.launchedByCoordinator === true || !!readStringValue(record?.meta?.meshNodeId);
1718
+ }
1719
+
1720
+ export function readLiveMeshNodeWorkspace(args: {
1721
+ meshId: string;
1722
+ nodeId: string;
1723
+ liveSessionRecords: any[];
1724
+ allowCoordinatorSession?: boolean;
1725
+ }): string {
1726
+ const directNodeWorkspace = args.liveSessionRecords.find((record) => (
1727
+ liveSessionRecordMatchesMeshNode(record, args.meshId, args.nodeId)
1728
+ && readStringValue(record?.workspace)
1729
+ ));
1730
+ if (directNodeWorkspace) {
1731
+ return readStringValue(directNodeWorkspace.workspace) || '';
1732
+ }
1733
+
1734
+ if (args.allowCoordinatorSession) {
1735
+ const coordinatorWorkspace = args.liveSessionRecords.find((record) => (
1736
+ readStringValue(record?.meta?.meshCoordinatorFor) === args.meshId
1737
+ && readStringValue(record?.workspace)
1738
+ ));
1739
+ if (coordinatorWorkspace) {
1740
+ return readStringValue(coordinatorWorkspace.workspace) || '';
1741
+ }
1742
+ }
1743
+
1744
+ return '';
1745
+ }
1746
+
1747
+ export function collectLiveMeshSessionRecords(args: {
1748
+ meshId: string;
1749
+ node: any;
1750
+ nodeId: string;
1751
+ liveSessionRecords: any[];
1752
+ allowCoordinatorSession?: boolean;
1753
+ }): any[] {
1754
+ const nodeWorkspace = readStringValue(args.node?.workspace);
1755
+ const nodeIsMissingLocalWorktree = args.node?.isLocalWorktree === true
1756
+ && !!nodeWorkspace
1757
+ && !fs.existsSync(nodeWorkspace);
1758
+ const matches = args.liveSessionRecords.filter((record) => {
1759
+ const recordNodeId = readStringValue(record?.meta?.meshNodeId);
1760
+ if (recordNodeId && recordNodeId !== args.nodeId) return false;
1761
+ if (liveSessionRecordMatchesMeshNode(record, args.meshId, args.nodeId, nodeWorkspace || '', nodeIsMissingLocalWorktree)) return true;
1762
+ if (nodeIsMissingLocalWorktree) return false;
1763
+ return !!nodeWorkspace && liveSessionRecordMatchesMeshWorkspace(record, args.meshId, nodeWorkspace);
1764
+ });
1765
+
1766
+ if (args.allowCoordinatorSession) {
1767
+ for (const record of args.liveSessionRecords) {
1768
+ if (readStringValue(record?.meta?.meshCoordinatorFor) !== args.meshId) continue;
1769
+ const sessionId = readStringValue(record?.sessionId);
1770
+ if (sessionId && matches.some((entry) => readStringValue(entry?.sessionId) === sessionId)) continue;
1771
+ matches.push(record);
1772
+ }
1773
+ }
1774
+
1775
+ return matches;
1776
+ }
1777
+
1778
+ export function buildHistoricalMeshSessions(args: {
1779
+ meshId: string;
1780
+ nodes: any[];
1781
+ liveSessionRecords: any[];
1782
+ }): { count: number; sessions: Record<string, unknown>[]; instruction: string } | undefined {
1783
+ const liveNodeIds = new Set<string>();
1784
+ const liveWorkspaces = new Set<string>();
1785
+ const missingLocalWorktreeNodeIds = new Set<string>();
1786
+ for (const node of args.nodes || []) {
1787
+ const nodeId = normalizeMeshNodeId(node);
1788
+ const workspace = readStringValue(node?.workspace);
1789
+ if (nodeId) liveNodeIds.add(nodeId);
1790
+ if (workspace) liveWorkspaces.add(workspace);
1791
+ if (nodeId && node?.isLocalWorktree === true && workspace && !fs.existsSync(workspace)) {
1792
+ missingLocalWorktreeNodeIds.add(nodeId);
1793
+ }
1794
+ }
1795
+
1796
+ const sessions: Record<string, unknown>[] = [];
1797
+ for (const record of args.liveSessionRecords || []) {
1798
+ const meta = readObjectRecord(record?.meta);
1799
+ const recordMeshId = readStringValue(meta.meshNodeFor, meta.meshCoordinatorFor);
1800
+ if (recordMeshId !== args.meshId) continue;
1801
+ const recordNodeId = readStringValue(meta.meshNodeId);
1802
+ const workspace = readStringValue(record?.workspace);
1803
+ const removedNode = !!recordNodeId && (!liveNodeIds.has(recordNodeId) || missingLocalWorktreeNodeIds.has(recordNodeId));
1804
+ const orphanedWorkspace = !!workspace && !liveWorkspaces.has(workspace) && meta.meshCoordinatorFor !== args.meshId;
1805
+ if (!removedNode && !orphanedWorkspace) continue;
1806
+ sessions.push({
1807
+ ...summarizeMeshSessionRecord(record),
1808
+ classification: removedNode ? 'removedNode' : 'orphanedSession',
1809
+ historical: true,
1810
+ meshNodeId: recordNodeId || null,
1811
+ reason: removedNode
1812
+ ? 'Session is tagged to a mesh node that is no longer in live membership.'
1813
+ : 'Session workspace is no longer attached to a live mesh node.',
1814
+ });
1815
+ }
1816
+ if (sessions.length === 0) return undefined;
1817
+ return {
1818
+ count: sessions.length,
1819
+ sessions: sessions.slice(0, 5),
1820
+ instruction: 'These sessions are separated from normal node activeSessions because their mesh node/workspace is no longer live. Use mesh_cleanup_sessions only if cleanup is intended.',
1821
+ };
1822
+ }
1823
+
1824
+ export function applyCachedInlineMeshNodeStatus(
1825
+ status: Record<string, unknown>,
1826
+ node: any,
1827
+ options?: { skipGit?: boolean; skipError?: boolean; skipHealth?: boolean },
1828
+ ): boolean {
1829
+ const cachedStatus = readObjectRecord(node?.cachedStatus);
1830
+ const liveGit = buildInlineMeshTransitGitStatus(node);
1831
+ const git = options?.skipGit ? undefined : (liveGit ?? buildCachedInlineMeshGitStatus(node));
1832
+ const error = options?.skipError ? undefined : (liveGit ? undefined : readStringValue(cachedStatus.error, node?.error));
1833
+ const health = options?.skipHealth ? undefined : (liveGit ? undefined : readStringValue(cachedStatus.health, node?.health));
1834
+ const machineStatus = readStringValue(cachedStatus.machineStatus, node?.machineStatus);
1835
+ const lastSeenAt = toIsoTimestamp(cachedStatus.lastSeenAt ?? cachedStatus.last_seen_at ?? node?.lastSeenAt ?? node?.last_seen_at);
1836
+ const updatedAt = toIsoTimestamp(cachedStatus.updatedAt ?? cachedStatus.updated_at ?? node?.updatedAt ?? node?.updated_at);
1837
+ const activeSessions = readCachedInlineMeshActiveSessions(node);
1838
+ const activeSessionDetails = readCachedInlineMeshActiveSessionDetails(node);
1839
+ if (!git && !error && !health && !machineStatus && !lastSeenAt && !updatedAt && activeSessions.length === 0) return false;
1840
+ if (git) status.git = git;
1841
+ if (error) status.error = error;
1842
+ if (machineStatus) status.machineStatus = machineStatus;
1843
+ if (lastSeenAt) status.lastSeenAt = lastSeenAt;
1844
+ if (updatedAt) status.updatedAt = updatedAt;
1845
+ if (activeSessions.length > 0) status.activeSessions = activeSessions;
1846
+ if (activeSessionDetails.length > 0) status.activeSessionDetails = activeSessionDetails;
1847
+ if (health) {
1848
+ status.health = health;
1849
+ return true;
1850
+ }
1851
+ if (git) {
1852
+ status.health = deriveMeshNodeHealthFromGit(git);
1853
+ return true;
1854
+ }
1855
+ return activeSessions.length > 0 || !!machineStatus || !!lastSeenAt || !!updatedAt;
1856
+ }
1857
+
1858
+ export async function resolveProviderTypeFromPriority(args: {
1859
+ nodeId: string;
1860
+ providerPriority: string[];
1861
+ providerLoader: ProviderLoader;
1862
+ onStatusChange?: () => void;
1863
+ }): Promise<{ providerType?: string; error?: string }> {
1864
+ if (!args.providerPriority.length) {
1865
+ return { error: `Node '${args.nodeId}' has no providerPriority policy; pass cliType explicitly or configure node.policy.providerPriority` };
1866
+ }
1867
+
1868
+ const failed: string[] = [];
1869
+ for (const requestedType of args.providerPriority) {
1870
+ const normalizedType = args.providerLoader.resolveAlias(requestedType);
1871
+ if (!args.providerLoader.isMachineProviderEnabled(normalizedType)) {
1872
+ failed.push(`${requestedType}: disabled`);
1873
+ continue;
1874
+ }
1875
+ const detected = await detectCLI(normalizedType, args.providerLoader, { includeVersion: false });
1876
+ args.providerLoader.setCliDetectionResults([{
1877
+ id: normalizedType,
1878
+ installed: !!detected,
1879
+ path: detected?.path,
1880
+ }], false);
1881
+ args.onStatusChange?.();
1882
+ if (detected) return { providerType: normalizedType };
1883
+ failed.push(`${requestedType}: not detected`);
1884
+ }
1885
+
1886
+ return { error: `No usable provider detected for node '${args.nodeId}' from providerPriority: ${failed.join('; ')}` };
1887
+ }