-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathralph.sh
More file actions
executable file
·2050 lines (1779 loc) · 73.1 KB
/
ralph.sh
File metadata and controls
executable file
·2050 lines (1779 loc) · 73.1 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
# Ralph Wiggum Technique - Continuous Agent Loop
# This script runs an AI coding agent in a loop until all features are complete
set -e
# Configuration
MAX_ITERATIONS=${MAX_ITERATIONS:-100}
SLEEP_BETWEEN_ITERATIONS=${SLEEP_BETWEEN_ITERATIONS:-5}
AGENT_PROMPT_FILE="${AGENT_PROMPT_FILE:-AGENT_PROMPT.md}"
PRD_FILE="${PRD_FILE:-.ralph/prd.json}"
PROGRESS_FILE="${PROGRESS_FILE:-.ralph/progress.txt}"
# Git Safety Configuration
# Protect important branches from direct commits
PROTECTED_BRANCHES="${PROTECTED_BRANCHES:-main,master}"
# Allow git push operations (default: false for safety)
ALLOW_GIT_PUSH="${ALLOW_GIT_PUSH:-false}"
# Auto-create feature branches when on protected branch (default: true)
AUTO_CREATE_BRANCH="${AUTO_CREATE_BRANCH:-true}"
# Run Mode Configuration
# Set how the script executes iterations:
# Options:
# "once" - Human-in-the-loop: Run one iteration, then stop for review (default)
# "continuous" - AFK mode: Run until all features complete or max iterations reached
RUN_MODE="${RUN_MODE:-once}"
# AI Agent Configuration
# Set your preferred AI agent command here
# Options:
# "manual" - Prompts you to run the agent manually (default for compatibility)
# "claude" - Uses Claude CLI (requires: npm install -g @anthropic-ai/claude-cli)
# "cursor" - Uses Cursor CLI (if available)
# "custom" - Set AI_AGENT_CUSTOM_CMD below for your own command
AI_AGENT_MODE="${AI_AGENT_MODE:-claude}"
# For custom commands, set this variable:
# Example: AI_AGENT_CUSTOM_CMD="your-ai-tool --prompt-file"
AI_AGENT_CUSTOM_CMD="${AI_AGENT_CUSTOM_CMD:-}"
# Git Safety Configuration
# Prevent commits to these branches (comma-separated)
PROTECTED_BRANCHES="${PROTECTED_BRANCHES:-main,master}"
# Allow git push to remote (default: false for safety)
ALLOW_GIT_PUSH="${ALLOW_GIT_PUSH:-false}"
# Error Recovery Configuration
# Automatically rollback git commit if tests fail after implementation
ROLLBACK_ON_FAILURE="${ROLLBACK_ON_FAILURE:-true}"
# Run verification tests before accepting a feature as complete
VERIFY_BEFORE_COMPLETE="${VERIFY_BEFORE_COMPLETE:-true}"
# Code Quality Configuration
# Automatically fix prettier formatting issues before verification
AUTOFIX_PRETTIER="${AUTOFIX_PRETTIER:-true}"
# Test Coverage Configuration (Feature 021)
# Require test files for feature and bug types (default: true)
# When true, features of type 'feature' or 'bug' cannot be marked complete without tests
TEST_REQUIRED_FOR_FEATURES="${TEST_REQUIRED_FOR_FEATURES:-true}"
# Test Output Mode Configuration (Feature 011)
# Controls how much test output is shown to conserve tokens
# Options: "full" (all output), "failures" (only failing tests), "summary" (stats only)
# Default: "failures" (optimal balance of information and token usage)
TEST_OUTPUT_MODE="${TEST_OUTPUT_MODE:-failures}"
# Sanity CMS Configuration (Feature 013)
# Configure Sanity project for PRD storage (used in Feature 014)
SANITY_PROJECT_ID="${SANITY_PROJECT_ID:-}"
SANITY_DATASET="${SANITY_DATASET:-production}"
SANITY_TOKEN="${SANITY_TOKEN:-}"
# PRD storage mode: "file" (default) or "sanity" (requires Feature 014)
PRD_STORAGE="${PRD_STORAGE:-file}"
# Logging Configuration (Feature 007)
# Log level: DEBUG, INFO, WARN, ERROR (default: INFO)
# DEBUG: Show all messages including debug info
# INFO: Show informational messages, warnings, and errors (default)
# WARN: Show only warnings and errors
# ERROR: Show only errors
LOG_LEVEL="${LOG_LEVEL:-INFO}"
# Optional log file for persistent logging (default: none, logs to console only)
# Example: LOG_FILE=".ralph/ralph.log"
LOG_FILE="${LOG_FILE:-}"
# Progress Header Configuration (Feature 024)
# Show persistent header with current task and progress stats
# Default: true (shows header at start of each iteration)
SHOW_PROGRESS_HEADER="${SHOW_PROGRESS_HEADER:-true}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
GRAY='\033[0;90m'
NC='\033[0m' # No Color
# Internal function to determine if message should be logged based on level
should_log() {
local msg_level="$1"
# Convert levels to numeric values for comparison
local level_value=0
case "$LOG_LEVEL" in
DEBUG) level_value=0 ;;
INFO) level_value=1 ;;
WARN) level_value=2 ;;
ERROR) level_value=3 ;;
*) level_value=1 ;; # Default to INFO
esac
local msg_value=0
case "$msg_level" in
DEBUG) msg_value=0 ;;
INFO) msg_value=1 ;;
WARN) msg_value=2 ;;
ERROR) msg_value=3 ;;
esac
# Log if message level >= configured log level
[ $msg_value -ge $level_value ]
}
# Internal function to write to log file if configured
write_to_log_file() {
local level="$1"
local message="$2"
if [ -n "$LOG_FILE" ]; then
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] [$level] $message" >> "$LOG_FILE"
fi
}
# Enhanced logging functions with level filtering and file output
log_debug() {
if should_log "DEBUG"; then
echo -e "${GRAY}[DEBUG]${NC} $1"
fi
write_to_log_file "DEBUG" "$1"
}
log_info() {
if should_log "INFO"; then
echo -e "${BLUE}[INFO]${NC} $1"
fi
write_to_log_file "INFO" "$1"
}
log_success() {
if should_log "INFO"; then
echo -e "${GREEN}[SUCCESS]${NC} $1"
fi
write_to_log_file "SUCCESS" "$1"
}
log_warning() {
if should_log "WARN"; then
echo -e "${YELLOW}[WARNING]${NC} $1"
fi
write_to_log_file "WARNING" "$1"
}
log_error() {
if should_log "ERROR"; then
echo -e "${RED}[ERROR]${NC} $1"
fi
write_to_log_file "ERROR" "$1"
}
# ==========================================
# Progress Header Display (Feature 024)
# ==========================================
# Calculate PRD statistics: total, completed, blocked, remaining
calculate_prd_stats() {
local prd_data="$1"
# Use Python to count features by status
python3 -c "
import json
import sys
try:
prd = json.loads('''$prd_data''')
features = prd.get('features', [])
total = len(features)
completed = sum(1 for f in features if f.get('passes') == True)
blocked = sum(1 for f in features if f.get('blocked_reason') not in [None, ''])
remaining = total - completed
# Return as CSV: total,completed,blocked,remaining
print(f'{total},{completed},{blocked},{remaining}')
except Exception as e:
# Fallback if parsing fails
print('0,0,0,0')
sys.exit(1)
" 2>/dev/null || echo "0,0,0,0"
}
# Get current feature info: ID, type, description
get_current_feature_info() {
local prd_data="$1"
# Use Python to find next incomplete feature
python3 -c "
import json
import sys
try:
prd = json.loads('''$prd_data''')
features = prd.get('features', [])
# Find first incomplete feature with met dependencies
for feature in features:
if feature.get('passes') == True:
continue
if feature.get('blocked_reason') not in [None, '']:
continue
# Check dependencies
deps = feature.get('depends_on', [])
deps_met = True
for dep_id in deps:
dep_feature = next((f for f in features if f.get('id') == dep_id), None)
if dep_feature is None or dep_feature.get('passes') != True:
deps_met = False
break
if deps_met:
feature_id = feature.get('id', 'unknown')
feature_type = feature.get('type', 'feature')
description = feature.get('description', 'No description')
# Truncate description if too long
if len(description) > 70:
description = description[:67] + '...'
print(f'{feature_id}|{feature_type}|{description}')
sys.exit(0)
# No feature found
print('none|none|All features complete or blocked')
except Exception as e:
print('error|error|Failed to parse PRD')
sys.exit(1)
" 2>/dev/null || echo "error|error|Failed to parse PRD"
}
# Display progress header with current task and stats
# Uses terminal control sequences to keep header static at top of screen
display_progress_header() {
# Accept feature parameters: feature_id, feature_type, description
# If not provided, will display header without feature info (just stats)
local feature_id="$1"
local feature_type="$2"
local description="$3"
# Only show if enabled and not in quiet mode
if [ "$SHOW_PROGRESS_HEADER" != "true" ]; then
return
fi
if [ "$LOG_LEVEL" = "ERROR" ]; then
return
fi
# Get PRD data
local prd_data
prd_data=$(get_prd_data)
if [ -z "$prd_data" ]; then
log_warning "Cannot display progress header: PRD data not available"
return
fi
# Calculate statistics
local stats
stats=$(calculate_prd_stats "$prd_data")
IFS=',' read -r total completed blocked remaining <<< "$stats"
# Calculate percentage
local percentage=0
if [ "$total" -gt 0 ]; then
percentage=$(( completed * 100 / total ))
fi
# Save current cursor position so we can return to it after displaying header
tput sc
# Move cursor to top of screen (row 0, column 0) to display header there
tput cup 0 0
# Display header with color coding (each line clears to end with tput el)
echo ""
tput el
echo -e "${BLUE}═══════════════════════════════════════════════════════════════════${NC}"
tput el
# Current feature line
if [ "$feature_id" = "none" ]; then
echo -e "${GREEN}🎯 Current: All features complete!${NC}"
tput el
elif [ "$feature_id" = "error" ]; then
echo -e "${RED}🎯 Current: Error reading PRD${NC}"
tput el
else
echo -e "${YELLOW}🎯 Current: [$feature_id] - $feature_type - $description${NC}"
tput el
fi
# Progress statistics line
local stats_line="📊 Progress: ${GREEN}$completed${NC}/$total (${GREEN}$percentage%${NC}) complete"
if [ "$blocked" -gt 0 ]; then
stats_line="$stats_line | ${RED}$blocked blocked${NC}"
fi
if [ "$remaining" -gt 0 ]; then
stats_line="$stats_line | ${YELLOW}$remaining remaining${NC}"
fi
echo -e "$stats_line"
tput el
echo -e "${BLUE}═══════════════════════════════════════════════════════════════════${NC}"
tput el
echo ""
tput el
# Restore cursor to original position so subsequent output continues where it was
tput rc
}
# ==========================================
# Tool Availability Checking (Feature 007)
# ==========================================
# Check if a command/tool is available
check_tool() {
local tool="$1"
local install_hint="$2"
if command -v "$tool" >/dev/null 2>&1; then
log_debug "✓ $tool is installed"
return 0
else
log_error "✗ $tool is not installed or not in PATH"
if [ -n "$install_hint" ]; then
log_info " Install with: $install_hint"
fi
return 1
fi
}
# Verify all required tools are available
check_required_tools() {
log_debug "Checking for required tools..."
local all_tools_available=true
# Check git
if ! check_tool "git" "brew install git (macOS) or apt-get install git (Linux)"; then
all_tools_available=false
fi
# Check python3
if ! check_tool "python3" "brew install python3 (macOS) or apt-get install python3 (Linux)"; then
all_tools_available=false
fi
# Check curl
if ! check_tool "curl" "brew install curl (macOS) or apt-get install curl (Linux)"; then
all_tools_available=false
fi
# Check optional tools (don't fail if missing, just warn)
if ! command -v "node" >/dev/null 2>&1; then
log_debug "○ node is not installed (optional for quality gates)"
fi
if ! command -v "npm" >/dev/null 2>&1; then
log_debug "○ npm is not installed (optional for quality gates)"
fi
if ! command -v "jq" >/dev/null 2>&1; then
log_debug "○ jq is not installed (optional, Python is used as fallback)"
fi
if [ "$all_tools_available" = false ]; then
log_error "Some required tools are missing. Please install them and try again."
return 1
fi
log_debug "All required tools are available"
return 0
}
# ==========================================
# Sanity CMS Integration Functions (Feature 014)
# ==========================================
# Validate Sanity configuration
validate_sanity_config() {
if [ -z "$SANITY_PROJECT_ID" ]; then
log_error "SANITY_PROJECT_ID not set. Required for PRD_STORAGE=sanity"
log_info "Set environment variable: export SANITY_PROJECT_ID=your-project-id"
return 1
fi
if [ -z "$SANITY_DATASET" ]; then
log_error "SANITY_DATASET not set. Required for PRD_STORAGE=sanity"
log_info "Set environment variable: export SANITY_DATASET=production"
return 1
fi
if [ -z "$SANITY_TOKEN" ]; then
log_error "SANITY_TOKEN not set. Required for PRD_STORAGE=sanity"
log_info "Create a token at: https://sanity.io/manage/project/$SANITY_PROJECT_ID/api"
log_info "Then set: export SANITY_TOKEN=your-token"
return 1
fi
return 0
}
# Fetch PRD from Sanity CMS
fetch_prd_from_sanity() {
local api_url="https://${SANITY_PROJECT_ID}.api.sanity.io/v2021-10-21/data/query/${SANITY_DATASET}"
# GROQ query to fetch ralphProject document
local query='*[_type == "ralphProject"][0]'
log_info "Fetching PRD from Sanity: $SANITY_PROJECT_ID/$SANITY_DATASET"
local response=$(curl -s -f \
--connect-timeout 10 \
--max-time 30 \
-H "Authorization: Bearer $SANITY_TOKEN" \
--get \
--data-urlencode "query=$query" \
"$api_url" 2>&1)
local curl_exit=$?
if [ $curl_exit -ne 0 ]; then
log_error "Failed to fetch PRD from Sanity (curl exit code: $curl_exit)"
log_error "Response: $response"
log_info "Check your SANITY_PROJECT_ID, SANITY_DATASET, and SANITY_TOKEN"
return 1
fi
# Extract result from response
local prd_doc=$(echo "$response" | python3 -c "
import json, sys
try:
data = json.load(sys.stdin)
result = data.get('result')
if result:
print(json.dumps(result))
else:
sys.stderr.write('No result found in Sanity response\n')
sys.exit(1)
except Exception as e:
sys.stderr.write(f'Error parsing Sanity response: {e}\n')
sys.exit(1)
" 2>&1)
local py_exit=$?
if [ $py_exit -ne 0 ]; then
log_error "Failed to parse Sanity response"
log_error "Error: $prd_doc"
log_info "Ensure a ralphProject document exists in your Sanity dataset"
return 1
fi
if [ -z "$prd_doc" ] || [ "$prd_doc" = "null" ]; then
log_error "No ralphProject document found in Sanity"
log_info "Use the migration script to import your PRD: node .ralph/sanity/migrate.js"
return 1
fi
log_success "PRD fetched from Sanity successfully"
echo "$prd_doc"
return 0
}
# Update feature status in Sanity CMS
update_prd_feature_in_sanity() {
local feature_id="$1"
local passes="$2"
local iterations_taken="$3"
local blocked_reason="$4"
if [ -z "$feature_id" ]; then
log_error "Feature ID required for update_prd_feature_in_sanity"
return 1
fi
local api_url="https://${SANITY_PROJECT_ID}.api.sanity.io/v2021-10-21/data/mutate/${SANITY_DATASET}"
log_info "Updating feature $feature_id in Sanity..."
# First, fetch the document to get its _id
local doc_query='*[_type == "ralphProject"][0]{_id, features}'
local doc_response=$(curl -s -f \
--connect-timeout 10 \
--max-time 30 \
-H "Authorization: Bearer $SANITY_TOKEN" \
--get \
--data-urlencode "query=$doc_query" \
"https://${SANITY_PROJECT_ID}.api.sanity.io/v2021-10-21/data/query/${SANITY_DATASET}")
if [ $? -ne 0 ]; then
log_error "Failed to fetch document for update"
return 1
fi
# Build the mutation JSON
local mutation=$(python3 -c "
import json, sys
doc_response = '''$doc_response'''
feature_id = '$feature_id'
passes = '$passes'
iterations_taken = '$iterations_taken'
blocked_reason = '''$blocked_reason'''
try:
data = json.loads(doc_response)
result = data.get('result')
if not result:
sys.stderr.write('No document found\n')
sys.exit(1)
doc_id = result.get('_id')
features = result.get('features', [])
# Find feature index
feature_idx = None
for idx, f in enumerate(features):
if f.get('id') == feature_id:
feature_idx = idx
break
if feature_idx is None:
sys.stderr.write(f'Feature {feature_id} not found\n')
sys.exit(1)
# Build Sanity mutation
mutations = {
'mutations': [
{
'patch': {
'id': doc_id,
'set': {
f'features[{feature_idx}].passes': passes.lower() == 'true',
f'features[{feature_idx}].iterations_taken': int(iterations_taken)
}
}
}
]
}
# Add blocked_reason if provided
if blocked_reason and blocked_reason != 'null':
mutations['mutations'][0]['patch']['set'][f'features[{feature_idx}].blocked_reason'] = blocked_reason
else:
mutations['mutations'][0]['patch']['unset'] = [f'features[{feature_idx}].blocked_reason']
print(json.dumps(mutations))
except Exception as e:
sys.stderr.write(f'Error building mutation: {e}\n')
sys.exit(1)
")
if [ $? -ne 0 ]; then
log_error "Failed to build mutation"
log_error "$mutation"
return 1
fi
# Execute mutation
local response=$(curl -s -f \
--connect-timeout 10 \
--max-time 30 \
-X POST \
-H "Authorization: Bearer $SANITY_TOKEN" \
-H "Content-Type: application/json" \
-d "$mutation" \
"$api_url")
if [ $? -ne 0 ]; then
log_error "Failed to update feature in Sanity"
log_error "Response: $response"
return 1
fi
log_success "Feature $feature_id updated in Sanity"
return 0
}
# Get PRD data (from file or Sanity based on PRD_STORAGE)
get_prd_data() {
if [ "$PRD_STORAGE" = "sanity" ]; then
fetch_prd_from_sanity
else
if [ ! -f "$PRD_FILE" ]; then
log_error "PRD file not found: $PRD_FILE"
return 1
fi
cat "$PRD_FILE"
fi
}
# ==========================================
# End Sanity Integration Functions
# ==========================================
# Check if current branch is protected
is_protected_branch() {
local current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
if [ -z "$current_branch" ]; then
return 1
fi
# Convert comma-separated list to array
IFS=',' read -ra PROTECTED <<< "$PROTECTED_BRANCHES"
for protected in "${PROTECTED[@]}"; do
# Trim whitespace
protected=$(echo "$protected" | xargs)
if [ "$current_branch" = "$protected" ]; then
return 0
fi
done
return 1
}
# Suggest creating a feature branch
suggest_feature_branch() {
local current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
echo ""
log_error "Cannot run Ralph on protected branch: $current_branch"
echo ""
log_info "Ralph prevents commits to protected branches for safety."
log_info "Protected branches: $PROTECTED_BRANCHES"
echo ""
log_info "To continue, create a feature branch:"
echo " git checkout -b feature/your-feature-name"
echo ""
log_info "Or override protection (not recommended):"
echo " PROTECTED_BRANCHES=\"\" $0"
echo ""
}
# Get next feature from PRD (highest priority incomplete feature with met dependencies)
get_next_feature_from_prd() {
# Get PRD data from file or Sanity
local prd_data=$(get_prd_data)
if [ $? -ne 0 ] || [ -z "$prd_data" ]; then
echo ""
return 1
fi
# Use Python to parse JSON and find next feature
echo "$prd_data" | python3 -c "
import json
import sys
try:
prd = json.load(sys.stdin)
features = prd.get('features', [])
# Priority order
priority_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}
# Filter to incomplete features with met dependencies
candidates = []
for feature in features:
if feature.get('passes', False):
continue
if feature.get('blocked_reason'):
continue
# Check dependencies
depends_on = feature.get('depends_on', [])
deps_met = True
for dep_id in depends_on:
dep_feature = next((f for f in features if f.get('id') == dep_id), None)
if not dep_feature or not dep_feature.get('passes', False):
deps_met = False
break
if deps_met:
candidates.append(feature)
if not candidates:
sys.exit(1)
# Sort by priority
candidates.sort(key=lambda f: (
priority_order.get(f.get('priority', 'low'), 99),
f.get('id', '')
))
# Output first candidate as JSON
print(json.dumps(candidates[0]))
except Exception as e:
sys.stderr.write(f'Error parsing PRD: {e}\n')
sys.exit(1)
" 2>/dev/null
}
# Generate branch name from feature
generate_branch_name() {
local feature_json="$1"
if [ -z "$feature_json" ]; then
# Fallback to generic name with timestamp
echo "feature/ralph-$(date +%Y%m%d-%H%M%S)"
return
fi
# Parse feature JSON
local feature_id=$(echo "$feature_json" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id', ''))")
local feature_type=$(echo "$feature_json" | python3 -c "import json,sys; print(json.load(sys.stdin).get('type', 'feature'))")
local feature_desc=$(echo "$feature_json" | python3 -c "import json,sys; print(json.load(sys.stdin).get('description', ''))")
# Determine branch prefix based on type
local prefix="feature"
case "$feature_type" in
bug) prefix="bugfix" ;;
refactor) prefix="refactor" ;;
test) prefix="test" ;;
feature|*) prefix="feature" ;;
esac
# Create slug from description (first few words, lowercase, dashes)
local slug=$(echo "$feature_desc" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9 ]//g' | tr -s ' ' | cut -d' ' -f1-4 | tr ' ' '-')
# Construct branch name
if [ -n "$feature_id" ] && [ -n "$slug" ]; then
echo "${prefix}/${feature_id}-${slug}"
elif [ -n "$feature_id" ]; then
echo "${prefix}/${feature_id}"
else
echo "${prefix}/ralph-$(date +%Y%m%d-%H%M%S)"
fi
}
# Auto-create and checkout feature branch
auto_create_feature_branch() {
local branch_name="$1"
if [ -z "$branch_name" ]; then
log_error "No branch name provided"
return 1
fi
log_info "Auto-creating feature branch: $branch_name"
if git show-ref --verify --quiet "refs/heads/$branch_name"; then
log_warning "Branch $branch_name already exists, checking out..."
git checkout "$branch_name"
else
log_info "Creating new branch from current HEAD..."
git checkout -b "$branch_name"
fi
log_success "Now on branch: $branch_name"
return 0
}
# Check prerequisites
check_prerequisites() {
log_info "Checking prerequisites..."
# Check required tools are installed
if ! check_required_tools; then
log_error "Missing required tools. Cannot continue."
exit 1
fi
# Check if on protected branch
if is_protected_branch; then
if [ "$AUTO_CREATE_BRANCH" = "true" ]; then
log_warning "Currently on protected branch: $(git rev-parse --abbrev-ref HEAD)"
echo ""
# Check if user provided custom branch name
if [ -n "$CUSTOM_BRANCH_NAME" ]; then
log_info "Using custom branch name: $CUSTOM_BRANCH_NAME"
auto_create_feature_branch "$CUSTOM_BRANCH_NAME" || {
suggest_feature_branch
exit 1
}
else
# Auto-detect next feature and create branch
log_info "AUTO_CREATE_BRANCH is enabled, inspecting PRD for next feature..."
local next_feature=$(get_next_feature_from_prd)
if [ -n "$next_feature" ]; then
local feature_id=$(echo "$next_feature" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id', 'unknown'))")
local feature_type=$(echo "$next_feature" | python3 -c "import json,sys; print(json.load(sys.stdin).get('type', 'feature'))")
local feature_desc=$(echo "$next_feature" | python3 -c "import json,sys; print(json.load(sys.stdin).get('description', ''))")
local feature_desc_short=$(echo "$next_feature" | python3 -c "import json,sys; d=json.load(sys.stdin).get('description', ''); print(d[:67] + '...' if len(d) > 70 else d)")
log_info "Next feature: [$feature_id] $feature_desc"
local branch_name=$(generate_branch_name "$next_feature")
log_info "Generated branch name: $branch_name"
echo ""
auto_create_feature_branch "$branch_name" || {
suggest_feature_branch
exit 1
}
# Display progress header after branch creation (Feature 028)
echo ""
display_progress_header "$feature_id" "$feature_type" "$feature_desc_short"
HEADER_DISPLAYED=true
else
log_warning "Could not determine next feature from PRD"
log_info "Creating generic feature branch..."
local fallback_branch="feature/ralph-$(date +%Y%m%d-%H%M%S)"
auto_create_feature_branch "$fallback_branch" || {
suggest_feature_branch
exit 1
}
# Display header without feature info
echo ""
display_progress_header "none" "none" "All features complete or blocked"
HEADER_DISPLAYED=true
fi
fi
echo ""
log_success "Branch created successfully! Ready to run Ralph."
echo ""
else
suggest_feature_branch
exit 1
fi
fi
if [ ! -f "$AGENT_PROMPT_FILE" ]; then
log_error "Agent prompt file not found: $AGENT_PROMPT_FILE"
exit 1
fi
# Check if .ralph directory exists
if [ ! -d ".ralph" ]; then
log_error ".ralph directory not found. Have you initialized the project?"
log_info "Run the initializer agent first, or create .ralph/ directory manually"
exit 1
fi
# Validate PRD storage configuration
if [ "$PRD_STORAGE" = "sanity" ]; then
log_info "PRD_STORAGE=sanity: Using Sanity CMS as source of truth"
if ! validate_sanity_config; then
log_error "Sanity configuration invalid"
exit 1
fi
# Test connection by fetching PRD
if ! get_prd_data > /dev/null; then
log_error "Failed to fetch PRD from Sanity"
exit 1
fi
log_success "Sanity connection verified"
else
# Default file-based storage
if [ ! -f "$PRD_FILE" ]; then
log_error "PRD file not found: $PRD_FILE"
exit 1
fi
fi
if [ ! -f "$PROGRESS_FILE" ]; then
log_warning "Progress file not found. Creating $PROGRESS_FILE"
touch "$PROGRESS_FILE"
echo "=== Ralph Wiggum Progress Log ===" > "$PROGRESS_FILE"
echo "Started: $(date)" >> "$PROGRESS_FILE"
echo "" >> "$PROGRESS_FILE"
fi
# Check if git repo exists
if [ ! -d ".git" ]; then
log_warning "No git repository found. Initializing..."
git init
git add .
git commit -m "Initial commit - Ralph Wiggum setup"
fi
# Select next feature and display progress header (Feature 028)
# This ensures header shows the actual feature that will be worked on
# Only do this if header wasn't already displayed in protected branch section
if [ -z "$HEADER_DISPLAYED" ]; then
local next_feature=$(get_next_feature_from_prd)
if [ -n "$next_feature" ]; then
local feature_id=$(echo "$next_feature" | python3 -c "import json,sys; print(json.load(sys.stdin).get('id', 'unknown'))")
local feature_type=$(echo "$next_feature" | python3 -c "import json,sys; print(json.load(sys.stdin).get('type', 'feature'))")
local feature_desc=$(echo "$next_feature" | python3 -c "import json,sys; d=json.load(sys.stdin).get('description', ''); print(d[:67] + '...' if len(d) > 70 else d)")
log_info "Next feature: [$feature_id] $feature_desc"
echo ""
# Display progress header with selected feature info
display_progress_header "$feature_id" "$feature_type" "$feature_desc"
else
log_info "No incomplete features found with met dependencies"
echo ""
# Display header without feature info (just stats)
display_progress_header "none" "none" "All features complete or blocked"
fi
fi
log_success "Prerequisites check complete"
}
# Health check command - verify Ralph setup and configuration
run_doctor() {
echo ""
echo "╔════════════════════════════════════════╗"
echo "║ Ralph Wiggum Health Check (Doctor) ║"
echo "╚════════════════════════════════════════╝"
echo ""
local all_checks_passed=true
# 1. Check required tools
log_info "1/7 Checking required tools..."
if check_required_tools; then
log_success "✓ All required tools are installed"
else
log_error "✗ Some required tools are missing"
all_checks_passed=false
fi
echo ""
# 2. Check git repository
log_info "2/7 Checking git repository..."
if [ -d ".git" ]; then
log_success "✓ Git repository exists"
local current_branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
if [ -n "$current_branch" ]; then
log_info " Current branch: $current_branch"
if is_protected_branch; then
log_warning " ⚠ You are on a protected branch: $current_branch"
log_info " Suggestion: Create a feature branch before running Ralph"
else
log_success " ✓ Branch is safe for commits"
fi
fi
else
log_error "✗ No git repository found"
log_info " Run: git init"
all_checks_passed=false
fi
echo ""
# 3. Check .ralph directory structure
log_info "3/7 Checking .ralph directory..."
if [ -d ".ralph" ]; then
log_success "✓ .ralph directory exists"
if [ -f "$PRD_FILE" ]; then
log_success " ✓ PRD file exists: $PRD_FILE"
# Validate PRD JSON structure
if python3 -c "import json; json.load(open('$PRD_FILE'))" 2>/dev/null; then
log_success " ✓ PRD file is valid JSON"
# Count features
local total_features=$(python3 -c "import json; prd=json.load(open('$PRD_FILE')); print(len(prd.get('features', [])))" 2>/dev/null)
local complete_features=$(python3 -c "import json; prd=json.load(open('$PRD_FILE')); print(sum(1 for f in prd.get('features', []) if f.get('passes', False)))" 2>/dev/null)
log_info " Features: $complete_features/$total_features complete"
else
log_error " ✗ PRD file is not valid JSON"
all_checks_passed=false
fi
else
log_error " ✗ PRD file not found: $PRD_FILE"
all_checks_passed=false
fi
if [ -f "$PROGRESS_FILE" ]; then
log_success " ✓ Progress file exists: $PROGRESS_FILE"
else