Repository navigation
Expand file tree
/
Copy pathcli.ts
More file actions
2845 lines (2499 loc) · 105 KB
/
Copy pathcli.ts
File metadata and controls
2845 lines (2499 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* code-session-memory CLI
*
* Usage:
* npx code-session-memory install — install for all detected supported tools
* npx code-session-memory status — show installation status
* npx code-session-memory uninstall — remove all installed components
* npx code-session-memory reset-db — wipe the database (with confirmation)
* npx code-session-memory sessions — browse / print / delete sessions
*/
import fs from "fs";
import path from "path";
import os from "os";
import * as clack from "@clack/prompts";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import { resolveDbPath, openDatabase } from "./database";
import { cmdSessions } from "./cli-sessions";
import { cmdQuery } from "./cli-query";
import {
resolveNodeExecutable,
isResolvedNodePath,
buildNodeCommand,
hydrateEnv,
captureEnvFromProcess,
saveEnvSnapshot,
loadEnvSnapshot,
getEnvFilePath,
maskEnvValue,
SNAPSHOT_ENV_KEYS,
REQUIRED_ENV_KEYS,
} from "./runtime-env";
import { getHookLogPath, readHookLog } from "./hook-log";
// ---------------------------------------------------------------------------
// Paths — OpenCode
// ---------------------------------------------------------------------------
function getOpenCodeConfigDir(): string {
const envDir = process.env.OPENCODE_CONFIG_DIR;
if (envDir) return envDir;
return path.join(os.homedir(), ".config", "opencode");
}
function getOpenCodePluginDst(): string {
return path.join(getOpenCodeConfigDir(), "plugins", "code-session-memory.ts");
}
function getOpenCodeSkillDst(): string {
return path.join(getOpenCodeConfigDir(), "skills", "code-session-memory", "SKILL.md");
}
function getGlobalOpenCodeConfigPath(): string {
return path.join(getOpenCodeConfigDir(), "opencode.json");
}
// ---------------------------------------------------------------------------
// Paths — Claude Code
// ---------------------------------------------------------------------------
function getClaudeConfigDir(): string {
const envDir = process.env.CLAUDE_CONFIG_DIR;
if (envDir) return envDir;
return path.join(os.homedir(), ".claude");
}
function getClaudeSettingsPath(): string {
return path.join(getClaudeConfigDir(), "settings.json");
}
/**
* ~/.claude.json — user-scoped config file where Claude Code stores global
* MCP servers (written by `claude mcp add --scope user`).
*/
function getClaudeUserConfigPath(): string {
// ~/.claude.json lives next to the ~/.claude/ directory
return path.join(path.dirname(getClaudeConfigDir()), ".claude.json");
}
function getClaudeMdPath(): string {
return path.join(getClaudeConfigDir(), "CLAUDE.md");
}
function getClaudeSkillDst(): string {
return path.join(getClaudeConfigDir(), "skills", "code-session-memory", "SKILL.md");
}
// ---------------------------------------------------------------------------
// Paths — package
// ---------------------------------------------------------------------------
function getPackageRoot(): string {
// __dirname is dist/src/ after build, so go two levels up
return path.resolve(__dirname, "..", "..");
}
function getPluginSrc(): string {
return path.join(getPackageRoot(), "plugin", "memory.ts");
}
function getSkillSrc(): string {
return path.join(getPackageRoot(), "skill", "memory.md");
}
function getMcpServerPath(): string {
return path.join(getPackageRoot(), "dist", "mcp", "index.js");
}
function getIndexerCliPath(): string {
return path.join(getPackageRoot(), "dist", "src", "indexer-cli.js");
}
function getIndexerCliClaudePath(): string {
return path.join(getPackageRoot(), "dist", "src", "indexer-cli-claude.js");
}
function getIndexerCliCursorPath(): string {
return path.join(getPackageRoot(), "dist", "src", "indexer-cli-cursor.js");
}
function getIndexerCliVscodePath(): string {
return path.join(getPackageRoot(), "dist", "src", "indexer-cli-vscode.js");
}
function getIndexerCliCodexPath(): string {
return path.join(getPackageRoot(), "dist", "src", "indexer-cli-codex.js");
}
function getIndexerCliGeminiPath(): string {
return path.join(getPackageRoot(), "dist", "src", "indexer-cli-gemini.js");
}
function getIndexerCliAntigravityPath(): string {
return path.join(getPackageRoot(), "dist", "src", "indexer-cli-antigravity.js");
}
// ---------------------------------------------------------------------------
// Paths — Cursor
// ---------------------------------------------------------------------------
function getCursorConfigDir(): string {
const envDir = process.env.CURSOR_CONFIG_DIR;
if (envDir) return envDir;
return path.join(os.homedir(), ".cursor");
}
function getCursorHooksPath(): string {
return path.join(getCursorConfigDir(), "hooks.json");
}
function getCursorHooksScriptDir(): string {
return path.join(getCursorConfigDir(), "hooks");
}
function getCursorMcpConfigPath(): string {
return path.join(getCursorConfigDir(), "mcp.json");
}
function getCursorSkillDst(): string {
return path.join(getCursorConfigDir(), "skills", "code-session-memory", "SKILL.md");
}
// ---------------------------------------------------------------------------
// Paths — VS Code
// ---------------------------------------------------------------------------
function getVscodeConfigDir(): string {
const envDir = process.env.VSCODE_CONFIG_DIR;
if (envDir) return envDir;
if (process.platform === "darwin") {
return path.join(os.homedir(), "Library", "Application Support", "Code", "User");
}
// Linux (and fallback)
return path.join(os.homedir(), ".config", "Code", "User");
}
function getVscodeSettingsPath(): string {
return path.join(getVscodeConfigDir(), "settings.json");
}
function getVscodeMcpConfigPath(): string {
return path.join(getVscodeConfigDir(), "mcp.json");
}
function getVscodeHooksPath(): string {
return path.join(getVscodeConfigDir(), "hooks", "code-session-memory.json");
}
// ---------------------------------------------------------------------------
// Paths — Codex
// ---------------------------------------------------------------------------
function getCodexConfigDir(): string {
const envDir = process.env.CODEX_HOME;
if (envDir) return envDir;
return path.join(os.homedir(), ".codex");
}
function getCodexConfigPath(): string {
return path.join(getCodexConfigDir(), "config.toml");
}
function getCodexSkillDst(): string {
return path.join(getCodexConfigDir(), "skills", "code-session-memory", "SKILL.md");
}
// ---------------------------------------------------------------------------
// Paths — Gemini CLI
// ---------------------------------------------------------------------------
function getGeminiConfigDir(): string {
const envDir = process.env.GEMINI_CONFIG_DIR;
if (envDir) return envDir;
return path.join(os.homedir(), ".gemini");
}
function getGeminiSettingsPath(): string {
return path.join(getGeminiConfigDir(), "settings.json");
}
function getGeminiSkillDst(): string {
return path.join(getGeminiConfigDir(), "skills", "code-session-memory", "SKILL.md");
}
// ---------------------------------------------------------------------------
// Paths — Antigravity 2.x
//
// Antigravity shares ~/.gemini with Gemini CLI but reads none of its files:
// its global customization root is ~/.gemini/config/, holding mcp_config.json,
// hooks.json and skills/<name>/SKILL.md. The same root serves all three
// surfaces (the 2.x app, the IDE and the CLI).
// ---------------------------------------------------------------------------
function getAntigravityConfigDir(): string {
const envDir = process.env.ANTIGRAVITY_CONFIG_DIR;
if (envDir) return envDir;
return path.join(getGeminiConfigDir(), "config");
}
function getAntigravityMcpConfigPath(): string {
return path.join(getAntigravityConfigDir(), "mcp_config.json");
}
function getAntigravityHooksPath(): string {
return path.join(getAntigravityConfigDir(), "hooks.json");
}
function getAntigravitySkillDst(): string {
return path.join(getAntigravityConfigDir(), "skills", "code-session-memory", "SKILL.md");
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Parse a JSONC string (JSON with comments and trailing commas).
* VS Code's settings.json uses JSONC, so we need this to read it safely.
*/
function parseJsonc(text: string): unknown {
// Remove single-line comments (// ...)
// Remove multi-line comments (/* ... */)
// Remove trailing commas before } or ]
const stripped = text
.replace(/\/\/[^\n]*/g, "")
.replace(/\/\*[\s\S]*?\*\//g, "")
.replace(/,(\s*[}\]])/g, "$1");
return JSON.parse(stripped);
}
/**
* Reads a JSON file, returning {} for empty/whitespace-only files.
* Throws a descriptive error for non-empty invalid JSON.
*/
function readJsonFileOrEmpty(filePath: string, parser: (text: string) => unknown = JSON.parse): Record<string, unknown> {
const raw = fs.readFileSync(filePath, "utf8").trim();
if (!raw) return {};
try {
return parser(raw) as Record<string, unknown>;
} catch {
throw new Error(`Could not parse existing ${filePath} — please check it is valid JSON.`);
}
}
function ensureDir(dir: string): void {
fs.mkdirSync(dir, { recursive: true });
}
function copyFile(src: string, dst: string): void {
if (!fs.existsSync(src)) {
throw new Error(`Source file not found: ${src}\nDid you run "npm run build" first?`);
}
ensureDir(path.dirname(dst));
fs.copyFileSync(src, dst);
}
/**
* Copies the OpenCode plugin template, replacing the OPENCODE_MEMORY_INDEXER_PATH
* placeholder with the absolute path to indexer-cli.js.
*/
function installOpenCodePlugin(src: string, dst: string, nodePath: string): void {
if (!fs.existsSync(src)) {
throw new Error(`Plugin source not found: ${src}\nDid you run "npm run build" first?`);
}
let content = fs.readFileSync(src, "utf8");
content = content.replace(
'"OPENCODE_MEMORY_INDEXER_PATH"',
JSON.stringify(getIndexerCliPath()),
);
content = content.replace(
'"OPENCODE_MEMORY_NODE_PATH"',
JSON.stringify(nodePath),
);
ensureDir(path.dirname(dst));
fs.writeFileSync(dst, content, "utf8");
}
/**
* Merges the code-session-memory MCP entry into the global opencode.json.
*/
function installOpenCodeMcpConfig(mcpServerPath: string, nodePath: string): { configPath: string; existed: boolean } {
const configPath = getGlobalOpenCodeConfigPath();
const existed = fs.existsSync(configPath);
let config: Record<string, unknown> = { $schema: "https://opencode.ai/config.json" };
if (existed) {
config = { ...config, ...readJsonFileOrEmpty(configPath) };
}
if (!config.mcp || typeof config.mcp !== "object") config.mcp = {};
(config.mcp as Record<string, unknown>)["code-session-memory"] = {
type: "local",
command: [nodePath, mcpServerPath],
};
ensureDir(path.dirname(configPath));
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return { configPath, existed };
}
/**
* Removes the code-session-memory MCP entry from opencode.json.
*/
function uninstallOpenCodeMcpConfig(): "done" | "not_found" {
const configPath = getGlobalOpenCodeConfigPath();
if (!fs.existsSync(configPath)) return "not_found";
try {
const cfg = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record<string, unknown>;
if (cfg.mcp && typeof cfg.mcp === "object" && "code-session-memory" in (cfg.mcp as object)) {
delete (cfg.mcp as Record<string, unknown>)["code-session-memory"];
fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + "\n", "utf8");
return "done";
}
return "not_found";
} catch {
return "not_found";
}
}
/**
* Installs/updates the Claude Code Stop hook in ~/.claude/settings.json.
*/
function installClaudeHook(indexerCliClaudePath: string, nodePath: string): { settingsPath: string; existed: boolean } {
const settingsPath = getClaudeSettingsPath();
const existed = fs.existsSync(settingsPath);
let settings: Record<string, unknown> = {};
if (existed) {
settings = readJsonFileOrEmpty(settingsPath);
}
if (!settings.hooks || typeof settings.hooks !== "object") settings.hooks = {};
const hooks = settings.hooks as Record<string, unknown[]>;
// Remove any existing code-session-memory Stop hook
if (Array.isArray(hooks.Stop)) {
hooks.Stop = hooks.Stop.filter((group: unknown) => {
if (!group || typeof group !== "object") return true;
const g = group as Record<string, unknown>;
if (!Array.isArray(g.hooks)) return true;
return !g.hooks.some((h: unknown) => {
const handler = h as Record<string, unknown>;
return typeof handler.command === "string" &&
handler.command.includes("indexer-cli-claude");
});
});
} else {
hooks.Stop = [];
}
// Add our hook (synchronous — must NOT be async so the JSONL is fully
// written by Claude Code before we read it)
hooks.Stop.push({
hooks: [
{
type: "command",
command: buildNodeCommand(nodePath, indexerCliClaudePath),
},
],
});
ensureDir(path.dirname(settingsPath));
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
return { settingsPath, existed };
}
/**
* Removes the code-session-memory Stop hook from ~/.claude/settings.json.
*/
function uninstallClaudeHook(): "done" | "not_found" {
const settingsPath = getClaudeSettingsPath();
if (!fs.existsSync(settingsPath)) return "not_found";
try {
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
const hooks = settings.hooks as Record<string, unknown[]> | undefined;
if (!hooks || !Array.isArray(hooks.Stop)) return "not_found";
const before = hooks.Stop.length;
hooks.Stop = hooks.Stop.filter((group: unknown) => {
if (!group || typeof group !== "object") return true;
const g = group as Record<string, unknown>;
if (!Array.isArray(g.hooks)) return true;
return !g.hooks.some((h: unknown) => {
const handler = h as Record<string, unknown>;
return typeof handler.command === "string" &&
handler.command.includes("indexer-cli-claude");
});
});
if (hooks.Stop.length === before) return "not_found";
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
return "done";
} catch {
return "not_found";
}
}
/**
* Appends the memory skill context to ~/.claude/CLAUDE.md.
*/
function installClaudeMd(skillSrc: string): { mdPath: string; existed: boolean } {
const mdPath = getClaudeMdPath();
const existed = fs.existsSync(mdPath);
const marker = "<!-- code-session-memory -->";
const skillContent = fs.existsSync(skillSrc)
? fs.readFileSync(skillSrc, "utf8")
: "";
if (existed) {
const current = fs.readFileSync(mdPath, "utf8");
// Replace existing block if present
if (current.includes(marker)) {
const updated = current.replace(
new RegExp(`${marker}[\\s\\S]*?${marker}`, "g"),
`${marker}\n${skillContent}\n${marker}`,
);
fs.writeFileSync(mdPath, updated, "utf8");
return { mdPath, existed };
}
// Append
fs.writeFileSync(mdPath, current + `\n\n${marker}\n${skillContent}\n${marker}\n`, "utf8");
} else {
ensureDir(path.dirname(mdPath));
fs.writeFileSync(mdPath, `${marker}\n${skillContent}\n${marker}\n`, "utf8");
}
return { mdPath, existed };
}
/**
* Removes the code-session-memory block from CLAUDE.md.
*/
function uninstallClaudeMd(): "done" | "not_found" {
const mdPath = getClaudeMdPath();
if (!fs.existsSync(mdPath)) return "not_found";
const marker = "<!-- code-session-memory -->";
const content = fs.readFileSync(mdPath, "utf8");
if (!content.includes(marker)) return "not_found";
const updated = content
.replace(new RegExp(`\\n?\\n?${marker}[\\s\\S]*?${marker}\\n?`, "g"), "")
.trimEnd();
fs.writeFileSync(mdPath, updated ? updated + "\n" : "", "utf8");
return "done";
}
function installClaudeSkill(skillSrc: string): { dstPath: string; existed: boolean } {
const dstPath = getClaudeSkillDst();
const existed = fs.existsSync(dstPath);
if (!fs.existsSync(skillSrc)) {
throw new Error(`Skill source not found: ${skillSrc}\nDid you run "npm run build" first?`);
}
const skillBody = fs.readFileSync(skillSrc, "utf8");
const bodyWithoutFrontmatter = skillBody.replace(/^---[\s\S]*?---\s*\n?/, "").trimStart();
const frontmatter = [
"---",
"name: code-session-memory",
"description: Search past OpenCode, Claude Code, Cursor, VS Code, Codex, and Gemini CLI sessions. Use when the user asks about past work, decisions, or implementations.",
"---",
"",
].join("\n");
ensureDir(path.dirname(dstPath));
fs.writeFileSync(dstPath, frontmatter + bodyWithoutFrontmatter, "utf8");
// Migrate: clean up old CLAUDE.md injection if present
uninstallClaudeMd();
return { dstPath, existed };
}
function checkClaudeSkillInstalled(): boolean {
return fs.existsSync(getClaudeSkillDst());
}
function uninstallClaudeSkill(): "done" | "not_found" {
const dst = getClaudeSkillDst();
if (!fs.existsSync(dst)) return "not_found";
fs.rmSync(path.dirname(dst), { recursive: true, force: true });
return "done";
}
function checkMcpConfigured(): boolean {
const configPath = getGlobalOpenCodeConfigPath();
try {
const raw = fs.readFileSync(configPath, "utf8");
const cfg = JSON.parse(raw) as Record<string, unknown>;
return !!(cfg.mcp && typeof cfg.mcp === "object" && "code-session-memory" in (cfg.mcp as object));
} catch { return false; }
}
/**
* Merges the code-session-memory MCP entry into ~/.claude.json (user-scoped).
* Claude Code stores global MCP servers here under "mcpServers" with
* { type: "stdio", command, args, env } shape.
*/
function installClaudeMcpConfig(mcpServerPath: string, nodePath: string): { configPath: string; existed: boolean } {
const configPath = getClaudeUserConfigPath();
const existed = fs.existsSync(configPath);
let config: Record<string, unknown> = {};
if (existed) {
config = readJsonFileOrEmpty(configPath);
}
if (!config.mcpServers || typeof config.mcpServers !== "object") config.mcpServers = {};
(config.mcpServers as Record<string, unknown>)["code-session-memory"] = {
type: "stdio",
command: nodePath,
args: [mcpServerPath],
env: {},
};
ensureDir(path.dirname(configPath));
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return { configPath, existed };
}
/**
* Removes the code-session-memory MCP entry from ~/.claude.json.
*/
function uninstallClaudeMcpConfig(): "done" | "not_found" {
const configPath = getClaudeUserConfigPath();
if (!fs.existsSync(configPath)) return "not_found";
try {
const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record<string, unknown>;
if (
config.mcpServers &&
typeof config.mcpServers === "object" &&
"code-session-memory" in (config.mcpServers as object)
) {
delete (config.mcpServers as Record<string, unknown>)["code-session-memory"];
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return "done";
}
return "not_found";
} catch {
return "not_found";
}
}
function checkClaudeMcpConfigured(): boolean {
const configPath = getClaudeUserConfigPath();
try {
const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record<string, unknown>;
return !!(
config.mcpServers &&
typeof config.mcpServers === "object" &&
"code-session-memory" in (config.mcpServers as object)
);
} catch { return false; }
}
function checkClaudeHookInstalled(): boolean {
const settingsPath = getClaudeSettingsPath();
try {
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
const hooks = settings.hooks as Record<string, unknown[]> | undefined;
if (!hooks || !Array.isArray(hooks.Stop)) return false;
return hooks.Stop.some((group: unknown) => {
if (!group || typeof group !== "object") return false;
const g = group as Record<string, unknown>;
if (!Array.isArray(g.hooks)) return false;
return g.hooks.some((h: unknown) => {
const handler = h as Record<string, unknown>;
return typeof handler.command === "string" &&
handler.command.includes("indexer-cli-claude");
});
});
} catch { return false; }
}
function checkClaudeMdInstalled(): boolean {
const mdPath = getClaudeMdPath();
if (!fs.existsSync(mdPath)) return false;
return fs.readFileSync(mdPath, "utf8").includes("<!-- code-session-memory -->");
}
// ---------------------------------------------------------------------------
// Cursor — hook
// ---------------------------------------------------------------------------
/**
* Installs/updates the Cursor stop hook in ~/.cursor/hooks.json.
* Merges with any existing hooks — never clobbers other entries.
*/
function installCursorHook(indexerCliCursorPath: string, nodePath: string): { hooksPath: string; existed: boolean } {
const hooksPath = getCursorHooksPath();
const existed = fs.existsSync(hooksPath);
let config: { version?: number; hooks?: Record<string, unknown[]> } = {};
if (existed) {
config = readJsonFileOrEmpty(hooksPath) as typeof config;
}
config.version = config.version ?? 1;
if (!config.hooks || typeof config.hooks !== "object") config.hooks = {};
// Remove any existing code-session-memory stop hook
if (Array.isArray(config.hooks.stop)) {
config.hooks.stop = config.hooks.stop.filter((entry: unknown) => {
if (!entry || typeof entry !== "object") return true;
const e = entry as Record<string, unknown>;
return typeof e.command !== "string" || !e.command.includes("indexer-cli-cursor");
});
} else {
config.hooks.stop = [];
}
config.hooks.stop.push({ command: buildNodeCommand(nodePath, indexerCliCursorPath) });
ensureDir(path.dirname(hooksPath));
fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return { hooksPath, existed };
}
/**
* Removes the code-session-memory stop hook from ~/.cursor/hooks.json.
*/
function uninstallCursorHook(): "done" | "not_found" {
const hooksPath = getCursorHooksPath();
if (!fs.existsSync(hooksPath)) return "not_found";
try {
const config = JSON.parse(fs.readFileSync(hooksPath, "utf8")) as {
version?: number;
hooks?: Record<string, unknown[]>;
};
const stop = config.hooks?.stop;
if (!Array.isArray(stop)) return "not_found";
const before = stop.length;
config.hooks!.stop = stop.filter((entry: unknown) => {
if (!entry || typeof entry !== "object") return true;
const e = entry as Record<string, unknown>;
return typeof e.command !== "string" || !e.command.includes("indexer-cli-cursor");
});
if (config.hooks!.stop.length === before) return "not_found";
fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return "done";
} catch {
return "not_found";
}
}
function checkCursorHookInstalled(): boolean {
const hooksPath = getCursorHooksPath();
try {
const config = JSON.parse(fs.readFileSync(hooksPath, "utf8")) as {
hooks?: Record<string, unknown[]>;
};
const stop = config.hooks?.stop;
if (!Array.isArray(stop)) return false;
return stop.some((entry: unknown) => {
if (!entry || typeof entry !== "object") return false;
const e = entry as Record<string, unknown>;
return typeof e.command === "string" && e.command.includes("indexer-cli-cursor");
});
} catch { return false; }
}
// ---------------------------------------------------------------------------
// Cursor — MCP config
// ---------------------------------------------------------------------------
/**
* Merges the code-session-memory MCP entry into ~/.cursor/mcp.json.
*/
function installCursorMcpConfig(mcpServerPath: string, nodePath: string): { configPath: string; existed: boolean } {
const configPath = getCursorMcpConfigPath();
const existed = fs.existsSync(configPath);
let config: Record<string, unknown> = {};
if (existed) {
config = readJsonFileOrEmpty(configPath);
}
if (!config.mcpServers || typeof config.mcpServers !== "object") config.mcpServers = {};
(config.mcpServers as Record<string, unknown>)["code-session-memory"] = {
command: nodePath,
args: [mcpServerPath],
env: {},
};
ensureDir(path.dirname(configPath));
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return { configPath, existed };
}
/**
* Removes the code-session-memory MCP entry from ~/.cursor/mcp.json.
*/
function uninstallCursorMcpConfig(): "done" | "not_found" {
const configPath = getCursorMcpConfigPath();
if (!fs.existsSync(configPath)) return "not_found";
try {
const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record<string, unknown>;
if (
config.mcpServers &&
typeof config.mcpServers === "object" &&
"code-session-memory" in (config.mcpServers as object)
) {
delete (config.mcpServers as Record<string, unknown>)["code-session-memory"];
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return "done";
}
return "not_found";
} catch {
return "not_found";
}
}
function checkCursorMcpConfigured(): boolean {
const configPath = getCursorMcpConfigPath();
try {
const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record<string, unknown>;
return !!(
config.mcpServers &&
typeof config.mcpServers === "object" &&
"code-session-memory" in (config.mcpServers as object)
);
} catch { return false; }
}
// ---------------------------------------------------------------------------
// Cursor — skill
// ---------------------------------------------------------------------------
/**
* Copies the shared skill file to ~/.cursor/skills/code-session-memory/SKILL.md,
* prepending Cursor-compatible YAML frontmatter.
*/
function installCursorSkill(skillSrc: string): { dstPath: string; existed: boolean } {
const dstPath = getCursorSkillDst();
const existed = fs.existsSync(dstPath);
if (!fs.existsSync(skillSrc)) {
throw new Error(`Skill source not found: ${skillSrc}\nDid you run "npm run build" first?`);
}
const skillBody = fs.readFileSync(skillSrc, "utf8");
// Strip any existing frontmatter (--- ... ---) before adding Cursor's
const bodyWithoutFrontmatter = skillBody
.replace(/^---[\s\S]*?---\s*\n?/, "")
.trimStart();
const cursorFrontmatter = [
"---",
"name: code-session-memory",
"description: Search past AI coding sessions semantically across OpenCode, Claude Code, Cursor, VS Code, Codex, and Gemini CLI. Use this when the user asks about past work, decisions, or implementations.",
"---",
"",
].join("\n");
ensureDir(path.dirname(dstPath));
fs.writeFileSync(dstPath, cursorFrontmatter + bodyWithoutFrontmatter, "utf8");
return { dstPath, existed };
}
/**
* Removes the code-session-memory skill from ~/.cursor/skills/.
*/
function uninstallCursorSkill(): "done" | "not_found" {
const dstPath = getCursorSkillDst();
if (!fs.existsSync(dstPath)) return "not_found";
fs.unlinkSync(dstPath);
// Remove the directory if empty
try {
const dir = path.dirname(dstPath);
if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
} catch { /* ignore */ }
return "done";
}
// ---------------------------------------------------------------------------
// VS Code — hook
// ---------------------------------------------------------------------------
/**
* Installs the VS Code Stop hook at ~/.vscode/hooks/code-session-memory.json
* using the Copilot hook format.
*/
function installVscodeHook(indexerCliVscodePath: string, nodePath: string): { hooksPath: string; existed: boolean } {
const hooksPath = getVscodeHooksPath();
const existed = fs.existsSync(hooksPath);
// Always overwrite with our hook config (this file is owned by us)
const config = {
hooks: {
Stop: [
{
type: "command",
command: buildNodeCommand(nodePath, indexerCliVscodePath),
},
],
},
};
ensureDir(path.dirname(hooksPath));
fs.writeFileSync(hooksPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return { hooksPath, existed };
}
/**
* Removes the VS Code Stop hook file.
*/
function uninstallVscodeHook(): "done" | "not_found" {
const hooksPath = getVscodeHooksPath();
if (!fs.existsSync(hooksPath)) return "not_found";
fs.unlinkSync(hooksPath);
// Remove the directory if empty
try {
const dir = path.dirname(hooksPath);
if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
} catch { /* ignore */ }
return "done";
}
function checkVscodeHookInstalled(): boolean {
const hooksPath = getVscodeHooksPath();
try {
const config = JSON.parse(fs.readFileSync(hooksPath, "utf8")) as {
hooks?: Record<string, unknown[]>;
};
const stop = config.hooks?.Stop;
if (!Array.isArray(stop)) return false;
return stop.some((entry: unknown) => {
if (!entry || typeof entry !== "object") return false;
const e = entry as Record<string, unknown>;
return typeof e.command === "string" && e.command.includes("indexer-cli-vscode");
});
} catch { return false; }
}
// ---------------------------------------------------------------------------
// VS Code — hook location registration
// ---------------------------------------------------------------------------
/**
* Returns the VS Code hooks path as a ~-prefixed string.
* VS Code supports ~ in hookFilesLocations, which improves portability across
* machines and avoids VS Code showing the fully-expanded path as an error.
*/
function getVscodeHooksPathTilde(): string {
const hooksPath = getVscodeHooksPath();
const home = os.homedir();
if (hooksPath.startsWith(home + path.sep)) {
return "~" + hooksPath.slice(home.length);
}
return hooksPath;
}
/**
* Adds the hook file path to VS Code's settings.json under
* `chat.hookFilesLocations` so VS Code discovers our hook.
* Uses a ~-prefixed path for portability.
*/
function installVscodeHookLocation(): { settingsPath: string; existed: boolean } {
const settingsPath = getVscodeSettingsPath();
const existed = fs.existsSync(settingsPath);
let settings: Record<string, unknown> = {};
if (existed) {
settings = readJsonFileOrEmpty(settingsPath, parseJsonc);
}
const hookLocations = (settings["chat.hookFilesLocations"] ?? {}) as Record<string, boolean>;
// Remove any previously installed absolute path entry (migration)
const absolutePath = getVscodeHooksPath();
if (absolutePath in hookLocations) {
delete hookLocations[absolutePath];
}
hookLocations[getVscodeHooksPathTilde()] = true;
settings["chat.hookFilesLocations"] = hookLocations;
ensureDir(path.dirname(settingsPath));
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
return { settingsPath, existed };
}
/**
* Removes our hook file path from VS Code's `chat.hookFilesLocations` setting.
* Handles both ~ and absolute path variants.
*/
function uninstallVscodeHookLocation(): "done" | "not_found" {
const settingsPath = getVscodeSettingsPath();
if (!fs.existsSync(settingsPath)) return "not_found";
try {
const settings = parseJsonc(fs.readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
const hookLocations = settings["chat.hookFilesLocations"] as Record<string, boolean> | undefined;
if (!hookLocations) return "not_found";
const tildePath = getVscodeHooksPathTilde();
const absolutePath = getVscodeHooksPath();
const foundTilde = tildePath in hookLocations;
const foundAbsolute = absolutePath in hookLocations;
if (!foundTilde && !foundAbsolute) return "not_found";
if (foundTilde) delete hookLocations[tildePath];
if (foundAbsolute) delete hookLocations[absolutePath];
settings["chat.hookFilesLocations"] = hookLocations;
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
return "done";
} catch {
return "not_found";
}
}
function checkVscodeHookLocationRegistered(): boolean {
const settingsPath = getVscodeSettingsPath();
try {
const settings = parseJsonc(fs.readFileSync(settingsPath, "utf8")) as Record<string, unknown>;
const hookLocations = settings["chat.hookFilesLocations"] as Record<string, boolean> | undefined;
if (!hookLocations) return false;
return hookLocations[getVscodeHooksPathTilde()] === true ||
hookLocations[getVscodeHooksPath()] === true;
} catch { return false; }
}
// ---------------------------------------------------------------------------
// VS Code — MCP config
// ---------------------------------------------------------------------------
/**
* Merges the code-session-memory MCP entry into VS Code's mcp.json.
*/
function installVscodeMcpConfig(mcpServerPath: string, nodePath: string): { configPath: string; existed: boolean } {
const configPath = getVscodeMcpConfigPath();
const existed = fs.existsSync(configPath);
let config: Record<string, unknown> = {};
if (existed) {
config = readJsonFileOrEmpty(configPath);
}
if (!config.servers || typeof config.servers !== "object") config.servers = {};
(config.servers as Record<string, unknown>)["code-session-memory"] = {
type: "stdio",
command: nodePath,
args: [mcpServerPath],
};
ensureDir(path.dirname(configPath));
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return { configPath, existed };
}
/**
* Removes the code-session-memory MCP entry from VS Code's mcp.json.
*/
function uninstallVscodeMcpConfig(): "done" | "not_found" {
const configPath = getVscodeMcpConfigPath();
if (!fs.existsSync(configPath)) return "not_found";
try {
const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record<string, unknown>;
if (
config.servers &&
typeof config.servers === "object" &&
"code-session-memory" in (config.servers as object)
) {
delete (config.servers as Record<string, unknown>)["code-session-memory"];
fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf8");
return "done";
}