#!/bin/bash
# Ralph Autonomous Loop (Beads Mode)
# Generated by /create-ralph

MAX_ITERATIONS=${1:-25}
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "Starting Ralph loop with beads (max $MAX_ITERATIONS iterations)"
echo "Output: <promise>COMPLETE</promise> when done"
echo "---"

for i in $(seq 1 $MAX_ITERATIONS); do
  echo ""
  echo "=== Ralph Iteration $i of $MAX_ITERATIONS ==="
  echo ""

  # Run pipeline in current shell (not subshell) so PIPESTATUS is available.
  # tee writes to stderr for live output; stdout is captured via tmpfile.
  TMPFILE=$(mktemp)
  cat "$SCRIPT_DIR/prompt.md" | claude 2>&1 | tee /dev/stderr > "$TMPFILE"
  AI_EXIT=${PIPESTATUS[1]}
  OUTPUT=$(cat "$TMPFILE")
  rm -f "$TMPFILE"
  if [ "$AI_EXIT" -ne 0 ]; then
    echo "=== WARNING: AI tool exited with status $AI_EXIT on iteration $i ==="
  fi

  # grep -xF: exact whole-line match + fixed string.
  # This prevents signal strings embedded in generated code, comments, or prose
  # from triggering a false exit. The signal must appear alone on its own line.
  if printf '%s\n' "$OUTPUT" | grep -qxF "<promise>COMPLETE</promise>"; then
    echo ""
    echo "=== Ralph completed all tasks! ==="
    exit 0
  fi

  if printf '%s\n' "$OUTPUT" | grep -qxF "<promise>BLOCKED</promise>"; then
    echo ""
    echo "=== Ralph is blocked - manual intervention needed ==="
    exit 1
  fi
done

echo ""
echo "=== Max iterations reached without completion ==="
exit 2
