@adhdev/daemon-core 0.9.82-rc.16 → 0.9.82-rc.160

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 (182) hide show
  1. package/dist/boot/process-hardening.d.ts +50 -0
  2. package/dist/chat/source-machine.d.ts +166 -0
  3. package/dist/chat/source-resolver.d.ts +104 -0
  4. package/dist/chat/subscription-updates.d.ts +1 -0
  5. package/dist/cli-adapter-types.d.ts +5 -1
  6. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  7. package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
  8. package/dist/cli-adapters/provider-cli-adapter.d.ts +104 -63
  9. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  10. package/dist/cli-adapters/provider-cli-shared.d.ts +27 -0
  11. package/dist/commands/handler.d.ts +66 -0
  12. package/dist/commands/router.d.ts +22 -0
  13. package/dist/config/chat-history.d.ts +5 -0
  14. package/dist/config/config.d.ts +5 -0
  15. package/dist/config/mesh-config.d.ts +68 -1
  16. package/dist/git/git-commands.d.ts +5 -1
  17. package/dist/index.d.ts +20 -6
  18. package/dist/index.js +13154 -3031
  19. package/dist/index.js.map +1 -1
  20. package/dist/index.mjs +13100 -3023
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/installer.d.ts +1 -4
  23. package/dist/ipc/local-ipc-server.d.ts +91 -0
  24. package/dist/launch.d.ts +1 -1
  25. package/dist/logging/async-batch-writer.d.ts +10 -0
  26. package/dist/mesh/beads-db.d.ts +72 -0
  27. package/dist/mesh/contracts.d.ts +164 -0
  28. package/dist/mesh/coordinator-registry.d.ts +25 -0
  29. package/dist/mesh/mesh-active-work.d.ts +90 -0
  30. package/dist/mesh/mesh-events.d.ts +77 -5
  31. package/dist/mesh/mesh-fast-forward.d.ts +39 -0
  32. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  33. package/dist/mesh/mesh-ledger.d.ts +58 -1
  34. package/dist/mesh/mesh-refine-status.d.ts +26 -0
  35. package/dist/mesh/mesh-work-queue.d.ts +44 -5
  36. package/dist/mesh/preview-freshness.d.ts +18 -0
  37. package/dist/mesh/refine-config.d.ts +193 -0
  38. package/dist/mesh/worktree-bootstrap-config.d.ts +113 -0
  39. package/dist/providers/approval-utils.d.ts +9 -0
  40. package/dist/providers/cli-provider-instance.d.ts +6 -1
  41. package/dist/providers/contracts.d.ts +50 -5
  42. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  43. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  44. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  45. package/dist/providers/native-history/index.d.ts +11 -0
  46. package/dist/providers/provider-loader.d.ts +19 -1
  47. package/dist/providers/read-chat-contract.d.ts +29 -0
  48. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  49. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  50. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  51. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +64 -0
  52. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  53. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  54. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  55. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  56. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  57. package/dist/providers/sdk/v1/index.d.ts +30 -0
  58. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  59. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  60. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  61. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  62. package/dist/providers/sdk/v1/types/common/index.d.ts +169 -0
  63. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  64. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  65. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  66. package/dist/providers/transcript-v2.d.ts +176 -0
  67. package/dist/repo-mesh-types.d.ts +67 -0
  68. package/dist/shared-types.d.ts +12 -0
  69. package/dist/status/reporter.d.ts +2 -0
  70. package/dist/status/snapshot.d.ts +1 -0
  71. package/dist/types.d.ts +5 -0
  72. package/package.json +6 -2
  73. package/src/boot/daemon-lifecycle.ts +17 -10
  74. package/src/boot/process-hardening.ts +89 -0
  75. package/src/chat/source-machine.ts +534 -0
  76. package/src/chat/source-resolver.ts +0 -0
  77. package/src/chat/subscription-updates.ts +14 -1
  78. package/src/cli-adapter-types.d.ts +1 -0
  79. package/src/cli-adapter-types.ts +3 -1
  80. package/src/cli-adapters/cli-script-runner.ts +421 -0
  81. package/src/cli-adapters/cli-state-engine.ts +1086 -0
  82. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  83. package/src/cli-adapters/provider-cli-adapter.ts +664 -1137
  84. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  85. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  86. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  87. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  88. package/src/cli-adapters/provider-cli-shared.ts +57 -11
  89. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +17 -1
  90. package/src/cli-adapters/terminal-backends/xterm-backend.ts +8 -1
  91. package/src/commands/chat-commands.ts +1451 -52
  92. package/src/commands/cli-manager.ts +184 -3
  93. package/src/commands/handler.ts +547 -2
  94. package/src/commands/mesh-coordinator.ts +13 -143
  95. package/src/commands/router.ts +3285 -428
  96. package/src/config/chat-history.ts +79 -24
  97. package/src/config/config.ts +12 -0
  98. package/src/config/mesh-config.ts +249 -2
  99. package/src/config/recent-activity.ts +8 -2
  100. package/src/daemon/dev-cli-debug.ts +10 -1
  101. package/src/detection/ide-detector.ts +26 -16
  102. package/src/git/git-commands.ts +17 -5
  103. package/src/git/git-worktree.ts +8 -1
  104. package/src/index.ts +72 -5
  105. package/src/installer.d.ts +1 -1
  106. package/src/installer.ts +8 -6
  107. package/src/ipc/local-ipc-server.ts +278 -0
  108. package/src/launch.d.ts +1 -1
  109. package/src/launch.ts +37 -28
  110. package/src/logging/async-batch-writer.ts +55 -0
  111. package/src/logging/logger.ts +2 -1
  112. package/src/mesh/beads-db.ts +479 -0
  113. package/src/mesh/contracts.ts +329 -0
  114. package/src/mesh/coordinator-prompt.ts +40 -22
  115. package/src/mesh/coordinator-registry.ts +75 -0
  116. package/src/mesh/mesh-active-work.ts +437 -0
  117. package/src/mesh/mesh-events.ts +820 -61
  118. package/src/mesh/mesh-fast-forward.ts +430 -0
  119. package/src/mesh/mesh-host-ownership.ts +73 -0
  120. package/src/mesh/mesh-ledger.ts +457 -104
  121. package/src/mesh/mesh-refine-status.ts +144 -0
  122. package/src/mesh/mesh-work-queue.ts +216 -158
  123. package/src/mesh/preview-freshness.ts +118 -0
  124. package/src/mesh/refine-config.ts +366 -0
  125. package/src/mesh/worktree-bootstrap-config.ts +247 -0
  126. package/src/providers/approval-utils.ts +39 -5
  127. package/src/providers/chat-message-normalization.ts +4 -11
  128. package/src/providers/cli-provider-instance.ts +380 -44
  129. package/src/providers/contracts.ts +52 -5
  130. package/src/providers/ide-provider-instance.ts +17 -3
  131. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  132. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  133. package/src/providers/native-history/codex-cli-transcript.ts +419 -0
  134. package/src/providers/native-history/index.ts +23 -0
  135. package/src/providers/provider-loader.ts +294 -28
  136. package/src/providers/provider-schema.ts +31 -13
  137. package/src/providers/read-chat-contract.ts +76 -16
  138. package/src/providers/sdk/README.md +49 -0
  139. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  140. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  141. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  142. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +245 -0
  143. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  144. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  145. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  146. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  147. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  148. package/src/providers/sdk/v1/index.ts +152 -0
  149. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  150. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  151. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  152. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +444 -0
  153. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  154. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  155. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  156. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  157. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  158. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  159. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  160. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  161. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +119 -0
  162. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  163. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  164. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  165. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  166. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  167. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  168. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  169. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  170. package/src/providers/sdk/v1/types/common/index.ts +210 -0
  171. package/src/providers/sdk/v1/validators/index.ts +19 -0
  172. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  173. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  174. package/src/providers/transcript-v2.ts +567 -0
  175. package/src/providers/version-archive.ts +38 -20
  176. package/src/repo-mesh-types.ts +77 -0
  177. package/src/shared-types.ts +9 -0
  178. package/src/status/builders.ts +23 -6
  179. package/src/status/reporter.ts +15 -0
  180. package/src/status/snapshot.ts +35 -11
  181. package/src/system/host-memory.ts +29 -12
  182. package/src/types.ts +5 -0
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Mesh contract v2 — first-class identity, scopes, and protocol version.
3
+ *
4
+ * Replaces the implicit conventions that grew across mesh-events.ts,
5
+ * mesh-work-queue.ts, mesh-ledger.ts, and mesh-tools.ts where the same
6
+ * concept (a coordinator, a session, a task status) appeared in different
7
+ * shapes per file. The audit found:
8
+ *
9
+ * - PendingMeshCoordinatorEvent had no targetCoordinatorDaemonId. All
10
+ * events were broadcast to every coordinator that drained them. Two
11
+ * coordinators sharing a mesh would each receive every event,
12
+ * leading to duplicate completion handling and missed targeting.
13
+ * - drainPendingMeshCoordinatorEvents accepted only meshId. The caller's
14
+ * coordinator identity was never available, so per-coordinator
15
+ * routing was impossible by construction.
16
+ * - Session identifier keys diverged across stores: targetSessionId /
17
+ * assignedSessionId / instanceId / runtimeSessionId / providerSessionId.
18
+ * resolveEventSessionId() tried four fallbacks per call.
19
+ * - No protocol version on the JSONL ledger or BeadsDB. Schema
20
+ * evolutions had no guard rail.
21
+ * - mesh_reconcile_ledger existed as a routine recovery tool, not as
22
+ * an incident-response escape hatch. That itself signals the routing
23
+ * layer cannot be trusted.
24
+ *
25
+ * This module introduces the types; the actual wiring lands in B2 (data
26
+ * model + 3-way transactional store), B3 (MCP layer enforcement), and B4
27
+ * (frontend consumption). B1 is intentionally non-breaking — it adds the
28
+ * types and leaves runtime behaviour unchanged.
29
+ */
30
+
31
+ /** Provider type identifier (e.g. 'claude-cli', 'codex-cli', 'roo-code').
32
+ * Free-form string; no shared enum exists in daemon-core yet. */
33
+ type ProviderType = string;
34
+
35
+ // ─── Protocol version ────────────────────────────────────────────────────
36
+
37
+ export const MESH_PROTOCOL_VERSION_V1 = '1.0' as const;
38
+ export const MESH_PROTOCOL_VERSION_V2 = '2.0' as const;
39
+
40
+ export type MeshProtocolVersion =
41
+ | typeof MESH_PROTOCOL_VERSION_V1
42
+ | typeof MESH_PROTOCOL_VERSION_V2;
43
+
44
+ export const SUPPORTED_MESH_PROTOCOL_VERSIONS: readonly MeshProtocolVersion[] = [
45
+ MESH_PROTOCOL_VERSION_V1,
46
+ MESH_PROTOCOL_VERSION_V2,
47
+ ] as const;
48
+
49
+ export function isSupportedMeshProtocolVersion(value: unknown): value is MeshProtocolVersion {
50
+ return typeof value === 'string'
51
+ && (SUPPORTED_MESH_PROTOCOL_VERSIONS as readonly string[]).includes(value);
52
+ }
53
+
54
+ // ─── Coordinator identity ────────────────────────────────────────────────
55
+
56
+ /**
57
+ * Identity of a mesh coordinator. Required (non-optional) on every dispatch
58
+ * and drain operation in v2 — opaque/missing identity is the audit's
59
+ * smoking gun for routing failures and is structurally banned by the v2
60
+ * types.
61
+ *
62
+ * - daemonId: the machineId of the daemon hosting the coordinator. Stable
63
+ * across coordinator restarts on the same machine.
64
+ * - coordinatorRunId: a UUID generated when the coordinator process starts.
65
+ * Stable for the coordinator's lifetime, fresh on restart. Required so
66
+ * two coordinators on the same daemon (one CLI, one MCP) can be told
67
+ * apart without conflating their drains.
68
+ * - sessionId: optional CLI coordinator session identifier (instanceId).
69
+ * Present when the coordinator is itself a CLI session, absent for
70
+ * pure MCP coordinators.
71
+ */
72
+ export interface CoordinatorIdentity {
73
+ readonly daemonId: string;
74
+ readonly coordinatorRunId: string;
75
+ readonly sessionId?: string;
76
+ }
77
+
78
+ export function coordinatorIdentityEquals(a: CoordinatorIdentity, b: CoordinatorIdentity): boolean {
79
+ return a.daemonId === b.daemonId
80
+ && a.coordinatorRunId === b.coordinatorRunId
81
+ && (a.sessionId ?? '') === (b.sessionId ?? '');
82
+ }
83
+
84
+ export function coordinatorIdentityKey(identity: CoordinatorIdentity): string {
85
+ // Stable string form for map keys and ledger payloads. Avoids the
86
+ // {a:b, c:d} JSON.stringify ordering trap by enforcing field order.
87
+ return `${identity.daemonId}|${identity.coordinatorRunId}|${identity.sessionId ?? ''}`;
88
+ }
89
+
90
+ // ─── Session handle ──────────────────────────────────────────────────────
91
+
92
+ /**
93
+ * Unified mesh session identifier. v1 referred to "the session" with five
94
+ * different field names depending on which store you were reading; v2
95
+ * collapses them into one explicit handle that carries every disambiguator
96
+ * a consumer might need.
97
+ *
98
+ * - nodeId: the mesh node this session belongs to (FK into mesh node table).
99
+ * - sessionId: provider-instance identifier (the runtime session id).
100
+ * - providerType: which provider category/type the session runs (e.g.
101
+ * 'claude-cli', 'codex-cli', 'roo-code').
102
+ * - coordinatorDaemonId: which coordinator dispatched the work that
103
+ * spawned this session. Used for completion event routing.
104
+ * - assignedAt: ms epoch when the session was bound to its current task.
105
+ */
106
+ export interface MeshSessionHandle {
107
+ readonly nodeId: string;
108
+ readonly sessionId: string;
109
+ readonly providerType: ProviderType;
110
+ readonly coordinatorDaemonId: string;
111
+ readonly assignedAt: number;
112
+ }
113
+
114
+ export function meshSessionHandleKey(handle: MeshSessionHandle): string {
115
+ return `${handle.nodeId}|${handle.sessionId}`;
116
+ }
117
+
118
+ // ─── Task status (canonical enum) ────────────────────────────────────────
119
+
120
+ /**
121
+ * Single canonical task status enum. v1 had at least three overlapping
122
+ * sets (queue / ledger / direct-dispatch). v2 consumers import from here.
123
+ */
124
+ export const MESH_TASK_STATUSES = [
125
+ 'pending',
126
+ 'assigned',
127
+ 'in_progress',
128
+ 'completed',
129
+ 'failed',
130
+ 'cancelled',
131
+ ] as const;
132
+ export type MeshTaskStatus = typeof MESH_TASK_STATUSES[number];
133
+
134
+ export function isMeshTaskStatus(value: unknown): value is MeshTaskStatus {
135
+ return typeof value === 'string'
136
+ && (MESH_TASK_STATUSES as readonly string[]).includes(value);
137
+ }
138
+
139
+ // ─── Event scope ─────────────────────────────────────────────────────────
140
+
141
+ /**
142
+ * Explicit scope for pending coordinator events. v1 had no scope: every
143
+ * event was broadcast to every drainer. v2 forces producers to declare
144
+ * intent.
145
+ *
146
+ * - 'unicast': delivered to exactly one coordinator (intendedFor). Other
147
+ * coordinators' drains skip it.
148
+ * - 'broadcast': delivered to every coordinator on the mesh. Used for
149
+ * system-wide signals (e.g. mesh-wide policy changes). The v1 default
150
+ * becomes explicit here so audit tools can flag unintended broadcasts.
151
+ * - 'system': delivered to the daemon-level handler, not coordinators.
152
+ * Reserved for infrastructure events that no coordinator should see
153
+ * (e.g. ledger reconciliation outcomes).
154
+ */
155
+ export const MESH_EVENT_SCOPES = ['unicast', 'broadcast', 'system'] as const;
156
+ export type MeshEventScope = typeof MESH_EVENT_SCOPES[number];
157
+
158
+ export function isMeshEventScope(value: unknown): value is MeshEventScope {
159
+ return typeof value === 'string'
160
+ && (MESH_EVENT_SCOPES as readonly string[]).includes(value);
161
+ }
162
+
163
+ // ─── Pending coordinator event v2 ────────────────────────────────────────
164
+
165
+ /**
166
+ * v2 shape of a pending coordinator event. Strict supersets of the v1
167
+ * shape — every v1 field is preserved so existing readers do not break;
168
+ * v2 fields (scope, dispatchedBy, intendedFor, protocolVersion) are
169
+ * additive and consulted by v2-aware drainers only.
170
+ *
171
+ * Mixed v1/v2 events coexist during the rollout window. B2 fully cuts
172
+ * over once every coordinator drain is v2-aware.
173
+ */
174
+ export interface PendingMeshCoordinatorEventV2 {
175
+ // v1 fields (preserved exactly)
176
+ readonly event: string;
177
+ readonly meshId: string;
178
+ readonly nodeLabel: string;
179
+ readonly nodeId?: string;
180
+ readonly workspace?: string;
181
+ readonly metadataEvent: Record<string, unknown>;
182
+ readonly coordinatorMessage?: string;
183
+ readonly queuedAt: number;
184
+
185
+ // v2 additions
186
+ readonly protocolVersion: MeshProtocolVersion;
187
+ readonly scope: MeshEventScope;
188
+ readonly dispatchedBy: CoordinatorIdentity;
189
+ /**
190
+ * Required when scope === 'unicast', forbidden otherwise. Drainers MUST
191
+ * skip unicast events whose intendedFor does not equal their own identity.
192
+ */
193
+ readonly intendedFor?: CoordinatorIdentity;
194
+ }
195
+
196
+ // ─── Ledger entry v2 ─────────────────────────────────────────────────────
197
+
198
+ /**
199
+ * v2 ledger entry additions. The originatingCoordinator field is the
200
+ * source of truth that lets completion events route back to the
201
+ * coordinator that dispatched the task. v1's "worker settings carried it
202
+ * if it happened to be set" approach is replaced.
203
+ */
204
+ export interface MeshLedgerOriginatingCoordinatorV2 {
205
+ readonly originatingCoordinator: CoordinatorIdentity;
206
+ readonly protocolVersion: MeshProtocolVersion;
207
+ }
208
+
209
+ // ─── Validation primitives ───────────────────────────────────────────────
210
+
211
+ export class MeshContractViolationError extends Error {
212
+ readonly violationPath: string;
213
+ readonly protocolVersion: MeshProtocolVersion;
214
+ constructor(
215
+ protocolVersion: MeshProtocolVersion,
216
+ violationPath: string,
217
+ detail: string,
218
+ ) {
219
+ super(`mesh contract ${protocolVersion} violation at ${violationPath}: ${detail}`);
220
+ this.name = 'MeshContractViolationError';
221
+ this.violationPath = violationPath;
222
+ this.protocolVersion = protocolVersion;
223
+ }
224
+ }
225
+
226
+ function isNonEmptyString(value: unknown): value is string {
227
+ return typeof value === 'string' && value.length > 0;
228
+ }
229
+
230
+ export function assertCoordinatorIdentity(raw: unknown, path: string): CoordinatorIdentity {
231
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
232
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path, 'must be an object');
233
+ }
234
+ const obj = raw as Record<string, unknown>;
235
+ if (!isNonEmptyString(obj.daemonId)) {
236
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.daemonId`, 'must be a non-empty string');
237
+ }
238
+ if (!isNonEmptyString(obj.coordinatorRunId)) {
239
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.coordinatorRunId`, 'must be a non-empty string');
240
+ }
241
+ const sessionId = obj.sessionId;
242
+ if (sessionId !== undefined && !isNonEmptyString(sessionId)) {
243
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.sessionId`, 'must be a non-empty string when provided');
244
+ }
245
+ return sessionId !== undefined
246
+ ? { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId, sessionId }
247
+ : { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId };
248
+ }
249
+
250
+ export function assertPendingMeshCoordinatorEventV2(raw: unknown, path = '$'): PendingMeshCoordinatorEventV2 {
251
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
252
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path, 'must be an object');
253
+ }
254
+ const obj = raw as Record<string, unknown>;
255
+ if (!isSupportedMeshProtocolVersion(obj.protocolVersion)) {
256
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.protocolVersion`, `must be one of ${SUPPORTED_MESH_PROTOCOL_VERSIONS.join(', ')}`);
257
+ }
258
+ if (!isMeshEventScope(obj.scope)) {
259
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.scope`, `must be one of ${MESH_EVENT_SCOPES.join(', ')}`);
260
+ }
261
+ if (!isNonEmptyString(obj.event)) {
262
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.event`, 'must be a non-empty string');
263
+ }
264
+ if (!isNonEmptyString(obj.meshId)) {
265
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.meshId`, 'must be a non-empty string');
266
+ }
267
+ const dispatchedBy = assertCoordinatorIdentity(obj.dispatchedBy, `${path}.dispatchedBy`);
268
+
269
+ if (obj.scope === 'unicast') {
270
+ if (!obj.intendedFor) {
271
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.intendedFor`, 'unicast scope requires intendedFor');
272
+ }
273
+ } else if (obj.intendedFor !== undefined) {
274
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.intendedFor`, 'only unicast scope may set intendedFor');
275
+ }
276
+ const intendedFor = obj.intendedFor
277
+ ? assertCoordinatorIdentity(obj.intendedFor, `${path}.intendedFor`)
278
+ : undefined;
279
+
280
+ const metadata = obj.metadataEvent && typeof obj.metadataEvent === 'object' && !Array.isArray(obj.metadataEvent)
281
+ ? (obj.metadataEvent as Record<string, unknown>)
282
+ : null;
283
+ if (!metadata) {
284
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.metadataEvent`, 'must be an object');
285
+ }
286
+ const queuedAt = typeof obj.queuedAt === 'number' && Number.isFinite(obj.queuedAt) ? obj.queuedAt : null;
287
+ if (queuedAt === null) {
288
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path}.queuedAt`, 'must be a finite number');
289
+ }
290
+
291
+ return {
292
+ event: obj.event,
293
+ meshId: obj.meshId,
294
+ nodeLabel: isNonEmptyString(obj.nodeLabel) ? obj.nodeLabel : '',
295
+ nodeId: typeof obj.nodeId === 'string' ? obj.nodeId : undefined,
296
+ workspace: typeof obj.workspace === 'string' ? obj.workspace : undefined,
297
+ metadataEvent: metadata,
298
+ coordinatorMessage: typeof obj.coordinatorMessage === 'string' ? obj.coordinatorMessage : undefined,
299
+ queuedAt,
300
+ protocolVersion: obj.protocolVersion,
301
+ scope: obj.scope,
302
+ dispatchedBy,
303
+ ...(intendedFor ? { intendedFor } : {}),
304
+ };
305
+ }
306
+
307
+ // ─── Routing helper ──────────────────────────────────────────────────────
308
+
309
+ /**
310
+ * Decide whether a v2 pending event should be delivered to the given drainer.
311
+ * Centralised so every drain implementation uses the same rule.
312
+ *
313
+ * - 'broadcast': always delivered.
314
+ * - 'system': never delivered to coordinators (system handler only).
315
+ * - 'unicast': delivered iff intendedFor matches drainer identity.
316
+ *
317
+ * v1 events (no scope / no protocolVersion) are treated as broadcast for
318
+ * backward compatibility during rollout; B3 tightens this so v1 events
319
+ * are quarantined to a dedicated drain endpoint instead.
320
+ */
321
+ export function shouldDeliverPendingEventToCoordinator(
322
+ event: PendingMeshCoordinatorEventV2,
323
+ drainer: CoordinatorIdentity,
324
+ ): boolean {
325
+ if (event.scope === 'system') return false;
326
+ if (event.scope === 'broadcast') return true;
327
+ if (!event.intendedFor) return false;
328
+ return coordinatorIdentityEquals(event.intendedFor, drainer);
329
+ }
@@ -76,7 +76,12 @@ Repository: \`${mesh.repoIdentity}\`${mesh.defaultBranch ? `\nDefault branch: \`
76
76
  // ─── Section Builders ───────────────────────────
77
77
 
78
78
  function buildNodeStatusSection(nodes: RepoMeshNodeStatus[]): string {
79
- const lines = ['## Current Node Status', ''];
79
+ const lines = [
80
+ '## Current Node Status',
81
+ '',
82
+ 'Node labels are display context, not aliases. Use exact `nodeId` values in mesh tool calls; do not invent shorthand names such as M1/M2 unless they are explicitly configured labels.',
83
+ '',
84
+ ];
80
85
  for (const n of nodes) {
81
86
  const healthIcon = n.health === 'online' ? '🟢' :
82
87
  n.health === 'dirty' ? '🟡' :
@@ -85,21 +90,33 @@ function buildNodeStatusSection(nodes: RepoMeshNodeStatus[]): string {
85
90
  ? `sessions: ${n.activeSessions.join(', ')}`
86
91
  : 'no active sessions';
87
92
  const branch = n.git?.branch ? `branch: \`${n.git.branch}\`` : '';
88
- lines.push(`- ${healthIcon} **${n.machineLabel}** (${n.nodeId})`);
89
- lines.push(` workspace: \`${n.workspace}\` | ${branch} | ${sessions}`);
93
+ const context = [
94
+ n.daemonId ? `daemon: \`${n.daemonId}\`` : '',
95
+ n.providers?.length ? `providers: ${n.providers.join(', ')}` : '',
96
+ ].filter(Boolean).join(' | ');
97
+ lines.push(`- ${healthIcon} **${n.machineLabel}** (nodeId: \`${n.nodeId}\`)`);
98
+ lines.push(` workspace: \`${n.workspace}\`${context ? ` | ${context}` : ''} | ${branch} | ${sessions}`);
90
99
  if (n.error) lines.push(` ⚠️ ${n.error}`);
91
100
  }
92
101
  return lines.join('\n');
93
102
  }
94
103
 
95
104
  function buildNodeConfigSection(mesh: LocalMeshEntry): string {
96
- const lines = ['## Configured Nodes', ''];
105
+ const lines = [
106
+ '## Configured Nodes',
107
+ '',
108
+ 'Node labels are display context, not aliases. Use exact `nodeId` values in mesh tool calls; do not invent shorthand names such as M1/M2 unless they are explicitly configured labels.',
109
+ '',
110
+ ];
97
111
  for (const n of mesh.nodes) {
98
112
  const labels: string[] = [];
99
113
  if (n.isLocalWorktree) labels.push('worktree');
100
114
  if (n.policy?.readOnly) labels.push('read-only');
101
115
  const suffix = labels.length ? ` [${labels.join(', ')}]` : '';
102
- lines.push(`- **${n.workspace}** (${n.id})${suffix}`);
116
+ const explicitMachineLabel = typeof (n as any).machineLabel === 'string' ? (n as any).machineLabel : '';
117
+ const explicitLabel = explicitMachineLabel ? ` label: **${explicitMachineLabel}** |` : '';
118
+ const providerPriority = n.policy?.providerPriority?.length ? ` | providers: ${n.policy.providerPriority.join(', ')}` : '';
119
+ lines.push(`- ${explicitLabel} nodeId: \`${n.id}\` | workspace: \`${n.workspace}\`${n.daemonId ? ` | daemon: \`${n.daemonId}\`` : ''}${providerPriority}${suffix}`);
103
120
  }
104
121
  lines.push('', '_Use `mesh_status` to probe live health before delegating work._');
105
122
  return lines.join('\n');
@@ -110,6 +127,9 @@ function buildPolicySection(policy: RepoMeshPolicy): string {
110
127
  if (policy.requirePreTaskCheckpoint) rules.push('- Create a git checkpoint **before** starting each task');
111
128
  if (policy.requirePostTaskCheckpoint) rules.push('- Create a git checkpoint **after** each task completes');
112
129
  if (policy.requireApprovalForPush) rules.push('- **Ask for user approval** before pushing to remote');
130
+ if (policy.allowAutoPublishSubmoduleMainCommits) {
131
+ rules.push('- Refinery may auto-publish unreachable submodule gitlink commits to submodule origin/main with non-force pushes after validation and patch-equivalence pass');
132
+ }
113
133
  if (policy.requireApprovalForDestructiveGit) rules.push('- **Ask for user approval** before destructive git operations (force push, reset, etc.)');
114
134
 
115
135
  const dirtyBehavior = {
@@ -140,6 +160,7 @@ const TOOLS_SECTION = `## Available Tools
140
160
  | \`mesh_read_debug\` | Collect a daemon-side chat/parser debug bundle for a session |
141
161
  | \`mesh_task_history\` | Read the task ledger — dispatches, completions, failures. Use to understand what has been done before deciding next steps |
142
162
  | \`mesh_git_status\` | Check git status on a specific node |
163
+ | \`mesh_fast_forward_node\` | Safely dry-run or explicitly execute an obvious clean fast-forward without launching an agent session |
143
164
  | \`mesh_checkpoint\` | Create a git checkpoint on a node |
144
165
  | \`mesh_approve\` | Approve/reject a pending agent action |
145
166
  | \`mesh_clone_node\` | Create a worktree node for isolated parallel branch work |
@@ -161,10 +182,10 @@ const WORKFLOW_SECTION = `## Orchestration Workflow
161
182
  c. **Targeted Tasks**: Use \`mesh_send_task\` only when you need to bypass the queue and force a specific node to execute a task immediately.
162
183
  d. For the first dispatch of a new task, provide a **complete, self-contained** instruction that includes all context the agent needs (file paths, line numbers, what to change, why). Do not send partial instructions expecting future follow-up.
163
184
  e. For a continuation of the same issue in an existing session, send a concise **delta instruction**: current verified state, the exact failed/blocked step, the newly approved action, and final reporting requirements. Do not resend the full original task or open a new chat solely to continue the same work; that wastes coordinator and worker context.
164
- 4. **Monitor** — Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Use \`mesh_view_queue\` to see the status of all pending, assigned, completed, and failed tasks. Do not call \`mesh_read_chat\` again within a few seconds for the same generating session. Use at most one compact \`mesh_read_chat\` check after a completion/approval signal. Handle approvals via \`mesh_approve\`.
185
+ 4. **Monitor** — Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Do **not** repeatedly call \`mesh_status\` or \`mesh_view_queue\` just to wait for assigned/generating work. After dispatching a direct or queued task, send one progress update with the task/session handle, then stop. Wait for \`pendingCoordinatorEvents\` or another completion/approval/status signal, an explicit user status request, or a real timeout/stall signal before reading status/chat/queue again. Use at most one compact \`mesh_read_chat\` check after a terminal signal. Handle approvals via \`mesh_approve\`.
165
186
  5. **Verify** — When a task reports completion or git work is visible, call \`mesh_git_status\` to verify changes were made.
166
187
  6. **Checkpoint** — Call \`mesh_checkpoint\` to save the work.
167
- 7. **Converge branches** — Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary and \`mesh_refine_node\` for clean worktree branches when safe. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
188
+ 7. **Converge branches** — Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary. For obvious clean branch catch-up (ahead 0, behind > 0, upstream fresh, no dirty/stash/submodule issues), use \`mesh_fast_forward_node\` dry-run first and execute only when explicitly safe/approved; this avoids consuming an agent session. Use \`mesh_refine_node\` for clean worktree branches when safe. Before/refine merging root commits that contain submodule gitlink changes, require each submodule commit to be reachable from the configured submodule remote main branch, not merely present on a feature ref or local checkout. If \`mesh_refine_node\` returns \`submodule_reachability_failed\` or publish-required evidence, keep the public convergence bucket as \`blocked_review\`; unless \`allowAutoPublishSubmoduleMainCommits\` is explicitly enabled and Refinery reports successful non-force publish plus post-publish verification, ask the user for explicit approval to push/publish the unreachable submodule commit(s) to submodule main, then rerun \`mesh_refine_node\`. Do not merge the root branch until the submodule commit(s) are reachable from submodule origin/main. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
168
189
  8. **Clean up** — Remove worktree nodes via \`mesh_remove_node\` after their work is merged or no longer needed.
169
190
  9. **Report** — Summarize what was done, what changed, any issues, and the branch convergence state.
170
191
 
@@ -188,19 +209,16 @@ function buildRulesSection(coordinatorCliType?: string): string {
188
209
 
189
210
  return `## Rules
190
211
 
191
- - **Minimize coordinator context.** The coordinator's job is routing, not implementing. Do not read source files, run commands, or analyze code directly delegate all of that to node agents. Your context should stay lean.
192
- - **Delegate analysis too.** If you need to understand a bug or explore the codebase, send that investigation as a task to the queue or a node. Do not do it yourself.
193
- - **Respect explicit provider requests.** If the user names an agent/provider, pass the matching provider type to \`mesh_launch_session\`: Hermes \`hermes-cli\`, Claude Code/Claude \`claude-cli\`, Codex \`codex-cli\`, Gemini \`gemini-cli\`. Never substitute \`claude-cli\` just because the coordinator itself is Claude Code.
194
- - **Front-load new task messages.** When calling \`mesh_enqueue_task\` or \`mesh_send_task\` for a new task, include everything the agent needs: what files to touch, what the problem is, what the fix should look like. The agent won't ask follow-up questions.
195
- - **Avoid context-wasting restarts.** For follow-up, retry, commit/push, preview, or cleanup work on the same issue, prefer the existing idle session and send only the delta from its last verified state. Start a fresh chat/session only for genuinely independent work, explicit provider/user request, unsafe transcript contamination, or required branch/worktree isolation.
196
- - **Don't inspect code.** Treat delegated agent summaries as self-reports, not verification. Verify side effects via \`mesh_git_status\` (including related repo freshness when configured), not by reading source files.
197
- - **Don't over-parallelize.** Start with 1-2 concurrent tasks. Scale up if they succeed. Never launch a duplicate session or second worker solely because \`mesh_read_chat\` has no final assistant message while the delegated session is still showing tool/terminal activity.
198
- - **Handle failures with context.** If a task fails, check \`mesh_task_history\` first to see if this task was attempted before and how it failed. Read the chat to understand why, then decide: retry on the same node, reassign to a different node, or escalate to the user.
199
- - **Check history before starting.** At the beginning of a coordination session, call \`mesh_task_history\` to understand what was previously delegated and its outcomes. This prevents duplicate work and informs recovery decisions.
200
- - **Keep the user informed.** Report progress after each delegation round one or two sentences, not a narration.
201
- - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
202
- - **Never fabricate tool results.** Always call the actual tool; never pretend you did.
203
- - **Clean up worktree nodes.** After a worktree task completes and its changes are merged or checkpointed, call \`mesh_remove_node\` to free resources.
204
- - **Do not strand completed branches.** A checkpointed or clean feature/worktree branch is not done by itself. Merge/refine it to the mesh default branch, or explicitly report one of \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\` with the next action.
205
- - **Name worktree branches meaningfully.** Use descriptive names like \`feat/auth-refactor\` or \`fix/build-123\`.${coordinatorNote}`;
212
+ - **Route, don't implement.** Delegate all code reading, analysis, and execution to node agents. Never read source files or run commands in the coordinatorkeep context lean.
213
+ - **Front-load task messages.** Include everything the agent needs (files, problem, expected fix) in \`mesh_enqueue_task\` / \`mesh_send_task\`. Append a structured result request at the end: ask the worker to conclude with a JSON block containing \`status\`, \`changedFiles\`, \`gitStatus\`, \`validationResults\`, \`errors\`, \`nextAction\`. The daemon parses this automatically; you can read it from \`mesh_task_history\`.
214
+ - **Reuse idle sessions.** For follow-up, retry, commit/push, or cleanup on the same issue, send only the delta to the existing idle session. Start fresh only for independent work, provider mismatch, transcript contamination, or required worktree isolation.
215
+ - **Respect explicit provider requests.** Map: Hermes \`hermes-cli\`, Claude/Claude Code \`claude-cli\`, Codex \`codex-cli\`, Gemini \`gemini-cli\`, Antigravity \`antigravity-cli\`. Never substitute the coordinator's own runtime.
216
+ - **Verify via git, not source.** Use \`mesh_git_status\` to confirm side effects. Treat agent summaries as self-reports, not verification.
217
+ - **Limit parallelism.** Start with 1–2 tasks; scale only on success. Never duplicate a session because \`mesh_read_chat\` shows no final message while tool/terminal activity is ongoing.
218
+ - **Check history first.** Call \`mesh_task_history\` at session start to avoid duplicate work and inform recovery. On failure, read task history before retrying.
219
+ - **Converge branches.** After worktree tasks: refine/fast-forward, or classify as \`pushed_feature_branch_needs_merge\` / \`blocked_review\` / \`cleanup_candidate\` / \`not_mergeable\`. Clean up with \`mesh_remove_node\`.
220
+ - **Refinery is config-driven.** \`mesh_refine_node\` must run validation from \`.adhdev/refine.{json,yaml,yml}\` or \`repo-mesh.refine.*\`. Heuristics are scaffolding only.
221
+ - **Submodule reachability = publish-needed.** \`submodule_reachability_failed\` classify as \`blocked_review\`, request user approval to push to submodule main, then rerun \`mesh_refine_node\`.
222
+ - **Never fabricate tool results.** Always call the actual tool.
223
+ - **Keep the user informed.** One or two sentences after each delegation round.${coordinatorNote}`;
206
224
  }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * MeshCoordinatorRegistry — Persisted record of active mesh coordinator sessions.
3
+ *
4
+ * Survives daemon restarts: when a CLI coordinator session is re-attached after
5
+ * a daemon restart the in-memory `settings.meshCoordinatorFor` on the provider
6
+ * instance is gone, so the registry file fills the gap.
7
+ *
8
+ * Keyed by sessionId (the CLI instance key / runtimeKey).
9
+ */
10
+
11
+ import { join } from 'path';
12
+ import { existsSync, readFileSync, writeFileSync } from 'fs';
13
+ import { getDaemonDataDir } from '../config/config.js';
14
+
15
+ export interface CoordinatorRegistryEntry {
16
+ meshId: string;
17
+ sessionId: string;
18
+ workspace?: string;
19
+ startedAt: number;
20
+ }
21
+
22
+ const _registry = new Map<string, CoordinatorRegistryEntry>();
23
+
24
+ function getRegistryPath(): string {
25
+ return join(getDaemonDataDir(), 'mesh-coordinators.json');
26
+ }
27
+
28
+ /** Load persisted coordinator registry from disk into in-memory map. Called once on daemon boot. */
29
+ export function loadMeshCoordinatorRegistry(): void {
30
+ const path = getRegistryPath();
31
+ if (!existsSync(path)) return;
32
+ try {
33
+ const raw = JSON.parse(readFileSync(path, 'utf-8'));
34
+ if (!Array.isArray(raw)) return;
35
+ _registry.clear();
36
+ for (const entry of raw) {
37
+ if (typeof entry?.sessionId === 'string' && typeof entry?.meshId === 'string') {
38
+ _registry.set(entry.sessionId, entry as CoordinatorRegistryEntry);
39
+ }
40
+ }
41
+ } catch { /* ignore corrupt file */ }
42
+ }
43
+
44
+ function saveRegistry(): void {
45
+ try {
46
+ writeFileSync(
47
+ getRegistryPath(),
48
+ JSON.stringify([..._registry.values()], null, 2),
49
+ { encoding: 'utf-8', mode: 0o600 },
50
+ );
51
+ } catch { /* best-effort */ }
52
+ }
53
+
54
+ /** Register a coordinator session. Persists to disk immediately. */
55
+ export function registerMeshCoordinator(entry: CoordinatorRegistryEntry): void {
56
+ _registry.set(entry.sessionId, entry);
57
+ saveRegistry();
58
+ }
59
+
60
+ /** Remove a coordinator session by sessionId. Persists to disk. */
61
+ export function unregisterMeshCoordinator(sessionId: string): void {
62
+ if (_registry.delete(sessionId)) {
63
+ saveRegistry();
64
+ }
65
+ }
66
+
67
+ /** Look up a coordinator entry by session ID. Returns undefined if not registered. */
68
+ export function getCoordinatorForSession(sessionId: string): CoordinatorRegistryEntry | undefined {
69
+ return _registry.get(sessionId);
70
+ }
71
+
72
+ /** List all coordinator entries for a given workspace path. */
73
+ export function listCoordinatorsForWorkspace(workspace: string): CoordinatorRegistryEntry[] {
74
+ return [..._registry.values()].filter(e => e.workspace === workspace);
75
+ }