#!/usr/bin/env bash
# The software factory, one gate at a time.
#
# A throwaway `hird-server` with a factory roster, and a crew of six that each
# hold a token: two builders, two reviewers, CI and a human. One small release
# — three tasks, one waiting on another — walked through every stage the
# factory has, with each refusal it exists to make shown at the moment it
# matters:
#
#   ready → claimed → built → in_review → approved → merged
#                       ↑         │          │
#                       └── CI fails, or the reviewer sends it back
#                           (the third time, it asks a human: escalated)
#
# Unlike `factory-floor.py`, which plays a crew at random for you to watch,
# this is a script: the same moves in the same order every time, each one a
# real tool call the server checks against the caller's roles.
#
#   ./examples/factory.sh             # HIRD_PORT=7475 by default
#
# While it runs, the floor is live at the /watch URL it prints. Pass
# `--pause` to stop between acts and watch the cards move.

source "$(dirname "$0")/lib/mcp.sh"

PAUSE=false
[[ "${1:-}" == "--pause" ]] && PAUSE=true

# ---------------------------------------------------------------- the server

REPO="$(cd "$(dirname "$0")/.." && pwd)"
SERVER_BIN="${HIRD_SERVER_BIN:-}"
if [[ -z "$SERVER_BIN" ]]; then
    if command -v hird-server >/dev/null 2>&1; then
        SERVER_BIN="$(command -v hird-server)"
    else
        echo "hird-server is not on PATH — building $REPO" >&2
        (cd "$REPO" && cargo build --quiet -p hird-server)
        SERVER_BIN="$REPO/target/debug/hird-server"
    fi
fi

PORT="${HIRD_PORT:-7475}"
URL="http://127.0.0.1:$PORT"
PROJECT=/srv/acme
WORK="$(mktemp -d)"

# A config of its own, so your real one (a dispatch hook, say) stays out of
# it. The witness reads this host's tree, which no factory worker shares.
mkdir -p "$WORK/config/hird"
printf 'witness = false\n' >"$WORK/config/hird/config.toml"
export XDG_CONFIG_HOME="$WORK/config"
export HIRD_DB="$WORK/factory.db"
unset HIRD_HARNESS

# One token per member of the crew. Roles come from this file and nowhere
# else: no client, header or tool argument can grant one.
token() { printf '%s-%032x' "$1" "$RANDOM$RANDOM$RANDOM"; }
ANA=$(token ana) BEN=$(token ben) CY=$(token cy) EVE=$(token eve) CI=$(token ci) DEE=$(token dee)
cat >"$WORK/roster.toml" <<TOML
project = "$PROJECT"

[factory]
reviewer_harness_differs = true
max_attempts = 3
require_ci_to_merge = true

[[worker]]
token = "$ANA"
identity = "ana"
harness = "claude-code"
model = "builder-model-a"
roles = ["builder"]

[[worker]]
token = "$BEN"
identity = "ben"
harness = "codex"
model = "builder-model-b"
roles = ["builder"]

[[worker]]
token = "$CY"
identity = "cy"
harness = "codex"
model = "reviewer-model-c"
roles = ["reviewer"]

[[worker]]
token = "$EVE"
identity = "eve"
harness = "copilot"
model = "reviewer-model-d"
roles = ["reviewer"]

[[worker]]
token = "$CI"
identity = "ci"
harness = "ci"
roles = ["ci"]

[[worker]]
token = "$DEE"
identity = "dee"
harness = "human"
roles = ["human"]
TOML

"$SERVER_BIN" --roster "$WORK/roster.toml" --port "$PORT" >"$WORK/server.log" 2>&1 &
SERVER_PID=$!
cleanup() {
    kill "$SERVER_PID" 2>/dev/null || true
    wait "$SERVER_PID" 2>/dev/null || true
    rm -r "$WORK"
}
trap cleanup EXIT

for _ in $(seq 50); do
    curl -sf "$URL/watch" >/dev/null 2>&1 && break
    sleep 0.1
done
curl -sf "$URL/watch" >/dev/null || { cat "$WORK/server.log"; exit 1; }

echo "server:   $URL  (roster: $WORK/roster.toml)"
echo "the floor: $URL/watch#token=$DEE"

# ------------------------------------------------------------------ the wire

# One tool call as one member of the crew, the way a 2026-07-28 harness makes
# it: no handshake, a bearer token, and `_meta` on the request. Each token is
# one agent for as long as the server runs, so its leases carry across calls.
#
#   as ana task_claim '{"seq":1}'
as() {
    local who="$1" tool="$2" args="${3:-"{}"}" var text
    var="${who^^}"
    text=$(curl -s "$URL/mcp" \
        -H "Authorization: Bearer ${!var}" \
        -H 'Content-Type: application/json' \
        -H 'Accept: application/json, text/event-stream' \
        -H 'MCP-Protocol-Version: 2026-07-28' \
        -H 'Mcp-Method: tools/call' \
        -H "Mcp-Name: $tool" \
        -d "$(call_stateless 1 "$tool" "$args")" |
        sed -n 's/^data: //p' | grep -v '^$' | head -n1)
    printf '  %-4s %s %s\n' "$who" "$tool" "$args"
    if command -v jq >/dev/null 2>&1; then
        # The answers are written for a model to read in full. Here the long
        # parts (the brief, the reminder, the lease clock) are trimmed so the
        # move itself stands out; each attempt keeps who rejected it and why.
        printf '%s\n' "$text" | jq -r '
            def trim: if type == "object" then
                    del(.body, .reminder, .lease_expires_at, .project, .priority, .advice, .links, .questions)
                    | (if .attempts | type == "array" then
                        .attempts |= map({n, by: .source, output}) else . end)
                    | (if .claimed | type == "object" then .claimed |= trim else . end)
                    | (if .recused then .recused |= map(.seq) else . end)
                    | (if .gated then .gated |= map(.seq) else . end)
                  else . end;
            .result
            | if .isError then "       REFUSED: " + .content[0].text
              else "       → " + (.content[0].text | (fromjson? | trim | tojson) // .)
              end'
    else
        printf '       %s\n' "$text"
    fi
}

# The board as the human sees it: one line per work task.
board() {
    echo
    local text
    text=$(curl -s "$URL/mcp" \
        -H "Authorization: Bearer $DEE" \
        -H 'Content-Type: application/json' \
        -H 'Accept: application/json, text/event-stream' \
        -H 'MCP-Protocol-Version: 2026-07-28' \
        -H 'Mcp-Method: tools/call' -H 'Mcp-Name: factory_board' \
        -d "$(call_stateless 1 factory_board '{}')" |
        sed -n 's/^data: //p' | grep -v '^$' | head -n1)
    if command -v jq >/dev/null 2>&1; then
        printf '%s\n' "$text" | jq -r '.result.content[0].text | fromjson | .tasks[]
            | "  board  #\(.seq)  \(.stage | . + " " * (10 - length))  \(.title)"
              + (if .attempts > 0 then "  · attempts \(.attempts)" else "" end)
              + (if (.waiting_on | length) > 0 then "  · waits on \(.waiting_on | map("#\(.)") | join(", "))" else "" end)'
    else
        printf '  board  %s\n' "$text"
    fi
}

act() {
    if $PAUSE; then
        printf '\n[enter for the next act] '
        read -r _
    fi
    say "$@"
}

# ----------------------------------------------------------------- the acts

act "dee files the release: #1 and #3 are free, #2 waits on #1"
hird add --project "$PROJECT" "Parse the config format" \
    --body "Parse config.toml into the Config struct." >/dev/null
hird add --project "$PROJECT" "Wire the config into the server" --needs 1 \
    --body "Read the parsed Config at start-up." >/dev/null
hird add --project "$PROJECT" "Fix the flaky lease-expiry test" --priority 1 \
    --body "test_lease_expiry times out on slow runners." >/dev/null
board

act "ana builds #1 — and the factory files its review whether asked or not"
as ana task_claim '{"seq":1}'
as ana task_update '{"seq":1,"note":"on a branch","branch":"feat/parse-config","pr_url":"https://git.example/acme/pull/1"}'
as ana task_complete '{"seq":1,"result":"Parser and tests on feat/parse-config."}'
board

act "a builder may not review, and #2 cannot start on work that is not merged"
as ana task_claim '{"seq":4}'
as ana task_claim '{"seq":2}'

act "CI fails #1: an attempt, the output kept, the work back at ready"
as ci factory_gate '{"seq":1,"outcome":"fail","output":"test_parse_empty ... FAILED: unwrap on None","evidence":"https://ci.example/acme/runs/101"}'
board

act "ben picks it up and is handed what went wrong the first time"
as ben task_claim '{"seq":1}'
as ben task_complete '{"seq":1,"result":"Empty input is now an empty Config; test added."}'

act "cy runs codex, like ben: under the policy, no harness that held the work reviews it"
as cy task_next
as eve task_claim '{"seq":5}'
as eve task_complete '{"seq":5,"verdict":"upheld","result":"Reads well; the empty case is covered."}'
board

act "approved is not merged: not by a builder, and not while CI's last word is a fail"
as ana factory_merge '{"seq":1,"evidence":"4f2a9c1"}'
as ci factory_merge '{"seq":1,"evidence":"4f2a9c1"}'
as ci factory_gate '{"seq":1,"outcome":"pass","evidence":"https://ci.example/acme/runs/102"}'
as ci factory_merge '{"seq":1,"evidence":"4f2a9c1"}'
board

act "the flaky test: three rejections, and the third asks a human instead of retrying"
for round in 1 2 3; do
    as ana task_claim '{"seq":3}'
    as ana task_complete '{"seq":3,"result":"Raised the timeout to 2s."}'
    as ci factory_gate "{\"seq\":3,\"outcome\":\"fail\",\"output\":\"test_lease_expiry ... FAILED (timed out, round $round)\"}"
done
board

act "nobody can take escalated work until dee answers"
as ben task_claim '{"seq":3}'
as dee factory_decide '{"seq":3,"action":"answer","text":"It is the runner clock, not the code. Use a fake clock in the test."}'
board

act "the rest of the release: ben builds #2, ana has another go at #3 with dee's answer"
as ben task_claim '{"seq":2}'
as ben task_complete '{"seq":2,"result":"Config is read once at start-up."}'
as ana task_claim '{"seq":3}'
as ana task_complete '{"seq":3,"result":"The test drives a fake clock; no sleeps left."}'
board

act "each review goes to a harness that held none of the work: eve (copilot) for ben's, cy (codex) for ana's"
as eve task_claim '{"seq":9}'
as eve task_complete '{"seq":9,"verdict":"upheld","result":"Small and right."}'
as cy task_claim '{"seq":10}'
as cy task_complete '{"seq":10,"verdict":"upheld","result":"No more wall-clock in the test. Good."}'
as ci factory_gate '{"seq":2,"outcome":"pass","evidence":"https://ci.example/acme/runs/110"}'
as ci factory_gate '{"seq":3,"outcome":"pass","evidence":"https://ci.example/acme/runs/111"}'
as ci factory_merge '{"seq":2,"evidence":"9b1e07d"}'
as dee factory_merge '{"seq":3,"evidence":"https://git.example/acme/pull/3"}'
board

act "the trail on #1: every move, who made it, and the evidence — append-only"
hird events --all-projects --task 1

if $PAUSE; then
    printf '\n[enter to stop the server] '
    read -r _
fi
