@adhdev/daemon-core 0.9.82-rc.33 → 0.9.82-rc.331

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 (316) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -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 +46 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +115 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +279 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +51 -12
  37. package/dist/index.js +38419 -13805
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +41329 -16835
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/mesh/contracts.d.ts +164 -0
  48. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  49. package/dist/mesh/coordinator-registry.d.ts +59 -0
  50. package/dist/mesh/mesh-active-work.d.ts +174 -0
  51. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  52. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  53. package/dist/mesh/mesh-events-pending.d.ts +45 -0
  54. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  55. package/dist/mesh/mesh-events-utils.d.ts +47 -0
  56. package/dist/mesh/mesh-events.d.ts +6 -49
  57. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  58. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  59. package/dist/mesh/mesh-init.d.ts +86 -0
  60. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  61. package/dist/mesh/mesh-ledger.d.ts +77 -1
  62. package/dist/mesh/mesh-missions.d.ts +116 -0
  63. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  64. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  65. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  66. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  67. package/dist/mesh/mesh-routing.d.ts +70 -0
  68. package/dist/mesh/mesh-runtime-store.d.ts +401 -0
  69. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  70. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  71. package/dist/mesh/mesh-work-queue.d.ts +207 -5
  72. package/dist/mesh/preview-freshness.d.ts +18 -0
  73. package/dist/mesh/refine-config.d.ts +215 -0
  74. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  75. package/dist/providers/acp-provider-instance.d.ts +2 -0
  76. package/dist/providers/approval-utils.d.ts +13 -0
  77. package/dist/providers/chat-message-normalization.d.ts +12 -0
  78. package/dist/providers/cli-provider-instance.d.ts +61 -3
  79. package/dist/providers/contracts.d.ts +130 -6
  80. package/dist/providers/external-sources.d.ts +71 -0
  81. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  82. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  83. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  84. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  85. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  86. package/dist/providers/native-history/index.d.ts +13 -0
  87. package/dist/providers/provider-instance-manager.d.ts +13 -0
  88. package/dist/providers/provider-instance.d.ts +13 -1
  89. package/dist/providers/provider-loader.d.ts +26 -4
  90. package/dist/providers/provider-trust.d.ts +31 -0
  91. package/dist/providers/read-chat-contract.d.ts +29 -0
  92. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  93. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  94. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  95. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  96. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  97. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  98. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  99. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  100. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  101. package/dist/providers/sdk/v1/index.d.ts +30 -0
  102. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  103. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  104. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  105. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  106. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  107. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  108. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  109. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  110. package/dist/providers/spec/adapter.d.ts +69 -0
  111. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  112. package/dist/providers/spec/evaluator.d.ts +23 -0
  113. package/dist/providers/spec/fsm-driver.d.ts +306 -0
  114. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  115. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  116. package/dist/providers/spec/fsm-types.d.ts +144 -0
  117. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  118. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  119. package/dist/providers/spec/route.d.ts +4 -0
  120. package/dist/providers/spec/types.d.ts +180 -0
  121. package/dist/providers/status-monitor.d.ts +7 -7
  122. package/dist/providers/transcript-v2.d.ts +176 -0
  123. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  124. package/dist/providers/working-dir.d.ts +17 -0
  125. package/dist/repo-mesh-types.d.ts +295 -13
  126. package/dist/sessions/registry.d.ts +6 -0
  127. package/dist/shared-types-extra.d.ts +2 -4
  128. package/dist/shared-types.d.ts +52 -2
  129. package/dist/status/normalize.d.ts +1 -1
  130. package/dist/status/normalize.js +1 -0
  131. package/dist/status/normalize.js.map +1 -1
  132. package/dist/status/normalize.mjs +1 -0
  133. package/dist/status/normalize.mjs.map +1 -1
  134. package/dist/status/reporter.d.ts +2 -0
  135. package/dist/status/snapshot.d.ts +1 -0
  136. package/dist/types.d.ts +5 -0
  137. package/package.json +7 -3
  138. package/src/agent-stream/poller.ts +2 -3
  139. package/src/agent-stream/provider-adapter.ts +1 -1
  140. package/src/boot/daemon-lifecycle.ts +55 -12
  141. package/src/boot/process-hardening.ts +89 -0
  142. package/src/build-info.ts +73 -0
  143. package/src/chat/source-machine.ts +534 -0
  144. package/src/chat/source-resolver.ts +0 -0
  145. package/src/chat/subscription-updates.ts +20 -1
  146. package/src/cli-adapter-types.d.ts +1 -0
  147. package/src/cli-adapter-types.ts +47 -2
  148. package/src/cli-adapters/cli-script-runner.ts +421 -0
  149. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  150. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  151. package/src/cli-adapters/provider-cli-adapter.ts +713 -1141
  152. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  153. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  154. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  155. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  156. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  157. package/src/cli-adapters/pty-transport.ts +2 -1
  158. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  159. package/src/cli-adapters/resolve-executable.ts +90 -0
  160. package/src/cli-adapters/session-host-transport.ts +2 -1
  161. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  162. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  163. package/src/cli-adapters/terminal-screen.ts +16 -81
  164. package/src/commands/chat-commands.ts +1823 -62
  165. package/src/commands/cli-manager.ts +286 -14
  166. package/src/commands/handler.ts +809 -2
  167. package/src/commands/mesh-coordinator.ts +332 -122
  168. package/src/commands/router.ts +7270 -1306
  169. package/src/commands/stream-commands.ts +8 -0
  170. package/src/commands/upgrade-helper.ts +81 -30
  171. package/src/config/chat-history.ts +483 -24
  172. package/src/config/config.ts +12 -0
  173. package/src/config/mesh-config.ts +388 -6
  174. package/src/config/recent-activity.ts +8 -2
  175. package/src/daemon/dev-auto-implement.ts +3 -2
  176. package/src/daemon/dev-cli-debug.ts +10 -1
  177. package/src/detection/cli-detector.ts +28 -9
  178. package/src/detection/ide-detector.ts +55 -16
  179. package/src/detection/win32-ide-version.ts +106 -0
  180. package/src/git/change-impact-config.ts +354 -0
  181. package/src/git/git-commands.ts +55 -14
  182. package/src/git/git-diff.ts +53 -0
  183. package/src/git/git-executor.ts +12 -0
  184. package/src/git/git-status.ts +574 -43
  185. package/src/git/git-types.ts +14 -62
  186. package/src/git/git-worktree.ts +8 -1
  187. package/src/git/index.ts +16 -0
  188. package/src/index.ts +145 -11
  189. package/src/installer.d.ts +1 -1
  190. package/src/installer.ts +8 -6
  191. package/src/ipc/local-ipc-server.ts +278 -0
  192. package/src/launch.d.ts +1 -1
  193. package/src/launch.ts +37 -28
  194. package/src/logging/async-batch-writer.ts +55 -0
  195. package/src/logging/log-redactor.ts +100 -0
  196. package/src/logging/log-tail-reader.ts +220 -0
  197. package/src/logging/logger.ts +2 -1
  198. package/src/mesh/contracts.ts +329 -0
  199. package/src/mesh/coordinator-prompt.ts +234 -31
  200. package/src/mesh/coordinator-registry.ts +121 -0
  201. package/src/mesh/mesh-active-work.ts +623 -0
  202. package/src/mesh/mesh-delivery-policy.ts +315 -0
  203. package/src/mesh/mesh-events-coordinator.ts +2110 -0
  204. package/src/mesh/mesh-events-pending.ts +508 -0
  205. package/src/mesh/mesh-events-stale.ts +290 -0
  206. package/src/mesh/mesh-events-utils.ts +254 -0
  207. package/src/mesh/mesh-events.ts +30 -1035
  208. package/src/mesh/mesh-fast-forward.ts +839 -0
  209. package/src/mesh/mesh-host-ownership.ts +73 -0
  210. package/src/mesh/mesh-init.ts +260 -0
  211. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  212. package/src/mesh/mesh-ledger.ts +589 -102
  213. package/src/mesh/mesh-missions.ts +248 -0
  214. package/src/mesh/mesh-reconcile-loop.ts +786 -0
  215. package/src/mesh/mesh-refine-batch.ts +197 -0
  216. package/src/mesh/mesh-refine-status.ts +231 -0
  217. package/src/mesh/mesh-review-inbox.ts +307 -0
  218. package/src/mesh/mesh-routing.ts +291 -0
  219. package/src/mesh/mesh-runtime-store.ts +1578 -0
  220. package/src/mesh/mesh-task-stats.ts +154 -0
  221. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  222. package/src/mesh/mesh-work-queue.ts +874 -141
  223. package/src/mesh/preview-freshness.ts +118 -0
  224. package/src/mesh/refine-config.ts +403 -0
  225. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  226. package/src/providers/acp-provider-instance.ts +25 -9
  227. package/src/providers/approval-utils.d.ts +4 -0
  228. package/src/providers/approval-utils.ts +47 -5
  229. package/src/providers/chat-message-normalization.ts +45 -5
  230. package/src/providers/cli-provider-instance.ts +986 -99
  231. package/src/providers/contracts.d.ts +55 -0
  232. package/src/providers/contracts.ts +141 -6
  233. package/src/providers/extension-provider-instance.ts +12 -7
  234. package/src/providers/external-sources.ts +218 -0
  235. package/src/providers/ide-provider-instance.ts +35 -12
  236. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  237. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  238. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  239. package/src/providers/native-history/dispatcher.ts +340 -0
  240. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  241. package/src/providers/native-history/index.ts +30 -0
  242. package/src/providers/provider-instance-manager.ts +30 -0
  243. package/src/providers/provider-instance.ts +10 -1
  244. package/src/providers/provider-loader.ts +662 -50
  245. package/src/providers/provider-schema.ts +87 -14
  246. package/src/providers/provider-trust.ts +114 -0
  247. package/src/providers/read-chat-contract.ts +76 -16
  248. package/src/providers/sdk/README.md +49 -0
  249. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  250. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  251. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  252. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  253. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  254. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  255. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  256. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  257. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  258. package/src/providers/sdk/v1/index.ts +152 -0
  259. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  260. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  261. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  262. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  263. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  264. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  265. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  272. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  279. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  280. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  281. package/src/providers/sdk/v1/validators/index.ts +19 -0
  282. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  283. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  284. package/src/providers/spec/adapter.ts +168 -0
  285. package/src/providers/spec/cli-adapter.ts +986 -0
  286. package/src/providers/spec/evaluator.ts +345 -0
  287. package/src/providers/spec/fsm-driver.ts +993 -0
  288. package/src/providers/spec/fsm-evaluator.ts +255 -0
  289. package/src/providers/spec/fsm-loader.ts +120 -0
  290. package/src/providers/spec/fsm-types.ts +238 -0
  291. package/src/providers/spec/native-history-executor.ts +1136 -0
  292. package/src/providers/spec/pre-launch-trust.ts +104 -0
  293. package/src/providers/spec/route.ts +51 -0
  294. package/src/providers/spec/types.ts +226 -0
  295. package/src/providers/status-monitor.d.ts +7 -7
  296. package/src/providers/status-monitor.ts +37 -22
  297. package/src/providers/transcript-v2.ts +567 -0
  298. package/src/providers/types/interactive-prompt.ts +536 -0
  299. package/src/providers/version-archive.ts +64 -24
  300. package/src/providers/working-dir.ts +23 -0
  301. package/src/repo-mesh-types.ts +378 -14
  302. package/src/sessions/registry.ts +6 -0
  303. package/src/shared-types-extra.ts +2 -4
  304. package/src/shared-types.d.ts +8 -0
  305. package/src/shared-types.ts +57 -1
  306. package/src/status/builders.ts +26 -6
  307. package/src/status/normalize.ts +2 -0
  308. package/src/status/reporter.ts +19 -1
  309. package/src/status/snapshot.ts +84 -25
  310. package/src/system/host-memory.ts +29 -12
  311. package/src/types.ts +5 -0
  312. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  313. package/dist/mesh/mesh-sync.d.ts +0 -53
  314. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  315. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  316. package/src/mesh/mesh-sync.ts +0 -111
@@ -1,28 +1,334 @@
1
- import { existsSync, writeFileSync, readFileSync, openSync, closeSync, unlinkSync } from 'fs';
2
- import { join } from 'path';
3
1
  import { randomUUID } from 'crypto';
4
- import { getLedgerDir } from './mesh-ledger.js';
2
+ import { requireMeshHostQueueOwner } from './mesh-host-ownership.js';
3
+ import type { RepoMeshDaemonRole } from '../repo-mesh-types.js';
4
+ import { MESH_CONVERGE_REFINE_TAG, resolveAutoConvergeCodeChange } from '../repo-mesh-types.js';
5
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
6
+ import { getMesh } from '../config/mesh-config.js';
5
7
 
6
8
  export type MeshTaskStatus = 'pending' | 'assigned' | 'completed' | 'failed' | 'cancelled';
7
9
  export type MeshActiveTaskStatus = Extract<MeshTaskStatus, 'pending' | 'assigned'>;
8
10
  export type MeshHistoricalTaskStatus = Extract<MeshTaskStatus, 'completed' | 'failed' | 'cancelled'>;
11
+ export type MeshTaskMode = 'code_change' | 'validation' | 'live_debug_readonly' | 'launch_app' | 'convergence';
9
12
 
10
13
  export const ACTIVE_MESH_QUEUE_STATUSES: MeshActiveTaskStatus[] = ['pending', 'assigned'];
11
14
  export const HISTORICAL_MESH_QUEUE_STATUSES: MeshHistoricalTaskStatus[] = ['completed', 'failed', 'cancelled'];
15
+ export const MESH_TASK_MODES: MeshTaskMode[] = ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'];
16
+
17
+ export interface MeshTaskModeValidationResult {
18
+ valid: boolean;
19
+ taskMode?: MeshTaskMode;
20
+ violations: string[];
21
+ allowedOperations?: string[];
22
+ }
23
+
24
+ const LIVE_DEBUG_READONLY_FORBIDDEN: Array<{ label: string; pattern: RegExp }> = [
25
+ { label: 'source_edit', pattern: /\b(edit|modify|patch|apply\s+patch|write\s+(?:to\s+)?(?:file|source)|overwrite|delete\s+file|remove\s+file|create\s+file|touch\s+file)\b/i },
26
+ { label: 'checkpoint', pattern: /\b(checkpoint|mesh_checkpoint)\b/i },
27
+ { label: 'deploy_or_version_bump', pattern: /\b(deploy|wrangler\s+deploy|version[-\s]?bump|npm\s+version|release|npm\s+publish|yarn\s+publish|pnpm\s+publish)\b/i },
28
+ { label: 'destructive_shell', pattern: /\b(rm\s+-rf|mv\s+\S+\s+\S+|truncate\s|tee\s+\S+|sed\s+-i|shred\b)\b/i },
29
+ { label: 'package_install', pattern: /\b(npm\s+(?:install|i|add|link|uninstall|remove)|yarn\s+(?:add|remove|link)|pnpm\s+(?:add|remove|link)|pip\s+install|brew\s+install|apt\s+install|cargo\s+install)\b/i },
30
+ { label: 'container_mutation', pattern: /\b(docker\s+(?:build|run|exec|push|tag|rmi|rm|create|start|stop|kill)|kubectl\s+(?:apply|delete|patch|replace|create|scale))\b/i },
31
+ ];
32
+
33
+ /**
34
+ * Negation cues that, when they appear shortly before a mutation keyword inside
35
+ * the same clause, mean the keyword is being *forbidden* or described rather
36
+ * than invoked (e.g. "do not git reset", "절대 push 하지 마세요"). Matched
37
+ * case-insensitively. The Korean cues intentionally include sub-string forms
38
+ * ("않", "금지", "말 것") so conjugated variants are caught.
39
+ */
40
+ const NEGATION_CUES: string[] = [
41
+ "don't", 'do not', 'never', 'avoid', 'without', 'no longer', 'not', 'forbidden',
42
+ '하지 마', '하지 마세요', '말 것', '금지', '없음', '않',
43
+ ];
44
+
45
+ /** How many whitespace-delimited tokens before a keyword we scan for negation. */
46
+ const NEGATION_WINDOW_TOKENS = 6;
47
+
48
+ /**
49
+ * Returns true if a negation cue appears within {@link NEGATION_WINDOW_TOKENS}
50
+ * tokens before `matchIndex`, staying inside the same clause — we stop at
51
+ * sentence/line/clause boundaries (newline, `.`/`!`/`?`, `;`) so a negation in a
52
+ * previous sentence does not suppress a real command in the next one.
53
+ */
54
+ function hasNegationBefore(text: string, matchIndex: number): boolean {
55
+ const before = text.slice(0, matchIndex);
56
+ // Restrict to the current clause: cut at the last clause/sentence/line break.
57
+ const clauseStart = Math.max(
58
+ before.lastIndexOf('\n'),
59
+ before.lastIndexOf('. '),
60
+ before.lastIndexOf('! '),
61
+ before.lastIndexOf('? '),
62
+ before.lastIndexOf(';'),
63
+ );
64
+ const clause = before.slice(clauseStart + 1);
65
+ const lower = clause.toLowerCase();
66
+ // Whitespace tokens immediately preceding the keyword, within the window.
67
+ const tokens = clause.split(/\s+/).filter(Boolean);
68
+ const windowTokens = tokens.slice(Math.max(0, tokens.length - NEGATION_WINDOW_TOKENS));
69
+ const windowText = windowTokens.join(' ').toLowerCase();
70
+ for (const cue of NEGATION_CUES) {
71
+ const c = cue.toLowerCase();
72
+ // ASCII cues are word-ish phrases — match in the bounded window only.
73
+ // CJK cues have no spaces, so the window-join can miss them; for those
74
+ // fall back to scanning the whole clause (still clause-bounded).
75
+ if (/[^\x00-\x7f]/.test(c)) {
76
+ if (lower.includes(c)) return true;
77
+ } else if (windowText.includes(c)) {
78
+ return true;
79
+ }
80
+ }
81
+ return false;
82
+ }
83
+
84
+ /**
85
+ * Korean (and other) negation often trails the verb it negates ("git reset 하지
86
+ * 마세요" = "do not git reset"). Returns true if a CJK negation cue appears
87
+ * shortly after `matchEnd`, within the same clause. Scoped to CJK cues only —
88
+ * trailing ASCII words rarely negate a preceding command and would over-match.
89
+ */
90
+ function hasTrailingNegation(text: string, matchEnd: number): boolean {
91
+ const after = text.slice(matchEnd);
92
+ // Clause-bound the lookahead: stop at the next clause/line break.
93
+ const clauseEnd = (() => {
94
+ const stops = [after.indexOf('\n'), after.indexOf('. '), after.indexOf('; ')]
95
+ .filter(i => i >= 0);
96
+ return stops.length ? Math.min(...stops) : after.length;
97
+ })();
98
+ const clause = after.slice(0, clauseEnd).toLowerCase();
99
+ for (const cue of NEGATION_CUES) {
100
+ const c = cue.toLowerCase();
101
+ if (/[^\x00-\x7f]/.test(c) && clause.includes(c)) return true;
102
+ }
103
+ return false;
104
+ }
105
+
106
+ /**
107
+ * Returns true when the keyword at [matchStart, matchEnd) looks like an actual
108
+ * command invocation rather than a plain-prose mention. Command context is:
109
+ * - inside a fenced code block (``` ... ```) or inline backticks (`...`)
110
+ * - on a shell-prompt line (starts with `$ ` or `> `)
111
+ * - at a command-call position: line start (leading whitespace allowed) or
112
+ * right after a shell connective (`&&`, `||`, `|`, `;`) or an imperative
113
+ * connective ("then"/"run"/"," ) that introduces a command.
114
+ * Plain mid-sentence prose mentions (no backticks, no command position) are not
115
+ * command context and are excluded from violations.
116
+ */
117
+ function isMutationKeywordInCommandContext(text: string, matchStart: number, matchEnd: number): boolean {
118
+ if (isInsideBackticksOrFence(text, matchStart, matchEnd)) return true;
119
+
120
+ // The line containing the match, and the portion of it before the keyword.
121
+ const lineStart = text.lastIndexOf('\n', matchStart - 1) + 1;
122
+ const linePrefix = text.slice(lineStart, matchStart);
123
+
124
+ // Shell-prompt line: "$ ..." or "> ..." (leading whitespace allowed).
125
+ if (/^\s*[$>]\s/.test(text.slice(lineStart))) return true;
126
+
127
+ // Line start (only whitespace before the keyword on this line).
128
+ if (/^\s*$/.test(linePrefix)) return true;
129
+
130
+ // After a shell connective or imperative connective introducing a command.
131
+ // We look at what immediately precedes the keyword on the same line.
132
+ if (/(?:&&|\|\||\||;)\s*$/.test(linePrefix)) return true;
133
+ if (/(?:^|[\s,])(?:then|run|first)\s+$/i.test(linePrefix)) return true;
134
+ if (/,\s*$/.test(linePrefix)) return true;
135
+
136
+ return false;
137
+ }
138
+
139
+ /**
140
+ * True if [matchStart, matchEnd) lies inside an inline-backtick span or a fenced
141
+ * code block. Fenced blocks (```...```) take precedence; otherwise we count
142
+ * inline backticks before the match — an odd count means we are inside a span.
143
+ */
144
+ function isInsideBackticksOrFence(text: string, matchStart: number, matchEnd: number): boolean {
145
+ // Fenced code blocks: count ``` fences before the match.
146
+ const fenceRe = /```/g;
147
+ let fenceCount = 0;
148
+ let m: RegExpExecArray | null;
149
+ while ((m = fenceRe.exec(text)) !== null) {
150
+ if (m.index >= matchStart) break;
151
+ fenceCount++;
152
+ }
153
+ if (fenceCount % 2 === 1) return true;
154
+
155
+ // Inline backticks: count single backticks before the match start, ignoring
156
+ // those that are part of a ``` fence (handled above). An odd count → inside.
157
+ let inlineCount = 0;
158
+ for (let i = 0; i < matchStart; i++) {
159
+ if (text[i] === '`') {
160
+ // Skip triple-fence backticks.
161
+ if (text[i + 1] === '`' && text[i + 2] === '`') {
162
+ i += 2;
163
+ continue;
164
+ }
165
+ inlineCount++;
166
+ }
167
+ }
168
+ return inlineCount % 2 === 1;
169
+ }
170
+
171
+ /**
172
+ * Decides whether a forbidden keyword match at [matchStart, matchEnd) should
173
+ * count as a real violation. A match counts only when it is in command context
174
+ * and not negated. Negation always wins (even inside a code block), per the
175
+ * conservative rule: code-block + negation → exclude; other code-block → keep.
176
+ */
177
+ function isRealMutationMatch(text: string, matchStart: number, matchEnd: number): boolean {
178
+ if (hasNegationBefore(text, matchStart)) return false;
179
+ if (hasTrailingNegation(text, matchEnd)) return false;
180
+ return isMutationKeywordInCommandContext(text, matchStart, matchEnd);
181
+ }
182
+
183
+ /**
184
+ * Runs a global regex over `text` and returns true if any match is a real
185
+ * mutation (command context, not negated).
186
+ */
187
+ function patternHasRealMutation(pattern: RegExp, text: string): boolean {
188
+ const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');
189
+ let match: RegExpExecArray | null;
190
+ while ((match = re.exec(text)) !== null) {
191
+ if (isRealMutationMatch(text, match.index, match.index + match[0].length)) return true;
192
+ if (match.index === re.lastIndex) re.lastIndex++; // avoid zero-width loop
193
+ }
194
+ return false;
195
+ }
196
+
197
+ /**
198
+ * Git subcommands that mutate the working tree, index, refs, or remote.
199
+ * `stash` and `checkout` are intentionally absent here: they have read-only
200
+ * variants (`git stash list`/`show`, `git checkout-index`) and are classified
201
+ * token-by-token in {@link detectGitMutation} rather than by bare keyword.
202
+ */
203
+ const GIT_MUTATION_SUBCOMMANDS = new Set([
204
+ 'add', 'commit', 'push', 'reset', 'rebase', 'clean', 'switch', 'merge',
205
+ 'tag', 'restore', 'rm', 'mv', 'cherry-pick', 'revert', 'pull', 'fetch',
206
+ 'am', 'apply', 'gc', 'prune',
207
+ ]);
208
+
209
+ /**
210
+ * Read-only `git stash` variants. Any other `git stash <x>` (pop/apply/drop/
211
+ * push/save/clear, or bare `git stash` which defaults to push) is a mutation.
212
+ */
213
+ const GIT_STASH_READONLY_SUBCOMMANDS = new Set(['list', 'show']);
214
+
215
+ /**
216
+ * Detects a true git mutation in free-text task message, token-aware so that
217
+ * read-only diagnostics (`git stash list`, `git stash show --stat`,
218
+ * `git checkout-index`, `git status`, `git diff`, `git log`, ...) are allowed.
219
+ * Returns true only when a genuine mutating git invocation is present.
220
+ */
221
+ function detectGitMutation(message: string): boolean {
222
+ const re = /\bgit\s+([a-z][a-z0-9-]*)/gi;
223
+ let match: RegExpExecArray | null;
224
+ while ((match = re.exec(message)) !== null) {
225
+ const sub = match[1].toLowerCase();
226
+ // Only treat a mutating `git <sub>` as a real violation when it appears
227
+ // as an actual command (code/command context) and is not negated. Plain
228
+ // prose mentions ("don't git reset", "we won't push") are ignored.
229
+ const isReal = () => isRealMutationMatch(message, match!.index, match!.index + match![0].length);
230
+ if (GIT_MUTATION_SUBCOMMANDS.has(sub)) {
231
+ if (isReal()) return true;
232
+ continue;
233
+ }
234
+ if (sub === 'stash') {
235
+ // Token following `git stash`; read-only only for list/show.
236
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
237
+ const next = after ? after[1].toLowerCase() : '';
238
+ if (!GIT_STASH_READONLY_SUBCOMMANDS.has(next) && isReal()) return true; // bare stash = push, or pop/apply/drop/...
239
+ } else if (sub === 'checkout') {
240
+ // `git checkout <ref/path>` mutates; `git checkout-index` is matched
241
+ // as its own token by the regex (sub === 'checkout-index') and is read-only.
242
+ if (isReal()) return true;
243
+ } else if (sub === 'submodule') {
244
+ // `git submodule update` mutates; `git submodule status` is read-only.
245
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
246
+ const next = after ? after[1].toLowerCase() : '';
247
+ if ((next === 'update' || next === 'add' || next === 'sync' || next === 'deinit') && isReal()) return true;
248
+ } else if (sub === 'worktree') {
249
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
250
+ const next = after ? after[1].toLowerCase() : '';
251
+ if ((next === 'add' || next === 'remove' || next === 'move' || next === 'prune') && isReal()) return true;
252
+ }
253
+ // checkout-index, stash-with-no-next-already-handled, status/diff/log/show/
254
+ // rev-parse/branch/submodule status fall through as read-only.
255
+ }
256
+ return false;
257
+ }
258
+
259
+ export function normalizeMeshTaskMode(value: unknown): MeshTaskMode | undefined {
260
+ if (typeof value !== 'string') return undefined;
261
+ const normalized = value.trim() as MeshTaskMode;
262
+ return (MESH_TASK_MODES as string[]).includes(normalized) ? normalized : undefined;
263
+ }
264
+
265
+ export function validateMeshTaskModeRequest(mode: unknown, message: string): MeshTaskModeValidationResult {
266
+ const taskMode = normalizeMeshTaskMode(mode);
267
+ if (!taskMode) {
268
+ return { valid: true, violations: [] };
269
+ }
270
+ if (taskMode !== 'live_debug_readonly') {
271
+ return { valid: true, taskMode, violations: [] };
272
+ }
273
+ const text = message || '';
274
+ // Only flag keywords that look like real commands (code/command context) and
275
+ // are not negated — descriptive/prohibitive prose ("don't run `npm publish`",
276
+ // "read-only, no deploy") must not trip the guardrail.
277
+ const violations = LIVE_DEBUG_READONLY_FORBIDDEN
278
+ .filter(rule => patternHasRealMutation(rule.pattern, text))
279
+ .map(rule => rule.label);
280
+ if (detectGitMutation(text)) {
281
+ violations.push('git_mutation');
282
+ }
283
+ return {
284
+ valid: violations.length === 0,
285
+ taskMode,
286
+ violations,
287
+ allowedOperations: [
288
+ 'process/log/window/port/session inspection',
289
+ 'read-only filesystem listing/reading',
290
+ 'status probes and keep-running handle reporting',
291
+ 'diagnostic summaries without source edits, commits, checkpoints, pushes, deploys, resets, rebases, or destructive cleanups',
292
+ ],
293
+ };
294
+ }
12
295
 
13
296
  export interface MeshWorkQueueEntry {
14
297
  id: string;
15
298
  meshId: string;
16
299
  message: string;
17
300
  status: MeshTaskStatus;
301
+ taskMode?: MeshTaskMode;
18
302
  /** If specified, only this node can claim the task (used by legacy mesh_send_task) */
19
303
  targetNodeId?: string;
20
304
  /** If specified, only this runtime session can claim the task */
21
305
  targetSessionId?: string;
306
+ /** If specified, a node must expose all tags before it can claim the task. */
307
+ requiredTags?: string[];
308
+ /**
309
+ * M1: ids of tasks that must reach 'completed' before this task is claimable.
310
+ * Forward references (ids not yet enqueued) are allowed for batch flows and
311
+ * simply keep the task waiting until the referenced task exists and completes.
312
+ */
313
+ dependsOn?: string[];
314
+ /** M1/M3: mission this task belongs to (joins mesh_missions). */
315
+ missionId?: string;
316
+ /**
317
+ * M1: why this task is held back (e.g. "dependency_failed:<taskId>").
318
+ * Only set by the system on dependency failure under the 'block' policy;
319
+ * waiting-on-dependency state is computed at view time, not stored.
320
+ */
321
+ blockedReason?: string;
22
322
  /** The node that actually claimed and is executing the task */
23
323
  assignedNodeId?: string;
24
324
  /** The session currently executing the task */
25
325
  assignedSessionId?: string;
326
+ /**
327
+ * Provider type of the session that claimed the task. Recorded so the queue
328
+ * can enforce per-(node, provider) maxParallel caps (RepoMeshNodePolicy
329
+ * providerRoles) by counting active assignments grouped by node + provider.
330
+ */
331
+ assignedProviderType?: string;
26
332
  /** Human/operator reason for terminal cancellation. */
27
333
  cancelReason?: string;
28
334
  cancelledAt?: string;
@@ -30,6 +336,8 @@ export interface MeshWorkQueueEntry {
30
336
  requeueReason?: string;
31
337
  requeuedAt?: string;
32
338
  requeueCount?: number;
339
+ /** Max automatic requeue attempts. When requeueCount reaches this, task is auto-failed. */
340
+ maxRetries?: number;
33
341
  /** Last automatic queue session spin-up attempt, for mesh_view_queue/debug visibility. */
34
342
  autoLaunch?: {
35
343
  status: 'skipped' | 'started' | 'failed' | 'completed';
@@ -45,50 +353,199 @@ export interface MeshWorkQueueEntry {
45
353
  updatedAt: string;
46
354
  }
47
355
 
48
- function getQueuePath(meshId: string): string {
49
- const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
50
- return join(getLedgerDir(), `${safe}.queue.json`);
356
+ export interface MeshQueueMutationOptions {
357
+ ownerRole?: RepoMeshDaemonRole;
51
358
  }
52
359
 
53
- function getLockPath(meshId: string): string {
54
- const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
55
- return join(getLedgerDir(), `${safe}.queue.lock`);
360
+ export function normalizeMeshCapabilityTags(value: unknown): string[] {
361
+ if (!Array.isArray(value)) return [];
362
+ const seen = new Set<string>();
363
+ return value
364
+ .map(tag => typeof tag === 'string' ? tag.trim() : '')
365
+ .filter(Boolean)
366
+ .filter(tag => {
367
+ if (seen.has(tag)) return false;
368
+ seen.add(tag);
369
+ return true;
370
+ });
371
+ }
372
+
373
+ function firstProviderPriority(policy: unknown): string | undefined {
374
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
375
+ ? (policy as Record<string, unknown>).providerPriority
376
+ : undefined;
377
+ if (!Array.isArray(raw)) return undefined;
378
+ return raw.find(type => typeof type === 'string' && type.trim())?.trim();
379
+ }
380
+
381
+ function readNodeOverride(node: { userOverrides?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
382
+ const overrides = node?.userOverrides;
383
+ if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) return null;
384
+ const value = (overrides as Record<string, unknown>)[key];
385
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
56
386
  }
57
387
 
58
388
  /**
59
- * Simple advisory file lock using O_EXCL (atomic create) for queue mutations.
60
- * Retries up to 10 times at 30 ms intervals; proceeds without lock on timeout
61
- * to prevent deadlock (best-effort far better than no locking at all).
389
+ * Live, self-reported platform/arch the owning daemon stamped onto the node from
390
+ * its own process.platform/process.arch via the git_status envelope. Kept on a
391
+ * field DISTINCT from userOverrides so capability-tag derivation can prefer an
392
+ * explicit operator override while still self-healing auto-detected nodes — and
393
+ * so the value reflects the node's real OS rather than the coordinator's.
62
394
  */
63
- function withQueueLock<T>(meshId: string, fn: () => T): T {
64
- const lockPath = getLockPath(meshId);
65
- let fd = -1;
66
- for (let i = 0; i < 10; i++) {
67
- try { fd = openSync(lockPath, 'wx'); break; } catch {
68
- const deadline = Date.now() + 30;
69
- while (Date.now() < deadline) { /* spin */ }
70
- }
71
- }
72
- try { return fn(); } finally {
73
- if (fd !== -1) try { closeSync(fd); } catch { /* noop */ }
74
- try { unlinkSync(lockPath); } catch { /* already removed */ }
75
- }
395
+ function readNodeReporter(node: { reportedPlatform?: unknown; reportedArch?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
396
+ const value = key === 'platform' ? node?.reportedPlatform : node?.reportedArch;
397
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
76
398
  }
77
399
 
78
- function readQueue(meshId: string): MeshWorkQueueEntry[] {
79
- const path = getQueuePath(meshId);
80
- if (!existsSync(path)) return [];
400
+ export function buildMeshNodeCapabilityTags(
401
+ node: { capabilities?: unknown; policy?: unknown; isLocalWorktree?: unknown; worktreeBranch?: unknown; userOverrides?: unknown; reportedPlatform?: unknown; reportedArch?: unknown } | undefined,
402
+ providerType?: string,
403
+ ): string[] {
404
+ const provider = typeof providerType === 'string' && providerType.trim()
405
+ ? providerType.trim()
406
+ : firstProviderPriority(node?.policy);
407
+ const worktreeBranch = typeof node?.worktreeBranch === 'string' && node.worktreeBranch.trim()
408
+ ? node.worktreeBranch.trim()
409
+ : null;
410
+ // Per-node platform/arch precedence (highest → lowest):
411
+ // 1. userOverrides.platform/arch — an EXPLICIT operator override always wins.
412
+ // 2. reportedPlatform/reportedArch — the live OS the owning daemon
413
+ // self-reported (its own process.platform/process.arch via the git_status
414
+ // envelope), persisted to the node record on each direct probe. This is
415
+ // why a Windows member advertises os=win32 even though the COORDINATOR
416
+ // computing these tags runs on darwin — without it the consumer reads the
417
+ // persistent node (operator userOverrides empty) and would fall straight
418
+ // through to the coordinator's own process.platform, mislabeling every
419
+ // node os=darwin. We prefer this LIVE value over any stale auto-stamp.
420
+ // 3. process.platform/process.arch — last-resort fallback, correct only for
421
+ // the local coordinator node / local worktree nodes that have not yet
422
+ // been probed (their workspace lives on THIS machine anyway).
423
+ // Vocabulary is raw process.platform/process.arch ("darwin"/"win32"/"linux",
424
+ // "arm64"/"x64") on both the advertiser and the required_tags matcher, which
425
+ // compares with plain string equality (nodeSatisfiesRequiredTags) — so this
426
+ // keeps the win32/darwin/linux vocabulary the matcher already expects.
427
+ const os = readNodeOverride(node, 'platform') ?? readNodeReporter(node, 'platform') ?? process.platform;
428
+ const arch = readNodeOverride(node, 'arch') ?? readNodeReporter(node, 'arch') ?? process.arch;
429
+ return normalizeMeshCapabilityTags([
430
+ ...(Array.isArray(node?.capabilities) ? node.capabilities : []),
431
+ `os=${os}`,
432
+ `arch=${arch}`,
433
+ ...(provider ? [`provider=${provider}`] : []),
434
+ // Worktree nodes automatically expose a "worktree=<branch>" tag so that
435
+ // mesh_enqueue_task with required_tags: ["worktree=<branch>"] routes
436
+ // only to the matching worktree node.
437
+ ...(node?.isLocalWorktree === true && worktreeBranch ? [`worktree=${worktreeBranch}`] : []),
438
+ // Convergence routing: advertise how this node can land its work onto base.
439
+ // - converge=refine: local worktree nodes (on ANY machine — refine_mesh_node
440
+ // now forwards to the owning daemon) can run the Refinery merge → push →
441
+ // cleanup against their own checkout, so they accept code_change tasks.
442
+ // - converge=fast_forward: non-worktree nodes (the machine itself) can only
443
+ // ff/push an already-converged branch; they are NOT a destination for
444
+ // code_change work (a worktree is created first, and that worktree node
445
+ // receives the task instead). Reuses the ordinary required-tags filter —
446
+ // the load-balancing scheduler auto-injects converge=refine for code_change
447
+ // so such work is hard-filtered onto refine-capable nodes.
448
+ ...(node?.isLocalWorktree === true ? ['converge=refine'] : ['converge=fast_forward']),
449
+ ]);
450
+ }
451
+
452
+ export function nodeSatisfiesRequiredTags(requiredTags: unknown, capabilityTags: unknown): boolean {
453
+ const required = normalizeMeshCapabilityTags(requiredTags);
454
+ if (required.length === 0) return true;
455
+ const available = new Set(normalizeMeshCapabilityTags(capabilityTags));
456
+ return required.every(tag => available.has(tag));
457
+ }
458
+
459
+ /**
460
+ * Convergence-aware required-tags resolution (load-balancing scheduler, opt-in).
461
+ *
462
+ * When the mesh enables policy.autoConvergeCodeChange, a `converge=refine` required
463
+ * tag is merged into a code_change task's required tags at enqueue time, so the
464
+ * scheduler hard-filters the task onto refine-capable worktree nodes only (on any
465
+ * machine — refine_mesh_node forwards to the owning daemon). Because the tag is
466
+ * persisted on the queue entry, BOTH the eligibility scan (maybeAutoLaunchOneQueueSession)
467
+ * and the claim transaction (claimNextQueueTask → nodeSatisfiesRequiredTags) enforce
468
+ * it consistently.
469
+ *
470
+ * Strict backward compatibility — the injection is skipped (returns the explicit tags
471
+ * unchanged) when ANY of:
472
+ * - the mesh does not opt in (autoConvergeCodeChange !== true), or
473
+ * - the task is not code_change (validation / live_debug_readonly / launch_app /
474
+ * convergence carry no merge cost and may run anywhere), or
475
+ * - the task is explicitly targeted (targetNodeId): the operator chose the node, so
476
+ * we do not second-guess it by filtering on convergence capability.
477
+ * Idempotent: normalizeMeshCapabilityTags dedupes, so re-injection is a no-op.
478
+ */
479
+ export function resolveConvergeRequiredTags(
480
+ meshId: string,
481
+ taskMode: MeshTaskMode | undefined,
482
+ explicitRequiredTags: string[],
483
+ opts?: { targetNodeId?: string },
484
+ ): string[] {
485
+ if (taskMode !== 'code_change') return explicitRequiredTags;
486
+ if (typeof opts?.targetNodeId === 'string' && opts.targetNodeId.trim()) return explicitRequiredTags;
487
+ let optedIn = false;
81
488
  try {
82
- const content = readFileSync(path, 'utf-8');
83
- return JSON.parse(content) as MeshWorkQueueEntry[];
489
+ optedIn = resolveAutoConvergeCodeChange(getMesh(meshId)?.policy as any);
84
490
  } catch {
85
- return [];
491
+ optedIn = false;
86
492
  }
493
+ if (!optedIn) return explicitRequiredTags;
494
+ return normalizeMeshCapabilityTags([...explicitRequiredTags, MESH_CONVERGE_REFINE_TAG]);
495
+ }
496
+
497
+ function withQueueLock<T>(_meshId: string, fn: () => T): T {
498
+ return MeshRuntimeStore.getInstance().transaction(fn);
499
+ }
500
+
501
+ function readQueue(meshId: string): MeshWorkQueueEntry[] {
502
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId);
87
503
  }
88
504
 
89
505
  function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
90
- const path = getQueuePath(meshId);
91
- writeFileSync(path, JSON.stringify(queue, null, 2), 'utf-8');
506
+ MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
507
+ }
508
+
509
+ function normalizeDependsOn(value: unknown): string[] {
510
+ if (!Array.isArray(value)) return [];
511
+ const seen = new Set<string>();
512
+ return value
513
+ .map(id => typeof id === 'string' ? id.trim() : '')
514
+ .filter(Boolean)
515
+ .filter(id => {
516
+ if (seen.has(id)) return false;
517
+ seen.add(id);
518
+ return true;
519
+ });
520
+ }
521
+
522
+ /**
523
+ * M1: detect dependency cycles before enqueue. Walks the dependency graph of
524
+ * existing queue entries plus the new task's edges. Fail-closed: a cycle
525
+ * rejects the enqueue entirely. Synchronous and bounded by queue size.
526
+ */
527
+ export function assertNoDependencyCycle(meshId: string, newTaskId: string, dependsOn: string[]): void {
528
+ if (dependsOn.length === 0) return;
529
+ if (dependsOn.includes(newTaskId)) {
530
+ throw new Error(`dependency_cycle_detected: task '${newTaskId}' cannot depend on itself`);
531
+ }
532
+ const adjacency = new Map<string, string[]>();
533
+ for (const entry of readQueue(meshId)) {
534
+ adjacency.set(entry.id, normalizeDependsOn(entry.dependsOn));
535
+ }
536
+ adjacency.set(newTaskId, dependsOn);
537
+ // DFS from the new task: if we can reach newTaskId again, the edges form a cycle.
538
+ const stack = [...dependsOn];
539
+ const visited = new Set<string>();
540
+ while (stack.length > 0) {
541
+ const current = stack.pop()!;
542
+ if (current === newTaskId) {
543
+ throw new Error(`dependency_cycle_detected: task '${newTaskId}' is part of a dependency cycle via '${dependsOn.join(', ')}'`);
544
+ }
545
+ if (visited.has(current)) continue;
546
+ visited.add(current);
547
+ stack.push(...(adjacency.get(current) ?? []));
548
+ }
92
549
  }
93
550
 
94
551
  /**
@@ -97,22 +554,120 @@ function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
97
554
  export function enqueueTask(
98
555
  meshId: string,
99
556
  message: string,
100
- opts?: { targetNodeId?: string; targetSessionId?: string }
557
+ opts?: {
558
+ targetNodeId?: string;
559
+ targetSessionId?: string;
560
+ taskMode?: MeshTaskMode | string;
561
+ requiredTags?: string[];
562
+ /** M1: tasks that must complete before this one is claimable. */
563
+ dependsOn?: string[];
564
+ /** M1/M3: mission this task belongs to. */
565
+ missionId?: string;
566
+ /** Explicit task id for batch/template flows (M5). Random UUID when omitted. */
567
+ id?: string;
568
+ } & MeshQueueMutationOptions,
101
569
  ): MeshWorkQueueEntry {
570
+ requireMeshHostQueueOwner(opts);
571
+ const modeValidation = validateMeshTaskModeRequest(opts?.taskMode, message);
572
+ if (!modeValidation.valid) {
573
+ throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
574
+ }
575
+ const id = typeof opts?.id === 'string' && opts.id.trim() ? opts.id.trim() : randomUUID();
576
+ const dependsOn = normalizeDependsOn(opts?.dependsOn);
102
577
  return withQueueLock(meshId, () => {
103
- const queue = readQueue(meshId);
578
+ if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, id)) {
579
+ throw new Error(`duplicate_task_id: task '${id}' already exists in mesh '${meshId}'`);
580
+ }
581
+ assertNoDependencyCycle(meshId, id, dependsOn);
582
+ const callerTags = normalizeMeshCapabilityTags(opts?.requiredTags);
583
+ // Convergence routing (opt-in): auto-inject converge=refine for code_change
584
+ // tasks so they hard-filter onto refine-capable worktree nodes. No-op unless
585
+ // the mesh opts in; explicit target_node_id / required_tags are preserved.
586
+ // Routing is otherwise governed solely by the caller's required_tags (hard
587
+ // filter through nodeSatisfiesRequiredTags) — no role/taskMode auto-routing.
588
+ const resolvedRequiredTags = resolveConvergeRequiredTags(
589
+ meshId,
590
+ modeValidation.taskMode,
591
+ callerTags,
592
+ { targetNodeId: opts?.targetNodeId },
593
+ );
104
594
  const entry: MeshWorkQueueEntry = {
105
- id: randomUUID(),
595
+ id,
106
596
  meshId,
107
597
  message,
108
598
  status: 'pending',
599
+ taskMode: modeValidation.taskMode,
109
600
  targetNodeId: opts?.targetNodeId,
110
601
  targetSessionId: opts?.targetSessionId,
602
+ requiredTags: resolvedRequiredTags,
603
+ ...(dependsOn.length > 0 ? { dependsOn } : {}),
604
+ ...(typeof opts?.missionId === 'string' && opts.missionId.trim() ? { missionId: opts.missionId.trim() } : {}),
111
605
  createdAt: new Date().toISOString(),
112
606
  updatedAt: new Date().toISOString(),
113
607
  };
114
- queue.push(entry);
115
- writeQueue(meshId, queue);
608
+ MeshRuntimeStore.getInstance().insertQueueEntry(entry);
609
+ return entry;
610
+ });
611
+ }
612
+
613
+ /**
614
+ * Record a direct-dispatch task (mesh_send_task) as an already-assigned queue
615
+ * entry so it is attributable to a mission.
616
+ *
617
+ * Direct dispatch normally bypasses the queue entirely — the task lives only in
618
+ * the ledger + mesh_direct_dispatches table, neither of which carries a
619
+ * missionId, so {@link summarizeMissionTasks}/{@link computeMeshTaskStats}
620
+ * (which both scan the queue for `task.missionId`) count it as 0. When a
621
+ * mission is attached, we materialise the same queue entry shape an enqueued
622
+ * task would have, but pre-assigned to the dispatched node/session and stamped
623
+ * with the dispatch timestamp. The terminal event path (updateSessionTaskStatus
624
+ * → findAssignedBySession) then flips it to completed/failed exactly like a
625
+ * pulled task, so mission total + completed aggregates work with no extra wiring.
626
+ *
627
+ * Intentionally separate from {@link enqueueTask}: enqueue creates `pending`
628
+ * work for the queue to assign, whereas this records work already dispatched
629
+ * out-of-band. They share the missionId stamping rule and mode validation.
630
+ */
631
+ export function recordDirectDispatchTask(
632
+ meshId: string,
633
+ message: string,
634
+ opts: {
635
+ id: string;
636
+ missionId: string;
637
+ assignedNodeId?: string;
638
+ assignedSessionId?: string;
639
+ taskMode?: MeshTaskMode | string;
640
+ dispatchedAt?: string;
641
+ },
642
+ ): MeshWorkQueueEntry | null {
643
+ const missionId = typeof opts.missionId === 'string' ? opts.missionId.trim() : '';
644
+ if (!missionId) return null;
645
+ const taskId = typeof opts.id === 'string' ? opts.id.trim() : '';
646
+ if (!taskId) return null;
647
+ const modeValidation = validateMeshTaskModeRequest(opts.taskMode, message);
648
+ if (!modeValidation.valid) {
649
+ throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
650
+ }
651
+ const now = opts.dispatchedAt && opts.dispatchedAt.trim() ? opts.dispatchedAt : new Date().toISOString();
652
+ return withQueueLock(meshId, () => {
653
+ if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId)) {
654
+ // Already materialised (e.g. retry of the same dispatch) — leave it untouched.
655
+ return null;
656
+ }
657
+ const entry: MeshWorkQueueEntry = {
658
+ id: taskId,
659
+ meshId,
660
+ message,
661
+ status: 'assigned',
662
+ ...(modeValidation.taskMode ? { taskMode: modeValidation.taskMode } : {}),
663
+ missionId,
664
+ ...(opts.assignedNodeId ? { targetNodeId: opts.assignedNodeId, assignedNodeId: opts.assignedNodeId } : {}),
665
+ ...(opts.assignedSessionId ? { targetSessionId: opts.assignedSessionId, assignedSessionId: opts.assignedSessionId } : {}),
666
+ dispatchTimestamp: now,
667
+ createdAt: now,
668
+ updatedAt: now,
669
+ };
670
+ MeshRuntimeStore.getInstance().insertQueueEntry(entry);
116
671
  return entry;
117
672
  });
118
673
  }
@@ -121,43 +676,83 @@ export function enqueueTask(
121
676
  * Get all tasks in the queue, optionally filtered by status.
122
677
  */
123
678
  export function getQueue(meshId: string, opts?: { status?: MeshTaskStatus[] }): MeshWorkQueueEntry[] {
124
- let queue = readQueue(meshId);
125
- if (opts?.status?.length) {
126
- const statuses = new Set(opts.status);
127
- queue = queue.filter(q => statuses.has(q.status));
128
- }
129
- return queue;
679
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId, opts?.status?.length ? opts.status : undefined);
680
+ }
681
+
682
+ export function getMeshQueueRevision(meshId: string): string {
683
+ return MeshRuntimeStore.getInstance().getQueueRevision(meshId);
130
684
  }
131
685
 
132
686
  /**
133
687
  * Find the next pending task that this node is allowed to claim, and mark it as assigned.
688
+ *
689
+ * `opts.providerType` is stamped onto the claimed entry (assignedProviderType) so
690
+ * per-(node, provider) caps can be counted. `opts.providerMaxParallel`, when set,
691
+ * is the enforced per-(node, provider) cap from RepoMeshNodePolicy.providerRoles:
692
+ * a task is not assigned to this (node, provider) once it already has that many
693
+ * active assignments. This composes with the global/taskMode caps (stricter wins).
134
694
  */
135
- export function claimNextTask(meshId: string, nodeId: string, sessionId: string): MeshWorkQueueEntry | null {
136
- return withQueueLock(meshId, () => {
137
- const queue = readQueue(meshId);
138
- const hasActiveAssignment = queue.some(q => q.status === 'assigned' && (
139
- q.assignedSessionId === sessionId || q.assignedNodeId === nodeId
140
- ));
141
- if (hasActiveAssignment) return null;
142
- let targetIdx = queue.findIndex(q => q.status === 'pending' && q.targetSessionId === sessionId);
143
- if (targetIdx === -1) {
144
- targetIdx = queue.findIndex(q => q.status === 'pending' && q.targetNodeId === nodeId && !q.targetSessionId);
145
- }
146
- if (targetIdx === -1) {
147
- targetIdx = queue.findIndex(q => q.status === 'pending' && !q.targetNodeId && !q.targetSessionId);
695
+ export function claimNextTask(
696
+ meshId: string,
697
+ nodeId: string,
698
+ sessionId: string,
699
+ capabilityTags?: string[],
700
+ opts?: { providerType?: string; providerMaxParallel?: number },
701
+ ): MeshWorkQueueEntry | null {
702
+ return MeshRuntimeStore.getInstance().claimNextQueueTask(meshId, nodeId, sessionId, capabilityTags, opts);
703
+ }
704
+
705
+ // ─── M1: Dependency Failure Propagation ─────────
706
+
707
+ export type DependencyFailurePolicy = 'block' | 'cancel';
708
+
709
+ function resolveDependencyFailurePolicy(meshId: string): DependencyFailurePolicy {
710
+ try {
711
+ const policy = (getMesh(meshId)?.policy ?? {}) as Record<string, unknown>;
712
+ return policy.onDependencyFailure === 'cancel' ? 'cancel' : 'block';
713
+ } catch {
714
+ return 'block';
715
+ }
716
+ }
717
+
718
+ /**
719
+ * Apply the mesh's onDependencyFailure policy to pending dependents of a task
720
+ * that just reached a failed/cancelled terminal state.
721
+ *
722
+ * - 'block' (default): dependents stay pending with blockedReason
723
+ * "dependency_failed:<taskId>" so an operator can requeue/cancel them.
724
+ * - 'cancel': dependents are cancelled (cascading to their own dependents).
725
+ *
726
+ * Must be called inside the queue lock of the triggering transition.
727
+ */
728
+ function propagateDependencyFailure(meshId: string, failedTaskId: string): void {
729
+ const policy = resolveDependencyFailurePolicy(meshId);
730
+ const store = MeshRuntimeStore.getInstance();
731
+ const frontier = [failedTaskId];
732
+ const seen = new Set<string>(frontier);
733
+ while (frontier.length > 0) {
734
+ const currentId = frontier.pop()!;
735
+ const dependents = store.getQueueEntries(meshId, ['pending'])
736
+ .filter(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(currentId));
737
+ for (const dependent of dependents) {
738
+ if (seen.has(dependent.id)) continue;
739
+ seen.add(dependent.id);
740
+ if (policy === 'cancel') {
741
+ dependent.status = 'cancelled';
742
+ dependent.cancelledAt = new Date().toISOString();
743
+ dependent.cancelReason = `dependency_failed:${currentId}`;
744
+ store.updateQueueEntry(dependent);
745
+ frontier.push(dependent.id); // cascade to transitive dependents
746
+ } else {
747
+ dependent.blockedReason = `dependency_failed:${currentId}`;
748
+ store.updateQueueEntry(dependent);
749
+ }
148
750
  }
149
- if (targetIdx === -1) return null;
150
- const entry = queue[targetIdx];
151
- entry.status = 'assigned';
152
- entry.assignedNodeId = nodeId;
153
- entry.assignedSessionId = sessionId;
154
- entry.dispatchTimestamp = new Date().toISOString();
155
- entry.updatedAt = new Date().toISOString();
156
- writeQueue(meshId, queue);
157
- return entry;
158
- });
751
+ }
159
752
  }
160
753
 
754
+ const DEPENDENCY_FAILURE_TERMINALS = new Set<MeshTaskStatus>(['failed', 'cancelled']);
755
+
161
756
  /**
162
757
  * Update the status of a specific task.
163
758
  * Used when a session completes, fails, or stalls.
@@ -166,15 +761,16 @@ export function updateTaskStatus(
166
761
  meshId: string,
167
762
  taskId: string,
168
763
  status: MeshTaskStatus,
764
+ opts?: MeshQueueMutationOptions,
169
765
  ): MeshWorkQueueEntry | null {
766
+ requireMeshHostQueueOwner(opts);
170
767
  return withQueueLock(meshId, () => {
171
- const queue = readQueue(meshId);
172
- const idx = queue.findIndex(q => q.id === taskId);
173
- if (idx === -1) return null;
174
- queue[idx].status = status;
175
- queue[idx].updatedAt = new Date().toISOString();
176
- writeQueue(meshId, queue);
177
- return queue[idx];
768
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
769
+ if (!entry) return null;
770
+ entry.status = status;
771
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
772
+ if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, taskId);
773
+ return entry;
178
774
  });
179
775
  }
180
776
 
@@ -184,14 +780,12 @@ export function recordTaskAutoLaunch(
184
780
  autoLaunch: Omit<NonNullable<MeshWorkQueueEntry['autoLaunch']>, 'updatedAt'>,
185
781
  ): MeshWorkQueueEntry | null {
186
782
  return withQueueLock(meshId, () => {
187
- const queue = readQueue(meshId);
188
- const idx = queue.findIndex(q => q.id === taskId);
189
- if (idx === -1) return null;
783
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
784
+ if (!entry) return null;
190
785
  const now = new Date().toISOString();
191
- queue[idx].autoLaunch = { ...autoLaunch, updatedAt: now };
192
- queue[idx].updatedAt = now;
193
- writeQueue(meshId, queue);
194
- return queue[idx];
786
+ entry.autoLaunch = { ...autoLaunch, updatedAt: now };
787
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
788
+ return entry;
195
789
  });
196
790
  }
197
791
 
@@ -201,19 +795,19 @@ export function recordTaskAutoLaunch(
201
795
  export function cancelTask(
202
796
  meshId: string,
203
797
  taskId: string,
204
- opts?: { reason?: string },
798
+ opts?: { reason?: string } & MeshQueueMutationOptions,
205
799
  ): MeshWorkQueueEntry | null {
800
+ requireMeshHostQueueOwner(opts);
206
801
  return withQueueLock(meshId, () => {
207
- const queue = readQueue(meshId);
208
- const idx = queue.findIndex(q => q.id === taskId);
209
- if (idx === -1) return null;
802
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
803
+ if (!entry) return null;
210
804
  const now = new Date().toISOString();
211
- queue[idx].status = 'cancelled';
212
- queue[idx].updatedAt = now;
213
- queue[idx].cancelledAt = now;
214
- if (opts?.reason) queue[idx].cancelReason = opts.reason;
215
- writeQueue(meshId, queue);
216
- return queue[idx];
805
+ entry.status = 'cancelled';
806
+ entry.cancelledAt = now;
807
+ if (opts?.reason) entry.cancelReason = opts.reason;
808
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
809
+ propagateDependencyFailure(meshId, taskId);
810
+ return entry;
217
811
  });
218
812
  }
219
813
 
@@ -221,6 +815,11 @@ export function cancelTask(
221
815
  * Return a queue task to pending for retry. By default, dead session targeting
222
816
  * and assigned ownership are cleared so stale assignments do not strand again.
223
817
  */
818
+ export type RequeueResult =
819
+ | { status: 'requeued'; entry: MeshWorkQueueEntry }
820
+ | { status: 'failed_max_retries'; entry: MeshWorkQueueEntry; maxRetries: number; requeueCount: number }
821
+ | { status: 'not_found' };
822
+
224
823
  export function requeueTask(
225
824
  meshId: string,
226
825
  taskId: string,
@@ -230,15 +829,34 @@ export function requeueTask(
230
829
  targetSessionId?: string;
231
830
  clearTargetNode?: boolean;
232
831
  clearTargetSession?: boolean;
233
- },
832
+ /**
833
+ * Override the retry cap for this call. Use only for explicit operator actions.
834
+ * If true, the task is requeued even when requeueCount >= maxRetries.
835
+ */
836
+ force?: boolean;
837
+ /** Per-task retry cap override. Falls back to mesh policy maxTaskRetries (default 1). */
838
+ maxRetries?: number;
839
+ } & MeshQueueMutationOptions,
234
840
  ): MeshWorkQueueEntry | null {
841
+ requireMeshHostQueueOwner(opts);
235
842
  return withQueueLock(meshId, () => {
236
- const queue = readQueue(meshId);
237
- const idx = queue.findIndex(q => q.id === taskId);
238
- if (idx === -1) return null;
239
- const entry = queue[idx];
240
- const now = new Date().toISOString();
843
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
844
+ if (!entry) return null;
845
+ const currentCount = entry.requeueCount || 0;
846
+ const maxRetries = opts?.maxRetries ?? entry.maxRetries ?? 1;
847
+ if (!opts?.force && currentCount >= maxRetries) {
848
+ // Auto-fail: cap exceeded without explicit force override.
849
+ entry.status = 'failed';
850
+ entry.cancelReason = `max_retries_exceeded: requeued ${currentCount} time(s), limit is ${maxRetries}`;
851
+ entry.updatedAt = new Date().toISOString();
852
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
853
+ propagateDependencyFailure(meshId, taskId);
854
+ return entry;
855
+ }
241
856
  entry.status = 'pending';
857
+ // Operator requeue clears a dependency-failure block — the operator is
858
+ // explicitly overriding the held-back state.
859
+ delete entry.blockedReason;
242
860
  delete entry.assignedNodeId;
243
861
  delete entry.assignedSessionId;
244
862
  delete entry.cancelledAt;
@@ -247,11 +865,10 @@ export function requeueTask(
247
865
  if (typeof opts?.targetNodeId === 'string') entry.targetNodeId = opts.targetNodeId;
248
866
  if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
249
867
  if (typeof opts?.targetSessionId === 'string') entry.targetSessionId = opts.targetSessionId;
250
- entry.updatedAt = now;
251
- entry.requeuedAt = now;
252
- entry.requeueCount = (entry.requeueCount || 0) + 1;
868
+ entry.requeuedAt = new Date().toISOString();
869
+ entry.requeueCount = currentCount + 1;
253
870
  if (opts?.reason) entry.requeueReason = opts.reason;
254
- writeQueue(meshId, queue);
871
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
255
872
  return entry;
256
873
  });
257
874
  }
@@ -266,25 +883,42 @@ export function updateSessionTaskStatus(
266
883
  opts?: { occurredAt?: string },
267
884
  ): MeshWorkQueueEntry | null {
268
885
  return withQueueLock(meshId, () => {
269
- const queue = readQueue(meshId);
270
- const occurredAtTime = opts?.occurredAt ? new Date(opts.occurredAt).getTime() : Number.NaN;
271
- const hasOccurredAt = Number.isFinite(occurredAtTime);
272
- let bestIdx = -1;
273
- let bestTime = 0;
274
- for (let i = queue.length - 1; i >= 0; i--) {
275
- if (queue[i].assignedSessionId !== sessionId || queue[i].status !== 'assigned') continue;
276
- const time = new Date(queue[i].dispatchTimestamp || queue[i].updatedAt).getTime();
277
- if (hasOccurredAt && Number.isFinite(time) && time > occurredAtTime) continue;
278
- if (time > bestTime) { bestTime = time; bestIdx = i; }
279
- }
280
- if (bestIdx === -1) return null;
281
- queue[bestIdx].status = status;
282
- queue[bestIdx].updatedAt = new Date().toISOString();
283
- writeQueue(meshId, queue);
284
- return queue[bestIdx];
886
+ const occurredAtIso = opts?.occurredAt ? new Date(opts.occurredAt).toISOString() : undefined;
887
+ const entry = MeshRuntimeStore.getInstance().findAssignedBySession(meshId, sessionId, occurredAtIso);
888
+ if (!entry) return null;
889
+ entry.status = status;
890
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
891
+ if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, entry.id);
892
+ return entry;
285
893
  });
286
894
  }
287
895
 
896
+ /**
897
+ * M1-3: true when at least one pending task is waiting on the given task.
898
+ * Used by the completion event path to decide whether to wake the queue.
899
+ */
900
+ export function hasPendingDependents(meshId: string, taskId: string): boolean {
901
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId, ['pending'])
902
+ .some(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(taskId));
903
+ }
904
+
905
+ /**
906
+ * M1-4: view-time dependency state for a task — unmet dependency ids and
907
+ * whether the task is currently claimable from a dependency standpoint.
908
+ * Not stored (truth stays in task statuses).
909
+ */
910
+ export function describeTaskDependencyState(
911
+ entry: Pick<MeshWorkQueueEntry, 'dependsOn' | 'blockedReason'>,
912
+ statusById: Map<string, MeshTaskStatus | string>,
913
+ ): { waitingOn: string[]; dependenciesSatisfied: boolean } {
914
+ const deps = Array.isArray(entry.dependsOn) ? entry.dependsOn : [];
915
+ const waitingOn = deps.filter(depId => statusById.get(depId) !== 'completed');
916
+ return {
917
+ waitingOn,
918
+ dependenciesSatisfied: waitingOn.length === 0 && !entry.blockedReason,
919
+ };
920
+ }
921
+
288
922
  export interface MeshWorkQueueStats {
289
923
  total: number;
290
924
  active: number;
@@ -310,14 +944,16 @@ export interface MeshWorkQueueStats {
310
944
  * Return aggregate queue statistics for the given mesh.
311
945
  */
312
946
  export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
313
- const queue = readQueue(meshId);
314
- const pending = queue.filter(q => q.status === 'pending').length;
315
- const assigned = queue.filter(q => q.status === 'assigned').length;
316
- const completed = queue.filter(q => q.status === 'completed').length;
317
- const failed = queue.filter(q => q.status === 'failed').length;
318
- const cancelled = queue.filter(q => q.status === 'cancelled').length;
947
+ const rows = MeshRuntimeStore.getInstance().getQueueStatsByStatus(meshId);
948
+ const counts: Record<string, number> = {};
949
+ for (const r of rows) counts[r.status] = r.count;
950
+ const pending = counts['pending'] ?? 0;
951
+ const assigned = counts['assigned'] ?? 0;
952
+ const completed = counts['completed'] ?? 0;
953
+ const failed = counts['failed'] ?? 0;
954
+ const cancelled = counts['cancelled'] ?? 0;
319
955
  return {
320
- total: queue.length,
956
+ total: pending + assigned + completed + failed + cancelled,
321
957
  active: pending + assigned,
322
958
  historical: completed + failed + cancelled,
323
959
  pending,
@@ -325,22 +961,119 @@ export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
325
961
  completed,
326
962
  failed,
327
963
  cancelled,
328
- activeCounts: {
329
- pending,
330
- assigned,
331
- },
332
- historicalCounts: {
333
- completed,
334
- failed,
335
- cancelled,
336
- },
337
- activeAssignments: queue
338
- .filter(q => q.status === 'assigned')
339
- .map(q => ({
340
- id: q.id,
341
- nodeId: q.assignedNodeId,
342
- sessionId: q.assignedSessionId,
343
- message: q.message,
344
- })),
964
+ activeCounts: { pending, assigned },
965
+ historicalCounts: { completed, failed, cancelled },
966
+ activeAssignments: MeshRuntimeStore.getInstance().getActiveAssignmentDetails(meshId),
345
967
  };
346
968
  }
969
+
970
+ export function __replaceMeshQueueForTests(meshId: string, queue: MeshWorkQueueEntry[]): void {
971
+ MeshRuntimeStore.getInstance().transaction(() => {
972
+ MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
973
+ });
974
+ }
975
+
976
+ export function __clearMeshQueueForTests(meshId: string): void {
977
+ MeshRuntimeStore.getInstance().deleteQueue(meshId);
978
+ }
979
+
980
+ export function __clearDirectDispatchesForTests(meshId: string): void {
981
+ MeshRuntimeStore.getInstance().deleteDirectDispatches(meshId);
982
+ }
983
+
984
+ export function __resetMeshRuntimeStoreForTests(): void {
985
+ MeshRuntimeStore.resetForTests();
986
+ }
987
+
988
+ // ── Direct Dispatch Tracking ─────────────────────────────────────────────────
989
+ // Persists direct (non-queue) task dispatches so buildMeshActiveWork can read
990
+ // active work from MeshRuntimeStore instead of scanning ledger JSONL entries.
991
+
992
+ export type DirectDispatchRecord = ReturnType<MeshRuntimeStore['getActiveDirectDispatches']>[number];
993
+
994
+ export function insertDirectDispatch(
995
+ meshId: string,
996
+ data: {
997
+ taskId: string;
998
+ nodeId?: string;
999
+ sessionId?: string;
1000
+ providerType?: string;
1001
+ message: string;
1002
+ taskMode?: string;
1003
+ via: string;
1004
+ dispatchedToIdleSession?: boolean;
1005
+ dispatchedAt: string;
1006
+ },
1007
+ ): void {
1008
+ try {
1009
+ MeshRuntimeStore.getInstance().insertDirectDispatch({ ...data, meshId });
1010
+ } catch (e: any) {
1011
+ process.stderr.write(`[adhdev-mesh] insertDirectDispatch failed for task ${data.taskId}: ${e?.message || e}\n`);
1012
+ }
1013
+ }
1014
+
1015
+ export function getActiveDirectDispatches(meshId: string): DirectDispatchRecord[] {
1016
+ try {
1017
+ return MeshRuntimeStore.getInstance().getActiveDirectDispatches(meshId);
1018
+ } catch {
1019
+ return [];
1020
+ }
1021
+ }
1022
+
1023
+ export function updateDirectDispatchStatus(
1024
+ meshId: string,
1025
+ sessionId: string,
1026
+ status: 'acked' | 'completed' | 'failed' | 'stale',
1027
+ ): void {
1028
+ try {
1029
+ MeshRuntimeStore.getInstance().updateDirectDispatchStatus(meshId, sessionId, status);
1030
+ } catch { /* best-effort */ }
1031
+ }
1032
+
1033
+ export function cleanupTerminalDirectDispatches(olderThanMs = 7 * 24 * 60 * 60_000): void {
1034
+ try {
1035
+ MeshRuntimeStore.getInstance().cleanupTerminalDirectDispatches(olderThanMs);
1036
+ } catch { /* best-effort */ }
1037
+ }
1038
+
1039
+ export function markStaleDirectDispatches(meshId: string, olderThanMs = 60 * 60_000): void {
1040
+ try {
1041
+ MeshRuntimeStore.getInstance().markStaleDirectDispatches(meshId, olderThanMs);
1042
+ } catch { /* best-effort */ }
1043
+ }
1044
+
1045
+ /**
1046
+ * Delete specific direct dispatch rows by taskId. Returns the number of rows deleted.
1047
+ * Used by the staleDirect prune path to evict orphaned/terminal dispatch records from the
1048
+ * active staleDirect surface while leaving the append-only mesh ledger (audit history) intact.
1049
+ */
1050
+ export function deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
1051
+ try {
1052
+ return MeshRuntimeStore.getInstance().deleteDirectDispatchesByTaskId(meshId, taskIds);
1053
+ } catch {
1054
+ return 0;
1055
+ }
1056
+ }
1057
+
1058
+ export type MeshToolCallRateResult = { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null };
1059
+
1060
+ /**
1061
+ * Record a coordinator tool call and return a rate-limit advisory when the
1062
+ * call rate for that tool exceeds the allowed threshold.
1063
+ *
1064
+ * Defaults: 10-second sliding window, max 5 calls before advisory is raised.
1065
+ * Returns { rateLimitExceeded: false } on any store error so callers are not blocked.
1066
+ */
1067
+ export function recordMeshToolCall(opts: {
1068
+ meshId: string;
1069
+ tool: string;
1070
+ sessionId?: string | null;
1071
+ windowMs?: number;
1072
+ maxCalls?: number;
1073
+ }): MeshToolCallRateResult {
1074
+ try {
1075
+ return MeshRuntimeStore.getInstance().recordMeshToolCall(opts);
1076
+ } catch {
1077
+ return { rateLimitExceeded: false, callsInWindow: 0, advisory: null };
1078
+ }
1079
+ }