forked from snarktank/ralph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.sh
More file actions
1769 lines (1526 loc) · 57.9 KB
/
run.sh
File metadata and controls
1769 lines (1526 loc) · 57.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
# run.sh - Unified Ralph entry point
#
# Usage:
# .ralph/run.sh # Auto-detect mode, run
# .ralph/run.sh status # Rich status display
# .ralph/run.sh switch # Interactive plan switcher
# .ralph/run.sh --plan M1 --tool claude # Run specific masterplan
# .ralph/run.sh --tool claude --model sonnet 15 # Ralph mode with options
# .ralph/run.sh --plan M1 --start-phase 5 # Resume mega mode from phase
set -e
# ---------------------------------------------------------------------------
# Signal handling - ensure Ctrl-C kills everything
# ---------------------------------------------------------------------------
OUTFILE=""
CHILD_PID=""
# Kill the entire process tree rooted at a given PID
kill_tree() {
local pid="$1"
# Find all descendants (children, grandchildren, etc.)
local children
children=$(ps -o pid= --ppid "$pid" 2>/dev/null || true)
for child in $children; do
kill_tree "$child"
done
kill -TERM "$pid" 2>/dev/null || true
}
cleanup() {
echo ""
echo "Interrupted."
rm -f "$OUTFILE"
# Remove trap to avoid recursion
trap - INT TERM
# Kill tracked child and its entire process tree
if [[ -n "$CHILD_PID" ]]; then
kill_tree "$CHILD_PID"
fi
# Also kill our process group as a safety net
kill -- -$$ 2>/dev/null || kill 0 2>/dev/null || true
exit 130
}
trap cleanup INT TERM
# ---------------------------------------------------------------------------
# Path setup
# ---------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
STATE_DIR="$SCRIPT_DIR/current" # symlink to active state dir
PRD_FILE="$STATE_DIR/prd.json"
PROGRESS_FILE="$STATE_DIR/progress.txt"
LAST_BRANCH_FILE="$STATE_DIR/.last-branch"
ARCHIVE_DIR="$SCRIPT_DIR/archive"
PLANS_DIR="$PROJECT_ROOT/plans"
PRD_PROMPT_TEMPLATE="$SCRIPT_DIR/mega-claude-prompt.md"
CONVERT_PROMPT_TEMPLATE="$SCRIPT_DIR/mega-ralph-convert-prompt.md"
REFLECT_PROMPT_TEMPLATE="$SCRIPT_DIR/mega-ralph-reflect-prompt.md"
REVIEW_PROMPT_TMPL="$SCRIPT_DIR/review-prompt.md"
REVIEW_FIXES_PROMPT_TMPL="$SCRIPT_DIR/review-fixes-prompt.md"
PHASE_REVIEW_PROMPT_TMPL="$SCRIPT_DIR/phase-review-prompt.md"
# ---------------------------------------------------------------------------
# Help
# ---------------------------------------------------------------------------
show_help() {
echo "Usage: run.sh [SUBCOMMAND] [OPTIONS] [max_iterations]"
echo ""
echo "Subcommands:"
echo " status Show current plan status"
echo " switch Interactive plan switcher"
echo ""
echo "Options:"
echo " --plan M1|FILE Plan shorthand (M1) or file path"
echo " --start-phase N Resume mega mode from phase N (default: 1)"
echo " --max-iterations-per-phase N Max iterations per phase in mega mode (default: 25)"
echo " --tool amp|claude|codex AI tool to use (default: claude)"
echo " --model MODEL Model to use (e.g., sonnet, opus)"
echo " --base BRANCH Base branch for feature branches (skip interactive prompt)"
echo " --with-review Enable code review after each story and phase"
echo " --review-tool TOOL Tool for review (default: same as --tool)"
echo " --review-model MODEL Model for review (default: same as --model)"
echo " -h, --help Show this help"
echo ""
echo "When no --plan is given, auto-detects mode:"
echo " current/masterplan.json exists -> mega mode (resume)"
echo " current/prd.json exists -> ralph mode (iteration loop)"
exit 0
}
# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------
# Create branch from base if it doesn't exist, or switch to it if it does.
# No-op if already on correct branch.
git_ensure_branch() {
local branch="$1"
local base="$2"
local current
current=$(cd "$PROJECT_ROOT" && git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
if [[ "$current" == "$branch" ]]; then
return 0
fi
# Check if branch exists (local or remote)
if (cd "$PROJECT_ROOT" && git show-ref --verify --quiet "refs/heads/$branch" 2>/dev/null); then
echo " Switching to existing branch: $branch"
(cd "$PROJECT_ROOT" && git checkout "$branch")
elif (cd "$PROJECT_ROOT" && git show-ref --verify --quiet "refs/remotes/origin/$branch" 2>/dev/null); then
echo " Checking out remote branch: $branch"
(cd "$PROJECT_ROOT" && git checkout -b "$branch" "origin/$branch")
else
echo " Creating branch: $branch (from $base)"
(cd "$PROJECT_ROOT" && git checkout -b "$branch" "$base")
fi
}
# Checkout target, merge source with --no-ff, checkout back.
# On conflict: error with clear message and exit.
git_merge_branch() {
local source="$1"
local target="$2"
local current
current=$(cd "$PROJECT_ROOT" && git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")
echo " Merging $source → $target"
(cd "$PROJECT_ROOT" && git checkout "$target")
if ! (cd "$PROJECT_ROOT" && git merge --no-ff "$source" -m "merge: $source into $target"); then
echo ""
echo "Error: Merge conflict merging $source into $target"
echo "Resolve conflicts manually and re-run."
(cd "$PROJECT_ROOT" && git merge --abort 2>/dev/null || true)
(cd "$PROJECT_ROOT" && git checkout "$current" 2>/dev/null || true)
exit 1
fi
# Return to original branch if different
if [[ "$current" != "$target" ]]; then
(cd "$PROJECT_ROOT" && git checkout "$current")
fi
}
# ---------------------------------------------------------------------------
# Base branch selection
# ---------------------------------------------------------------------------
# Interactive prompt for base branch selection.
# Sets BASE_BRANCH global. Skipped if --base was provided.
prompt_base_branch() {
# If --base was given, use it directly
if [[ -n "${ARG_BASE_BRANCH:-}" ]]; then
BASE_BRANCH="$ARG_BASE_BRANCH"
echo " Base branch: $BASE_BRANCH (from --base)"
return
fi
# On resume, load from stored config
if [[ -n "${STORED_BASE_BRANCH:-}" ]]; then
BASE_BRANCH="$STORED_BASE_BRANCH"
echo " Base branch: $BASE_BRANCH (from saved config)"
return
fi
# Non-interactive (piped stdin): default to main
if [[ ! -t 0 ]]; then
BASE_BRANCH="main"
echo " Warning: Non-interactive mode, defaulting base branch to 'main'"
return
fi
# Interactive prompt
local current_branch
current_branch=$(cd "$PROJECT_ROOT" && git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "main")
echo ""
echo "Base branch for feature branches:"
echo " 1) main"
if [[ "$current_branch" != "main" ]]; then
echo " 2) $current_branch (current)"
echo " 3) develop"
echo " 4) other (enter branch name)"
echo ""
read -r -p "Select [1-4, default 1]: " selection
else
echo " 2) develop"
echo " 3) other (enter branch name)"
echo ""
read -r -p "Select [1-3, default 1]: " selection
fi
case "${selection:-1}" in
1)
BASE_BRANCH="main"
;;
2)
if [[ "$current_branch" != "main" ]]; then
BASE_BRANCH="$current_branch"
else
BASE_BRANCH="develop"
fi
;;
3)
if [[ "$current_branch" != "main" ]]; then
BASE_BRANCH="develop"
else
read -r -p "Enter branch name: " BASE_BRANCH
if [[ -z "$BASE_BRANCH" ]]; then
BASE_BRANCH="main"
fi
fi
;;
4)
read -r -p "Enter branch name: " BASE_BRANCH
if [[ -z "$BASE_BRANCH" ]]; then
BASE_BRANCH="main"
fi
;;
*)
BASE_BRANCH="main"
;;
esac
echo " Base branch: $BASE_BRANCH"
}
# ---------------------------------------------------------------------------
# Review turn runner
# ---------------------------------------------------------------------------
# Builds prompt from template with substitutions, invokes review tool.
# Non-fatal on failure (warning + continue).
#
# Usage: run_review_turn <template_file> <key1> <val1> [<key2> <val2> ...]
run_review_turn() {
local template_file="$1"
shift
if [[ ! -f "$template_file" ]]; then
echo " Warning: Review template not found: $template_file (skipping review)"
return 0
fi
local review_tool="${REVIEW_TOOL:-$TOOL}"
local review_model="${REVIEW_MODEL:-$MODEL}"
local review_model_args=""
if [[ -n "$review_model" ]]; then
review_model_args="--model $review_model"
fi
# Build prompt with key/value substitutions
local prompt_file
prompt_file=$(mktemp)
cp "$template_file" "$prompt_file"
while [[ $# -ge 2 ]]; do
local key="$1"
local val="$2"
shift 2
# Use sed for simple placeholder replacement
# Escape sed special chars in val
local escaped_val
escaped_val=$(printf '%s\n' "$val" | sed 's/[&/\]/\\&/g')
sed -i "s|${key}|${escaped_val}|g" "$prompt_file"
done
# Ensure reviews directory exists
mkdir -p "$STATE_DIR/reviews"
echo " Running review ($review_tool)..."
local exit_code=0
if [[ "$review_tool" == "amp" ]]; then
amp --dangerously-allow-all < "$prompt_file" >/dev/null 2>&1 &
elif [[ "$review_tool" == "codex" ]]; then
local codex_model_args=""
if [[ -n "$review_model" ]]; then
codex_model_args="--model $review_model"
fi
codex exec --full-auto $codex_model_args - < "$prompt_file" >/dev/null 2>&1 &
else
claude --dangerously-skip-permissions $review_model_args --print < "$prompt_file" >/dev/null 2>&1 &
fi
CHILD_PID=$!
wait $CHILD_PID 2>/dev/null || exit_code=$?
CHILD_PID=""
rm -f "$prompt_file"
if [[ $exit_code -ne 0 ]]; then
echo " Warning: Review failed (exit code $exit_code). Continuing without review."
return 0
fi
}
# ═══════════════════════════════════════════════════════════════════════════
# STATUS SUBCOMMAND
# ═══════════════════════════════════════════════════════════════════════════
do_status() {
echo ""
echo "Ralph Status"
echo "════════════════════════════════════════════"
echo ""
# Check if current symlink exists
if [[ ! -L "$SCRIPT_DIR/current" ]]; then
echo " No active plan. Use /ralph or /masterplan skill to set one up."
echo ""
echo "════════════════════════════════════════════"
exit 0
fi
# Determine plan ID from symlink target
CURRENT_TARGET=$(readlink "$SCRIPT_DIR/current" 2>/dev/null || echo "")
PLAN_ID=$(basename "$CURRENT_TARGET")
# Read masterplan.json if exists (for mega-ralph plans)
MASTERPLAN_FILE="$STATE_DIR/masterplan.json"
if [[ -f "$MASTERPLAN_FILE" ]]; then
PLAN_NAME=$(jq -r '.project // "Unknown"' "$MASTERPLAN_FILE" 2>/dev/null || echo "Unknown")
TOTAL_PHASES=$(jq -r '.totalPhases // "?"' "$MASTERPLAN_FILE" 2>/dev/null || echo "?")
CURRENT_PHASE=$(jq -r '.currentPhase // "?"' "$MASTERPLAN_FILE" 2>/dev/null || echo "?")
PHASE_TITLE=$(jq -r --argjson p "${CURRENT_PHASE}" \
'(.phases[] | select(.phase == $p) | .title) // "Unknown"' \
"$MASTERPLAN_FILE" 2>/dev/null || echo "Unknown")
echo " Active Plan: $PLAN_ID - $PLAN_NAME"
echo " Phase: $CURRENT_PHASE of $TOTAL_PHASES ($PHASE_TITLE)"
else
echo " Active Plan: $PLAN_ID (standalone)"
fi
# Read branch from prd.json
if [[ -f "$PRD_FILE" ]]; then
BRANCH=$(jq -r '.branchName // "unknown"' "$PRD_FILE" 2>/dev/null || echo "unknown")
echo " Branch: $BRANCH"
fi
echo ""
# Stories status
if [[ -f "$PRD_FILE" ]]; then
TOTAL_STORIES=$(jq '.userStories | length' "$PRD_FILE" 2>/dev/null || echo "0")
DONE_STORIES=$(jq '[.userStories[] | select(.passes == true)] | length' "$PRD_FILE" 2>/dev/null || echo "0")
FIRST_PENDING=$(jq -r '[.userStories[] | select(.passes == false)][0].id // empty' "$PRD_FILE" 2>/dev/null || echo "")
echo " Stories: $DONE_STORIES/$TOTAL_STORIES complete"
# List each story with status marker
jq -r --arg pending "$FIRST_PENDING" '.userStories[] |
if .passes == true then " \u2713 \(.id) \(.title)"
elif .id == $pending then " \u2192 \(.id) \(.title)"
else " \u00b7 \(.id) \(.title)"
end' "$PRD_FILE" 2>/dev/null
else
echo " Stories: No prd.json found"
fi
echo ""
# Last commit
LAST_COMMIT=$(cd "$PROJECT_ROOT" && git log --oneline -1 2>/dev/null || echo "(no commits)")
LAST_TIME=$(cd "$PROJECT_ROOT" && git log -1 --format='%ar' 2>/dev/null || echo "")
echo " Last Commit: $LAST_COMMIT${LAST_TIME:+ ($LAST_TIME)}"
# Progress file location
echo " Progress: $STATE_DIR/progress.txt"
echo ""
echo "════════════════════════════════════════════"
exit 0
}
# ═══════════════════════════════════════════════════════════════════════════
# SWITCH SUBCOMMAND
# ═══════════════════════════════════════════════════════════════════════════
do_switch() {
echo ""
echo "Ralph Plans"
echo "════════════════════════════════════════════"
echo ""
# Find all state directories
local state_dirs=()
local plan_ids=()
local plan_names=()
local plan_progress=()
if [[ ! -d "$SCRIPT_DIR/state" ]]; then
echo " No plans found. Use /ralph or /masterplan skill to create one."
echo ""
exit 0
fi
local current_target=""
if [[ -L "$SCRIPT_DIR/current" ]]; then
current_target=$(readlink "$SCRIPT_DIR/current" 2>/dev/null || echo "")
current_target=$(basename "$current_target")
fi
local idx=0
for dir in "$SCRIPT_DIR"/state/*/; do
[[ -d "$dir" ]] || continue
local plan_id
plan_id=$(basename "$dir")
plan_ids+=("$plan_id")
state_dirs+=("$dir")
# Get plan name and progress
local name="" progress_str=""
if [[ -f "$dir/masterplan.json" ]]; then
name=$(jq -r '.project // ""' "$dir/masterplan.json" 2>/dev/null || echo "")
local total completed
total=$(jq -r '.totalPhases // 0' "$dir/masterplan.json" 2>/dev/null || echo "0")
completed=$(jq '[.phases[] | select(.status == "completed")] | length' "$dir/masterplan.json" 2>/dev/null || echo "0")
progress_str="Phase $completed/$total"
elif [[ -f "$dir/prd.json" ]]; then
name=$(jq -r '.description // ""' "$dir/prd.json" 2>/dev/null || echo "")
# Truncate long descriptions
if [[ ${#name} -gt 40 ]]; then
name="${name:0:37}..."
fi
local total done_count
total=$(jq '.userStories | length' "$dir/prd.json" 2>/dev/null || echo "0")
done_count=$(jq '[.userStories[] | select(.passes == true)] | length' "$dir/prd.json" 2>/dev/null || echo "0")
if [[ "$done_count" -eq "$total" && "$total" -gt 0 ]]; then
progress_str="complete"
elif [[ "$done_count" -eq 0 ]]; then
progress_str="not started"
else
progress_str="$done_count/$total stories"
fi
else
progress_str="empty"
fi
plan_names+=("$name")
plan_progress+=("$progress_str")
idx=$((idx + 1))
done
if [[ ${#plan_ids[@]} -eq 0 ]]; then
echo " No plans found."
echo ""
exit 0
fi
# Display plans
for i in "${!plan_ids[@]}"; do
local marker=" "
if [[ "${plan_ids[$i]}" == "$current_target" ]]; then
marker="→ "
fi
local num=$((i + 1))
local display="${plan_ids[$i]}"
if [[ -n "${plan_names[$i]}" ]]; then
display="$display ${plan_names[$i]}"
fi
if [[ -n "${plan_progress[$i]}" ]]; then
display="$display (${plan_progress[$i]})"
fi
printf " %d. %s%s\n" "$num" "$marker" "$display"
done
echo ""
# Prompt for selection
read -r -p "Select plan [1-${#plan_ids[@]}]: " selection
if [[ -z "$selection" ]]; then
echo "No selection made."
exit 0
fi
if [[ ! "$selection" =~ ^[0-9]+$ ]] || [[ "$selection" -lt 1 ]] || [[ "$selection" -gt ${#plan_ids[@]} ]]; then
echo "Invalid selection."
exit 1
fi
local selected_idx=$((selection - 1))
local selected_id="${plan_ids[$selected_idx]}"
ln -sfn "state/$selected_id" "$SCRIPT_DIR/current"
echo ""
echo "Switched to $selected_id${plan_names[$selected_idx]:+ (${plan_names[$selected_idx]})}"
exit 0
}
# ═══════════════════════════════════════════════════════════════════════════
# RALPH MODE — iteration loop
# ═══════════════════════════════════════════════════════════════════════════
run_ralph() {
local max_iterations="$1"
local tool="$2"
local model="$3"
# Build model args for claude/codex CLI
local claude_model_args=""
local codex_model_args=""
if [[ -n "$model" ]]; then
claude_model_args="--model $model"
codex_model_args="--model $model"
fi
# Ensure state directory exists (via current symlink)
if [[ ! -L "$SCRIPT_DIR/current" ]]; then
mkdir -p "$SCRIPT_DIR/state/default"
ln -sfn "state/default" "$SCRIPT_DIR/current"
fi
# Ensure the target of current exists
mkdir -p "$STATE_DIR"
# Branch setup for standalone ralph mode (not called from run_mega)
if [[ -z "${PLAN_ID:-}" ]]; then
# Load stored base branch if resuming
local branch_config="$STATE_DIR/.branch-config"
if [[ -f "$branch_config" ]]; then
STORED_BASE_BRANCH=$(grep '^base=' "$branch_config" 2>/dev/null | cut -d= -f2)
fi
prompt_base_branch
# Save branch config for resume
echo "base=$BASE_BRANCH" > "$branch_config"
# Set up the feature branch if prd.json has a branchName
if [[ -f "$PRD_FILE" ]]; then
local feature_branch
feature_branch=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "")
if [[ -n "$feature_branch" ]]; then
git_ensure_branch "$feature_branch" "$BASE_BRANCH"
fi
fi
fi
# Archive previous run if branch changed
if [ -f "$PRD_FILE" ] && [ -f "$LAST_BRANCH_FILE" ]; then
local current_branch last_branch
current_branch=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "")
last_branch=$(cat "$LAST_BRANCH_FILE" 2>/dev/null || echo "")
if [ -n "$current_branch" ] && [ -n "$last_branch" ] && [ "$current_branch" != "$last_branch" ]; then
local date_str folder_name archive_folder
date_str=$(date +%Y-%m-%d)
folder_name=$(echo "$last_branch" | sed 's|^feat/||' | sed 's|^ralph/||')
archive_folder="$ARCHIVE_DIR/$date_str-$folder_name"
echo "Archiving previous run: $last_branch"
mkdir -p "$archive_folder"
[ -f "$PRD_FILE" ] && cp "$PRD_FILE" "$archive_folder/"
[ -f "$PROGRESS_FILE" ] && cp "$PROGRESS_FILE" "$archive_folder/"
echo " Archived to: $archive_folder"
echo "# Ralph Progress Log" > "$PROGRESS_FILE"
echo "Started: $(date)" >> "$PROGRESS_FILE"
echo "---" >> "$PROGRESS_FILE"
fi
fi
# Track current branch
if [ -f "$PRD_FILE" ]; then
local current_branch
current_branch=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "")
if [ -n "$current_branch" ]; then
echo "$current_branch" > "$LAST_BRANCH_FILE"
fi
fi
# Initialize progress file if it doesn't exist
if [ ! -f "$PROGRESS_FILE" ]; then
echo "# Ralph Progress Log" > "$PROGRESS_FILE"
echo "Started: $(date)" >> "$PROGRESS_FILE"
echo "---" >> "$PROGRESS_FILE"
fi
if [[ -n "$model" ]]; then
echo "Starting Ralph - Tool: $tool - Model: $model - Max iterations: $max_iterations"
else
echo "Starting Ralph - Tool: $tool - Max iterations: $max_iterations"
fi
if [[ "${WITH_REVIEW:-false}" == "true" ]]; then
echo " Review: enabled (tool: ${REVIEW_TOOL:-$tool}, model: ${REVIEW_MODEL:-${model:-default}})"
fi
echo "Interjection: echo 'your notes' > $STATE_DIR/interjection.md"
# Exponential backoff settings
local backoff=5
local max_backoff=300
# Review templates
local REVIEW_PROMPT_TEMPLATE="$SCRIPT_DIR/review-prompt.md"
local REVIEW_FIXES_PROMPT_TEMPLATE="$SCRIPT_DIR/review-fixes-prompt.md"
for i in $(seq 1 "$max_iterations"); do
echo ""
echo "==============================================================="
echo " Ralph Iteration $i of $max_iterations ($tool)"
echo "==============================================================="
# Snapshot passed stories before iteration (for review detection)
local pre_passed_ids=""
if [[ "${WITH_REVIEW:-false}" == "true" && -f "$PRD_FILE" ]]; then
pre_passed_ids=$(jq -r '[.userStories[] | select(.passes == true) | .id] | join(",")' "$PRD_FILE" 2>/dev/null || echo "")
fi
# Check for interjection file
local interjection_file="$STATE_DIR/interjection.md"
local interjection=""
if [[ -f "$interjection_file" ]] && [[ -s "$interjection_file" ]]; then
interjection=$(cat "$interjection_file")
echo ""
echo " ** Interjection detected — incorporating user notes **"
echo ""
> "$interjection_file"
fi
# Build the prompt
local prompt_file
prompt_file=$(mktemp)
local base_prompt
if [[ "$tool" == "amp" ]]; then
base_prompt="$SCRIPT_DIR/prompt.md"
else
base_prompt="$SCRIPT_DIR/CLAUDE.md"
fi
if [[ -n "$interjection" ]]; then
printf '## IMPORTANT — User Interjection\n\nThe user has added the following notes before this iteration. Take these into account and prioritize them:\n\n%s\n\n---\n\n' "$interjection" > "$prompt_file"
cat "$base_prompt" >> "$prompt_file"
else
cp "$base_prompt" "$prompt_file"
fi
# Run the tool
local exit_code=0
if [[ "$tool" == "amp" ]]; then
amp --dangerously-allow-all < "$prompt_file" >/dev/null 2>&1 &
elif [[ "$tool" == "codex" ]]; then
codex exec --full-auto $codex_model_args - < "$prompt_file" >/dev/null 2>&1 &
else
claude --dangerously-skip-permissions $claude_model_args --print < "$prompt_file" >/dev/null 2>&1 &
fi
CHILD_PID=$!
wait $CHILD_PID 2>/dev/null || exit_code=$?
CHILD_PID=""
rm -f "$prompt_file"
# Exit immediately on SIGINT/SIGTERM
if [[ $exit_code -eq 130 || $exit_code -eq 143 ]]; then
echo ""
echo "Interrupted."
exit $exit_code
fi
# Check if all stories are done by reading prd.json directly
if [[ -f "$PRD_FILE" ]]; then
local remaining
remaining=$(jq '[.userStories[] | select(.passes == false)] | length' "$PRD_FILE" 2>/dev/null || echo "1")
if [[ "$remaining" -eq 0 ]]; then
echo ""
echo "Ralph completed all tasks!"
echo "Completed at iteration $i of $max_iterations"
return 0
fi
fi
# Check for errors and apply exponential backoff
if [[ $exit_code -ne 0 ]]; then
echo ""
echo "Error on iteration $i (exit code $exit_code). Retrying in ${backoff}s..."
sleep "$backoff"
backoff=$((backoff * 2))
if [[ $backoff -gt $max_backoff ]]; then
backoff=$max_backoff
fi
continue
fi
# Reset backoff on success
backoff=5
# Per-story review: detect if a new story passed in this iteration
if [[ "${WITH_REVIEW:-false}" == "true" && -f "$PRD_FILE" && -f "$REVIEW_PROMPT_TEMPLATE" ]]; then
local post_passed_ids
post_passed_ids=$(jq -r '[.userStories[] | select(.passes == true) | .id] | join(",")' "$PRD_FILE" 2>/dev/null || echo "")
if [[ "$post_passed_ids" != "$pre_passed_ids" ]]; then
# Find newly passed story IDs
local new_ids=""
IFS=',' read -ra post_arr <<< "$post_passed_ids"
IFS=',' read -ra pre_arr <<< "$pre_passed_ids"
for pid in "${post_arr[@]}"; do
local found=false
for ppid in "${pre_arr[@]}"; do
if [[ "$pid" == "$ppid" ]]; then
found=true
break
fi
done
if [[ "$found" == "false" && -n "$pid" ]]; then
new_ids="$pid"
break # Review the first newly passed story
fi
done
if [[ -n "$new_ids" ]]; then
local story_title
story_title=$(jq -r --arg id "$new_ids" '.userStories[] | select(.id == $id) | .title' "$PRD_FILE" 2>/dev/null || echo "")
local review_doc="$STATE_DIR/reviews/review-${new_ids}.md"
echo ""
echo " ── Per-story review: $new_ids ──"
# Review turn
run_review_turn "$REVIEW_PROMPT_TEMPLATE" \
"{{STORY_ID}}" "$new_ids" \
"{{STORY_TITLE}}" "$story_title" \
"{{REVIEW_DOC_PATH}}" "$review_doc"
# Fixes turn (only if review doc was created)
if [[ -f "$review_doc" ]] && grep -q "NEEDS-FIXES" "$review_doc" 2>/dev/null; then
echo " Review verdict: NEEDS-FIXES — running fixes..."
run_review_turn "$REVIEW_FIXES_PROMPT_TEMPLATE" \
"{{STORY_ID}}" "$new_ids" \
"{{REVIEW_DOC_PATH}}" "$review_doc"
elif [[ -f "$review_doc" ]]; then
echo " Review verdict: PASS"
fi
echo " ── Review complete ──"
echo ""
fi
fi
fi
echo "Iteration $i complete. Continuing..."
sleep 2
done
echo ""
echo "Ralph reached max iterations ($max_iterations) without completing all tasks."
echo "Check $PROGRESS_FILE for status."
return 1
}
# ═══════════════════════════════════════════════════════════════════════════
# MEGA MODE — multi-phase orchestrator
# ═══════════════════════════════════════════════════════════════════════════
# ---------------------------------------------------------------------------
# Parse the master plan to extract phases
# ---------------------------------------------------------------------------
parse_phases() {
local plan_file="$1"
local phases_json="[]"
local current_phase=""
local current_title=""
local current_desc=""
local in_phase=false
while IFS= read -r line || [[ -n "$line" ]]; do
if [[ "$line" =~ ^##[[:space:]]+[Pp]hase[[:space:]]+([0-9]+)[[:space:]]*[:.]+[[:space:]]*(.*)|^##[[:space:]]+[Pp]hase[[:space:]]+([0-9]+)[[:space:]]*[-]+[[:space:]]+(.*) ]]; then
if [[ -n "${BASH_REMATCH[1]}" ]]; then
_phase="${BASH_REMATCH[1]}"
_title="${BASH_REMATCH[2]}"
else
_phase="${BASH_REMATCH[3]}"
_title="${BASH_REMATCH[4]}"
fi
if $in_phase && [[ -n "$current_phase" ]]; then
current_desc=$(echo "$current_desc" | sed 's/[[:space:]]*$//')
phases_json=$(echo "$phases_json" | jq \
--arg num "$current_phase" \
--arg title "$current_title" \
--arg desc "$current_desc" \
'. + [{"phase": ($num | tonumber), "title": $title, "description": $desc}]')
fi
current_phase="$_phase"
current_title="$_title"
current_desc=""
in_phase=true
elif $in_phase; then
if [[ -n "$current_desc" ]]; then
current_desc="$current_desc
$line"
else
if [[ -n "$line" ]]; then
current_desc="$line"
fi
fi
fi
done < "$plan_file"
if $in_phase && [[ -n "$current_phase" ]]; then
current_desc=$(echo "$current_desc" | sed 's/[[:space:]]*$//')
phases_json=$(echo "$phases_json" | jq \
--arg num "$current_phase" \
--arg title "$current_title" \
--arg desc "$current_desc" \
'. + [{"phase": ($num | tonumber), "title": $title, "description": $desc}]')
fi
echo "$phases_json"
}
# ---------------------------------------------------------------------------
# Initialize or load masterplan.json
# ---------------------------------------------------------------------------
init_progress() {
local total_phases="$1"
local project_name
project_name=$(basename "$PROJECT_ROOT" | sed 's/[^a-zA-Z0-9_-]/-/g')
if [[ -f "$MEGA_PROGRESS" ]]; then
echo "Resuming from existing masterplan.json"
return
fi
cat > "$MEGA_PROGRESS" <<EOJSON
{
"project": "$project_name",
"masterPlan": "$(basename "$PLAN_PATH")",
"totalPhases": $total_phases,
"currentPhase": $START_PHASE,
"phases": []
}
EOJSON
echo "Created masterplan.json for $total_phases phases"
}
# ---------------------------------------------------------------------------
# Update masterplan.json
# ---------------------------------------------------------------------------
update_progress_start() {
local phase_num="$1"
local phase_title="$2"
local branch_name="$3"
local started_at
started_at=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
local existing
existing=$(jq --argjson p "$phase_num" '.phases[] | select(.phase == $p)' "$MEGA_PROGRESS" 2>/dev/null || echo "")
if [[ -n "$existing" ]]; then
jq --argjson p "$phase_num" \
--arg status "in_progress" \
--arg started "$started_at" \
--arg branch "$branch_name" \
'(.phases[] | select(.phase == $p)) |= . + {
"status": $status,
"startedAt": $started,
"branch": $branch
} | .currentPhase = $p' "$MEGA_PROGRESS" > "$MEGA_PROGRESS.tmp" && mv "$MEGA_PROGRESS.tmp" "$MEGA_PROGRESS"
else
jq --argjson p "$phase_num" \
--arg title "$phase_title" \
--arg status "in_progress" \
--arg started "$started_at" \
--arg branch "$branch_name" \
'.phases += [{
"phase": $p,
"title": $title,
"status": $status,
"startedAt": $started,
"completedAt": null,
"iterations": 0,
"branch": $branch
}] | .currentPhase = $p' "$MEGA_PROGRESS" > "$MEGA_PROGRESS.tmp" && mv "$MEGA_PROGRESS.tmp" "$MEGA_PROGRESS"
fi
}
update_progress_complete() {
local phase_num="$1"
local iterations="$2"
local completed_at
completed_at=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
jq --argjson p "$phase_num" \
--arg status "completed" \
--arg completed "$completed_at" \
--argjson iters "$iterations" \
'(.phases[] | select(.phase == $p)) |= . + {
"status": $status,
"completedAt": $completed,
"iterations": $iters
}' "$MEGA_PROGRESS" > "$MEGA_PROGRESS.tmp" && mv "$MEGA_PROGRESS.tmp" "$MEGA_PROGRESS"
}
update_progress_failed() {
local phase_num="$1"
local iterations="$2"
jq --argjson p "$phase_num" \
--arg status "failed" \
--argjson iters "$iterations" \
'(.phases[] | select(.phase == $p)) |= . + {
"status": $status,
"iterations": $iters
}' "$MEGA_PROGRESS" > "$MEGA_PROGRESS.tmp" && mv "$MEGA_PROGRESS.tmp" "$MEGA_PROGRESS"
}
# ---------------------------------------------------------------------------
# Get previous phases summary
# ---------------------------------------------------------------------------
get_previous_phases_summary() {
local current_phase="$1"
local summary=""
if [[ "$current_phase" -le 1 ]]; then
echo "This is the first phase. No previous phases."
return
fi
local completed_phases
completed_phases=$(jq -r --argjson p "$current_phase" \
'.phases[] | select(.phase < $p and .status == "completed") | "Phase \(.phase): \(.title) [branch: \(.branch)]"' \
"$MEGA_PROGRESS" 2>/dev/null || echo "")
if [[ -n "$completed_phases" ]]; then
summary="Completed phases:
$completed_phases
"
fi
local git_log
git_log=$(cd "$PROJECT_ROOT" && git log --oneline -30 2>/dev/null || echo "(no git history available)")
if [[ -n "$git_log" ]]; then
summary="${summary}
Recent git history:
$git_log"
fi
echo "$summary"
}
# ---------------------------------------------------------------------------
# Generate a branch name from phase number and title
# ---------------------------------------------------------------------------
make_branch_name() {
local phase_num="$1"
local phase_title="$2"
local slug
slug=$(echo "$phase_title" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//')
# In mega mode: feat/M<idx>-P<padded>-<slug>
# In ralph mode: feat/<slug>
if [[ -n "${PLAN_ID:-}" ]]; then
printf "feat/%s-P%02d-%s" "$PLAN_ID" "$phase_num" "$slug"
else
printf "feat/%s" "$slug"
fi
}
# Generate the top-level mega feature branch name
make_mega_branch_name() {
local plan_idx="$1"
local project_name="$2"
local slug
slug=$(echo "$project_name" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/--*/-/g' | sed 's/^-//' | sed 's/-$//')
printf "feat/M%s-%s" "$plan_idx" "$slug"
}
# ---------------------------------------------------------------------------
# Build a prompt by replacing placeholders in a template
# ---------------------------------------------------------------------------
build_prompt() {
local template_file="$1"
local phase_number="$2"
local phase_title="$3"
local phase_description="$4"
local previous_summary="$5"
local project_name="$6"
local prd_file="${7:-}"
local prd_filename="${8:-}"
local branch_name="${9:-}"
local output_file
output_file=$(mktemp)
local plan_file_tmp desc_file summary_file prd_file_tmp
plan_file_tmp=$(mktemp)
desc_file=$(mktemp)
summary_file=$(mktemp)
prd_file_tmp=$(mktemp)
cat "$PLAN_PATH" > "$plan_file_tmp"