-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathrun-loop.sh
More file actions
executable file
·2243 lines (1980 loc) · 83.9 KB
/
Copy pathrun-loop.sh
File metadata and controls
executable file
·2243 lines (1980 loc) · 83.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# ClosedLoop External Loop Runner
# Runs Claude iterations with fresh context by launching claude -p in a loop
# State maintained in .closedloop-ai/closedloop-loop.local.md
# Integrates with the ClosedLoop Self-Learning System
set -euo pipefail
# Claude binary path. When spawned by the closedloop-electron desktop app,
# CLAUDE_BIN is set to the absolute path that the desktop validated in its
# pre-flight check. This avoids PATH mismatches between Electron's spawn env
# and the user's login shell (e.g. non-Homebrew installs, symlinked binaries).
# Falls back to bare `claude` for manual/interactive runs where PATH is trusted.
CLAUDE="${CLAUDE_BIN:-claude}"
# Single source of truth for the state directory name
CLOSEDLOOP_STATE_DIR=".closedloop-ai"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# State file location
STATE_FILE="$CLOSEDLOOP_STATE_DIR/closedloop-loop.local.md"
PROGRESS_LOG="$CLOSEDLOOP_STATE_DIR/closedloop-progress.log"
LOOP_USER_VISIBLE_FAILURE_FILE_NAME="loop-error.json"
# Electron provides this per-run value so the parent harness can sign intentional
# failure markers. Keep it as a shell variable, then remove the exported env var
# before spawning Claude so repository/tool commands cannot forge the marker.
LOOP_USER_VISIBLE_FAILURE_SECRET="${CLOSEDLOOP_USER_VISIBLE_FAILURE_SECRET:-}"
unset CLOSEDLOOP_USER_VISIBLE_FAILURE_SECRET
# Learning system paths
LOCK_FILE=".learnings/.lock"
SCRIPTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Run identification
RUN_ID=""
START_SHA=""
SELF_LEARNING=false
LAST_CLAUDE_COMMAND=""
LAST_CLAUDE_SESSION_ID=""
# Write an intentionally user-visible failure marker for the Electron finalizer.
#
# This is an explicit opt-in channel only. Do not call this from ERR traps or
# generic command-failure handling; ordinary bash failures should stay generic.
# Usage:
# fail_loop_user_visible RUNNER_ERROR XYZ "Loop execution failed because XYZ."
write_loop_user_visible_failure() {
local code="$1"
local subcode="$2"
local message="$3"
if [[ -z "${CLOSEDLOOP_WORKDIR:-}" ]]; then
echo "Error: CLOSEDLOOP_WORKDIR is required to write loop failure marker" >&2
return 1
fi
if [[ -z "$LOOP_USER_VISIBLE_FAILURE_SECRET" ]]; then
echo "Error: CLOSEDLOOP_USER_VISIBLE_FAILURE_SECRET is required to write loop failure marker" >&2
return 1
fi
case "$code" in
RUNNER_ERROR|PRE_RUN_VALIDATION_FAILED|PLAN_STATE_UNAVAILABLE)
;;
*)
echo "Error: unsupported loop failure code: $code" >&2
return 1
;;
esac
if [[ ! "$subcode" =~ ^[A-Z][A-Z0-9_]{2,63}$ ]]; then
echo "Error: loop failure subcode must match ^[A-Z][A-Z0-9_]{2,63}$" >&2
return 1
fi
if [[ -z "$message" || ${#message} -gt 1000 ]]; then
echo "Error: loop failure message must be 1-1000 characters" >&2
return 1
fi
local payload
if ! payload=$(jq -n -c \
--arg code "$code" \
--arg message "$message" \
--arg subcode "$subcode" \
'{code:$code,message:$message,result:{subcode:$subcode}}'); then
return 1
fi
local signature
if ! signature=$(
printf '%s\0%s' "$LOOP_USER_VISIBLE_FAILURE_SECRET" "$payload" \
| python3 -c 'import hashlib, hmac, sys; secret, payload = sys.stdin.buffer.read().split(b"\0", 1); print("sha256=" + hmac.new(secret, payload, hashlib.sha256).hexdigest())'
); then
return 1
fi
local failure_file="${CLOSEDLOOP_WORKDIR}/${LOOP_USER_VISIBLE_FAILURE_FILE_NAME}"
local tmp_file="${failure_file}.tmp.$$"
mkdir -p "$(dirname "$failure_file")"
umask 077
if ! jq -c --arg signature "$signature" '. + {signature:$signature}' \
<<< "$payload" \
> "$tmp_file"; then
rm -f "$tmp_file"
return 1
fi
if ! mv "$tmp_file" "$failure_file"; then
rm -f "$tmp_file"
return 1
fi
}
fail_loop_user_visible() {
local code="$1"
local subcode="$2"
local message="$3"
if ! write_loop_user_visible_failure "$code" "$subcode" "$message"; then
echo "Error: failed to write user-visible loop failure marker" >&2
fi
echo "CLOSEDLOOP_FATAL[$subcode]: $message" >&2
exit 1
}
# Loop commands whose result bundle declares plan.json REQUIRED. Mirrors the
# ResultBundle manifest that the cloud side validates against (PLAN and
# REQUEST_CHANGES both require plan.json).
#
# EXECUTE is deliberately absent, and that is the load-bearing part: its
# required artifact is execution-result.json, which is only written after a
# successful commit AND push, so a legitimate no-changes EXECUTE run ends
# without it. A blanket "required artifact missing => spurious" rule would fail
# every one of those runs. Listing the non-plan commands by name below keeps
# EXECUTE excluded on purpose rather than by the accident of it not carrying a
# --prd.
LOOP_COMMANDS_OWING_PLAN="PLAN REQUEST_CHANGES"
LOOP_COMMANDS_NOT_OWING_PLAN="EXECUTE CHAT EXPLORE REQUEST_PRD_CHANGES DECOMPOSE EVALUATE_PRD GENERATE_PRD EVALUATE_PLAN EVALUATE_CODE EVALUATE_FEATURE BOOTSTRAP MANUAL"
# Normalize a command label to the canonical LoopCommand spelling.
# The desktop sets CLOSEDLOOP_COMMAND to the wire spelling (PLAN, EXECUTE,
# REQUEST_CHANGES); a local CLI run resolves it from --prompt instead, whose
# values are the prompt file names (plan-prompt, execute-prompt). Both map to
# the same command, so normalize rather than special-case the caller.
normalize_loop_command() {
local raw="${1:-}"
raw="${raw%-prompt}"
raw="${raw%_prompt}"
printf '%s' "$raw" | tr '[:lower:]-' '[:upper:]_'
}
# Does this run owe a plan.json? Echoes nothing; returns 0 (owes) or 1 (does not).
# Args: $1 = command label (raw), $2 = prd_file
#
# Version skew, both directions: an unrecognized command -- an older desktop
# sending nothing, or a newer one sending a command this script has never heard
# of -- is not an error and never blocks. It falls back to the --prd proxy,
# which is exactly the behaviour before commands were modelled at all.
run_owes_plan_json() {
local command
command=$(normalize_loop_command "${1:-}")
local prd_file="${2:-}"
case " $LOOP_COMMANDS_OWING_PLAN " in
*" $command "*) return 0 ;;
esac
case " $LOOP_COMMANDS_NOT_OWING_PLAN " in
*" $command "*) return 1 ;;
esac
[[ -n "$prd_file" ]]
}
# Classify the plan artifact at $1 as: missing | empty | unparseable | present.
#
# "Exists" is not "was produced". The incident evidence is literally a 0-byte
# plan.json: [[ -f ]] passes on it, jq yields nothing, and every pendingTasks
# check below reads 0 pending tasks and calls the run clean. A file that is
# absent, zero-byte, or not parseable JSON carries the same fact -- no plan was
# written -- and all three must be treated as unproduced.
classify_plan_artifact() {
local plan_file="$1"
if [[ ! -f "$plan_file" ]]; then
printf 'missing'
return
fi
if [[ ! -s "$plan_file" ]]; then
printf 'empty'
return
fi
if ! jq -e . "$plan_file" >/dev/null 2>&1; then
printf 'unparseable'
return
fi
printf 'present'
}
# Detect a spurious COMPLETE: the orchestrator's Phase 7 contract forbids
# emitting <promise>COMPLETE</promise> when plan.json has pending tasks, but
# it sometimes violates that contract -- typically when tasks are blocked by
# unanswered questions. Reads plan.json directly (not via validate_plan.py
# extraction) so the check still fires when the plan has format issues that
# would otherwise mask pendingTasks.
#
# Echoes a JSON object on stdout:
# {"subcode": "...", "message": "..."} when a violation is detected
# {} otherwise
#
# Args: $1 = workdir
# $2 = prd file (defaults to $PRD_FILE; tests pass it explicitly)
# $3 = command (defaults to $CLOSEDLOOP_COMMAND; ditto)
#
# Caller is responsible for telemetry, cleanup, and invoking
# fail_loop_user_visible.
detect_spurious_complete() {
local workdir="$1"
# Defaults to the global so the existing single-argument call site is
# unchanged; passed explicitly by tests. Non-empty means this run was asked to
# draft a plan from a PRD, which is what makes a missing plan.json a broken
# promise rather than a run that never owed one.
local prd_file="${2-${PRD_FILE:-}}"
# Defaults to the global the desktop exports; passed explicitly by tests.
local command="${3-${CLOSEDLOOP_COMMAND:-}}"
local plan_file="$workdir/plan.json"
local state_file="$workdir/state.json"
# Fail OPEN when the workspace itself is gone. "The artifact was not produced"
# and "the workspace no longer exists" are different facts, and only the first
# one is evidence of a spurious completion. Live-exit and boot-recovery paths
# delete the temp workdir right after finalization, so adjudicating a run
# whose directory has already been reclaimed would flip a genuine success into
# a failure -- a permanent divergence that no re-run can repair. A missing
# workdir means "cannot judge", so judge nothing.
if [[ ! -d "$workdir" ]]; then
echo '{}'
return
fi
# Skip the check when the orchestrator emitted COMPLETE as part of an
# AWAITING_USER_SEQUENCE hard stop (e.g., the Phase 1.1 plan review
# checkpoint). In those cases pending tasks and open questions are
# expected -- the plan was just drafted and is waiting on the user. Only
# a status of COMPLETED (or no state file at all) represents a final
# completion claim that should be validated against pendingTasks.
if [[ -f "$state_file" ]]; then
local state_status
state_status=$(jq -r '.status // ""' "$state_file" 2>/dev/null || echo "")
if [[ "$state_status" == "AWAITING_USER" ]]; then
echo '{}'
return
fi
fi
local plan_state
plan_state=$(classify_plan_artifact "$plan_file")
if [[ "$plan_state" != "present" ]]; then
# A PLAN or REQUEST_CHANGES run exists to produce plan.json. Claiming
# COMPLETE without one is the strongest spurious-completion signal there is,
# and this branch used to wave it through: the checks below only validate
# pendingTasks INSIDE an existing plan, so "no plan at all" -- the case that
# actually happens -- was the one case nothing could catch.
#
# Observed: the orchestrator launched plan-draft-writer in the BACKGROUND,
# said "Plan-draft-writer is running in the background. Waiting for
# completion.", and that same turn carried the completion promise. The loop
# ended, the writer was abandoned mid-flight, post-loop code review passed
# vacuously over an empty diff ("the base ref you passed equals HEAD, so
# nothing was examined"), and the run exited 0 having produced nothing. The
# user got an implementation-plan artifact that looked done and was empty.
#
# Scoped per-command: a run that never owed a plan is left alone.
#
# REQUEST_CHANGES is included, with a known limit: the harness seeds
# plan.json before an amend run, so PRESENCE PROVES NOTHING there. This
# branch still catches "no plan at all" (including a seeded file truncated
# to zero bytes), but it cannot see "the amend ran and produced nothing" --
# that needs a pre-run baseline the detector is not given. Do not read a
# clean result on a REQUEST_CHANGES run as proof the amend did work.
if run_owes_plan_json "$command" "$prd_file"; then
local plan_detail
case "$plan_state" in
empty)
plan_detail="plan.json is zero bytes -- the file exists but no plan was ever written into it"
;;
unparseable)
plan_detail="plan.json is not parseable JSON -- the file exists but no usable plan was written into it"
;;
*)
plan_detail="no plan.json was ever written"
;;
esac
jq -n -c \
--arg subcode "PLAN_MISSING_AT_COMPLETION" \
--arg message "Loop emitted COMPLETE but $plan_detail. The planning phase did not finish -- a background plan-draft-writer that is still running when the completion promise fires is abandoned. Inspect state.json and the loop output, then re-run /code:code to continue." \
'{subcode:$subcode,message:$message}'
return
fi
echo '{}'
return
fi
local pending_count
pending_count=$(jq -r '(.pendingTasks // []) | length' "$plan_file" 2>/dev/null || echo 0)
if ! [[ "$pending_count" =~ ^[0-9]+$ ]] || [[ "$pending_count" -eq 0 ]]; then
echo '{}'
return
fi
local pending_ids
pending_ids=$(jq -r '(.pendingTasks // []) | map(.id // "?") | .[0:10] | join(", ")' "$plan_file" 2>/dev/null || echo "unknown")
if [[ "$pending_count" -gt 10 ]]; then
pending_ids="$pending_ids, +$((pending_count - 10)) more"
fi
local open_q_count
open_q_count=$(jq -r '(.openQuestions // []) | length' "$plan_file" 2>/dev/null || echo 0)
local subcode message
if [[ "$open_q_count" =~ ^[0-9]+$ ]] && [[ "$open_q_count" -gt 0 ]]; then
subcode="PENDING_TASKS_BLOCKED_BY_QUESTIONS"
message="Loop emitted COMPLETE but $pending_count task(s) remain pending ($pending_ids) while $open_q_count open question(s) are unanswered in plan.json. Answer the open questions and re-run /code:code to continue."
else
subcode="PENDING_TASKS_AT_COMPLETION"
message="Loop emitted COMPLETE but $pending_count task(s) still pending ($pending_ids). Inspect plan.json and re-run /code:code to continue."
fi
jq -n -c --arg subcode "$subcode" --arg message "$message" \
'{subcode:$subcode,message:$message}'
}
# Handle a spurious COMPLETE: emit telemetry, release the lock, remove the
# state file, and fail out via fail_loop_user_visible (which exits 1).
# Only call when detect_spurious_complete returned a non-empty result.
handle_spurious_complete() {
local workdir="$1"
local iteration="$2"
local subcode="$3"
local message="$4"
echo -e "\n${RED}Spurious COMPLETE detected: $message${NC}" >&2
log_progress "Spurious COMPLETE: $message"
write_runs_log_entry "$workdir" "$iteration" "spurious_complete" "plan_execute"
rename_output_on_exit
release_lock "$workdir"
rm -f "$STATE_FILE"
fail_loop_user_visible "RUNNER_ERROR" "$subcode" "$message"
}
# Classify Claude CLI terminal failures from one iteration's structured stream.
# The helper is side-effect free so tests can exercise new/legacy JSONL shapes
# without running the full loop.
detect_claude_terminal_failure() {
local output_file="$1"
local stderr_file="${2:-}"
if [[ -s "$output_file" ]]; then
local detection
detection=$(jq -R -s -c '
def entries:
split("\n") | map(fromjson? | select(type == "object"));
def clamp_message:
if length > 900 then .[0:900] + "..." else . end;
def error_string:
if (.error? | type) == "string" then .error else "" end;
def rate_event_message($entries):
[
$entries[]
| select(.type == "rate_limit_event")
| .rate_limit_info?
| select(type == "object")
| "Claude rate limit reached"
+ (if .rateLimitType then " (" + (.rateLimitType | tostring) + ")" else "" end)
+ (if .resetsAt then "; resetsAt=" + (.resetsAt | tostring) else "" end)
] | .[0] // "";
def status_429:
((.api_error_status? | tostring) == "429")
or ((.apiErrorStatus? | tostring) == "429");
def envelope_text_match(pat):
((.is_error? == true) and ((.result? | strings | test(pat; "i")) // false))
or ((.isApiErrorMessage? == true) and ((.error? | strings | test(pat; "i")) // false));
def rate_limit_signal:
((.type? == "rate_limit_event") and (
(.rate_limit_info? | type) == "object"
and (
(.rate_limit_info.status? == "rejected")
or ((.rate_limit_info.isUsingOverage? == true) and (.rate_limit_info.overageStatus? == "rejected"))
)
))
or (error_string | ascii_downcase | test("^rate_limit(_error)?$"))
or status_429
or envelope_text_match("you.?ve hit your limit|usage limit|rate[_ -]?limit|rate limit reached");
def context_limit_signal:
envelope_text_match("prompt is too long|exceed context limit|context limit reached|conversation too long");
def auth_challenge_signal:
envelope_text_match("authentication_error|invalid bearer token|billing_error|permission_error|overloaded_error|api overloaded|unauthorized|token.*expired|not authenticated|please log in|login required");
def entry_message:
((.result? | strings) // (.error? | strings) // "");
def unknown_skill_signal:
((.result? | strings | test("Unknown skill:")) // false)
or ((.error? | strings | test("Unknown skill:")) // false);
entries as $entries
| rate_event_message($entries) as $rateMessage
| if any($entries[]; unknown_skill_signal) then
([$entries[] | select(unknown_skill_signal)] | .[0]) as $trigger
| ($trigger | entry_message) as $triggerMsg
| {
status: "unknown_skill",
subcode: "CLAUDE_UNKNOWN_SKILL",
message: (
if ($triggerMsg | length) > 0 then
"Claude plugin command unavailable: " + $triggerMsg
else
"Claude plugin command unavailable: Unknown skill"
end
| clamp_message
)
}
elif any($entries[]; rate_limit_signal) then
([$entries[] | select(rate_limit_signal)] | .[0]) as $trigger
| ($trigger | entry_message) as $triggerMsg
| {
status: "claude_rate_limit",
subcode: "CLAUDE_RATE_LIMIT",
message: (
if ($triggerMsg | length) > 0 then
"Claude rate limit reached: " + $triggerMsg
elif ($rateMessage | length) > 0 then
$rateMessage
else
"Claude rate limit reached. Wait for the limit to reset, then re-run /code:code."
end
| clamp_message
)
}
elif any($entries[]; context_limit_signal) then
([$entries[] | select(context_limit_signal)] | .[0]) as $trigger
| ($trigger | entry_message) as $triggerMsg
| {
status: "context_limit",
subcode: "CLAUDE_CONTEXT_LIMIT",
message: (
if ($triggerMsg | length) > 0 then
"Claude context limit reached: " + $triggerMsg
else
"Claude context limit reached. Start a fresh run with a smaller prompt or reduced context."
end
| clamp_message
)
}
elif any($entries[]; auth_challenge_signal) then
([$entries[] | select(auth_challenge_signal)] | .[0]) as $trigger
| ($trigger | entry_message) as $triggerMsg
| {
status: "claude_auth_error",
subcode: "CLAUDE_AUTH_CHALLENGE",
message: (
if ($triggerMsg | length) > 0 then
"Claude authentication or account challenge: " + $triggerMsg
else
"Claude authentication or account challenge detected. Re-authenticate Claude, then re-run /code:code."
end
| clamp_message
)
}
else
{}
end
' "$output_file" 2>/dev/null || echo '{}')
if [[ "${DEBUG:-}" == "1" ]] && [[ "$detection" != "{}" ]]; then
echo "[detect_claude_terminal_failure] detection=$detection" >&2
fi
if [[ "$detection" != "{}" ]]; then
echo "$detection"
return
fi
fi
if [[ -s "$stderr_file" ]]; then
local stderr_text
stderr_text=$(tr '\n' ' ' < "$stderr_file" | sed 's/[[:space:]][[:space:]]*/ /g' | cut -c 1-800)
if grep -qiE "you.?ve hit your limit|usage limit|rate[_ -]?limit|rate limit reached" "$stderr_file"; then
jq -n -c --arg message "Claude rate limit reached: ${stderr_text:-Wait for the limit to reset, then re-run /code:code.}" \
'{status:"claude_rate_limit",subcode:"CLAUDE_RATE_LIMIT",message:$message}'
return
fi
if grep -qiE "prompt is too long|exceed context limit|context limit reached|conversation too long" "$stderr_file"; then
jq -n -c --arg message "Claude context limit reached: ${stderr_text:-Start a fresh run with a smaller prompt or reduced context.}" \
'{status:"context_limit",subcode:"CLAUDE_CONTEXT_LIMIT",message:$message}'
return
fi
if grep -qiE "authentication_error|invalid bearer token|billing_error|permission_error|overloaded_error|api overloaded|unauthorized|token.*expired|not authenticated|please log in|login required" "$stderr_file"; then
jq -n -c --arg message "Claude authentication or account challenge: ${stderr_text:-Re-authenticate Claude, then re-run /code:code.}" \
'{status:"claude_auth_error",subcode:"CLAUDE_AUTH_CHALLENGE",message:$message}'
return
fi
fi
echo '{}'
}
# Terminal known Claude failures are intentionally user-visible: preserve the
# output sidecar for Desktop, release local state, then write the signed marker.
handle_claude_terminal_failure() {
local workdir="$1"
local iteration="$2"
local status="$3"
local subcode="$4"
local message="$5"
echo -e "\n${RED}Claude terminal failure detected: $message${NC}" >&2
log_progress "Claude terminal failure [$subcode]: $message"
write_runs_log_entry "$workdir" "$iteration" "$status" "plan_execute"
rename_output_on_exit
release_lock "$workdir"
rm -f "$STATE_FILE"
fail_loop_user_visible "RUNNER_ERROR" "$subcode" "$message"
}
# Check for jq dependency (required for learning system)
check_jq_dependency() {
if ! command -v jq &> /dev/null; then
echo -e "${RED}Error: jq is required for the learning system but not found${NC}"
echo "Install with: brew install jq (macOS) or apt-get install jq (Linux)"
exit 1
fi
}
# Generate unique run ID
generate_run_id() {
local timestamp=$(date +%Y%m%d-%H%M%S)
local random_suffix=$(head -c 4 /dev/urandom | xxd -p)
echo "${timestamp}-${random_suffix}"
}
# Acquire lock file for concurrent protection
acquire_lock() {
local workdir="$1"
local lock_file="$workdir/$LOCK_FILE"
local lock_dir=$(dirname "$lock_file")
mkdir -p "$lock_dir"
if [[ -f "$lock_file" ]]; then
local lock_content=$(cat "$lock_file" 2>/dev/null || echo "")
local lock_age_seconds=0
if [[ "$(uname)" == "Darwin" ]]; then
lock_age_seconds=$(( $(date +%s) - $(stat -f %m "$lock_file" 2>/dev/null || echo "$(date +%s)") ))
else
lock_age_seconds=$(( $(date +%s) - $(stat -c %Y "$lock_file" 2>/dev/null || echo "$(date +%s)") ))
fi
# Consider lock stale after 4 hours
local stale_seconds=$((4 * 3600))
if [[ $lock_age_seconds -lt $stale_seconds ]]; then
echo -e "${RED}Error: Another ClosedLoop loop is already running${NC}"
echo "Lock file: $lock_file"
echo "Lock content: $lock_content"
echo "Lock age: $((lock_age_seconds / 60)) minutes"
echo ""
echo "If you're sure no other loop is running, remove the lock file:"
echo " rm $lock_file"
exit 1
else
echo -e "${YELLOW}Warning: Found stale lock file ($((lock_age_seconds / 3600))h old), removing${NC}"
rm -f "$lock_file"
fi
fi
# Create lock file with run info
echo "run_id=$RUN_ID|pid=$$|started=$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$lock_file"
log_progress "Lock acquired: $lock_file"
}
# Release lock file
release_lock() {
local workdir="$1"
local lock_file="$workdir/$LOCK_FILE"
if [[ -f "$lock_file" ]]; then
rm -f "$lock_file"
log_progress "Lock released: $lock_file"
fi
}
# Bootstrap run-specific learnings directories
bootstrap_learnings() {
local workdir="$1"
if [[ "${SELF_LEARNING:-false}" != "true" ]]; then
return
fi
local bootstrap_script="$SCRIPTS_DIR/bootstrap-learnings.sh"
if [[ ! -d "$workdir/.learnings" ]]; then
echo -e "${BLUE}Initializing learning system...${NC}"
# Use bootstrap script to create directory structure
if [[ -x "$bootstrap_script" ]]; then
"$bootstrap_script" "$workdir/.learnings"
else
# Minimal bootstrap if script not available
mkdir -p "$workdir/.learnings/pending"
mkdir -p "$workdir/.learnings/sessions"
echo -e "${GREEN}Created minimal .learnings structure${NC}"
fi
# Copy org learnings from .closedloop-ai/learnings/ if available (overwrite defaults)
local org_learnings_dir=""
local workdir_state_dir="$(dirname "$workdir")"
# Check project root first, then the workdir-adjacent .closedloop-ai state directory.
if [[ -d "$CLOSEDLOOP_STATE_DIR/learnings" ]]; then
org_learnings_dir="$CLOSEDLOOP_STATE_DIR/learnings"
elif [[ "$(basename "$workdir_state_dir")" == "$CLOSEDLOOP_STATE_DIR" ]] && [[ -d "$workdir_state_dir/learnings" ]]; then
org_learnings_dir="$workdir_state_dir/learnings"
fi
if [[ -n "$org_learnings_dir" ]]; then
echo -e "${BLUE}Copying org learnings from $org_learnings_dir${NC}"
[[ -f "$org_learnings_dir/org-patterns.toon" ]] && cp "$org_learnings_dir/org-patterns.toon" "$workdir/.learnings/"
[[ -f "$org_learnings_dir/goal.yaml" ]] && cp "$org_learnings_dir/goal.yaml" "$workdir/.learnings/"
[[ -f "$org_learnings_dir/retention.yaml" ]] && cp "$org_learnings_dir/retention.yaml" "$workdir/.learnings/"
fi
fi
}
# Load goal configuration
load_goal_config() {
local workdir="$1"
local goal_file="$workdir/.learnings/goal.yaml"
if [[ -f "$goal_file" ]] && command -v python3 &> /dev/null; then
# Extract active goal using Python
local active_goal=$(python3 -c "
import yaml
try:
with open('$goal_file') as f:
config = yaml.safe_load(f) or {}
print(config.get('active_goal', ''))
except:
pass
" 2>/dev/null)
if [[ -n "$active_goal" ]]; then
export CLOSEDLOOP_ACTIVE_GOAL="$active_goal"
echo -e "Active goal: ${GREEN}$active_goal${NC}"
fi
fi
}
# Capture git SHA at start for citation verification
capture_start_sha() {
local workdir="$1"
if [[ -d "$workdir/.git" ]] || git -C "$workdir" rev-parse --git-dir &> /dev/null 2>&1; then
START_SHA=$(git -C "$workdir" rev-parse HEAD 2>/dev/null || echo "")
if [[ -n "$START_SHA" ]]; then
log_progress "Start SHA: $START_SHA"
fi
fi
}
# Create iteration marker file
create_iteration_marker() {
local workdir="$1"
local iteration="$2"
local session_dir="$workdir/.learnings/sessions/run-$RUN_ID"
mkdir -p "$session_dir"
echo "$iteration" > "$session_dir/current-iteration"
}
sanitize_runs_log_field() {
local raw="$1"
raw="${raw//$'\r'/ }"
raw="${raw//$'\n'/ }"
raw="${raw//|/_}"
echo "$raw"
}
extract_claude_session_id() {
local output_file="$1"
if [[ ! -s "$output_file" ]]; then
return 0
fi
jq -r '
[
.session_id?,
.sessionId?,
.message.session_id?,
.message.sessionId?,
.item.session_id?,
.item.sessionId?
]
| map(select(type == "string" and length > 0))
| .[0] // empty
| select(length > 0)
' "$output_file" 2>/dev/null | tail -n 1
}
record_claude_session_id() {
local workdir="$1"
local command="$2"
local session_id="$3"
if [[ -z "$session_id" ]]; then
return 0
fi
LAST_CLAUDE_COMMAND="$command"
LAST_CLAUDE_SESSION_ID="$session_id"
export CLOSEDLOOP_SESSION_ID="$session_id"
# Desktop finalization reads one session-id.txt. Keep that file scoped to the
# primary plan/execute Claude session so post-loop review/fix sessions do not
# overwrite the operation-level correlation id.
if [[ "$command" == "plan_execute" ]]; then
printf '%s\n' "$session_id" > "$workdir/session-id.txt"
fi
}
# Write runs.log entry for goal evaluation and session correlation.
#
# Format:
# run_id|timestamp|goal|iteration|status|command|last_session_id[|successful_iterations]
# The first five fields are the legacy contract; append-only fields keep older
# self-learning readers compatible while allowing command-scoped session lookup.
# The optional 8th field (successful_iterations) is appended only when provided.
write_runs_log_entry() {
local workdir="$1"
local iteration="$2"
local status="${3:-in_progress}"
local command
local session_id
local explicit_session_id=false
if [[ $# -ge 4 ]]; then
command="$4"
else
# Default precedence: LAST_CLAUDE_COMMAND (set after the first claude
# invocation, accurate for review/fix sub-steps) → CLOSEDLOOP_COMMAND
# (set by main() from parent-process pre-set or --prompt) → plan_execute.
# `self_learning` is no longer used as a default — it overcounted on
# fresh-start Loops before any review step had run (FEA-936 fix 1).
command="${LAST_CLAUDE_COMMAND:-${CLOSEDLOOP_COMMAND:-plan_execute}}"
fi
if [[ $# -ge 5 ]]; then
session_id="$5"
explicit_session_id=true
else
session_id="${LAST_CLAUDE_SESSION_ID:-}"
fi
local success_count=""
if [[ $# -ge 6 ]]; then
success_count="$6"
fi
local runs_log="$workdir/runs.log"
local timestamp
timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
if [[ "$explicit_session_id" == "false" && -z "$session_id" && -f "$workdir/session-id.txt" ]]; then
session_id=$(tr -d '\r\n' < "$workdir/session-id.txt" 2>/dev/null || true)
fi
command=$(sanitize_runs_log_field "$command")
session_id=$(sanitize_runs_log_field "$session_id")
mkdir -p "$(dirname "$runs_log")"
local entry="$RUN_ID|$timestamp|${CLOSEDLOOP_ACTIVE_GOAL:-reduce-failures}|$iteration|$status|$command|$session_id"
if [[ -n "$success_count" ]]; then
entry="$entry|$success_count"
fi
echo "$entry" >> "$runs_log"
}
# Post-iteration processing: enrichment pipeline, learning capture, citation verification, success rates
post_iteration_processing() {
local workdir="$1"
local iteration="$2"
log_progress "Starting post-iteration processing for iteration $iteration"
# Export environment variables for process-learnings command
export CLOSEDLOOP_WORKDIR="$workdir"
export CLOSEDLOOP_RUN_ID="$RUN_ID"
export CLOSEDLOOP_ITERATION="$iteration"
local tools_dir="$SCRIPTS_DIR/../tools/python"
local sl_tools_dir="$SCRIPTS_DIR/../../self-learning/tools/python"
# Step 1: Generate changed-files.json from git diff
if [[ -n "$START_SHA" ]]; then
echo -e "${BLUE}[1/10] Generating changed-files.json...${NC}"
log_progress "Step 1: Generating changed-files.json"
mkdir -p "$workdir/.learnings"
run_timed_step 1 "changed_files" bash -c "
{ git diff --name-only '$START_SHA' HEAD 2>/dev/null; \
git diff --name-only HEAD 2>/dev/null; \
git diff --name-only --cached 2>/dev/null; } \
| sort -u \
| python3 -c \"import json,sys; print(json.dumps([l.strip() for l in sys.stdin if l.strip()]))\" \
> '$workdir/.learnings/changed-files.json'
" || log_progress "Step 1: changed-files.json generation encountered errors (continuing)"
else
emit_skipped_step 1 "changed_files"
fi
if [[ "${SELF_LEARNING:-false}" == "true" ]]; then
# Step 2: pattern_relevance.py (score patterns -> relevance-scores.json)
local relevance_script="$sl_tools_dir/pattern_relevance.py"
if [[ -f "$relevance_script" ]] && [[ -f "$workdir/.learnings/changed-files.json" ]]; then
echo -e "${BLUE}[2/10] Computing pattern relevance...${NC}"
log_progress "Step 2: Running pattern_relevance.py"
if run_timed_step 2 "pattern_relevance" bash -c "
python3 '$relevance_script' \
--workdir '$workdir' \
--changed-files '$workdir/.learnings/changed-files.json' \
--output '$workdir/.learnings/relevance-scores.json' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 2: Pattern relevance completed"
else
log_progress "Step 2: pattern_relevance.py encountered errors (continuing)"
fi
else
emit_skipped_step 2 "pattern_relevance"
fi
# Step 3: merge_relevance.py (append relevance to outcomes.log)
local merge_rel_script="$sl_tools_dir/merge_relevance.py"
if [[ -f "$merge_rel_script" ]] && [[ -f "$workdir/.learnings/relevance-scores.json" ]]; then
echo -e "${BLUE}[3/10] Merging relevance scores...${NC}"
log_progress "Step 3: Running merge_relevance.py"
if run_timed_step 3 "merge_relevance" bash -c "
python3 '$merge_rel_script' \
--workdir '$workdir' \
--relevance-file '$workdir/.learnings/relevance-scores.json' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 3: Relevance merge completed"
else
log_progress "Step 3: merge_relevance.py encountered errors (continuing)"
fi
else
emit_skipped_step 3 "merge_relevance"
fi
# Step 4: evaluate_goal.py (evaluate goal -> goal-outcome.json)
local eval_script="$sl_tools_dir/evaluate_goal.py"
if [[ -f "$eval_script" ]]; then
echo -e "${BLUE}[4/10] Evaluating goal...${NC}"
log_progress "Step 4: Running evaluate_goal.py"
if run_timed_step 4 "evaluate_goal" bash -c "
python3 '$eval_script' \
--workdir '$workdir' \
--run-id '$RUN_ID' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 4: Goal evaluation completed"
else
log_progress "Step 4: evaluate_goal.py encountered errors (continuing)"
fi
else
emit_skipped_step 4 "evaluate_goal"
fi
# Step 5: merge_goal_outcome.py (append goal data to outcomes.log)
local merge_goal_script="$sl_tools_dir/merge_goal_outcome.py"
if [[ -f "$merge_goal_script" ]] && [[ -f "$workdir/.learnings/goal-outcome.json" ]]; then
echo -e "${BLUE}[5/10] Merging goal outcome...${NC}"
log_progress "Step 5: Running merge_goal_outcome.py"
if run_timed_step 5 "merge_goal_outcome" bash -c "
python3 '$merge_goal_script' \
--workdir '$workdir' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 5: Goal outcome merge completed"
else
log_progress "Step 5: merge_goal_outcome.py encountered errors (continuing)"
fi
else
emit_skipped_step 5 "merge_goal_outcome"
fi
# Step 6: verify_citations.py (mark |unverified in outcomes.log)
if [[ -n "$START_SHA" ]]; then
local verify_script="$sl_tools_dir/verify_citations.py"
if [[ -f "$verify_script" ]]; then
echo -e "${BLUE}[6/10] Verifying citations...${NC}"
log_progress "Step 6: Running verify_citations.py"
if run_timed_step 6 "verify_citations" bash -c "
python3 '$verify_script' --start-sha '$START_SHA' --workdir '$workdir' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 6: Citation verification passed"
else
log_progress "Step 6: Citation verification found issues (see failures.md)"
fi
else
emit_skipped_step 6 "verify_citations"
fi
else
emit_skipped_step 6 "verify_citations"
fi
# Step 7: Merge build-validator results into outcomes.log
local merge_build_script="$sl_tools_dir/merge_build_result.py"
if [[ -f "$merge_build_script" ]] && [[ -f "$workdir/.learnings/build-result.json" ]]; then
echo -e "${BLUE}[7/10] Merging build-validator results...${NC}"
log_progress "Step 7: Running merge_build_result.py"
if run_timed_step 7 "merge_build_result" bash -c "
python3 '$merge_build_script' --workdir '$workdir' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 7: Build result merge completed"
else
log_progress "Step 7: merge_build_result.py encountered errors (continuing)"
fi
else
emit_skipped_step 7 "merge_build_result"
fi
# Step 8: Process pending learnings (LLM classifies and aggregates into org-patterns.toon)
local pending_dir="$workdir/.learnings/pending"
if [[ -d "$pending_dir" ]] && [[ -n "$(ls -A "$pending_dir"/*.json 2>/dev/null)" ]]; then
echo -e "${BLUE}[8/10] Processing pending learnings...${NC}"
log_progress "Step 8: Running process-learnings"
if run_timed_step 8 "process_learnings" bash -c "
\"$CLAUDE\" -p 'Run /self-learning:process-learnings $workdir' \
--allowed-tools=Bash,Grep,Glob,Read,Write \
--max-turns 100 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 8: Learning processing completed"
else
log_progress "Step 8: Learning processing encountered errors (continuing)"
fi
else
emit_skipped_step 8 "process_learnings"
fi
# Step 8.5: Write merge-result.json → org-patterns.toon (deterministic)
local merge_script="$sl_tools_dir/write_merged_patterns.py"
local merge_result="$workdir/.learnings/merge-result.json"
if [[ -f "$merge_result" ]] && [[ -f "$merge_script" ]]; then
echo -e "${BLUE}[8.5/10] Writing merged patterns to TOON...${NC}"
log_progress "Step 8.5: Running write_merged_patterns.py"
if run_timed_step 8.5 "write_merged_patterns" bash -c "
python3 '$merge_script' --merge-result '$merge_result' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 8.5: TOON write completed"
# Cleanup session files only after successful TOON write
rm -rf "$workdir/.learnings/sessions/run-"* 2>/dev/null || true
else
log_progress "Step 8.5: TOON write failed — session files preserved for retry"
fi
else
emit_skipped_step 8.5 "write_merged_patterns"
fi
# Step 9: compute_success_rates.py (deterministic rates -> update org-patterns.toon)
local rates_script="$sl_tools_dir/compute_success_rates.py"
if [[ -f "$rates_script" ]]; then
echo -e "${BLUE}[9/10] Computing success rates...${NC}"
log_progress "Step 9: Running compute_success_rates.py"
if run_timed_step 9 "compute_success_rates" bash -c "
python3 '$rates_script' --workdir '$workdir' 2>&1 | tee -a '$PROGRESS_LOG'
"; then
log_progress "Step 9: Success rate computation completed"
else
log_progress "Step 9: compute_success_rates.py encountered errors (continuing)"
fi
else
emit_skipped_step 9 "compute_success_rates"
fi
# Step 10: Export closedloop learnings to global location
if [[ -f "$workdir/.learnings/pending-closedloop.json" ]]; then
echo -e "${BLUE}[10/10] Exporting closedloop learnings...${NC}"
log_progress "Step 10: Running export-closedloop-learnings"
if run_timed_step 10 "export_closedloop_learnings" bash -c "
\"$CLAUDE\" -p '/self-learning:export-closedloop-learnings $workdir' \
--allowed-tools=Bash,Grep,Glob,Read,Write \