@kolivri/memoreal-mcp 1.0.2 → 1.1.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.
@@ -1,6 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
4
7
 
5
8
  export const POLITE_ONBOARDING_ACTION =
6
9
  'Polite Onboarding Action: Invite the user in chat to connect their free Memoreal account (1,000 free API calls & memories) in 1 click by calling the connect_account tool (opens Chrome OAuth automatically, zero copy-paste), or share https://memoreal.kolivri.com/connect (terminal wizard: npx -y @kolivri/memoreal-mcp setup). Never ask the user to paste their raw API key into chat.\n\n' +
@@ -51,7 +54,138 @@ export function sanitizeApiKey(raw) {
51
54
  }
52
55
 
53
56
  export function resolveHomeDir(options = {}) {
54
- return options.homeDir || options.env?.MEMOREAL_HOME || process.env.MEMOREAL_HOME || os.homedir();
57
+ const env = options.env || process.env;
58
+ const platform = options.platform || process.platform;
59
+ const envHome =
60
+ platform === 'win32'
61
+ ? env.USERPROFILE || env.HOME
62
+ : env.HOME || env.USERPROFILE;
63
+ return (
64
+ options.homeDir ||
65
+ env.MEMOREAL_HOME ||
66
+ envHome ||
67
+ (env.HOMEDRIVE && env.HOMEPATH ? path.join(env.HOMEDRIVE, env.HOMEPATH) : '') ||
68
+ os.homedir()
69
+ );
70
+ }
71
+
72
+ export function resolveOsPaths({ homeDir, env = process.env, platform = process.platform } = {}) {
73
+ const home = resolveHomeDir({ homeDir, env, platform });
74
+ const xdgConfig = env.XDG_CONFIG_HOME || path.join(home, '.config');
75
+ const appData = env.APPDATA || path.join(home, 'AppData', 'Roaming');
76
+ const localAppData = env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
77
+ const claudeDir = env.CLAUDE_CONFIG_DIR || path.join(home, '.claude');
78
+ const codexDir = env.CODEX_HOME || path.join(home, '.codex');
79
+ const vscodeUserDir =
80
+ platform === 'win32'
81
+ ? path.join(appData, 'Code', 'User')
82
+ : platform === 'darwin'
83
+ ? path.join(home, 'Library', 'Application Support', 'Code', 'User')
84
+ : path.join(xdgConfig, 'Code', 'User');
85
+ const vscodeGlobalStorage = path.join(vscodeUserDir, 'globalStorage');
86
+ const traeUserDir =
87
+ platform === 'win32'
88
+ ? path.join(appData, 'Trae', 'User')
89
+ : platform === 'darwin'
90
+ ? path.join(home, 'Library', 'Application Support', 'Trae', 'User')
91
+ : path.join(xdgConfig, 'Trae', 'User');
92
+
93
+ const claudeDesktopCandidates =
94
+ platform === 'win32'
95
+ ? [
96
+ path.join(appData, 'Claude', 'claude_desktop_config.json'),
97
+ path.join(localAppData, 'Claude', 'claude_desktop_config.json'),
98
+ ]
99
+ : platform === 'darwin'
100
+ ? [
101
+ path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'),
102
+ path.join(xdgConfig, 'Claude', 'claude_desktop_config.json'),
103
+ path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
104
+ ]
105
+ : [
106
+ path.join(xdgConfig, 'Claude', 'claude_desktop_config.json'),
107
+ path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
108
+ ];
109
+ const claudeDesktopPaths = [...new Set(claudeDesktopCandidates)];
110
+
111
+ return {
112
+ home,
113
+ platform,
114
+ xdgConfig,
115
+ appData,
116
+ localAppData,
117
+ vscodeUserDir,
118
+ vscodeGlobalStorage,
119
+ traeUserDir,
120
+ claudeDesktopPaths,
121
+ codexDir,
122
+ claudeDir,
123
+ };
124
+ }
125
+
126
+ export function resolveCaseInsensitiveMdPath(dir, defaultName) {
127
+ try {
128
+ if (fs.existsSync(dir)) {
129
+ const entries = fs.readdirSync(dir);
130
+ const targetLower = defaultName.toLowerCase();
131
+ const match = entries.find((e) => e.toLowerCase() === targetLower);
132
+ if (match) {
133
+ return path.join(dir, match);
134
+ }
135
+ }
136
+ } catch {}
137
+ return path.join(dir, defaultName);
138
+ }
139
+
140
+ export function safeBackupFile(filePath, mode) {
141
+ try {
142
+ if (!fs.existsSync(filePath)) return false;
143
+ const st = fs.lstatSync(filePath);
144
+ if (st.isSymbolicLink() || !st.isFile()) return false;
145
+ const bakPath = filePath + '.bak';
146
+ try {
147
+ if (fs.existsSync(bakPath) || fs.lstatSync(bakPath)) {
148
+ if (fs.lstatSync(bakPath).isSymbolicLink()) {
149
+ fs.unlinkSync(bakPath);
150
+ }
151
+ }
152
+ } catch {}
153
+ fs.copyFileSync(filePath, bakPath);
154
+ if (mode !== undefined) {
155
+ try {
156
+ fs.chmodSync(bakPath, mode);
157
+ } catch {}
158
+ }
159
+ return true;
160
+ } catch {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ export const HARNESS_REGISTRY = [
166
+ { id: 'opencode', name: 'OpenCode', configType: 'native' },
167
+ { id: 'cursor', name: 'Cursor', configType: 'mcp.json' },
168
+ { id: 'claude-code', name: 'Claude Code', configType: 'claude.json' },
169
+ { id: 'claude-desktop', name: 'Claude Desktop', configType: 'claude_desktop_config.json' },
170
+ { id: 'codex', name: 'OpenAI Codex', configType: 'config.toml' },
171
+ { id: 'vscode', name: 'VS Code / GitHub Copilot', configType: 'mcp.json' },
172
+ { id: 'windsurf', name: 'Windsurf', configType: 'mcp_config.json' },
173
+ { id: 'zed', name: 'Zed', configType: 'settings.json' },
174
+ { id: 'gemini', name: 'Gemini CLI', configType: 'settings.json' },
175
+ { id: 'cline', name: 'Cline', configType: 'cline_mcp_settings.json' },
176
+ { id: 'roo-code', name: 'Roo Code', configType: 'mcp_settings.json' },
177
+ { id: 'kilo-code', name: 'Kilo Code', configType: 'mcp_settings.json' },
178
+ { id: 'continue', name: 'Continue', configType: 'memoreal.json' },
179
+ { id: 'goose', name: 'Goose', configType: 'config.yaml' },
180
+ { id: 'amp', name: 'Amp', configType: 'settings.json' },
181
+ { id: 'kiro', name: 'AWS Kiro', configType: 'mcp.json' },
182
+ { id: 'amazon-q', name: 'Amazon Q', configType: 'mcp.json' },
183
+ { id: 'trae', name: 'Trae', configType: 'mcp.json' },
184
+ { id: 'aider', name: 'Aider', configType: 'conventions' },
185
+ ];
186
+
187
+ for (const entry of HARNESS_REGISTRY) {
188
+ HARNESS_REGISTRY[entry.id] = entry;
55
189
  }
56
190
 
57
191
  export function normalizeApiUrl(raw) {
@@ -114,7 +248,7 @@ export function readSavedMemorealConfig(options = {}) {
114
248
  path.join(explicitHome, '.memoria', 'config.env'),
115
249
  ];
116
250
  } else {
117
- const home = os.homedir();
251
+ const home = resolveHomeDir(options);
118
252
  candidates = [
119
253
  path.join(home, '.memoreal', 'config.env'),
120
254
  path.join(home, '.memoria', 'config.env'),
@@ -221,7 +355,7 @@ export function resolveEffectiveApiUrl(overrideUrl, options = {}) {
221
355
  }
222
356
  }
223
357
 
224
- return 'https://memoria.kolivri.com';
358
+ return 'https://memoreal.kolivri.com';
225
359
  }
226
360
 
227
361
  export function saveMemorealConfig({ apiKey, apiUrl, homeDir, env, configDir } = {}) {
@@ -256,11 +390,7 @@ export function saveMemorealConfig({ apiKey, apiUrl, homeDir, env, configDir } =
256
390
 
257
391
  const targetFile = path.join(targetDir, 'config.env');
258
392
  if (fs.existsSync(targetFile)) {
259
- const bakFile = targetFile + '.bak';
260
- fs.copyFileSync(targetFile, bakFile);
261
- try {
262
- fs.chmodSync(bakFile, 0o600);
263
- } catch {}
393
+ safeBackupFile(targetFile, 0o600);
264
394
  }
265
395
 
266
396
  fs.writeFileSync(targetFile, configContent, { mode: 0o600 });
@@ -304,10 +434,22 @@ export function saveMemorealConfig({ apiKey, apiUrl, homeDir, env, configDir } =
304
434
  };
305
435
  }
306
436
 
307
- export function configureDetectedIdes({ apiKey, apiUrl, homeDir, env, preferredTool } = {}) {
437
+ export function configureDetectedIdes({ apiKey, apiUrl, homeDir, env, preferredTool, platform } = {}) {
308
438
  const cleanKey = sanitizeApiKey(apiKey);
309
- const resolvedHome = resolveHomeDir({ homeDir, env });
310
- const cleanUrl = resolveEffectiveApiUrl(apiUrl, { homeDir, env });
439
+ const osPaths = resolveOsPaths({ homeDir, env, platform });
440
+ const {
441
+ home: resolvedHome,
442
+ xdgConfig,
443
+ appData,
444
+ localAppData,
445
+ vscodeUserDir,
446
+ vscodeGlobalStorage,
447
+ traeUserDir,
448
+ claudeDesktopPaths,
449
+ codexDir,
450
+ } = osPaths;
451
+ const isWin = (platform || process.platform) === 'win32';
452
+ const cleanUrl = resolveEffectiveApiUrl(apiUrl, { homeDir: resolvedHome, env });
311
453
  const mcpUrl = cleanUrl.endsWith('/v1/mcp') ? cleanUrl : `${cleanUrl}/v1/mcp`;
312
454
 
313
455
  const updated = [];
@@ -315,11 +457,7 @@ export function configureDetectedIdes({ apiKey, apiUrl, homeDir, env, preferredT
315
457
 
316
458
  function writeIdeJson(filePath, newObj, isCreate) {
317
459
  if (!isCreate && fs.existsSync(filePath)) {
318
- const bakPath = filePath + '.bak';
319
- fs.copyFileSync(filePath, bakPath);
320
- try {
321
- fs.chmodSync(bakPath, 0o600);
322
- } catch {}
460
+ safeBackupFile(filePath, 0o600);
323
461
  }
324
462
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
325
463
  fs.writeFileSync(filePath, JSON.stringify(newObj, null, 2) + '\n', { mode: 0o600 });
@@ -345,55 +483,7 @@ export function configureDetectedIdes({ apiKey, apiUrl, homeDir, env, preferredT
345
483
  }
346
484
  }
347
485
 
348
- // 1. OpenCode: <resolvedHome>/.config/opencode/opencode.json
349
- const opencodePath = path.join(resolvedHome, '.config', 'opencode', 'opencode.json');
350
- const opencodeDir = path.dirname(opencodePath);
351
- const shouldTouchOpencode =
352
- fs.existsSync(opencodePath) ||
353
- fs.existsSync(opencodeDir) ||
354
- normalizedPreferred === 'opencode';
355
-
356
- if (shouldTouchOpencode) {
357
- const { parsed, isCreate, malformed } = readIdeJson(opencodePath);
358
- if (malformed) {
359
- updated.push({ file: opencodePath, status: 'skipped_malformed_json' });
360
- } else {
361
- const config = parsed || {
362
- '$schema': 'https://opencode.ai/config.json',
363
- mcp: {},
364
- };
365
- config.mcp = config.mcp || {};
366
- if (config.mcp.memoreal && config.mcp.memoreal.type === 'local') {
367
- config.mcp.memoreal.environment = config.mcp.memoreal.environment || {};
368
- if (cleanKey) {
369
- config.mcp.memoreal.environment.MEMOREAL_API_KEY = cleanKey;
370
- config.mcp.memoreal.environment.MEMORIA_API_KEY = cleanKey;
371
- }
372
- } else {
373
- const memorealEntry = {
374
- type: 'remote',
375
- url: mcpUrl,
376
- enabled: true,
377
- };
378
- if (cleanKey) {
379
- memorealEntry.headers = { Authorization: `Bearer ${cleanKey}` };
380
- }
381
- config.mcp.memoreal = {
382
- ...(config.mcp.memoreal || {}),
383
- ...memorealEntry,
384
- };
385
- }
386
- if (config.mcpServers?.memoreal) {
387
- delete config.mcpServers.memoreal;
388
- if (Object.keys(config.mcpServers).length === 0) {
389
- delete config.mcpServers;
390
- }
391
- }
392
- writeIdeJson(opencodePath, config, isCreate);
393
- }
394
- }
395
-
396
- // Helper for IDEs using .mcpServers.memoreal
486
+ // Helper for IDEs using .mcpServers.memoreal HTTP/stdio
397
487
  function handleMcpServersIde(filePath, shouldTouch) {
398
488
  if (!shouldTouch) return;
399
489
  const { parsed, isCreate, malformed } = readIdeJson(filePath);
@@ -427,7 +517,335 @@ export function configureDetectedIdes({ apiKey, apiUrl, homeDir, env, preferredT
427
517
  writeIdeJson(filePath, config, isCreate);
428
518
  }
429
519
 
430
- // 2. Cursor: <resolvedHome>/.cursor/mcp.json
520
+ // Helper for IDEs using stdio entry
521
+ function writeStdioMcpJson(filePath, shouldTouch) {
522
+ if (!shouldTouch) return;
523
+ const { parsed, isCreate, malformed } = readIdeJson(filePath);
524
+ if (malformed) {
525
+ updated.push({ file: filePath, status: 'skipped_malformed_json' });
526
+ return;
527
+ }
528
+ const config = parsed || { mcpServers: {} };
529
+ config.mcpServers = config.mcpServers || {};
530
+ const existingMcp = config.mcpServers.memoreal || {};
531
+ config.mcpServers.memoreal = {
532
+ ...existingMcp,
533
+ command: isWin ? 'cmd' : 'npx',
534
+ args: isWin ? ['/c', 'npx', '-y', '@kolivri/memoreal-mcp'] : ['-y', '@kolivri/memoreal-mcp'],
535
+ env: {
536
+ ...(existingMcp.env || {}),
537
+ ...(cleanKey ? { MEMOREAL_API_KEY: cleanKey } : {}),
538
+ MEMOREAL_API_URL: cleanUrl,
539
+ },
540
+ };
541
+ writeIdeJson(filePath, config, isCreate);
542
+ }
543
+
544
+ // Helper for VS Code mcp.json (both servers.memoreal and mcpServers.memoreal)
545
+ function handleVscodeMcp(filePath, shouldTouch) {
546
+ if (!shouldTouch) return;
547
+ const { parsed, isCreate, malformed } = readIdeJson(filePath);
548
+ if (malformed) {
549
+ updated.push({ file: filePath, status: 'skipped_malformed_json' });
550
+ return;
551
+ }
552
+ const config = parsed || {};
553
+ config.servers = config.servers || {};
554
+ config.mcpServers = config.mcpServers || {};
555
+
556
+ const serverEntry = {
557
+ type: 'http',
558
+ url: mcpUrl,
559
+ ...(cleanKey ? { headers: { Authorization: `Bearer ${cleanKey}` } } : {}),
560
+ };
561
+
562
+ config.servers.memoreal = {
563
+ ...(config.servers.memoreal || {}),
564
+ ...serverEntry,
565
+ };
566
+
567
+ const existingMcp = config.mcpServers.memoreal;
568
+ if (existingMcp && (existingMcp.command || existingMcp.type === 'stdio' || (!existingMcp.type && existingMcp.command))) {
569
+ config.mcpServers.memoreal.env = config.mcpServers.memoreal.env || {};
570
+ if (cleanKey) {
571
+ config.mcpServers.memoreal.env.MEMOREAL_API_KEY = cleanKey;
572
+ config.mcpServers.memoreal.env.MEMORIA_API_KEY = cleanKey;
573
+ }
574
+ } else {
575
+ config.mcpServers.memoreal = {
576
+ ...(existingMcp || {}),
577
+ ...serverEntry,
578
+ };
579
+ }
580
+
581
+ writeIdeJson(filePath, config, isCreate);
582
+ }
583
+
584
+ // Helper for OpenAI Codex config.toml
585
+ function upsertCodexToml(filePath, targetMcpUrl, targetCleanKey) {
586
+ const memorealSectionLines = [
587
+ '[mcp_servers.memoreal]',
588
+ `url = "${targetMcpUrl}"`,
589
+ ];
590
+ if (targetCleanKey) {
591
+ memorealSectionLines.push(`http_headers = { "Authorization" = "Bearer ${targetCleanKey}" }`);
592
+ }
593
+
594
+ if (!fs.existsSync(filePath)) {
595
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
596
+ fs.writeFileSync(filePath, memorealSectionLines.join('\n') + '\n', { mode: 0o600 });
597
+ try {
598
+ fs.chmodSync(filePath, 0o600);
599
+ } catch {}
600
+ updated.push({ file: filePath, status: 'created' });
601
+ return;
602
+ }
603
+
604
+ let raw;
605
+ try {
606
+ raw = fs.readFileSync(filePath, 'utf8');
607
+ } catch {
608
+ updated.push({ file: filePath, status: 'skipped_malformed_toml' });
609
+ return;
610
+ }
611
+
612
+ if (raw.includes('\0')) {
613
+ updated.push({ file: filePath, status: 'skipped_malformed_toml' });
614
+ return;
615
+ }
616
+
617
+ safeBackupFile(filePath, 0o600);
618
+
619
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
620
+ const lines = raw.split(/\r?\n/);
621
+ const outLines = [];
622
+ let inMemoreal = false;
623
+ let replaced = false;
624
+
625
+ for (let i = 0; i < lines.length; i++) {
626
+ const line = lines[i];
627
+ const arrayHeader = line.match(/^\s*\[\[([^\]]+)\]\]\s*(?:#.*)?$/);
628
+ const tableHeader = !arrayHeader ? line.match(/^\s*\[([^\[\]]+)\]\s*(?:#.*)?$/) : null;
629
+
630
+ if (arrayHeader) {
631
+ inMemoreal = false;
632
+ } else if (tableHeader) {
633
+ const normSec = tableHeader[1].trim().replace(/["']/g, '').replace(/\s*\.\s*/g, '.');
634
+ if (normSec === 'mcp_servers.memoreal' || normSec.startsWith('mcp_servers.memoreal.')) {
635
+ if (!replaced) {
636
+ outLines.push(...memorealSectionLines);
637
+ replaced = true;
638
+ }
639
+ inMemoreal = true;
640
+ continue;
641
+ } else {
642
+ inMemoreal = false;
643
+ }
644
+ }
645
+
646
+ if (!inMemoreal) {
647
+ outLines.push(line);
648
+ }
649
+ }
650
+
651
+ if (!replaced) {
652
+ const joined = outLines.join(eol).trimEnd();
653
+ const memBlock = memorealSectionLines.join(eol) + eol;
654
+ const finalContent = joined ? joined + eol + eol + memBlock : memBlock;
655
+ fs.writeFileSync(filePath, finalContent, { mode: 0o600 });
656
+ } else {
657
+ fs.writeFileSync(
658
+ filePath,
659
+ outLines.join(eol) + (outLines[outLines.length - 1] === '' ? '' : eol),
660
+ { mode: 0o600 }
661
+ );
662
+ }
663
+ try {
664
+ fs.chmodSync(filePath, 0o600);
665
+ } catch {}
666
+ updated.push({ file: filePath, status: 'updated' });
667
+ }
668
+
669
+ // Helper for Goose config.yaml
670
+ function upsertGooseYaml(filePath, targetApiUrl, targetCleanKey, winTarget) {
671
+ const memorealLines = [
672
+ ' memoreal:',
673
+ ' name: memoreal',
674
+ ' type: stdio',
675
+ ' enabled: true',
676
+ ` cmd: ${winTarget ? 'cmd' : 'npx'}`,
677
+ ' args:',
678
+ ...(winTarget
679
+ ? [' - /c', ' - npx', ' - -y', ' - "@kolivri/memoreal-mcp"']
680
+ : [' - -y', ' - "@kolivri/memoreal-mcp"']),
681
+ ' envs:',
682
+ ` MEMOREAL_API_URL: ${targetApiUrl}`,
683
+ ];
684
+ if (targetCleanKey) {
685
+ memorealLines.push(` MEMOREAL_API_KEY: ${targetCleanKey}`);
686
+ }
687
+
688
+ if (!fs.existsSync(filePath)) {
689
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
690
+ const content = `extensions:\n${memorealLines.join('\n')}\n`;
691
+ fs.writeFileSync(filePath, content, { mode: 0o600 });
692
+ try {
693
+ fs.chmodSync(filePath, 0o600);
694
+ } catch {}
695
+ updated.push({ file: filePath, status: 'created' });
696
+ return;
697
+ }
698
+
699
+ let raw;
700
+ try {
701
+ raw = fs.readFileSync(filePath, 'utf8');
702
+ } catch {
703
+ updated.push({ file: filePath, status: 'skipped_malformed_yaml' });
704
+ return;
705
+ }
706
+
707
+ if (raw.includes('\0')) {
708
+ updated.push({ file: filePath, status: 'skipped_malformed_yaml' });
709
+ return;
710
+ }
711
+
712
+ safeBackupFile(filePath, 0o600);
713
+
714
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
715
+ const lines = raw.split(/\r?\n/);
716
+ const extIndex = lines.findIndex((l) =>
717
+ /^extensions:\s*(?:\{\s*\}|\[\s*\])?\s*(?:#.*)?$/.test(l)
718
+ );
719
+
720
+ if (extIndex === -1) {
721
+ const joined = raw.trimEnd();
722
+ const finalContent = joined
723
+ ? `${joined}${eol}${eol}extensions:${eol}${memorealLines.join(eol)}${eol}`
724
+ : `extensions:${eol}${memorealLines.join(eol)}${eol}`;
725
+ fs.writeFileSync(filePath, finalContent, { mode: 0o600 });
726
+ try {
727
+ fs.chmodSync(filePath, 0o600);
728
+ } catch {}
729
+ updated.push({ file: filePath, status: 'updated' });
730
+ return;
731
+ }
732
+
733
+ lines[extIndex] = 'extensions:';
734
+
735
+ let memorealStart = -1;
736
+ let memorealEnd = -1;
737
+ for (let i = extIndex + 1; i < lines.length; i++) {
738
+ const line = lines[i];
739
+ if (/^[^\s#]/.test(line)) {
740
+ break;
741
+ }
742
+ if (/^ {2}memoreal:\s*$/.test(line)) {
743
+ memorealStart = i;
744
+ memorealEnd = i + 1;
745
+ while (memorealEnd < lines.length) {
746
+ const nextLine = lines[memorealEnd];
747
+ if (/^ {2}[a-zA-Z0-9_-]+:/.test(nextLine) || /^[^\s#]/.test(nextLine)) {
748
+ break;
749
+ }
750
+ memorealEnd++;
751
+ }
752
+ break;
753
+ }
754
+ }
755
+
756
+ if (memorealStart !== -1) {
757
+ lines.splice(memorealStart, memorealEnd - memorealStart, ...memorealLines);
758
+ } else {
759
+ lines.splice(extIndex + 1, 0, ...memorealLines);
760
+ }
761
+
762
+ fs.writeFileSync(
763
+ filePath,
764
+ lines.join(eol) + (lines[lines.length - 1] === '' ? '' : eol),
765
+ { mode: 0o600 }
766
+ );
767
+ try {
768
+ fs.chmodSync(filePath, 0o600);
769
+ } catch {}
770
+ updated.push({ file: filePath, status: 'updated' });
771
+ }
772
+
773
+ // 1. OpenAI Codex: <codexDir>/config.toml and <codexDir>/mcp.json
774
+ const codexTomlPath = path.join(codexDir, 'config.toml');
775
+ const codexJsonPath = path.join(codexDir, 'mcp.json');
776
+ const shouldTouchCodex =
777
+ fs.existsSync(codexDir) ||
778
+ fs.existsSync(codexTomlPath) ||
779
+ fs.existsSync(codexJsonPath) ||
780
+ normalizedPreferred === 'codex';
781
+
782
+ if (shouldTouchCodex) {
783
+ upsertCodexToml(codexTomlPath, mcpUrl, cleanKey);
784
+ handleMcpServersIde(codexJsonPath, true);
785
+ }
786
+
787
+ // 2. OpenCode: <xdgConfig>/opencode/opencode.json (+ legacy / win32 candidates)
788
+ const opencodeCandidates = [path.join(xdgConfig, 'opencode', 'opencode.json')];
789
+ const legacyOpencode = path.join(resolvedHome, '.config', 'opencode', 'opencode.json');
790
+ if (!opencodeCandidates.includes(legacyOpencode)) {
791
+ opencodeCandidates.push(legacyOpencode);
792
+ }
793
+ if (isWin) {
794
+ const winOpencode = path.join(appData, 'opencode', 'opencode.json');
795
+ if (!opencodeCandidates.includes(winOpencode)) {
796
+ opencodeCandidates.push(winOpencode);
797
+ }
798
+ }
799
+
800
+ for (const opencodePath of opencodeCandidates) {
801
+ const opencodeDir = path.dirname(opencodePath);
802
+ const shouldTouchOpencode =
803
+ fs.existsSync(opencodePath) ||
804
+ fs.existsSync(opencodeDir) ||
805
+ (opencodePath === opencodeCandidates[0] && normalizedPreferred === 'opencode');
806
+
807
+ if (shouldTouchOpencode) {
808
+ const { parsed, isCreate, malformed } = readIdeJson(opencodePath);
809
+ if (malformed) {
810
+ updated.push({ file: opencodePath, status: 'skipped_malformed_json' });
811
+ } else {
812
+ const config = parsed || {
813
+ '$schema': 'https://opencode.ai/config.json',
814
+ mcp: {},
815
+ };
816
+ config.mcp = config.mcp || {};
817
+ if (config.mcp.memoreal && config.mcp.memoreal.type === 'local') {
818
+ config.mcp.memoreal.environment = config.mcp.memoreal.environment || {};
819
+ if (cleanKey) {
820
+ config.mcp.memoreal.environment.MEMOREAL_API_KEY = cleanKey;
821
+ config.mcp.memoreal.environment.MEMORIA_API_KEY = cleanKey;
822
+ }
823
+ } else {
824
+ const memorealEntry = {
825
+ type: 'remote',
826
+ url: mcpUrl,
827
+ enabled: true,
828
+ };
829
+ if (cleanKey) {
830
+ memorealEntry.headers = { Authorization: `Bearer ${cleanKey}` };
831
+ }
832
+ config.mcp.memoreal = {
833
+ ...(config.mcp.memoreal || {}),
834
+ ...memorealEntry,
835
+ };
836
+ }
837
+ if (config.mcpServers?.memoreal) {
838
+ delete config.mcpServers.memoreal;
839
+ if (Object.keys(config.mcpServers).length === 0) {
840
+ delete config.mcpServers;
841
+ }
842
+ }
843
+ writeIdeJson(opencodePath, config, isCreate);
844
+ }
845
+ }
846
+ }
847
+
848
+ // 3. Cursor: <resolvedHome>/.cursor/mcp.json
431
849
  const cursorPath = path.join(resolvedHome, '.cursor', 'mcp.json');
432
850
  const shouldTouchCursor =
433
851
  fs.existsSync(cursorPath) ||
@@ -435,7 +853,7 @@ export function configureDetectedIdes({ apiKey, apiUrl, homeDir, env, preferredT
435
853
  normalizedPreferred === 'cursor';
436
854
  handleMcpServersIde(cursorPath, shouldTouchCursor);
437
855
 
438
- // Windsurf: <resolvedHome>/.codeium/windsurf/mcp_config.json
856
+ // 4. Windsurf: <resolvedHome>/.codeium/windsurf/mcp_config.json
439
857
  const windsurfPath = path.join(resolvedHome, '.codeium', 'windsurf', 'mcp_config.json');
440
858
  const shouldTouchWindsurf =
441
859
  fs.existsSync(windsurfPath) ||
@@ -443,44 +861,689 @@ export function configureDetectedIdes({ apiKey, apiUrl, homeDir, env, preferredT
443
861
  normalizedPreferred === 'windsurf';
444
862
  handleMcpServersIde(windsurfPath, shouldTouchWindsurf);
445
863
 
446
- // VS Code: <resolvedHome>/.vscode/mcp.json
447
- const vscodePath = path.join(resolvedHome, '.vscode', 'mcp.json');
448
- const shouldTouchVscode =
449
- fs.existsSync(vscodePath) ||
450
- fs.existsSync(path.dirname(vscodePath)) ||
451
- normalizedPreferred === 'vscode';
452
- handleMcpServersIde(vscodePath, shouldTouchVscode);
453
-
454
- // Claude Desktop:
455
- const claudeDesktopPaths = [
456
- path.join(resolvedHome, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'),
457
- path.join(resolvedHome, '.config', 'Claude', 'claude_desktop_config.json'),
458
- path.join(resolvedHome, 'AppData', 'Roaming', 'Claude', 'claude_desktop_config.json'),
459
- ];
864
+ // 5. VS Code / GitHub Copilot: <resolvedHome>/.vscode/mcp.json & <vscodeUserDir>/mcp.json
865
+ const vscodeHomePath = path.join(resolvedHome, '.vscode', 'mcp.json');
866
+ const shouldTouchVscodeHome =
867
+ fs.existsSync(vscodeHomePath) ||
868
+ fs.existsSync(path.dirname(vscodeHomePath)) ||
869
+ normalizedPreferred === 'vscode' ||
870
+ normalizedPreferred === 'copilot';
871
+ handleVscodeMcp(vscodeHomePath, shouldTouchVscodeHome);
872
+
873
+ const vscodeUserPath = path.join(vscodeUserDir, 'mcp.json');
874
+ const shouldTouchVscodeUser =
875
+ fs.existsSync(vscodeUserPath) ||
876
+ fs.existsSync(vscodeUserDir) ||
877
+ normalizedPreferred === 'vscode' ||
878
+ normalizedPreferred === 'copilot';
879
+ if (vscodeUserPath !== vscodeHomePath) {
880
+ handleVscodeMcp(vscodeUserPath, shouldTouchVscodeUser);
881
+ }
882
+
883
+ // 6. Claude Desktop: OS-specific desktop paths
460
884
  for (const desktopPath of claudeDesktopPaths) {
461
885
  const shouldTouchDesktop =
462
886
  fs.existsSync(desktopPath) ||
463
- fs.existsSync(path.dirname(desktopPath));
887
+ fs.existsSync(path.dirname(desktopPath)) ||
888
+ (desktopPath === claudeDesktopPaths[0] && normalizedPreferred === 'claude-desktop');
464
889
  if (shouldTouchDesktop) {
465
890
  handleMcpServersIde(desktopPath, true);
466
891
  }
467
892
  }
468
893
 
469
- // Codex CLI: <resolvedHome>/.codex/mcp.json
470
- const codexPath = path.join(resolvedHome, '.codex', 'mcp.json');
471
- const shouldTouchCodex =
472
- fs.existsSync(codexPath) ||
473
- fs.existsSync(path.dirname(codexPath)) ||
474
- normalizedPreferred === 'codex';
475
- if (shouldTouchCodex) {
476
- handleMcpServersIde(codexPath, true);
477
- }
478
-
479
- // 3. Claude Code: <resolvedHome>/.claude.json (ONLY if already exists!)
894
+ // 7. Claude Code: <resolvedHome>/.claude.json (ONLY if already exists!)
480
895
  const claudeCodePath = path.join(resolvedHome, '.claude.json');
481
896
  if (fs.existsSync(claudeCodePath)) {
482
897
  handleMcpServersIde(claudeCodePath, true);
483
898
  }
484
899
 
900
+ // 8. Zed: <xdgConfig>/zed/settings.json, win32 <appData>/Zed/settings.json, darwin Library/...
901
+ const zedCandidates = isWin
902
+ ? [path.join(appData, 'Zed', 'settings.json'), path.join(xdgConfig, 'zed', 'settings.json')]
903
+ : [path.join(xdgConfig, 'zed', 'settings.json')];
904
+ if (platform === 'darwin') {
905
+ const macZed = path.join(resolvedHome, 'Library', 'Application Support', 'Zed', 'settings.json');
906
+ if (!zedCandidates.includes(macZed)) {
907
+ zedCandidates.push(macZed);
908
+ }
909
+ }
910
+
911
+ for (const zedPath of zedCandidates) {
912
+ const shouldTouchZed =
913
+ fs.existsSync(zedPath) ||
914
+ fs.existsSync(path.dirname(zedPath)) ||
915
+ (zedPath === zedCandidates[0] && normalizedPreferred === 'zed');
916
+
917
+ if (shouldTouchZed) {
918
+ const { parsed, isCreate, malformed } = readIdeJson(zedPath);
919
+ if (malformed) {
920
+ updated.push({ file: zedPath, status: 'skipped_malformed_json' });
921
+ } else {
922
+ const config = parsed || {};
923
+ config.context_servers = config.context_servers || {};
924
+ config.context_servers.memoreal = {
925
+ command: {
926
+ path: isWin ? 'cmd' : 'npx',
927
+ args: isWin
928
+ ? ['/c', 'npx', '-y', '@kolivri/memoreal-mcp']
929
+ : ['-y', '@kolivri/memoreal-mcp'],
930
+ env: {
931
+ ...(cleanKey ? { MEMOREAL_API_KEY: cleanKey } : {}),
932
+ MEMOREAL_API_URL: cleanUrl,
933
+ },
934
+ },
935
+ };
936
+ writeIdeJson(zedPath, config, isCreate);
937
+ }
938
+ }
939
+ }
940
+
941
+ // 9. Gemini CLI: <resolvedHome>/.gemini/settings.json
942
+ const geminiPath = path.join(resolvedHome, '.gemini', 'settings.json');
943
+ const shouldTouchGemini =
944
+ fs.existsSync(geminiPath) ||
945
+ fs.existsSync(path.dirname(geminiPath)) ||
946
+ normalizedPreferred === 'gemini' ||
947
+ normalizedPreferred === 'gemini-cli';
948
+ handleMcpServersIde(geminiPath, shouldTouchGemini);
949
+
950
+ // 10. Cline: <vscodeGlobalStorage>/saoudrizwan.claude-dev/settings/cline_mcp_settings.json
951
+ const clineDir = path.join(vscodeGlobalStorage, 'saoudrizwan.claude-dev');
952
+ const clinePath = path.join(clineDir, 'settings', 'cline_mcp_settings.json');
953
+ const shouldTouchCline =
954
+ fs.existsSync(clinePath) || fs.existsSync(clineDir) || normalizedPreferred === 'cline';
955
+ writeStdioMcpJson(clinePath, shouldTouchCline);
956
+
957
+ // 11. Roo Code: <vscodeGlobalStorage>/rooveterinaryinc.roo-cline/settings/mcp_settings.json
958
+ const rooDir = path.join(vscodeGlobalStorage, 'rooveterinaryinc.roo-cline');
959
+ const rooPath = path.join(rooDir, 'settings', 'mcp_settings.json');
960
+ const shouldTouchRoo =
961
+ fs.existsSync(rooPath) ||
962
+ fs.existsSync(rooDir) ||
963
+ normalizedPreferred === 'roo-code' ||
964
+ normalizedPreferred === 'roo';
965
+ writeStdioMcpJson(rooPath, shouldTouchRoo);
966
+
967
+ // 12. Kilo Code: <vscodeGlobalStorage>/kilocode.kilo-code/settings/mcp_settings.json
968
+ const kiloDir = path.join(vscodeGlobalStorage, 'kilocode.kilo-code');
969
+ const kiloPath = path.join(kiloDir, 'settings', 'mcp_settings.json');
970
+ const shouldTouchKilo =
971
+ fs.existsSync(kiloPath) ||
972
+ fs.existsSync(kiloDir) ||
973
+ normalizedPreferred === 'kilo-code' ||
974
+ normalizedPreferred === 'kilo';
975
+ writeStdioMcpJson(kiloPath, shouldTouchKilo);
976
+
977
+ // 13. Continue: <resolvedHome>/.continue/mcpServers/memoreal.json
978
+ const continueDir = path.join(resolvedHome, '.continue');
979
+ const continuePath = path.join(continueDir, 'mcpServers', 'memoreal.json');
980
+ const shouldTouchContinue =
981
+ fs.existsSync(continuePath) || fs.existsSync(continueDir) || normalizedPreferred === 'continue';
982
+ writeStdioMcpJson(continuePath, shouldTouchContinue);
983
+
984
+ // 14. Goose: <xdgConfig>/goose/config.yaml or <appData>/Block/goose/config/config.yaml
985
+ const gooseCandidates = isWin
986
+ ? [
987
+ path.join(appData, 'Block', 'goose', 'config', 'config.yaml'),
988
+ path.join(xdgConfig, 'goose', 'config.yaml'),
989
+ ]
990
+ : [path.join(xdgConfig, 'goose', 'config.yaml')];
991
+
992
+ for (const goosePath of gooseCandidates) {
993
+ const shouldTouchGoose =
994
+ fs.existsSync(goosePath) ||
995
+ fs.existsSync(path.dirname(goosePath)) ||
996
+ (goosePath === gooseCandidates[0] && normalizedPreferred === 'goose');
997
+ if (shouldTouchGoose) {
998
+ upsertGooseYaml(goosePath, cleanUrl, cleanKey, isWin);
999
+ }
1000
+ }
1001
+
1002
+ // 15. Sourcegraph Amp: <xdgConfig>/amp/settings.json and win32 <appData>/amp/settings.json
1003
+ const ampCandidates = [
1004
+ path.join(xdgConfig, 'amp', 'settings.json'),
1005
+ ...(isWin ? [path.join(appData, 'amp', 'settings.json')] : []),
1006
+ ];
1007
+ const uniqueAmpCandidates = [...new Set(ampCandidates)];
1008
+
1009
+ for (const aPath of uniqueAmpCandidates) {
1010
+ const shouldTouchAmp =
1011
+ fs.existsSync(aPath) ||
1012
+ fs.existsSync(path.dirname(aPath)) ||
1013
+ (aPath === uniqueAmpCandidates[0] && normalizedPreferred === 'amp');
1014
+ if (shouldTouchAmp) {
1015
+ const { parsed, isCreate, malformed } = readIdeJson(aPath);
1016
+ if (malformed) {
1017
+ updated.push({ file: aPath, status: 'skipped_malformed_json' });
1018
+ } else {
1019
+ const config = parsed || {};
1020
+ config['amp.mcpServers'] = config['amp.mcpServers'] || {};
1021
+ const memorealEntry = { url: mcpUrl };
1022
+ if (cleanKey) {
1023
+ memorealEntry.headers = { Authorization: `Bearer ${cleanKey}` };
1024
+ }
1025
+ config['amp.mcpServers'].memoreal = {
1026
+ ...(config['amp.mcpServers'].memoreal || {}),
1027
+ ...memorealEntry,
1028
+ };
1029
+ writeIdeJson(aPath, config, isCreate);
1030
+ }
1031
+ }
1032
+ }
1033
+
1034
+ // 16. AWS Kiro: <resolvedHome>/.kiro/settings/mcp.json
1035
+ const kiroDir = path.join(resolvedHome, '.kiro');
1036
+ const kiroPath = path.join(kiroDir, 'settings', 'mcp.json');
1037
+ const shouldTouchKiro =
1038
+ fs.existsSync(kiroPath) ||
1039
+ fs.existsSync(path.dirname(kiroPath)) ||
1040
+ fs.existsSync(kiroDir) ||
1041
+ normalizedPreferred === 'kiro';
1042
+ handleMcpServersIde(kiroPath, shouldTouchKiro);
1043
+
1044
+ // 17. Amazon Q: <resolvedHome>/.aws/amazonq/mcp.json
1045
+ const qPath = path.join(resolvedHome, '.aws', 'amazonq', 'mcp.json');
1046
+ const shouldTouchQ =
1047
+ fs.existsSync(qPath) ||
1048
+ fs.existsSync(path.dirname(qPath)) ||
1049
+ normalizedPreferred === 'amazon-q' ||
1050
+ normalizedPreferred === 'amazonq' ||
1051
+ normalizedPreferred === 'q';
1052
+ handleMcpServersIde(qPath, shouldTouchQ);
1053
+
1054
+ // 18. Trae: <traeUserDir>/mcp.json
1055
+ const traePath = path.join(traeUserDir, 'mcp.json');
1056
+ const shouldTouchTrae =
1057
+ fs.existsSync(traePath) || fs.existsSync(traeUserDir) || normalizedPreferred === 'trae';
1058
+ handleMcpServersIde(traePath, shouldTouchTrae);
1059
+
485
1060
  return { updated };
486
1061
  }
1062
+
1063
+ export function provisionMemorealAgentAssets({ homeDir, projectDir, env, preferredTool, platform } = {}) {
1064
+ const osPaths = resolveOsPaths({ homeDir, env, platform });
1065
+ const {
1066
+ home: resolvedHome,
1067
+ xdgConfig,
1068
+ appData,
1069
+ localAppData,
1070
+ vscodeUserDir,
1071
+ codexDir,
1072
+ } = osPaths;
1073
+ const isWin = (platform || process.platform) === 'win32';
1074
+ const normalizedPreferred = (preferredTool || '').toLowerCase().trim();
1075
+ const provisioned = [];
1076
+ const updated = [];
1077
+ const skipped = [];
1078
+
1079
+ function recordAction(filePath, status) {
1080
+ provisioned.push(filePath);
1081
+ updated.push({ file: filePath, status });
1082
+ }
1083
+
1084
+ function copyFileWithBak(srcFile, destFile, mode = 0o644) {
1085
+ if (!fs.existsSync(srcFile)) return false;
1086
+ fs.mkdirSync(path.dirname(destFile), { recursive: true });
1087
+ let destExists = false;
1088
+ try {
1089
+ destExists = fs.existsSync(destFile) || fs.lstatSync(destFile);
1090
+ } catch {}
1091
+
1092
+ if (destExists) {
1093
+ try {
1094
+ if (fs.realpathSync(srcFile) === fs.realpathSync(destFile)) {
1095
+ return false;
1096
+ }
1097
+ } catch {}
1098
+ try {
1099
+ if (fs.lstatSync(destFile).isSymbolicLink()) {
1100
+ fs.unlinkSync(destFile);
1101
+ destExists = false;
1102
+ }
1103
+ } catch {}
1104
+ }
1105
+
1106
+ const isCreate = !destExists;
1107
+ if (!isCreate) {
1108
+ safeBackupFile(destFile, mode);
1109
+ }
1110
+ fs.copyFileSync(srcFile, destFile);
1111
+ if (mode !== undefined) {
1112
+ try {
1113
+ fs.chmodSync(destFile, mode);
1114
+ } catch {}
1115
+ }
1116
+ recordAction(destFile, isCreate ? 'created' : 'updated');
1117
+ return true;
1118
+ }
1119
+
1120
+ function copyDirectoryRecursiveWithBak(srcDir, destDir) {
1121
+ if (!fs.existsSync(srcDir)) return;
1122
+ fs.mkdirSync(destDir, { recursive: true });
1123
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
1124
+ for (const entry of entries) {
1125
+ const srcPath = path.join(srcDir, entry.name);
1126
+ const destPath = path.join(destDir, entry.name);
1127
+ if (entry.isDirectory()) {
1128
+ copyDirectoryRecursiveWithBak(srcPath, destPath);
1129
+ } else if (entry.isFile()) {
1130
+ copyFileWithBak(srcPath, destPath, 0o644);
1131
+ }
1132
+ }
1133
+ }
1134
+
1135
+ function getMemorealMarkdownBlock() {
1136
+ const claudeMdPath = path.join(PACKAGE_ROOT, 'CLAUDE.md');
1137
+ if (fs.existsSync(claudeMdPath)) {
1138
+ const content = fs.readFileSync(claudeMdPath, 'utf8');
1139
+ const startTag = '<!-- memoreal:start -->';
1140
+ const endTag = '<!-- memoreal:end -->';
1141
+ const startIdx = content.indexOf(startTag);
1142
+ const endIdx = content.indexOf(endTag);
1143
+ if (startIdx !== -1 && endIdx !== -1 && endIdx >= startIdx) {
1144
+ return content.slice(startIdx, endIdx + endTag.length);
1145
+ }
1146
+ }
1147
+ return '<!-- memoreal:start -->\n## Memoreal Long-Term Memory (32 MCP Tools)\n<!-- memoreal:end -->';
1148
+ }
1149
+
1150
+ function upsertMarkdownWithBak(targetFile) {
1151
+ const rawBlockContent = getMemorealMarkdownBlock();
1152
+ if (!rawBlockContent) return;
1153
+ fs.mkdirSync(path.dirname(targetFile), { recursive: true });
1154
+
1155
+ let targetExists = false;
1156
+ try {
1157
+ targetExists = fs.existsSync(targetFile) || fs.lstatSync(targetFile);
1158
+ } catch {}
1159
+
1160
+ if (targetExists) {
1161
+ try {
1162
+ if (fs.lstatSync(targetFile).isSymbolicLink()) {
1163
+ fs.unlinkSync(targetFile);
1164
+ targetExists = false;
1165
+ }
1166
+ } catch {}
1167
+ }
1168
+
1169
+ const isCreate = !targetExists;
1170
+ if (!isCreate) {
1171
+ const existing = fs.readFileSync(targetFile, 'utf8');
1172
+ const eol = existing.includes('\r\n') ? '\r\n' : '\n';
1173
+ const blockContent =
1174
+ eol === '\r\n' ? rawBlockContent.replace(/\r?\n/g, '\r\n') : rawBlockContent;
1175
+
1176
+ safeBackupFile(targetFile, fs.lstatSync(targetFile).mode);
1177
+
1178
+ const memorealRegex = /<!-- memoreal:start -->[\s\S]*?<!-- memoreal:end -->/;
1179
+ const memoriaRegex = /<!-- memoria:start -->[\s\S]*?<!-- memoria:end -->/;
1180
+
1181
+ let updatedContent;
1182
+ if (memorealRegex.test(existing)) {
1183
+ updatedContent = existing.replace(memorealRegex, blockContent);
1184
+ } else if (memoriaRegex.test(existing)) {
1185
+ updatedContent = existing.replace(memoriaRegex, blockContent);
1186
+ } else {
1187
+ const trimmed = existing.trimEnd();
1188
+ updatedContent = trimmed
1189
+ ? `${trimmed}${eol}${eol}${blockContent}${eol}`
1190
+ : `${blockContent}${eol}`;
1191
+ }
1192
+ fs.writeFileSync(targetFile, updatedContent, { mode: 0o644 });
1193
+ recordAction(targetFile, 'updated');
1194
+ } else {
1195
+ fs.writeFileSync(targetFile, `${rawBlockContent}\n`, { mode: 0o644 });
1196
+ recordAction(targetFile, 'created');
1197
+ }
1198
+ }
1199
+
1200
+ // 1. Install <homeDir>/.memoreal/bin/ {memoreal-ns, memoreal-ns.mjs, memoreal-ns.cmd, memoreal-hook.mjs} (0o755) with .bak backup
1201
+ const binScripts = ['memoreal-ns', 'memoreal-ns.mjs', 'memoreal-ns.cmd', 'memoreal-hook.mjs'];
1202
+ for (const scriptName of binScripts) {
1203
+ const binSource = path.join(PACKAGE_ROOT, 'bin', scriptName);
1204
+ const binTarget = path.join(resolvedHome, '.memoreal', 'bin', scriptName);
1205
+ copyFileWithBak(binSource, binTarget, 0o755);
1206
+ }
1207
+
1208
+ // 2. OpenCode: xdgConfig/opencode (+ legacy ~/.config/opencode and win32 appData/opencode)
1209
+ const opencodeDirs = [path.join(xdgConfig, 'opencode')];
1210
+ const legacyOpencodeDir = path.join(resolvedHome, '.config', 'opencode');
1211
+ if (!opencodeDirs.includes(legacyOpencodeDir)) {
1212
+ opencodeDirs.push(legacyOpencodeDir);
1213
+ }
1214
+ if (isWin) {
1215
+ const winOpencodeDir = path.join(appData, 'opencode');
1216
+ if (!opencodeDirs.includes(winOpencodeDir)) {
1217
+ opencodeDirs.push(winOpencodeDir);
1218
+ }
1219
+ }
1220
+
1221
+ for (const opDir of opencodeDirs) {
1222
+ const shouldTouchOpencode =
1223
+ fs.existsSync(opDir) ||
1224
+ (opDir === opencodeDirs[0] && normalizedPreferred === 'opencode');
1225
+
1226
+ if (shouldTouchOpencode) {
1227
+ const opencodePluginSrc = path.join(PACKAGE_ROOT, 'opencode', 'memoreal-hooks.js');
1228
+ const opencodePluginDest = path.join(opDir, 'plugins', 'memoreal-hooks.js');
1229
+ copyFileWithBak(opencodePluginSrc, opencodePluginDest, 0o644);
1230
+
1231
+ const opencodeBinSrc = path.join(PACKAGE_ROOT, 'bin', 'memoreal-ns.mjs');
1232
+ const opencodeBinDest = path.join(opDir, 'bin', 'memoreal-ns.mjs');
1233
+ copyFileWithBak(opencodeBinSrc, opencodeBinDest, 0o755);
1234
+
1235
+ const skillsSrc = path.join(PACKAGE_ROOT, 'skills');
1236
+ const opencodeSkillsDest = path.join(opDir, 'skills');
1237
+ copyDirectoryRecursiveWithBak(skillsSrc, opencodeSkillsDest);
1238
+
1239
+ const opencodeAgentsMd = resolveCaseInsensitiveMdPath(opDir, 'AGENTS.md');
1240
+ upsertMarkdownWithBak(opencodeAgentsMd);
1241
+ }
1242
+ }
1243
+
1244
+ // 3. Claude Code: <claudeDir> exists or preferredTool === 'claude-code' | 'claude'
1245
+ const claudeDir = osPaths.claudeDir;
1246
+ const shouldTouchClaude =
1247
+ fs.existsSync(claudeDir) ||
1248
+ normalizedPreferred === 'claude-code' ||
1249
+ normalizedPreferred === 'claude';
1250
+
1251
+ if (shouldTouchClaude) {
1252
+ const claudeSettingsPath = path.join(claudeDir, 'settings.json');
1253
+ const hooksSourcePath = path.join(PACKAGE_ROOT, 'hooks', 'hooks.json');
1254
+
1255
+ if (fs.existsSync(hooksSourcePath)) {
1256
+ try {
1257
+ const hooksJsonRaw = fs.readFileSync(hooksSourcePath, 'utf8');
1258
+ const hooksConfig = JSON.parse(hooksJsonRaw);
1259
+ const sourceHooks = hooksConfig.hooks || {};
1260
+
1261
+ let parsedSettings = null;
1262
+ let isCreate = !fs.existsSync(claudeSettingsPath);
1263
+ let malformed = false;
1264
+
1265
+ if (!isCreate) {
1266
+ const rawSettings = fs.readFileSync(claudeSettingsPath, 'utf8');
1267
+ try {
1268
+ parsedSettings = JSON.parse(rawSettings);
1269
+ if (
1270
+ typeof parsedSettings !== 'object' ||
1271
+ parsedSettings === null ||
1272
+ Array.isArray(parsedSettings)
1273
+ ) {
1274
+ malformed = true;
1275
+ }
1276
+ } catch {
1277
+ malformed = true;
1278
+ }
1279
+ } else {
1280
+ parsedSettings = { hooks: {} };
1281
+ }
1282
+
1283
+ if (malformed) {
1284
+ skipped.push({
1285
+ file: claudeSettingsPath,
1286
+ status: 'skipped_malformed_json',
1287
+ });
1288
+ } else {
1289
+ const forwardSlashedHome = resolvedHome.replace(/\\/g, '/');
1290
+ if (/["`\r\n\0$]/.test(forwardSlashedHome)) {
1291
+ skipped.push({
1292
+ file: claudeSettingsPath,
1293
+ status: 'skipped_unsafe_home_path',
1294
+ });
1295
+ } else {
1296
+ if (!isCreate) {
1297
+ safeBackupFile(claudeSettingsPath, fs.statSync(claudeSettingsPath).mode);
1298
+ }
1299
+ parsedSettings.hooks = parsedSettings.hooks || {};
1300
+
1301
+ for (const [eventName, eventGroups] of Object.entries(sourceHooks)) {
1302
+ if (!Array.isArray(eventGroups)) continue;
1303
+ if (!/^[A-Za-z0-9_-]+$/.test(eventName)) continue;
1304
+
1305
+ if (!Array.isArray(parsedSettings.hooks[eventName])) {
1306
+ parsedSettings.hooks[eventName] = [];
1307
+ }
1308
+ const existingGroups = parsedSettings.hooks[eventName];
1309
+
1310
+ for (const group of eventGroups) {
1311
+ const matcher = group.matcher || '';
1312
+ const hooksList = Array.isArray(group.hooks) ? group.hooks : [];
1313
+ const matcherArg = matcher || 'all';
1314
+ if (!/^[A-Za-z0-9_-]+$/.test(matcherArg)) continue;
1315
+
1316
+ const nonDuplicateHooks = [];
1317
+
1318
+ for (const hook of hooksList) {
1319
+ const marker = hook.command
1320
+ ? (hook.command.match(/\[(memoreal|memoria)-[^\]]+\]/)?.[0] || null)
1321
+ : null;
1322
+
1323
+ const rewrittenCommand = marker
1324
+ ? `node "${forwardSlashedHome}/.memoreal/bin/memoreal-hook.mjs" ${eventName} ${matcherArg} "${marker}"`
1325
+ : hook.command;
1326
+
1327
+ const targetHook = { ...hook, command: rewrittenCommand };
1328
+
1329
+ let isDuplicate = false;
1330
+ for (const eg of existingGroups) {
1331
+ if ((eg.matcher || '') !== matcher) continue;
1332
+ for (const eh of (eg.hooks || [])) {
1333
+ if (eh.command === rewrittenCommand) {
1334
+ isDuplicate = true;
1335
+ break;
1336
+ }
1337
+ if (marker && typeof eh.command === 'string') {
1338
+ const memorealMarker = marker.replace('[memoria-', '[memoreal-');
1339
+ const legacyMarker = memorealMarker.replace('[memoreal-', '[memoria-');
1340
+ if (eh.command.includes(memorealMarker) || eh.command.includes(legacyMarker)) {
1341
+ eh.command = rewrittenCommand;
1342
+ isDuplicate = true;
1343
+ break;
1344
+ }
1345
+ }
1346
+ }
1347
+ if (isDuplicate) break;
1348
+ }
1349
+
1350
+ if (!isDuplicate) {
1351
+ nonDuplicateHooks.push(targetHook);
1352
+ }
1353
+ }
1354
+
1355
+ if (nonDuplicateHooks.length === 0) continue;
1356
+
1357
+ const matchingGroup = existingGroups.find(
1358
+ (eg) => (eg.matcher || '') === matcher
1359
+ );
1360
+ if (matchingGroup) {
1361
+ matchingGroup.hooks = matchingGroup.hooks || [];
1362
+ matchingGroup.hooks.push(...nonDuplicateHooks);
1363
+ } else {
1364
+ existingGroups.push({
1365
+ matcher,
1366
+ hooks: nonDuplicateHooks,
1367
+ });
1368
+ }
1369
+ }
1370
+ }
1371
+
1372
+ fs.mkdirSync(claudeDir, { recursive: true });
1373
+ fs.writeFileSync(
1374
+ claudeSettingsPath,
1375
+ JSON.stringify(parsedSettings, null, 2) + '\n',
1376
+ { mode: 0o600 }
1377
+ );
1378
+ try {
1379
+ fs.chmodSync(claudeSettingsPath, 0o600);
1380
+ } catch {}
1381
+ recordAction(claudeSettingsPath, isCreate ? 'created' : 'updated');
1382
+ }
1383
+ }
1384
+ } catch {
1385
+ // Safe fallback if hooks.json cannot be read
1386
+ }
1387
+ }
1388
+
1389
+ const skillsSrc = path.join(PACKAGE_ROOT, 'skills');
1390
+ const claudeSkillsDest = path.join(claudeDir, 'skills');
1391
+ copyDirectoryRecursiveWithBak(skillsSrc, claudeSkillsDest);
1392
+
1393
+ const claudeMdPath = resolveCaseInsensitiveMdPath(claudeDir, 'CLAUDE.md');
1394
+ upsertMarkdownWithBak(claudeMdPath);
1395
+ }
1396
+
1397
+ // 4. Cursor: <resolvedHome>/.cursor exists or preferredTool === 'cursor'
1398
+ const cursorDir = path.join(resolvedHome, '.cursor');
1399
+ const shouldTouchCursor =
1400
+ fs.existsSync(cursorDir) || normalizedPreferred === 'cursor';
1401
+
1402
+ if (shouldTouchCursor) {
1403
+ const rulesSource = path.join(PACKAGE_ROOT, 'rules', 'memoreal.mdc');
1404
+ const userRuleTarget = path.join(cursorDir, 'rules', 'memoreal.mdc');
1405
+ copyFileWithBak(rulesSource, userRuleTarget, 0o644);
1406
+ }
1407
+
1408
+ // projectDir/.cursor/rules/memoreal.mdc when projectDir/.cursor exists
1409
+ if (projectDir) {
1410
+ const projectCursorDir = path.join(projectDir, '.cursor');
1411
+ if (fs.existsSync(projectCursorDir)) {
1412
+ const rulesSource = path.join(PACKAGE_ROOT, 'rules', 'memoreal.mdc');
1413
+ const projectRuleTarget = path.join(projectCursorDir, 'rules', 'memoreal.mdc');
1414
+ copyFileWithBak(rulesSource, projectRuleTarget, 0o644);
1415
+ }
1416
+ }
1417
+
1418
+ // 5. Codex: <codexDir> exists or preferredTool === 'codex' (.codex/AGENTS.md + .codex/skills/*)
1419
+ const shouldTouchCodex =
1420
+ fs.existsSync(codexDir) || normalizedPreferred === 'codex';
1421
+
1422
+ if (shouldTouchCodex) {
1423
+ const codexAgentsMd = resolveCaseInsensitiveMdPath(codexDir, 'AGENTS.md');
1424
+ upsertMarkdownWithBak(codexAgentsMd);
1425
+
1426
+ const skillsSrc = path.join(PACKAGE_ROOT, 'skills');
1427
+ const codexSkillsDest = path.join(codexDir, 'skills');
1428
+ copyDirectoryRecursiveWithBak(skillsSrc, codexSkillsDest);
1429
+ }
1430
+
1431
+ // 6. Windsurf: memories/global_rules.md
1432
+ const windsurfDir = path.join(resolvedHome, '.codeium', 'windsurf');
1433
+ const shouldTouchWindsurf =
1434
+ fs.existsSync(windsurfDir) || normalizedPreferred === 'windsurf';
1435
+
1436
+ if (shouldTouchWindsurf) {
1437
+ const windsurfRules = path.join(windsurfDir, 'memories', 'global_rules.md');
1438
+ upsertMarkdownWithBak(windsurfRules);
1439
+ }
1440
+
1441
+ // 7. Gemini CLI: .gemini/GEMINI.md
1442
+ const geminiDir = path.join(resolvedHome, '.gemini');
1443
+ const shouldTouchGemini =
1444
+ fs.existsSync(geminiDir) ||
1445
+ normalizedPreferred === 'gemini' ||
1446
+ normalizedPreferred === 'gemini-cli';
1447
+
1448
+ if (shouldTouchGemini) {
1449
+ const geminiMd = resolveCaseInsensitiveMdPath(geminiDir, 'GEMINI.md');
1450
+ upsertMarkdownWithBak(geminiMd);
1451
+ }
1452
+
1453
+ // 8. Amp: <xdgConfig>/amp/AGENTS.md and win32 <appData>/amp/AGENTS.md
1454
+ const ampDirs = [path.join(xdgConfig, 'amp')];
1455
+ if (isWin) {
1456
+ const winAmpDir = path.join(appData, 'amp');
1457
+ if (!ampDirs.includes(winAmpDir)) {
1458
+ ampDirs.push(winAmpDir);
1459
+ }
1460
+ }
1461
+
1462
+ for (const aDir of ampDirs) {
1463
+ const shouldTouchAmp =
1464
+ fs.existsSync(aDir) || (aDir === ampDirs[0] && normalizedPreferred === 'amp');
1465
+
1466
+ if (shouldTouchAmp) {
1467
+ const ampAgentsMd = resolveCaseInsensitiveMdPath(aDir, 'AGENTS.md');
1468
+ upsertMarkdownWithBak(ampAgentsMd);
1469
+ }
1470
+ }
1471
+
1472
+ // 9. Kiro: <resolvedHome>/.kiro/steering/memoreal.md
1473
+ const kiroDir = path.join(resolvedHome, '.kiro');
1474
+ const shouldTouchKiro =
1475
+ fs.existsSync(kiroDir) || normalizedPreferred === 'kiro';
1476
+
1477
+ if (shouldTouchKiro) {
1478
+ const kiroSteering = path.join(kiroDir, 'steering', 'memoreal.md');
1479
+ upsertMarkdownWithBak(kiroSteering);
1480
+ }
1481
+
1482
+ // 10. Aider: <resolvedHome>/.memoreal/CONVENTIONS.md
1483
+ const aiderConfig = path.join(resolvedHome, '.aider.conf.yml');
1484
+ const shouldTouchAider =
1485
+ fs.existsSync(aiderConfig) || normalizedPreferred === 'aider';
1486
+
1487
+ if (shouldTouchAider) {
1488
+ const aiderConventions = path.join(resolvedHome, '.memoreal', 'CONVENTIONS.md');
1489
+ upsertMarkdownWithBak(aiderConventions);
1490
+ }
1491
+
1492
+ // 11. Project instructions: CLAUDE.md, .claude/CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, .clinerules, .roorules
1493
+ if (projectDir) {
1494
+ // Project-level CLAUDE.md (or case-insensitive claude.md) if existing
1495
+ const projClaudeMd = resolveCaseInsensitiveMdPath(projectDir, 'CLAUDE.md');
1496
+ if (fs.existsSync(projClaudeMd)) {
1497
+ upsertMarkdownWithBak(projClaudeMd);
1498
+ }
1499
+
1500
+ // Project-level .claude/CLAUDE.md (or claude.md) if existing
1501
+ const projDotClaudeDir = path.join(projectDir, '.claude');
1502
+ if (fs.existsSync(projDotClaudeDir)) {
1503
+ const projDotClaudeMd = resolveCaseInsensitiveMdPath(projDotClaudeDir, 'CLAUDE.md');
1504
+ if (fs.existsSync(projDotClaudeMd)) {
1505
+ upsertMarkdownWithBak(projDotClaudeMd);
1506
+ }
1507
+ }
1508
+
1509
+ // Project-level AGENTS.md (or case-insensitive agents.md) if existing
1510
+ const projAgentsMd = resolveCaseInsensitiveMdPath(projectDir, 'AGENTS.md');
1511
+ if (fs.existsSync(projAgentsMd)) {
1512
+ upsertMarkdownWithBak(projAgentsMd);
1513
+ }
1514
+
1515
+ const githubDir = path.join(projectDir, '.github');
1516
+ const copilotMd = path.join(githubDir, 'copilot-instructions.md');
1517
+ if (
1518
+ fs.existsSync(githubDir) &&
1519
+ (normalizedPreferred === 'vscode' ||
1520
+ normalizedPreferred === 'copilot' ||
1521
+ fs.existsSync(copilotMd))
1522
+ ) {
1523
+ upsertMarkdownWithBak(copilotMd);
1524
+ }
1525
+
1526
+ const clineRules = path.join(projectDir, '.clinerules');
1527
+ if (
1528
+ fs.existsSync(clineRules) ||
1529
+ (normalizedPreferred === 'cline' && fs.existsSync(path.join(projectDir, '.vscode')))
1530
+ ) {
1531
+ upsertMarkdownWithBak(clineRules);
1532
+ }
1533
+
1534
+ const rooRules = path.join(projectDir, '.roorules');
1535
+ if (
1536
+ fs.existsSync(rooRules) ||
1537
+ ((normalizedPreferred === 'roo-code' || normalizedPreferred === 'roo') &&
1538
+ fs.existsSync(path.join(projectDir, '.vscode')))
1539
+ ) {
1540
+ upsertMarkdownWithBak(rooRules);
1541
+ }
1542
+ }
1543
+
1544
+ return {
1545
+ provisioned,
1546
+ updated,
1547
+ skipped,
1548
+ };
1549
+ }