#!/usr/bin/env bash
# verify-goals.sh — Layer 05. Runs every heartbeat. A broken claim reopens work.
# Each finished task appends a standing goal to goals.jsonl; this re-proves them all, forever.
set -uo pipefail

goals="$(dirname "$0")/goals.jsonl"
[ -f "$goals" ] || { echo "no goals yet"; exit 0; }

fails=0
while IFS= read -r line; do
  [ -z "$line" ] && continue
  claim=$(echo "$line" | jq -r .claim)
  check=$(echo "$line" | jq -r .check)
  if bash -c "$check" >/dev/null 2>&1; then
    echo "✓ $claim"
  else
    echo "✗ REGRESSED: $claim"
    fails=$((fails + 1))
    # File an issue so the next heartbeat picks it up as work — the system self-heals.
    if command -v gh >/dev/null 2>&1; then
      gh issue create --label agent \
        --title "Regression: $claim" \
        --body "Standing goal failed. Check: \`$check\`" >/dev/null 2>&1 || true
    fi
  fi
done < "$goals"

exit $(( fails > 0 ? 1 : 0 ))
