@adhdev/daemon-core 0.9.82-rc.29 → 0.9.82-rc.290

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 (281) 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 +23 -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 +106 -63
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-shared.d.ts +38 -0
  13. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  14. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  15. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  16. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  17. package/dist/commands/cli-manager.d.ts +2 -1
  18. package/dist/commands/handler.d.ts +110 -0
  19. package/dist/commands/mesh-coordinator.d.ts +85 -1
  20. package/dist/commands/router.d.ts +160 -1
  21. package/dist/config/chat-history.d.ts +9 -0
  22. package/dist/config/config.d.ts +5 -0
  23. package/dist/config/mesh-config.d.ts +72 -1
  24. package/dist/git/git-commands.d.ts +9 -1
  25. package/dist/git/git-diff.d.ts +6 -0
  26. package/dist/git/git-status.d.ts +7 -0
  27. package/dist/git/git-types.d.ts +2 -50
  28. package/dist/index.d.ts +51 -12
  29. package/dist/index.js +34510 -12948
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.mjs +38172 -16711
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/installer.d.ts +1 -4
  34. package/dist/ipc/local-ipc-server.d.ts +91 -0
  35. package/dist/launch.d.ts +1 -1
  36. package/dist/logging/async-batch-writer.d.ts +10 -0
  37. package/dist/mesh/contracts.d.ts +164 -0
  38. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  39. package/dist/mesh/coordinator-registry.d.ts +59 -0
  40. package/dist/mesh/mesh-active-work.d.ts +108 -0
  41. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  42. package/dist/mesh/mesh-events-coordinator.d.ts +133 -0
  43. package/dist/mesh/mesh-events-pending.d.ts +45 -0
  44. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  45. package/dist/mesh/mesh-events-utils.d.ts +47 -0
  46. package/dist/mesh/mesh-events.d.ts +6 -49
  47. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  48. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  49. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  50. package/dist/mesh/mesh-ledger.d.ts +77 -1
  51. package/dist/mesh/mesh-missions.d.ts +68 -0
  52. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  53. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  54. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  55. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  56. package/dist/mesh/mesh-routing.d.ts +70 -0
  57. package/dist/mesh/mesh-runtime-store.d.ts +345 -0
  58. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  59. package/dist/mesh/mesh-work-queue.d.ts +166 -5
  60. package/dist/mesh/preview-freshness.d.ts +18 -0
  61. package/dist/mesh/refine-config.d.ts +215 -0
  62. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  63. package/dist/providers/acp-provider-instance.d.ts +2 -0
  64. package/dist/providers/approval-utils.d.ts +13 -0
  65. package/dist/providers/cli-provider-instance.d.ts +61 -3
  66. package/dist/providers/contracts.d.ts +130 -6
  67. package/dist/providers/external-sources.d.ts +71 -0
  68. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  69. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  70. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  71. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  72. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  73. package/dist/providers/native-history/index.d.ts +13 -0
  74. package/dist/providers/provider-instance-manager.d.ts +13 -0
  75. package/dist/providers/provider-instance.d.ts +13 -1
  76. package/dist/providers/provider-loader.d.ts +26 -4
  77. package/dist/providers/provider-trust.d.ts +31 -0
  78. package/dist/providers/read-chat-contract.d.ts +29 -0
  79. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  80. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  81. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  82. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  83. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  84. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  85. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  86. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  87. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  88. package/dist/providers/sdk/v1/index.d.ts +30 -0
  89. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  90. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  91. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  92. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  93. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  94. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  95. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  96. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  97. package/dist/providers/spec/adapter.d.ts +59 -0
  98. package/dist/providers/spec/cli-adapter.d.ts +140 -0
  99. package/dist/providers/spec/evaluator.d.ts +23 -0
  100. package/dist/providers/spec/fsm-driver.d.ts +278 -0
  101. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  102. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  103. package/dist/providers/spec/fsm-types.d.ts +128 -0
  104. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  105. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  106. package/dist/providers/spec/route.d.ts +4 -0
  107. package/dist/providers/spec/types.d.ts +144 -0
  108. package/dist/providers/transcript-v2.d.ts +176 -0
  109. package/dist/providers/types/interactive-prompt.d.ts +48 -0
  110. package/dist/repo-mesh-types.d.ts +148 -13
  111. package/dist/sessions/registry.d.ts +6 -0
  112. package/dist/shared-types-extra.d.ts +2 -4
  113. package/dist/shared-types.d.ts +42 -1
  114. package/dist/status/normalize.d.ts +1 -1
  115. package/dist/status/normalize.js +1 -0
  116. package/dist/status/normalize.js.map +1 -1
  117. package/dist/status/normalize.mjs +1 -0
  118. package/dist/status/normalize.mjs.map +1 -1
  119. package/dist/status/reporter.d.ts +2 -0
  120. package/dist/status/snapshot.d.ts +1 -0
  121. package/dist/types.d.ts +5 -0
  122. package/package.json +7 -3
  123. package/src/agent-stream/poller.ts +2 -3
  124. package/src/boot/daemon-lifecycle.ts +55 -12
  125. package/src/boot/process-hardening.ts +89 -0
  126. package/src/build-info.ts +73 -0
  127. package/src/chat/source-machine.ts +534 -0
  128. package/src/chat/source-resolver.ts +0 -0
  129. package/src/chat/subscription-updates.ts +20 -1
  130. package/src/cli-adapter-types.d.ts +1 -0
  131. package/src/cli-adapter-types.ts +22 -2
  132. package/src/cli-adapters/cli-script-runner.ts +421 -0
  133. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  134. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  135. package/src/cli-adapters/provider-cli-adapter.ts +674 -1139
  136. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  137. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  138. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  139. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  140. package/src/cli-adapters/provider-cli-shared.ts +68 -11
  141. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  142. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  143. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  144. package/src/cli-adapters/terminal-screen.ts +16 -81
  145. package/src/commands/chat-commands.ts +1813 -60
  146. package/src/commands/cli-manager.ts +286 -14
  147. package/src/commands/handler.ts +809 -2
  148. package/src/commands/mesh-coordinator.ts +332 -122
  149. package/src/commands/router.ts +5721 -546
  150. package/src/config/chat-history.ts +229 -24
  151. package/src/config/config.ts +12 -0
  152. package/src/config/mesh-config.ts +303 -3
  153. package/src/config/recent-activity.ts +8 -2
  154. package/src/daemon/dev-auto-implement.ts +3 -2
  155. package/src/daemon/dev-cli-debug.ts +10 -1
  156. package/src/detection/ide-detector.ts +26 -16
  157. package/src/git/git-commands.ts +42 -12
  158. package/src/git/git-diff.ts +53 -0
  159. package/src/git/git-status.ts +198 -7
  160. package/src/git/git-types.ts +14 -62
  161. package/src/git/git-worktree.ts +8 -1
  162. package/src/index.ts +131 -11
  163. package/src/installer.d.ts +1 -1
  164. package/src/installer.ts +8 -6
  165. package/src/ipc/local-ipc-server.ts +278 -0
  166. package/src/launch.d.ts +1 -1
  167. package/src/launch.ts +37 -28
  168. package/src/logging/async-batch-writer.ts +55 -0
  169. package/src/logging/logger.ts +2 -1
  170. package/src/mesh/contracts.ts +329 -0
  171. package/src/mesh/coordinator-prompt.ts +219 -31
  172. package/src/mesh/coordinator-registry.ts +121 -0
  173. package/src/mesh/mesh-active-work.ts +468 -0
  174. package/src/mesh/mesh-delivery-policy.ts +315 -0
  175. package/src/mesh/mesh-events-coordinator.ts +1679 -0
  176. package/src/mesh/mesh-events-pending.ts +508 -0
  177. package/src/mesh/mesh-events-stale.ts +283 -0
  178. package/src/mesh/mesh-events-utils.ts +254 -0
  179. package/src/mesh/mesh-events.ts +30 -1035
  180. package/src/mesh/mesh-fast-forward.ts +839 -0
  181. package/src/mesh/mesh-host-ownership.ts +73 -0
  182. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  183. package/src/mesh/mesh-ledger.ts +589 -102
  184. package/src/mesh/mesh-missions.ts +172 -0
  185. package/src/mesh/mesh-reconcile-loop.ts +411 -0
  186. package/src/mesh/mesh-refine-batch.ts +197 -0
  187. package/src/mesh/mesh-refine-status.ts +231 -0
  188. package/src/mesh/mesh-review-inbox.ts +307 -0
  189. package/src/mesh/mesh-routing.ts +275 -0
  190. package/src/mesh/mesh-runtime-store.ts +1399 -0
  191. package/src/mesh/mesh-task-stats.ts +154 -0
  192. package/src/mesh/mesh-work-queue.ts +586 -145
  193. package/src/mesh/preview-freshness.ts +118 -0
  194. package/src/mesh/refine-config.ts +403 -0
  195. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  196. package/src/providers/acp-provider-instance.ts +15 -1
  197. package/src/providers/approval-utils.d.ts +4 -0
  198. package/src/providers/approval-utils.ts +47 -5
  199. package/src/providers/chat-message-normalization.ts +4 -11
  200. package/src/providers/cli-provider-instance.ts +920 -81
  201. package/src/providers/contracts.d.ts +55 -0
  202. package/src/providers/contracts.ts +141 -6
  203. package/src/providers/external-sources.ts +218 -0
  204. package/src/providers/ide-provider-instance.ts +19 -5
  205. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  206. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  207. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  208. package/src/providers/native-history/dispatcher.ts +340 -0
  209. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  210. package/src/providers/native-history/index.ts +30 -0
  211. package/src/providers/provider-instance-manager.ts +30 -0
  212. package/src/providers/provider-instance.ts +10 -1
  213. package/src/providers/provider-loader.ts +584 -50
  214. package/src/providers/provider-schema.ts +87 -14
  215. package/src/providers/provider-trust.ts +114 -0
  216. package/src/providers/read-chat-contract.ts +76 -16
  217. package/src/providers/sdk/README.md +49 -0
  218. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  219. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  220. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  221. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  222. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  223. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  224. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  225. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  226. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  227. package/src/providers/sdk/v1/index.ts +152 -0
  228. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  229. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  230. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  231. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  232. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  233. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  234. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  235. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  236. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  237. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  238. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  239. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  240. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  241. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  242. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  243. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  244. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  245. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  246. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  247. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  248. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  249. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  250. package/src/providers/sdk/v1/validators/index.ts +19 -0
  251. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  252. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  253. package/src/providers/spec/adapter.ts +155 -0
  254. package/src/providers/spec/cli-adapter.ts +730 -0
  255. package/src/providers/spec/evaluator.ts +345 -0
  256. package/src/providers/spec/fsm-driver.ts +875 -0
  257. package/src/providers/spec/fsm-evaluator.ts +255 -0
  258. package/src/providers/spec/fsm-loader.ts +112 -0
  259. package/src/providers/spec/fsm-types.ts +222 -0
  260. package/src/providers/spec/native-history-executor.ts +943 -0
  261. package/src/providers/spec/pre-launch-trust.ts +104 -0
  262. package/src/providers/spec/route.ts +51 -0
  263. package/src/providers/spec/types.ts +189 -0
  264. package/src/providers/transcript-v2.ts +567 -0
  265. package/src/providers/types/interactive-prompt.ts +488 -0
  266. package/src/providers/version-archive.ts +38 -20
  267. package/src/repo-mesh-types.ts +177 -13
  268. package/src/sessions/registry.ts +6 -0
  269. package/src/shared-types-extra.ts +2 -4
  270. package/src/shared-types.ts +45 -1
  271. package/src/status/builders.ts +26 -6
  272. package/src/status/normalize.ts +2 -0
  273. package/src/status/reporter.ts +15 -0
  274. package/src/status/snapshot.ts +84 -25
  275. package/src/system/host-memory.ts +29 -12
  276. package/src/types.ts +5 -0
  277. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  278. package/dist/mesh/mesh-sync.d.ts +0 -53
  279. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  280. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  281. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,172 @@
1
+ /**
2
+ * M3: Mission persistence (minimal form).
3
+ *
4
+ * A mission is a persistent record of a multi-task goal so the plan lives in
5
+ * the system rather than in the coordinator LLM's context. Coordinator
6
+ * sessions can die or compact; a new coordinator reads the mission back at
7
+ * launch and continues.
8
+ *
9
+ * Explicit non-goals (see docs/mesh-product-plan-v2.md Phase M3): this is not
10
+ * a workflow engine and there is no automatic takeover daemon. Progress is
11
+ * never stored — it is derived from queue task statuses (mission_id) at
12
+ * query time.
13
+ */
14
+
15
+ import { randomUUID } from 'crypto';
16
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
17
+ import { getQueue } from './mesh-work-queue.js';
18
+
19
+ export type MeshMissionStatus = 'active' | 'paused' | 'completed' | 'abandoned';
20
+
21
+ export const MESH_MISSION_STATUSES: MeshMissionStatus[] = ['active', 'paused', 'completed', 'abandoned'];
22
+
23
+ export interface MeshMissionRecord {
24
+ id: string;
25
+ meshId: string;
26
+ title: string;
27
+ goal: string;
28
+ status: MeshMissionStatus;
29
+ createdAt: string;
30
+ updatedAt: string;
31
+ }
32
+
33
+ export interface MeshMissionTaskAggregate {
34
+ total: number;
35
+ pending: number;
36
+ assigned: number;
37
+ completed: number;
38
+ failed: number;
39
+ cancelled: number;
40
+ /** Pending tasks held back by a dependency failure (blockedReason set). */
41
+ blocked: number;
42
+ /** Latest updatedAt across the mission's tasks, or null with no tasks. */
43
+ lastActivityAt: string | null;
44
+ }
45
+
46
+ export interface MeshMissionSummary extends MeshMissionRecord {
47
+ tasks: MeshMissionTaskAggregate;
48
+ }
49
+
50
+ function normalizeMissionStatus(value: unknown): MeshMissionStatus {
51
+ return MESH_MISSION_STATUSES.includes(value as MeshMissionStatus)
52
+ ? value as MeshMissionStatus
53
+ : 'active';
54
+ }
55
+
56
+ export function upsertMeshMission(meshId: string, input: {
57
+ id?: string;
58
+ title: string;
59
+ goal?: string;
60
+ status?: string;
61
+ }): MeshMissionRecord {
62
+ const title = typeof input.title === 'string' ? input.title.trim() : '';
63
+ if (!title) throw new Error('mission_title_required: a mission needs a non-empty title');
64
+ if (input.status !== undefined && !MESH_MISSION_STATUSES.includes(input.status as MeshMissionStatus)) {
65
+ throw new Error(`invalid_mission_status: '${input.status}' (valid: ${MESH_MISSION_STATUSES.join(', ')})`);
66
+ }
67
+ const id = typeof input.id === 'string' && input.id.trim() ? input.id.trim() : randomUUID();
68
+ const store = MeshRuntimeStore.getInstance();
69
+ const existing = store.getMission(meshId, id);
70
+ const record = {
71
+ id,
72
+ meshId,
73
+ title,
74
+ goal: typeof input.goal === 'string' ? input.goal : existing?.goal ?? '',
75
+ status: normalizeMissionStatus(input.status ?? existing?.status),
76
+ };
77
+ store.upsertMission(record);
78
+ const saved = store.getMission(meshId, id)!;
79
+ return { ...saved, status: normalizeMissionStatus(saved.status) };
80
+ }
81
+
82
+ export function getMeshMissions(meshId: string, statuses?: MeshMissionStatus[]): MeshMissionRecord[] {
83
+ return MeshRuntimeStore.getInstance().getMissions(meshId, statuses)
84
+ .map(m => ({ ...m, status: normalizeMissionStatus(m.status) }));
85
+ }
86
+
87
+ export function getMeshMission(meshId: string, missionId: string): MeshMissionRecord | null {
88
+ const record = MeshRuntimeStore.getInstance().getMission(meshId, missionId);
89
+ return record ? { ...record, status: normalizeMissionStatus(record.status) } : null;
90
+ }
91
+
92
+ /** Aggregate task statuses for a mission at query time (no stored progress). */
93
+ export function summarizeMissionTasks(meshId: string, missionId: string): MeshMissionTaskAggregate {
94
+ const tasks = getQueue(meshId).filter(task => task.missionId === missionId);
95
+ const aggregate: MeshMissionTaskAggregate = {
96
+ total: tasks.length,
97
+ pending: 0,
98
+ assigned: 0,
99
+ completed: 0,
100
+ failed: 0,
101
+ cancelled: 0,
102
+ blocked: 0,
103
+ lastActivityAt: null,
104
+ };
105
+ for (const task of tasks) {
106
+ if (task.status === 'pending') aggregate.pending += 1;
107
+ else if (task.status === 'assigned') aggregate.assigned += 1;
108
+ else if (task.status === 'completed') aggregate.completed += 1;
109
+ else if (task.status === 'failed') aggregate.failed += 1;
110
+ else if (task.status === 'cancelled') aggregate.cancelled += 1;
111
+ if (task.status === 'pending' && task.blockedReason) aggregate.blocked += 1;
112
+ if (task.updatedAt && (!aggregate.lastActivityAt || task.updatedAt > aggregate.lastActivityAt)) {
113
+ aggregate.lastActivityAt = task.updatedAt;
114
+ }
115
+ }
116
+ return aggregate;
117
+ }
118
+
119
+ export function summarizeMeshMission(meshId: string, mission: MeshMissionRecord): MeshMissionSummary {
120
+ return { ...mission, tasks: summarizeMissionTasks(meshId, mission.id) };
121
+ }
122
+
123
+ /** Active mission summaries for mesh_status / coordinator prompt injection. */
124
+ export function getActiveMeshMissionSummaries(meshId: string): MeshMissionSummary[] {
125
+ return getMeshMissions(meshId, ['active']).map(mission => summarizeMeshMission(meshId, mission));
126
+ }
127
+
128
+ /**
129
+ * Mission summaries for the mesh_status dashboard surface: every active/paused
130
+ * mission plus a capped, newest-first slice of completed/abandoned history so
131
+ * the dashboard can render a collapsible "history" section without unbounded
132
+ * payload growth. Returned newest-first within each group (active/paused first,
133
+ * then history), so the frontend can split on `status` directly.
134
+ */
135
+ export function getMeshStatusMissionSummaries(
136
+ meshId: string,
137
+ options?: { historyLimit?: number },
138
+ ): MeshMissionSummary[] {
139
+ const historyLimit = Math.max(0, options?.historyLimit ?? 10);
140
+ const all = getMeshMissions(meshId);
141
+ const live = all.filter(m => m.status === 'active' || m.status === 'paused');
142
+ const history = all
143
+ .filter(m => m.status === 'completed' || m.status === 'abandoned')
144
+ .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))
145
+ .slice(0, historyLimit);
146
+ return [...live, ...history].map(mission => summarizeMeshMission(meshId, mission));
147
+ }
148
+
149
+ /**
150
+ * M3-3: render active missions as a prompt section for {{mission}}.
151
+ * Empty string when no active mission — the prompt stays byte-identical to
152
+ * the pre-M3 output in that case (regression guarantee).
153
+ */
154
+ export function buildMissionPromptSection(meshId: string): string {
155
+ const summaries = getActiveMeshMissionSummaries(meshId);
156
+ if (summaries.length === 0) return '';
157
+ const lines: string[] = ['## Active Mission' + (summaries.length > 1 ? 's' : '')];
158
+ for (const mission of summaries) {
159
+ const t = mission.tasks;
160
+ lines.push(
161
+ `- **${mission.title}** (id: \`${mission.id}\`)`
162
+ + (mission.goal ? `\n Goal: ${mission.goal}` : '')
163
+ + `\n Tasks: ${t.total} total — ${t.pending} pending (${t.blocked} blocked), ${t.assigned} assigned, ${t.completed} completed, ${t.failed} failed, ${t.cancelled} cancelled`
164
+ + (t.lastActivityAt ? `\n Last activity: ${t.lastActivityAt}` : ''),
165
+ );
166
+ }
167
+ lines.push(
168
+ 'Continue this mission from its current task state. Do not re-enqueue tasks that already exist — check mesh_view_queue first. '
169
+ + 'Update the mission with mesh_mission_upsert when its goal changes or it reaches a terminal state (completed/abandoned).',
170
+ );
171
+ return lines.join('\n');
172
+ }
@@ -0,0 +1,411 @@
1
+ // ---------------------------------------------------------------------------
2
+ // mesh-reconcile-loop — periodic queue → live coordinator reconciliation
3
+ // ---------------------------------------------------------------------------
4
+ // Single-model replacement for the old event-based "spontaneous forward" paths
5
+ // (remote P2P mesh_forward_event dispatch + live-CLI PTY fire-and-forget inject).
6
+ // Those pushed events at the moment a worker transitioned state, and silently
7
+ // dropped on the network (P2P) or when the coordinator was generating.
8
+ //
9
+ // The reliable backbone has always been the pending-events queue (SQLite +
10
+ // JSONL): every mesh coordinator event is persisted there before anything else
11
+ // (see injectMeshSystemMessage). What was missing was an *active* drainer that
12
+ // runs on a schedule rather than only when the coordinator (an LLM) happens to
13
+ // call a mesh tool.
14
+ //
15
+ // This loop is that drainer. On a fixed interval it:
16
+ // 1. Finds live CLI coordinator sessions on THIS daemon (meshCoordinatorFor
17
+ // stamp). For each mesh, drains the local queue scoped to this daemon and
18
+ // injects pending events into the coordinator. When a coordinator is idle it
19
+ // receives every queued event. When ONLY generating coordinators exist (the
20
+ // common case while the coordinator is blocked awaiting a worker result), the
21
+ // loop force-drains ONLY the force-inject events (completion / approval / stop /
22
+ // refine·bootstrap terminal) and force-writes them into the generating PTY —
23
+ // the same busy-bypass send-guard escape the live-CLI inject used to use.
24
+ // Non-force progress events stay queued for the next idle tick (injecting them
25
+ // mid-generation would be noise). This is what makes a coordinator parked in
26
+ // `generating` while awaiting a worker's completion actually receive it.
27
+ // 2. In cloud mode (dispatchMeshCommand present), pulls each remote worker
28
+ // node daemon's queue over P2P (get_pending_mesh_events) and re-injects via
29
+ // handleMeshForwardEvent — the same pull the MCP drainCoordinatorPendingEvents
30
+ // already does, now driven by the daemon timer instead of an LLM tool call.
31
+ //
32
+ // IMPORTANT — limits of this loop:
33
+ // - It only delivers to *live CLI coordinator instances* on this daemon. A
34
+ // pure stdio MCP coordinator (an LLM with no live CLI session to inject
35
+ // into) has no inject target here; that case stays pull-driven — the LLM
36
+ // drains the queue when it calls mesh_status / mesh_read_chat. We do NOT try
37
+ // to "wake" an LLM from the daemon; that is structurally impossible over a
38
+ // stdio request/response transport. See docs/refactoring/2026-06-15-mesh-event-to-queue-polling.md §4.7.
39
+ // - Queue persistence (queuePendingMeshCoordinatorEvent) and the SQLite
40
+ // drained=1 idempotency are the trust backbone and are untouched by this loop.
41
+ // ---------------------------------------------------------------------------
42
+
43
+ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
44
+ import type { LocalMeshEntry } from '../repo-mesh-types.js';
45
+ import { loadConfig } from '../config/config.js';
46
+ import { listMeshes } from '../config/mesh-config.js';
47
+ import { LOG } from '../logging/logger.js';
48
+ import { drainPendingMeshCoordinatorEvents } from './mesh-events-pending.js';
49
+ import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
50
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
51
+ import { handleMeshForwardEvent, shouldForceInjectMeshEvent, MESH_FORCE_INJECT_EVENTS } from './mesh-events-coordinator.js';
52
+ import { readNonEmptyString } from './mesh-events-utils.js';
53
+
54
+ // Default reconcile cadence. approval/completion notifications to a live CLI
55
+ // coordinator land within at most one interval. Overridable via env for tuning.
56
+ const DEFAULT_RECONCILE_INTERVAL_MS = 4_000;
57
+
58
+ function resolveReconcileIntervalMs(): number {
59
+ const raw = readNonEmptyString(process.env.MESH_RECONCILE_INTERVAL_MS);
60
+ if (raw) {
61
+ const parsed = Number.parseInt(raw, 10);
62
+ if (Number.isFinite(parsed) && parsed >= 1_000 && parsed <= 60_000) return parsed;
63
+ }
64
+ return DEFAULT_RECONCILE_INTERVAL_MS;
65
+ }
66
+
67
+ interface LiveCoordinator {
68
+ meshId: string;
69
+ instance: ReturnType<DaemonComponents['instanceManager']['getInstance']>;
70
+ idle: boolean;
71
+ }
72
+
73
+ // The set of coordinator-daemon ids THIS daemon answers to when draining the
74
+ // pending-events queue. A unicast completion event is stamped with the worker's
75
+ // meshCoordinatorDaemonId, which can be either:
76
+ // - the daemon's canonical status id (`standalone_<machineId>` / `daemon_<machineId>`),
77
+ // stamped by the MCP layer via ctx.localDaemonId (= getStatus().status.instanceId), or
78
+ // - the bare machineId, stamped by the local queue-assignment path (loadConfig().machineId).
79
+ // Draining with only one of these silently misses events stamped with the other —
80
+ // the exact reason a generating coordinator never self-received local completions.
81
+ // We accept BOTH so the drain matches regardless of which path stamped the event.
82
+ function resolveCoordinatorDaemonIds(components: DaemonComponents): string[] {
83
+ const ids = new Set<string>();
84
+ const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
85
+ if (statusInstanceId) ids.add(statusInstanceId);
86
+ const machineId = readNonEmptyString(loadConfig().machineId);
87
+ if (machineId) ids.add(machineId);
88
+ return [...ids];
89
+ }
90
+
91
+ // Whether THIS daemon is the coordinator/host for a mesh — i.e. the daemon that
92
+ // owns coordinator ownership and must collect every worker node's completion
93
+ // events into its local queue. This is true regardless of whether a *live CLI*
94
+ // coordinator session currently exists: the coordinator is frequently a pure
95
+ // stdio MCP LLM (no live CLI session to inject into), and that LLM only sees the
96
+ // queue when it next calls a mesh tool. For it to see remote worker completions
97
+ // at all, the daemon must have already pulled them into the local queue on the
98
+ // timer — which is exactly what this predicate gates.
99
+ //
100
+ // Rule: this daemon hosts the mesh when meshHost.role is 'host' (the default for
101
+ // standalone-compat meshes with no host metadata) AND, when a hostDaemonId is
102
+ // pinned, it resolves to one of this daemon's ids. Member-only daemons return
103
+ // false — their own queue is pulled BY the host, not the other way around.
104
+ //
105
+ // `daemonIds` here is the EXPANDED self-identity set (runtime drain ids ∪ this
106
+ // daemon's mesh-config node id forms) — see resolveCoordinatorSelfIds. The
107
+ // pinned hostDaemonId is itself a config-form id and frequently does NOT equal a
108
+ // runtime id (bare machineId / status id), so gating on the runtime ids alone
109
+ // would wrongly classify the real host as a non-host and skip the remote pull
110
+ // entirely.
111
+ function daemonHostsMesh(mesh: LocalMeshEntry, daemonIds: string[]): boolean {
112
+ const host = mesh.meshHost;
113
+ // No metadata → default host (standalone compatibility, see createDefaultMeshHostMetadata).
114
+ if (!host) return true;
115
+ if (host.role && host.role !== 'host') return false;
116
+ const hostDaemonId = readNonEmptyString(host.hostDaemonId);
117
+ // Host role but no pinned hostDaemonId → treat as host (single-daemon / legacy).
118
+ if (!hostDaemonId) return true;
119
+ return daemonIds.includes(hostDaemonId);
120
+ }
121
+
122
+ // Resolve EVERY id-form this daemon answers to FOR A GIVEN MESH: the runtime drain
123
+ // ids (status id + bare machineId) unioned with this daemon's mesh-config identity
124
+ // forms — the self node's daemonId/machineId (the node whose daemonId/machineId
125
+ // matches a runtime id) and the pinned meshHost.hostDaemonId WHEN it is provably
126
+ // ours. This is the single source of truth for "is this id me?" across both the
127
+ // host gate and the remote pull filter; the worker's meshCoordinatorDaemonId stamp
128
+ // is guaranteed to be one of these forms (it comes from resolveCoordinatorDaemonId,
129
+ // which prefers the coordinator node's config-form daemonId over the runtime status id).
130
+ function resolveCoordinatorSelfIds(mesh: LocalMeshEntry, drainDaemonIds: string[]): string[] {
131
+ const ids = new Set<string>(drainDaemonIds);
132
+ // Expand with the config-form id(s) of the self node — the mesh node whose
133
+ // daemonId/machineId matches a runtime id. Its config-form daemonId is exactly
134
+ // what resolveCoordinatorNode()→resolveCoordinatorDaemonId() stamps onto a worker.
135
+ for (const node of mesh.nodes) {
136
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
137
+ const nodeMachineId = readNonEmptyString(node.machineId);
138
+ const isSelf = (nodeDaemonId && drainDaemonIds.includes(nodeDaemonId))
139
+ || (nodeMachineId && drainDaemonIds.includes(nodeMachineId));
140
+ if (!isSelf) continue;
141
+ if (nodeDaemonId) ids.add(nodeDaemonId);
142
+ if (nodeMachineId) ids.add(nodeMachineId);
143
+ }
144
+ // The pinned host id is included ONLY when it is provably one of THIS daemon's ids
145
+ // (it already matches a runtime id or a resolved self-node id). A hostDaemonId that
146
+ // names a DIFFERENT daemon must NOT be claimed — that would make a member-only
147
+ // daemon believe it is the host and pull queues it does not own. Having a node on
148
+ // this daemon does not make this daemon the host; daemonHostsMesh still honours a
149
+ // foreign hostDaemonId and rejects ownership.
150
+ const hostDaemonId = readNonEmptyString(mesh.meshHost?.hostDaemonId);
151
+ if (hostDaemonId && ids.has(hostDaemonId)) ids.add(hostDaemonId);
152
+ return [...ids];
153
+ }
154
+
155
+ // Find live CLI coordinator instances on THIS daemon, keyed by mesh.
156
+ function findLiveCoordinators(components: DaemonComponents): LiveCoordinator[] {
157
+ const out: LiveCoordinator[] = [];
158
+ for (const inst of components.instanceManager.getByCategory('cli')) {
159
+ const state = inst.getState();
160
+ const settings = state.settings && typeof state.settings === 'object'
161
+ ? state.settings as Record<string, unknown>
162
+ : {};
163
+ const meshId = readNonEmptyString(settings.meshCoordinatorFor);
164
+ if (!meshId) continue;
165
+ const status = readNonEmptyString(state.status).toLowerCase();
166
+ out.push({ meshId, instance: inst, idle: status === 'idle' });
167
+ }
168
+ return out;
169
+ }
170
+
171
+ // Inject a drained pending event into a live coordinator session. Force-inject
172
+ // events carry force:true so they bypass the busy send-guard and land in the PTY
173
+ // even while the coordinator is generating (see shouldForceInjectMeshEvent).
174
+ function injectPendingIntoCoordinator(
175
+ coordinator: LiveCoordinator['instance'],
176
+ pending: PendingMeshCoordinatorEvent,
177
+ ): void {
178
+ if (!coordinator || !pending.coordinatorMessage) return;
179
+ const force = shouldForceInjectMeshEvent(pending.event);
180
+ coordinator.onEvent('send_message', {
181
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
182
+ ...(force ? { force: true } : {}),
183
+ });
184
+ }
185
+
186
+ // One reconcile tick. Two independent phases:
187
+ //
188
+ // PHASE 1 — Remote queue pull (the fix for remote worktree completions never
189
+ // reaching an MCP/LLM coordinator). For EVERY mesh this daemon hosts/
190
+ // coordinates, pull each remote worker node's pending-events queue over P2P
191
+ // into THIS daemon's local queue. This runs *regardless of whether a live CLI
192
+ // coordinator exists* — the coordinator is usually a pure stdio MCP LLM with
193
+ // no live CLI session, and it can only observe a remote worker's completion
194
+ // once that event has been pulled into the local queue (which it then drains
195
+ // on its next mesh tool call). Previously this pull was gated behind a live
196
+ // CLI coordinator and so never ran for MCP/LLM coordinators — remote
197
+ // completions sat on the remote node's queue until the LLM happened to call
198
+ // mesh_read_chat, which triggered the MCP-side pull. The daemon now does it
199
+ // autonomously on the timer. Standalone (no dispatchMeshCommand) skips this
200
+ // phase entirely — there are no remote nodes to pull from.
201
+ //
202
+ // PHASE 2 — Live CLI inject. For each mesh that has a live CLI coordinator on
203
+ // THIS daemon, drain the local queue and inject pending events into the PTY.
204
+ // Unchanged from before.
205
+ export async function runMeshReconcileTick(components: DaemonComponents): Promise<void> {
206
+ const localDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
207
+ // The id-set used to scope the local queue drain (status id + machineId). See
208
+ // resolveCoordinatorDaemonIds — the status id is what the MCP layer stamps and
209
+ // is mandatory here for a generating CLI coordinator to self-receive completions.
210
+ const drainDaemonIds = resolveCoordinatorDaemonIds(components);
211
+ const dispatchMeshCommand = components.dispatchMeshCommand;
212
+ const store = (() => {
213
+ try { return MeshRuntimeStore.getInstance(); } catch { return undefined; }
214
+ })();
215
+
216
+ // ── PHASE 1: pull remote node queues for every mesh this daemon hosts ──────
217
+ // Cloud-only (dispatchMeshCommand present). Runs whether or not a live CLI
218
+ // coordinator exists — this is what lets an MCP/LLM coordinator ever see a
219
+ // remote worker's completion.
220
+ if (dispatchMeshCommand) {
221
+ for (const mesh of listMeshes()) {
222
+ // Expand to every id-form this daemon answers to for this mesh (runtime
223
+ // drain ids ∪ config-form node/host ids) and use it for BOTH the host gate
224
+ // and the remote pull filter, so a worker stamp in any form is recovered.
225
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
226
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
227
+ try {
228
+ await pullRemoteNodeQueues(components, mesh, localDaemonId, selfIds);
229
+ } catch (e: any) {
230
+ LOG.warn('MeshReconcile', `Remote node pull failed for mesh ${mesh.id}: ${e?.message || e}`);
231
+ }
232
+ }
233
+ }
234
+
235
+ // ── PHASE 2: inject into live CLI coordinators on this daemon ──────────────
236
+ const coordinators = findLiveCoordinators(components);
237
+ if (coordinators.length === 0) {
238
+ // No live CLI coordinator on this daemon — nothing to inject into.
239
+ // (MCP-only LLM coordinators drain the local queue via their own tool
240
+ // calls; PHASE 1 above has already populated it from remote nodes.)
241
+ return;
242
+ }
243
+
244
+ // Group coordinators by mesh; multiple coordinator instances for one mesh is
245
+ // unusual but supported (each gets the same drained events).
246
+ const byMesh = new Map<string, LiveCoordinator[]>();
247
+ for (const c of coordinators) {
248
+ const list = byMesh.get(c.meshId);
249
+ if (list) list.push(c);
250
+ else byMesh.set(c.meshId, [c]);
251
+ }
252
+
253
+ for (const [meshId, meshCoordinators] of byMesh) {
254
+ // Drain the local queue scoped to this coordinator daemon and inject.
255
+ // - If an idle coordinator exists, FULL-drain and deliver every event to it
256
+ // (it can receive non-force progress events without deadlocking).
257
+ // - If only GENERATING coordinators exist, force-drain ONLY the force-inject
258
+ // events (completion/approval/stop/refine·bootstrap terminal) and force-inject
259
+ // them so a coordinator parked in `generating` while awaiting that very event
260
+ // is not deadlocked. Non-force progress events stay queued for the next idle
261
+ // tick — injecting them would be noise mid-generation. Both drains mark the
262
+ // consumed rows drained=1 atomically, so the pull path can't re-deliver.
263
+ const idleCoordinators = meshCoordinators.filter(c => c.idle);
264
+ const generatingCoordinators = meshCoordinators.filter(c => !c.idle);
265
+ const targetCoordinators = idleCoordinators.length > 0 ? idleCoordinators : generatingCoordinators;
266
+ const forceOnly = idleCoordinators.length === 0;
267
+
268
+ // O(1) guard: skip the drain entirely when the queue is empty.
269
+ if (store) {
270
+ try {
271
+ if (store.pendingEventCount(meshId) === 0) continue;
272
+ } catch { /* fall through to drain */ }
273
+ }
274
+
275
+ let pendingEvents: PendingMeshCoordinatorEvent[] = [];
276
+ try {
277
+ pendingEvents = drainPendingMeshCoordinatorEvents(
278
+ meshId,
279
+ drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
280
+ forceOnly ? { onlyEvents: MESH_FORCE_INJECT_EVENTS } : undefined,
281
+ );
282
+ } catch (e: any) {
283
+ LOG.warn('MeshReconcile', `Drain failed for mesh ${meshId}: ${e?.message || e}`);
284
+ continue;
285
+ }
286
+ if (pendingEvents.length === 0) continue;
287
+
288
+ const mode = forceOnly ? 'force-drain → generating' : 'inject → idle';
289
+ LOG.info('MeshReconcile', `Reconcile ${mode}: ${pendingEvents.length} pending event(s) → ${targetCoordinators.length} coordinator(s) for mesh ${meshId}`);
290
+ for (const pending of pendingEvents) {
291
+ for (const c of targetCoordinators) {
292
+ injectPendingIntoCoordinator(c.instance, pending);
293
+ }
294
+ }
295
+ }
296
+ }
297
+
298
+ // Cloud-only: poll each remote worker node daemon for pending coordinator events
299
+ // and re-inject them locally via handleMeshForwardEvent (which re-queues +
300
+ // surfaces to the live coordinator on the next tick / immediately if idle).
301
+ //
302
+ // Scoping: the remote handler (get_pending_mesh_events) drains its queue filtered
303
+ // by coordinatorDaemonId — returning events targeted at that id OR unscoped, and
304
+ // leaving events targeted at a *different* coordinator. A remote worker stamps the
305
+ // coordinator id in one of SEVERAL forms (the canonical status id `standalone_`/
306
+ // `daemon_<machineId>` stamped by the MCP layer, the bare machineId stamped by the
307
+ // local queue path, OR — most commonly for remote launches — the coordinator mesh
308
+ // node's config-form `daemonId`, which resolveCoordinatorDaemonId prefers and which
309
+ // is NOT canonicalised). `candidateDaemonIds` is the already-expanded self-identity
310
+ // set (resolveCoordinatorSelfIds: runtime drain ids ∪ this daemon's mesh-config node/
311
+ // host id forms), so we pull ONCE PER candidate id and a completion stamped with any
312
+ // of them is recovered. The remote drain is atomic (drained=1), so issuing multiple
313
+ // pulls cannot double-deliver — the first pull that matches consumes the event; the
314
+ // rest see nothing. When no ids resolve we fall back to a single unscoped pull.
315
+ async function pullRemoteNodeQueues(
316
+ components: DaemonComponents,
317
+ mesh: LocalMeshEntry,
318
+ localDaemonId: string | undefined,
319
+ candidateDaemonIds: string[],
320
+ ): Promise<void> {
321
+ const dispatchMeshCommand = components.dispatchMeshCommand;
322
+ if (!dispatchMeshCommand) return;
323
+ const meshId = mesh.id;
324
+
325
+ // One args object per candidate coordinator-id form, or a single unscoped pull
326
+ // when none resolve.
327
+ const pulls: Array<Record<string, unknown>> = candidateDaemonIds.length > 0
328
+ ? candidateDaemonIds.map(id => ({ meshId, coordinatorDaemonId: id }))
329
+ : [{ meshId }];
330
+
331
+ for (const node of mesh.nodes) {
332
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
333
+ // Skip nodes without a daemon, and nodes on THIS daemon (their events are
334
+ // already in the local queue drained in PHASE 2). "This daemon" is matched
335
+ // against the full self-identity set (candidateDaemonIds), not just the bare
336
+ // localDaemonId — a self node can be registered under the config-form daemonId
337
+ // (`daemon_<machineId>`) which would NOT equal bare localDaemonId, and pulling
338
+ // from ourselves over P2P is both wasteful and a self-dispatch hazard.
339
+ if (!nodeDaemonId) continue;
340
+ if (localDaemonId && nodeDaemonId === localDaemonId) continue;
341
+ if (candidateDaemonIds.includes(nodeDaemonId)) continue;
342
+
343
+ for (const pendingEventArgs of pulls) {
344
+ let events: unknown;
345
+ try {
346
+ events = await dispatchMeshCommand(nodeDaemonId, 'get_pending_mesh_events', pendingEventArgs);
347
+ } catch {
348
+ // Remote pull is best-effort; the node may be offline. Retry next tick.
349
+ break; // node unreachable — don't bother with the other id form this tick.
350
+ }
351
+ const list = extractPendingEvents(events).filter(e => readNonEmptyString(e?.meshId) === meshId);
352
+ for (const event of list) {
353
+ const payload = buildForwardPayloadFromPending(event);
354
+ if (!payload.event || !payload.meshId) continue;
355
+ try {
356
+ handleMeshForwardEvent(components, payload);
357
+ } catch { /* best-effort re-inject */ }
358
+ }
359
+ }
360
+ }
361
+ }
362
+
363
+ function extractPendingEvents(raw: unknown): any[] {
364
+ if (Array.isArray(raw)) return raw;
365
+ if (raw && typeof raw === 'object') {
366
+ const events = (raw as Record<string, unknown>).events;
367
+ if (Array.isArray(events)) return events;
368
+ }
369
+ return [];
370
+ }
371
+
372
+ // Flatten a queued PendingMeshCoordinatorEvent into the flat payload shape
373
+ // handleMeshForwardEvent expects (mirrors the MCP buildMeshForwardPayloadFromPendingEvent).
374
+ function buildForwardPayloadFromPending(event: any): Record<string, unknown> {
375
+ const metadata = event?.metadataEvent && typeof event.metadataEvent === 'object'
376
+ ? event.metadataEvent as Record<string, unknown>
377
+ : {};
378
+ return {
379
+ event: readNonEmptyString(event?.event),
380
+ meshId: readNonEmptyString(event?.meshId),
381
+ nodeId: readNonEmptyString(event?.nodeId) || readNonEmptyString(metadata.meshNodeId),
382
+ workspace: readNonEmptyString(event?.workspace) || readNonEmptyString(metadata.workspace),
383
+ ...metadata,
384
+ };
385
+ }
386
+
387
+ interface ReconcileLoopHandle {
388
+ stop(): void;
389
+ }
390
+
391
+ // Start the periodic reconcile loop. Returns a handle with stop() for shutdown.
392
+ export function setupMeshReconcileLoop(components: DaemonComponents): ReconcileLoopHandle {
393
+ const intervalMs = resolveReconcileIntervalMs();
394
+ let running = false;
395
+ const timer = setInterval(() => {
396
+ if (running) return; // never overlap ticks
397
+ running = true;
398
+ void runMeshReconcileTick(components)
399
+ .catch((e: any) => LOG.warn('MeshReconcile', `Reconcile tick error: ${e?.message || e}`))
400
+ .finally(() => { running = false; });
401
+ }, intervalMs);
402
+ // Don't keep the process alive solely for this timer.
403
+ if (typeof timer.unref === 'function') timer.unref();
404
+ LOG.info('MeshReconcile', `Mesh reconcile loop started (interval ${intervalMs}ms)`);
405
+ return {
406
+ stop() {
407
+ clearInterval(timer);
408
+ LOG.info('MeshReconcile', 'Mesh reconcile loop stopped');
409
+ },
410
+ };
411
+ }