forked from PolyArch/humanize
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop-codex-stop-hook.sh
More file actions
executable file
·1699 lines (1393 loc) · 64.8 KB
/
loop-codex-stop-hook.sh
File metadata and controls
executable file
·1699 lines (1393 loc) · 64.8 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
#
# Stop Hook for RLCR loop
#
# Intercepts Claude's exit attempts and uses Codex to review work.
# If Codex doesn't confirm completion, blocks exit and feeds review back.
#
# State directory: .humanize/rlcr/<timestamp>/
# State file: state.md (current_round, max_iterations, codex config)
# Summary file: round-N-summary.md (Claude's work summary)
# Review prompt: round-N-review-prompt.md (prompt sent to Codex)
# Review result: round-N-review-result.md (Codex's review)
#
set -euo pipefail
# ========================================
# Default Configuration
# ========================================
# DEFAULT_CODEX_MODEL and DEFAULT_CODEX_EFFORT are provided by loop-common.sh (sourced below)
DEFAULT_CODEX_TIMEOUT=5400
# ========================================
# Read Hook Input
# ========================================
HOOK_INPUT=$(cat)
# NOTE: We intentionally do NOT check stop_hook_active here.
# For iterative loops, stop_hook_active will be true when Claude is continuing
# from a previous blocked stop. We WANT to run Codex review each iteration.
# Loop termination is controlled by:
# - No active loop directory (no state.md) -> exit early below
# - Codex outputs MARKER_COMPLETE -> allow exit
# - current_round >= max_iterations -> allow exit
# ========================================
# Find Active Loop
# ========================================
PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$(pwd)}"
LOOP_BASE_DIR="$PROJECT_ROOT/.humanize/rlcr"
# Source shared loop functions and template loader
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
source "$SCRIPT_DIR/lib/loop-common.sh"
# Source portable timeout wrapper for git operations
PLUGIN_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PLUGIN_ROOT/scripts/portable-timeout.sh"
# Default timeout for git operations (30 seconds)
GIT_TIMEOUT=30
# Template directory is set by loop-common.sh via template-loader.sh
# Extract session_id from hook input for session-aware loop filtering
HOOK_SESSION_ID=$(extract_session_id "$HOOK_INPUT")
LOOP_DIR=$(find_active_loop "$LOOP_BASE_DIR" "$HOOK_SESSION_ID")
# If no active loop (or session_id mismatch), allow exit
if [[ -z "$LOOP_DIR" ]]; then
exit 0
fi
# ========================================
# Detect Loop Phase: Normal or Finalize
# ========================================
# Normal loop: state.md exists
# Finalize Phase: finalize-state.md exists (after Codex COMPLETE, before final completion)
STATE_FILE=$(resolve_active_state_file "$LOOP_DIR")
if [[ -z "$STATE_FILE" ]]; then
# No state file found, allow exit
exit 0
fi
IS_FINALIZE_PHASE=false
if [[ "$STATE_FILE" == *"/finalize-state.md" ]]; then
IS_FINALIZE_PHASE=true
fi
# ========================================
# Parse State File (using shared function)
# ========================================
# First extract raw frontmatter to check which fields are actually present
# This prevents silently using defaults for missing critical fields
RAW_FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$STATE_FILE" 2>/dev/null || echo "")
# Check if critical fields are present before parsing (which applies defaults)
RAW_CURRENT_ROUND=$(echo "$RAW_FRONTMATTER" | grep "^current_round:" || true)
RAW_MAX_ITERATIONS=$(echo "$RAW_FRONTMATTER" | grep "^max_iterations:" || true)
RAW_FULL_REVIEW_ROUND=$(echo "$RAW_FRONTMATTER" | grep "^full_review_round:" || true)
# Use tolerant parsing to extract values
# Note: parse_state_file applies defaults for missing current_round/max_iterations
if ! parse_state_file "$STATE_FILE" 2>/dev/null; then
echo "Warning: parse_state_file returned non-zero, proceeding to schema validation" >&2
fi
# Map STATE_* variables to local names for backward compatibility
PLAN_TRACKED="$STATE_PLAN_TRACKED"
START_BRANCH="$STATE_START_BRANCH"
BASE_BRANCH="${STATE_BASE_BRANCH:-}"
BASE_COMMIT="${STATE_BASE_COMMIT:-}"
PLAN_FILE="$STATE_PLAN_FILE"
CURRENT_ROUND="$STATE_CURRENT_ROUND"
MAX_ITERATIONS="$STATE_MAX_ITERATIONS"
PUSH_EVERY_ROUND="$STATE_PUSH_EVERY_ROUND"
FULL_REVIEW_ROUND="${STATE_FULL_REVIEW_ROUND:-5}"
REVIEW_STARTED="$STATE_REVIEW_STARTED"
# RLCR mode split:
# - codex exec uses state codex_model/codex_effort (from loop-common.sh defaults)
# - codex review uses same model, with fixed effort "high"
CODEX_EXEC_MODEL="${STATE_CODEX_MODEL:-$DEFAULT_CODEX_MODEL}"
CODEX_EXEC_EFFORT="${STATE_CODEX_EFFORT:-$DEFAULT_CODEX_EFFORT}"
CODEX_REVIEW_MODEL="${STATE_CODEX_MODEL:-$DEFAULT_CODEX_MODEL}"
CODEX_REVIEW_EFFORT="high"
CODEX_TIMEOUT="${STATE_CODEX_TIMEOUT:-${CODEX_TIMEOUT:-$DEFAULT_CODEX_TIMEOUT}}"
ASK_CODEX_QUESTION="${STATE_ASK_CODEX_QUESTION:-false}"
AGENT_TEAMS="${STATE_AGENT_TEAMS:-false}"
# Re-validate Codex Model and Effort for YAML safety (in case state.md was manually edited)
# Use same validation patterns as setup-rlcr-loop.sh
if [[ ! "$CODEX_EXEC_MODEL" =~ ^[a-zA-Z0-9._-]+$ ]]; then
echo "Error: Invalid codex_model in state file: $CODEX_EXEC_MODEL" >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_UNEXPECTED"
exit 0
fi
if [[ ! "$CODEX_EXEC_EFFORT" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Error: Invalid codex_effort in state file: $CODEX_EXEC_EFFORT" >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_UNEXPECTED"
exit 0
fi
if [[ ! "$CODEX_REVIEW_MODEL" =~ ^[a-zA-Z0-9._-]+$ ]]; then
echo "Error: Invalid review model in hook config: $CODEX_REVIEW_MODEL" >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_UNEXPECTED"
exit 0
fi
if [[ ! "$CODEX_REVIEW_EFFORT" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Error: Invalid review effort in hook config: $CODEX_REVIEW_EFFORT" >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_UNEXPECTED"
exit 0
fi
# Validate critical fields were actually present (not just defaulted)
# This prevents silently treating a truncated state file as round 0
if [[ -z "$RAW_CURRENT_ROUND" ]]; then
echo "Error: State file missing required field: current_round" >&2
echo " State file may be truncated or corrupted" >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_UNEXPECTED"
exit 0
fi
if [[ -z "$RAW_MAX_ITERATIONS" ]]; then
echo "Error: State file missing required field: max_iterations" >&2
echo " State file may be truncated or corrupted" >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_UNEXPECTED"
exit 0
fi
# Validate numeric fields
if [[ ! "$CURRENT_ROUND" =~ ^[0-9]+$ ]]; then
echo "Warning: State file corrupted (current_round not numeric), stopping loop" >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_UNEXPECTED"
exit 0
fi
if [[ ! "$MAX_ITERATIONS" =~ ^[0-9]+$ ]]; then
echo "Warning: State file corrupted (max_iterations not numeric), using default" >&2
MAX_ITERATIONS=42
fi
# ========================================
# Quick-check 0: Schema Validation (v1.1.2+ fields)
# ========================================
# If schema is outdated, terminate loop as unexpected
if [[ -z "$PLAN_TRACKED" || -z "$START_BRANCH" ]]; then
REASON="RLCR loop state file is missing required fields (plan_tracked or start_branch).
This indicates the loop was started with an older version of humanize.
**Options:**
1. Cancel the loop: \`/humanize:cancel-rlcr-loop\`
2. Update humanize plugin to version 1.1.2+
3. Restart the RLCR loop with the updated plugin"
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - state schema outdated" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
# ========================================
# Quick-check 0.1: Schema Validation (v1.5.0+ fields)
# ========================================
# Validate review_started and base_branch fields for v1.5.0+ state files
if [[ -z "$REVIEW_STARTED" || ( "$REVIEW_STARTED" != "true" && "$REVIEW_STARTED" != "false" ) ]]; then
REASON="RLCR loop state file is missing or has invalid review_started field.
This indicates the loop was started with an older version of humanize (pre-1.5.0).
**Options:**
1. Cancel the loop: \`/humanize:cancel-rlcr-loop\`
2. Update humanize plugin to version 1.5.0+
3. Restart the RLCR loop with the updated plugin"
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - state schema outdated (missing review_started)" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
if [[ -z "$BASE_BRANCH" ]]; then
REASON="RLCR loop state file is missing base_branch field.
This indicates the loop was started with an older version of humanize (pre-1.5.0).
**Options:**
1. Cancel the loop: \`/humanize:cancel-rlcr-loop\`
2. Update humanize plugin to version 1.5.0+
3. Restart the RLCR loop with the updated plugin"
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - state schema outdated (missing base_branch)" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
# ========================================
# Quick-check 0.2: Schema Warning (v1.5.2+ fields)
# ========================================
# Warn about missing full_review_round field (introduced in v1.5.2)
# This is a non-blocking warning - we continue with default value (5)
if [[ -z "$RAW_FULL_REVIEW_ROUND" ]]; then
echo "Note: State file missing full_review_round field (introduced in v1.5.2)." >&2
echo " Using default value: 5 (Full Alignment Checks at rounds 4, 9, 14, ...)" >&2
echo " To use configurable Full Alignment Check intervals, upgrade to humanize v1.5.2+" >&2
echo " and restart the RLCR loop with --full-review-round <N> option." >&2
fi
# ========================================
# Quick-check 0.5: Branch Consistency
# ========================================
# Use || GIT_EXIT_CODE=$? to prevent set -e from aborting on non-zero exit
CURRENT_BRANCH=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" rev-parse --abbrev-ref HEAD 2>/dev/null) || GIT_EXIT_CODE=$?
GIT_EXIT_CODE=${GIT_EXIT_CODE:-0}
if [[ $GIT_EXIT_CODE -ne 0 || -z "$CURRENT_BRANCH" ]]; then
REASON="Git operation failed or timed out.
Cannot verify branch consistency. This may indicate:
- Git is not responding
- Repository is in an invalid state
- Network issues (if remote operations are involved)
Please check git status manually and try again."
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - git operation failed" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
if [[ -n "$START_BRANCH" && "$CURRENT_BRANCH" != "$START_BRANCH" ]]; then
REASON="Git branch changed during RLCR loop.
Started on: $START_BRANCH
Current: $CURRENT_BRANCH
Branch switching is not allowed. Switch back to $START_BRANCH or cancel the loop."
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - branch changed" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
# ========================================
# Quick-check 0.6: Plan File Integrity
# ========================================
# Skip this check in Review Phase (review_started=true)
# In review phase, the plan file is no longer needed - only code review matters.
# This is especially important for skip-impl mode where no real plan file exists.
if [[ "$REVIEW_STARTED" == "true" ]]; then
echo "Review phase: skipping plan file integrity check (plan no longer needed)" >&2
else
BACKUP_PLAN="$LOOP_DIR/plan.md"
FULL_PLAN_PATH="$PROJECT_ROOT/$PLAN_FILE"
# Check backup exists
if [[ ! -f "$BACKUP_PLAN" ]]; then
REASON="Plan file backup not found in loop directory.
Please copy the plan file to the loop directory:
cp \"$FULL_PLAN_PATH\" \"$BACKUP_PLAN\"
This backup is required for plan integrity verification."
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - plan backup missing" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
# Check original plan file still matches backup
if [[ ! -f "$FULL_PLAN_PATH" ]]; then
REASON="Project plan file has been deleted.
Original: $PLAN_FILE
Backup available at: $BACKUP_PLAN
You can restore from backup if needed. Plan file modifications are not allowed during RLCR loop."
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - plan file deleted" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
# Check plan file integrity
# For tracked files: check both git status (uncommitted) AND content diff (committed changes)
# For gitignored files: check content diff only
if [[ "$PLAN_TRACKED" == "true" ]]; then
# Tracked file: first check git status for uncommitted changes
PLAN_GIT_STATUS=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" status --porcelain "$PLAN_FILE" 2>/dev/null || echo "")
if [[ -n "$PLAN_GIT_STATUS" ]]; then
REASON="Plan file has uncommitted modifications.
File: $PLAN_FILE
Status: $PLAN_GIT_STATUS
This RLCR loop was started with --track-plan-file. Plan file modifications are not allowed during the loop."
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - plan file modified (uncommitted)" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
fi
# Plan changes are now allowed: plan.md is a symlink to the original, so this diff always passes
if ! diff -q "$FULL_PLAN_PATH" "$BACKUP_PLAN" &>/dev/null; then
FALLBACK="# Plan File Modified
The plan file \`$PLAN_FILE\` has been modified since the RLCR loop started.
**Modifying plan files is forbidden during an active RLCR loop.**
If you need to change the plan:
1. Cancel the current loop: \`/humanize:cancel-rlcr-loop\`
2. Update the plan file
3. Start a new loop: \`/humanize:start-rlcr-loop $PLAN_FILE\`
Backup available at: \`$BACKUP_PLAN\`"
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/plan-file-modified.md" "$FALLBACK" \
"PLAN_FILE=$PLAN_FILE" \
"BACKUP_PATH=$BACKUP_PLAN")
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - plan file modified" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
fi # End of REVIEW_STARTED != true check for plan file integrity
# ========================================
# Quick Check: Are All Tasks Completed?
# ========================================
# Before running expensive Codex review, check if Claude still has
# incomplete tasks. If yes, block immediately and tell Claude to finish.
# Supports both legacy TodoWrite and new Task system (TaskCreate/TaskUpdate).
TODO_CHECKER="$SCRIPT_DIR/check-todos-from-transcript.py"
if [[ -f "$TODO_CHECKER" ]]; then
# Pass hook input to the task checker
TODO_RESULT=$(echo "$HOOK_INPUT" | python3 "$TODO_CHECKER" 2>&1) || TODO_EXIT=$?
TODO_EXIT=${TODO_EXIT:-0}
if [[ "$TODO_EXIT" -eq 2 ]]; then
# Parse error - block and surface the error
REASON="Task checker encountered a parse error.
Error: $TODO_RESULT
This may indicate an issue with the hook input or transcript format.
Please try again or cancel the loop if this persists."
jq -n \
--arg reason "$REASON" \
--arg msg "Loop: Blocked - task checker parse error" \
'{
"decision": "block",
"reason": $reason,
"systemMessage": $msg
}'
exit 0
fi
if [[ "$TODO_EXIT" -eq 1 ]]; then
# Incomplete tasks found - block immediately without Codex review
# Extract the incomplete task list from the result
INCOMPLETE_LIST=$(echo "$TODO_RESULT" | tail -n +2)
FALLBACK="# Incomplete Tasks
Complete these tasks before exiting:
{{INCOMPLETE_LIST}}"
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/incomplete-todos.md" "$FALLBACK" \
"INCOMPLETE_LIST=$INCOMPLETE_LIST")
jq -n \
--arg reason "$REASON" \
--arg msg "Loop: Blocked - incomplete tasks detected, please finish all tasks first" \
'{
"decision": "block",
"reason": $reason,
"systemMessage": $msg
}'
exit 0
fi
fi
# ========================================
# Helper: Clean Up Stale index.lock
# ========================================
# git status (and other git commands) temporarily create .git/index.lock
# while refreshing the index. If a git process is killed mid-operation
# (e.g., by a timeout wrapper), the lock file can be left behind,
# causing subsequent git add/commit to fail with:
# fatal: Unable to create '.git/index.lock': File exists.
# This helper removes the stale lock so Claude's commit won't fail.
cleanup_stale_index_lock() {
local git_dir
git_dir=$(git rev-parse --git-dir 2>/dev/null) || return 0
if [[ -f "$git_dir/index.lock" ]]; then
echo "Removing stale $git_dir/index.lock" >&2
rm -f "$git_dir/index.lock"
fi
}
# ========================================
# Cache Git Status Output
# ========================================
# Cache git status output to avoid calling it multiple times.
# Used by both large file check and git clean check below.
# IMPORTANT: Fail-closed on git failures to prevent bypassing checks.
GIT_STATUS_CACHED=""
GIT_IS_REPO=false
if command -v git &>/dev/null && run_with_timeout "$GIT_TIMEOUT" git rev-parse --git-dir &>/dev/null 2>&1; then
GIT_IS_REPO=true
# Capture exit code to detect timeout/failure - do NOT use || echo "" which would fail-open
GIT_STATUS_EXIT=0
GIT_STATUS_CACHED=$(run_with_timeout "$GIT_TIMEOUT" git status --porcelain 2>/dev/null) || GIT_STATUS_EXIT=$?
if [[ $GIT_STATUS_EXIT -ne 0 ]]; then
# Git status failed or timed out - fail-closed by blocking exit
# The timed-out git status may have left a stale index.lock
cleanup_stale_index_lock
FALLBACK="# Git Status Failed
Git status operation failed or timed out (exit code {{GIT_STATUS_EXIT}}).
Cannot verify repository state. Please check git status manually and try again."
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/git-status-failed.md" "$FALLBACK" \
"GIT_STATUS_EXIT=$GIT_STATUS_EXIT")
jq -n --arg reason "$REASON" --arg msg "Loop: Blocked - git status failed (exit $GIT_STATUS_EXIT)" \
'{"decision": "block", "reason": $reason, "systemMessage": $msg}'
exit 0
fi
fi
# ========================================
# Quick Check: Large File Detection
# ========================================
# Check if any tracked or new files exceed the line limit.
# Large files should be split into smaller modules.
MAX_LINES=2000
if [[ "$GIT_IS_REPO" == "true" ]]; then
LARGE_FILES=""
while IFS= read -r line; do
# Skip empty lines
if [ -z "$line" ]; then
continue
fi
# Extract filename (skip first 3 chars: "XY ")
filename="${line#???}"
# Handle renames: "old -> new" format
case "$filename" in
*" -> "*) filename="${filename##* -> }" ;;
esac
# Skip deleted files
if [ ! -f "$filename" ]; then
continue
fi
# Get file extension and convert to lowercase
ext="${filename##*.}"
ext_lower=$(to_lower "$ext")
# Determine file type based on extension
case "$ext_lower" in
py|js|ts|tsx|jsx|java|c|cpp|cc|cxx|h|hpp|cs|go|rs|rb|php|swift|kt|kts|scala|sh|bash|zsh)
file_type="code"
;;
md|rst|txt|adoc|asciidoc)
file_type="documentation"
;;
*)
continue
;;
esac
# Count lines and trim whitespace (portable across shells)
line_count=$(wc -l < "$filename" 2>/dev/null | tr -d ' ') || continue
# Validate line_count is numeric before comparison
[[ "$line_count" =~ ^[0-9]+$ ]] || continue
if [ "$line_count" -gt "$MAX_LINES" ]; then
LARGE_FILES="${LARGE_FILES}
- \`${filename}\`: ${line_count} lines (${file_type} file)"
fi
done <<< "$GIT_STATUS_CACHED"
if [ -n "$LARGE_FILES" ]; then
FALLBACK="# Large Files Detected
Files exceeding {{MAX_LINES}} lines:
{{LARGE_FILES}}
Split these into smaller modules before continuing."
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/large-files.md" "$FALLBACK" \
"MAX_LINES=$MAX_LINES" \
"LARGE_FILES=$LARGE_FILES")
jq -n \
--arg reason "$REASON" \
--arg msg "Loop: Blocked - large files detected (>${MAX_LINES} lines), please split into smaller modules" \
'{
"decision": "block",
"reason": $reason,
"systemMessage": $msg
}'
exit 0
fi
fi
# ========================================
# Quick Check: Git Clean and Pushed?
# ========================================
# Before running expensive Codex review, check if all changes have been
# committed and pushed. This ensures work is properly saved.
# Use cached git status from above
if [[ "$GIT_IS_REPO" == "true" ]]; then
GIT_ISSUES=""
SPECIAL_NOTES=""
# Check for uncommitted changes (staged or unstaged) using cached status
if [[ -n "$GIT_STATUS_CACHED" ]]; then
GIT_ISSUES="uncommitted changes"
# Check for special cases in untracked files
UNTRACKED=$(echo "$GIT_STATUS_CACHED" | grep '^??' || true)
# Check if .humanize* directories are untracked (includes .humanize/ and any legacy .humanize-* dirs)
if echo "$UNTRACKED" | grep -q '\.humanize'; then
HUMANIZE_LOCAL_NOTE=$(load_template "$TEMPLATE_DIR" "block/git-not-clean-humanize-local.md" 2>/dev/null)
if [[ -z "$HUMANIZE_LOCAL_NOTE" ]]; then
HUMANIZE_LOCAL_NOTE="Note: .humanize* directories are intentionally untracked."
fi
SPECIAL_NOTES="$SPECIAL_NOTES$HUMANIZE_LOCAL_NOTE"
fi
# Check for other untracked files (potential artifacts)
OTHER_UNTRACKED=$(echo "$UNTRACKED" | grep -v '\.humanize' || true)
if [[ -n "$OTHER_UNTRACKED" ]]; then
UNTRACKED_NOTE=$(load_template "$TEMPLATE_DIR" "block/git-not-clean-untracked.md" 2>/dev/null)
if [[ -z "$UNTRACKED_NOTE" ]]; then
UNTRACKED_NOTE="Review untracked files - add to .gitignore or commit them."
fi
SPECIAL_NOTES="$SPECIAL_NOTES$UNTRACKED_NOTE"
fi
fi
# Block if there are uncommitted changes
if [[ -n "$GIT_ISSUES" ]]; then
# Clean up stale index.lock before Claude attempts git add/commit
cleanup_stale_index_lock
# Git has uncommitted changes - block and remind Claude to commit
FALLBACK="# Git Not Clean
Detected: {{GIT_ISSUES}}
Please commit all changes before exiting.
{{SPECIAL_NOTES}}"
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/git-not-clean.md" "$FALLBACK" \
"GIT_ISSUES=$GIT_ISSUES" \
"SPECIAL_NOTES=$SPECIAL_NOTES")
jq -n \
--arg reason "$REASON" \
--arg msg "Loop: Blocked - $GIT_ISSUES detected, please commit first" \
'{
"decision": "block",
"reason": $reason,
"systemMessage": $msg
}'
exit 0
fi
# ========================================
# Check Unpushed Commits (only when push_every_round is true)
# ========================================
if [[ "$PUSH_EVERY_ROUND" == "true" ]]; then
# Check if local branch is ahead of remote (unpushed commits)
GIT_AHEAD=$(run_with_timeout "$GIT_TIMEOUT" git status -sb 2>/dev/null | grep -o 'ahead [0-9]*' || true)
if [[ -n "$GIT_AHEAD" ]]; then
AHEAD_COUNT=$(echo "$GIT_AHEAD" | grep -o '[0-9]*')
CURRENT_BRANCH=$(run_with_timeout "$GIT_TIMEOUT" git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
FALLBACK="# Unpushed Commits
You have {{AHEAD_COUNT}} unpushed commit(s) on branch {{CURRENT_BRANCH}}.
Please push before exiting."
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/unpushed-commits.md" "$FALLBACK" \
"AHEAD_COUNT=$AHEAD_COUNT" \
"CURRENT_BRANCH=$CURRENT_BRANCH")
jq -n \
--arg reason "$REASON" \
--arg msg "Loop: Blocked - $AHEAD_COUNT unpushed commit(s) detected, please push first" \
'{
"decision": "block",
"reason": $reason,
"systemMessage": $msg
}'
exit 0
fi
fi
fi
# ========================================
# Check Summary File Exists
# ========================================
# In Finalize Phase, expect finalize-summary.md instead of round-N-summary.md
if [[ "$IS_FINALIZE_PHASE" == "true" ]]; then
SUMMARY_FILE="$LOOP_DIR/finalize-summary.md"
else
SUMMARY_FILE="$LOOP_DIR/round-${CURRENT_ROUND}-summary.md"
fi
if [[ ! -f "$SUMMARY_FILE" ]]; then
# Summary file doesn't exist - Claude didn't write it
# Block exit and remind Claude to write summary
FALLBACK="# Work Summary Missing
Please write your work summary to: {{SUMMARY_FILE}}"
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/work-summary-missing.md" "$FALLBACK" \
"SUMMARY_FILE=$SUMMARY_FILE")
if [[ "$IS_FINALIZE_PHASE" == "true" ]]; then
SYSTEM_MSG="Loop: Finalize Phase - summary file missing"
else
SYSTEM_MSG="Loop: Summary file missing for round $CURRENT_ROUND"
fi
jq -n \
--arg reason "$REASON" \
--arg msg "$SYSTEM_MSG" \
'{
"decision": "block",
"reason": $reason,
"systemMessage": $msg
}'
exit 0
fi
# ========================================
# Check Goal Tracker Initialization (Round 0 only, skip in Finalize Phase)
# ========================================
GOAL_TRACKER_FILE="$LOOP_DIR/goal-tracker.md"
# Skip this check in Finalize Phase, Review Phase, or when review_started is already true (skip-impl mode)
# - Finalize Phase: goal tracker was already initialized before COMPLETE
# - Review Phase (review_started=true): skip-impl mode skips implementation, no goal tracker needed
if [[ "$IS_FINALIZE_PHASE" != "true" ]] && [[ "$REVIEW_STARTED" != "true" ]] && [[ "$CURRENT_ROUND" -eq 0 ]] && [[ -f "$GOAL_TRACKER_FILE" ]]; then
# Check if goal-tracker.md still contains placeholder text
# Extract each section and check for generic placeholder pattern within that section
# This avoids coupling to specific placeholder wording and prevents false positives
# from stray mentions of placeholder text elsewhere in the file
HAS_GOAL_PLACEHOLDER=false
HAS_AC_PLACEHOLDER=false
HAS_TASKS_PLACEHOLDER=false
# Extract Ultimate Goal section (### Ultimate Goal to next heading)
# Use awk to extract lines between start and end patterns, excluding end pattern
GOAL_SECTION=$(awk '/^### Ultimate Goal/{found=1; next} /^##/{found=0} found' "$GOAL_TRACKER_FILE" 2>/dev/null)
# Check for generic placeholder pattern "[To be " within this section
if echo "$GOAL_SECTION" | grep -qE '\[To be [a-z]'; then
HAS_GOAL_PLACEHOLDER=true
fi
# Extract Acceptance Criteria section (### Acceptance Criteria to next heading)
AC_SECTION=$(awk '/^### Acceptance Criteria/{found=1; next} /^##/{found=0} found' "$GOAL_TRACKER_FILE" 2>/dev/null)
# Check for generic placeholder pattern "[To be " within this section
if echo "$AC_SECTION" | grep -qE '\[To be [a-z]'; then
HAS_AC_PLACEHOLDER=true
fi
# Extract Active Tasks section (#### Active Tasks to next heading or EOF)
# Active Tasks is a level-4 heading, so match any ## or higher
TASKS_SECTION=$(awk '/^#### Active Tasks/{found=1; next} /^##/{found=0} found' "$GOAL_TRACKER_FILE" 2>/dev/null)
# Check for generic placeholder pattern "[To be " within this section
if echo "$TASKS_SECTION" | grep -qE '\[To be [a-z]'; then
HAS_TASKS_PLACEHOLDER=true
fi
# Build list of missing items
MISSING_ITEMS=""
if [[ "$HAS_GOAL_PLACEHOLDER" == "true" ]]; then
MISSING_ITEMS="$MISSING_ITEMS
- **Ultimate Goal**: Still contains placeholder text"
fi
if [[ "$HAS_AC_PLACEHOLDER" == "true" ]]; then
MISSING_ITEMS="$MISSING_ITEMS
- **Acceptance Criteria**: Still contains placeholder text"
fi
if [[ "$HAS_TASKS_PLACEHOLDER" == "true" ]]; then
MISSING_ITEMS="$MISSING_ITEMS
- **Active Tasks**: Still contains placeholder text"
fi
if [[ -n "$MISSING_ITEMS" ]]; then
FALLBACK="# Goal Tracker Not Initialized
Please fill in the Goal Tracker ({{GOAL_TRACKER_FILE}}):
{{MISSING_ITEMS}}"
REASON=$(load_and_render_safe "$TEMPLATE_DIR" "block/goal-tracker-not-initialized.md" "$FALLBACK" \
"GOAL_TRACKER_FILE=$GOAL_TRACKER_FILE" \
"MISSING_ITEMS=$MISSING_ITEMS")
jq -n \
--arg reason "$REASON" \
--arg msg "Loop: Goal Tracker not initialized in Round 0" \
'{
"decision": "block",
"reason": $reason,
"systemMessage": $msg
}'
exit 0
fi
fi
# ========================================
# Check Max Iterations (skip in Finalize Phase - already post-COMPLETE)
# ========================================
NEXT_ROUND=$((CURRENT_ROUND + 1))
# Skip max iterations check in Finalize Phase or Review Phase
# - Finalize Phase: already received COMPLETE from codex
# - Review Phase: must continue until [P?] issues are cleared, regardless of iteration count
if [[ "$IS_FINALIZE_PHASE" != "true" ]] && [[ "$REVIEW_STARTED" != "true" ]] && [[ $NEXT_ROUND -gt $MAX_ITERATIONS ]]; then
echo "RLCR loop did not complete, but reached max iterations ($MAX_ITERATIONS). Exiting." >&2
end_loop "$LOOP_DIR" "$STATE_FILE" "$EXIT_MAXITER"
exit 0
fi
# ========================================
# Finalize Phase Completion (skip Codex review)
# ========================================
# If we're in Finalize Phase and all checks have passed, complete the loop
# No Codex review is performed - this is the final step after Codex already confirmed COMPLETE
if [[ "$IS_FINALIZE_PHASE" == "true" ]]; then
echo "Finalize Phase complete. All checks passed. Loop finished!" >&2
# Rename finalize-state.md to complete-state.md
mv "$STATE_FILE" "$LOOP_DIR/complete-state.md"
echo "State preserved as: $LOOP_DIR/complete-state.md" >&2
exit 0
fi
# ========================================
# Get Docs Path from Config
# ========================================
# Note: PLUGIN_ROOT already defined at line 51
DOCS_PATH="docs"
# ========================================
# Build Codex Review Prompt
# ========================================
PROMPT_FILE="$LOOP_DIR/round-${CURRENT_ROUND}-prompt.md"
REVIEW_PROMPT_FILE="$LOOP_DIR/round-${CURRENT_ROUND}-review-prompt.md"
REVIEW_RESULT_FILE="$LOOP_DIR/round-${CURRENT_ROUND}-review-result.md"
SUMMARY_CONTENT=$(cat "$SUMMARY_FILE")
# Shared prompt section for Goal Tracker Update Requests (used in both Full Alignment and Regular reviews)
GOAL_TRACKER_SECTION_FALLBACK="## Goal Tracker Updates
If Claude's summary includes a Goal Tracker Update Request section, apply the requested changes to {{GOAL_TRACKER_FILE}}."
GOAL_TRACKER_UPDATE_SECTION=$(load_and_render_safe "$TEMPLATE_DIR" "codex/goal-tracker-update-section.md" "$GOAL_TRACKER_SECTION_FALLBACK" \
"GOAL_TRACKER_FILE=$GOAL_TRACKER_FILE")
# Determine if this is a Full Alignment Check round (every FULL_REVIEW_ROUND rounds)
# Full Alignment Checks occur at rounds (N-1), (2N-1), (3N-1), etc. where N=FULL_REVIEW_ROUND
# Validate FULL_REVIEW_ROUND is a positive integer (default to 5 if invalid/corrupted)
if ! [[ "$FULL_REVIEW_ROUND" =~ ^[0-9]+$ ]] || [[ "$FULL_REVIEW_ROUND" -lt 2 ]]; then
echo "Warning: Invalid full_review_round value '$FULL_REVIEW_ROUND', defaulting to 5" >&2
FULL_REVIEW_ROUND=5
fi
FULL_ALIGNMENT_CHECK=false
if [[ $((CURRENT_ROUND % FULL_REVIEW_ROUND)) -eq $((FULL_REVIEW_ROUND - 1)) ]]; then
FULL_ALIGNMENT_CHECK=true
fi
# Calculate derived values for templates
LOOP_TIMESTAMP=$(basename "$LOOP_DIR")
COMPLETED_ITERATIONS=$((CURRENT_ROUND + 1))
# Clamp previous round indices to 0 minimum to avoid negative file references
# This can happen with --full-review-round 2 where first alignment check is at round 1
PREV_ROUND=$(( CURRENT_ROUND > 0 ? CURRENT_ROUND - 1 : 0 ))
PREV_PREV_ROUND=$(( CURRENT_ROUND > 1 ? CURRENT_ROUND - 2 : 0 ))
# Build the review prompt
FULL_ALIGNMENT_FALLBACK="# Full Alignment Review (Round {{CURRENT_ROUND}})
Review Claude's work against the plan and goal tracker. Check all goals are being met.
## Claude's Summary
{{SUMMARY_CONTENT}}
{{GOAL_TRACKER_UPDATE_SECTION}}
Write your review to {{REVIEW_RESULT_FILE}}. End with COMPLETE if done, or list issues."
REGULAR_REVIEW_FALLBACK="# Code Review (Round {{CURRENT_ROUND}})
Review Claude's work for this round.
## Claude's Summary
{{SUMMARY_CONTENT}}
{{GOAL_TRACKER_UPDATE_SECTION}}
Write your review to {{REVIEW_RESULT_FILE}}. End with COMPLETE if done, or list issues."
if [[ "$FULL_ALIGNMENT_CHECK" == "true" ]]; then
# Full Alignment Check prompt
load_and_render_safe "$TEMPLATE_DIR" "codex/full-alignment-review.md" "$FULL_ALIGNMENT_FALLBACK" \
"CURRENT_ROUND=$CURRENT_ROUND" \
"PLAN_FILE=$PLAN_FILE" \
"SUMMARY_CONTENT=$SUMMARY_CONTENT" \
"GOAL_TRACKER_FILE=$GOAL_TRACKER_FILE" \
"DOCS_PATH=$DOCS_PATH" \
"GOAL_TRACKER_UPDATE_SECTION=$GOAL_TRACKER_UPDATE_SECTION" \
"COMPLETED_ITERATIONS=$COMPLETED_ITERATIONS" \
"LOOP_TIMESTAMP=$LOOP_TIMESTAMP" \
"PREV_ROUND=$PREV_ROUND" \
"PREV_PREV_ROUND=$PREV_PREV_ROUND" \
"REVIEW_RESULT_FILE=$REVIEW_RESULT_FILE" > "$REVIEW_PROMPT_FILE"
else
# Regular review prompt with goal alignment section
# Note: Pass all derived variables for consistency with full alignment template
load_and_render_safe "$TEMPLATE_DIR" "codex/regular-review.md" "$REGULAR_REVIEW_FALLBACK" \
"CURRENT_ROUND=$CURRENT_ROUND" \
"PLAN_FILE=$PLAN_FILE" \
"PROMPT_FILE=$PROMPT_FILE" \
"SUMMARY_CONTENT=$SUMMARY_CONTENT" \
"GOAL_TRACKER_FILE=$GOAL_TRACKER_FILE" \
"DOCS_PATH=$DOCS_PATH" \
"GOAL_TRACKER_UPDATE_SECTION=$GOAL_TRACKER_UPDATE_SECTION" \
"COMPLETED_ITERATIONS=$COMPLETED_ITERATIONS" \
"LOOP_TIMESTAMP=$LOOP_TIMESTAMP" \
"PREV_ROUND=$PREV_ROUND" \
"PREV_PREV_ROUND=$PREV_PREV_ROUND" \
"REVIEW_RESULT_FILE=$REVIEW_RESULT_FILE" > "$REVIEW_PROMPT_FILE"
fi
# ========================================
# Shared Setup: Cache Directory and Codex Arguments
# ========================================
# Initialize these before the REVIEW_STARTED guard so they are available in both
# impl phase (codex exec) and review phase (codex review)
# First, check if codex command exists
if ! command -v codex &>/dev/null; then
REASON="# Codex Not Found
The 'codex' command is not installed or not in PATH.
RLCR loop requires Codex CLI to perform code reviews.
**To fix:**
1. Install Codex CLI: https://github.com/openai/codex
2. Retry the exit
Or use \`/cancel-rlcr-loop\` to end the loop."
cat <<EOF
{
"decision": "block",
"reason": $(echo "$REASON" | jq -Rs .)
}
EOF
exit 0
fi
# Debug log files go to XDG_CACHE_HOME/humanize/<project-path>/<timestamp>/ to avoid polluting project dir
# Respects XDG_CACHE_HOME for testability in restricted environments (falls back to $HOME/.cache)
# This prevents Claude and Codex from reading these debug files during their work
# The project path is sanitized to replace problematic characters with '-'
LOOP_TIMESTAMP=$(basename "$LOOP_DIR")
# Sanitize project root path: replace / and other problematic chars with -
# This matches Claude Code's convention (e.g., /home/sihao/github.com/foo -> -home-sihao-github-com-foo)
SANITIZED_PROJECT_PATH=$(echo "$PROJECT_ROOT" | sed 's/[^a-zA-Z0-9._-]/-/g' | sed 's/--*/-/g')
CACHE_BASE="${XDG_CACHE_HOME:-$HOME/.cache}"
CACHE_DIR="$CACHE_BASE/humanize/$SANITIZED_PROJECT_PATH/$LOOP_TIMESTAMP"
mkdir -p "$CACHE_DIR"
# Note: portable-timeout.sh already sourced at line 52
# Build Codex command arguments for codex exec
# codex exec uses: -m MODEL, --full-auto (or --dangerously-bypass-approvals-and-sandbox), -C DIR, -c key=value
CODEX_EXEC_ARGS=("-m" "$CODEX_EXEC_MODEL")
if [[ -n "$CODEX_EXEC_EFFORT" ]]; then
CODEX_EXEC_ARGS+=("-c" "model_reasoning_effort=${CODEX_EXEC_EFFORT}")
fi
# Determine automation flag based on environment variable
# Default: Use --full-auto (safe mode with sandbox)
# If HUMANIZE_CODEX_BYPASS_SANDBOX is "true" or "1": Use --dangerously-bypass-approvals-and-sandbox
CODEX_AUTO_FLAG="--full-auto"
if [[ "${HUMANIZE_CODEX_BYPASS_SANDBOX:-}" == "true" ]] || [[ "${HUMANIZE_CODEX_BYPASS_SANDBOX:-}" == "1" ]]; then
CODEX_AUTO_FLAG="--dangerously-bypass-approvals-and-sandbox"
fi
CODEX_EXEC_ARGS+=("$CODEX_AUTO_FLAG" "-C" "$PROJECT_ROOT")
# Build Codex command arguments for codex review
# codex review uses different format: -c model=xxx -c review_model=xxx -c model_reasoning_effort=xxx
# No -m, no --full-auto, no -C
CODEX_REVIEW_ARGS=("-c" "model=${CODEX_REVIEW_MODEL}" "-c" "review_model=${CODEX_REVIEW_MODEL}")
if [[ -n "$CODEX_REVIEW_EFFORT" ]]; then
CODEX_REVIEW_ARGS+=("-c" "model_reasoning_effort=${CODEX_REVIEW_EFFORT}")
fi
# ========================================
# Helper Functions for Code Review Phase
# ========================================
# Run codex review and save debug files
# Arguments: $1=round_number
# Sets: CODEX_REVIEW_EXIT_CODE, CODEX_REVIEW_LOG_FILE
# Returns: exit code from codex review
# Note: codex review --base cannot be used with PROMPT, so we only use --base and -c args
run_codex_code_review() {
local round="$1"
local timestamp
timestamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
# Determine review base: prefer BASE_COMMIT (captured at loop start) over BASE_BRANCH
# Using the fixed commit SHA prevents comparing a branch to itself when working on main,
# as the branch ref advances with each commit but the captured SHA stays fixed
local review_base="${BASE_COMMIT:-$BASE_BRANCH}"
local review_base_type="branch"
if [[ -n "$BASE_COMMIT" ]]; then
review_base_type="commit"
fi
CODEX_REVIEW_CMD_FILE="$CACHE_DIR/round-${round}-codex-review.cmd"
# Note: codex review outputs everything to stderr, so we capture both stdout and stderr to the log file
CODEX_REVIEW_LOG_FILE="$CACHE_DIR/round-${round}-codex-review.log"
local prompt_file="$LOOP_DIR/round-${round}-review-prompt.md"
# Create audit prompt file (codex review doesn't accept prompts, but we create this for audit)
local prompt_fallback="# Code Review Phase - Round ${round}
This file documents the code review invocation for audit purposes.
Note: codex review does not accept prompt input; it performs automated code review based on git diff.
## Review Configuration
- Base Branch: ${BASE_BRANCH}
- Base Commit: ${BASE_COMMIT:-N/A}
- Review Base (${review_base_type}): ${review_base}
- Review Round: ${round}
- Timestamp: ${timestamp}
"
load_and_render_safe "$TEMPLATE_DIR" "codex/code-review-phase.md" "$prompt_fallback" \
"REVIEW_ROUND=$round" \
"BASE_BRANCH=$BASE_BRANCH" \