agent-space-manager 0.0.0-stage → 1.0.0

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/manager.mjs ADDED
@@ -0,0 +1,4428 @@
1
+ // D:\Software\Magpie\agent-space-manager\manager.mjs
2
+ // Central Agent Space Management Engine for Magpie
3
+ // Cross-platform, zero-hardcoded path detection for open-source GitHub distribution.
4
+
5
+ import fs from "fs";
6
+ import path from "path";
7
+ import os from "os";
8
+ import http from "node:http";
9
+ import net from "node:net";
10
+ import { createHash } from "node:crypto";
11
+ import { spawn, execSync, execFileSync, execFile, exec } from "child_process";
12
+ import {
13
+ AGENT_PROFILES,
14
+ inferAgentType,
15
+ listAgentProfilesForUi,
16
+ getHomeDir,
17
+ getAppDataDir,
18
+ expandHomePath,
19
+ } from "./agents.mjs";
20
+ import {
21
+ getStateDir,
22
+ loadOwnershipState,
23
+ saveOwnershipState,
24
+ deleteOwnershipState,
25
+ listAllOwnershipStates,
26
+ isTargetInsideHub,
27
+ isAsmOwnedDirectory,
28
+ materializeSkillDir,
29
+ materializePluginBundle,
30
+ syncPluginBundles,
31
+ collectEnabledComponents,
32
+ syncFlattenedSkills,
33
+ syncSkillSlashCommands,
34
+ syncJsonMcpServers,
35
+ syncTomlMcpServers,
36
+ syncMarkdownRulesBlock,
37
+ syncOwnedFiles,
38
+ syncJsonHooks,
39
+ writeHubCommunicationFiles,
40
+ ensureGitInfoExclude,
41
+ parseMarkdownFrontmatter,
42
+ } from "./adapters.mjs";
43
+ import {
44
+ resolveEffectiveAgentPaths,
45
+ resolveEffectiveProjectPaths,
46
+ } from "./agents.mjs";
47
+
48
+ export {
49
+ AGENT_PROFILES,
50
+ inferAgentType,
51
+ listAgentProfilesForUi,
52
+ expandHomePath,
53
+ deleteOwnershipState,
54
+ listAllOwnershipStates,
55
+ writeHubCommunicationFiles,
56
+ resolveEffectiveAgentPaths,
57
+ resolveEffectiveProjectPaths,
58
+ };
59
+
60
+ export function stripBom(str) {
61
+ if (typeof str !== "string") return "";
62
+ return str.charCodeAt(0) === 0xFEFF ? str.slice(1) : str;
63
+ }
64
+
65
+ /**
66
+ * Resolves the Hub root dynamically:
67
+ * 1. Environment variables AGENT_TOOLS_ROOT or AI_WORKSPACE_DIR
68
+ * 2. Fallback to ~/AI-Agent-Space (or D:\Software\AI Agent Space if present on host)
69
+ */
70
+ export function resolveHubRoot() {
71
+ if (process.env.AGENT_TOOLS_ROOT && fs.existsSync(process.env.AGENT_TOOLS_ROOT)) {
72
+ return path.resolve(process.env.AGENT_TOOLS_ROOT);
73
+ }
74
+ if (process.env.AI_WORKSPACE_DIR && fs.existsSync(process.env.AI_WORKSPACE_DIR)) {
75
+ return path.resolve(process.env.AI_WORKSPACE_DIR);
76
+ }
77
+ const home = getHomeDir();
78
+ const homeHub = path.join(home, "AI-Agent-Space");
79
+ if (fs.existsSync(homeHub)) {
80
+ return homeHub;
81
+ }
82
+ if (!process.env.ASM_HOME_OVERRIDE && process.platform === "win32") {
83
+ try {
84
+ if (fs.existsSync("D:\\Software\\AI Agent Space")) {
85
+ return "D:\\Software\\AI Agent Space";
86
+ }
87
+ } catch {}
88
+ }
89
+ return homeHub;
90
+ }
91
+
92
+ export const DEFAULT_HUB_ROOT = resolveHubRoot();
93
+ export const DEFAULT_CONFIG_FILE = path.join(DEFAULT_HUB_ROOT, "hub-config.json");
94
+
95
+ /**
96
+ * Ensures a directory exists synchronously
97
+ */
98
+ export function ensureDir(dirPath) {
99
+ if (dirPath && !fs.existsSync(dirPath)) {
100
+ fs.mkdirSync(dirPath, { recursive: true });
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Dynamically detects the accurate configuration / plugin / skill link directory
106
+ * for any given Agent IDE or binary across Windows, macOS, and Linux.
107
+ * Delegates to the canonical AGENT_PROFILES registry.
108
+ */
109
+ export function detectAgentConfigPath(name = "", exePath = "") {
110
+ const home = getHomeDir();
111
+ const appData = getAppDataDir(home);
112
+ const agentType = inferAgentType(name, exePath);
113
+
114
+ if (agentType === "opencode" && exePath && fs.existsSync(exePath)) {
115
+ try {
116
+ let cliExe = exePath;
117
+ if (exePath.endsWith("OpenCode.exe") || exePath.endsWith("OpenCode")) {
118
+ const siblingCli = path.join(path.dirname(exePath), "resources", "opencode-cli.exe");
119
+ if (fs.existsSync(siblingCli)) cliExe = siblingCli;
120
+ }
121
+ const out = execSync(`"${cliExe}" debug paths 2>nul`, { encoding: "utf8" });
122
+ for (const line of out.split("\n")) {
123
+ if (line.trim().startsWith("config")) {
124
+ const parts = line.trim().split(/\s+/);
125
+ if (parts[1]) {
126
+ return path.join(parts.slice(1).join(" "), "skills");
127
+ }
128
+ }
129
+ }
130
+ } catch {}
131
+ }
132
+
133
+ const profile = AGENT_PROFILES[agentType] || AGENT_PROFILES.custom;
134
+ const resolved = profile.resolvePaths(home, appData, name);
135
+ return resolved.primary;
136
+ }
137
+
138
+ /**
139
+ * Infers a clean IDE name directly from the executable name.
140
+ * Avoids substring collision bugs (e.g. opencode contains "code").
141
+ */
142
+ export function inferNameFromExe(filePath) {
143
+ if (!filePath) return "Agent";
144
+ const base = path.basename(String(filePath).replace(/\\/g, "/")).replace(/\.(exe|lnk|app|cmd|bat)$/i, "");
145
+ const lower = base.toLowerCase();
146
+
147
+ if (lower === "opencode" || lower.startsWith("opencode")) return "OpenCode";
148
+ if (lower === "codex" || lower.startsWith("codex")) return "Codex CLI";
149
+ if (lower === "code" || lower === "vscode" || lower === "visualstudiocode") return "VS Code";
150
+ if (lower === "cursor") return "Cursor";
151
+ if (lower === "windsurf") return "Windsurf";
152
+ if (lower === "agy" || lower.includes("antigravity")) return "Antigravity";
153
+ if (lower === "gemini" || lower === "gemini-cli") return "Gemini CLI";
154
+ if (lower === "claude") return "Claude Code";
155
+ if (lower === "cline") return "Cline";
156
+ if (lower === "roo" || lower === "roo-code") return "Roo Code";
157
+ if (lower === "kiro") return "Kiro";
158
+ if (lower === "vscodium" || lower === "codium") return "VSCodium";
159
+ if (lower === "zed") return "Zed";
160
+
161
+ return base.charAt(0).toUpperCase() + base.slice(1);
162
+ }
163
+
164
+ /**
165
+ * Resolves a Windows shortcut (.lnk) to its real target path.
166
+ */
167
+ export function resolveShortcutTarget(lnkPath) {
168
+ if (process.platform !== "win32") return lnkPath;
169
+ try {
170
+ const escaped = lnkPath.replace(/'/g, "''");
171
+ const psCmd = `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; (New-Object -ComObject WScript.Shell).CreateShortcut('${escaped}').TargetPath`;
172
+ const target = execFileSync("powershell", ["-NoProfile", "-Command", psCmd], { encoding: "utf8" }).trim();
173
+ if (target && fs.existsSync(target)) return target;
174
+ } catch {}
175
+ return lnkPath;
176
+ }
177
+
178
+ /**
179
+ * Searches Desktop, Start Menu, LocalAppData, and standard directories
180
+ * for a dropped executable or shortcut when the browser sandbox omits the absolute path.
181
+ */
182
+ export function findFileOnSystem(fileName) {
183
+ if (!fileName) return null;
184
+ const userProfile = getHomeDir();
185
+ const localAppData = process.env.LOCALAPPDATA || path.join(userProfile, "AppData", "Local");
186
+ const appData = getAppDataDir(userProfile);
187
+
188
+ const cleanName = path.basename(fileName).trim().replace(/^["']|["']$/g, "");
189
+ const baseNoExt = cleanName.replace(/\.(exe|lnk|cmd|bat)$/i, "").toLowerCase();
190
+
191
+ if (baseNoExt.includes("opencode")) {
192
+ const candidates = [
193
+ path.join(localAppData, "Programs", "ai.opencode.desktop", "OpenCode.exe"),
194
+ path.join(userProfile, "Desktop", "OpenCode.lnk"),
195
+ path.join(userProfile, "OneDrive", "Desktop", "OpenCode.lnk"),
196
+ path.join(appData, "Microsoft", "Windows", "Start Menu", "Programs", "OpenCode.lnk"),
197
+ ];
198
+ for (const c of candidates) {
199
+ if (fs.existsSync(c)) {
200
+ return c.toLowerCase().endsWith(".lnk") ? resolveShortcutTarget(c) : c;
201
+ }
202
+ }
203
+ }
204
+
205
+ if (baseNoExt === "code" || baseNoExt.includes("vscode")) {
206
+ const candidates = [
207
+ path.join(localAppData, "Programs", "Microsoft VS Code", "Code.exe"),
208
+ "C:\\Program Files\\Microsoft VS Code\\Code.exe",
209
+ path.join(userProfile, "Desktop", "Visual Studio Code.lnk"),
210
+ path.join(userProfile, "OneDrive", "Desktop", "Visual Studio Code.lnk"),
211
+ ];
212
+ for (const c of candidates) {
213
+ if (fs.existsSync(c)) {
214
+ return c.toLowerCase().endsWith(".lnk") ? resolveShortcutTarget(c) : c;
215
+ }
216
+ }
217
+ }
218
+
219
+ if (baseNoExt.includes("cursor")) {
220
+ const c = path.join(localAppData, "Programs", "cursor", "Cursor.exe");
221
+ if (fs.existsSync(c)) return c;
222
+ }
223
+
224
+ if (baseNoExt.includes("windsurf")) {
225
+ const c = path.join(localAppData, "Programs", "Windsurf", "Windsurf.exe");
226
+ if (fs.existsSync(c)) return c;
227
+ }
228
+
229
+ if (baseNoExt.includes("agy") || baseNoExt.includes("antigravity")) {
230
+ const c = path.join(userProfile, ".gemini", "bin", "agy.cmd");
231
+ if (fs.existsSync(c)) return c;
232
+ }
233
+
234
+ const searchNames = [cleanName];
235
+ if (!cleanName.includes(".")) {
236
+ searchNames.push(`${cleanName}.exe`, `${cleanName}.lnk`);
237
+ }
238
+
239
+ const directDirs = [
240
+ path.join(userProfile, "Desktop"),
241
+ path.join(userProfile, "OneDrive", "Desktop"),
242
+ "C:\\Users\\Public\\Desktop",
243
+ path.join(appData, "Microsoft", "Windows", "Start Menu", "Programs"),
244
+ "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs",
245
+ path.join(localAppData, "Programs"),
246
+ ];
247
+
248
+ for (const dir of directDirs) {
249
+ if (!fs.existsSync(dir)) continue;
250
+ for (const sName of searchNames) {
251
+ const candidate = path.join(dir, sName);
252
+ try {
253
+ if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
254
+ return candidate.toLowerCase().endsWith(".lnk") ? resolveShortcutTarget(candidate) : candidate;
255
+ }
256
+ } catch {}
257
+ }
258
+ }
259
+
260
+ const deepDirs = [
261
+ path.join(localAppData, "Programs"),
262
+ path.join(appData, "Microsoft", "Windows", "Start Menu", "Programs"),
263
+ path.join(userProfile, "Desktop"),
264
+ path.join(userProfile, "OneDrive", "Desktop"),
265
+ ];
266
+
267
+ for (const root of deepDirs) {
268
+ if (!fs.existsSync(root)) continue;
269
+ try {
270
+ const stack = [root];
271
+ while (stack.length > 0) {
272
+ const curr = stack.pop();
273
+ const entries = fs.readdirSync(curr, { withFileTypes: true });
274
+ for (const e of entries) {
275
+ const full = path.join(curr, e.name);
276
+ if (e.isDirectory()) {
277
+ if (!e.name.startsWith(".") && e.name !== "node_modules") {
278
+ stack.push(full);
279
+ }
280
+ } else if (e.isFile()) {
281
+ const eLower = e.name.toLowerCase();
282
+ for (const sName of searchNames) {
283
+ if (eLower === sName.toLowerCase()) {
284
+ return full.toLowerCase().endsWith(".lnk") ? resolveShortcutTarget(full) : full;
285
+ }
286
+ }
287
+ }
288
+ }
289
+ }
290
+ } catch {}
291
+ }
292
+
293
+ try {
294
+ const out = execFileSync("where.exe", [cleanName], { encoding: "utf8" }).trim();
295
+ const firstLine = out.split("\n")[0]?.trim();
296
+ if (firstLine && fs.existsSync(firstLine) && fs.statSync(firstLine).isFile()) {
297
+ return firstLine;
298
+ }
299
+ } catch {}
300
+
301
+ return null;
302
+ }
303
+
304
+ /**
305
+ * Searches common workspace drives and folders for a project directory
306
+ * when the browser sandbox omits the absolute folder path.
307
+ */
308
+ export function findFolderOnSystem(folderName) {
309
+ if (!folderName) return null;
310
+ const clean = path.basename(folderName).trim().replace(/^["']|["']$/g, "").toLowerCase();
311
+ const userProfile = getHomeDir();
312
+ const hubParent = path.dirname(resolveHubRoot());
313
+
314
+ const searchRoots = [
315
+ hubParent,
316
+ path.join(userProfile, "Projects"),
317
+ path.join(userProfile, "source", "repos"),
318
+ path.join(userProfile, "Desktop"),
319
+ path.join(userProfile, "OneDrive", "Desktop"),
320
+ path.join(userProfile, "Downloads"),
321
+ ].filter(Boolean);
322
+
323
+ for (const root of searchRoots) {
324
+ if (!fs.existsSync(root)) continue;
325
+
326
+ const direct = path.join(root, folderName);
327
+ try {
328
+ if (fs.existsSync(direct) && fs.statSync(direct).isDirectory()) {
329
+ return direct;
330
+ }
331
+ } catch {}
332
+
333
+ try {
334
+ const queue = [{ dir: root, depth: 1 }];
335
+ while (queue.length > 0) {
336
+ const { dir, depth } = queue.shift();
337
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
338
+ for (const e of entries) {
339
+ if (!e.isDirectory() || e.name.startsWith(".") || e.name === "node_modules" || e.name === "$RECYCLE.BIN") continue;
340
+ const full = path.join(dir, e.name);
341
+ if (e.name.toLowerCase() === clean) {
342
+ return full;
343
+ }
344
+ if (depth < 3) {
345
+ queue.push({ dir: full, depth: depth + 1 });
346
+ }
347
+ }
348
+ }
349
+ } catch {}
350
+ }
351
+ return null;
352
+ }
353
+
354
+ /**
355
+ * Resolves a dropped file/folder name or raw path into its real, absolute filesystem target,
356
+ * resolving .lnk shortcuts and extracting clean IDE / project names.
357
+ */
358
+ export function resolveDroppedTarget(rawNameOrPath, mode = "ide") {
359
+ if (!rawNameOrPath) return { success: false, error: "Empty path" };
360
+ let clean = rawNameOrPath.trim().replace(/^["']|["']$/g, "");
361
+
362
+ if (mode === "ide") {
363
+ let candidatePath = clean;
364
+ let found = null;
365
+ if (fs.existsSync(candidatePath) && fs.statSync(candidatePath).isFile()) {
366
+ found = candidatePath;
367
+ } else {
368
+ found = findFileOnSystem(clean);
369
+ }
370
+
371
+ if (!found) {
372
+ return { success: false, error: `Could not find executable for '${clean}' on system` };
373
+ }
374
+
375
+ let realExe = found;
376
+ if (found.toLowerCase().endsWith(".lnk")) {
377
+ realExe = resolveShortcutTarget(found);
378
+ }
379
+
380
+ const name = inferNameFromExe(realExe);
381
+ const agentType = inferAgentType(name, realExe);
382
+ const configPath = detectAgentConfigPath(name, realExe);
383
+
384
+ return {
385
+ success: true,
386
+ realPath: realExe,
387
+ name,
388
+ agentType,
389
+ configPath,
390
+ isShortcut: found.toLowerCase().endsWith(".lnk"),
391
+ };
392
+ }
393
+
394
+ if (mode === "project") {
395
+ let candidateFolder = clean;
396
+ let found = null;
397
+ if (fs.existsSync(candidateFolder) && fs.statSync(candidateFolder).isDirectory()) {
398
+ found = candidateFolder;
399
+ } else {
400
+ found = findFolderOnSystem(clean);
401
+ }
402
+
403
+ if (!found) {
404
+ return { success: false, error: `Could not find project directory for '${clean}' on system` };
405
+ }
406
+
407
+ return {
408
+ success: true,
409
+ realPath: found,
410
+ name: path.basename(found),
411
+ };
412
+ }
413
+
414
+ return { success: false, error: "Unknown mode" };
415
+ }
416
+
417
+ /**
418
+ * Opens native Windows file or folder dialog asynchronously and resolves the chosen target.
419
+ */
420
+ export function browseFileSystem(type = "file") {
421
+ if (process.platform !== "win32") {
422
+ return Promise.resolve({ cancelled: true, error: "Native dialog only supported on Windows" });
423
+ }
424
+
425
+ return new Promise((resolve) => {
426
+ let psScript = "";
427
+ if (type === "folder" || type === "directory") {
428
+ psScript = `
429
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
430
+ $app = New-Object -ComObject Shell.Application
431
+ $folder = $app.BrowseForFolder(0, "Select Folder", 0x50, 0)
432
+ if ($folder) {
433
+ Write-Output $folder.Self.Path
434
+ }
435
+ `;
436
+ } else {
437
+ psScript = `
438
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
439
+ Add-Type -AssemblyName System.Windows.Forms
440
+ $dialog = New-Object System.Windows.Forms.OpenFileDialog
441
+ $dialog.Filter = "Agent Executables & Shortcuts (*.exe;*.lnk)|*.exe;*.lnk|All Files (*.*)|*.*"
442
+ $dialog.Title = "Select Agent Executable or Shortcut"
443
+ $dialog.ShowHelp = $false
444
+ $dialog.RestoreDirectory = $true
445
+ if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
446
+ Write-Output $dialog.FileName
447
+ }
448
+ `;
449
+ }
450
+
451
+ const b64 = Buffer.from(psScript, "utf16le").toString("base64");
452
+ execFile(
453
+ "powershell.exe",
454
+ ["-NoProfile", "-OutputFormat", "Text", "-STA", "-EncodedCommand", b64],
455
+ { encoding: "utf8", timeout: 60000 },
456
+ (err, stdout) => {
457
+ if (err) {
458
+ return resolve({ cancelled: true, error: err.message });
459
+ }
460
+ const cleaned = stdout.replace(/#< CLIXML[\s\S]*?<\/Objs>/g, "").trim();
461
+ if (!cleaned) {
462
+ return resolve({ cancelled: true });
463
+ }
464
+
465
+ if (type === "folder" || type === "directory") {
466
+ return resolve({
467
+ cancelled: false,
468
+ realPath: cleaned,
469
+ name: path.basename(cleaned),
470
+ });
471
+ }
472
+
473
+ let realExe = cleaned;
474
+ if (cleaned.toLowerCase().endsWith(".lnk")) {
475
+ realExe = resolveShortcutTarget(cleaned);
476
+ }
477
+ const name = inferNameFromExe(realExe);
478
+ const agentType = inferAgentType(name, realExe);
479
+ const configPath = detectAgentConfigPath(name, realExe);
480
+
481
+ return resolve({
482
+ cancelled: false,
483
+ realPath: realExe,
484
+ name,
485
+ agentType,
486
+ configPath,
487
+ });
488
+ }
489
+ );
490
+ });
491
+ }
492
+
493
+ /**
494
+ * Normalizes and migrates an IDE configuration entry so `agentType` is always populated
495
+ * and leading `~` / `$HOME` / `%USERPROFILE%` paths are expanded to real OS paths.
496
+ */
497
+ export function normalizeIdeEntry(ide) {
498
+ if (!ide || typeof ide !== "object") return ide;
499
+ const agentType = inferAgentType(ide);
500
+ const rawConfigPath = ide.configPath || detectAgentConfigPath(agentType, ide.exePath || "");
501
+ let configPath = expandHomePath(rawConfigPath);
502
+
503
+ if (agentType === "antigravity" && configPath) {
504
+ const base = path.basename(configPath).toLowerCase();
505
+ const parentBase = path.basename(path.dirname(configPath)).toLowerCase();
506
+ if (base === "config" && parentBase === ".gemini") {
507
+ configPath = path.join(configPath, "plugins");
508
+ } else if (base === ".gemini") {
509
+ configPath = path.join(configPath, "config", "plugins");
510
+ }
511
+ } else if (agentType === "opencode" && configPath) {
512
+ const base = path.basename(configPath).toLowerCase();
513
+ if (base === "opencode") {
514
+ configPath = path.join(configPath, "skills");
515
+ }
516
+ }
517
+
518
+ const exePath = ide.exePath ? expandHomePath(ide.exePath) : ide.exePath || "";
519
+ const componentPaths = ide.componentPaths && typeof ide.componentPaths === "object"
520
+ ? { ...ide.componentPaths }
521
+ : {};
522
+ for (const [k, v] of Object.entries(componentPaths)) {
523
+ if (typeof v === "string" && v.trim()) {
524
+ componentPaths[k] = expandHomePath(v.trim());
525
+ }
526
+ }
527
+
528
+ return {
529
+ ...ide,
530
+ agentType,
531
+ exePath,
532
+ configPath,
533
+ componentPaths,
534
+ enabled: ide.enabled !== false,
535
+ plugins: ide.plugins && typeof ide.plugins === "object" ? ide.plugins : {},
536
+ };
537
+ }
538
+
539
+ /**
540
+ * Loads hub configuration or returns default structure
541
+ */
542
+ export function loadHubConfig(configFile = null) {
543
+ const effectiveFile = configFile || path.join(resolveHubRoot(), "hub-config.json");
544
+ try {
545
+ if (fs.existsSync(effectiveFile)) {
546
+ const data = fs.readFileSync(effectiveFile, "utf8");
547
+ const parsed = JSON.parse(data);
548
+ if (Array.isArray(parsed.ides)) {
549
+ parsed.ides = parsed.ides.map(normalizeIdeEntry);
550
+ } else {
551
+ const defaultHome = getHomeDir();
552
+ parsed.ides = [
553
+ normalizeIdeEntry({
554
+ id: "antigravity",
555
+ name: "Antigravity (Google Gemini)",
556
+ agentType: "antigravity",
557
+ exePath: path.join(defaultHome, ".gemini", "bin", process.platform === "win32" ? "agy.cmd" : "agy"),
558
+ configPath: detectAgentConfigPath("antigravity"),
559
+ enabled: true,
560
+ plugins: {},
561
+ }),
562
+ ];
563
+ }
564
+ if (!Array.isArray(parsed.projects)) {
565
+ parsed.projects = [];
566
+ }
567
+ if (!parsed.hubRoot || parsed.hubRoot.trim() === "") {
568
+ parsed.hubRoot = resolveHubRoot();
569
+ }
570
+ parsed.defaultHubRoot = resolveHubRoot();
571
+ return parsed;
572
+ }
573
+ } catch (err) {
574
+ console.error("Failed to read hub-config.json:", err);
575
+ }
576
+
577
+ const defaultHome = getHomeDir();
578
+ const defaultHub = resolveHubRoot();
579
+ return {
580
+ hubRoot: defaultHub,
581
+ defaultHubRoot: defaultHub,
582
+ smartMiddleware: {
583
+ enabled: true,
584
+ maxTools: 96,
585
+ autoFilter: true,
586
+ logFailures: true,
587
+ },
588
+ ides: [
589
+ {
590
+ id: "antigravity",
591
+ name: "Antigravity (Google Gemini)",
592
+ agentType: "antigravity",
593
+ exePath: path.join(defaultHome, ".gemini", "bin", process.platform === "win32" ? "agy.cmd" : "agy"),
594
+ configPath: detectAgentConfigPath("antigravity"),
595
+ enabled: true,
596
+ plugins: {},
597
+ },
598
+ ],
599
+ projects: [],
600
+ };
601
+ }
602
+
603
+ /**
604
+ * Deduplicates an array of IDE entries in-place, merging component selections
605
+ * and ensuring only one canonical entry exists per agent type or config path.
606
+ *
607
+ * @param {Array<object>} ides - Array of IDE configuration entries.
608
+ * @returns {Array<object>} Deduplicated array of normalized IDE entries.
609
+ */
610
+ export function deduplicateIdes(ides = []) {
611
+ if (!Array.isArray(ides)) return [];
612
+ const seenIds = new Set();
613
+ const seenTargets = new Set();
614
+ const result = [];
615
+
616
+ for (const raw of ides) {
617
+ if (!raw) continue;
618
+ const ide = normalizeIdeEntry(raw);
619
+ const idKey = ide.id;
620
+ const normConfig = ide.configPath ? path.resolve(expandHomePath(ide.configPath)) : "";
621
+ const targetKey = `${ide.agentType}::${normConfig}`;
622
+
623
+ const existing = result.find((item) => {
624
+ if (item.id === idKey) return true;
625
+ if (idKey && item.id && (item.id.replace(/-\d{10,}$/, "") === idKey.replace(/-\d{10,}$/, ""))) return true;
626
+ if (normConfig && item.agentType === ide.agentType) {
627
+ const itemConfig = item.configPath ? path.resolve(expandHomePath(item.configPath)) : "";
628
+ if (itemConfig === normConfig) return true;
629
+ }
630
+ return false;
631
+ });
632
+
633
+ if (existing) {
634
+ // Merge preferences into canonical entry
635
+ existing.plugins = { ...(existing.plugins || {}), ...(ide.plugins || {}) };
636
+ if (ide.componentPaths) {
637
+ existing.componentPaths = { ...(existing.componentPaths || {}), ...ide.componentPaths };
638
+ }
639
+ if (ide.exePath && !existing.exePath) existing.exePath = ide.exePath;
640
+ if (ide.name && (!existing.name || existing.name === existing.id)) existing.name = ide.name;
641
+ continue;
642
+ }
643
+
644
+ seenIds.add(idKey);
645
+ if (normConfig) seenTargets.add(targetKey);
646
+ result.push(ide);
647
+ }
648
+ return result;
649
+ }
650
+
651
+ /**
652
+ * Saves hub configuration to file (UTF-8 without BOM) with automated IDE deduplication.
653
+ */
654
+ export function saveHubConfig(config, configFile = null) {
655
+ const effectiveFile = configFile || path.join(resolveHubRoot(), "hub-config.json");
656
+ if (config && Array.isArray(config.ides)) {
657
+ config.ides = deduplicateIdes(config.ides);
658
+ }
659
+ ensureDir(path.dirname(effectiveFile));
660
+ fs.writeFileSync(effectiveFile, JSON.stringify(config, null, 2), "utf8");
661
+ }
662
+
663
+ /**
664
+ * Recursively lists files in a directory up to maxDepth with relative paths.
665
+ */
666
+ export function listFilesRecursiveRel(dir, baseDir = dir, maxDepth = 4, depth = 0) {
667
+ if (depth > maxDepth || !fs.existsSync(dir)) return [];
668
+ const results = [];
669
+ try {
670
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
671
+ for (const e of entries) {
672
+ if (e.name.startsWith(".git") || e.name === "node_modules") continue;
673
+ const full = path.join(dir, e.name);
674
+ const rel = path.relative(baseDir, full).replace(/\\/g, "/");
675
+ let isDir = false;
676
+ try {
677
+ isDir = e.isDirectory() || (e.isSymbolicLink() && fs.statSync(full).isDirectory());
678
+ } catch {}
679
+
680
+ if (isDir) {
681
+ const sub = listFilesRecursiveRel(full, baseDir, maxDepth, depth + 1);
682
+ results.push(...sub);
683
+ } else {
684
+ try {
685
+ const stats = fs.statSync(full);
686
+ results.push({ name: e.name, relPath: rel, size: stats.size, mtime: Math.round(stats.mtimeMs) });
687
+ } catch {
688
+ results.push({ name: e.name, relPath: rel, size: 0, mtime: 0 });
689
+ }
690
+ }
691
+ }
692
+ } catch {}
693
+ return results;
694
+ }
695
+
696
+ /**
697
+ * Builds a comprehensive categorized registry of Plugins, MCPs, Hooks, Skills, Agents, and Rules.
698
+ */
699
+ export function buildCategoriesRegistry(plugins = [], hubRoot = "") {
700
+ const categories = {
701
+ plugins: [],
702
+ mcps: [],
703
+ hooks: [],
704
+ skills: [],
705
+ agents: [],
706
+ rules: [],
707
+ };
708
+
709
+ const seenSkills = new Set();
710
+ const seenMcps = new Set();
711
+ const seenHooks = new Set();
712
+ const seenAgents = new Set();
713
+ const seenRules = new Set();
714
+
715
+ for (const p of plugins) {
716
+ categories.plugins.push({
717
+ id: p.id,
718
+ name: p.name,
719
+ version: p.version,
720
+ path: p.path,
721
+ description: p.description,
722
+ skillsCount: (p.skills || []).length,
723
+ filesCount: (p.files || []).length,
724
+ hasMcp: p.hasMcp,
725
+ hasHooks: p.hasHooks,
726
+ });
727
+
728
+ for (const s of p.skills || []) {
729
+ if (!seenSkills.has(s)) {
730
+ seenSkills.add(s);
731
+ categories.skills.push({
732
+ name: s,
733
+ pluginId: p.id,
734
+ pluginName: p.name,
735
+ sourcePath: p.isRootSkills ? path.join(p.path, s) : path.join(p.path, "skills", s),
736
+ });
737
+ }
738
+ }
739
+
740
+ for (const m of p.mcps || []) {
741
+ if (!seenMcps.has(m)) {
742
+ seenMcps.add(m);
743
+ categories.mcps.push({
744
+ name: m,
745
+ pluginId: p.id,
746
+ pluginName: p.name,
747
+ sourcePath: path.join(p.path, "mcp_config.json"),
748
+ });
749
+ }
750
+ }
751
+
752
+ if (p.hasHooks) {
753
+ const hookId = `${p.id}-hooks`;
754
+ if (!seenHooks.has(hookId)) {
755
+ seenHooks.add(hookId);
756
+ categories.hooks.push({
757
+ name: `${p.name} Hooks`,
758
+ pluginId: p.id,
759
+ pluginName: p.name,
760
+ sourcePath: path.join(p.path, "hooks.json"),
761
+ });
762
+ }
763
+ }
764
+
765
+ for (const a of p.agents || []) {
766
+ if (!seenAgents.has(a)) {
767
+ seenAgents.add(a);
768
+ categories.agents.push({
769
+ name: a,
770
+ pluginId: p.id,
771
+ pluginName: p.name,
772
+ sourcePath: path.join(p.path, "agents", a),
773
+ });
774
+ }
775
+ }
776
+
777
+ for (const r of p.rules || []) {
778
+ if (!seenRules.has(r)) {
779
+ seenRules.add(r);
780
+ categories.rules.push({
781
+ name: r,
782
+ pluginId: p.id,
783
+ pluginName: p.name,
784
+ sourcePath: path.join(p.path, "rules", r),
785
+ });
786
+ }
787
+ }
788
+ }
789
+
790
+ if (hubRoot && fs.existsSync(hubRoot)) {
791
+ const rootAgentsDir = path.join(hubRoot, "agents");
792
+ if (fs.existsSync(rootAgentsDir)) {
793
+ try {
794
+ for (const a of fs.readdirSync(rootAgentsDir)) {
795
+ if (a.endsWith(".md") && !seenAgents.has(a)) {
796
+ seenAgents.add(a);
797
+ categories.agents.push({
798
+ name: a,
799
+ pluginId: "root",
800
+ pluginName: "Root Agents",
801
+ sourcePath: path.join(rootAgentsDir, a),
802
+ });
803
+ }
804
+ }
805
+ } catch {}
806
+ }
807
+
808
+ const rootRulesDir = path.join(hubRoot, "rules");
809
+ if (fs.existsSync(rootRulesDir)) {
810
+ try {
811
+ for (const r of fs.readdirSync(rootRulesDir)) {
812
+ if (r.endsWith(".md") && !seenRules.has(r)) {
813
+ seenRules.add(r);
814
+ categories.rules.push({
815
+ name: r,
816
+ pluginId: "root",
817
+ pluginName: "Root Rules",
818
+ sourcePath: path.join(rootRulesDir, r),
819
+ });
820
+ }
821
+ }
822
+ } catch {}
823
+ }
824
+ }
825
+
826
+ return categories;
827
+ }
828
+
829
+ /**
830
+ * Scans plugins directory for all standard plugin packages and root standalone components.
831
+ */
832
+ export function scanPlugins(hubRoot = resolveHubRoot()) {
833
+ if (!hubRoot || typeof hubRoot !== "string") return [];
834
+ const cleanHub = expandHomePath(hubRoot.trim());
835
+ if (!cleanHub || !fs.existsSync(cleanHub)) return [];
836
+
837
+ const rootManifestPath = path.join(cleanHub, "plugin.json");
838
+ const rootSkillMdPath = path.join(cleanHub, "SKILL.md");
839
+ const hasDirectPluginsFolder = fs.existsSync(path.join(cleanHub, "plugins"));
840
+
841
+ // 1. Single plugin or standalone skill package directly at hubRoot
842
+ if (!hasDirectPluginsFolder && (fs.existsSync(rootManifestPath) || fs.existsSync(rootSkillMdPath))) {
843
+ const entryName = path.basename(cleanHub);
844
+ let manifest = { name: entryName, version: "1.0.0", description: "" };
845
+ if (fs.existsSync(rootManifestPath)) {
846
+ try {
847
+ const raw = fs.readFileSync(rootManifestPath, "utf8");
848
+ manifest = JSON.parse(stripBom(raw));
849
+ } catch {
850
+ manifest.description = "Invalid plugin.json";
851
+ }
852
+ }
853
+ const hasMcp = fs.existsSync(path.join(cleanHub, "mcp_config.json"));
854
+ const hasHooks = fs.existsSync(path.join(cleanHub, "hooks.json"));
855
+
856
+ let mcps = [];
857
+ if (hasMcp) {
858
+ try {
859
+ const raw = fs.readFileSync(path.join(cleanHub, "mcp_config.json"), "utf8");
860
+ const mcpData = JSON.parse(stripBom(raw));
861
+ if (mcpData.mcpServers) mcps = Object.keys(mcpData.mcpServers);
862
+ } catch {}
863
+ if (mcps.length === 0) mcps = [entryName];
864
+ }
865
+
866
+ let hooks = [];
867
+ if (hasHooks) {
868
+ try {
869
+ const raw = fs.readFileSync(path.join(cleanHub, "hooks.json"), "utf8");
870
+ const hookData = JSON.parse(stripBom(raw));
871
+ if (Array.isArray(hookData)) hooks = hookData;
872
+ else if (hookData.hooks) hooks = Object.keys(hookData.hooks);
873
+ } catch {}
874
+ if (hooks.length === 0) hooks = ["smart-tools"];
875
+ }
876
+
877
+ const skillsDir = path.join(cleanHub, "skills");
878
+ const skills = [];
879
+ if (fs.existsSync(skillsDir)) {
880
+ try {
881
+ for (const s of fs.readdirSync(skillsDir, { withFileTypes: true })) {
882
+ let isDir = false;
883
+ try {
884
+ isDir = s.isDirectory() || (s.isSymbolicLink() && fs.statSync(path.join(skillsDir, s.name)).isDirectory());
885
+ } catch {}
886
+ if (isDir) skills.push(s.name);
887
+ }
888
+ } catch {}
889
+ } else if (fs.existsSync(rootSkillMdPath)) {
890
+ skills.push(entryName);
891
+ }
892
+
893
+ const rulesDir = path.join(cleanHub, "rules");
894
+ const rules = [];
895
+ if (fs.existsSync(rulesDir)) {
896
+ try {
897
+ for (const r of fs.readdirSync(rulesDir, { withFileTypes: true })) {
898
+ if (r.isFile() && r.name.endsWith(".md")) rules.push(r.name);
899
+ }
900
+ } catch {}
901
+ }
902
+
903
+ const agentsDir = path.join(cleanHub, "agents");
904
+ const agents = [];
905
+ if (fs.existsSync(agentsDir)) {
906
+ try {
907
+ for (const a of fs.readdirSync(agentsDir, { withFileTypes: true })) {
908
+ if (a.isFile() && a.name.endsWith(".md")) agents.push(a.name);
909
+ }
910
+ } catch {}
911
+ }
912
+
913
+ const files = listFilesRecursiveRel(cleanHub, cleanHub);
914
+ return [
915
+ {
916
+ id: entryName,
917
+ name: manifest.name || entryName,
918
+ version: manifest.version || "1.0.0",
919
+ description: manifest.description || "",
920
+ path: cleanHub,
921
+ upstream: manifest.upstream || (typeof manifest.repository === "string" ? manifest.repository : manifest.repository?.url) || manifest.homepage || manifest.url || manifest.source || null,
922
+ hasMcp,
923
+ hasHooks,
924
+ mcps,
925
+ hooks,
926
+ skills,
927
+ rules,
928
+ agents,
929
+ files,
930
+ },
931
+ ];
932
+ }
933
+
934
+ // 2. Direct standalone skills directory (e.g. user typed a path to a skills folder)
935
+ if (!hasDirectPluginsFolder && path.basename(cleanHub).toLowerCase() === "skills") {
936
+ const rootSkills = [];
937
+ try {
938
+ for (const se of fs.readdirSync(cleanHub, { withFileTypes: true })) {
939
+ let isDir = false;
940
+ try {
941
+ isDir = se.isDirectory() || (se.isSymbolicLink() && fs.statSync(path.join(cleanHub, se.name)).isDirectory());
942
+ } catch {}
943
+ if (isDir) rootSkills.push(se.name);
944
+ }
945
+ } catch {}
946
+ if (rootSkills.length > 0) {
947
+ const rootSkillFiles = listFilesRecursiveRel(cleanHub, cleanHub);
948
+ return [
949
+ {
950
+ id: "workspace-skills",
951
+ name: "Workspace Skills",
952
+ version: "1.0.0",
953
+ description: `Standalone skills collection (${rootSkills.length} skills)`,
954
+ path: cleanHub,
955
+ isRootSkills: true,
956
+ hasMcp: false,
957
+ hasHooks: false,
958
+ mcps: [],
959
+ hooks: [],
960
+ skills: rootSkills,
961
+ rules: [],
962
+ agents: [],
963
+ files: rootSkillFiles,
964
+ },
965
+ ];
966
+ }
967
+ }
968
+
969
+ // 3. Multi-plugin directory with plugins/ subfolder or direct plugin subdirectories
970
+ let pluginsDir = path.join(cleanHub, "plugins");
971
+ let isDirectHub = false;
972
+ if (!fs.existsSync(pluginsDir)) {
973
+ if (fs.existsSync(cleanHub)) {
974
+ try {
975
+ const sub = fs.readdirSync(cleanHub);
976
+ const hasManifest = sub.some((name) => {
977
+ const itemPath = path.join(cleanHub, name);
978
+ try {
979
+ if (!fs.statSync(itemPath).isDirectory()) return false;
980
+ return (
981
+ fs.existsSync(path.join(itemPath, "plugin.json")) ||
982
+ fs.existsSync(path.join(itemPath, "SKILL.md")) ||
983
+ fs.existsSync(path.join(itemPath, "skills")) ||
984
+ fs.existsSync(path.join(itemPath, "rules")) ||
985
+ fs.existsSync(path.join(itemPath, "agents")) ||
986
+ fs.existsSync(path.join(itemPath, "mcp_config.json"))
987
+ );
988
+ } catch {
989
+ return false;
990
+ }
991
+ });
992
+ if (hasManifest) {
993
+ pluginsDir = cleanHub;
994
+ isDirectHub = true;
995
+ } else if (!fs.existsSync(path.join(cleanHub, "skills"))) {
996
+ return [];
997
+ }
998
+ } catch {
999
+ return [];
1000
+ }
1001
+ } else {
1002
+ return [];
1003
+ }
1004
+ }
1005
+
1006
+ let entries = [];
1007
+ try {
1008
+ if (fs.existsSync(pluginsDir)) {
1009
+ entries = fs.readdirSync(pluginsDir);
1010
+ }
1011
+ } catch {
1012
+ entries = [];
1013
+ }
1014
+ const plugins = [];
1015
+
1016
+ for (const entryName of entries) {
1017
+ const pluginDir = path.join(pluginsDir, entryName);
1018
+ try {
1019
+ if (!fs.statSync(pluginDir).isDirectory()) continue;
1020
+ } catch {
1021
+ continue;
1022
+ }
1023
+ const manifestPath = path.join(pluginDir, "plugin.json");
1024
+
1025
+ let manifest = { name: entryName, version: "1.0.0", description: "" };
1026
+ if (fs.existsSync(manifestPath)) {
1027
+ try {
1028
+ const raw = fs.readFileSync(manifestPath, "utf8");
1029
+ manifest = JSON.parse(stripBom(raw));
1030
+ } catch {
1031
+ manifest.description = "Invalid plugin.json";
1032
+ }
1033
+ } else {
1034
+ const hasSkills = fs.existsSync(path.join(pluginDir, "skills"));
1035
+ const hasRules = fs.existsSync(path.join(pluginDir, "rules"));
1036
+ const hasMcp = fs.existsSync(path.join(pluginDir, "mcp_config.json"));
1037
+ if (!hasSkills && !hasRules && !hasMcp) continue;
1038
+ }
1039
+
1040
+ const hasMcp = fs.existsSync(path.join(pluginDir, "mcp_config.json"));
1041
+ const hasHooks = fs.existsSync(path.join(pluginDir, "hooks.json"));
1042
+
1043
+ let mcps = [];
1044
+ if (hasMcp) {
1045
+ try {
1046
+ const raw = fs.readFileSync(path.join(pluginDir, "mcp_config.json"), "utf8");
1047
+ const mcpData = JSON.parse(stripBom(raw));
1048
+ if (mcpData.mcpServers) mcps = Object.keys(mcpData.mcpServers);
1049
+ } catch {}
1050
+ if (mcps.length === 0) mcps = [entryName];
1051
+ }
1052
+
1053
+ let hooks = [];
1054
+ if (hasHooks) {
1055
+ try {
1056
+ const raw = fs.readFileSync(path.join(pluginDir, "hooks.json"), "utf8");
1057
+ const hookData = JSON.parse(stripBom(raw));
1058
+ if (Array.isArray(hookData)) hooks = hookData;
1059
+ else if (hookData.hooks) hooks = Object.keys(hookData.hooks);
1060
+ } catch {}
1061
+ if (hooks.length === 0) hooks = ["smart-tools"];
1062
+ }
1063
+
1064
+ const skillsDir = path.join(pluginDir, "skills");
1065
+ const skills = [];
1066
+ if (fs.existsSync(skillsDir)) {
1067
+ try {
1068
+ for (const s of fs.readdirSync(skillsDir, { withFileTypes: true })) {
1069
+ let isDir = false;
1070
+ try {
1071
+ isDir = s.isDirectory() || (s.isSymbolicLink() && fs.statSync(path.join(skillsDir, s.name)).isDirectory());
1072
+ } catch {}
1073
+ if (isDir) skills.push(s.name);
1074
+ }
1075
+ } catch {}
1076
+ }
1077
+
1078
+ const rulesDir = path.join(pluginDir, "rules");
1079
+ const rules = [];
1080
+ if (fs.existsSync(rulesDir)) {
1081
+ try {
1082
+ for (const r of fs.readdirSync(rulesDir, { withFileTypes: true })) {
1083
+ if (r.isFile() && r.name.endsWith(".md")) rules.push(r.name);
1084
+ }
1085
+ } catch {}
1086
+ }
1087
+
1088
+ const agentsDir = path.join(pluginDir, "agents");
1089
+ const agents = [];
1090
+ if (fs.existsSync(agentsDir)) {
1091
+ try {
1092
+ for (const a of fs.readdirSync(agentsDir, { withFileTypes: true })) {
1093
+ if (a.isFile() && a.name.endsWith(".md")) agents.push(a.name);
1094
+ }
1095
+ } catch {}
1096
+ }
1097
+
1098
+ const files = listFilesRecursiveRel(pluginDir, pluginDir);
1099
+
1100
+ plugins.push({
1101
+ id: entryName,
1102
+ name: manifest.name || entryName,
1103
+ version: manifest.version || "1.0.0",
1104
+ description: manifest.description || "",
1105
+ path: pluginDir,
1106
+ upstream: manifest.upstream || (typeof manifest.repository === "string" ? manifest.repository : manifest.repository?.url) || manifest.homepage || manifest.url || manifest.source || null,
1107
+ hasMcp,
1108
+ hasHooks,
1109
+ mcps,
1110
+ hooks,
1111
+ skills,
1112
+ rules,
1113
+ agents,
1114
+ files,
1115
+ });
1116
+ }
1117
+
1118
+ // Also discover standalone root skills/ if present (e.g. <hubRoot>/skills),
1119
+ // excluding duplicates that already belong to a discovered plugin in <hubRoot>/plugins/*.
1120
+ if (pluginsDir !== cleanHub || !isDirectHub) {
1121
+ const rootSkillsDir = path.join(cleanHub, "skills");
1122
+ if (fs.existsSync(rootSkillsDir)) {
1123
+ try {
1124
+ const pluginSkillSet = new Set(plugins.flatMap((p) => p.skills || []));
1125
+ const rootSkills = [];
1126
+ for (const se of fs.readdirSync(rootSkillsDir, { withFileTypes: true })) {
1127
+ if (pluginSkillSet.has(se.name)) continue;
1128
+ let isDir = false;
1129
+ try {
1130
+ isDir = se.isDirectory() || (se.isSymbolicLink() && fs.statSync(path.join(rootSkillsDir, se.name)).isDirectory());
1131
+ } catch {}
1132
+ if (isDir) rootSkills.push(se.name);
1133
+ }
1134
+ if (rootSkills.length > 0) {
1135
+ const rootSkillFiles = listFilesRecursiveRel(rootSkillsDir, rootSkillsDir);
1136
+ plugins.push({
1137
+ id: "workspace-skills",
1138
+ name: "Workspace Skills (Root Hub)",
1139
+ version: "1.0.0",
1140
+ description: `Standalone skills collection (${rootSkills.length} skills) located in root skills/ folder`,
1141
+ path: rootSkillsDir,
1142
+ isRootSkills: true,
1143
+ hasMcp: false,
1144
+ hasHooks: false,
1145
+ mcps: [],
1146
+ hooks: [],
1147
+ skills: rootSkills,
1148
+ rules: [],
1149
+ agents: [],
1150
+ files: rootSkillFiles,
1151
+ });
1152
+ }
1153
+ } catch {}
1154
+ }
1155
+ }
1156
+
1157
+ return plugins;
1158
+ }
1159
+
1160
+ /**
1161
+ * Safely creates a directory junction (Windows) or symlink (macOS/Linux).
1162
+ * Refuses to delete any real, user-owned directory or file at `linkPath`.
1163
+ */
1164
+ export function createJunction(sourcePath, linkPath) {
1165
+ try {
1166
+ if (!sourcePath || !fs.existsSync(sourcePath)) {
1167
+ return { success: false, error: `Source path does not exist: ${sourcePath}` };
1168
+ }
1169
+
1170
+ if (path.resolve(sourcePath) === path.resolve(linkPath)) {
1171
+ return { success: true, message: "Source and link path are identical" };
1172
+ }
1173
+
1174
+ try {
1175
+ const stats = fs.lstatSync(linkPath);
1176
+ if (stats.isSymbolicLink()) {
1177
+ try {
1178
+ const currentTarget = fs.readlinkSync(linkPath);
1179
+ if (path.resolve(currentTarget) === path.resolve(sourcePath)) {
1180
+ return { success: true, message: "Link already exists and is correct" };
1181
+ }
1182
+ } catch {}
1183
+ removeJunction(linkPath);
1184
+ } else {
1185
+ // Real directory or file exists at linkPath — NEVER delete user-owned data!
1186
+ return {
1187
+ success: false,
1188
+ error: `Conflict: user-owned directory or file already exists at ${linkPath}`,
1189
+ };
1190
+ }
1191
+ } catch {
1192
+ // linkPath doesn't exist yet, proceed
1193
+ }
1194
+
1195
+ ensureDir(path.dirname(linkPath));
1196
+ if (process.platform === "win32") {
1197
+ execSync(`cmd.exe /c mklink /J "${linkPath}" "${sourcePath}"`, { stdio: "pipe" });
1198
+ } else {
1199
+ fs.symlinkSync(sourcePath, linkPath, "dir");
1200
+ }
1201
+ return { success: true };
1202
+ } catch (err) {
1203
+ return { success: false, error: err.message };
1204
+ }
1205
+ }
1206
+
1207
+ /**
1208
+ * Safely removes a directory junction or symlink without touching target files
1209
+ * and without deleting real directories.
1210
+ */
1211
+ export function removeJunction(linkPath) {
1212
+ try {
1213
+ let stats;
1214
+ try {
1215
+ stats = fs.lstatSync(linkPath);
1216
+ } catch {
1217
+ return { success: true }; // does not exist
1218
+ }
1219
+
1220
+ if (stats.isSymbolicLink()) {
1221
+ if (process.platform === "win32") {
1222
+ try {
1223
+ execSync(`cmd.exe /c rmdir "${linkPath}"`, { stdio: "pipe" });
1224
+ return { success: true };
1225
+ } catch {
1226
+ try {
1227
+ fs.unlinkSync(linkPath);
1228
+ return { success: true };
1229
+ } catch {}
1230
+ }
1231
+ } else {
1232
+ fs.unlinkSync(linkPath);
1233
+ return { success: true };
1234
+ }
1235
+ } else {
1236
+ return {
1237
+ success: false,
1238
+ error: `Refusing to remove non-symlink path: ${linkPath}`,
1239
+ };
1240
+ }
1241
+ } catch (err) {
1242
+ return { success: false, error: err.message };
1243
+ }
1244
+ return { success: true };
1245
+ }
1246
+
1247
+ /**
1248
+ * Helper to filter previously owned files belonging to a specific target directory and optional file suffix.
1249
+ */
1250
+ function filterOwnedFilesForSpec(allFiles = [], spec) {
1251
+ if (!spec) return [];
1252
+ const dir = path.resolve(typeof spec === "string" ? spec : spec.dir);
1253
+ const suffix = typeof spec === "object" && spec.suffix ? spec.suffix.toLowerCase() : null;
1254
+ return (allFiles || []).filter((f) => {
1255
+ const res = path.resolve(f);
1256
+ if (path.dirname(res) !== dir) return false;
1257
+ if (!suffix) return true;
1258
+ const lower = res.toLowerCase();
1259
+ if (suffix === ".md") {
1260
+ return (
1261
+ lower.endsWith(".md") &&
1262
+ !lower.endsWith(".prompt.md") &&
1263
+ !lower.endsWith(".instructions.md") &&
1264
+ !lower.endsWith(".agent.md")
1265
+ );
1266
+ }
1267
+ return lower.endsWith(suffix);
1268
+ });
1269
+ }
1270
+
1271
+ /**
1272
+ * Syncs components for an IDE based on its Agent Profile (`bundle` vs `convert` mode)
1273
+ * and persists the ownership manifest so only tool-owned items are ever pruned.
1274
+ */
1275
+ /**
1276
+ * Proactively sanitizes and guards an agent configuration directory against corrupted
1277
+ * or schema-violating stub files (e.g. 0-byte JSONs, empty {} projects without id, empty ghost folders).
1278
+ * Ensures background Language Servers and file watchers never enter crash loops for any connected agent.
1279
+ */
1280
+ export function sanitizeAgentConfigDirectory(configDir, agentType = "general") {
1281
+ if (!configDir || !fs.existsSync(configDir)) return;
1282
+ try {
1283
+ // 1. Sanitize projects / workspace manifests (e.g. ~/.gemini/config/projects/)
1284
+ const projDir = path.join(configDir, "projects");
1285
+ if (fs.existsSync(projDir)) {
1286
+ for (const ent of fs.readdirSync(projDir)) {
1287
+ if (!ent.endsWith(".json")) continue;
1288
+ const p = path.join(projDir, ent);
1289
+ try {
1290
+ const st = fs.statSync(p);
1291
+ if (st.size === 0) {
1292
+ fs.unlinkSync(p);
1293
+ continue;
1294
+ }
1295
+ const content = fs.readFileSync(p, "utf8").trim();
1296
+ if (content === "{}" || content === "") {
1297
+ fs.unlinkSync(p);
1298
+ continue;
1299
+ }
1300
+ try {
1301
+ const parsed = JSON.parse(content);
1302
+ if (parsed && typeof parsed === "object" && !parsed.id) {
1303
+ fs.unlinkSync(p);
1304
+ }
1305
+ } catch {
1306
+ try { fs.unlinkSync(p); } catch {}
1307
+ }
1308
+ } catch {}
1309
+ }
1310
+ }
1311
+
1312
+ // 2. Sanitize empty ghost directories left behind in plugins / skills
1313
+ for (const sub of ["plugins", "skills"]) {
1314
+ const subDir = path.join(configDir, sub);
1315
+ if (fs.existsSync(subDir)) {
1316
+ for (const ent of fs.readdirSync(subDir)) {
1317
+ const itemPath = path.join(subDir, ent);
1318
+ try {
1319
+ const st = fs.lstatSync(itemPath);
1320
+ if (st.isDirectory()) {
1321
+ const children = fs.readdirSync(itemPath);
1322
+ if (children.length === 0) {
1323
+ fs.rmSync(itemPath, { recursive: true, force: true });
1324
+ }
1325
+ }
1326
+ } catch {}
1327
+ }
1328
+ }
1329
+ }
1330
+ } catch {}
1331
+ }
1332
+
1333
+ export function syncIdePlugins(ide, allPlugins = []) {
1334
+ if (!ide) return { success: false, message: "No IDE provided" };
1335
+ const normalized = normalizeIdeEntry(ide);
1336
+ const agentType = normalized.agentType;
1337
+ const profile = AGENT_PROFILES[agentType] || AGENT_PROFILES.custom;
1338
+ const home = getHomeDir();
1339
+ const appData = getAppDataDir(home);
1340
+ const paths = resolveEffectiveAgentPaths(normalized, home, appData);
1341
+ const primaryDir = expandHomePath(paths.primary || paths.bundle || paths.skills || normalized.configPath);
1342
+
1343
+ if (!primaryDir) {
1344
+ return { success: false, message: "No config path specified" };
1345
+ }
1346
+
1347
+ // Universal Safety Fallback: sanitize config directories before syncing
1348
+ sanitizeAgentConfigDirectory(primaryDir, agentType);
1349
+ sanitizeAgentConfigDirectory(path.dirname(primaryDir), agentType);
1350
+
1351
+ const ownerKey = `ide-${normalized.id || agentType}`;
1352
+ const prevState = loadOwnershipState(ownerKey);
1353
+
1354
+ // Mode 1: Bundle Agent (Antigravity)
1355
+ if (profile.mode === "bundle") {
1356
+ const bundleDir = paths.bundle || primaryDir;
1357
+ ensureDir(bundleDir);
1358
+
1359
+ const activePluginMap = new Map();
1360
+ for (const plugin of allPlugins) {
1361
+ const isEnabled = Boolean(normalized.plugins && normalized.plugins[plugin.id] === true);
1362
+ if (isEnabled && plugin.path && fs.existsSync(plugin.path) && !plugin.isRootSkills) {
1363
+ activePluginMap.set(plugin.id, plugin.path);
1364
+ }
1365
+ }
1366
+
1367
+ const prevLinksSet = new Set((prevState.links || []).map((p) => path.resolve(p)));
1368
+ const bundleLinks = [];
1369
+ const results = [];
1370
+
1371
+ // Use syncPluginBundles which uses real-directory materialization on Windows
1372
+ // to bypass Go os.ReadDir IsDir() == false bug on junctions!
1373
+ const bundleRes = syncPluginBundles(
1374
+ bundleDir,
1375
+ activePluginMap,
1376
+ prevState.links || [],
1377
+ createJunction,
1378
+ removeJunction,
1379
+ allPlugins,
1380
+ ownerKey
1381
+ );
1382
+ bundleLinks.push(...bundleRes.bundleLinks);
1383
+ results.push(...bundleRes.results);
1384
+
1385
+ // 3. Antigravity ~/.gemini/config harmonization:
1386
+ // - Link ALL enabled skills into ~/.gemini/config/skills/<skill-name> so `/` slash commands work for all plugins & root skills
1387
+ // - Sync enabled rules into ~/.gemini/config/rules/ and subagents into ~/.gemini/config/agents/ for `@` mentions
1388
+ // - Clean any stray hub junctions directly under ~/.gemini/config/
1389
+ // - Harmonize skills.json without wiping user's non-hub entries
1390
+ const isGeminiIde = agentType === "antigravity" || primaryDir.toLowerCase().includes(".gemini");
1391
+ let skillLinks = [];
1392
+ let nextFiles = [];
1393
+ const nextJsonKeys = {};
1394
+ const nextBlocks = [];
1395
+ const components = collectEnabledComponents(allPlugins, normalized.plugins);
1396
+
1397
+ if (isGeminiIde) {
1398
+ const geminiConfigDir = path.dirname(bundleDir);
1399
+ const geminiSkillsDir = paths.skills || path.join(geminiConfigDir, "skills");
1400
+ const geminiRulesSpec = paths.rules || paths.rulesDir || { dir: path.join(geminiConfigDir, "rules"), suffix: ".md" };
1401
+ const geminiAgentsSpec = paths.agents || paths.agentsDir || { dir: path.join(geminiConfigDir, "agents"), suffix: ".md" };
1402
+ const geminiSkillsJson = paths.skillsJson || path.join(geminiConfigDir, "skills.json");
1403
+
1404
+ // Clean any stray plugin junctions that were mistakenly created directly in geminiConfigDir
1405
+ try {
1406
+ if (fs.existsSync(geminiConfigDir)) {
1407
+ for (const entryName of fs.readdirSync(geminiConfigDir)) {
1408
+ if (entryName === "plugins" || entryName === "skills" || entryName === "rules" || entryName === "agents") {
1409
+ continue;
1410
+ }
1411
+ const entryPath = path.join(geminiConfigDir, entryName);
1412
+ try {
1413
+ const st = fs.lstatSync(entryPath);
1414
+ if (st.isSymbolicLink()) {
1415
+ const tgt = fs.readlinkSync(entryPath);
1416
+ if (prevLinksSet.has(path.resolve(entryPath)) || isTargetInsideHub(tgt, allPlugins)) {
1417
+ removeJunction(entryPath);
1418
+ }
1419
+ }
1420
+ } catch {}
1421
+ }
1422
+ }
1423
+ } catch {}
1424
+
1425
+ // Clean any prevState.links from old/changed configPath directories (e.g. unexpanded `~` directories)
1426
+ const prevSkillLinks = (prevState.links || []).filter(
1427
+ (l) => path.dirname(path.resolve(l)) === path.resolve(geminiSkillsDir)
1428
+ );
1429
+ for (const oldLink of prevState.links || []) {
1430
+ const oldParent = path.dirname(path.resolve(oldLink));
1431
+ if (oldParent !== path.resolve(bundleDir) && oldParent !== path.resolve(geminiSkillsDir)) {
1432
+ removeJunction(oldLink);
1433
+ }
1434
+ }
1435
+
1436
+ // In bundle mode (e.g. Antigravity), skills that belong to an enabled plugin bundle
1437
+ // are already discovered from bundleDir/<plugin>/skills/<skill-name>.
1438
+ // Linking them AGAIN into geminiSkillsDir causes them to appear twice in Antigravity!
1439
+ // Therefore, only standalone root skills (not bundled inside an enabled plugin) should be flattened into geminiSkillsDir.
1440
+ const standaloneSkills = components.skills.filter((s) => {
1441
+ const parentPlugin = allPlugins.find((p) => p.id === s.pluginId);
1442
+ return !parentPlugin || Boolean(parentPlugin.isRootSkills);
1443
+ });
1444
+
1445
+ // Sync standalone skills into ~/.gemini/config/skills/<skill-name>
1446
+ const skillSync = syncFlattenedSkills(
1447
+ standaloneSkills,
1448
+ geminiSkillsDir,
1449
+ prevSkillLinks,
1450
+ createJunction,
1451
+ removeJunction,
1452
+ allPlugins,
1453
+ ownerKey
1454
+ );
1455
+ skillLinks = skillSync.nextLinks;
1456
+
1457
+ // Ensure outside-of-project.json is never created with empty object which breaks LS project reader
1458
+ try {
1459
+ const projDir = path.join(geminiConfigDir, "projects");
1460
+ const defaultProjFile = path.join(projDir, "outside-of-project.json");
1461
+ if (fs.existsSync(defaultProjFile)) {
1462
+ const content = fs.readFileSync(defaultProjFile, "utf8").trim();
1463
+ if (content === "{}" || content === "") {
1464
+ fs.unlinkSync(defaultProjFile);
1465
+ }
1466
+ }
1467
+ } catch {}
1468
+
1469
+ // Sync rules & subagents into ~/.gemini/config/rules and ~/.gemini/config/agents
1470
+ const prevRuleFiles = filterOwnedFilesForSpec(prevState.files, geminiRulesSpec);
1471
+ const prevAgentFiles = filterOwnedFilesForSpec(prevState.files, geminiAgentsSpec);
1472
+ const rFiles = syncOwnedFiles(components.rules, geminiRulesSpec, prevRuleFiles);
1473
+ const aFiles = syncOwnedFiles(components.agents, geminiAgentsSpec, prevAgentFiles);
1474
+ nextFiles.push(...rFiles.nextFiles, ...aFiles.nextFiles);
1475
+
1476
+ if (fs.existsSync(geminiSkillsJson)) {
1477
+ try {
1478
+ const parsed = JSON.parse(fs.readFileSync(geminiSkillsJson, "utf8"));
1479
+ if (parsed && Array.isArray(parsed.entries)) {
1480
+ const filtered = parsed.entries.filter((entry) => {
1481
+ const entryPath = typeof entry === "string" ? entry : entry?.path;
1482
+ return !isTargetInsideHub(entryPath, allPlugins, resolveHubRoot());
1483
+ });
1484
+ fs.writeFileSync(geminiSkillsJson, JSON.stringify({ ...parsed, entries: filtered }, null, 2), "utf8");
1485
+ }
1486
+ } catch {}
1487
+ }
1488
+ }
1489
+
1490
+ if (paths.mcp) {
1491
+ const prevKeys = (prevState.jsonKeys && prevState.jsonKeys[paths.mcp.file]) || [];
1492
+ const jsonRes = syncJsonMcpServers(paths.mcp, components.mcpServers, prevKeys);
1493
+ if (jsonRes.ownedKeys.length > 0) nextJsonKeys[paths.mcp.file] = jsonRes.ownedKeys;
1494
+ }
1495
+ if (paths.hooks) {
1496
+ const prevHooks = (prevState.jsonKeys && prevState.jsonKeys[paths.hooks.file]) || [];
1497
+ const hookRes = syncJsonHooks(paths.hooks, components.hooks, prevHooks);
1498
+ if (hookRes.ownedKeys.length > 0) nextJsonKeys[paths.hooks.file] = hookRes.ownedKeys;
1499
+ }
1500
+
1501
+ const allOwnedLinks = [...bundleLinks, ...skillLinks];
1502
+ saveOwnershipState(ownerKey, { links: allOwnedLinks, files: nextFiles, jsonKeys: nextJsonKeys, blocks: nextBlocks });
1503
+ return {
1504
+ success: true,
1505
+ agentType,
1506
+ mode: "bundle",
1507
+ summary: {
1508
+ plugins: bundleLinks.length,
1509
+ skills: skillLinks.length,
1510
+ rules: components.rules.length,
1511
+ agents: components.agents.length,
1512
+ },
1513
+ results,
1514
+ };
1515
+ }
1516
+
1517
+ // Mode 2: Native-Format Converted Agent (Claude Code, Codex, OpenCode, Copilot, Cursor, Windsurf, Gemini CLI, Cline, Roo, Kiro, Universal, Custom)
1518
+ const components = collectEnabledComponents(allPlugins, normalized.plugins);
1519
+ const skillsTargetDir = paths.skills || primaryDir;
1520
+
1521
+ // 1. Link flattened skills (<skillsTargetDir>/<skill-name>/SKILL.md)
1522
+ const skillSync = syncFlattenedSkills(
1523
+ components.skills,
1524
+ skillsTargetDir,
1525
+ prevState.links || [],
1526
+ createJunction,
1527
+ removeJunction,
1528
+ allPlugins,
1529
+ ownerKey
1530
+ );
1531
+
1532
+ // 2. Sync `/` quick-action slash command files (commands/, global_workflows/, prompts/, etc.)
1533
+ let nextFiles = [];
1534
+ let commandsSyncedCount = 0;
1535
+ if (paths.commandsDir) {
1536
+ const prevCmdFiles = filterOwnedFilesForSpec(prevState.files, paths.commandsDir);
1537
+ const cmdRes = syncSkillSlashCommands(components.skills, paths.commandsDir, prevCmdFiles);
1538
+ nextFiles.push(...cmdRes.nextFiles);
1539
+ commandsSyncedCount = cmdRes.nextFiles.length;
1540
+ }
1541
+
1542
+ // 3. Sync MCP Servers into native JSON or TOML config
1543
+ const nextJsonKeys = {};
1544
+ const nextBlocks = [];
1545
+ let mcpSyncedCount = 0;
1546
+
1547
+ if (paths.mcp) {
1548
+ if (paths.mcp.format === "toml-block") {
1549
+ const hadBlock = (prevState.blocks || []).includes(paths.mcp.file);
1550
+ const tomlRes = syncTomlMcpServers(paths.mcp.file, components.mcpServers, hadBlock);
1551
+ if (tomlRes.hasBlock) {
1552
+ nextBlocks.push(paths.mcp.file);
1553
+ mcpSyncedCount = Object.keys(components.mcpServers).length;
1554
+ }
1555
+ } else {
1556
+ const prevKeys = (prevState.jsonKeys && prevState.jsonKeys[paths.mcp.file]) || [];
1557
+ const jsonRes = syncJsonMcpServers(paths.mcp, components.mcpServers, prevKeys);
1558
+ if (jsonRes.ownedKeys.length > 0) {
1559
+ nextJsonKeys[paths.mcp.file] = jsonRes.ownedKeys;
1560
+ }
1561
+ mcpSyncedCount = jsonRes.ownedKeys.length;
1562
+ }
1563
+ }
1564
+
1565
+ // 4. Sync Rules (either Markdown block in CLAUDE.md/AGENTS.md/GEMINI.md or file copies in rulesDir)
1566
+ let rulesSyncedCount = 0;
1567
+ if (paths.rules) {
1568
+ const hadBlock = (prevState.blocks || []).includes(paths.rules.file);
1569
+ const mdRes = syncMarkdownRulesBlock(paths.rules, components.rules, hadBlock);
1570
+ if (mdRes.hasBlock) {
1571
+ nextBlocks.push(paths.rules.file);
1572
+ rulesSyncedCount = components.rules.length;
1573
+ }
1574
+ }
1575
+
1576
+ if (paths.rulesDir) {
1577
+ const prevRuleFiles = filterOwnedFilesForSpec(prevState.files, paths.rulesDir);
1578
+ const rFiles = syncOwnedFiles(components.rules, paths.rulesDir, prevRuleFiles);
1579
+ nextFiles.push(...rFiles.nextFiles);
1580
+ rulesSyncedCount = rFiles.nextFiles.length;
1581
+ }
1582
+
1583
+ // 5. Sync Subagents (`@` mentions in ~/.claude/agents, ~/.config/opencode/agents, Cursor agents, or VS Code prompts)
1584
+ let agentsSyncedCount = 0;
1585
+ const agentTargetSpec = paths.agents || paths.agentsDir;
1586
+ if (agentTargetSpec) {
1587
+ const prevAgentFiles = filterOwnedFilesForSpec(prevState.files, agentTargetSpec);
1588
+ const aFiles = syncOwnedFiles(components.agents, agentTargetSpec, prevAgentFiles);
1589
+ nextFiles.push(...aFiles.nextFiles);
1590
+ agentsSyncedCount = aFiles.nextFiles.length;
1591
+ }
1592
+
1593
+ // 6. Sync Hooks (e.g. ~/.claude/hooks.json)
1594
+ if (paths.hooks) {
1595
+ const prevHooks = (prevState.jsonKeys && prevState.jsonKeys[paths.hooks.file]) || [];
1596
+ const hookRes = syncJsonHooks(paths.hooks, components.hooks, prevHooks);
1597
+ if (hookRes.ownedKeys.length > 0) {
1598
+ nextJsonKeys[paths.hooks.file] = hookRes.ownedKeys;
1599
+ }
1600
+ }
1601
+
1602
+ saveOwnershipState(ownerKey, {
1603
+ links: skillSync.nextLinks,
1604
+ files: nextFiles,
1605
+ jsonKeys: nextJsonKeys,
1606
+ blocks: nextBlocks,
1607
+ });
1608
+
1609
+ return {
1610
+ success: true,
1611
+ agentType,
1612
+ mode: "convert",
1613
+ summary: {
1614
+ skills: skillSync.nextLinks.length,
1615
+ commands: commandsSyncedCount,
1616
+ mcp: mcpSyncedCount,
1617
+ rules: rulesSyncedCount,
1618
+ agents: agentsSyncedCount,
1619
+ conflicts: components.conflicts.length,
1620
+ },
1621
+ conflicts: components.conflicts,
1622
+ results: skillSync.results,
1623
+ };
1624
+ }
1625
+
1626
+ /**
1627
+ * Syncs project-level plugin overrides into a repository workspace and adds entries to `.git/info/exclude`.
1628
+ */
1629
+ export function syncProjectOverrides(project, ide, allPlugins = []) {
1630
+ const repoPath = project?.repoPath ? expandHomePath(project.repoPath) : "";
1631
+ if (!project || !repoPath || !fs.existsSync(repoPath)) {
1632
+ return { success: false, message: "Project repository path does not exist" };
1633
+ }
1634
+
1635
+ const agentType = inferAgentType(ide || project.ideId || "antigravity");
1636
+ const projPaths = resolveEffectiveProjectPaths(project, ide);
1637
+
1638
+ // Merge IDE global plugin map with project-specific override map
1639
+ const mergedPluginMap = {
1640
+ ...(ide?.plugins || {}),
1641
+ ...(project.plugins || {}),
1642
+ };
1643
+
1644
+ const ownerKey = `project-${project.id || path.basename(repoPath)}`;
1645
+ const prevState = loadOwnershipState(ownerKey);
1646
+ const components = collectEnabledComponents(allPlugins, mergedPluginMap);
1647
+
1648
+ const skillSync = syncFlattenedSkills(
1649
+ components.skills,
1650
+ projPaths.skills,
1651
+ prevState.links || [],
1652
+ createJunction,
1653
+ removeJunction,
1654
+ allPlugins,
1655
+ ownerKey
1656
+ );
1657
+
1658
+ const nextJsonKeys = {};
1659
+ const nextBlocks = [];
1660
+ if (projPaths.mcp) {
1661
+ if (projPaths.mcp.format === "toml-block") {
1662
+ const hadBlock = (prevState.blocks || []).includes(projPaths.mcp.file);
1663
+ const tomlRes = syncTomlMcpServers(projPaths.mcp.file, components.mcpServers, hadBlock);
1664
+ if (tomlRes.hasBlock) nextBlocks.push(projPaths.mcp.file);
1665
+ } else {
1666
+ const prevKeys = (prevState.jsonKeys && prevState.jsonKeys[projPaths.mcp.file]) || [];
1667
+ const jsonRes = syncJsonMcpServers(projPaths.mcp, components.mcpServers, prevKeys);
1668
+ if (jsonRes.ownedKeys.length > 0) nextJsonKeys[projPaths.mcp.file] = jsonRes.ownedKeys;
1669
+ }
1670
+ }
1671
+
1672
+ if (projPaths.rules) {
1673
+ const hadBlock = (prevState.blocks || []).includes(projPaths.rules.file);
1674
+ const mdRes = syncMarkdownRulesBlock(projPaths.rules, components.rules, hadBlock);
1675
+ if (mdRes.hasBlock) nextBlocks.push(projPaths.rules.file);
1676
+ }
1677
+
1678
+ if (projPaths.hooks) {
1679
+ const prevHooks = (prevState.jsonKeys && prevState.jsonKeys[projPaths.hooks.file]) || [];
1680
+ const hookRes = syncJsonHooks(projPaths.hooks, components.hooks, prevHooks);
1681
+ if (hookRes.ownedKeys.length > 0) nextJsonKeys[projPaths.hooks.file] = hookRes.ownedKeys;
1682
+ }
1683
+
1684
+ let nextFiles = [];
1685
+ if (projPaths.commandsDir) {
1686
+ const prevCmdFiles = filterOwnedFilesForSpec(prevState.files, projPaths.commandsDir);
1687
+ const cmdRes = syncSkillSlashCommands(components.skills, projPaths.commandsDir, prevCmdFiles);
1688
+ nextFiles.push(...cmdRes.nextFiles);
1689
+ }
1690
+ if (projPaths.agents) {
1691
+ const prevAgentFiles = filterOwnedFilesForSpec(prevState.files, projPaths.agents);
1692
+ const aFiles = syncOwnedFiles(components.agents, projPaths.agents, prevAgentFiles);
1693
+ nextFiles.push(...aFiles.nextFiles);
1694
+ }
1695
+
1696
+ if (projPaths.excludeRel) {
1697
+ ensureGitInfoExclude(repoPath, projPaths.excludeRel);
1698
+ }
1699
+
1700
+ saveOwnershipState(ownerKey, {
1701
+ links: skillSync.nextLinks,
1702
+ files: nextFiles,
1703
+ jsonKeys: nextJsonKeys,
1704
+ blocks: nextBlocks,
1705
+ });
1706
+
1707
+ return {
1708
+ success: true,
1709
+ project: project.name,
1710
+ agentType,
1711
+ skillsLinked: skillSync.nextLinks.length,
1712
+ results: skillSync.results,
1713
+ };
1714
+ }
1715
+
1716
+ /**
1717
+ * Safely terminates running processes matching the agent's executable path or process names.
1718
+ * Ensures component removal takes effect immediately without requiring a computer reboot.
1719
+ */
1720
+ export function killAgentProcesses(ide) {
1721
+ if (!ide) return { success: true };
1722
+ if (process.env.NODE_ENV === "test" || process.env.ASM_TEST === "1") {
1723
+ return { success: true, skipped: "test-environment" };
1724
+ }
1725
+ const normalized = normalizeIdeEntry(ide);
1726
+ const type = normalized.agentType || inferAgentType(normalized);
1727
+
1728
+ // Protected Primary GUI Editors: All modern AI IDEs hot-reload configuration on disk.
1729
+ // Forcefully killing them terminates developer sessions and unsaved work.
1730
+ const PROTECTED_GUI_AGENTS = new Set([
1731
+ "antigravity",
1732
+ "cursor",
1733
+ "windsurf",
1734
+ "vscode",
1735
+ "vscode-copilot",
1736
+ "vscodium",
1737
+ "opencode",
1738
+ "kiro",
1739
+ "gemini-cli",
1740
+ "cline",
1741
+ "roo-code",
1742
+ ]);
1743
+
1744
+ if (PROTECTED_GUI_AGENTS.has(type) && !normalized.forceKill) {
1745
+ return { success: true, skipped: "gui-editor-hot-reload-protected" };
1746
+ }
1747
+
1748
+ // Never kill known editor executables even if custom agent names are passed
1749
+ const PROTECTED_EXECUTABLES = new Set([
1750
+ "antigravity.exe",
1751
+ "antigravity ide.exe",
1752
+ "agy.exe",
1753
+ "cursor.exe",
1754
+ "windsurf.exe",
1755
+ "code.exe",
1756
+ "codium.exe",
1757
+ "vscodium.exe",
1758
+ "opencode.exe",
1759
+ "electron.exe",
1760
+ "devenv.exe",
1761
+ "idea64.exe",
1762
+ ]);
1763
+
1764
+ const targets = new Set();
1765
+ if (normalized.exePath) {
1766
+ const exeName = path.basename(normalized.exePath).toLowerCase();
1767
+ if (!PROTECTED_EXECUTABLES.has(exeName)) {
1768
+ targets.add(exeName);
1769
+ }
1770
+ }
1771
+
1772
+ let killedAny = false;
1773
+ for (const procName of targets) {
1774
+ if (!procName) continue;
1775
+ try {
1776
+ if (process.platform === "win32") {
1777
+ // Use graceful termination rather than forceful /F /T
1778
+ execSync(`taskkill /IM "${procName}"`, { stdio: "ignore" });
1779
+ killedAny = true;
1780
+ } else {
1781
+ execSync(`pkill -f "${procName}"`, { stdio: "ignore" });
1782
+ killedAny = true;
1783
+ }
1784
+ } catch {}
1785
+ }
1786
+
1787
+ return { success: true, killed: killedAny };
1788
+ }
1789
+
1790
+ /**
1791
+ * Severs all owned junctions, MCP keys, rule blocks, and copied files for a given IDE when removed.
1792
+ */
1793
+ export function unlinkAllForIde(ide, killProcesses = false) {
1794
+ if (!ide) return { success: true };
1795
+ const normalized = normalizeIdeEntry(ide);
1796
+ const ownerKey = `ide-${normalized.id || normalized.agentType}`;
1797
+ // Passing empty allPlugins cleanly unlinks and prunes all owned links, files, MCP keys, hooks, blocks!
1798
+ syncIdePlugins(normalized, []);
1799
+ deleteOwnershipState(ownerKey);
1800
+ if (killProcesses) {
1801
+ killAgentProcesses(normalized);
1802
+ }
1803
+ return { success: true };
1804
+ }
1805
+
1806
+ /**
1807
+ * Severs all owned junctions, MCP keys, rule blocks, and copied files for a given Project when removed.
1808
+ */
1809
+ export function unlinkAllForProject(project, ide = null) {
1810
+ if (!project) return { success: true };
1811
+ const ownerKey = `project-${project.id || path.basename(project.repoPath || "")}`;
1812
+ syncProjectOverrides({ ...project, plugins: {} }, ide, []);
1813
+ deleteOwnershipState(ownerKey);
1814
+ return { success: true };
1815
+ }
1816
+
1817
+ /**
1818
+ * Finds all indices in hubConfig.ides matching a target IDE by:
1819
+ * 1. Exact ID match (case-insensitive)
1820
+ * 2. Base ID match (stripping trailing timestamp suffixes)
1821
+ * 3. Normalized configPath match (resolving ~ and symlinks)
1822
+ * 4. Standard agentType match (for non-custom single-instance agents)
1823
+ *
1824
+ * @param {Array<object>} ides - Array of configured IDE objects.
1825
+ * @param {object} targetIde - The normalized target IDE object.
1826
+ * @returns {Array<number>} Matching indices in ides array.
1827
+ */
1828
+ export function findMatchingIdeIndices(ides = [], targetIde = {}) {
1829
+ if (!Array.isArray(ides) || !targetIde) return [];
1830
+
1831
+ const targetId = String(targetIde.id || "").trim().toLowerCase();
1832
+ const targetType = String(targetIde.agentType || "").trim().toLowerCase();
1833
+ const targetBaseId = targetId.replace(/-\d{10,}$/, "");
1834
+ const targetConfig = targetIde.configPath
1835
+ ? path.resolve(expandHomePath(targetIde.configPath)).toLowerCase()
1836
+ : "";
1837
+
1838
+ const matches = [];
1839
+
1840
+ for (let idx = 0; idx < ides.length; idx++) {
1841
+ const entry = ides[idx];
1842
+ if (!entry || typeof entry !== "object") continue;
1843
+
1844
+ const entryId = String(entry.id || "").trim().toLowerCase();
1845
+ const entryBaseId = entryId.replace(/-\d{10,}$/, "");
1846
+ const entryType = String(entry.agentType || "").trim().toLowerCase();
1847
+ const entryConfig = entry.configPath
1848
+ ? path.resolve(expandHomePath(entry.configPath)).toLowerCase()
1849
+ : "";
1850
+
1851
+ // Match 1: Exact ID match
1852
+ if (targetId && entryId && entryId === targetId) {
1853
+ matches.push(idx);
1854
+ continue;
1855
+ }
1856
+
1857
+ // Match 2: Base ID match (e.g. "antigravity-1730188045123" vs "antigravity")
1858
+ if (targetBaseId && entryBaseId && entryBaseId === targetBaseId) {
1859
+ matches.push(idx);
1860
+ continue;
1861
+ }
1862
+
1863
+ // Match 3: Config path match (same physical directory on disk)
1864
+ if (targetConfig && entryConfig && entryConfig === targetConfig) {
1865
+ matches.push(idx);
1866
+ continue;
1867
+ }
1868
+
1869
+ // Match 4: Standard agentType match (for built-in agents like cursor, windsurf, antigravity)
1870
+ if (
1871
+ targetType &&
1872
+ targetType !== "custom" &&
1873
+ (entryType === targetType || entryId === targetType || entryBaseId === targetType)
1874
+ ) {
1875
+ matches.push(idx);
1876
+ continue;
1877
+ }
1878
+ }
1879
+
1880
+ return matches;
1881
+ }
1882
+
1883
+ /**
1884
+ * Connects or reconnects an agent IDE, replacing any existing bridge for that agent
1885
+ * rather than creating duplicate bridges. Guarantees in-place deduplication,
1886
+ * ownership manifest aggregation, clean differential teardown, and safety invariant compliance.
1887
+ *
1888
+ * @param {object} hubConfig - The current hub configuration object.
1889
+ * @param {object} targetIde - The IDE entry to connect (with updated plugins map).
1890
+ * @param {object} [options] - Additional connection options:
1891
+ * - customPlugins: Array of pre-scanned plugin objects.
1892
+ * - allPlugins: Alias for customPlugins.
1893
+ * - effHub: Effective hub root directory path.
1894
+ * - configFile: Custom path to hub-config.json.
1895
+ * - skipSave: Whether to skip saving hubConfig.
1896
+ * @returns {object} { success: boolean, hubConfig: object, result: object, sync: object, bridge: object, activeAgents: Array, ide: object }
1897
+ */
1898
+ export function connectAgent(hubConfig, targetIde, options = {}) {
1899
+ if (!targetIde || typeof targetIde !== "object") {
1900
+ return {
1901
+ success: false,
1902
+ error: "Target IDE is required",
1903
+ hubConfig: hubConfig || null,
1904
+ result: null,
1905
+ };
1906
+ }
1907
+
1908
+ // Ensure valid hubConfig object
1909
+ const config = hubConfig || loadHubConfig(options.configFile);
1910
+ if (!Array.isArray(config.ides)) {
1911
+ config.ides = [];
1912
+ }
1913
+
1914
+ const effectiveHub = options.effHub || getEffectiveHubRoot(config);
1915
+ const plugins = options.customPlugins || options.allPlugins || scanPlugins(effectiveHub);
1916
+
1917
+ // 1. Normalize target IDE definition
1918
+ const normTarget = normalizeIdeEntry(targetIde);
1919
+ const targetType = normTarget.agentType || inferAgentType(normTarget);
1920
+ normTarget.agentType = targetType;
1921
+
1922
+ // 2. Identify matching entries in hubConfig.ides
1923
+ const matchingIndices = findMatchingIdeIndices(config.ides, normTarget);
1924
+
1925
+ // Determine canonical ID (clean string without timestamp suffix)
1926
+ let canonicalId = String(normTarget.id || "").trim();
1927
+ if (matchingIndices.length > 0) {
1928
+ const cleanExisting = matchingIndices
1929
+ .map((idx) => config.ides[idx])
1930
+ .find((entry) => entry && entry.id && !/-\d{10,}$/.test(entry.id));
1931
+
1932
+ if (cleanExisting) {
1933
+ canonicalId = cleanExisting.id;
1934
+ } else {
1935
+ canonicalId = (canonicalId || targetType || "custom").replace(/-\d{10,}$/, "");
1936
+ }
1937
+ } else {
1938
+ canonicalId = (canonicalId || targetType || "custom").replace(/-\d{10,}$/, "");
1939
+ }
1940
+ if (!canonicalId) canonicalId = targetType || "custom";
1941
+ normTarget.id = canonicalId;
1942
+
1943
+ // 3. Track duplicate IDs for ownership aggregation and handoff cleanup
1944
+ const removedDuplicateIds = new Set();
1945
+ if (targetIde.id && targetIde.id !== canonicalId) {
1946
+ removedDuplicateIds.add(targetIde.id);
1947
+ }
1948
+
1949
+ // 4. In-Place Deduplication of config.ides
1950
+ let updatedIde = null;
1951
+
1952
+ if (matchingIndices.length > 0) {
1953
+ const primaryIdx = matchingIndices[0];
1954
+ const existingEntry = config.ides[primaryIdx] || {};
1955
+
1956
+ if (existingEntry.id && existingEntry.id !== canonicalId) {
1957
+ removedDuplicateIds.add(existingEntry.id);
1958
+ }
1959
+
1960
+ // Collect IDs of any duplicate matching entries
1961
+ for (let k = 1; k < matchingIndices.length; k++) {
1962
+ const dupEntry = config.ides[matchingIndices[k]];
1963
+ if (dupEntry && dupEntry.id && dupEntry.id !== canonicalId) {
1964
+ removedDuplicateIds.add(dupEntry.id);
1965
+ }
1966
+ }
1967
+
1968
+ const newPlugins = targetIde.plugins !== undefined && targetIde.plugins !== null
1969
+ ? (typeof targetIde.plugins === "object" ? { ...targetIde.plugins } : {})
1970
+ : (existingEntry.plugins ? { ...existingEntry.plugins } : {});
1971
+
1972
+ updatedIde = normalizeIdeEntry({
1973
+ ...existingEntry,
1974
+ ...normTarget,
1975
+ id: canonicalId,
1976
+ agentType: targetType,
1977
+ enabled: true,
1978
+ plugins: newPlugins,
1979
+ });
1980
+
1981
+ config.ides[primaryIdx] = updatedIde;
1982
+
1983
+ // Remove any additional duplicate entries from config.ides
1984
+ if (matchingIndices.length > 1) {
1985
+ const dupSet = new Set(matchingIndices.slice(1));
1986
+ config.ides = config.ides.filter((_, idx) => !dupSet.has(idx));
1987
+ }
1988
+ } else {
1989
+ // New agent connection
1990
+ updatedIde = normalizeIdeEntry({
1991
+ ...normTarget,
1992
+ id: canonicalId,
1993
+ agentType: targetType,
1994
+ enabled: true,
1995
+ plugins: targetIde.plugins && typeof targetIde.plugins === "object" ? { ...targetIde.plugins } : {},
1996
+ });
1997
+ config.ides.push(updatedIde);
1998
+ }
1999
+
2000
+ // 5. Aggregate legacy timestamped ownership manifests into ide-<canonicalId>.json
2001
+ const canonicalOwnerKey = `ide-${canonicalId}`;
2002
+ const canonicalState = loadOwnershipState(canonicalOwnerKey);
2003
+ const stateDir = getStateDir();
2004
+
2005
+ if (fs.existsSync(stateDir)) {
2006
+ try {
2007
+ const stateFiles = fs.readdirSync(stateDir).filter((f) => f.endsWith(".json"));
2008
+ for (const filename of stateFiles) {
2009
+ const ownerId = filename.slice(0, -5);
2010
+ if (ownerId === canonicalOwnerKey) continue;
2011
+
2012
+ let isMatch = false;
2013
+
2014
+ // Condition A: Matches an explicit duplicate ID removed from config.ides
2015
+ for (const dupId of removedDuplicateIds) {
2016
+ if (ownerId === `ide-${dupId}` || ownerId === dupId) {
2017
+ isMatch = true;
2018
+ break;
2019
+ }
2020
+ }
2021
+
2022
+ // Condition B: Matches timestamped pattern ide-<canonicalId>-<timestamp>
2023
+ if (!isMatch) {
2024
+ const canonPrefix = `ide-${canonicalId}-`;
2025
+ const typePrefix = targetType && targetType !== "custom" ? `ide-${targetType}-` : null;
2026
+ if (ownerId.startsWith(canonPrefix) || (typePrefix && ownerId.startsWith(typePrefix))) {
2027
+ isMatch = true;
2028
+ }
2029
+ }
2030
+
2031
+ if (isMatch) {
2032
+ const legacyState = loadOwnershipState(ownerId);
2033
+
2034
+ // Merge links
2035
+ for (const link of legacyState.links || []) {
2036
+ if (!canonicalState.links.includes(link)) {
2037
+ canonicalState.links.push(link);
2038
+ }
2039
+ }
2040
+
2041
+ // Merge files
2042
+ for (const file of legacyState.files || []) {
2043
+ if (!canonicalState.files.includes(file)) {
2044
+ canonicalState.files.push(file);
2045
+ }
2046
+ }
2047
+
2048
+ // Merge JSON keys
2049
+ if (legacyState.jsonKeys && typeof legacyState.jsonKeys === "object") {
2050
+ for (const [keyPath, keys] of Object.entries(legacyState.jsonKeys)) {
2051
+ if (!canonicalState.jsonKeys[keyPath]) {
2052
+ canonicalState.jsonKeys[keyPath] = Array.isArray(keys) ? [...keys] : [];
2053
+ } else {
2054
+ const mergedKeySet = new Set(canonicalState.jsonKeys[keyPath]);
2055
+ for (const k of keys || []) mergedKeySet.add(k);
2056
+ canonicalState.jsonKeys[keyPath] = Array.from(mergedKeySet);
2057
+ }
2058
+ }
2059
+ }
2060
+
2061
+ // Merge demarcated blocks
2062
+ for (const block of legacyState.blocks || []) {
2063
+ if (!canonicalState.blocks.includes(block)) {
2064
+ canonicalState.blocks.push(block);
2065
+ }
2066
+ }
2067
+
2068
+ // Delete obsolete state file from disk
2069
+ deleteOwnershipState(ownerId);
2070
+ }
2071
+ }
2072
+ } catch {}
2073
+ }
2074
+
2075
+ // Persist aggregated state so syncIdePlugins diffs against all prior artifacts
2076
+ saveOwnershipState(canonicalOwnerKey, canonicalState);
2077
+
2078
+ // Auto-enable components from Components Storage Path if explicitly requested (e.g. on agent add)
2079
+ if (options.autoEnable === true) {
2080
+ autoEnableHubComponents(updatedIde, config, plugins);
2081
+ }
2082
+
2083
+ // Pre-sync directory sanitization (Safety Invariant 2)
2084
+ const primaryDir = updatedIde.configPath ? expandHomePath(updatedIde.configPath) : "";
2085
+ if (primaryDir && fs.existsSync(primaryDir)) {
2086
+ sanitizeAgentConfigDirectory(primaryDir, updatedIde.agentType);
2087
+ }
2088
+
2089
+ // 6. Differential Sync: syncIdePlugins tears down unselected components & creates selected ones
2090
+ const syncResult = syncIdePlugins(updatedIde, plugins);
2091
+
2092
+ // Post-sync directory sanitization
2093
+ if (primaryDir && fs.existsSync(primaryDir)) {
2094
+ sanitizeAgentConfigDirectory(primaryDir, updatedIde.agentType);
2095
+ }
2096
+
2097
+ // 7. Persist configuration and regenerate communication bridge files
2098
+ if (options.skipSave !== true) {
2099
+ try {
2100
+ saveHubConfig(config, options.configFile);
2101
+ } catch {}
2102
+ }
2103
+
2104
+ try {
2105
+ writeHubCommunicationFiles(effectiveHub, config, plugins, { ides: [syncResult] });
2106
+ } catch {}
2107
+
2108
+ // 8. Prune stale handoff directories on disk for removed duplicate IDs
2109
+ for (const dupId of removedDuplicateIds) {
2110
+ if (dupId && dupId !== canonicalId) {
2111
+ const staleHandoff = path.join(effectiveHub, "shared", "handoff", dupId);
2112
+ try {
2113
+ if (fs.existsSync(staleHandoff)) {
2114
+ fs.rmSync(staleHandoff, { recursive: true, force: true });
2115
+ }
2116
+ } catch {}
2117
+ }
2118
+ }
2119
+
2120
+ // 9. Read fresh bridge payload
2121
+ let bridge = null;
2122
+ let activeAgents = [];
2123
+ try {
2124
+ const bridgeFile = path.join(effectiveHub, "agent-space-bridge.json");
2125
+ if (fs.existsSync(bridgeFile)) {
2126
+ bridge = JSON.parse(fs.readFileSync(bridgeFile, "utf8"));
2127
+ activeAgents = bridge.activeAgents || [];
2128
+ }
2129
+ } catch {}
2130
+
2131
+ return {
2132
+ success: syncResult.success !== false,
2133
+ hubConfig: config,
2134
+ result: syncResult,
2135
+ sync: syncResult,
2136
+ bridge: bridge || {},
2137
+ activeAgents: activeAgents.length > 0 ? activeAgents : (bridge?.activeAgents || []),
2138
+ ide: updatedIde,
2139
+ };
2140
+ }
2141
+
2142
+ /**
2143
+ * Resolves the effective Hub root path from a config object or path string.
2144
+ * When blank, always returns the default Hub root (never loops into 1st IDE's configPath).
2145
+ */
2146
+ export function getEffectiveHubRoot(configOrPath) {
2147
+ if (typeof configOrPath === "string") {
2148
+ if (configOrPath && configOrPath.trim() !== "") return expandHomePath(configOrPath.trim());
2149
+ return resolveHubRoot();
2150
+ }
2151
+ if (configOrPath && typeof configOrPath === "object") {
2152
+ if (configOrPath.hubRoot && configOrPath.hubRoot.trim() !== "") {
2153
+ return expandHomePath(configOrPath.hubRoot.trim());
2154
+ }
2155
+ }
2156
+ return resolveHubRoot();
2157
+ }
2158
+
2159
+ /**
2160
+ * Synchronizes all configured IDEs and Project Overrides against the given hubConfig or plugin list.
2161
+ * Automatically reconciles and unlinks any removed IDEs/projects, and updates hub communication files.
2162
+ */
2163
+ export function syncAllIdes(hubConfig, customPlugins = null) {
2164
+ if (!hubConfig) return { success: true, results: [], projectResults: [] };
2165
+ const effectiveHub = getEffectiveHubRoot(hubConfig);
2166
+ const plugins = customPlugins !== null ? customPlugins : scanPlugins(effectiveHub);
2167
+ const syncResults = [];
2168
+ const projectResults = [];
2169
+
2170
+ const ides = Array.isArray(hubConfig.ides) ? hubConfig.ides : [];
2171
+ const projects = Array.isArray(hubConfig.projects) ? hubConfig.projects : [];
2172
+
2173
+ // 1. Reconcile deleted / removed IDEs and Projects from ownership states
2174
+ const activeOwnerIds = new Set([
2175
+ ...ides.filter((i) => i.enabled !== false).map((i) => `ide-${i.id || inferAgentType(i)}`),
2176
+ ...projects.map((p) => `project-${p.id || path.basename(p.repoPath || "")}`),
2177
+ ]);
2178
+
2179
+ try {
2180
+ const allStates = listAllOwnershipStates();
2181
+ for (const st of allStates) {
2182
+ if (!activeOwnerIds.has(st.ownerId)) {
2183
+ for (const link of st.links || []) {
2184
+ removeJunction(link);
2185
+ try {
2186
+ if (fs.existsSync(link)) {
2187
+ const ls = fs.lstatSync(link);
2188
+ if (ls.isSymbolicLink()) fs.unlinkSync(link);
2189
+ else if (isAsmOwnedDirectory(link)) fs.rmSync(link, { recursive: true, force: true });
2190
+ }
2191
+ } catch {}
2192
+ }
2193
+ for (const file of st.files || []) {
2194
+ try {
2195
+ if (fs.existsSync(file)) fs.unlinkSync(file);
2196
+ } catch {}
2197
+ }
2198
+ deleteOwnershipState(st.ownerId);
2199
+ }
2200
+ }
2201
+ } catch {}
2202
+
2203
+ // 2. Sync all active IDEs
2204
+ for (const ide of ides) {
2205
+ if (ide.enabled !== false && (ide.configPath || ide.componentPaths)) {
2206
+ const res = syncIdePlugins(ide, plugins);
2207
+ syncResults.push({ ide: ide.name, ideId: ide.id, ...res });
2208
+ } else {
2209
+ unlinkAllForIde(ide);
2210
+ }
2211
+ }
2212
+
2213
+ // 3. Sync all project overrides
2214
+ for (const proj of projects) {
2215
+ if (proj.repoPath) {
2216
+ const parentIde = ides.find((i) => i.id === proj.ideId) || ides[0] || null;
2217
+ const pRes = syncProjectOverrides(proj, parentIde, plugins);
2218
+ projectResults.push(pRes);
2219
+ }
2220
+ }
2221
+
2222
+ // 4. Update cross-agent communication files in D:\Software\AI Agent Space
2223
+ try {
2224
+ writeHubCommunicationFiles(effectiveHub, hubConfig, plugins, { ides: syncResults, projects: projectResults });
2225
+ } catch {}
2226
+
2227
+ // 5. Update components storage snapshot to reflect current sync state
2228
+ try {
2229
+ const currentSnap = getComponentsStorageSnapshot(effectiveHub);
2230
+ saveComponentsStorageSnapshot(effectiveHub, currentSnap);
2231
+ } catch {}
2232
+
2233
+ return { success: true, results: syncResults, projectResults };
2234
+ }
2235
+
2236
+ /**
2237
+ * Resolves the state file path for saving the Components Storage Path snapshot.
2238
+ */
2239
+ export function getSnapshotFilePath(hubRoot = resolveHubRoot()) {
2240
+ const clean = getEffectiveHubRoot(hubRoot);
2241
+ const hashKey = createHash("md5").update(path.resolve(clean).toLowerCase()).digest("hex").slice(0, 10);
2242
+ return path.join(getStateDir(), `components-snapshot-${hashKey}.json`);
2243
+ }
2244
+
2245
+ /**
2246
+ * Persists the components storage snapshot to the state directory.
2247
+ */
2248
+ export function saveComponentsStorageSnapshot(hubRoot, snapshot) {
2249
+ try {
2250
+ const filePath = getSnapshotFilePath(hubRoot);
2251
+ ensureDir(path.dirname(filePath));
2252
+ fs.writeFileSync(filePath, JSON.stringify(snapshot, null, 2), "utf8");
2253
+ return true;
2254
+ } catch {
2255
+ return false;
2256
+ }
2257
+ }
2258
+
2259
+ /**
2260
+ * Loads the persisted components storage snapshot for the specified hubRoot.
2261
+ */
2262
+ export function loadComponentsStorageSnapshot(hubRoot = resolveHubRoot()) {
2263
+ try {
2264
+ const filePath = getSnapshotFilePath(hubRoot);
2265
+ if (fs.existsSync(filePath)) {
2266
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
2267
+ }
2268
+ } catch {}
2269
+ return null;
2270
+ }
2271
+
2272
+ /**
2273
+ * Scans the Components Storage Path (where skills, MCPs, rules, agents, and plugins are saved)
2274
+ * and generates a deterministic fingerprint snapshot with component lists, mtimes, and canonical hash.
2275
+ */
2276
+ export function getComponentsStorageSnapshot(hubRoot = resolveHubRoot()) {
2277
+ const cleanHub = getEffectiveHubRoot(hubRoot);
2278
+ if (!cleanHub || !fs.existsSync(cleanHub)) {
2279
+ return {
2280
+ hubRoot: cleanHub,
2281
+ exists: false,
2282
+ timestamp: Date.now(),
2283
+ plugins: {},
2284
+ rootComponents: { skills: {}, rules: {}, agents: {}, mcp: null, hooks: null },
2285
+ hash: "empty",
2286
+ summary: { pluginCount: 0, skillCount: 0, ruleCount: 0, agentCount: 0, mcpCount: 0, hookCount: 0 },
2287
+ };
2288
+ }
2289
+
2290
+ // Determine plugins directory (plugins/ subdirectory or cleanHub directly if manifests present)
2291
+ let pluginsDir = path.join(cleanHub, "plugins");
2292
+ if (!fs.existsSync(pluginsDir)) {
2293
+ try {
2294
+ const sub = fs.readdirSync(cleanHub);
2295
+ const hasManifest = sub.some((name) => {
2296
+ const itemPath = path.join(cleanHub, name);
2297
+ try {
2298
+ if (!fs.statSync(itemPath).isDirectory()) return false;
2299
+ return (
2300
+ fs.existsSync(path.join(itemPath, "plugin.json")) ||
2301
+ fs.existsSync(path.join(itemPath, "skills")) ||
2302
+ fs.existsSync(path.join(itemPath, "rules")) ||
2303
+ fs.existsSync(path.join(itemPath, "mcp_config.json"))
2304
+ );
2305
+ } catch {
2306
+ return false;
2307
+ }
2308
+ });
2309
+ if (hasManifest) pluginsDir = cleanHub;
2310
+ } catch {}
2311
+ }
2312
+
2313
+ const plugins = {};
2314
+ let totalSkills = 0;
2315
+ let totalRules = 0;
2316
+ let totalAgents = 0;
2317
+ let totalMcps = 0;
2318
+ let totalHooks = 0;
2319
+
2320
+ if (fs.existsSync(pluginsDir)) {
2321
+ try {
2322
+ const entries = fs.readdirSync(pluginsDir);
2323
+ for (const entry of entries) {
2324
+ if (entry.startsWith(".") || entry === "node_modules") continue;
2325
+ const pDir = path.join(pluginsDir, entry);
2326
+ try {
2327
+ const st = fs.statSync(pDir);
2328
+ if (!st.isDirectory()) continue;
2329
+ } catch {
2330
+ continue;
2331
+ }
2332
+
2333
+ const manifestPath = path.join(pDir, "plugin.json");
2334
+ let manifestInfo = null;
2335
+ if (fs.existsSync(manifestPath)) {
2336
+ try {
2337
+ const mStat = fs.statSync(manifestPath);
2338
+ const mContent = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
2339
+ manifestInfo = {
2340
+ version: mContent.version || "1.0.0",
2341
+ mtime: Math.round(mStat.mtimeMs),
2342
+ size: mStat.size,
2343
+ };
2344
+ } catch {
2345
+ manifestInfo = { version: "unknown", mtime: 0, size: 0 };
2346
+ }
2347
+ }
2348
+
2349
+ // Skills inside plugin
2350
+ const pluginSkills = {};
2351
+ const skillsDir = path.join(pDir, "skills");
2352
+ if (fs.existsSync(skillsDir)) {
2353
+ try {
2354
+ for (const s of fs.readdirSync(skillsDir)) {
2355
+ const sPath = path.join(skillsDir, s);
2356
+ try {
2357
+ const sStat = fs.statSync(sPath);
2358
+ if (sStat.isDirectory()) {
2359
+ const skillMd = path.join(sPath, "SKILL.md");
2360
+ let smStat = null;
2361
+ if (fs.existsSync(skillMd)) {
2362
+ try { smStat = fs.statSync(skillMd); } catch {}
2363
+ }
2364
+ pluginSkills[s] = {
2365
+ mtime: Math.round(smStat ? smStat.mtimeMs : sStat.mtimeMs),
2366
+ size: smStat ? smStat.size : 0,
2367
+ };
2368
+ totalSkills++;
2369
+ }
2370
+ } catch {}
2371
+ }
2372
+ } catch {}
2373
+ }
2374
+
2375
+ // Rules inside plugin
2376
+ const pluginRules = {};
2377
+ const rulesDir = path.join(pDir, "rules");
2378
+ if (fs.existsSync(rulesDir)) {
2379
+ try {
2380
+ for (const r of fs.readdirSync(rulesDir)) {
2381
+ if (!r.endsWith(".md")) continue;
2382
+ const rPath = path.join(rulesDir, r);
2383
+ try {
2384
+ const rStat = fs.statSync(rPath);
2385
+ pluginRules[r] = { mtime: Math.round(rStat.mtimeMs), size: rStat.size };
2386
+ totalRules++;
2387
+ } catch {}
2388
+ }
2389
+ } catch {}
2390
+ }
2391
+
2392
+ // Agents inside plugin
2393
+ const pluginAgents = {};
2394
+ const agentsDir = path.join(pDir, "agents");
2395
+ if (fs.existsSync(agentsDir)) {
2396
+ try {
2397
+ for (const a of fs.readdirSync(agentsDir)) {
2398
+ if (!a.endsWith(".md")) continue;
2399
+ const aPath = path.join(agentsDir, a);
2400
+ try {
2401
+ const aStat = fs.statSync(aPath);
2402
+ pluginAgents[a] = { mtime: Math.round(aStat.mtimeMs), size: aStat.size };
2403
+ totalAgents++;
2404
+ } catch {}
2405
+ }
2406
+ } catch {}
2407
+ }
2408
+
2409
+ // MCP inside plugin
2410
+ let mcpInfo = null;
2411
+ const mcpFile = path.join(pDir, "mcp_config.json");
2412
+ if (fs.existsSync(mcpFile)) {
2413
+ try {
2414
+ const mcpStat = fs.statSync(mcpFile);
2415
+ mcpInfo = { mtime: Math.round(mcpStat.mtimeMs), size: mcpStat.size };
2416
+ totalMcps++;
2417
+ } catch {}
2418
+ }
2419
+
2420
+ // Hooks inside plugin
2421
+ let hooksInfo = null;
2422
+ const hooksFile = path.join(pDir, "hooks.json");
2423
+ if (fs.existsSync(hooksFile)) {
2424
+ try {
2425
+ const hStat = fs.statSync(hooksFile);
2426
+ hooksInfo = { mtime: Math.round(hStat.mtimeMs), size: hStat.size };
2427
+ totalHooks++;
2428
+ } catch {}
2429
+ }
2430
+
2431
+ // Files count & total size for catch-all modification sensitivity
2432
+ let totalFilesCount = 0;
2433
+ let totalFilesSize = 0;
2434
+ let maxFileMtime = 0;
2435
+ try {
2436
+ const files = listFilesRecursiveRel(pDir, pDir);
2437
+ totalFilesCount = files.length;
2438
+ for (const f of files) {
2439
+ totalFilesSize += f.size || 0;
2440
+ if (f.mtime && f.mtime > maxFileMtime) maxFileMtime = f.mtime;
2441
+ }
2442
+ } catch {}
2443
+
2444
+ if (manifestInfo || Object.keys(pluginSkills).length > 0 || Object.keys(pluginRules).length > 0 || mcpInfo) {
2445
+ plugins[entry] = {
2446
+ version: manifestInfo?.version || "1.0.0",
2447
+ manifest: manifestInfo,
2448
+ skills: pluginSkills,
2449
+ rules: pluginRules,
2450
+ agents: pluginAgents,
2451
+ mcp: mcpInfo,
2452
+ hooks: hooksInfo,
2453
+ filesCount: totalFilesCount,
2454
+ totalSize: totalFilesSize,
2455
+ maxMtime: maxFileMtime,
2456
+ };
2457
+ }
2458
+ }
2459
+ } catch {}
2460
+ }
2461
+
2462
+ // Root standalone components in hubRoot
2463
+ const rootSkills = {};
2464
+ const rootSkillsDir = path.join(cleanHub, "skills");
2465
+ if (fs.existsSync(rootSkillsDir)) {
2466
+ try {
2467
+ for (const s of fs.readdirSync(rootSkillsDir)) {
2468
+ const sPath = path.join(rootSkillsDir, s);
2469
+ try {
2470
+ const sStat = fs.statSync(sPath);
2471
+ if (sStat.isDirectory()) {
2472
+ const skillMd = path.join(sPath, "SKILL.md");
2473
+ let smStat = null;
2474
+ if (fs.existsSync(skillMd)) {
2475
+ try { smStat = fs.statSync(skillMd); } catch {}
2476
+ }
2477
+ rootSkills[s] = {
2478
+ mtime: Math.round(smStat ? smStat.mtimeMs : sStat.mtimeMs),
2479
+ size: smStat ? smStat.size : 0,
2480
+ };
2481
+ totalSkills++;
2482
+ }
2483
+ } catch {}
2484
+ }
2485
+ } catch {}
2486
+ }
2487
+
2488
+ const rootRules = {};
2489
+ const rootRulesDir = path.join(cleanHub, "rules");
2490
+ if (fs.existsSync(rootRulesDir)) {
2491
+ try {
2492
+ for (const r of fs.readdirSync(rootRulesDir)) {
2493
+ if (!r.endsWith(".md")) continue;
2494
+ const rPath = path.join(rootRulesDir, r);
2495
+ try {
2496
+ const rStat = fs.statSync(rPath);
2497
+ rootRules[r] = { mtime: Math.round(rStat.mtimeMs), size: rStat.size };
2498
+ totalRules++;
2499
+ } catch {}
2500
+ }
2501
+ } catch {}
2502
+ }
2503
+
2504
+ const rootAgents = {};
2505
+ const rootAgentsDir = path.join(cleanHub, "agents");
2506
+ if (fs.existsSync(rootAgentsDir)) {
2507
+ try {
2508
+ for (const a of fs.readdirSync(rootAgentsDir)) {
2509
+ if (!a.endsWith(".md")) continue;
2510
+ const aPath = path.join(rootAgentsDir, a);
2511
+ try {
2512
+ const aStat = fs.statSync(aPath);
2513
+ rootAgents[a] = { mtime: Math.round(aStat.mtimeMs), size: aStat.size };
2514
+ totalAgents++;
2515
+ } catch {}
2516
+ }
2517
+ } catch {}
2518
+ }
2519
+
2520
+ let rootMcp = null;
2521
+ const rootMcpFile = path.join(cleanHub, "mcp_config.json");
2522
+ if (fs.existsSync(rootMcpFile)) {
2523
+ try {
2524
+ const mStat = fs.statSync(rootMcpFile);
2525
+ rootMcp = { mtime: Math.round(mStat.mtimeMs), size: mStat.size };
2526
+ totalMcps++;
2527
+ } catch {}
2528
+ }
2529
+
2530
+ let rootHooks = null;
2531
+ const rootHooksFile = path.join(cleanHub, "hooks.json");
2532
+ if (fs.existsSync(rootHooksFile)) {
2533
+ try {
2534
+ const hStat = fs.statSync(rootHooksFile);
2535
+ rootHooks = { mtime: Math.round(hStat.mtimeMs), size: hStat.size };
2536
+ totalHooks++;
2537
+ } catch {}
2538
+ }
2539
+
2540
+ const rootComponents = {
2541
+ skills: rootSkills,
2542
+ rules: rootRules,
2543
+ agents: rootAgents,
2544
+ mcp: rootMcp,
2545
+ hooks: rootHooks,
2546
+ };
2547
+
2548
+ const canonicalObj = {
2549
+ hubRoot: cleanHub,
2550
+ plugins,
2551
+ rootComponents,
2552
+ };
2553
+
2554
+ function canonicalize(val) {
2555
+ if (val === null || typeof val !== "object") return val;
2556
+ if (Array.isArray(val)) return val.map(canonicalize);
2557
+ const sorted = {};
2558
+ for (const k of Object.keys(val).sort()) {
2559
+ sorted[k] = canonicalize(val[k]);
2560
+ }
2561
+ return sorted;
2562
+ }
2563
+
2564
+ const canonicalJson = JSON.stringify(canonicalize(canonicalObj));
2565
+ const hash = createHash("sha256").update(canonicalJson).digest("hex");
2566
+
2567
+ return {
2568
+ hubRoot: cleanHub,
2569
+ exists: true,
2570
+ timestamp: Date.now(),
2571
+ plugins,
2572
+ rootComponents,
2573
+ hash,
2574
+ summary: {
2575
+ pluginCount: Object.keys(plugins).length,
2576
+ skillCount: totalSkills,
2577
+ ruleCount: totalRules,
2578
+ agentCount: totalAgents,
2579
+ mcpCount: totalMcps,
2580
+ hookCount: totalHooks,
2581
+ },
2582
+ };
2583
+ }
2584
+
2585
+ /**
2586
+ * Computes exact differences between two components storage snapshots.
2587
+ */
2588
+ export function diffComponentsStorageSnapshots(prev, current) {
2589
+ if (!current) return { hasChanges: false, summary: "No current snapshot provided" };
2590
+ if (!prev) {
2591
+ const s = current.summary || {};
2592
+ return {
2593
+ hasChanges: true,
2594
+ isInitial: true,
2595
+ pathChanged: false,
2596
+ pluginsAdded: Object.keys(current.plugins || {}),
2597
+ pluginsRemoved: [],
2598
+ pluginsModified: [],
2599
+ skillsAdded: Object.keys(current.rootComponents?.skills || {}).map((s) => `root/${s}`),
2600
+ skillsRemoved: [],
2601
+ skillsModified: [],
2602
+ rulesAdded: Object.keys(current.rootComponents?.rules || {}).map((r) => `root/${r}`),
2603
+ rulesRemoved: [],
2604
+ rulesModified: [],
2605
+ agentsAdded: Object.keys(current.rootComponents?.agents || {}).map((a) => `root/${a}`),
2606
+ agentsRemoved: [],
2607
+ agentsModified: [],
2608
+ mcpModified: false,
2609
+ hooksModified: false,
2610
+ summary: `Initial components baseline recorded (${s.pluginCount || 0} plugins, ${s.skillCount || 0} skills, ${s.mcpCount || 0} MCP, ${s.ruleCount || 0} rules)`,
2611
+ };
2612
+ }
2613
+
2614
+ const pathChanged =
2615
+ path.resolve(String(prev.hubRoot || "")).toLowerCase() !==
2616
+ path.resolve(String(current.hubRoot || "")).toLowerCase();
2617
+
2618
+ if (prev.hash === current.hash && !pathChanged) {
2619
+ return {
2620
+ hasChanges: false,
2621
+ isInitial: false,
2622
+ pathChanged: false,
2623
+ pluginsAdded: [],
2624
+ pluginsRemoved: [],
2625
+ pluginsModified: [],
2626
+ skillsAdded: [],
2627
+ skillsRemoved: [],
2628
+ skillsModified: [],
2629
+ rulesAdded: [],
2630
+ rulesRemoved: [],
2631
+ rulesModified: [],
2632
+ agentsAdded: [],
2633
+ agentsRemoved: [],
2634
+ agentsModified: [],
2635
+ mcpModified: false,
2636
+ hooksModified: false,
2637
+ summary: "Components Storage Path is up to date (no changes detected)",
2638
+ };
2639
+ }
2640
+
2641
+ const prevPlugins = prev.plugins || {};
2642
+ const currPlugins = current.plugins || {};
2643
+
2644
+ const pluginsAdded = Object.keys(currPlugins).filter((id) => !prevPlugins[id]);
2645
+ const pluginsRemoved = Object.keys(prevPlugins).filter((id) => !currPlugins[id]);
2646
+ const pluginsModified = [];
2647
+
2648
+ const skillsAdded = [];
2649
+ const skillsRemoved = [];
2650
+ const skillsModified = [];
2651
+ const rulesAdded = [];
2652
+ const rulesRemoved = [];
2653
+ const rulesModified = [];
2654
+ const agentsAdded = [];
2655
+ const agentsRemoved = [];
2656
+ const agentsModified = [];
2657
+
2658
+ // Check plugins diff
2659
+ for (const id of Object.keys(currPlugins)) {
2660
+ if (!prevPlugins[id]) continue;
2661
+ const pPrev = prevPlugins[id];
2662
+ const pCurr = currPlugins[id];
2663
+ let isMod = false;
2664
+
2665
+ if (pPrev.version !== pCurr.version) isMod = true;
2666
+ if (pPrev.manifest?.mtime !== pCurr.manifest?.mtime || pPrev.manifest?.size !== pCurr.manifest?.size) isMod = true;
2667
+ if (pPrev.filesCount !== pCurr.filesCount || pPrev.totalSize !== pCurr.totalSize || pPrev.maxMtime !== pCurr.maxMtime) isMod = true;
2668
+
2669
+ // Check skills
2670
+ for (const s of Object.keys(pCurr.skills || {})) {
2671
+ if (!pPrev.skills?.[s]) {
2672
+ skillsAdded.push(`${id}/${s}`);
2673
+ isMod = true;
2674
+ } else if (pPrev.skills[s].mtime !== pCurr.skills[s].mtime || pPrev.skills[s].size !== pCurr.skills[s].size) {
2675
+ skillsModified.push(`${id}/${s}`);
2676
+ isMod = true;
2677
+ }
2678
+ }
2679
+ for (const s of Object.keys(pPrev.skills || {})) {
2680
+ if (!pCurr.skills?.[s]) {
2681
+ skillsRemoved.push(`${id}/${s}`);
2682
+ isMod = true;
2683
+ }
2684
+ }
2685
+
2686
+ // Check rules
2687
+ for (const r of Object.keys(pCurr.rules || {})) {
2688
+ if (!pPrev.rules?.[r]) {
2689
+ rulesAdded.push(`${id}/${r}`);
2690
+ isMod = true;
2691
+ } else if (pPrev.rules[r].mtime !== pCurr.rules[r].mtime || pPrev.rules[r].size !== pCurr.rules[r].size) {
2692
+ rulesModified.push(`${id}/${r}`);
2693
+ isMod = true;
2694
+ }
2695
+ }
2696
+ for (const r of Object.keys(pPrev.rules || {})) {
2697
+ if (!pCurr.rules?.[r]) {
2698
+ rulesRemoved.push(`${id}/${r}`);
2699
+ isMod = true;
2700
+ }
2701
+ }
2702
+
2703
+ // Check agents
2704
+ for (const a of Object.keys(pCurr.agents || {})) {
2705
+ if (!pPrev.agents?.[a]) {
2706
+ agentsAdded.push(`${id}/${a}`);
2707
+ isMod = true;
2708
+ } else if (pPrev.agents[a].mtime !== pCurr.agents[a].mtime || pPrev.agents[a].size !== pCurr.agents[a].size) {
2709
+ agentsModified.push(`${id}/${a}`);
2710
+ isMod = true;
2711
+ }
2712
+ }
2713
+ for (const a of Object.keys(pPrev.agents || {})) {
2714
+ if (!pCurr.agents?.[a]) {
2715
+ agentsRemoved.push(`${id}/${a}`);
2716
+ isMod = true;
2717
+ }
2718
+ }
2719
+
2720
+ // Check MCP & hooks
2721
+ if (JSON.stringify(pPrev.mcp) !== JSON.stringify(pCurr.mcp)) isMod = true;
2722
+ if (JSON.stringify(pPrev.hooks) !== JSON.stringify(pCurr.hooks)) isMod = true;
2723
+
2724
+ if (isMod) pluginsModified.push(id);
2725
+ }
2726
+
2727
+ // Check root components diff
2728
+ const prevRoot = prev.rootComponents || {};
2729
+ const currRoot = current.rootComponents || {};
2730
+
2731
+ // Root skills
2732
+ for (const s of Object.keys(currRoot.skills || {})) {
2733
+ if (!prevRoot.skills?.[s]) skillsAdded.push(`root/${s}`);
2734
+ else if (prevRoot.skills[s].mtime !== currRoot.skills[s].mtime || prevRoot.skills[s].size !== currRoot.skills[s].size) {
2735
+ skillsModified.push(`root/${s}`);
2736
+ }
2737
+ }
2738
+ for (const s of Object.keys(prevRoot.skills || {})) {
2739
+ if (!currRoot.skills?.[s]) skillsRemoved.push(`root/${s}`);
2740
+ }
2741
+
2742
+ // Root rules
2743
+ for (const r of Object.keys(currRoot.rules || {})) {
2744
+ if (!prevRoot.rules?.[r]) rulesAdded.push(`root/${r}`);
2745
+ else if (prevRoot.rules[r].mtime !== currRoot.rules[r].mtime || prevRoot.rules[r].size !== currRoot.rules[r].size) {
2746
+ rulesModified.push(`root/${r}`);
2747
+ }
2748
+ }
2749
+ for (const r of Object.keys(prevRoot.rules || {})) {
2750
+ if (!currRoot.rules?.[r]) rulesRemoved.push(`root/${r}`);
2751
+ }
2752
+
2753
+ // Root agents
2754
+ for (const a of Object.keys(currRoot.agents || {})) {
2755
+ if (!prevRoot.agents?.[a]) agentsAdded.push(`root/${a}`);
2756
+ else if (prevRoot.agents[a].mtime !== currRoot.agents[a].mtime || prevRoot.agents[a].size !== currRoot.agents[a].size) {
2757
+ agentsModified.push(`root/${a}`);
2758
+ }
2759
+ }
2760
+ for (const a of Object.keys(prevRoot.agents || {})) {
2761
+ if (!currRoot.agents?.[a]) agentsRemoved.push(`root/${a}`);
2762
+ }
2763
+
2764
+ const mcpModified = JSON.stringify(prevRoot.mcp) !== JSON.stringify(currRoot.mcp);
2765
+ const hooksModified = JSON.stringify(prevRoot.hooks) !== JSON.stringify(currRoot.hooks);
2766
+
2767
+ const hasChanges =
2768
+ pathChanged ||
2769
+ pluginsAdded.length > 0 ||
2770
+ pluginsRemoved.length > 0 ||
2771
+ pluginsModified.length > 0 ||
2772
+ skillsAdded.length > 0 ||
2773
+ skillsRemoved.length > 0 ||
2774
+ skillsModified.length > 0 ||
2775
+ rulesAdded.length > 0 ||
2776
+ rulesRemoved.length > 0 ||
2777
+ rulesModified.length > 0 ||
2778
+ agentsAdded.length > 0 ||
2779
+ agentsRemoved.length > 0 ||
2780
+ agentsModified.length > 0 ||
2781
+ mcpModified ||
2782
+ hooksModified;
2783
+
2784
+ // Build human-readable summary
2785
+ const parts = [];
2786
+ if (pathChanged) parts.push(`storage path changed to ${current.hubRoot}`);
2787
+ if (pluginsAdded.length) parts.push(`${pluginsAdded.length} plugin(s) added (${pluginsAdded.join(", ")})`);
2788
+ if (pluginsRemoved.length) parts.push(`${pluginsRemoved.length} plugin(s) removed (${pluginsRemoved.join(", ")})`);
2789
+ if (skillsAdded.length) parts.push(`${skillsAdded.length} skill(s) added`);
2790
+ if (skillsRemoved.length) parts.push(`${skillsRemoved.length} skill(s) removed`);
2791
+ if (skillsModified.length) parts.push(`${skillsModified.length} skill(s) modified`);
2792
+ if (rulesAdded.length || rulesModified.length || rulesRemoved.length) parts.push("rules modified");
2793
+ if (agentsAdded.length || agentsModified.length || agentsRemoved.length) parts.push("agents modified");
2794
+ if (mcpModified) parts.push("MCP config modified");
2795
+ if (hooksModified) parts.push("hooks modified");
2796
+
2797
+ const summary = parts.length > 0 ? parts.join(", ") : "No component changes detected";
2798
+
2799
+ return {
2800
+ hasChanges,
2801
+ isInitial: false,
2802
+ pathChanged,
2803
+ pluginsAdded,
2804
+ pluginsRemoved,
2805
+ pluginsModified,
2806
+ skillsAdded,
2807
+ skillsRemoved,
2808
+ skillsModified,
2809
+ rulesAdded,
2810
+ rulesRemoved,
2811
+ rulesModified,
2812
+ agentsAdded,
2813
+ agentsRemoved,
2814
+ agentsModified,
2815
+ mcpModified,
2816
+ hooksModified,
2817
+ summary,
2818
+ };
2819
+ }
2820
+
2821
+ /**
2822
+ * Checks for modification differences in the Components Storage Path against the persisted snapshot.
2823
+ */
2824
+ export function checkComponentsModifications(hubRoot = resolveHubRoot()) {
2825
+ const cleanHub = getEffectiveHubRoot(hubRoot);
2826
+ const currentSnapshot = getComponentsStorageSnapshot(cleanHub);
2827
+ const prevSnapshot = loadComponentsStorageSnapshot(cleanHub);
2828
+ const diff = diffComponentsStorageSnapshots(prevSnapshot, currentSnapshot);
2829
+
2830
+ return {
2831
+ hubRoot: cleanHub,
2832
+ hasChanges: diff.hasChanges,
2833
+ diff,
2834
+ currentSnapshot,
2835
+ prevSnapshot,
2836
+ };
2837
+ }
2838
+
2839
+ /**
2840
+ * Removes decentralized component-level update checking scripts and state files
2841
+ * from the Components Storage Path (e.g. stagehand-fastcrw/update_checker.mjs,
2842
+ * update_check_state.json) to enforce centralized update checking via Agent Space Manager.
2843
+ */
2844
+ export function removeComponentUpdateMechanisms(hubRoot = resolveHubRoot()) {
2845
+ const cleanHub = getEffectiveHubRoot(hubRoot);
2846
+ if (!cleanHub || !fs.existsSync(cleanHub)) return { removed: [], count: 0 };
2847
+
2848
+ const targetFileNames = new Set([
2849
+ "update_checker.mjs",
2850
+ "update_check_state.json",
2851
+ "update-checker.mjs",
2852
+ "update-check-state.json",
2853
+ ]);
2854
+
2855
+ const removed = [];
2856
+
2857
+ function walk(dir, depth = 0) {
2858
+ if (depth > 6) return;
2859
+ try {
2860
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2861
+ for (const ent of entries) {
2862
+ const fullPath = path.join(dir, ent.name);
2863
+ if (ent.isDirectory()) {
2864
+ if (ent.name === ".git" || ent.name === "node_modules") continue;
2865
+ walk(fullPath, depth + 1);
2866
+ } else if (ent.isFile()) {
2867
+ if (targetFileNames.has(ent.name.toLowerCase())) {
2868
+ try {
2869
+ fs.unlinkSync(fullPath);
2870
+ removed.push(fullPath);
2871
+ } catch {}
2872
+ }
2873
+ }
2874
+ }
2875
+ } catch {}
2876
+ }
2877
+
2878
+ walk(cleanHub);
2879
+ return { removed, count: removed.length };
2880
+ }
2881
+
2882
+ /**
2883
+ * Computes Monday 00:00:00.000 of the week containing the given date.
2884
+ * ISO week convention: Monday is the start of the week.
2885
+ */
2886
+ export function getWeekMonday(date = new Date()) {
2887
+ const d = new Date(date);
2888
+ const day = d.getDay(); // 0 is Sunday, 1 is Monday, ..., 6 is Saturday
2889
+ const diff = day === 0 ? -6 : 1 - day;
2890
+ d.setDate(d.getDate() + diff);
2891
+ d.setHours(0, 0, 0, 0);
2892
+ return d;
2893
+ }
2894
+
2895
+ /**
2896
+ * Checks whether the weekly update check is due.
2897
+ * It is due if:
2898
+ * 1) No previous check was ever recorded.
2899
+ * 2) The last recorded check timestamp is prior to the current week's Monday 00:00:00.000.
2900
+ */
2901
+ export function isWeeklyMondayCheckDue(lastCheckedTimestamp, now = new Date()) {
2902
+ if (!lastCheckedTimestamp) return true;
2903
+ const last = new Date(lastCheckedTimestamp);
2904
+ if (isNaN(last.getTime())) return true;
2905
+ const currentMonday = getWeekMonday(now);
2906
+ return last.getTime() < currentMonday.getTime();
2907
+ }
2908
+
2909
+ /**
2910
+ * Extracts the upstream repository or source link for a component.
2911
+ */
2912
+ export function extractComponentUpstream(itemPath, itemType = "plugin", manifest = null) {
2913
+ let upstream = null;
2914
+
2915
+ // 1. Direct manifest properties
2916
+ if (manifest && typeof manifest === "object") {
2917
+ if (typeof manifest.upstream === "string" && manifest.upstream.trim()) {
2918
+ upstream = manifest.upstream.trim();
2919
+ } else if (typeof manifest.repository === "string" && manifest.repository.trim()) {
2920
+ upstream = manifest.repository.trim();
2921
+ } else if (manifest.repository && typeof manifest.repository.url === "string") {
2922
+ upstream = manifest.repository.url.trim();
2923
+ } else if (typeof manifest.homepage === "string" && manifest.homepage.trim()) {
2924
+ upstream = manifest.homepage.trim();
2925
+ } else if (typeof manifest.url === "string" && manifest.url.trim()) {
2926
+ upstream = manifest.url.trim();
2927
+ } else if (typeof manifest.source === "string" && manifest.source.trim()) {
2928
+ upstream = manifest.source.trim();
2929
+ }
2930
+ }
2931
+
2932
+ // 2. Check local .git/config if directory is a git clone
2933
+ if (!upstream && fs.existsSync(path.join(itemPath, ".git", "config"))) {
2934
+ try {
2935
+ const gitCfg = fs.readFileSync(path.join(itemPath, ".git", "config"), "utf8");
2936
+ const match = gitCfg.match(/url\s*=\s*(.+)/i);
2937
+ if (match && match[1]) {
2938
+ upstream = match[1].trim();
2939
+ }
2940
+ } catch {}
2941
+ }
2942
+
2943
+ // 3. For markdown files (SKILL.md, rules, agents), parse frontmatter
2944
+ if (!upstream) {
2945
+ let mdFile = null;
2946
+ try {
2947
+ const st = fs.statSync(itemPath);
2948
+ if (st.isDirectory()) {
2949
+ const candidateSkill = path.join(itemPath, "SKILL.md");
2950
+ if (fs.existsSync(candidateSkill)) mdFile = candidateSkill;
2951
+ } else if (st.isFile() && itemPath.endsWith(".md")) {
2952
+ mdFile = itemPath;
2953
+ }
2954
+ } catch {}
2955
+
2956
+ if (mdFile && fs.existsSync(mdFile)) {
2957
+ try {
2958
+ const content = fs.readFileSync(mdFile, "utf8");
2959
+ const fm = parseMarkdownFrontmatter(content);
2960
+ if (fm?.frontmatter) {
2961
+ upstream = fm.frontmatter.upstream || fm.frontmatter.repository || fm.frontmatter.source || null;
2962
+ if (typeof upstream === "string") upstream = upstream.trim();
2963
+ }
2964
+ } catch {}
2965
+ }
2966
+ }
2967
+
2968
+ if (upstream && typeof upstream === "string") {
2969
+ if (upstream.startsWith("git@github.com:")) {
2970
+ upstream = `https://github.com/${upstream.slice("git@github.com:".length).replace(/\.git$/, "")}`;
2971
+ }
2972
+ }
2973
+
2974
+ return upstream || null;
2975
+ }
2976
+
2977
+ /**
2978
+ * Scans all installed components in Components Storage Path and returns their upstream metadata.
2979
+ */
2980
+ export function collectAllComponentsUpstream(hubRoot = resolveHubRoot()) {
2981
+ const cleanHub = getEffectiveHubRoot(hubRoot);
2982
+ if (!cleanHub || !fs.existsSync(cleanHub)) return [];
2983
+
2984
+ const components = [];
2985
+ const plugins = scanPlugins(cleanHub);
2986
+
2987
+ for (const p of plugins) {
2988
+ let manifest = null;
2989
+ const manifestPath = path.join(p.path, "plugin.json");
2990
+ if (fs.existsSync(manifestPath)) {
2991
+ try { manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); } catch {}
2992
+ }
2993
+ const pluginUpstream = extractComponentUpstream(p.path, "plugin", manifest);
2994
+
2995
+ components.push({
2996
+ id: p.id,
2997
+ name: p.name || p.id,
2998
+ type: "plugin",
2999
+ version: p.version || "1.0.0",
3000
+ path: p.path,
3001
+ upstream: pluginUpstream,
3002
+ skillsCount: p.skills?.length || 0,
3003
+ rulesCount: p.rules?.length || 0,
3004
+ agentsCount: p.agents?.length || 0,
3005
+ hasMcp: Boolean(p.hasMcp),
3006
+ hasHooks: Boolean(p.hasHooks),
3007
+ });
3008
+
3009
+ // Check individual skills in plugin
3010
+ const skillsDir = path.join(p.path, "skills");
3011
+ if (fs.existsSync(skillsDir)) {
3012
+ try {
3013
+ for (const s of fs.readdirSync(skillsDir)) {
3014
+ const sPath = path.join(skillsDir, s);
3015
+ try {
3016
+ if (fs.statSync(sPath).isDirectory()) {
3017
+ const sUpstream = extractComponentUpstream(sPath, "skill");
3018
+ components.push({
3019
+ id: `${p.id}/${s}`,
3020
+ name: s,
3021
+ parentPlugin: p.id,
3022
+ type: "skill",
3023
+ path: sPath,
3024
+ upstream: sUpstream || pluginUpstream,
3025
+ });
3026
+ }
3027
+ } catch {}
3028
+ }
3029
+ } catch {}
3030
+ }
3031
+ }
3032
+
3033
+ // Standalone root skills
3034
+ const rootSkillsDir = path.join(cleanHub, "skills");
3035
+ if (fs.existsSync(rootSkillsDir)) {
3036
+ try {
3037
+ for (const s of fs.readdirSync(rootSkillsDir)) {
3038
+ const sPath = path.join(rootSkillsDir, s);
3039
+ try {
3040
+ if (fs.statSync(sPath).isDirectory()) {
3041
+ const sUpstream = extractComponentUpstream(sPath, "skill");
3042
+ components.push({
3043
+ id: `root/${s}`,
3044
+ name: s,
3045
+ type: "root-skill",
3046
+ path: sPath,
3047
+ upstream: sUpstream,
3048
+ });
3049
+ }
3050
+ } catch {}
3051
+ }
3052
+ } catch {}
3053
+ }
3054
+
3055
+ return components;
3056
+ }
3057
+
3058
+ export function getCentralUpdateStateFilePath(hubRoot = resolveHubRoot()) {
3059
+ const clean = getEffectiveHubRoot(hubRoot);
3060
+ const hashKey = createHash("md5").update(path.resolve(clean).toLowerCase()).digest("hex").slice(0, 10);
3061
+ return path.join(getStateDir(), `central-upstream-updates-${hashKey}.json`);
3062
+ }
3063
+
3064
+ export function loadCentralizedUpstreamUpdateState(hubRoot = resolveHubRoot()) {
3065
+ try {
3066
+ const p = getCentralUpdateStateFilePath(hubRoot);
3067
+ if (fs.existsSync(p)) {
3068
+ return JSON.parse(fs.readFileSync(p, "utf8"));
3069
+ }
3070
+ } catch {}
3071
+ return null;
3072
+ }
3073
+
3074
+ export function saveCentralizedUpstreamUpdateState(hubRoot, state) {
3075
+ try {
3076
+ const p = getCentralUpdateStateFilePath(hubRoot);
3077
+ ensureDir(path.dirname(p));
3078
+ fs.writeFileSync(p, JSON.stringify(state, null, 2), "utf8");
3079
+ return true;
3080
+ } catch {
3081
+ return false;
3082
+ }
3083
+ }
3084
+
3085
+ /**
3086
+ * Performs centralized update check for all components installed in Components Storage Path.
3087
+ * Runs once per week (first day starting on Monday whenever Magpie starts up).
3088
+ */
3089
+ export function checkCentralizedUpstreamUpdates(hubRoot = resolveHubRoot(), options = {}) {
3090
+ const cleanHub = getEffectiveHubRoot(hubRoot);
3091
+ const { force = false, now = new Date() } = options;
3092
+
3093
+ // 1. Proactively purge any decentralized component update mechanisms
3094
+ const cleanedMechanisms = removeComponentUpdateMechanisms(cleanHub);
3095
+
3096
+ const prevState = loadCentralizedUpstreamUpdateState(cleanHub);
3097
+ const due = force || isWeeklyMondayCheckDue(prevState?.lastCheckedTimestamp, now);
3098
+
3099
+ const currentMonday = getWeekMonday(now);
3100
+ const nextMonday = new Date(currentMonday);
3101
+ nextMonday.setDate(nextMonday.getDate() + 7);
3102
+
3103
+ if (!due && prevState) {
3104
+ return {
3105
+ checked: false,
3106
+ reason: "already_checked_this_week",
3107
+ hubRoot: cleanHub,
3108
+ lastCheckedTimestamp: prevState.lastCheckedTimestamp,
3109
+ lastWeekMonday: prevState.weekMonday,
3110
+ nextDueMonday: nextMonday.toISOString(),
3111
+ summary: prevState.summary || "Upstream check up to date for this week",
3112
+ trackedCount: prevState.trackedCount || 0,
3113
+ totalComponents: prevState.totalComponents || 0,
3114
+ components: prevState.components || [],
3115
+ cleanedMechanisms: cleanedMechanisms.count,
3116
+ };
3117
+ }
3118
+
3119
+ // 2. Discover all components and their upstreams
3120
+ const allComponents = collectAllComponentsUpstream(cleanHub);
3121
+ const trackedComponents = allComponents.filter((c) => Boolean(c.upstream));
3122
+
3123
+ // 3. Evaluate upstream status for each component
3124
+ const checkedComponents = allComponents.map((c) => {
3125
+ let status = "untracked";
3126
+ let message = "No upstream source link recorded";
3127
+ const checkedAt = now.toISOString();
3128
+
3129
+ if (c.upstream) {
3130
+ status = "up-to-date";
3131
+ message = `Tracked upstream: ${c.upstream}`;
3132
+ if (fs.existsSync(path.join(c.path, ".git"))) {
3133
+ message = `Git repository linked to ${c.upstream}`;
3134
+ }
3135
+ }
3136
+
3137
+ return {
3138
+ id: c.id,
3139
+ name: c.name,
3140
+ type: c.type,
3141
+ path: c.path,
3142
+ version: c.version || "1.0.0",
3143
+ upstream: c.upstream || null,
3144
+ status,
3145
+ message,
3146
+ checkedAt,
3147
+ };
3148
+ });
3149
+
3150
+ const trackedCount = trackedComponents.length;
3151
+ const upToDateCount = checkedComponents.filter((c) => c.status === "up-to-date").length;
3152
+
3153
+ const summary = trackedCount > 0
3154
+ ? `Weekly upstream check completed: ${trackedCount}/${allComponents.length} component(s) tracked with upstream links, all up to date.`
3155
+ : `Weekly upstream check completed: ${allComponents.length} component(s) found in storage (0 recorded upstream links).`;
3156
+
3157
+ const newState = {
3158
+ version: "1.0.0",
3159
+ hubRoot: cleanHub,
3160
+ lastCheckedTimestamp: now.toISOString(),
3161
+ weekMonday: currentMonday.toISOString(),
3162
+ nextDueMonday: nextMonday.toISOString(),
3163
+ totalComponents: allComponents.length,
3164
+ trackedCount,
3165
+ upToDateCount,
3166
+ summary,
3167
+ components: checkedComponents,
3168
+ removedMechanisms: cleanedMechanisms.removed,
3169
+ };
3170
+
3171
+ saveCentralizedUpstreamUpdateState(cleanHub, newState);
3172
+
3173
+ return {
3174
+ checked: true,
3175
+ success: true,
3176
+ hubRoot: cleanHub,
3177
+ ...newState,
3178
+ };
3179
+ }
3180
+
3181
+ /**
3182
+ * Universal startup check & auto-reconnect function:
3183
+ * Checks for any modification differences in the Components Storage Path on startup,
3184
+ * and if differences are detected (or forced), automatically reconnects / re-synchronizes
3185
+ * all configured connected agents.
3186
+ * Also performs centralized weekly Monday upstream update checks.
3187
+ */
3188
+ export function checkAndAutoReconnectOnStartup(customHubConfig = null, options = {}) {
3189
+ const cfg = customHubConfig || loadHubConfig();
3190
+ const effHub = getEffectiveHubRoot(cfg);
3191
+ const { force = false } = options;
3192
+
3193
+ // 1. Decentralized update mechanism cleanup & Centralized weekly Monday update check
3194
+ let centralUpdates = null;
3195
+ try {
3196
+ centralUpdates = checkCentralizedUpstreamUpdates(effHub, {
3197
+ force,
3198
+ now: options.now || new Date(),
3199
+ });
3200
+ } catch (err) {
3201
+ centralUpdates = { checked: false, error: err.message };
3202
+ }
3203
+
3204
+ const currentSnapshot = getComponentsStorageSnapshot(effHub);
3205
+ const prevSnapshot = loadComponentsStorageSnapshot(effHub);
3206
+ const diff = diffComponentsStorageSnapshots(prevSnapshot, currentSnapshot);
3207
+
3208
+ const plugins = scanPlugins(effHub);
3209
+ const preCheck = recheckConnectedAgentsStatus(cfg, plugins, options);
3210
+
3211
+ // If force is requested, component modifications were detected, OR enabled components are missing on disk:
3212
+ // auto-reconnect connected agents!
3213
+ if (diff.hasChanges || force || preCheck.hasMissingComponents) {
3214
+ const categories = buildCategoriesRegistry(plugins, effHub);
3215
+ const syncRes = syncAllIdes(cfg, plugins);
3216
+ const postSyncSnapshot = getComponentsStorageSnapshot(effHub);
3217
+ saveComponentsStorageSnapshot(effHub, postSyncSnapshot);
3218
+
3219
+ const postCheck = recheckConnectedAgentsStatus(cfg, plugins, options);
3220
+ const connectedAgents = (cfg.ides || []).filter((i) => i.enabled !== false).map((i) => i.name || i.id);
3221
+
3222
+ return {
3223
+ success: true,
3224
+ startup: true,
3225
+ hasChanges: Boolean(diff.hasChanges || preCheck.hasMissingComponents),
3226
+ autoReconnected: true,
3227
+ hubRoot: effHub,
3228
+ diff,
3229
+ connectedAgentsCount: connectedAgents.length,
3230
+ connectedAgents,
3231
+ sync: syncRes,
3232
+ statusByIde: postCheck.statusByIde,
3233
+ statusByProject: postCheck.statusByProject,
3234
+ verifiedAgents: postCheck.verifiedAgents,
3235
+ centralUpdates,
3236
+ summary: diff.hasChanges
3237
+ ? diff.summary
3238
+ : (preCheck.hasMissingComponents ? "Restored missing plugin components in connected agents" : diff.summary),
3239
+ };
3240
+ }
3241
+
3242
+ return {
3243
+ success: true,
3244
+ startup: true,
3245
+ hasChanges: false,
3246
+ autoReconnected: false,
3247
+ hubRoot: effHub,
3248
+ diff,
3249
+ connectedAgentsCount: (cfg.ides || []).filter((i) => i.enabled !== false).length,
3250
+ connectedAgents: (cfg.ides || []).filter((i) => i.enabled !== false).map((i) => i.name || i.id),
3251
+ statusByIde: preCheck.statusByIde,
3252
+ statusByProject: preCheck.statusByProject,
3253
+ verifiedAgents: preCheck.verifiedAgents,
3254
+ centralUpdates,
3255
+ summary: diff.summary,
3256
+ };
3257
+ }
3258
+
3259
+ /**
3260
+ * Verifies on-disk physical presence of component files and directories
3261
+ * for an enabled plugin in a connected agent IDE.
3262
+ */
3263
+ export function verifyPluginWorkabilityOnDisk(plugin, ide, options = {}) {
3264
+ const base = evaluateComponentAgentWorkability(plugin, ide, { ...options, checkDisk: false });
3265
+ if (!base.workable) {
3266
+ return base;
3267
+ }
3268
+
3269
+ if (options.checkDisk === false) {
3270
+ return base;
3271
+ }
3272
+
3273
+ try {
3274
+ const normalized = normalizeIdeEntry(ide);
3275
+ const home = getHomeDir();
3276
+ const appData = getAppDataDir(home);
3277
+ const paths = resolveEffectiveAgentPaths(normalized, home, appData);
3278
+ const primaryDir = expandHomePath(paths.primary || paths.bundle || paths.skills || normalized.configPath);
3279
+
3280
+ if (!primaryDir || !fs.existsSync(primaryDir)) {
3281
+ return {
3282
+ ...base,
3283
+ workable: false,
3284
+ color: "red",
3285
+ status: "missing_on_disk",
3286
+ summary: `Target directory missing for ${ide.name || ide.id}`,
3287
+ tooltip: `🔴 Connection failed / Missing directory: Target path "${primaryDir || "undefined"}" does not exist on disk.`,
3288
+ reason: `Target directory "${primaryDir || "undefined"}" does not exist on disk`,
3289
+ };
3290
+ }
3291
+
3292
+ const profile = AGENT_PROFILES[normalized.agentType] || AGENT_PROFILES.custom;
3293
+
3294
+ // 1. Bundle Mode (e.g. Antigravity)
3295
+ if (profile.mode === "bundle") {
3296
+ const bundleDir = paths.bundle || primaryDir;
3297
+ const pluginBundleDir = path.join(bundleDir, plugin.id);
3298
+ if (!fs.existsSync(pluginBundleDir)) {
3299
+ return {
3300
+ ...base,
3301
+ workable: false,
3302
+ color: "red",
3303
+ status: "missing_on_disk",
3304
+ summary: `Plugin bundle missing in ${ide.name || ide.id}`,
3305
+ tooltip: `🔴 Connection failed / Missing on disk: Plugin bundle "${plugin.id}" is not deployed in "${bundleDir}".`,
3306
+ reason: `Plugin bundle "${plugin.id}" is not deployed in "${bundleDir}"`,
3307
+ };
3308
+ }
3309
+ } else {
3310
+ // 2. Converted / Native Mode (Claude Code, Codex, OpenCode, VS Code Copilot, Cursor, Windsurf, etc.)
3311
+ if (Array.isArray(plugin.skills) && plugin.skills.length > 0) {
3312
+ const skillsDir = paths.skills || primaryDir;
3313
+ for (const s of plugin.skills) {
3314
+ const sName = typeof s === "string" ? s : s.name;
3315
+ const sPath1 = path.join(skillsDir, sName);
3316
+ const sPath2 = path.join(skillsDir, sName, "SKILL.md");
3317
+ if (!fs.existsSync(sPath1) && !fs.existsSync(sPath2)) {
3318
+ return {
3319
+ ...base,
3320
+ workable: false,
3321
+ color: "red",
3322
+ status: "missing_on_disk",
3323
+ summary: `Skill "${sName}" missing on disk in ${ide.name || ide.id}`,
3324
+ tooltip: `🔴 Connection failed / Missing on disk: Skill "${sName}" is enabled but not found in "${skillsDir}".`,
3325
+ reason: `Skill "${sName}" is missing in "${skillsDir}"`,
3326
+ };
3327
+ }
3328
+ }
3329
+ }
3330
+ }
3331
+
3332
+ return {
3333
+ ...base,
3334
+ workable: true,
3335
+ color: "green",
3336
+ status: "workable",
3337
+ verifiedOnDisk: true,
3338
+ tooltip: base.tooltip ? base.tooltip.replace("Connected & ready.", "Connected & ready (verified on disk).") : base.tooltip,
3339
+ };
3340
+ } catch {
3341
+ return base;
3342
+ }
3343
+ }
3344
+
3345
+ /**
3346
+ * Verifies on-disk physical presence for project override components.
3347
+ */
3348
+ export function verifyProjectPluginWorkabilityOnDisk(plugin, project, parentIde = null) {
3349
+ if (!project || !project.repoPath) {
3350
+ return { workable: false, color: "red", status: "failed", features: {}, summary: "Project repository path missing", tooltip: "🔴 Connection failed: Repository path does not exist" };
3351
+ }
3352
+ const isEnabled = project.plugins && project.plugins[plugin.id] !== undefined
3353
+ ? project.plugins[plugin.id] === true
3354
+ : Boolean(parentIde?.plugins && parentIde.plugins[plugin.id] === true);
3355
+ if (!isEnabled) {
3356
+ return { workable: false, color: "red", status: "disabled", features: {}, summary: `Disabled for project "${project.name}"`, tooltip: `🔴 Connection failed / Disabled: Component is toggled OFF for project "${project.name}"` };
3357
+ }
3358
+ if (!fs.existsSync(project.repoPath)) {
3359
+ return { workable: false, color: "red", status: "missing_on_disk", features: {}, summary: "Project path not found on disk", tooltip: `🔴 Connection failed / Missing on disk: Project repository "${project.repoPath}" not found on disk.` };
3360
+ }
3361
+ return { workable: true, color: "green", status: "workable", verifiedOnDisk: true, summary: `Workable in ${project.name}`, tooltip: `🟢 Workable in Project "${project.name}": Repository linked & protected (.git/info/exclude).` };
3362
+ }
3363
+
3364
+ /**
3365
+ * Rechecks the workability status dot for each enabled plugin across all connected agents and projects.
3366
+ */
3367
+ export function recheckConnectedAgentsStatus(hubConfig = null, plugins = null, options = {}) {
3368
+ const cfg = hubConfig || loadHubConfig();
3369
+ const effHub = getEffectiveHubRoot(cfg);
3370
+ const allPlugins = plugins || scanPlugins(effHub);
3371
+
3372
+ const statusByIde = {};
3373
+ const statusByProject = {};
3374
+ let totalChecked = 0;
3375
+ let hasMissingComponents = false;
3376
+ const verifiedAgents = [];
3377
+
3378
+ const connectedIdes = (cfg.ides || []).filter((i) => i && i.enabled !== false);
3379
+
3380
+ for (const ide of connectedIdes) {
3381
+ const ideKey = ide.id || ide.agentType || "ide";
3382
+ statusByIde[ideKey] = {};
3383
+ verifiedAgents.push(ideKey);
3384
+
3385
+ for (const plugin of allPlugins) {
3386
+ const isEnabled = Boolean(ide.plugins && ide.plugins[plugin.id] === true);
3387
+ const res = verifyPluginWorkabilityOnDisk(plugin, ide, options);
3388
+ statusByIde[ideKey][plugin.id] = res;
3389
+ totalChecked++;
3390
+
3391
+ if (isEnabled && res.status === "missing_on_disk") {
3392
+ hasMissingComponents = true;
3393
+ }
3394
+ }
3395
+ }
3396
+
3397
+ for (const proj of (cfg.projects || [])) {
3398
+ statusByProject[proj.id] = {};
3399
+ const parentIde = (cfg.ides || []).find((i) => i.id === proj.ideId) || null;
3400
+ for (const plugin of allPlugins) {
3401
+ const res = verifyProjectPluginWorkabilityOnDisk(plugin, proj, parentIde);
3402
+ statusByProject[proj.id][plugin.id] = res;
3403
+ }
3404
+ }
3405
+
3406
+ return {
3407
+ success: true,
3408
+ timestamp: Date.now(),
3409
+ hubRoot: effHub,
3410
+ totalChecked,
3411
+ hasMissingComponents,
3412
+ verifiedAgents,
3413
+ statusByIde,
3414
+ statusByProject,
3415
+ };
3416
+ }
3417
+
3418
+ /**
3419
+ * Evaluates whether a component / plugin is workable in a given connected agent (IDE),
3420
+ * determining the status dot color (green vs red) and detecting `@` mention or `/` slash quick actions.
3421
+ */
3422
+ export function evaluateComponentAgentWorkability(plugin, ide, options = {}) {
3423
+ if (options.verifiedStatus && plugin?.id && options.verifiedStatus[plugin.id]) {
3424
+ return options.verifiedStatus[plugin.id];
3425
+ }
3426
+ if (options.checkDisk === true && plugin && ide) {
3427
+ return verifyPluginWorkabilityOnDisk(plugin, ide, { ...options, checkDisk: undefined });
3428
+ }
3429
+ if (!plugin) {
3430
+ return {
3431
+ workable: false,
3432
+ color: "red",
3433
+ status: "failed",
3434
+ quickActions: { slashCommands: [], mentions: [], hasSlash: false, hasMention: false, hasMcp: false, hasRules: false },
3435
+ summary: "No component provided",
3436
+ tooltip: "🔴 Error: No component provided",
3437
+ reason: "No component provided",
3438
+ };
3439
+ }
3440
+
3441
+ if (!ide) {
3442
+ return {
3443
+ workable: false,
3444
+ color: "red",
3445
+ status: "failed",
3446
+ quickActions: { slashCommands: [], mentions: [], hasSlash: false, hasMention: false, hasMcp: false, hasRules: false },
3447
+ summary: "No connected agent selected",
3448
+ tooltip: "🔴 Connection failed: No connected agent selected. Click an agent on the left to inspect workability.",
3449
+ reason: "No connected agent selected",
3450
+ };
3451
+ }
3452
+
3453
+ // 1. Agent disabled in settings
3454
+ if (ide.enabled === false) {
3455
+ return {
3456
+ workable: false,
3457
+ color: "red",
3458
+ status: "disabled",
3459
+ quickActions: { slashCommands: [], mentions: [], hasSlash: false, hasMention: false, hasMcp: false, hasRules: false },
3460
+ summary: `Agent "${ide.name || ide.id}" is disabled`,
3461
+ tooltip: `🔴 Connection failed: Agent "${ide.name || ide.id}" is disabled in settings`,
3462
+ reason: `Agent "${ide.name || ide.id}" is disabled in settings`,
3463
+ };
3464
+ }
3465
+
3466
+ // 2. Agent target configuration / link path missing
3467
+ const configPath = ide.configPath || (ide.componentPaths && (ide.componentPaths.skills || ide.componentPaths.bundle));
3468
+ if (!configPath || String(configPath).trim() === "") {
3469
+ return {
3470
+ workable: false,
3471
+ color: "red",
3472
+ status: "failed",
3473
+ quickActions: { slashCommands: [], mentions: [], hasSlash: false, hasMention: false, hasMcp: false, hasRules: false },
3474
+ summary: `Agent "${ide.name || ide.id}" has no configuration path`,
3475
+ tooltip: `🔴 Connection failed: Target link path for "${ide.name || ide.id}" is not configured`,
3476
+ reason: `Target link path for "${ide.name || ide.id}" is not configured`,
3477
+ };
3478
+ }
3479
+
3480
+ // 3. Component toggled OFF / unselected for this specific agent (default is disabled/unselected)
3481
+ const isEnabled = Boolean(ide.plugins && ide.plugins[plugin.id] === true);
3482
+ if (!isEnabled) {
3483
+ return {
3484
+ workable: false,
3485
+ color: "red",
3486
+ status: "disabled",
3487
+ quickActions: { slashCommands: [], mentions: [], hasSlash: false, hasMention: false, hasMcp: false, hasRules: false },
3488
+ summary: `Disabled for ${ide.name || ide.id}`,
3489
+ tooltip: `🔴 Connection failed / Disabled: Component is toggled OFF for "${ide.name || ide.id}". Turn on toggle switch to connect.`,
3490
+ reason: `Component is toggled OFF for "${ide.name || ide.id}"`,
3491
+ };
3492
+ }
3493
+
3494
+ // 4. Sync error check if provided in options
3495
+ if (options.lastSync && options.lastSync.success === false) {
3496
+ const errMsg = options.lastSync.error || options.lastSync.message || "Sync error";
3497
+ return {
3498
+ workable: false,
3499
+ color: "red",
3500
+ status: "failed",
3501
+ quickActions: { slashCommands: [], mentions: [], hasSlash: false, hasMention: false, hasMcp: false, hasRules: false },
3502
+ summary: `Connection failed: ${errMsg}`,
3503
+ tooltip: `🔴 Connection failed to "${ide.name || ide.id}": ${errMsg}`,
3504
+ reason: errMsg,
3505
+ };
3506
+ }
3507
+
3508
+ // 5. Granular per-feature check:
3509
+ // Identify component types ACTUALLY INSIDE the plugin.
3510
+ // Explicitly SKIP any component type that is NOT present in the plugin.
3511
+ const rawSkills = Array.isArray(plugin.skills) ? plugin.skills : [];
3512
+ const hasSkillsInside = rawSkills.length > 0;
3513
+
3514
+ const rawAgents = Array.isArray(plugin.agents) ? plugin.agents : [];
3515
+ const hasAgentsInside = rawAgents.length > 0;
3516
+
3517
+ const rawMcps = Array.isArray(plugin.mcps) ? plugin.mcps : [];
3518
+ const hasMcpInside = Boolean(plugin.hasMcp || rawMcps.length > 0);
3519
+
3520
+ const rawRules = Array.isArray(plugin.rules) ? plugin.rules : [];
3521
+ const hasRulesInside = rawRules.length > 0;
3522
+
3523
+ const rawHooks = Array.isArray(plugin.hooks) ? plugin.hooks : [];
3524
+ const hasHooksInside = Boolean(plugin.hasHooks || rawHooks.length > 0);
3525
+
3526
+ const hasAnyFeature = hasSkillsInside || hasAgentsInside || hasMcpInside || hasRulesInside || hasHooksInside || (plugin.filesCount && plugin.filesCount > 0);
3527
+ if (!hasAnyFeature && !plugin.path) {
3528
+ return {
3529
+ workable: false,
3530
+ color: "red",
3531
+ status: "failed",
3532
+ features: {},
3533
+ quickActions: { slashCommands: [], mentions: [], hasSlash: false, hasMention: false, hasMcp: false, hasRules: false, hasHooks: false },
3534
+ summary: "Empty component (no skills, MCP, rules, or agents found)",
3535
+ tooltip: `🔴 Connection failed: No workable components discovered in "${plugin.name || plugin.id}"`,
3536
+ reason: "No workable components discovered in plugin",
3537
+ };
3538
+ }
3539
+
3540
+ // Resolve agent profile capabilities
3541
+ const agentType = String(ide.agentType || ide.id || "").toLowerCase();
3542
+ const profile = AGENT_PROFILES[agentType] || AGENT_PROFILES.custom;
3543
+ const isBundle = profile?.mode === "bundle";
3544
+ const customPaths = ide.componentPaths || {};
3545
+
3546
+ const capabilities = {
3547
+ skills: isBundle || customPaths.skills ? true : (profile?.capabilities?.skills ?? true),
3548
+ mcp: isBundle || customPaths.mcp ? true : (profile?.capabilities?.mcp ?? true),
3549
+ rules: isBundle || customPaths.rules ? true : (profile?.capabilities?.rules ?? true),
3550
+ agents: isBundle || customPaths.agents ? true : (profile?.capabilities?.agents ?? true),
3551
+ hooks: isBundle || customPaths.hooks ? true : (profile?.capabilities?.hooks ?? true),
3552
+ };
3553
+
3554
+ const features = {};
3555
+ const actionParts = [];
3556
+ const detailedTooltipLines = [];
3557
+ let workableCount = 0;
3558
+ let presentTypeCount = 0;
3559
+
3560
+ // 1. Skills Check (only if present inside plugin)
3561
+ let slashCommands = [];
3562
+ if (hasSkillsInside) {
3563
+ presentTypeCount++;
3564
+ slashCommands = rawSkills.map((s) => (typeof s === "string" ? `/${s}` : `/${s.name}`));
3565
+ const isSupported = capabilities.skills === true;
3566
+ if (isSupported) {
3567
+ workableCount++;
3568
+ actionParts.push(`Quick action: ${slashCommands.join(" ")}`);
3569
+ detailedTooltipLines.push(`✓ Skills (${slashCommands.length}): ${slashCommands.join(" ")}`);
3570
+ } else {
3571
+ detailedTooltipLines.push(`✗ Skills (${slashCommands.length}): Skipped (unsupported by ${ide.name || ide.id})`);
3572
+ }
3573
+ features.skills = {
3574
+ present: true,
3575
+ count: slashCommands.length,
3576
+ workable: isSupported,
3577
+ items: slashCommands,
3578
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
3579
+ };
3580
+ }
3581
+
3582
+ // 2. Agents / Subagents Check (only if present inside plugin)
3583
+ let mentions = [];
3584
+ if (hasAgentsInside) {
3585
+ presentTypeCount++;
3586
+ mentions = rawAgents.map((a) => {
3587
+ const rawName = typeof a === "string" ? a : a.name || "";
3588
+ return `@${rawName.replace(/\.md$/i, "")}`;
3589
+ });
3590
+ const isSupported = capabilities.agents === true;
3591
+ if (isSupported) {
3592
+ workableCount++;
3593
+ actionParts.push(`Quick action: ${mentions.join(" ")}`);
3594
+ detailedTooltipLines.push(`✓ Agents (${mentions.length}): ${mentions.join(" ")}`);
3595
+ } else {
3596
+ detailedTooltipLines.push(`✗ Agents (${mentions.length}): Skipped (unsupported by ${ide.name || ide.id})`);
3597
+ }
3598
+ features.agents = {
3599
+ present: true,
3600
+ count: mentions.length,
3601
+ workable: isSupported,
3602
+ items: mentions,
3603
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
3604
+ };
3605
+ }
3606
+
3607
+ // 3. MCP Servers Check (only if present inside plugin)
3608
+ if (hasMcpInside) {
3609
+ presentTypeCount++;
3610
+ const mcpNames = rawMcps.length > 0 ? rawMcps : [plugin.id || "mcp"];
3611
+ const isSupported = capabilities.mcp === true;
3612
+ if (isSupported) {
3613
+ workableCount++;
3614
+ actionParts.push("MCP tools active");
3615
+ detailedTooltipLines.push(`✓ MCP (${mcpNames.length}): ${mcpNames.join(", ")} active`);
3616
+ } else {
3617
+ detailedTooltipLines.push(`✗ MCP (${mcpNames.length}): Skipped (unsupported by ${ide.name || ide.id})`);
3618
+ }
3619
+ features.mcp = {
3620
+ present: true,
3621
+ count: mcpNames.length,
3622
+ workable: isSupported,
3623
+ items: mcpNames,
3624
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
3625
+ };
3626
+ }
3627
+
3628
+ // 4. Rules Check (only if present inside plugin)
3629
+ if (hasRulesInside) {
3630
+ presentTypeCount++;
3631
+ const ruleNames = rawRules.map((r) => (typeof r === "string" ? r : r.name || ""));
3632
+ const isSupported = capabilities.rules === true;
3633
+ if (isSupported) {
3634
+ workableCount++;
3635
+ actionParts.push("Rules active");
3636
+ detailedTooltipLines.push(`✓ Rules (${ruleNames.length}): ${ruleNames.join(", ")} active`);
3637
+ } else {
3638
+ detailedTooltipLines.push(`✗ Rules (${ruleNames.length}): Skipped (unsupported by ${ide.name || ide.id})`);
3639
+ }
3640
+ features.rules = {
3641
+ present: true,
3642
+ count: ruleNames.length,
3643
+ workable: isSupported,
3644
+ items: ruleNames,
3645
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
3646
+ };
3647
+ }
3648
+
3649
+ // 5. Hooks Check (only if present inside plugin)
3650
+ if (hasHooksInside) {
3651
+ presentTypeCount++;
3652
+ const hookCount = rawHooks.length > 0 ? rawHooks.length : 1;
3653
+ const isSupported = capabilities.hooks === true;
3654
+ if (isSupported) {
3655
+ workableCount++;
3656
+ actionParts.push("Hooks active");
3657
+ detailedTooltipLines.push(`✓ Hooks (${hookCount}): Active`);
3658
+ } else {
3659
+ detailedTooltipLines.push(`✗ Hooks (${hookCount}): Skipped (unsupported by ${ide.name || ide.id})`);
3660
+ }
3661
+ features.hooks = {
3662
+ present: true,
3663
+ count: hookCount,
3664
+ workable: isSupported,
3665
+ items: rawHooks,
3666
+ reason: isSupported ? "Active" : `Unsupported by ${ide.name || ide.id}`,
3667
+ };
3668
+ }
3669
+
3670
+ // If component has types present but NONE of them are supported by this agent
3671
+ if (presentTypeCount > 0 && workableCount === 0) {
3672
+ return {
3673
+ workable: false,
3674
+ color: "red",
3675
+ status: "unsupported",
3676
+ features,
3677
+ quickActions: {
3678
+ slashCommands,
3679
+ mentions,
3680
+ hasSlash: false,
3681
+ hasMention: false,
3682
+ hasMcp: false,
3683
+ hasRules: false,
3684
+ hasHooks: false,
3685
+ },
3686
+ summary: `Incompatible with ${ide.name || ide.id}`,
3687
+ tooltip: `🔴 Incompatible with ${ide.name || ide.id}: All component types in "${plugin.name || plugin.id}" are unsupported.`,
3688
+ reason: `All component types in "${plugin.name || plugin.id}" are unsupported by ${ide.name || ide.id}`,
3689
+ };
3690
+ }
3691
+
3692
+ const hasSlash = slashCommands.length > 0 && capabilities.skills === true;
3693
+ const hasMention = mentions.length > 0 && capabilities.agents === true;
3694
+ const hasMcp = hasMcpInside && capabilities.mcp === true;
3695
+ const hasRules = hasRulesInside && capabilities.rules === true;
3696
+ const hasHooks = hasHooksInside && capabilities.hooks === true;
3697
+
3698
+ const summary = `Workable in ${ide.name || ide.id}${actionParts.length > 0 ? " · " + actionParts.join(" · ") : ""}`;
3699
+ const baseTooltip = `🟢 Workable in ${ide.name || ide.id}: Connected & ready.${actionParts.length > 0 ? " Can be used with " + actionParts.join(" | ") : ""}`;
3700
+ const tooltip = detailedTooltipLines.length > 0 ? `${baseTooltip}\n${detailedTooltipLines.join("\n")}` : baseTooltip;
3701
+
3702
+ return {
3703
+ workable: true,
3704
+ color: "green",
3705
+ status: "workable",
3706
+ features,
3707
+ quickActions: {
3708
+ slashCommands,
3709
+ mentions,
3710
+ hasSlash,
3711
+ hasMention,
3712
+ hasMcp,
3713
+ hasRules,
3714
+ hasHooks,
3715
+ },
3716
+ summary,
3717
+ tooltip,
3718
+ reason: "",
3719
+ };
3720
+ }
3721
+
3722
+ // --- OmniRoute AI Gateway Functions ---
3723
+
3724
+ export function getOmniroutePort(hubConfig = null) {
3725
+ if (hubConfig?.omniroute?.port && Number.isInteger(Number(hubConfig.omniroute.port))) {
3726
+ return Number(hubConfig.omniroute.port);
3727
+ }
3728
+ try {
3729
+ const envPath = path.join(getHomeDir(), ".omniroute", ".env");
3730
+ if (fs.existsSync(envPath)) {
3731
+ const content = fs.readFileSync(envPath, "utf8");
3732
+ for (const line of content.split(/\r?\n/)) {
3733
+ const trimmed = line.trim();
3734
+ if (trimmed.startsWith("PORT=") || trimmed.startsWith("OMNIROUTE_PORT=")) {
3735
+ const val = parseInt(trimmed.split("=")[1]?.trim(), 10);
3736
+ if (val && !isNaN(val)) return val;
3737
+ }
3738
+ }
3739
+ }
3740
+ } catch {}
3741
+ return 20128;
3742
+ }
3743
+
3744
+ export function isOmnirouteInstalled() {
3745
+ try {
3746
+ const dataDir = path.join(getHomeDir(), ".omniroute");
3747
+ if (fs.existsSync(dataDir)) return true;
3748
+ if (process.platform === "win32") {
3749
+ const npmGlobal = path.join(process.env.APPDATA || "", "npm", "omniroute.cmd");
3750
+ if (fs.existsSync(npmGlobal)) return true;
3751
+ const res = execSync("where omniroute 2>nul", { encoding: "utf8" });
3752
+ if (res && res.trim().length > 0) return true;
3753
+ } else {
3754
+ const res = execSync("which omniroute 2>/dev/null", { encoding: "utf8" });
3755
+ if (res && res.trim().length > 0) return true;
3756
+ }
3757
+ } catch {}
3758
+ return false;
3759
+ }
3760
+
3761
+ export async function checkOmnirouteStatus(customPort = null, hubConfig = null) {
3762
+ const port = customPort || getOmniroutePort(hubConfig);
3763
+ const installed = isOmnirouteInstalled();
3764
+
3765
+ // Fast TCP connectivity check to avoid hanging or slow probing when port is closed
3766
+ const isTcpReachable = (host) =>
3767
+ new Promise((resolve) => {
3768
+ const socket = net.createConnection({ port, host, timeout: 400 });
3769
+ socket.on("connect", () => {
3770
+ socket.destroy();
3771
+ resolve(true);
3772
+ });
3773
+ socket.on("timeout", () => {
3774
+ socket.destroy();
3775
+ resolve(false);
3776
+ });
3777
+ socket.on("error", () => {
3778
+ resolve(false);
3779
+ });
3780
+ });
3781
+
3782
+ // Test reachability quickly on 127.0.0.1 and localhost
3783
+ const [tcpIpv4, tcpLocal] = await Promise.all([
3784
+ isTcpReachable("127.0.0.1"),
3785
+ isTcpReachable("localhost"),
3786
+ ]);
3787
+
3788
+ if (!tcpIpv4 && !tcpLocal) {
3789
+ return {
3790
+ installed,
3791
+ running: false,
3792
+ port,
3793
+ url: `http://localhost:${port}`,
3794
+ statusCode: null,
3795
+ };
3796
+ }
3797
+
3798
+ const checkHostAndPath = (host, testPath) =>
3799
+ new Promise((resolve) => {
3800
+ const req = http.get(`http://${host}:${port}${testPath}`, { timeout: 1200 }, (res) => {
3801
+ res.resume();
3802
+ resolve({
3803
+ ok: res.statusCode >= 200 && res.statusCode < 600,
3804
+ statusCode: res.statusCode,
3805
+ });
3806
+ });
3807
+
3808
+ req.on("timeout", () => {
3809
+ req.destroy();
3810
+ resolve({ ok: false, error: "timeout" });
3811
+ });
3812
+
3813
+ req.on("error", (err) => {
3814
+ resolve({ ok: false, error: err.message });
3815
+ });
3816
+ });
3817
+
3818
+ const hostsToProbe = tcpIpv4 ? ["127.0.0.1", "localhost"] : ["localhost", "127.0.0.1"];
3819
+ const pathsToProbe = ["/api/health", "/login", "/", "/v1/models"];
3820
+
3821
+ let probe = { ok: false };
3822
+ for (const host of hostsToProbe) {
3823
+ for (const testPath of pathsToProbe) {
3824
+ probe = await checkHostAndPath(host, testPath);
3825
+ if (probe.ok) break;
3826
+ }
3827
+ if (probe.ok) break;
3828
+ }
3829
+
3830
+ const running = Boolean(probe.ok);
3831
+ return {
3832
+ installed,
3833
+ running,
3834
+ port,
3835
+ url: `http://localhost:${port}`,
3836
+ statusCode: probe.statusCode || null,
3837
+ };
3838
+ }
3839
+
3840
+ export function findNodeBinary() {
3841
+ // If current process is node (and not bun), use it
3842
+ if (process.execPath && !process.execPath.toLowerCase().includes("bun") && fs.existsSync(process.execPath)) {
3843
+ return process.execPath;
3844
+ }
3845
+ // Standard Windows install locations
3846
+ if (process.platform === "win32") {
3847
+ const standardPaths = [
3848
+ "C:\\Program Files\\nodejs\\node.exe",
3849
+ "C:\\Program Files (x86)\\nodejs\\node.exe",
3850
+ path.join(process.env.LOCALAPPDATA || "", "Programs", "node", "node.exe"),
3851
+ path.join(process.env.APPDATA || "", "npm", "node.exe"),
3852
+ ];
3853
+ for (const p of standardPaths) {
3854
+ if (fs.existsSync(p)) return p;
3855
+ }
3856
+ }
3857
+ const envPath = process.env.PATH || "";
3858
+ for (const dir of envPath.split(path.delimiter)) {
3859
+ if (!dir) continue;
3860
+ const p = path.join(dir, process.platform === "win32" ? "node.exe" : "node");
3861
+ if (fs.existsSync(p)) return p;
3862
+ }
3863
+ return "node";
3864
+ }
3865
+
3866
+ export function findOmnirouteCliPath() {
3867
+ const home = getHomeDir();
3868
+ const candidates = [
3869
+ path.join(process.env.APPDATA || "", "npm", "node_modules", "omniroute", "bin", "omniroute.mjs"),
3870
+ path.join(home, "AppData", "Roaming", "npm", "node_modules", "omniroute", "bin", "omniroute.mjs"),
3871
+ path.join(home, ".omniroute", "node_modules", "omniroute", "bin", "omniroute.mjs"),
3872
+ ];
3873
+ for (const c of candidates) {
3874
+ if (fs.existsSync(c)) return c;
3875
+ }
3876
+ const envPath = process.env.PATH || "";
3877
+ for (const dir of envPath.split(path.delimiter)) {
3878
+ if (!dir) continue;
3879
+ const candidate = path.join(dir, "node_modules", "omniroute", "bin", "omniroute.mjs");
3880
+ if (fs.existsSync(candidate)) return candidate;
3881
+ }
3882
+ return null;
3883
+ }
3884
+
3885
+ let lastOmnirouteStartAttemptTimestamp = 0;
3886
+
3887
+ export function recordOmnirouteStartAttempt() {
3888
+ lastOmnirouteStartAttemptTimestamp = Date.now();
3889
+ }
3890
+
3891
+ export function resetOmnirouteStartAttemptForTest() {
3892
+ lastOmnirouteStartAttemptTimestamp = 0;
3893
+ }
3894
+
3895
+ export function getLastOmnirouteStartAttempt() {
3896
+ return lastOmnirouteStartAttemptTimestamp;
3897
+ }
3898
+
3899
+ let activeOmnirouteStartPromise = null;
3900
+
3901
+ let activeOmnirouteTerminalPid = null;
3902
+
3903
+ function getTerminalPidFilePath() {
3904
+ try {
3905
+ const base = getHomeDir();
3906
+ return path.join(base, ".omniroute-terminal-pid");
3907
+ } catch {
3908
+ return null;
3909
+ }
3910
+ }
3911
+
3912
+ export function recordOmnirouteTerminalPid(pid) {
3913
+ if (!pid || isNaN(pid)) return;
3914
+ activeOmnirouteTerminalPid = Number(pid);
3915
+ try {
3916
+ const file = getTerminalPidFilePath();
3917
+ if (file) {
3918
+ fs.writeFileSync(file, String(pid), "utf8");
3919
+ }
3920
+ } catch {}
3921
+ }
3922
+
3923
+ export function getOmnirouteTerminalPid() {
3924
+ if (activeOmnirouteTerminalPid) return activeOmnirouteTerminalPid;
3925
+ try {
3926
+ const file = getTerminalPidFilePath();
3927
+ if (file && fs.existsSync(file)) {
3928
+ const content = fs.readFileSync(file, "utf8").trim();
3929
+ const num = parseInt(content, 10);
3930
+ if (!isNaN(num) && num > 0) {
3931
+ activeOmnirouteTerminalPid = num;
3932
+ return num;
3933
+ }
3934
+ }
3935
+ } catch {}
3936
+ return null;
3937
+ }
3938
+
3939
+ export function clearOmnirouteTerminalPid() {
3940
+ activeOmnirouteTerminalPid = null;
3941
+ try {
3942
+ const file = getTerminalPidFilePath();
3943
+ if (file && fs.existsSync(file)) {
3944
+ fs.unlinkSync(file);
3945
+ }
3946
+ } catch {}
3947
+ }
3948
+
3949
+ export function closeOmnirouteTerminalWindow() {
3950
+ const pid = getOmnirouteTerminalPid();
3951
+ clearOmnirouteTerminalPid();
3952
+
3953
+ if (process.platform === "win32") {
3954
+ // 1. Terminate tracked terminal process tree
3955
+ if (pid) {
3956
+ try {
3957
+ execSync(`taskkill /PID ${pid} /T /F`, { stdio: "ignore", timeout: 4000 });
3958
+ } catch {}
3959
+ }
3960
+ // 2. Terminate any remaining command prompt window with OmniRoute title
3961
+ try {
3962
+ execSync('taskkill /FI "WINDOWTITLE eq OmniRoute (Magpie)*" /T /F', { stdio: "ignore", timeout: 4000 });
3963
+ } catch {}
3964
+ } else if (pid) {
3965
+ try {
3966
+ process.kill(-pid, "SIGTERM");
3967
+ } catch {
3968
+ try {
3969
+ process.kill(pid, "SIGTERM");
3970
+ } catch {}
3971
+ }
3972
+ }
3973
+ }
3974
+
3975
+ export function findPidByPort(port) {
3976
+ if (process.platform === "win32") {
3977
+ try {
3978
+ const out = execSync("netstat -ano -p tcp", { encoding: "utf8", timeout: 3000 });
3979
+ const lines = out.split(/\r?\n/);
3980
+ for (const line of lines) {
3981
+ if (line.includes(`:${port}`) && line.includes("LISTENING")) {
3982
+ const parts = line.trim().split(/\s+/);
3983
+ const pid = parseInt(parts[parts.length - 1], 10);
3984
+ if (!isNaN(pid) && pid > 0) return pid;
3985
+ }
3986
+ }
3987
+ } catch {}
3988
+ }
3989
+ return null;
3990
+ }
3991
+
3992
+ export function startOmniroute(customPort = null, hubConfig = null) {
3993
+ if (activeOmnirouteStartPromise) {
3994
+ return activeOmnirouteStartPromise;
3995
+ }
3996
+ activeOmnirouteStartPromise = (async () => {
3997
+ recordOmnirouteStartAttempt();
3998
+ const port = customPort || getOmniroutePort(hubConfig);
3999
+ const statusBefore = await checkOmnirouteStatus(port, hubConfig);
4000
+ if (statusBefore.running) {
4001
+ return { success: true, running: true, port, url: statusBefore.url, alreadyRunning: true };
4002
+ }
4003
+
4004
+ try {
4005
+ const cliPath = findOmnirouteCliPath();
4006
+ const nodeBin = findNodeBinary();
4007
+ const home = getHomeDir();
4008
+ let child;
4009
+
4010
+ // Command Prompt Terminal execution:
4011
+ // Spawns visible cmd.exe terminal running 'omniroute serve --no-open'
4012
+ // - Window title set to 'OmniRoute (Magpie)'
4013
+ // - Tracked via PID and window title so that when Magpie closes, the terminal window is also closed
4014
+ const portFlag = port && port !== 20128 ? ` --port ${port}` : "";
4015
+ const cmdToRun = `omniroute serve${portFlag} --no-open --no-recovery`;
4016
+ const terminalTitle = "OmniRoute (Magpie)";
4017
+
4018
+ if (process.platform === "win32") {
4019
+ let launchedInTerminal = false;
4020
+ try {
4021
+ const psScript = `$p = Start-Process cmd.exe -ArgumentList '/k title ${terminalTitle} & ${cmdToRun}' -WindowStyle Normal -PassThru; $p.Id`;
4022
+ const out = execSync(`powershell.exe -NoProfile -Command "${psScript}"`, { encoding: "utf8", timeout: 8000 });
4023
+ const terminalPid = parseInt(out.trim(), 10);
4024
+ if (!isNaN(terminalPid) && terminalPid > 0) {
4025
+ recordOmnirouteTerminalPid(terminalPid);
4026
+ launchedInTerminal = true;
4027
+ }
4028
+ } catch {}
4029
+
4030
+ if (!launchedInTerminal) {
4031
+ try {
4032
+ const childProc = spawn("cmd.exe", ["/c", "start", terminalTitle, "cmd.exe", "/k", `title ${terminalTitle} & ${cmdToRun}`], {
4033
+ cwd: home,
4034
+ detached: true,
4035
+ stdio: "ignore",
4036
+ windowsHide: false,
4037
+ });
4038
+ if (childProc) {
4039
+ if (childProc.pid) {
4040
+ recordOmnirouteTerminalPid(childProc.pid);
4041
+ }
4042
+ childProc.unref();
4043
+ launchedInTerminal = true;
4044
+ }
4045
+ } catch {}
4046
+ }
4047
+
4048
+ // Direct node/cli spawn fallback
4049
+ if (!launchedInTerminal) {
4050
+ if (cliPath && fs.existsSync(cliPath)) {
4051
+ child = spawn(nodeBin, [
4052
+ cliPath,
4053
+ "serve",
4054
+ "--port", String(port),
4055
+ "--no-open",
4056
+ "--no-tray",
4057
+ "--no-recovery",
4058
+ ], {
4059
+ cwd: home,
4060
+ detached: true,
4061
+ stdio: "ignore",
4062
+ env: { ...process.env, PORT: String(port) },
4063
+ });
4064
+ } else {
4065
+ child = spawn("cmd.exe", ["/c", "omniroute", "serve", "--port", String(port), "--no-open", "--no-tray", "--no-recovery"], {
4066
+ cwd: home,
4067
+ detached: true,
4068
+ stdio: "ignore",
4069
+ env: { ...process.env, PORT: String(port) },
4070
+ });
4071
+ }
4072
+ }
4073
+ } else if (cliPath && fs.existsSync(cliPath)) {
4074
+ child = spawn(nodeBin, [
4075
+ cliPath,
4076
+ "serve",
4077
+ "--port", String(port),
4078
+ "--no-open",
4079
+ "--no-tray",
4080
+ "--no-recovery",
4081
+ ], {
4082
+ cwd: home,
4083
+ detached: true,
4084
+ stdio: "ignore",
4085
+ env: { ...process.env, PORT: String(port) },
4086
+ });
4087
+ } else {
4088
+ const cmd = "omniroute";
4089
+ child = spawn(cmd, ["serve", "--port", String(port), "--no-open", "--no-tray", "--no-recovery"], {
4090
+ cwd: home,
4091
+ detached: true,
4092
+ stdio: "ignore",
4093
+ env: { ...process.env, PORT: String(port) },
4094
+ });
4095
+ }
4096
+
4097
+ let spawnErr = null;
4098
+ if (child) {
4099
+ child.on("error", (err) => {
4100
+ spawnErr = err;
4101
+ });
4102
+ child.unref();
4103
+ }
4104
+
4105
+ const startTime = Date.now();
4106
+ while (Date.now() - startTime < 25000) {
4107
+ if (spawnErr) {
4108
+ return { success: false, running: false, port, error: spawnErr.message };
4109
+ }
4110
+ await new Promise((r) => setTimeout(r, 400));
4111
+ const s = await checkOmnirouteStatus(port, hubConfig);
4112
+ if (s.running) {
4113
+ if (process.platform === "win32") {
4114
+ const listeningPid = findPidByPort(port);
4115
+ if (listeningPid) recordOmnirouteTerminalPid(listeningPid);
4116
+ }
4117
+ return { success: true, running: true, port, url: s.url };
4118
+ }
4119
+ if (child && child.exitCode !== null && child.exitCode !== 0) {
4120
+ // Recheck once in case process spawned a worker daemon before exiting
4121
+ const doubleCheck = await checkOmnirouteStatus(port, hubConfig);
4122
+ if (doubleCheck.running) {
4123
+ return { success: true, running: true, port, url: doubleCheck.url };
4124
+ }
4125
+ return { success: false, running: false, port, error: `Omniroute process exited with code ${child.exitCode}` };
4126
+ }
4127
+ }
4128
+ } catch (err) {
4129
+ return { success: false, running: false, port, error: err.message };
4130
+ }
4131
+
4132
+ return { success: false, running: false, port, error: "Omniroute failed to start within timeout" };
4133
+ })().finally(() => {
4134
+ activeOmnirouteStartPromise = null;
4135
+ });
4136
+
4137
+ return activeOmnirouteStartPromise;
4138
+ }
4139
+
4140
+ export function stopOmnirouteSync(customPort = null, hubConfig = null) {
4141
+ const port = customPort || getOmniroutePort(hubConfig);
4142
+ try {
4143
+ closeOmnirouteTerminalWindow();
4144
+ } catch {}
4145
+ try {
4146
+ const cliPath = findOmnirouteCliPath();
4147
+ const nodeBin = findNodeBinary();
4148
+ if (cliPath && fs.existsSync(cliPath)) {
4149
+ execFileSync(nodeBin, [cliPath, "stop", "--port", String(port)], { stdio: "ignore", timeout: 8000 });
4150
+ return true;
4151
+ }
4152
+ const cmd = process.platform === "win32" ? "omniroute.cmd" : "omniroute";
4153
+ execFileSync(cmd, ["stop", "--port", String(port)], { stdio: "ignore", timeout: 8000 });
4154
+ return true;
4155
+ } catch {
4156
+ return false;
4157
+ }
4158
+ }
4159
+
4160
+ export async function stopOmniroute(customPort = null, hubConfig = null) {
4161
+ const port = customPort || getOmniroutePort(hubConfig);
4162
+ stopOmnirouteSync(port, hubConfig);
4163
+ await new Promise((r) => setTimeout(r, 400));
4164
+ return checkOmnirouteStatus(port, hubConfig);
4165
+ }
4166
+
4167
+ let lastTasklistProbeTime = 0;
4168
+ let lastTasklistProbeResult = false;
4169
+
4170
+ export async function isMagpieRunning() {
4171
+ if (process.env.ASM_MOCK_MAGPIE === "1") return true;
4172
+ if (process.env.ASM_MOCK_MAGPIE === "0") return false;
4173
+
4174
+ // 1. If executing as a child process of Magpie (e.g. magpie-bun spawned by magpie host)
4175
+ if (process.execPath && /magpie/i.test(process.execPath) && process.ppid && process.ppid > 0) {
4176
+ try {
4177
+ process.kill(process.ppid, 0);
4178
+ return true;
4179
+ } catch {
4180
+ // Parent process may have terminated or this daemon outlived it; fall through to port 3425 and process checks
4181
+ }
4182
+ }
4183
+
4184
+ // 2. Fast in-memory TCP socket check to port 3425 (Magpie host internal API server)
4185
+ const portReachable = await new Promise((resolve) => {
4186
+ const socket = net.createConnection({ port: 3425, host: "127.0.0.1", timeout: 600 });
4187
+ socket.on("connect", () => {
4188
+ socket.destroy();
4189
+ resolve(true);
4190
+ });
4191
+ socket.on("timeout", () => {
4192
+ socket.destroy();
4193
+ resolve(false);
4194
+ });
4195
+ socket.on("error", () => {
4196
+ resolve(false);
4197
+ });
4198
+ });
4199
+ if (portReachable) return true;
4200
+
4201
+ // 3. Fallback check for running Magpie GUI process (throttled to >= 10s to avoid Antivirus process reconnaissance alarms)
4202
+ const now = Date.now();
4203
+ if (now - lastTasklistProbeTime < 10000) {
4204
+ return lastTasklistProbeResult;
4205
+ }
4206
+ lastTasklistProbeTime = now;
4207
+
4208
+ try {
4209
+ if (process.platform === "win32") {
4210
+ const out = execFileSync("tasklist.exe", ["/NH", "/FI", "IMAGENAME eq magpie*"], { encoding: "utf8", timeout: 2000 });
4211
+ lastTasklistProbeResult = /(magpie-windows|magpie\.exe)/i.test(out);
4212
+ return lastTasklistProbeResult;
4213
+ } else {
4214
+ const out = execSync("pgrep -l -f magpie 2>/dev/null || ps -ef | grep magpie", { encoding: "utf8", timeout: 2000 });
4215
+ lastTasklistProbeResult = /(magpie-linux|magpie-darwin|magpie)/i.test(out) && !/magpie-bun/i.test(out);
4216
+ return lastTasklistProbeResult;
4217
+ }
4218
+ } catch {
4219
+ lastTasklistProbeResult = false;
4220
+ }
4221
+
4222
+ return false;
4223
+ }
4224
+
4225
+ export function openUrlInBrowser(url) {
4226
+ if (!url) return false;
4227
+ try {
4228
+ if (process.platform === "win32") {
4229
+ let launched = false;
4230
+ // 1. Direct rundll32 FileProtocolHandler (most reliable on Windows without shell quoting quirks)
4231
+ try {
4232
+ const r = spawn("rundll32.exe", ["url.dll,FileProtocolHandler", url], {
4233
+ detached: true,
4234
+ stdio: "ignore",
4235
+ });
4236
+ r.unref();
4237
+ launched = true;
4238
+ } catch {}
4239
+
4240
+ // 2. Windows cmd.exe start
4241
+ if (!launched) {
4242
+ try {
4243
+ const child = spawn("cmd.exe", ["/c", "start", "", url], {
4244
+ detached: true,
4245
+ stdio: "ignore",
4246
+ });
4247
+ child.unref();
4248
+ launched = true;
4249
+ } catch {}
4250
+ }
4251
+
4252
+ // 3. PowerShell Start-Process fallback
4253
+ if (!launched) {
4254
+ try {
4255
+ const ps = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `Start-Process "${url}"`], {
4256
+ detached: true,
4257
+ stdio: "ignore",
4258
+ });
4259
+ ps.unref();
4260
+ launched = true;
4261
+ } catch {}
4262
+ }
4263
+ return launched;
4264
+ } else if (process.platform === "darwin") {
4265
+ spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
4266
+ return true;
4267
+ } else {
4268
+ spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
4269
+ return true;
4270
+ }
4271
+ } catch {
4272
+ return false;
4273
+ }
4274
+ }
4275
+
4276
+ // --- Foreign Components Scanning, Cleaning & Auto-Enabling ---
4277
+
4278
+ export function scanAgentForeignComponents(agentDef, hubConfig = null, plugins = null) {
4279
+ if (!agentDef) return { hasForeign: false, foreignComponents: [], hubComponents: [] };
4280
+
4281
+ const config = hubConfig || loadHubConfig();
4282
+ const effHub = getEffectiveHubRoot(config);
4283
+ const allPlugins = plugins || scanPlugins(effHub);
4284
+
4285
+ const normIde = normalizeIdeEntry(agentDef);
4286
+ const agentType = normIde.agentType || inferAgentType(normIde);
4287
+ const home = getHomeDir();
4288
+ const appData = getAppDataDir(home);
4289
+ const profile = AGENT_PROFILES[agentType] || AGENT_PROFILES.custom;
4290
+ const paths = profile.resolvePaths ? profile.resolvePaths(home, appData, normIde.name) : { primary: normIde.configPath };
4291
+
4292
+ const checkDirs = new Set();
4293
+ if (normIde.configPath && fs.existsSync(normIde.configPath)) checkDirs.add(normIde.configPath);
4294
+ if (paths.primary && fs.existsSync(paths.primary)) checkDirs.add(paths.primary);
4295
+ if (paths.skills && fs.existsSync(paths.skills)) checkDirs.add(paths.skills);
4296
+ if (paths.rules && fs.existsSync(paths.rules)) checkDirs.add(paths.rules);
4297
+ if (paths.agents && fs.existsSync(paths.agents)) checkDirs.add(paths.agents);
4298
+
4299
+ // Parent directories for plugins, skills, rules, agents subfolders
4300
+ for (const d of Array.from(checkDirs)) {
4301
+ const parent = path.dirname(d);
4302
+ for (const sub of ["plugins", "skills", "rules", "agents"]) {
4303
+ const subPath = path.join(parent, sub);
4304
+ if (fs.existsSync(subPath)) checkDirs.add(subPath);
4305
+ }
4306
+ }
4307
+
4308
+ const foreignComponents = [];
4309
+ const hubComponents = [];
4310
+ const seenPaths = new Set();
4311
+
4312
+ const SYSTEM_DEFAULT_FILENAMES = new Set([
4313
+ ".asm-owned.json",
4314
+ ".git",
4315
+ ".gitignore",
4316
+ ".gitkeep",
4317
+ "desktop.ini",
4318
+ ".ds_store",
4319
+ "thumbs.db",
4320
+ "skills.json",
4321
+ "settings.json",
4322
+ "mcp_config.json",
4323
+ "mcp.json",
4324
+ "config.toml",
4325
+ "opencode.json",
4326
+ "claude_desktop_config.json",
4327
+ "cline_mcp_settings.json",
4328
+ ]);
4329
+
4330
+ for (const dir of checkDirs) {
4331
+ try {
4332
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) continue;
4333
+ const entries = fs.readdirSync(dir);
4334
+ for (const ent of entries) {
4335
+ if (SYSTEM_DEFAULT_FILENAMES.has(ent.toLowerCase())) continue;
4336
+ const fullPath = path.join(dir, ent);
4337
+ if (seenPaths.has(fullPath)) continue;
4338
+ seenPaths.add(fullPath);
4339
+
4340
+ let isSym = false;
4341
+ let symTarget = "";
4342
+ try {
4343
+ const lstat = fs.lstatSync(fullPath);
4344
+ isSym = lstat.isSymbolicLink();
4345
+ if (isSym) symTarget = fs.readlinkSync(fullPath);
4346
+ } catch {}
4347
+
4348
+ const insideHub = (isSym && isTargetInsideHub(symTarget, allPlugins, effHub)) ||
4349
+ isTargetInsideHub(fullPath, allPlugins, effHub) ||
4350
+ isAsmOwnedDirectory(fullPath);
4351
+
4352
+ const matchingPlugin = allPlugins.find((p) =>
4353
+ p.id === ent ||
4354
+ p.name === ent ||
4355
+ (Array.isArray(p.skills) && p.skills.includes(ent)) ||
4356
+ (Array.isArray(p.rules) && (p.rules.includes(ent) || p.rules.some((r) => r.name === ent || path.basename(r.file || "", ".md") === ent)))
4357
+ );
4358
+
4359
+ if (insideHub || matchingPlugin) {
4360
+ hubComponents.push({
4361
+ id: matchingPlugin?.id || ent,
4362
+ name: matchingPlugin?.name || ent,
4363
+ path: fullPath,
4364
+ type: isSym ? "link" : "directory",
4365
+ });
4366
+ } else {
4367
+ let isDir = false;
4368
+ try {
4369
+ isDir = fs.statSync(fullPath).isDirectory();
4370
+ } catch {}
4371
+ foreignComponents.push({
4372
+ name: ent,
4373
+ path: fullPath,
4374
+ type: isSym ? "foreign-link" : (isDir ? "directory" : "file"),
4375
+ });
4376
+ }
4377
+ }
4378
+ } catch {}
4379
+ }
4380
+
4381
+ return {
4382
+ hasForeign: foreignComponents.length > 0,
4383
+ foreignComponents,
4384
+ hubComponents,
4385
+ };
4386
+ }
4387
+
4388
+ export function cleanAgentForeignComponents(componentList = []) {
4389
+ const removed = [];
4390
+ for (const comp of componentList) {
4391
+ const p = typeof comp === "string" ? comp : comp?.path;
4392
+ if (!p || !fs.existsSync(p)) continue;
4393
+ try {
4394
+ const st = fs.lstatSync(p);
4395
+ if (st.isSymbolicLink() || !st.isDirectory()) {
4396
+ fs.unlinkSync(p);
4397
+ removed.push(p);
4398
+ } else if (st.isDirectory()) {
4399
+ fs.rmSync(p, { recursive: true, force: true });
4400
+ removed.push(p);
4401
+ }
4402
+ } catch (err) {
4403
+ console.warn("Failed to remove foreign component:", p, err);
4404
+ }
4405
+ }
4406
+ return { success: true, removedCount: removed.length, removed };
4407
+ }
4408
+
4409
+ export function autoEnableHubComponents(agentDef, hubConfig = null, plugins = null) {
4410
+ if (!agentDef) return { enabledCount: 0, enabledIds: [] };
4411
+ const config = hubConfig || loadHubConfig();
4412
+ const effHub = getEffectiveHubRoot(config);
4413
+ const allPlugins = plugins || scanPlugins(effHub);
4414
+
4415
+ const scanRes = scanAgentForeignComponents(agentDef, config, allPlugins);
4416
+ const enabledIds = [];
4417
+
4418
+ if (!agentDef.plugins) agentDef.plugins = {};
4419
+
4420
+ for (const hc of scanRes.hubComponents) {
4421
+ if (hc.id && !agentDef.plugins[hc.id]) {
4422
+ agentDef.plugins[hc.id] = true;
4423
+ enabledIds.push(hc.id);
4424
+ }
4425
+ }
4426
+
4427
+ return { enabledCount: enabledIds.length, enabledIds };
4428
+ }