-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloop.sh
More file actions
executable file
Β·1521 lines (1284 loc) Β· 55.5 KB
/
loop.sh
File metadata and controls
executable file
Β·1521 lines (1284 loc) Β· 55.5 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
#
# beads-loop v3 - Production-grade loop runner for Claude Code
#
# Features:
# - Real-time TUI dashboard
# - Session persistence & resume
# - Live token streaming & cost tracking
# - Webhooks & integrations
# - Interactive approval mode
# - Rich jj diff display
# - Automatic rate limit handling
# - Report generation
#
set -euo pipefail
readonly VERSION="3.0.0"
readonly SCRIPT_NAME="$(basename "$0")"
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Constants & Defaults
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
readonly STATE_DIR=".ralph"
readonly CONFIG_FILE=".ralph/config.toml"
readonly HISTORY_FILE="$STATE_DIR/history.jsonl"
# Default configuration
declare -A CONFIG=(
[mode]="build"
[max_iterations]=500
[model]="opus"
[delay]=3
[max_retries]=2
[retry_delay]=10
[auto_stop_empty]=true
[auto_stop_failures]=3
[push_enabled]=true
[notifications]=true
[sound]=false
[interactive]=false
[webhook_url]=""
[rate_limit_pause]=60
[checkpoint_interval]=5
[verbose]=false
[review_enabled]=true
[review_model]="gpt-5.3-codex"
[review_max_revisions]=5
[epic]=""
)
# Runtime state
declare -A STATE=(
[session_id]=""
[iteration]=0
[consecutive_failures]=0
[total_tokens]=0
[total_cost]="0"
[start_time]=0
[status]="initializing"
[paused]=false
[interrupted]=false
[review_passes]=0
[review_revisions]=0
[review_skipped]=0
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Terminal & Colors
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
setup_terminal() {
# Check if we have a real terminal
if [[ -t 1 ]]; then
HAS_TTY=true
TERM_COLS=$(tput cols 2>/dev/null || echo 80)
TERM_ROWS=$(tput lines 2>/dev/null || echo 24)
else
HAS_TTY=false
TERM_COLS=80
TERM_ROWS=24
fi
# Colors (with fallback for non-color terminals)
if [[ "${TERM:-}" != "dumb" ]] && [[ "$HAS_TTY" == true ]]; then
C_RESET=$'\033[0m'
C_BOLD=$'\033[1m'
C_DIM=$'\033[2m'
C_ITALIC=$'\033[3m'
C_UNDER=$'\033[4m'
C_RED=$'\033[38;5;203m'
C_GREEN=$'\033[38;5;114m'
C_YELLOW=$'\033[38;5;221m'
C_BLUE=$'\033[38;5;69m'
C_MAGENTA=$'\033[38;5;176m'
C_CYAN=$'\033[38;5;80m'
C_ORANGE=$'\033[38;5;215m'
C_GRAY=$'\033[38;5;245m'
C_WHITE=$'\033[38;5;255m'
C_BG_DARK=$'\033[48;5;236m'
else
C_RESET="" C_BOLD="" C_DIM="" C_ITALIC="" C_UNDER=""
C_RED="" C_GREEN="" C_YELLOW="" C_BLUE="" C_MAGENTA=""
C_CYAN="" C_ORANGE="" C_GRAY="" C_WHITE="" C_BG_DARK=""
fi
}
# Symbols (with ASCII fallback)
setup_symbols() {
if [[ "${LANG:-}" == *UTF-8* ]] || [[ "${LC_ALL:-}" == *UTF-8* ]]; then
SYM_CHECK="β"
SYM_CROSS="β"
SYM_ARROW="βΈ"
SYM_BULLET="β"
SYM_CIRCLE="β"
SYM_SPARK="β¦"
SYM_WARN="β "
SYM_INFO="βΉ"
SYM_PLAY="βΆ"
SYM_PAUSE="βΈ"
SYM_STOP="βΉ"
SYM_CLOCK="β·"
SYM_GEAR="β"
SYM_GRAPH="βββββ
βββ"
SYM_SPIN="β β β Ήβ Έβ Όβ ΄β ¦β §β β "
else
SYM_CHECK="+"
SYM_CROSS="x"
SYM_ARROW=">"
SYM_BULLET="*"
SYM_CIRCLE="o"
SYM_SPARK="*"
SYM_WARN="!"
SYM_INFO="i"
SYM_PLAY=">"
SYM_PAUSE="||"
SYM_STOP="[]"
SYM_CLOCK="@"
SYM_GEAR="#"
SYM_GRAPH="12345678"
SYM_SPIN="-\\|/"
fi
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Logging System
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
LOG_FILE=""
METRICS_FILE=""
init_logging() {
local session_dir="$STATE_DIR/sessions/${STATE[session_id]}"
mkdir -p "$session_dir"
LOG_FILE="$session_dir/session.log"
METRICS_FILE="$session_dir/metrics.jsonl"
# Rotate old logs if too large (>10MB)
if [[ -f "$LOG_FILE" ]]; then
local size
size=$(stat -f%z "$LOG_FILE" 2>/dev/null || stat -c%s "$LOG_FILE" 2>/dev/null || echo 0)
[[ "$size" -gt 10485760 ]] && mv "$LOG_FILE" "$LOG_FILE.$(date +%s).bak"
fi
}
log() {
local level="${1:-INFO}"
local msg="${2:-}"
local ts=$(date '+%Y-%m-%d %H:%M:%S')
# Strip colors for file
local clean_msg=$(echo -e "$msg" | sed 's/\x1b\[[0-9;]*m//g')
echo "[$ts] [$level] $clean_msg" >> "$LOG_FILE"
# Console output based on level
case "$level" in
DEBUG)
[[ "${CONFIG[verbose]:-false}" == true ]] && echo -e "${C_DIM}$msg${C_RESET}" ;;
INFO)
echo -e "$msg" ;;
WARN)
echo -e "${C_YELLOW}${SYM_WARN} $msg${C_RESET}" ;;
ERROR)
echo -e "${C_RED}${SYM_CROSS} $msg${C_RESET}" >&2 ;;
SUCCESS)
echo -e "${C_GREEN}${SYM_CHECK} $msg${C_RESET}" ;;
esac
}
log_metric() {
local metric="$1"
local value="$2"
local tags="${3:-}"
local json="{\"ts\":$(date +%s),\"iteration\":${STATE[iteration]},\"metric\":\"$metric\",\"value\":$value"
[[ -n "$tags" ]] && json="$json,\"tags\":$tags"
json="$json}"
echo "$json" >> "$METRICS_FILE"
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# TUI Components
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cursor_save() { [[ "$HAS_TTY" == true ]] && tput sc || true; }
cursor_restore() { [[ "$HAS_TTY" == true ]] && tput rc || true; }
cursor_hide() { [[ "$HAS_TTY" == true ]] && tput civis 2>/dev/null || true; }
cursor_show() { [[ "$HAS_TTY" == true ]] && tput cnorm 2>/dev/null || true; }
clear_line() { [[ "$HAS_TTY" == true ]] && printf '\r%*s\r' "$TERM_COLS" '' || true; }
move_to() { [[ "$HAS_TTY" == true ]] && tput cup "$1" "$2" || true; }
# Progress bar
progress_bar() {
local current=$1
local total=$2
local width=${3:-40}
local label="${4:-}"
if [[ $total -eq 0 ]]; then
printf "${C_DIM}[%*s]${C_RESET}" "$width" ""
return
fi
local pct=$((current * 100 / total))
local filled=$((current * width / total))
local empty=$((width - filled))
printf "${C_CYAN}["
[[ $filled -gt 0 ]] && printf '%*s' "$filled" '' | tr ' ' 'β'
[[ $empty -gt 0 ]] && printf "${C_DIM}%*s${C_CYAN}" "$empty" '' | tr ' ' 'β'
printf "]${C_RESET} %3d%%" "$pct"
[[ -n "$label" ]] && printf " ${C_DIM}%s${C_RESET}" "$label"
}
# Sparkline from array of values
sparkline() {
local -a values=("$@")
local max=1
for v in "${values[@]}"; do
[[ $v -gt $max ]] && max=$v
done
local chars="${SYM_GRAPH}"
local result=""
for v in "${values[@]}"; do
local idx=$((v * 7 / max))
result+="${chars:idx:1}"
done
echo "$result"
}
# Spinner with message
declare SPINNER_PID=""
spinner_start() {
local msg="$1"
[[ "$HAS_TTY" != true ]] && return
cursor_hide
(
local i=0
local spin="${SYM_SPIN}"
while true; do
printf "\r ${C_CYAN}%s${C_RESET} %s" "${spin:i++%${#spin}:1}" "$msg"
sleep 0.1
done
) &
SPINNER_PID=$!
}
spinner_stop() {
[[ -n "$SPINNER_PID" ]] && kill "$SPINNER_PID" 2>/dev/null && wait "$SPINNER_PID" 2>/dev/null || true
SPINNER_PID=""
clear_line
cursor_show
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Dashboard
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
draw_header() {
local width=$TERM_COLS
local mode_label="${CONFIG[mode]^^}"
local title=" BEADS LOOP v$VERSION :: ${mode_label} MODE "
local pad=$(( (width - ${#title}) / 2 ))
echo -e "${C_BG_DARK}${C_WHITE}"
printf '%*s%s%*s' "$pad" '' "$title" "$((width - pad - ${#title}))" ''
echo -e "${C_RESET}"
}
draw_status_bar() {
local status_icon status_color
case "${STATE[status]}" in
running) status_icon="$SYM_PLAY"; status_color="$C_GREEN" ;;
paused) status_icon="$SYM_PAUSE"; status_color="$C_YELLOW" ;;
failed) status_icon="$SYM_CROSS"; status_color="$C_RED" ;;
complete) status_icon="$SYM_CHECK"; status_color="$C_GREEN" ;;
*) status_icon="$SYM_CIRCLE"; status_color="$C_GRAY" ;;
esac
local elapsed=$(($(date +%s) - STATE[start_time]))
local elapsed_fmt=$(format_duration $elapsed)
printf "${C_DIM}β${C_RESET} "
printf "${status_color}%s %s${C_RESET}" "$status_icon" "${STATE[status]^^}"
printf " ${C_DIM}β${C_RESET} "
printf "${C_BOLD}${C_CYAN}%s${C_RESET} " "${CONFIG[mode]^^}"
printf "${C_CYAN}%s${C_RESET} iter %d" "$SYM_CLOCK" "${STATE[iteration]}"
[[ ${CONFIG[max_iterations]} -gt 0 ]] && printf "/${CONFIG[max_iterations]}"
printf " ${C_DIM}β${C_RESET} "
printf "%s %s" "$SYM_CLOCK" "$elapsed_fmt"
printf " ${C_DIM}β${C_RESET} "
printf "${C_GREEN}$%s${C_RESET}" "${STATE[total_cost]}"
if [[ "${CONFIG[review_enabled]}" == true ]]; then
printf " ${C_DIM}β${C_RESET} "
printf "${C_GREEN}%d${C_RESET}${C_DIM}S${C_RESET}" "${STATE[review_passes]}"
printf "/${C_YELLOW}%d${C_RESET}${C_DIM}R${C_RESET}" "${STATE[review_revisions]}"
[[ ${STATE[review_skipped]} -gt 0 ]] && printf "/${C_GRAY}%d${C_RESET}${C_DIM}?${C_RESET}" "${STATE[review_skipped]}"
fi
printf " ${C_DIM}β${C_RESET}"
echo ""
}
draw_box() {
local title="$1"
local content="$2"
local width=${3:-$((TERM_COLS - 4))}
echo -e "${C_DIM}ββ${C_RESET}${C_BOLD} $title ${C_RESET}${C_DIM}$(printf 'β%.0s' $(seq 1 $((width - ${#title} - 4))))β${C_RESET}"
echo -e "$content" | while IFS= read -r line; do
printf "${C_DIM}β${C_RESET} %-$((width-2))s ${C_DIM}β${C_RESET}\n" "$line"
done
echo -e "${C_DIM}β$(printf 'β%.0s' $(seq 1 $((width))))β${C_RESET}"
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Utilities
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
format_duration() {
local seconds=$1
if [[ $seconds -lt 60 ]]; then
printf '%ds' "$seconds"
elif [[ $seconds -lt 3600 ]]; then
printf '%dm%02ds' $((seconds/60)) $((seconds%60))
else
printf '%dh%02dm%02ds' $((seconds/3600)) $((seconds%3600/60)) $((seconds%60))
fi
}
format_number() {
local num=$1
if [[ $num -lt 1000 ]]; then
echo "$num"
elif [[ $num -lt 1000000 ]]; then
printf '%.1fK' "$(bc <<< "scale=1; $num/1000")"
else
printf '%.2fM' "$(bc <<< "scale=2; $num/1000000")"
fi
}
format_bytes() {
local bytes=$1
if [[ $bytes -lt 1024 ]]; then
echo "${bytes}B"
elif [[ $bytes -lt 1048576 ]]; then
printf '%.1fKB' "$(bc <<< "scale=1; $bytes/1024")"
else
printf '%.1fMB' "$(bc <<< "scale=1; $bytes/1048576")"
fi
}
json_escape() {
local str="$1"
str="${str//\\/\\\\}"
str="${str//\"/\\\"}"
str="${str//$'\n'/\\n}"
str="${str//$'\t'/\\t}"
echo "$str"
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Notifications & Integrations
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
notify() {
local title="$1"
local message="$2"
local urgency="${3:-normal}" # low, normal, critical
[[ "${CONFIG[notifications]}" != true ]] && return
# Desktop notification
if [[ "$(uname)" == "Darwin" ]]; then
osascript -e "display notification \"$message\" with title \"$title\"" 2>/dev/null || true
elif command -v notify-send &>/dev/null; then
notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
fi
# Sound
if [[ "${CONFIG[sound]}" == true ]]; then
if [[ "$(uname)" == "Darwin" ]]; then
afplay /System/Library/Sounds/Glass.aiff 2>/dev/null &
elif command -v paplay &>/dev/null; then
paplay /usr/share/sounds/freedesktop/stereo/complete.oga 2>/dev/null &
fi
fi
}
send_webhook() {
local event="$1"
local payload="$2"
[[ -z "${CONFIG[webhook_url]}" ]] && return
local full_payload=$(cat <<EOF
{
"event": "$event",
"session_id": "${STATE[session_id]}",
"iteration": ${STATE[iteration]},
"timestamp": "$(date -Iseconds)",
"data": $payload
}
EOF
)
curl -s -X POST \
-H "Content-Type: application/json" \
-d "$full_payload" \
"${CONFIG[webhook_url]}" &>/dev/null &
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# VCS Operations (jj/Jujutsu)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
vcs_branch() {
jj log -r @ --no-graph -T 'bookmarks' 2>/dev/null | head -1 || echo "none"
}
vcs_commit_short() {
jj log -r @ --no-graph -T 'change_id.shortest(8)' 2>/dev/null || echo "unknown"
}
vcs_is_dirty() {
# In jj, the working copy is always a commit; check if it has changes
local status
status=$(jj diff --stat 2>/dev/null)
[[ -n "$status" ]]
}
vcs_changes_summary() {
local from_change="$1"
local to_change="${2:-@}"
[[ "$from_change" == "$to_change" ]] && return
local output=""
local files
files=$(jj diff --from "$from_change" --to "$to_change" --name-only 2>/dev/null)
local file_count=$(echo "$files" | grep -c . 2>/dev/null || echo 0)
[[ $file_count -eq 0 ]] && return
output+="${C_BOLD}Changes:${C_RESET}\n"
while IFS= read -r file; do
[[ -z "$file" ]] && continue
local stat
stat=$(jj diff --from "$from_change" --to "$to_change" --stat -- "$file" 2>/dev/null | head -1)
local added=$(echo "$stat" | grep -oE '[0-9]+ insertion' | grep -oE '[0-9]+' || echo 0)
local removed=$(echo "$stat" | grep -oE '[0-9]+ deletion' | grep -oE '[0-9]+' || echo 0)
# File type icon
local icon="π"
case "${file##*.}" in
rs) icon="π¦" ;;
py) icon="π" ;;
ts|tsx) icon="π" ;;
js|jsx) icon="π" ;;
go) icon="πΉ" ;;
rb) icon="π" ;;
md) icon="π" ;;
toml|yaml|yml|json) icon="βοΈ " ;;
sh|bash) icon="π" ;;
sql) icon="ποΈ " ;;
html|css) icon="π" ;;
Dockerfile|docker*) icon="π³" ;;
esac
output+=" $icon ${C_WHITE}$file${C_RESET}"
[[ -n "$added" ]] && [[ "$added" != "0" ]] && output+=" ${C_GREEN}+$added${C_RESET}"
[[ -n "$removed" ]] && [[ "$removed" != "0" ]] && output+=" ${C_RED}-$removed${C_RESET}"
output+="\n"
done <<< "$(echo "$files" | head -8)"
[[ $file_count -gt 8 ]] && output+=" ${C_DIM}... and $((file_count - 8)) more files${C_RESET}\n"
# Summary stats
local total_stats
total_stats=$(jj diff --from "$from_change" --to "$to_change" --stat 2>/dev/null | tail -1)
[[ -n "$total_stats" ]] && output+="${C_DIM} $total_stats${C_RESET}\n"
echo -e "$output"
}
vcs_push() {
[[ "${CONFIG[push_enabled]}" != true ]] && return 0
if jj git push 2>/dev/null; then
log DEBUG "Pushed via jj git push"
return 0
fi
log WARN "Failed to push to remote"
return 1
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Beads Integration
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
beads_check() {
if [[ ! -d ".beads" ]]; then
log ERROR "Beads not initialized. Run: ${C_CYAN}br init${C_RESET}"
return 1
fi
if ! command -v br &>/dev/null; then
log ERROR "br command not found"
return 1
fi
return 0
}
beads_ready_count() {
local epic_flag=""
[[ -n "${CONFIG[epic]}" ]] && epic_flag="--parent ${CONFIG[epic]}"
br ready --json $epic_flag 2>/dev/null | jq -r 'length' 2>/dev/null || echo "0"
}
beads_ready_items() {
local limit=${1:-5}
local epic_flag=""
[[ -n "${CONFIG[epic]}" ]] && epic_flag="--parent ${CONFIG[epic]}"
br ready --json $epic_flag 2>/dev/null | jq -r ".[:$limit][] | \" ${SYM_BULLET} \" + .title" 2>/dev/null || \
br ready --limit "$limit" $epic_flag 2>/dev/null
}
beads_sync() {
br sync 2>/dev/null || true
}
beads_stats() {
br stats 2>/dev/null || echo "No stats available"
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Claude Execution
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Stream Claude output and capture metrics in real-time
run_claude_streaming() {
local prompt_file="$1"
local output_file="$2"
local temp_json=$(mktemp)
local exit_code=0
# Run Claude with stream-json, process output
# Note: We capture PIPESTATUS immediately after pipeline to get claude's exit code
cat "$prompt_file" | claude -p \
--dangerously-skip-permissions \
--model "${CONFIG[model]}" \
--output-format stream-json \
--verbose 2>&1 | tee "$temp_json" | \
while IFS= read -r line; do
# Try to parse as JSON
if echo "$line" | jq -e '.type' &>/dev/null; then
local type=$(echo "$line" | jq -r '.type')
case "$type" in
content_block_delta)
# Extract and print text content
local text=$(echo "$line" | jq -r '.delta.text // empty' 2>/dev/null)
[[ -n "$text" ]] && printf '%s' "$text"
;;
message_start)
# Could extract model info here
;;
message_delta)
# Extract token usage
local usage=$(echo "$line" | jq -r '.usage // empty' 2>/dev/null)
[[ -n "$usage" ]] && echo "$usage" >> "$output_file.usage"
;;
esac
else
# Non-JSON line (verbose output), save to log
echo "$line" >> "$output_file.verbose"
fi
done
# Capture claude's exit code from PIPESTATUS (index 1: cat=0, claude=1, tee=2, while=3)
# Must be done immediately - any command resets PIPESTATUS
exit_code=${PIPESTATUS[1]}
# Move temp file to final location
mv "$temp_json" "$output_file.json"
return $exit_code
}
# Parse token usage from Claude output
parse_claude_metrics() {
local output_file="$1"
local input_tokens=0
local output_tokens=0
# Try to get from usage file first
if [[ -f "$output_file.usage" ]]; then
input_tokens=$(jq -s 'map(.input_tokens // 0) | add' "$output_file.usage" 2>/dev/null || echo 0)
output_tokens=$(jq -s 'map(.output_tokens // 0) | add' "$output_file.usage" 2>/dev/null || echo 0)
fi
# Fallback: parse from verbose output
if [[ $input_tokens -eq 0 ]] && [[ -f "$output_file.verbose" ]]; then
input_tokens=$(grep -oE 'input.?tokens[:\s]+([0-9,]+)' "$output_file.verbose" 2>/dev/null | grep -oE '[0-9,]+' | tr -d ',' | tail -1 || echo 0)
output_tokens=$(grep -oE 'output.?tokens[:\s]+([0-9,]+)' "$output_file.verbose" 2>/dev/null | grep -oE '[0-9,]+' | tr -d ',' | tail -1 || echo 0)
fi
input_tokens=${input_tokens:-0}
output_tokens=${output_tokens:-0}
local total=$((input_tokens + output_tokens))
# Cost calculation (Opus pricing: $15/M input, $75/M output)
local cost=$(bc <<< "scale=4; ($input_tokens * 0.015 + $output_tokens * 0.075) / 1000" 2>/dev/null || echo "0")
STATE[total_tokens]=$((STATE[total_tokens] + total))
STATE[total_cost]=$(bc <<< "scale=2; ${STATE[total_cost]} + $cost" 2>/dev/null || echo "${STATE[total_cost]}")
log_metric "tokens_input" "$input_tokens"
log_metric "tokens_output" "$output_tokens"
log_metric "cost" "$cost"
echo "$total|$cost"
}
# Run Claude with retries
run_claude_with_retry() {
local prompt_file="$1"
local output_file="$2"
local attempt=1
local max_attempts=$((CONFIG[max_retries] + 1))
while [[ $attempt -le $max_attempts ]]; do
[[ "${STATE[interrupted]}" == true ]] && return 1
if [[ $attempt -gt 1 ]]; then
log WARN "Retry $((attempt-1))/${CONFIG[max_retries]} in ${CONFIG[retry_delay]}s..."
sleep "${CONFIG[retry_delay]}" || true
[[ "${STATE[interrupted]}" == true ]] && return 1
fi
local exit_code=0
echo ""
echo -e "${C_DIM}$(printf 'β%.0s' $(seq 1 $TERM_COLS))${C_RESET}"
if run_claude_streaming "$prompt_file" "$output_file"; then
echo ""
echo -e "${C_DIM}$(printf 'β%.0s' $(seq 1 $TERM_COLS))${C_RESET}"
return 0
else
exit_code=$?
fi
[[ "${STATE[interrupted]}" == true ]] && return 1
echo ""
# Check for rate limit
if grep -qi "rate.limit\|429\|too.many.requests" "$output_file.verbose" 2>/dev/null; then
log WARN "Rate limited. Waiting ${CONFIG[rate_limit_pause]}s..."
sleep "${CONFIG[rate_limit_pause]}" || true
[[ "${STATE[interrupted]}" == true ]] && return 1
fi
log ERROR "Claude exited with code $exit_code"
attempt=$((attempt + 1))
done
return 1
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Review Phase
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Run review using codex exec. Returns 0=SHIP, 1=REVISE, 2=parse failure, 3=fatal error
run_review() {
local iter_log="$1"
local review_file="${iter_log}.review"
local feedback_file="${iter_log}.review_feedback"
local review_model="${CONFIG[review_model]}"
local prompt_file="${SCRIPT_DIR}/PROMPT_review.md"
[[ ! -f "$prompt_file" ]] && { log WARN "Review prompt not found: $prompt_file"; return 2; }
# Check that codex command exists
if ! command -v codex &>/dev/null; then
log ERROR "codex command not found - install it or use --no-review"
return 3
fi
# Build review input: jj diff + task context
local review_input
review_input=$(mktemp)
{
echo "## Diff (latest changes)"
echo '```'
jj diff -r @- 2>/dev/null || jj diff 2>/dev/null || echo "(no diff available)"
echo '```'
echo ""
echo "## In-progress tasks"
br list --status in_progress 2>/dev/null || echo "(none)"
echo ""
cat "$prompt_file"
} > "$review_input"
log INFO " ${C_MAGENTA}${SYM_GEAR} Running review${C_RESET} ${C_DIM}(${review_model})${C_RESET}"
# Invoke codex exec in read-only sandbox, full-auto mode
local exit_code=0
if codex exec \
--model "$review_model" \
--sandbox read-only \
--full-auto \
< "$review_input" \
> "$review_file" 2>&1; then
exit_code=0
else
exit_code=$?
log WARN "codex exec exited with code $exit_code"
fi
rm -f "$review_input"
# Detect fatal errors (auth failures, connection errors, unsupported model)
# These should stop the loop, not silently skip review
if [[ $exit_code -ne 0 ]] && [[ -f "$review_file" ]]; then
if grep -qiE '401 Unauthorized|403 Forbidden|exceeded retry limit|not supported|authentication|invalid.*api.*key' "$review_file"; then
log ERROR "Review failed with auth/connection error (codex exit code $exit_code):"
grep -iE 'ERROR:|Unauthorized|Forbidden|exceeded|not supported|authentication|invalid' "$review_file" | head -3 | while IFS= read -r line; do
log ERROR " $line"
done
return 3
fi
fi
# Check if output file has content
if [[ ! -s "$review_file" ]]; then
if [[ $exit_code -ne 0 ]]; then
log ERROR "Review produced no output (codex exit code $exit_code)"
return 3
fi
log WARN "Review produced no output"
return 2
fi
# Parse RESULT line
local result_line
result_line=$(grep -E '^RESULT:\s*(SHIP|REVISE)' "$review_file" | tail -1)
if [[ -z "$result_line" ]]; then
log WARN "Could not parse review result from output"
return 2
fi
if echo "$result_line" | grep -q 'SHIP'; then
log SUCCESS "Review: ${C_GREEN}SHIP${C_RESET}"
return 0
else
log WARN "Review: ${C_YELLOW}REVISE${C_RESET}"
# Save feedback (everything before the RESULT line)
sed '/^RESULT:/d' "$review_file" > "$feedback_file"
return 1
fi
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Session Management
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
session_new() {
STATE[session_id]=$(date +%Y%m%d_%H%M%S)_$$
STATE[start_time]=$(date +%s)
STATE[iteration]=0
STATE[consecutive_failures]=0
STATE[total_tokens]=0
STATE[total_cost]="0"
STATE[status]="initializing"
mkdir -p "$STATE_DIR/sessions/${STATE[session_id]}"
session_save
}
session_save() {
local session_file="$STATE_DIR/sessions/${STATE[session_id]}/state.json"
cat > "$session_file" <<EOF
{
"session_id": "${STATE[session_id]}",
"iteration": ${STATE[iteration]},
"consecutive_failures": ${STATE[consecutive_failures]},
"total_tokens": ${STATE[total_tokens]},
"total_cost": ${STATE[total_cost]},
"start_time": ${STATE[start_time]},
"status": "${STATE[status]}",
"review": {
"enabled": ${CONFIG[review_enabled]},
"model": "${CONFIG[review_model]}",
"passes": ${STATE[review_passes]},
"revisions": ${STATE[review_revisions]},
"skipped": ${STATE[review_skipped]}
},
"config": {
"mode": "${CONFIG[mode]}",
"model": "${CONFIG[model]}",
"max_iterations": ${CONFIG[max_iterations]}
},
"vcs": {
"bookmark": "$(vcs_branch)",
"change": "$(vcs_commit_short)"
},
"updated_at": "$(date -Iseconds)"
}
EOF
# Also update latest symlink
ln -sf "sessions/${STATE[session_id]}" "$STATE_DIR/latest"
}
session_load() {
local session_id="$1"
local session_file="$STATE_DIR/sessions/$session_id/state.json"
[[ ! -f "$session_file" ]] && return 1
STATE[session_id]="$session_id"
STATE[iteration]=$(jq -r '.iteration' "$session_file")
STATE[consecutive_failures]=$(jq -r '.consecutive_failures' "$session_file")
STATE[total_tokens]=$(jq -r '.total_tokens' "$session_file")
STATE[total_cost]=$(jq -r '.total_cost' "$session_file")
STATE[start_time]=$(jq -r '.start_time' "$session_file")
STATE[status]=$(jq -r '.status' "$session_file")
return 0
}
session_list() {
echo -e "${C_BOLD}Recent sessions:${C_RESET}\n"
for dir in $(ls -dt "$STATE_DIR/sessions"/*/ 2>/dev/null | head -10); do
local state_file="$dir/state.json"
[[ ! -f "$state_file" ]] && continue
local sid=$(jq -r '.session_id' "$state_file")
local status=$(jq -r '.status' "$state_file")
local iters=$(jq -r '.iteration' "$state_file")
local updated=$(jq -r '.updated_at' "$state_file")
local status_color="$C_GRAY"
case "$status" in
complete) status_color="$C_GREEN" ;;
running) status_color="$C_CYAN" ;;
failed) status_color="$C_RED" ;;
esac
printf " ${C_BOLD}%s${C_RESET} ${status_color}%-10s${C_RESET} %d iters ${C_DIM}%s${C_RESET}\n" \
"$sid" "$status" "$iters" "$updated"
done
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Main Loop
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
run_iteration() {
local iter_num=$1
local iter_start=$(date +%s)
local session_dir="$STATE_DIR/sessions/${STATE[session_id]}"
local iter_log="$session_dir/iter_$(printf '%03d' $iter_num)"
local before_commit
before_commit=$(jj log -r @ --no-graph -T 'commit_id.shortest(12)' 2>/dev/null || echo "unknown")
STATE[status]="running"
session_save
# Header
echo ""
echo -e "${C_BLUE}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ${C_RESET}"
echo -e "${C_BOLD} ${CONFIG[mode]^^} ITERATION $iter_num${C_RESET} ${C_DIM}$(date '+%H:%M:%S')${C_RESET} ${C_DIM}commit:${C_RESET} $(vcs_commit_short)"
echo -e "${C_BLUE}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ${C_RESET}"
# Sync and show ready work
beads_sync
echo ""
echo -e " ${C_CYAN}${SYM_ARROW} Ready work${C_RESET}"
local ready_count=$(beads_ready_count)
if [[ -z "$ready_count" ]] || [[ "$ready_count" -eq 0 ]] 2>/dev/null; then
echo -e " ${C_DIM}No items ready${C_RESET}"
if [[ "${CONFIG[auto_stop_empty]}" == true ]]; then
log INFO "No more work available"
return 2 # Signal to stop
fi
else
echo -e " ${C_GREEN}$ready_count${C_RESET} items:"
beads_ready_items 3 | head -6
fi
# Interactive confirmation
if [[ "${CONFIG[interactive]}" == true ]]; then
echo ""
read -rp " ${C_YELLOW}Continue? [Y/n/s(kip)]${C_RESET} " response
case "$response" in
n|N) return 2 ;;
s|S) return 0 ;;
esac
fi
# Get prompt file
local prompt_file
if [[ "${CONFIG[mode]}" == "plan" ]]; then
prompt_file="PROMPT_plan.md"
else
prompt_file="PROMPT_build.md"
fi
[[ ! -f "$prompt_file" ]] && { log ERROR "Prompt file not found: $prompt_file"; return 1; }
# If --epic is set, prepend epic context to the prompt
if [[ -n "${CONFIG[epic]}" ]]; then
local epic_prompt_file=$(mktemp)
{
echo "## Epic Context"
echo "You are working within epic \`${CONFIG[epic]}\`. Scope all task selection to this epic."
echo "Use \`br ready --json --limit 1 --type task --parent ${CONFIG[epic]}\` instead of the default br ready call."
echo "If no tasks are found, try \`br ready --json --limit 1 --type bug --parent ${CONFIG[epic]}\`."
echo ""
cat "$prompt_file"
} > "$epic_prompt_file"
prompt_file="$epic_prompt_file"
fi
# Run Claude (with optional review-revision loop)
local revision=0
local max_revisions=${CONFIG[review_max_revisions]}
local review_shipped=false
local active_prompt_file="$prompt_file"
while true; do
revision=$((revision + 1))
# Capture VCS state before Claude runs so we can detect changes
local pre_claude_commit
pre_claude_commit=$(jj log -r @ --no-graph -T 'commit_id.shortest(12)' 2>/dev/null || echo "unknown")
[[ "${STATE[interrupted]}" == true ]] && break
if [[ $revision -gt 1 ]]; then
echo ""
echo -e " ${C_YELLOW}${SYM_ARROW} Revision $((revision - 1))/${max_revisions}${C_RESET} ${C_DIM}(incorporating review feedback)${C_RESET}"
else
echo ""
echo -e " ${C_CYAN}${SYM_ARROW} Running Claude${C_RESET} ${C_DIM}(${CONFIG[model]})${C_RESET}"
fi
if ! run_claude_with_retry "$active_prompt_file" "$iter_log"; then
[[ "${STATE[interrupted]}" == true ]] && return 1
STATE[consecutive_failures]=$((STATE[consecutive_failures] + 1))
STATE[status]="failed"
log_metric "status" "\"failed\""
if [[ ${STATE[consecutive_failures]} -ge ${CONFIG[auto_stop_failures]} ]]; then
log ERROR "${STATE[consecutive_failures]} consecutive failures"
return 2