@adhdev/daemon-core 0.9.67 → 0.9.69

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.
package/dist/index.mjs CHANGED
@@ -25,6 +25,22 @@ var __copyProps = (to, from, except, desc) => {
25
25
  };
26
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
27
 
28
+ // src/repo-mesh-types.ts
29
+ var DEFAULT_MESH_POLICY;
30
+ var init_repo_mesh_types = __esm({
31
+ "src/repo-mesh-types.ts"() {
32
+ "use strict";
33
+ DEFAULT_MESH_POLICY = {
34
+ requirePreTaskCheckpoint: false,
35
+ requirePostTaskCheckpoint: true,
36
+ requireApprovalForPush: true,
37
+ requireApprovalForDestructiveGit: true,
38
+ dirtyWorkspaceBehavior: "warn",
39
+ maxParallelTasks: 2
40
+ };
41
+ }
42
+ });
43
+
28
44
  // src/config/config.ts
29
45
  var config_exports = {};
30
46
  __export(config_exports, {
@@ -263,6 +279,275 @@ var init_config = __esm({
263
279
  }
264
280
  });
265
281
 
282
+ // src/config/mesh-config.ts
283
+ var mesh_config_exports = {};
284
+ __export(mesh_config_exports, {
285
+ addNode: () => addNode,
286
+ createMesh: () => createMesh,
287
+ deleteMesh: () => deleteMesh,
288
+ getMesh: () => getMesh,
289
+ getMeshByRepo: () => getMeshByRepo,
290
+ listMeshes: () => listMeshes,
291
+ normalizeRepoIdentity: () => normalizeRepoIdentity,
292
+ removeNode: () => removeNode,
293
+ updateMesh: () => updateMesh,
294
+ updateNode: () => updateNode
295
+ });
296
+ import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
297
+ import { join as join3 } from "path";
298
+ import { randomUUID as randomUUID3 } from "crypto";
299
+ function getMeshConfigPath() {
300
+ return join3(getConfigDir(), "meshes.json");
301
+ }
302
+ function loadMeshConfig() {
303
+ const path26 = getMeshConfigPath();
304
+ if (!existsSync3(path26)) return { meshes: [] };
305
+ try {
306
+ const raw = JSON.parse(readFileSync2(path26, "utf-8"));
307
+ if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
308
+ return raw;
309
+ } catch {
310
+ return { meshes: [] };
311
+ }
312
+ }
313
+ function saveMeshConfig(config) {
314
+ const path26 = getMeshConfigPath();
315
+ writeFileSync2(path26, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
316
+ }
317
+ function normalizeRepoIdentity(remoteUrl) {
318
+ let identity = remoteUrl.trim();
319
+ if (identity.startsWith("http://") || identity.startsWith("https://")) {
320
+ try {
321
+ const url = new URL(identity);
322
+ const path26 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
323
+ return `${url.hostname}/${path26}`;
324
+ } catch {
325
+ }
326
+ }
327
+ const sshMatch = identity.match(/^(?:ssh:\/\/)?[\w.-]+@([\w.-]+)[:/]([\w.\-/]+?)(?:\.git)?$/);
328
+ if (sshMatch) return `${sshMatch[1]}/${sshMatch[2]}`;
329
+ return identity;
330
+ }
331
+ function listMeshes() {
332
+ return loadMeshConfig().meshes;
333
+ }
334
+ function getMesh(meshId) {
335
+ return loadMeshConfig().meshes.find((m) => m.id === meshId);
336
+ }
337
+ function getMeshByRepo(repoIdentity) {
338
+ return loadMeshConfig().meshes.find((m) => m.repoIdentity === repoIdentity);
339
+ }
340
+ function createMesh(opts) {
341
+ const config = loadMeshConfig();
342
+ if (config.meshes.length >= 20) {
343
+ throw new Error("Maximum 20 meshes allowed");
344
+ }
345
+ const repoIdentity = opts.repoIdentity || (opts.repoRemoteUrl ? normalizeRepoIdentity(opts.repoRemoteUrl) : "");
346
+ if (!repoIdentity) throw new Error("Either repoRemoteUrl or repoIdentity is required");
347
+ const now = (/* @__PURE__ */ new Date()).toISOString();
348
+ const mesh = {
349
+ id: `mesh_${randomUUID3().replace(/-/g, "")}`,
350
+ name: opts.name.trim().slice(0, 100),
351
+ repoIdentity,
352
+ repoRemoteUrl: opts.repoRemoteUrl,
353
+ defaultBranch: opts.defaultBranch,
354
+ policy: { ...DEFAULT_MESH_POLICY, ...opts.policy },
355
+ coordinator: opts.coordinator || {},
356
+ nodes: [],
357
+ createdAt: now,
358
+ updatedAt: now
359
+ };
360
+ config.meshes.push(mesh);
361
+ saveMeshConfig(config);
362
+ return mesh;
363
+ }
364
+ function updateMesh(meshId, opts) {
365
+ const config = loadMeshConfig();
366
+ const mesh = config.meshes.find((m) => m.id === meshId);
367
+ if (!mesh) return void 0;
368
+ if (opts.name !== void 0) mesh.name = opts.name.trim().slice(0, 100);
369
+ if (opts.defaultBranch !== void 0) mesh.defaultBranch = opts.defaultBranch;
370
+ if (opts.policy) mesh.policy = { ...mesh.policy, ...opts.policy };
371
+ if (opts.coordinator) mesh.coordinator = opts.coordinator;
372
+ mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
373
+ saveMeshConfig(config);
374
+ return mesh;
375
+ }
376
+ function deleteMesh(meshId) {
377
+ const config = loadMeshConfig();
378
+ const idx = config.meshes.findIndex((m) => m.id === meshId);
379
+ if (idx === -1) return false;
380
+ config.meshes.splice(idx, 1);
381
+ saveMeshConfig(config);
382
+ return true;
383
+ }
384
+ function addNode(meshId, opts) {
385
+ const config = loadMeshConfig();
386
+ const mesh = config.meshes.find((m) => m.id === meshId);
387
+ if (!mesh) return void 0;
388
+ if (mesh.nodes.length >= 10) {
389
+ throw new Error("Maximum 10 nodes per mesh");
390
+ }
391
+ if (mesh.nodes.some((n) => n.workspace === opts.workspace)) {
392
+ throw new Error("This workspace is already in the mesh");
393
+ }
394
+ const node = {
395
+ id: `node_${randomUUID3().replace(/-/g, "")}`,
396
+ workspace: opts.workspace.trim(),
397
+ repoRoot: opts.repoRoot,
398
+ userOverrides: opts.userOverrides || {},
399
+ policy: opts.policy || {},
400
+ isLocalWorktree: opts.isLocalWorktree
401
+ };
402
+ mesh.nodes.push(node);
403
+ mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
404
+ saveMeshConfig(config);
405
+ return node;
406
+ }
407
+ function removeNode(meshId, nodeId) {
408
+ const config = loadMeshConfig();
409
+ const mesh = config.meshes.find((m) => m.id === meshId);
410
+ if (!mesh) return false;
411
+ const idx = mesh.nodes.findIndex((n) => n.id === nodeId);
412
+ if (idx === -1) return false;
413
+ mesh.nodes.splice(idx, 1);
414
+ mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
415
+ saveMeshConfig(config);
416
+ return true;
417
+ }
418
+ function updateNode(meshId, nodeId, opts) {
419
+ const config = loadMeshConfig();
420
+ const mesh = config.meshes.find((m) => m.id === meshId);
421
+ if (!mesh) return void 0;
422
+ const node = mesh.nodes.find((n) => n.id === nodeId);
423
+ if (!node) return void 0;
424
+ if (opts.userOverrides) node.userOverrides = { ...node.userOverrides, ...opts.userOverrides };
425
+ if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
426
+ mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
427
+ saveMeshConfig(config);
428
+ return node;
429
+ }
430
+ var init_mesh_config = __esm({
431
+ "src/config/mesh-config.ts"() {
432
+ "use strict";
433
+ init_config();
434
+ init_repo_mesh_types();
435
+ }
436
+ });
437
+
438
+ // src/mesh/coordinator-prompt.ts
439
+ var coordinator_prompt_exports = {};
440
+ __export(coordinator_prompt_exports, {
441
+ buildCoordinatorSystemPrompt: () => buildCoordinatorSystemPrompt
442
+ });
443
+ function buildCoordinatorSystemPrompt(ctx) {
444
+ const { mesh, status, userInstruction } = ctx;
445
+ const sections = [];
446
+ sections.push(`You are a **Repo Mesh Coordinator** \u2014 a technical team lead who orchestrates work across multiple agent sessions on a shared Git repository.
447
+
448
+ Your mesh: **${mesh.name}**
449
+ Repository: \`${mesh.repoIdentity}\`${mesh.defaultBranch ? `
450
+ Default branch: \`${mesh.defaultBranch}\`` : ""}`);
451
+ if (status?.nodes?.length) {
452
+ sections.push(buildNodeStatusSection(status.nodes));
453
+ } else if (mesh.nodes.length) {
454
+ sections.push(buildNodeConfigSection(mesh));
455
+ } else {
456
+ sections.push("## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`.");
457
+ }
458
+ sections.push(buildPolicySection(mesh.policy));
459
+ sections.push(TOOLS_SECTION);
460
+ sections.push(WORKFLOW_SECTION);
461
+ sections.push(RULES_SECTION);
462
+ if (userInstruction) {
463
+ sections.push(`## Additional Context
464
+ ${userInstruction}`);
465
+ }
466
+ if (mesh.coordinator.systemPromptSuffix) {
467
+ sections.push(mesh.coordinator.systemPromptSuffix);
468
+ }
469
+ return sections.join("\n\n");
470
+ }
471
+ function buildNodeStatusSection(nodes) {
472
+ const lines = ["## Current Node Status", ""];
473
+ for (const n of nodes) {
474
+ const healthIcon = n.health === "online" ? "\u{1F7E2}" : n.health === "dirty" ? "\u{1F7E1}" : n.health === "offline" ? "\u26AB" : "\u{1F534}";
475
+ const sessions = n.activeSessions.length > 0 ? `sessions: ${n.activeSessions.join(", ")}` : "no active sessions";
476
+ const branch = n.git?.branch ? `branch: \`${n.git.branch}\`` : "";
477
+ lines.push(`- ${healthIcon} **${n.machineLabel}** (${n.nodeId})`);
478
+ lines.push(` workspace: \`${n.workspace}\` | ${branch} | ${sessions}`);
479
+ if (n.error) lines.push(` \u26A0\uFE0F ${n.error}`);
480
+ }
481
+ return lines.join("\n");
482
+ }
483
+ function buildNodeConfigSection(mesh) {
484
+ const lines = ["## Configured Nodes", ""];
485
+ for (const n of mesh.nodes) {
486
+ const labels = [];
487
+ if (n.isLocalWorktree) labels.push("worktree");
488
+ if (n.policy.readOnly) labels.push("read-only");
489
+ const suffix = labels.length ? ` [${labels.join(", ")}]` : "";
490
+ lines.push(`- **${n.workspace}** (${n.id})${suffix}`);
491
+ }
492
+ lines.push("", "_Use `mesh_status` to probe live health before delegating work._");
493
+ return lines.join("\n");
494
+ }
495
+ function buildPolicySection(policy) {
496
+ const rules = [];
497
+ if (policy.requirePreTaskCheckpoint) rules.push("- Create a git checkpoint **before** starting each task");
498
+ if (policy.requirePostTaskCheckpoint) rules.push("- Create a git checkpoint **after** each task completes");
499
+ if (policy.requireApprovalForPush) rules.push("- **Ask for user approval** before pushing to remote");
500
+ if (policy.requireApprovalForDestructiveGit) rules.push("- **Ask for user approval** before destructive git operations (force push, reset, etc.)");
501
+ const dirtyBehavior = {
502
+ block: "- **Do not** send tasks to nodes with dirty workspaces",
503
+ warn: "- Warn the user if a node has uncommitted changes before sending a task",
504
+ checkpoint_then_continue: "- Auto-checkpoint dirty nodes before sending tasks"
505
+ }[policy.dirtyWorkspaceBehavior] || "";
506
+ if (dirtyBehavior) rules.push(dirtyBehavior);
507
+ rules.push(`- Maximum **${policy.maxParallelTasks}** tasks running in parallel`);
508
+ return `## Policy
509
+ ${rules.join("\n")}`;
510
+ }
511
+ var TOOLS_SECTION, WORKFLOW_SECTION, RULES_SECTION;
512
+ var init_coordinator_prompt = __esm({
513
+ "src/mesh/coordinator-prompt.ts"() {
514
+ "use strict";
515
+ TOOLS_SECTION = `## Available Tools
516
+
517
+ | Tool | Purpose |
518
+ |------|---------|
519
+ | \`mesh_status\` | Check all nodes' health, git state, and active sessions |
520
+ | \`mesh_list_nodes\` | List nodes with workspace paths |
521
+ | \`mesh_launch_session\` | Start a new agent session on a node |
522
+ | \`mesh_send_task\` | Send a task (natural language) to a running agent |
523
+ | \`mesh_read_chat\` | Read an agent's recent messages to check progress |
524
+ | \`mesh_git_status\` | Check git status on a specific node |
525
+ | \`mesh_checkpoint\` | Create a git checkpoint on a node |
526
+ | \`mesh_approve\` | Approve/reject a pending agent action |`;
527
+ WORKFLOW_SECTION = `## Orchestration Workflow
528
+
529
+ 1. **Assess** \u2014 Call \`mesh_status\` to see which nodes are healthy and available.
530
+ 2. **Plan** \u2014 Decompose the user's request into independent tasks for parallel execution, or sequential tasks when dependencies exist.
531
+ 3. **Delegate** \u2014 For each task:
532
+ a. Pick the best node (consider: health, dirty state, current workload).
533
+ b. If no session exists, call \`mesh_launch_session\` to start one.
534
+ c. Call \`mesh_send_task\` with a clear, self-contained natural-language instruction.
535
+ 4. **Monitor** \u2014 Periodically call \`mesh_read_chat\` to check progress. Handle approvals via \`mesh_approve\`.
536
+ 5. **Verify** \u2014 When a task reports completion, call \`mesh_git_status\` to verify changes were made.
537
+ 6. **Checkpoint** \u2014 Call \`mesh_checkpoint\` to save the work.
538
+ 7. **Report** \u2014 Summarize what was done, what changed, and any issues.`;
539
+ RULES_SECTION = `## Rules
540
+
541
+ - **Be conversational.** Delegate work the way a tech lead would \u2014 clear, specific instructions in natural language.
542
+ - **Don't inspect code.** Trust the agent's output. Verify via git diff/status, not by reading source files.
543
+ - **Don't over-parallelize.** Start with 1-2 concurrent tasks. Scale up if they succeed.
544
+ - **Handle failures gracefully.** If a task fails, read the chat to understand why, then retry or reassign.
545
+ - **Keep the user informed.** Report progress after each delegation round.
546
+ - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
547
+ - **Never fabricate tool results.** Always call the actual tool; never pretend you did.`;
548
+ }
549
+ });
550
+
266
551
  // src/logging/logger.ts
267
552
  import * as fs2 from "fs";
268
553
  import * as path9 from "path";
@@ -3320,15 +3605,8 @@ var init_provider_cli_adapter = __esm({
3320
3605
  }
3321
3606
  });
3322
3607
 
3323
- // src/repo-mesh-types.ts
3324
- var DEFAULT_MESH_POLICY = {
3325
- requirePreTaskCheckpoint: false,
3326
- requirePostTaskCheckpoint: true,
3327
- requireApprovalForPush: true,
3328
- requireApprovalForDestructiveGit: true,
3329
- dirtyWorkspaceBehavior: "warn",
3330
- maxParallelTasks: 2
3331
- };
3608
+ // src/index.ts
3609
+ init_repo_mesh_types();
3332
3610
 
3333
3611
  // src/git/git-executor.ts
3334
3612
  import { execFile } from "child_process";
@@ -5031,343 +5309,108 @@ function applySessionNotificationOverlay(session, overlay) {
5031
5309
  const dismissedNotificationId = typeof overlay.dismissedNotificationId === "string" ? overlay.dismissedNotificationId.trim() : "";
5032
5310
  const unreadNotificationId = typeof overlay.unreadNotificationId === "string" ? overlay.unreadNotificationId.trim() : "";
5033
5311
  if (unreadNotificationId && (currentNotificationId === unreadNotificationId || taskCompleteNotificationId === unreadNotificationId)) {
5034
- const forcedInboxBucket = session.inboxBucket === "needs_attention" || session.status === "waiting_approval" ? "needs_attention" : "task_complete";
5035
- return {
5036
- unread: true,
5037
- inboxBucket: forcedInboxBucket
5038
- };
5039
- }
5040
- if (!currentNotificationId || !dismissedNotificationId || currentNotificationId !== dismissedNotificationId) {
5041
- return {
5042
- unread: !!session.unread,
5043
- inboxBucket: session.inboxBucket || "idle"
5044
- };
5045
- }
5046
- return {
5047
- unread: false,
5048
- inboxBucket: "idle"
5049
- };
5050
- }
5051
- function markSessionSeen(state, sessionId, seenAt = Date.now(), completionMarker, providerSessionId) {
5052
- const prev = state.sessionReads || {};
5053
- const prevMarkers = state.sessionReadMarkers || {};
5054
- const nextMarker = typeof completionMarker === "string" ? completionMarker : "";
5055
- const readKeys = Array.from(new Set([
5056
- sessionId,
5057
- buildSessionReadStateKey(sessionId, providerSessionId)
5058
- ].filter(Boolean)));
5059
- const nextSessionReads = { ...prev };
5060
- const nextSessionReadMarkers = { ...prevMarkers };
5061
- const nextSessionNotificationDismissals = { ...state.sessionNotificationDismissals || {} };
5062
- const nextSessionNotificationUnreadOverrides = { ...state.sessionNotificationUnreadOverrides || {} };
5063
- for (const key of readKeys) {
5064
- nextSessionReads[key] = Math.max(prev[key] || 0, seenAt);
5065
- if (nextMarker) nextSessionReadMarkers[key] = nextMarker;
5066
- delete nextSessionNotificationDismissals[key];
5067
- delete nextSessionNotificationUnreadOverrides[key];
5068
- }
5069
- return {
5070
- ...state,
5071
- sessionReads: nextSessionReads,
5072
- sessionReadMarkers: nextMarker ? nextSessionReadMarkers : prevMarkers,
5073
- sessionNotificationDismissals: nextSessionNotificationDismissals,
5074
- sessionNotificationUnreadOverrides: nextSessionNotificationUnreadOverrides
5075
- };
5076
- }
5077
-
5078
- // src/config/saved-sessions.ts
5079
- import * as path6 from "path";
5080
- var MAX_SAVED_SESSIONS = 500;
5081
- function normalizeWorkspace2(workspace) {
5082
- if (!workspace) return "";
5083
- try {
5084
- return path6.resolve(expandPath(workspace));
5085
- } catch {
5086
- return path6.resolve(workspace);
5087
- }
5088
- }
5089
- function buildSavedProviderSessionKey(providerSessionId) {
5090
- return `saved:${providerSessionId.trim()}`;
5091
- }
5092
- function upsertSavedProviderSession(state, entry) {
5093
- const providerSessionId = typeof entry.providerSessionId === "string" ? entry.providerSessionId.trim() : "";
5094
- if (!providerSessionId) return state;
5095
- const id = buildSavedProviderSessionKey(providerSessionId);
5096
- const existing = (state.savedProviderSessions || []).find((item) => item.id === id);
5097
- const nextEntry = {
5098
- id,
5099
- kind: entry.kind,
5100
- providerType: entry.providerType,
5101
- providerName: entry.providerName,
5102
- providerSessionId,
5103
- workspace: entry.workspace ? normalizeWorkspace2(entry.workspace) : void 0,
5104
- summaryMetadata: normalizePersistedSummaryMetadata({
5105
- summaryMetadata: entry.summaryMetadata
5106
- }),
5107
- title: entry.title,
5108
- createdAt: existing?.createdAt || entry.createdAt || Date.now(),
5109
- lastUsedAt: entry.lastUsedAt || Date.now()
5110
- };
5111
- const filtered = (state.savedProviderSessions || []).filter((item) => item.id !== id);
5112
- return {
5113
- ...state,
5114
- savedProviderSessions: [nextEntry, ...filtered].slice(0, MAX_SAVED_SESSIONS)
5115
- };
5116
- }
5117
- function getSavedProviderSessions(state, filters) {
5118
- return [...state.savedProviderSessions || []].filter((entry) => {
5119
- if (filters?.providerType && entry.providerType !== filters.providerType) return false;
5120
- if (filters?.kind && entry.kind !== filters.kind) return false;
5121
- return true;
5122
- }).map((entry) => ({
5123
- ...entry,
5124
- summaryMetadata: normalizePersistedSummaryMetadata({
5125
- summaryMetadata: entry.summaryMetadata
5126
- })
5127
- })).sort((a, b) => b.lastUsedAt - a.lastUsedAt);
5128
- }
5129
-
5130
- // src/config/mesh-config.ts
5131
- init_config();
5132
- import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
5133
- import { join as join3 } from "path";
5134
- import { randomUUID as randomUUID3 } from "crypto";
5135
- function getMeshConfigPath() {
5136
- return join3(getConfigDir(), "meshes.json");
5137
- }
5138
- function loadMeshConfig() {
5139
- const path26 = getMeshConfigPath();
5140
- if (!existsSync3(path26)) return { meshes: [] };
5141
- try {
5142
- const raw = JSON.parse(readFileSync2(path26, "utf-8"));
5143
- if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
5144
- return raw;
5145
- } catch {
5146
- return { meshes: [] };
5147
- }
5148
- }
5149
- function saveMeshConfig(config) {
5150
- const path26 = getMeshConfigPath();
5151
- writeFileSync2(path26, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
5152
- }
5153
- function normalizeRepoIdentity(remoteUrl) {
5154
- let identity = remoteUrl.trim();
5155
- if (identity.startsWith("http://") || identity.startsWith("https://")) {
5156
- try {
5157
- const url = new URL(identity);
5158
- const path26 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
5159
- return `${url.hostname}/${path26}`;
5160
- } catch {
5161
- }
5162
- }
5163
- const sshMatch = identity.match(/^(?:ssh:\/\/)?[\w.-]+@([\w.-]+)[:/]([\w.\-/]+?)(?:\.git)?$/);
5164
- if (sshMatch) return `${sshMatch[1]}/${sshMatch[2]}`;
5165
- return identity;
5166
- }
5167
- function listMeshes() {
5168
- return loadMeshConfig().meshes;
5169
- }
5170
- function getMesh(meshId) {
5171
- return loadMeshConfig().meshes.find((m) => m.id === meshId);
5172
- }
5173
- function getMeshByRepo(repoIdentity) {
5174
- return loadMeshConfig().meshes.find((m) => m.repoIdentity === repoIdentity);
5175
- }
5176
- function createMesh(opts) {
5177
- const config = loadMeshConfig();
5178
- if (config.meshes.length >= 20) {
5179
- throw new Error("Maximum 20 meshes allowed");
5180
- }
5181
- const repoIdentity = opts.repoIdentity || (opts.repoRemoteUrl ? normalizeRepoIdentity(opts.repoRemoteUrl) : "");
5182
- if (!repoIdentity) throw new Error("Either repoRemoteUrl or repoIdentity is required");
5183
- const now = (/* @__PURE__ */ new Date()).toISOString();
5184
- const mesh = {
5185
- id: `mesh_${randomUUID3().replace(/-/g, "")}`,
5186
- name: opts.name.trim().slice(0, 100),
5187
- repoIdentity,
5188
- repoRemoteUrl: opts.repoRemoteUrl,
5189
- defaultBranch: opts.defaultBranch,
5190
- policy: { ...DEFAULT_MESH_POLICY, ...opts.policy },
5191
- coordinator: opts.coordinator || {},
5192
- nodes: [],
5193
- createdAt: now,
5194
- updatedAt: now
5195
- };
5196
- config.meshes.push(mesh);
5197
- saveMeshConfig(config);
5198
- return mesh;
5199
- }
5200
- function updateMesh(meshId, opts) {
5201
- const config = loadMeshConfig();
5202
- const mesh = config.meshes.find((m) => m.id === meshId);
5203
- if (!mesh) return void 0;
5204
- if (opts.name !== void 0) mesh.name = opts.name.trim().slice(0, 100);
5205
- if (opts.defaultBranch !== void 0) mesh.defaultBranch = opts.defaultBranch;
5206
- if (opts.policy) mesh.policy = { ...mesh.policy, ...opts.policy };
5207
- if (opts.coordinator) mesh.coordinator = opts.coordinator;
5208
- mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
5209
- saveMeshConfig(config);
5210
- return mesh;
5211
- }
5212
- function deleteMesh(meshId) {
5213
- const config = loadMeshConfig();
5214
- const idx = config.meshes.findIndex((m) => m.id === meshId);
5215
- if (idx === -1) return false;
5216
- config.meshes.splice(idx, 1);
5217
- saveMeshConfig(config);
5218
- return true;
5219
- }
5220
- function addNode(meshId, opts) {
5221
- const config = loadMeshConfig();
5222
- const mesh = config.meshes.find((m) => m.id === meshId);
5223
- if (!mesh) return void 0;
5224
- if (mesh.nodes.length >= 10) {
5225
- throw new Error("Maximum 10 nodes per mesh");
5226
- }
5227
- if (mesh.nodes.some((n) => n.workspace === opts.workspace)) {
5228
- throw new Error("This workspace is already in the mesh");
5229
- }
5230
- const node = {
5231
- id: `node_${randomUUID3().replace(/-/g, "")}`,
5232
- workspace: opts.workspace.trim(),
5233
- repoRoot: opts.repoRoot,
5234
- userOverrides: opts.userOverrides || {},
5235
- policy: opts.policy || {},
5236
- isLocalWorktree: opts.isLocalWorktree
5237
- };
5238
- mesh.nodes.push(node);
5239
- mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
5240
- saveMeshConfig(config);
5241
- return node;
5242
- }
5243
- function removeNode(meshId, nodeId) {
5244
- const config = loadMeshConfig();
5245
- const mesh = config.meshes.find((m) => m.id === meshId);
5246
- if (!mesh) return false;
5247
- const idx = mesh.nodes.findIndex((n) => n.id === nodeId);
5248
- if (idx === -1) return false;
5249
- mesh.nodes.splice(idx, 1);
5250
- mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
5251
- saveMeshConfig(config);
5252
- return true;
5253
- }
5254
- function updateNode(meshId, nodeId, opts) {
5255
- const config = loadMeshConfig();
5256
- const mesh = config.meshes.find((m) => m.id === meshId);
5257
- if (!mesh) return void 0;
5258
- const node = mesh.nodes.find((n) => n.id === nodeId);
5259
- if (!node) return void 0;
5260
- if (opts.userOverrides) node.userOverrides = { ...node.userOverrides, ...opts.userOverrides };
5261
- if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
5262
- mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
5263
- saveMeshConfig(config);
5264
- return node;
5265
- }
5266
-
5267
- // src/mesh/coordinator-prompt.ts
5268
- function buildCoordinatorSystemPrompt(ctx) {
5269
- const { mesh, status, userInstruction } = ctx;
5270
- const sections = [];
5271
- sections.push(`You are a **Repo Mesh Coordinator** \u2014 a technical team lead who orchestrates work across multiple agent sessions on a shared Git repository.
5272
-
5273
- Your mesh: **${mesh.name}**
5274
- Repository: \`${mesh.repoIdentity}\`${mesh.defaultBranch ? `
5275
- Default branch: \`${mesh.defaultBranch}\`` : ""}`);
5276
- if (status?.nodes?.length) {
5277
- sections.push(buildNodeStatusSection(status.nodes));
5278
- } else if (mesh.nodes.length) {
5279
- sections.push(buildNodeConfigSection(mesh));
5280
- } else {
5281
- sections.push("## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`.");
5282
- }
5283
- sections.push(buildPolicySection(mesh.policy));
5284
- sections.push(TOOLS_SECTION);
5285
- sections.push(WORKFLOW_SECTION);
5286
- sections.push(RULES_SECTION);
5287
- if (userInstruction) {
5288
- sections.push(`## Additional Context
5289
- ${userInstruction}`);
5312
+ const forcedInboxBucket = session.inboxBucket === "needs_attention" || session.status === "waiting_approval" ? "needs_attention" : "task_complete";
5313
+ return {
5314
+ unread: true,
5315
+ inboxBucket: forcedInboxBucket
5316
+ };
5290
5317
  }
5291
- if (mesh.coordinator.systemPromptSuffix) {
5292
- sections.push(mesh.coordinator.systemPromptSuffix);
5318
+ if (!currentNotificationId || !dismissedNotificationId || currentNotificationId !== dismissedNotificationId) {
5319
+ return {
5320
+ unread: !!session.unread,
5321
+ inboxBucket: session.inboxBucket || "idle"
5322
+ };
5293
5323
  }
5294
- return sections.join("\n\n");
5324
+ return {
5325
+ unread: false,
5326
+ inboxBucket: "idle"
5327
+ };
5295
5328
  }
5296
- function buildNodeStatusSection(nodes) {
5297
- const lines = ["## Current Node Status", ""];
5298
- for (const n of nodes) {
5299
- const healthIcon = n.health === "online" ? "\u{1F7E2}" : n.health === "dirty" ? "\u{1F7E1}" : n.health === "offline" ? "\u26AB" : "\u{1F534}";
5300
- const sessions = n.activeSessions.length > 0 ? `sessions: ${n.activeSessions.join(", ")}` : "no active sessions";
5301
- const branch = n.git?.branch ? `branch: \`${n.git.branch}\`` : "";
5302
- lines.push(`- ${healthIcon} **${n.machineLabel}** (${n.nodeId})`);
5303
- lines.push(` workspace: \`${n.workspace}\` | ${branch} | ${sessions}`);
5304
- if (n.error) lines.push(` \u26A0\uFE0F ${n.error}`);
5329
+ function markSessionSeen(state, sessionId, seenAt = Date.now(), completionMarker, providerSessionId) {
5330
+ const prev = state.sessionReads || {};
5331
+ const prevMarkers = state.sessionReadMarkers || {};
5332
+ const nextMarker = typeof completionMarker === "string" ? completionMarker : "";
5333
+ const readKeys = Array.from(new Set([
5334
+ sessionId,
5335
+ buildSessionReadStateKey(sessionId, providerSessionId)
5336
+ ].filter(Boolean)));
5337
+ const nextSessionReads = { ...prev };
5338
+ const nextSessionReadMarkers = { ...prevMarkers };
5339
+ const nextSessionNotificationDismissals = { ...state.sessionNotificationDismissals || {} };
5340
+ const nextSessionNotificationUnreadOverrides = { ...state.sessionNotificationUnreadOverrides || {} };
5341
+ for (const key of readKeys) {
5342
+ nextSessionReads[key] = Math.max(prev[key] || 0, seenAt);
5343
+ if (nextMarker) nextSessionReadMarkers[key] = nextMarker;
5344
+ delete nextSessionNotificationDismissals[key];
5345
+ delete nextSessionNotificationUnreadOverrides[key];
5305
5346
  }
5306
- return lines.join("\n");
5347
+ return {
5348
+ ...state,
5349
+ sessionReads: nextSessionReads,
5350
+ sessionReadMarkers: nextMarker ? nextSessionReadMarkers : prevMarkers,
5351
+ sessionNotificationDismissals: nextSessionNotificationDismissals,
5352
+ sessionNotificationUnreadOverrides: nextSessionNotificationUnreadOverrides
5353
+ };
5307
5354
  }
5308
- function buildNodeConfigSection(mesh) {
5309
- const lines = ["## Configured Nodes", ""];
5310
- for (const n of mesh.nodes) {
5311
- const labels = [];
5312
- if (n.isLocalWorktree) labels.push("worktree");
5313
- if (n.policy.readOnly) labels.push("read-only");
5314
- const suffix = labels.length ? ` [${labels.join(", ")}]` : "";
5315
- lines.push(`- **${n.workspace}** (${n.id})${suffix}`);
5355
+
5356
+ // src/config/saved-sessions.ts
5357
+ import * as path6 from "path";
5358
+ var MAX_SAVED_SESSIONS = 500;
5359
+ function normalizeWorkspace2(workspace) {
5360
+ if (!workspace) return "";
5361
+ try {
5362
+ return path6.resolve(expandPath(workspace));
5363
+ } catch {
5364
+ return path6.resolve(workspace);
5316
5365
  }
5317
- lines.push("", "_Use `mesh_status` to probe live health before delegating work._");
5318
- return lines.join("\n");
5319
5366
  }
5320
- function buildPolicySection(policy) {
5321
- const rules = [];
5322
- if (policy.requirePreTaskCheckpoint) rules.push("- Create a git checkpoint **before** starting each task");
5323
- if (policy.requirePostTaskCheckpoint) rules.push("- Create a git checkpoint **after** each task completes");
5324
- if (policy.requireApprovalForPush) rules.push("- **Ask for user approval** before pushing to remote");
5325
- if (policy.requireApprovalForDestructiveGit) rules.push("- **Ask for user approval** before destructive git operations (force push, reset, etc.)");
5326
- const dirtyBehavior = {
5327
- block: "- **Do not** send tasks to nodes with dirty workspaces",
5328
- warn: "- Warn the user if a node has uncommitted changes before sending a task",
5329
- checkpoint_then_continue: "- Auto-checkpoint dirty nodes before sending tasks"
5330
- }[policy.dirtyWorkspaceBehavior] || "";
5331
- if (dirtyBehavior) rules.push(dirtyBehavior);
5332
- rules.push(`- Maximum **${policy.maxParallelTasks}** tasks running in parallel`);
5333
- return `## Policy
5334
- ${rules.join("\n")}`;
5367
+ function buildSavedProviderSessionKey(providerSessionId) {
5368
+ return `saved:${providerSessionId.trim()}`;
5369
+ }
5370
+ function upsertSavedProviderSession(state, entry) {
5371
+ const providerSessionId = typeof entry.providerSessionId === "string" ? entry.providerSessionId.trim() : "";
5372
+ if (!providerSessionId) return state;
5373
+ const id = buildSavedProviderSessionKey(providerSessionId);
5374
+ const existing = (state.savedProviderSessions || []).find((item) => item.id === id);
5375
+ const nextEntry = {
5376
+ id,
5377
+ kind: entry.kind,
5378
+ providerType: entry.providerType,
5379
+ providerName: entry.providerName,
5380
+ providerSessionId,
5381
+ workspace: entry.workspace ? normalizeWorkspace2(entry.workspace) : void 0,
5382
+ summaryMetadata: normalizePersistedSummaryMetadata({
5383
+ summaryMetadata: entry.summaryMetadata
5384
+ }),
5385
+ title: entry.title,
5386
+ createdAt: existing?.createdAt || entry.createdAt || Date.now(),
5387
+ lastUsedAt: entry.lastUsedAt || Date.now()
5388
+ };
5389
+ const filtered = (state.savedProviderSessions || []).filter((item) => item.id !== id);
5390
+ return {
5391
+ ...state,
5392
+ savedProviderSessions: [nextEntry, ...filtered].slice(0, MAX_SAVED_SESSIONS)
5393
+ };
5394
+ }
5395
+ function getSavedProviderSessions(state, filters) {
5396
+ return [...state.savedProviderSessions || []].filter((entry) => {
5397
+ if (filters?.providerType && entry.providerType !== filters.providerType) return false;
5398
+ if (filters?.kind && entry.kind !== filters.kind) return false;
5399
+ return true;
5400
+ }).map((entry) => ({
5401
+ ...entry,
5402
+ summaryMetadata: normalizePersistedSummaryMetadata({
5403
+ summaryMetadata: entry.summaryMetadata
5404
+ })
5405
+ })).sort((a, b) => b.lastUsedAt - a.lastUsedAt);
5335
5406
  }
5336
- var TOOLS_SECTION = `## Available Tools
5337
-
5338
- | Tool | Purpose |
5339
- |------|---------|
5340
- | \`mesh_status\` | Check all nodes' health, git state, and active sessions |
5341
- | \`mesh_list_nodes\` | List nodes with workspace paths |
5342
- | \`mesh_launch_session\` | Start a new agent session on a node |
5343
- | \`mesh_send_task\` | Send a task (natural language) to a running agent |
5344
- | \`mesh_read_chat\` | Read an agent's recent messages to check progress |
5345
- | \`mesh_git_status\` | Check git status on a specific node |
5346
- | \`mesh_checkpoint\` | Create a git checkpoint on a node |
5347
- | \`mesh_approve\` | Approve/reject a pending agent action |`;
5348
- var WORKFLOW_SECTION = `## Orchestration Workflow
5349
-
5350
- 1. **Assess** \u2014 Call \`mesh_status\` to see which nodes are healthy and available.
5351
- 2. **Plan** \u2014 Decompose the user's request into independent tasks for parallel execution, or sequential tasks when dependencies exist.
5352
- 3. **Delegate** \u2014 For each task:
5353
- a. Pick the best node (consider: health, dirty state, current workload).
5354
- b. If no session exists, call \`mesh_launch_session\` to start one.
5355
- c. Call \`mesh_send_task\` with a clear, self-contained natural-language instruction.
5356
- 4. **Monitor** \u2014 Periodically call \`mesh_read_chat\` to check progress. Handle approvals via \`mesh_approve\`.
5357
- 5. **Verify** \u2014 When a task reports completion, call \`mesh_git_status\` to verify changes were made.
5358
- 6. **Checkpoint** \u2014 Call \`mesh_checkpoint\` to save the work.
5359
- 7. **Report** \u2014 Summarize what was done, what changed, and any issues.`;
5360
- var RULES_SECTION = `## Rules
5361
5407
 
5362
- - **Be conversational.** Delegate work the way a tech lead would \u2014 clear, specific instructions in natural language.
5363
- - **Don't inspect code.** Trust the agent's output. Verify via git diff/status, not by reading source files.
5364
- - **Don't over-parallelize.** Start with 1-2 concurrent tasks. Scale up if they succeed.
5365
- - **Handle failures gracefully.** If a task fails, read the chat to understand why, then retry or reassign.
5366
- - **Keep the user informed.** Report progress after each delegation round.
5367
- - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
5368
- - **Never fabricate tool results.** Always call the actual tool; never pretend you did.`;
5408
+ // src/index.ts
5409
+ init_mesh_config();
5410
+ init_coordinator_prompt();
5369
5411
 
5370
5412
  // src/mesh/mesh-sync.ts
5413
+ init_mesh_config();
5371
5414
  async function syncMeshes(transport) {
5372
5415
  const result = { pushed: 0, pulled: 0, deleted: 0, errors: [] };
5373
5416
  let remoteMeshes;
@@ -17301,6 +17344,8 @@ var KNOWN_PROVIDER_FIELDS = /* @__PURE__ */ new Set([
17301
17344
  "type",
17302
17345
  "name",
17303
17346
  "category",
17347
+ "transcriptAuthority",
17348
+ "transcriptContext",
17304
17349
  "aliases",
17305
17350
  "cdpPorts",
17306
17351
  "targetFilter",
@@ -17345,6 +17390,7 @@ var KNOWN_PROVIDER_FIELDS = /* @__PURE__ */ new Set([
17345
17390
  "staticConfigOptions",
17346
17391
  "spawnArgBuilder",
17347
17392
  "auth",
17393
+ "meshCoordinator",
17348
17394
  "contractVersion",
17349
17395
  "capabilities",
17350
17396
  "providerVersion",
@@ -17402,6 +17448,7 @@ function validateProviderDefinition(raw) {
17402
17448
  }
17403
17449
  validateCapabilities(provider, controls, errors);
17404
17450
  validateCanonicalHistory(provider.canonicalHistory, errors);
17451
+ validateMeshCoordinator(provider.meshCoordinator, errors);
17405
17452
  for (const control of controls) {
17406
17453
  validateControl(control, errors);
17407
17454
  }
@@ -17492,6 +17539,60 @@ function validateCanonicalHistory(raw, errors) {
17492
17539
  }
17493
17540
  }
17494
17541
  }
17542
+ function validateMeshCoordinator(raw, errors) {
17543
+ if (raw === void 0) return;
17544
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
17545
+ errors.push("meshCoordinator must be an object");
17546
+ return;
17547
+ }
17548
+ const meshCoordinator = raw;
17549
+ if (typeof meshCoordinator.supported !== "boolean") {
17550
+ errors.push("meshCoordinator.supported must be boolean");
17551
+ }
17552
+ if (meshCoordinator.reason !== void 0 && (typeof meshCoordinator.reason !== "string" || !meshCoordinator.reason.trim())) {
17553
+ errors.push("meshCoordinator.reason must be a non-empty string when provided");
17554
+ }
17555
+ const mcpConfig = meshCoordinator.mcpConfig;
17556
+ if (mcpConfig === void 0) return;
17557
+ if (!mcpConfig || typeof mcpConfig !== "object" || Array.isArray(mcpConfig)) {
17558
+ errors.push("meshCoordinator.mcpConfig must be an object");
17559
+ return;
17560
+ }
17561
+ const config = mcpConfig;
17562
+ const mode = config.mode;
17563
+ if (!["auto_import", "manual", "none"].includes(String(mode))) {
17564
+ errors.push("meshCoordinator.mcpConfig.mode must be one of: auto_import, manual, none");
17565
+ }
17566
+ const format = config.format;
17567
+ if (format !== void 0 && !["claude_mcp_json", "hermes_config_yaml"].includes(String(format))) {
17568
+ errors.push("meshCoordinator.mcpConfig.format must be one of: claude_mcp_json, hermes_config_yaml");
17569
+ }
17570
+ for (const key of ["path", "serverName", "configPathCommand", "instructions", "template"]) {
17571
+ const value = config[key];
17572
+ if (value !== void 0 && (typeof value !== "string" || !value.trim())) {
17573
+ errors.push(`meshCoordinator.mcpConfig.${key} must be a non-empty string when provided`);
17574
+ }
17575
+ }
17576
+ if (config.requiresRestart !== void 0 && typeof config.requiresRestart !== "boolean") {
17577
+ errors.push("meshCoordinator.mcpConfig.requiresRestart must be boolean when provided");
17578
+ }
17579
+ if (mode === "auto_import") {
17580
+ if (format === void 0) {
17581
+ errors.push("meshCoordinator.mcpConfig.format is required for auto_import MCP setup");
17582
+ }
17583
+ if (typeof config.path !== "string" || !config.path.trim()) {
17584
+ errors.push("meshCoordinator.mcpConfig.path is required for auto_import MCP setup");
17585
+ }
17586
+ }
17587
+ if (mode === "manual") {
17588
+ if (typeof config.instructions !== "string" || !config.instructions.trim()) {
17589
+ errors.push("meshCoordinator.mcpConfig.instructions is required for manual MCP setup");
17590
+ }
17591
+ if (typeof config.template !== "string" || !config.template.trim()) {
17592
+ errors.push("meshCoordinator.mcpConfig.template is required for manual MCP setup");
17593
+ }
17594
+ }
17595
+ }
17495
17596
  function validateControl(control, errors) {
17496
17597
  if (!control || typeof control !== "object") {
17497
17598
  errors.push("controls: each control must be an object");
@@ -19647,6 +19748,69 @@ cleanOldFiles();
19647
19748
  // src/commands/router.ts
19648
19749
  init_logger();
19649
19750
 
19751
+ // src/commands/mesh-coordinator.ts
19752
+ import { join as join17 } from "path";
19753
+ var DEFAULT_SERVER_NAME = "adhdev-mesh";
19754
+ var DEFAULT_ADHDEV_MCP_COMMAND = "adhdev-mcp";
19755
+ function resolveMeshCoordinatorSetup(options) {
19756
+ const { provider, meshId, workspace } = options;
19757
+ const config = provider?.meshCoordinator;
19758
+ if (!config?.supported) {
19759
+ return {
19760
+ kind: "unsupported",
19761
+ reason: config?.reason || "Provider does not declare Repo Mesh coordinator support"
19762
+ };
19763
+ }
19764
+ const mcpConfig = config.mcpConfig;
19765
+ if (!mcpConfig || mcpConfig.mode === "none") {
19766
+ return {
19767
+ kind: "unsupported",
19768
+ reason: config.reason || "Provider does not declare a usable Repo Mesh MCP configuration mode"
19769
+ };
19770
+ }
19771
+ const serverName = mcpConfig.serverName?.trim() || DEFAULT_SERVER_NAME;
19772
+ if (mcpConfig.mode === "auto_import") {
19773
+ const path26 = mcpConfig.path?.trim();
19774
+ if (!path26) {
19775
+ return { kind: "unsupported", reason: "Provider auto-import MCP config is missing a config path" };
19776
+ }
19777
+ return {
19778
+ kind: "auto_import",
19779
+ serverName,
19780
+ configPath: join17(workspace, path26),
19781
+ configFormat: mcpConfig.format
19782
+ };
19783
+ }
19784
+ if (mcpConfig.mode === "manual") {
19785
+ const instructions = mcpConfig.instructions?.trim();
19786
+ const template = mcpConfig.template;
19787
+ if (!instructions || !template?.trim()) {
19788
+ return { kind: "unsupported", reason: "Provider manual MCP setup is missing instructions or template" };
19789
+ }
19790
+ return {
19791
+ kind: "manual",
19792
+ serverName,
19793
+ configFormat: mcpConfig.format,
19794
+ configPathCommand: mcpConfig.configPathCommand,
19795
+ requiresRestart: mcpConfig.requiresRestart === true,
19796
+ instructions,
19797
+ template: renderMeshCoordinatorTemplate(template, {
19798
+ meshId,
19799
+ workspace,
19800
+ serverName,
19801
+ adhdevMcpCommand: options.adhdevMcpCommand || DEFAULT_ADHDEV_MCP_COMMAND
19802
+ })
19803
+ };
19804
+ }
19805
+ return {
19806
+ kind: "unsupported",
19807
+ reason: `Unsupported Repo Mesh MCP configuration mode: ${String(mcpConfig.mode)}`
19808
+ };
19809
+ }
19810
+ function renderMeshCoordinatorTemplate(template, values) {
19811
+ return template.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g, (_, key) => values[key] || "");
19812
+ }
19813
+
19650
19814
  // src/status/snapshot.ts
19651
19815
  init_config();
19652
19816
  import * as os17 from "os";
@@ -19698,7 +19862,8 @@ function buildAvailableProviders(providerLoader) {
19698
19862
  ...provider.enabled !== void 0 ? { enabled: provider.enabled } : {},
19699
19863
  ...provider.machineStatus !== void 0 ? { machineStatus: provider.machineStatus } : {},
19700
19864
  ...provider.lastDetection !== void 0 ? { lastDetection: provider.lastDetection } : {},
19701
- ...provider.lastVerification !== void 0 ? { lastVerification: provider.lastVerification } : {}
19865
+ ...provider.lastVerification !== void 0 ? { lastVerification: provider.lastVerification } : {},
19866
+ ...provider.meshCoordinator !== void 0 ? { meshCoordinator: provider.meshCoordinator } : {}
19702
19867
  }));
19703
19868
  }
19704
19869
  function buildMachineInfo(profile = "full") {
@@ -21023,6 +21188,178 @@ var DaemonCommandRouter = class {
21023
21188
  updateConfig({ machineNickname: nickname || null });
21024
21189
  return { success: true };
21025
21190
  }
21191
+ // ─── Mesh CRUD (local meshes.json) ───
21192
+ case "list_meshes": {
21193
+ try {
21194
+ const { listMeshes: listMeshes2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21195
+ return { success: true, meshes: listMeshes2() };
21196
+ } catch (e) {
21197
+ return { success: false, error: e.message };
21198
+ }
21199
+ }
21200
+ case "get_mesh": {
21201
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
21202
+ if (!meshId) return { success: false, error: "meshId required" };
21203
+ try {
21204
+ const { getMesh: getMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21205
+ const mesh = getMesh3(meshId);
21206
+ if (!mesh) return { success: false, error: "Mesh not found" };
21207
+ return { success: true, mesh };
21208
+ } catch (e) {
21209
+ return { success: false, error: e.message };
21210
+ }
21211
+ }
21212
+ case "create_mesh": {
21213
+ const name = typeof args?.name === "string" ? args.name.trim() : "";
21214
+ const repoIdentity = typeof args?.repoIdentity === "string" ? args.repoIdentity.trim() : "";
21215
+ const repoRemoteUrl = typeof args?.repoRemoteUrl === "string" ? args.repoRemoteUrl.trim() : void 0;
21216
+ const defaultBranch = typeof args?.defaultBranch === "string" ? args.defaultBranch.trim() : void 0;
21217
+ if (!name) return { success: false, error: "name required" };
21218
+ try {
21219
+ const { createMesh: createMesh2 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21220
+ const mesh = createMesh2({ name, repoIdentity, repoRemoteUrl, defaultBranch });
21221
+ return { success: true, mesh };
21222
+ } catch (e) {
21223
+ return { success: false, error: e.message };
21224
+ }
21225
+ }
21226
+ case "delete_mesh": {
21227
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
21228
+ if (!meshId) return { success: false, error: "meshId required" };
21229
+ try {
21230
+ const { deleteMesh: deleteMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21231
+ const deleted = deleteMesh3(meshId);
21232
+ return { success: true, deleted };
21233
+ } catch (e) {
21234
+ return { success: false, error: e.message };
21235
+ }
21236
+ }
21237
+ case "add_mesh_node": {
21238
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
21239
+ const workspace = typeof args?.workspace === "string" ? args.workspace.trim() : "";
21240
+ if (!meshId) return { success: false, error: "meshId required" };
21241
+ if (!workspace) return { success: false, error: "workspace required" };
21242
+ try {
21243
+ const { addNode: addNode3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21244
+ const node = addNode3(meshId, { workspace });
21245
+ if (!node) return { success: false, error: "Mesh not found" };
21246
+ return { success: true, node };
21247
+ } catch (e) {
21248
+ return { success: false, error: e.message };
21249
+ }
21250
+ }
21251
+ case "remove_mesh_node": {
21252
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
21253
+ const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
21254
+ if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
21255
+ try {
21256
+ const { removeNode: removeNode3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21257
+ const removed = removeNode3(meshId, nodeId);
21258
+ return { success: true, removed };
21259
+ } catch (e) {
21260
+ return { success: false, error: e.message };
21261
+ }
21262
+ }
21263
+ // ─── Mesh Coordinator Launch ───
21264
+ case "launch_mesh_coordinator": {
21265
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
21266
+ const cliType = typeof args?.cliType === "string" ? args.cliType.trim() : "claude-cli";
21267
+ if (!meshId) return { success: false, error: "meshId required" };
21268
+ try {
21269
+ const { getMesh: getMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21270
+ const { buildCoordinatorSystemPrompt: buildCoordinatorSystemPrompt2 } = await Promise.resolve().then(() => (init_coordinator_prompt(), coordinator_prompt_exports));
21271
+ const mesh = getMesh3(meshId);
21272
+ if (!mesh) return { success: false, error: "Mesh not found" };
21273
+ if (mesh.nodes.length === 0) return { success: false, error: "No nodes in mesh" };
21274
+ const workspace = mesh.nodes[0].workspace;
21275
+ const providerMeta = this.deps.providerLoader.resolve?.(cliType) || this.deps.providerLoader.getMeta(cliType);
21276
+ const coordinatorSetup = resolveMeshCoordinatorSetup({
21277
+ provider: providerMeta,
21278
+ meshId,
21279
+ workspace
21280
+ });
21281
+ if (coordinatorSetup.kind === "unsupported") {
21282
+ return {
21283
+ success: false,
21284
+ code: "mesh_coordinator_unsupported",
21285
+ error: coordinatorSetup.reason,
21286
+ meshId,
21287
+ cliType,
21288
+ workspace
21289
+ };
21290
+ }
21291
+ if (coordinatorSetup.kind === "manual") {
21292
+ return {
21293
+ success: false,
21294
+ code: "mesh_coordinator_manual_mcp_setup_required",
21295
+ error: coordinatorSetup.instructions,
21296
+ meshId,
21297
+ cliType,
21298
+ workspace,
21299
+ meshCoordinatorSetup: coordinatorSetup
21300
+ };
21301
+ }
21302
+ if (coordinatorSetup.configFormat !== "claude_mcp_json") {
21303
+ return {
21304
+ success: false,
21305
+ code: "mesh_coordinator_unsupported",
21306
+ error: `Unsupported auto-import MCP config format: ${String(coordinatorSetup.configFormat)}`,
21307
+ meshId,
21308
+ cliType,
21309
+ workspace
21310
+ };
21311
+ }
21312
+ const { existsSync: existsSync21, readFileSync: readFileSync15, writeFileSync: writeFileSync12, copyFileSync: copyFileSync3 } = await import("fs");
21313
+ const mcpConfigPath = coordinatorSetup.configPath;
21314
+ const hadExistingMcpConfig = existsSync21(mcpConfigPath);
21315
+ let existingMcpConfig = {};
21316
+ if (hadExistingMcpConfig) {
21317
+ try {
21318
+ existingMcpConfig = JSON.parse(readFileSync15(mcpConfigPath, "utf-8"));
21319
+ copyFileSync3(mcpConfigPath, mcpConfigPath + ".backup");
21320
+ } catch {
21321
+ }
21322
+ }
21323
+ const mcpConfig = {
21324
+ ...existingMcpConfig,
21325
+ mcpServers: {
21326
+ ...existingMcpConfig.mcpServers || {},
21327
+ [coordinatorSetup.serverName]: {
21328
+ command: "adhdev-mcp",
21329
+ args: ["--repo-mesh", meshId]
21330
+ }
21331
+ }
21332
+ };
21333
+ writeFileSync12(mcpConfigPath, JSON.stringify(mcpConfig, null, 2), "utf-8");
21334
+ LOG.info("MeshCoordinator", `Wrote ${mcpConfigPath} with ${coordinatorSetup.serverName} server`);
21335
+ let systemPrompt = "";
21336
+ try {
21337
+ systemPrompt = buildCoordinatorSystemPrompt2({ mesh });
21338
+ } catch {
21339
+ systemPrompt = `You are a Repo Mesh Coordinator for "${mesh.name}". Use the adhdev-mesh MCP tools (mesh_status, mesh_list_nodes, mesh_send_task, mesh_read_chat, mesh_launch_session, etc.) to orchestrate work across ${mesh.nodes.length} node(s).`;
21340
+ }
21341
+ const launchResult = await this.deps.cliManager.handleCliCommand("launch_cli", {
21342
+ cliType,
21343
+ dir: workspace,
21344
+ initialPrompt: systemPrompt
21345
+ });
21346
+ if (!launchResult?.success) {
21347
+ return { success: false, error: launchResult?.error || "Failed to launch CLI session" };
21348
+ }
21349
+ LOG.info("MeshCoordinator", `Launched ${cliType} coordinator for mesh ${meshId} in ${workspace}`);
21350
+ return {
21351
+ success: true,
21352
+ meshId,
21353
+ cliType,
21354
+ workspace,
21355
+ sessionId: launchResult.sessionId || launchResult.id,
21356
+ mcpConfigWritten: true
21357
+ };
21358
+ } catch (e) {
21359
+ LOG.error("MeshCoordinator", `Failed: ${e.message}`);
21360
+ return { success: false, error: e.message };
21361
+ }
21362
+ }
21026
21363
  default:
21027
21364
  break;
21028
21365
  }