@adhdev/daemon-core 0.9.82-rc.49 → 0.9.82-rc.490

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 (473) 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 +220 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +137 -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 +23 -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 +71 -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-aggregate-status.d.ts +24 -0
  56. package/dist/commands/router-mesh-session-owner.d.ts +59 -0
  57. package/dist/commands/router-refine.d.ts +151 -0
  58. package/dist/commands/router-worktree-cleanup.d.ts +133 -0
  59. package/dist/commands/router.d.ts +203 -15
  60. package/dist/commands/upgrade-helper.d.ts +41 -1
  61. package/dist/config/chat-history.d.ts +11 -0
  62. package/dist/config/config.d.ts +19 -0
  63. package/dist/config/mesh-config.d.ts +65 -0
  64. package/dist/config/mesh-json-config.d.ts +199 -0
  65. package/dist/config/registry-resolver.d.ts +54 -0
  66. package/dist/config/repo-settings.d.ts +77 -0
  67. package/dist/config/state-store.d.ts +30 -0
  68. package/dist/daemon/dev-server.d.ts +0 -2
  69. package/dist/detection/cli-detector.d.ts +17 -0
  70. package/dist/detection/ide-detector.d.ts +13 -0
  71. package/dist/detection/win32-ide-version.d.ts +37 -0
  72. package/dist/git/change-impact-config.d.ts +159 -0
  73. package/dist/git/git-commands.d.ts +26 -2
  74. package/dist/git/git-diff.d.ts +6 -0
  75. package/dist/git/git-executor.d.ts +11 -0
  76. package/dist/git/git-status.d.ts +80 -0
  77. package/dist/git/git-types.d.ts +2 -50
  78. package/dist/git/git-worktree.d.ts +71 -1
  79. package/dist/git/index.d.ts +3 -1
  80. package/dist/index.d.ts +70 -17
  81. package/dist/index.js +53532 -19073
  82. package/dist/index.js.map +1 -1
  83. package/dist/index.mjs +53283 -18989
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/installer.d.ts +1 -4
  86. package/dist/ipc/local-ipc-server.d.ts +91 -0
  87. package/dist/launch.d.ts +1 -1
  88. package/dist/logging/async-batch-writer.d.ts +10 -0
  89. package/dist/logging/debug-config.d.ts +16 -0
  90. package/dist/logging/log-redactor.d.ts +24 -0
  91. package/dist/logging/log-tail-reader.d.ts +81 -0
  92. package/dist/logging/logger.d.ts +1 -1
  93. package/dist/mesh/contracts.d.ts +256 -0
  94. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  95. package/dist/mesh/coordinator-registry.d.ts +59 -0
  96. package/dist/mesh/mesh-active-work.d.ts +203 -0
  97. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  98. package/dist/mesh/mesh-completion-synthesis.d.ts +4 -0
  99. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  100. package/dist/mesh/mesh-delivery-policy.d.ts +104 -0
  101. package/dist/mesh/mesh-event-classify.d.ts +7 -0
  102. package/dist/mesh/mesh-event-forwarding.d.ts +58 -0
  103. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  104. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  105. package/dist/mesh/mesh-events-pending.d.ts +258 -0
  106. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  107. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  108. package/dist/mesh/mesh-events.d.ts +6 -49
  109. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  110. package/dist/mesh/mesh-host-ownership.d.ts +21 -1
  111. package/dist/mesh/mesh-init.d.ts +128 -0
  112. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  113. package/dist/mesh/mesh-ledger.d.ts +139 -1
  114. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  115. package/dist/mesh/mesh-missions.d.ts +281 -0
  116. package/dist/mesh/mesh-node-identity.d.ts +310 -0
  117. package/dist/mesh/mesh-queue-assignment.d.ts +162 -0
  118. package/dist/mesh/mesh-reconcile-acked-hold.d.ts +17 -0
  119. package/dist/mesh/mesh-reconcile-config.d.ts +6 -0
  120. package/dist/mesh/mesh-reconcile-identity.d.ts +6 -0
  121. package/dist/mesh/mesh-reconcile-loop.d.ts +84 -0
  122. package/dist/mesh/mesh-reconcile-v2-backstop.d.ts +16 -0
  123. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  124. package/dist/mesh/mesh-refine-gates.d.ts +457 -0
  125. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  126. package/dist/mesh/mesh-remote-event-pull.d.ts +15 -0
  127. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  128. package/dist/mesh/mesh-routing.d.ts +70 -0
  129. package/dist/mesh/mesh-runtime-store.d.ts +567 -0
  130. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  131. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  132. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  133. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +34 -0
  134. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  135. package/dist/mesh/mesh-work-queue.d.ts +392 -1
  136. package/dist/mesh/preview-freshness.d.ts +28 -0
  137. package/dist/mesh/refine-config.d.ts +97 -0
  138. package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
  139. package/dist/providers/acp-provider-instance.d.ts +5 -0
  140. package/dist/providers/approval-utils.d.ts +46 -0
  141. package/dist/providers/chat-message-normalization.d.ts +58 -1
  142. package/dist/providers/cli-provider-effect-format.d.ts +30 -0
  143. package/dist/providers/cli-provider-history-dedup.d.ts +17 -0
  144. package/dist/providers/cli-provider-input-prompt.d.ts +12 -0
  145. package/dist/providers/cli-provider-instance-types.d.ts +45 -0
  146. package/dist/providers/cli-provider-instance.d.ts +426 -30
  147. package/dist/providers/cli-provider-status-helpers.d.ts +46 -0
  148. package/dist/providers/cli-provider-transcript-merge.d.ts +7 -0
  149. package/dist/providers/contracts.d.ts +196 -6
  150. package/dist/providers/external-sources.d.ts +71 -0
  151. package/dist/providers/manual-attendance.d.ts +79 -0
  152. package/dist/providers/native-history/antigravity-claim-registry.d.ts +39 -0
  153. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
  154. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  155. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  156. package/dist/providers/native-history/constants.d.ts +12 -0
  157. package/dist/providers/native-history/dispatcher.d.ts +44 -0
  158. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  159. package/dist/providers/native-history/index.d.ts +13 -0
  160. package/dist/providers/provider-instance-manager.d.ts +30 -0
  161. package/dist/providers/provider-instance.d.ts +31 -1
  162. package/dist/providers/provider-loader.d.ts +42 -5
  163. package/dist/providers/provider-trust.d.ts +31 -0
  164. package/dist/providers/read-chat-contract.d.ts +29 -0
  165. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  166. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  167. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  168. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  169. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  170. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  171. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  172. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  173. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  174. package/dist/providers/sdk/v1/index.d.ts +30 -0
  175. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  176. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  177. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  178. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  179. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  180. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  181. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  182. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  183. package/dist/providers/spec/adapter.d.ts +98 -0
  184. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  185. package/dist/providers/spec/evaluator.d.ts +45 -0
  186. package/dist/providers/spec/fsm-driver.d.ts +449 -0
  187. package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
  188. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  189. package/dist/providers/spec/fsm-types.d.ts +202 -0
  190. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  191. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  192. package/dist/providers/spec/route.d.ts +4 -0
  193. package/dist/providers/spec/types.d.ts +244 -0
  194. package/dist/providers/status-monitor.d.ts +7 -7
  195. package/dist/providers/transcript-v2.d.ts +176 -0
  196. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  197. package/dist/providers/working-dir.d.ts +17 -0
  198. package/dist/repo-mesh-types.d.ts +616 -12
  199. package/dist/runtime-defaults.d.ts +2 -0
  200. package/dist/session-host/managed-host.d.ts +64 -0
  201. package/dist/session-host/runtime-surface.d.ts +10 -16
  202. package/dist/sessions/registry.d.ts +26 -0
  203. package/dist/shared-types-extra.d.ts +2 -4
  204. package/dist/shared-types.d.ts +110 -55
  205. package/dist/status/chat-tail-hot-sessions.d.ts +40 -0
  206. package/dist/status/normalize.d.ts +1 -1
  207. package/dist/status/normalize.js +1 -0
  208. package/dist/status/normalize.js.map +1 -1
  209. package/dist/status/normalize.mjs +1 -0
  210. package/dist/status/normalize.mjs.map +1 -1
  211. package/dist/status/reporter.d.ts +2 -0
  212. package/dist/status/snapshot.d.ts +27 -0
  213. package/dist/system/hash.d.ts +8 -0
  214. package/dist/system/load-better-sqlite3.d.ts +21 -0
  215. package/dist/types.d.ts +20 -6
  216. package/package.json +11 -4
  217. package/src/agent-stream/poller.ts +2 -3
  218. package/src/agent-stream/provider-adapter.ts +1 -1
  219. package/src/boot/daemon-lifecycle.ts +80 -14
  220. package/src/boot/process-hardening.ts +89 -0
  221. package/src/build-info.ts +73 -0
  222. package/src/chat/source-machine.ts +534 -0
  223. package/src/chat/source-resolver.ts +0 -0
  224. package/src/chat/subscription-updates.ts +20 -1
  225. package/src/cli-adapter-types.d.ts +3 -1
  226. package/src/cli-adapter-types.ts +68 -2
  227. package/src/cli-adapters/cli-script-runner.ts +421 -0
  228. package/src/cli-adapters/cli-state-engine.ts +1282 -0
  229. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  230. package/src/cli-adapters/provider-cli-adapter.ts +1048 -1143
  231. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  232. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  233. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  234. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  235. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  236. package/src/cli-adapters/pty-transport.ts +2 -1
  237. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  238. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  239. package/src/cli-adapters/resolve-executable.ts +204 -0
  240. package/src/cli-adapters/session-host-transport.ts +2 -1
  241. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  242. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  243. package/src/cli-adapters/terminal-screen.ts +16 -81
  244. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  245. package/src/commands/chat-commands-read.ts +2788 -0
  246. package/src/commands/chat-commands-scope.ts +54 -0
  247. package/src/commands/chat-commands-shared.ts +114 -0
  248. package/src/commands/chat-commands-write.ts +891 -0
  249. package/src/commands/chat-commands.ts +19 -1841
  250. package/src/commands/cli-manager.d.ts +2 -0
  251. package/src/commands/cli-manager.ts +724 -27
  252. package/src/commands/handler.ts +865 -2
  253. package/src/commands/high-family/index.ts +28 -0
  254. package/src/commands/high-family/mesh-coordinator-launch.ts +696 -0
  255. package/src/commands/high-family/mesh-events.ts +102 -0
  256. package/src/commands/high-family/mesh-status.ts +857 -0
  257. package/src/commands/high-family/types.ts +80 -0
  258. package/src/commands/low-family/coordinator-prompt.ts +125 -0
  259. package/src/commands/low-family/daemon-lifecycle.ts +120 -0
  260. package/src/commands/low-family/diagnostics.ts +57 -0
  261. package/src/commands/low-family/index.ts +37 -0
  262. package/src/commands/low-family/mesh-ledger.ts +62 -0
  263. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  264. package/src/commands/low-family/notification.ts +116 -0
  265. package/src/commands/low-family/refine-config.ts +106 -0
  266. package/src/commands/low-family/session-host.ts +282 -0
  267. package/src/commands/low-family/spec-providerdev.ts +217 -0
  268. package/src/commands/low-family/status-meta.ts +112 -0
  269. package/src/commands/low-family/types.ts +39 -0
  270. package/src/commands/med-family/cli-agent.ts +270 -0
  271. package/src/commands/med-family/fast-forward.ts +230 -0
  272. package/src/commands/med-family/ide.ts +163 -0
  273. package/src/commands/med-family/index.ts +37 -0
  274. package/src/commands/med-family/mesh-crud.ts +1268 -0
  275. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  276. package/src/commands/med-family/mesh-queue.ts +167 -0
  277. package/src/commands/med-family/mesh-restart.ts +92 -0
  278. package/src/commands/med-family/types.ts +153 -0
  279. package/src/commands/mesh-coordinator.ts +334 -124
  280. package/src/commands/router-aggregate-status.ts +209 -0
  281. package/src/commands/router-mesh-session-owner.ts +114 -0
  282. package/src/commands/router-refine.ts +1794 -0
  283. package/src/commands/router-worktree-cleanup.ts +870 -0
  284. package/src/commands/router.ts +567 -4149
  285. package/src/commands/stream-commands.ts +8 -0
  286. package/src/commands/upgrade-helper.ts +310 -45
  287. package/src/config/chat-history.ts +517 -24
  288. package/src/config/config.ts +30 -0
  289. package/src/config/mesh-config.ts +300 -24
  290. package/src/config/mesh-json-config.ts +376 -0
  291. package/src/config/recent-activity.ts +8 -2
  292. package/src/config/registry-resolver.ts +100 -0
  293. package/src/config/repo-settings.ts +111 -0
  294. package/src/config/state-store.ts +55 -0
  295. package/src/daemon/dev-auto-implement.ts +3 -2
  296. package/src/daemon/dev-cli-debug.ts +10 -1
  297. package/src/daemon/dev-server.ts +0 -541
  298. package/src/detection/cli-detector.ts +94 -9
  299. package/src/detection/ide-detector.ts +55 -16
  300. package/src/detection/win32-ide-version.ts +106 -0
  301. package/src/git/change-impact-config.ts +354 -0
  302. package/src/git/git-commands.ts +112 -16
  303. package/src/git/git-diff.ts +81 -11
  304. package/src/git/git-executor.ts +12 -0
  305. package/src/git/git-status.ts +822 -48
  306. package/src/git/git-types.ts +14 -62
  307. package/src/git/git-worktree.ts +261 -4
  308. package/src/git/index.ts +17 -0
  309. package/src/index.ts +190 -13
  310. package/src/installer.d.ts +1 -1
  311. package/src/installer.ts +8 -6
  312. package/src/ipc/local-ipc-server.ts +278 -0
  313. package/src/launch.d.ts +1 -1
  314. package/src/launch.ts +37 -28
  315. package/src/logging/async-batch-writer.ts +55 -0
  316. package/src/logging/command-log.ts +7 -5
  317. package/src/logging/debug-config.ts +25 -0
  318. package/src/logging/debug-trace.ts +7 -2
  319. package/src/logging/log-redactor.ts +100 -0
  320. package/src/logging/log-tail-reader.ts +341 -0
  321. package/src/logging/logger.ts +14 -7
  322. package/src/mesh/contracts.ts +510 -0
  323. package/src/mesh/coordinator-prompt.ts +627 -34
  324. package/src/mesh/coordinator-registry.ts +121 -0
  325. package/src/mesh/mesh-active-work.ts +706 -0
  326. package/src/mesh/mesh-clone-grace.ts +68 -0
  327. package/src/mesh/mesh-completion-synthesis.ts +416 -0
  328. package/src/mesh/mesh-coordinator-config.ts +97 -0
  329. package/src/mesh/mesh-delivery-policy.ts +284 -0
  330. package/src/mesh/mesh-event-classify.ts +78 -0
  331. package/src/mesh/mesh-event-forwarding.ts +2030 -0
  332. package/src/mesh/mesh-event-trace.ts +67 -0
  333. package/src/mesh/mesh-events-coordinator.ts +32 -0
  334. package/src/mesh/mesh-events-pending.ts +1548 -0
  335. package/src/mesh/mesh-events-stale.ts +452 -0
  336. package/src/mesh/mesh-events-utils.ts +443 -0
  337. package/src/mesh/mesh-events.ts +43 -1035
  338. package/src/mesh/mesh-fast-forward.ts +856 -0
  339. package/src/mesh/mesh-host-ownership.ts +41 -3
  340. package/src/mesh/mesh-init.ts +350 -0
  341. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  342. package/src/mesh/mesh-ledger.ts +897 -102
  343. package/src/mesh/mesh-magi-status.ts +223 -0
  344. package/src/mesh/mesh-missions.ts +695 -0
  345. package/src/mesh/mesh-node-identity.ts +2065 -0
  346. package/src/mesh/mesh-queue-assignment.ts +2498 -0
  347. package/src/mesh/mesh-reconcile-acked-hold.ts +230 -0
  348. package/src/mesh/mesh-reconcile-config.ts +66 -0
  349. package/src/mesh/mesh-reconcile-identity.ts +103 -0
  350. package/src/mesh/mesh-reconcile-loop.ts +1696 -0
  351. package/src/mesh/mesh-reconcile-v2-backstop.ts +62 -0
  352. package/src/mesh/mesh-refine-batch.ts +205 -0
  353. package/src/mesh/mesh-refine-gates.ts +1792 -0
  354. package/src/mesh/mesh-refine-status.ts +231 -0
  355. package/src/mesh/mesh-remote-event-pull.ts +279 -0
  356. package/src/mesh/mesh-review-inbox.ts +308 -0
  357. package/src/mesh/mesh-routing.ts +291 -0
  358. package/src/mesh/mesh-runtime-store.ts +2292 -0
  359. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  360. package/src/mesh/mesh-task-inflight.ts +70 -0
  361. package/src/mesh/mesh-task-stats.ts +161 -0
  362. package/src/mesh/mesh-unresolved-forward-outbox.ts +215 -0
  363. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  364. package/src/mesh/mesh-work-queue.ts +1489 -145
  365. package/src/mesh/preview-freshness.ts +163 -0
  366. package/src/mesh/refine-config.ts +129 -12
  367. package/src/mesh/worktree-bootstrap-config.ts +599 -0
  368. package/src/providers/acp-provider-instance.ts +43 -10
  369. package/src/providers/approval-utils.d.ts +5 -0
  370. package/src/providers/approval-utils.ts +100 -6
  371. package/src/providers/chat-message-normalization.ts +126 -4
  372. package/src/providers/cli-provider-effect-format.ts +53 -0
  373. package/src/providers/cli-provider-history-dedup.ts +75 -0
  374. package/src/providers/cli-provider-input-prompt.ts +133 -0
  375. package/src/providers/cli-provider-instance-types.ts +131 -0
  376. package/src/providers/cli-provider-instance.ts +2771 -499
  377. package/src/providers/cli-provider-status-helpers.ts +123 -0
  378. package/src/providers/cli-provider-transcript-merge.ts +114 -0
  379. package/src/providers/contracts.d.ts +55 -0
  380. package/src/providers/contracts.ts +207 -6
  381. package/src/providers/extension-provider-instance.ts +12 -7
  382. package/src/providers/external-sources.ts +218 -0
  383. package/src/providers/ide-provider-instance.ts +35 -12
  384. package/src/providers/manual-attendance.ts +105 -0
  385. package/src/providers/native-history/antigravity-claim-registry.ts +138 -0
  386. package/src/providers/native-history/antigravity-cli-transcript.ts +1275 -0
  387. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  388. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  389. package/src/providers/native-history/constants.ts +19 -0
  390. package/src/providers/native-history/dispatcher.ts +617 -0
  391. package/src/providers/native-history/hermes-cli-transcript.ts +312 -0
  392. package/src/providers/native-history/index.ts +30 -0
  393. package/src/providers/provider-instance-manager.ts +71 -0
  394. package/src/providers/provider-instance.ts +24 -1
  395. package/src/providers/provider-loader.ts +700 -55
  396. package/src/providers/provider-schema.ts +93 -14
  397. package/src/providers/provider-trust.ts +114 -0
  398. package/src/providers/read-chat-contract.ts +76 -16
  399. package/src/providers/sdk/README.md +49 -0
  400. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  401. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  402. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  403. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
  404. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  405. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  406. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  407. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  408. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  409. package/src/providers/sdk/v1/index.ts +152 -0
  410. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  411. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  412. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  413. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +538 -0
  414. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  415. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  416. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  417. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  418. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  419. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  420. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  421. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  422. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  423. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  424. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  425. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  426. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  427. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  428. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  429. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  430. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  431. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  432. package/src/providers/sdk/v1/validators/index.ts +19 -0
  433. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  434. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  435. package/src/providers/spec/adapter.ts +246 -0
  436. package/src/providers/spec/cli-adapter.ts +1064 -0
  437. package/src/providers/spec/evaluator.ts +407 -0
  438. package/src/providers/spec/fsm-driver.ts +1528 -0
  439. package/src/providers/spec/fsm-evaluator.ts +290 -0
  440. package/src/providers/spec/fsm-loader.ts +128 -0
  441. package/src/providers/spec/fsm-types.ts +301 -0
  442. package/src/providers/spec/native-history-executor.ts +1241 -0
  443. package/src/providers/spec/pre-launch-trust.ts +104 -0
  444. package/src/providers/spec/route.ts +51 -0
  445. package/src/providers/spec/types.ts +284 -0
  446. package/src/providers/status-monitor.d.ts +7 -7
  447. package/src/providers/status-monitor.ts +37 -22
  448. package/src/providers/transcript-v2.ts +567 -0
  449. package/src/providers/types/interactive-prompt.ts +536 -0
  450. package/src/providers/version-archive.ts +64 -24
  451. package/src/providers/working-dir.ts +23 -0
  452. package/src/repo-mesh-types.ts +861 -14
  453. package/src/runtime-defaults.ts +39 -0
  454. package/src/session-host/managed-host.ts +218 -0
  455. package/src/session-host/runtime-surface.ts +20 -80
  456. package/src/sessions/registry.ts +44 -0
  457. package/src/shared-types-extra.ts +2 -4
  458. package/src/shared-types.d.ts +8 -0
  459. package/src/shared-types.ts +148 -55
  460. package/src/status/builders.ts +69 -6
  461. package/src/status/chat-tail-hot-sessions.ts +117 -2
  462. package/src/status/normalize.ts +2 -0
  463. package/src/status/reporter.ts +19 -1
  464. package/src/status/snapshot.ts +100 -27
  465. package/src/system/hash.ts +23 -0
  466. package/src/system/host-memory.ts +29 -12
  467. package/src/system/load-better-sqlite3.ts +68 -0
  468. package/src/types.ts +26 -6
  469. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  470. package/dist/mesh/mesh-sync.d.ts +0 -53
  471. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  472. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  473. package/src/mesh/mesh-sync.ts +0 -111
@@ -8,15 +8,81 @@
8
8
  * 3. How to orchestrate work across nodes
9
9
  *
10
10
  * The prompt is generated dynamically from the current mesh state.
11
+ *
12
+ * User customization:
13
+ * ~/.adhdev/coordinator-prompts/<cliType>.md — full override
14
+ * ~/.adhdev/coordinator-prompts/<cliType>.append.md — appended to default
15
+ * ~/.adhdev/coordinator-prompts/default.md — full override (any CLI)
16
+ * ~/.adhdev/coordinator-prompts/default.append.md — appended to default (any CLI)
17
+ *
18
+ * CLI-specific files take precedence over default.* files. The override file
19
+ * still gets the node/policy facts substituted via the same {{placeholders}}
20
+ * the daemon understands; an override that doesn't reference them just gets
21
+ * a static prompt, which is also fine.
11
22
  */
12
23
 
24
+ import * as fs from 'node:fs';
25
+ import * as os from 'node:os';
26
+ import * as path from 'node:path';
27
+
13
28
  import type {
14
29
  LocalMeshEntry,
15
30
  RepoMeshPolicy,
16
31
  RepoMeshStatus,
17
32
  RepoMeshNodeStatus,
18
33
  } from '../repo-mesh-types.js';
19
- import { DEFAULT_MESH_POLICY } from '../repo-mesh-types.js';
34
+ import { mergeAndNormalizePolicy } from '../repo-mesh-types.js';
35
+ import { getDifficultyBrains } from '../config/mesh-config.js';
36
+ import { MESH_TASK_DIFFICULTIES } from '@adhdev/mesh-shared';
37
+
38
+ /**
39
+ * Cheap, locally-derived "what just happened" snapshot for the coordinator
40
+ * prompt. Built at launch from the local ledger + work-queue stats — no remote
41
+ * peer probe. Surfaces the gap a fresh coordinator otherwise misses: it can't
42
+ * see recent failures / queue depth until it manually calls mesh_task_history.
43
+ *
44
+ * All fields are optional so callers that have nothing to report (or fail to
45
+ * read the ledger) simply omit the section — the prompt output stays identical
46
+ * to the pre-activity form in that case.
47
+ */
48
+ export interface CoordinatorRecentActivity {
49
+ /** task_failed entries from the recent window, newest last. */
50
+ recentFailures?: Array<{
51
+ timestamp?: string;
52
+ nodeId?: string;
53
+ /** Short task title/message, already truncated by the caller. */
54
+ summary?: string;
55
+ }>;
56
+ /** Count of task_failed entries inside the recent window. */
57
+ recentFailureCount?: number;
58
+ /**
59
+ * Size of the "recent" window in minutes. Drives the "failed in the last
60
+ * N min" phrasing. Omitted → defaults to 30, matching the prior hardcoded
61
+ * wording so existing callers render identically.
62
+ */
63
+ windowMinutes?: number;
64
+ /** Pending (unclaimed) tasks in the work queue. */
65
+ pendingTasks?: number;
66
+ /** Assigned-but-not-yet-terminal tasks in the work queue. */
67
+ assignedTasks?: number;
68
+ /** Stalled tasks recorded in the ledger. */
69
+ stalledTasks?: number;
70
+ /** ISO timestamp of the most recent ledger activity, if any. */
71
+ lastActivityAt?: string | null;
72
+ }
73
+
74
+ /**
75
+ * One coordinator operating note — a runtime-accumulated lesson (provider
76
+ * quirk, pattern to avoid, recovery lesson) persisted in the ledger so it
77
+ * survives coordinator restarts and is provider-neutral (visible to codex /
78
+ * hermes / antigravity coordinators, not just Claude's memory).
79
+ */
80
+ export interface CoordinatorOperatingNote {
81
+ text: string;
82
+ category?: 'provider_quirk' | 'pattern_to_avoid' | 'recovery_lesson';
83
+ createdAt?: string;
84
+ sourceCoordinator?: string;
85
+ }
20
86
 
21
87
  // ─── Prompt Builder ─────────────────────────────
22
88
 
@@ -25,10 +91,157 @@ export interface CoordinatorPromptContext {
25
91
  status?: RepoMeshStatus;
26
92
  userInstruction?: string;
27
93
  coordinatorCliType?: string;
94
+ /**
95
+ * M3: pre-rendered active mission section (from buildMissionPromptSection).
96
+ * Empty/undefined when the mesh has no active mission — the prompt output
97
+ * stays identical to the pre-M3 form in that case.
98
+ */
99
+ missionSection?: string;
100
+ /**
101
+ * Gap1: recent ledger/queue activity surfaced so a freshly-launched
102
+ * coordinator sees recent failures + queue depth without first calling
103
+ * mesh_task_history. Omitted → no "## Recent Activity" section.
104
+ */
105
+ recentActivity?: CoordinatorRecentActivity;
106
+ /**
107
+ * Gap2-A: runtime-accumulated operating notes (provider-neutral lessons)
108
+ * read from the ledger at launch. Omitted/empty → no "## Operating Notes"
109
+ * section.
110
+ */
111
+ operatingNotes?: CoordinatorOperatingNote[];
112
+ }
113
+
114
+ /**
115
+ * Compose the final coordinator prompt from four layers, in this precedence:
116
+ *
117
+ * 1. Per-launch `extraSystemPrompt` (always appended, as "## Additional
118
+ * Context"). Never wins as a base — it's launch-scope context.
119
+ * 2. Mesh-level append (`mesh.coordinator.systemPromptAppend` or the legacy
120
+ * `systemPromptSuffix`). Stacks after whichever base won.
121
+ * 3. User-file append (`~/.adhdev/coordinator-prompts/<cli>.append.md` or
122
+ * `default.append.md`). Also stacks; same placeholder expansion as the
123
+ * override path.
124
+ * 4. Base prompt, picked in this order:
125
+ * a. `mesh.coordinator.systemPromptOverride` (mesh-level override)
126
+ * b. user-file override (`~/.adhdev/coordinator-prompts/<cli>.md` or
127
+ * `default.md`)
128
+ * c. daemon default (assembled from identity/nodes/policy/tools/…)
129
+ *
130
+ * That layering lets a user customize prompts at three increasing scopes
131
+ * (machine, mesh, single launch) without losing the daemon's stock rules.
132
+ */
133
+ /**
134
+ * 6-4: total prompt soft cap. When the assembled prompt exceeds this, we shed
135
+ * the two runtime-accumulated, daemon-generated sections — operating notes
136
+ * first, then recent activity — because they grow unboundedly from the ledger.
137
+ * We NEVER trim user append/override content or the fixed hardcoded sections
138
+ * (identity/nodes/policy/tools/workflow/onboarding/rules): those carry user
139
+ * intent or invariant instructions. If shedding both still overflows, we keep
140
+ * the prompt as-is rather than mangling protected content.
141
+ */
142
+ const PROMPT_SOFT_CAP_BYTES = 60 * 1024;
143
+
144
+ /**
145
+ * Which daemon-generated optional sections to drop from the default base.
146
+ * Used only by the 6-4 soft-cap retry — an override base ignores these
147
+ * because its operating-notes/recent-activity content comes from the user's
148
+ * own {{placeholder}}s and is not ours to trim.
149
+ */
150
+ interface DefaultPromptDropFlags {
151
+ dropOperatingNotes?: boolean;
152
+ dropRecentActivity?: boolean;
28
153
  }
29
154
 
30
155
  export function buildCoordinatorSystemPrompt(ctx: CoordinatorPromptContext): string {
31
- const { mesh, status, userInstruction, coordinatorCliType } = ctx;
156
+ // First pass: assemble with everything included.
157
+ let prompt = assembleCoordinatorPrompt(ctx, {});
158
+ if (byteLength(prompt) <= PROMPT_SOFT_CAP_BYTES) return prompt;
159
+
160
+ // Over the soft cap. Only the default base carries daemon-generated
161
+ // operating-notes / recent-activity sections we're allowed to shed; an
162
+ // override base is user content and stays whole. If we're on an override
163
+ // base there's nothing safe to trim, so return the first pass unchanged.
164
+ if (usesOverrideBase(ctx)) return prompt;
165
+
166
+ const shed: string[] = [];
167
+
168
+ // 1) Shed operating notes first.
169
+ prompt = assembleCoordinatorPrompt(ctx, { dropOperatingNotes: true });
170
+ shed.push('operating notes');
171
+ if (byteLength(prompt) <= PROMPT_SOFT_CAP_BYTES) {
172
+ return appendTruncationNotice(prompt, shed);
173
+ }
174
+
175
+ // 2) Still over → also shed recent activity.
176
+ prompt = assembleCoordinatorPrompt(ctx, { dropOperatingNotes: true, dropRecentActivity: true });
177
+ shed.push('recent activity');
178
+ return appendTruncationNotice(prompt, shed);
179
+ }
180
+
181
+ /** True when the base prompt is a mesh-level or user-file override (not the daemon default). */
182
+ function usesOverrideBase(ctx: CoordinatorPromptContext): boolean {
183
+ if (ctx.mesh.coordinator?.systemPromptOverride?.trim()) return true;
184
+ return readUserPromptFile(ctx.coordinatorCliType, 'md') !== null;
185
+ }
186
+
187
+ /** UTF-8 byte length — the cap is a byte budget, not a code-unit count. */
188
+ function byteLength(s: string): number {
189
+ return Buffer.byteLength(s, 'utf8');
190
+ }
191
+
192
+ /**
193
+ * Append a single trailing line recording which daemon-generated sections were
194
+ * shed to fit the soft cap, so the coordinator (and anyone reading the prompt)
195
+ * knows the omission was deliberate, not a data-loss bug.
196
+ */
197
+ function appendTruncationNotice(prompt: string, shed: string[]): string {
198
+ if (shed.length === 0) return prompt;
199
+ return `${prompt}\n\n_Prompt exceeded the ${Math.floor(PROMPT_SOFT_CAP_BYTES / 1024)}KB soft cap; omitted to fit: ${shed.join(', ')}. Full detail remains in the ledger (\`mesh_task_history\` / \`mesh_record_note\`)._`;
200
+ }
201
+
202
+ function assembleCoordinatorPrompt(ctx: CoordinatorPromptContext, drop: DefaultPromptDropFlags): string {
203
+ const { mesh, userInstruction, coordinatorCliType } = ctx;
204
+
205
+ // ── Pick the base prompt ──
206
+ const meshOverride = mesh.coordinator?.systemPromptOverride?.trim();
207
+ let base: string;
208
+ if (meshOverride) {
209
+ base = expandPromptPlaceholders(meshOverride, ctx);
210
+ } else {
211
+ const userOverride = readUserPromptFile(coordinatorCliType, 'md');
212
+ if (userOverride !== null) {
213
+ base = expandPromptPlaceholders(userOverride, ctx);
214
+ } else {
215
+ base = buildDefaultCoordinatorPrompt(ctx, drop);
216
+ }
217
+ }
218
+
219
+ const sections: string[] = [base];
220
+
221
+ // ── User-level append runs after whichever base won ──
222
+ const userAppend = readUserPromptFile(coordinatorCliType, 'append.md');
223
+ if (userAppend !== null) {
224
+ sections.push(expandPromptPlaceholders(userAppend, ctx));
225
+ }
226
+
227
+ // ── Mesh-level append (prefer the new field, fall back to the legacy alias) ──
228
+ const meshAppend = (mesh.coordinator?.systemPromptAppend
229
+ ?? mesh.coordinator?.systemPromptSuffix)?.trim();
230
+ if (meshAppend) {
231
+ sections.push(expandPromptPlaceholders(meshAppend, ctx));
232
+ }
233
+
234
+ // ── Per-launch context lands last so it's the most recent thing the
235
+ // agent reads. Marked as Additional Context, not a rule update. ──
236
+ if (userInstruction) {
237
+ sections.push(`## Additional Context\n${userInstruction}`);
238
+ }
239
+
240
+ return sections.join('\n\n');
241
+ }
242
+
243
+ function buildDefaultCoordinatorPrompt(ctx: CoordinatorPromptContext, drop: DefaultPromptDropFlags = {}): string {
244
+ const { mesh, status, coordinatorCliType } = ctx;
32
245
  const sections: string[] = [];
33
246
 
34
247
  // ── Identity ──
@@ -46,8 +259,30 @@ Repository: \`${mesh.repoIdentity}\`${mesh.defaultBranch ? `\nDefault branch: \`
46
259
  sections.push('## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`.');
47
260
  }
48
261
 
262
+ // ── Active Mission (M3) — only present when one exists ──
263
+ if (ctx.missionSection?.trim()) {
264
+ sections.push(ctx.missionSection.trim());
265
+ }
266
+
267
+ // ── Recent Activity (Gap1) — only present when there's something to show.
268
+ // Shed under the 6-4 soft cap (drop.dropRecentActivity). ──
269
+ if (!drop.dropRecentActivity) {
270
+ const recentActivity = buildRecentActivitySection(ctx.recentActivity);
271
+ if (recentActivity) sections.push(recentActivity);
272
+ }
273
+
274
+ // ── Operating Notes (Gap2-A) — only present when notes exist. Shed first
275
+ // under the 6-4 soft cap (drop.dropOperatingNotes). ──
276
+ if (!drop.dropOperatingNotes) {
277
+ const operatingNotes = buildOperatingNotesSection(ctx.operatingNotes);
278
+ if (operatingNotes) sections.push(operatingNotes);
279
+ }
280
+
49
281
  // ── Policy ──
50
- sections.push(buildPolicySection({ ...DEFAULT_MESH_POLICY, ...(mesh.policy || {}) }));
282
+ sections.push(buildPolicySection(mergeAndNormalizePolicy(undefined, mesh.policy)));
283
+
284
+ // ── Brain presets (difficulty → model/thinking) ──
285
+ sections.push(buildBrainPresetsSection());
51
286
 
52
287
  // ── Tools ──
53
288
  sections.push(TOOLS_SECTION);
@@ -58,25 +293,102 @@ Repository: \`${mesh.repoIdentity}\`${mesh.defaultBranch ? `\nDefault branch: \`
58
293
  // ── Workflow ──
59
294
  sections.push(WORKFLOW_SECTION);
60
295
 
296
+ // ── Onboarding / Reinit ──
297
+ sections.push(ONBOARDING_SECTION);
298
+
61
299
  // ── Rules ──
62
300
  sections.push(buildRulesSection(coordinatorCliType));
63
301
 
64
- // ── User instruction ──
65
- if (userInstruction) {
66
- sections.push(`## Additional Context\n${userInstruction}`);
67
- }
302
+ return sections.join('\n\n');
303
+ }
68
304
 
69
- if (mesh.coordinator?.systemPromptSuffix) {
70
- sections.push(mesh.coordinator.systemPromptSuffix);
305
+ /**
306
+ * Look up a user-customization file under ~/.adhdev/coordinator-prompts/.
307
+ *
308
+ * Lookup order:
309
+ * 1. <cliType>.<suffix> — provider-specific
310
+ * 2. default.<suffix> — shared across providers
311
+ *
312
+ * Returns null when neither exists; an empty/whitespace-only file is also
313
+ * treated as "no override" so users can drop in a stub without affecting
314
+ * behavior. Read errors (permission, IO) are swallowed and logged-as-null
315
+ * intentionally: a broken override file should never block coordinator
316
+ * launch, it should just behave as if the file weren't there.
317
+ */
318
+ function readUserPromptFile(cliType: string | undefined, suffix: string): string | null {
319
+ const dir = path.join(os.homedir(), '.adhdev', 'coordinator-prompts');
320
+ const candidates: string[] = [];
321
+ if (cliType) candidates.push(path.join(dir, `${cliType}.${suffix}`));
322
+ candidates.push(path.join(dir, `default.${suffix}`));
323
+ for (const p of candidates) {
324
+ try {
325
+ const text = fs.readFileSync(p, 'utf8');
326
+ if (text.trim()) return text;
327
+ } catch { /* missing file is the common case — keep going */ }
71
328
  }
329
+ return null;
330
+ }
72
331
 
73
- return sections.join('\n\n');
332
+ /**
333
+ * Expand `{{placeholder}}` tokens against current mesh state.
334
+ *
335
+ * Tokens we support today:
336
+ * {{meshName}} — mesh.name
337
+ * {{repo}} — mesh.repoIdentity
338
+ * {{defaultBranch}} — mesh.defaultBranch or empty
339
+ * {{cliType}} — coordinator CLI type or empty
340
+ * {{nodes}} — full node section (status if known, otherwise config)
341
+ * {{mission}} — active mission summary section (empty when none)
342
+ * {{recentActivity}} — recent failures + queue depth section (empty when none)
343
+ * {{operatingNotes}} — accumulated operating notes section (empty when none)
344
+ * {{policy}} — full policy section
345
+ * {{tools}} — the canonical tools table
346
+ * {{workflow}} — the canonical orchestration workflow
347
+ * {{onboarding}} — the guided init/reinit onboarding section
348
+ * {{rules}} — the canonical rules section (with coordinatorNote)
349
+ * {{toolExposurePreflight}} — the MCP-missing preflight reminder
350
+ *
351
+ * Unknown tokens are left as-is — that way typos are obvious in the rendered
352
+ * prompt instead of silently disappearing. Tokens are not recursive: an
353
+ * expanded value's own {{...}} content stays literal.
354
+ */
355
+ function expandPromptPlaceholders(template: string, ctx: CoordinatorPromptContext): string {
356
+ const { mesh, status, coordinatorCliType } = ctx;
357
+ const nodesSection = status?.nodes?.length
358
+ ? buildNodeStatusSection(status.nodes)
359
+ : mesh.nodes.length
360
+ ? buildNodeConfigSection(mesh)
361
+ : '## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`.';
362
+ const replacements: Record<string, string> = {
363
+ meshName: mesh.name,
364
+ repo: mesh.repoIdentity,
365
+ defaultBranch: mesh.defaultBranch || '',
366
+ cliType: coordinatorCliType || '',
367
+ nodes: nodesSection,
368
+ mission: ctx.missionSection?.trim() || '',
369
+ recentActivity: buildRecentActivitySection(ctx.recentActivity) || '',
370
+ operatingNotes: buildOperatingNotesSection(ctx.operatingNotes) || '',
371
+ policy: buildPolicySection(mergeAndNormalizePolicy(undefined, mesh.policy)),
372
+ tools: TOOLS_SECTION,
373
+ workflow: WORKFLOW_SECTION,
374
+ onboarding: ONBOARDING_SECTION,
375
+ rules: buildRulesSection(coordinatorCliType),
376
+ toolExposurePreflight: TOOL_EXPOSURE_PREFLIGHT_SECTION,
377
+ };
378
+ return template.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g, (m, key) => {
379
+ return Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : m;
380
+ });
74
381
  }
75
382
 
76
383
  // ─── Section Builders ───────────────────────────
77
384
 
78
385
  function buildNodeStatusSection(nodes: RepoMeshNodeStatus[]): string {
79
- const lines = ['## Current Node Status', ''];
386
+ const lines = [
387
+ '## Current Node Status',
388
+ '',
389
+ 'Node labels are display context, not aliases. Use exact `nodeId` values in mesh tool calls; do not invent shorthand names such as M1/M2 unless they are explicitly configured labels.',
390
+ '',
391
+ ];
80
392
  for (const n of nodes) {
81
393
  const healthIcon = n.health === 'online' ? '🟢' :
82
394
  n.health === 'dirty' ? '🟡' :
@@ -85,31 +397,251 @@ function buildNodeStatusSection(nodes: RepoMeshNodeStatus[]): string {
85
397
  ? `sessions: ${n.activeSessions.join(', ')}`
86
398
  : 'no active sessions';
87
399
  const branch = n.git?.branch ? `branch: \`${n.git.branch}\`` : '';
88
- lines.push(`- ${healthIcon} **${n.machineLabel}** (${n.nodeId})`);
89
- lines.push(` workspace: \`${n.workspace}\` | ${branch} | ${sessions}`);
400
+ // Render each provider with its detected version when known (T7 visibility)
401
+ // so the coordinator can eyeball a per-node provider-version skew inline —
402
+ // e.g. `claude-cli@1.2.3`. Providers without a reported version render bare.
403
+ const providerVersions = n.providerVersions && typeof n.providerVersions === 'object'
404
+ ? n.providerVersions
405
+ : undefined;
406
+ const providersRendered = n.providers?.length
407
+ ? n.providers
408
+ .map((p) => {
409
+ const version = providerVersions?.[p];
410
+ return version ? `${p}@${version}` : p;
411
+ })
412
+ .join(', ')
413
+ : '';
414
+ const buildVersion = typeof n.daemonBuildVersion === 'string' && n.daemonBuildVersion
415
+ ? `build: ${n.daemonBuildVersion}`
416
+ : '';
417
+ const context = [
418
+ n.daemonId ? `daemon: \`${n.daemonId}\`` : '',
419
+ providersRendered ? `providers: ${providersRendered}` : '',
420
+ buildVersion,
421
+ ].filter(Boolean).join(' | ');
422
+ lines.push(`- ${healthIcon} **${n.machineLabel}** (nodeId: \`${n.nodeId}\`)`);
423
+ lines.push(` workspace: \`${n.workspace}\`${context ? ` | ${context}` : ''} | ${branch} | ${sessions}`);
90
424
  if (n.error) lines.push(` ⚠️ ${n.error}`);
425
+ const nodePrompt = typeof (n as any).systemPrompt === 'string' ? (n as any).systemPrompt.trim() : '';
426
+ if (nodePrompt) {
427
+ lines.push(` 📌 Node instruction: ${indentFollowing(nodePrompt, ' ')}`);
428
+ }
91
429
  }
92
430
  return lines.join('\n');
93
431
  }
94
432
 
95
433
  function buildNodeConfigSection(mesh: LocalMeshEntry): string {
96
- const lines = ['## Configured Nodes', ''];
434
+ const lines = [
435
+ '## Configured Nodes',
436
+ '',
437
+ 'Node labels are display context, not aliases. Use exact `nodeId` values in mesh tool calls; do not invent shorthand names such as M1/M2 unless they are explicitly configured labels.',
438
+ '',
439
+ ];
97
440
  for (const n of mesh.nodes) {
98
441
  const labels: string[] = [];
99
442
  if (n.isLocalWorktree) labels.push('worktree');
100
443
  if (n.policy?.readOnly) labels.push('read-only');
101
444
  const suffix = labels.length ? ` [${labels.join(', ')}]` : '';
102
- lines.push(`- **${n.workspace}** (${n.id})${suffix}`);
445
+ const explicitMachineLabel = typeof (n as any).machineLabel === 'string' ? (n as any).machineLabel : '';
446
+ const explicitLabel = explicitMachineLabel ? ` label: **${explicitMachineLabel}** |` : '';
447
+ const providerPriority = n.policy?.providerPriority?.length ? ` | providers: ${n.policy.providerPriority.join(', ')}` : '';
448
+ // Per-(node, provider) maxParallel cap. Only maxParallel is enforced by the
449
+ // queue; routing is governed by required_tags, not provider roles.
450
+ const providerRoles = Array.isArray(n.policy?.providerRoles)
451
+ ? (n.policy!.providerRoles as Array<{ providerType?: unknown; maxParallel?: unknown }>)
452
+ .map(r => {
453
+ const type = typeof r?.providerType === 'string' ? r.providerType.trim() : '';
454
+ if (!type) return '';
455
+ const cap = Number.isFinite(Number(r?.maxParallel)) ? ` (max ${Math.floor(Number(r.maxParallel))})` : '';
456
+ return `${type}${cap}`;
457
+ })
458
+ .filter(Boolean)
459
+ : [];
460
+ const providerRolesSuffix = providerRoles.length ? ` | caps: ${providerRoles.join(', ')}` : '';
461
+ lines.push(`- ${explicitLabel} nodeId: \`${n.id}\` | workspace: \`${n.workspace}\`${n.daemonId ? ` | daemon: \`${n.daemonId}\`` : ''}${providerPriority}${providerRolesSuffix}${suffix}`);
462
+ // Routing tags: what this node advertises for mesh_enqueue_task required_tags.
463
+ // Surfaced so the coordinator can route by-capability (e.g. enqueue a Windows
464
+ // build with required_tags:["os=win32"], or a custom "test-runner" node).
465
+ // os=/arch= use the same userOverrides → reported precedence as the matcher;
466
+ // the internal converge= tag is omitted (it is not something to target by hand).
467
+ const routingTags: string[] = [];
468
+ const custom = Array.isArray((n as any).capabilities) ? (n as any).capabilities : [];
469
+ for (const t of custom) { const s = typeof t === 'string' ? t.trim() : ''; if (s) routingTags.push(s); }
470
+ const tagOs = ((n as any).userOverrides?.platform || (n as any).reportedPlatform || '').toString().trim();
471
+ const tagArch = ((n as any).userOverrides?.arch || (n as any).reportedArch || '').toString().trim();
472
+ if (tagOs) routingTags.push(`os=${tagOs}`);
473
+ if (tagArch) routingTags.push(`arch=${tagArch}`);
474
+ const wtBranch = typeof (n as any).worktreeBranch === 'string' ? (n as any).worktreeBranch.trim() : '';
475
+ if (n.isLocalWorktree && wtBranch) routingTags.push(`worktree=${wtBranch}`);
476
+ if (routingTags.length) {
477
+ lines.push(` 🏷️ routing tags: ${routingTags.map(t => `\`${t}\``).join(', ')}`);
478
+ }
479
+ const nodePrompt = typeof (n as any).systemPrompt === 'string' ? (n as any).systemPrompt.trim() : '';
480
+ if (nodePrompt) {
481
+ lines.push(` 📌 Node instruction: ${indentFollowing(nodePrompt, ' ')}`);
482
+ }
103
483
  }
104
484
  lines.push('', '_Use `mesh_status` to probe live health before delegating work._');
105
485
  return lines.join('\n');
106
486
  }
107
487
 
488
+ /**
489
+ * Indent every line after the first by `pad`. Used so multi-line node
490
+ * instructions still visually nest under the node bullet without the
491
+ * second line dangling at column zero.
492
+ */
493
+ function indentFollowing(text: string, pad: string): string {
494
+ const lines = text.split('\n');
495
+ if (lines.length === 1) return lines[0];
496
+ return [lines[0], ...lines.slice(1).map(l => pad + l)].join('\n');
497
+ }
498
+
499
+ /**
500
+ * Gap1 — render the "## Recent Activity" section from the locally-derived
501
+ * activity snapshot. Returns '' (no section) when there's nothing worth
502
+ * surfacing: no recent failures, no queued work, no stalls. This keeps a quiet
503
+ * mesh's prompt identical to the pre-activity form.
504
+ */
505
+ function buildRecentActivitySection(activity?: CoordinatorRecentActivity): string {
506
+ if (!activity) return '';
507
+ const failures = Array.isArray(activity.recentFailures) ? activity.recentFailures : [];
508
+ const pending = Number.isFinite(activity.pendingTasks) ? Number(activity.pendingTasks) : 0;
509
+ const assigned = Number.isFinite(activity.assignedTasks) ? Number(activity.assignedTasks) : 0;
510
+ const stalled = Number.isFinite(activity.stalledTasks) ? Number(activity.stalledTasks) : 0;
511
+ const recentFailureCount = Number.isFinite(activity.recentFailureCount)
512
+ ? Number(activity.recentFailureCount)
513
+ : failures.length;
514
+ const windowMinutes = Number.isFinite(activity.windowMinutes) && Number(activity.windowMinutes) > 0
515
+ ? Math.floor(Number(activity.windowMinutes))
516
+ : 30;
517
+
518
+ // Nothing actionable to show → omit the section entirely.
519
+ if (failures.length === 0 && pending === 0 && assigned === 0 && stalled === 0 && recentFailureCount === 0) {
520
+ return '';
521
+ }
522
+
523
+ const lines: string[] = ['## Recent Activity', ''];
524
+ lines.push('A snapshot of this mesh\'s recent ledger/queue state at launch. Use it to decide what needs attention first; call `mesh_task_history` / `mesh_view_queue` for full detail.');
525
+ lines.push('');
526
+
527
+ const counts: string[] = [];
528
+ if (pending > 0) counts.push(`**${pending}** pending`);
529
+ if (assigned > 0) counts.push(`**${assigned}** assigned`);
530
+ if (stalled > 0) counts.push(`**${stalled}** stalled`);
531
+ if (recentFailureCount > 0) counts.push(`**${recentFailureCount}** failed in the last ${windowMinutes} min`);
532
+ if (counts.length) lines.push(`- Queue/ledger: ${counts.join(', ')}.`);
533
+ if (activity.lastActivityAt) lines.push(`- Last ledger activity: ${activity.lastActivityAt}.`);
534
+
535
+ if (failures.length > 0) {
536
+ // Newest first, capped to the 5 most recent so the prompt stays lean.
537
+ const recent = failures.slice(-5).reverse();
538
+ lines.push('', 'Recent failures (newest first):');
539
+ for (const f of recent) {
540
+ const when = f.timestamp ? `${f.timestamp} ` : '';
541
+ const node = f.nodeId ? `node \`${f.nodeId}\`` : 'unknown node';
542
+ const summary = (f.summary || '').trim();
543
+ lines.push(`- ${when}${node}${summary ? ` — ${summary}` : ''}`);
544
+ }
545
+ lines.push('', '_Check `mesh_task_history` before retrying; repeated failures on the same node mean reassign or escalate, not retry._');
546
+ }
547
+
548
+ return lines.join('\n');
549
+ }
550
+
551
+ /**
552
+ * Gap2-A — render the "## Operating Notes" section from accumulated coordinator
553
+ * notes. Returns '' when there are none, so a mesh that has never recorded a
554
+ * note gets the unchanged prompt. Notes are runtime-accumulated lessons that
555
+ * persist across coordinator restarts and are provider-neutral.
556
+ */
557
+ /**
558
+ * 6-4 prompt-build caps for the Operating Notes section. These bound how much
559
+ * of the ledger rides into every coordinator prompt — the ledger itself keeps
560
+ * more (keep-latest 100 prune lives in mesh-ledger.ts); this is a separate,
561
+ * tighter cap applied only when composing the prompt.
562
+ */
563
+ const OPERATING_NOTES_PROMPT_CAP = 20;
564
+ const OPERATING_NOTE_MAX_CHARS = 300;
565
+
566
+ function buildOperatingNotesSection(notes?: CoordinatorOperatingNote[]): string {
567
+ const valid = Array.isArray(notes)
568
+ ? notes.filter(n => n && typeof n.text === 'string' && n.text.trim())
569
+ : [];
570
+ if (valid.length === 0) return '';
571
+
572
+ const categoryLabel: Record<string, string> = {
573
+ provider_quirk: 'provider quirk',
574
+ pattern_to_avoid: 'pattern to avoid',
575
+ recovery_lesson: 'recovery lesson',
576
+ };
577
+
578
+ // Keep only the most recent OPERATING_NOTES_PROMPT_CAP notes in the prompt.
579
+ // `valid` is oldest-first (ledger order), so the newest are at the tail.
580
+ const omittedCount = Math.max(0, valid.length - OPERATING_NOTES_PROMPT_CAP);
581
+ const shown = omittedCount > 0 ? valid.slice(-OPERATING_NOTES_PROMPT_CAP) : valid;
582
+
583
+ const lines: string[] = ['## Operating Notes', ''];
584
+ lines.push('Lessons earlier coordinators on this mesh recorded via `mesh_record_note`. Treat them as accumulated operating knowledge — apply them. When you learn a durable lesson (a provider quirk, a pattern to avoid, a recovery lesson), record it with `mesh_record_note` so future coordinators inherit it.');
585
+ lines.push('');
586
+ for (const n of shown) {
587
+ const cat = n.category && categoryLabel[n.category] ? `[${categoryLabel[n.category]}] ` : '';
588
+ lines.push(`- ${cat}${truncateNote(n.text.trim())}`);
589
+ }
590
+ if (omittedCount > 0) {
591
+ lines.push('');
592
+ lines.push(`_${omittedCount} older note${omittedCount === 1 ? '' : 's'} omitted (kept in ledger; prune with \`mesh_forget_note\`)._`);
593
+ }
594
+ return lines.join('\n');
595
+ }
596
+
597
+ /**
598
+ * Truncate a single operating note to OPERATING_NOTE_MAX_CHARS, appending an
599
+ * ellipsis marker so the coordinator knows the note was clipped in the prompt
600
+ * (the full text stays in the ledger).
601
+ */
602
+ function truncateNote(text: string): string {
603
+ if (text.length <= OPERATING_NOTE_MAX_CHARS) return text;
604
+ return `${text.slice(0, OPERATING_NOTE_MAX_CHARS).trimEnd()}… [truncated]`;
605
+ }
606
+
607
+ /**
608
+ * Render the difficulty→brain presets so the coordinator knows what each
609
+ * `difficulty` value resolves to (which model / thinking level). Machine-local,
610
+ * read live at prompt-build time — seeded defaults when nothing is configured.
611
+ */
612
+ function buildBrainPresetsSection(): string {
613
+ let brains;
614
+ try { brains = getDifficultyBrains(); } catch { brains = {}; }
615
+ const lines = [
616
+ '## Brain presets',
617
+ '',
618
+ 'When you pass `difficulty` on `mesh_enqueue_task`, it resolves to this model / thinking level (an explicit model/thinkingLevel on the task overrides it). Pick easy for trivial work to save tokens, difficult for hard reasoning.',
619
+ '',
620
+ ];
621
+ for (const key of MESH_TASK_DIFFICULTIES) {
622
+ const slot = (brains as Record<string, { provider?: string; model?: string; thinkingLevel?: string } | undefined>)[key];
623
+ if (!slot || (!slot.provider && !slot.model && !slot.thinkingLevel)) {
624
+ lines.push(`- **${key}**: (no preset — ordinary routing)`);
625
+ continue;
626
+ }
627
+ const parts = [
628
+ slot.provider ? `provider: \`${slot.provider}\`` : '',
629
+ slot.model ? `model: \`${slot.model}\`` : '',
630
+ slot.thinkingLevel ? `thinking: \`${slot.thinkingLevel}\`` : '',
631
+ ].filter(Boolean).join(' | ');
632
+ lines.push(`- **${key}**: ${parts}`);
633
+ }
634
+ return lines.join('\n');
635
+ }
636
+
108
637
  function buildPolicySection(policy: RepoMeshPolicy): string {
109
638
  const rules: string[] = [];
110
639
  if (policy.requirePreTaskCheckpoint) rules.push('- Create a git checkpoint **before** starting each task');
111
640
  if (policy.requirePostTaskCheckpoint) rules.push('- Create a git checkpoint **after** each task completes');
112
641
  if (policy.requireApprovalForPush) rules.push('- **Ask for user approval** before pushing to remote');
642
+ if (policy.allowAutoPublishSubmoduleMainCommits) {
643
+ rules.push('- Refinery may auto-publish unreachable submodule gitlink commits to submodule origin/main with non-force pushes after validation and patch-equivalence pass');
644
+ }
113
645
  if (policy.requireApprovalForDestructiveGit) rules.push('- **Ask for user approval** before destructive git operations (force push, reset, etc.)');
114
646
 
115
647
  const dirtyBehavior = {
@@ -135,17 +667,44 @@ const TOOLS_SECTION = `## Available Tools
135
667
  | \`mesh_queue_cancel\` | Cancel a queue task without deleting audit history |
136
668
  | \`mesh_queue_requeue\` | Return a task to pending for retry; clears stale session targets |
137
669
  | \`mesh_send_task\` | Legacy push: enqueue a task targeted at a specific node |
670
+ | \`mesh_mission_upsert\` | Create/update a persistent mission so a multi-task plan survives coordinator restarts; set status completed/abandoned when the outcome is decided |
671
+ | \`mesh_mission_list\` | List every mission with goal, status, and live task progress — the authority for "what work remains" (never hidden by status) |
138
672
  | \`mesh_launch_session\` | Start a new agent session on a node |
139
673
  | \`mesh_read_chat\` | Read recent chat messages from a delegated agent session |
140
674
  | \`mesh_read_debug\` | Collect a daemon-side chat/parser debug bundle for a session |
141
675
  | \`mesh_task_history\` | Read the task ledger — dispatches, completions, failures. Use to understand what has been done before deciding next steps |
676
+ | \`mesh_ledger_query\` | Read-only ledger query along the kind/time/node axes (complement to task-axis mesh_task_history): filter by kind, since, node, tail — answer "what happened on node X / what failed since T" without scanning transcripts |
677
+ | \`mesh_reconcile_ledger\` | Reconcile daemon-local ledgers over P2P — import missing entries from remote nodes into the coordinator local ledger |
678
+ | \`mesh_requeue_held_events\` | Restore recoverable held coordinator events (T6 quarantine / pending-trim) back to the pending queue; lossless, no double-requeue |
679
+ | \`mesh_wait_events\` | Long-poll blocking wait for coordinator events (worker completions/approvals/nudges) up to timeoutMs — drains immediately if any are pending, else blocks until they arrive. Use this instead of busy-polling mesh_status/mesh_view_queue after dispatching work |
680
+ | \`mesh_review_inbox\` | List local worktree nodes needing human review — merge candidates and Refinery-blocked results with evidence/diff summaries |
681
+ | \`mesh_record_note\` | Record a durable, provider-neutral operating note (provider quirk / pattern to avoid / recovery lesson). Future coordinators see it under "## Operating Notes" at launch |
682
+ | \`mesh_forget_note\` | Retract a stale/wrong operating note by note_id or exact text so it stops riding into future coordinators' prompts (append-only tombstone; history preserved) |
142
683
  | \`mesh_git_status\` | Check git status on a specific node |
684
+ | \`mesh_read_node_logs\` | Fetch a remote node's daemon log tail directly over P2P (grep/since/byte-bounded, secrets redacted) — no session/PowerShell needed to debug a node's daemon |
685
+ | \`mesh_fast_forward_node\` | Safely dry-run or explicitly execute an obvious clean fast-forward without launching an agent session |
686
+ | \`mesh_restart_daemon\` | Update a node's daemon to the latest published version on its channel and restart it (the dashboard "preview update" path, as a mesh command) |
143
687
  | \`mesh_checkpoint\` | Create a git checkpoint on a node |
144
688
  | \`mesh_approve\` | Approve/reject a pending agent action |
689
+ | \`mesh_list_pending_approvals\` | List every session across the mesh awaiting an approval decision (the approval inbox) — read-only; enumerate all blocked sessions at once, then drive a mesh_approve for each |
145
690
  | \`mesh_clone_node\` | Create a worktree node for isolated parallel branch work |
146
691
  | \`mesh_refine_node\` | Validate and merge a completed worktree node back into its base branch |
692
+ | \`mesh_refine_batch\` | Batch Refinery: converge multiple sibling worktree nodes onto the base branch in one conflict-aware sequential pipeline |
693
+ | \`mesh_refine_plan\` | Dry-run Refinery plan for a worktree node — config source, validation commands, merge/cleanup intent — without executing validation or git merge |
694
+ | \`mesh_refine_config\` | Refinery config helper (read-only) — unified entry for schema/validate/suggest via a required \`mode\` |
695
+ | \`mesh_change_impact_config\` | Change Impact config helper — unified entry for schema/validate/suggest via a required \`mode\` |
147
696
  | \`mesh_remove_node\` | Remove a node (cleans up worktree if applicable) |
148
- | \`mesh_cleanup_sessions\` | Manually clean up delegated session records for a node |`;
697
+ | \`mesh_cleanup_sessions\` | Manually clean up delegated session records for a node |
698
+ | \`mesh_prune_stale_direct\` | Prune orphaned staleDirect dispatch records (dry-run by default); live/pending work and audit history preserved |
699
+ | \`mesh_init\` | Guided onboarding for a fresh repo: dry-run scan → suggest \`.adhdev/*\` configs (refine/bootstrap/change-impact) + providerPriority + current-config echo; gated write on approval |
700
+ | \`mesh_reinit\` | Re-onboard an already-configured repo: re-suggest with overwrite semantics + current-vs-suggested diff; dry-run preview first, per-section approval before write |
701
+ | \`mesh_write_mesh_json_config\` | Gated write of \`.adhdev/mesh.json\` (repo coordinator-prompt config) from the mesh entry — dry-run/overwrite like mesh_init |
702
+ | \`mesh_magi_review\` | Cross-verify a read-only investigation across a standing panel of independent mesh agents (different machines/providers) instead of a single worker |
703
+ | \`mesh_magi_collect\` | Collect + synthesize a previously dispatched MAGI fan-out by its consensus group id (async companion to mesh_magi_review wait:false) |
704
+ | \`mesh_magi_kind_panel_set\` | Bind a task_kind → MAGI kind-panel slots (the SOLE MAGI panel-resolution surface; machine-local, wholesale replacement — approve current-vs-new first) |
705
+ | \`mesh_magi_kind_panel_list\` | List configured task_kind → MAGI kind-panel slot bindings (machine-local, read-only) |
706
+ | \`mesh_node_slots_list\` | List a node's capability slots (its AI-tool profile: provider/model/thinking + difficulty range + capability tags), read-only |
707
+ | \`mesh_node_slots_set\` | PROPOSE (dry-run) or APPLY a node's capability slots — how you autonomously retune a node's tool profile; WHOLESALE replacement, present current-vs-proposed and get user approval before write=true |`;
149
708
 
150
709
  const TOOL_EXPOSURE_PREFLIGHT_SECTION = `## Tool Exposure Preflight
151
710
 
@@ -154,17 +713,18 @@ Before doing any coordinator work, confirm that the actual callable tool list in
154
713
  const WORKFLOW_SECTION = `## Orchestration Workflow
155
714
 
156
715
  1. **Assess** — Call \`mesh_status\` to see which nodes are healthy and available. Check \`mesh_task_history\` to understand what has already been done in this mesh — previous delegations, completions, and failures.
157
- 2. **Plan** — Decompose the user's request into independent tasks for parallel execution, or sequential tasks when dependencies exist. If \`mesh_task_history\` shows a recent failure for a task, decide whether to retry or reassign.
716
+ 2. **Plan** — Decompose the user's request into independent tasks for parallel execution, or sequential tasks when dependencies exist. If \`mesh_task_history\` shows a recent failure for a task, decide whether to retry or reassign. **For multi-task work, create a mission first**: call \`mesh_mission_upsert\` with a title and goal, then attach every enqueued task with \`mission_id\`. Express "B after A" ordering with \`depends_on\` on the queue task instead of waiting and polling — the system claims dependents automatically when their dependencies complete. When the mission's outcome is decided, update its status (\`completed\`/\`abandoned\`) via \`mesh_mission_upsert\`. If the prompt already shows an **Active Mission**, continue it from its current task state — do not re-enqueue tasks that already exist.
158
717
  3. **Queue / Delegate** — The Mesh uses an autonomous pull-based Work Queue:
159
718
  a. **General Tasks**: Enqueue tasks using \`mesh_enqueue_task\`. Idle node agents will automatically pull tasks from the queue and begin working.
160
719
  b. **Node Preparation**: Reuse an existing idle session on the correct node/provider before launching a new chat/session. Call \`mesh_launch_session\` only when no suitable session exists, when the user explicitly asks for a fresh provider/session, or when branch/worktree isolation requires it. If you need branch isolation for parallel work, call \`mesh_clone_node\` to create a worktree node first.
720
+ b1. **Keep a branch's work on its worktree (worktree affinity).** A worktree node is a durable per-branch workspace, not a one-task throwaway — implement, review, and fix for the same branch all belong on the SAME worktree, and it lives until its work is converged (merged/pushed) and it is cleaned up. So once you clone a worktree for a branch, route every subsequent \`code_change\`/\`validation\`/fix task for that branch back to that same node: pass \`required_tags: ["worktree=<branch>"]\` or \`target_node_id: <that worktree node's id>\`. **Where to get the node id / tag:** the \`mesh_clone_node\` result returns the new node's \`id\` and \`worktreeBranch\` directly — use them immediately. The Configured Nodes list in this prompt is a launch-time snapshot and will NOT list a worktree you cloned after this session started, so do not rely on it for freshly-cloned worktrees; take the id/branch from the \`mesh_clone_node\` result, or call \`mesh_status\` to re-list the live nodes (each worktree there advertises its \`worktree=<branch>\` tag). Do NOT leave same-branch follow-ups untargeted — an untargeted task is claimed by whichever node polls first (usually the base machine node), which strands the work off the branch's worktree. The ONE exception is a \`convergence\` task (merge/push): that is base-only and must NOT be pinned to the worktree.
161
721
  c. **Targeted Tasks**: Use \`mesh_send_task\` only when you need to bypass the queue and force a specific node to execute a task immediately.
162
722
  d. For the first dispatch of a new task, provide a **complete, self-contained** instruction that includes all context the agent needs (file paths, line numbers, what to change, why). Do not send partial instructions expecting future follow-up.
163
723
  e. For a continuation of the same issue in an existing session, send a concise **delta instruction**: current verified state, the exact failed/blocked step, the newly approved action, and final reporting requirements. Do not resend the full original task or open a new chat solely to continue the same work; that wastes coordinator and worker context.
164
- 4. **Monitor** — Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Use \`mesh_view_queue\` to see the status of all pending, assigned, completed, and failed tasks. Do not call \`mesh_read_chat\` again within a few seconds for the same generating session. Use at most one compact \`mesh_read_chat\` check after a completion/approval signal. Handle approvals via \`mesh_approve\`.
724
+ 4. **Monitor** — Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Do **not** repeatedly call \`mesh_status\` or \`mesh_view_queue\` just to wait for assigned/generating work. After dispatching a direct or queued task, send one progress update with the task/session handle, then stop. Wait for \`pendingCoordinatorEvents\` or another completion/approval/status signal, an explicit user status request, or a real timeout/stall signal before reading status/chat/queue again. Use at most one compact \`mesh_read_chat\` check after a terminal signal. Handle approvals via \`mesh_approve\`. **Proactively parallelize new work.** When the user reports a new bug or asks for new work, start it immediately if it is independent of in-flight tasks and there is headroom under \`maxParallelTasks\` — do not wait for a current task to finish or for the user to prompt you to parallelize. Read-only diagnosis (\`live_debug_readonly\`) has no isolation or merge cost, so dispatch it in parallel right away. The no-polling / concurrency-limit rules constrain *re-checking or duplicating already-dispatched work*; they are **not** a reason to defer starting a new, independent task.
165
725
  5. **Verify** — When a task reports completion or git work is visible, call \`mesh_git_status\` to verify changes were made.
166
726
  6. **Checkpoint** — Call \`mesh_checkpoint\` to save the work.
167
- 7. **Converge branches** — Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary and \`mesh_refine_node\` for clean worktree branches when safe. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
727
+ 7. **Converge branches** — Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary. For obvious clean branch catch-up (ahead 0, behind > 0, upstream fresh, no dirty/stash/submodule issues), use \`mesh_fast_forward_node\` dry-run first and execute only when explicitly safe/approved; this avoids consuming an agent session. Use \`mesh_refine_node\` for clean worktree branches when safe. Before/refine merging root commits that contain submodule gitlink changes, require each submodule commit to be reachable from the configured submodule remote main branch, not merely present on a feature ref or local checkout. If \`mesh_refine_node\` returns \`submodule_reachability_failed\` or publish-required evidence, keep the public convergence bucket as \`blocked_review\`; unless \`allowAutoPublishSubmoduleMainCommits\` is explicitly enabled and Refinery reports successful non-force publish plus post-publish verification, ask the user for explicit approval to push/publish the unreachable submodule commit(s) to submodule main, then rerun \`mesh_refine_node\`. Do not merge the root branch until the submodule commit(s) are reachable from submodule origin/main. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
168
728
  8. **Clean up** — Remove worktree nodes via \`mesh_remove_node\` after their work is merged or no longer needed.
169
729
  9. **Report** — Summarize what was done, what changed, any issues, and the branch convergence state.
170
730
 
@@ -181,6 +741,28 @@ Follow these recovery rules:
181
741
  3. **If no recovery context**: The stop may be intentional (normal completion). Use \`mesh_read_chat\` once to verify, then move on.
182
742
  4. **Always record what happened**: After handling a failure, briefly note the outcome in your report to the user.`;
183
743
 
744
+ const ONBOARDING_SECTION = `## Onboarding / Reinit
745
+
746
+ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (or to **re-init / reconfigure** an already-onboarded repo), run ONE guided, approval-gated conversation. You draft, the user approves, the daemon writes. Never auto-write a heuristic suggestion without an explicit user approval turn.
747
+
748
+ **Save scopes — label every draft with its scope before asking for approval:**
749
+ - **repo-file (commit target)** — \`.adhdev/refine.json\`, \`.adhdev/worktree_bootstrap.json\`, \`.adhdev/change-impact.json\`, \`.adhdev/mesh.json\`. These are committed to the repository and shared with every machine/contributor.
750
+ - **machine-local** — MAGI kind→panel bindings, node providerPriority (\`~/.adhdev/meshes.json\`). These stay on this machine and are NOT committed.
751
+
752
+ **Guided sequence:**
753
+ 1. **Scan (dry-run)** — Call \`mesh_init\` (write=false, the default). It returns per-domain suggested configs for refine / worktree_bootstrap / change-impact, a recommended providerPriority, AND \`currentConfig\` — the currently-saved config per domain (repo files + machine-local \`magiKindPanels\`). Nothing is written.
754
+ 2. **Present drafts** — For each domain, show the user the suggested config with its **save scope label** (repo-file vs machine-local). When \`currentConfig\` already has a saved value for a domain (init on a partially-onboarded repo, or any reinit), present a **current-vs-suggested diff**, not just the suggestion.
755
+ 3. **Approve → gated write** — Only after the user approves, call the matching gated-write tool:
756
+ - repo \`.adhdev/*\` config files → \`mesh_init\` with \`write=true\` (and \`overwrite=true\` ONLY for domains the user approved replacing).
757
+ - \`.adhdev/mesh.json\` (coordinator prompt / operating notes) → \`mesh_write_mesh_json_config\` (write=true, overwrite only if approved).
758
+ - machine-local MAGI kind→panel slots → \`mesh_magi_kind_panel_set\` (write=true). NOTE: a kind binding is a **wholesale replacement** of that kind's slot list — present the current-vs-new slots first. providerPriority → apply via node policy update.
759
+
760
+ **init vs reinit:**
761
+ - **\`mesh_init\`** — for a fresh, never-onboarded repo. Existing config files are kept (existing-wins) unless the user explicitly approves overwrite. Use for first-time setup.
762
+ - **\`mesh_reinit\`** — for a repo that is already onboarded and needs its config refreshed. It re-suggests with OVERWRITE semantics and returns the current-vs-suggested \`currentConfig\` echo. Its first call is a DRY-RUN preview: you MUST present the per-section current-vs-suggested diff and get EXPLICIT per-section approval before re-invoking with write=true. Overwrite is a wholesale replacement, so it silently drops operator hand-edits if you skip the diff — never do that.
763
+
764
+ `;
765
+
184
766
  function buildRulesSection(coordinatorCliType?: string): string {
185
767
  const coordinatorNote = coordinatorCliType
186
768
  ? `\n- **Coordinator runtime is not a delegation default.** This coordinator is running as \`${coordinatorCliType}\`, but delegated node sessions must follow the user's requested provider, not the coordinator's own runtime.`
@@ -188,19 +770,30 @@ function buildRulesSection(coordinatorCliType?: string): string {
188
770
 
189
771
  return `## Rules
190
772
 
191
- - **Minimize coordinator context.** The coordinator's job is routing, not implementing. Do not read source files, run commands, or analyze code directly delegate all of that to node agents. Your context should stay lean.
192
- - **Delegate analysis too.** If you need to understand a bug or explore the codebase, send that investigation as a task to the queue or a node. Do not do it yourself.
193
- - **Respect explicit provider requests.** If the user names an agent/provider, pass the matching provider type to \`mesh_launch_session\`: Hermes \`hermes-cli\`, Claude Code/Claude \`claude-cli\`, Codex \`codex-cli\`, Gemini \`gemini-cli\`. Never substitute \`claude-cli\` just because the coordinator itself is Claude Code.
194
- - **Front-load new task messages.** When calling \`mesh_enqueue_task\` or \`mesh_send_task\` for a new task, include everything the agent needs: what files to touch, what the problem is, what the fix should look like. The agent won't ask follow-up questions.
195
- - **Avoid context-wasting restarts.** For follow-up, retry, commit/push, preview, or cleanup work on the same issue, prefer the existing idle session and send only the delta from its last verified state. Start a fresh chat/session only for genuinely independent work, explicit provider/user request, unsafe transcript contamination, or required branch/worktree isolation.
196
- - **Don't inspect code.** Treat delegated agent summaries as self-reports, not verification. Verify side effects via \`mesh_git_status\` (including related repo freshness when configured), not by reading source files.
197
- - **Don't over-parallelize.** Start with 1-2 concurrent tasks. Scale up if they succeed. Never launch a duplicate session or second worker solely because \`mesh_read_chat\` has no final assistant message while the delegated session is still showing tool/terminal activity.
198
- - **Handle failures with context.** If a task fails, check \`mesh_task_history\` first to see if this task was attempted before and how it failed. Read the chat to understand why, then decide: retry on the same node, reassign to a different node, or escalate to the user.
199
- - **Check history before starting.** At the beginning of a coordination session, call \`mesh_task_history\` to understand what was previously delegated and its outcomes. This prevents duplicate work and informs recovery decisions.
200
- - **Keep the user informed.** Report progress after each delegation round one or two sentences, not a narration.
201
- - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
202
- - **Never fabricate tool results.** Always call the actual tool; never pretend you did.
203
- - **Clean up worktree nodes.** After a worktree task completes and its changes are merged or checkpointed, call \`mesh_remove_node\` to free resources.
204
- - **Do not strand completed branches.** A checkpointed or clean feature/worktree branch is not done by itself. Merge/refine it to the mesh default branch, or explicitly report one of \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\` with the next action.
205
- - **Name worktree branches meaningfully.** Use descriptive names like \`feat/auth-refactor\` or \`fix/build-123\`.${coordinatorNote}`;
773
+ - **Route, don't implement.** Delegate all code reading, analysis, and execution to node agents. Never read source files or run commands in the coordinatorkeep context lean.
774
+ - **Front-load task messages.** Include everything the agent needs (files, problem, expected fix) in \`mesh_enqueue_task\` / \`mesh_send_task\`. Append a structured result request at the end: ask the worker to conclude with a JSON block containing \`status\`, \`changedFiles\`, \`gitStatus\`, \`validationResults\`, \`errors\`, \`nextAction\`. The daemon parses this automatically; you can read it from \`mesh_task_history\`.
775
+ - **Reuse idle sessions.** For follow-up, retry, commit/push, or cleanup on the same issue, send only the delta to the existing idle session. Start fresh only for independent work, provider mismatch, transcript contamination, or required worktree isolation.
776
+ - **Worktree affinity.** A worktree is a durable per-branch workspace; keep all of a branch's code_change/fix/review work on its worktree node by targeting \`required_tags: ["worktree=<branch>"]\` or \`target_node_id\`. Get the id/branch from the \`mesh_clone_node\` result or a live \`mesh_status\` the Configured Nodes snapshot won't list a worktree cloned after launch. Untargeted same-branch follow-ups drift to the base node. Only \`convergence\` (merge/push) runs on the base, never pinned to the worktree.
777
+ - **Classify task difficulty to save tokens.** For each task you enqueue, judge its execution difficulty and pass \`difficulty\`: \`easy\` (extraction, renames, doc tweaks, trivial fixes), \`medium\` (ordinary feature/bugfix work), \`difficult\` (architecture, tricky debugging, multi-file refactors, subtle reasoning), or \`freeform\`. The mesh's per-difficulty brain preset then runs easy tasks on a cheaper model at low reasoning effort and hard tasks on a stronger model at high effort — real token savings on simple work. The current presets are shown in the "Brain presets" section below. You may still pass an explicit \`model\`/\`thinkingLevel\` to override the preset for one task.
778
+ - **Retune node profiles when routing is a poor fit — but only with approval.** A node's capability slots (its provider/model/thinking + difficulty range + capability tags, seen via \`mesh_node_slots_list\`) are what task→node fitness routing matches against. If you notice a persistent mismatch — e.g. every \`difficult\` task lands on a node whose only slot is a cheap model, or a capability a node clearly has isn't declared — you MAY propose a slot change with \`mesh_node_slots_set\` (write=false). That returns current-vs-proposed; present that diff to the user with a one-line reason and apply (write=true) ONLY after they approve. It is a WHOLESALE replacement of the node's slots, so include the slots you want to keep. Never rewrite a node's profile silently or without a clear routing reason.
779
+ - **Respect explicit provider requests.** Map: Hermes \`hermes-cli\`, Claude/Claude Code \`claude-cli\`, Codex \`codex-cli\`, Gemini \`gemini-cli\`, Antigravity \`antigravity-cli\`. Never substitute the coordinator's own runtime.
780
+ - **Verify via git, not source.** Use \`mesh_git_status\` to confirm side effects. Treat agent summaries as self-reports, not verification.
781
+ - **Limit parallelism.** Start with 1–2 tasks; scale only on success. Never duplicate a session because \`mesh_read_chat\` shows no final message while tool/terminal activity is ongoing. This caps *concurrent* load — it does not mean serialize independent work: when a new, independent request arrives and there is headroom under \`maxParallelTasks\`, dispatch it right away rather than waiting for an in-flight task or a user nudge (read-only diagnosis especially, since it has no merge cost).
782
+ - **Check history first.** Call \`mesh_task_history\` at session start to avoid duplicate work and inform recovery. On failure, read task history before retrying.
783
+ - **Sequence shared-base-moving merges.** Parallel dispatch is encouraged, but merging one worktree can advance another in-flight worktree's base especially a shared submodule pointer — turning a clean fast-forward into a diverged rebase (patch-equivalence correctly blocks this). Before merging an in-flight worktree while siblings are also in flight, land in an intentional order, re-clone long-running worktrees from the advanced base, or expect to manually rebase + ff-only the laggards; merging an independent fix mid-flight can strand siblings into a rebase.
784
+ - **Converge branches.** After worktree tasks: refine/fast-forward, or classify as \`pushed_feature_branch_needs_merge\` / \`blocked_review\` / \`cleanup_candidate\` / \`not_mergeable\`. Clean up with \`mesh_remove_node\`.
785
+ - **Refinery is config-driven.** \`mesh_refine_node\` must run validation from \`.adhdev/refine.{json,yaml,yml}\` or \`repo-mesh.refine.*\`. Heuristics are scaffolding only.
786
+ - **Submodule reachability = publish-needed.** \`submodule_reachability_failed\` classify as \`blocked_review\`, request user approval to push to submodule main, then rerun \`mesh_refine_node\`.
787
+ - **Honor per-node instructions.** When a node carries a 📌 Node instruction in the nodes section, include the relevant parts of that instruction in the task message you send to that node. Don't paraphrase the instruction into your own words — quote it verbatim so the worker agent sees exactly what the user wrote.
788
+ - **Mission status does not update itself.** When a mission's tasks are all done or the work is abandoned, explicitly call \`mesh_mission_upsert\` to set status \`completed\` or \`abandoned\`. Never leave a finished mission in \`active\`. All-cancelled tasks with no further work → \`abandoned\`.
789
+ - **Never fabricate tool results.** Always call the actual tool.
790
+ - **Keep the user informed.** One or two sentences after each delegation round.${coordinatorNote}
791
+
792
+ ### Task Messaging Requirements
793
+
794
+ When you compose the task message you dispatch to a node, include these requirements so the worker follows repo conventions the daemon can't enforce for it:
795
+
796
+ - **OSS English commits.** If a task commits anything under \`oss/\` (an AGPL public repo whose history external contributors read), tell the worker explicitly that commit messages in \`oss/\` MUST be English. Root-level commits (proprietary packages) may use any language.
797
+ - **Scoped test runs.** For a validation or code-change task, instruct the worker to run only the tests covering the changed files (\`vitest run <path>\` or \`-t <name>\`), not the whole suite. Run the full suite only when the task is explicitly a full-suite gate — a broad daemon-core run is minutes of wall-clock and the biggest source of worker slowness.
798
+ - **Branch convergence state.** For a worktree task, require the completion report to classify the touched branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. A task that ends on a non-main branch is not complete unless the report names that state and the next step.`;
206
799
  }