#!/usr/bin/env bash
# usage: r4.sh <before|after> <builddir> <projdir> <basedir>
set -u
b=$1; tag=${5:-R4}; dir=$2; proj=$3; base=$4; out=/tmp/ev-23636/out/$tag-$b.transcript.txt
msg="Use only the CronCreate tool. Do not use any other tool, do not read or edit any file. First, schedule a one-shot (non-recurring) cron for 14:18 UTC today (the machine's local time zone is UTC) whose prompt is: 'Append the line FIRED-$tag-$b followed by the current UTC time to $proj/cron.log using a single shell append, and do nothing else.' After scheduling, use no tools at all and write a 2000-word essay about the history of lighthouses."
cd "$dir"
tid=$(node apps/server/src/bin.ts thread start "$proj" "$msg" --base-dir "$base" --title "$tag-$b" --provider claudeAgent --model claude-sonnet-5-5 --json | grep -o '"threadId":"[^"]*"' | cut -d'"' -f4)
echo "$(date -u +%FT%TZ) started $tag-$b thread=$tid" >> $out
for i in $(seq 1 120); do
  act=$(/tmp/ev-23636/driver/mcp.sh $b t3_thread_read "{\"threadId\":\"$tid\",\"view\":\"activity\",\"limit\":100}" 2>/dev/null)
  if echo "$act" | python3 -c 'import json,sys;d=json.load(sys.stdin)["structuredContent"];sys.exit(0 if any(i.get("type")=="dynamic_tool" and i.get("status")=="completed" and "CronCreate" in (i.get("text") or "") for i in d["items"]) else 1)' 2>/dev/null; then
    echo "$(date -u +%FT%TZ) CronCreate observed in activity (poll $i)" >> $out; break; fi
  sleep 0.5
done
echo "$(date -u +%FT%TZ) interrupt request:" >> $out
/tmp/ev-23636/driver/mcp.sh $b t3_thread_interrupt "{\"threadId\":\"$tid\",\"reason\":\"ev-23636 R4 interrupt after CronCreate\"}" >> $out 2>&1
echo >> $out
