#!/usr/bin/env bash
# Launch one refactor task in its own worktree, on the CLI its brief routes it to.
#
#   .agents/scripts/launch.sh 01 scaffold
#   .agents/scripts/launch.sh 02 tokens --base refactor/task-01-scaffold
#   .agents/scripts/launch.sh 07 primitives --cli mm --fg
#
# Routing comes from plans/astro-refactor/MODEL-ROUTING.md. Override with --cli.
# All four CLIs are launched with their permission prompts disabled: these run
# unattended inside a worktree, and a blocked edit or bash call just hangs.
set -euo pipefail

cd "$(git rev-parse --show-toplevel)"

number=${1:?usage: launch.sh <task-number> <slug> [--base ref] [--cli codex|agy|mm|oc] [--fg]}
slug=${2:?slug, e.g. scaffold}
shift 2

base="main"
cli=""
foreground=0
while [ $# -gt 0 ]; do
  case "$1" in
    --base) base=$2; shift 2 ;;
    --cli)  cli=$2;  shift 2 ;;
    --fg)   foreground=1; shift ;;
    *) echo "unknown flag: $1" >&2; exit 2 ;;
  esac
done

# Model routing. Codex takes the long iterate-until-green loops, Gemini the two
# tasks that need whole-corpus context plus visual judgement, MiniMax the rest.
if [ -z "$cli" ]; then
  case "$number" in
    01|03|15|16|19) cli=codex ;;
    02|18)          cli=agy   ;;
    *)              cli=mm    ;;
  esac
fi

dir="../af-task-${number}"
branch="refactor/task-${number}-${slug}"
plan="plans/astro-refactor/task-${number}-${slug}.md"
log="$(pwd)/.agents/logs/task-${number}-${slug}.log"

[ -f "$plan" ] || { echo "no plan at $plan — check the number and slug" >&2; exit 1; }
mkdir -p .agents/logs

# The brief names its own agent; pull it out so the prompt can point at the file.
# [a-z0-9-] not [a-z-]: content-i18n-migrator has digits in it.
agent=$(sed -n 's/.*\*\*Agent\*\*: `\([a-z0-9-]*\)`.*/\1/p' "$plan" | head -1)
[ -n "$agent" ] || { echo "could not read the agent name out of $plan" >&2; exit 1; }
[ -f ".agents/agents/${agent}.md" ] || { echo "no such agent: .agents/agents/${agent}.md" >&2; exit 1; }

if [ -d "$dir" ]; then
  echo "worktree $dir already exists — reusing it"
else
  git worktree add "$dir" -b "$branch" "$base"
fi

# pnpm install works only once task 01 has produced a lockfile. The pre-existing root
# package.json carries two scripts and no dependencies, so before task 01 there
# is no toolchain to install and no hooks to verify.
if [ -f "$dir/pnpm-lock.yaml" ]; then
  ( cd "$dir" && pnpm install --frozen-lockfile && .agents/scripts/verify-hooks.sh )
fi

prompt=$(cat <<PROMPT
You are the \`${agent}\` specialist on the ai-for-dummies Astro refactor.
You are working alone in the git worktree at $(cd "$dir" && pwd), on branch ${branch}.

Read these, in this order, before you write anything:

1. AGENTS.md                       — project entry point and the "never touch" list
2. .agents/agents/${agent}.md       — your role, what you own, what you must not do
3. ${plan}                          — your task brief: scope, steps, done-when, do-not
4. every file the brief and your agent definition tell you to read
   (.agents/context/*, .agents/rules/*, .agents/skills/*, .agents/checklists/*)

Then do the task. Rules that override your own judgement:

- Stay inside the scope in the brief. Do not do work belonging to another task.
- Honour every "Do not" line in the brief and in your agent definition.
- The site must look and read exactly as it does today. This is a refactor,
  not a redesign. If you find something that looks like a bug in the current
  design, write it down in the final report — do not fix it.
- Never delete or weaken an assertion in scripts/verify.mjs to make a suite
  green. Only the verification-engineer may reduce assertion count, with a
  written reason per removal.
- Commit as you go with conventional-commit messages. The commit-msg and
  pre-commit hooks are live; if a hook rejects you, fix the cause, never
  bypass with --no-verify.
- Work through the done-when checklist at the end and actually run each check.

Finish by printing: what you changed, which done-when boxes are genuinely
ticked, which are not and why, and anything the next task needs to know.
PROMPT
)

echo "task    : ${number} ${slug}"
echo "agent   : ${agent}"
echo "cli     : ${cli}"
echo "worktree: ${dir}  (branch ${branch}, from ${base})"
echo "log     : ${log}"
echo

run() {
  case "$cli" in
    codex)
      codex exec --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check \
        -C "$dir" "$prompt"
      ;;
    agy)
      ( cd "$dir" && agy --dangerously-skip-permissions \
          --model gemini-3.1-pro-high --print-timeout 4h -p "$prompt" )
      ;;
    mm)
      ( cd "$dir" && mm --dangerously-skip-permissions \
          --model opus -p "$prompt" )
      ;;
    oc)
      # Claude Code against a local-Ollama-backed model, through the headroom
      # hub. Unproven on this repo — give it the task whose failure is cheapest.
      ( cd "$dir" && OLLAMA_CLAUDE_MODEL="${OC_MODEL:-glm-5.3:cloud}" \
          ollama-claude --dangerously-skip-permissions -p "$prompt" )
      ;;
    *) echo "unknown cli: $cli" >&2; exit 2 ;;
  esac
}

if [ "$foreground" = 1 ]; then
  run 2>&1 | tee "$log"
else
  export cli dir prompt
  nohup bash -c "$(declare -f run); run" >"$log" 2>&1 &
  echo "launched in background, pid $!"
  echo "follow: tail -f $log"
fi
