setup-rlcr-loop.sh 55.8 KB
Newer Older
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
#!/usr/bin/env bash
#
# Setup script for start-rlcr-loop
#
# Creates state files for the loop that uses Codex to review Claude's work.
#
# Usage:
#   setup-rlcr-loop.sh <path/to/plan.md> [--max N] [--codex-model MODEL:EFFORT]
#

set -euo pipefail

# ========================================
# Default Configuration
# ========================================

# DEFAULT_CODEX_MODEL and DEFAULT_CODEX_EFFORT are provided by loop-common.sh
DEFAULT_CODEX_TIMEOUT=5400
DEFAULT_MAX_ITERATIONS=84
DEFAULT_FULL_REVIEW_ROUND=5

# Default timeout for git operations (30 seconds)
GIT_TIMEOUT=30

# Source portable timeout wrapper
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
source "$SCRIPT_DIR/portable-timeout.sh"

# Source shared loop library (provides runtime-aware DEFAULT_CODEX_MODEL and other constants)
# Callers can override by exporting DEFAULT_CODEX_MODEL/DEFAULT_CODEX_EFFORT/DEFAULT_AGENT_TEAMS
# before invoking this script.
HOOKS_LIB_DIR="$(cd "$SCRIPT_DIR/../hooks/lib" && pwd)"
source "$HOOKS_LIB_DIR/loop-common.sh"

# ========================================
# Parse Arguments
# ========================================

PLAN_FILE=""
PLAN_FILE_EXPLICIT=""
TRACK_PLAN_FILE="false"
MAX_ITERATIONS="$DEFAULT_MAX_ITERATIONS"
CODEX_MODEL="$DEFAULT_CODEX_MODEL"
CODEX_EFFORT="$DEFAULT_CODEX_EFFORT"
CODEX_TIMEOUT="$DEFAULT_CODEX_TIMEOUT"
PUSH_EVERY_ROUND="false"
BASE_BRANCH=""
FULL_REVIEW_ROUND="$DEFAULT_FULL_REVIEW_ROUND"
SKIP_IMPL="false"
SKIP_IMPL_NO_PLAN="false"
SKIP_IMPL_PLAN_ANCHORED="false"
ASK_CODEX_QUESTION="true"
AGENT_TEAMS="${DEFAULT_AGENT_TEAMS:-false}"
BITLESSON_ALLOW_EMPTY_NONE="true"
PRIVACY_MODE="false"

extract_plan_goal_content() {
    local plan_path="$1"
    local goal_section=""

    goal_section=$({ sed -n '/^##[[:space:]]*[Gg]oal\|^##[[:space:]]*[Oo]bjective\|^##[[:space:]]*[Pp]urpose/,/^##/p' "$plan_path" 2>/dev/null || true; } | head -20 | tail -n +2 | head -10)
    if [[ -n "$goal_section" ]]; then
        printf '%s\n' "$goal_section"
        return
    fi

    awk '
        /^[[:space:]]*#/ { next }
        /^[[:space:]]*$/ {
            if (started) {
                exit
            }
            next
        }
        {
            print
            started=1
            lines++
            if (lines >= 5) {
                exit
            }
        }
    ' "$plan_path"
}

extract_plan_ac_content() {
    local plan_path="$1"
    { sed -n '/^##[[:space:]]*[Aa]cceptance\|^##[[:space:]]*[Cc]riteria\|^##[[:space:]]*[Rr]equirements/,/^##/p' "$plan_path" 2>/dev/null || true; } | head -30 | tail -n +2 | head -25
}

show_help() {
    cat <<HELP_EOF
start-rlcr-loop - Iterative development with Codex review

USAGE:
  /humanize:start-rlcr-loop <path/to/plan.md> [OPTIONS]

ARGUMENTS:
  <path/to/plan.md>    Path to a markdown file containing the implementation plan
                       (must exist, have at least 5 lines, no spaces in path)

OPTIONS:
  --plan-file <path>   Explicit plan file path (alternative to positional arg)
  --track-plan-file    Indicate plan file should be tracked in git (must be clean)
  --max <N>            Maximum iterations before auto-stop (default: 84)
  --codex-model <MODEL:EFFORT>
                       Codex model and reasoning effort for codex exec (default: ${DEFAULT_CODEX_MODEL}:${DEFAULT_CODEX_EFFORT})
  --codex-timeout <SECONDS>
                       Timeout for each Codex review in seconds (default: 5400)
  --push-every-round   Require git push after each round (default: commits stay local)
  --base-branch <BRANCH>
                       Base branch for code review phase (default: auto-detect)
                       Priority: user input > remote default > main > master
  --full-review-round <N>
                       Interval for Full Alignment Check rounds (default: 5, min: 2)
                       Full Alignment Checks occur at rounds N-1, 2N-1, 3N-1, etc.
  --skip-impl          Skip implementation phase and go directly to code review
                       Plan file is optional when using this flag
  --claude-answer-codex
                       When Codex finds Open Questions, let Claude answer them
                       directly instead of asking user via AskUserQuestion.
                       NOT RECOMMENDED: Open Questions usually indicate gaps in
                       your plan that deserve human clarification. By default,
                       Claude asks user for clarification, which is preferred.
  --agent-teams        Enable Claude Code Agent Teams mode for parallel development.
                       Requires CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 environment variable.
                       Claude acts as team leader, splitting tasks among team members.
  --yolo               Skip Plan Understanding Quiz and let Claude answer Codex Open
                       Questions directly. Convenience alias for --skip-quiz
                       --claude-answer-codex. Use when you trust the plan and want
                       maximum automation.
  --skip-quiz          Skip the Plan Understanding Quiz only (without other behavioral
                       changes). The quiz is an advisory pre-flight check that verifies
                       you understand the plan before committing to an RLCR loop.
  --allow-empty-bitlesson-none
                       Allow BitLesson delta with action:none even with no new entries (default)
  --require-bitlesson-entry-for-none
                       Require at least one BitLesson entry when action is none
  --privacy            Disable methodology analysis at loop exit (default: analysis enabled)
  -h, --help           Show this help message

DESCRIPTION:
  Starts an iterative loop with Codex review in your CURRENT session.
  This command:

  1. Takes a markdown plan file as input (not a prompt string)
  2. Uses Codex to independently review Claude's work each iteration
  3. Has two phases: Implementation Phase and Review Phase

  The flow:
  1. Claude executes plan tasks with tag-based routing (Implementation Phase)
     - \`coding\` tasks: Claude implements directly
     - \`analyze\` tasks: Claude delegates execution via \`/humanize:ask-codex\`
  2. Claude writes a summary to round-N-summary.md
  3. On exit attempt, Codex reviews the summary
  4. If Codex finds issues, it blocks exit and sends feedback
  5. If Codex outputs "COMPLETE", enters Review Phase
  6. In Review Phase, codex review checks code quality with [P0-9] markers
  7. If code review finds issues, Claude fixes them
  8. When no issues found, enters Finalize Phase and loop ends

EXAMPLES:
  /humanize:start-rlcr-loop docs/feature-plan.md
  /humanize:start-rlcr-loop docs/impl.md --max 20
  /humanize:start-rlcr-loop plan.md --codex-model ${DEFAULT_CODEX_MODEL}:${DEFAULT_CODEX_EFFORT}
  /humanize:start-rlcr-loop plan.md --codex-timeout 7200  # 2 hour timeout
  /humanize:start-rlcr-loop plan.md --yolo              # skip quiz, full automation
  /humanize:start-rlcr-loop plan.md --skip-quiz          # skip quiz only

STOPPING:
  - /humanize:cancel-rlcr-loop   Cancel the active loop
  - Reach --max iterations
  - Pass code review (no [P0-9] issues) after COMPLETE

MONITORING:
  # View current state:
  cat .humanize/rlcr/*/state.md

  # View latest summary:
  cat .humanize/rlcr/*/round-*-summary.md | tail -50

  # View Codex review:
  cat .humanize/rlcr/*/round-*-review-result.md | tail -50
HELP_EOF
    exit 0
}

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            show_help
            ;;
        --max)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --max requires a number argument" >&2
                exit 1
            fi
            if ! [[ "$2" =~ ^[0-9]+$ ]]; then
                echo "Error: --max must be a positive integer, got: $2" >&2
                exit 1
            fi
            MAX_ITERATIONS="$2"
            shift 2
            ;;
        --codex-model)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --codex-model requires a MODEL:EFFORT argument" >&2
                exit 1
            fi
            # Parse MODEL:EFFORT format (portable - works in bash and zsh)
            if [[ "$2" == *:* ]]; then
                CODEX_MODEL="${2%%:*}"
                CODEX_EFFORT="${2#*:}"
            else
                CODEX_MODEL="$2"
                CODEX_EFFORT="$DEFAULT_CODEX_EFFORT"
            fi
            shift 2
            ;;
        --codex-timeout)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --codex-timeout requires a number argument (seconds)" >&2
                exit 1
            fi
            if ! [[ "$2" =~ ^[0-9]+$ ]]; then
                echo "Error: --codex-timeout must be a positive integer (seconds), got: $2" >&2
                exit 1
            fi
            CODEX_TIMEOUT="$2"
            shift 2
            ;;
        --push-every-round)
            PUSH_EVERY_ROUND="true"
            shift
            ;;
        --plan-file)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --plan-file requires a file path" >&2
                exit 1
            fi
            PLAN_FILE_EXPLICIT="$2"
            shift 2
            ;;
        --track-plan-file)
            TRACK_PLAN_FILE="true"
            shift
            ;;
        --base-branch)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --base-branch requires a branch name argument" >&2
                exit 1
            fi
            BASE_BRANCH="$2"
            shift 2
            ;;
        --full-review-round)
            if [[ -z "${2:-}" ]]; then
                echo "Error: --full-review-round requires a number argument" >&2
                exit 1
            fi
            if ! [[ "$2" =~ ^[0-9]+$ ]]; then
                echo "Error: --full-review-round must be a positive integer, got: $2" >&2
                exit 1
            fi
            if [[ "$2" -lt 2 ]]; then
                echo "Error: --full-review-round must be at least 2, got: $2" >&2
                exit 1
            fi
            FULL_REVIEW_ROUND="$2"
            shift 2
            ;;
        --skip-impl)
            SKIP_IMPL="true"
            shift
            ;;
        --claude-answer-codex)
            ASK_CODEX_QUESTION="false"
            shift
            ;;
        --agent-teams)
            AGENT_TEAMS="true"
            shift
            ;;
        --yolo)
            ASK_CODEX_QUESTION="false"
            shift
            ;;
        --skip-quiz)
            # No-op in setup script; quiz logic lives in command markdown
            shift
            ;;
        --allow-empty-bitlesson-none)
            BITLESSON_ALLOW_EMPTY_NONE="true"
            shift
            ;;
        --require-bitlesson-entry-for-none)
            BITLESSON_ALLOW_EMPTY_NONE="false"
            shift
            ;;
        --privacy)
            PRIVACY_MODE="true"
            shift
            ;;
        -*)
            echo "Unknown option: $1" >&2
            echo "Use --help for usage information" >&2
            exit 1
            ;;
        *)
            if [[ -z "$PLAN_FILE" ]]; then
                PLAN_FILE="$1"
            else
                echo "Error: Multiple plan files specified" >&2
                echo "Only one plan file is allowed" >&2
                exit 1
            fi
            shift
            ;;
    esac
done

# ========================================
# Validate Prerequisites
# ========================================

PROJECT_ROOT="$(resolve_project_root)" || {
    echo "Error: Cannot determine humanize project root." >&2
    echo "  Set CLAUDE_PROJECT_DIR or run inside a git repository." >&2
    exit 1
}

# loop-common.sh already sourced above (provides find_active_loop, etc.)

# ========================================
# Required Dependency Check
# ========================================
# Check all required external tools upfront so users get a single,
# actionable error message instead of a cryptic mid-loop failure.

MISSING_DEPS=()

if ! command -v codex &>/dev/null; then
    MISSING_DEPS+=("codex  - Install: https://github.com/openai/codex")
fi

if ! command -v jq &>/dev/null; then
    MISSING_DEPS+=("jq     - Install: https://jqlang.github.io/jq/download/")
fi

if ! command -v git &>/dev/null; then
    MISSING_DEPS+=("git    - Install: https://git-scm.com/downloads")
fi

if [[ ${#MISSING_DEPS[@]} -gt 0 ]]; then
    echo "Error: Missing required dependencies for RLCR loop" >&2
    echo "" >&2
    for dep in "${MISSING_DEPS[@]}"; do
        echo "  - $dep" >&2
    done
    echo "" >&2
    echo "Please install the missing tools and try again." >&2
    exit 1
fi

# ========================================
# Mutual Exclusion Check
# ========================================

# Check for existing active RLCR loop
RLCR_LOOP_DIR=$(find_active_loop "$PROJECT_ROOT/.humanize/rlcr" 2>/dev/null || echo "")

if [[ -n "$RLCR_LOOP_DIR" ]]; then
    echo "Error: An RLCR loop is already active" >&2
    echo "  Active loop: $RLCR_LOOP_DIR" >&2
    echo "" >&2
    echo "Only one loop can be active at a time." >&2
    echo "Cancel the RLCR loop first with: /humanize:cancel-rlcr-loop" >&2
    exit 1
fi

# ========================================
# Agent Teams Validation
# ========================================

if [[ "$AGENT_TEAMS" == "true" ]]; then
    if [[ "${CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS:-}" != "1" ]]; then
        echo "Error: --agent-teams requires the CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS environment variable to be set." >&2
        echo "" >&2
        echo "Claude Code Agent Teams is an experimental feature that must be enabled before use." >&2
        echo "To enable it, set the environment variable before starting Claude Code:" >&2
        echo "" >&2
        echo "  export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1" >&2
        echo "" >&2
        echo "Or add it to your shell profile (~/.bashrc, ~/.zshrc) for persistent access." >&2
        exit 1
    fi
fi

# Merge explicit and positional plan file
if [[ -n "$PLAN_FILE_EXPLICIT" && -n "$PLAN_FILE" ]]; then
    echo "Error: Cannot specify both --plan-file and positional plan file" >&2
    exit 1
fi
if [[ -n "$PLAN_FILE_EXPLICIT" ]]; then
    PLAN_FILE="$PLAN_FILE_EXPLICIT"
fi

# Check plan file is provided (optional when --skip-impl is used)
if [[ -z "$PLAN_FILE" ]]; then
    if [[ "$SKIP_IMPL" == "true" ]]; then
        # Use internal placeholder for skip-impl mode
        PLAN_FILE=".humanize/skip-impl-placeholder.md"
        SKIP_IMPL_NO_PLAN="true"
        # Force TRACK_PLAN_FILE to false since there's no real plan file to track
        if [[ "$TRACK_PLAN_FILE" == "true" ]]; then
            echo "Warning: --track-plan-file ignored in skip-impl mode without a plan file" >&2
            TRACK_PLAN_FILE="false"
        fi
    else
        echo "Error: No plan file provided" >&2
        echo "" >&2
        echo "Usage: /humanize:start-rlcr-loop <path/to/plan.md> [OPTIONS]" >&2
        echo "" >&2
        echo "For help: /humanize:start-rlcr-loop --help" >&2
        exit 1
    fi
fi

# ========================================
# Git Repository Validation
# ========================================

# Check git repo (with timeout)
if ! run_with_timeout "$GIT_TIMEOUT" git rev-parse --git-dir &>/dev/null; then
    echo "Error: Project must be a git repository (or git command timed out)" >&2
    exit 1
fi

# Check at least one commit (with timeout)
if ! run_with_timeout "$GIT_TIMEOUT" git rev-parse HEAD &>/dev/null 2>&1; then
    echo "Error: Git repository must have at least one commit (or git command timed out)" >&2
    exit 1
fi

# Plan File Path Validation
# ========================================

# Skip plan file validation in skip-impl mode with no plan provided
if [[ "$SKIP_IMPL_NO_PLAN" == "true" ]]; then
    echo "Skip-impl mode: skipping plan file validation" >&2
    FULL_PLAN_PATH=""
    PLAN_IS_TRACKED="false"
else

# Reject absolute paths
if [[ "$PLAN_FILE" = /* ]]; then
    echo "Error: Plan file must be a relative path, got: $PLAN_FILE" >&2
    exit 1
fi

# Reject paths with spaces (not supported for YAML serialization consistency)
if [[ "$PLAN_FILE" =~ [[:space:]] ]]; then
    echo "Error: Plan file path cannot contain spaces" >&2
    echo "  Got: $PLAN_FILE" >&2
    echo "  Rename the file or directory to remove spaces" >&2
    exit 1
fi

# Reject paths with shell metacharacters (prevents injection when used in shell commands)
# Use glob pattern matching (== *[...]*) instead of regex (=~) for portability
if [[ "$PLAN_FILE" == *[\;\&\|\$\`\<\>\(\)\{\}\[\]\!\#\~\*\?\\]* ]]; then
    echo "Error: Plan file path contains shell metacharacters" >&2
    echo "  Got: $PLAN_FILE" >&2
    echo "  Rename the file to use only alphanumeric, dash, underscore, dot, and slash" >&2
    exit 1
fi

# Build full path
FULL_PLAN_PATH="$PROJECT_ROOT/$PLAN_FILE"

# Reject symlinks (file itself)
if [[ -L "$FULL_PLAN_PATH" ]]; then
    echo "Error: Plan file cannot be a symbolic link" >&2
    exit 1
fi

# Check parent directory exists (provides clearer error for typos in path)
PLAN_DIR="$(dirname "$FULL_PLAN_PATH")"
if [[ ! -d "$PLAN_DIR" ]]; then
    echo "Error: Plan file directory not found: $(dirname "$PLAN_FILE")" >&2
    exit 1
fi

# Reject symlinks in parent directory path (walk each segment)
# This prevents symlink-based path traversal attacks
CHECK_PATH="$PROJECT_ROOT"
# Split PLAN_FILE by / and check each parent directory segment
# Use parameter expansion for portability (works in bash and zsh)
REMAINING_PATH="${PLAN_FILE%/*}"
if [[ "$REMAINING_PATH" != "$PLAN_FILE" ]]; then
    # There are parent directories to check
    IFS='/' read -ra PATH_SEGMENTS <<< "$REMAINING_PATH"
    for segment in "${PATH_SEGMENTS[@]}"; do
        if [[ -z "$segment" ]]; then
            continue
        fi
        CHECK_PATH="$CHECK_PATH/$segment"
        if [[ -L "$CHECK_PATH" ]]; then
            echo "Error: Plan file path contains a symbolic link in parent directory" >&2
            echo "  Symlink found at: $segment" >&2
            echo "  Plan file paths must not traverse symbolic links" >&2
            exit 1
        fi
    done
fi

# Check file exists
if [[ ! -f "$FULL_PLAN_PATH" ]]; then
    echo "Error: Plan file not found: $PLAN_FILE" >&2
    exit 1
fi

# Check file is readable
if [[ ! -r "$FULL_PLAN_PATH" ]]; then
    echo "Error: Plan file not readable: $PLAN_FILE" >&2
    exit 1
fi

# Check file is within project (no ../ escaping)
# Resolve the real path by cd'ing to the directory and getting pwd
# This handles symlinks in parent directories and ../ path components
RESOLVED_PLAN_DIR=$(cd "$PLAN_DIR" 2>/dev/null && pwd) || {
    echo "Error: Cannot resolve plan file directory: $(dirname "$PLAN_FILE")" >&2
    echo "  This may indicate permission issues or broken symlinks in the path" >&2
    exit 1
}
REAL_PLAN_PATH="$RESOLVED_PLAN_DIR/$(basename "$FULL_PLAN_PATH")"
if [[ ! "$REAL_PLAN_PATH" = "$PROJECT_ROOT"/* ]]; then
    echo "Error: Plan file must be within project directory" >&2
    exit 1
fi

# Check not in submodule
# Quick check: only run expensive git submodule status if .gitmodules exists
if [[ -f "$PROJECT_ROOT/.gitmodules" ]]; then
    if run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" submodule status 2>/dev/null | grep -q .; then
        # Get list of submodule paths
        SUBMODULES=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" submodule status | awk '{print $2}')
        for submod in $SUBMODULES; do
            if [[ "$PLAN_FILE" = "$submod"/* || "$PLAN_FILE" = "$submod" ]]; then
                echo "Error: Plan file cannot be inside a git submodule: $submod" >&2
                exit 1
            fi
        done
    fi
fi

# ========================================
# Plan File Tracking Status Validation
# ========================================

# Check git status - fail closed on timeout
# Use || true to capture exit code without triggering set -e
PLAN_GIT_STATUS=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" status --porcelain "$PLAN_FILE" 2>/dev/null) || STATUS_EXIT=$?
STATUS_EXIT=${STATUS_EXIT:-0}
if [[ $STATUS_EXIT -eq 124 ]]; then
    echo "Error: Git operation timed out while checking plan file status" >&2
    exit 1
fi

# Check if tracked - fail closed on timeout
# ls-files --error-unmatch returns 1 for untracked files (expected behavior)
# We need to distinguish between: 0 (tracked), 1 (not tracked), 124 (timeout)
run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" ls-files --error-unmatch "$PLAN_FILE" &>/dev/null || LS_FILES_EXIT=$?
LS_FILES_EXIT=${LS_FILES_EXIT:-0}
if [[ $LS_FILES_EXIT -eq 124 ]]; then
    echo "Error: Git operation timed out while checking plan file tracking status" >&2
    exit 1
fi
PLAN_IS_TRACKED=$([[ $LS_FILES_EXIT -eq 0 ]] && echo "true" || echo "false")

if [[ "$TRACK_PLAN_FILE" == "true" ]]; then
    # Must be tracked and clean
    if [[ "$PLAN_IS_TRACKED" != "true" ]]; then
        echo "Error: --track-plan-file requires plan file to be tracked in git" >&2
        echo "  File: $PLAN_FILE" >&2
        echo "  Run: git add $PLAN_FILE && git commit" >&2
        exit 1
    fi
    if [[ -n "$PLAN_GIT_STATUS" ]]; then
        echo "Error: --track-plan-file requires plan file to be clean (no modifications)" >&2
        echo "  File: $PLAN_FILE" >&2
        echo "  Status: $PLAN_GIT_STATUS" >&2
        echo "  Commit or stash your changes first" >&2
        exit 1
    fi
else
    # Must be gitignored (not tracked)
    if [[ "$PLAN_IS_TRACKED" == "true" ]]; then
        echo "Error: Plan file must be gitignored when not using --track-plan-file" >&2
        echo "  File: $PLAN_FILE" >&2
        echo "  Either:" >&2
        echo "    1. Add to .gitignore and remove from git: git rm --cached $PLAN_FILE" >&2
        echo "    2. Use --track-plan-file if you want to track the plan file" >&2
        exit 1
    fi
fi

fi  # End of skip-impl plan file validation skip

# ========================================
# Plan File Content Validation
# ========================================

# Skip plan file content validation in skip-impl mode with no plan provided
if [[ "$SKIP_IMPL_NO_PLAN" != "true" ]]; then

# Check plan file has at least 5 lines
LINE_COUNT=$(wc -l < "$FULL_PLAN_PATH" | tr -d ' ')
if [[ "$LINE_COUNT" -lt 5 ]]; then
    echo "Error: Plan is too simple (only $LINE_COUNT lines, need at least 5)" >&2
    echo "" >&2
    echo "The plan file should contain enough detail for implementation." >&2
    echo "Consider adding more context, acceptance criteria, or steps." >&2
    exit 1
fi

# Check plan has actual content (not just whitespace/blank lines/comments)
# Exclude: blank lines, shell/YAML comments (# ...), and HTML comments (<!-- ... -->)
# Note: Lines starting with # are treated as comments, not markdown headings
# A "content line" is any line that is not blank and not purely a comment
# For multi-line HTML comments, we count lines inside them as non-content
CONTENT_LINES=0
IN_COMMENT=false
while IFS= read -r line || [[ -n "$line" ]]; do
    # If inside multi-line comment, check for end marker
    if [[ "$IN_COMMENT" == "true" ]]; then
        if [[ "$line" =~ --\>[[:space:]]*$ ]]; then
            IN_COMMENT=false
        fi
        continue
    fi
    # Skip blank lines
    if [[ "$line" =~ ^[[:space:]]*$ ]]; then
        continue
    fi
    # Skip single-line HTML comments (must check BEFORE multi-line start)
    # Single-line: <!-- ... --> on same line
    if [[ "$line" =~ ^[[:space:]]*\<!--.*--\>[[:space:]]*$ ]]; then
        continue
    fi
    # Check for multi-line HTML comment start (<!-- without closing --> on same line)
    # Only trigger if the line contains <!-- but NOT -->
    if [[ "$line" =~ ^[[:space:]]*\<!-- ]] && ! [[ "$line" =~ --\> ]]; then
        IN_COMMENT=true
        continue
    fi
    # Skip shell/YAML style comments (lines starting with #)
    if [[ "$line" =~ ^[[:space:]]*# ]]; then
        continue
    fi
    # This is a content line
    CONTENT_LINES=$((CONTENT_LINES + 1))
done < "$FULL_PLAN_PATH"

if [[ "$CONTENT_LINES" -lt 3 ]]; then
    echo "Error: Plan file has insufficient content (only $CONTENT_LINES content lines)" >&2
    echo "" >&2
    echo "The plan file should contain meaningful content, not just blank lines or comments." >&2
    exit 1
fi

else
    # Skip-impl mode: set placeholder LINE_COUNT
    LINE_COUNT=0
fi  # End of skip-impl plan file content validation skip

if [[ "$SKIP_IMPL" == "true" ]] && [[ "$SKIP_IMPL_NO_PLAN" != "true" ]]; then
    SKIP_IMPL_PLAN_ANCHORED="true"
fi

# ========================================
# Record Branch
# ========================================

START_BRANCH=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" rev-parse --abbrev-ref HEAD)
if [[ -z "$START_BRANCH" ]]; then
    echo "Error: Failed to get current branch (git command timed out or failed)" >&2
    exit 1
fi

# Validate branch name for YAML safety (prevents injection in state.md)
# Reject branches with YAML-unsafe characters: colon, hash, quotes, newlines
if [[ "$START_BRANCH" == *[:\#\"\'\`]* ]] || [[ "$START_BRANCH" =~ $'\n' ]]; then
    echo "Error: Branch name contains YAML-unsafe characters" >&2
    echo "  Branch: $START_BRANCH" >&2
    echo "  Characters not allowed: : # \" ' \` newline" >&2
    echo "  Please checkout a branch with a simpler name" >&2
    exit 1
fi

# Validate codex model for YAML safety
# Only alphanumeric, hyphen, underscore, dot allowed
if [[ ! "$CODEX_MODEL" =~ ^[a-zA-Z0-9._-]+$ ]]; then
    echo "Error: Codex model contains invalid characters" >&2
    echo "  Model: $CODEX_MODEL" >&2
    echo "  Only alphanumeric, hyphen, underscore, dot allowed" >&2
    exit 1
fi

# Validate codex effort matches allowed values (consistent with stop-hook validation)
if [[ ! "$CODEX_EFFORT" =~ ^(xhigh|high|medium|low)$ ]]; then
    echo "Error: Invalid codex effort: $CODEX_EFFORT" >&2
    echo "  Must be one of: xhigh, high, medium, low" >&2
    exit 1
fi

# ========================================
# Git Working Tree Clean Check
# ========================================
# Placed after input validation so users see input errors first

GIT_STATUS_OUTPUT=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" status --porcelain --untracked-files=all 2>/dev/null) || GIT_STATUS_EXIT=$?
GIT_STATUS_EXIT=${GIT_STATUS_EXIT:-0}
if [[ $GIT_STATUS_EXIT -eq 124 ]]; then
    echo "Error: Git operation timed out while checking working tree status" >&2
    exit 1
fi
# Filter out untracked .humanize/ paths and .humanize-* dash-separated legacy variants.
# These are gitignored runtime directories and do not indicate a dirty working tree.
GIT_STATUS_OUTPUT=$(echo "$GIT_STATUS_OUTPUT" | grep -vE '^\?\? \.humanize[-/]' || true)
if [[ -n "$GIT_STATUS_OUTPUT" ]]; then
    echo "Error: Git working tree is not clean" >&2
    echo "" >&2
    echo "RLCR loop can only be started on a clean git repository." >&2
    echo "Please commit or stash your changes before starting the loop." >&2
    echo "" >&2
    echo "Current status:" >&2
    echo "$GIT_STATUS_OUTPUT" >&2
    exit 1
fi

# ========================================
# Determine Base Branch for Code Review
# ========================================
# Priority: user input > remote default > local main > local master

if [[ -n "$BASE_BRANCH" ]]; then
    # User specified base branch - validate it exists LOCALLY
    # codex review --base requires a local ref, so remote-only branches won't work
    if run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" show-ref --verify --quiet "refs/heads/$BASE_BRANCH" 2>/dev/null; then
        : # Branch exists locally, good
    else
        # Check if it exists on remote but not locally
        if run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" ls-remote --heads origin "$BASE_BRANCH" 2>/dev/null | grep -q .; then
            echo "Error: Base branch '$BASE_BRANCH' exists on remote but not locally" >&2
            echo "  codex review requires a local branch reference" >&2
            echo "  Run: git fetch origin $BASE_BRANCH:$BASE_BRANCH" >&2
            exit 1
        else
            echo "Error: Specified base branch does not exist: $BASE_BRANCH" >&2
            echo "  Not found locally or on any remote" >&2
            exit 1
        fi
    fi
else
    # Auto-detect base branch
    # Note: codex review --base requires a LOCAL branch, so we must verify local existence
    # Priority 1: Remote default branch (if it exists locally)
    # Guard with || true to prevent pipefail from terminating script when origin is missing
    REMOTE_DEFAULT=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" remote show origin 2>/dev/null | grep "HEAD branch:" | sed 's/.*HEAD branch:[[:space:]]*//' || true)
    if [[ -n "$REMOTE_DEFAULT" && "$REMOTE_DEFAULT" != "(unknown)" ]]; then
        # Verify the remote default branch exists locally
        if run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" show-ref --verify --quiet "refs/heads/$REMOTE_DEFAULT" 2>/dev/null; then
            BASE_BRANCH="$REMOTE_DEFAULT"
        fi
    fi
    # Priority 2: Local main branch (if not already set)
    if [[ -z "$BASE_BRANCH" ]] && run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" show-ref --verify --quiet refs/heads/main 2>/dev/null; then
        BASE_BRANCH="main"
    fi
    # Priority 3: Local master branch (if not already set)
    if [[ -z "$BASE_BRANCH" ]] && run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" show-ref --verify --quiet refs/heads/master 2>/dev/null; then
        BASE_BRANCH="master"
    fi
    # Error if no base branch found
    if [[ -z "$BASE_BRANCH" ]]; then
        echo "Error: Cannot determine base branch for code review" >&2
        echo "  No local main or master branch found" >&2
        if [[ -n "$REMOTE_DEFAULT" && "$REMOTE_DEFAULT" != "(unknown)" ]]; then
            echo "  Remote default '$REMOTE_DEFAULT' exists but not locally" >&2
            echo "  Run: git fetch origin $REMOTE_DEFAULT:$REMOTE_DEFAULT" >&2
        fi
        echo "  Use --base-branch to specify explicitly" >&2
        exit 1
    fi
fi

# Validate base branch name for YAML safety
if [[ "$BASE_BRANCH" == *[:\#\"\'\`]* ]] || [[ "$BASE_BRANCH" =~ $'\n' ]]; then
    echo "Error: Base branch name contains YAML-unsafe characters" >&2
    echo "  Branch: $BASE_BRANCH" >&2
    echo "  Characters not allowed: : # \" ' \` newline" >&2
    exit 1
fi

# Capture the base commit SHA at loop start time
# This prevents issues when working on the base branch itself (e.g., main)
# where the branch ref advances with commits, making diff against itself empty
BASE_COMMIT=$(run_with_timeout "$GIT_TIMEOUT" git -C "$PROJECT_ROOT" rev-parse "$BASE_BRANCH" 2>/dev/null)
if [[ -z "$BASE_COMMIT" ]]; then
    echo "Error: Failed to get commit SHA for base branch: $BASE_BRANCH" >&2
    exit 1
fi
echo "Base commit SHA captured: $BASE_COMMIT" >&2

# ========================================
# Setup State Directory
# ========================================

LOOP_BASE_DIR="$PROJECT_ROOT/.humanize/rlcr"

# Create timestamp for this loop session
TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)
LOOP_DIR="$LOOP_BASE_DIR/$TIMESTAMP"

mkdir -p "$LOOP_DIR"

# Copy plan file to loop directory as backup (or create placeholder for skip-impl)
if [[ "$SKIP_IMPL_NO_PLAN" == "true" ]]; then
    # Create placeholder plan file for skip-impl mode
    cat > "$LOOP_DIR/plan.md" << 'SKIP_IMPL_PLAN_EOF'
# Skip Implementation Mode

This RLCR loop was started with `--skip-impl` flag, which skips the implementation phase
and goes directly to code review.

No implementation plan was provided - this is expected for skip-impl mode.

The loop will:
1. Run `codex review` on the current branch changes
2. If issues are found, Claude will fix them
3. When no issues remain, enter finalize phase

SKIP_IMPL_PLAN_EOF
    # Update PLAN_FILE to point to the actual placeholder location (repo-relative path)
    # Using relative path because git ls-files requires repo-relative paths
    PLAN_FILE=".humanize/rlcr/$TIMESTAMP/plan.md"
else
    cp "$FULL_PLAN_PATH" "$LOOP_DIR/plan.md"
fi

# Docs path default
DOCS_PATH="docs"

# ========================================
# Initialize BitLesson File
# ========================================

BITLESSON_FILE_REL=".humanize/bitlesson.md"
BITLESSON_FILE="$PROJECT_ROOT/$BITLESSON_FILE_REL"
PLUGIN_BITLESSON_TEMPLATE="$SCRIPT_DIR/../templates/bitlesson.md"
bash "$SCRIPT_DIR/bitlesson-init.sh" \
    --project-root "$PROJECT_ROOT" \
    --template "$PLUGIN_BITLESSON_TEMPLATE" \
    --bitlesson-relpath "$BITLESSON_FILE_REL" > /dev/null

# ========================================
# Create State File
# ========================================

# Determine initial review_started value based on skip-impl mode
INITIAL_REVIEW_STARTED="$SKIP_IMPL"

# Skip-impl mode does not use BitLesson-aware summary templates,
# so disable enforcement to avoid blocking the review-only workflow.
BITLESSON_STATE_VALUE="true"
[[ "$SKIP_IMPL" == "true" ]] && BITLESSON_STATE_VALUE="false"

cat > "$LOOP_DIR/state.md" << EOF
---
current_round: 0
max_iterations: $MAX_ITERATIONS
codex_model: $CODEX_MODEL
codex_effort: $CODEX_EFFORT
codex_timeout: $CODEX_TIMEOUT
push_every_round: $PUSH_EVERY_ROUND
full_review_round: $FULL_REVIEW_ROUND
plan_file: $PLAN_FILE
plan_tracked: $TRACK_PLAN_FILE
start_branch: $START_BRANCH
base_branch: $BASE_BRANCH
base_commit: $BASE_COMMIT
review_started: $INITIAL_REVIEW_STARTED
ask_codex_question: $ASK_CODEX_QUESTION
session_id:
agent_teams: $AGENT_TEAMS
privacy_mode: $PRIVACY_MODE
bitlesson_required: $BITLESSON_STATE_VALUE
bitlesson_file: $BITLESSON_FILE_REL
bitlesson_allow_empty_none: $BITLESSON_ALLOW_EMPTY_NONE
mainline_stall_count: 0
last_mainline_verdict: unknown
drift_status: normal
started_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)
---
EOF

# Create signal file for PostToolUse hook to record session_id
# The hook will read the session_id from its JSON input and patch state.md
# Format: line 1 = state file path, line 2 = command marker for verification
# The PostToolUse hook will only consume this signal when the Bash command
# that triggered it matches the setup script marker, preventing other sessions
# from accidentally claiming the signal.
mkdir -p "$PROJECT_ROOT/.humanize"
# Write full resolved script path as command signature for strict verification
SCRIPT_SELF_PATH="$SCRIPT_DIR/$(basename "${BASH_SOURCE[0]:-$0}")"
printf '%s\n%s\n' "$LOOP_DIR/state.md" "$SCRIPT_SELF_PATH" > "$PROJECT_ROOT/.humanize/.pending-session-id"

# Create review phase marker file for skip-impl mode
if [[ "$SKIP_IMPL" == "true" ]]; then
    echo "build_finish_round=0" > "$LOOP_DIR/.review-phase-started"
fi

# ========================================
# Create Goal Tracker File
# ========================================

GOAL_TRACKER_FILE="$LOOP_DIR/goal-tracker.md"

if [[ "$SKIP_IMPL" == "true" ]]; then
    if [[ "$SKIP_IMPL_PLAN_ANCHORED" == "true" ]]; then
        PLAN_GOAL_CONTENT=$(extract_plan_goal_content "$FULL_PLAN_PATH")
        PLAN_AC_CONTENT=$(extract_plan_ac_content "$FULL_PLAN_PATH")

        if [[ -z "$PLAN_GOAL_CONTENT" ]]; then
            PLAN_GOAL_CONTENT="Preserve the original plan scope from $PLAN_FILE while resolving code review findings on the current branch."
        fi

        if [[ -z "$PLAN_AC_CONTENT" ]]; then
            PLAN_AC_CONTENT=$(cat <<EOF
- The current branch remains aligned with the original plan at $PLAN_FILE.
- All blocking \`[P0-9]\` code review findings are resolved without widening scope beyond the original plan.
- Non-blocking follow-up items are explicitly queued and do not block completion.
EOF
)
        fi

        cat > "$GOAL_TRACKER_FILE" << EOF
# Goal Tracker (Skip Implementation Mode with Plan Anchor)

This RLCR loop was started with \`--skip-impl\` flag. The implementation phase was skipped,
but an explicit plan was provided and remains the scope anchor for review-only work.

This tracker is still used to keep the review loop aligned around one mainline objective
and to separate blocking issues from queued follow-up work.

## IMMUTABLE SECTION

### Ultimate Goal

$PLAN_GOAL_CONTENT

### Acceptance Criteria

$PLAN_AC_CONTENT

---

## MUTABLE SECTION

### Plan Version: Review-Only (Updated: Round 0)

#### Plan Evolution Log
| Round | Change | Reason | Impact on AC |
|-------|--------|--------|--------------|
| 0 | Skip implementation mode initialized around explicit plan anchor | Loop started with \`--skip-impl\` and retained @$PLAN_FILE as scope anchor | Review stays aligned with original plan |

#### Active Tasks
| Task | Target AC | Status | Notes |
|------|-----------|--------|-------|
| [mainline] Preserve original plan alignment while resolving blocking review findings | Plan ACs in scope | pending | Review-only mode with explicit plan anchor |

### Blocking Side Issues
| Issue | Discovered Round | Blocking AC | Resolution Path |
|-------|-----------------|-------------|-----------------|

### Queued Side Issues
| Issue | Discovered Round | Why Not Blocking | Revisit Trigger |
|-------|-----------------|------------------|-----------------|

### Completed and Verified
| AC | Task | Completed Round | Verified Round | Evidence |
|----|------|-----------------|----------------|----------|

### Explicitly Deferred
| Task | Original AC | Deferred Since | Justification | When to Reconsider |
|------|-------------|----------------|---------------|-------------------|

EOF
    else
        # Create review-only goal tracker for skip-impl mode without a plan (no placeholder text)
        cat > "$GOAL_TRACKER_FILE" << 'GOAL_TRACKER_EOF'
# Goal Tracker (Skip Implementation Mode)

This RLCR loop was started with `--skip-impl` flag. The implementation phase was skipped,
and the loop is running in code review mode only.

This tracker is still used to keep the review loop aligned around one mainline objective
and to separate blocking issues from queued follow-up work.

## IMMUTABLE SECTION

### Ultimate Goal

Pass code review for the current branch without regressing existing behavior.

### Acceptance Criteria

- AC-1: All blocking `[P0-9]` code review findings are resolved.
- AC-2: Non-blocking follow-up items are explicitly queued and do not block completion.
- AC-3: Finalize phase can complete without introducing new review regressions.

---

## MUTABLE SECTION

### Plan Version: Review-Only (Updated: Round 0)

#### Plan Evolution Log
| Round | Change | Reason | Impact on AC |
|-------|--------|--------|--------------|
| 0 | Skip implementation mode initialized | Loop started with `--skip-impl` | Focus on review-only objective |

#### Active Tasks
| Task | Target AC | Status | Notes |
|------|-----------|--------|-------|
| [mainline] Pass code review for current branch | AC-1 | pending | Review-only mode |

### Blocking Side Issues
| Issue | Discovered Round | Blocking AC | Resolution Path |
|-------|-----------------|-------------|-----------------|

### Queued Side Issues
| Issue | Discovered Round | Why Not Blocking | Revisit Trigger |
|-------|-----------------|------------------|-----------------|

### Completed and Verified
| AC | Task | Completed Round | Verified Round | Evidence |
|----|------|-----------------|----------------|----------|

### Explicitly Deferred
| Task | Original AC | Deferred Since | Justification | When to Reconsider |
|------|-------------|----------------|---------------|-------------------|

GOAL_TRACKER_EOF
    fi

else
    # Normal mode: create full goal tracker

cat > "$GOAL_TRACKER_FILE" << 'GOAL_TRACKER_EOF'
# Goal Tracker

<!--
This file tracks the ultimate goal, acceptance criteria, and plan evolution.
It prevents goal drift by maintaining a persistent anchor across all rounds.

RULES:
- IMMUTABLE SECTION: Do not modify after initialization
- MUTABLE SECTION: Update each round, but document all changes
- Every task must be in one of: Active, Completed, or Deferred
- Deferred items require explicit justification
-->

## IMMUTABLE SECTION
<!-- Do not modify after initialization -->

### Ultimate Goal
GOAL_TRACKER_EOF

# Extract goal from plan file (look for ## Goal, ## Objective, or first paragraph)
# This is a heuristic - Claude will refine it in round 0
# Use ^## without leading whitespace - markdown headers should start at column 0
GOAL_SECTION=$(extract_plan_goal_content "$FULL_PLAN_PATH")
if [[ -n "$GOAL_SECTION" ]]; then
    echo "$GOAL_SECTION" >> "$GOAL_TRACKER_FILE"
else
    # Use first non-empty, non-heading paragraph as goal description
    echo "[To be extracted from plan by Claude in Round 0]" >> "$GOAL_TRACKER_FILE"
    echo "" >> "$GOAL_TRACKER_FILE"
    echo "Source plan: $PLAN_FILE" >> "$GOAL_TRACKER_FILE"
fi

cat >> "$GOAL_TRACKER_FILE" << 'GOAL_TRACKER_EOF'

### Acceptance Criteria
<!-- Each criterion must be independently verifiable -->
<!-- Claude must extract or define these in Round 0 -->

GOAL_TRACKER_EOF

# Extract acceptance criteria from plan file (look for ## Acceptance, ## Criteria, ## Requirements)
# Use ^## without leading whitespace - markdown headers should start at column 0
# Use || true after sed to ignore SIGPIPE when head closes the pipe early (pipefail mode)
AC_SECTION=$(extract_plan_ac_content "$FULL_PLAN_PATH")
if [[ -n "$AC_SECTION" ]]; then
    echo "$AC_SECTION" >> "$GOAL_TRACKER_FILE"
else
    echo "[To be defined by Claude in Round 0 based on the plan]" >> "$GOAL_TRACKER_FILE"
fi

cat >> "$GOAL_TRACKER_FILE" << 'GOAL_TRACKER_EOF'

---

## MUTABLE SECTION
<!-- Update each round with justification for changes -->

### Plan Version: 1 (Updated: Round 0)

#### Plan Evolution Log
<!-- Document any changes to the plan with justification -->
| Round | Change | Reason | Impact on AC |
|-------|--------|--------|--------------|
| 0 | Initial plan | - | - |

#### Active Tasks
<!-- Mainline tasks only: each task must directly advance the current round objective and carry routing metadata -->
| Task | Target AC | Status | Tag | Owner | Notes |
|------|-----------|--------|-----|-------|-------|
| [To be populated by Claude based on plan] | - | pending | coding or analyze | claude or codex | mainline task only |

### Blocking Side Issues
<!-- Only issues that directly block current mainline progress belong here -->
| Issue | Discovered Round | Blocking AC | Resolution Path |
|-------|-----------------|-------------|-----------------|

### Queued Side Issues
<!-- Non-blocking issues stay queued and must NOT replace the round objective -->
| Issue | Discovered Round | Why Not Blocking | Revisit Trigger |
|-------|-----------------|------------------|-----------------|

### Completed and Verified
<!-- Only move tasks here after Codex verification -->
| AC | Task | Completed Round | Verified Round | Evidence |
|----|------|-----------------|----------------|----------|

### Explicitly Deferred
<!-- Items here require strong justification -->
| Task | Original AC | Deferred Since | Justification | When to Reconsider |
|------|-------------|----------------|---------------|-------------------|

GOAL_TRACKER_EOF

fi  # End of skip-impl goal tracker handling

# ========================================
# Summary Template Helper
# ========================================

write_summary_template() {
    local summary_path="$1"
    cat > "$summary_path" << 'SUMMARY_TMPL_EOF'
# Round 0 Summary

## What Was Implemented

[Describe what was done]

## Files Changed

[List files created/modified/deleted]

## Validation

[List tests/commands run and outcomes]

## Remaining Items

[List any deferred or pending items]

## BitLesson Delta

Action: none
Lesson ID(s): NONE
Notes: [what changed and why]
SUMMARY_TMPL_EOF
}

# ========================================
# Create Initial Prompt
# ========================================

SUMMARY_PATH="$LOOP_DIR/round-0-summary.md"
ROUND_CONTRACT_PATH="$LOOP_DIR/round-0-contract.md"

# Create the round-0 summary scaffold before either mode starts so stop-hook
# validation and BitLesson Delta checks have a valid target file.
write_summary_template "$SUMMARY_PATH"

if [[ "$SKIP_IMPL" == "true" ]]; then
    if [[ "$SKIP_IMPL_PLAN_ANCHORED" == "true" ]]; then
        cat > "$ROUND_CONTRACT_PATH" << EOF
# Round 0 Contract

- Mainline Objective: Keep the current branch aligned with @$PLAN_FILE while resolving only review findings that block clean acceptance.
- Target ACs: The original plan acceptance criteria affected by the current branch changes.
- Blocking Side Issues In Scope: Any \`[P0-9]\` findings or regressions that block review acceptance or violate the original plan scope.
- Queued Side Issues Out of Scope: Non-blocking cleanup, follow-up refactors, or future improvements that do not block review acceptance or plan alignment.
- Success Criteria: Code review passes and the current branch still matches the original plan's intended scope.
EOF
    else
        cat > "$ROUND_CONTRACT_PATH" << 'ROUND_CONTRACT_EOF'
# Round 0 Contract

- Mainline Objective: Run code review for the current branch and resolve only findings that block clean acceptance.
- Target ACs: AC-1, AC-2
- Blocking Side Issues In Scope: Any `[P0-9]` findings from the active review cycle.
- Queued Side Issues Out of Scope: Non-blocking cleanup, follow-up refactors, or future improvements that do not block review acceptance.
- Success Criteria: Code review passes with no blocking findings, and any remaining non-blocking follow-up is explicitly queued.
ROUND_CONTRACT_EOF
    fi

    # Skip-impl mode: create a prompt for code review only
    cat > "$LOOP_DIR/round-0-prompt.md" << EOF
# Skip Implementation Mode - Code Review Loop

This RLCR loop was started with \`--skip-impl\` flag.

**Mode**: Code Review Only (skipping implementation phase)
**Base Branch**: $BASE_BRANCH
**Current Branch**: $START_BRANCH

## What This Means

The loop will automatically run \`codex review\` on your changes when you try to exit.
If issues are found (marked with [P0-9] priority), you'll need to fix them before the loop ends.
Do not try to execute anything to trigger the review - just stop and it will run automatically.

Before requesting review, read:
- @$PLAN_FILE
- @$GOAL_TRACKER_FILE
- @$ROUND_CONTRACT_PATH

## Your Task

1. Review your current work
2. When ready, try to exit - Codex will review your code
3. Fix any issues Codex finds
4. Repeat until no issues remain
5. Enter finalize phase for code simplification

## Review Objective

Use the round contract as the current anchor:
- Keep one stable mainline objective and do not let it drift
- Treat review findings as \`[blocking]\` only if they block review acceptance
- Record non-blocking follow-up as \`[queued]\`
- Do not let queued work take over the round

EOF
    if [[ "$SKIP_IMPL_PLAN_ANCHORED" == "true" ]]; then
        cat >> "$LOOP_DIR/round-0-prompt.md" << EOF
- Keep review-only work aligned with the original plan at @$PLAN_FILE

Implementation phase is skipped, but the original plan still defines the intended branch scope.

EOF
    else
        cat >> "$LOOP_DIR/round-0-prompt.md" << 'EOF'
There is no explicit implementation plan for this loop, so the review-only contract is the primary anchor.

EOF
    fi

    cat >> "$LOOP_DIR/round-0-prompt.md" << EOF

Keep @$ROUND_CONTRACT_PATH updated if the blocking/queued split changes materially during review iterations.

When you're ready for review, write a brief summary of your changes and try to exit (do not try to execute anything, just stop).

Write your summary to: @$SUMMARY_PATH

EOF
else
    # Normal mode: create full implementation prompt

# Write prompt header
cat > "$LOOP_DIR/round-0-prompt.md" << EOF
Read and execute below with ultrathink

## Goal Tracker Setup (REQUIRED FIRST STEP)

Before starting implementation, you MUST initialize the Goal Tracker:

1. Read @$GOAL_TRACKER_FILE
2. If the "Ultimate Goal" section says "[To be extracted...]", extract a clear goal statement from the plan
3. If the "Acceptance Criteria" section says "[To be defined...]", define 3-7 specific, testable criteria
4. Populate the "Active Tasks" table with MAINLINE tasks from the plan, mapping each to an AC and filling Tag/Owner
5. Record any already-known side issues in either "Blocking Side Issues" or "Queued Side Issues"
6. Write the updated goal-tracker.md

## Round Contract Setup (REQUIRED BEFORE CODING)

Before starting implementation, create @$ROUND_CONTRACT_PATH with:

1. **One mainline objective** for this round
2. **Target ACs** (1-2 ACs only)
3. **Blocking side issues in scope** for this round
4. **Queued side issues out of scope** for this round
5. **Round success criteria**

Use this contract to keep the round focused. Do NOT let non-blocking bugs or cleanup work replace the mainline objective.

**IMPORTANT**: The IMMUTABLE SECTION can only be modified in Round 0. After this round, it becomes read-only.

---

## Implementation Plan

For all tasks that need to be completed, please use the Task system (TaskCreate, TaskUpdate, TaskList).

Every task MUST start with exactly one lane tag:
- \`[mainline]\` for plan-derived work that directly advances the round objective
- \`[blocking]\` for issues that prevent the mainline objective from succeeding safely
- \`[queued]\` for non-blocking bugs, cleanup, or follow-up work

Rules:
- \`[mainline]\` tasks are the primary success condition for the round
- \`[blocking]\` tasks may be resolved in the round only if they truly block mainline progress
- \`[queued]\` tasks must NOT become the round objective and do NOT need to be cleared before moving on
- If a new issue is not blocking the current objective, tag it \`[queued]\` and keep moving on the mainline

## Task Tag Routing (MUST FOLLOW)

Each task must have one routing tag from the plan: \`coding\` or \`analyze\`.

- Tag \`coding\`: Claude executes the task directly.
- Tag \`analyze\`: Claude must execute via \`/humanize:ask-codex\`, then integrate Codex output.
- Keep Goal Tracker "Active Tasks" columns **Tag** and **Owner** aligned with execution (\`coding -> claude\`, \`analyze -> codex\`).
- If a task has no explicit tag, default to \`coding\` (Claude executes directly).

EOF

# Append plan content directly (avoids command substitution size limits for large files)
cat "$LOOP_DIR/plan.md" >> "$LOOP_DIR/round-0-prompt.md"

# Append BitLesson Selection section
cat >> "$LOOP_DIR/round-0-prompt.md" << EOF

---

## BitLesson Selection (REQUIRED FOR EACH TASK)

Before executing each task or sub-task, you MUST:

1. Read @$BITLESSON_FILE
2. Run \`bitlesson-selector\` for each task/sub-task to select relevant lesson IDs
3. Follow the selected lesson IDs (or \`NONE\`) during implementation

Include a \`## BitLesson Delta\` section in your summary with:
- Action: none|add|update
- Lesson ID(s): NONE or comma-separated IDs
- Notes: what changed and why (required if action is add or update)

Reference: @$BITLESSON_FILE
EOF

# Inject agent-teams instructions if enabled (header + shared core)
if [[ "$AGENT_TEAMS" == "true" ]]; then
    AGENT_TEAMS_HEADER="$TEMPLATE_DIR/claude/agent-teams-instructions.md"
    AGENT_TEAMS_CORE="$TEMPLATE_DIR/claude/agent-teams-core.md"
    if [[ -f "$AGENT_TEAMS_HEADER" ]] && [[ -f "$AGENT_TEAMS_CORE" ]]; then
        echo "" >> "$LOOP_DIR/round-0-prompt.md"
        cat "$AGENT_TEAMS_HEADER" >> "$LOOP_DIR/round-0-prompt.md"
        echo "" >> "$LOOP_DIR/round-0-prompt.md"
        cat "$AGENT_TEAMS_CORE" >> "$LOOP_DIR/round-0-prompt.md"
    else
        cat >> "$LOOP_DIR/round-0-prompt.md" << 'AGENT_TEAMS_EOF'

## Agent Teams Mode

You are operating in **Agent Teams mode** as the **Team Leader**.

Split tasks into independent units, create agent teams to execute them, and coordinate team members.
Do NOT do implementation work yourself - delegate all coding to team members.
Prevent overlapping changes by assigning clear file ownership boundaries.
AGENT_TEAMS_EOF
    fi
fi

# Write prompt footer
cat >> "$LOOP_DIR/round-0-prompt.md" << EOF

---

## Goal Tracker Rules

Throughout your work, you MUST maintain the Goal Tracker:

1. **Before starting a round**: Re-anchor on the original plan and current round contract
2. **Before starting a task**: Mark the relevant mainline task as "in_progress" in Active Tasks
   - Confirm Tag/Owner routing is correct before execution
3. **Active Tasks** are MAINLINE tasks only - side issues do not belong there
4. **Blocking Side Issues** are reserved for issues that truly stop mainline progress
5. **Queued Side Issues** are non-blocking and must not take over the round
6. **After completing a mainline task**: Move it to "Completed and Verified" with evidence (but mark as "pending verification")
7. **If you discover the plan has errors**:
   - Do NOT silently change direction
   - Add entry to "Plan Evolution Log" with justification
   - Explain how the change still serves the Ultimate Goal
8. **If you need to defer a task**:
   - Move it to "Explicitly Deferred" section
   - Provide strong justification
   - Explain impact on Acceptance Criteria
9. **If you discover new issues**:
   - Add to "Blocking Side Issues" only if mainline progress is blocked
   - Otherwise add to "Queued Side Issues" or keep them as \`[queued]\` tasks/backlog

---

Note: You MUST NOT try to exit \`start-rlcr-loop\` loop by lying or edit loop state file or try to execute \`cancel-rlcr-loop\`

After completing the work, please:
0. If you have access to the \`code-simplifier\` agent, use it to review and optimize the code you just wrote
1. Finalize @$GOAL_TRACKER_FILE (this is Round 0, so you are initializing it - see "Goal Tracker Setup" above)
2. Write your round contract into @$ROUND_CONTRACT_PATH
3. Commit your changes with a descriptive commit message
4. Write your work summary into @$SUMMARY_PATH
EOF

# Add push instruction only if push_every_round is true
if [[ "$PUSH_EVERY_ROUND" == "true" ]]; then
    cat >> "$LOOP_DIR/round-0-prompt.md" << 'EOF'

Note: Since `--push-every-round` is enabled, you must push your commits to remote after each round.
EOF
fi

fi  # End of skip-impl prompt handling

# ========================================
# Output Setup Message
# ========================================

# All important work is done. If output fails due to SIGPIPE (pipe closed), exit cleanly.
# This trap is set here (not at script start) to avoid affecting internal pipelines.
trap 'exit 0' PIPE

if [[ "$SKIP_IMPL" == "true" ]]; then
    cat << EOF
=== start-rlcr-loop activated (SKIP-IMPL MODE) ===

Mode: Code Review Only (--skip-impl)
Start Branch: $START_BRANCH
Base Branch: $BASE_BRANCH
Codex Model: $CODEX_MODEL
Codex Effort: $CODEX_EFFORT
Codex Timeout: ${CODEX_TIMEOUT}s
Loop Directory: $LOOP_DIR

Skip-impl mode is active. The implementation phase is skipped.
When you try to exit, codex review will run automatically by itself.

The loop will:
1. Run codex review on changes between $BASE_BRANCH and $START_BRANCH
2. If issues are found ([P0-9] markers), you'll need to fix them
3. When no issues remain, enters Finalize Phase and loop ends

To cancel: /humanize:cancel-rlcr-loop

---

EOF
else
    cat << EOF
=== start-rlcr-loop activated ===

Plan File: $PLAN_FILE ($LINE_COUNT lines)
Plan Tracked: $TRACK_PLAN_FILE
Start Branch: $START_BRANCH
Base Branch: $BASE_BRANCH
Max Iterations: $MAX_ITERATIONS
Codex Model: $CODEX_MODEL
Codex Effort: $CODEX_EFFORT
Codex Timeout: ${CODEX_TIMEOUT}s
Full Review Round: $FULL_REVIEW_ROUND (Full Alignment Checks at rounds $((FULL_REVIEW_ROUND - 1)), $((2 * FULL_REVIEW_ROUND - 1)), $((3 * FULL_REVIEW_ROUND - 1)), ...)
Ask User for Codex Questions: $ASK_CODEX_QUESTION
Agent Teams: $AGENT_TEAMS
Loop Directory: $LOOP_DIR

The loop is now active. When you try to exit:
1. Codex will review your work summary
2. If issues are found, you'll receive feedback and continue
3. If Codex outputs "COMPLETE", enters Review Phase (code review)
4. Code review checks for [P0-9] issues; if found, you fix them
5. When no issues found, enters Finalize Phase and loop ends

To cancel: /humanize:cancel-rlcr-loop

---

EOF
fi

# Output the initial prompt
cat "$LOOP_DIR/round-0-prompt.md"

echo ""
echo "==========================================="
echo "CRITICAL - Work Completion Requirements"
echo "==========================================="
echo ""
echo "When you complete your work, you MUST:"
echo ""
if [[ "$PUSH_EVERY_ROUND" == "true" ]]; then
echo "1. COMMIT and PUSH your changes:"
echo "   - Create a commit with descriptive message"
echo "   - Push to the remote repository"
else
echo "1. COMMIT your changes:"
echo "   - Create a commit with descriptive message"
echo "   - (Commits stay local - no push required)"
fi
echo ""
echo "2. Write a detailed summary to:"
echo "   $SUMMARY_PATH"
echo ""
echo "   The summary should include:"
echo "   - What was implemented"
echo "   - Files created/modified"
echo "   - Tests added/passed"
echo "   - Any remaining items"
echo "   - ## BitLesson Delta section (Action: none|add|update)"
echo ""
echo "Codex will review this summary to determine if work is complete."
echo "==========================================="

# Explicit exit 0 to ensure clean exit code even if final output fails
exit 0