loop-common.sh 61.4 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
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
#!/usr/bin/env bash
#
# Common functions for RLCR loop hooks
#
# This library provides shared functionality used by:
# - loop-read-validator.sh
# - loop-write-validator.sh
# - loop-edit-validator.sh
# - loop-bash-validator.sh
# - loop-plan-file-validator.sh
# - loop-codex-stop-hook.sh
# - setup-rlcr-loop.sh
# - cancel-rlcr-loop.sh
#

# Source guard: prevent double-sourcing (readonly vars would fail)
[[ -n "${_LOOP_COMMON_LOADED:-}" ]] && return 0 2>/dev/null || true
_LOOP_COMMON_LOADED=1

# ========================================
# Constants
# ========================================

# State file field names
readonly FIELD_PLAN_TRACKED="plan_tracked"
readonly FIELD_START_BRANCH="start_branch"
readonly FIELD_BASE_BRANCH="base_branch"
readonly FIELD_BASE_COMMIT="base_commit"
readonly FIELD_PLAN_FILE="plan_file"
readonly FIELD_CURRENT_ROUND="current_round"
readonly FIELD_MAX_ITERATIONS="max_iterations"
readonly FIELD_PUSH_EVERY_ROUND="push_every_round"
readonly FIELD_CODEX_MODEL="codex_model"
readonly FIELD_CODEX_EFFORT="codex_effort"
readonly FIELD_CODEX_TIMEOUT="codex_timeout"
readonly FIELD_REVIEW_STARTED="review_started"
readonly FIELD_FULL_REVIEW_ROUND="full_review_round"
readonly FIELD_ASK_CODEX_QUESTION="ask_codex_question"
readonly FIELD_SESSION_ID="session_id"
readonly FIELD_AGENT_TEAMS="agent_teams"
readonly FIELD_PRIVACY_MODE="privacy_mode"
readonly FIELD_MAINLINE_STALL_COUNT="mainline_stall_count"
readonly FIELD_LAST_MAINLINE_VERDICT="last_mainline_verdict"
readonly FIELD_DRIFT_STATUS="drift_status"

readonly MAINLINE_VERDICT_ADVANCED="advanced"
readonly MAINLINE_VERDICT_STALLED="stalled"
readonly MAINLINE_VERDICT_REGRESSED="regressed"
readonly MAINLINE_VERDICT_UNKNOWN="unknown"

readonly DRIFT_STATUS_NORMAL="normal"
readonly DRIFT_STATUS_REPLAN_REQUIRED="replan_required"

# Default Codex configuration (single source of truth - all scripts reference this)
# Scripts can pre-set DEFAULT_CODEX_MODEL/DEFAULT_CODEX_EFFORT before sourcing to override.
# Config-backed defaults are loaded from the merge hierarchy after config-loader.sh is sourced.
# Precedence: pre-set value > config value > hardcoded fallback (gpt-5.5/high)
#
# The actual assignment happens in the "Config-backed defaults" section below,
# after config-loader.sh has been sourced and merged config is available.

# Codex review markers
readonly MARKER_COMPLETE="COMPLETE"
readonly MARKER_STOP="STOP"

# Exit reasons (used with end_loop function)
# complete   - Codex confirmed all goals achieved (normal success)
# cancel     - User cancelled with /cancel-rlcr-loop
# maxiter    - Reached maximum iterations limit
# stop       - Codex triggered circuit breaker (stagnation detected)
# unexpected - System error or invalid state (e.g., corrupted state file)
readonly EXIT_COMPLETE="complete"
readonly EXIT_CANCEL="cancel"
readonly EXIT_MAXITER="maxiter"
readonly EXIT_STOP="stop"
readonly EXIT_UNEXPECTED="unexpected"

# ========================================
# JSON Input Validation
# ========================================

# Validate JSON input and extract tool_name
# Usage: validate_hook_input "$json_input"
# Returns: 0 if valid JSON with tool_name, 1 if invalid
# Sets: VALIDATED_TOOL_NAME, VALIDATED_TOOL_INPUT
#
# Non-UTF8 handling behavior:
# - Null bytes (0x00): Rejected with exit 1
# - Invalid UTF-8 sequences (0x80-0xFF outside valid UTF-8): Rejected by jq as invalid JSON
# - Valid UTF-8 non-ASCII characters: Accepted (jq handles Unicode correctly)
validate_hook_input() {
    local input="$1"

    # Reject null bytes (security) - portable check without grep -P (BSD incompatible)
    # tr -cd '\0' keeps only null bytes, wc -c counts them
    if [[ $(printf '%s' "$input" | tr -cd '\0' | wc -c) -gt 0 ]]; then
        echo "Error: Input contains null bytes" >&2
        return 1
    fi

    # Reject non-UTF8 bytes (security/consistency)
    # Check for bytes in 0x80-0xFF that are NOT part of valid UTF-8 sequences
    # Skip if iconv is not available (common in minimal containers like Alpine)
    if command -v iconv >/dev/null 2>&1; then
        if ! printf '%s' "$input" | iconv -f UTF-8 -t UTF-8 >/dev/null 2>&1; then
            echo "Error: Input contains invalid UTF-8 sequences" >&2
            return 1
        fi
    fi

    # Validate JSON syntax with jq
    if ! printf '%s' "$input" | jq -e '.' >/dev/null 2>&1; then
        echo "Error: Invalid JSON syntax" >&2
        return 1
    fi

    # Extract tool_name (required)
    VALIDATED_TOOL_NAME=$(printf '%s' "$input" | jq -r '.tool_name // empty')
    if [[ -z "$VALIDATED_TOOL_NAME" ]]; then
        echo "Error: Missing required field: tool_name" >&2
        return 1
    fi

    # Extract tool_input (required for Read/Write/Bash)
    VALIDATED_TOOL_INPUT=$(printf '%s' "$input" | jq -r '.tool_input // empty')

    return 0
}

# Validate that a specific field exists in tool_input
# Usage: require_tool_input_field "$json_input" "field_name"
# Returns: 0 if field exists and is non-empty, 1 otherwise
require_tool_input_field() {
    local input="$1"
    local field="$2"

    local value
    value=$(printf '%s' "$input" | jq -r ".tool_input.$field // empty")

    if [[ -z "$value" ]]; then
        echo "Error: Missing required field: tool_input.$field" >&2
        return 1
    fi

    return 0
}

# Check if JSON is deeply nested (potential DoS)
# Usage: is_deeply_nested "$json_input" [max_depth]
# Returns: 0 if too deeply nested, 1 otherwise
is_deeply_nested() {
    local input="$1"
    local max_depth="${2:-30}"

    # Use jq to check depth - getpath on recursive descent gives us depth
    local actual_depth
    actual_depth=$(printf '%s' "$input" | jq '[paths | length] | max // 0' 2>/dev/null || echo "0")

    if [[ "$actual_depth" -gt "$max_depth" ]]; then
        echo "Error: JSON structure exceeds maximum depth of $max_depth (actual: $actual_depth)" >&2
        return 0
    fi

    return 1
}

# ========================================
# Library Setup
# ========================================

# Source template loader
LOOP_COMMON_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
LOOP_COMMON_PLUGIN_ROOT="$(cd "$LOOP_COMMON_DIR/../.." && pwd)"
export PLUGIN_ROOT="${PLUGIN_ROOT:-$LOOP_COMMON_PLUGIN_ROOT}"

# Shared project-root resolver (CLAUDE_PROJECT_DIR -> git toplevel,
# realpath-canonicalized). Must load before any caller needs PROJECT_ROOT.
source "$LOOP_COMMON_DIR/project-root.sh"

_lc_errexit=false; [[ -o errexit ]] && _lc_errexit=true
_lc_nounset=false; [[ -o nounset ]] && _lc_nounset=true
_lc_pipefail=false; [[ -o pipefail ]] && _lc_pipefail=true
source "$LOOP_COMMON_PLUGIN_ROOT/scripts/lib/config-loader.sh"
$_lc_errexit && set -e || set +e
$_lc_nounset && set -u || set +u
$_lc_pipefail && set -o pipefail || set +o pipefail
unset _lc_errexit _lc_nounset _lc_pipefail

_LOOP_COMMON_PROJECT_ROOT="$(resolve_project_root 2>/dev/null || true)"
# Config loading is best-effort: use || true so a config-load failure does not
# abort sourcing before callers' dependency checks (jq, codex) are reached.
# Stderr is NOT suppressed so malformed config warnings remain visible.
#
# Skip config loading when no project root is available (e.g. humanize.sh is
# sourced from .bashrc/.zshrc in a non-repo directory like $HOME). Passing an
# empty project_root to load_merged_config would surface a usage error on
# stderr every time the shell starts.
if [[ -n "$_LOOP_COMMON_PROJECT_ROOT" ]]; then
    _LOOP_COMMON_CONFIG="$(load_merged_config "$LOOP_COMMON_PLUGIN_ROOT" "$_LOOP_COMMON_PROJECT_ROOT")" || true
else
    _LOOP_COMMON_CONFIG=""
fi

# Load bitlesson model from merged config (controls which CLI bitlesson-select.sh uses)
DEFAULT_BITLESSON_MODEL="$(get_config_value "$_LOOP_COMMON_CONFIG" "bitlesson_model" 2>/dev/null || true)"
DEFAULT_BITLESSON_MODEL="${DEFAULT_BITLESSON_MODEL:-haiku}"

# Load codex model/effort from merged config so .humanize/config.json can set persistent
# defaults for all Codex-using features (RLCR, ask-codex).
# Precedence: pre-set by caller > config value > hardcoded fallback (gpt-5.5/high)
_cfg_codex_model="$(get_config_value "$_LOOP_COMMON_CONFIG" "codex_model" 2>/dev/null || true)"
if [[ -n "$_cfg_codex_model" && ! "$_cfg_codex_model" =~ ^[a-zA-Z0-9._-]+$ ]]; then
    echo "Warning: Invalid codex_model in merged config: $_cfg_codex_model" >&2
    echo "  Ignoring configured codex_model; using caller preset or fallback" >&2
    _cfg_codex_model=""
elif [[ -n "$_cfg_codex_model" && ! "$_cfg_codex_model" =~ ^(gpt-|o[0-9]) ]]; then
    echo "Warning: Unsupported codex_model in merged config: $_cfg_codex_model" >&2
    echo "  Must start with a Codex model prefix: gpt- or o[0-9]" >&2
    echo "  Ignoring configured codex_model; using caller preset or fallback" >&2
    _cfg_codex_model=""
fi
DEFAULT_CODEX_MODEL="${DEFAULT_CODEX_MODEL:-${_cfg_codex_model:-gpt-5.5}}"
_cfg_codex_effort="$(get_config_value "$_LOOP_COMMON_CONFIG" "codex_effort" 2>/dev/null || true)"
if [[ -n "$_cfg_codex_effort" && ! "$_cfg_codex_effort" =~ ^(xhigh|high|medium|low)$ ]]; then
    echo "Warning: Invalid codex_effort in merged config: $_cfg_codex_effort" >&2
    echo "  Must be one of: xhigh, high, medium, low" >&2
    echo "  Ignoring configured codex_effort; using caller preset or fallback" >&2
    _cfg_codex_effort=""
fi
DEFAULT_CODEX_EFFORT="${DEFAULT_CODEX_EFFORT:-${_cfg_codex_effort:-high}}"

# Load agent_teams from merged config (controls whether RLCR uses agent teams by default)
# Precedence: pre-set by caller (e.g. --agent-teams flag) > config value > hardcoded fallback (false)
_cfg_agent_teams="$(get_config_value "$_LOOP_COMMON_CONFIG" "agent_teams" 2>/dev/null || true)"
DEFAULT_AGENT_TEAMS="${DEFAULT_AGENT_TEAMS:-${_cfg_agent_teams:-false}}"
unset _cfg_codex_model _cfg_codex_effort _cfg_agent_teams

unset _LOOP_COMMON_PROJECT_ROOT _LOOP_COMMON_CONFIG

source "$LOOP_COMMON_DIR/template-loader.sh"

# Initialize template directory (can be overridden by sourcing script)
TEMPLATE_DIR="${TEMPLATE_DIR:-$(get_template_dir "$LOOP_COMMON_DIR")}"

# Validate template directory exists (warn but don't fail - allows graceful degradation)
if ! validate_template_dir "$TEMPLATE_DIR" 2>/dev/null; then
    echo "Warning: Template directory validation failed. Using inline fallbacks." >&2
fi

# Extract session_id from hook JSON input
# Usage: extract_session_id "$json_input"
# Outputs the session_id to stdout, or empty string if not available
extract_session_id() {
    local input="$1"
    printf '%s' "$input" | jq -r '.session_id // empty' 2>/dev/null || echo ""
}

# Background-task helpers (expand_leading_tilde, extract_transcript_path,
# derive_loop_start_iso_ts, list/has/count_pending_background_task[_ids],
# handle_bg_task_short_circuit) live in loop-bg-tasks.sh and are sourced
# at the bottom of this file so every existing consumer of loop-common.sh
# continues to get them transparently.

# Resolve the active state file for a loop directory
# Checks for finalize-state.md first, then state.md
# Usage: resolve_active_state_file "$loop_dir"
# Outputs the state file path to stdout, or empty string if none found
resolve_active_state_file() {
    local loop_dir="$1"

    if [[ -f "$loop_dir/methodology-analysis-state.md" ]]; then
        echo "$loop_dir/methodology-analysis-state.md"
    elif [[ -f "$loop_dir/finalize-state.md" ]]; then
        echo "$loop_dir/finalize-state.md"
    elif [[ -f "$loop_dir/state.md" ]]; then
        echo "$loop_dir/state.md"
    else
        echo ""
    fi
}

# Resolve any state file in a loop directory (active or terminal)
# Checks active states first (state.md, finalize-state.md), then falls back
# to any terminal state file (*-state.md such as complete-state.md, cancel-state.md).
# Usage: resolve_any_state_file "$loop_dir"
# Outputs the state file path to stdout, or empty string if none found
resolve_any_state_file() {
    local loop_dir="$1"

    # Prefer active states
    if [[ -f "$loop_dir/methodology-analysis-state.md" ]]; then
        echo "$loop_dir/methodology-analysis-state.md"
        return
    elif [[ -f "$loop_dir/finalize-state.md" ]]; then
        echo "$loop_dir/finalize-state.md"
        return
    elif [[ -f "$loop_dir/state.md" ]]; then
        echo "$loop_dir/state.md"
        return
    fi

    # Fall back to any terminal state file
    local terminal_state
    terminal_state=$(ls -1 "$loop_dir"/*-state.md 2>/dev/null | head -1)
    echo "${terminal_state:-}"
}

# Find the most recent active loop directory matching optional session_id filter
#
# Without session_id filter: only checks the single newest directory.
#   If it has state.md or finalize-state.md, returns it; otherwise returns empty.
#   This preserves zombie-loop protection: older directories are never examined,
#   so a stale state.md in an older directory cannot be accidentally revived.
#
# With session_id filter: finds the newest directory belonging to that session
#   (matching ANY *state.md file including terminal states), then checks whether
#   it is still active. If the session's newest directory is in terminal state
#   (complete-state.md, cancel-state.md, etc.), returns empty immediately --
#   preventing stale older loops from being revived. This enables multiple
#   concurrent RLCR loops with different session IDs in the same project.
#
# Empty stored session_id matches any filter (backward compat for pre-session
# state files).
#
# Third parameter `allow_bg_marker_fallback` (default "false"): when "true",
# the session-filter branch also considers a mismatched-session dir that holds
# a `bg-pending.marker` file AND an active state file. Only the RLCR stop
# hook opts in to this; every other caller (read/write/bash/plan-file
# validators, ...) keeps strict session isolation.
#
# Outputs the directory path to stdout, or empty string if none found
find_active_loop() {
    local loop_base_dir="$1"
    local filter_session_id="${2:-}"
    local allow_bg_marker_fallback="${3:-false}"

    if [[ ! -d "$loop_base_dir" ]]; then
        echo ""
        return
    fi

    if [[ -z "$filter_session_id" ]]; then
        # No filter: only check the single newest directory (zombie-loop protection)
        local newest_dir
        newest_dir=$(ls -1d "$loop_base_dir"/*/ 2>/dev/null | sort -r | head -1)

        if [[ -n "$newest_dir" ]]; then
            local state_file
            state_file=$(resolve_active_state_file "${newest_dir%/}")
            if [[ -n "$state_file" ]]; then
                echo "${newest_dir%/}"
                return
            fi
        fi
        echo ""
        return
    fi

    # Session filter: iterate newest-to-oldest.
    #
    # The caller's own (exact stored session_id) match takes precedence over
    # any marker-based adoption: with multiple active RLCR loops in the same
    # repo, a newer dir parked by a different session must not be returned
    # before an older dir that actually belongs to the caller. Marker
    # candidates are recorded during the scan and only used as a fallback
    # when no exact match is found anywhere. Zombie-loop protection
    # (terminal newest for this session returns empty) still wins over
    # marker fallback.
    local dir
    local marker_candidate=""
    while IFS= read -r dir; do
        [[ -z "$dir" ]] && continue
        local trimmed_dir="${dir%/}"

        local any_state
        any_state=$(resolve_any_state_file "$trimmed_dir")
        if [[ -z "$any_state" ]]; then
            continue
        fi

        local stored_session_id
        stored_session_id=$(sed -n '/^---$/,/^---$/{ /^'"${FIELD_SESSION_ID}"':/{ s/'"${FIELD_SESSION_ID}"': *//; p; } }' "$any_state" 2>/dev/null | tr -d ' ')

        # Empty stored session_id matches any session (backward compat).
        if [[ -z "$stored_session_id" ]] || [[ "$stored_session_id" == "$filter_session_id" ]]; then
            # Newest dir for this session -- only return if active.
            local active_state
            active_state=$(resolve_active_state_file "$trimmed_dir")
            if [[ -n "$active_state" ]]; then
                echo "$trimmed_dir"
                return
            fi
            # Session's newest loop is in terminal state; do not fall through
            # to marker-based adoption either.
            echo ""
            return
        fi

        # Session mismatch. Only the stop hook opts in to marker-based
        # adoption; validators and other callers keep strict isolation, so
        # the candidate is only recorded when the caller explicitly allows
        # it.
        if [[ "$allow_bg_marker_fallback" == "true" ]] \
           && [[ -z "$marker_candidate" ]] \
           && [[ -f "$trimmed_dir/bg-pending.marker" ]]; then
            local candidate_state
            candidate_state=$(resolve_active_state_file "$trimmed_dir")
            if [[ -n "$candidate_state" ]]; then
                marker_candidate="$trimmed_dir"
            fi
            # Marker on a terminal loop is stale; leave it alone.
        fi
    done < <(ls -1d "$loop_base_dir"/*/ 2>/dev/null | sort -r)

    # No exact session match. Fall back to marker-based adoption only when
    # the caller explicitly opted in -- the stop hook uses this to surface
    # a "parked by another session" notice or to resume its own parked
    # loop after a previous session died before the bg completion arrived.
    if [[ "$allow_bg_marker_fallback" == "true" ]] && [[ -n "$marker_candidate" ]]; then
        echo "$marker_candidate"
        return
    fi

    echo ""
}

# Extract current round number from state.md
# Outputs the round number to stdout, defaults to 0
# Note: For full state parsing, use parse_state_file() instead
get_current_round() {
    local state_file="$1"

    local frontmatter
    frontmatter=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$state_file" 2>/dev/null || echo "")

    local current_round
    current_round=$(echo "$frontmatter" | grep "^${FIELD_CURRENT_ROUND}:" | sed "s/${FIELD_CURRENT_ROUND}: *//" | tr -d ' ')

    echo "${current_round:-0}"
}

# Extract state fields from frontmatter content (internal helper)
# Usage: _parse_state_fields
# Requires STATE_FRONTMATTER to be set before calling
# Sets all STATE_* field variables without applying defaults
_parse_state_fields() {
    # Parse fields with consistent quote handling
    # Legacy quote-stripping kept for backward compatibility with older state files
    STATE_PLAN_TRACKED=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_PLAN_TRACKED}:" | sed "s/${FIELD_PLAN_TRACKED}: *//" | tr -d ' ' || true)
    STATE_START_BRANCH=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_START_BRANCH}:" | sed "s/${FIELD_START_BRANCH}: *//; s/^\"//; s/\"\$//" || true)
    STATE_BASE_BRANCH=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_BASE_BRANCH}:" | sed "s/${FIELD_BASE_BRANCH}: *//; s/^\"//; s/\"\$//" || true)
    STATE_BASE_COMMIT=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_BASE_COMMIT}:" | sed "s/${FIELD_BASE_COMMIT}: *//; s/^\"//; s/\"\$//" || true)
    STATE_PLAN_FILE=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_PLAN_FILE}:" | sed "s/${FIELD_PLAN_FILE}: *//; s/^\"//; s/\"\$//" || true)
    STATE_CURRENT_ROUND=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_CURRENT_ROUND}:" | sed "s/${FIELD_CURRENT_ROUND}: *//" | tr -d ' ' || true)
    STATE_MAX_ITERATIONS=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_MAX_ITERATIONS}:" | sed "s/${FIELD_MAX_ITERATIONS}: *//" | tr -d ' ' || true)
    STATE_PUSH_EVERY_ROUND=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_PUSH_EVERY_ROUND}:" | sed "s/${FIELD_PUSH_EVERY_ROUND}: *//" | tr -d ' ' || true)
    STATE_CODEX_MODEL=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_CODEX_MODEL}:" | sed "s/${FIELD_CODEX_MODEL}: *//" | tr -d ' ' || true)
    STATE_CODEX_EFFORT=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_CODEX_EFFORT}:" | sed "s/${FIELD_CODEX_EFFORT}: *//" | tr -d ' ' || true)
    STATE_CODEX_TIMEOUT=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_CODEX_TIMEOUT}:" | sed "s/${FIELD_CODEX_TIMEOUT}: *//" | tr -d ' ' || true)
    STATE_REVIEW_STARTED=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_REVIEW_STARTED}:" | sed "s/${FIELD_REVIEW_STARTED}: *//" | tr -d ' ' || true)
    STATE_FULL_REVIEW_ROUND=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_FULL_REVIEW_ROUND}:" | sed "s/${FIELD_FULL_REVIEW_ROUND}: *//" | tr -d ' ' || true)
    STATE_ASK_CODEX_QUESTION=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_ASK_CODEX_QUESTION}:" | sed "s/${FIELD_ASK_CODEX_QUESTION}: *//" | tr -d ' ' || true)
    STATE_SESSION_ID=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_SESSION_ID}:" | sed "s/${FIELD_SESSION_ID}: *//" || true)
    STATE_AGENT_TEAMS=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_AGENT_TEAMS}:" | sed "s/${FIELD_AGENT_TEAMS}: *//" | tr -d ' ' || true)
    STATE_PRIVACY_MODE=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_PRIVACY_MODE}:" | sed "s/${FIELD_PRIVACY_MODE}: *//" | tr -d ' ' || true)
    STATE_MAINLINE_STALL_COUNT=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_MAINLINE_STALL_COUNT}:" | sed "s/${FIELD_MAINLINE_STALL_COUNT}: *//" | tr -d ' ' || true)
    STATE_LAST_MAINLINE_VERDICT=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_LAST_MAINLINE_VERDICT}:" | sed "s/${FIELD_LAST_MAINLINE_VERDICT}: *//" | tr -d ' ' || true)
    STATE_DRIFT_STATUS=$(echo "$STATE_FRONTMATTER" | grep "^${FIELD_DRIFT_STATUS}:" | sed "s/${FIELD_DRIFT_STATUS}: *//" | tr -d ' ' || true)
}

# Parse state file frontmatter and set variables (tolerant mode with defaults)
# Usage: parse_state_file "$STATE_FILE"
# Sets the following variables (caller must declare them):
#   STATE_FRONTMATTER - raw frontmatter content
#   STATE_PLAN_TRACKED - "true" or "false"
#   STATE_START_BRANCH - branch name
#   STATE_BASE_BRANCH - base branch for code review
#   STATE_PLAN_FILE - plan file path
#   STATE_CURRENT_ROUND - current round number
#   STATE_MAX_ITERATIONS - max iterations
#   STATE_PUSH_EVERY_ROUND - "true" or "false"
#   STATE_CODEX_MODEL - codex model name
#   STATE_CODEX_EFFORT - codex effort level
#   STATE_CODEX_TIMEOUT - codex timeout in seconds
#   STATE_REVIEW_STARTED - "true" or "false"
#   STATE_FULL_REVIEW_ROUND - interval for Full Alignment Check (default: 5)
#   STATE_ASK_CODEX_QUESTION - "true" or "false" (v1.6.5+)
#   STATE_AGENT_TEAMS - "true" or "false"
#   STATE_MAINLINE_STALL_COUNT - consecutive stalled/regressed implementation rounds
#   STATE_LAST_MAINLINE_VERDICT - advanced/stalled/regressed/unknown
#   STATE_DRIFT_STATUS - normal/replan_required
# Returns: 0 on success, 1 if file not found
# Note: For strict validation, use parse_state_file_strict() instead
parse_state_file() {
    local state_file="$1"

    if [[ ! -f "$state_file" ]]; then
        return 1
    fi

    STATE_FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$state_file" 2>/dev/null || echo "")

    _parse_state_fields

    # Apply defaults for non-schema-critical fields only
    # Note: review_started is NOT defaulted here so we can detect missing schema fields
    # and block with a proper message in the stop hook
    STATE_CURRENT_ROUND="${STATE_CURRENT_ROUND:-0}"
    STATE_MAX_ITERATIONS="${STATE_MAX_ITERATIONS:-10}"
    STATE_PUSH_EVERY_ROUND="${STATE_PUSH_EVERY_ROUND:-false}"
    STATE_FULL_REVIEW_ROUND="${STATE_FULL_REVIEW_ROUND:-5}"
    STATE_ASK_CODEX_QUESTION="${STATE_ASK_CODEX_QUESTION:-true}"
    STATE_AGENT_TEAMS="${STATE_AGENT_TEAMS:-false}"
    # Default privacy_mode to "true" for legacy loops that pre-date this field
    STATE_PRIVACY_MODE="${STATE_PRIVACY_MODE:-true}"
    STATE_MAINLINE_STALL_COUNT="${STATE_MAINLINE_STALL_COUNT:-0}"
    STATE_LAST_MAINLINE_VERDICT="${STATE_LAST_MAINLINE_VERDICT:-$MAINLINE_VERDICT_UNKNOWN}"
    STATE_DRIFT_STATUS="${STATE_DRIFT_STATUS:-$DRIFT_STATUS_NORMAL}"
    # STATE_REVIEW_STARTED left as-is (empty if missing, to allow schema validation)

    return 0
}

# Strict state file parser that rejects malformed files
# Usage: parse_state_file_strict "$STATE_FILE"
# Sets the same variables as parse_state_file()
# Returns: 0 on success, non-zero on validation failure
#   1 - file not found
#   2 - missing YAML frontmatter separators
#   3 - missing required field (current_round or max_iterations)
#   4 - non-numeric current_round value
#   5 - non-numeric max_iterations value
parse_state_file_strict() {
    local state_file="$1"

    if [[ ! -f "$state_file" ]]; then
        echo "Error: State file not found: $state_file" >&2
        return 1
    fi

    # Check for YAML frontmatter separators (must have at least two --- lines)
    local separator_count
    separator_count=$(grep -c '^---$' "$state_file" 2>/dev/null || echo "0")
    if [[ "$separator_count" -lt 2 ]]; then
        echo "Error: Missing YAML frontmatter separators (---)" >&2
        return 2
    fi

    # Extract frontmatter and parse all fields (reuse shared helper, no defaults applied)
    STATE_FRONTMATTER=$(sed -n '/^---$/,/^---$/{ /^---$/d; p; }' "$state_file" 2>/dev/null || echo "")
    _parse_state_fields

    # Validate required fields exist
    if [[ -z "$STATE_CURRENT_ROUND" ]]; then
        echo "Error: Missing required field: current_round" >&2
        return 3
    fi
    if [[ -z "$STATE_MAX_ITERATIONS" ]]; then
        echo "Error: Missing required field: max_iterations" >&2
        return 3
    fi
    if [[ -z "$STATE_REVIEW_STARTED" ]]; then
        echo "Error: Missing required field: review_started" >&2
        return 3
    fi
    if [[ -z "$STATE_BASE_BRANCH" ]]; then
        echo "Error: Missing required field: base_branch" >&2
        return 3
    fi

    # Validate current_round is numeric (including 0 and negative)
    if ! [[ "$STATE_CURRENT_ROUND" =~ ^-?[0-9]+$ ]]; then
        echo "Error: Non-numeric current_round value: $STATE_CURRENT_ROUND" >&2
        return 4
    fi

    # Validate max_iterations is numeric
    if ! [[ "$STATE_MAX_ITERATIONS" =~ ^-?[0-9]+$ ]]; then
        echo "Error: Non-numeric max_iterations value: $STATE_MAX_ITERATIONS" >&2
        return 5
    fi

    # Validate review_started is boolean
    if [[ "$STATE_REVIEW_STARTED" != "true" && "$STATE_REVIEW_STARTED" != "false" ]]; then
        echo "Error: Invalid review_started value (must be true or false): $STATE_REVIEW_STARTED" >&2
        return 6
    fi

    # Apply defaults for optional fields only
    STATE_PUSH_EVERY_ROUND="${STATE_PUSH_EVERY_ROUND:-false}"
    STATE_FULL_REVIEW_ROUND="${STATE_FULL_REVIEW_ROUND:-5}"
    STATE_ASK_CODEX_QUESTION="${STATE_ASK_CODEX_QUESTION:-true}"
    STATE_AGENT_TEAMS="${STATE_AGENT_TEAMS:-false}"
    STATE_PRIVACY_MODE="${STATE_PRIVACY_MODE:-true}"
    STATE_MAINLINE_STALL_COUNT="${STATE_MAINLINE_STALL_COUNT:-0}"
    STATE_LAST_MAINLINE_VERDICT="${STATE_LAST_MAINLINE_VERDICT:-$MAINLINE_VERDICT_UNKNOWN}"
    STATE_DRIFT_STATUS="${STATE_DRIFT_STATUS:-$DRIFT_STATUS_NORMAL}"

    return 0
}

# Normalize mainline progress verdict to a safe enum.
# Usage: normalize_mainline_progress_verdict "ADVANCED"
normalize_mainline_progress_verdict() {
    local verdict_lower
    verdict_lower=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')

    case "$verdict_lower" in
        "$MAINLINE_VERDICT_ADVANCED"|"$MAINLINE_VERDICT_STALLED"|"$MAINLINE_VERDICT_REGRESSED")
            echo "$verdict_lower"
            ;;
        *)
            echo "$MAINLINE_VERDICT_UNKNOWN"
            ;;
    esac
}

# Normalize drift status to a safe enum.
# Usage: normalize_drift_status "replan_required"
normalize_drift_status() {
    local status_lower
    status_lower=$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')

    case "$status_lower" in
        "$DRIFT_STATUS_REPLAN_REQUIRED")
            echo "$DRIFT_STATUS_REPLAN_REQUIRED"
            ;;
        *)
            echo "$DRIFT_STATUS_NORMAL"
            ;;
    esac
}

# Extract "Mainline Progress Verdict" from Codex review content.
# Outputs one of: advanced, stalled, regressed, unknown
# Usage: extract_mainline_progress_verdict "$review_content"
extract_mainline_progress_verdict() {
    local review_content="$1"
    local verdict_line
    local verdict_value

    verdict_line=$(printf '%s\n' "$review_content" | grep -Ei 'Mainline Progress Verdict:[[:space:]]*(ADVANCED|STALLED|REGRESSED)([^A-Za-z]|$)' | tail -1 || true)
    if [[ -z "$verdict_line" ]]; then
        echo "$MAINLINE_VERDICT_UNKNOWN"
        return
    fi

    # Extract the verdict word using grep -oEi (portable) instead of sed /I (GNU-only).
    # The preceding grep -Ei already ensures the line contains one of the three verdicts.
    # Reject lines with multiple verdict keywords (e.g. placeholder template formats)
    # to avoid silently accepting an ambiguous verdict.
    local _verdict_matches
    _verdict_matches=$(printf '%s\n' "$verdict_line" | grep -oEi 'ADVANCED|STALLED|REGRESSED')
    local _match_count
    _match_count=$(printf '%s\n' "$_verdict_matches" | wc -l)
    if [[ "$_match_count" -gt 1 ]]; then
        echo "$MAINLINE_VERDICT_UNKNOWN"
        return
    fi
    verdict_value=$(printf '%s\n' "$_verdict_matches" | head -1)
    normalize_mainline_progress_verdict "$verdict_value"
}

# Upsert simple YAML frontmatter fields in a state file.
# Values must not contain newlines.
# Usage: upsert_state_fields "/path/to/state.md" "field=value" "other=value"
upsert_state_fields() {
    local state_file="$1"
    shift

    local temp_file="${state_file}.tmp.$$"

    awk -v assignments="$*" '
        BEGIN {
            count = split(assignments, pairs, " ");
            for (i = 1; i <= count; i++) {
                eq = index(pairs[i], "=");
                key = substr(pairs[i], 1, eq - 1);
                val = substr(pairs[i], eq + 1);
                keys[key] = val;
                order[i] = key;
            }
            separator_count = 0;
        }
        {
            if ($0 == "---") {
                separator_count++;
                if (separator_count == 2) {
                    for (i = 1; i <= count; i++) {
                        key = order[i];
                        if (!(key in seen)) {
                            print key ": " keys[key];
                            seen[key] = 1;
                        }
                    }
                }
                print;
                next;
            }

            handled = 0;
            for (i = 1; i <= count; i++) {
                key = order[i];
                if ($0 ~ ("^" key ":")) {
                    print key ": " keys[key];
                    seen[key] = 1;
                    handled = 1;
                    break;
                }
            }

            if (!handled) {
                print;
            }
        }
    ' "$state_file" > "$temp_file" && mv "$temp_file" "$state_file"
}

# Detect review issues from codex review log file
# Returns:
#   0 - issues found (caller should continue review loop)
#   1 - no issues found (caller can proceed to finalize)
#   2 - log file missing/empty (hard error - caller must block and require retry)
# Outputs: extracted review content to stdout if issues found
# Arguments: $1=round_number
# Required globals: LOOP_DIR, CACHE_DIR
#
# Algorithm:
# 1. Scan the last 50 lines of the log file for [P?] markers in the first 10
#    characters of each line. Real review issues only appear near the end of the
#    log; scanning the full file risks false positives from earlier debug output
#    and can hit argument-list-too-long limits on very large logs.
# 2. Find the first such line where [P?] (? is a digit) appears in the first 10
#    characters.
# 3. If found: extract from that line to the end and output it.
# 4. If not found: no issues, return 1.
#
# Note: codex review outputs to stderr, so we analyze the combined log file
# which contains both stdout and stderr (redirected with 2>&1).
detect_review_issues() {
    local round="$1"
    local log_file="$CACHE_DIR/round-${round}-codex-review.log"
    local result_file="$LOOP_DIR/round-${round}-review-result.md"

    # Check if log file exists and is not empty
    if [[ ! -f "$log_file" || ! -s "$log_file" ]]; then
        echo "Error: Codex review log file not found or empty: $log_file" >&2
        return 2
    fi

    local total_lines
    total_lines=$(wc -l < "$log_file")
    echo "Analyzing log file: $log_file ($total_lines lines)" >&2

    # Only scan the last 50 lines - real issues always appear near the end
    local scan_lines=50
    local start_line=$((total_lines > scan_lines ? total_lines - scan_lines + 1 : 1))

    # Use awk on the tail to find the first line where [P?] appears in first 10 chars
    local relative_line
    relative_line=$(tail -n "$scan_lines" "$log_file" | awk '
        substr($0, 1, 10) ~ /\[P[0-9]\]/ {
            print NR
            exit
        }
    ')

    if [[ -n "$relative_line" && "$relative_line" -gt 0 ]]; then
        # Convert relative line (within tail) to absolute line in the full file
        local found_line=$((start_line + relative_line - 1))
        echo "Found [P?] issue at line $found_line" >&2

        # Extract from found_line to end
        local extracted_content
        extracted_content=$(sed -n "${found_line},\$p" "$log_file")

        # Save to result file for audit purposes
        printf '%s\n' "$extracted_content" > "$result_file"
        echo "Review issues extracted to: $result_file" >&2

        # Output the content for the caller
        printf '## Codex Review Issues\n\n%s\n' "$extracted_content"
        return 0
    fi

    echo "No [P?] issues found in log file" >&2
    return 1
}

# Convert a string to lowercase
to_lower() {
    echo "$1" | tr '[:upper:]' '[:lower:]'
}

# Check if a path (lowercase) matches a round file pattern
# Usage: is_round_file "$lowercase_path" "summary|prompt|todos|contract"
is_round_file_type() {
    local path_lower="$1"
    local file_type="$2"

    echo "$path_lower" | grep -qE "round-[0-9]+-${file_type}\\.md\$"
}

# Extract round number from a filename
# Usage: extract_round_number "round-5-summary.md"
# Outputs the round number or empty string
extract_round_number() {
    local filename="$1"
    local filename_lower
    filename_lower=$(to_lower "$filename")

    # Use sed for portable regex extraction (works in both bash and zsh)
    echo "$filename_lower" | sed -n 's/.*round-\([0-9][0-9]*\)-\(summary\|prompt\|todos\|contract\)\.md$/\1/p'
}

# Check if a file is in the allowlist for the active loop
# Usage: is_allowlisted_file "$file_path" "$active_loop_dir"
# Returns: 0 if allowlisted, 1 otherwise
is_allowlisted_file() {
    local file_path="$1"
    local active_loop_dir="$2"

    local allowlist=(
        "round-1-todos.md"
        "round-2-todos.md"
        "round-0-summary.md"
        "round-1-summary.md"
    )

    for allowed in "${allowlist[@]}"; do
        if [[ "$file_path" == "$active_loop_dir/$allowed" ]]; then
            return 0
        fi
    done

    return 1
}

# Standard message for blocking todos file access
# Usage: todos_blocked_message "Read|Write|Bash"
todos_blocked_message() {
    local action="$1"
    local fallback="# Todos File Access Blocked

Do NOT create or access round-*-todos.md files. Use the native Task tools instead (TaskCreate, TaskUpdate, TaskList)."

    load_and_render_safe "$TEMPLATE_DIR" "block/todos-file-access.md" "$fallback"
}

# Standard message for blocking prompt file writes
prompt_write_blocked_message() {
    local fallback="# Prompt File Write Blocked

You cannot write to round-*-prompt.md files. These contain instructions FROM Codex TO you."

    load_and_render_safe "$TEMPLATE_DIR" "block/prompt-file-write.md" "$fallback"
}

# Standard message for blocking state file modifications
state_file_blocked_message() {
    local fallback="# State File Modification Blocked

You cannot modify state.md. This file is managed by the loop system."

    load_and_render_safe "$TEMPLATE_DIR" "block/state-file-modification.md" "$fallback"
}

# Standard message for blocking finalize-state file modifications
finalize_state_file_blocked_message() {
    local fallback="# Finalize State File Modification Blocked

You cannot modify finalize-state.md. This file is managed by the loop system during the Finalize Phase."

    load_and_render_safe "$TEMPLATE_DIR" "block/finalize-state-file-modification.md" "$fallback"
}

# Standard message for blocking round contract access during Finalize Phase
# Usage: finalize_contract_blocked_message "read"
finalize_contract_blocked_message() {
    local action="$1"
    local fallback="# Finalize Contract Access Blocked

There is no active round contract during the Finalize Phase.

Do not {{ACTION}} historical round contract files.
Use finalize-summary.md for finalize-only notes and goal-tracker.md for current state."

    load_and_render_safe "$TEMPLATE_DIR" "block/finalize-contract-access.md" "$fallback" \
        "ACTION=$action"
}

# Standard message for blocking summary file modifications via Bash
# Usage: summary_bash_blocked_message "$correct_summary_path"
summary_bash_blocked_message() {
    local correct_path="$1"
    local fallback="# Bash Write Blocked

Do not use Bash commands to modify summary files. Use the Write or Edit tool instead: {{CORRECT_PATH}}"

    load_and_render_safe "$TEMPLATE_DIR" "block/summary-bash-write.md" "$fallback" "CORRECT_PATH=$correct_path"
}

# Standard message for blocking goal-tracker modifications via Bash in Round 0
# Usage: goal_tracker_bash_blocked_message "$correct_goal_tracker_path"
goal_tracker_bash_blocked_message() {
    local correct_path="$1"
    local fallback="# Bash Write Blocked

Do not use Bash commands to modify goal-tracker.md. Use the Write or Edit tool instead: {{CORRECT_PATH}}"

    load_and_render_safe "$TEMPLATE_DIR" "block/goal-tracker-bash-write.md" "$fallback" "CORRECT_PATH=$correct_path"
}

# Check if a path (lowercase) targets goal-tracker.md
is_goal_tracker_path() {
    local path_lower="$1"
    echo "$path_lower" | grep -qE 'goal-tracker\.md$'
}

# Extract the immutable section from a goal-tracker content stream.
# Supports both current trackers (with --- separator) and older trackers
# that jump directly from IMMUTABLE SECTION to MUTABLE SECTION.
extract_goal_tracker_immutable_from_stream() {
    awk '
        /^## IMMUTABLE SECTION[[:space:]]*$/ { capture=1 }
        capture && /^## MUTABLE SECTION[[:space:]]*$/ { exit }
        capture && /^---[[:space:]]*$/ { exit }
        capture { print }
    '
}

# Extract the immutable section from an on-disk goal-tracker file.
# Usage: extract_goal_tracker_immutable_from_file "/path/to/goal-tracker.md"
extract_goal_tracker_immutable_from_file() {
    local tracker_file="$1"
    if [[ ! -f "$tracker_file" ]]; then
        return 1
    fi
    extract_goal_tracker_immutable_from_stream < "$tracker_file"
}

# Extract the immutable section from an in-memory goal-tracker string.
# Usage: extract_goal_tracker_immutable_from_text "$content"
extract_goal_tracker_immutable_from_text() {
    local tracker_content="$1"
    printf '%s' "$tracker_content" | extract_goal_tracker_immutable_from_stream
}

# Check whether a proposed goal-tracker update preserves the immutable section.
# Usage: goal_tracker_mutable_update_allowed "/path/to/current.md" "$new_content"
goal_tracker_mutable_update_allowed() {
    local tracker_file="$1"
    local updated_content="$2"

    local current_immutable=""
    local updated_immutable=""
    current_immutable=$(extract_goal_tracker_immutable_from_file "$tracker_file" 2>/dev/null || true)
    updated_immutable=$(extract_goal_tracker_immutable_from_text "$updated_content" 2>/dev/null || true)

    # Legacy trackers without IMMUTABLE SECTION: allow edits unconditionally.
    [[ -n "$current_immutable" ]] || return 0
    [[ "$current_immutable" == "$updated_immutable" ]]
}

# Render the post-edit contents for a literal Edit operation.
# Returns non-zero if the edit preview cannot be produced.
# Usage: preview_edit_result "/path/to/file" "$old_string" "$new_string" "true|false"
preview_edit_result() {
    local file_path="$1"
    local old_string="$2"
    local new_string="$3"
    local replace_all="${4:-false}"

    command -v perl >/dev/null 2>&1 || return 1

    FILE_PATH="$file_path" \
    OLD_STRING="$old_string" \
    NEW_STRING="$new_string" \
    REPLACE_ALL="$replace_all" \
    perl -0pe '
        BEGIN {
            $old = $ENV{"OLD_STRING"};
            $new = $ENV{"NEW_STRING"};
            $replace_all = $ENV{"REPLACE_ALL"} eq "true";
        }
        if ($replace_all) {
            s/\Q$old\E/$new/g;
        } else {
            s/\Q$old\E/$new/;
        }
    ' "$file_path"
}

# Check if a path (lowercase) targets state.md
is_state_file_path() {
    local path_lower="$1"
    echo "$path_lower" | grep -qE 'state\.md$'
}

# Check if a path (lowercase) targets finalize-state.md
is_finalize_state_file_path() {
    local path_lower="$1"
    echo "$path_lower" | grep -qE 'finalize-state\.md$'
}

# Check if a path (lowercase) targets methodology-analysis-state.md
is_methodology_analysis_state_file_path() {
    local path_lower="$1"
    echo "$path_lower" | grep -qE 'methodology-analysis-state\.md$'
}

# Standard message for blocking methodology-analysis-state file modifications
methodology_analysis_state_file_blocked_message() {
    local fallback="# Methodology Analysis State File Modification Blocked

You cannot modify methodology-analysis-state.md. This file is managed by the loop system during the Methodology Analysis Phase."

    load_and_render_safe "$TEMPLATE_DIR" "block/methodology-analysis-state-file-modification.md" "$fallback"
}

# Check if a path (lowercase) targets finalize-summary.md
is_finalize_summary_path() {
    local path_lower="$1"
    echo "$path_lower" | grep -qE 'finalize-summary\.md$'
}

# Normalize paths by removing /./ and collapsing // to /
# This allows paths like /path/to/./state.md to match /path/to/state.md
_normalize_path() {
    echo "$1" | sed 's|/\./|/|g; s|//|/|g'
}

# Check if cancel operation is authorized via signal file
# Usage: is_cancel_authorized "$active_loop_dir" "$command_lower"
# Returns: 0 if authorized, non-zero otherwise
#   1 - missing signal file
#   2 - security violation (injection, command substitution, etc.)
#   3 - mixed quote styles
#   4 - multiple trailing spaces
#   5 - invalid command structure
#   6 - source file is a symlink (filesystem check)
#
# Security notes:
# - Normalizes $loop_dir/${loop_dir} to actual path before validation
# - Rejects $(cmd) command substitution and backticks
# - Rejects any remaining $ after normalization (prevents hidden vars like ${IFS})
# - Enforces exactly two arguments: state.md or finalize-state.md source and cancel-state.md dest
# - Rejects shell operators for command chaining
# - Rejects mixed quote styles and multiple trailing spaces
# - Rejects if source file is a symlink
is_cancel_authorized() {
    local active_loop_dir="$1"
    local command_lower="$2"

    local cancel_signal="$active_loop_dir/.cancel-requested"

    # Signal file must exist
    if [[ ! -f "$cancel_signal" ]]; then
        return 1
    fi

    # SECURITY: Reject command substitution and backticks
    if echo "$command_lower" | grep -qE '\$\(|`'; then
        return 2
    fi

    # Reject newlines (multi-command injection)
    if [[ "$command_lower" == *$'\n'* ]]; then
        return 2
    fi

    # Reject shell operators for command chaining
    if echo "$command_lower" | grep -qE ';|&&|\|\||\|'; then
        return 2
    fi

    # Reject multiple trailing spaces
    if echo "$command_lower" | grep -qE '[[:space:]]{2,}$'; then
        return 4
    fi

    # Canonicalize the loop dir (idempotent: resolve_project_root already
    # canonicalizes, but callers may supply a non-canonical override). Both
    # sides of the upcoming string comparisons must be canonicalized through
    # the same transformation or a symlinked prefix in the user's command
    # (e.g. /var/... vs /private/var/... on macOS) will spuriously fail the
    # authorization check.
    local canonical_loop_dir
    canonical_loop_dir="$(canonicalize_path "${active_loop_dir%/}")"
    canonical_loop_dir="${canonical_loop_dir:-${active_loop_dir%/}}"

    # Normalize: Replace $loop_dir and ${loop_dir} with actual path
    local normalized="$command_lower"
    local loop_dir_lower
    loop_dir_lower="${canonical_loop_dir}/"
    loop_dir_lower=$(echo "$loop_dir_lower" | tr '[:upper:]' '[:lower:]')

    normalized="${normalized//\$\{loop_dir\}/$loop_dir_lower}"
    normalized="${normalized//\$loop_dir/$loop_dir_lower}"

    # After normalization, reject any remaining $ (prevents hidden vars like ${IFS})
    if echo "$normalized" | grep -qE '\$'; then
        return 2
    fi

    # Must start with mv followed by space
    if ! echo "$normalized" | grep -qE '^mv[[:space:]]+'; then
        return 5
    fi

    # Extract arguments after "mv "
    local args
    args=$(echo "$normalized" | sed 's/^mv[[:space:]]*//')

    # Detect quote types used in both arguments
    # Check for mixed quotes by detecting if both ' and " are used as delimiters
    local has_single=false has_double=false
    local first_char
    first_char=$(echo "$args" | cut -c1)
    if [[ "$first_char" == '"' ]]; then
        has_double=true
    elif [[ "$first_char" == "'" ]]; then
        has_single=true
    fi

    # Skip first argument to check second
    local args_after_first
    if [[ "$first_char" == '"' ]]; then
        args_after_first=$(echo "$args" | sed 's/^"[^"]*"[[:space:]]*//')
    elif [[ "$first_char" == "'" ]]; then
        args_after_first=$(echo "$args" | sed "s/^'[^']*'[[:space:]]*//")
    else
        args_after_first=$(echo "$args" | sed 's/^[^[:space:]]*[[:space:]]*//')
    fi

    local second_char
    second_char=$(echo "$args_after_first" | cut -c1)
    if [[ "$second_char" == '"' ]]; then
        has_double=true
    elif [[ "$second_char" == "'" ]]; then
        has_single=true
    fi

    # Reject mixed quote styles
    if [[ "$has_single" == "true" ]] && [[ "$has_double" == "true" ]]; then
        return 3
    fi

    # Parse arguments, respecting quotes
    local src dest
    if echo "$args" | grep -qE "^[\"']"; then
        local quote_char
        quote_char=$(echo "$args" | cut -c1)
        if [[ "$quote_char" == '"' ]]; then
            src=$(echo "$args" | sed -n 's/^"\([^"]*\)".*/\1/p')
            args=$(echo "$args" | sed 's/^"[^"]*"[[:space:]]*//')
        else
            src=$(echo "$args" | sed -n "s/^'\\([^']*\\)'.*/\\1/p")
            args=$(echo "$args" | sed "s/^'[^']*'[[:space:]]*//")
        fi
    else
        src=$(echo "$args" | sed 's/[[:space:]].*//')
        args=$(echo "$args" | sed 's/^[^[:space:]]*[[:space:]]*//')
    fi

    if echo "$args" | grep -qE "^[\"']"; then
        local quote_char
        quote_char=$(echo "$args" | cut -c1)
        if [[ "$quote_char" == '"' ]]; then
            dest=$(echo "$args" | sed -n 's/^"\([^"]*\)".*/\1/p')
            args=$(echo "$args" | sed 's/^"[^"]*"[[:space:]]*//')
        else
            dest=$(echo "$args" | sed -n "s/^'\\([^']*\\)'.*/\\1/p")
            args=$(echo "$args" | sed "s/^'[^']*'[[:space:]]*//")
        fi
    else
        dest=$(echo "$args" | sed 's/[[:space:]].*//')
        args=$(echo "$args" | sed 's/^[^[:space:]]*//')
    fi

    if [[ -z "$src" ]] || [[ -z "$dest" ]]; then
        return 5
    fi

    # Check for extra arguments
    args=$(echo "$args" | sed 's/^[[:space:]]*//')
    if [[ -n "$args" ]]; then
        return 5
    fi

    # Normalize and validate source path.
    #
    # Use canonicalize_path_prefix (NOT canonicalize_path): we need to resolve
    # symlinks in the parent directory so a symlinked project prefix matches
    # canonical_loop_dir, but we MUST NOT dereference a symlink at the leaf.
    # Otherwise a symlink like /tmp/alias -> <loop>/state.md would canonicalize
    # to <loop>/state.md and pass the check, but `mv` would then operate on
    # the link path itself, escaping the loop directory and/or corrupting
    # loop state. The on-disk symlink rejection below (src_original check)
    # still fires because it probes the real state.md under canonical_loop_dir.
    #
    # Re-lowercase after canonicalization because realpath on case-insensitive
    # filesystems may restore the original casing of path components, which
    # would diverge from the already-lowercased expected_* values.
    src=$(_normalize_path "$src")
    local src_canonical
    src_canonical="$(canonicalize_path_prefix "$src")"
    src_canonical="${src_canonical:-$src}"
    src_canonical=$(echo "$src_canonical" | tr '[:upper:]' '[:lower:]')
    local expected_src_state="${loop_dir_lower}state.md"
    local expected_src_finalize="${loop_dir_lower}finalize-state.md"
    local expected_src_methodology="${loop_dir_lower}methodology-analysis-state.md"
    if [[ "$src_canonical" != "$expected_src_state" ]] && [[ "$src_canonical" != "$expected_src_finalize" ]] && [[ "$src_canonical" != "$expected_src_methodology" ]]; then
        return 5
    fi

    # Normalize and validate destination path. Uses canonicalize_path_prefix
    # for the same reason as src: a symlink alias pointing at the real
    # cancel-state.md must NOT pass authorization, because `mv` onto a
    # symlink replaces the link rather than creating <loop>/cancel-state.md,
    # corrupting loop state and moving state.md outside the loop dir.
    dest=$(_normalize_path "$dest")
    local dest_canonical
    dest_canonical="$(canonicalize_path_prefix "$dest")"
    dest_canonical="${dest_canonical:-$dest}"
    dest_canonical=$(echo "$dest_canonical" | tr '[:upper:]' '[:lower:]')
    local expected_dest="${loop_dir_lower}cancel-state.md"
    if [[ "$dest_canonical" != "$expected_dest" ]]; then
        return 5
    fi

    # SECURITY: Reject if source file is a symlink (filesystem check)
    # Determine source file by comparing against expected paths (not substring match)
    # This avoids vulnerability when loop directory path contains "finalize" or "methodology"
    # Use canonical_loop_dir so the symlink check runs against the real on-disk
    # path rather than a user-supplied non-canonical form.
    local src_original
    if [[ "$src_canonical" == "$expected_src_methodology" ]]; then
        src_original="${canonical_loop_dir}/methodology-analysis-state.md"
    elif [[ "$src_canonical" == "$expected_src_finalize" ]]; then
        src_original="${canonical_loop_dir}/finalize-state.md"
    else
        src_original="${canonical_loop_dir}/state.md"
    fi
    if [[ -L "$src_original" ]]; then
        return 6  # Source is a symlink
    fi

    return 0
}

# Check if a path is inside .humanize/rlcr directory
is_in_humanize_loop_dir() {
    local path="$1"
    echo "$path" | grep -q '\.humanize/rlcr/'
}

# Check if a git add command would add .humanize files to version control
# Usage: git_adds_humanize "$command_lower"
# Returns 0 if the command would add .humanize files, 1 otherwise
#
# IMPORTANT: This function receives LOWERCASED input from the validator.
# Git flags like -A become -a after lowercasing, so we match both.
#
# Handles:
# - git -C <dir> add (git options before add subcommand)
# - Chained commands: cd repo && git add .humanize
# - Shell operators: ;, &&, ||, |
#
# Blocks:
# - git add .humanize or git add .humanize/
# - git add .humanize/* or git add .humanize/**
# - git add -f .humanize* (force add)
# - git add -f . or git add --force . (force add all - bypasses gitignore)
# - git add -f -A or git add --force --all (force add all)
# - git add -fA or similar combined flags
# - git add -A or git add --all (when .humanize exists)
# - git add . or git add * (when .humanize exists and not gitignored)
#
git_adds_humanize() {
    local cmd="$1"

    # Split command on shell operators and check each segment
    # This handles chained commands like: cd repo && git add .humanize
    local segments
    segments=$(echo "$cmd" | sed '
        s/&&/\n/g
        s/||/\n/g
        s/|/\n/g
        s/;/\n/g
    ')

    while IFS= read -r segment; do
        [[ -z "$segment" ]] && continue

        # Check if this segment contains a git add command
        # Pattern: git (with optional flags/options) followed by add
        # Handles:
        # - git add
        # - git -C dir add (short option with separate arg)
        # - git --git-dir=x add (long option with = arg)
        # - git -c key=value add (short option with = arg)
        # The pattern allows any non-add tokens between git and add
        if ! echo "$segment" | grep -qE '(^|[[:space:]])git[[:space:]]+([^[:space:]]+[[:space:]]+)*add([[:space:]]|$)'; then
            continue
        fi

        # Extract the part after "add" for analysis
        local add_args
        add_args=$(echo "$segment" | sed -n 's/.*[[:space:]]add[[:space:]]*//p')

        # Normalize add_args: strip quotes for path matching
        # This handles: git add ".humanize", git add '.humanize'
        local add_args_normalized
        add_args_normalized=$(echo "$add_args" | sed "s/[\"']//g")

        # Check for direct .humanize reference (blocked regardless of other flags)
        # Handles: .humanize, ./.humanize, path/to/.humanize, ".humanize", '.humanize'
        # Pattern matches .humanize at start, after space, after / or ./ AND followed by end, /, or space
        # This avoids over-blocking .humanizeconfig or .humanize-backup.
        if echo "$add_args_normalized" | grep -qE '(^|[[:space:]]|/)\.humanize($|/|[[:space:]])'; then
            return 0
        fi

        # Check for -f or --force flag (including combined flags like -fa, -af)
        local has_force=false
        if echo "$add_args" | grep -qE '(^|[[:space:]])--force([[:space:]]|$)'; then
            has_force=true
        elif echo "$add_args" | grep -qE '(^|[[:space:]])-[a-z]*f[a-z]*([[:space:]]|$)'; then
            has_force=true
        fi

        # Check for -A/--all flag (including combined flags like -fa, -af)
        # Note: input is lowercased, so -A becomes -a
        local has_all=false
        if echo "$add_args" | grep -qE '(^|[[:space:]])--all([[:space:]]|$)'; then
            has_all=true
        elif echo "$add_args" | grep -qE '(^|[[:space:]])-[a-z]*a[a-z]*([[:space:]]|$)'; then
            has_all=true
        fi

        # Check for broad scope targets: . or * alone
        local has_broad_scope=false
        if echo "$add_args" | grep -qE '(^|[[:space:]])(\.|\*)([[:space:]]|$)'; then
            has_broad_scope=true
        fi

        # Force add with any broad scope (force bypasses gitignore entirely)
        if [[ "$has_force" == "true" ]]; then
            if [[ "$has_all" == "true" ]] || [[ "$has_broad_scope" == "true" ]]; then
                return 0
            fi
        fi

        # Check if .humanize exists - needed for non-force blocking
        if [[ ! -d ".humanize" ]]; then
            continue
        fi

        # git add -A/--all when .humanize exists
        # Always block because -A adds all changes including untracked files
        if [[ "$has_all" == "true" ]]; then
            return 0
        fi

        # git add . or git add * when .humanize exists and not gitignored
        # Only block if .humanize is NOT protected by gitignore
        if [[ "$has_broad_scope" == "true" ]]; then
            if ! git check-ignore -q .humanize 2>/dev/null; then
                return 0
            fi
        fi
    done <<< "$segments"

    return 1
}

# Standard message for blocking git add .humanize commands
# Usage: git_add_humanize_blocked_message
git_add_humanize_blocked_message() {
    local fallback="# Git Add Blocked: .humanize Protection

The \`.humanize/\` directory contains local loop state that should NOT be committed.

Your command was blocked because it would add .humanize files to version control.

## Allowed Commands

Use specific file paths instead of broad patterns:

    git add <specific-file>
    git add src/
    git add -p  # patch mode

## Blocked Commands

These commands are blocked when .humanize exists:

    git add .humanize      # direct reference
    git add -A             # adds all including .humanize
    git add --all          # adds all including .humanize
    git add .              # may include .humanize if not gitignored
    git add -f .           # force bypasses gitignore

## Adding .humanize to .gitignore

If you need to add \`.humanize*\` to \`.gitignore\`, follow these steps:

1. Edit \`.gitignore\` to append \`.humanize*\`
2. Run: \`git add .gitignore\`
3. Run: \`git commit -m \"Add humanize local folder into gitignore\"\`

IMPORTANT: The commit message must NOT contain the literal string \".humanize\" to avoid triggering this protection."

    load_and_render_safe "$TEMPLATE_DIR" "block/git-add-humanize.md" "$fallback"
}

# Return success if local Humanize runtime state has entered git tracking or the index.
# Untracked .humanize state is allowed; tracked or staged state must be blocked.
# Usage: git_has_tracked_humanize_state [project_root]
#
# Intentionally scoped to .humanize/ to stay consistent with git_adds_humanize,
# which explicitly allows unrelated paths like .humanize-backup or
# .humanizeconfig (see tests/test-humanize-escape.sh). ls-files covers both
# committed entries and paths staged via git add; paths the user has staged for
# removal via git rm --cached are correctly omitted so the user can unstick
# themselves without being re-blocked.
git_has_tracked_humanize_state() {
    local project_root="${1:-.}"

    if [[ ! -d "$project_root/.git" ]] && ! git -C "$project_root" rev-parse --git-dir >/dev/null 2>&1; then
        return 1
    fi

    if git -C "$project_root" ls-files -- .humanize 2>/dev/null | grep -q '.'; then
        return 0
    fi

    return 1
}

# Standard message for blocking tracked/staged .humanize state.
# Usage: git_tracked_humanize_blocked_message
git_tracked_humanize_blocked_message() {
    local fallback="# Tracked Humanize State Blocked

Detected tracked or staged files under \`.humanize/\`.

These files are local Humanize loop state and must remain outside version control.

## Required Fix

1. Remove Humanize state from the index:

       git rm --cached -r .humanize

2. Keep only real project files staged.
3. Retry the stop action after the local state is no longer tracked.

## Important

- Do NOT use \`git add -f\` on Humanize state files.
- Do NOT commit RLCR trackers, round summaries, contracts, or cancel/finalize markers."

    load_and_render_safe "$TEMPLATE_DIR" "block/git-tracked-humanize.md" "$fallback"
}

# Standard message for blocking direct execution of hook scripts
# Usage: stop_hook_direct_execution_blocked_message
stop_hook_direct_execution_blocked_message() {
    local fallback="# Direct Execution of Hook Scripts Blocked

You are attempting to directly execute a hook script via Bash. This is not allowed during an active loop.

Hook scripts are managed by the hooks system and are triggered automatically at the appropriate time. You should NOT execute them manually.

Simply complete your work and end your response. The hooks system will handle the rest automatically."

    load_and_render_safe "$TEMPLATE_DIR" "block/stop-hook-direct-execution.md" "$fallback"
}

# Check if a shell command attempts to modify a file matching the given pattern
# Usage: command_modifies_file "$command_lower" "goal-tracker\.md"
# Returns 0 if the command tries to modify the file, 1 otherwise
command_modifies_file() {
    local command_lower="$1"
    local file_pattern="$2"

    local patterns=(
        ">[[:space:]]*[^[:space:]]*${file_pattern}"
        ">>[[:space:]]*[^[:space:]]*${file_pattern}"
        "tee[[:space:]]+(-a[[:space:]]+)?[^[:space:]]*${file_pattern}"
        "sed[[:space:]]+-i[^|]*${file_pattern}"
        "awk[[:space:]]+-i[[:space:]]+inplace[^|]*${file_pattern}"
        "perl[[:space:]]+-[^[:space:]]*i[^|]*${file_pattern}"
        "(mv|cp)[[:space:]]+[^[:space:]]+[[:space:]]+[^[:space:]]*${file_pattern}"
        "rm[[:space:]]+(-[rfv]+[[:space:]]+)?[^[:space:]]*${file_pattern}"
        "dd[[:space:]].*of=[^[:space:]]*${file_pattern}"
        "truncate[[:space:]]+[^|]*${file_pattern}"
        "printf[[:space:]].*>[[:space:]]*[^[:space:]]*${file_pattern}"
        "exec[[:space:]]+[0-9]*>[[:space:]]*[^[:space:]]*${file_pattern}"
    )

    for pattern in "${patterns[@]}"; do
        if echo "$command_lower" | grep -qE "$pattern"; then
            return 0
        fi
    done
    return 1
}

# Standard message for blocking goal-tracker modifications after Round 0
# Usage: goal_tracker_blocked_message "$current_round" "$correct_goal_tracker_path"
goal_tracker_blocked_message() {
    local current_round="$1"
    local correct_path="$2"
    local fallback="# Goal Tracker Update Blocked (Round {{CURRENT_ROUND}})

After Round 0, you may update only the **MUTABLE SECTION** of the active goal tracker.

Use Write or Edit on: {{CORRECT_PATH}}

Rules:
- Keep the **IMMUTABLE SECTION** unchanged
- Do not modify `goal-tracker.md` via Bash
- Do not write to an old loop session's tracker"

    load_and_render_safe "$TEMPLATE_DIR" "block/goal-tracker-modification.md" "$fallback" \
        "CURRENT_ROUND=$current_round" \
        "CORRECT_PATH=$correct_path"
}

# End the loop by renaming state.md to indicate exit reason
# Usage: end_loop "$loop_dir" "$state_file" "complete|cancel|maxiter|stop|unexpected"
# Arguments:
#   $1 - loop_dir: Path to the loop directory
#   $2 - state_file: Path to the state.md file
#   $3 - reason: One of complete, cancel, maxiter, stop, unexpected
# Returns: 0 on success, 1 on failure
end_loop() {
    local loop_dir="$1"
    local state_file="$2"
    local reason="$3"  # complete, cancel, maxiter, stop, unexpected

    # Validate reason
    case "$reason" in
        complete|cancel|maxiter|stop|unexpected)
            ;;
        *)
            echo "Error: Invalid end_loop reason: $reason" >&2
            return 1
            ;;
    esac

    local target_name="${reason}-state.md"

    if [[ -f "$state_file" ]]; then
        mv "$state_file" "$loop_dir/$target_name"
        echo "Loop ended: $reason" >&2
        echo "State preserved as: $loop_dir/$target_name" >&2
        return 0
    else
        echo "Warning: State file not found, cannot end loop" >&2
        return 1
    fi
}

# Source background-task helpers. Sourced at the bottom so every function
# above is available to callers that only need loop-common.sh, while bg-aware
# callers (the stop hook, the test suite) still get the bg helpers via a
# single source of loop-common.sh.
#
# _LOOP_COMMON_DIR is set here instead of at the top of the file because
# loop-bg-tasks.sh lives in the same directory as this file and we want to
# locate it regardless of how loop-common.sh was sourced.
_LOOP_COMMON_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
# shellcheck source=loop-bg-tasks.sh
source "$_LOOP_COMMON_DIR/loop-bg-tasks.sh"