#!/usr/bin/env bash
# usage: tools/author/launch_agy.sh <job_dir>   Gemini 4 Argon twin of launch.sh (15 Oct 2026, operator: "a mix with Astra and
# Gemini 4 through AGY"): same job.json, same PROMPT.txt, run by Google's Antigravity CLI (~/bin/agy4, Vertex = Google grant).
# agy diffs every untracked file of the git repo it starts in, so the job runs in a scratch copy outside git
# (/tmp/agy-author/<job>) and its deliverables are copied back; node_modules and caches stay behind.
# Writes started.txt, finished.txt, rc.txt, astra.log (the agent's output, same name as the Astra lane so the loops work)
# and agy-relay.log (one line per model call: the usage record, tools: ~/forge-hub/agent/agy4_cost.py).
set -euo pipefail
J=$(readlink -f "$1"); NAME=$(basename "$J")
# PROMPT.txt from the shared template (launch.sh's renderer, without its Astra run)
sed -n '/^python3 - "\$J" <<.PY.$/,/^PY$/p' "$(dirname "$0")/launch.sh" > /tmp/agy-author-render-$$.sh
(cd "$J" && J="$J" bash /tmp/agy-author-render-$$.sh); rm -f /tmp/agy-author-render-$$.sh
EFF=$(python3 -c "import json;print(json.load(open('$J/job.json')).get('effort','medium'))")
W=/tmp/agy-author/$NAME; mkdir -p "$W"
cp "$J"/job.json "$J"/PROMPT.txt "$W"/
for r in $(python3 -c "import json;print(' '.join(json.load(open('$J/job.json'))['refs']))"); do cp "$J/$r" "$W/"; done
date -u +%FT%TZ > "$J/started.txt"
set +e
(cd "$W" && timeout 7200 env AGY4_RELAY_LOG="$W/agy-relay.log" ~/bin/agy4 --model forge:build-gemini-4 --effort "$EFF" --worker \
  -p < PROMPT.txt > astra.log 2>&1); rc=$?
set -e
rsync -a --exclude node_modules --exclude .cache --exclude '__pycache__' "$W"/ "$J"/
date -u +%FT%TZ > "$J/finished.txt"; echo "$rc" > "$J/rc.txt"; exit $rc
