-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathcli.c
More file actions
3268 lines (2840 loc) · 102 KB
/
cli.c
File metadata and controls
3268 lines (2840 loc) · 102 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
/*
* cli.c — CLI subcommand handlers for install, uninstall, update, version.
*
* Port of Go cmd/codebase-memory-mcp/ install/update logic.
* All functions accept explicit paths for testability.
*/
#include "cli/cli.h"
#include "foundation/compat.h"
#include "foundation/str_util.h"
#include "foundation/platform.h"
// the correct standard headers are included below but clang-tidy doesn't map them.
#include <ctype.h>
#ifndef _WIN32
#include <signal.h>
#include <unistd.h>
#endif
#include "foundation/compat_fs.h"
#ifndef CBM_VERSION
#define CBM_VERSION "dev"
#endif
#include <errno.h> // EEXIST
#include <fcntl.h> // open, O_WRONLY, O_CREAT, O_TRUNC
#include <stdint.h> // uintptr_t
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strtok_r
#include <sys/stat.h> // mode_t, S_IXUSR
#include <zlib.h> // MAX_WBITS
/* yyjson for JSON read-modify-write */
#include "yyjson/yyjson.h"
/* ── Constants ────────────────────────────────────────────────── */
/* Directory permissions: rwxr-x--- */
#define DIR_PERMS 0750
/* Decompression buffer cap (500 MB) */
#define DECOMPRESS_MAX_BYTES ((size_t)500 * 1024 * 1024)
/* Tar header field offsets */
#define TAR_NAME_LEN 101 /* filename field: bytes 0-99 + NUL */
#define TAR_SIZE_OFFSET 124 /* octal size field offset */
#define TAR_SIZE_LEN 13 /* octal size field: bytes 124-135 + NUL */
#define TAR_TYPE_OFFSET 156 /* type flag byte */
#define TAR_BINARY_NAME "codebase-memory-mcp"
#define TAR_BINARY_NAME_LEN 19
#define TAR_BLOCK_SIZE 512 /* tar record alignment */
#define TAR_BLOCK_MASK 511 /* TAR_BLOCK_SIZE - 1 */
/* ── Version ──────────────────────────────────────────────────── */
static const char *cli_version = "dev";
void cbm_cli_set_version(const char *ver) {
if (ver) {
cli_version = ver;
}
}
const char *cbm_cli_get_version(void) {
return cli_version;
}
/* ── Version comparison ───────────────────────────────────────── */
/* Parse semver major.minor.patch into array. Returns number of parts parsed. */
static int parse_semver(const char *v, int out[3]) {
out[0] = out[1] = out[2] = 0;
/* Skip v prefix */
if (*v == 'v' || *v == 'V') {
v++;
}
int count = 0;
while (*v && count < 3) {
if (*v == '-') {
break; /* stop at pre-release suffix */
}
char *endptr;
long val = strtol(v, &endptr, 10);
out[count++] = (int)val;
if (*endptr == '.') {
v = endptr + 1;
} else {
break;
}
}
return count;
}
static bool has_prerelease(const char *v) {
if (*v == 'v' || *v == 'V') {
v++;
}
return strchr(v, '-') != NULL;
}
int cbm_compare_versions(const char *a, const char *b) {
int pa[3];
int pb[3];
parse_semver(a, pa);
parse_semver(b, pb);
for (int i = 0; i < 3; i++) {
if (pa[i] != pb[i]) {
return pa[i] - pb[i];
}
}
/* Same base version — non-dev beats dev */
bool a_pre = has_prerelease(a);
bool b_pre = has_prerelease(b);
if (a_pre && !b_pre) {
return -1;
}
if (!a_pre && b_pre) {
return 1;
}
return 0;
}
/* ── Shell RC detection ───────────────────────────────────────── */
const char *cbm_detect_shell_rc(const char *home_dir) {
static char buf[512];
if (!home_dir || !home_dir[0]) {
return "";
}
// NOLINTNEXTLINE(concurrency-mt-unsafe)
const char *shell = getenv("SHELL");
if (!shell) {
shell = "";
}
if (strstr(shell, "/zsh")) {
snprintf(buf, sizeof(buf), "%s/.zshrc", home_dir);
return buf;
}
if (strstr(shell, "/bash")) {
/* Prefer .bashrc, fall back to .bash_profile */
snprintf(buf, sizeof(buf), "%s/.bashrc", home_dir);
struct stat st;
if (stat(buf, &st) == 0) {
return buf;
}
snprintf(buf, sizeof(buf), "%s/.bash_profile", home_dir);
return buf;
}
if (strstr(shell, "/fish")) {
snprintf(buf, sizeof(buf), "%s/.config/fish/config.fish", home_dir);
return buf;
}
/* Default to .profile */
snprintf(buf, sizeof(buf), "%s/.profile", home_dir);
return buf;
}
/* ── CLI binary detection ─────────────────────────────────────── */
const char *cbm_find_cli(const char *name, const char *home_dir) {
static char buf[512];
if (!name || !name[0]) {
return "";
}
/* Check PATH first */
// NOLINTNEXTLINE(concurrency-mt-unsafe)
const char *path_env = getenv("PATH");
if (path_env) {
char path_copy[4096];
snprintf(path_copy, sizeof(path_copy), "%s", path_env);
char *saveptr;
// NOLINTNEXTLINE(misc-include-cleaner) — strtok_r provided by standard header
char *dir = strtok_r(path_copy, ":", &saveptr);
while (dir) {
snprintf(buf, sizeof(buf), "%s/%s", dir, name);
struct stat st;
// NOLINTNEXTLINE(misc-include-cleaner) — S_IXUSR provided by standard header
if (stat(buf, &st) == 0 && (st.st_mode & S_IXUSR)) {
return buf;
}
dir = strtok_r(NULL, ":", &saveptr);
}
}
/* Check common install locations */
if (home_dir && home_dir[0]) {
const char *candidates[] = {
"/usr/local/bin/%s",
NULL, /* filled dynamically */
NULL,
NULL,
NULL,
};
char paths[5][512];
snprintf(paths[0], sizeof(paths[0]), "/usr/local/bin/%s", name);
snprintf(paths[1], sizeof(paths[1]), "%s/.npm/bin/%s", home_dir, name);
snprintf(paths[2], sizeof(paths[2]), "%s/.local/bin/%s", home_dir, name);
snprintf(paths[3], sizeof(paths[3]), "%s/.cargo/bin/%s", home_dir, name);
#ifdef __APPLE__
snprintf(paths[4], sizeof(paths[4]), "/opt/homebrew/bin/%s", name);
#else
paths[4][0] = '\0';
#endif
(void)candidates;
for (int i = 0; i < 5; i++) {
if (!paths[i][0]) {
continue;
}
struct stat st;
if (stat(paths[i], &st) == 0 && (st.st_mode & S_IXUSR)) {
snprintf(buf, sizeof(buf), "%s", paths[i]);
return buf;
}
}
}
return "";
}
/* ── File utilities ───────────────────────────────────────────── */
int cbm_copy_file(const char *src, const char *dst) {
FILE *in = fopen(src, "rb");
if (!in) {
return -1;
}
FILE *out = fopen(dst, "wb");
if (!out) {
(void)fclose(in);
return -1;
}
char buf[8192];
int err = 0;
while (!feof(in) && !ferror(in)) {
size_t n = fread(buf, 1, sizeof(buf), in);
if (n == 0) {
break;
}
if (fwrite(buf, 1, n, out) != n) {
err = 1;
break;
}
}
if (err || ferror(in)) {
(void)fclose(in);
(void)fclose(out);
return -1;
}
(void)fclose(in);
int rc = fclose(out);
return rc == 0 ? 0 : -1;
}
/* Replace a binary file. Unlinks the old file first (handles read-only and
* running binaries on Unix where unlink succeeds on open files). On all
* platforms, the caller should tell the user to restart after update. */
int cbm_replace_binary(const char *path, const unsigned char *data, int len, int mode) {
if (!path || !data || len <= 0) {
return -1;
}
/* Remove existing file if it exists. On Unix, unlink works even if the
* binary is running (inode stays alive until the process exits). On Windows,
* unlink fails on running .exe — rename it aside as fallback. */
struct stat st_check;
if (stat(path, &st_check) == 0) {
/* File exists — remove or rename it */
if (cbm_unlink(path) != 0) {
#ifdef _WIN32
/* Windows: can't unlink running .exe — rename aside */
char old_path[1024];
snprintf(old_path, sizeof(old_path), "%s.old", path);
(void)cbm_unlink(old_path);
if (rename(path, old_path) != 0) {
return -1;
}
#else
return -1;
#endif
}
}
#ifndef _WIN32
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, (mode_t)mode);
if (fd < 0) {
return -1;
}
FILE *f = fdopen(fd, "wb");
if (!f) {
close(fd);
return -1;
}
#else
(void)mode;
FILE *f = fopen(path, "wb");
if (!f) {
return -1;
}
#endif
size_t written = fwrite(data, 1, (size_t)len, f);
(void)fclose(f);
return written == (size_t)len ? 0 : -1;
}
/* ── Skill file content (embedded) ────────────────────────────── */
static const char skill_exploring_content[] =
"---\n"
"name: codebase-memory-exploring\n"
"description: Codebase knowledge graph expert. ALWAYS invoke this skill when the user "
"explores code, searches for functions/classes/routes, asks about architecture, or needs "
"codebase orientation. Do not use Grep, Glob, or file search directly — use "
"codebase-memory-mcp search_graph and get_architecture first.\n"
"---\n"
"\n"
"# Codebase Exploration\n"
"\n"
"Use codebase-memory-mcp tools to explore the codebase:\n"
"\n"
"## Workflow\n"
"1. `get_graph_schema` — understand what node/edge types exist\n"
"2. `search_graph` — find functions, classes, routes by pattern\n"
"3. `get_code_snippet` — read specific function implementations\n"
"4. `get_architecture` — get high-level project summary\n"
"\n"
"## Tips\n"
"- Use `search_graph(name_pattern=\".*Pattern.*\")` for fuzzy matching\n"
"- Use `search_graph(label=\"Route\")` to find HTTP routes\n"
"- Use `search_graph(label=\"Function\", file_pattern=\"*.go\")` to scope by language\n";
static const char skill_tracing_content[] =
"---\n"
"name: codebase-memory-tracing\n"
"description: Call chain and dependency expert. ALWAYS invoke this skill when the user "
"asks who calls a function, what a function calls, needs impact analysis, or traces "
"dependencies. Do not grep for function names directly — use codebase-memory-mcp "
"trace_path first.\n"
"---\n"
"\n"
"# Call Tracing & Impact Analysis\n"
"\n"
"Use codebase-memory-mcp tools to trace call paths:\n"
"\n"
"## Workflow\n"
"1. `search_graph(name_pattern=\".*FuncName.*\")` — find exact function name\n"
"2. `trace_path(function_name=\"FuncName\", direction=\"both\")` — trace callers + "
"callees\n"
"3. `detect_changes` — find what changed and assess risk_labels\n"
"\n"
"## Direction Options\n"
"- `inbound` — who calls this function?\n"
"- `outbound` — what does this function call?\n"
"- `both` — full context (callers + callees)\n";
static const char skill_quality_content[] =
"---\n"
"name: codebase-memory-quality\n"
"description: Code quality analysis expert. ALWAYS invoke this skill when the user asks "
"about dead code, unused functions, complexity, refactor candidates, or cleanup "
"opportunities. Do not search files manually — use codebase-memory-mcp search_graph "
"with degree filters first.\n"
"---\n"
"\n"
"# Code Quality Analysis\n"
"\n"
"Use codebase-memory-mcp tools for quality analysis:\n"
"\n"
"## Dead Code Detection\n"
"- `search_graph(max_degree=0, exclude_entry_points=true)` — find unreferenced functions\n"
"- `search_graph(max_degree=0, label=\"Function\")` — unreferenced functions only\n"
"\n"
"## Complexity Analysis\n"
"- `search_graph(min_degree=10)` — high fan-out functions\n"
"- `search_graph(label=\"Function\", sort_by=\"degree\")` — most-connected functions\n";
static const char skill_reference_content[] =
"---\n"
"name: codebase-memory-reference\n"
"description: Codebase-memory-mcp reference guide. ALWAYS invoke this skill when the user "
"asks about MCP tools, graph queries, Cypher syntax, edge types, or how to use the "
"knowledge graph. Do not guess tool parameters — load this reference first.\n"
"---\n"
"\n"
"# Codebase Memory MCP Reference\n"
"\n"
"## 14 total MCP Tools\n"
"- `index_repository` — index a project\n"
"- `index_status` — check indexing progress\n"
"- `detect_changes` — find what changed since last index\n"
"- `search_graph` — find nodes by pattern\n"
"- `search_code` — text search in source\n"
"- `query_graph` — Cypher query language\n"
"- `trace_path` — call chain traversal\n"
"- `get_code_snippet` — read function source\n"
"- `get_graph_schema` — node/edge type catalog\n"
"- `get_architecture` — high-level summary\n"
"- `list_projects` — indexed projects\n"
"- `delete_project` — remove a project\n"
"- `manage_adr` — architecture decision records\n"
"- `ingest_traces` — import runtime traces\n"
"\n"
"## Edge Types\n"
"CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD,\n"
"HANDLES, IMPLEMENTS, CONTAINS_FILE, CONTAINS_FOLDER, CONTAINS_PACKAGE\n"
"\n"
"## Cypher Examples\n"
"```\n"
"MATCH (f:Function) WHERE f.name =~ '.*Handler.*' RETURN f.name, f.file_path\n"
"MATCH (a)-[r:CALLS]->(b) WHERE a.name = 'main' RETURN b.name\n"
"MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path\n"
"```\n";
static const char codex_instructions_content[] =
"# Codebase Knowledge Graph\n"
"\n"
"This project uses codebase-memory-mcp to maintain a knowledge graph of the codebase.\n"
"Use the MCP tools to explore and understand the code:\n"
"\n"
"- `search_graph` — find functions, classes, routes by pattern\n"
"- `trace_path` — trace who calls a function or what it calls\n"
"- `get_code_snippet` — read function source code\n"
"- `query_graph` — run Cypher queries for complex patterns\n"
"- `get_architecture` — high-level project summary\n"
"\n"
"Always prefer graph tools over grep for code discovery.\n";
static const cbm_skill_t skills[CBM_SKILL_COUNT] = {
{"codebase-memory-exploring", skill_exploring_content},
{"codebase-memory-tracing", skill_tracing_content},
{"codebase-memory-quality", skill_quality_content},
{"codebase-memory-reference", skill_reference_content},
};
const cbm_skill_t *cbm_get_skills(void) {
return skills;
}
const char *cbm_get_codex_instructions(void) {
return codex_instructions_content;
}
/* ── Recursive mkdir (via compat_fs) ──────────────────────────── */
static int mkdirp(const char *path, int mode) {
return (int)cbm_mkdir_p(path, mode) ? 0 : -1;
}
/* ── Recursive rmdir ──────────────────────────────────────────── */
// NOLINTNEXTLINE(misc-no-recursion) — intentional recursive directory removal
static int rmdir_recursive(const char *path) {
cbm_dir_t *d = cbm_opendir(path);
if (!d) {
return -1;
}
cbm_dirent_t *ent;
while ((ent = cbm_readdir(d)) != NULL) {
char child[1024];
snprintf(child, sizeof(child), "%s/%s", path, ent->name);
struct stat st;
if (stat(child, &st) == 0 && S_ISDIR(st.st_mode)) {
rmdir_recursive(child);
} else {
cbm_unlink(child);
}
}
cbm_closedir(d);
return cbm_rmdir(path);
}
/* ── Skill management ─────────────────────────────────────────── */
int cbm_install_skills(const char *skills_dir, bool force, bool dry_run) {
if (!skills_dir) {
return 0;
}
int count = 0;
for (int i = 0; i < CBM_SKILL_COUNT; i++) {
char skill_path[1024];
snprintf(skill_path, sizeof(skill_path), "%s/%s", skills_dir, skills[i].name);
char file_path[1024];
snprintf(file_path, sizeof(file_path), "%s/SKILL.md", skill_path);
/* Check if already exists */
if (!force) {
struct stat st;
if (stat(file_path, &st) == 0) {
continue;
}
}
if (dry_run) {
count++;
continue;
}
if (mkdirp(skill_path, DIR_PERMS) != 0) {
continue;
}
FILE *f = fopen(file_path, "w");
if (!f) {
continue;
}
(void)fwrite(skills[i].content, 1, strlen(skills[i].content), f);
(void)fclose(f);
count++;
}
return count;
}
int cbm_remove_skills(const char *skills_dir, bool dry_run) {
if (!skills_dir) {
return 0;
}
int count = 0;
for (int i = 0; i < CBM_SKILL_COUNT; i++) {
char skill_path[1024];
snprintf(skill_path, sizeof(skill_path), "%s/%s", skills_dir, skills[i].name);
struct stat st;
if (stat(skill_path, &st) != 0) {
continue;
}
if (dry_run) {
count++;
continue;
}
if (rmdir_recursive(skill_path) == 0) {
count++;
}
}
return count;
}
bool cbm_remove_old_monolithic_skill(const char *skills_dir, bool dry_run) {
if (!skills_dir) {
return false;
}
char old_path[1024];
snprintf(old_path, sizeof(old_path), "%s/codebase-memory-mcp", skills_dir);
struct stat st;
if (stat(old_path, &st) != 0 || !S_ISDIR(st.st_mode)) {
return false;
}
if (dry_run) {
return true;
}
return rmdir_recursive(old_path) == 0;
}
/* ── JSON config helpers (using yyjson) ───────────────────────── */
/* Read a JSON file into a yyjson document. Returns NULL on error. */
static yyjson_doc *read_json_file(const char *path) {
FILE *f = fopen(path, "r");
if (!f) {
return NULL;
}
(void)fseek(f, 0, SEEK_END);
long size = ftell(f);
(void)fseek(f, 0, SEEK_SET);
if (size <= 0 || size > 10L * 1024 * 1024) {
(void)fclose(f);
return NULL;
}
char *buf = malloc((size_t)size + 1);
if (!buf) {
(void)fclose(f);
return NULL;
}
size_t nread = fread(buf, 1, (size_t)size, f);
(void)fclose(f);
// NOLINTNEXTLINE(clang-analyzer-security.ArrayBound)
buf[nread] = '\0';
/* Allow JSONC (comments + trailing commas) — Zed settings.json uses this format */
yyjson_read_flag flags = YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS;
yyjson_doc *doc = yyjson_read(buf, nread, flags);
free(buf);
return doc;
}
/* Write a mutable yyjson document to a file with pretty printing. */
static int write_json_file(const char *path, yyjson_mut_doc *doc) {
/* Ensure parent directory exists */
char dir[1024];
snprintf(dir, sizeof(dir), "%s", path);
char *last_slash = strrchr(dir, '/');
if (last_slash) {
*last_slash = '\0';
mkdirp(dir, DIR_PERMS);
}
yyjson_write_flag flags = YYJSON_WRITE_PRETTY | YYJSON_WRITE_ESCAPE_UNICODE;
size_t len;
char *json = yyjson_mut_write(doc, flags, &len);
if (!json) {
return -1;
}
FILE *f = fopen(path, "w");
if (!f) {
free(json);
return -1;
}
size_t written = fwrite(json, 1, len, f);
/* Add trailing newline */
(void)fputc('\n', f);
(void)fclose(f);
free(json);
return written == len ? 0 : -1;
}
/* ── Editor MCP: Cursor/Windsurf/Gemini (mcpServers key) ──────── */
int cbm_install_editor_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
return -1;
}
/* Read existing or start fresh */
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
return -1;
}
yyjson_doc *doc = read_json_file(config_path);
yyjson_mut_val *root;
if (doc) {
root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc));
yyjson_doc_free(doc);
} else {
root = yyjson_mut_obj(mdoc);
}
if (!root) {
yyjson_mut_doc_free(mdoc);
return -1;
}
yyjson_mut_doc_set_root(mdoc, root);
/* Get or create mcpServers object */
yyjson_mut_val *servers = yyjson_mut_obj_get(root, "mcpServers");
if (!servers || !yyjson_mut_is_obj(servers)) {
servers = yyjson_mut_obj(mdoc);
yyjson_mut_obj_add_val(mdoc, root, "mcpServers", servers);
}
/* Remove existing entry if present */
yyjson_mut_obj_remove_key(servers, "codebase-memory-mcp");
/* Add our entry */
yyjson_mut_val *entry = yyjson_mut_obj(mdoc);
yyjson_mut_obj_add_str(mdoc, entry, "command", binary_path);
yyjson_mut_obj_add_val(mdoc, servers, "codebase-memory-mcp", entry);
int rc = write_json_file(config_path, mdoc);
yyjson_mut_doc_free(mdoc);
return rc;
}
int cbm_remove_editor_mcp(const char *config_path) {
if (!config_path) {
return -1;
}
yyjson_doc *doc = read_json_file(config_path);
if (!doc) {
return -1;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc));
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
return -1;
}
yyjson_mut_doc_set_root(mdoc, root);
yyjson_mut_val *servers = yyjson_mut_obj_get(root, "mcpServers");
if (!servers || !yyjson_mut_is_obj(servers)) {
yyjson_mut_doc_free(mdoc);
return 0;
}
yyjson_mut_obj_remove_key(servers, "codebase-memory-mcp");
int rc = write_json_file(config_path, mdoc);
yyjson_mut_doc_free(mdoc);
return rc;
}
/* ── VS Code MCP (servers key with type:stdio) ────────────────── */
int cbm_install_vscode_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
return -1;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
return -1;
}
yyjson_doc *doc = read_json_file(config_path);
yyjson_mut_val *root;
if (doc) {
root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc));
yyjson_doc_free(doc);
} else {
root = yyjson_mut_obj(mdoc);
}
if (!root) {
yyjson_mut_doc_free(mdoc);
return -1;
}
yyjson_mut_doc_set_root(mdoc, root);
yyjson_mut_val *servers = yyjson_mut_obj_get(root, "servers");
if (!servers || !yyjson_mut_is_obj(servers)) {
servers = yyjson_mut_obj(mdoc);
yyjson_mut_obj_add_val(mdoc, root, "servers", servers);
}
yyjson_mut_obj_remove_key(servers, "codebase-memory-mcp");
yyjson_mut_val *entry = yyjson_mut_obj(mdoc);
yyjson_mut_obj_add_str(mdoc, entry, "type", "stdio");
yyjson_mut_obj_add_str(mdoc, entry, "command", binary_path);
yyjson_mut_obj_add_val(mdoc, servers, "codebase-memory-mcp", entry);
int rc = write_json_file(config_path, mdoc);
yyjson_mut_doc_free(mdoc);
return rc;
}
int cbm_remove_vscode_mcp(const char *config_path) {
if (!config_path) {
return -1;
}
yyjson_doc *doc = read_json_file(config_path);
if (!doc) {
return -1;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc));
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
return -1;
}
yyjson_mut_doc_set_root(mdoc, root);
yyjson_mut_val *servers = yyjson_mut_obj_get(root, "servers");
if (!servers || !yyjson_mut_is_obj(servers)) {
yyjson_mut_doc_free(mdoc);
return 0;
}
yyjson_mut_obj_remove_key(servers, "codebase-memory-mcp");
int rc = write_json_file(config_path, mdoc);
yyjson_mut_doc_free(mdoc);
return rc;
}
/* ── Zed MCP (context_servers with command + args) ────────────── */
int cbm_install_zed_mcp(const char *binary_path, const char *config_path) {
if (!binary_path || !config_path) {
return -1;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
if (!mdoc) {
return -1;
}
yyjson_doc *doc = read_json_file(config_path);
yyjson_mut_val *root;
if (doc) {
root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc));
yyjson_doc_free(doc);
} else {
root = yyjson_mut_obj(mdoc);
}
if (!root) {
yyjson_mut_doc_free(mdoc);
return -1;
}
yyjson_mut_doc_set_root(mdoc, root);
yyjson_mut_val *servers = yyjson_mut_obj_get(root, "context_servers");
if (!servers || !yyjson_mut_is_obj(servers)) {
servers = yyjson_mut_obj(mdoc);
yyjson_mut_obj_add_val(mdoc, root, "context_servers", servers);
}
yyjson_mut_obj_remove_key(servers, "codebase-memory-mcp");
yyjson_mut_val *entry = yyjson_mut_obj(mdoc);
yyjson_mut_obj_add_str(mdoc, entry, "command", binary_path);
yyjson_mut_val *args = yyjson_mut_arr(mdoc);
yyjson_mut_arr_add_str(mdoc, args, "");
yyjson_mut_obj_add_val(mdoc, entry, "args", args);
yyjson_mut_obj_add_val(mdoc, servers, "codebase-memory-mcp", entry);
int rc = write_json_file(config_path, mdoc);
yyjson_mut_doc_free(mdoc);
return rc;
}
int cbm_remove_zed_mcp(const char *config_path) {
if (!config_path) {
return -1;
}
yyjson_doc *doc = read_json_file(config_path);
if (!doc) {
return -1;
}
yyjson_mut_doc *mdoc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_val_mut_copy(mdoc, yyjson_doc_get_root(doc));
yyjson_doc_free(doc);
if (!root) {
yyjson_mut_doc_free(mdoc);
return -1;
}
yyjson_mut_doc_set_root(mdoc, root);
yyjson_mut_val *servers = yyjson_mut_obj_get(root, "context_servers");
if (!servers || !yyjson_mut_is_obj(servers)) {
yyjson_mut_doc_free(mdoc);
return 0;
}
yyjson_mut_obj_remove_key(servers, "codebase-memory-mcp");
int rc = write_json_file(config_path, mdoc);
yyjson_mut_doc_free(mdoc);
return rc;
}
/* ── Agent detection ──────────────────────────────────────────── */
cbm_detected_agents_t cbm_detect_agents(const char *home_dir) {
cbm_detected_agents_t agents;
memset(&agents, 0, sizeof(agents));
if (!home_dir || !home_dir[0]) {
return agents;
}
char path[1024];
struct stat st;
/* Claude Code: ~/.claude/ */
snprintf(path, sizeof(path), "%s/.claude", home_dir);
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.claude_code = true;
}
/* Codex CLI: ~/.codex/ */
snprintf(path, sizeof(path), "%s/.codex", home_dir);
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.codex = true;
}
/* Gemini CLI: ~/.gemini/ */
snprintf(path, sizeof(path), "%s/.gemini", home_dir);
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.gemini = true;
}
/* Zed: platform-specific config dir */
#ifdef __APPLE__
snprintf(path, sizeof(path), "%s/Library/Application Support/Zed", home_dir);
#else
snprintf(path, sizeof(path), "%s/.config/zed", home_dir);
#endif
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.zed = true;
}
/* OpenCode: binary on PATH */
const char *oc = cbm_find_cli("opencode", home_dir);
if (oc[0]) {
agents.opencode = true;
}
/* Antigravity: ~/.gemini/antigravity/ */
snprintf(path, sizeof(path), "%s/.gemini/antigravity", home_dir);
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.antigravity = true;
agents.gemini = true; /* parent dir implies gemini */
}
/* Aider: binary on PATH */
const char *ai = cbm_find_cli("aider", home_dir);
if (ai[0]) {
agents.aider = true;
}
/* KiloCode: globalStorage dir */
snprintf(path, sizeof(path), "%s/.config/Code/User/globalStorage/kilocode.kilo-code", home_dir);
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.kilocode = true;
}
/* VS Code: User config dir */
#ifdef __APPLE__
snprintf(path, sizeof(path), "%s/Library/Application Support/Code/User", home_dir);
#else
snprintf(path, sizeof(path), "%s/.config/Code/User", home_dir);
#endif
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.vscode = true;
}
/* OpenClaw: ~/.openclaw/ dir */
snprintf(path, sizeof(path), "%s/.openclaw", home_dir);
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.openclaw = true;
}
/* Kiro: ~/.kiro/ */
snprintf(path, sizeof(path), "%s/.kiro", home_dir);
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
agents.kiro = true;
}
return agents;
}
/* ── Shared agent instructions content ────────────────────────── */
static const char agent_instructions_content[] =
"# Codebase Knowledge Graph (codebase-memory-mcp)\n"
"\n"
"This project uses codebase-memory-mcp to maintain a knowledge graph of the codebase.\n"
"ALWAYS prefer MCP graph tools over grep/glob/file-search for code discovery.\n"
"\n"
"## Priority Order\n"
"1. `search_graph` — find functions, classes, routes, variables by pattern\n"
"2. `trace_path` — trace who calls a function or what it calls\n"
"3. `get_code_snippet` — read specific function/class source code\n"
"4. `query_graph` — run Cypher queries for complex patterns\n"
"5. `get_architecture` — high-level project summary\n"
"\n"
"## When to fall back to grep/glob\n"
"- Searching for string literals, error messages, config values\n"
"- Searching non-code files (Dockerfiles, shell scripts, configs)\n"
"- When MCP tools return insufficient results\n"
"\n"
"## Examples\n"
"- Find a handler: `search_graph(name_pattern=\".*OrderHandler.*\")`\n"
"- Who calls it: `trace_path(function_name=\"OrderHandler\", direction=\"inbound\")`\n"
"- Read source: `get_code_snippet(qualified_name=\"pkg/orders.OrderHandler\")`\n";
const char *cbm_get_agent_instructions(void) {
return agent_instructions_content;
}
/* ── Instructions file upsert ─────────────────────────────────── */
#define CMM_MARKER_START "<!-- codebase-memory-mcp:start -->"
#define CMM_MARKER_END "<!-- codebase-memory-mcp:end -->"
/* Read entire file into malloc'd buffer. Returns NULL on error. */
static char *read_file_str(const char *path, size_t *out_len) {
FILE *f = fopen(path, "r");
if (!f) {
if (out_len) {