@adhdev/daemon-core 0.9.82-rc.364 → 0.9.82-rc.366

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 (41) hide show
  1. package/dist/commands/high-family/index.d.ts +3 -0
  2. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  3. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  4. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  5. package/dist/commands/high-family/types.d.ts +60 -0
  6. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  7. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  8. package/dist/commands/med-family/ide.d.ts +10 -0
  9. package/dist/commands/med-family/index.d.ts +3 -0
  10. package/dist/commands/med-family/mesh-crud.d.ts +2 -0
  11. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  12. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  13. package/dist/commands/med-family/types.d.ts +116 -0
  14. package/dist/commands/router.d.ts +291 -0
  15. package/dist/index.js +3824 -3565
  16. package/dist/index.js.map +1 -1
  17. package/dist/index.mjs +3811 -3553
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/mesh/mesh-events-coordinator.d.ts +8 -0
  20. package/dist/system/hash.d.ts +8 -0
  21. package/package.json +2 -2
  22. package/src/commands/cli-manager.ts +30 -3
  23. package/src/commands/high-family/index.ts +28 -0
  24. package/src/commands/high-family/mesh-coordinator-launch.ts +592 -0
  25. package/src/commands/high-family/mesh-events.ts +47 -0
  26. package/src/commands/high-family/mesh-status.ts +639 -0
  27. package/src/commands/high-family/types.ts +76 -0
  28. package/src/commands/med-family/cli-agent.ts +218 -0
  29. package/src/commands/med-family/fast-forward.ts +198 -0
  30. package/src/commands/med-family/ide.ts +163 -0
  31. package/src/commands/med-family/index.ts +35 -0
  32. package/src/commands/med-family/mesh-crud.ts +788 -0
  33. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  34. package/src/commands/med-family/mesh-queue.ts +131 -0
  35. package/src/commands/med-family/types.ts +120 -0
  36. package/src/commands/mesh-coordinator.ts +2 -2
  37. package/src/commands/router.ts +328 -2847
  38. package/src/config/mesh-config.ts +3 -2
  39. package/src/mesh/mesh-active-work.ts +59 -81
  40. package/src/mesh/mesh-events-coordinator.ts +35 -1
  41. package/src/system/hash.ts +23 -0
@@ -0,0 +1,788 @@
1
+ /**
2
+ * RF-ROUTER MED family — mesh CRUD + node CRUD commands.
3
+ *
4
+ * Mesh records (list/get/create/update/delete_mesh) and node lifecycle
5
+ * (add/update/remove/clone_mesh_node, cleanup_mesh_sessions,
6
+ * retry_mesh_node_bootstrap). get_mesh hydrates direct git truth; the mutating
7
+ * node commands gate on the Mesh Host owner check and bust the aggregate-status
8
+ * cache; clone/remove/retry forward to the owning daemon for remote worktrees.
9
+ * Extracted verbatim from executeDaemonCommand; the inline-cache, session/worktree
10
+ * cleanup and aggregate-status collaborators come from ctx.
11
+ */
12
+ import { daemonIdsEquivalent, meshNodeIdMatches } from '@adhdev/mesh-shared';
13
+ import { resolveMeshHostStatus, normalizeMeshDaemonRole } from '../../mesh/mesh-host-ownership.js';
14
+ import {
15
+ loadMeshWorktreeBootstrapConfig,
16
+ runMeshWorktreeBootstrap,
17
+ type WorktreeBootstrapState,
18
+ } from '../../mesh/worktree-bootstrap-config.js';
19
+ import { handleMeshForwardEvent, queuePendingMeshCoordinatorEvent } from '../../mesh/mesh-events.js';
20
+ import { loadConfig } from '../../config/config.js';
21
+ import {
22
+ hydrateInlineMeshDirectTruth,
23
+ normalizeProviderRoles,
24
+ readMeshNodeMachineId,
25
+ } from '../router.js';
26
+ import type { CommandRouterResult } from '../router.js';
27
+ import type { MedFamilyContext, MedFamilyHandler } from './types.js';
28
+
29
+ export const meshCrudHandlers: Record<string, MedFamilyHandler> = {
30
+ list_meshes: async (_ctx: MedFamilyContext, _args: any) => {
31
+ try {
32
+ const { listMeshes } = await import('../../config/mesh-config.js');
33
+ return { success: true, meshes: listMeshes() };
34
+ } catch (e: any) {
35
+ return { success: false, error: e.message };
36
+ }
37
+ },
38
+
39
+ get_mesh: async (ctx: MedFamilyContext, args: any) => {
40
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
41
+ if (!meshId) return { success: false, error: 'meshId required' };
42
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
43
+ if (!meshRecord?.mesh) return { success: false, error: 'Mesh not found' };
44
+
45
+ const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
46
+ // Only an explicit refresh fans out a blocking peer probe.
47
+ // Default loads are satisfied from held standing-state git truth.
48
+ const probeRemotePeers = args?.refresh === true || args?.forceRefresh === true;
49
+ const directTruth = await hydrateInlineMeshDirectTruth({
50
+ mesh: meshRecord.mesh,
51
+ meshSource: meshRecord.source,
52
+ dispatchMeshCommand: ctx.deps.dispatchMeshCommand,
53
+ getMeshPeerConnectionStatus: ctx.deps.getMeshPeerConnectionStatus,
54
+ statusInstanceId: ctx.deps.statusInstanceId,
55
+ localMachineId: loadConfig().machineId || '',
56
+ probeRemotePeers,
57
+ probeCache: ctx.meshGitProbeCache,
58
+ });
59
+ const directTruthSatisfied = meshRecord.source !== 'inline_bootstrap' || directTruth.directEvidenceCount > 0;
60
+ const sourceOfTruth = {
61
+ membership: meshRecord.source === 'inline_cache'
62
+ ? 'coordinator_inline_mesh_cache'
63
+ : meshRecord.source === 'local_config'
64
+ ? 'local_mesh_config'
65
+ : 'inline_bootstrap_snapshot',
66
+ coordinatorOwnsLiveTruth: directTruthSatisfied,
67
+ directPeerTruth: {
68
+ required: requireDirectPeerTruth,
69
+ satisfied: directTruthSatisfied,
70
+ directEvidenceCount: directTruth.directEvidenceCount,
71
+ localConfirmedCount: directTruth.localConfirmedCount,
72
+ peerAttemptedCount: directTruth.peerAttemptedCount,
73
+ peerConfirmedCount: directTruth.peerConfirmedCount,
74
+ unavailableNodeIds: directTruth.unavailableNodeIds,
75
+ },
76
+ };
77
+ if (requireDirectPeerTruth && !directTruthSatisfied) {
78
+ return {
79
+ success: false,
80
+ code: 'mesh_direct_peer_truth_unavailable',
81
+ error: 'Selected coordinator could not confirm direct mesh truth yet. Bootstrap inventory stays unavailable until direct get_mesh probes succeed.',
82
+ sourceOfTruth,
83
+ };
84
+ }
85
+ return { success: true, mesh: meshRecord.mesh, sourceOfTruth };
86
+ },
87
+
88
+ create_mesh: async (_ctx: MedFamilyContext, args: any) => {
89
+ const name = typeof args?.name === 'string' ? args.name.trim() : '';
90
+ const repoIdentity = typeof args?.repoIdentity === 'string' ? args.repoIdentity.trim() : '';
91
+ const repoRemoteUrl = typeof args?.repoRemoteUrl === 'string' ? args.repoRemoteUrl.trim() : undefined;
92
+ const defaultBranch = typeof args?.defaultBranch === 'string' ? args.defaultBranch.trim() : undefined;
93
+ if (!name) return { success: false, error: 'name required' };
94
+ try {
95
+ const { createMesh } = await import('../../config/mesh-config.js');
96
+ const meshHost = args?.meshHost && typeof args.meshHost === 'object' && !Array.isArray(args.meshHost)
97
+ ? args.meshHost
98
+ : undefined;
99
+ const mesh = createMesh({ name, repoIdentity, repoRemoteUrl, defaultBranch, policy: args?.policy, meshHost });
100
+ return { success: true, mesh };
101
+ } catch (e: any) {
102
+ return { success: false, error: e.message };
103
+ }
104
+ },
105
+
106
+ update_mesh: async (ctx: MedFamilyContext, args: any) => {
107
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
108
+ if (!meshId) return { success: false, error: 'meshId required' };
109
+ try {
110
+ const { updateMesh } = await import('../../config/mesh-config.js');
111
+ const patch: Record<string, unknown> = {};
112
+ if (typeof args?.name === 'string') patch.name = args.name;
113
+ if (typeof args?.defaultBranch === 'string') patch.defaultBranch = args.defaultBranch;
114
+ if (args?.policy && typeof args.policy === 'object' && !Array.isArray(args.policy)) patch.policy = args.policy;
115
+ if (args?.coordinator && typeof args.coordinator === 'object' && !Array.isArray(args.coordinator)) patch.coordinator = args.coordinator;
116
+ if (args?.meshHost && typeof args.meshHost === 'object' && !Array.isArray(args.meshHost)) patch.meshHost = args.meshHost;
117
+ if (!Object.keys(patch).length) return { success: false, error: 'No updates provided' };
118
+ const mesh = updateMesh(meshId, patch as any);
119
+ if (!mesh) return { success: false, error: 'Mesh not found' };
120
+ ctx.inlineMeshCache.set(meshId, mesh);
121
+ ctx.invalidateAggregateMeshStatus(meshId);
122
+ return { success: true, mesh };
123
+ } catch (e: any) {
124
+ return { success: false, error: e.message };
125
+ }
126
+ },
127
+
128
+ delete_mesh: async (_ctx: MedFamilyContext, args: any) => {
129
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
130
+ if (!meshId) return { success: false, error: 'meshId required' };
131
+ try {
132
+ const { deleteMesh } = await import('../../config/mesh-config.js');
133
+ const deleted = deleteMesh(meshId);
134
+ return { success: true, deleted };
135
+ } catch (e: any) {
136
+ return { success: false, error: e.message };
137
+ }
138
+ },
139
+
140
+ add_mesh_node: async (ctx: MedFamilyContext, args: any) => {
141
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
142
+ const workspace = typeof args?.workspace === 'string' ? args.workspace.trim() : '';
143
+ if (!meshId) return { success: false, error: 'meshId required' };
144
+ if (!workspace) return { success: false, error: 'workspace required' };
145
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node addition');
146
+ if (ownerFailure) return ownerFailure;
147
+ try {
148
+ const { addNode } = await import('../../config/mesh-config.js');
149
+ const providerPriority = Array.isArray(args?.providerPriority)
150
+ ? args.providerPriority.map((type: any) => typeof type === 'string' ? type.trim() : '').filter(Boolean)
151
+ : [];
152
+ const readOnly = args?.readOnly === true;
153
+ const providerRoles = normalizeProviderRoles(args?.providerRoles);
154
+ const policy = {
155
+ ...(readOnly ? { readOnly: true } : {}),
156
+ ...(providerPriority.length ? { providerPriority } : {}),
157
+ ...(providerRoles.length ? { providerRoles } : {}),
158
+ };
159
+ const role = normalizeMeshDaemonRole(args?.role);
160
+ const daemonId = typeof args?.daemonId === 'string' && args.daemonId.trim() ? args.daemonId.trim() : undefined;
161
+ const machineId = typeof args?.machineId === 'string' && args.machineId.trim() ? args.machineId.trim() : undefined;
162
+ const repoRoot = typeof args?.repoRoot === 'string' && args.repoRoot.trim() ? args.repoRoot.trim() : undefined;
163
+ const node = addNode(meshId, {
164
+ workspace,
165
+ ...(repoRoot ? { repoRoot } : {}),
166
+ ...(daemonId ? { daemonId } : {}),
167
+ ...(machineId ? { machineId } : {}),
168
+ ...(policy ? { policy } : {}),
169
+ ...(role ? { role } : {}),
170
+ });
171
+ if (!node) return { success: false, error: 'Mesh not found' };
172
+ // mesh_status hands back a coordinator-memory aggregate
173
+ // snapshot keyed on (meshId, queueRevision). Adding a
174
+ // node touches neither, so without an explicit cache
175
+ // bust the dashboard graph keeps rendering the pre-add
176
+ // node list (empty for a fresh mesh) even after the
177
+ // user clicks Refresh.
178
+ ctx.invalidateAggregateMeshStatus(meshId);
179
+ return { success: true, node };
180
+ } catch (e: any) {
181
+ return { success: false, error: e.message };
182
+ }
183
+ },
184
+
185
+ update_mesh_node: async (ctx: MedFamilyContext, args: any) => {
186
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
187
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
188
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
189
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node update');
190
+ if (ownerFailure) return ownerFailure;
191
+ try {
192
+ const { updateNode } = await import('../../config/mesh-config.js');
193
+ const policy = args?.policy && typeof args.policy === 'object' && !Array.isArray(args.policy)
194
+ ? { ...(args.policy as Record<string, unknown>) }
195
+ : {};
196
+ if (Array.isArray(args?.providerPriority)) {
197
+ const providerPriority = args.providerPriority
198
+ .map((type: any) => typeof type === 'string' ? type.trim() : '')
199
+ .filter(Boolean);
200
+ delete (policy as any).provider_priority;
201
+ if (providerPriority.length) {
202
+ (policy as any).providerPriority = providerPriority;
203
+ } else {
204
+ delete (policy as any).providerPriority;
205
+ }
206
+ }
207
+ // providerRoles: per-(node, provider) role label + maxParallel cap.
208
+ // Passing an explicit (possibly empty) array clears/replaces the
209
+ // declarations; omitting the arg leaves any value already on policy
210
+ // untouched (a full policy object passed by the caller still carries it).
211
+ if (Array.isArray(args?.providerRoles)) {
212
+ const providerRoles = normalizeProviderRoles(args.providerRoles);
213
+ if (providerRoles.length) {
214
+ (policy as any).providerRoles = providerRoles;
215
+ } else {
216
+ delete (policy as any).providerRoles;
217
+ }
218
+ }
219
+ const patch: Record<string, unknown> = { policy: policy as any };
220
+ if (typeof args?.systemPrompt === 'string') {
221
+ const trimmed = (args.systemPrompt as string).trim();
222
+ patch.systemPrompt = trimmed || undefined;
223
+ } else if (args?.systemPrompt === null) {
224
+ patch.systemPrompt = undefined;
225
+ }
226
+ const node = updateNode(meshId, nodeId, patch as any);
227
+ if (!node) return { success: false, error: 'Mesh node not found' };
228
+ // Provider priority / systemPrompt changes don't touch
229
+ // the queue revision, so without a manual bust the
230
+ // cached aggregate keeps surfacing pre-update values
231
+ // (priority chip, coordinator prompt preview, etc.).
232
+ ctx.invalidateAggregateMeshStatus(meshId);
233
+ return { success: true, node };
234
+ } catch (e: any) {
235
+ return { success: false, error: e.message };
236
+ }
237
+ },
238
+
239
+ cleanup_mesh_sessions: async (ctx: MedFamilyContext, args: any) => {
240
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
241
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
242
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
243
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'node removal');
244
+ if (ownerFailure) return ownerFailure;
245
+ try {
246
+ // preferInline so inline-cache-only clone nodes resolve (matches owner check above).
247
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
248
+ const mesh = meshRecord?.mesh;
249
+ if (!mesh) return { success: false, error: 'Mesh not found' };
250
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
251
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
252
+ const mode = ctx.normalizeMeshSessionCleanupMode(args?.mode ?? mesh?.policy?.sessionCleanupOnNodeRemove);
253
+ const sessionIds = Array.isArray(args?.sessionIds)
254
+ ? args.sessionIds.map((id: any) => typeof id === 'string' ? id.trim() : '').filter(Boolean)
255
+ : undefined;
256
+ const result = await ctx.cleanupMeshSessions({
257
+ meshId,
258
+ nodeId,
259
+ node,
260
+ mode,
261
+ sessionIds,
262
+ dryRun: args?.dryRun === true,
263
+ source: 'mesh_cleanup_sessions',
264
+ });
265
+ return result;
266
+ } catch (e: any) {
267
+ return { success: false, error: e.message };
268
+ }
269
+ },
270
+
271
+ remove_mesh_node: async (ctx: MedFamilyContext, args: any) => {
272
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
273
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
274
+ if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
275
+ try {
276
+ // preferInline so removal can resolve inline-cache-only clone worktree nodes.
277
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
278
+ const mesh = meshRecord?.mesh;
279
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
280
+
281
+ // Guard: refuse to remove the coordinator's OWN local base node
282
+ // (same machine, NOT a worktree). Removing it breaks live mesh
283
+ // membership — the coordinator can no longer be reached and has
284
+ // to be restarted. Worktree clones are always safe to remove;
285
+ // only the non-worktree node bound to this daemon is protected.
286
+ // An explicit force:true overrides for intentional mesh teardown.
287
+ if (node && !args?._meshDirectDispatch && node.isLocalWorktree !== true && args?.force !== true) {
288
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : '';
289
+ const nodeMachineId = readMeshNodeMachineId(node as Record<string, unknown>) || '';
290
+ const selfDaemonId = ctx.deps.statusInstanceId || '';
291
+ const selfMachineId = (() => { try { return loadConfig().machineId || ''; } catch { return ''; } })();
292
+ const isCoordinatorBaseNode =
293
+ (!!selfDaemonId && (nodeDaemonId === selfDaemonId || nodeMachineId === selfDaemonId))
294
+ || (!!selfMachineId && (nodeDaemonId === selfMachineId || nodeMachineId === selfMachineId));
295
+ if (isCoordinatorBaseNode) {
296
+ return {
297
+ success: false,
298
+ removed: false,
299
+ code: 'mesh_remove_coordinator_base_node_protected',
300
+ error: `Refusing to remove the coordinator's own base node '${typeof node.workspace === 'string' ? node.workspace : nodeId}'. `
301
+ + `It is the local non-worktree node bound to this coordinator daemon; removing it breaks live mesh membership and forces a restart.`,
302
+ recoveryHint: 'Remove worktree clone nodes instead, or pass force:true only if you are intentionally tearing down this mesh and accept that the coordinator must be re-registered/restarted.',
303
+ };
304
+ }
305
+ }
306
+
307
+ const sessionCleanupMode = ctx.normalizeMeshSessionCleanupMode(
308
+ args?.sessionCleanupMode ?? args?.session_cleanup_mode ?? mesh?.policy?.sessionCleanupOnNodeRemove,
309
+ );
310
+ // Explicit sessionIds (e.g. supplied by refine auto-cleanup) bypass the
311
+ // workspace-only-match guard so a delegate session that lacks a
312
+ // meta.meshNodeId binding can still be stopped/deleted.
313
+ const explicitSessionIds = Array.isArray(args?.sessionIds)
314
+ ? (args.sessionIds as unknown[]).filter((v): v is string => typeof v === 'string' && v.trim().length > 0).map(v => v.trim())
315
+ : undefined;
316
+ let sessionCleanup: Record<string, unknown> | undefined;
317
+ if (node && sessionCleanupMode !== 'preserve') {
318
+ sessionCleanup = await ctx.cleanupMeshSessions({
319
+ meshId,
320
+ nodeId,
321
+ node,
322
+ mode: sessionCleanupMode,
323
+ ...(explicitSessionIds && explicitSessionIds.length > 0 ? { sessionIds: explicitSessionIds } : {}),
324
+ source: 'mesh_remove_node',
325
+ });
326
+ if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
327
+ }
328
+
329
+ let worktreeCleanup: Record<string, unknown> | undefined;
330
+ if (node?.isLocalWorktree) {
331
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
332
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
333
+ // clean up locally, do not forward. Equivalent → local.
334
+ const isRemoteWorktree = nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
335
+ && !args?._meshDirectDispatch;
336
+ if (isRemoteWorktree) {
337
+ // Worktree lives on a different machine — ask that daemon to clean it up.
338
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
339
+ const forwarded = await ctx.deps.dispatchMeshCommand!(nodeDaemonId!, 'remove_mesh_node', {
340
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
341
+ _meshDirectDispatch: true,
342
+ });
343
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
344
+ }
345
+ const cleanupResult = await ctx.cleanupLocalWorktreeNode({ mesh, node, nodeId, force: args?.force === true });
346
+ // De-gating: membership removal is NOT gated on the worktree
347
+ // directory actually being deleted. cleanupLocalWorktreeNode now
348
+ // returns success:true (with a residue flag) whenever the path is
349
+ // proven managed and the only remaining problem is leftover
350
+ // directory bytes (e.g. Windows EINVAL). A success:false here means
351
+ // a genuinely-unsafe condition — missing metadata, a non-managed /
352
+ // unexpected path, a branch mismatch, a dirty worktree, or an
353
+ // unverified force fallback — and those still block removal.
354
+ if (cleanupResult.success === false) {
355
+ return {
356
+ success: false,
357
+ removed: false,
358
+ code: cleanupResult.code,
359
+ error: cleanupResult.error,
360
+ recoveryHint: cleanupResult.recoveryHint,
361
+ ...(sessionCleanup ? { sessionCleanup } : {}),
362
+ worktreeCleanup: cleanupResult,
363
+ };
364
+ }
365
+ worktreeCleanup = cleanupResult;
366
+ }
367
+
368
+ let removed = false;
369
+ if (meshRecord?.inline) {
370
+ removed = ctx.removeInlineMeshNode(meshId, mesh, nodeId);
371
+ // Inline meshes share the same aggregate snapshot cache as
372
+ // local-config meshes; without this bust the removed node
373
+ // keeps showing up in the dashboard graph until the cache
374
+ // ages out on its own.
375
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
376
+ // Node was already absent from the inline mesh (e.g. removed by a
377
+ // prior refine cleanup). Treat as removed so caller gets removed:true.
378
+ if (!removed && !node) removed = true;
379
+ } else {
380
+ const { removeNode } = await import('../../config/mesh-config.js');
381
+ removed = removeNode(meshId, nodeId);
382
+ // Node already absent from config (e.g. removed by a prior refine
383
+ // cleanup after a successful Refinery merge). Treat as removed so
384
+ // the response is accurate.
385
+ if (!removed && !node) removed = true;
386
+ if (removed) ctx.invalidateAggregateMeshStatus(meshId);
387
+ }
388
+
389
+ // Record in task ledger
390
+ if (removed) {
391
+ try {
392
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
393
+ appendLedgerEntry(meshId, {
394
+ kind: 'node_removed',
395
+ nodeId,
396
+ payload: {
397
+ worktree: !!node?.isLocalWorktree,
398
+ sessionCleanupMode,
399
+ workspace: typeof node?.workspace === 'string' ? node.workspace : undefined,
400
+ daemonId: typeof node?.daemonId === 'string' ? node.daemonId : undefined,
401
+ worktreeBranch: typeof node?.worktreeBranch === 'string' ? node.worktreeBranch : undefined,
402
+ worktreeCleanupFallback: typeof worktreeCleanup?.fallback === 'string' ? worktreeCleanup.fallback : undefined,
403
+ forced: worktreeCleanup?.forced === true ? true : undefined,
404
+ forceFallbackReason: typeof worktreeCleanup?.reason === 'string' ? worktreeCleanup.reason : undefined,
405
+ },
406
+ });
407
+ } catch { /* ledger append is best-effort */ }
408
+ }
409
+
410
+ // Surface leftover-directory residue at the top level so callers
411
+ // see the node was dropped from the mesh even though the worktree
412
+ // directory could not be fully removed (best-effort, non-gating).
413
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === 'string'
414
+ ? worktreeCleanup.residueWarning
415
+ : undefined;
416
+ return {
417
+ success: true,
418
+ removed,
419
+ ...(residueWarning ? { residueWarning } : {}),
420
+ ...(sessionCleanup ? { sessionCleanup } : {}),
421
+ ...(worktreeCleanup ? { worktreeCleanup } : {}),
422
+ };
423
+ } catch (e: any) {
424
+ return { success: false, error: e.message };
425
+ }
426
+ },
427
+
428
+ clone_mesh_node: async (ctx: MedFamilyContext, args: any) => {
429
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
430
+ const sourceNodeId = typeof args?.sourceNodeId === 'string' ? args.sourceNodeId.trim() : '';
431
+ const branch = typeof args?.branch === 'string' ? args.branch.trim() : '';
432
+ const baseBranch = typeof args?.baseBranch === 'string' ? args.baseBranch.trim() : undefined;
433
+ if (!meshId) return { success: false, error: 'meshId required' };
434
+ if (!sourceNodeId) return { success: false, error: 'sourceNodeId required' };
435
+ if (!branch) return { success: false, error: 'branch required' };
436
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'worktree clone');
437
+ if (ownerFailure) return ownerFailure;
438
+
439
+ try {
440
+ // Resolve with preferInline so the clone writes the new node into the
441
+ // same representation that get_mesh reads back. The MCP coordinator
442
+ // passes inlineMesh on every mesh command, so when it owns an inline
443
+ // mesh the membership read path (get_mesh, preferInline: true) returns
444
+ // the inline cache. Without preferInline here, clone could resolve to a
445
+ // local-config mesh and write the node only to config — leaving the
446
+ // inline cache (and therefore get_mesh / refreshMeshFromDaemon) without
447
+ // the node, so the new worktree node is never visible in live mesh
448
+ // membership even though worktree_bootstrap_complete fires.
449
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
450
+ const mesh = meshRecord?.mesh;
451
+ if (!mesh) return { success: false, error: 'Mesh not found' };
452
+
453
+ const sourceNode = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, sourceNodeId));
454
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
455
+
456
+ // Forward to the source node's daemon if it's on a different machine.
457
+ // _meshDirectDispatch prevents infinite re-forwarding when the stored daemonId
458
+ // uses a legacy format that doesn't match the receiving daemon's statusInstanceId.
459
+ const sourceDaemonId = typeof sourceNode.daemonId === 'string' ? sourceNode.daemonId.trim() : undefined;
460
+ // daemonIdsEquivalent: an equivalent-form source daemonId is this machine —
461
+ // clone locally, do not forward. Equivalent → local.
462
+ if (sourceDaemonId && !daemonIdsEquivalent(sourceDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
463
+ && !args?._meshDirectDispatch) {
464
+ const forwarded = await ctx.deps.dispatchMeshCommand(sourceDaemonId, 'clone_mesh_node', {
465
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
466
+ _meshDirectDispatch: true,
467
+ });
468
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
469
+ }
470
+
471
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
472
+ const { createWorktree } = await import('../../git/git-worktree.js');
473
+ const result = await createWorktree({
474
+ repoRoot,
475
+ branch,
476
+ baseBranch,
477
+ meshName: mesh.name,
478
+ });
479
+
480
+ let node: any;
481
+ if (meshRecord.inline) {
482
+ const { randomUUID } = await import('crypto');
483
+ node = {
484
+ id: `node_${randomUUID().replace(/-/g, '')}`,
485
+ workspace: result.worktreePath,
486
+ repoRoot: result.worktreePath,
487
+ daemonId: sourceNode.daemonId,
488
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
489
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
490
+ policy: { ...(sourceNode.policy || {}) },
491
+ isLocalWorktree: true,
492
+ worktreeBranch: result.branch,
493
+ clonedFromNodeId: sourceNodeId,
494
+ };
495
+ ctx.updateInlineMeshNode(meshId, mesh, node);
496
+ } else {
497
+ const { addNode } = await import('../../config/mesh-config.js');
498
+ node = addNode(meshId, {
499
+ workspace: result.worktreePath,
500
+ repoRoot: result.worktreePath,
501
+ daemonId: sourceNode.daemonId,
502
+ machineId: sourceNode.machineId ?? (sourceNode as any).machine_id,
503
+ userOverrides: { ...(sourceNode.userOverrides || {}) },
504
+ isLocalWorktree: true,
505
+ worktreeBranch: result.branch,
506
+ clonedFromNodeId: sourceNodeId,
507
+ policy: { ...(sourceNode.policy || {}) },
508
+ });
509
+ if (!node) return { success: false, error: 'Failed to register worktree node' };
510
+ // Also reconcile the freshly-registered node into any warmed inline
511
+ // cache for this mesh. get_mesh (preferInline: true) reads the inline
512
+ // cache first when one exists; if we only wrote to local config the
513
+ // node would be invisible to membership reads. updateInlineMeshNode is
514
+ // a no-op when no inline cache is present.
515
+ const inlineForReconcile = ctx.getCachedInlineMesh(meshId);
516
+ if (inlineForReconcile) ctx.updateInlineMeshNode(meshId, inlineForReconcile, node);
517
+ ctx.invalidateAggregateMeshStatus(meshId);
518
+ }
519
+
520
+ const persistWorktreeSetupState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
521
+ node.worktreeBootstrap = bootstrapState;
522
+ if (meshRecord.inline) {
523
+ ctx.updateInlineMeshNode(meshId, mesh, node);
524
+ return;
525
+ }
526
+ try {
527
+ const { updateNode } = await import('../../config/mesh-config.js');
528
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
529
+ ctx.invalidateAggregateMeshStatus(meshId);
530
+ } catch { /* bootstrap status persistence is best-effort */ }
531
+ };
532
+
533
+ const appendCloneLedger = async (initSubmodules: boolean, bootstrapState: WorktreeBootstrapState): Promise<void> => {
534
+ try {
535
+ const { appendLedgerEntry } = await import('../../mesh/mesh-ledger.js');
536
+ appendLedgerEntry(meshId, {
537
+ kind: 'node_cloned',
538
+ nodeId: node.id,
539
+ payload: {
540
+ sourceNodeId,
541
+ branch: result.branch,
542
+ worktreePath: result.worktreePath,
543
+ submodulesInitialized: initSubmodules,
544
+ worktreeBootstrap: {
545
+ status: bootstrapState.status,
546
+ required: bootstrapState.required,
547
+ configSource: bootstrapState.configSource,
548
+ configSourceType: bootstrapState.configSourceType,
549
+ lastCommand: bootstrapState.lastCommand,
550
+ exitCode: bootstrapState.exitCode,
551
+ },
552
+ },
553
+ });
554
+ } catch { /* ledger append is best-effort */ }
555
+ };
556
+
557
+ const initSubmodules = (sourceNode.policy as any)?.initSubmodulesOnClone !== false;
558
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, result.worktreePath);
559
+ const runningBootstrapState: WorktreeBootstrapState = {
560
+ status: 'running',
561
+ required: loadedBootstrap.config?.required !== false,
562
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
563
+ configSourceType: loadedBootstrap.sourceType,
564
+ startedAt: new Date().toISOString(),
565
+ };
566
+ await persistWorktreeSetupState(runningBootstrapState);
567
+
568
+ const finishWorktreeSetup = async (): Promise<{ submodulesInitialized: boolean; bootstrapState: WorktreeBootstrapState }> => {
569
+ let submodulesInitialized = false;
570
+ if (initSubmodules) {
571
+ try {
572
+ const { runGit } = await import('../../git/git-executor.js');
573
+ await runGit(
574
+ { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
575
+ ['submodule', 'update', '--init', '--recursive'],
576
+ { timeoutMs: 120000 },
577
+ );
578
+ submodulesInitialized = true;
579
+
580
+ // Sync oss submodule to source node HEAD (best-effort)
581
+ const sourceWorkspace = sourceNode.repoRoot || sourceNode.workspace;
582
+ if (sourceWorkspace) {
583
+ try {
584
+ const { runGit: rg } = await import('../../git/git-executor.js');
585
+ const sourceCtx = { workspace: sourceWorkspace, repoRoot: sourceWorkspace, isGitRepo: true };
586
+ const worktreeCtx = { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true };
587
+
588
+ // Read source node's oss submodule SHA
589
+ const sourceStatusOut = await rg(sourceCtx, ['submodule', 'status', 'oss'], { timeoutMs: 10000 });
590
+ const sourceStatusLine = (typeof sourceStatusOut === 'string' ? sourceStatusOut : (sourceStatusOut as any)?.stdout ?? '').trim();
591
+ const sourceShaMatch = sourceStatusLine.match(/^[+\- ]?([0-9a-f]{40})/);
592
+ const sourceSha = sourceShaMatch?.[1];
593
+
594
+ if (sourceSha) {
595
+ // Read worktree's current oss HEAD
596
+ const ossCtx = { workspace: `${result.worktreePath}/oss`, repoRoot: `${result.worktreePath}/oss`, isGitRepo: true };
597
+ const worktreeOssHeadOut = await rg(ossCtx, ['rev-parse', 'HEAD'], { timeoutMs: 10000 });
598
+ const worktreeOssSha = (typeof worktreeOssHeadOut === 'string' ? worktreeOssHeadOut : (worktreeOssHeadOut as any)?.stdout ?? '').trim();
599
+
600
+ if (worktreeOssSha !== sourceSha) {
601
+ // Fetch target SHA from source node's oss directory
602
+ await rg(ossCtx, ['fetch', `${sourceWorkspace}/oss`, 'HEAD'], { timeoutMs: 60000 });
603
+ await rg(ossCtx, ['checkout', sourceSha], { timeoutMs: 10000 });
604
+ await rg(worktreeCtx, ['add', 'oss'], { timeoutMs: 10000 });
605
+ await rg(worktreeCtx, ['commit', '-m', 'chore: sync oss to source node HEAD on clone'], { timeoutMs: 10000 });
606
+ console.log(`[mesh] Synced oss submodule to source HEAD ${sourceSha.slice(0, 8)} in worktree`);
607
+ }
608
+ }
609
+ } catch (ossErr: any) {
610
+ console.warn('[mesh] oss submodule sync to source HEAD failed (best-effort):', ossErr.message);
611
+ }
612
+ }
613
+ } catch (subErr: any) {
614
+ // Submodule init is best-effort; don't fail the clone
615
+ console.warn('[mesh] Submodule init failed for worktree:', subErr.message);
616
+ }
617
+ }
618
+ const bootstrapState: WorktreeBootstrapState = await runMeshWorktreeBootstrap(mesh, result.worktreePath);
619
+ await persistWorktreeSetupState(bootstrapState);
620
+ await appendCloneLedger(submodulesInitialized, bootstrapState);
621
+ return { submodulesInitialized, bootstrapState };
622
+ };
623
+
624
+ const requestedSetupWaitMs = Number(args?.setupWaitMs ?? args?.bootstrapWaitMs ?? 8000);
625
+ const setupWaitMs = Number.isFinite(requestedSetupWaitMs)
626
+ ? Math.min(Math.max(requestedSetupWaitMs, 0), 14000)
627
+ : 8000;
628
+ const setupPromise = finishWorktreeSetup();
629
+ const setupResult = await Promise.race([
630
+ setupPromise.then((value) => ({ completed: true as const, value })),
631
+ new Promise<{ completed: false }>((resolve) => setTimeout(() => resolve({ completed: false }), setupWaitMs)),
632
+ ]);
633
+
634
+ const emitBootstrapEvent = (eventStatus: 'bootstrap_complete' | 'bootstrap_failed', bootstrapState: WorktreeBootstrapState, startedAtMs: number, extraPayload?: Record<string, unknown>): void => {
635
+ try {
636
+ const durationMs = Date.now() - startedAtMs;
637
+ const event = `worktree_${eventStatus}` as const;
638
+ const metadataEvent = {
639
+ source: 'clone_mesh_node_bootstrap',
640
+ nodeId: node.id,
641
+ status: eventStatus,
642
+ worktreePath: result.worktreePath,
643
+ durationMs,
644
+ bootstrapStatus: bootstrapState.status,
645
+ ...(bootstrapState.error ? { error: bootstrapState.error } : {}),
646
+ ...(bootstrapState.exitCode !== undefined ? { exitCode: bootstrapState.exitCode } : {}),
647
+ ...(extraPayload || {}),
648
+ };
649
+ if (typeof ctx.deps.instanceManager?.getByCategory === 'function') {
650
+ const forwarded = handleMeshForwardEvent(
651
+ { instanceManager: ctx.deps.instanceManager } as any,
652
+ { event, meshId, nodeId: node.id, workspace: result.worktreePath, metadataEvent },
653
+ );
654
+ if (forwarded?.success === true) return;
655
+ }
656
+ queuePendingMeshCoordinatorEvent({
657
+ event,
658
+ meshId,
659
+ nodeLabel: node.id,
660
+ nodeId: node.id,
661
+ workspace: result.worktreePath,
662
+ metadataEvent,
663
+ queuedAt: Date.now(),
664
+ });
665
+ } catch { /* event emission is best-effort */ }
666
+ };
667
+
668
+ const bootstrapStartedMs = Date.now();
669
+
670
+ if (!setupResult.completed) {
671
+ setupPromise
672
+ .then(({ bootstrapState }) => {
673
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
674
+ })
675
+ .catch((error: any) => {
676
+ const failedState: WorktreeBootstrapState = {
677
+ ...runningBootstrapState,
678
+ status: 'failed',
679
+ completedAt: new Date().toISOString(),
680
+ error: error?.message || String(error),
681
+ };
682
+ void persistWorktreeSetupState(failedState);
683
+ void appendCloneLedger(false, failedState);
684
+ emitBootstrapEvent('bootstrap_failed', failedState, bootstrapStartedMs, { error: error?.message || String(error) });
685
+ });
686
+ return {
687
+ success: true,
688
+ async: true,
689
+ status: 'accepted',
690
+ node,
691
+ worktreePath: result.worktreePath,
692
+ branch: result.branch,
693
+ worktreeBootstrap: runningBootstrapState,
694
+ worktreeSetup: {
695
+ status: 'running',
696
+ setupWaitMs,
697
+ message: 'Worktree node is registered; submodule/bootstrap setup is continuing in the background.',
698
+ },
699
+ };
700
+ }
701
+
702
+ const { submodulesInitialized, bootstrapState } = setupResult.value;
703
+ emitBootstrapEvent('bootstrap_complete', bootstrapState, bootstrapStartedMs);
704
+ return {
705
+ success: true,
706
+ node,
707
+ worktreePath: result.worktreePath,
708
+ branch: result.branch,
709
+ submodulesInitialized,
710
+ worktreeBootstrap: bootstrapState,
711
+ };
712
+ } catch (e: any) {
713
+ return { success: false, error: e.message };
714
+ }
715
+ },
716
+
717
+ retry_mesh_node_bootstrap: async (ctx: MedFamilyContext, args: any) => {
718
+ const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
719
+ const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
720
+ if (!meshId) return { success: false, error: 'meshId required' };
721
+ if (!nodeId) return { success: false, error: 'nodeId required' };
722
+ const ownerFailure = await ctx.requireMeshHostMutationOwner(meshId, args?.inlineMesh, 'bootstrap retry');
723
+ if (ownerFailure) return ownerFailure;
724
+
725
+ try {
726
+ // preferInline so bootstrap-retry can resolve inline-cache-only clone worktree nodes.
727
+ const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
728
+ const mesh = meshRecord?.mesh;
729
+ if (!mesh) return { success: false, error: 'Mesh not found' };
730
+
731
+ const node = mesh.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
732
+ if (!node) return { success: false, error: `Node '${nodeId}' not found in mesh` };
733
+ if (!node.isLocalWorktree) return { success: false, error: 'Node is not a local worktree node' };
734
+
735
+ // Bootstrap runs scripts in the worktree path — forward to the node's daemon if remote.
736
+ // _meshDirectDispatch prevents re-forwarding when stored daemonId uses legacy format.
737
+ const nodeDaemonId = typeof node.daemonId === 'string' ? node.daemonId.trim() : undefined;
738
+ // daemonIdsEquivalent: an equivalent-form daemonId is this machine —
739
+ // bootstrap locally, do not forward. Equivalent → local.
740
+ if (nodeDaemonId && !daemonIdsEquivalent(nodeDaemonId, ctx.deps.statusInstanceId) && ctx.deps.dispatchMeshCommand
741
+ && !args?._meshDirectDispatch) {
742
+ const forwarded = await ctx.deps.dispatchMeshCommand(nodeDaemonId, 'retry_mesh_node_bootstrap', {
743
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
744
+ _meshDirectDispatch: true,
745
+ });
746
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
747
+ }
748
+
749
+ const currentBootstrap = node.worktreeBootstrap as WorktreeBootstrapState | undefined;
750
+ if (currentBootstrap?.status === 'running') {
751
+ return { success: false, error: 'Bootstrap is already running for this node' };
752
+ }
753
+
754
+ const worktreePath: string = node.workspace || node.repoRoot;
755
+ if (!worktreePath) return { success: false, error: 'Node has no workspace path' };
756
+
757
+ const loadedBootstrap = loadMeshWorktreeBootstrapConfig(mesh, worktreePath);
758
+ const runningState: WorktreeBootstrapState = {
759
+ status: 'running',
760
+ required: loadedBootstrap.config?.required !== false,
761
+ configSource: loadedBootstrap.path || loadedBootstrap.source,
762
+ configSourceType: loadedBootstrap.sourceType,
763
+ startedAt: new Date().toISOString(),
764
+ };
765
+
766
+ const persistState = async (bootstrapState: WorktreeBootstrapState): Promise<void> => {
767
+ node.worktreeBootstrap = bootstrapState;
768
+ if (meshRecord.inline) {
769
+ ctx.updateInlineMeshNode(meshId, mesh, node);
770
+ return;
771
+ }
772
+ try {
773
+ const { updateNode } = await import('../../config/mesh-config.js');
774
+ updateNode(meshId, node.id, { worktreeBootstrap: bootstrapState });
775
+ ctx.invalidateAggregateMeshStatus(meshId);
776
+ } catch { /* best-effort */ }
777
+ };
778
+
779
+ await persistState(runningState);
780
+ const bootstrapState = await runMeshWorktreeBootstrap(mesh, worktreePath);
781
+ await persistState(bootstrapState);
782
+
783
+ return { success: true, bootstrapState };
784
+ } catch (e: any) {
785
+ return { success: false, error: e.message };
786
+ }
787
+ },
788
+ };