-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloop.sh
More file actions
executable file
·5448 lines (4913 loc) · 185 KB
/
loop.sh
File metadata and controls
executable file
·5448 lines (4913 loc) · 185 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# LoopDex · loop.sh
#
# Usage: ./loop.sh N /path/to/myproject
# Example: ./loop.sh 3 /path/to/myproject
#
# Prerequisites:
# - codex CLI: npm install -g @openai/codex
# - ChatGPT account login: codex login (Plus subscription or higher required)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AGENTS_DIR="$SCRIPT_DIR/agents"
ORIGINAL_COMMAND="$0"
for arg in "$@"; do
printf -v quoted_arg '%q' "$arg"
ORIGINAL_COMMAND+=" $quoted_arg"
done
# ── User-env snapshots ────────────────────────────────────────
# Capture user-exported env BEFORE any defaults or config loading so that
# precedence (user env > config.env > built-in default) is preserved.
LOOP_USER_CLI_ENV="${LOOP_CLI:-}"
LOOP_USER_CODEX_MODEL="${CODEX_MODEL:-}"
LOOP_USER_GEMINI_MODEL="${LOOP_GEMINI_MODEL:-}"
LOOP_USER_BRANCH_PREFIX="${LOOP_REQUIRE_BRANCH_PREFIX:-}"
# Defaults for config-managed keys are applied AFTER load_or_init_config
# (search for "apply_config_managed_defaults"). Don't set CODEX_MODEL here.
# After Impl Critic PASS, pins the implementation result as a git commit.
# Can be disabled at runtime:
# COMMIT_ON_PASS=0 ./loop.sh 3 /path/to/project
COMMIT_ON_PASS="${COMMIT_ON_PASS:-1}"
# Verify commands run with a 300 second timeout by default; override with LOOP_VERIFY_TIMEOUT.
LOOP_VERIFY_TIMEOUT="${LOOP_VERIFY_TIMEOUT:-300}"
# A task is blocked after 5 consecutive failures by default; override with LOOP_MAX_ATTEMPTS.
LOOP_MAX_ATTEMPTS="${LOOP_MAX_ATTEMPTS:-5}"
# Keep the newest N loop evidence directories; 0 disables evidence retention.
LOOP_EVIDENCE_KEEP_RUNS="${LOOP_EVIDENCE_KEEP_RUNS:-10}"
# Prune the current loop's evidence directory immediately after a PASS commit.
# Defaults to 1: PASS-loop diffs/verify outputs are redundant with git history,
# so removing them keeps .loop-agent/evidence/ small. Set to 0 to retain
# PASS evidence (e.g. for forensic auditing). FAIL/BLOCKED/proposal evidence
# is never affected by this flag.
LOOP_EVIDENCE_PRUNE_PASS="${LOOP_EVIDENCE_PRUNE_PASS:-1}"
# Risk mode controls built-in CLI bypass flags for unattended execution.
LOOP_RISK_MODE="${LOOP_RISK_MODE:-unattended}"
. "$SCRIPT_DIR/lib/cli_adapters.sh"
. "$SCRIPT_DIR/lib/decision.sh"
. "$SCRIPT_DIR/lib/evidence.sh"
# ── Colors ────────────────────────────────────────────────────
RED="\033[31m"; GREEN="\033[32m"; YELLOW="\033[33m"
CYAN="\033[36m"; GRAY="\033[90m"; BOLD="\033[1m"; RESET="\033[0m"
err() { echo -e "${RED}Error: $*${RESET}" >&2; }
ok() { echo -e "${GREEN}✓ $*${RESET}"; }
info() { echo -e "${GRAY} $*${RESET}"; }
warn() { echo -e "${YELLOW}⚠ $*${RESET}"; }
# Placeholder model IDs (kept empty by default — every shipped default is now
# a real model ID per the wizard list). Add IDs here if a future LoopDex
# release ships an unverified default that should warn users at startup.
LOOP_PLACEHOLDER_CODEX_MODELS=()
LOOP_PLACEHOLDER_GEMINI_MODELS=()
is_placeholder_model() {
local val="$1"; shift
local m
for m in "$@"; do
[[ "$val" == "$m" ]] && return 0
done
return 1
}
# ── pick_one: numbered multiple-choice prompt ────────────────
# Usage: pick_one "Prompt text" "choice 1" "choice 2" ...
# Echoes the chosen value to stdout. Exits 1 on EOF.
pick_one() {
local prompt="$1"; shift
local -a choices=("$@")
local i n
echo "" >&2
echo "$prompt" >&2
for ((i=0; i<${#choices[@]}; i++)); do
printf " %d) %s\n" "$((i+1))" "${choices[$i]}" >&2
done
while true; do
printf "Choice [1-%d]: " "${#choices[@]}" >&2
if ! read -r n; then
echo "" >&2
return 1
fi
if [[ "$n" =~ ^[0-9]+$ ]] && (( n >= 1 && n <= ${#choices[@]} )); then
printf '%s\n' "${choices[$((n-1))]}"
return 0
fi
echo " Invalid. Enter a number from 1 to ${#choices[@]}." >&2
done
}
# ── parse_config_file: source whitelisted KEY=VALUE config ───
# Lines starting with # are comments. Only known keys are exported.
parse_config_file() {
local f="$1"
[[ -f "$f" ]] || return 0
local line key val
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line%%#*}"
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
[[ -z "$line" ]] && continue
[[ "$line" != *=* ]] && continue
key="${line%%=*}"
val="${line#*=}"
val="${val#\"}"; val="${val%\"}"
val="${val#\'}"; val="${val%\'}"
case "$key" in
LOOP_CLI|CODEX_MODEL|LOOP_GEMINI_MODEL|LOOP_REQUIRE_BRANCH_PREFIX|LOOP_RISK_MODE|LOOP_BACKLOG_SOURCE)
export "$key=$val"
;;
esac
done < "$f"
}
# ── run_config_wizard: interactive multiple-choice setup ─────
# Writes .loop-agent/config.env. Skipped on non-TTY (CI).
run_config_wizard() {
local cfg="$1"
local cfg_dir
cfg_dir="$(dirname "$cfg")"
mkdir -p "$cfg_dir"
echo "" >&2
echo -e "${BOLD}${CYAN}First-time setup for $(basename "$PROJECT_DIR")${RESET}" >&2
echo -e "${GRAY}Saved to .loop-agent/config.env — edit anytime to change.${RESET}" >&2
# 1) CLI — auto-pick if only one installed
local cli=""
local has_codex=0 has_gemini=0
command -v codex >/dev/null 2>&1 && has_codex=1
command -v gemini >/dev/null 2>&1 && has_gemini=1
if (( has_codex == 1 && has_gemini == 1 )); then
cli="$(pick_one "AI CLI to use:" "codex" "gemini")" || return 1
elif (( has_codex == 1 )); then
cli="codex"
info "AI CLI: codex (auto-detected, only one installed)" >&2
elif (( has_gemini == 1 )); then
cli="gemini"
info "AI CLI: gemini (auto-detected, only one installed)" >&2
else
cli="$(pick_one "AI CLI to use (neither detected on PATH — install before running):" "codex" "gemini")" || return 1
fi
# 2) Model — fixed list + Other escape
local model=""
local -a model_options
case "$cli" in
codex)
model_options=(
"gpt-5.5"
"gpt-5.4"
"gpt-5.4-mini"
"gpt-5.3-codex"
"gpt-5.3-codex-spark"
"gpt-5.2"
"Other (type manually)"
)
;;
gemini)
model_options=(
"gemini-3.1-pro-preview"
"gemini-3.1-pro-preview-customtools"
"gemini-3-flash-preview"
"gemini-3.1-flash-lite-preview"
"gemini-2.5-pro"
"gemini-2.5-flash"
"Other (type manually)"
)
;;
esac
model="$(pick_one "Model ID for ${cli}:" "${model_options[@]}")" || return 1
if [[ "$model" == "Other (type manually)" ]]; then
while [[ -z "$model" || "$model" == "Other (type manually)" ]]; do
printf "Model ID: " >&2
read -r model || return 1
done
fi
# 3) Branch prefix
local prefix_choice
prefix_choice="$(pick_one "Required git branch prefix (refuse to run on other branches):" \
"loop/ (recommended)" \
"(none — allow any branch)" \
"Other (type manually)")" || return 1
local prefix=""
case "$prefix_choice" in
"loop/ (recommended)") prefix="loop/" ;;
"(none — allow any branch)") prefix="" ;;
"Other (type manually)")
printf "Branch prefix (e.g. work/, feat/, leave empty to skip): " >&2
read -r prefix || return 1
;;
esac
# 4) Backlog source — let users skip Setup Agent if they bring their own
local backlog_choice backlog_source
backlog_choice="$(pick_one "Backlog source:" \
"Generate from planning docs (default — Setup Agent reads SPEC.md etc.)" \
"I'll provide .loop-agent/backlog.md myself (skip Setup Agent)")" || return 1
case "$backlog_choice" in
"Generate"*) backlog_source="generated" ;;
"I'll provide"*) backlog_source="user" ;;
*) backlog_source="generated" ;;
esac
# Write config.env
{
echo "# LoopDex per-project config — generated by setup wizard"
echo "# Edit values or delete this file to re-run the wizard."
echo ""
echo "LOOP_CLI=$cli"
case "$cli" in
codex) echo "CODEX_MODEL=$model" ;;
gemini) echo "LOOP_GEMINI_MODEL=$model" ;;
esac
[[ -n "$prefix" ]] && echo "LOOP_REQUIRE_BRANCH_PREFIX=$prefix"
echo "LOOP_BACKLOG_SOURCE=$backlog_source"
} > "$cfg"
ok "Saved $cfg" >&2
echo "" >&2
}
# ── load_or_init_config: load config.env, run wizard if missing ─
# Run mode + TTY + missing config → wizard.
# Init mode + TTY + missing config → wizard.
# Non-TTY or status/doctor → silently skip wizard, just load if file exists.
load_or_init_config() {
local cfg="$STATE_DIR/config.env"
if [[ -f "$cfg" ]]; then
parse_config_file "$cfg"
return 0
fi
case "$LOOP_MODE" in
init|run)
if [[ -t 0 ]] && [[ -t 1 ]]; then
run_config_wizard "$cfg" || { warn "Setup cancelled."; return 0; }
parse_config_file "$cfg"
fi
;;
esac
}
phase() { echo -e "\n${BOLD}${CYAN}── $* ──${RESET}"; }
banner() { echo -e "\n${BOLD}${CYAN}╔══════════════════════════════════════╗${RESET}"
echo -e "${BOLD}${CYAN}║ $*${RESET}"
echo -e "${BOLD}${CYAN}╚══════════════════════════════════════╝${RESET}"; }
# ── RESULTS array ─────────────────────────────────────────────
RESULTS=()
LOOP=0 # Loop number. Initial value to prevent undefined variable in prerequisites/Ctrl+C
add_result() {
RESULTS+=("$1")
# Immediately update window after writing to progress.txt
build_progress_window 2>/dev/null || true
}
print_results() {
echo -e "\n${BOLD}=== Summary ===${RESET}"
for r in "${RESULTS[@]}"; do
echo -e " $r"
done
echo ""
if [[ -n "${PROJECT_DIR:-}" ]]; then
echo -e " State files: ${GRAY}${PROJECT_DIR}/.loop-agent/${RESET}"
echo -e " Report: ${CYAN}${PROJECT_DIR}/.loop-agent/report.md${RESET}"
fi
echo ""
}
# ── Ctrl+C handler ────────────────────────────────────────────
cleanup() {
echo ""
# LOOP=0 means interrupted during prerequisite checks
if [[ "$LOOP" -eq 0 ]]; then
add_result "Before start: INTERRUPTED"
else
add_result "Loop ${LOOP}: INTERRUPTED"
fi
# Kill any running agent process
if [[ -n "${CODEX_PID:-}" ]]; then
kill "$CODEX_PID" 2>/dev/null || true
fi
# Restore protected state files that were in progress at interrupt time
# - If PROTECTED_BACKUPS is empty, no-op (before snapshot or already restored)
# - If not empty, restore from .protected and clean up → preserves next-run baseline
if declare -f restore_state_files_if_modified >/dev/null 2>&1; then
restore_state_files_if_modified "Interrupted (loop ${LOOP})" 2>/dev/null || true
fi
if declare -f release_project_lock >/dev/null 2>&1; then
release_project_lock 2>/dev/null || true
fi
print_results
echo -e "${YELLOW}Interrupted.${RESET}"
echo ""
echo "Temporary files from the current loop (plan.md, impl_summary.md, etc.)"
echo "may remain in .loop-agent/."
echo "These files are not carried over between loops and will be"
echo "re-initialized in Phase 0 on the next run."
echo ""
echo "Planner reads both progress.txt and the current project file state."
echo "If Implementer modified files before the interrupt,"
echo "progress.txt and the project file state may be out of sync."
echo "In that case, Planner prioritizes the actual file state."
exit 130
}
trap cleanup INT TERM
# ── Argument check ────────────────────────────────────────────
usage() {
echo "Usage:"
echo " ./loop.sh <iterations> <project folder> [cli]"
echo " ./loop.sh run --iterations <n> --project <dir> [--cli codex|gemini]"
echo " ./loop.sh init --project <dir> [--cli codex|gemini]"
echo " ./loop.sh status --project <dir>"
echo " ./loop.sh doctor --project <dir>"
echo " cli: codex (default), gemini"
}
LOOP_MODE="run"
LOOP_EXPLICIT_SUBCOMMAND=0
MAX_LOOPS=""
MAX_LOOPS_FROM_FLAG=0
PROJECT_DIR=""
LOOP_CLI=""
LOOP_CLI_FROM_FLAG=0
if [[ $# -eq 0 ]]; then
err "Invalid arguments."
usage
exit 1
fi
case "$1" in
run)
LOOP_MODE="run"
LOOP_EXPLICIT_SUBCOMMAND=1
shift
while [[ $# -gt 0 ]]; do
case "$1" in
--iterations|-i)
if [[ $# -lt 2 ]]; then
err "Missing value for --iterations."
exit 1
fi
MAX_LOOPS="$2"
MAX_LOOPS_FROM_FLAG=1
shift 2
;;
--project)
if [[ $# -lt 2 ]]; then
err "Missing value for --project."
exit 1
fi
PROJECT_DIR="$2"
shift 2
;;
--cli)
if [[ $# -lt 2 ]]; then
err "Missing value for --cli."
exit 1
fi
LOOP_CLI="$2"
LOOP_CLI_FROM_FLAG=1
shift 2
;;
*)
err "Unknown run option: $1"
usage
exit 1
;;
esac
done
if [[ -z "$PROJECT_DIR" ]]; then
err "Missing project."
exit 1
fi
;;
init)
LOOP_MODE="init"
LOOP_EXPLICIT_SUBCOMMAND=1
shift
while [[ $# -gt 0 ]]; do
case "$1" in
--project)
if [[ $# -lt 2 ]]; then
err "Missing value for --project."
exit 1
fi
PROJECT_DIR="$2"
shift 2
;;
--cli)
if [[ $# -lt 2 ]]; then
err "Missing value for --cli."
exit 1
fi
LOOP_CLI="$2"
LOOP_CLI_FROM_FLAG=1
shift 2
;;
*)
err "Unknown init option: $1"
usage
exit 1
;;
esac
done
if [[ -z "$PROJECT_DIR" ]]; then
err "Missing project."
exit 1
fi
;;
status|doctor)
LOOP_MODE="$1"
shift
while [[ $# -gt 0 ]]; do
case "$1" in
--project)
if [[ $# -lt 2 ]]; then
err "Missing value for --project."
exit 1
fi
PROJECT_DIR="$2"
shift 2
;;
--cli)
if [[ $# -lt 2 ]]; then
err "Missing value for --cli."
exit 1
fi
LOOP_CLI="$2"
LOOP_CLI_FROM_FLAG=1
shift 2
;;
*)
err "Unknown ${LOOP_MODE} option: $1"
usage
exit 1
;;
esac
done
if [[ -z "$PROJECT_DIR" ]]; then
err "Missing project."
exit 1
fi
if [[ ! -d "$PROJECT_DIR" ]]; then
err "Project folder not found: $PROJECT_DIR"
exit 1
fi
PROJECT_DIR="$(cd "$PROJECT_DIR" && pwd)"
STATE_DIR_STATUS="$PROJECT_DIR/.loop-agent"
# Load config so doctor/status can report stored values.
# Wizard does NOT run for status/doctor — only init/run trigger it.
DOCTOR_FLAG_CLI=""
[[ "$LOOP_CLI_FROM_FLAG" == "1" ]] && DOCTOR_FLAG_CLI="$LOOP_CLI"
if [[ -f "$STATE_DIR_STATUS/config.env" ]]; then
parse_config_file "$STATE_DIR_STATUS/config.env"
fi
# Precedence: CLI flag > user env > config > default
if [[ -n "$DOCTOR_FLAG_CLI" ]]; then
LOOP_CLI="$DOCTOR_FLAG_CLI"
elif [[ -n "$LOOP_USER_CLI_ENV" ]]; then
LOOP_CLI="$LOOP_USER_CLI_ENV"
fi
[[ -n "$LOOP_USER_CODEX_MODEL" ]] && CODEX_MODEL="$LOOP_USER_CODEX_MODEL"
[[ -n "$LOOP_USER_GEMINI_MODEL" ]] && LOOP_GEMINI_MODEL="$LOOP_USER_GEMINI_MODEL"
[[ -n "$LOOP_USER_BRANCH_PREFIX" ]] && LOOP_REQUIRE_BRANCH_PREFIX="$LOOP_USER_BRANCH_PREFIX"
LOOP_CLI="${LOOP_CLI:-codex}"
CODEX_MODEL="${CODEX_MODEL:-gpt-5.5}"
LOOP_GEMINI_MODEL="${LOOP_GEMINI_MODEL:-gemini-3.1-pro-preview}"
# Re-sync the cli_adapters cache (GEMINI_MODEL was set at sourcing time before config load).
GEMINI_MODEL="$LOOP_GEMINI_MODEL"
if [[ "$LOOP_MODE" == "status" ]]; then
STATUS_BACKLOG="$STATE_DIR_STATUS/backlog.md"
if [[ -n "${PYTHON:-}" ]]; then
STATUS_PYTHON=("$PYTHON")
elif STATUS_PYTHON_PATH="$(command -v python3 2>/dev/null)" && [[ "$STATUS_PYTHON_PATH" != *"WindowsApps"* ]]; then
STATUS_PYTHON=("python3")
elif STATUS_PYTHON_PATH="$(command -v python 2>/dev/null)" && [[ "$STATUS_PYTHON_PATH" != *"WindowsApps"* ]]; then
STATUS_PYTHON=("python")
else
err "python not found."
exit 1
fi
echo "loop-agent status"
echo "Project: $PROJECT_DIR"
if [[ ! -f "$STATUS_BACKLOG" ]]; then
err "backlog.md not found: $STATUS_BACKLOG"
exit 1
fi
if ! STATUS_JSON="$(PYTHONUTF8=1 PYTHONIOENCODING=utf-8 "${STATUS_PYTHON[@]}" "$SCRIPT_DIR/backlog_manager.py" status "$STATUS_BACKLOG")"; then
err "Could not read backlog status."
exit 1
fi
STATUS_JSON="$STATUS_JSON" STATUS_EVENTS="$STATE_DIR_STATUS/events.jsonl" \
PYTHONUTF8=1 PYTHONIOENCODING=utf-8 "${STATUS_PYTHON[@]}" - <<'PY'
import json
import os
status = json.loads(os.environ["STATUS_JSON"])
print(f"Total tasks: {status.get('total', 0)}")
print(f"Done: {status.get('done', 0)}")
print(f"Pending: {status.get('pending', 0)}")
print(f"Blocked: {status.get('blocked', 0)}")
next_task = status.get("next_task")
if next_task:
print(f"Next task: {next_task.get('id', '')} - {next_task.get('name', '')}")
else:
print("Next task: none")
last_decision = None
events_path = os.environ["STATUS_EVENTS"]
if os.path.exists(events_path):
with open(events_path, "r", encoding="utf-8", errors="replace") as events_file:
for line in events_file:
line = line.strip()
if not line:
continue
try:
event = json.loads(line)
except json.JSONDecodeError:
continue
if event.get("event") == "decision" or event.get("type") == "decision":
last_decision = event
if last_decision:
outcome = last_decision.get("outcome") or last_decision.get("status") or "unknown"
details = []
for key in ("task_id", "stage", "reason"):
value = last_decision.get(key)
if value:
details.append(f"{key}={value}")
if details:
print(f"Last decision: {outcome} ({', '.join(details)})")
else:
print(f"Last decision: {outcome}")
else:
print("Last decision: none")
PY
else
if [[ "$LOOP_CLI" != "codex" && "$LOOP_CLI" != "gemini" ]]; then
err "Invalid CLI value: $LOOP_CLI (supported: codex, gemini)"
exit 1
fi
DOCTOR_BACKLOG="$STATE_DIR_STATUS/backlog.md"
DOCTOR_PYTHON=()
if [[ -n "${PYTHON:-}" ]]; then
DOCTOR_PYTHON=("$PYTHON")
elif DOCTOR_PYTHON_PATH="$(command -v python3 2>/dev/null)" && [[ "$DOCTOR_PYTHON_PATH" != *"WindowsApps"* ]]; then
DOCTOR_PYTHON=("python3")
elif DOCTOR_PYTHON_PATH="$(command -v python 2>/dev/null)" && [[ "$DOCTOR_PYTHON_PATH" != *"WindowsApps"* ]]; then
DOCTOR_PYTHON=("python")
fi
echo "loop-agent doctor"
echo "Project: $PROJECT_DIR"
if command -v git >/dev/null 2>&1; then
echo "Git: available ($(git --version 2>/dev/null || echo "version unknown"))"
else
echo "Git: missing"
fi
if [[ ${#DOCTOR_PYTHON[@]} -gt 0 ]]; then
echo "Python: available ($("${DOCTOR_PYTHON[@]}" --version 2>&1 || echo "version unknown"))"
else
echo "Python: missing"
fi
if [[ -n "${BASH_VERSION:-}" ]]; then
echo "Bash: available ($BASH_VERSION)"
elif command -v bash >/dev/null 2>&1; then
echo "Bash: available ($(bash --version 2>/dev/null | head -n 1 || echo "version unknown"))"
else
echo "Bash: missing"
fi
if command -v "$LOOP_CLI" >/dev/null 2>&1; then
echo "AI CLI ($LOOP_CLI): available"
else
echo "AI CLI ($LOOP_CLI): missing"
fi
case "$LOOP_CLI" in
codex)
if is_placeholder_model "${CODEX_MODEL:-}" "${LOOP_PLACEHOLDER_CODEX_MODELS[@]}"; then
echo "Model: PLACEHOLDER (CODEX_MODEL='$CODEX_MODEL' — override with a real ID)"
else
echo "Model: $CODEX_MODEL"
fi
;;
gemini)
gem_cur="${GEMINI_MODEL:-${LOOP_GEMINI_MODEL:-}}"
if is_placeholder_model "$gem_cur" "${LOOP_PLACEHOLDER_GEMINI_MODELS[@]}"; then
echo "Model: PLACEHOLDER (LOOP_GEMINI_MODEL='$gem_cur' — override with a real ID)"
else
echo "Model: $gem_cur"
fi
;;
esac
if command -v git >/dev/null 2>&1 && git -C "$PROJECT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
DOCTOR_BRANCH="$(git -C "$PROJECT_DIR" rev-parse --abbrev-ref HEAD 2>/dev/null || echo unknown)"
if [[ "$DOCTOR_BRANCH" =~ ^(main|master|develop|trunk)$ ]] && [[ -z "${LOOP_REQUIRE_BRANCH_PREFIX:-}" ]]; then
echo "Branch: $DOCTOR_BRANCH (warning: 'run' will commit directly here; consider LOOP_REQUIRE_BRANCH_PREFIX)"
else
echo "Branch: $DOCTOR_BRANCH"
fi
fi
if [[ -f "$DOCTOR_BACKLOG" ]]; then
echo "Backlog: present"
if [[ ${#DOCTOR_PYTHON[@]} -gt 0 ]]; then
if DOCTOR_LINT_OUTPUT="$(PYTHONUTF8=1 PYTHONIOENCODING=utf-8 "${DOCTOR_PYTHON[@]}" "$SCRIPT_DIR/backlog_manager.py" lint "$DOCTOR_BACKLOG" 2>&1)"; then
echo "Backlog lint: passed"
else
echo "Backlog lint: failed"
if [[ -n "$DOCTOR_LINT_OUTPUT" ]]; then
echo "$DOCTOR_LINT_OUTPUT"
fi
fi
else
echo "Backlog lint: skipped (python missing)"
fi
else
echo "Backlog: missing"
echo "Backlog lint: skipped (backlog missing)"
fi
if command -v git >/dev/null 2>&1 && git -C "$PROJECT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
if DOCTOR_GIT_STATUS="$(git -C "$PROJECT_DIR" status --porcelain=v1 --untracked-files=all 2>&1)"; then
if [[ -z "$DOCTOR_GIT_STATUS" ]]; then
echo "Clean tree: clean"
else
echo "Clean tree: dirty"
fi
else
echo "Clean tree: error"
echo "$DOCTOR_GIT_STATUS"
fi
else
echo "Clean tree: not a git work tree"
fi
fi
exit 0
;;
*)
if [[ "$1" =~ ^[0-9]+$ ]]; then
if [[ $# -lt 2 ]] || [[ $# -gt 3 ]]; then
err "Invalid arguments."
usage
exit 1
fi
LOOP_MODE="run"
MAX_LOOPS="$1"
MAX_LOOPS_FROM_FLAG=1
PROJECT_DIR="$2"
if [[ -n "${3:-}" ]]; then
LOOP_CLI="$3"
LOOP_CLI_FROM_FLAG=1
fi
else
err "Invalid subcommand: $1"
usage
exit 1
fi
;;
esac
# LOOP_CLI / MAX_LOOPS validations are deferred until after load_or_init_config
# so config.env values + interactive prompts can fill in missing pieces.
if [[ "$LOOP_MODE" == "run" ]] && ! [[ "$LOOP_VERIFY_TIMEOUT" =~ ^[1-9][0-9]*$ ]]; then
err "LOOP_VERIFY_TIMEOUT must be a positive integer: $LOOP_VERIFY_TIMEOUT"
exit 1
fi
if [[ "$LOOP_MODE" == "run" ]] && ! [[ "$LOOP_MAX_ATTEMPTS" =~ ^[1-9][0-9]*$ ]]; then
err "LOOP_MAX_ATTEMPTS must be a positive integer: $LOOP_MAX_ATTEMPTS"
exit 1
fi
if [[ "$LOOP_MODE" == "run" ]] && ! [[ "$LOOP_EVIDENCE_KEEP_RUNS" =~ ^[0-9]+$ ]]; then
err "LOOP_EVIDENCE_KEEP_RUNS must be a non-negative integer (0 disables retention): $LOOP_EVIDENCE_KEEP_RUNS"
exit 1
fi
if [[ "$LOOP_MODE" == "run" ]]; then
case "$LOOP_RISK_MODE" in
safe|unattended) ;;
*)
err "Invalid LOOP_RISK_MODE: $LOOP_RISK_MODE (supported: safe, unattended)"
exit 1
;;
esac
fi
RUN_MODE_NONINTERACTIVE=0
if [[ "$LOOP_MODE" == "run" ]] && [[ "$LOOP_EXPLICIT_SUBCOMMAND" == "1" ]]; then
RUN_MODE_NONINTERACTIVE=1
fi
CLEAN_TREE_PREFLIGHT_STATUS="not checked"
BRANCH_PREFIX_PREFLIGHT_STATUS="not checked"
BACKLOG_LINT_STATUS="not checked"
clean_tree_preflight_path_allowed() {
local path="$1"
path="${path#./}"
case "$path" in
.loop-agent|\
.loop-agent/backlog.md|\
.loop-agent/backlog_archive.md|\
.loop-agent/current_task.md|\
.loop-agent/plan.md|\
.loop-agent/plan_critique.md|\
.loop-agent/impl_summary.md|\
.loop-agent/impl_critique.md|\
.loop-agent/report.md|\
.loop-agent/events.jsonl|\
.loop-agent/progress.txt|\
.loop-agent/progress_window.md|\
.loop-agent/file_index_before.md|\
.loop-agent/file_index_after.md|\
.loop-agent/current_transaction.json|\
.loop-agent/codex.log|\
.loop-agent/setup_agent_rendered.md|\
.loop-agent/setup_critic_rendered.md|\
.loop-agent/setup_critic.md|\
.loop-agent/setup_critique.md|\
.loop-agent/backlog_draft.md|\
.loop-agent/loop.lock|\
.loop-agent/loop.lock.d|\
.loop-agent/loop.lock.d/*|\
.loop-agent/evidence|\
.loop-agent/evidence/*|\
.loop-agent/proposals|\
.loop-agent/proposals/*|\
.loop-agent/*.protected|\
.loop-agent/.bm_*.tmp)
return 0
;;
esac
return 1
}
clean_tree_preflight() {
if [[ "$RUN_MODE_NONINTERACTIVE" != "1" ]]; then
CLEAN_TREE_PREFLIGHT_STATUS="not required"
return 0
fi
if [[ "${LOOP_ALLOW_DIRTY:-}" == "1" ]]; then
CLEAN_TREE_PREFLIGHT_STATUS="bypassed (LOOP_ALLOW_DIRTY=1)"
warn "LOOP_ALLOW_DIRTY=1 set; dirty tree protection is bypassed."
return 0
fi
if ! git -C "$PROJECT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
CLEAN_TREE_PREFLIGHT_STATUS="not a git work tree"
return 0
fi
local raw_status
raw_status="$(mktemp)"
if ! git -C "$PROJECT_DIR" status --porcelain=v1 -z --untracked-files=all > "$raw_status"; then
rm -f "$raw_status"
CLEAN_TREE_PREFLIGHT_STATUS="error"
err "Could not inspect git status for clean-tree preflight."
return 1
fi
local record status path path2 x y
local -a dirty_paths=()
while IFS= read -r -d '' record; do
[[ -z "$record" ]] && continue
status="${record:0:2}"
path="${record:3}"
x="${status:0:1}"
y="${status:1:1}"
if [[ "$x" == "R" || "$y" == "R" || "$x" == "C" || "$y" == "C" ]]; then
path2=""
IFS= read -r -d '' path2 || true
path2="${path2#./}"
if [[ -n "$path2" ]] && ! clean_tree_preflight_path_allowed "$path2"; then
dirty_paths+=("$path2")
fi
fi
path="${path#./}"
if [[ -n "$path" ]] && ! clean_tree_preflight_path_allowed "$path"; then
dirty_paths+=("$path")
fi
done < "$raw_status"
rm -f "$raw_status"
if [[ ${#dirty_paths[@]} -eq 0 ]]; then
CLEAN_TREE_PREFLIGHT_STATUS="clean"
return 0
fi
CLEAN_TREE_PREFLIGHT_STATUS="dirty"
err "run mode requires a clean working tree."
echo "Dirty paths:" >&2
for path in "${dirty_paths[@]}"; do
echo " - $path" >&2
done
echo "" >&2
echo "Commit, stash, or revert these changes before running loop-agent." >&2
echo "To bypass this protection explicitly, rerun with LOOP_ALLOW_DIRTY=1." >&2
return 1
}
branch_prefix_preflight() {
if [[ "$RUN_MODE_NONINTERACTIVE" != "1" ]]; then
BRANCH_PREFIX_PREFLIGHT_STATUS="not required"
return 0
fi
if [[ -z "${LOOP_REQUIRE_BRANCH_PREFIX:-}" ]]; then
BRANCH_PREFIX_PREFLIGHT_STATUS="not required"
return 0
fi
if ! git -C "$PROJECT_DIR" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
BRANCH_PREFIX_PREFLIGHT_STATUS="not a git work tree"
return 0
fi
local current_branch
current_branch="$(git -C "$PROJECT_DIR" branch --show-current 2>/dev/null || true)"
if [[ -z "$current_branch" ]]; then
BRANCH_PREFIX_PREFLIGHT_STATUS="failed (detached HEAD)"
err "run mode requires branch prefix: $LOOP_REQUIRE_BRANCH_PREFIX"
echo "Current branch: detached HEAD" >&2
echo "Required prefix: $LOOP_REQUIRE_BRANCH_PREFIX" >&2
return 1
fi
if [[ "$current_branch" != "$LOOP_REQUIRE_BRANCH_PREFIX"* ]]; then
BRANCH_PREFIX_PREFLIGHT_STATUS="failed ($current_branch)"
err "run mode requires branch prefix: $LOOP_REQUIRE_BRANCH_PREFIX"
echo "Current branch: $current_branch" >&2
echo "Required prefix: $LOOP_REQUIRE_BRANCH_PREFIX" >&2
return 1
fi
BRANCH_PREFIX_PREFLIGHT_STATUS="passed ($current_branch)"
return 0
}
print_safety_summary_banner() {
[[ "$LOOP_MODE" == "run" ]] || return 0
banner "Run Safety Summary"
echo -e " Project path: ${BOLD}$PROJECT_DIR${RESET}"
echo -e " CLI: ${CYAN}$LOOP_CLI${RESET}"
echo -e " Risk mode: $LOOP_RISK_MODE"
echo -e " Clean tree: $CLEAN_TREE_PREFLIGHT_STATUS"
echo -e " Branch requirement: $BRANCH_PREFIX_PREFLIGHT_STATUS"
echo -e " Backlog lint: $BACKLOG_LINT_STATUS"
echo ""
}
# ── Windows PATH merge (fix for pnpm etc. not found in Git Bash) ──
# Git Bash may omit parts of the Windows PATH
# Merge Windows PATH into Git Bash PATH via cmd //c path
if [[ -n "${WINDIR:-}" ]] || [[ "$(uname -s)" == MINGW* ]] || [[ "$(uname -s)" == MSYS* ]]; then
# Add npm global path directly (instead of parsing cmd PATH — avoids encoding issues)
NPM_PREFIX="$(npm config get prefix 2>/dev/null || true)"
if [[ -n "$NPM_PREFIX" ]]; then
NPM_UNIX="$(cygpath -u "$NPM_PREFIX" 2>/dev/null || echo "")"
if [[ -n "$NPM_UNIX" ]] && [[ ":$PATH:" != *":$NPM_UNIX:"* ]]; then
export PATH="$PATH:$NPM_UNIX"
fi
fi
# Also add AppData/Roaming/npm (for pnpm etc.)
if [[ -n "${APPDATA:-}" ]]; then
APPDATA_NPM="$(cygpath -u "$APPDATA/npm" 2>/dev/null || echo "")"
if [[ -n "$APPDATA_NPM" ]] && [[ ":$PATH:" != *":$APPDATA_NPM:"* ]]; then
export PATH="$PATH:$APPDATA_NPM"
fi
fi
fi
# ── Prerequisites ─────────────────────────────────────────────
# Project folder
if [[ ! -d "$PROJECT_DIR" ]]; then
add_result "Before start: ERROR (prerequisites failed)"
print_results
err "Project folder not found: $PROJECT_DIR"
exit 1
fi
PROJECT_DIR="$(cd "$PROJECT_DIR" && pwd)"
STATE_DIR="$PROJECT_DIR/.loop-agent"
# ── Per-project config: load .loop-agent/config.env, run wizard if missing.
# Precedence: CLI flag > user-exported env > config.env > built-in default.
MAIN_FLAG_CLI=""
[[ "$LOOP_CLI_FROM_FLAG" == "1" ]] && MAIN_FLAG_CLI="$LOOP_CLI"
load_or_init_config
# Precedence restore (config may have overwritten LOOP_CLI; CLI flag must win)
if [[ -n "$MAIN_FLAG_CLI" ]]; then
LOOP_CLI="$MAIN_FLAG_CLI"
elif [[ -n "$LOOP_USER_CLI_ENV" ]]; then
LOOP_CLI="$LOOP_USER_CLI_ENV"
fi
[[ -n "$LOOP_USER_CODEX_MODEL" ]] && CODEX_MODEL="$LOOP_USER_CODEX_MODEL"
[[ -n "$LOOP_USER_GEMINI_MODEL" ]] && LOOP_GEMINI_MODEL="$LOOP_USER_GEMINI_MODEL"
[[ -n "$LOOP_USER_BRANCH_PREFIX" ]] && LOOP_REQUIRE_BRANCH_PREFIX="$LOOP_USER_BRANCH_PREFIX"
# Apply built-in fallback defaults for anything still empty after config + env
LOOP_CLI="${LOOP_CLI:-codex}"
CODEX_MODEL="${CODEX_MODEL:-gpt-5.5}"
LOOP_GEMINI_MODEL="${LOOP_GEMINI_MODEL:-gemini-3.1-pro-preview}"
# Re-sync the cli_adapters cache (GEMINI_MODEL was set at sourcing time before config load).
GEMINI_MODEL="$LOOP_GEMINI_MODEL"
# Validate LOOP_CLI now that all sources have contributed
case "$LOOP_CLI" in
codex|gemini) ;;
*)
err "Invalid CLI value: $LOOP_CLI (supported: codex, gemini)"
exit 1
;;
esac
# Iterations: prompt interactively if not given on CLI in run mode + TTY.
# Non-TTY (CI) without --iterations → error.
if [[ "$LOOP_MODE" == "run" ]] && [[ -z "$MAX_LOOPS" ]]; then
if [[ -t 0 ]] && [[ -t 1 ]]; then
while true; do
printf "Iterations to run: " >&2
read -r MAX_LOOPS || { err "Iterations required for run mode."; exit 1; }
[[ "$MAX_LOOPS" =~ ^[1-9][0-9]*$ ]] && break
echo " Must be a positive integer." >&2
done
else
err "Iterations required for run mode (use --iterations N or -i N)."
exit 1
fi
fi
if [[ "$LOOP_MODE" == "run" ]] && ! [[ "$MAX_LOOPS" =~ ^[1-9][0-9]*$ ]]; then
err "Iterations must be a positive integer: $MAX_LOOPS"
exit 1
fi
if ! clean_tree_preflight; then
exit 1
fi
if ! branch_prefix_preflight; then
exit 1
fi
if [[ "$RUN_MODE_NONINTERACTIVE" == "1" ]] && [[ ! -f "$PROJECT_DIR/.loop-agent/backlog.md" ]]; then
err "run mode requires .loop-agent/backlog.md. Run ./loop.sh init first."
exit 1
fi
# envsubst (CLI-agnostic)
if ! command -v envsubst &>/dev/null; then
add_result "Before start: ERROR (prerequisites failed)"
print_results
err "envsubst is not installed."
echo " In Git Bash, the gettext package or a package that includes envsubst is required."
echo " Alternatively, replace the render function in loop.sh with a Python-based substitution."
exit 1
fi
# CLI-specific prerequisites (install + auth)