@adhdev/daemon-core 0.9.82-rc.46 → 0.9.82-rc.460

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