Files
2026-08-16 19:10:31 +02:00

281 lines
15 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
set -uo pipefail
MAX_RETRIES="${MAX_RETRIES:-3}"
DISPATCH_TTL="${DISPATCH_TTL:-3000}"
PYTHON="${PYTHON:-python3}"
STATE_FILE=".build_state"
LOCK_DIR=".orchestrate.lock"
ROOT_BASHPID="$BASHPID"
cleanup() {
if [[ "$BASHPID" == "$ROOT_BASHPID" ]]; then
rm -rf "$LOCK_DIR"
fi
}
acquire_lock() {
if mkdir "$LOCK_DIR" 2>/dev/null; then
printf '%s\n' "$$" > "$LOCK_DIR/pid"
return
fi
local owner=""
[[ -f "$LOCK_DIR/pid" ]] && read -r owner < "$LOCK_DIR/pid"
if [[ -n "$owner" ]] && kill -0 "$owner" 2>/dev/null; then
echo "Another orchestrate.sh is already running (PID $owner)." >&2
exit 1
fi
rm -rf "$LOCK_DIR"
mkdir "$LOCK_DIR"
printf '%s\n' "$$" > "$LOCK_DIR/pid"
}
trap cleanup EXIT INT TERM
acquire_lock
if ! command -v pi >/dev/null 2>&1; then
echo "pi is not installed or not on PATH." >&2
exit 1
fi
if ! command -v "$PYTHON" >/dev/null 2>&1; then
echo "$PYTHON is not installed or not on PATH." >&2
exit 1
fi
TIMEOUT_BIN=""
if command -v timeout >/dev/null 2>&1; then
TIMEOUT_BIN="timeout"
elif command -v gtimeout >/dev/null 2>&1; then
TIMEOUT_BIN="gtimeout"
fi
dispatch() {
local label="$1"
local prompt="$2"
local prompt_file
prompt_file="$(mktemp "${TMPDIR:-/tmp}/underdepths-prompt.XXXXXX")"
printf '%s\n' "$prompt" > "$prompt_file"
echo "==> Dispatch: $label"
if [[ -n "$TIMEOUT_BIN" ]]; then
"$TIMEOUT_BIN" --signal=TERM --kill-after=30s "${DISPATCH_TTL}s" pi -p "$(<"$prompt_file")"
local status=$?
rm -f "$prompt_file"
return "$status"
fi
"$PYTHON" - "$DISPATCH_TTL" "$prompt_file" <<'PY'
import os
import signal
import subprocess
import sys
ttl = int(sys.argv[1])
with open(sys.argv[2], encoding="utf-8") as handle:
prompt = handle.read()
process = subprocess.Popen(["pi", "-p", prompt], start_new_session=True)
try:
raise SystemExit(process.wait(timeout=ttl))
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=30)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
print(f"pi dispatch exceeded {ttl}s and was killed", file=sys.stderr)
raise SystemExit(124)
PY
local status=$?
rm -f "$prompt_file"
return "$status"
}
base_prompt() {
printf '%s' "Read AGENTS.md and plan.md completely before editing. Work only in this repository. Use the default model; do not invoke other pi sessions. Follow the existing architecture and type conventions. Implement real behavior, not stubs or TODOs. Preserve every previously passing phase. Run the relevant smoke gate before finishing."
}
build_phase_1() {
dispatch "phase 1 foundation" "$(base_prompt)
Implement Phase 1 — Foundation exactly as specified: data/constants.py, entities/entity.py, entities/player.py, entities/enemy.py, engine/map_gen.py, a minimal playable pygame main.py, package initializers as needed, and real Phase 1 checks in tests/smoke.py. Generate compact BSP maps with 8–12 non-overlapping rooms, recorded 3x3 junctions where needed, only recorded corridor carving, ordered corridor centerlines no longer than 14 movement steps, reachable rooms, and reachable stairs on floors 0–8. Generate and inspect at least five maps. Finish only when python tests/smoke.py --phase 1 passes and prints an ASCII map plus measured longest corridor section."
}
build_phase_2() {
local common
common="$(base_prompt)"
if [[ -f engine/fov.py || -f engine/pathfinding.py || -f engine/combat.py ]]; then
local resumed_status=0
[[ -f engine/fov.py ]] || dispatch "phase 2 FOV (resume)" "$common
Implement only engine/fov.py for Phase 2: genuine recursive shadowcasting across eight octants with sight radius 8, wall occlusion, visible-grid refresh, and explored-grid merge. Keep compatibility with current map/state types." || resumed_status=1
[[ -f engine/pathfinding.py ]] || dispatch "phase 2 A* (resume)" "$common
Implement only engine/pathfinding.py for Phase 2: grid A* using Manhattan distance, walls and occupied tiles as obstacles, no stacking, and a safe no-path result. Keep compatibility with current map/state types." || resumed_status=1
[[ -f engine/combat.py ]] || dispatch "phase 2 combat (resume)" "$common
Implement only engine/combat.py for Phase 2: specified clamped hit chance, armor reduction, critical hits, HP changes, and human-readable combat logging through session state. Keep compatibility with current entity/state types." || resumed_status=1
if [[ ! -f ai/behaviors.py ]]; then
dispatch "phase 2 AI and integration (resume)" "$common
Complete Phase 2 after the independent modules. Implement ai/behaviors.py and real Phase 2 smoke gates, then make python tests/smoke.py --phase 2 pass." || resumed_status=1
fi
return "$resumed_status"
fi
dispatch "phase 2 FOV" "$common
Implement only engine/fov.py for Phase 2: genuine recursive shadowcasting across eight octants with sight radius 8, wall occlusion, visible-grid refresh, and explored-grid merge. Do not edit tests/smoke.py because another worker will integrate the phase gate. Keep compatibility with current map/state types." > .orchestrator-phase2-fov.log 2>&1 &
local fov_pid=$!
dispatch "phase 2 A*" "$common
Implement only engine/pathfinding.py for Phase 2: grid A* using Manhattan distance, walls and occupied tiles as obstacles, no stacking, and a safe no-path result. Do not edit tests/smoke.py because another worker will integrate the phase gate. Keep compatibility with current map/state types." > .orchestrator-phase2-astar.log 2>&1 &
local astar_pid=$!
dispatch "phase 2 combat" "$common
Implement only engine/combat.py for Phase 2: specified clamped hit chance, armor reduction, critical hits, HP changes, and human-readable combat logging through session state. Do not edit tests/smoke.py because another worker will integrate the phase gate. Keep compatibility with current entity/state types." > .orchestrator-phase2-combat.log 2>&1 &
local combat_pid=$!
local status=0
wait "$fov_pid" || status=1
wait "$astar_pid" || status=1
wait "$combat_pid" || status=1
for log in .orchestrator-phase2-fov.log .orchestrator-phase2-astar.log .orchestrator-phase2-combat.log; do
echo "--- $log ---"
while IFS= read -r line; do echo "$line"; done < "$log"
done
dispatch "phase 2 AI and integration" "$common
Complete Phase 2 after the independent FOV, A*, and combat modules. Inspect and integrate their actual APIs, implement ai/behaviors.py with wander, chase/last-known-position, flee, ranged/kiting, phase, and split behavior support, and extend tests/smoke.py with real Phase 2 gates. Verify walled-in FOV, A* between floor tiles, 1000 combat simulations in the expected range, and an enemy chasing through a corridor. Fix integration defects you find. Finish only when python tests/smoke.py --phase 2 passes." || status=1
return "$status"
}
build_phase_3() {
local status=0
if [[ ! -f entities/item.py || ! -f data/items.py || ! -f data/enemies.py ]]; then
dispatch "phase 3a catalogs and entities" "$(base_prompt)
Implement only Phase 3 entity/catalog models: entities/item.py, data/items.py, data/enemies.py, Player inventory/equipment and XP/leveling. Include every specified item and all seven enemy definitions. Implement now; do not spend the turn writing a plan." || status=1
fi
if [[ ! -f engine/game_state.py ]]; then
dispatch "phase 3b session and floor content" "$(base_prompt)
Implement engine/game_state.py and floor content generation only. GameSession owns mutable state and creates all ten floors. Spawn exact regular enemy counts 4..20, distributed on reachable floor tiles; guarantee reachable Shoes on internal floor 1 and Bow on floor 2; build the floor-9 dragon arena with two potions and no stairs. Ensure obtainable deep gear can damage armor 8. Reuse existing catalogs/map generator. Implement immediately and run phases 1–2." || status=1
fi
dispatch "phase 3c gameplay actions" "$(base_prompt)
Complete Phase 3 gameplay actions against existing GameSession: pickup/equip/use items, potion and scroll effects, full enemy turns and death/split/boss victory handling, XP and leveling, and Bow fire using existing combat/FOV. Bow must prefer a fleeing visible target, respect range 8 and walls, spend a turn, and log no-target/miss/hit/crit/kill. Keep the API small and implement immediately." || status=1
dispatch "phase 3d smoke integration" "$(base_prompt)
Replace the Phase 3 smoke stub with real gates for enemy stats, exact density, reachable guaranteed Shoes/Bow, equipment changes, normal Bow action target preference/walls/turn/damage/kill/logs, enemy XP/level-up, split, boss arena and dragon winnability. Fix integration defects rather than weakening tests. Finish only when python tests/smoke.py --phase 3 passes and phases 1–2 still pass." || status=1
return "$status"
}
build_phase_4() {
local status=0
if "$PYTHON" tests/smoke.py --phase 4 >/dev/null 2>&1; then
return 0
fi
if [[ ! -f engine/serializers.py || ! -f engine/audio.py || ! -f engine/clock.py ]]; then
dispatch "phase 4a persistence, audio, and input clock" "$(base_prompt)
Implement only Phase 4 persistence/audio/input foundations: exact JSON save/load including all floors/equipment/timers; safe atomic file boundaries; generated mixer tones with mute and silent fallback; and real Shoes held-key polling with 180ms/75ms cadence and stop conditions. Integrate existing actions/menu state. Implement immediately." || status=1
fi
if [[ ! -f render/renderer.py ]]; then
dispatch "phase 4b pure renderer" "$(base_prompt)
Complete only the procedural renderer. Existing data/sprites.py, render/sprites.py, and render/effects.py may be partial: audit and fix them, then add render/renderer.py as pure composition. Draw distinct cached multi-color pixel art for every entity/item/equipment variant, Bow, winged Shoes, walls/floors, and a glowing stairs sprite blitted at every stairs_down. Include FOV radial lighting/explored dimming, texture/bevel/shadows, particles/shake/vignette, bordered HP/XP/log/equipment/context UI. No external assets or flat entity squares. Add a small renderer API test. Implement now." || status=1
fi
dispatch "phase 4c main loop integration" "$(base_prompt)
Finish main.py against the existing engine and render/renderer.py. Remove interim flat drawing and delegate pure rendering. Complete New Game/Continue/How to Play/Quit, show How to Play before each new game and via ?, exact G/F contextual prompts, inventory/equipment/potion/scroll overlays, real key paths for g/f/b/S/m, held-key polling, death/victory, and a bounded --headless-smoke mode for automated play. Keep pygame/audio failure headless-safe. Run phases 1–3." || status=1
dispatch "phase 4d end-to-end smoke gate" "$(base_prompt)
Replace the Phase 4 smoke stub with strong end-to-end checks: save/load structural equality including all equipment; menu/help/overlay states; real Game keydown g pickup and f descent; HeldKeyClock immediate/179/180/75ms cadence with Shoes only and every stop condition; real b key target preference/wall/turn/kill; forced audio failure and mute; renderer proof that stairs and distinct sprites are actually blitted; headless main smoke. Fix root causes. Finish only when python tests/smoke.py --phase 4 and the full suite pass." || status=1
return "$status"
}
run_gate() {
local phase="$1"
local log_file=".orchestrator-gate-${phase}.log"
"$PYTHON" tests/smoke.py --phase "$phase" > "$log_file" 2>&1
local status=$?
while IFS= read -r line; do echo "$line"; done < "$log_file"
return "$status"
}
fix_phase() {
local phase="$1"
local attempt="$2"
local gate_output
gate_output="$(<".orchestrator-gate-${phase}.log")"
dispatch "phase $phase repair $attempt" "$(base_prompt)
The Phase $phase gate failed. Diagnose the root cause, inspect every caller of code you change, and make the smallest complete fix without weakening or deleting tests. Re-run python tests/smoke.py --phase $phase until it passes.
Actual gate output:
---
$gate_output
---"
}
run_phase() {
local phase="$1"
local state="$2"
if (( state >= phase )); then
echo "==> Phase $phase already complete"
return
fi
echo "==> Building phase $phase"
"build_phase_${phase}" || echo "Initial phase $phase dispatch reported failure; running its gate against any partial work."
local repair=0
until run_gate "$phase"; do
if (( repair >= MAX_RETRIES )); then
echo "Phase $phase failed after $MAX_RETRIES repair attempts. See .orchestrator-gate-${phase}.log" >&2
exit 1
fi
repair=$((repair + 1))
fix_phase "$phase" "$repair" || true
done
printf '%s\n' "$phase" > "${STATE_FILE}.tmp"
mv "${STATE_FILE}.tmp" "$STATE_FILE"
echo "==> Phase $phase passed"
}
run_goal_backstop() {
local attempt=0
while (( attempt <= MAX_RETRIES )); do
attempt=$((attempt + 1))
dispatch "goal backstop $attempt" "$(base_prompt)
Perform the final Underdepths goal backstop. Read every checkbox in plan.md Acceptance Criteria and audit the implementation criterion by criterion. Run python tests/smoke.py and a bounded headless main.py playthrough that exercises menu/how-to-play, movement, combat, pickup, equipment, Shoes held-running/release, Bow fleeing-target fire and wall blocking, stairs descent, save/quit/reload, death, and victory. Generate multiple maps and measure rooms/corridors/reachability/enemy counts. Inspect procedural sprite definitions and the actual renderer path, including visible stairs. Fix every failure you find, add or strengthen automated checks where needed, and repeat until all criteria that can be automated pass. Do not merely report failures and do not weaken tests. Write goal_report.txt: first line exactly ALL_PASS only when every Acceptance Criteria checkbox is satisfied; otherwise first line FAIL followed by concrete remaining failures."
"$PYTHON" tests/smoke.py > .orchestrator-final-smoke.log 2>&1
local smoke_status=$?
while IFS= read -r line; do echo "$line"; done < .orchestrator-final-smoke.log
if [[ "$smoke_status" -eq 0 && -f goal_report.txt ]] && IFS= read -r first_line < goal_report.txt && [[ "$first_line" == "ALL_PASS" ]]; then
echo "==> Final goal backstop passed"
return
fi
echo "Goal backstop attempt $attempt did not prove all criteria."
done
echo "Final goal backstop failed after $MAX_RETRIES repairs. See goal_report.txt and .orchestrator-final-smoke.log" >&2
exit 1
}
state=0
if [[ -f "$STATE_FILE" ]]; then
read -r state < "$STATE_FILE"
fi
if ! [[ "$state" =~ ^[0-4]$ ]]; then
echo "Invalid $STATE_FILE value: $state" >&2
exit 1
fi
for phase in 1 2 3 4; do
run_phase "$phase" "$state"
state="$phase"
done
run_goal_backstop
echo "Underdepths build complete: all phase gates and the final goal backstop passed."