-
Notifications
You must be signed in to change notification settings - Fork 619
Expand file tree
/
Copy pathralph_loop.sh
More file actions
executable file
·2510 lines (2180 loc) · 103 KB
/
ralph_loop.sh
File metadata and controls
executable file
·2510 lines (2180 loc) · 103 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
# Claude Code Ralph Loop with Rate Limiting and Documentation
# Adaptation of the Ralph technique for Claude Code with usage management
# Note: CLAUDE_CODE_ENABLE_DANGEROUS_PERMISSIONS_IN_SANDBOX and IS_SANDBOX
# environment variables are NOT exported here. Tool restrictions are handled
# via --allowedTools flag in CLAUDE_CMD_ARGS, which is the proper approach.
# Exporting sandbox variables without a verified sandbox would be misleading.
# Source library components
SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")"
source "$SCRIPT_DIR/lib/date_utils.sh" || { echo "FATAL: Failed to source lib/date_utils.sh" >&2; exit 1; }
source "$SCRIPT_DIR/lib/timeout_utils.sh" || { echo "FATAL: Failed to source lib/timeout_utils.sh" >&2; exit 1; }
source "$SCRIPT_DIR/lib/response_analyzer.sh" || { echo "FATAL: Failed to source lib/response_analyzer.sh" >&2; exit 1; }
source "$SCRIPT_DIR/lib/circuit_breaker.sh" || { echo "FATAL: Failed to source lib/circuit_breaker.sh" >&2; exit 1; }
source "$SCRIPT_DIR/lib/file_protection.sh" || { echo "FATAL: Failed to source lib/file_protection.sh" >&2; exit 1; }
source "$SCRIPT_DIR/lib/log_utils.sh" || { echo "FATAL: Failed to source lib/log_utils.sh" >&2; exit 1; }
# Configuration
# Ralph-specific files live in .ralph/ subfolder
RALPH_DIR=".ralph"
PROMPT_FILE="$RALPH_DIR/PROMPT.md"
LOG_DIR="$RALPH_DIR/logs"
DOCS_DIR="$RALPH_DIR/docs/generated"
STATUS_FILE="$RALPH_DIR/status.json"
PROGRESS_FILE="$RALPH_DIR/progress.json"
SLEEP_DURATION=3600 # 1 hour in seconds
LIVE_OUTPUT=false # Show Claude Code output in real-time (streaming)
LIVE_LOG_FILE="$RALPH_DIR/live.log" # Fixed file for live output monitoring
CALL_COUNT_FILE="$RALPH_DIR/.call_count"
TOKEN_COUNT_FILE="$RALPH_DIR/.token_count"
TIMESTAMP_FILE="$RALPH_DIR/.last_reset"
USE_TMUX=false
# Save environment variable state BEFORE setting defaults
# These are used by load_ralphrc() to determine which values came from environment
_env_MAX_CALLS_PER_HOUR="${MAX_CALLS_PER_HOUR:-}"
_env_MAX_TOKENS_PER_HOUR="${MAX_TOKENS_PER_HOUR:-}"
_env_CLAUDE_TIMEOUT_MINUTES="${CLAUDE_TIMEOUT_MINUTES:-}"
_env_CLAUDE_OUTPUT_FORMAT="${CLAUDE_OUTPUT_FORMAT:-}"
_env_CLAUDE_ALLOWED_TOOLS="${CLAUDE_ALLOWED_TOOLS:-}"
_env_CLAUDE_USE_CONTINUE="${CLAUDE_USE_CONTINUE:-}"
_env_CLAUDE_SESSION_EXPIRY_HOURS="${CLAUDE_SESSION_EXPIRY_HOURS:-}"
_env_VERBOSE_PROGRESS="${VERBOSE_PROGRESS:-}"
_env_CB_COOLDOWN_MINUTES="${CB_COOLDOWN_MINUTES:-}"
_env_CB_AUTO_RESET="${CB_AUTO_RESET:-}"
_env_CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-}"
_env_CLAUDE_AUTO_UPDATE="${CLAUDE_AUTO_UPDATE:-}"
_env_CLAUDE_MODEL="${CLAUDE_MODEL:-}"
_env_CLAUDE_EFFORT="${CLAUDE_EFFORT:-}"
_env_RALPH_SHELL_INIT_FILE="${RALPH_SHELL_INIT_FILE:-}"
_env_ENABLE_NOTIFICATIONS="${ENABLE_NOTIFICATIONS:-}"
_env_ENABLE_BACKUP="${ENABLE_BACKUP:-}"
# Now set defaults (only if not already set by environment)
MAX_CALLS_PER_HOUR="${MAX_CALLS_PER_HOUR:-100}"
MAX_TOKENS_PER_HOUR="${MAX_TOKENS_PER_HOUR:-0}" # 0 = disabled; set to limit cumulative tokens/hour
VERBOSE_PROGRESS="${VERBOSE_PROGRESS:-false}"
CLAUDE_TIMEOUT_MINUTES="${CLAUDE_TIMEOUT_MINUTES:-15}"
# Modern Claude CLI configuration (Phase 1.1)
CLAUDE_OUTPUT_FORMAT="${CLAUDE_OUTPUT_FORMAT:-json}"
# Safe git subcommands only - broad Bash(git *) allows destructive commands like git clean/git rm (Issue #149)
CLAUDE_ALLOWED_TOOLS="${CLAUDE_ALLOWED_TOOLS:-Write,Read,Edit,Bash(git add *),Bash(git commit *),Bash(git diff *),Bash(git log *),Bash(git status),Bash(git status *),Bash(git push *),Bash(git pull *),Bash(git fetch *),Bash(git checkout *),Bash(git branch *),Bash(git stash *),Bash(git merge *),Bash(git tag *),Bash(npm *),Bash(pytest)}"
CLAUDE_USE_CONTINUE="${CLAUDE_USE_CONTINUE:-true}"
CLAUDE_SESSION_FILE="$RALPH_DIR/.claude_session_id" # Session ID persistence file
CLAUDE_MIN_VERSION="2.0.76" # Minimum required Claude CLI version
CLAUDE_AUTO_UPDATE="${CLAUDE_AUTO_UPDATE:-true}" # Auto-update Claude CLI at startup
CLAUDE_CODE_CMD="${CLAUDE_CODE_CMD:-claude}" # Claude Code CLI command (default: global install)
CLAUDE_MODEL="${CLAUDE_MODEL:-}" # Model override (e.g. claude-sonnet-4-6); empty = CLI default
CLAUDE_EFFORT="${CLAUDE_EFFORT:-}" # Effort level override (e.g. high, low); empty = CLI default
RALPH_SHELL_INIT_FILE="${RALPH_SHELL_INIT_FILE:-}" # Shell init file to source before running claude (e.g. ~/.zshrc)
DRY_RUN="${DRY_RUN:-false}" # Simulate loop without making actual Claude API calls
ENABLE_NOTIFICATIONS="${ENABLE_NOTIFICATIONS:-false}" # Enable desktop notifications; set true or use --notify flag
ENABLE_BACKUP="${ENABLE_BACKUP:-false}" # Enable automatic git backups before each loop; set true or use --backup flag
# Session management configuration (Phase 1.2)
# Note: SESSION_EXPIRATION_SECONDS is defined in lib/response_analyzer.sh (86400 = 24 hours)
RALPH_SESSION_FILE="$RALPH_DIR/.ralph_session" # Ralph-specific session tracking (lifecycle)
RALPH_SESSION_HISTORY_FILE="$RALPH_DIR/.ralph_session_history" # Session transition history
# Session expiration: 24 hours default balances project continuity with fresh context
# Too short = frequent context loss; Too long = stale context causes unpredictable behavior
CLAUDE_SESSION_EXPIRY_HOURS=${CLAUDE_SESSION_EXPIRY_HOURS:-24}
# Valid tool patterns for --allowed-tools validation
# Tools can be exact matches or pattern matches with wildcards in parentheses
VALID_TOOL_PATTERNS=(
"Write"
"Read"
"Edit"
"MultiEdit"
"Glob"
"Grep"
"Task"
"TodoWrite"
"WebFetch"
"WebSearch"
"Bash"
"Bash(git *)"
"Bash(npm *)"
"Bash(bats *)"
"Bash(python *)"
"Bash(node *)"
"NotebookEdit"
)
# Exit detection configuration
EXIT_SIGNALS_FILE="$RALPH_DIR/.exit_signals"
RESPONSE_ANALYSIS_FILE="$RALPH_DIR/.response_analysis"
MAX_CONSECUTIVE_TEST_LOOPS=3
MAX_CONSECUTIVE_DONE_SIGNALS=2
TEST_PERCENTAGE_THRESHOLD=30 # If more than 30% of recent loops are test-only, flag it
# .ralphrc configuration file
RALPHRC_FILE=".ralphrc"
RALPHRC_LOADED=false
# load_ralphrc - Load project-specific configuration from .ralphrc
#
# This function sources .ralphrc if it exists, applying project-specific
# settings. Environment variables take precedence over .ralphrc values.
#
# Configuration values that can be overridden:
# - MAX_CALLS_PER_HOUR
# - MAX_TOKENS_PER_HOUR (cumulative token limit per hour; 0 = disabled)
# - CLAUDE_TIMEOUT_MINUTES
# - CLAUDE_OUTPUT_FORMAT
# - ALLOWED_TOOLS (mapped to CLAUDE_ALLOWED_TOOLS)
# - SESSION_CONTINUITY (mapped to CLAUDE_USE_CONTINUE)
# - SESSION_EXPIRY_HOURS (mapped to CLAUDE_SESSION_EXPIRY_HOURS)
# - CB_NO_PROGRESS_THRESHOLD
# - CB_SAME_ERROR_THRESHOLD
# - CB_OUTPUT_DECLINE_THRESHOLD
# - RALPH_VERBOSE
# - CLAUDE_CODE_CMD (path or command for Claude Code CLI)
# - CLAUDE_AUTO_UPDATE (auto-update Claude CLI at startup)
# - RALPH_SHELL_INIT_FILE (shell init file to source before running claude)
#
load_ralphrc() {
if [[ ! -f "$RALPHRC_FILE" ]]; then
return 0
fi
# Source .ralphrc (this may override default values)
# shellcheck source=/dev/null
source "$RALPHRC_FILE"
# Map .ralphrc variable names to internal names
if [[ -n "${ALLOWED_TOOLS:-}" ]]; then
CLAUDE_ALLOWED_TOOLS="$ALLOWED_TOOLS"
fi
if [[ -n "${SESSION_CONTINUITY:-}" ]]; then
CLAUDE_USE_CONTINUE="$SESSION_CONTINUITY"
fi
if [[ -n "${SESSION_EXPIRY_HOURS:-}" ]]; then
CLAUDE_SESSION_EXPIRY_HOURS="$SESSION_EXPIRY_HOURS"
fi
if [[ -n "${RALPH_VERBOSE:-}" ]]; then
VERBOSE_PROGRESS="$RALPH_VERBOSE"
fi
# Restore ONLY values that were explicitly set via environment variables
# (not script defaults). The _env_* variables were captured BEFORE defaults were set.
# If _env_* is non-empty, the user explicitly set it in their environment.
[[ -n "$_env_MAX_CALLS_PER_HOUR" ]] && MAX_CALLS_PER_HOUR="$_env_MAX_CALLS_PER_HOUR"
[[ -n "$_env_MAX_TOKENS_PER_HOUR" ]] && MAX_TOKENS_PER_HOUR="$_env_MAX_TOKENS_PER_HOUR"
[[ -n "$_env_CLAUDE_TIMEOUT_MINUTES" ]] && CLAUDE_TIMEOUT_MINUTES="$_env_CLAUDE_TIMEOUT_MINUTES"
[[ -n "$_env_CLAUDE_OUTPUT_FORMAT" ]] && CLAUDE_OUTPUT_FORMAT="$_env_CLAUDE_OUTPUT_FORMAT"
[[ -n "$_env_CLAUDE_ALLOWED_TOOLS" ]] && CLAUDE_ALLOWED_TOOLS="$_env_CLAUDE_ALLOWED_TOOLS"
[[ -n "$_env_CLAUDE_USE_CONTINUE" ]] && CLAUDE_USE_CONTINUE="$_env_CLAUDE_USE_CONTINUE"
[[ -n "$_env_CLAUDE_SESSION_EXPIRY_HOURS" ]] && CLAUDE_SESSION_EXPIRY_HOURS="$_env_CLAUDE_SESSION_EXPIRY_HOURS"
[[ -n "$_env_VERBOSE_PROGRESS" ]] && VERBOSE_PROGRESS="$_env_VERBOSE_PROGRESS"
[[ -n "$_env_CB_COOLDOWN_MINUTES" ]] && CB_COOLDOWN_MINUTES="$_env_CB_COOLDOWN_MINUTES"
[[ -n "$_env_CB_AUTO_RESET" ]] && CB_AUTO_RESET="$_env_CB_AUTO_RESET"
[[ -n "$_env_CLAUDE_CODE_CMD" ]] && CLAUDE_CODE_CMD="$_env_CLAUDE_CODE_CMD"
[[ -n "$_env_CLAUDE_AUTO_UPDATE" ]] && CLAUDE_AUTO_UPDATE="$_env_CLAUDE_AUTO_UPDATE"
[[ -n "$_env_CLAUDE_MODEL" ]] && CLAUDE_MODEL="$_env_CLAUDE_MODEL"
[[ -n "$_env_CLAUDE_EFFORT" ]] && CLAUDE_EFFORT="$_env_CLAUDE_EFFORT"
[[ -n "$_env_RALPH_SHELL_INIT_FILE" ]] && RALPH_SHELL_INIT_FILE="$_env_RALPH_SHELL_INIT_FILE"
[[ -n "$_env_ENABLE_NOTIFICATIONS" ]] && ENABLE_NOTIFICATIONS="$_env_ENABLE_NOTIFICATIONS"
[[ -n "$_env_ENABLE_BACKUP" ]] && ENABLE_BACKUP="$_env_ENABLE_BACKUP"
RALPHRC_LOADED=true
return 0
}
# validate_claude_command - Verify the Claude Code CLI is available
#
# Checks that CLAUDE_CODE_CMD resolves to an executable command.
# For npx-based commands, validates that npx is available.
# Returns 0 if valid, 1 if not found (with helpful error message).
#
validate_claude_command() {
local cmd="$CLAUDE_CODE_CMD"
# For npx-based commands, check that npx itself is available
if [[ "$cmd" == npx\ * ]] || [[ "$cmd" == "npx" ]]; then
if ! command -v npx &>/dev/null; then
echo ""
echo -e "${RED}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║ NPX NOT FOUND ║${NC}"
echo -e "${RED}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}CLAUDE_CODE_CMD is set to use npx, but npx is not installed.${NC}"
echo ""
echo -e "${YELLOW}To fix this:${NC}"
echo " 1. Install Node.js (includes npx): https://nodejs.org"
echo " 2. Or install Claude Code globally:"
echo " npm install -g @anthropic-ai/claude-code"
echo " Then set in .ralphrc: CLAUDE_CODE_CMD=\"claude\""
echo ""
return 1
fi
return 0
fi
# For direct commands, check that the command exists
if ! command -v "$cmd" &>/dev/null; then
echo ""
echo -e "${RED}╔════════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║ CLAUDE CODE CLI NOT FOUND ║${NC}"
echo -e "${RED}╚════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}The Claude Code CLI command '${cmd}' is not available.${NC}"
echo ""
echo -e "${YELLOW}Installation options:${NC}"
echo " 1. Install globally (recommended):"
echo " npm install -g @anthropic-ai/claude-code"
echo ""
echo " 2. Use npx (no global install needed):"
echo " Add to .ralphrc: CLAUDE_CODE_CMD=\"npx @anthropic-ai/claude-code\""
echo ""
echo -e "${YELLOW}Current configuration:${NC} CLAUDE_CODE_CMD=\"${cmd}\""
echo ""
echo -e "${YELLOW}After installation or configuration:${NC}"
echo " ralph --monitor # Restart Ralph"
echo ""
return 1
fi
return 0
}
# Colors for terminal output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m' # No Color
# Initialize directories
mkdir -p "$LOG_DIR" "$DOCS_DIR"
# Check if tmux is available
check_tmux_available() {
if ! command -v tmux &> /dev/null; then
log_status "ERROR" "tmux is not installed. Please install tmux or run without --monitor flag."
echo "Install tmux:"
echo " Ubuntu/Debian: sudo apt-get install tmux"
echo " macOS: brew install tmux"
echo " CentOS/RHEL: sudo yum install tmux"
exit 1
fi
}
# Get the tmux base-index for windows (handles custom tmux configurations)
# Returns: the base window index (typically 0 or 1)
get_tmux_base_index() {
local base_index
base_index=$(tmux show-options -gv base-index 2>/dev/null)
# Default to 0 if not set or tmux command fails
echo "${base_index:-0}"
}
# Setup tmux session with monitor
setup_tmux_session() {
local session_name="ralph-$(date +%s)"
local ralph_home="${RALPH_HOME:-$HOME/.ralph}"
local project_dir="$(pwd)"
# Get the tmux base-index to handle custom configurations (e.g., base-index 1)
local base_win
base_win=$(get_tmux_base_index)
log_status "INFO" "Setting up tmux session: $session_name"
# Initialize live.log file
echo "=== Ralph Live Output - Waiting for first loop... ===" > "$LIVE_LOG_FILE"
# Create new tmux session detached (left pane - Ralph loop)
tmux new-session -d -s "$session_name" -c "$project_dir"
# Split window vertically (right side)
tmux split-window -h -t "$session_name" -c "$project_dir"
# Split right pane horizontally (top: Claude output, bottom: status)
tmux split-window -v -t "$session_name:${base_win}.1" -c "$project_dir"
# Right-top pane (pane 1): Live Claude Code output
tmux send-keys -t "$session_name:${base_win}.1" "tail -f '$project_dir/$LIVE_LOG_FILE'" Enter
# Right-bottom pane (pane 2): Ralph status monitor
if command -v ralph-monitor &> /dev/null; then
tmux send-keys -t "$session_name:${base_win}.2" "ralph-monitor" Enter
else
tmux send-keys -t "$session_name:${base_win}.2" "'$ralph_home/ralph_monitor.sh'" Enter
fi
# Start ralph loop in the left pane (exclude tmux flag to avoid recursion)
# Forward all CLI parameters that were set by the user
local ralph_cmd
if command -v ralph &> /dev/null; then
ralph_cmd="ralph"
else
ralph_cmd="'$ralph_home/ralph_loop.sh'"
fi
# Always use --live mode in tmux for real-time streaming
ralph_cmd="$ralph_cmd --live"
# Forward --calls if non-default
if [[ "$MAX_CALLS_PER_HOUR" != "100" ]]; then
ralph_cmd="$ralph_cmd --calls $MAX_CALLS_PER_HOUR"
fi
# Forward --prompt if non-default
if [[ "$PROMPT_FILE" != "$RALPH_DIR/PROMPT.md" ]]; then
ralph_cmd="$ralph_cmd --prompt '$PROMPT_FILE'"
fi
# Forward --output-format if non-default (default is json)
if [[ "$CLAUDE_OUTPUT_FORMAT" != "json" ]]; then
ralph_cmd="$ralph_cmd --output-format $CLAUDE_OUTPUT_FORMAT"
fi
# Forward --verbose if enabled
if [[ "$VERBOSE_PROGRESS" == "true" ]]; then
ralph_cmd="$ralph_cmd --verbose"
fi
# Forward --timeout if non-default (default is 15)
if [[ "$CLAUDE_TIMEOUT_MINUTES" != "15" ]]; then
ralph_cmd="$ralph_cmd --timeout $CLAUDE_TIMEOUT_MINUTES"
fi
# Forward --allowed-tools if non-default
# Safe git subcommands only - broad Bash(git *) allows destructive commands like git clean/git rm (Issue #149)
if [[ "$CLAUDE_ALLOWED_TOOLS" != "Write,Read,Edit,Bash(git add *),Bash(git commit *),Bash(git diff *),Bash(git log *),Bash(git status),Bash(git status *),Bash(git push *),Bash(git pull *),Bash(git fetch *),Bash(git checkout *),Bash(git branch *),Bash(git stash *),Bash(git merge *),Bash(git tag *),Bash(npm *),Bash(pytest)" ]]; then
ralph_cmd="$ralph_cmd --allowed-tools '$CLAUDE_ALLOWED_TOOLS'"
fi
# Forward --no-continue if session continuity disabled
if [[ "$CLAUDE_USE_CONTINUE" == "false" ]]; then
ralph_cmd="$ralph_cmd --no-continue"
fi
# Forward --session-expiry if non-default (default is 24)
if [[ "$CLAUDE_SESSION_EXPIRY_HOURS" != "24" ]]; then
ralph_cmd="$ralph_cmd --session-expiry $CLAUDE_SESSION_EXPIRY_HOURS"
fi
# Forward --auto-reset-circuit if enabled
if [[ "$CB_AUTO_RESET" == "true" ]]; then
ralph_cmd="$ralph_cmd --auto-reset-circuit"
fi
# Forward --backup if enabled (Issue #23)
if [[ "$ENABLE_BACKUP" == "true" ]]; then
ralph_cmd="$ralph_cmd --backup"
fi
# Chain tmux kill-session after the loop command so the entire tmux
# session is torn down when the Ralph loop exits (graceful completion,
# circuit breaker, error, or manual interrupt). Without this, the
# tail -f and ralph_monitor.sh panes keep the session alive forever.
# Issue: https://github.com/frankbria/ralph-claude-code/issues/176
tmux send-keys -t "$session_name:${base_win}.0" "$ralph_cmd; tmux kill-session -t $session_name 2>/dev/null" Enter
# Focus on left pane (main ralph loop)
tmux select-pane -t "$session_name:${base_win}.0"
# Set pane titles (requires tmux 2.6+)
tmux select-pane -t "$session_name:${base_win}.0" -T "Ralph Loop"
tmux select-pane -t "$session_name:${base_win}.1" -T "Claude Output"
tmux select-pane -t "$session_name:${base_win}.2" -T "Status"
# Set window title
tmux rename-window -t "$session_name:${base_win}" "Ralph: Loop | Output | Status"
log_status "SUCCESS" "Tmux session created with 3 panes:"
log_status "INFO" " Left: Ralph loop"
log_status "INFO" " Right-top: Claude Code live output"
log_status "INFO" " Right-bottom: Status monitor"
log_status "INFO" ""
log_status "INFO" "Use Ctrl+B then D to detach from session"
log_status "INFO" "Use 'tmux attach -t $session_name' to reattach"
# Attach to session (this will block until session ends)
tmux attach-session -t "$session_name"
exit 0
}
# Initialize call tracking
init_call_tracking() {
# Debug logging removed for cleaner output
local current_hour=$(date +%Y%m%d%H)
local last_reset_hour=""
if [[ -f "$TIMESTAMP_FILE" ]]; then
last_reset_hour=$(cat "$TIMESTAMP_FILE")
fi
# Reset counters if it's a new hour
if [[ "$current_hour" != "$last_reset_hour" ]]; then
echo "0" > "$CALL_COUNT_FILE"
echo "0" > "$TOKEN_COUNT_FILE"
echo "$current_hour" > "$TIMESTAMP_FILE"
log_status "INFO" "Call and token counters reset for new hour: $current_hour"
fi
# Initialize exit signals tracking if it doesn't exist
if [[ ! -f "$EXIT_SIGNALS_FILE" ]]; then
echo '{"test_only_loops": [], "done_signals": [], "completion_indicators": []}' > "$EXIT_SIGNALS_FILE"
fi
# Initialize circuit breaker
init_circuit_breaker
}
# Log function with timestamps and colors
log_status() {
local level=$1
local message=$2
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
local color=""
case $level in
"INFO") color=$BLUE ;;
"WARN") color=$YELLOW ;;
"ERROR") color=$RED ;;
"SUCCESS") color=$GREEN ;;
"LOOP") color=$PURPLE ;;
esac
# Write to stderr so log messages don't interfere with function return values
# 2>/dev/null suppresses "Input/output error" when tmux pty is broken (Issue #188)
echo -e "${color}[$timestamp] [$level] $message${NC}" >&2 2>/dev/null
echo "[$timestamp] [$level] $message" >> "$LOG_DIR/ralph.log" 2>/dev/null
}
# Update status JSON for external monitoring
update_status() {
local loop_count=$1
local calls_made=$2
local last_action=$3
local status=$4
local exit_reason=${5:-""}
local tokens_used
tokens_used=$(cat "$TOKEN_COUNT_FILE" 2>/dev/null || echo "0")
cat > "$STATUS_FILE" << STATUSEOF
{
"timestamp": "$(get_iso_timestamp)",
"loop_count": $loop_count,
"calls_made_this_hour": $calls_made,
"max_calls_per_hour": $MAX_CALLS_PER_HOUR,
"tokens_used_this_hour": $tokens_used,
"max_tokens_per_hour": $MAX_TOKENS_PER_HOUR,
"last_action": "$last_action",
"status": "$status",
"exit_reason": "$exit_reason",
"next_reset": "$(get_next_hour_time)"
}
STATUSEOF
}
# Send a desktop notification if ENABLE_NOTIFICATIONS is true
# Cross-platform: macOS (osascript), Linux (notify-send), fallback (terminal bell)
# Errors are suppressed so notification failures never break the loop.
send_notification() {
local title="$1"
local message="$2"
[[ "$ENABLE_NOTIFICATIONS" == "true" ]] || return 0
# Strip double quotes to prevent osascript AppleScript string breakage
local safe_title="${title//\"/}"
local safe_message="${message//\"/}"
if command -v osascript &>/dev/null; then
osascript -e "display notification \"$safe_message\" with title \"$safe_title\"" 2>/dev/null || true
elif command -v notify-send &>/dev/null; then
notify-send "$title" "$message" 2>/dev/null || true
else
printf '\a\n'
fi
}
# Extract token usage from a Claude output file
# Handles both Claude CLI format (metadata.usage) and stream-json result format (.usage)
# Outputs total tokens (input + output), or 0 on failure
extract_token_usage() {
local output_file=$1
if [[ ! -f "$output_file" ]]; then
echo "0"
return
fi
local tokens
tokens=$(jq -r '
((.usage.input_tokens // .metadata.usage.input_tokens // 0) |
if type == "number" then . else 0 end) +
((.usage.output_tokens // .metadata.usage.output_tokens // 0) |
if type == "number" then . else 0 end)
' "$output_file" 2>/dev/null)
echo "${tokens:-0}"
}
# Accumulate token usage after a Claude invocation
update_token_count() {
local output_file=$1
local new_tokens
new_tokens=$(extract_token_usage "$output_file")
if [[ "$new_tokens" -gt 0 ]] 2>/dev/null; then
local current
current=$(cat "$TOKEN_COUNT_FILE" 2>/dev/null || echo "0")
echo $(( current + new_tokens )) > "$TOKEN_COUNT_FILE"
log_status "INFO" "Tokens this hour: $((current + new_tokens))${MAX_TOKENS_PER_HOUR:+/$MAX_TOKENS_PER_HOUR} (+${new_tokens})"
fi
}
# Check if we can make another call
can_make_call() {
local calls_made=0
if [[ -f "$CALL_COUNT_FILE" ]]; then
calls_made=$(cat "$CALL_COUNT_FILE")
fi
if [[ $calls_made -ge $MAX_CALLS_PER_HOUR ]]; then
return 1 # Cannot make call — invocation limit reached
fi
# Check token limit only when configured (MAX_TOKENS_PER_HOUR > 0)
if [[ "${MAX_TOKENS_PER_HOUR:-0}" -gt 0 ]] 2>/dev/null; then
local tokens_used=0
tokens_used=$(cat "$TOKEN_COUNT_FILE" 2>/dev/null || echo "0")
if [[ $tokens_used -ge $MAX_TOKENS_PER_HOUR ]]; then
return 1 # Cannot make call — token limit reached
fi
fi
return 0 # Can make call
}
# Increment call counter
increment_call_counter() {
local calls_made=0
if [[ -f "$CALL_COUNT_FILE" ]]; then
calls_made=$(cat "$CALL_COUNT_FILE")
fi
((calls_made++))
echo "$calls_made" > "$CALL_COUNT_FILE"
echo "$calls_made"
}
# Track loop execution metrics to logs/metrics.jsonl (Issue #21)
# Arguments: loop_num duration_seconds success(true|false) calls_made
track_metrics() {
local loop_num=$1
local duration=$2
local success=$3
local calls=$4
local ts
ts=$(get_iso_timestamp)
local metrics_file="$LOG_DIR/metrics.jsonl"
mkdir -p "$LOG_DIR"
printf '{"timestamp":"%s","loop":%d,"duration":%d,"success":%s,"calls":%d}\n' \
"$ts" "$loop_num" "$duration" "$success" "$calls" >> "$metrics_file"
}
# Print a one-line metrics summary from logs/metrics.jsonl (Issue #21)
print_metrics_summary() {
local metrics_file="$LOG_DIR/metrics.jsonl"
[[ -f "$metrics_file" ]] || return 0
command -v jq &>/dev/null || return 0
local summary
summary=$(jq -s '{
total_loops: length,
successful: (map(select(.success==true)) | length),
avg_duration: (if length > 0 then (map(.duration) | add) / length else 0 end),
total_calls: (map(.calls) | add // 0)
}' "$metrics_file" 2>/dev/null)
[[ -n "$summary" ]] && log_status "INFO" "Metrics summary: $summary"
}
# Wait for rate limit reset with countdown
wait_for_reset() {
local calls_made=$(cat "$CALL_COUNT_FILE" 2>/dev/null || echo "0")
local tokens_used=$(cat "$TOKEN_COUNT_FILE" 2>/dev/null || echo "0")
local limit_reason="calls: $calls_made/$MAX_CALLS_PER_HOUR"
if [[ "${MAX_TOKENS_PER_HOUR:-0}" -gt 0 ]]; then
limit_reason="$limit_reason, tokens: $tokens_used/$MAX_TOKENS_PER_HOUR"
fi
log_status "WARN" "Rate limit reached ($limit_reason). Waiting for reset..."
send_notification "Ralph - Rate Limit" "Rate limit reached ($limit_reason). Waiting for reset..."
# Calculate time until next hour
local current_minute=$(date +%M)
local current_second=$(date +%S)
local wait_time=$(((60 - current_minute - 1) * 60 + (60 - current_second)))
log_status "INFO" "Sleeping for $wait_time seconds until next hour..."
# Countdown display
while [[ $wait_time -gt 0 ]]; do
local hours=$((wait_time / 3600))
local minutes=$(((wait_time % 3600) / 60))
local seconds=$((wait_time % 60))
printf "\r${YELLOW}Time until reset: %02d:%02d:%02d${NC}" $hours $minutes $seconds
sleep 1
((wait_time--))
done
printf "\n"
# Reset counters
echo "0" > "$CALL_COUNT_FILE"
echo "0" > "$TOKEN_COUNT_FILE"
echo "$(date +%Y%m%d%H)" > "$TIMESTAMP_FILE"
log_status "SUCCESS" "Rate limit reset! Ready for new calls."
}
# Check if we should gracefully exit
should_exit_gracefully() {
if [[ ! -f "$EXIT_SIGNALS_FILE" ]]; then
return 1 # Don't exit, file doesn't exist
fi
local signals=$(cat "$EXIT_SIGNALS_FILE")
# Count recent signals (last 5 loops) - with error handling
local recent_test_loops
local recent_done_signals
local recent_completion_indicators
recent_test_loops=$(echo "$signals" | jq '.test_only_loops | length' 2>/dev/null || echo "0")
recent_done_signals=$(echo "$signals" | jq '.done_signals | length' 2>/dev/null || echo "0")
recent_completion_indicators=$(echo "$signals" | jq '.completion_indicators | length' 2>/dev/null || echo "0")
# Diagnostic logging for exit signal check (Issue #194)
[[ "${VERBOSE_PROGRESS:-}" == "true" ]] && log_status "DEBUG" "Exit check: test_loops=$recent_test_loops done_signals=$recent_done_signals completion_indicators=$recent_completion_indicators"
# Check for exit conditions
# 0. Permission denials (highest priority - Issue #101)
# When Claude Code is denied permission to run commands, halt immediately
# to allow user to update .ralphrc ALLOWED_TOOLS configuration
if [[ -f "$RESPONSE_ANALYSIS_FILE" ]]; then
local has_permission_denials=$(jq -r '.analysis.has_permission_denials // false' "$RESPONSE_ANALYSIS_FILE" 2>/dev/null || echo "false")
if [[ "$has_permission_denials" == "true" ]]; then
local denied_count=$(jq -r '.analysis.permission_denial_count // 0' "$RESPONSE_ANALYSIS_FILE" 2>/dev/null || echo "0")
local denied_cmds=$(jq -r '.analysis.denied_commands | join(", ")' "$RESPONSE_ANALYSIS_FILE" 2>/dev/null || echo "unknown")
log_status "WARN" "🚫 Permission denied for $denied_count command(s): $denied_cmds"
log_status "WARN" "Update ALLOWED_TOOLS in .ralphrc to include the required tools"
echo "permission_denied"
return 0
fi
fi
# 1. Too many consecutive test-only loops
if [[ $recent_test_loops -ge $MAX_CONSECUTIVE_TEST_LOOPS ]]; then
log_status "WARN" "Exit condition: Too many test-focused loops ($recent_test_loops >= $MAX_CONSECUTIVE_TEST_LOOPS)"
echo "test_saturation"
return 0
fi
# 2. Multiple "done" signals
if [[ $recent_done_signals -ge $MAX_CONSECUTIVE_DONE_SIGNALS ]]; then
log_status "WARN" "Exit condition: Multiple completion signals ($recent_done_signals >= $MAX_CONSECUTIVE_DONE_SIGNALS)"
echo "completion_signals"
return 0
fi
# 3. Safety circuit breaker - force exit after 5 consecutive EXIT_SIGNAL=true responses
# Note: completion_indicators only accumulates when Claude explicitly sets EXIT_SIGNAL=true
# (not based on confidence score). This safety breaker catches cases where Claude signals
# completion 5+ times but the normal exit path (completion_indicators >= 2 + EXIT_SIGNAL=true)
# didn't trigger for some reason. Threshold of 5 prevents API waste while being higher than
# the normal threshold (2) to avoid false positives.
if [[ $recent_completion_indicators -ge 5 ]]; then
log_status "WARN" "🚨 SAFETY CIRCUIT BREAKER: Force exit after 5 consecutive EXIT_SIGNAL=true responses ($recent_completion_indicators)" >&2
echo "safety_circuit_breaker"
return 0
fi
# 4. Strong completion indicators (only if Claude's EXIT_SIGNAL is true)
# This prevents premature exits when heuristics detect completion patterns
# but Claude explicitly indicates work is still in progress via RALPH_STATUS block.
# The exit_signal in .response_analysis represents Claude's explicit intent.
local claude_exit_signal="false"
if [[ -f "$RESPONSE_ANALYSIS_FILE" ]]; then
claude_exit_signal=$(jq -r '.analysis.exit_signal // false' "$RESPONSE_ANALYSIS_FILE" 2>/dev/null || echo "false")
fi
if [[ $recent_completion_indicators -ge 2 ]] && [[ "$claude_exit_signal" == "true" ]]; then
log_status "WARN" "Exit condition: Strong completion indicators ($recent_completion_indicators) with EXIT_SIGNAL=true" >&2
echo "project_complete"
return 0
fi
# 5. Check fix_plan.md for completion
# Fix #144: Only match valid markdown checkboxes, not date entries like [2026-01-29]
# Valid patterns: "- [ ]" (uncompleted) and "- [x]" or "- [X]" (completed)
if [[ -f "$RALPH_DIR/fix_plan.md" ]]; then
local uncompleted_items=$(grep -cE "^[[:space:]]*- \[ \]" "$RALPH_DIR/fix_plan.md" 2>/dev/null || echo "0")
local completed_items=$(grep -cE "^[[:space:]]*- \[[xX]\]" "$RALPH_DIR/fix_plan.md" 2>/dev/null || echo "0")
local total_items=$((uncompleted_items + completed_items))
if [[ $total_items -gt 0 ]] && [[ $completed_items -eq $total_items ]]; then
log_status "WARN" "Exit condition: All fix_plan.md items completed ($completed_items/$total_items)" >&2
echo "plan_complete"
return 0
fi
fi
echo "" # Return empty string instead of using return code
}
# =============================================================================
# MODERN CLI HELPER FUNCTIONS (Phase 1.1)
# =============================================================================
# Compare two semver strings: returns 0 if ver1 >= ver2, 1 if ver1 < ver2
# Uses sequential major→minor→patch comparison (safe for any patch number)
compare_semver() {
local ver1="$1" ver2="$2"
local v1_major v1_minor v1_patch
local v2_major v2_minor v2_patch
IFS='.' read -r v1_major v1_minor v1_patch <<< "$ver1"
IFS='.' read -r v2_major v2_minor v2_patch <<< "$ver2"
v1_major=${v1_major:-0}; v1_minor=${v1_minor:-0}; v1_patch=${v1_patch:-0}
v2_major=${v2_major:-0}; v2_minor=${v2_minor:-0}; v2_patch=${v2_patch:-0}
if [[ $v1_major -gt $v2_major ]]; then return 0; fi
if [[ $v1_major -lt $v2_major ]]; then return 1; fi
if [[ $v1_minor -gt $v2_minor ]]; then return 0; fi
if [[ $v1_minor -lt $v2_minor ]]; then return 1; fi
if [[ $v1_patch -lt $v2_patch ]]; then return 1; fi
return 0
}
# Check Claude CLI version for compatibility with modern flags
check_claude_version() {
local version
version=$($CLAUDE_CODE_CMD --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if [[ -z "$version" ]]; then
log_status "WARN" "Cannot detect Claude CLI version, assuming compatible"
return 0
fi
if ! compare_semver "$version" "$CLAUDE_MIN_VERSION"; then
log_status "WARN" "Claude CLI version $version < $CLAUDE_MIN_VERSION. Some modern features may not work."
log_status "WARN" "Consider upgrading: npm update -g @anthropic-ai/claude-code"
return 1
fi
log_status "INFO" "Claude CLI version $version (>= $CLAUDE_MIN_VERSION) - modern features enabled"
return 0
}
# Check for Claude CLI updates and attempt auto-update (Issue #190)
check_claude_updates() {
if [[ "${CLAUDE_AUTO_UPDATE:-true}" != "true" ]]; then
return 0
fi
local installed_version
installed_version=$($CLAUDE_CODE_CMD --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if [[ -z "$installed_version" ]]; then
return 0
fi
# Query latest version from npm registry (with timeout to avoid hanging on flaky networks)
local latest_version
latest_version=$(portable_timeout 5s npm view @anthropic-ai/claude-code version 2>/dev/null)
if [[ -z "$latest_version" ]]; then
log_status "INFO" "Could not check for Claude CLI updates (npm registry unreachable)"
return 0
fi
if [[ "$installed_version" == "$latest_version" ]]; then
log_status "INFO" "Claude CLI is up to date ($installed_version)"
return 0
fi
if compare_semver "$installed_version" "$latest_version"; then
return 0
fi
# Auto-update attempt
log_status "INFO" "Claude CLI update available: $installed_version → $latest_version. Attempting auto-update..."
local update_output
if update_output=$(npm update -g @anthropic-ai/claude-code 2>&1); then
local new_version
new_version=$($CLAUDE_CODE_CMD --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
log_status "SUCCESS" "Claude CLI updated: $installed_version → ${new_version:-$latest_version}"
return 0
fi
# Auto-update failed — warn with environment-specific guidance
log_status "WARN" "Claude CLI auto-update failed ($installed_version → $latest_version)"
[[ -n "$update_output" ]] && log_status "DEBUG" "npm output: $update_output"
log_status "WARN" "Update manually: npm update -g @anthropic-ai/claude-code"
log_status "WARN" "In Docker: rebuild your image to include the latest version"
return 1
}
# Validate allowed tools against whitelist
# Returns 0 if valid, 1 if invalid with error message
validate_allowed_tools() {
local tools_input=$1
if [[ -z "$tools_input" ]]; then
return 0 # Empty is valid (uses defaults)
fi
# Split by comma
local IFS=','
read -ra tools <<< "$tools_input"
for tool in "${tools[@]}"; do
# Trim whitespace
tool=$(echo "$tool" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
if [[ -z "$tool" ]]; then
continue
fi
local valid=false
# Check against valid patterns
for pattern in "${VALID_TOOL_PATTERNS[@]}"; do
if [[ "$tool" == "$pattern" ]]; then
valid=true
break
fi
# Check for Bash(*) pattern - any Bash with parentheses is allowed
if [[ "$tool" =~ ^Bash\(.+\)$ ]]; then
valid=true
break
fi
done
if [[ "$valid" == "false" ]]; then
echo "Error: Invalid tool in --allowed-tools: '$tool'"
echo "Valid tools: ${VALID_TOOL_PATTERNS[*]}"
echo "Note: Bash(...) patterns with any content are allowed (e.g., 'Bash(git *)')"
return 1
fi
done
return 0
}
# Build loop context for Claude Code session
# Provides loop-specific context via --append-system-prompt
build_loop_context() {
local loop_count=$1
local context=""
# Add loop number
context="Loop #${loop_count}. "
# Extract incomplete tasks from fix_plan.md
# Bug #3 Fix: Support indented markdown checkboxes with [[:space:]]* pattern
if [[ -f "$RALPH_DIR/fix_plan.md" ]]; then
local incomplete_tasks=$(grep -cE "^[[:space:]]*- \[ \]" "$RALPH_DIR/fix_plan.md" 2>/dev/null || echo "0")
context+="Remaining tasks: ${incomplete_tasks}. "
fi
# Add circuit breaker state
if [[ -f "$RALPH_DIR/.circuit_breaker_state" ]]; then
local cb_state=$(jq -r '.state // "UNKNOWN"' "$RALPH_DIR/.circuit_breaker_state" 2>/dev/null)
if [[ "$cb_state" != "CLOSED" && "$cb_state" != "null" && -n "$cb_state" ]]; then
context+="Circuit breaker: ${cb_state}. "
fi
fi
# Add previous loop summary (truncated)
if [[ -f "$RESPONSE_ANALYSIS_FILE" ]]; then
local prev_summary=$(jq -r '.analysis.work_summary // ""' "$RESPONSE_ANALYSIS_FILE" 2>/dev/null | head -c 200)
if [[ -n "$prev_summary" && "$prev_summary" != "null" ]]; then
context+="Previous: ${prev_summary} "
fi
fi
# If previous loop detected questions, inject corrective guidance (Issue #190 Bug 2)
if [[ -f "$RESPONSE_ANALYSIS_FILE" ]]; then
local prev_asking_questions
prev_asking_questions=$(jq -r '.analysis.asking_questions // false' "$RESPONSE_ANALYSIS_FILE" 2>/dev/null || echo "false")
if [[ "$prev_asking_questions" == "true" ]]; then
context+="IMPORTANT: You asked questions in the previous loop. This is a headless automation loop with no human to answer. Do NOT ask questions. Choose the most conservative/safe default and proceed autonomously. "
fi
fi
# Limit total length to ~500 chars
echo "${context:0:500}"
}
# Get session file age in hours (cross-platform)
# Returns: age in hours on stdout, or -1 if stat fails
# Note: Returns 0 for files less than 1 hour old
get_session_file_age_hours() {
local file=$1
if [[ ! -f "$file" ]]; then
echo "0"
return
fi
# Get file modification time using capability detection
# Handles macOS with Homebrew coreutils where stat flags differ
local file_mtime
# Try GNU stat first (Linux, macOS with Homebrew coreutils)
if file_mtime=$(stat -c %Y "$file" 2>/dev/null) && [[ -n "$file_mtime" && "$file_mtime" =~ ^[0-9]+$ ]]; then
: # success
# Try BSD stat (native macOS)
elif file_mtime=$(stat -f %m "$file" 2>/dev/null) && [[ -n "$file_mtime" && "$file_mtime" =~ ^[0-9]+$ ]]; then
: # success
# Fallback to date -r (most portable)
elif file_mtime=$(date -r "$file" +%s 2>/dev/null) && [[ -n "$file_mtime" && "$file_mtime" =~ ^[0-9]+$ ]]; then
: # success
else
file_mtime=""
fi
# Handle stat failure - return -1 to indicate error
# This prevents false expiration when stat fails
if [[ -z "$file_mtime" || "$file_mtime" == "0" ]]; then
echo "-1"
return
fi
local current_time
current_time=$(date +%s)
local age_seconds=$((current_time - file_mtime))
local age_hours=$((age_seconds / 3600))
echo "$age_hours"
}
# Initialize or resume Claude session (with expiration check)
#
# Session Expiration Strategy:
# - Default expiration: 24 hours (configurable via CLAUDE_SESSION_EXPIRY_HOURS)
# - 24 hours chosen because: long enough for multi-day projects, short enough
# to prevent stale context from causing unpredictable behavior
# - Sessions auto-expire to ensure Claude starts fresh periodically
#
# Returns (stdout):
# - Session ID string: when resuming a valid, non-expired session
# - Empty string: when starting new session (no file, expired, or stat error)
#
# Return codes:
# - 0: Always returns success (caller should check stdout for session ID)
#
init_claude_session() {
if [[ -f "$CLAUDE_SESSION_FILE" ]]; then
# Check session age
local age_hours
age_hours=$(get_session_file_age_hours "$CLAUDE_SESSION_FILE")
# Handle stat failure (-1) - treat as needing new session
# Don't expire sessions when we can't determine age
if [[ $age_hours -eq -1 ]]; then
log_status "WARN" "Could not determine session age, starting new session"
rm -f "$CLAUDE_SESSION_FILE"
echo ""
return 0
fi
# Check if session has expired
if [[ $age_hours -ge $CLAUDE_SESSION_EXPIRY_HOURS ]]; then
log_status "INFO" "Session expired (${age_hours}h old, max ${CLAUDE_SESSION_EXPIRY_HOURS}h), starting new session"
rm -f "$CLAUDE_SESSION_FILE"
echo ""
return 0
fi
# Session is valid, try to read it
local session_id=$(cat "$CLAUDE_SESSION_FILE" 2>/dev/null)
if [[ -n "$session_id" ]]; then
log_status "INFO" "Resuming Claude session: ${session_id:0:20}... (${age_hours}h old)"
echo "$session_id"
return 0