-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathralphing.sh
More file actions
executable file
·2597 lines (2220 loc) · 80.6 KB
/
ralphing.sh
File metadata and controls
executable file
·2597 lines (2220 loc) · 80.6 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
# ============================================
# Ralphing - Autonomous AI Coding Loop
# Core version - Supports Claude, OpenCode, Codex, and Cursor
# For z.ai with zclaude, use ralphing_z_ai.sh
# Runs until PRD is complete
# ============================================
set -euo pipefail
# ============================================
# CONFIGURATION & DEFAULTS
# ============================================
VERSION="3.1.0"
# Runtime options
SKIP_TESTS=false
SKIP_LINT=false
AI_ENGINE="claude" # claude, opencode, cursor, or codex (for z.ai zclaude, use ralphing_z_ai.sh)
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="master"
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=""
# 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=()
WORKTREE_BASE="" # Base directory for parallel agent worktrees
ORIGINAL_DIR="" # Original working directory (for worktree operations)
# ============================================
# 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
}
# ============================================
# HELP & VERSION
# ============================================
show_help() {
cat << EOF
${BOLD}Ralphing${RESET} - Autonomous AI Coding Loop (v${VERSION})
${BOLD}USAGE:${RESET}
./ralphing.sh [options]
${BOLD}AI ENGINE OPTIONS:${RESET}
--claude Use Claude API (default)
--opencode Use OpenCode
--cursor Use Cursor agent
--codex Use Codex CLI
${BOLD}NOTE:${RESET} For z.ai with zclaude (GLM-4-Flash), use ralphing_z_ai.sh instead
${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
${BOLD}OTHER OPTIONS:${RESET}
-v, --verbose Show debug output
-h, --help Show this help
--version Show version number
${BOLD}EXAMPLES:${RESET}
./ralphing.sh # Run with Claude API (default)
./ralphing.sh --codex # Run with Codex CLI
./ralphing.sh --opencode # Run with OpenCode
./ralphing.sh --cursor # Run with Cursor agent
./ralphing.sh --branch-per-task --create-pr # Feature branch workflow
./ralphing.sh --parallel --max-parallel 4 # Run 4 tasks concurrently
./ralphing.sh --yaml tasks.yaml # Use YAML task file
./ralphing.sh --github owner/repo # Fetch from GitHub issues
# For z.ai with zclaude (GLM-4-Flash model):
./ralphing_z_ai.sh # Use z.ai version
${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 "Ralphing 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
;;
--claude)
AI_ENGINE="claude"
shift
;;
--opencode)
AI_ENGINE="opencode"
shift
;;
--zclaude)
AI_ENGINE="zclaude"
shift
;;
--cursor|--agent)
AI_ENGINE="cursor"
shift
;;
--codex)
AI_ENGINE="codex"
shift
;;
--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
;;
-v|--verbose)
VERBOSE=true
shift
;;
-h|--help)
show_help
exit 0
;;
--version)
show_version
exit 0
;;
*)
log_error "Unknown option: $1"
echo "Use --help for usage"
exit 1
;;
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"
exit 1
fi
;;
yaml)
if [[ ! -f "$PRD_FILE" ]]; then
log_error "$PRD_FILE not found in current directory"
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)
if ! command -v opencode &>/dev/null; then
log_error "OpenCode CLI not found. Install from https://opencode.ai/docs/"
exit 1
fi
;;
codex)
if ! command -v codex &>/dev/null; then
log_error "Codex CLI not found. Make sure 'codex' is in your PATH."
exit 1
fi
;;
cursor)
if ! command -v agent &>/dev/null; then
log_error "Cursor agent CLI not found. Make sure Cursor is installed and 'agent' is in your PATH."
exit 1
fi
;;
*)
if ! command -v zclaude &>/dev/null; then
log_error "zclaude Code CLI not found. Install from https://github.com/anthropics/zclaude-code"
exit 1
fi
;;
esac
# Check for jq
if ! command -v jq &>/dev/null; then
missing+=("jq")
fi
# Check for gh if PR creation is requested
if [[ "$CREATE_PR" == true ]] && ! command -v gh &>/dev/null; then
log_error "GitHub CLI (gh) is required for --create-pr. Install from https://cli.github.com/"
exit 1
fi
if [[ ${#missing[@]} -gt 0 ]]; then
log_warn "Missing optional dependencies: ${missing[*]}"
log_warn "Token tracking may not work properly"
fi
# Create progress.txt if missing
if [[ ! -f "progress.txt" ]]; then
log_warn "progress.txt not found, creating it..."
touch progress.txt
fi
# Set base branch if not specified
if [[ "$BRANCH_PER_TASK" == true ]] && [[ -z "$BASE_BRANCH" ]]; then
BASE_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "main")
log_debug "Using base branch: $BASE_BRANCH"
fi
}
# ============================================
# CLEANUP HANDLER
# ============================================
cleanup() {
local exit_code=$?
log_debug "========== Cleanup started (exit code: $exit_code) =========="
# Kill background processes
if [[ -n "$monitor_pid" ]]; then
log_debug "Killing monitor process: $monitor_pid"
kill "$monitor_pid" 2>/dev/null || true
fi
if [[ -n "$ai_pid" ]]; then
log_debug "Killing AI process: $ai_pid"
kill "$ai_pid" 2>/dev/null || true
fi
# Kill parallel processes
if [[ ${#parallel_pids[@]} -gt 0 ]]; then
log_debug "Killing ${#parallel_pids[@]} parallel processes"
fi
for pid in "${parallel_pids[@]+"${parallel_pids[@]}"}"; do
kill "$pid" 2>/dev/null || true
done
# Kill any remaining child processes
log_debug "Cleaning up remaining child processes"
pkill -P $$ 2>/dev/null || true
# Remove temp file
if [[ -n "$tmpfile" ]]; then
log_debug "Removing temp file: $tmpfile"
rm -f "$tmpfile"
fi
if [[ -n "$CODEX_LAST_MESSAGE_FILE" ]]; then
log_debug "Removing Codex temp file: $CODEX_LAST_MESSAGE_FILE"
rm -f "$CODEX_LAST_MESSAGE_FILE"
fi
# Cleanup parallel worktrees
if [[ -n "$WORKTREE_BASE" ]] && [[ -d "$WORKTREE_BASE" ]]; then
# Remove all worktrees we created
for dir in "$WORKTREE_BASE"/agent-*; do
if [[ -d "$dir" ]]; then
if git -C "$dir" status --porcelain 2>/dev/null | grep -q .; then
log_warn "Preserving dirty worktree: $dir"
continue
fi
git worktree remove "$dir" 2>/dev/null || true
fi
done
if ! find "$WORKTREE_BASE" -maxdepth 1 -type d -name 'agent-*' -print -quit 2>/dev/null | grep -q .; then
rm -rf "$WORKTREE_BASE" 2>/dev/null || true
else
log_warn "Preserving worktree base with dirty agents: $WORKTREE_BASE"
fi
fi
# Show message on interrupt
if [[ $exit_code -eq 130 ]]; then
printf "\n"
log_warn "Interrupted! Cleaned up."
# Show branches created if any
if [[ -n "${task_branches[*]+"${task_branches[*]}"}" ]]; then
log_info "Branches created: ${task_branches[*]}"
fi
fi
}
# ============================================
# TASK SOURCES - MARKDOWN
# ============================================
get_tasks_markdown() {
grep '^\- \[ \]' "$PRD_FILE" 2>/dev/null | sed 's/^- \[ \] //' || true
}
get_next_task_markdown() {
grep -m1 '^\- \[ \]' "$PRD_FILE" 2>/dev/null | sed 's/^- \[ \] //' | cut -c1-50 || echo ""
}
count_remaining_markdown() {
grep -c '^\- \[ \]' "$PRD_FILE" 2>/dev/null || echo "0"
}
count_completed_markdown() {
grep -c '^\- \[x\]' "$PRD_FILE" 2>/dev/null || echo "0"
}
mark_task_complete_markdown() {
local task=$1
# For macOS sed (BRE), we need to:
# - Escape: [ ] \ . * ^ $ /
# - NOT escape: { } ( ) + ? | (these are literal in BRE)
local escaped_task
escaped_task=$(printf '%s\n' "$task" | sed 's/[[\.*^$/]/\\&/g')
sed -i.bak "s/^- \[ \] ${escaped_task}/- [x] ${escaped_task}/" "$PRD_FILE"
rm -f "${PRD_FILE}.bak"
}
# ============================================
# TASK SOURCES - YAML
# ============================================
get_tasks_yaml() {
yq -r '.tasks[] | select(.completed != true) | .title' "$PRD_FILE" 2>/dev/null || true
}
get_next_task_yaml() {
yq -r '.tasks[] | select(.completed != true) | .title' "$PRD_FILE" 2>/dev/null | head -1 | cut -c1-50 || echo ""
}
count_remaining_yaml() {
yq -r '[.tasks[] | select(.completed != true)] | length' "$PRD_FILE" 2>/dev/null || echo "0"
}
count_completed_yaml() {
yq -r '[.tasks[] | select(.completed == true)] | length' "$PRD_FILE" 2>/dev/null || echo "0"
}
mark_task_complete_yaml() {
local task=$1
yq -i "(.tasks[] | select(.title == \"$task\")).completed = true" "$PRD_FILE"
}
get_parallel_group_yaml() {
local task=$1
yq -r ".tasks[] | select(.title == \"$task\") | .parallel_group // 0" "$PRD_FILE" 2>/dev/null || echo "0"
}
get_tasks_in_group_yaml() {
local group=$1
yq -r ".tasks[] | select(.completed != true and (.parallel_group // 0) == $group) | .title" "$PRD_FILE" 2>/dev/null || true
}
# ============================================
# TASK SOURCES - GITHUB ISSUES
# ============================================
get_tasks_github() {
local args=(--repo "$GITHUB_REPO" --state open --json number,title)
[[ -n "$GITHUB_LABEL" ]] && args+=(--label "$GITHUB_LABEL")
gh issue list "${args[@]}" \
--jq '.[] | "\(.number):\(.title)"' 2>/dev/null || true
}
get_next_task_github() {
local args=(--repo "$GITHUB_REPO" --state open --limit 1 --json number,title)
[[ -n "$GITHUB_LABEL" ]] && args+=(--label "$GITHUB_LABEL")
gh issue list "${args[@]}" \
--jq '.[0] | "\(.number):\(.title)"' 2>/dev/null | cut -c1-50 || echo ""
}
count_remaining_github() {
local args=(--repo "$GITHUB_REPO" --state open --json number)
[[ -n "$GITHUB_LABEL" ]] && args+=(--label "$GITHUB_LABEL")
gh issue list "${args[@]}" \
--jq 'length' 2>/dev/null || echo "0"
}
count_completed_github() {
local args=(--repo "$GITHUB_REPO" --state closed --json number)
[[ -n "$GITHUB_LABEL" ]] && args+=(--label "$GITHUB_LABEL")
gh issue list "${args[@]}" \
--jq 'length' 2>/dev/null || echo "0"
}
mark_task_complete_github() {
local task=$1
# Extract issue number from "number:title" format
local issue_num="${task%%:*}"
gh issue close "$issue_num" --repo "$GITHUB_REPO" 2>/dev/null || true
}
get_github_issue_body() {
local task=$1
local issue_num="${task%%:*}"
gh issue view "$issue_num" --repo "$GITHUB_REPO" --json body --jq '.body' 2>/dev/null || echo ""
}
# ============================================
# UNIFIED TASK INTERFACE
# ============================================
get_next_task() {
case "$PRD_SOURCE" in
markdown) get_next_task_markdown ;;
yaml) get_next_task_yaml ;;
github) get_next_task_github ;;
esac
}
get_all_tasks() {
case "$PRD_SOURCE" in
markdown) get_tasks_markdown ;;
yaml) get_tasks_yaml ;;
github) get_tasks_github ;;
esac
}
count_remaining_tasks() {
case "$PRD_SOURCE" in
markdown) count_remaining_markdown ;;
yaml) count_remaining_yaml ;;
github) count_remaining_github ;;
esac
}
count_completed_tasks() {
case "$PRD_SOURCE" in
markdown) count_completed_markdown ;;
yaml) count_completed_yaml ;;
github) count_completed_github ;;
esac
}
mark_task_complete() {
local task=$1
log_debug "Marking task complete in $PRD_SOURCE: ${task:0:50}"
case "$PRD_SOURCE" in
markdown)
log_debug "Updating markdown PRD file"
mark_task_complete_markdown "$task"
;;
yaml)
log_debug "Updating YAML task file"
mark_task_complete_yaml "$task"
;;
github)
log_debug "Closing GitHub issue"
mark_task_complete_github "$task"
;;
esac
}
# ============================================
# GIT BRANCH MANAGEMENT
# ============================================
create_task_branch() {
local task=$1
local branch_name="ralphing/$(slugify "$task")"
log_debug "Creating branch: $branch_name from $BASE_BRANCH"
log_debug "Task slug: $(slugify "$task")"
# Stash any changes (only pop if a new stash was created)
local stash_before stash_after stashed=false
stash_before=$(git stash list -1 --format='%gd %s' 2>/dev/null || true)
log_debug "Stashing uncommitted changes (if any)"
git stash push -m "ralphing-autostash" >/dev/null 2>&1 || true
stash_after=$(git stash list -1 --format='%gd %s' 2>/dev/null || true)
if [[ -n "$stash_after" ]] && [[ "$stash_after" != "$stash_before" ]] && [[ "$stash_after" == *"ralphing-autostash"* ]]; then
stashed=true
log_debug "Stashed changes successfully"
fi
# Create and checkout new branch
log_debug "Checking out base branch: $BASE_BRANCH"
git checkout "$BASE_BRANCH" 2>/dev/null || true
log_debug "Pulling latest from origin/$BASE_BRANCH"
git pull origin "$BASE_BRANCH" 2>/dev/null || true
log_debug "Creating new branch: $branch_name"
git checkout -b "$branch_name" 2>/dev/null || {
# Branch might already exist
log_debug "Branch exists, checking it out"
git checkout "$branch_name" 2>/dev/null || true
}
# Pop stash if we stashed
if [[ "$stashed" == true ]]; then
log_debug "Restoring stashed changes"
git stash pop >/dev/null 2>&1 || true
fi
task_branches+=("$branch_name")
log_debug "Branch created and tracked: $branch_name"
echo "$branch_name"
}
create_pull_request() {
local branch=$1
local task=$2
local body="${3:-Automated PR created by Ralphing}"
local draft_flag=""
[[ "$PR_DRAFT" == true ]] && draft_flag="--draft"
log_info "Creating pull request for $branch..."
# Push branch first
git push -u origin "$branch" 2>/dev/null || {
log_warn "Failed to push branch $branch"
return 1
}
# Create PR
local pr_url
pr_url=$(gh pr create \
--base "$BASE_BRANCH" \
--head "$branch" \
--title "$task" \
--body "$body" \
$draft_flag 2>/dev/null) || {
log_warn "Failed to create PR for $branch"
return 1
}
log_success "PR created: $pr_url"
echo "$pr_url"
}
return_to_base_branch() {
if [[ "$BRANCH_PER_TASK" == true ]]; then
git checkout "$BASE_BRANCH" 2>/dev/null || true
fi
}
# ============================================
# PROGRESS MONITOR
# ============================================
monitor_progress() {
local file=$1
local task=$2
local start_time
start_time=$(date +%s)
local spinstr='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
local spin_idx=0
# Colorful blinking indicators
local indicators=("${RED}⏺${RESET}" "${YELLOW}⏺${RESET}" "${GREEN}⏺${RESET}" "${CYAN}⏺${RESET}" "${BLUE}⏺${RESET}" "${MAGENTA}⏺${RESET}")
local indicator_idx=0
local last_status_time=0
task="${task:0:40}"
while true; do
local elapsed=$(($(date +%s) - start_time))
local mins=$((elapsed / 60))
local secs=$((elapsed % 60))
# Check latest output for step indicators
if [[ -f "$file" ]] && [[ -s "$file" ]]; then
local content
content=$(tail -c 5000 "$file" 2>/dev/null || true)
if echo "$content" | grep -qE 'git commit|"command":"git commit'; then
current_step="Committing"
elif echo "$content" | grep -qE 'git add|"command":"git add'; then
current_step="Staging"
elif echo "$content" | grep -qE 'progress\.txt'; then
current_step="Logging"
elif echo "$content" | grep -qE 'PRD\.md|tasks\.yaml'; then
current_step="Updating PRD"
elif echo "$content" | grep -qE 'lint|eslint|biome|prettier'; then
current_step="Linting"
elif echo "$content" | grep -qE 'vitest|jest|bun test|npm test|pytest|go test'; then
current_step="Testing"
elif echo "$content" | grep -qE '\.test\.|\.spec\.|__tests__|_test\.go'; then
current_step="Writing tests"
elif echo "$content" | grep -qE '"tool":"[Ww]rite"|"tool":"[Ee]dit"|"name":"write"|"name":"edit"'; then
current_step="Implementing"
elif echo "$content" | grep -qE '"tool":"[Rr]ead"|"tool":"[Gg]lob"|"tool":"[Gg]rep"|"name":"read"|"name":"glob"|"name":"grep"'; then
current_step="Reading code"
fi
fi
# Every 30 seconds, print detailed status update
if [[ $((elapsed - last_status_time)) -ge 30 ]] && [[ $elapsed -gt 0 ]]; then
last_status_time=$elapsed
# Clear the spinner line first
tput cr 2>/dev/null || printf "\r"
tput el 2>/dev/null || true
echo ""
echo " ${BOLD}${CYAN}═══ Agent Status Update (${mins}m ${secs}s) ═══${RESET}"
# Show last activity from AI output
if [[ -f "$file" ]]; then
local recent_output
# Extract recent tool calls or content
recent_output=$(tail -100 "$file" 2>/dev/null | grep -oE '"tool":"[^"]+"|"name":"[^"]+"|"file_path":"[^"]+"|"command":"[^"]{0,60}' | tail -5)
if [[ -n "$recent_output" ]]; then
echo " ${DIM}Recent activity:${RESET}"
echo "$recent_output" | sed 's/"tool":/ Tool: /g; s/"name":/ Action: /g; s/"file_path":/ File: /g; s/"command":/ Cmd: /g' | sed 's/"//g' | head -5
else
echo " ${DIM}Agent is processing...${RESET}"
fi
fi
echo " ${DIM}Current step: ${current_step}${RESET}"
echo ""
fi
local spinner_char="${spinstr:$spin_idx:1}"
local step_color=""
local indicator="${indicators[$indicator_idx]}"
# Color-code steps
case "$current_step" in
"Thinking"|"Reading code") step_color="$CYAN" ;;
"Implementing"|"Writing tests") step_color="$MAGENTA" ;;
"Testing"|"Linting") step_color="$YELLOW" ;;
"Staging"|"Committing") step_color="$GREEN" ;;
*) step_color="$BLUE" ;;
esac
# Use tput for cleaner line clearing
tput cr 2>/dev/null || printf "\r"
tput el 2>/dev/null || true
printf " %s %s ${step_color}%-14s${RESET} │ %s ${DIM}[%02d:%02d]${RESET}" "$indicator" "$spinner_char" "$current_step" "$task" "$mins" "$secs"
spin_idx=$(( (spin_idx + 1) % ${#spinstr} ))
indicator_idx=$(( (indicator_idx + 1) % ${#indicators[@]} ))
sleep 0.12
done
}
# ============================================
# NOTIFICATION (Cross-platform)
# ============================================
notify_done() {
local message="${1:-Ralphing has completed all tasks!}"
# macOS
if command -v afplay &>/dev/null; then
afplay /System/Library/Sounds/Glass.aiff 2>/dev/null &
fi
# macOS notification
if command -v osascript &>/dev/null; then
osascript -e "display notification \"$message\" with title \"Ralphing\"" 2>/dev/null || true
fi
# Linux (notify-send)
if command -v notify-send &>/dev/null; then
notify-send "Ralphing" "$message" 2>/dev/null || true
fi
# Linux (paplay for sound)
if command -v paplay &>/dev/null; then
paplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null &
fi
# Windows (powershell)
if command -v powershell.exe &>/dev/null; then
powershell.exe -Command "[System.Media.SystemSounds]::Asterisk.Play()" 2>/dev/null || true
fi
}
notify_error() {
local message="${1:-Ralphing encountered an error}"
# macOS
if command -v osascript &>/dev/null; then
osascript -e "display notification \"$message\" with title \"Ralphing - Error\"" 2>/dev/null || true
fi
# Linux
if command -v notify-send &>/dev/null; then
notify-send -u critical "Ralphing - Error" "$message" 2>/dev/null || true
fi
}
# ============================================
# PROMPT BUILDER
# ============================================
build_prompt() {
local task_override="${1:-}"
local prompt=""
# Add context based on PRD source
case "$PRD_SOURCE" in
markdown)
prompt="@${PRD_FILE} @progress.txt"
;;
yaml)
prompt="@${PRD_FILE} @progress.txt"
;;
github)
# For GitHub issues, we include the issue body
local issue_body=""
if [[ -n "$task_override" ]]; then
issue_body=$(get_github_issue_body "$task_override")
fi
prompt="Task from GitHub Issue: $task_override
Issue Description:
$issue_body
@progress.txt"
;;
esac
prompt="$prompt
1. Find the highest-priority incomplete task and implement it."
local step=2
if [[ "$SKIP_TESTS" == false ]]; then
prompt="$prompt
$step. Write tests for the feature.
$((step+1)). Run tests and ensure they pass before proceeding."
step=$((step+2))
fi
if [[ "$SKIP_LINT" == false ]]; then
prompt="$prompt
$step. Run linting and ensure it passes before proceeding."
step=$((step+1))
fi
# Adjust completion step based on PRD source
case "$PRD_SOURCE" in
markdown)
prompt="$prompt
$step. Update the PRD to mark the task as complete (change '- [ ]' to '- [x]')."
;;
yaml)
prompt="$prompt
$step. Update ${PRD_FILE} to mark the task as completed (set completed: true)."
;;
github)
prompt="$prompt
$step. The task will be marked complete automatically. Just note the completion in progress.txt."
;;
esac
step=$((step+1))
prompt="$prompt
$step. Append your progress to progress.txt.
$((step+1)). Commit your changes with a descriptive message.
ONLY WORK ON A SINGLE TASK."
if [[ "$SKIP_TESTS" == false ]]; then
prompt="$prompt Do not proceed if tests fail."
fi
if [[ "$SKIP_LINT" == false ]]; then
prompt="$prompt Do not proceed if linting fails."
fi
prompt="$prompt
If ALL tasks in the PRD are complete, output <promise>COMPLETE</promise>."
echo "$prompt"
}
# ============================================
# AI ENGINE ABSTRACTION
# ============================================
run_ai_command() {
local prompt=$1
local output_file=$2
log_debug "Starting AI engine: $AI_ENGINE"
log_debug "Output file: $output_file"
case "$AI_ENGINE" in
claude)
# Claude API: use claude with standard flags
log_debug "Running Claude with API"
claude --dangerously-skip-permissions \
--verbose \
--output-format stream-json \
-p "$prompt" > "$output_file" 2>&1 &
;;
zclaude)
# z.ai zclaude: use zclaude with z.ai backend (GLM-4-Flash)
log_debug "Running z.ai zclaude with GLM-4-Flash model"
zclaude --dangerously-skip-permissions \
--verbose \
--output-format stream-json \
-p "$prompt" > "$output_file" 2>&1 &
;;
opencode)
# OpenCode: use 'run' command with JSON format and permissive settings
log_debug "Running OpenCode with full permissions"
OPENCODE_PERMISSION='{"*":"allow"}' opencode run \
--format json \
"$prompt" > "$output_file" 2>&1 &
;;
cursor)
# Cursor agent: use --print for non-interactive, --force to allow all commands
log_debug "Running Cursor agent in non-interactive mode"
agent --print --force \
--output-format stream-json \
"$prompt" > "$output_file" 2>&1 &
;;