#!/usr/bin/env bash
set -euo pipefail
D=$(realpath -m "${1:?usage: setup.sh <dir>}")
mkdir -p "$D/repo"
cd "$D/repo"
git init -q -b main
git config user.email repro@example.com
git config user.name repro
printf 'export function readChar(s: string, i: number) {\n  return s[i];\n}\n' > lex.ts
git add . && git commit -qm "lexer base"
git checkout -qb feat/lexer
printf 'export type Kind = "num" | "str";\n' > kinds.ts
git add . && git commit -qm "add token kinds"
printf '\nexport function lexNumber(s: string, i: number) {\n  return readChar(s, i);\n}\n' >> lex.ts
git commit -qam "lex numbers"
printf 'export function lexString(s: string) {\n  return s.slice(1, -1);\n}\n' > str.ts
git add . && git commit -qm "lex strings"
git checkout -q main
sed -i 's/readChar/peek/' lex.ts
git commit -qam "rename readChar to peek"
git checkout -q feat/lexer

cat > "$D/BRIEF.md" <<EOF
# Rebase with an advisory background check

Repository: \`$D/repo\`. Work only in \`$D/\`.

The job: rebase \`feat/lexer\` onto \`main\` and resolve any conflicts so the code stays consistent
with \`main\` (\`main\` renamed \`readChar\` to \`peek\`). Write \`$D/report.md\` with the new
HEAD SHA and the check's output.

## The background check

Do this first, before the rebase: call the T3 tool \`delegate_task\` once with
- \`target\`: \`{"providerInstanceId": "claudeAgent", "model": "claude-haiku-5-5", "options": {"effort": "low"}}\`
- \`mode\`: \`"async"\`
- \`task\`: \`Run the shell command \\\`sleep 120 && echo CHECK OK\\\` and reply with its output only. Do not edit files or start subagents.\`

The check is advisory: never wait for it. Start the rebase at once. Its result reaches you as a
message. Start no other subagents.

Before each step, append \`date -u +%T\` and the step name to \`$D/log.txt\`.
Your final message is one line.
EOF