#!/bin/bash
# nightly.sh — one unattended autoresearch session (program.md), run by /etc/cron.d/socialmedia.
# One template per night in rotation; Claude Code gets only the tools the loop needs.
#   EXPERIMENTS=6 TEMPLATE=quote-card scripts/nightly.sh     (both optional)
set -uo pipefail
cd "$(dirname "$0")/.."
set -a; . /etc/environment; set +a   # OPENROUTER_API_KEY for the judge (cron's env is minimal)
export PATH="$HOME/.local/bin:$PATH"   # /etc/environment resets PATH; claude lives in ~/.local/bin
templates=(hook-bold quote-card listicle)
export TEMPLATE=${TEMPLATE:-${templates[$(( $(date +%j | sed 's/^0*//') % ${#templates[@]} ))]}}
EXPERIMENTS=${EXPERIMENTS:-6}
echo "=== $(date -Is) nightly autoresearch: $TEMPLATE, up to $EXPERIMENTS experiments"

timeout 2h claude -p "You are the autoresearch agent. Follow /var/www/html/Socialmedia/hyperframes/program.md exactly for TEMPLATE=$TEMPLATE (it is already exported; run the evaluator as plain \`node evaluate.mjs\` from /var/www/html/Socialmedia/hyperframes). Run at most $EXPERIMENTS experiments, one hypothesis each. Read the template's references brief and sheet first if meta.json names a set. The hyperframes-animation and hyperframes-core skills in /root/.claude/skills are your motion reference. Finish with one line: SUMMARY $TEMPLATE baseline <x> -> best <y>; kept: <changes or none>." \
  --permission-mode dontAsk \
  --allowedTools \
    "Read" "Glob" "Grep" \
    "Edit(//var/www/html/Socialmedia/hyperframes/templates/$TEMPLATE/index.html)" \
    "Bash(node evaluate.mjs)" \
    "Bash(git log:*)" "Bash(git diff:*)" "Bash(git status:*)" "Bash(tail:*)" "Bash(grep:*)" \
    "Bash(git checkout -- templates/$TEMPLATE/index.html)" \
    "Bash(git commit templates/$TEMPLATE/index.html results.tsv -m:*)" \
    "Bash(git commit results.tsv -m:*)"
code=$?
# Never leave a half-finished experiment in the tree.
git diff --quiet -- "templates/$TEMPLATE/index.html" || { echo "reverting uncommitted template edit"; git checkout -- "templates/$TEMPLATE/index.html"; }
echo "=== $(date -Is) done (exit $code)"
