-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquantum-loop.sh
More file actions
1439 lines (1313 loc) · 55 KB
/
quantum-loop.sh
File metadata and controls
1439 lines (1313 loc) · 55 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
set -euo pipefail
# =============================================================================
# quantum-loop.sh -- PLUGIN-LEVEL autonomous development loop.
#
# THIS SCRIPT IS FOR THE QUANTUM-LOOP PLUGIN REPO ITSELF.
# It requires lib/*.sh modules and jq. It operates at the STORY level
# (one story per agent invocation) and uses CLAUDE.md as the agent prompt.
#
# FOR USER PROJECTS: Use templates/quantum-loop.sh instead.
# That script is self-contained (no lib/ dependency), uses node for JSON,
# and operates at the TASK level. Download it via:
# curl -sO https://raw.githubusercontent.com/andyzengmath/quantum-loop/main/templates/quantum-loop.sh
#
# Features: DAG-based story selection, two-stage review gates,
# structured error recovery, parallel execution via worktree agents.
#
# Usage:
# ./quantum-loop.sh [OPTIONS]
#
# Options:
# --audit Print §6 measurement metrics and exit (read-only).
# --max-iterations N Maximum iterations before stopping (default: 20)
# --max-retries N Max retry attempts per story (default: 3)
# --tool TOOL AI tool to use (default: "claude"). Any runner in runners/*.json.
# --parallel Enable parallel execution of independent stories
# --max-parallel N Maximum concurrent agents in parallel mode (default: 4)
# --help Show this help message
#
# Prerequisites:
# - quantum.json must exist in the current directory (run /quantum-loop:plan first)
# - jq must be installed
# - The selected runner CLI must be installed (see runners/*.json)
# =============================================================================
# Defaults
MAX_ITERATIONS=20
MAX_RETRIES=3
TOOL="claude"
PARALLEL_MODE=false
MAX_PARALLEL=4
STALE_TIMEOUT=20
QL_CRITIC="${QL_CRITIC:-auto}" # P5.A2 / US-002 default
QL_PLANNER="${QL_PLANNER:-auto}" # P5.B1 / US-009 default
QL_EXECUTOR="${QL_EXECUTOR:-auto}" # P5.B1 / US-009 default
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# =============================================================================
# P5.B1 / US-009 — Per-role provider routing (--planner / --critic / --executor)
# Subsumes US-002's --critic flag; adds --planner and --executor with the
# same availability-check + fallback semantics. Resolved choices are
# snapshotted to quantum.json.routing at run start for replay determinism.
# =============================================================================
# parse_role_arg ROLE VALUE
# Validates VALUE against the per-role enum and runs availability check.
# Roles: planner | critic | executor.
# Enums:
# planner: auto | claude | codex | gemini
# critic: auto | claude | codex | gemini | none (critic may be disabled)
# executor: auto | claude | codex | gemini
# On absence of codex/gemini, emits WARN to stderr and rewrites to 'claude'.
parse_role_arg() {
local role="${1:-}"
local value="${2:-}"
case "$role" in
planner|critic|executor) : ;;
*) printf "Error: parse_role_arg: unknown role %q\n" "$role" >&2; return 1 ;;
esac
case "$value" in
auto|claude|codex|gemini) : ;;
none)
if [[ "$role" != "critic" ]]; then
printf "Error: --%s=none not supported (only --critic accepts 'none')\n" "$role" >&2
return 1
fi
;;
*)
local extra=""
[[ "$role" == "critic" ]] && extra='|none'
printf "Error: --%s value must be auto|claude|codex|gemini%s (got [%s])\n" \
"$role" "$extra" "$value" >&2
return 1
;;
esac
# Availability check for non-claude/auto/none providers
case "$value" in
codex|gemini)
if ! command -v "$value" >/dev/null 2>&1; then
printf "WARN: per-role routing: %s provider %s not available, falling back to claude\n" "$role" "$value" >&2
value="claude"
fi
;;
esac
printf '%s' "$value"
}
# =============================================================================
# P5.A2 / US-002 — --critic=auto|codex|gemini|claude|none flag with
# availability detection at runtime. 'auto' triggers existing tier-driven
# dispatch (lib/deep-review.sh); 'none' disables critic entirely; explicit
# values override. When chosen provider's CLI binary is not on \$PATH, log
# warning and degrade to 'none' rather than failing the review gate.
# Note: parse_role_arg above is the unified entry point; parse_critic_arg
# remains for backward compatibility with US-002 callers.
# =============================================================================
# parse_critic_arg VALUE
# Validates VALUE against the enum (auto|codex|gemini|claude|none) and runs
# availability check on codex/gemini. On absence, emits WARN to stderr and
# rewrites the choice to 'none'. Echoes the resolved value on stdout.
# Returns 0 on success, 1 on invalid enum value (caller should exit).
parse_critic_arg() {
local value="${1:-}"
case "$value" in
auto|codex|gemini|claude|none) : ;;
*)
printf "Error: --critic value must be one of auto|codex|gemini|claude|none (got [%s])\n" "$value" >&2
return 1
;;
esac
# Availability check for external providers.
# claude is assumed present (the orchestrator binary itself); auto/none
# never need a binary check.
case "$value" in
codex|gemini)
if ! command -v "$value" >/dev/null 2>&1; then
printf "WARN: critic provider %s not available, falling back to none\n" "$value" >&2
value="none"
fi
;;
esac
printf '%s' "$value"
}
# =============================================================================
# --audit flag support (Phase 44 / US-001 -- US-004). Read-only repo-hygiene
# check per idea-stage/IDEA_REPORT.md §6 measurement plan.
# Helpers live near the top so the pre-arg-loop audit shortcut can call them.
# =============================================================================
# _audit_format_row PIPE_ROW
# Takes one pipe-delimited string "name|value|target|status|drill" and emits
# formatted output on stdout. Single line for OK, two lines for FAIL (main
# line + indented drill-down with └─ prefix). Column widths locked so CI
# scripts can grep reliably.
_audit_format_row() {
local row="${1:-}"
local name value target status drill
IFS='|' read -r name value target status drill <<< "$row"
# Main line: "<name>: <value> (target <target>) <status>"
# Column widths: name: padded to 18, value+target padded to 30, status right.
printf "%-18s %s (target %s) %6s\n" "${name}:" "$value" "$target" "$status"
# Drill only when FAIL and non-empty drill
if [[ "$status" == "FAIL" && -n "$drill" ]]; then
printf " └─ %s\n" "$drill"
fi
}
# _audit_drill_join NAMES_VAR_REF (bash-4 nameref pattern)
# Given an array of offending names, emit at most the first 3 joined with
# ", " plus "(+N more)" when there's a tail. Empty input → empty string.
# Requires bash 4.3+ (uses `local -n` nameref). All audit code paths are
# bash-4-only; older bashes (e.g., macOS default 3.2) are unsupported.
_audit_drill_join() {
local -n _arr="$1" # nameref (bash 4.3+)
local n="${#_arr[@]}"
if (( n == 0 )); then printf ""; return 0; fi
local head_count=3
(( n < head_count )) && head_count=$n
local i=0 out=""
while (( i < head_count )); do
if (( i > 0 )); then out+=", "; fi
out+="${_arr[$i]}"
i=$((i + 1))
done
if (( n > head_count )); then
out+=" (+$((n - head_count)) more)"
fi
printf '%s' "$out"
}
# _audit_branches_local
# Counts local branches excluding master/HEAD; emits OK row if count <=
# QL_AUDIT_BRANCH_MAX (default 10) else FAIL with first-3 drill.
_audit_branches_local() {
local max="${QL_AUDIT_BRANCH_MAX:-10}"
local -a names=()
local b
while IFS= read -r b; do
b="${b#\* }"
b="${b# }"
[[ -z "$b" || "$b" == "master" || "$b" == "HEAD" ]] && continue
names+=("$b")
done < <({ git branch 2>/dev/null ; } || true)
local n="${#names[@]}"
if (( n <= max )); then
printf 'branches-local|%d|≤%d|OK|\n' "$n" "$max"
else
local drill
drill=$(_audit_drill_join names)
printf 'branches-local|%d|≤%d|FAIL|%s\n' "$n" "$max" "$drill"
fi
}
# _audit_branches_remote
# Same as _audit_branches_local but against `git branch -r`, excluding
# HEAD pointers and origin/master.
_audit_branches_remote() {
local max="${QL_AUDIT_BRANCH_MAX:-10}"
local -a names=()
local b
while IFS= read -r b; do
b="${b# }"
[[ -z "$b" ]] && continue
[[ "$b" == *"HEAD"* ]] && continue
[[ "$b" == "origin/master" ]] && continue
names+=("$b")
done < <({ git branch -r 2>/dev/null ; } || true)
local n="${#names[@]}"
if (( n <= max )); then
printf 'branches-remote|%d|≤%d|OK|\n' "$n" "$max"
else
local drill
drill=$(_audit_drill_join names)
printf 'branches-remote|%d|≤%d|FAIL|%s\n' "$n" "$max" "$drill"
fi
}
# _audit_readme_conflicts
# Counts merge-conflict markers in README.md. Guards against missing file.
# Target QL_AUDIT_CONFLICT_MAX (default 0). Drill = first 3 line numbers.
_audit_readme_conflicts() {
local max="${QL_AUDIT_CONFLICT_MAX:-0}"
local n=0
local -a lines=()
if [[ -f README.md ]]; then
local ln
while IFS=: read -r ln _; do
[[ -n "$ln" ]] && lines+=("$ln")
done < <({ grep -nE '^(<<<<<<<|=======|>>>>>>>)' README.md 2>/dev/null ; } || true)
n="${#lines[@]}"
fi
if (( n <= max )); then
printf 'readme-conflicts|%d|%d|OK|\n' "$n" "$max"
else
local drill
drill=$(_audit_drill_join lines)
printf 'readme-conflicts|%d|%d|FAIL|%s\n' "$n" "$max" "$drill"
fi
}
# _audit_orphan_worktrees
# Counts .claude/worktrees/agent-* directories. Target QL_AUDIT_ORPHAN_MAX
# (default 0). Drill = first 3 basenames.
_audit_orphan_worktrees() {
local max="${QL_AUDIT_ORPHAN_MAX:-0}"
local -a names=()
local d
while IFS= read -r d; do
[[ -z "$d" ]] && continue
[[ -d "$d" ]] || continue
names+=("$(basename "$d")")
done < <({ ls -d .claude/worktrees/agent-* 2>/dev/null ; } || true)
local n="${#names[@]}"
if (( n <= max )); then
printf 'orphan-worktrees|%d|%d|OK|\n' "$n" "$max"
else
local drill
drill=$(_audit_drill_join names)
printf 'orphan-worktrees|%d|%d|FAIL|%s\n' "$n" "$max" "$drill"
fi
}
# _audit_cpc_files
# Counts CPC-variant files (legacy *-CPC-*.json / *-CPC-*.md / etc).
# Target QL_AUDIT_CPC_MAX (default 0). Drill = first 3 paths.
_audit_cpc_files() {
local max="${QL_AUDIT_CPC_MAX:-0}"
local -a names=()
local f
while IFS= read -r f; do
[[ -z "$f" ]] && continue
names+=("$f")
done < <({ find . -maxdepth 3 -name '*-CPC-*' -not -path './.git/*' 2>/dev/null ; } || true)
local n="${#names[@]}"
if (( n <= max )); then
printf 'cpc-files|%d|%d|OK|\n' "$n" "$max"
else
local drill
drill=$(_audit_drill_join names)
printf 'cpc-files|%d|%d|FAIL|%s\n' "$n" "$max" "$drill"
fi
}
# _audit_validate_env
# Validate env-var inputs to the audit before any output is emitted.
# Per PRD FR-11: QL_AUDIT_TEST_GLOB must match ^[A-Za-z0-9._/*-]+$. On
# mismatch print error + exit 2. Called from the pre-arg-loop audit
# shortcut so invalid input never produces a half-rendered audit frame.
_audit_validate_env() {
local test_glob="${QL_AUDIT_TEST_GLOB:-*}"
if [[ ! "$test_glob" =~ ^[A-Za-z0-9._/*-]+$ ]]; then
printf "Error: invalid QL_AUDIT_TEST_GLOB (must match [A-Za-z0-9._/*-]+)\n" >&2
exit 2
fi
}
# _audit_test_suites
# Inspects the most-recent .omc/phase-*-evidence/ dir for evidence logs
# matching `=== Results: <P>/<T> passed, <F> failed ===`. Sums P/T/F.
# OK iff F == 0. When no evidence dir exists, emits unknown/FAIL per FR-10.
#
# Filtered by QL_AUDIT_TEST_GLOB (default "*", validated by
# _audit_validate_env before this helper runs).
_audit_test_suites() {
local test_glob="${QL_AUDIT_TEST_GLOB:-*}"
local -a dirs=()
local d
while IFS= read -r d; do
[[ -z "$d" || ! -d "$d" ]] && continue
dirs+=("$d")
done < <({ ls -d .omc/phase-*-evidence 2>/dev/null ; } || true)
if (( ${#dirs[@]} == 0 )); then
printf 'test-suites|unknown|green|FAIL|no evidence logs found — run tests first\n'
return 0
fi
# Pick latest by NUMERIC phase number. Plain `sort` is lexicographic so
# phase-9 sorts after phase-43 (wrong). `sort -V` handles version-style
# numeric-aware sorting and is available on GNU + BSD + Git Bash.
local latest
latest=$(printf '%s\n' "${dirs[@]}" | sort -V | tail -1)
local sum_p=0 sum_t=0 sum_f=0
local -a failing=()
local log line p t f
# shellcheck disable=SC2231 # intentional glob expansion of validated TEST_GLOB
for log in "$latest"/${test_glob}.log; do
[[ -f "$log" ]] || continue
line=$({ grep -E '^=== (Final )?Results: [0-9]+/[0-9]+ passed' "$log" 2>/dev/null ; } || true)
[[ -z "$line" ]] && continue
if [[ "$line" =~ ([0-9]+)/([0-9]+)\ passed(,\ ([0-9]+)\ failed)? ]]; then
p="${BASH_REMATCH[1]}"
t="${BASH_REMATCH[2]}"
f="${BASH_REMATCH[4]:-0}"
sum_p=$((sum_p + p))
sum_t=$((sum_t + t))
sum_f=$((sum_f + f))
if (( f > 0 )); then
failing+=("$(basename "$log" .log)")
fi
fi
done
if (( sum_f == 0 )); then
printf 'test-suites|%d/%d passed|green|OK|\n' "$sum_p" "$sum_t"
else
local drill
drill=$(_audit_drill_join failing)
printf 'test-suites|%d/%d passed|green|FAIL|%s\n' "$sum_p" "$sum_t" "$drill"
fi
}
# do_audit
# Driver for --audit. Calls all 6 metric helpers in canonical order, renders
# each row via _audit_format_row, returns 0 if all OK else 1.
do_audit() {
printf "=== Quantum-loop audit ===\n"
local -a ROWS=()
ROWS+=("$(_audit_branches_local)")
ROWS+=("$(_audit_branches_remote)")
ROWS+=("$(_audit_orphan_worktrees)")
ROWS+=("$(_audit_readme_conflicts)")
ROWS+=("$(_audit_cpc_files)")
ROWS+=("$(_audit_test_suites)")
local any_fail=0 ok_count=0 total=0
local row
for row in "${ROWS[@]}"; do
_audit_format_row "$row"
total=$((total + 1))
if [[ "$row" == *"|FAIL|"* ]]; then
any_fail=1
else
ok_count=$((ok_count + 1))
fi
done
printf "\nSummary: %d/%d metrics on target.\n" "$ok_count" "$total"
return "$any_fail"
}
# Test-mode guard (Phase 44 / US-001): when QL_AUDIT_TEST_MODE=1 is set,
# sourcing this file returns here so unit tests can reach the audit
# helpers defined above without triggering the main arg-loop or any
# state-mutating code below.
[[ "${QL_AUDIT_TEST_MODE:-0}" == "1" ]] && return 0 2>/dev/null
# Pre-arg-loop audit shortcut: --audit is exclusive and takes no other args.
# Must run BEFORE the normal arg-parsing loop so any stray sibling flag
# (--audit --parallel) is rejected with exit 2.
if [[ " $* " == *" --audit "* ]]; then
if [[ "$#" -ne 1 ]]; then
printf "Error: --audit is exclusive and takes no other arguments\n" >&2
exit 2
fi
_audit_validate_env
do_audit
exit $?
fi
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--max-iterations)
MAX_ITERATIONS="$2"
shift 2
;;
--max-retries)
MAX_RETRIES="$2"
shift 2
;;
--tool)
TOOL="$2"
shift 2
;;
--parallel)
PARALLEL_MODE=true
shift
;;
--max-parallel)
MAX_PARALLEL="$2"
shift 2
;;
--stale-timeout)
STALE_TIMEOUT="$2"
shift 2
;;
--critic=*)
# P5.A2 / US-002 -- critic provider routing (subsumed by US-009 per-role)
_ql_critic_raw="${1#--critic=}"
QL_CRITIC=$(parse_role_arg critic "$_ql_critic_raw") || exit 2
export QL_CRITIC
shift
;;
--critic)
if [[ $# -lt 2 || "${2:-}" == --* ]]; then
printf "Error: --critic requires a value (auto|claude|codex|gemini|none)\n" >&2
exit 2
fi
QL_CRITIC=$(parse_role_arg critic "$2") || exit 2
export QL_CRITIC
shift 2
;;
--planner=*)
# P5.B1 / US-009 — per-role planner routing
_ql_planner_raw="${1#--planner=}"
QL_PLANNER=$(parse_role_arg planner "$_ql_planner_raw") || exit 2
export QL_PLANNER
shift
;;
--planner)
if [[ $# -lt 2 || "${2:-}" == --* ]]; then
printf "Error: --planner requires a value (auto|claude|codex|gemini)\n" >&2
exit 2
fi
QL_PLANNER=$(parse_role_arg planner "$2") || exit 2
export QL_PLANNER
shift 2
;;
--executor=*)
# P5.B1 / US-009 — per-role executor routing
_ql_executor_raw="${1#--executor=}"
QL_EXECUTOR=$(parse_role_arg executor "$_ql_executor_raw") || exit 2
export QL_EXECUTOR
shift
;;
--executor)
if [[ $# -lt 2 || "${2:-}" == --* ]]; then
printf "Error: --executor requires a value (auto|claude|codex|gemini)\n" >&2
exit 2
fi
QL_EXECUTOR=$(parse_role_arg executor "$2") || exit 2
export QL_EXECUTOR
shift 2
;;
--non-interactive)
NON_INTERACTIVE=true
shift
;;
--help)
head -29 "$0" | tail -24
exit 0
;;
*)
printf "Unknown option: %s\n" "$1"
exit 1
;;
esac
done
# Validate dependencies
if ! command -v jq &>/dev/null; then
printf "ERROR: jq is required. Install it: https://jqlang.github.io/jq/download/\n"
exit 1
fi
# Validate quantum.json
if [[ ! -f quantum.json ]]; then
printf "ERROR: quantum.json not found. Run /quantum-loop:plan first to create it.\n"
exit 1
fi
# Source library functions
source "$SCRIPT_DIR/lib/common.sh" || { printf "ERROR: lib/common.sh not found\n"; exit 1; }
source "$SCRIPT_DIR/lib/json-atomic.sh" || { printf "ERROR: lib/json-atomic.sh not found\n"; exit 1; }
source "$SCRIPT_DIR/lib/runner.sh" || { printf "ERROR: lib/runner.sh not found\n"; exit 1; }
# Load runner manifest (validates tool name, binary existence, sets RUNNER_* vars)
runner_load "$TOOL" || exit 1
runner_ensure_instructions || true
# Experimental tier warning
if [[ "$RUNNER_TIER" == "experimental" && "${NON_INTERACTIVE:-}" != "true" ]]; then
printf "\nWARNING: Runner '%s' is experimental (tier: %s).\n" "$RUNNER_NAME" "$RUNNER_TIER"
printf "Experimental runners may not reliably emit quantum signals.\n"
printf "Press Enter to continue or Ctrl-C to abort...\n"
read -r
fi
if [[ "$PARALLEL_MODE" == "true" ]]; then
source "$SCRIPT_DIR/lib/dag-query.sh" || { printf "ERROR: lib/dag-query.sh not found\n"; exit 1; }
source "$SCRIPT_DIR/lib/worktree.sh" || { printf "ERROR: lib/worktree.sh not found\n"; exit 1; }
source "$SCRIPT_DIR/lib/spawn.sh" || { printf "ERROR: lib/spawn.sh not found\n"; exit 1; }
source "$SCRIPT_DIR/lib/monitor.sh" || { printf "ERROR: lib/monitor.sh not found\n"; exit 1; }
source "$SCRIPT_DIR/lib/resilience.sh" || { printf "ERROR: lib/resilience.sh not found\n"; exit 1; }
fi
# =============================================================================
# Archive previous run if branch changed
# =============================================================================
BRANCH=$(jq -r '.branchName' quantum.json)
LAST_BRANCH_FILE=".last-ql-branch"
if [[ -f "$LAST_BRANCH_FILE" ]]; then
LAST_BRANCH=$(cat "$LAST_BRANCH_FILE")
if [[ "$LAST_BRANCH" != "$BRANCH" ]]; then
ARCHIVE_DIR="archive/$(date +%Y-%m-%d)-${BRANCH//\//-}"
printf "Branch changed from %s to %s\n" "$LAST_BRANCH" "$BRANCH"
printf "Archiving previous run to %s\n" "$ARCHIVE_DIR"
mkdir -p "$ARCHIVE_DIR"
cp quantum.json "$ARCHIVE_DIR/quantum.json" 2>/dev/null || true
printf "Archive complete.\n"
fi
fi
printf "%s" "$BRANCH" > "$LAST_BRANCH_FILE"
# Update maxAttempts in quantum.json if different from default
jq --argjson max "$MAX_RETRIES" '
.stories |= map(.retries.maxAttempts = $max)
' quantum.json > quantum.json.tmp && mv quantum.json.tmp quantum.json
# =============================================================================
# Summary table function
# =============================================================================
print_summary_table() {
printf "\n"
printf "Summary\n"
printf "%-10s %-40s %-8s %-6s %-8s\n" "Story" "Title" "Status" "Wave" "Retries"
printf "%-10s %-40s %-8s %-6s %-8s\n" "----------" "----------------------------------------" "--------" "------" "--------"
jq -r '.stories[] | "\(.id)|\(.title)|\(.status)|\(.retries.attempts)/\(.retries.maxAttempts)"' quantum.json | \
while IFS='|' read -r sid title status retries; do
printf "%-10s %-40s %-8s %-6s %-8s\n" "$sid" "${title:0:40}" "$status" "-" "$retries"
done
printf "\n"
local total passed failed
total=$(jq '.stories | length' quantum.json)
passed=$(jq '[.stories[] | select(.status == "passed")] | length' quantum.json)
failed=$((total - passed))
printf "Result: %d/%d stories passed\n" "$passed" "$total"
}
# =============================================================================
# Stale story detection
# =============================================================================
detect_stale_stories() {
local threshold="${STALE_TIMEOUT:-20}"
local now_epoch
now_epoch=$(date +%s)
# Find all in_progress stories with startedAt set
local stale_ids
stale_ids=$(jq -r --argjson threshold "$threshold" '
.stories[] |
select(.status == "in_progress" and .startedAt != null) |
select(
((now | floor) - (.startedAt | fromdateiso8601)) > ($threshold * 60)
) |
.id
' quantum.json 2>/dev/null) || return 0
if [[ -z "$stale_ids" ]]; then
return 0
fi
while IFS= read -r sid; do
[[ -z "$sid" ]] && continue
printf "[STALE] %s - resetting to failed (exceeded %d minute threshold)\n" "$sid" "$threshold"
jq --arg id "$sid" --argjson threshold "$threshold" '
.stories |= map(if .id == $id then
.status = (if .retries.attempts + 1 >= .retries.maxAttempts then "blocked" else "failed" end) |
.startedAt = null |
.retries.attempts += 1 |
.retries.failureLog += [{"phase": "stale_detection", "timestamp": (now | todate), "error": ("Story exceeded " + ($threshold | tostring) + " minute stale threshold")}]
else . end)
' quantum.json > quantum.json.tmp && mv quantum.json.tmp quantum.json
done <<< "$stale_ids"
}
# =============================================================================
# Safe test command execution (allowlist + metacharacter rejection)
# =============================================================================
# Allowlist of known-safe test command prefixes
ALLOWED_TEST_PREFIXES=("npm test" "npx jest" "npx vitest" "yarn test" "pnpm test" "python -m pytest" "pytest" "cargo test" "go test" "make test" "bash tests/" "shellcheck")
# validate_and_run_test_cmd(cmd, [work_dir])
# Validates a test command against the allowlist and rejects shell metacharacters.
# Executes via array splitting (no eval). Returns the command's exit code.
validate_and_run_test_cmd() {
local cmd="$1"
local work_dir="${2:-.}"
if [[ -z "$cmd" ]]; then
return 1
fi
# Reject shell metacharacters
if [[ "$cmd" =~ [\;\|\&\$\`\(\)\>\<\!] ]] || [[ "$cmd" == *$'\n'* ]]; then
printf "ERROR: Test command contains unsafe characters: %s\n" "$cmd" >&2
return 1
fi
# Check allowlist
local allowed=false
for prefix in "${ALLOWED_TEST_PREFIXES[@]}"; do
if [[ "$cmd" == "$prefix" || "$cmd" == "$prefix "* ]]; then
allowed=true
break
fi
done
if [[ "$allowed" != "true" ]]; then
printf "ERROR: Test command '%s' does not match any allowed prefix — refusing to execute\n" "$cmd" >&2
return 1
fi
# Execute as array to prevent shell interpretation
local -a cmd_array
read -ra cmd_array <<< "$cmd"
(cd "$work_dir" && "${cmd_array[@]}" >/dev/null 2>&1)
}
# =============================================================================
# Final verification sweep before declaring COMPLETE
# =============================================================================
final_verification_sweep() {
printf "\n[FINAL SWEEP] Running test suite before declaring COMPLETE...\n"
# Detect test command
local TEST_CMD=""
if [[ -f "package.json" ]]; then TEST_CMD="npm test"
elif [[ -f "pyproject.toml" ]] || [[ -f "setup.py" ]]; then TEST_CMD="python -m pytest -x -q"
elif [[ -f "Cargo.toml" ]]; then TEST_CMD="cargo test"
elif [[ -f "go.mod" ]]; then TEST_CMD="go test ./..."
fi
if [[ -n "$TEST_CMD" ]]; then
if validate_and_run_test_cmd "$TEST_CMD"; then
printf "[FINAL SWEEP] Test suite passed.\n"
else
printf "[FINAL SWEEP] FAILED: test suite. Cannot declare COMPLETE.\n"
print_summary_table
exit 1
fi
else
printf "[FINAL SWEEP] No test suite detected, skipping.\n"
fi
# Import smoke test (warning only)
if [[ -f "package.json" ]]; then
local entry
entry=$(jq -r '.main // empty' package.json 2>/dev/null)
if [[ -n "$entry" ]]; then
if node -e "require('./$entry')" >/dev/null 2>&1; then
printf "[FINAL SWEEP] Import smoke test passed.\n"
else
printf "[FINAL SWEEP] WARNING: Import smoke test failed for %s (non-blocking).\n" "$entry"
fi
fi
elif [[ -f "go.mod" ]]; then
if go build ./... >/dev/null 2>&1; then
printf "[FINAL SWEEP] Go build passed.\n"
else
printf "[FINAL SWEEP] WARNING: go build failed (non-blocking).\n"
fi
fi
}
# =============================================================================
# Generate execution observations document
# =============================================================================
generate_observations() {
local branch
branch=$(jq -r '.branchName' quantum.json)
local date_str
date_str=$(date +%Y-%m-%d)
local obs_file="docs/post-mortems/${date_str}-${branch//\//-}-observations.md"
mkdir -p docs/post-mortems
local total passed failed blocked
total=$(jq '.stories | length' quantum.json)
passed=$(jq '[.stories[] | select(.status == "passed")] | length' quantum.json)
failed=$(jq '[.stories[] | select(.status == "failed")] | length' quantum.json)
blocked=$(jq '[.stories[] | select(.status == "blocked")] | length' quantum.json)
{
printf "# Execution Observations: %s\n\n" "$branch"
printf "**Date:** %s\n" "$date_str"
printf "**Stories:** %d passed, %d failed, %d blocked (of %d total)\n" "$passed" "$failed" "$blocked" "$total"
printf "**Mode:** %s\n\n" "$(if $PARALLEL_MODE; then echo 'parallel'; else echo 'sequential'; fi)"
printf "## Failure Summary\n\n"
local failures
# Sanitize pipe characters in title so the markdown table stays aligned
failures=$(jq -r '.stories[] | select(.status == "failed" or .status == "blocked") | "\(.id)|\(.title | gsub("\\|"; "/"))|\(.status)|\(.retries.attempts)/\(.retries.maxAttempts)"' quantum.json 2>/dev/null)
if [[ -n "$failures" ]]; then
printf "| Story | Title | Status | Retries |\n"
printf "|-------|-------|--------|--------|\n"
while IFS='|' read -r sid title status retries; do
printf "| %s | %s | %s | %s |\n" "$sid" "${title:0:40}" "$status" "$retries"
done <<< "$failures"
else
printf "No failures.\n"
fi
# Phase 6 / P1.7 — Progress Log table: one row per failed-story phase
# so the learning loop has structured data (previously this block was
# just an empty <details> block when .progress was []).
printf "\n## Progress Log\n\n"
local progress_rows
progress_rows=$(jq -r '
[
(.stories[] | select(.retries.failureLog // [] | length > 0)
| .id as $sid
| (.retries.failureLog // [])[]
| [ $sid,
(.phase // "unknown"),
((.error // "") | gsub("\\|"; "/") | .[0:80]),
"",
"",
"" ]
| @tsv),
(.progress // []
| .[]
| [ (.storyId // "(pipeline)"),
(.action // "unknown"),
((.details // "") | gsub("\\|"; "/") | .[0:80]),
"",
"",
(.learnings // "") ]
| @tsv)
] | .[]
' quantum.json 2>/dev/null)
if [[ -n "$progress_rows" ]]; then
printf "| Story | Phase / Action | Error / Detail | Root cause | Fix applied | Lesson |\n"
printf "|-------|----------------|----------------|-----------|-------------|--------|\n"
while IFS=$'\t' read -r sid phase detail rc fix lesson; do
[[ -z "$sid" && -z "$phase" ]] && continue
printf "| %s | %s | %s | %s | %s | %s |\n" \
"${sid:-(pipeline)}" "${phase:-unknown}" "${detail:-}" "${rc:-}" "${fix:-}" "${lesson:-}"
done <<< "$progress_rows"
else
printf "_No failed / retried stories. Progress log is empty._\n"
fi
printf "\n## Raw Data\n\n"
printf "<details>\n<summary>Progress JSON</summary>\n\n"
printf '```json\n'
jq '.progress' quantum.json
printf '```\n\n'
printf "</details>\n\n"
printf "<details>\n<summary>Failure Logs</summary>\n\n"
printf '```json\n'
jq '[.stories[] | select(.retries.failureLog | length > 0) | {id, failureLog: .retries.failureLog}]' quantum.json
printf '```\n\n'
printf "</details>\n"
} > "$obs_file"
# Phase 6 / P1.7 — promote generalizable lessons from progress entries into
# codebasePatterns so the next iteration inherits them.
local new_patterns
new_patterns=$(jq '[.progress // [] | .[] | select(.learnings? and (.learnings | length > 0)) | .learnings]' quantum.json 2>/dev/null)
if [[ "$new_patterns" != "[]" && -n "$new_patterns" ]]; then
local tmpfile
tmpfile=$(mktemp 2>/dev/null || mktemp -t qlobs)
jq --argjson newlessons "$new_patterns" '
.codebasePatterns = ((.codebasePatterns // []) + $newlessons | unique)
' quantum.json > "$tmpfile" 2>/dev/null
if [[ -s "$tmpfile" ]]; then
mv "$tmpfile" quantum.json
printf "[OBSERVATIONS] Promoted %s lessons into codebasePatterns.\n" \
"$(echo "$new_patterns" | jq 'length')"
else
rm -f "$tmpfile"
fi
fi
git add "$obs_file" && git commit -m "docs: execution observations for $branch" >/dev/null 2>&1 || true
printf "[OBSERVATIONS] Generated %s\n" "$obs_file"
# Check if observations contain issues worth reporting
local has_blocked has_recurring
has_blocked=$(jq '[.stories[] | select(.status == "blocked" or .status == "failed")] | length' quantum.json)
has_recurring=$(jq '[.stories[] | (.retries.failureLog // [])[] | .phase] | group_by(.) | map(select(length > 1)) | length' quantum.json 2>/dev/null || echo "0")
if [[ "$has_blocked" -gt 0 || "$has_recurring" -gt 0 ]]; then
# Skip prompt if non-interactive
if [[ ! -t 0 ]] || [[ "${NON_INTERACTIVE:-false}" == "true" ]]; then
printf "[OBSERVATIONS] Skipping GitHub issue prompt (non-interactive mode).\n"
return
fi
printf "\n[OBSERVATIONS] Found issues worth reporting (%d blocked/failed, %d recurring patterns).\n" "$has_blocked" "$has_recurring"
read -rp "File observations as GitHub issue on quantum-loop? [y/N] " response
if [[ "$response" =~ ^[Yy]$ ]]; then
if command -v gh >/dev/null 2>&1; then
gh issue create --repo andyzengmath/quantum-loop \
--title "Execution observations: $branch ($date_str)" \
--body "$(cat "$obs_file")" \
--label "execution-feedback" 2>/dev/null && \
printf "[OBSERVATIONS] GitHub issue filed.\n" || \
printf "[OBSERVATIONS] Failed to file GitHub issue (gh error). Local doc is available.\n"
else
printf "[OBSERVATIONS] gh CLI not found. Local doc is available at %s\n" "$obs_file"
fi
fi
fi
}
# =============================================================================
# Main header
# =============================================================================
printf "===========================================\n"
printf " Quantum-Loop Autonomous Development\n"
printf "===========================================\n"
printf " Branch: %s\n" "$BRANCH"
printf " Runner: %s (%s)\n" "$RUNNER_NAME" "$RUNNER_BINARY"
printf " Tier: %s\n" "$RUNNER_TIER"
printf " Instruction: %s\n" "$RUNNER_INSTRUCTION_NATIVE"
printf " Max Iter: %s\n" "$MAX_ITERATIONS"
printf " Max Retries: %s\n" "$MAX_RETRIES"
if [[ "$PARALLEL_MODE" == "true" ]]; then
printf " Mode: Parallel (max %s concurrent)\n" "$MAX_PARALLEL"
else
printf " Mode: Sequential\n"
fi
printf "===========================================\n\n"
# =============================================================================
# Parallel execution mode
# =============================================================================
if [[ "$PARALLEL_MODE" == "true" ]]; then
# Phase 20 / P2.11 — platform-aware reaper. Load lib/reaper.sh so the trap
# cascades through `taskkill //T //F` on Git Bash (where `kill` on a subshell
# pid does NOT reach the native claude.exe child) and via `kill -TERM -pgid`
# on POSIX where available. Durable pidfiles live in REAPER_PID_DIR so a
# separate `ql-housekeep --reap-orphans` can clean up anything this trap
# misses (terminal close, crash, Agent-tool grandchildren).
REAPER_PID_DIR="${REAPER_PID_DIR:-.ql-agent-pids}"
export REAPER_PID_DIR
if [[ -f "$REPO_ROOT/lib/reaper.sh" ]]; then
# shellcheck source=lib/reaper.sh
source "$REPO_ROOT/lib/reaper.sh"
fi
declare -a AGENT_PIDS=()
declare -a AGENT_STORIES=()
cleanup_on_exit() {
printf "\n[INTERRUPT] Cleaning up agents...\n"
if type reap_agent &>/dev/null; then
# Phase 21 fix: background each reap so the SIGTERM → grace → SIGKILL
# escalation happens IN PARALLEL across all agents. Without this,
# Ctrl+C blocks for N × REAPER_GRACE_SECS (20+ seconds with
# MAX_PARALLEL=4). Waits ≤ 1 × REAPER_GRACE_SECS regardless of
# agent count.
local -a REAP_PIDS=()
for sid in "${AGENT_STORIES[@]+"${AGENT_STORIES[@]}"}"; do
reap_agent "$REAPER_PID_DIR" "$sid" &
REAP_PIDS+=("$!")
done
for rp in "${REAP_PIDS[@]+"${REAP_PIDS[@]}"}"; do
wait "$rp" 2>/dev/null || true
done
else
# Fallback: legacy best-effort kill if reaper missing
for pid in "${AGENT_PIDS[@]+"${AGENT_PIDS[@]}"}"; do
kill "$pid" 2>/dev/null || true
done
for pid in "${AGENT_PIDS[@]+"${AGENT_PIDS[@]}"}"; do
wait "$pid" 2>/dev/null || true
done
fi
exit 130
}
trap cleanup_on_exit INT TERM
# Crash recovery on startup
REPO_ROOT="$(pwd)"
recover_orphaned_worktrees "$REPO_ROOT/quantum.json" "$REPO_ROOT" || true
cleanup_stale_tmp "$REPO_ROOT/quantum.json" || true
# Phase 20 / P2.11 — reap any claude processes left by a prior crashed run
# (their pidfiles will be in REAPER_PID_DIR with start_epoch older than
# REAPER_STALE_SECS, default 1h). No-op if reaper not loaded.
if type reap_orphans &>/dev/null; then
REAPED=$(reap_orphans "$REPO_ROOT/$REAPER_PID_DIR" 2>/dev/null || echo 0)
if [[ -n "$REAPED" && "$REAPED" != "0" ]]; then
printf "[REAPER] reaped %s orphan agent(s) from prior run\n" "$REAPED"
fi
fi
WAVE=0
for ITERATION in $(seq 1 "$MAX_ITERATIONS"); do
printf "\n=== Iteration %d / %d ===\n\n" "$ITERATION" "$MAX_ITERATIONS"
# Detect stale stories before DAG query
detect_stale_stories
# Get executable stories from DAG
EXECUTABLE=$(get_executable_stories "$REPO_ROOT/quantum.json")
if [[ "$EXECUTABLE" == "COMPLETE" ]]; then
final_verification_sweep
printf "\n===========================================\n"
printf " <quantum>COMPLETE</quantum>\n"
printf " All stories passed! Feature is done.\n"
printf "===========================================\n"
print_summary_table
exit 0
fi
if [[ "$EXECUTABLE" == "BLOCKED" ]]; then
printf "\n===========================================\n"
printf " <quantum>BLOCKED</quantum>\n"
printf " No executable stories remain.\n"
printf "===========================================\n"
print_summary_table
exit 1
fi
if [[ -z "$EXECUTABLE" ]]; then
printf "WARNING: No executable stories found\n"
print_summary_table
exit 1
fi
# Filter out stories that share files with higher-priority stories in this wave
EXECUTABLE=$(filter_file_conflicts "$REPO_ROOT/quantum.json" "$EXECUTABLE")
# Count executable stories
EXEC_COUNT=$(echo "$EXECUTABLE" | jq '. | length')
WAVE=$((WAVE + 1))
# Setup execution metadata
update_execution_field "$REPO_ROOT/quantum.json" "parallel" "$MAX_PARALLEL" "$WAVE" || true
# Arrays to track spawned agents
declare -a AGENT_PIDS=()
declare -a AGENT_STORIES=()
declare -a AGENT_WORKTREES=()
declare -a AGENT_START_TIMES=()
# Spawn agents for each executable story (up to MAX_PARALLEL)
SPAWN_COUNT=0
for i in $(seq 0 $((EXEC_COUNT - 1))); do
if [[ "$SPAWN_COUNT" -ge "$MAX_PARALLEL" ]]; then
break
fi