@adhdev/daemon-core 0.9.82-rc.45 → 0.9.82-rc.451

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