-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·2701 lines (2477 loc) · 109 KB
/
Copy pathsetup.sh
File metadata and controls
executable file
·2701 lines (2477 loc) · 109 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 bash
set -euo pipefail
# setup.sh — Automated installer for codebase-memory-mcp Claude Code hooks
#
# Supported platforms: macOS, Linux (including WSL on Windows). Native Windows
# and *BSD are not currently supported — see RESEARCH Cluster 1 in Phase 56.
#
# Synced upstream VBW version: 1.37.0
#
# Usage:
# ./setup.sh [--global] [--project] [--all] [--force] [--dry-run] [--skip-mcp-check] [--no-migrate] [--skip-statusline] [--force-local-cmm] [--verify]
#
# Flags:
# --global Install global hooks and rules to ~/.claude/ and merge into ~/.claude/settings.json
# --project Install project hooks to .claude/hooks/, rules to .claude/rules/,
# create .mcp.json, and merge into .claude/settings.json
# --all Install both global and project hooks
# --force Overwrite existing files without prompting (default: detect drift and prompt)
# --dry-run Show what would be done without making changes
# --skip-mcp-check Bypass all MCP availability checks (CMM binary, registration,
# tool allowlist, context-mode). Useful for CI/automation.
# --skip-statusline Skip the CMM statusline installation offer
# --force-local-cmm Register CMM in the project .mcp.json even when CMM is already
# registered in the global Claude Code settings.json (escape hatch
# for per-project version pins; default is to defer to the global
# registration and skip the local entry).
# --verify After installing hooks, verify file integrity against CHECKSUMS.sha256
#
# No flags: interactive prompt asking which to install.
#
# Prerequisites:
# - python3 (required — used for JSON merging)
# - codebase-memory-mcp (optional — warns if not found on PATH)
#
# Run from the repo root (the directory containing this script).
# chmod +x setup.sh before first run.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FORCE=false
DRY_RUN=false
INSTALL_GLOBAL=false
INSTALL_PROJECT=false
SKIP_MCP_CHECK=false
SKIP_STATUSLINE=false
# CMM install-scope globals (set by detect_cmm_install_scope; consumed by install_project)
# Four-value enum: none | global | project | both
CMM_INSTALL_SCOPE="none"
# Whether to write codebase-memory-mcp into project .mcp.json (default on; detect may flip false)
INSTALL_CMM_LOCAL=true
# Set by --force-local-cmm. When true, detect_cmm_install_scope short-circuits and forces local install.
FORCE_LOCAL_CMM=false
VERIFY=false
YES_FLAG=false
RECONFIGURE_STATUSLINE=false
# Hooks that have been retired or merged — names are deleted from any installed
# hooks/ directory and pruned from settings.json on every install run, regardless
# of whether the wrapper file is still on disk (orphan entries get cleaned too).
# Used by both install_project (project scope) and install_global (global scope).
# IMPORTANT: only deletes hooks on this explicit list — never deletes unknown
# hooks, as they may be user-created or generated by other install steps
# (e.g. statusline-cmm.sh).
DEPRECATED_HOOKS=(
"cmm-session-gate.sh"
"context-mode-session-gate.sh"
"ctx-search-nudge.sh"
"context-mode-event-logger.sh"
"context-mode-pre-compact.sh"
"ctx-annotate-nudge.sh"
)
# Detect Claude Code config directory at runtime.
# Priority: $CLAUDE_CONFIG_DIR (set by Claude Code) > ~/.config/claude-code (XDG) > ~/.claude (legacy)
detect_config_dir() {
if [ -n "${CLAUDE_CONFIG_DIR:-}" ]; then
echo "$CLAUDE_CONFIG_DIR"
elif [ -d "$HOME/.config/claude-code" ]; then
echo "$HOME/.config/claude-code"
else
echo "$HOME/.claude"
fi
}
# ---------------------------------------------------------------------------
# Utility functions
# ---------------------------------------------------------------------------
copy_file() {
local src="$1"
local dest="$2"
if [ "$DRY_RUN" = true ]; then
echo " [DRY RUN] Would copy $(basename "$src") -> $dest"
return
fi
if [ -e "$dest" ] && [ "$FORCE" != true ]; then
# Drift detection: compare content first
if cmp -s "$src" "$dest"; then
echo " [ok] $(basename "$dest") unchanged"
return
fi
# Files differ — show mtime direction context
echo " [warn] $(basename "$dest") differs from source"
if [ "$src" -nt "$dest" ]; then
echo " (source is newer — upstream update available)"
elif [ "$dest" -nt "$src" ]; then
echo " (installed is newer — local modifications present)"
else
echo " (same timestamp — content differs)"
fi
# Interactive per-file prompt gated on tty
if [ -t 0 ]; then
printf " Overwrite %s? [y/N]: " "$(basename "$dest")"
local _drift_choice
read -r _drift_choice || true
case "${_drift_choice:-}" in
y|Y) ;;
*) echo " [skip] Kept existing $(basename "$dest")"; return ;;
esac
else
echo " [skip] Non-interactive — kept existing $(basename "$dest")"
return
fi
fi
cp "$src" "$dest"
echo " [ok] Copied $(basename "$dest")"
}
set_executable() {
local file="$1"
if [ "$DRY_RUN" = true ]; then
echo " [DRY RUN] Would chmod +x $file"
return
fi
chmod +x "$file"
}
# purge_deprecated_hooks — Remove retired hook files and prune their settings.json
# entries. Used by both install_project (project scope) and install_global (global
# scope, $CLAUDE_CONFIG_DIR) so cleanup logic stays symmetric.
# Args:
# $1 hooks_dir — directory containing installed *.sh hook files
# $2 settings_file — settings.json to prune deprecated entries from
# $@ (positional 3+) — names of deprecated hook files (basenames)
# Honors $DRY_RUN. Settings prune always runs (regardless of disk presence) so
# orphan entries from prior bad cleanups still get removed.
purge_deprecated_hooks() {
local hooks_dir="$1"
local settings_file="$2"
shift 2
local hooks=("$@")
[ "${#hooks[@]}" -eq 0 ] && return 0
local name installed
for name in "${hooks[@]}"; do
installed="$hooks_dir/$name"
if [ -f "$installed" ]; then
if [ "$DRY_RUN" = true ]; then
echo " [DRY RUN] Would remove deprecated hook: $name"
else
rm -f "$installed"
echo " [removed] Deprecated hook: $name"
fi
fi
done
if [ "$DRY_RUN" = false ] && [ -f "$settings_file" ]; then
python3 -c '
import json, os, sys
target = sys.argv[1]
stale = set(sys.argv[2].split())
try:
with open(target) as f:
data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
sys.exit(0)
def _last_token_basename(cmd):
if not isinstance(cmd, str):
return ""
parts = cmd.split()
if not parts:
return ""
return os.path.basename(parts[-1])
changed = False
for hook_type in list(data.get("hooks", {})):
before = len(data["hooks"][hook_type])
data["hooks"][hook_type] = [
entry for entry in data["hooks"][hook_type]
if not any(
_last_token_basename(h.get("command", "")) in stale
for h in entry.get("hooks", [])
)
]
if len(data["hooks"][hook_type]) < before:
changed = True
if not data["hooks"][hook_type]:
del data["hooks"][hook_type]
if changed:
tmp = target + ".tmp"
with open(tmp, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
os.replace(tmp, target)
print(" [ok] Pruned deprecated hook entries from " + os.path.basename(target))
' "$settings_file" "${hooks[*]}"
fi
}
# scan_drift_summary — Read-only pre-scan of copy_file-managed files.
# Prints a single summary line: " Scanning N file(s): X unchanged, Y changed, Z new"
# Args: dest_dir src_file [src_file ...]
# Only runs when FORCE!=true and DRY_RUN!=true.
scan_drift_summary() {
local dest_dir="$1"
shift
if [ "$FORCE" = true ] || [ "$DRY_RUN" = true ]; then
return
fi
if [ "$#" -eq 0 ]; then
return
fi
local unchanged=0 changed=0 new_files=0 src
for src in "$@"; do
local dest="${dest_dir}/$(basename "$src")"
if [ ! -e "$dest" ]; then
new_files=$((new_files + 1))
elif cmp -s "$src" "$dest"; then
unchanged=$((unchanged + 1))
else
changed=$((changed + 1))
fi
done
local total=$((unchanged + changed + new_files))
echo " Scanning ${total} file(s): ${unchanged} unchanged, ${changed} changed, ${new_files} new"
}
# ---------------------------------------------------------------------------
# verify_repo_remote
# ---------------------------------------------------------------------------
# Checks that setup.sh is being run from a repo with an expected git remote.
# Non-blocking: warns and prompts for confirmation if remote looks unexpected.
# Skips silently if no .git directory is present (e.g. zip extract, CI).
verify_repo_remote() {
if [ ! -d "$SCRIPT_DIR/.git" ]; then
return 0
fi
local remote_url
remote_url=$(git -C "$SCRIPT_DIR" remote get-url origin 2>/dev/null || echo "")
if [ -z "$remote_url" ]; then
return 0
fi
local expected_pattern="github\.com[/:].*cmm.*setup|github\.com[/:].*codebase-memory"
if ! echo "$remote_url" | grep -qE "$expected_pattern"; then
echo "" >&2
echo " [WARN] Unexpected git remote: $remote_url" >&2
echo " [WARN] Expected a github.com/*/cmm-claude-code-setup remote." >&2
echo " [WARN] This may indicate you cloned from an unofficial source." >&2
printf " Continue anyway? [y/N]: " >&2
read -r choice
if [ "$choice" != "y" ] && [ "$choice" != "Y" ]; then
echo "Aborting. Clone from the official repo and re-run setup.sh." >&2
exit 1
fi
fi
}
# ---------------------------------------------------------------------------
# verify_installation
# ---------------------------------------------------------------------------
# Validates installed file integrity against CHECKSUMS.sha256 when --verify is set.
# Non-blocking if CHECKSUMS.sha256 is absent: prints a warning and returns.
# Exits non-zero if checksums are present but files fail verification.
verify_installation() {
if [ "$VERIFY" != true ]; then
return 0
fi
local checksum_file="$SCRIPT_DIR/CHECKSUMS.sha256"
if [ ! -f "$checksum_file" ]; then
echo " [warn] CHECKSUMS.sha256 not found — skipping verification" >&2
return 0
fi
echo ""
echo "Verifying file integrity..."
local failures=0
while IFS= read -r line; do
[ -z "$line" ] && continue
local expected file full actual
expected=$(echo "$line" | cut -c1-64)
file=$(echo "$line" | cut -c67-)
full="$SCRIPT_DIR/$file"
if [ ! -f "$full" ]; then
echo " [?] $file (not installed — skipped)" >&2
continue
fi
actual=$(shasum -a 256 "$full" 2>/dev/null | cut -c1-64 || sha256sum "$full" 2>/dev/null | cut -c1-64)
if [ "$actual" != "$expected" ]; then
echo " [✗] $file (checksum mismatch)" >&2
failures=$((failures + 1))
else
echo " [✓] $file"
fi
done < "$checksum_file"
if [ "$failures" -gt 0 ]; then
echo "" >&2
echo " [ERROR] $failures file(s) failed integrity check." >&2
echo " [ERROR] Your installation may be corrupted or tampered with." >&2
exit 1
fi
echo " All files verified."
}
# ---------------------------------------------------------------------------
# interactive_prompt
# ---------------------------------------------------------------------------
interactive_prompt() {
while true; do
echo ""
echo "Which hooks would you like to install?"
echo " g) Global hooks only ($(detect_config_dir)/hooks/)"
echo " p) Project hooks only (.claude/hooks/)"
echo " a) Both global and project"
echo " q) Quit"
echo ""
printf "Choice [a]: "
read -r choice
choice="${choice:-a}"
case "$choice" in
g) INSTALL_GLOBAL=true; break ;;
p) INSTALL_PROJECT=true; break ;;
a) INSTALL_GLOBAL=true; INSTALL_PROJECT=true; break ;;
q) exit 0 ;;
*) echo "Invalid choice: '$choice'. Please enter g, p, a, or q." ;;
esac
done
}
# ---------------------------------------------------------------------------
# detect_cmm_binary
# ---------------------------------------------------------------------------
# Status variable populated by detect_cmm_binary(); read by print_preflight_summary()
CMM_BINARY_STATUS="unknown"
CMM_BINARY_PATH=""
detect_cmm_binary() {
if [ "$SKIP_MCP_CHECK" = true ]; then
CMM_BINARY_STATUS="skip"
return 0
fi
# 1. PATH lookup (fastest, most reliable)
if command -v codebase-memory-mcp >/dev/null 2>&1; then
CMM_BINARY_PATH="$(command -v codebase-memory-mcp)"
CMM_BINARY_STATUS="ok"
return 0
fi
# 2-N. Fallback paths
local fallback
local fallbacks=(
"$HOME/.local/bin/codebase-memory-mcp"
"$HOME/go/bin/codebase-memory-mcp"
"/usr/local/bin/codebase-memory-mcp"
"/opt/homebrew/bin/codebase-memory-mcp"
)
if command -v npm >/dev/null 2>&1; then
local npm_prefix
npm_prefix="$(npm prefix -g 2>/dev/null)"
if [ -n "$npm_prefix" ]; then
fallbacks+=("$npm_prefix/bin/codebase-memory-mcp")
fi
fi
for fallback in "${fallbacks[@]}"
do
if [ -x "$fallback" ]; then
CMM_BINARY_PATH="$fallback"
CMM_BINARY_STATUS="ok"
echo " [info] Found codebase-memory-mcp at $fallback (not on PATH)"
echo " [info] Consider adding $(dirname "$fallback") to your PATH."
return 0
fi
done
# Not found anywhere
CMM_BINARY_STATUS="warn"
echo ""
echo " [warn] codebase-memory-mcp binary not found on PATH or common install paths."
echo " [info] Install it via one of the following:"
echo " npm: npm install -g codebase-memory-mcp"
echo " pip: pip install codebase-memory-mcp"
echo " Homebrew: brew install codebase-memory-mcp"
echo " Releases: https://github.com/DeusData/codebase-memory-mcp/releases/latest"
echo " One-liner (copy and run):"
echo " curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/scripts/setup.sh | bash"
echo ""
printf " Continue without CMM binary? [y/N]: "
read -r choice
choice="${choice:-n}"
if [ "$choice" != "y" ] && [ "$choice" != "Y" ]; then
echo "Aborting. Install codebase-memory-mcp and re-run setup.sh." >&2
exit 1
fi
return 0
}
# ---------------------------------------------------------------------------
# detect_cmm_registration
# ---------------------------------------------------------------------------
# Status variable populated by detect_cmm_registration(); read by print_preflight_summary()
CMM_REGISTRATION_STATUS="unknown"
detect_cmm_registration() {
if [ "$SKIP_MCP_CHECK" = true ]; then
CMM_REGISTRATION_STATUS="skip"
return 0
fi
# 1. Project .mcp.json
if [ -f ".mcp.json" ] && grep -q "codebase-memory-mcp" ".mcp.json"; then
CMM_REGISTRATION_STATUS="ok"
echo " [ok] CMM registered (project .mcp.json)"
return 0
fi
# 2. Global settings.json + user-scope .claude.json (where `claude mcp add` writes).
local config_dir
config_dir=$(detect_config_dir)
for _cmm_probe in "${config_dir}/settings.json" "${config_dir}/.claude.json" "${HOME}/.claude.json"; do
if grep -q "codebase-memory-mcp" "$_cmm_probe" 2>/dev/null; then
CMM_REGISTRATION_STATUS="ok"
echo " [ok] CMM registered ($_cmm_probe)"
return 0
fi
done
# Not registered yet
if [ "$INSTALL_PROJECT" = true ] || [ "$INSTALL_GLOBAL" = true ]; then
# setup.sh will register CMM in .mcp.json during install — no need to abort
CMM_REGISTRATION_STATUS="ok"
echo " [info] CMM not yet registered — setup will add it to .mcp.json"
return 0
fi
# Neither --project nor --global: warn and offer to abort
CMM_REGISTRATION_STATUS="warn"
echo ""
echo " [warn] CMM not registered with Claude Code."
echo " [info] Register it by running (copy and run):"
echo " codebase-memory-mcp install"
echo " [info] Or manually add to .mcp.json:"
echo ' { "mcpServers": { "codebase-memory-mcp": { "command": "codebase-memory-mcp", "args": [], "type": "stdio" } } }'
echo ""
printf " Continue without registering CMM? [y/N]: "
read -r choice
choice="${choice:-n}"
if [ "$choice" != "y" ] && [ "$choice" != "Y" ]; then
echo "Aborting. Register CMM and re-run setup.sh." >&2
exit 1
fi
return 0
}
# ---------------------------------------------------------------------------
# detect_cmm_install_scope (Phase 59)
# ---------------------------------------------------------------------------
# Probe global + local CMM registration and set INSTALL_CMM_LOCAL / CMM_INSTALL_SCOPE.
# NONE (neither) → INSTALL_CMM_LOCAL=true, CMM_INSTALL_SCOPE="none"
# GLOBAL only → INSTALL_CMM_LOCAL=false, CMM_INSTALL_SCOPE="global"
# PROJECT only → INSTALL_CMM_LOCAL=true, CMM_INSTALL_SCOPE="project"
# BOTH → INSTALL_CMM_LOCAL=false, CMM_INSTALL_SCOPE="both"
#
# "Present" means the file is valid JSON with a `mcpServers."codebase-memory-mcp"`
# object key (NOT a substring match — substring grep produces false positives from
# `enabledMcpjsonServers` allowlists, sibling-name collisions, comments — F-01).
detect_cmm_install_scope() {
# --force-local-cmm: skip all probes and force local install.
if [ "$FORCE_LOCAL_CMM" = true ]; then
INSTALL_CMM_LOCAL=true
CMM_INSTALL_SCOPE="none"
echo " [info] --force-local-cmm: skipping global scope detection; will register CMM in .mcp.json"
return 0
fi
local _global_present=false
local _local_present=false
# Probe global Claude Code config for an mcpServers.codebase-memory-mcp key.
# User-scope MCP entries added via `claude mcp add` live in ~/.claude.json (and
# ${config_dir}/.claude.json on macOS). Global plugin-style entries live in
# settings.json under mcpServers. Check all three locations.
local config_dir
config_dir=$(detect_config_dir)
local _probe_paths=(
"${config_dir}/settings.json"
"${config_dir}/.claude.json"
"${HOME}/.claude.json"
)
for _probe in "${_probe_paths[@]}"; do
[ -f "$_probe" ] || continue
if python3 -c "
import json,sys
try:
with open('${_probe}') as f:
d = json.load(f)
sys.exit(0 if isinstance(d, dict) and isinstance(d.get('mcpServers'), dict) and 'codebase-memory-mcp' in d['mcpServers'] else 1)
except Exception:
sys.exit(1)
" 2>/dev/null; then
_global_present=true
break
fi
done
# Probe project .mcp.json for the same key.
if [ -f ".mcp.json" ]; then
if python3 -c "
import json,sys
try:
with open('.mcp.json') as f:
d = json.load(f)
sys.exit(0 if isinstance(d, dict) and isinstance(d.get('mcpServers'), dict) and 'codebase-memory-mcp' in d['mcpServers'] else 1)
except Exception:
sys.exit(1)
" 2>/dev/null; then
_local_present=true
fi
fi
# --skip-mcp-check: bypass scope-driven skip behavior (treat as NONE for installation
# purposes, install locally). Still report the detected global presence so CI users
# know they're getting the redundant entry.
if [ "$SKIP_MCP_CHECK" = true ]; then
INSTALL_CMM_LOCAL=true
CMM_INSTALL_SCOPE="none"
if [ "$_global_present" = true ]; then
echo " [info] --skip-mcp-check: bypassing global scope detection; local entry will be added even though CMM is registered globally at ${config_dir}/settings.json"
fi
return 0
fi
# Classify into four states.
if [ "$_global_present" = true ] && [ "$_local_present" = true ]; then
CMM_INSTALL_SCOPE="both"
INSTALL_CMM_LOCAL=false
echo " [info] CMM registered in both global settings and local .mcp.json"
elif [ "$_global_present" = true ]; then
CMM_INSTALL_SCOPE="global"
INSTALL_CMM_LOCAL=false
echo " [info] CMM registered globally — skipping local .mcp.json entry"
elif [ "$_local_present" = true ]; then
CMM_INSTALL_SCOPE="project"
INSTALL_CMM_LOCAL=true
else
CMM_INSTALL_SCOPE="none"
INSTALL_CMM_LOCAL=true
fi
return 0
}
# ---------------------------------------------------------------------------
# detect_cmm_tools_allowed
# ---------------------------------------------------------------------------
# Status variable populated by detect_cmm_tools_allowed(); read by print_preflight_summary()
CMM_TOOLS_STATUS="unknown"
CMM_TOOLS_COUNT=0
detect_cmm_tools_allowed() {
if [ "$SKIP_MCP_CHECK" = true ]; then
CMM_TOOLS_STATUS="skip"
return 0
fi
local settings_file=".claude/settings.json"
if [ ! -f "$settings_file" ]; then
CMM_TOOLS_STATUS="missing"
return 0
fi
# Count mcp__codebase-memory-mcp__ entries in permissions.allow
CMM_TOOLS_COUNT=$(python3 - "$settings_file" <<'PYEOF'
import json, sys
try:
with open(sys.argv[1]) as f:
data = json.load(f)
allow = data.get("permissions", {}).get("allow", [])
count = sum(1 for t in allow if "mcp__codebase-memory-mcp__" in str(t))
print(count)
except Exception:
print(0)
PYEOF
)
if [ "$CMM_TOOLS_COUNT" -ge 13 ]; then
CMM_TOOLS_STATUS="ok"
return 0
fi
CMM_TOOLS_STATUS="warn"
return 0
}
# ---------------------------------------------------------------------------
# detect_context_mode
# ---------------------------------------------------------------------------
# Status variable populated by detect_context_mode(); read by print_preflight_summary()
CONTEXT_MODE_STATUS="skip"
# Whether to register context-mode in .mcp.json (set by detect_context_mode)
# Default: register context-mode (flip to false only when --skip-context-mode is passed).
INSTALL_CONTEXT_MODE=true
# Set by --skip-context-mode. When true, detect_context_mode forces INSTALL_CONTEXT_MODE=false
# so context-mode registration is skipped entirely (fresh installs only — existing entries
# in .mcp.json are preserved by the idempotency guard in install_project).
SKIP_CONTEXT_MODE=false
# Set by --no-migrate (Phase 57 G1). When true, the MCP_ONLY migration prompt in
# detect_context_mode is forced to the `n` branch silently — useful for CI /
# non-interactive automation. Also implicitly forced when stdin is not a TTY.
NO_MIGRATE=false
# Four-state install-form classification set by detect_context_mode() per G1:
# NONE — neither plugin nor MCP-server form detected (fresh-install path).
# MCP_ONLY — legacy MCP-server form only; triggers interactive migration prompt.
# PLUGIN — plugin form present; canonical going forward, no prompt fires.
# BOTH — plugin AND MCP-server forms both present; plugin wins, REDUNDANT_MCP=1.
# Downstream callers (merge_context_mode_hooks, print_preflight_summary) read this.
CONTEXT_MODE_INSTALL_FORM="NONE"
# Set to 1 when BOTH forms are detected, so the caller can warn-and-offer to remove
# the now-redundant MCP-server .mcp.json entry. Reset to empty on each detect call.
REDUNDANT_MCP=""
# Set to true by detect_context_mode when CONTEXT_MODE_INSTALL_FORM is PLUGIN or BOTH.
# Gates ONLY the .mcp.json context-mode entry write — upstream hook registration
# and the tool allowlist still treat context-mode as installed and proceed normally
# (because hooks and allowlist apply equally to plugin-form installs).
SUPPRESS_MCP_CONTEXT_ENTRY=false
# detect_context_mode — Phase 57 G1 four-state install-form matrix:
# NONE — neither install form present. Fresh-install path: register
# MCP-server form in .mcp.json (existing default behavior preserved).
# MCP_ONLY — only legacy MCP-server form (.mcp.json `context-mode` entry).
# Interactive prompt offers migration to /plugin install context-mode.
# --no-migrate or non-TTY stdin forces the `n` branch silently.
# PLUGIN — plugin-form install detected via ${CLAUDE_PLUGIN_ROOT} or via
# ~/.claude/plugins/cache/<marketplace>/context-mode/.claude-plugin/plugin.json.
# Plugin form is canonical going forward; no prompt fires.
# BOTH — plugin AND MCP-server forms both present. Plugin wins; sets
# REDUNDANT_MCP=1 so the caller can warn-and-offer-cleanup.
detect_context_mode() {
# --skip-context-mode wins unconditionally — opt out of context-mode registration.
if [ "$SKIP_CONTEXT_MODE" = true ]; then
CONTEXT_MODE_STATUS="skip"
INSTALL_CONTEXT_MODE=false
# Surface existing registration so the user knows the webfetch-nudge hook
# will continue to block WebFetch based on project-level context-mode state.
if [ "$INSTALL_PROJECT" = true ] && [ -f ".mcp.json" ] && \
grep -q "context-mode" ".mcp.json" 2>/dev/null; then
echo " [info] --skip-context-mode set; existing context-mode entry in .mcp.json preserved"
echo " [info] webfetch-nudge will continue to block WebFetch while context-mode remains registered"
fi
# Invalidate the webfetch-nudge availability cache so stale /tmp state does
# not keep the hook blocking after context-mode is removed from .mcp.json.
if [ "$DRY_RUN" != true ]; then
rm -f /tmp/ctx-webfetch-avail-* 2>/dev/null || true
fi
return 0
fi
# Only runs for project installs (context-mode is registered in project .mcp.json)
if [ "$INSTALL_PROJECT" != true ]; then
CONTEXT_MODE_STATUS="skip"
INSTALL_CONTEXT_MODE=false
return 0
fi
# Default-on: register context-mode. INSTALL_CONTEXT_MODE is already true from
# initialization (and will only be flipped false by --skip-context-mode above).
# Idempotency: the install_project MCP merge block guards with
# `if "context-mode" not in data["mcpServers"]` — re-running setup preserves
# existing context-mode entries and user customizations.
INSTALL_CONTEXT_MODE=true
# --- Phase 57 G1: probe both install forms independently ---
# Reset transitional state on each call (idempotency: re-runs reclassify cleanly).
REDUNDANT_MCP=""
SUPPRESS_MCP_CONTEXT_ENTRY=false
local _plugin_form_present=false
local _mcp_server_form_present=false
# Plugin-form probe: $CLAUDE_PLUGIN_ROOT resolves when run from inside an active
# Claude Code plugin session. Outside that context, scan the global plugin cache
# for any marketplace dir that contains a `context-mode` plugin (validated via
# the presence of .claude-plugin/plugin.json with `"name": "context-mode"`).
if [ -n "${CLAUDE_PLUGIN_ROOT:-}" ] && \
[ -f "${CLAUDE_PLUGIN_ROOT}/.claude-plugin/plugin.json" ] && \
grep -q '"name"[[:space:]]*:[[:space:]]*"context-mode"' \
"${CLAUDE_PLUGIN_ROOT}/.claude-plugin/plugin.json" 2>/dev/null; then
_plugin_form_present=true
else
# Fall back to scanning ${CLAUDE_CONFIG_DIR:-~/.claude}/plugins/cache/ for any context-mode
# plugin install. Real layout is <cache>/<marketplace>/<plugin>/[<version>/]/.claude-plugin/...
# so a fixed-depth glob misses versioned installs — use find with broader nesting.
local _plugin_cache_root="${CLAUDE_CONFIG_DIR:-${HOME}/.claude}/plugins/cache"
if [ -d "$_plugin_cache_root" ]; then
while IFS= read -r _plugin_manifest; do
[ -z "$_plugin_manifest" ] && continue
if grep -q '"name"[[:space:]]*:[[:space:]]*"context-mode"' "$_plugin_manifest" 2>/dev/null; then
_plugin_form_present=true
break
fi
done < <(find "$_plugin_cache_root" -maxdepth 7 -name 'plugin.json' \
-path '*/.claude-plugin/*' 2>/dev/null)
fi
# Also accept enabledPlugins entry (form: "context-mode@<marketplace>: true") in any
# global Claude Code config location — this is the canonical install flag.
if [ "$_plugin_form_present" = false ]; then
for _probe in "${CLAUDE_CONFIG_DIR:-${HOME}/.config/claude-code}/settings.json" \
"${HOME}/.claude/settings.json"; do
[ -f "$_probe" ] || continue
if python3 -c "
import json,sys
try:
with open('${_probe}') as f:
cfg = json.load(f)
for k,v in (cfg.get('enabledPlugins') or {}).items():
if v and k.split('@',1)[0] == 'context-mode':
sys.exit(0)
except Exception: pass
sys.exit(1)
" 2>/dev/null; then
_plugin_form_present=true
break
fi
done
fi
fi
# MCP-server-form probe: existing .mcp.json "context-mode" entry presence.
if [ -f ".mcp.json" ] && grep -q "context-mode" ".mcp.json" 2>/dev/null; then
_mcp_server_form_present=true
fi
# Classify into one of the four states.
if [ "$_plugin_form_present" = true ] && [ "$_mcp_server_form_present" = true ]; then
CONTEXT_MODE_INSTALL_FORM="BOTH"
REDUNDANT_MCP=1
elif [ "$_plugin_form_present" = true ]; then
CONTEXT_MODE_INSTALL_FORM="PLUGIN"
elif [ "$_mcp_server_form_present" = true ]; then
CONTEXT_MODE_INSTALL_FORM="MCP_ONLY"
else
CONTEXT_MODE_INSTALL_FORM="NONE"
fi
# If a prior session wrote the migration sentinel and plugin form is now
# present, clear the sentinel — the migration follow-up is complete (G1).
local _migration_sentinel=".vbw-planning/.context-mode-migration-pending"
if [ "$_plugin_form_present" = true ] && [ -f "$_migration_sentinel" ]; then
if [ "$DRY_RUN" != true ]; then
rm -f "$_migration_sentinel" 2>/dev/null || true
echo " [ok] migration follow-up complete — plugin form detected; sentinel cleared"
else
echo " [DRY RUN] Would clear migration sentinel $_migration_sentinel"
fi
fi
# Dispatch on form. The MCP_ONLY branch will trigger the interactive migration
# prompt implemented in maybe_offer_context_mode_migration() (Phase 57 task 2).
# Other branches preserve historical behavior for users not on the legacy form.
case "$CONTEXT_MODE_INSTALL_FORM" in
PLUGIN)
CONTEXT_MODE_STATUS="ok"
# Plugin form is canonical — do not add a redundant MCP-server entry.
# Only suppress the .mcp.json write; upstream hooks and the tool allowlist
# still need to register because they apply to plugin-form installs too.
SUPPRESS_MCP_CONTEXT_ENTRY=true
echo " [ok] context-mode detected (plugin form: /plugin install context-mode@context-mode)"
echo " [info] plugin form is canonical — skipping .mcp.json entry"
;;
BOTH)
CONTEXT_MODE_STATUS="ok"
# User already has both forms; suppress only the .mcp.json re-add. Upstream
# hooks + allowlist still register (same reasoning as PLUGIN above).
SUPPRESS_MCP_CONTEXT_ENTRY=true
echo " [ok] context-mode detected (plugin form preferred; MCP-server entry in .mcp.json is redundant)"
;;
MCP_ONLY)
CONTEXT_MODE_STATUS="ok"
echo " [ok] context-mode detected (legacy MCP-server form via .mcp.json)"
;;
NONE)
CONTEXT_MODE_STATUS="ok"
echo " [info] context-mode will be registered in .mcp.json (use --skip-context-mode to opt out)"
echo " [info] Docs: https://github.com/mksglu/context-mode"
echo " [info] Tip: the canonical install form is now /plugin install context-mode@context-mode"
;;
esac
# Offer interactive migration when only the legacy form is present.
if [ "$CONTEXT_MODE_INSTALL_FORM" = "MCP_ONLY" ]; then
maybe_offer_context_mode_migration
fi
if [ "$CONTEXT_MODE_INSTALL_FORM" = "BOTH" ]; then
maybe_offer_redundant_mcp_cleanup
fi
return 0
}
# ---------------------------------------------------------------------------
# maybe_offer_context_mode_migration (Phase 57 G1)
# ---------------------------------------------------------------------------
# Called from detect_context_mode() when CONTEXT_MODE_INSTALL_FORM == MCP_ONLY.
# Offers an interactive Y/n/keep prompt to migrate the legacy MCP-server form to
# the canonical /plugin install context-mode@context-mode form. Silent `n`
# fallback under --no-migrate or non-TTY stdin.
#
# Sentinel files (mirror existing project-state sentinel patterns):
# .vbw-planning/.context-mode-migration-pending — created on Y, cleared once
# plugin form is detected.
# .vbw-planning/.context-mode-form-preference — written on `keep` (single
# line: `mcp-server`).
maybe_offer_context_mode_migration() {
# If user already expressed `keep` preference, do not nag again.
local _pref_file=".vbw-planning/.context-mode-form-preference"
if [ -f "$_pref_file" ] && grep -qx "mcp-server" "$_pref_file" 2>/dev/null; then
return 0
fi
# If sentinel already exists, user previously answered Y but hasn't yet run
# /plugin install. Print a one-line reminder rather than re-prompting.
local _sentinel=".vbw-planning/.context-mode-migration-pending"
if [ -f "$_sentinel" ]; then
echo " [info] migration pending — run /plugin install context-mode@context-mode in your next Claude Code session"
return 0
fi
# Non-interactive paths: --no-migrate flag OR stdin is not a TTY OR --yes is set.
# YES_FLAG defaults to accepting prompts; explicit silent skip avoids surprising
# CI runs by NOT migrating when the user did not explicitly opt in via TTY.
if [ "$NO_MIGRATE" = true ] || [ ! -t 0 ] || [ "${YES_FLAG:-false}" = true ]; then
echo " [info] context-mode is on the legacy MCP-server form; recommended path: /plugin install context-mode@context-mode (skipped non-interactively)"
return 0
fi
# --dry-run mode: surface the offer but do not mutate state.
if [ "$DRY_RUN" = true ]; then
echo " [DRY RUN] Would prompt to migrate context-mode to /plugin install form"
return 0
fi
echo ""
echo " Upstream now recommends \`/plugin install context-mode@context-mode\` (enables"
echo " slash commands, automatic hook routing, full feature set)."
printf " Migrate now? [Y/n/keep] "
local _answer
# F-05: EOF (Ctrl-D) at the prompt would abort setup.sh under `set -e`.
# Treat EOF as 'n' (don't migrate) — safer than the default-Y fallback.
if ! read -r _answer; then
echo ""
echo " [info] No answer received (EOF); treating as 'n'"
_answer=n
fi
_answer="${_answer:-Y}"
case "$_answer" in
Y|y|yes|YES)
_do_context_mode_migration_yes "$_sentinel"
;;
n|N|no|NO)
echo " [info] Keeping MCP-server form. Recommended path stays: /plugin install context-mode@context-mode"
;;
keep|KEEP|k|K)
mkdir -p "$(dirname "$_pref_file")" 2>/dev/null
printf 'mcp-server\n' > "$_pref_file"
echo " [ok] Wrote $_pref_file — migration reminder suppressed on future runs"
;;
*)
echo " [warn] Unrecognized answer '$_answer'; treating as 'n'"
;;
esac
}
# _do_context_mode_migration_yes <sentinel_path>
# Helper for the Y branch: remove .mcp.json `context-mode` entry, write
# sentinel, and print explicit follow-up instructions.
_do_context_mode_migration_yes() {
local _sentinel="$1"
# Remove the context-mode entry from .mcp.json while preserving other entries.
# F-02: atomic .tmp + os.replace (matches install_project's MCP merge pattern).
# F-03: wrap python in if/else so a write failure (EACCES/ENOSPC/read-only FS)
# degrades to a [warn] instead of aborting setup.sh under `set -euo pipefail`.
if [ -f ".mcp.json" ]; then
if python3 - <<'PYEOF'
import json, os, sys
try:
with open(".mcp.json") as f:
data = json.load(f)
except Exception:
sys.exit(0) # fail-open: leave file untouched
if not isinstance(data, dict):
sys.exit(0)
servers = data.get("mcpServers")
if isinstance(servers, dict) and "context-mode" in servers:
del servers["context-mode"]
tmp = ".mcp.json.tmp"
with open(tmp, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
os.replace(tmp, ".mcp.json")
print(" [ok] Removed context-mode from .mcp.json (other entries preserved)")
PYEOF
then
:
else
echo " [warn] Failed to update .mcp.json (Y migration aborted; existing state preserved)"
return 0
fi
# F-01: prevent install_project's later MCP-merge block from silently
# re-adding the entry we just removed (same-run migration was a no-op).
# If context-mode is no longer registered, flip the install flag false.
# INSTALL_CONTEXT_MODE is a setup.sh global (no `local`) so the assignment
# propagates back to install_project's `if install_ctx:` gate.
if ! python3 -c "import json,sys;d=json.load(open('.mcp.json'));sys.exit(0 if 'context-mode' in d.get('mcpServers',{}) else 1)" 2>/dev/null; then
INSTALL_CONTEXT_MODE=false
fi
fi
# Write the sentinel marker with an ISO timestamp + follow-up instructions.
mkdir -p "$(dirname "$_sentinel")" 2>/dev/null
local _ts
_ts="$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u)"
cat > "$_sentinel" <<EOF
$_ts
context-mode migration pending: run \`/plugin install context-mode@context-mode\`
in your next Claude Code session. setup.sh will clear this sentinel automatically
once the plugin form is detected on a follow-up run.
EOF
echo " [ok] Wrote $_sentinel"
echo ""
echo " Next step: in your next Claude Code session, run:"
echo " /plugin install context-mode@context-mode"
echo " Then re-run \`bash setup.sh --project\` and this sentinel will be cleared."
echo ""
}
# ---------------------------------------------------------------------------
# maybe_offer_redundant_mcp_cleanup (Phase 57 G1, BOTH-form branch)
# ---------------------------------------------------------------------------
# Called when CONTEXT_MODE_INSTALL_FORM == BOTH. Plugin wins. The MCP-server
# entry in .mcp.json is now redundant; offer a one-line y/N prompt to remove it
# unless we are non-interactive or --no-migrate is set, in which case warn only.
maybe_offer_redundant_mcp_cleanup() {
if [ "$NO_MIGRATE" = true ] || [ ! -t 0 ] || [ "${YES_FLAG:-false}" = true ] || [ "$DRY_RUN" = true ]; then
echo " [warn] MCP-server entry in .mcp.json is redundant alongside plugin form (skipping cleanup non-interactively)"
return 0
fi
printf " MCP-server entry in .mcp.json is redundant; remove it? [y/N] "
local _answer
# F-05: EOF at the prompt should be treated as 'N' (don't remove), matching
# the prompt's default. Without this, `read` failure aborts setup.sh under `set -e`.
read -r _answer || _answer=n
case "$_answer" in
y|Y|yes|YES)
# F-02/F-03: atomic .tmp + os.replace, wrapped in if/else so write
# failures degrade to [warn] instead of aborting setup.sh.
if python3 - <<'PYEOF'
import json, os
try:
with open(".mcp.json") as f:
data = json.load(f)
except Exception:
raise SystemExit(0)
if isinstance(data, dict):
servers = data.get("mcpServers")
if isinstance(servers, dict) and "context-mode" in servers:
del servers["context-mode"]
tmp = ".mcp.json.tmp"
with open(tmp, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
os.replace(tmp, ".mcp.json")
print(" [ok] Removed redundant context-mode entry from .mcp.json")
PYEOF
then
:
else
echo " [warn] Failed to update .mcp.json (redundant-entry cleanup skipped)"
fi
;;
*)
echo " [info] Keeping MCP-server entry — duplicate registration is harmless but non-canonical"