-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart-devstream.sh
More file actions
executable file
·3443 lines (2901 loc) · 116 KB
/
Copy pathstart-devstream.sh
File metadata and controls
executable file
·3443 lines (2901 loc) · 116 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
# DevStream Production Launcher v2.0 - Direct DB Architecture
# Starts DevStream with Direct DB Architecture and Agent Auto-Delegation System
# Integrated: Context7, Agent Routing, Memory System, Direct Database
set -euo pipefail
# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
print_status() {
echo -e "${GREEN}[STATUS]${NC} $1"
}
print_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
print_feature() {
echo -e "${CYAN}[FEATURE]${NC} $1"
}
# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Capture invocation directory for path normalization (Context7 best practice)
INVOCATION_DIR="$(pwd -P 2>/dev/null || pwd)"
# Resolve a candidate directory to an absolute canonical path
resolve_absolute_dir() {
local candidate="$1"
local base_dir="${2:-$INVOCATION_DIR}"
local expanded="$candidate"
if [ -z "$expanded" ]; then
return 1
fi
# Expand leading tilde if present
if [[ "$expanded" == "~"* ]]; then
expanded="${expanded/#\~/$HOME}"
fi
(
if [[ "$expanded" == /* ]]; then
cd "$expanded" 2>/dev/null || exit 1
else
cd "$base_dir" 2>/dev/null || exit 1
cd "$expanded" 2>/dev/null || exit 1
fi
pwd -P
)
}
# Normalize project root to absolute path (fails if directory is invalid)
normalize_project_root() {
local candidate="$1"
local resolved=""
if [ -z "$candidate" ]; then
return 1
fi
if ! resolved=$(resolve_absolute_dir "$candidate"); then
return 1
fi
if [ -z "$resolved" ] || [ ! -d "$resolved" ]; then
return 1
fi
echo "$resolved"
return 0
}
# Function to find DevStream project root using upward search
find_devstream_project_root() {
local start_dir="${1:-$(pwd)}"
local current_dir="$start_dir"
local max_depth=20
local depth=0
# Upward search for .env.devstream marker
while [ "$current_dir" != "/" ] && [ $depth -lt $max_depth ]; do
if [ -f "$current_dir/.env.devstream" ]; then
# Validate complete DevStream installation
if [ -d "$current_dir/.claude/hooks/devstream" ] && \
[ -d "$current_dir/.devstream" ]; then
echo "$current_dir"
return 0
fi
fi
current_dir="$(dirname "$current_dir")"
depth=$((depth + 1))
done
return 1 # Not found
}
# Multi-project detection logic
DEVSTREAM_INSTALLATION_ROOT="$SCRIPT_DIR"
DEVSTREAM_SCRIPT_DIR="$DEVSTREAM_INSTALLATION_ROOT"
LOCAL_PROJECT_ROOT=""
PROJECT_ROOT=""
# Priority 1: Explicit project root (manual override)
if [ -n "${DEVSTREAM_PROJECT_ROOT:-}" ]; then
local_explicit_root="$DEVSTREAM_PROJECT_ROOT"
if explicit_root=$(normalize_project_root "$local_explicit_root"); then
PROJECT_ROOT="$explicit_root"
export DEVSTREAM_PROJECT_ROOT="$PROJECT_ROOT"
if [ "$PROJECT_ROOT" != "$local_explicit_root" ]; then
print_info "Multi-project mode (explicit): $PROJECT_ROOT"
print_warning "DEVSTREAM_PROJECT_ROOT normalized from '$local_explicit_root'"
else
print_info "Multi-project mode (explicit): $PROJECT_ROOT"
fi
else
print_warning "Ignoring invalid DEVSTREAM_PROJECT_ROOT: $local_explicit_root"
unset DEVSTREAM_PROJECT_ROOT
fi
fi
# Priority 2: Auto-detect from invocation directory
if [ -z "$PROJECT_ROOT" ]; then
if LOCAL_PROJECT_ROOT=$(find_devstream_project_root "$INVOCATION_DIR"); then
if auto_root=$(normalize_project_root "$LOCAL_PROJECT_ROOT"); then
PROJECT_ROOT="$auto_root"
export DEVSTREAM_PROJECT_ROOT="$PROJECT_ROOT"
print_info "Multi-project mode (auto-detected): $PROJECT_ROOT"
else
print_error "Auto-detected project root is invalid: $LOCAL_PROJECT_ROOT"
exit 1
fi
fi
fi
# Priority 3: Use DevStream installation as project (fallback)
if [ -z "$PROJECT_ROOT" ]; then
PROJECT_ROOT="$DEVSTREAM_INSTALLATION_ROOT"
print_warning "No DevStream project found in current directory tree"
print_info "Falling back to DevStream installation: $PROJECT_ROOT"
fi
# Final guard: ensure project root is absolute (Context7 reliability requirement)
if [[ "$PROJECT_ROOT" != /* ]]; then
print_error "DevStream project root must be an absolute path (got: $PROJECT_ROOT)"
print_error "Unset DEVSTREAM_PROJECT_ROOT or provide an absolute path."
exit 1
fi
print_info "DevStream installation: $DEVSTREAM_SCRIPT_DIR"
# Function to validate DevStream project installation
validate_devstream_project() {
local project_root="$1"
local validation_failed=0
print_status "Validating DevStream project at: $project_root"
# Check required directories
if [ ! -d "$project_root/.claude" ]; then
print_error "Missing: .claude directory"
validation_failed=1
fi
if [ ! -d "$project_root/.claude/hooks/devstream" ]; then
print_error "Missing: .claude/hooks/devstream directory"
validation_failed=1
fi
if [ ! -d "$project_root/.devstream" ]; then
print_error "Missing: .devstream virtual environment"
validation_failed=1
fi
# Check required files
if [ ! -f "$project_root/.env.devstream" ]; then
print_error "Missing: .env.devstream configuration"
validation_failed=1
fi
if [ ! -f "$project_root/data/devstream.db" ]; then
print_warning "Missing: data/devstream.db (will be created)"
fi
# Check Python version in venv
if [ -x "$project_root/.devstream/bin/python" ]; then
local python_version=$("$project_root/.devstream/bin/python" --version 2>&1 | awk '{print $2}')
if [[ ! "$python_version" =~ ^3\.11\. ]]; then
print_error "Wrong Python version: $python_version (expected 3.11.x)"
validation_failed=1
fi
else
print_error "Python interpreter not found in .devstream/bin/"
validation_failed=1
fi
if [ $validation_failed -eq 1 ]; then
print_error ""
print_error "DevStream installation incomplete or corrupted"
print_error "Run: $DEVSTREAM_SCRIPT_DIR/scripts/install-devstream.sh"
return 1
fi
print_status "✅ DevStream project validation passed"
return 0
}
# Function to display project information
print_project_info() {
local project_root="$1"
local project_name=$(basename "$project_root")
local db_size="N/A"
if [ -f "$project_root/data/devstream.db" ]; then
db_size=$(du -h "$project_root/data/devstream.db" | awk '{print $1}')
fi
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🚀 DevStream Project Detected"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo " Project Name: $project_name"
echo " Location: $project_root"
echo " Database: data/devstream.db ($db_size)"
echo " Python Venv: .devstream/"
echo " Python: $($project_root/.devstream/bin/python --version 2>&1)"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
}
# Validate the detected project
if ! validate_devstream_project "$PROJECT_ROOT"; then
print_error "❌ Project validation failed"
exit 1
fi
# Show project information
print_project_info "$PROJECT_ROOT"
# MCP server directory (kept for compatibility but not used in Direct DB mode)
MCP_SERVER_DIR="$DEVSTREAM_SCRIPT_DIR/mcp-devstream-server"
VENV_DIR="$DEVSTREAM_SCRIPT_DIR/.devstream"
# Function to check and setup Python virtual environment
check_python_venv() {
print_status "Checking Python virtual environment..."
# Check if venv exists
if [ ! -d "$VENV_DIR" ]; then
print_warning "Virtual environment not found, creating..."
python3.11 -m venv "$VENV_DIR"
print_status "✅ Virtual environment created"
fi
# Verify Python version
local python_version=$("$VENV_DIR/bin/python" --version 2>&1 | cut -d' ' -f2)
print_info "Python: $python_version"
# Check critical dependencies (Context7 best practice: handle broken pipes)
print_status "Checking hook dependencies..."
if ! "$VENV_DIR/bin/python" -m pip list 2>/dev/null | grep -q "cchooks"; then
print_warning "Installing hook dependencies..."
# Context7 best practice: use proper error handling and pipe management
if "$VENV_DIR/bin/pip" install -q cchooks>=0.1.4 aiohttp>=3.8.0 structlog>=23.0.0 python-dotenv>=1.0.0 2>/dev/null; then
print_status "✅ Hook dependencies installed"
else
print_error "❌ Failed to install hook dependencies"
return 1
fi
else
print_info "Hook dependencies: OK"
fi
}
# Function to verify Agent Auto-Delegation System
verify_agent_delegation() {
print_status "Verifying Agent Auto-Delegation System..."
# Check if agent modules exist
if [ ! -f "$DEVSTREAM_SCRIPT_DIR/.claude/hooks/devstream/agents/pattern_matcher.py" ]; then
print_error "Pattern matcher not found"
return 1
fi
if [ ! -f "$DEVSTREAM_SCRIPT_DIR/.claude/hooks/devstream/agents/agent_router.py" ]; then
print_error "Agent router not found"
return 1
fi
# Test module import
local import_test=$("$VENV_DIR/bin/python" -c "
import sys
sys.path.insert(0, '$DEVSTREAM_SCRIPT_DIR/.claude/hooks/devstream')
try:
from agents.pattern_matcher import PatternMatcher
from agents.agent_router import AgentRouter
print('OK')
except Exception as e:
print(f'ERROR: {e}')
" 2>&1)
if [ "$import_test" = "OK" ]; then
print_status "✅ Agent Auto-Delegation System verified"
return 0
else
print_error "Agent delegation import failed: $import_test"
return 1
fi
}
# Function to handle authentication switching
switch_auth_provider() {
local provider="${1:-anthropic}"
print_status "Switching authentication provider to: $provider"
case "$provider" in
"z.ai")
# Validate z.ai API key
if [ -z "${ZAI_API_KEY:-}" ]; then
print_error "ZAI_API_KEY not configured in .env"
print_error "Get your API key from: https://z.ai/manage-apikey/apikey-list"
return 1
fi
# Set z.ai environment with CORRECT variable names per official docs
# See: https://docs.z.ai/scenario-example/develop-tools/claude
export ANTHROPIC_BASE_URL="https://api.z.ai/api/anthropic"
export ANTHROPIC_AUTH_TOKEN="$ZAI_API_KEY" # z.ai requires AUTH_TOKEN, not API_KEY
# Configure Claude Code settings for GLM-4.6
configure_claude_settings_for_zai
print_status "✅ Switched to z.ai (GLM-4.6)"
print_info " Base URL: $ANTHROPIC_BASE_URL"
print_info " Auth Token: ${ZAI_API_KEY:0:10}..."
print_info " Model: GLM-4.6 (configured in settings.json)"
;;
"anthropic"|"")
# Reset to Anthropic Max Plan (OAuth-based authentication)
# CRITICAL: Must unset ALL API env vars to preserve Max Plan subscription
# See: https://docs.anthropic.com/en/api/client-sdks
print_info "Resetting to Anthropic Max Plan (OAuth)..."
unset ANTHROPIC_BASE_URL # Remove z.ai override
unset ANTHROPIC_API_KEY # CRITICAL: Prevents Max Plan bypass
unset ANTHROPIC_AUTH_TOKEN # CRITICAL: Prevents Max Plan bypass
# Reset Claude Code settings to default
reset_claude_settings_to_default
# Verify Claude.ai authentication (non-blocking)
if command -v claude >/dev/null 2>&1; then
if ! claude auth status 2>/dev/null | grep -q "Logged in"; then
print_warning "Claude CLI not logged in"
print_info " If Claude Code login fails, run: claude login"
print_info " Visit: https://claude.ai/"
else
print_status "✅ Claude CLI authenticated"
print_info " Using Claude.ai subscription via OAuth login"
fi
else
print_info "Claude CLI not found (authentication handled by Claude Code)"
fi
print_status "✅ Switched to Anthropic Max Plan (OAuth)"
print_info " Authentication: Claude Code OAuth login"
;;
*)
print_error "Unknown provider: $provider"
print_info "Supported providers: anthropic, z.ai"
return 1
;;
esac
}
# Function to configure Claude Code settings for z.ai
configure_claude_settings_for_zai() {
local settings_file="$HOME/.claude/settings.json"
print_status "Configuring Claude Code settings for GLM-4.6..."
# Backup existing settings
if [ -f "$settings_file" ]; then
cp "$settings_file" "$settings_file.backup-zai-$(date +%Y%m%d_%H%M%S)"
print_info "✅ Backed up existing settings"
fi
# Use Python for robust JSON manipulation (best practice from Context7)
"$VENV_DIR/bin/python" << EOF
import json
import os
settings_file = "$settings_file"
# Read existing settings or create new
existing_data = {}
if os.path.exists(settings_file):
try:
with open(settings_file, 'r') as f:
existing_data = json.load(f)
except (json.JSONDecodeError, IOError):
print("Warning: Could not parse existing settings, creating new ones")
# Preserve hooks and mcpServers if they exist
preserved_data = {
"hooks": existing_data.get("hooks", {}),
"mcpServers": existing_data.get("mcpServers", {}),
"alwaysThinkingEnabled": existing_data.get("alwaysThinkingEnabled", False)
}
# Create new configuration
new_config = {
**preserved_data,
"model": "glm-4.6",
"env": {
"ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-4.6",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-4.6",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-4.5-air"
}
}
# Write new settings
with open(settings_file, 'w') as f:
json.dump(new_config, f, indent=2)
print("✅ Claude Code settings updated successfully")
EOF
if [ $? -eq 0 ]; then
print_status "✅ Claude Code configured for GLM-4.6"
else
print_error "❌ Failed to configure Claude Code settings"
return 1
fi
}
# Function to reset Claude Code settings to default
reset_claude_settings_to_default() {
local settings_file="$HOME/.claude/settings.json"
print_status "Resetting Claude Code settings to default..."
if [ -f "$settings_file" ]; then
# Use Python for robust JSON manipulation
"$VENV_DIR/bin/python" << EOF
import json
import os
settings_file = "$settings_file"
# Read existing settings
if os.path.exists(settings_file):
try:
with open(settings_file, 'r') as f:
existing_data = json.load(f)
except (json.JSONDecodeError, IOError):
print("Warning: Could not parse existing settings")
exit(1)
# Preserve only hooks and mcpServers, remove model-specific config
default_config = {
"hooks": existing_data.get("hooks", {}),
"mcpServers": existing_data.get("mcpServers", {}),
"alwaysThinkingEnabled": existing_data.get("alwaysThinkingEnabled", False)
}
# Write default settings
with open(settings_file, 'w') as f:
json.dump(default_config, f, indent=2)
print("✅ Claude Code settings reset to default")
else:
print("No settings file found")
EOF
fi
}
# Function to load LLM provider configuration
load_llm_provider() {
local provider="${1:-anthropic}"
print_status "Loading LLM Provider: $provider"
# Export provider for downstream functions
export DEVSTREAM_LLM_PROVIDER="$provider"
# Load root .env first (single source of truth) - always from DevStream installation
if [ -f "$DEVSTREAM_SCRIPT_DIR/.env" ]; then
set -a
source "$DEVSTREAM_SCRIPT_DIR/.env"
set +a
export DEVSTREAM_ANTHROPIC_API_KEY_DEFAULT="${ANTHROPIC_API_KEY:-}"
print_info "Root .env loaded"
fi
# Switch authentication provider after base env is available
switch_auth_provider "$provider"
# For non-anthropic providers, load additional config
if [ "$provider" != "anthropic" ] && [ -f "$DEVSTREAM_SCRIPT_DIR/.env.llm-providers" ]; then
source "$DEVSTREAM_SCRIPT_DIR/.env.llm-providers"
print_info "Additional provider configuration loaded"
fi
}
# Function to load DevStream configuration
load_devstream_config() {
print_status "Loading DevStream configuration..."
# Load .env.devstream - always from DevStream installation
if [ -f "$DEVSTREAM_SCRIPT_DIR/.env.devstream" ]; then
export $(cat "$DEVSTREAM_SCRIPT_DIR/.env.devstream" | grep -v '^#' | grep -v '^$' | xargs)
print_info ".env.devstream loaded"
else
print_warning ".env.devstream not found"
fi
# Verify Agent Auto-Delegation is enabled
if [ "${DEVSTREAM_AGENT_AUTO_DELEGATION_ENABLED:-true}" = "true" ]; then
print_feature "✅ Agent Auto-Delegation: ENABLED"
print_info " Confidence threshold: ${DEVSTREAM_AGENT_AUTO_DELEGATION_CONFIDENCE_THRESHOLD:-0.85}"
print_info " Auto-approve threshold: ${DEVSTREAM_AGENT_AUTO_DELEGATION_AUTO_APPROVE_THRESHOLD:-0.95}"
else
print_warning "⚠️ Agent Auto-Delegation: DISABLED"
fi
# Verify Memory System is enabled
if [ "${DEVSTREAM_MEMORY_ENABLED:-true}" = "true" ]; then
print_feature "✅ Semantic Memory: ENABLED"
else
print_warning "⚠️ Semantic Memory: DISABLED"
fi
# Verify Context7 is enabled
if [ "${DEVSTREAM_CONTEXT7_ENABLED:-true}" = "true" ]; then
print_feature "✅ Context7 Integration: ENABLED"
# Show Direct Client Hybrid Architecture status
local direct_mode="${DEVSTREAM_CONTEXT7_DIRECT_ENABLED:-false}"
local fallback="${DEVSTREAM_CONTEXT7_MCP_FALLBACK:-true}"
if [ "$direct_mode" = "true" ]; then
print_info " 🚀 Direct Client: ENABLED (bypass MCP for performance)"
elif [ "$direct_mode" = "rollout" ]; then
print_info " 🔄 Direct Client: ROLLOUT mode (10% gradual rollout)"
else
print_info " 📡 MCP Mode: ENABLED (traditional MCP server)"
fi
if [ "$fallback" = "true" ] && [ "$direct_mode" != "false" ]; then
print_info " 🛡️ MCP Fallback: ENABLED (graceful degradation)"
fi
else
print_warning "⚠️ Context7 Integration: DISABLED"
fi
}
# Function to initialize Context7
initialize_context7() {
print_status "Initializing Context7 MCP Integration..."
# Check if Context7 is configured
if [ ! -f "$PROJECT_ROOT/.config/context7.json" ]; then
print_info "Setting up Context7 MCP configuration..."
mkdir -p "$PROJECT_ROOT/.config"
cat > "$PROJECT_ROOT/.config/context7.json" << EOF
{
"enabled": true,
"mcp_endpoint": "npx -y @upstash/context7-mcp@latest",
"session_id": "devstream-$(date +%s)",
"auto_inject": true,
"cache_duration": 3600
}
EOF
print_status "✅ Context7 configuration created"
fi
# Set Context7 environment variables
export CONTEXT7_ENABLED=true
# Extract session ID with safe pipeline (file must exist at this point)
if [ -f "$PROJECT_ROOT/.config/context7.json" ]; then
export CONTEXT7_SESSION_ID=$(cat "$PROJECT_ROOT/.config/context7.json" | grep session_id | cut -d'"' -f4)
else
export CONTEXT7_SESSION_ID="devstream-default"
fi
if [ -n "${CONTEXT7_API_KEY:-}" ]; then
print_status "✅ Context7 initialized (Session: $CONTEXT7_SESSION_ID)"
else
print_warning "⚠️ CONTEXT7_API_KEY not set in environment"
fi
}
# Function to check Context7 availability
verify_context7() {
print_status "Verifying Context7 MCP availability..."
if command -v npx >/dev/null 2>&1; then
print_status "✅ npx available"
# Silently check Context7 package (will install on first use if needed)
print_info "Context7 will auto-install on first use if needed"
else
print_warning "⚠️ npx not available - Node.js may not be installed"
fi
}
# Function to check prerequisites
check_prerequisites() {
print_status "Checking prerequisites..."
local all_good=true
# Check Node.js
if ! command -v node >/dev/null 2>&1; then
print_error "Node.js not found"
all_good=false
else
print_info "Node.js: $(node --version)"
fi
# Check jq (required for JSON manipulation)
if ! command -v jq >/dev/null 2>&1; then
print_error "jq not found - required for Claude Code settings management"
print_info "Install jq: brew install jq"
all_good=false
else
print_info "jq: $(jq --version)"
fi
# Check database - use project directory for multi-project mode with Direct DB architecture
local db_path=""
if [ -n "${DEVSTREAM_PROJECT_ROOT:-}" ]; then
db_path="$PROJECT_ROOT/data/devstream.db"
print_info "Direct DB: Using project database at $db_path"
else
db_path="$DEVSTREAM_SCRIPT_DIR/data/devstream.db"
print_info "Direct DB: Using DevStream database at $db_path"
fi
if [ ! -f "$db_path" ]; then
print_error "Database not found: $db_path"
all_good=false
else
print_info "Database: Found at $db_path"
# Test Direct DB access
local db_test=$("$VENV_DIR/bin/python" -c "
import sqlite3
import sys
db_path = r'$db_path'
def table_counts(connection):
tables = [row[0] for row in connection.execute(
\"SELECT name FROM sqlite_master WHERE type='table' AND name IN ('memory', 'semantic_memory')\"
)]
if not tables:
return []
counts = []
for table_name in sorted(set(tables)):
query = \"SELECT COUNT(*) FROM {}\".format(table_name)
count = connection.execute(query).fetchone()[0]
counts.append('{}={}'.format(table_name, count))
return counts
try:
conn = sqlite3.connect(db_path)
stats = table_counts(conn)
conn.close()
if not stats:
print('ERROR:No memory tables found. Run make db-init to initialize the schema.')
sys.exit(1)
print('OK:' + ','.join(stats))
except Exception as exc:
print(f'ERROR:{exc}')
sys.exit(1)
" 2>&1)
if [[ "$db_test" == OK:* ]]; then
local record_info=${db_test#OK:}
print_info "Direct DB access: $record_info"
else
print_error "Direct DB access failed: ${db_test#ERROR:}"
all_good=false
fi
fi
# Check Ollama (non-blocking) - needed for embeddings in Direct DB
if ! curl -s http://localhost:11434/api/tags >/dev/null 2>&1; then
print_warning "Ollama service not responding at http://localhost:11434"
print_info "Start Ollama: brew services start ollama"
print_info "Embeddings will be disabled until Ollama is running"
else
print_info "Ollama: Running - embeddings available"
fi
if [ "$all_good" = false ]; then
print_error "Critical prerequisites not met. Please fix the issues above."
exit 1
fi
print_status "✅ All critical prerequisites met"
}
# Function to check Direct DB Architecture (NEW)
check_direct_db_architecture() {
print_status "Checking Direct DB Architecture..."
# Check if feature flag is enabled
local direct_db_enabled=false
if [ -f "$DEVSTREAM_SCRIPT_DIR/.env.devstream" ]; then
if grep -q "DEVSTREAM_FEATURE_DIRECT_DB_ENABLED=true" "$DEVSTREAM_SCRIPT_DIR/.env.devstream"; then
direct_db_enabled=true
fi
fi
if [ "$direct_db_enabled" = true ]; then
print_feature "✅ Direct DB Architecture: ENABLED"
print_info " Using SQLite direct connections via Python hooks"
print_info " MCP server is NOT required for core functionality"
return 0
else
print_feature "⚠️ Direct DB Architecture: DISABLED (legacy mode)"
print_info " MCP server will be started for compatibility"
return 1
fi
}
# Function to initialize Direct DB Architecture with automatic schema management
initialize_direct_db() {
print_status "Initializing Direct DB Architecture..."
# Verify Direct DB is enabled
if ! check_direct_db_architecture; then
print_error "❌ Direct DB Architecture is disabled"
print_error " Enable it by setting DEVSTREAM_FEATURE_DIRECT_DB_ENABLED=true"
exit 1
fi
# Set environment variables for Direct DB
if [ "$PROJECT_ROOT" != "$DEVSTREAM_SCRIPT_DIR" ]; then
export DEVSTREAM_DB_PATH="$PROJECT_ROOT/data/devstream.db"
export DEVSTREAM_PROJECT_ROOT="$PROJECT_ROOT"
export DEVSTREAM_LOG_DIR="$PROJECT_ROOT/.devstream/logs/devstream"
mkdir -p "$DEVSTREAM_LOG_DIR" || true
print_info "Direct DB configured for project: $PROJECT_ROOT"
print_info "Database path: $DEVSTREAM_DB_PATH"
else
export DEVSTREAM_DB_PATH="$DEVSTREAM_SCRIPT_DIR/data/devstream.db"
export DEVSTREAM_PROJECT_ROOT="$DEVSTREAM_SCRIPT_DIR"
export DEVSTREAM_LOG_DIR="$DEVSTREAM_SCRIPT_DIR/.devstream/logs/devstream"
mkdir -p "$DEVSTREAM_LOG_DIR" || true
print_info "Direct DB configured for DevStream installation"
print_info "Database path: $DEVSTREAM_DB_PATH"
fi
# Initialize or validate database schema (Context7 best practice)
initialize_database_schema
# Initialize project templates for multi-project setup
initialize_project_templates
# Initialize protocol reference docs for multi-project setup
initialize_project_protocols
# Initialize project virtual environment for multi-project setup (Context7 best practice)
initialize_project_venv
# Initialize project CLAUDE.md for multi-project setup (Context7 + projen/chezmoi patterns)
initialize_project_claude_md
# Initialize project memory for multi-project setup (Context7 best practices)
initialize_project_memory_bootstrap
# NEW: Enhanced hook copying integration for multi-project setup
if [ -n "${DEVSTREAM_PROJECT_ROOT:-}" ]; then
initialize_enhanced_hook_copying
fi
# NEW: Context7-compliant multi-project setup for additional robustness
if [ -n "${DEVSTREAM_PROJECT_ROOT:-}" ]; then
initialize_context7_multi_project_setup
fi
print_status "✅ Direct DB Architecture initialized"
}
# NEW: Function to initialize Context7-compliant multi-project setup
# Uses the new MultiProjectManager for comprehensive project initialization
initialize_context7_multi_project_setup() {
print_status "🔧 Initializing Context7-compliant multi-project setup..."
local multi_project_manager="$DEVSTREAM_SCRIPT_DIR/.claude/hooks/devstream/utils/multi_project_manager.py"
local hook_validator="$DEVSTREAM_SCRIPT_DIR/.claude/hooks/devstream/utils/hook_system_validator.py"
# Check if the new Context7-compliant tools are available
if [ ! -f "$multi_project_manager" ]; then
print_warning "⚠️ MultiProjectManager not found, skipping Context7 setup"
return 0
fi
# Run the comprehensive multi-project setup
print_info "🔄 Running Context7-compliant project setup..."
local setup_result=$("$VENV_DIR/bin/python" "$multi_project_manager" \
"$PROJECT_ROOT" \
--devstream-root "$DEVSTREAM_SCRIPT_DIR" \
--verbose 2>&1)
local setup_exit_code=$?
if [ $setup_exit_code -eq 0 ]; then
print_status "✅ Context7-compliant multi-project setup completed"
# Show key setup results
if echo "$setup_result" | grep -q "✅"; then
local success_count=$(echo "$setup_result" | grep -c "✅" || echo "0")
print_info " Completed operations: $success_count"
fi
if echo "$setup_result" | grep -q "Database initialized"; then
print_info " Database: Ready with required tables"
fi
if echo "$setup_result" | grep -q "Cross-project files"; then
print_info " Cross-project files: Ensured and synchronized"
fi
else
print_error "❌ Context7-compliant setup failed"
print_error " Error: $setup_result"
print_warning " Continuing with basic setup (some features may be limited)"
fi
# Run comprehensive hook system validation if available
if [ -f "$hook_validator" ]; then
print_info "🔍 Running comprehensive hook system validation..."
local validation_result=$("$VENV_DIR/bin/python" "$hook_validator" \
"$PROJECT_ROOT" \
--verbose 2>&1)
local validation_exit_code=$?
if [ $validation_exit_code -eq 0 ]; then
print_status "✅ Hook system validation passed"
# Show validation summary
if echo "$validation_result" | grep -q "tests passed"; then
local test_summary=$(echo "$validation_result" | grep "tests passed" | head -1)
print_info " $test_summary"
fi
else
print_warning "⚠️ Hook system validation has issues"
print_warning " Some hook features may not work correctly"
# Show critical issues
if echo "$validation_result" | grep -q "❌"; then
local critical_issues=$(echo "$validation_result" | grep "❌" | head -3 | tr '\n' '; ')
print_info " Critical issues: ${critical_issues%;}"
fi
fi
else
print_info "ℹ️ Hook validator not available, skipping validation"
fi
}
# Function to initialize database schema with automatic validation and creation
# Context7-inspired: robust database initialization with schema validation
initialize_database_schema() {
local db_path="$DEVSTREAM_DB_PATH"
print_status "🔧 Initializing database schema..."
# Ensure data directory exists
mkdir -p "$(dirname "$db_path")"
# Check if database exists
if [ ! -f "$db_path" ]; then
print_info "📁 Creating new database: $db_path"
create_complete_database "$db_path"
else
print_info "📁 Database exists: $db_path"
validate_and_upgrade_schema "$db_path"
fi
}
# Function to create complete database with all required tables
# Context7 best practice: atomic database creation with full schema
create_complete_database() {
local db_path="$1"
print_info "🏗️ Creating complete database schema..."
# Use Python for robust database creation (Context7 pattern)
"$VENV_DIR/bin/python" << EOF
import sqlite3
import sys
from datetime import datetime
db_path = r'$db_path'
try:
# Connect with sqlite-vec extension if available
conn = sqlite3.connect(db_path)
# Try to load sqlite-vec extension for project databases
try:
# Try common locations for sqlite-vec extension
extension_paths = [
'/opt/homebrew/lib/sqlite-vec.dylib', # macOS Homebrew
'/usr/local/lib/sqlite-vec.dylib', # Linux/local
'/usr/lib/sqlite-vec.dylib', # System
'./sqlite-vec.so', # Local
]
vec_loaded = False
for ext_path in extension_paths:
try:
conn.enable_load_extension(True)
conn.load_extension(ext_path)
print(f"✅ Loaded sqlite-vec extension from: {ext_path}")
vec_loaded = True
break
except:
continue
if not vec_loaded:
print("⚠️ sqlite-vec extension not available, using fallback schema")
except Exception as e:
print(f"⚠️ Could not load sqlite-vec extension: {e}")
cursor = conn.cursor()
# Enable WAL mode for better concurrency (Context7 best practice)
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA synchronous=NORMAL")
cursor.execute("PRAGMA cache_size=10000")
# Core tables for DevStream
tables_sql = [
# Memory table for semantic storage
"""
CREATE TABLE IF NOT EXISTS memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
content TEXT NOT NULL,
content_type TEXT NOT NULL DEFAULT 'code',
keywords TEXT,
metadata TEXT,
embedding_id INTEGER,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
)
""",
# Semantic memory table for vector embeddings (sqlite-vec)
"""
CREATE TABLE IF NOT EXISTS semantic_memory (
id INTEGER PRIMARY KEY,
embedding BLOB,
model TEXT NOT NULL DEFAULT 'default',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
)
""",
# Vector table for sqlite-vec (if available)
]
# Try to create vector table with sqlite-vec
try:
tables_sql.append("""
CREATE VIRTUAL TABLE IF NOT EXISTS vec_semantic_memory USING vec0(
embedding float[1536] PRIMARY KEY,
rowid INTEGER
)
""")
print("✅ Vector table created with sqlite-vec")
except Exception as e:
print(f"⚠️ Could not create vector table: {e}")
# Fallback: create basic table without vector capabilities
tables_sql.append("""
CREATE TABLE IF NOT EXISTS vec_semantic_memory_fallback (
id INTEGER PRIMARY KEY,