Skip to content

Instantly share code, notes, and snippets.

@Arsenalist
Created September 4, 2026 13:17
Show Gist options
  • Select an option

  • Save Arsenalist/de276782d29e0d3e44c829bda318927e to your computer and use it in GitHub Desktop.

Select an option

Save Arsenalist/de276782d29e0d3e44c829bda318927e to your computer and use it in GitHub Desktop.
Bounded multi-model loop for stabilizing an asynchronous Elixir test suite
#!/usr/bin/env bash
# Install at scripts/stabilize_test_suite.sh and run from a clean default branch.
# Requires Claude Code, Codex CLI, GitHub CLI, jq, and mise.
set -Eeuo pipefail
readonly REQUIRED_PASSES=3 MAX_FULL_RUNS=20 MAX_REVIEW_ROUNDS=5
readonly MAX_DIGEST_BYTES=65536 MAX_PATCH_BYTES=204800
readonly ORCHESTRATOR="scripts/stabilize_test_suite.sh"
readonly PR_TITLE="fix(test): stabilize flaky test suite"
BASE_BRANCH="" WORK_BRANCH="" LOG_DIR="" REVIEW_SCHEMA=""
FULL_RUNS=0 PASS_STREAK=0 FIXES_IMPLEMENTED=0
ENV_HASH="" ORCHESTRATOR_HASH=""
die() { printf 'error: %s\n' "$*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "missing command: $1"; }
env_hash() { git hash-object .env .env.test | tr '\n' ' '; }
assert_env_unchanged() {
[[ "$(env_hash)" == "$ENV_HASH" ]] || die ".env or .env.test changed"
}
assert_orchestrator_unchanged() {
[[ "$(git hash-object "$ORCHESTRATOR")" == "$ORCHESTRATOR_HASH" ]] ||
die "agent edited orchestrator: $ORCHESTRATOR"
}
diff_hash() {
git add -N -- .
git diff --binary HEAD | git hash-object --stdin
}
run_tests() {
local log_file="$1"
shift
printf '\n==> source .env && source .env.test && mise test %s\n' "$*"
set +e
(
# shellcheck disable=SC1091
source .env && source .env.test && mise test "$@"
) 2>&1 | tee "$log_file"
local status=${PIPESTATUS[0]}
set -e
return "$status"
}
append_failure_summary() {
local label="$1" log_file="$2"
printf '\n===== %s =====\n' "$label"
printf 'Log: %s (%s bytes, %s lines)\n' \
"$log_file" "$(wc -c <"$log_file" | tr -d ' ')" \
"$(wc -l <"$log_file" | tr -d ' ')"
printf '\n-- Failure index --\n'
grep -En \
'^[[:space:]]*[0-9]+\)[[:space:]]|test/[^:[:space:]]+\.exs:[0-9]+|^Finished in|^[[:space:]]*[0-9]+ tests?, [0-9]+ failures?|^Randomized with seed' \
"$log_file" | head -n 240 || true
printf '\n-- Numbered ExUnit failures --\n'
awk '
function starts_failure(line) {
return line ~ /^[[:space:]]*[0-9]+\)[[:space:]]/
}
starts_failure($0) {
failures += 1; printing = failures <= 10; lines = 0
}
printing && lines < 120 { print; lines += 1; next }
printing && lines == 120 { print "[failure block truncated]"; lines += 1 }
END {
if (failures == 0) print "[no numbered failure; inspect indexed lines]"
}
' "$log_file"
printf '\n-- Final status --\n'
grep -E \
'^Finished in|^[[:space:]]*[0-9]+ tests?, [0-9]+ failures?|^Randomized with seed' \
"$log_file" | tail -n 20 || tail -n 80 "$log_file"
}
build_digest() {
local full_log="$1" failed_log="$2" digest="$3" raw="$3.raw"
{
printf 'Bounded ExUnit digest. Full logs remain at paths below.\n'
append_failure_summary "FULL SUITE" "$full_log"
append_failure_summary "MISE TEST --FAILED" "$failed_log"
} >"$raw"
head -c "$MAX_DIGEST_BYTES" "$raw" >"$digest"
if [[ "$(wc -c <"$raw" | tr -d ' ')" -gt "$MAX_DIGEST_BYTES" ]]; then
printf '\n[digest capped at %d bytes]\n' "$MAX_DIGEST_BYTES" >>"$digest"
fi
rm -f -- "$raw"
}
create_fix_branch() {
[[ -n "$WORK_BRANCH" ]] && return
[[ -z "$(git status --porcelain)" ]] || die "tests changed working tree"
WORK_BRANCH="codex/stabilize-tests-$(date -u +%Y%m%d-%H%M%S)"
git switch -c "$WORK_BRANCH"
}
run_claude() {
local prompt_file="$1" output_file="$2"
claude --print \
--permission-mode acceptEdits \
--allowedTools "Bash,Edit,Read,Glob,Grep" \
--disallowedTools \
"Bash(git commit *)" "Bash(git push *)" "Bash(git reset *)" \
"Bash(git clean *)" "Bash(git checkout *)" "Bash(git switch *)" \
"Bash(gh *)" \
--output-format text <"$prompt_file" | tee "$output_file"
}
ask_claude_to_repair() {
local digest="$1"
local prompt="$LOG_DIR/claude-repair-prompt-$FULL_RUNS.txt"
local output="$LOG_DIR/claude-repair-output-$FULL_RUNS.txt"
local before
before="$(diff_hash)"
cat >"$prompt" <<EOF
Fix observed failures from this Elixir/Phoenix test suite.
Read bounded digest first: $digest
Do not read full logs wholesale. ExUnit output is asynchronous and may be interleaved. Correlate numbered failure blocks, test names, file:line anchors, exceptions, stacktraces, captured logs, and seed. Read small log ranges only when digest points to them. A passing focused rerun means likely flake, not success.
Implement smallest root-cause fix. Preserve async execution. Do not add sleeps, retries, skipped tests, weaker assertions, or async: false. Follow CLAUDE.md and project conventions for Ecto Sandbox, process ownership, Mimic, factories, and global state. Never edit $ORCHESTRATOR, .env, or .env.test. Do not commit, switch branches, push, or create a PR.
Run focused verification with:
source .env && source .env.test && mise test --failed
If failure is infrastructure-only or no safe fix exists, make no edits and explain why.
EOF
run_claude "$prompt" "$output" || die "Claude repair failed"
assert_env_unchanged
assert_orchestrator_unchanged
[[ "$(diff_hash)" != "$before" ]] || die "Claude changed nothing"
}
write_review_schema() {
cat >"$REVIEW_SCHEMA" <<'EOF'
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"additionalProperties": false,
"properties": {
"verdict": {"type": "string", "enum": ["ok", "changes_requested"]},
"findings": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"severity": {
"type": "string",
"enum": ["critical", "high", "medium", "low"]
},
"file": {"type": "string"},
"line": {"type": ["integer", "null"], "minimum": 1},
"message": {"type": "string"}
},
"required": ["severity", "file", "line", "message"]
}
}
},
"required": ["verdict", "findings"]
}
EOF
}
run_codex_review() {
local round="$1"
local patch="$LOG_DIR/review-target-$round.diff"
local prompt="$LOG_DIR/codex-review-prompt-$round.txt"
local events="$LOG_DIR/codex-review-events-$round.jsonl"
local review="$LOG_DIR/codex-review-$round.json"
git diff --no-ext-diff --unified=80 HEAD -- . \
":(exclude)$ORCHESTRATOR" >"$patch"
[[ -s "$patch" ]] || die "no repair patch available for review"
[[ "$(wc -c <"$patch" | tr -d ' ')" -le "$MAX_PATCH_BYTES" ]] ||
die "review patch exceeds $MAX_PATCH_BYTES bytes; split repair scope"
{
cat <<EOF
Review only patch below. It contains automated fixes for observed ExUnit failures. Do not edit files, run git commands, or review files absent from patch.
Check Elixir-specific correctness: process and mailbox ordering, linked process lifetime, ExUnit async safety, global state, Ecto SQL Sandbox ownership, Mimic expectations, deterministic factories, time and seed dependence, resource cleanup, and precise assertions. Reject sleeps, retries, skipped tests, weaker assertions, and unjustified async: false. Check production behavior when patch touches production code.
Return "changes_requested" for actionable correctness, reliability, or maintainability findings. Return "ok" only with empty findings. Output JSON matching supplied schema with no Markdown.
--- BEGIN PATCH ---
EOF
cat "$patch"
printf '\n--- END PATCH ---\n'
} >"$prompt"
codex exec \
--cd "$LOG_DIR" \
--skip-git-repo-check \
--ephemeral \
--sandbox read-only \
--output-schema "$REVIEW_SCHEMA" \
--output-last-message "$review" \
--json - <"$prompt" >"$events" 2>&1 ||
die "Codex review failed; see $events"
jq -e --arg excluded "$ORCHESTRATOR" '
((.verdict == "ok" and (.findings | length) == 0) or
(.verdict == "changes_requested" and (.findings | length) > 0)) and
all(.findings[]; (.file | sub("^\\./"; "")) != $excluded)
' "$review" >/dev/null || die "invalid Codex review: $review"
printf '%s\n' "$review"
}
apply_review_findings() {
local round="$1" review="$2"
local prompt="$LOG_DIR/claude-review-fix-prompt-$round.txt"
local output="$LOG_DIR/claude-review-fix-output-$round.txt"
local before
before="$(diff_hash)"
cat >"$prompt" <<EOF
Apply valid findings from structured Elixir review: $review
Edit only files named in findings. Never edit $ORCHESTRATOR, .env, or .env.test. Follow CLAUDE.md. Do not weaken tests, add sleeps or retries, change async mode without demonstrated global conflict, commit, switch branches, push, or create a PR.
Run focused verification with:
source .env && source .env.test && mise test --failed
EOF
run_claude "$prompt" "$output" || die "Claude review fix failed"
assert_env_unchanged
assert_orchestrator_unchanged
[[ "$(diff_hash)" != "$before" ]] || die "review requested changes but none made"
}
review_until_ok() {
local round review
for ((round = 1; round <= MAX_REVIEW_ROUNDS; round += 1)); do
review="$(run_codex_review "$round")"
jq . "$review"
[[ "$(jq -r '.verdict' "$review")" == "ok" ]] && return
apply_review_findings "$round" "$review"
done
die "Codex still requested changes after $MAX_REVIEW_ROUNDS rounds"
}
repair_failure() {
local full_log="$1"
local failed_log="$LOG_DIR/failed-rerun-$FULL_RUNS.log"
local digest="$LOG_DIR/failure-digest-$FULL_RUNS.txt"
printf 'Rerunning failed tests.\n'
if run_tests "$failed_log" --failed; then
printf 'Focused rerun passed; treating original failure as a flake.\n'
else
printf 'Focused rerun reproduced failure.\n'
fi
build_digest "$full_log" "$failed_log" "$digest"
create_fix_branch
ask_claude_to_repair "$digest"
FIXES_IMPLEMENTED=1
review_until_ok
}
create_pull_request() {
local body="$LOG_DIR/pr-body.md"
cat >"$body" <<EOF
## Summary
- fix observed ExUnit failure or flake
- apply independent Elixir review findings
- verify $REQUIRED_PASSES consecutive full-suite passes
## Validation
- \`source .env && source .env.test && mise test\`
- full-suite runs: $FULL_RUNS/$MAX_FULL_RUNS
EOF
git add -A
git diff --cached --check
git commit -m "$PR_TITLE"
git push --set-upstream origin "$WORK_BRANCH"
gh pr create --base "$BASE_BRANCH" --head "$WORK_BRANCH" \
--title "$PR_TITLE" --body-file "$body"
}
prepare_repository() {
local current_branch run_id
cd "$(git rev-parse --show-toplevel)"
[[ -f .env && -f .env.test ]] || die ".env and .env.test are required"
git ls-files --error-unmatch "$ORCHESTRATOR" >/dev/null 2>&1 ||
die "install this script at $ORCHESTRATOR"
[[ -z "$(git status --porcelain)" ]] || die "working tree must be clean"
BASE_BRANCH="$(gh repo view --json defaultBranchRef --jq '.defaultBranchRef.name')"
current_branch="$(git branch --show-current)"
[[ "$current_branch" == "$BASE_BRANCH" ]] || die "run from $BASE_BRANCH"
git fetch --quiet origin "$BASE_BRANCH"
[[ "$(git rev-parse HEAD)" == "$(git rev-parse "origin/$BASE_BRANCH")" ]] ||
die "$BASE_BRANCH must match origin/$BASE_BRANCH"
run_id="$(date -u +%Y%m%d-%H%M%S)"
LOG_DIR="$(git rev-parse --git-dir)/test-stabilizer/$run_id"
mkdir -p "$LOG_DIR"
REVIEW_SCHEMA="$LOG_DIR/codex-review.schema.json"
write_review_schema
ENV_HASH="$(env_hash)"
ORCHESTRATOR_HASH="$(git hash-object "$ORCHESTRATOR")"
printf 'Logs: %s\n' "$LOG_DIR"
}
main() {
local command full_log
(($# == 0)) || die "usage: $0"
for command in awk claude codex gh git grep head jq mise tail tee tr wc; do
need "$command"
done
prepare_repository
for ((FULL_RUNS = 1; FULL_RUNS <= MAX_FULL_RUNS; FULL_RUNS += 1)); do
full_log="$LOG_DIR/full-suite-$FULL_RUNS.log"
printf '\n==> Full-suite run %d/%d; clean streak %d/%d\n' \
"$FULL_RUNS" "$MAX_FULL_RUNS" "$PASS_STREAK" "$REQUIRED_PASSES"
if run_tests "$full_log"; then
((PASS_STREAK += 1))
if ((PASS_STREAK == REQUIRED_PASSES)); then
if ((FIXES_IMPLEMENTED == 1)); then
create_pull_request
else
printf 'Three clean runs; no changes and no PR.\n'
fi
return
fi
continue
fi
PASS_STREAK=0
printf 'Full suite failed; clean streak reset.\n'
repair_failure "$full_log"
done
die "suite did not pass $REQUIRED_PASSES times within $MAX_FULL_RUNS runs"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment