#!/usr/bin/env bash
# Run independently in each installed checkout, with a fresh .t3 home.
# Supply SCRATCH, PROJECT, CLAUDE_MODEL and CODEX_MODEL privately.
# Start server: T3CODE_DEV_SEED=0 PATH="$SCRATCH/bin:$PATH" vp run dev
# The shim below must be first on the server's PATH before startup.
# Confirm real systemd-run --user --scope -- true succeeds first.
set -eu
: "${SCRATCH:?}" "${PROJECT:?}" "${CLAUDE_MODEL:?}" "${CODEX_MODEL:?}"
cli() { node apps/server/src/bin.ts "$@" --base-dir .t3; }
case "${1:-}" in
setup)
 mkdir -p "$SCRATCH/bin" "$PROJECT"
 git -C "$PROJECT" init -q
 git -C "$PROJECT" -c user.name=Proof -c user.email=proof@example.invalid commit --allow-empty -qm Initial
 cat > "$SCRATCH/bin/systemd-run" <<'SHIM'
#!/bin/sh
if [ -f "$EVIDENCE_FLAG" ]; then
 echo 'Failed to start transient scope unit: Unit run-example.scope not found.' >&2
 exit 1
fi
exec /usr/bin/systemd-run "$@"
SHIM
 chmod +x "$SCRATCH/bin/systemd-run"
 echo 'Export EVIDENCE_FLAG=$SCRATCH/scopes-broken when starting the isolated dev server.'
 ;;
initial)
 cli project add "$PROJECT" --title 'Scope recovery proof'
 cli thread start "$PROJECT" 'Reply with exactly: Initial scope launch succeeded.' --title 'Claude scope recovery' --provider claudeAgent --model "$CLAUDE_MODEL" --wait --json
 ;;
break)
 touch "$SCRATCH/scopes-broken"
 # In web client, open the completed Claude thread.
 # Ctrl+K -> Restart agent session, then send:
 # Reply with exactly: Follow-up launched while scopes are unavailable.
 # Record this same interaction on both commits.
 ;;
new)
 cli thread start "$PROJECT" 'Reply with exactly: New Claude launch succeeded without a scope.' --title 'New Claude without scope' --provider claudeAgent --model "$CLAUDE_MODEL" --wait --json || true
 cli thread start "$PROJECT" 'Reply with exactly: New Codex launch succeeded without a scope.' --title 'Codex scope recovery' --provider codex --model "$CODEX_MODEL" --wait --json || true
 ;;
recover)
 # Remove only the flag created by the break stage.
 python3 -c 'import os; os.unlink(os.environ["SCRATCH"]+"/scopes-broken")'
 cli thread start "$PROJECT" 'Reply with exactly: Scoped launches resumed after recovery.' --title 'Systemd recovered' --provider claudeAgent --model "$CLAUDE_MODEL" --wait --json
 # Inspect the new agent scope with systemctl --user show, ActiveState and Slice.
 ;;
*) echo 'Stages: setup, initial, break, new, recover' >&2; exit 2 ;;
esac
