-
Notifications
You must be signed in to change notification settings - Fork 325
Expand file tree
/
Copy pathralphy.sh
More file actions
executable file
·3154 lines (2701 loc) · 96 KB
/
ralphy.sh
File metadata and controls
executable file
·3154 lines (2701 loc) · 96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# ============================================
# Ralphy - Autonomous AI Coding Loop
# Supports Claude Code, OpenCode, Codex, Cursor, Qwen-Code and Factory Droid
# Runs until PRD is complete
# ============================================
set -euo pipefail
# ============================================
# CONFIGURATION & DEFAULTS
# ============================================
VERSION="4.3.0"
# Ralphy config directory
RALPHY_DIR=".ralphy"
PROGRESS_FILE="$RALPHY_DIR/progress.txt"
CONFIG_FILE="$RALPHY_DIR/config.yaml"
SINGLE_TASK=""
INIT_MODE=false
SHOW_CONFIG=false
ADD_RULE=""
AUTO_COMMIT=true
# Runtime options
SKIP_TESTS=false
SKIP_LINT=false
AI_ENGINE="claude" # claude, opencode, cursor, codex, qwen, droid, or copilot
MODEL_OVERRIDE="" # Override default model for any engine (e.g., "sonnet", "gpt-4o-mini")
DRY_RUN=false
MAX_ITERATIONS=0 # 0 = unlimited
MAX_RETRIES=3
RETRY_DELAY=5
VERBOSE=false
# Git branch options
BRANCH_PER_TASK=false
CREATE_PR=false
BASE_BRANCH=""
PR_DRAFT=false
# Parallel execution
PARALLEL=false
MAX_PARALLEL=3
# PRD source options
PRD_SOURCE="markdown" # markdown, yaml, github
PRD_FILE="PRD.md"
GITHUB_REPO=""
GITHUB_LABEL=""
SYNC_ISSUE="" # GitHub issue number to sync PRD with
# Browser automation (agent-browser)
BROWSER_ENABLED="auto" # auto, true, false
# Colors (detect if terminal supports colors)
if [[ -t 1 ]] && command -v tput &>/dev/null && [[ $(tput colors 2>/dev/null || echo 0) -ge 8 ]]; then
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
BOLD=$(tput bold)
DIM=$(tput dim)
RESET=$(tput sgr0)
else
RED="" GREEN="" YELLOW="" BLUE="" MAGENTA="" CYAN="" BOLD="" DIM="" RESET=""
fi
# Global state
ai_pid=""
monitor_pid=""
tmpfile=""
CODEX_LAST_MESSAGE_FILE=""
current_step="Thinking"
total_input_tokens=0
total_output_tokens=0
total_actual_cost="0" # OpenCode provides actual cost
total_duration_ms=0 # Cursor provides duration
iteration=0
retry_count=0
declare -a parallel_pids=()
declare -a task_branches=()
declare -a integration_branches=() # Track integration branches for cleanup on interrupt
WORKTREE_BASE="" # Base directory for parallel agent worktrees
ORIGINAL_DIR="" # Original working directory (for worktree operations)
ORIGINAL_BASE_BRANCH="" # Original base branch before integration branches
# ============================================
# UTILITY FUNCTIONS
# ============================================
log_info() {
echo "${BLUE}[INFO]${RESET} $*"
}
log_success() {
echo "${GREEN}[OK]${RESET} $*"
}
log_warn() {
echo "${YELLOW}[WARN]${RESET} $*"
}
log_error() {
echo "${RED}[ERROR]${RESET} $*" >&2
}
log_debug() {
if [[ "$VERBOSE" == true ]]; then
echo "${DIM}[DEBUG] $*${RESET}"
fi
}
# Slugify text for branch names
slugify() {
echo "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g' | sed -E 's/^-|-$//g' | cut -c1-50
}
# Check if agent-browser is available
is_browser_available() {
if [[ "$BROWSER_ENABLED" == "false" ]]; then
return 1
fi
if [[ "$BROWSER_ENABLED" == "true" ]]; then
if ! command -v agent-browser &>/dev/null; then
log_warn "--browser flag used but agent-browser CLI not found"
log_warn "Install from: https://agent-browser.dev"
return 1
fi
return 0
fi
# auto mode: check if available
command -v agent-browser &>/dev/null
}
# Get browser instructions for prompt injection
get_browser_instructions() {
if ! is_browser_available; then
return
fi
cat << 'BROWSER_EOF'
## Browser Automation (agent-browser)
You have access to browser automation via the `agent-browser` CLI.
**Key Commands:**
- `agent-browser open <url>` - Open a URL in the browser
- `agent-browser snapshot` - Get accessibility tree with element refs (@e1, @e2, etc.)
- `agent-browser click @e1` - Click an element by reference
- `agent-browser type @e1 "text"` - Type text into an input field
- `agent-browser screenshot <file.png>` - Capture screenshot
- `agent-browser content` - Get page text content
- `agent-browser close` - Close browser session
**Workflow:**
1. Use `open` to navigate to a URL
2. Use `snapshot` to see available elements (returns refs like @e1, @e2)
3. Use `click`/`type` with element refs to interact
4. Use `screenshot` for visual verification
**Use browser automation for:**
- Testing web UI after implementing features
- Verifying deployments
- Filling forms or checking workflows
- Visual regression testing
BROWSER_EOF
}
# ============================================
# BROWNFIELD MODE (.ralphy/ configuration)
# ============================================
# Initialize .ralphy/ directory with config files
init_ralphy_config() {
if [[ -d "$RALPHY_DIR" ]]; then
log_warn "$RALPHY_DIR already exists"
REPLY='N' # Default if read times out or fails
read -p "Overwrite config? [y/N] " -n 1 -r -t 30 2>/dev/null || true
echo
[[ ! $REPLY =~ ^[Yy]$ ]] && exit 0
fi
mkdir -p "$RALPHY_DIR"
# Smart detection
local project_name=""
local lang=""
local framework=""
local test_cmd=""
local lint_cmd=""
local build_cmd=""
# Get project name from directory or package.json
project_name=$(basename "$PWD")
if [[ -f "package.json" ]]; then
# Get name from package.json if available
local pkg_name
pkg_name=$(jq -r '.name // ""' package.json 2>/dev/null)
[[ -n "$pkg_name" ]] && project_name="$pkg_name"
# Detect language
if [[ -f "tsconfig.json" ]]; then
lang="TypeScript"
else
lang="JavaScript"
fi
# Detect frameworks from dependencies (collect all matches)
local deps frameworks=()
deps=$(jq -r '(.dependencies // {}) + (.devDependencies // {}) | keys[]' package.json 2>/dev/null || true)
# Use grep for reliable exact matching
echo "$deps" | grep -qx "next" && frameworks+=("Next.js")
echo "$deps" | grep -qx "nuxt" && frameworks+=("Nuxt")
echo "$deps" | grep -qx "@remix-run/react" && frameworks+=("Remix")
echo "$deps" | grep -qx "svelte" && frameworks+=("Svelte")
echo "$deps" | grep -qE "@nestjs/" && frameworks+=("NestJS")
echo "$deps" | grep -qx "hono" && frameworks+=("Hono")
echo "$deps" | grep -qx "fastify" && frameworks+=("Fastify")
echo "$deps" | grep -qx "express" && frameworks+=("Express")
# Only add React/Vue if no meta-framework detected
if [[ ${#frameworks[@]} -eq 0 ]]; then
echo "$deps" | grep -qx "react" && frameworks+=("React")
echo "$deps" | grep -qx "vue" && frameworks+=("Vue")
fi
# Join frameworks with comma
framework=$(IFS=', '; echo "${frameworks[*]}")
# Detect commands from package.json scripts
local scripts
scripts=$(jq -r '.scripts // {}' package.json 2>/dev/null)
# Test command (prefer bun if lockfile exists)
if echo "$scripts" | jq -e '.test' >/dev/null 2>&1; then
test_cmd="npm test"
[[ -f "bun.lockb" ]] && test_cmd="bun test"
fi
# Lint command
if echo "$scripts" | jq -e '.lint' >/dev/null 2>&1; then
lint_cmd="npm run lint"
fi
# Build command
if echo "$scripts" | jq -e '.build' >/dev/null 2>&1; then
build_cmd="npm run build"
fi
elif [[ -f "pyproject.toml" ]] || [[ -f "requirements.txt" ]] || [[ -f "setup.py" ]]; then
lang="Python"
local py_frameworks=()
local py_deps=""
[[ -f "pyproject.toml" ]] && py_deps=$(cat pyproject.toml 2>/dev/null)
[[ -f "requirements.txt" ]] && py_deps+=$(cat requirements.txt 2>/dev/null)
echo "$py_deps" | grep -qi "fastapi" && py_frameworks+=("FastAPI")
echo "$py_deps" | grep -qi "django" && py_frameworks+=("Django")
echo "$py_deps" | grep -qi "flask" && py_frameworks+=("Flask")
framework=$(IFS=', '; echo "${py_frameworks[*]}")
test_cmd="pytest"
lint_cmd="ruff check ."
elif [[ -f "go.mod" ]]; then
lang="Go"
test_cmd="go test ./..."
lint_cmd="golangci-lint run"
elif [[ -f "Cargo.toml" ]]; then
lang="Rust"
test_cmd="cargo test"
lint_cmd="cargo clippy"
build_cmd="cargo build"
fi
# Show what we detected
echo ""
echo "${BOLD}Detected:${RESET}"
echo " Project: ${CYAN}$project_name${RESET}"
[[ -n "$lang" ]] && echo " Language: ${CYAN}$lang${RESET}"
[[ -n "$framework" ]] && echo " Framework: ${CYAN}$framework${RESET}"
[[ -n "$test_cmd" ]] && echo " Test: ${CYAN}$test_cmd${RESET}"
[[ -n "$lint_cmd" ]] && echo " Lint: ${CYAN}$lint_cmd${RESET}"
[[ -n "$build_cmd" ]] && echo " Build: ${CYAN}$build_cmd${RESET}"
echo ""
# Escape values for safe YAML (double quotes inside strings)
yaml_escape() { printf '%s' "$1" | sed 's/"/\\"/g'; }
# Create config.yaml with detected values
cat > "$CONFIG_FILE" << EOF
# Ralphy Configuration
# https://github.com/michaelshimeles/ralphy
# Project info (auto-detected, edit if needed)
project:
name: "$(yaml_escape "$project_name")"
language: "$(yaml_escape "${lang:-Unknown}")"
framework: "$(yaml_escape "${framework:-}")"
description: "" # Add a brief description
# Commands (auto-detected from package.json/pyproject.toml)
commands:
test: "$(yaml_escape "${test_cmd:-}")"
lint: "$(yaml_escape "${lint_cmd:-}")"
build: "$(yaml_escape "${build_cmd:-}")"
# Rules - instructions the AI MUST follow
# These are injected into every prompt
rules: []
# Examples:
# - "Always use TypeScript strict mode"
# - "Follow the error handling pattern in src/utils/errors.ts"
# - "All API endpoints must have input validation with Zod"
# - "Use server actions instead of API routes in Next.js"
# Boundaries - files/folders the AI should not modify
boundaries:
never_touch: []
# Examples:
# - "src/legacy/**"
# - "migrations/**"
# - "*.lock"
# Capabilities - optional tool integrations
capabilities:
# Browser automation via agent-browser (https://agent-browser.dev)
# Values: "auto" (detect), "true" (force enable), "false" (disable)
browser: "auto"
EOF
# Create progress.txt
echo "# Ralphy Progress Log" > "$PROGRESS_FILE"
echo "" >> "$PROGRESS_FILE"
log_success "Created $RALPHY_DIR/"
echo ""
echo " ${CYAN}$CONFIG_FILE${RESET} - Your rules and preferences"
echo " ${CYAN}$PROGRESS_FILE${RESET} - Progress log (auto-updated)"
echo ""
echo "${BOLD}Next steps:${RESET}"
echo " 1. Add rules: ${CYAN}ralphy --add-rule \"your rule here\"${RESET}"
echo " 2. Or edit: ${CYAN}$CONFIG_FILE${RESET}"
echo " 3. Run: ${CYAN}ralphy \"your task\"${RESET} or ${CYAN}ralphy${RESET} (with PRD.md)"
}
# Load rules from config.yaml
load_ralphy_rules() {
[[ ! -f "$CONFIG_FILE" ]] && return
if command -v yq &>/dev/null; then
yq -r '.rules // [] | .[]' "$CONFIG_FILE" 2>/dev/null || true
fi
}
# Load boundaries from config.yaml
load_ralphy_boundaries() {
local boundary_type="$1" # never_touch or always_test
[[ ! -f "$CONFIG_FILE" ]] && return
if command -v yq &>/dev/null; then
yq -r ".boundaries.$boundary_type // [] | .[]" "$CONFIG_FILE" 2>/dev/null || true
fi
}
# Load browser setting from config.yaml
load_browser_setting() {
[[ ! -f "$CONFIG_FILE" ]] && echo "auto" && return
if command -v yq &>/dev/null; then
local setting
setting=$(yq -r '.capabilities.browser // "auto"' "$CONFIG_FILE" 2>/dev/null || echo "auto")
echo "$setting"
else
echo "auto"
fi
}
# Show current config
show_ralphy_config() {
if [[ ! -f "$CONFIG_FILE" ]]; then
log_warn "No config found. Run 'ralphy --init' first."
exit 1
fi
echo ""
echo "${BOLD}Ralphy Configuration${RESET} ($CONFIG_FILE)"
echo ""
if command -v yq &>/dev/null; then
# Project info
local name lang framework desc
name=$(yq -r '.project.name // "Unknown"' "$CONFIG_FILE" 2>/dev/null)
lang=$(yq -r '.project.language // "Unknown"' "$CONFIG_FILE" 2>/dev/null)
framework=$(yq -r '.project.framework // ""' "$CONFIG_FILE" 2>/dev/null)
desc=$(yq -r '.project.description // ""' "$CONFIG_FILE" 2>/dev/null)
echo "${BOLD}Project:${RESET}"
echo " Name: $name"
echo " Language: $lang"
[[ -n "$framework" ]] && echo " Framework: $framework"
[[ -n "$desc" ]] && echo " About: $desc"
echo ""
# Commands
local test_cmd lint_cmd build_cmd
test_cmd=$(yq -r '.commands.test // ""' "$CONFIG_FILE" 2>/dev/null)
lint_cmd=$(yq -r '.commands.lint // ""' "$CONFIG_FILE" 2>/dev/null)
build_cmd=$(yq -r '.commands.build // ""' "$CONFIG_FILE" 2>/dev/null)
echo "${BOLD}Commands:${RESET}"
[[ -n "$test_cmd" ]] && echo " Test: $test_cmd" || echo " Test: ${DIM}(not set)${RESET}"
[[ -n "$lint_cmd" ]] && echo " Lint: $lint_cmd" || echo " Lint: ${DIM}(not set)${RESET}"
[[ -n "$build_cmd" ]] && echo " Build: $build_cmd" || echo " Build: ${DIM}(not set)${RESET}"
echo ""
# Rules
echo "${BOLD}Rules:${RESET}"
local rules
rules=$(yq -r '.rules // [] | .[]' "$CONFIG_FILE" 2>/dev/null)
if [[ -n "$rules" ]]; then
echo "$rules" | while read -r rule; do
echo " • $rule"
done
else
echo " ${DIM}(none - add with: ralphy --add-rule \"...\")${RESET}"
fi
echo ""
# Boundaries
local never_touch
never_touch=$(yq -r '.boundaries.never_touch // [] | .[]' "$CONFIG_FILE" 2>/dev/null)
if [[ -n "$never_touch" ]]; then
echo "${BOLD}Never Touch:${RESET}"
echo "$never_touch" | while read -r path; do
echo " • $path"
done
echo ""
fi
# Capabilities
local browser_setting
browser_setting=$(yq -r '.capabilities.browser // "auto"' "$CONFIG_FILE" 2>/dev/null)
echo "${BOLD}Capabilities:${RESET}"
local browser_status="$browser_setting"
if [[ "$browser_setting" == "auto" ]]; then
if command -v agent-browser &>/dev/null; then
browser_status="auto ${GREEN}(available)${RESET}"
else
browser_status="auto ${DIM}(not installed)${RESET}"
fi
fi
echo " Browser: $browser_status"
echo ""
else
# Fallback: just show the file
cat "$CONFIG_FILE"
fi
}
# Add a rule to config.yaml
add_ralphy_rule() {
local rule="$1"
if [[ ! -f "$CONFIG_FILE" ]]; then
log_error "No config found. Run 'ralphy --init' first."
exit 1
fi
if ! command -v yq &>/dev/null; then
log_error "yq is required to add rules. Install from https://github.com/mikefarah/yq"
log_info "Or manually edit $CONFIG_FILE"
exit 1
fi
# Add rule to the rules array (use env var to avoid YAML injection)
RULE="$rule" yq -i '.rules += [env(RULE)]' "$CONFIG_FILE"
log_success "Added rule: $rule"
}
# Load test command from config
load_test_command() {
[[ ! -f "$CONFIG_FILE" ]] && echo "" && return
if command -v yq &>/dev/null; then
yq -r '.commands.test // ""' "$CONFIG_FILE" 2>/dev/null || echo ""
else
echo ""
fi
}
# Load project context from config.yaml
load_project_context() {
[[ ! -f "$CONFIG_FILE" ]] && return
if command -v yq &>/dev/null; then
local name lang framework desc
name=$(yq -r '.project.name // ""' "$CONFIG_FILE" 2>/dev/null)
lang=$(yq -r '.project.language // ""' "$CONFIG_FILE" 2>/dev/null)
framework=$(yq -r '.project.framework // ""' "$CONFIG_FILE" 2>/dev/null)
desc=$(yq -r '.project.description // ""' "$CONFIG_FILE" 2>/dev/null)
local context=""
[[ -n "$name" ]] && context+="Project: $name\n"
[[ -n "$lang" ]] && context+="Language: $lang\n"
[[ -n "$framework" ]] && context+="Framework: $framework\n"
[[ -n "$desc" ]] && context+="Description: $desc\n"
echo -e "$context"
fi
}
# Log task to progress file
log_task_history() {
local task="$1"
local status="$2" # completed, failed
[[ ! -f "$PROGRESS_FILE" ]] && return
local timestamp
timestamp=$(date '+%Y-%m-%d %H:%M')
local icon="✓"
[[ "$status" == "failed" ]] && icon="✗"
echo "- [$icon] $timestamp - $task" >> "$PROGRESS_FILE"
}
# Build prompt with brownfield context
build_brownfield_prompt() {
local task="$1"
local prompt=""
# Add project context if available
local context
context=$(load_project_context)
if [[ -n "$context" ]]; then
prompt+="## Project Context
$context
"
fi
# Add rules if available
local rules
rules=$(load_ralphy_rules)
if [[ -n "$rules" ]]; then
prompt+="## Rules (you MUST follow these)
$rules
"
fi
# Add browser instructions if available
local browser_instructions
browser_instructions=$(get_browser_instructions)
if [[ -n "$browser_instructions" ]]; then
prompt+="$browser_instructions
"
fi
# Add boundaries
local never_touch
never_touch=$(load_ralphy_boundaries "never_touch")
if [[ -n "$never_touch" ]]; then
prompt+="## Boundaries
Do NOT modify these files/directories:
$never_touch
"
fi
# Add the task
prompt+="## Task
$task
## Instructions
1. Implement the task described above
2. Write tests if appropriate
3. Ensure the code works correctly"
# Add commit instruction only if auto-commit is enabled
if [[ "$AUTO_COMMIT" == "true" ]]; then
prompt+="
4. Commit your changes with a descriptive message"
fi
prompt+="
Keep changes focused and minimal. Do not refactor unrelated code."
echo "$prompt"
}
# Run a single brownfield task
run_brownfield_task() {
local task="$1"
echo ""
echo "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
echo "${BOLD}Task:${RESET} $task"
echo "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
echo ""
local prompt
prompt=$(build_brownfield_prompt "$task")
# Create temp file for output
local output_file
output_file=$(mktemp)
log_info "Running with $AI_ENGINE..."
if is_browser_available; then
log_info "Browser automation enabled (agent-browser)"
fi
# Run the AI engine (tee to show output while saving for parsing)
case "$AI_ENGINE" in
claude)
claude --dangerously-skip-permissions \
${MODEL_OVERRIDE:+--model "$MODEL_OVERRIDE"} \
-p "$prompt" 2>&1 | tee "$output_file"
;;
opencode)
opencode --output-format stream-json \
--approval-mode full-auto \
${MODEL_OVERRIDE:+--model "$MODEL_OVERRIDE"} \
"$prompt" 2>&1 | tee "$output_file"
;;
cursor)
agent --dangerously-skip-permissions \
-p "$prompt" 2>&1 | tee "$output_file"
;;
qwen)
qwen --output-format stream-json \
--approval-mode yolo \
-p "$prompt" 2>&1 | tee "$output_file"
;;
droid)
droid exec --output-format stream-json \
--auto medium \
"$prompt" 2>&1 | tee "$output_file"
;;
copilot)
copilot -p "$prompt" \
${MODEL_OVERRIDE:+--model "$MODEL_OVERRIDE"} \
2>&1 | tee "$output_file"
;;
codex)
codex exec --full-auto \
--json \
"$prompt" 2>&1 | tee "$output_file"
;;
esac
local exit_code=$?
# Log to history
if [[ $exit_code -eq 0 ]]; then
log_task_history "$task" "completed"
log_success "Task completed"
else
log_task_history "$task" "failed"
log_error "Task failed"
fi
rm -f "$output_file"
return $exit_code
}
# ============================================
# HELP & VERSION
# ============================================
show_help() {
cat << EOF
${BOLD}Ralphy${RESET} - Autonomous AI Coding Loop (v${VERSION})
${BOLD}USAGE:${RESET}
./ralphy.sh [options] # PRD mode (requires PRD.md)
./ralphy.sh "task description" # Single task mode (brownfield)
./ralphy.sh --init # Initialize .ralphy/ config
${BOLD}CONFIG & SETUP:${RESET}
--init Initialize .ralphy/ with smart defaults
--config Show current configuration
--add-rule "..." Add a rule to config (e.g., "Always use Zod")
${BOLD}SINGLE TASK MODE:${RESET}
"task description" Run a single task without PRD (quotes required)
--no-commit Don't auto-commit after task completion
${BOLD}AI ENGINE OPTIONS:${RESET}
--claude Use Claude Code (default, uses Opus)
--opencode Use OpenCode
--cursor Use Cursor agent
--codex Use Codex CLI
--qwen Use Qwen-Code
--droid Use Factory Droid
--copilot Use GitHub Copilot
--model <name> Override default model for any engine
Claude: sonnet, haiku, opus
OpenCode: gpt-4o, gpt-4o-mini, o1, o3-mini
--sonnet Shortcut for --claude --model sonnet
${BOLD}WORKFLOW OPTIONS:${RESET}
--no-tests Skip writing and running tests
--no-lint Skip linting
--fast Skip both tests and linting
${BOLD}EXECUTION OPTIONS:${RESET}
--max-iterations N Stop after N iterations (0 = unlimited)
--max-retries N Max retries per task on failure (default: 3)
--retry-delay N Seconds between retries (default: 5)
--dry-run Show what would be done without executing
${BOLD}PARALLEL EXECUTION:${RESET}
--parallel Run independent tasks in parallel
--max-parallel N Max concurrent tasks (default: 3)
${BOLD}GIT BRANCH OPTIONS:${RESET}
--branch-per-task Create a new git branch for each task
--base-branch NAME Base branch to create task branches from (default: current)
--create-pr Create a pull request after each task (requires gh CLI)
--draft-pr Create PRs as drafts
${BOLD}PRD SOURCE OPTIONS:${RESET}
--prd FILE PRD file path (default: PRD.md)
--yaml FILE Use YAML task file instead of markdown
--github REPO Fetch tasks from GitHub issues (e.g., owner/repo)
--github-label TAG Filter GitHub issues by label
--sync-issue NUM Sync PRD file to GitHub issue body on each iteration
${BOLD}CAPABILITIES:${RESET}
--browser Enable browser automation (requires agent-browser)
--no-browser Disable browser automation
${BOLD}OTHER OPTIONS:${RESET}
-v, --verbose Show debug output
-h, --help Show this help
--version Show version number
${BOLD}EXAMPLES:${RESET}
# Brownfield mode (single tasks in existing projects)
./ralphy.sh --init # Initialize config
./ralphy.sh "add dark mode toggle" # Run single task
./ralphy.sh "fix the login bug" --cursor # Single task with Cursor
./ralphy.sh "test the login flow" --browser # Task with browser automation
# PRD mode (task lists)
./ralphy.sh # Run with Claude Code
./ralphy.sh --codex # Run with Codex CLI
./ralphy.sh --branch-per-task --create-pr # Feature branch workflow
./ralphy.sh --parallel --max-parallel 4 # Run 4 tasks concurrently
./ralphy.sh --yaml tasks.yaml # Use YAML task file
./ralphy.sh --github owner/repo # Fetch from GitHub issues
${BOLD}PRD FORMATS:${RESET}
Markdown (PRD.md):
- [ ] Task description
YAML (tasks.yaml):
tasks:
- title: Task description
completed: false
parallel_group: 1 # Optional: tasks with same group run in parallel
GitHub Issues:
Uses open issues from the specified repository
EOF
}
show_version() {
echo "Ralphy v${VERSION}"
}
# ============================================
# ARGUMENT PARSING
# ============================================
parse_args() {
while [[ $# -gt 0 ]]; do
case $1 in
--no-tests|--skip-tests)
SKIP_TESTS=true
shift
;;
--no-lint|--skip-lint)
SKIP_LINT=true
shift
;;
--fast)
SKIP_TESTS=true
SKIP_LINT=true
shift
;;
--opencode)
AI_ENGINE="opencode"
shift
;;
--claude)
AI_ENGINE="claude"
shift
;;
--sonnet)
AI_ENGINE="claude"
MODEL_OVERRIDE="sonnet"
shift
;;
--cursor|--agent)
AI_ENGINE="cursor"
shift
;;
--codex)
AI_ENGINE="codex"
shift
;;
--qwen)
AI_ENGINE="qwen"
shift
;;
--droid)
AI_ENGINE="droid"
shift
;;
--copilot)
AI_ENGINE="copilot"
shift
;;
--model)
MODEL_OVERRIDE="$2"
shift 2
;;
--dry-run)
DRY_RUN=true
shift
;;
--max-iterations)
MAX_ITERATIONS="${2:-0}"
shift 2
;;
--max-retries)
MAX_RETRIES="${2:-3}"
shift 2
;;
--retry-delay)
RETRY_DELAY="${2:-5}"
shift 2
;;
--parallel)
PARALLEL=true
shift
;;
--max-parallel)
MAX_PARALLEL="${2:-3}"
shift 2
;;
--branch-per-task)
BRANCH_PER_TASK=true
shift
;;
--base-branch)
BASE_BRANCH="${2:-}"
shift 2
;;
--create-pr)
CREATE_PR=true
shift
;;
--draft-pr)
PR_DRAFT=true
shift
;;
--prd)
PRD_FILE="${2:-PRD.md}"
PRD_SOURCE="markdown"
shift 2
;;
--yaml)
PRD_FILE="${2:-tasks.yaml}"
PRD_SOURCE="yaml"
shift 2
;;
--github)
GITHUB_REPO="${2:-}"
PRD_SOURCE="github"
shift 2
;;
--github-label)
GITHUB_LABEL="${2:-}"
shift 2
;;
--sync-issue)
SYNC_ISSUE="${2:-}"
shift 2
;;
-v|--verbose)
VERBOSE=true
shift
;;
-h|--help)
show_help
exit 0
;;
--version)
show_version
exit 0
;;
--init)
INIT_MODE=true
shift
;;
--config)
SHOW_CONFIG=true
shift
;;
--add-rule)
[[ -z "${2:-}" ]] && { log_error "--add-rule requires an argument"; exit 1; }
ADD_RULE="$2"
shift 2
;;
--no-commit)
AUTO_COMMIT=false
shift
;;
--browser)
BROWSER_ENABLED="true"
shift
;;
--no-browser)
BROWSER_ENABLED="false"
shift
;;
-*)
log_error "Unknown option: $1"
echo "Use --help for usage"
exit 1
;;
*)
# Positional argument = single task (brownfield mode)
if [[ -z "$SINGLE_TASK" ]]; then
SINGLE_TASK="$1"
else
SINGLE_TASK="$SINGLE_TASK $1"
fi
shift
;;
esac
done
}
# ============================================
# PRE-FLIGHT CHECKS
# ============================================
check_requirements() {
local missing=()
# Check for PRD source
case "$PRD_SOURCE" in
markdown)
if [[ ! -f "$PRD_FILE" ]]; then
log_error "$PRD_FILE not found in current directory"
log_info "Create a PRD.md file with tasks marked as '- [ ] Task description'"
log_info "Or use: --yaml tasks.yaml for YAML task files"
exit 1
fi
;;
yaml)
if [[ ! -f "$PRD_FILE" ]]; then
log_error "$PRD_FILE not found in current directory"
log_info "Create a tasks.yaml file with tasks in YAML format"
log_info "Or use: --prd PRD.md for Markdown task files"
exit 1
fi
if ! command -v yq &>/dev/null; then
log_error "yq is required for YAML parsing. Install from https://github.com/mikefarah/yq"
exit 1
fi
;;
github)
if [[ -z "$GITHUB_REPO" ]]; then
log_error "GitHub repository not specified. Use --github owner/repo"
exit 1
fi
if ! command -v gh &>/dev/null; then
log_error "GitHub CLI (gh) is required. Install from https://cli.github.com/"
exit 1
fi
;;
esac
# Check for AI CLI
case "$AI_ENGINE" in
opencode)