Repository navigation
Expand file tree
/
Copy pathdotcontext
More file actions
executable file
·1915 lines (1715 loc) · 66.9 KB
/
Copy pathdotcontext
File metadata and controls
executable file
·1915 lines (1715 loc) · 66.9 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
#!/bin/bash
set -e
VERSION="0.19.0"
REPO="goca-se/dotcontext"
BRANCH="main"
BASE_URL="https://raw.githubusercontent.com/${REPO}/${BRANCH}"
# ── Colors ────────────────────────────────────────────────────────────────────
if [[ -t 1 ]]; then
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
GRAY='\033[0;90m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
else
RED='' GREEN='' YELLOW='' BLUE='' PURPLE='' CYAN='' GRAY='' BOLD='' DIM='' NC=''
fi
# Helper print functions
print_green() { printf "${GREEN}%s${NC}\n" "$1"; }
print_red() { printf "${RED}%s${NC}\n" "$1"; }
print_yellow() { printf "${YELLOW}%s${NC}\n" "$1"; }
print_blue() { printf "${BLUE}%s${NC}\n" "$1"; }
print_gray() { printf "${GRAY}%s${NC}\n" "$1"; }
print_cyan() { printf "${CYAN}%s${NC}\n" "$1"; }
# ── Icons ─────────────────────────────────────────────────────────────────────
ICON_SUCCESS="✓"
ICON_ERROR="✗"
ICON_WARNING="⚠"
ICON_ARROW="➤"
ICON_INFO="ℹ"
ICON_SECTION="◆"
ICON_DOWNLOAD="↓"
ICON_SKIP="○"
ICON_UPDATE="↻"
ICON_CHECK="◎"
ICON_ADMIN="⚙"
ICON_NAV="↳"
ICON_ADD="+"
ICON_MODIFY="~"
ICON_UNCHANGED="="
ICON_MANAGED="•"
# ── UI Utilities ──────────────────────────────────────────────────────────────
get_term_width() {
local width
width=$(tput cols 2>/dev/null || echo "")
if [ -z "$width" ] || [ "$width" -lt 40 ] 2>/dev/null; then
width=80
fi
echo "$width"
}
# Print a section header with divider line
# Usage: print_block_header "Title"
print_block_header() {
local title="$1"
local width
width=$(get_term_width)
local title_len=${#title}
local pad=$((width - title_len - 6))
[ "$pad" -lt 4 ] && pad=4
local line=""
local i
for ((i = 0; i < pad; i++)); do
line="${line}─"
done
printf "\n ${BOLD}── %s ${NC}${GRAY}%s${NC}\n" "$title" "$line"
}
# Print a block footer divider
print_block_footer() {
local width
width=$(get_term_width)
local pad=$((width - 4))
[ "$pad" -lt 10 ] && pad=10
local line=""
local i
for ((i = 0; i < pad; i++)); do
line="${line}─"
done
printf " ${GRAY}%s${NC}\n" "$line"
}
# Print aligned label-value pair
# Usage: print_aligned "label" "value" [indent]
print_aligned() {
local label="$1"
local value="$2"
local indent="${3:-4}"
local pad_fmt="%-${indent}s"
printf " ${pad_fmt}${GRAY}%s${NC}\n" "$label" "$value"
}
# ── Spinner ───────────────────────────────────────────────────────────────────
SPINNER_PID=""
start_spinner() {
local msg="$1"
local frames=(⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏)
local i=0
while true; do
printf "\r ${BLUE}${frames[$i]}${NC} ${msg}"
i=$(( (i + 1) % 10 ))
sleep 0.1
done &
SPINNER_PID=$!
}
stop_spinner() {
local msg="$1"
if [ -n "$SPINNER_PID" ]; then
kill "$SPINNER_PID" 2>/dev/null
wait "$SPINNER_PID" 2>/dev/null || true
SPINNER_PID=""
fi
printf "\r\033[K"
if [ -n "$msg" ]; then
echo "$msg"
fi
}
# ── Utilities ─────────────────────────────────────────────────────────────────
prompt() {
local message="$1"
local default="$2"
local result
if [ -n "$default" ]; then
printf "%s [%s]: " "$message" "$default" >&2
read -r result
echo "${result:-$default}"
else
printf "%s: " "$message" >&2
read -r result
echo "$result"
fi
}
confirm() {
local message="$1"
local answer
printf "%s [y/N]: " "$message"
read -r answer
[[ "$answer" =~ ^[Yy] ]]
}
confirm_yes() {
local message="$1"
local answer
printf "%s [Y/n]: " "$message"
read -r answer
[[ ! "$answer" =~ ^[Nn] ]]
}
download() {
local url="$1"
local target="$2"
if command -v curl &> /dev/null; then
curl -fsSL "$url" -o "$target"
elif command -v wget &> /dev/null; then
wget -q "$url" -O "$target"
else
print_red "Error: curl or wget required"
exit 1
fi
}
# Declarative cleanup: remove files in a managed directory that aren't in the expected list.
# Usage: cleanup_managed_dir <dir> <expected_file1> [expected_file2] ...
cleanup_managed_dir() {
local dir="$1"; shift
local expected=("$@")
[ -d "$dir" ] || return 0
[ ${#expected[@]} -eq 0 ] && return 0
for file in "$dir"/*; do
[ -L "$file" ] && continue
[ -f "$file" ] || continue
local name=$(basename "$file")
local keep=false
for expected_name in "${expected[@]}"; do
if [ "$name" = "$expected_name" ]; then
keep=true
break
fi
done
if [ "$keep" = false ]; then
rm -f "$file"
fi
done
}
# Compare two semver strings (X.Y.Z). Returns 0 if $1 > $2, else 1.
version_gt() {
[ "$1" = "$2" ] && return 1
local IFS=.
local a=($1) b=($2)
local i ai bi
for i in 0 1 2; do
ai=${a[i]:-0}; bi=${b[i]:-0}
# strip any pre-release suffix so "1.2.3-dev" compares as 3
ai=${ai%%[^0-9]*}; bi=${bi%%[^0-9]*}
if [ "${ai:-0}" -gt "${bi:-0}" ] 2>/dev/null; then return 0; fi
if [ "${ai:-0}" -lt "${bi:-0}" ] 2>/dev/null; then return 1; fi
done
return 1
}
# Fetch the latest released version from GitHub, cached for 1 day.
# Echoes the bare version (no leading "v"); returns 1 on failure/offline.
fetch_latest_version() {
local cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/dotcontext"
local cache_file="$cache_dir/latest_version"
# Serve from cache if fresh (modified within the last day)
if [ -f "$cache_file" ] && [ -n "$(find "$cache_file" -mtime -1 2>/dev/null)" ]; then
cat "$cache_file"
return 0
fi
local resp tag ver
if command -v curl &> /dev/null; then
resp=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null)
elif command -v wget &> /dev/null; then
resp=$(wget -qO- "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null)
else
return 1
fi
tag=$(echo "$resp" | grep '"tag_name"' | head -1 | sed -E 's/.*"([^"]+)".*/\1/')
ver=$(echo "$tag" | sed 's/^v//')
[ -z "$ver" ] && return 1
mkdir -p "$cache_dir" 2>/dev/null
echo "$ver" > "$cache_file" 2>/dev/null
echo "$ver"
}
# ── Hook Setup ────────────────────────────────────────────────────────────────
# Setup Claude Code hooks (project-local)
# - Notification + Stop: native OS notifications
# - PostToolUseFailure: tool failure guard (asks user after 4+ consecutive failures)
setup_notifications() {
local scripts_dir=".claude/scripts"
local settings_file=".claude/settings.json"
# Create scripts directory
mkdir -p "$scripts_dir"
# Download and install scripts into project
download "${BASE_URL}/scripts/notify.sh" "$scripts_dir/notify.sh"
chmod +x "$scripts_dir/notify.sh"
download "${BASE_URL}/scripts/tool-failure-guard.sh" "$scripts_dir/tool-failure-guard.sh"
chmod +x "$scripts_dir/tool-failure-guard.sh"
# Warn if global hooks exist from a previous dotcontext version
if [ -f "$HOME/.claude/settings.json" ] && grep -q "notify.sh" "$HOME/.claude/settings.json" 2>/dev/null; then
print_yellow "Global notification hooks detected in ~/.claude/settings.json"
print_yellow "dotcontext now configures hooks per-project. You can remove the global hooks manually."
fi
# Create or update project-local settings.json with hooks
local notification_hook='{
"matcher": "",
"hooks": [{"type": "command", "command": ".claude/scripts/notify.sh '\''Claude Code'\'' '\''Needs your attention'\'' question"}]
}'
local stop_hook='{
"matcher": "",
"hooks": [{"type": "command", "command": ".claude/scripts/notify.sh '\''Claude Code'\'' '\''Task completed'\'' success"}]
}'
local failure_guard_hook='{
"matcher": "",
"hooks": [{"type": "command", "command": ".claude/scripts/tool-failure-guard.sh"}]
}'
if [ ! -f "$settings_file" ]; then
cat > "$settings_file" << 'SETTINGS_EOF'
{
"hooks": {
"Notification": [
{
"matcher": "",
"hooks": [{"type": "command", "command": ".claude/scripts/notify.sh 'Claude Code' 'Needs your attention' question"}]
}
],
"Stop": [
{
"matcher": "",
"hooks": [{"type": "command", "command": ".claude/scripts/notify.sh 'Claude Code' 'Task completed' success"}]
}
],
"PostToolUseFailure": [
{
"matcher": "",
"hooks": [{"type": "command", "command": ".claude/scripts/tool-failure-guard.sh"}]
}
]
}
}
SETTINGS_EOF
print_gray "Hooks configured in .claude/settings.json"
else
# Check if hooks already configured
if ! grep -q "notify.sh" "$settings_file" 2>/dev/null; then
if command -v jq &>/dev/null; then
local temp_file=$(mktemp)
jq --argjson notif "$notification_hook" --argjson stop "$stop_hook" '
.hooks.Notification = ((.hooks.Notification // []) + [$notif]) |
.hooks.Stop = ((.hooks.Stop // []) + [$stop])
' "$settings_file" > "$temp_file" 2>/dev/null
if [ $? -eq 0 ] && [ -s "$temp_file" ]; then
mv "$temp_file" "$settings_file"
print_gray "Notification hooks added to .claude/settings.json"
else
rm -f "$temp_file"
fi
else
print_yellow "Install jq to auto-configure hooks, or add manually"
fi
fi
# Add failure guard if not already present
if ! grep -q "tool-failure-guard" "$settings_file" 2>/dev/null; then
if command -v jq &>/dev/null; then
local temp_file=$(mktemp)
jq --argjson guard "$failure_guard_hook" '
.hooks.PostToolUseFailure = ((.hooks.PostToolUseFailure // []) + [$guard])
' "$settings_file" > "$temp_file" 2>/dev/null
if [ $? -eq 0 ] && [ -s "$temp_file" ]; then
mv "$temp_file" "$settings_file"
print_gray "Tool failure guard hook added to .claude/settings.json"
else
rm -f "$temp_file"
fi
fi
fi
fi
}
# ── MCP Server Setup ──────────────────────────────────────────────────────────
# Setup MCP servers in .mcp.json
setup_mcp() {
local add_context7="$1"
local add_atlassian="$2"
local mcp_file=".mcp.json"
if [ -f "$mcp_file" ]; then
return 0
fi
local servers=""
local comma=""
if [ "$add_context7" = true ]; then
servers="${servers}${comma}
\"context7\": {
\"command\": \"npx\",
\"args\": [\"-y\", \"@upstash/context7-mcp\"]
}"
comma=","
fi
if [ "$add_atlassian" = true ]; then
servers="${servers}${comma}
\"atlassian\": {
\"type\": \"http\",
\"url\": \"https://mcp.atlassian.com/v1/sse\"
}"
fi
if [ -n "$servers" ]; then
cat > "$mcp_file" << EOF
{
"mcpServers": {${servers}
}
}
EOF
print_gray "MCP servers configured in .mcp.json"
fi
}
# ── Agent Adapter Registry ──────────────────────────────────────────────────
# Each supported coding agent is one entry. Adding an agent means adding it to
# AGENT_IDS and the case arms below — nothing else in the toolkit hard-codes an
# agent. (ADR-016)
#
# Emit modes for the project-instructions file:
# import — a thin stub that @-imports AGENTS.md (Claude Code, Gemini CLI)
# native — reads AGENTS.md directly; needs no file of its own (Codex,
# opencode, Copilot, Cursor incl. the cursor-agent CLI)
#
# AGENTS.md itself is the canonical single source and is always emitted.
AGENT_IDS="claude codex opencode gemini copilot cursor"
agent_name() {
case "$1" in
claude) echo "Claude Code" ;;
codex) echo "OpenAI Codex" ;;
opencode) echo "opencode" ;;
gemini) echo "Gemini CLI" ;;
copilot) echo "GitHub Copilot" ;;
cursor) echo "Cursor (cursor-agent)" ;;
*) echo "$1" ;;
esac
}
# Detection: is the agent's CLI installed?
agent_detect() {
case "$1" in
claude) command -v claude >/dev/null 2>&1 ;;
codex) command -v codex >/dev/null 2>&1 ;;
opencode) command -v opencode >/dev/null 2>&1 ;;
gemini) command -v gemini >/dev/null 2>&1 ;;
copilot) command -v copilot >/dev/null 2>&1 || \
{ command -v gh >/dev/null 2>&1 && gh extension list 2>/dev/null | grep -qi copilot; } ;;
cursor) command -v cursor-agent >/dev/null 2>&1 ;;
*) return 1 ;;
esac
}
# The instruction file this agent reads.
agent_instructions_file() {
case "$1" in
claude) echo "CLAUDE.md" ;;
gemini) echo "GEMINI.md" ;;
*) echo "AGENTS.md" ;;
esac
}
# How this agent gets its instructions: import | native
agent_emit_mode() {
case "$1" in
claude|gemini) echo "import" ;;
*) echo "native" ;;
esac
}
# Echo the ids of detected (installed) agents, space-separated.
detect_agents() {
local id out=""
for id in $AGENT_IDS; do
if agent_detect "$id"; then out="$out $id"; fi
done
echo "${out# }"
}
# Echo "url|target" instruction-file seed mappings for the selected agent ids.
# AGENTS.md (canonical) is always first; import-mode agents add their stub.
# Native agents need no extra file (they read AGENTS.md directly).
# The "|" separator can't appear in a URL or a filename, so consumers parse it
# unambiguously: url="${mapping%|*}", target="${mapping##*|}".
agent_instruction_seeds() {
local selected="$1" id target seen=" "
echo "${BASE_URL}/templates/AGENTS.md|AGENTS.md"
for id in $selected; do
[ "$(agent_emit_mode "$id")" = "import" ] || continue
target="$(agent_instructions_file "$id")"
case "$seen" in *" $target "*) continue ;; esac
seen="$seen$target "
echo "${BASE_URL}/templates/${target}|${target}"
done
}
# True if the id list contains a given agent.
agents_include() {
case " $1 " in *" $2 "*) return 0 ;; *) return 1 ;; esac
}
# Resolve which harnesses to instantiate. Sets the global SELECTED_AGENTS.
# Priority: explicit --agents list > non-interactive (detected, fallback claude)
# > interactive (confirm each detected agent; offer Claude if none).
# Must NOT run inside $(...) — it prompts on stdout. (ADR-016)
SELECTED_AGENTS=""
resolve_selected_agents() {
local agents_flag="$1" skip_prompts="$2"
SELECTED_AGENTS=""
if [ -n "$agents_flag" ]; then
local IFS=',' id
for id in $agents_flag; do
id="$(echo "$id" | tr -d '[:space:]')"
[ -z "$id" ] && continue
if agents_include "$AGENT_IDS" "$id"; then
SELECTED_AGENTS="$SELECTED_AGENTS $id"
else
print_yellow " unknown agent '$id' (skipped) — known: $AGENT_IDS"
fi
done
SELECTED_AGENTS="${SELECTED_AGENTS# }"
return 0
fi
local detected; detected="$(detect_agents)"
if [ "$skip_prompts" = "true" ]; then
SELECTED_AGENTS="$detected"
[ -z "$SELECTED_AGENTS" ] && SELECTED_AGENTS="claude"
return 0
fi
local id
if [ -n "$detected" ]; then
print_blue "Detected agents — choose which to set up:"
for id in $detected; do
if confirm_yes " Set up for $(agent_name "$id")?"; then
SELECTED_AGENTS="$SELECTED_AGENTS $id"
fi
done
fi
SELECTED_AGENTS="${SELECTED_AGENTS# }"
if [ -z "$SELECTED_AGENTS" ]; then
if confirm_yes " No agent selected — set up for Claude Code?"; then
SELECTED_AGENTS="claude"
fi
fi
}
# Create $2 as a symlink to $1 (relative), or copy if symlinks aren't available.
# No-op if $2 already exists. Used to mirror the skills dir across ecosystems.
link_or_copy_dir() {
local src="$1" dst="$2"
[ -d "$src" ] || return 0
if [ -e "$dst" ] || [ -L "$dst" ]; then return 0; fi
mkdir -p "$(dirname "$dst")"
ln -s "../$src" "$dst" 2>/dev/null || cp -r "$src" "$dst"
}
# ── Per-agent hooks ───────────────────────────────────────────────────────────
# Wire a "task finished / needs attention" notification per selected agent.
# Claude keeps its richer hooks (notify + tool-failure-guard) via
# setup_notifications. Non-Claude agents get a notification hook in their native
# config format, pointing at a shared, arg-driven notify.sh (it ignores stdin,
# so the same script works regardless of each agent's hook JSON contract).
# Best-effort + create-only: never clobbers an existing agent config.
NOTIFY_SHARED=".context/scripts/notify.sh"
ensure_shared_notify() {
[ -f "$NOTIFY_SHARED" ] && return 0
mkdir -p ".context/scripts"
download "${BASE_URL}/scripts/notify.sh" "$NOTIFY_SHARED" && chmod +x "$NOTIFY_SHARED"
}
setup_agent_hooks() {
local selected="$1" id done_any=false
for id in $selected; do
case "$id" in
claude)
setup_notifications 2>/dev/null || true
done_any=true
;;
codex)
ensure_shared_notify
if [ ! -f ".codex/hooks.json" ]; then
mkdir -p ".codex"
cat > ".codex/hooks.json" <<JSON
{
"hooks": {
"Stop": [
{ "hooks": [ { "type": "command", "command": "$NOTIFY_SHARED 'Codex' 'Task completed' success" } ] }
]
}
}
JSON
print_gray " hooks: .codex/hooks.json"
done_any=true
fi
;;
gemini)
ensure_shared_notify
if [ ! -f ".gemini/settings.json" ]; then
mkdir -p ".gemini"
cat > ".gemini/settings.json" <<JSON
{
"hooks": {
"Notification": [
{ "hooks": [ { "type": "command", "command": "$NOTIFY_SHARED 'Gemini' 'Needs your attention' question" } ] }
],
"AfterAgent": [
{ "hooks": [ { "type": "command", "command": "$NOTIFY_SHARED 'Gemini' 'Task completed' success" } ] }
]
}
}
JSON
print_gray " hooks: .gemini/settings.json"
done_any=true
fi
;;
copilot)
ensure_shared_notify
if [ ! -f ".github/hooks/dotcontext-notify.json" ]; then
mkdir -p ".github/hooks"
cat > ".github/hooks/dotcontext-notify.json" <<JSON
{
"hooks": {
"Stop": [
{ "hooks": [ { "type": "command", "command": "$NOTIFY_SHARED 'Copilot' 'Task completed' success" } ] }
]
}
}
JSON
print_gray " hooks: .github/hooks/dotcontext-notify.json"
done_any=true
fi
;;
cursor)
ensure_shared_notify
if [ ! -f ".cursor/hooks.json" ]; then
mkdir -p ".cursor"
cat > ".cursor/hooks.json" <<JSON
{
"version": 1,
"hooks": {
"stop": [
{ "command": "$NOTIFY_SHARED 'Cursor' 'Task completed' success" }
]
}
}
JSON
print_gray " hooks: .cursor/hooks.json"
done_any=true
fi
;;
opencode)
ensure_shared_notify
if [ ! -f ".opencode/plugins/dotcontext-notify.js" ]; then
mkdir -p ".opencode/plugins"
cat > ".opencode/plugins/dotcontext-notify.js" <<'JS'
// dotcontext: fire an OS notification when the session goes idle.
export const DotcontextNotify = async ({ $ }) => ({
event: async ({ event }) => {
if (event?.type === "session.idle") {
await $`.context/scripts/notify.sh 'opencode' 'Task completed' success`.catch(() => {})
}
},
})
JS
print_gray " hooks: .opencode/plugins/dotcontext-notify.js"
done_any=true
fi
;;
esac
done
[ "$done_any" = true ] || true
}
# ── Per-agent commands (hybrid, ADR-018) ──────────────────────────────────────
# The canonical workflow prompts ship in templates/.claude/commands/. Claude gets
# them in .claude/commands/ (handled in init). opencode and Copilot get native
# command/prompt files here; Gemini/Cursor/Codex rely on the "## Workflows"
# section emitted into AGENTS.md. Create-only — never clobbers existing files.
DOTCONTEXT_COMMANDS="setup-context spec-dc plan-dc execute-dc code-review commit create-pr pr-comment deep-context fix-bug add-decision add-skill add-command"
emit_agent_commands() {
local selected="$1" id name
for id in $selected; do
case "$id" in
opencode)
mkdir -p ".opencode/command"
for name in $DOTCONTEXT_COMMANDS; do
[ -f ".opencode/command/${name}.md" ] || \
download "${BASE_URL}/templates/.claude/commands/${name}.md" ".opencode/command/${name}.md"
done
print_gray " commands: .opencode/command/ (opencode)"
;;
copilot)
mkdir -p ".github/prompts"
for name in $DOTCONTEXT_COMMANDS; do
[ -f ".github/prompts/${name}.prompt.md" ] || \
download "${BASE_URL}/templates/.claude/commands/${name}.md" ".github/prompts/${name}.prompt.md"
done
print_gray " commands: .github/prompts/ (copilot)"
;;
esac
done
}
# ── Command: init ─────────────────────────────────────────────────────────────
cmd_init() {
local project_name=""
local skip_prompts=false
local skip_setup=false
local agents_flag=""
while [[ $# -gt 0 ]]; do
case "$1" in
-n|--name) project_name="$2"; shift 2 ;;
-y|--yes) skip_prompts=true; shift ;;
--no-setup) skip_setup=true; shift ;;
--agents) agents_flag="$2"; shift 2 ;;
*) shift ;;
esac
done
print_blue ""
printf "${BLUE}📁 dotcontext - AI Context Toolkit${NC}\n\n"
local cwd="$(pwd)"
local is_reinit=false
if [ -d ".context" ]; then
is_reinit=true
print_yellow "Existing .context/ detected — will add missing files without overwriting your content."
fi
if [ -z "$project_name" ]; then
if [ "$skip_prompts" = false ]; then
project_name=$(prompt "Project name" "$(basename "$cwd")")
else
project_name="$(basename "$cwd")"
fi
fi
# Resolve which harnesses to instantiate (sets SELECTED_AGENTS). Only the
# chosen harnesses get files — no .claude/ for a Codex-only user, etc. (ADR-016)
resolve_selected_agents "$agents_flag" "$skip_prompts"
local selected="$SELECTED_AGENTS"
if [ -z "$selected" ]; then
print_red "No harness selected — nothing to set up. Re-run and pick at least one agent."
return 1
fi
local wants_claude=false; agents_include "$selected" claude && wants_claude=true
local wants_agents_skills=false
local _id
for _id in $selected; do [ "$_id" != "claude" ] && wants_agents_skills=true; done
print_gray "Setting up for: $selected"
# Harness-agnostic context skeleton (always)
# specs/ + plans/ back the spec → plan → execute workflow (ADR-020).
mkdir -p ".context/decisions" ".context/specs" ".context/plans" \
".context/discoveries" ".context/bugs"
start_spinner "Downloading templates..."
# Helper: download only if file doesn't exist (seed/user-customizable files)
local skipped_files=""
download_if_missing() {
local url="$1"
local target="$2"
if [ -f "$target" ]; then
[ "$is_reinit" = true ] && skipped_files="${skipped_files}${target}\n"
return 0
fi
download "$url" "$target"
}
# ── Shared context (every harness) ──
download_if_missing "${BASE_URL}/templates/.context/CONTEXT.md" ".context/CONTEXT.md"
download_if_missing "${BASE_URL}/templates/.context/decisions/README.md" ".context/decisions/README.md"
download_if_missing "${BASE_URL}/templates/.context/specs/README.md" ".context/specs/README.md"
download_if_missing "${BASE_URL}/templates/.context/plans/README.md" ".context/plans/README.md"
# ── Project instructions: canonical AGENTS.md + import stubs for selected agents ──
for mapping in $(agent_instruction_seeds "$selected"); do
# mappings are "url|target" ("|" can't appear in a URL or filename)
download_if_missing "${mapping%|*}" "${mapping##*|}"
done
# ── Skills (shared SKILL.md content; physical home depends on selection) ──
local skills_dir
if [ "$wants_claude" = true ]; then skills_dir=".claude/skills"; else skills_dir=".agents/skills"; fi
mkdir -p "$skills_dir/bug-reproduction" "$skills_dir/batch-operations" \
"$skills_dir/git-platform" "$skills_dir/update-api-documentation"
download_if_missing "${BASE_URL}/templates/.claude/skills/bug-reproduction/SKILL.md" "$skills_dir/bug-reproduction/SKILL.md"
download_if_missing "${BASE_URL}/templates/.claude/skills/batch-operations/SKILL.md" "$skills_dir/batch-operations/SKILL.md"
download_if_missing "${BASE_URL}/templates/.claude/skills/git-platform/SKILL.md" "$skills_dir/git-platform/SKILL.md"
download_if_missing "${BASE_URL}/templates/.claude/skills/update-api-documentation/SKILL.md" "$skills_dir/update-api-documentation/SKILL.md"
# If both Claude and an AGENTS.md-reading agent are selected, mirror so both see the skills
if [ "$wants_claude" = true ] && [ "$wants_agents_skills" = true ]; then
link_or_copy_dir ".claude/skills" ".agents/skills"
fi
# ── Claude-only toolkit (commands, agents, statusline, ignore) ──
if [ "$wants_claude" = true ]; then
mkdir -p ".claude/commands" ".claude/scripts" \
".claude/agents/code-review" ".claude/agents/deep-context" ".claude/agents/fix-bug" \
".claude/agents/spec-dc" ".claude/agents/plan-dc" ".claude/agents/execute-dc"
download_if_missing "${BASE_URL}/templates/.claudeignore" ".claudeignore"
local c
for c in setup-context code-review spec-dc plan-dc execute-dc add-decision add-skill \
add-command create-pr pr-comment deep-context fix-bug commit; do
download "${BASE_URL}/templates/.claude/commands/${c}.md" ".claude/commands/${c}.md"
done
download "${BASE_URL}/templates/.claude/scripts/statusline.sh" ".claude/scripts/statusline.sh"
chmod +x ".claude/scripts/statusline.sh"
local a
for a in code-review/compliance-checker code-review/bug-detector code-review/security-analyst \
deep-context/step1-overview deep-context/step2-subsystems deep-context/step3-drill \
deep-context/step4-dataflow fix-bug/investigator fix-bug/fix-conservative \
fix-bug/fix-minimal fix-bug/fix-refactor fix-bug/reviewer \
spec-dc/reviewer-pro spec-dc/reviewer-fast \
plan-dc/reviewer-pro plan-dc/reviewer-fast \
execute-dc/reviewer-pro execute-dc/reviewer-fast; do
download "${BASE_URL}/templates/.claude/agents/${a}.md" ".claude/agents/${a}.md"
done
cleanup_managed_dir ".claude/agents/code-review" \
compliance-checker.md bug-detector.md security-analyst.md
cleanup_managed_dir ".claude/agents/deep-context" \
step1-overview.md step2-subsystems.md step3-drill.md step4-dataflow.md
cleanup_managed_dir ".claude/agents/fix-bug" \
investigator.md fix-conservative.md fix-minimal.md fix-refactor.md reviewer.md
cleanup_managed_dir ".claude/agents/spec-dc" \
reviewer-pro.md reviewer-fast.md
cleanup_managed_dir ".claude/agents/plan-dc" \
reviewer-pro.md reviewer-fast.md
cleanup_managed_dir ".claude/agents/execute-dc" \
reviewer-pro.md reviewer-fast.md
cleanup_managed_dir ".claude/scripts" \
statusline.sh notify.sh tool-failure-guard.sh
fi
stop_spinner
if [ -n "$skipped_files" ]; then
printf "$skipped_files" | while read -r f; do
[ -n "$f" ] && print_gray " skipped (exists): $f"
done
fi
touch ".context/discoveries/.keep" ".context/bugs/.keep"
# ── Commands per selected harness (opencode/Copilot native; others via AGENTS.md Workflows) ──
emit_agent_commands "$selected" 2>/dev/null || true
# ── Hooks per selected harness (notifications; Claude also gets the failure guard) ──
setup_agent_hooks "$selected" 2>/dev/null || true
# ── MCP servers (cross-agent; Context7/Atlassian work across harnesses) ──
if [ ! -f ".mcp.json" ]; then
local add_context7=false
local add_atlassian=false
if [ "$skip_prompts" = false ]; then
echo ""
print_blue "MCP Servers"
print_gray "Configure Model Context Protocol servers for your agents"
echo ""
confirm_yes " Add Context7? (up-to-date library docs for LLMs)" && add_context7=true
confirm_yes " Add Atlassian? (Jira + Confluence via OAuth)" && add_atlassian=true
else
add_context7=true
add_atlassian=true
fi
setup_mcp "$add_context7" "$add_atlassian"
else
print_gray " skipped (exists): .mcp.json"
fi
# Offer to install shell tab-completion (interactive runs only)
if [ "$skip_prompts" = false ] && [ -t 0 ]; then
offer_completion_install
fi
# Substitute project name in any instruction file that still has the placeholder
local inst_file
for inst_file in AGENTS.md CLAUDE.md GEMINI.md; do
if grep -q "{{projectName}}" "$inst_file" 2>/dev/null; then
if [[ "$OSTYPE" == "darwin"* ]]; then
sed -i '' "s/{{projectName}}/$project_name/g" "$inst_file"
else
sed -i "s/{{projectName}}/$project_name/g" "$inst_file"
fi
fi
done
echo ""
if [ "$is_reinit" = true ]; then
printf " ${GREEN}${ICON_SUCCESS}${NC} Context structure updated\n"
else
printf " ${GREEN}${ICON_SUCCESS}${NC} Context structure created\n"
fi
local _names="" _i
for _i in $selected; do _names="$_names$(agent_name "$_i"), "; done
printf " ${GRAY}Harnesses: %s${NC}\n" "${_names%, }"
echo ""
# /setup-context is a Claude command — only when Claude is part of the setup
if [ "$wants_claude" = true ]; then
if [ "$skip_setup" = true ]; then
printf " ${CYAN}Next:${NC} run ${CYAN}/setup-context${NC} in Claude Code\n"
elif command -v claude &> /dev/null; then
printf " ${CYAN}Running /setup-context...${NC}\n\n"
claude "/setup-context"
else
printf " ${YELLOW}Claude CLI not found.${NC} Run ${CYAN}/setup-context${NC} manually in Claude Code.\n"
fi
else
printf " ${CYAN}Next:${NC} edit ${CYAN}AGENTS.md${NC} and ${CYAN}.context/CONTEXT.md${NC} to describe your project\n"
fi
echo ""
}
# ── Command: update ───────────────────────────────────────────────────────────
cmd_update() {
local templates_only=false
local cli_only=false
local auto_yes=false
local dry_run=false
while [[ $# -gt 0 ]]; do
case "$1" in
--templates) templates_only=true; shift ;;
--cli) cli_only=true; shift ;;
--yes|-y) auto_yes=true; shift ;;
--dry-run) dry_run=true; shift ;;
*) shift ;;
esac
done
if [ "$templates_only" = true ]; then
cmd_update_templates "$auto_yes" "$dry_run"
elif [ "$cli_only" = true ]; then
cmd_update_cli
else
# Default: update CLI, then templates if in a project
cmd_update_cli
if [ -d ".context" ]; then
echo ""
# Re-exec with new binary so template list is up to date
local new_bin
new_bin=$(command -v dotcontext 2>/dev/null || echo "")
if [ -n "$new_bin" ] && [ -x "$new_bin" ]; then
local new_ver
new_ver=$("$new_bin" --version 2>/dev/null | sed 's/dotcontext //')
if [ "$new_ver" != "$VERSION" ]; then
local args="update --templates"
[ "$auto_yes" = "true" ] && args="$args --yes"
[ "$dry_run" = "true" ] && args="$args --dry-run"
exec "$new_bin" $args
fi
fi
cmd_update_templates "$auto_yes" "$dry_run"
fi
fi
}
cmd_update_cli() {
start_spinner "Checking for CLI updates..."
# Get latest version tag from GitHub (try releases first, then tags)
local latest_version
local latest_tag
local api_response
if command -v curl &> /dev/null; then
api_response=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null)
latest_tag=$(echo "$api_response" | grep '"tag_name"' | head -1 | sed -E 's/.*"([^"]+)".*/\1/')
latest_version=$(echo "$latest_tag" | sed 's/^v//')
if [ -z "$latest_version" ]; then
api_response=$(curl -fsSL "https://api.github.com/repos/${REPO}/tags" 2>/dev/null)
latest_tag=$(echo "$api_response" | grep '"name"' | head -1 | sed -E 's/.*"([^"]+)".*/\1/')
latest_version=$(echo "$latest_tag" | sed 's/^v//')
fi
else
api_response=$(wget -qO- "https://api.github.com/repos/${REPO}/releases/latest" 2>/dev/null)
latest_tag=$(echo "$api_response" | grep '"tag_name"' | head -1 | sed -E 's/.*"([^"]+)".*/\1/')
latest_version=$(echo "$latest_tag" | sed 's/^v//')
if [ -z "$latest_version" ]; then
api_response=$(wget -qO- "https://api.github.com/repos/${REPO}/tags" 2>/dev/null)
latest_tag=$(echo "$api_response" | grep '"name"' | head -1 | sed -E 's/.*"([^"]+)".*/\1/')
latest_version=$(echo "$latest_tag" | sed 's/^v//')
fi
fi
if [ -z "$latest_version" ]; then
stop_spinner
print_red "Could not check latest version."
return 1
fi
if [ "$VERSION" = "$latest_version" ]; then
stop_spinner "$(printf "${GREEN}${ICON_SUCCESS} CLI already at latest version ($VERSION)${NC}")"
return 0
fi
stop_spinner "$(printf "${GRAY}Current: $VERSION → Latest: $latest_version${NC}")"
# Find installation path
local install_path=$(command -v dotcontext)
if [ -z "$install_path" ]; then
install_path="/usr/local/bin/dotcontext"
fi
# Download from release tag (not main branch) to avoid unreleased code
local release_url="https://raw.githubusercontent.com/${REPO}/${latest_tag}/dotcontext"
start_spinner "Downloading from release ${latest_tag}..."