#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
ROOT=$(cd -- "$SCRIPT_DIR/../../.." && pwd -P)
MODULE="$ROOT/modules/subrouter"
MANIFEST="$MODULE/upstream.json"
PATCH_FILE="$MODULE/patches/0001-overdeck-authority-safety.patch"
DEFAULT_ARTIFACT_ROOT="$ROOT/.local/subrouter-artifacts"
ARTIFACT_ROOT=${OVERDECK_SUBROUTER_TEST_ARTIFACT_ROOT:-$DEFAULT_ARTIFACT_ROOT}
if [[ "$ARTIFACT_ROOT" != "$DEFAULT_ARTIFACT_ROOT" ]]; then
  [[ ${OVERDECK_SUBROUTER_TEST_MODE:-} == 1 && "$ARTIFACT_ROOT" == /* ]] || {
    printf '%s\n' 'subrouter verify: artifact-root override is test-only and must be absolute' >&2
    exit 77
  }
  ARTIFACT_ROOT=$(realpath -m -- "$ARTIFACT_ROOT")
  case "$ARTIFACT_ROOT" in
    "$ROOT"|"$ROOT"/*|/home/user/Projects/*) printf '%s\n' 'subrouter verify: test artifact root is inside a checkout ancestry' >&2; exit 77 ;;
  esac
fi
PHASE=${1:-}

die() {
  printf 'subrouter verify: %s\n' "$*" >&2
  exit 2
}

manifest_field() {
  python3 - "$MANIFEST" "$1" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as handle:
    value = json.load(handle)[sys.argv[2]]
if not isinstance(value, str) or not value:
    raise SystemExit(2)
print(value)
PY
}

require_manifest() {
  [[ -f "$MANIFEST" && -f "$PATCH_FILE" ]] || die 'manifest or patch is missing'
  python3 - "$MANIFEST" <<'PY'
import json, sys
expected = {
    "repository": "https://github.com/manaflow-ai/subrouter.git",
    "release": "v0.1.81",
    "revision": "29c7ebb306ac54739206f4752449e437047dd150",
    "archive_command": "git archive --format=tar 29c7ebb306ac54739206f4752449e437047dd150",
    "archive_sha256": "74ab8da37d467a7d36bb73b11d82d90fd5ea14f3b75c535026adb0e45d9529f6",
    "go": "1.24.0",
    "patch": "modules/subrouter/patches/0001-overdeck-authority-safety.patch",
}
with open(sys.argv[1], encoding="utf-8") as handle:
    actual = json.load(handle)
if actual != expected:
    raise SystemExit("pinned manifest does not match the S0 contract")
PY
}

validate_patch_scope() {
  python3 - "$PATCH_FILE" <<'PY'
import pathlib, re, sys
allowed = {
    "internal/accounts/refresh_attempt.go",
    "internal/accounts/refresh_attempt_test.go",
    "internal/accounts/codex_auth.go",
    "internal/accounts/codex_auth_test.go",
    "internal/agents/claude/store.go",
    "internal/agents/claude/store_test.go",
    "internal/accounts/store_lease.go",
    "internal/accounts/store_lease_test.go",
    "internal/authority/routes.go",
    "internal/authority/routes_test.go",
    "internal/proxy/authority_routes.go",
    "internal/proxy/authority_routes_test.go",
    "internal/proxy/proxy.go",
    "internal/proxy/proxy_test.go",
    "cmd/subrouter/authority_routes.go",
    "cmd/subrouter/authority_routes_test.go",
    "cmd/subrouter/authority_status.go",
    "cmd/subrouter/authority_status_test.go",
    "cmd/subrouter/main.go",
    "cmd/subrouter/sr_command.go",
    "cmd/subrouter/sr_command_test.go",
}
required = {
    "internal/authority/routes.go",
    "internal/authority/routes_test.go",
    "internal/proxy/authority_routes.go",
    "internal/proxy/authority_routes_test.go",
    "internal/proxy/proxy.go",
    "cmd/subrouter/authority_routes.go",
    "cmd/subrouter/authority_routes_test.go",
    "cmd/subrouter/authority_status.go",
    "cmd/subrouter/authority_status_test.go",
    "cmd/subrouter/main.go",
    "cmd/subrouter/sr_command.go",
    "cmd/subrouter/sr_command_test.go",
}
paths = set()
for line in pathlib.Path(sys.argv[1]).read_text().splitlines():
    match = re.fullmatch(r"diff --git a/(\S+) b/(\S+)", line)
    if match:
        if match.group(1) != match.group(2):
            raise SystemExit("renamed patch paths are refused")
        paths.add(match.group(1))
if not paths or not required <= paths or not paths <= allowed:
    raise SystemExit("patch path scope does not match the S1 allowlist")
PY
}

input_digest() {
  python3 - "$ROOT" <<'PY'
import hashlib, os, pathlib, subprocess, sys
root = pathlib.Path(sys.argv[1]).resolve()
owned = [
    root / "modules/subrouter",
    root / "modules/harness/seat",
    root / "modules/systray",
    root / "modules/workstation/claude/buildbox-hosts.json",
    root / "modules/workstation/claude/lib/buildbox-registry.mjs",
    root / "modules/workstation/claude/tests/buildbox-registry.test.mjs",
    root / "modules/workstation/claude/lib/remote-runner.sh",
    root / "modules/workstation/claude/tests/remote-runner-path.test.sh",
    root / "docs/plans/2026-08-17-subrouter-authority.md",
    root / "docs/specs/2026-08-17-subrouter-authority-design.md",
    root / "docs/plans/2026-08-22-subrouter-authority-s5.md",
    root / "docs/plans/2026-08-22-subrouter-authority-s6.md",
    root / "docs/plans/2026-08-22-workstation-ai-account-gateway.md",
    root / "docs/plans/INDEX.md",
]
h = hashlib.sha256()
head = subprocess.check_output(["git", "-c", f"safe.directory={root}", "-C", str(root), "rev-parse", "HEAD"], text=True).strip()
h.update(b"base\0" + head.encode() + b"\0")
files = []
for entry in owned:
    if entry.is_dir():
        files.extend(
            p for p in entry.rglob("*")
            if p.is_file()
            and not ({".local", ".pytest_cache", "__pycache__"} & set(p.parts))
            and p.suffix != ".pyc"
        )
    elif entry.is_file():
        files.append(entry)
for path in sorted(files, key=lambda p: p.relative_to(root).as_posix()):
    if path.is_symlink():
        raise SystemExit(f"input symlink refused: {path.relative_to(root)}")
    rel = path.relative_to(root).as_posix().encode()
    body = path.read_bytes()
    h.update(b"file\0" + rel + b"\0" + str(len(body)).encode() + b"\0" + body)
print(h.hexdigest())
PY
}

tree_diff_digest() {
  python3 - "$ROOT" <<'PY'
import hashlib, pathlib, subprocess, sys
root = pathlib.Path(sys.argv[1]).resolve()
paths = [
    "modules/subrouter",
    "modules/harness/seat",
    "modules/systray",
    "modules/workstation/claude/buildbox-hosts.json",
    "modules/workstation/claude/lib/buildbox-registry.mjs",
    "modules/workstation/claude/tests/buildbox-registry.test.mjs",
    "modules/workstation/claude/lib/remote-runner.sh",
    "modules/workstation/claude/tests/remote-runner-path.test.sh",
    "docs/plans/2026-08-17-subrouter-authority.md",
    "docs/specs/2026-08-17-subrouter-authority-design.md",
    "docs/plans/2026-08-22-subrouter-authority-s5.md",
    "docs/plans/2026-08-22-subrouter-authority-s6.md",
    "docs/plans/2026-08-22-workstation-ai-account-gateway.md",
    "docs/plans/INDEX.md",
]
h = hashlib.sha256()
diff = subprocess.check_output(
    ["git", "-c", f"safe.directory={root}", "-C", str(root), "diff", "--binary", "--no-ext-diff", "HEAD", "--", *paths]
)
h.update(b"tracked-diff\0" + diff)
untracked = subprocess.check_output(
    ["git", "-c", f"safe.directory={root}", "-C", str(root), "ls-files", "--others", "--exclude-standard", "-z", "--", *paths]
).split(b"\0")
for raw in sorted(item for item in untracked if item):
    rel = raw.decode()
    path = root / rel
    if {".local", ".pytest_cache", "__pycache__"} & set(path.parts) or path.suffix == ".pyc":
        continue
    if path.is_symlink():
        raise SystemExit(f"input symlink refused: {rel}")
    body = path.read_bytes()
    h.update(b"untracked\0" + raw + b"\0" + str(len(body)).encode() + b"\0" + body)
print(h.hexdigest())
PY
}

patch_digest() {
  sha256sum "$PATCH_FILE" | cut -d' ' -f1
}

candidate_digest() {
  local artifact=$1 tree_key=$2
  python3 - "$tree_key" "$(manifest_field revision)" "$(manifest_field archive_sha256)" "$(patch_digest)" "$(manifest_field go)" "$artifact/bin/subrouter" <<'PY'
import hashlib, pathlib, sys
h = hashlib.sha256()
for value in sys.argv[1:6]:
    h.update(value.encode() + b"\0")
h.update(hashlib.sha256(pathlib.Path(sys.argv[6]).read_bytes()).digest())
print(h.hexdigest())
PY
}

find_candidate() {
  python3 - "$ARTIFACT_ROOT" "$TREE_KEY" <<'PY'
import json, pathlib, sys
root = pathlib.Path(sys.argv[1])
tree_key = sys.argv[2]
matches = []
if root.is_dir():
    for child in root.iterdir():
        if not child.is_dir() or child.is_symlink() or child.name.startswith("."):
            continue
        receipt = child / "receipt.json"
        try:
            payload = json.loads(receipt.read_text())
        except (OSError, ValueError):
            continue
        if payload.get("complete") is True and payload.get("input_digest") == tree_key:
            matches.append(child)
if len(matches) != 1:
    raise SystemExit(f"expected one exact-tree candidate, found {len(matches)}")
print(matches[0])
PY
}

REGISTRY="$ROOT/modules/workstation/claude/buildbox-hosts.json"
REGISTRY_TOOL="$ROOT/modules/workstation/claude/lib/buildbox-registry.mjs"

prepare_source() {
  local work=$1 revision repository expected actual apply_log
  revision=$(manifest_field revision)
  repository=$(manifest_field repository)
  expected=$(manifest_field archive_sha256)
  mkdir -p "$work"
  run_allowlisted "$ROOT" git clone --quiet --no-checkout "$repository" "$work/source"
  run_allowlisted "$ROOT" git -C "$work/source" checkout --quiet --detach "$revision"
  [[ -z "$(run_allowlisted "$ROOT" git -C "$work/source" status --porcelain=v1)" ]] || die 'pinned source is dirty before patching'
  actual=$(run_allowlisted "$ROOT" git -C "$work/source" archive --format=tar "$revision" | sha256sum | cut -d' ' -f1)
  [[ "$actual" == "$expected" ]] || die "archive digest mismatch: $actual"
  apply_log="$work/patch-apply.log"
  if ! run_allowlisted "$ROOT" git -C "$work/source" apply --check --unidiff-zero --whitespace=error-all --verbose "$PATCH_FILE" >"$apply_log" 2>&1; then
    printf '%s\n' 'subrouter verify: patch check failed' >&2
    python3 - "$apply_log" <<'PY' >&2
import pathlib, sys
print(pathlib.Path(sys.argv[1]).read_text(errors="replace")[-8192:])
PY
    exit 2
  fi
  if grep -Eiq '(with fuzz|offset [0-9+-])' "$apply_log"; then
    die 'patch requires fuzz or offset'
  fi
  run_allowlisted "$ROOT" git -C "$work/source" apply --unidiff-zero --whitespace=error-all "$PATCH_FILE"
}

capture_dispatch_provenance() {
  local phase=$1 tree_key=$2 tree_diff=$3 output=$4
  local cgroup unit job_id job_dir meta identity worker machine_id identity_source
  [[ -f "$REGISTRY" && -f "$REGISTRY_TOOL" ]] || die 'source-controlled worker registry is missing'
  cgroup=$(< /proc/self/cgroup)
  unit=$(grep -Eo 'rb-[A-Za-z0-9_.-]+\.service' <<<"$cgroup" | tail -n1 || true)
  [[ -n "$unit" ]] || die 'worker is not running in a remote-build dispatch unit'
  job_id=${unit#rb-}
  job_id=${job_id%.service}
  job_dir="${HOME:?}/.rb/jobs/$job_id"
  meta="$job_dir/meta.json"
  [[ -f "$meta" ]] || die 'remote dispatch metadata is missing'
  identity=$(env -u OVERDECK_SEAT_HOST -u OVERDECK_SEAT_ID \
    BUILDBOX_HOSTS_CONFIG="$REGISTRY" node "$REGISTRY_TOOL" self) || die 'worker identity is not registered'
  read -r worker machine_id identity_source <<<"$identity"
  [[ "$worker" =~ ^[A-Za-z0-9._-]+$ && "$machine_id" =~ ^[0-9a-f]{32}$ && "$identity_source" == machine-id ]] \
    || die 'worker identity is not independently machine-id registered'
  python3 - "$meta" "$REGISTRY" "$output" "$phase" "$tree_key" "$tree_diff" "$worker" "$machine_id" "$job_id" "$ROOT" <<'PY'
import hashlib, json, pathlib, sys
meta_path, registry_path, output = map(pathlib.Path, sys.argv[1:4])
phase, tree_key, tree_diff, worker, machine_id, job_id, root = sys.argv[4:11]
meta_raw = meta_path.read_text()
meta = json.loads(meta_raw)
registry = json.loads(registry_path.read_text())
registered = next((host for host in registry.get("hosts", []) if host.get("name") == worker), None)
if not registered or registered.get("machine_id") != machine_id or registered.get("state") != "reachable" or worker not in registry.get("orders", {}).get("build", []):
    raise SystemExit("worker identity is not an eligible source-controlled build worker")
expected_key = f"subrouter-{tree_key[:16]}-{phase}"
argv = meta.get("argv")
if meta.get("key") != expected_key or not isinstance(argv, list):
    raise SystemExit("remote dispatch metadata does not match phase key")
expected_tail = ["__worker", phase, tree_key, tree_diff]
if len(argv) < 5 or argv[-4:] != expected_tail or not str(argv[-5]).endswith("/modules/subrouter/bin/verify-candidate"):
    raise SystemExit("remote dispatch metadata command mismatch")
if meta.get("env") not in ({}, None):
    raise SystemExit("remote dispatch metadata carries unapproved environment")
if not isinstance(meta.get("epoch"), str) or not meta["epoch"].isdigit() or int(meta["epoch"]) <= 0:
    raise SystemExit("remote dispatch epoch is invalid")
started = meta.get("started_at", "")
if not isinstance(started, str) or not started.endswith("Z"):
    raise SystemExit("remote dispatch start time is invalid")
mirror = pathlib.Path(meta.get("mirror", ""))
epoch_path = mirror / ".rb-epoch"
if not mirror.is_absolute() or not epoch_path.is_file() or epoch_path.read_text().strip() != str(meta["epoch"]):
    raise SystemExit("remote dispatch epoch is not bound to the source mirror")
payload = {
    "schema": 1,
    "dispatch_key": expected_key,
    "job_id": job_id,
    "epoch": meta["epoch"],
    "started_at": started,
    "remote_meta": meta,
    "remote_meta_raw": meta_raw,
    "argv_sha256": hashlib.sha256(json.dumps(argv, separators=(",", ":")).encode()).hexdigest(),
    "meta_sha256": hashlib.sha256(meta_raw.encode()).hexdigest(),
    "registry_sha256": hashlib.sha256(registry_path.read_bytes()).hexdigest(),
    "worker": worker,
    "machine_id_sha256": hashlib.sha256(machine_id.encode()).hexdigest(),
    "identity_source": "machine-id",
}
output.write_text(json.dumps(payload, sort_keys=True, indent=2) + "\n")
PY
}

run_allowlisted() {
  local cwd=$1; shift
  (
    cd -- "$cwd"
    exec /usr/bin/env -i \
      HOME="$worker_home" TMPDIR="$worker_tmp" PYTHONUSERBASE="$python_user_base" \
      PATH="$credential_bin:$go_bin:/usr/local/bin:/usr/bin:/bin" \
      GOMODCACHE="$go_mod_cache" GOCACHE="$go_build_cache" GOPATH="$go_path" \
      GOENV=off GOTOOLCHAIN=local CGO_ENABLED=1 \
      "$@"
  )
}

run_confined() {
  local cwd=$1; shift
  unshare --user --map-root-user --net -- /bin/bash -c '
    set -e
    /usr/sbin/ip link set lo up
    cd -- "$1"
    shift
    exec /usr/bin/env -i "$@"
  ' subrouter-net "$cwd" \
    HOME="$worker_home" TMPDIR="$worker_tmp" \
    PATH="$credential_bin:$go_bin:/usr/local/bin:/usr/bin:/bin" \
    GOMODCACHE="$go_mod_cache" GOCACHE="$go_build_cache" GOPATH="$go_path" \
    GOENV=off GOTOOLCHAIN=local CGO_ENABLED=1 \
    "$@"
}

run_python_confined() {
  local cwd=$1; shift
  unshare --user --map-root-user --net -- /bin/bash -c '
    set -e
    /usr/sbin/ip link set lo up
    cd -- "$1"
    shift
    exec /usr/bin/env -i "$@"
  ' subrouter-python-net "$cwd" \
    HOME="$worker_home" TMPDIR="$worker_tmp" PYTHONUSERBASE="$python_user_base" \
    PATH="$credential_bin:/usr/local/bin:/usr/bin:/bin" \
    "$@"
}

write_worker_record() {
  local artifact=$1 phase=$2 started=$3 exit_code=$4 log=$5 tree_key=$6 tree_diff=$7 provenance=$8
  local ended elapsed worker go_tool
  ended=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  elapsed=$(( $(date +%s) - started ))
  worker=$(python3 - "$provenance" <<'PY'
import json, pathlib, sys
print(json.loads(pathlib.Path(sys.argv[1]).read_text())["worker"])
PY
)
  go_tool=$(run_allowlisted "$ROOT" go version)
  python3 - "$artifact" "$phase" "$started" "$ended" "$elapsed" "$exit_code" "$worker" "$go_tool" "$log" "$tree_key" "$tree_diff" "$artifact/.go-sum.sha256" "$provenance" <<'PY'
import hashlib, json, os, pathlib, sys, tempfile
artifact = pathlib.Path(sys.argv[1])
phase = sys.argv[2]
log = pathlib.Path(sys.argv[9])
go_sum_path = pathlib.Path(sys.argv[12])
provenance_path = pathlib.Path(sys.argv[13])
provenance = json.loads(provenance_path.read_text())
payload = {
    "phase": phase,
    "input_digest": sys.argv[10],
    "tree_diff_sha256": sys.argv[11],
    "started_epoch": int(sys.argv[3]),
    "ended_at": sys.argv[4],
    "elapsed_seconds": int(sys.argv[5]),
    "exit": int(sys.argv[6]),
    "worker": sys.argv[7],
    "dispatch": provenance,
    "dispatch_sha256": hashlib.sha256(provenance_path.read_bytes()).hexdigest(),
    "go_version": sys.argv[8],
    "go_sum_sha256": go_sum_path.read_text().strip(),
    "log": log.name,
    "log_sha256": hashlib.sha256(log.read_bytes()).hexdigest(),
}
artifact.mkdir(parents=True, exist_ok=True)
fd, name = tempfile.mkstemp(prefix=f".{phase}.", dir=artifact)
try:
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(payload, handle, sort_keys=True, indent=2)
        handle.write("\n")
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(name, artifact / f"worker-{phase}.json")
    directory = os.open(artifact, os.O_DIRECTORY)
    try: os.fsync(directory)
    finally: os.close(directory)
finally:
    if os.path.exists(name): os.unlink(name)
PY
}

worker_phase() {
  local phase=$1 tree_key=$2 tree_diff=$3
  local run_id work artifact log started rc=0 unit_check provenance
  local go_mod_cache go_build_cache go_path go_bin worker_home worker_tmp credential_bin command python_user_base
  local -a go_files
  [[ "$tree_key" =~ ^[0-9a-f]{64}$ ]] || die 'invalid worker tree digest'
  [[ "$tree_diff" =~ ^[0-9a-f]{64}$ ]] || die 'invalid worker tree-diff digest'
  command -v go >/dev/null 2>&1 || die 'worker has no Go toolchain'
  [[ "$(go env GOVERSION)" == "go$(manifest_field go)" ]] || die "worker Go toolchain is not go$(manifest_field go)"
  go_bin=$(dirname -- "$(readlink -f -- "$(command -v go)")")
  go_mod_cache=$(go env GOMODCACHE)
  go_build_cache=$(go env GOCACHE)
  go_path=$(go env GOPATH)
  python_user_base=$(python3 -m site --user-base)
  [[ "$python_user_base" == "$HOME/.local" ]] || die 'worker Python user base is not the registered user-local runtime'
  run_id="$(date +%s)-$$-$phase"
  work="${XDG_CACHE_HOME:-$HOME/.cache}/overdeck/tests/subrouter/$run_id"
  private_test_root="/home/user/.overdeck-subrouter-candidate-tests/$run_id"
  case "$private_test_root" in
    /home/user/.overdeck-subrouter-candidate-tests/*) ;;
    *) die 'private test root is outside approved home path' ;;
  esac
  install -d -m 0700 /home/user/.overdeck-subrouter-candidate-tests "$private_test_root"
  case "$work" in
    "$ROOT"|"$ROOT"/*|/home/user/Projects/*) die 'worker temp root is inside a checkout ancestry' ;;
  esac
  artifact="$ARTIFACT_ROOT/.work-$tree_key"
  mkdir -p "$artifact/logs"
  log="$artifact/logs/$phase.log"
  provenance="$artifact/dispatch-$phase.json"
  capture_dispatch_provenance "$phase" "$tree_key" "$tree_diff" "$provenance"
  started=$(date +%s)
  worker_tmp=$(mktemp -d "/tmp/XXX")
  trap "chmod -R u+w -- $(printf '%q' "$work") $(printf '%q' "$private_test_root") 2>/dev/null || true; rm -rf -- $(printf '%q' "$work") $(printf '%q' "$worker_tmp") $(printf '%q' "$private_test_root")" EXIT
  worker_tmp=$(realpath -e -- "$worker_tmp")
  case "$worker_tmp" in
    "$ROOT"|"$ROOT"/*|/home/user/Projects/*) die 'worker TMPDIR is inside a checkout ancestry' ;;
  esac
  worker_home="$work/home"
  credential_bin="$work/credential-bin"
  mkdir -p "$worker_home" "$worker_tmp" "$credential_bin"
  for command in codex claude; do
    printf '%s\n' '#!/bin/sh' 'printf "%s\\n" "native account login tools are refused during candidate verification" >&2' 'exit 126' >"$credential_bin/$command"
    chmod 755 "$credential_bin/$command"
  done
  prepare_source "$work"
  run_allowlisted "$work/source" go mod download
  sha256sum "$work/source/go.sum" | cut -d' ' -f1 >"$artifact/.go-sum.sha256"
  case "$phase" in
    focused)
      run_confined "$work/source" go test ./internal/accounts ./internal/agents/claude ./internal/authority ./internal/proxy ./cmd/subrouter -run 'RefreshAttempt|RefreshStored|RefreshCredential|StoreLease|Authority|RouteGrant|ConcurrentMutations|ProviderAliasesResolve|LocalAccountUploadsPreserveSupportedAPIKeyProviders|SRSwitchAPIKeyWritesCodexAuthJSON|ListenerTransferAcceptsLegacyDualStackWildcardForIPv4Configuration' >"$log" 2>&1 || rc=$?
      if (( rc == 0 )); then run_allowlisted "$ROOT" bash modules/harness/seat/test/seat-creds.test.sh >>"$log" 2>&1 || rc=$?; fi
      if (( rc == 0 )); then run_allowlisted "$ROOT" bash modules/harness/seat/test/seat-authority.test.sh >>"$log" 2>&1 || rc=$?; fi
      if (( rc == 0 )); then run_allowlisted "$ROOT" bash modules/workstation/claude/tests/remote-runner-path.test.sh >>"$log" 2>&1 || rc=$?; fi
      if (( rc == 0 )); then run_allowlisted "$ROOT" node --test modules/workstation/claude/tests/buildbox-registry.test.mjs >>"$log" 2>&1 || rc=$?; fi
      if (( rc == 0 )); then run_allowlisted "$ROOT" python3 -m pytest --basetemp "$private_test_root/pytest" -q \
        modules/systray/tests/test_authority_migration.py \
        modules/systray/tests/test_provider_services.py \
        modules/systray/tests/test_command_router_authority.py \
        modules/systray/tests/test_account_registry.py \
        modules/systray/tests/test_authority_client.py \
        modules/systray/tests/test_gateway_account_manager.py \
        modules/systray/tests/test_gateway_account_cli.py \
        modules/systray/tests/test_claudex.py \
        modules/systray/tests/test_claudex_router.py \
        modules/systray/tests/test_tray_model.py \
        modules/systray/tests/test_ui_account_card.py \
        modules/systray/tests/test_ui_view_model.py \
        modules/systray/tests/test_ui_dashboard.py \
        modules/systray/tests/test_indicator.py \
        modules/systray/tests/test_install.py \
        modules/systray/tests/test_packaging_desktop_entry.py \
        modules/systray/tests/test_k3s_dispatch.py >>"$log" 2>&1 || rc=$?; fi
      if (( rc == 0 )); then
        fixture_out="$work/s5-fixture-receipts"
        mkdir -p "$fixture_out"
        run_allowlisted "$ROOT" python3 modules/systray/scripts/verify_authority_migration_fixtures.py --output-dir "$fixture_out" >>"$log" 2>&1 || rc=$?
      fi
      ;;
    static)
      run_allowlisted "$ROOT" python3 -m json.tool "$MANIFEST" >/dev/null
      run_allowlisted "$ROOT" bash -n "$MODULE/bin/verify-candidate" "$MODULE/bin/install-candidate" "$MODULE/bin/install-tailnet-edge" "$MODULE/bin/seat-grant" "$MODULE/bin/migration-provision" \
        "$ROOT/modules/harness/seat/seat-run.sh" "$ROOT/modules/harness/seat/seat-entrypoint.sh" "$ROOT/modules/harness/seat/test/seat-authority.test.sh" \
        "$ROOT/modules/workstation/claude/lib/remote-runner.sh" "$ROOT/modules/workstation/claude/tests/remote-runner-path.test.sh"
      run_allowlisted "$ROOT" node --check "$ROOT/modules/harness/seat/seat-creds.mjs"
      run_allowlisted "$ROOT" node --check "$ROOT/modules/harness/seat/remote-seat.mjs"
      run_allowlisted "$ROOT" node --check "$ROOT/modules/workstation/claude/lib/buildbox-registry.mjs"
      run_allowlisted "$ROOT" python3 -m py_compile "$MODULE/lib/tailnet_edge.py" \
        "$ROOT/modules/systray/account_registry.py" \
        "$ROOT/modules/systray/authority_client.py" \
        "$ROOT/modules/systray/authority_migration.py" \
        "$ROOT/modules/systray/gateway_account_manager.py" \
        "$ROOT/modules/systray/gateway_account_cli.py" \
        "$ROOT/modules/systray/claudex.py" \
        "$ROOT/modules/systray/claudex_router.py" \
        "$ROOT/modules/systray/command_router.py" \
        "$ROOT/modules/systray/indicator.py" \
        "$ROOT/modules/systray/install.py" \
        "$ROOT/modules/systray/tray_model.py" \
        "$ROOT/modules/systray/ui/view_model.py" \
        "$ROOT/modules/systray/ui/account_card.py" \
        "$ROOT/modules/systray/k3s_dispatch.py" \
        "$ROOT/modules/systray/provider_services.py" \
        "$ROOT/modules/systray/remote_dispatch.py" \
        "$ROOT/modules/systray/tests/test_authority_migration.py" \
        "$ROOT/modules/systray/tests/test_provider_services.py" \
        "$ROOT/modules/systray/tests/test_command_router_authority.py" \
        "$ROOT/modules/systray/tests/test_account_registry.py" \
        "$ROOT/modules/systray/tests/test_authority_client.py" \
        "$ROOT/modules/systray/tests/test_gateway_account_manager.py" \
        "$ROOT/modules/systray/tests/test_gateway_account_cli.py" \
        "$ROOT/modules/systray/tests/test_claudex.py" \
        "$ROOT/modules/systray/tests/test_claudex_router.py" \
        "$ROOT/modules/systray/tests/test_tray_model.py" \
        "$ROOT/modules/systray/tests/test_ui_account_card.py" \
        "$ROOT/modules/systray/tests/test_ui_view_model.py" \
        "$ROOT/modules/systray/tests/test_ui_dashboard.py" \
        "$ROOT/modules/systray/tests/test_indicator.py" \
        "$ROOT/modules/systray/tests/test_install.py" \
        "$ROOT/modules/systray/tests/test_packaging_desktop_entry.py" \
        "$ROOT/modules/systray/tests/test_k3s_dispatch.py" \
        "$ROOT/modules/systray/scripts/verify_authority_migration_fixtures.py"
      unit_check="$work/overdeck-subrouter.service"
      run_allowlisted "$ROOT" python3 - "$MODULE/systemd/overdeck-subrouter.service" "$unit_check" <<'PY'
import pathlib, sys
source = pathlib.Path(sys.argv[1]).read_text()
needle = "/var/lib/overdeck/subrouter/current/bin/subrouter"
if source.count(needle) != 1:
    raise SystemExit("unit must contain exactly one installed ExecStart path")
pathlib.Path(sys.argv[2]).write_text(source.replace(needle, "/bin/true"))
PY
      run_allowlisted "$ROOT" systemd-analyze verify "$unit_check" >"$log" 2>&1 || rc=$?
      if (( rc == 0 )); then
        mapfile -t go_files < <(run_allowlisted "$ROOT" git -C "$work/source" diff --name-only -- '*.go')
        [[ ${#go_files[@]} -gt 0 ]] || die 'patch changes no Go files'
        if [[ -n "$(run_confined "$work/source" gofmt -d "${go_files[@]}")" ]]; then rc=1; printf '%s\n' 'gofmt produced a diff' >>"$log"; fi
      fi
      if (( rc == 0 )); then run_confined "$work/source" go vet ./internal/accounts ./internal/agents/claude ./internal/authority ./internal/proxy ./cmd/subrouter >>"$log" 2>&1 || rc=$?; fi
      if (( rc == 0 )); then run_allowlisted "$ROOT" git -C "$work/source" diff --check >>"$log" 2>&1 || rc=$?; fi
      ;;
    module)
      command -v python3 >/dev/null 2>&1 || die 'worker has no Python runtime'
      [[ "$(run_python_confined "$ROOT" python3 -m pytest --version)" == "pytest 9.1.1" ]] || die 'worker pytest runtime is not 9.1.1'
      mkdir -p "$work/module-pytest"
      local collect_file="$work/module-nodeids.txt" collected nodeids_sha
      run_python_confined "$ROOT" python3 -m pytest modules/subrouter/tests/ --collect-only -q 2>/dev/null \
        | sed -n '/::/p' | LC_ALL=C sort >"$collect_file"
      collected=$(wc -l <"$collect_file" | tr -d ' ')
      [[ "$collected" =~ ^[1-9][0-9]*$ ]] || die 'module collection produced no tests'
      nodeids_sha=$(sha256sum "$collect_file" | cut -d' ' -f1)
      log="$artifact/logs/module.log"
      run_python_confined "$ROOT" python3 -m pytest modules/subrouter/tests/ -q --basetemp "$work/module-pytest" >"$log" 2>&1 || rc=$?
      if (( rc == 0 )); then
        write_remote_module_record "$artifact" "$started" "$log" "$work/module-pytest" "$tree_key" "$tree_diff" "$provenance" "$collected" "$nodeids_sha"
      fi
      ;;
    full)
      run_confined "$work/source" go test ./... >"$log" 2>&1 || rc=$?
      if (( rc == 0 )); then
        cp -- "$MANIFEST" "$artifact/manifest.json"
        mkdir -p "$artifact/bin"
        run_confined "$work/source" go build -trimpath -ldflags "-X main.authorityRevision=$(manifest_field revision) -X main.authoritySourceDigest=$(manifest_field archive_sha256) -X main.authorityPatchDigest=$(patch_digest)" -o "$artifact/bin/subrouter" ./cmd/subrouter >>"$log" 2>&1 || rc=$?
      fi
      ;;
    *) die 'invalid worker phase' ;;
  esac
  if [[ "$phase" != module ]]; then
    write_worker_record "$artifact" "$phase" "$started" "$rc" "$log" "$tree_key" "$tree_diff" "$provenance"
  fi
  (( rc == 0 )) || {
    python3 - "$log" <<'PY' >&2
import pathlib, sys
print(pathlib.Path(sys.argv[1]).read_text(errors="replace")[-8192:])
PY
    return "$rc"
  }
  if [[ "$phase" == full ]]; then
    sha256sum "$artifact/bin/subrouter" >"$artifact/bin/subrouter.sha256"
  fi
}

run_remote_phase() {
  local phase=$1 tree_key=$2 key log
  key="subrouter-${tree_key:0:16}-$phase"
  mkdir -p "$ARTIFACT_ROOT/.work-$tree_key/logs"
  log="$ARTIFACT_ROOT/.work-$tree_key/logs/dispatch-$phase.log"
  local gate="$HOME/.claude/bin/local-gate"
  [[ -x "$gate" ]] || die 'installed local-gate is unavailable'
  local dispatch_owner="$ROOT/modules/botmaster/tgbot"
  [[ -f "$dispatch_owner/package.json" ]] || die 'candidate dispatch package owner is missing'
  (
    cd "$dispatch_owner"
    "$gate" --remote-only --key "$key" --mode full -- "$MODULE/bin/verify-candidate" __worker "$phase" "$tree_key" "$TREE_DIFF"
  ) 2>&1 | tee "$log"
  [[ -f "$ARTIFACT_ROOT/.work-$tree_key/worker-$phase.json" ]] || die "remote $phase produced no worker record"
}

validate_worker_record() {
  local artifact=$1 phase=$2
  python3 - "$artifact" "$phase" "$TREE_KEY" "$TREE_DIFF" "$REGISTRY" <<'PY'
import datetime, hashlib, json, pathlib, re, sys
artifact = pathlib.Path(sys.argv[1])
phase = sys.argv[2]
record = json.loads((artifact / f"worker-{phase}.json").read_text())
if record.get("phase") != phase or record.get("exit") != 0:
    raise SystemExit(f"invalid {phase} worker result")
if record.get("input_digest") != sys.argv[3] or record.get("tree_diff_sha256") != sys.argv[4]:
    raise SystemExit(f"{phase} worker result is for different inputs")
if not re.fullmatch(r"[0-9a-f]{64}", record.get("go_sum_sha256", "")):
    raise SystemExit(f"invalid {phase} dependency digest")
provenance_path = artifact / f"dispatch-{phase}.json"
if not provenance_path.is_file() or hashlib.sha256(provenance_path.read_bytes()).hexdigest() != record.get("dispatch_sha256"):
    raise SystemExit(f"invalid {phase} dispatch receipt")
dispatch = json.loads(provenance_path.read_text())
if record.get("dispatch") != dispatch:
    raise SystemExit(f"tampered {phase} dispatch record")
expected_key = f"subrouter-{sys.argv[3][:16]}-{phase}"
if dispatch.get("schema") != 1 or dispatch.get("dispatch_key") != expected_key:
    raise SystemExit(f"invalid {phase} local-gate dispatch key")
remote_meta = dispatch.get("remote_meta")
expected_tail = ["__worker", phase, sys.argv[3], sys.argv[4]]
if not isinstance(remote_meta, dict) or remote_meta.get("key") != expected_key or remote_meta.get("env") not in ({}, None):
    raise SystemExit(f"invalid {phase} authenticated dispatch metadata")
argv = remote_meta.get("argv")
if not isinstance(argv, list) or len(argv) < 5 or argv[-4:] != expected_tail or not str(argv[-5]).endswith("/modules/subrouter/bin/verify-candidate"):
    raise SystemExit(f"invalid {phase} authenticated dispatch command")
remote_meta_raw = dispatch.get("remote_meta_raw")
if not isinstance(remote_meta_raw, str) or hashlib.sha256(remote_meta_raw.encode()).hexdigest() != dispatch.get("meta_sha256"):
    raise SystemExit(f"tampered {phase} authenticated dispatch metadata")
try:
    if json.loads(remote_meta_raw) != remote_meta:
        raise SystemExit(f"tampered {phase} authenticated dispatch metadata representation")
except (TypeError, ValueError):
    raise SystemExit(f"invalid {phase} authenticated dispatch metadata representation")
if hashlib.sha256(json.dumps(argv, separators=(",", ":")).encode()).hexdigest() != dispatch.get("argv_sha256"):
    raise SystemExit(f"tampered {phase} authenticated dispatch command")
if remote_meta.get("epoch") != dispatch.get("epoch") or remote_meta.get("started_at") != dispatch.get("started_at"):
    raise SystemExit(f"tampered {phase} dispatch binding")
if dispatch.get("worker") != record.get("worker") or dispatch.get("identity_source") != "machine-id":
    raise SystemExit(f"unregistered {phase} worker identity")
for field in ("argv_sha256", "meta_sha256", "registry_sha256", "machine_id_sha256"):
    if not re.fullmatch(r"[0-9a-f]{64}", dispatch.get(field, "")):
        raise SystemExit(f"invalid {phase} dispatch {field}")
registry_path = pathlib.Path(sys.argv[5])
if dispatch["registry_sha256"] != hashlib.sha256(registry_path.read_bytes()).hexdigest():
    raise SystemExit(f"unregistered {phase} worker registry")
registry = json.loads(registry_path.read_text())
registered = next((host for host in registry.get("hosts", []) if host.get("name") == dispatch.get("worker")), None)
if not registered or registered.get("state") != "reachable" or dispatch["worker"] not in registry.get("orders", {}).get("build", []):
    raise SystemExit(f"unregistered {phase} worker identity")
machine_id = registered.get("machine_id", "")
if not re.fullmatch(r"[0-9a-f]{32}", machine_id) or hashlib.sha256(machine_id.encode()).hexdigest() != dispatch["machine_id_sha256"]:
    raise SystemExit(f"unregistered {phase} worker machine identity")
if not isinstance(dispatch.get("epoch"), str) or not dispatch["epoch"].isdigit() or int(dispatch["epoch"]) <= 0 or not re.fullmatch(r"[A-Za-z0-9_.-]+", dispatch.get("job_id", "")):
    raise SystemExit(f"invalid {phase} remote dispatch receipt")
try:
    if not dispatch.get("started_at", "").endswith("Z") or not record.get("ended_at", "").endswith("Z"):
        raise ValueError("timestamps must be UTC Z")
    dispatch_started = datetime.datetime.fromisoformat(dispatch["started_at"].replace("Z", "+00:00")).timestamp()
    ended = datetime.datetime.fromisoformat(record["ended_at"].replace("Z", "+00:00")).timestamp()
except (KeyError, TypeError, ValueError):
    raise SystemExit(f"invalid {phase} timing record")
started = record.get("started_epoch")
elapsed = record.get("elapsed_seconds")
if not isinstance(started, int) or not isinstance(elapsed, int) or elapsed < 0 or started < dispatch_started - 1 or abs((started + elapsed) - ended) > 1:
    raise SystemExit(f"invalid {phase} timing record")
log = artifact / "logs" / record["log"]
if not log.is_file() or hashlib.sha256(log.read_bytes()).hexdigest() != record.get("log_sha256"):
    raise SystemExit(f"invalid {phase} log")
if phase == "module":
    if not record.get("tool_version", "").startswith("Python 3."):
        raise SystemExit("wrong Python toolchain in module")
else:
    if record.get("go_version", "").split()[2] != "go1.24.0":
        raise SystemExit(f"wrong Go toolchain in {phase}")
PY
}

write_remote_module_record() {
  local artifact=$1 started=$2 log=$3 basetemp=$4 tree_key=$5 tree_diff=$6 provenance=$7 collected=$8 nodeids_sha=$9
  local ended elapsed worker python_tool
  ended=$(date -u +%Y-%m-%dT%H:%M:%SZ)
  elapsed=$(( $(date +%s) - started ))
  worker=$(python3 - "$provenance" <<'PY'
import json, pathlib, sys
print(json.loads(pathlib.Path(sys.argv[1]).read_text())["worker"])
PY
)
  python_tool=$(run_python_confined "$ROOT" python3 --version 2>&1)
  python3 - "$artifact" "$started" "$ended" "$elapsed" "$worker" "$python_tool" "$log" "$basetemp" "$tree_key" "$tree_diff" "$collected" "$nodeids_sha" "$artifact/.go-sum.sha256" "$provenance" <<'PY'
import hashlib, json, os, pathlib, sys, tempfile
artifact = pathlib.Path(sys.argv[1])
log = pathlib.Path(sys.argv[7])
go_sum_path = pathlib.Path(sys.argv[13])
provenance_path = pathlib.Path(sys.argv[14])
provenance = json.loads(provenance_path.read_text())
payload = {
    "phase": "module",
    "input_digest": sys.argv[9],
    "tree_diff_sha256": sys.argv[10],
    "collected_tests": int(sys.argv[11]),
    "nodeids_sha256": sys.argv[12],
    "started_epoch": int(sys.argv[2]),
    "ended_at": sys.argv[3],
    "elapsed_seconds": int(sys.argv[4]),
    "exit": 0,
    "worker": sys.argv[5],
    "tool_version": sys.argv[6],
    "dispatch": provenance,
    "dispatch_sha256": hashlib.sha256(provenance_path.read_bytes()).hexdigest(),
    "go_sum_sha256": go_sum_path.read_text().strip(),
    "log": log.name,
    "log_sha256": hashlib.sha256(log.read_bytes()).hexdigest(),
    "basetemp": sys.argv[8],
}
fd, name = tempfile.mkstemp(prefix=".module.", dir=artifact)
try:
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(payload, handle, sort_keys=True, indent=2)
        handle.write("\n")
        handle.flush(); os.fsync(handle.fileno())
    os.replace(name, artifact / "worker-module.json")
    directory = os.open(artifact, os.O_DIRECTORY)
    try: os.fsync(directory)
    finally: os.close(directory)
finally:
    if os.path.exists(name): os.unlink(name)
PY
}


validate_module_record() {
  local artifact=$1
  validate_worker_record "$artifact" module
  python3 - "$artifact" "$ROOT" "$TREE_KEY" "$TREE_DIFF" <<'PY'
import hashlib, json, pathlib, re, sys
artifact = pathlib.Path(sys.argv[1])
root = pathlib.Path(sys.argv[2]).resolve()
record = json.loads((artifact / "worker-module.json").read_text())
if record.get("phase") != "module" or record.get("exit") != 0:
    raise SystemExit("invalid module result")
if record.get("input_digest") != sys.argv[3] or record.get("tree_diff_sha256") != sys.argv[4]:
    raise SystemExit("module result is for different inputs")
if not isinstance(record.get("collected_tests"), int) or record["collected_tests"] <= 0:
    raise SystemExit("module result collected no tests")
if not re.fullmatch(r"[0-9a-f]{64}", record.get("nodeids_sha256", "")):
    raise SystemExit("module result has invalid node-id digest")
log = artifact / "logs" / record.get("log", "")
if not log.is_file() or hashlib.sha256(log.read_bytes()).hexdigest() != record.get("log_sha256"):
    raise SystemExit("invalid module log")
basetemp = pathlib.Path(record.get("basetemp", ""))
if not basetemp.is_absolute():
    raise SystemExit("module basetemp is not absolute")
try:
    basetemp.resolve().relative_to(root)
except ValueError:
    pass
else:
    raise SystemExit("module basetemp is inside the checkout")
if not record.get("tool_version", "").startswith("Python 3."):
    raise SystemExit("invalid module toolchain")
PY
}

write_final_receipt() {
  local artifact=$1 tree_key=$2 candidate_key=$3
  python3 - "$ROOT" "$artifact" "$tree_key" "$(patch_digest)" "$candidate_key" <<'PY'
import hashlib, json, os, pathlib, platform, subprocess, sys, tempfile, time
root = pathlib.Path(sys.argv[1]).resolve()
artifact = pathlib.Path(sys.argv[2]).resolve()
tree_key, patch_sha, candidate_key = sys.argv[3:6]
manifest = json.loads((root / "modules/subrouter/upstream.json").read_text())
records = {}
for phase in ("focused", "static", "module", "full"):
    records[phase] = json.loads((artifact / f"worker-{phase}.json").read_text())
for phase, record in records.items():
    if record.get("input_digest") != tree_key:
        raise SystemExit(f"{phase} record input mismatch")
if len({records[phase].get("tree_diff_sha256") for phase in records}) != 1:
    raise SystemExit("phase tree-diff digests disagree")
if len({records[phase].get("go_sum_sha256") for phase in ("focused", "static", "full")}) != 1:
    raise SystemExit("phase dependency digests disagree")
binary = artifact / "bin/subrouter"
binary_sha = hashlib.sha256(binary.read_bytes()).hexdigest()
commands = {
    "focused": "modules/subrouter/bin/verify-candidate focused",
    "static": "modules/subrouter/bin/verify-candidate static",
    "module": "modules/subrouter/bin/verify-candidate module",
    "full": "modules/subrouter/bin/verify-candidate full",
}
payload = {
    "schema": 1,
    "complete": True,
    "candidate_digest": candidate_key,
    "base_commit": subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip(),
    "input_digest": tree_key,
    "tree_diff_sha256": records["full"]["tree_diff_sha256"],
    "revision": manifest["revision"],
    "archive_sha256": manifest["archive_sha256"],
    "patch_sha256": patch_sha,
    "go_version_required": manifest["go"],
    "binary_sha256": binary_sha,
    "commands": commands,
    "exits": {phase: records[phase]["exit"] for phase in records},
    "workers": {phase: records[phase]["worker"] for phase in records},
    "dispatch": {phase: records[phase]["dispatch"] for phase in records},
    "toolchains": {phase: records[phase].get("go_version", records[phase].get("tool_version")) for phase in records},
    "timing": {phase: {"started_epoch": records[phase]["started_epoch"], "ended_at": records[phase]["ended_at"], "elapsed_seconds": records[phase]["elapsed_seconds"]} for phase in records},
    "logs": {phase: {"path": "logs/" + records[phase]["log"], "sha256": records[phase]["log_sha256"]} for phase in records},
    "dependency_state": {"go_sum_sha256": records["full"]["go_sum_sha256"]},
    "temp_root_policy": "${XDG_CACHE_HOME:-$HOME/.cache}/overdeck/tests/subrouter/<unique-run>",
    "module_basetemp": records["module"]["basetemp"],
    "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
# Derive the dependency lock hash from the clean patched source indirectly from
# the pinned archive plus patch; neither mutable module caches nor build trees
# enter the candidate.
payload["dependency_state"]["source_archive_plus_patch_sha256"] = hashlib.sha256((manifest["archive_sha256"] + "\0" + patch_sha).encode()).hexdigest()
for path in artifact.rglob("*"):
    if path.is_file():
        descriptor = os.open(path, os.O_RDONLY)
        try: os.fsync(descriptor)
        finally: os.close(descriptor)
for path in sorted((p for p in artifact.rglob("*") if p.is_dir()), reverse=True):
    descriptor = os.open(path, os.O_DIRECTORY)
    try: os.fsync(descriptor)
    finally: os.close(descriptor)
fd, tmp = tempfile.mkstemp(prefix=".receipt.", dir=artifact)
try:
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        json.dump(payload, handle, sort_keys=True, indent=2)
        handle.write("\n")
        handle.flush(); os.fsync(handle.fileno())
    os.replace(tmp, artifact / "receipt.json")
    directory = os.open(artifact, os.O_DIRECTORY)
    try: os.fsync(directory)
    finally: os.close(directory)
finally:
    if os.path.exists(tmp): os.unlink(tmp)
PY
}

seal_artifact() {
  local artifact=$1
  python3 - "$artifact" <<'PY'
import pathlib, sys
artifact = pathlib.Path(sys.argv[1])
binary = artifact / "bin/subrouter"
for path in artifact.rglob("*"):
    if path.is_file():
        path.chmod(0o555 if path == binary else 0o444)
for path in sorted((p for p in artifact.rglob("*") if p.is_dir()), reverse=True):
    path.chmod(0o555)
artifact.chmod(0o555)
PY
}

validate_artifact() {
  local artifact=$1 tree_key=$2
  python3 - "$ROOT" "$artifact" "$tree_key" "$(patch_digest)" "$ARTIFACT_ROOT" "$TREE_DIFF" <<'PY'
import hashlib, json, os, pathlib, re, stat, subprocess, sys
root = pathlib.Path(sys.argv[1]).resolve()
artifact = pathlib.Path(sys.argv[2]).resolve()
tree_key, patch_sha = sys.argv[3:5]
artifact_root = pathlib.Path(sys.argv[5]).resolve()
tree_diff = sys.argv[6]
if not re.fullmatch(r"[0-9a-f]{64}", artifact.name) or not artifact.parent.samefile(artifact_root):
    raise SystemExit("artifact path does not match current digest")
if artifact.stat().st_mode & 0o222:
    raise SystemExit(f"artifact directory is writable: {artifact}")
for path in artifact.rglob("*"):
    mode = path.lstat().st_mode
    if stat.S_ISLNK(mode): raise SystemExit(f"artifact symlink refused: {path}")
    if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)): raise SystemExit(f"artifact special file refused: {path}")
    if mode & 0o222:
        raise SystemExit(f"artifact path is writable: {path}")
receipt_path = artifact / "receipt.json"
binary = artifact / "bin/subrouter"
artifact_manifest = artifact / "manifest.json"
if not receipt_path.is_file() or not binary.is_file() or not artifact_manifest.is_file(): raise SystemExit("artifact is incomplete")
r = json.loads(receipt_path.read_text())
phase_records = {phase: json.loads((artifact / f"worker-{phase}.json").read_text()) for phase in ("focused", "static", "module", "full")}
m = json.loads((root / "modules/subrouter/upstream.json").read_text())
if json.loads(artifact_manifest.read_text()) != m: raise SystemExit("artifact manifest mismatch")
checks = {
    "complete": True,
    "candidate_digest": artifact.name,
    "input_digest": tree_key,
    "tree_diff_sha256": tree_diff,
    "revision": m["revision"],
    "archive_sha256": m["archive_sha256"],
    "patch_sha256": patch_sha,
    "go_version_required": m["go"],
}
for key, expected in checks.items():
    if r.get(key) != expected: raise SystemExit(f"receipt mismatch: {key}")
if r.get("schema") != 1:
    raise SystemExit("receipt schema mismatch")
head = subprocess.check_output(["git", "-c", f"safe.directory={root}", "-C", str(root), "rev-parse", "HEAD"], text=True).strip()
if r.get("base_commit") != head:
    raise SystemExit("receipt base commit mismatch")
expected_commands = {
    "focused": "modules/subrouter/bin/verify-candidate focused",
    "static": "modules/subrouter/bin/verify-candidate static",
    "module": "modules/subrouter/bin/verify-candidate module",
    "full": "modules/subrouter/bin/verify-candidate full",
}
for phase, command in expected_commands.items():
    record = phase_records[phase]
    if r.get("workers", {}).get(phase) != record.get("worker"): raise SystemExit(f"receipt worker mismatch: {phase}")
    expected_timing = {name: record.get(name) for name in ("started_epoch", "ended_at", "elapsed_seconds")}
    if r.get("timing", {}).get(phase) != expected_timing: raise SystemExit(f"receipt timing mismatch: {phase}")
    if r.get("exits", {}).get(phase) != record.get("exit"): raise SystemExit(f"receipt exit record mismatch: {phase}")
    if r.get("dispatch", {}).get(phase) != record.get("dispatch"):
        raise SystemExit(f"receipt dispatch record mismatch: {phase}")
    if r.get("commands", {}).get(phase) != command: raise SystemExit(f"receipt command mismatch: {phase}")
    worker = r.get("workers", {}).get(phase, "")
    if not isinstance(worker, str) or not worker or len(worker) > 128: raise SystemExit(f"receipt worker mismatch: {phase}")
    timing = r.get("timing", {}).get(phase, {})
    if not isinstance(timing.get("started_epoch"), int) or not isinstance(timing.get("elapsed_seconds"), int) or timing["elapsed_seconds"] < 0:
        raise SystemExit(f"receipt timing mismatch: {phase}")
    if not isinstance(timing.get("ended_at"), str) or not timing["ended_at"].endswith("Z"):
        raise SystemExit(f"receipt end time mismatch: {phase}")
    tool = r.get("toolchains", {}).get(phase, "")
    if phase == "module":
        if not tool.startswith("Python 3."): raise SystemExit("receipt toolchain mismatch: module")
    elif tool.split()[2:3] != ["go" + m["go"]]:
        raise SystemExit(f"receipt toolchain mismatch: {phase}")
deps = r.get("dependency_state", {})
go_sum_sha = deps.get("go_sum_sha256", "")
if not re.fullmatch(r"[0-9a-f]{64}", go_sum_sha): raise SystemExit("receipt go.sum digest mismatch")
source_patch_sha = hashlib.sha256((m["archive_sha256"] + "\0" + patch_sha).encode()).hexdigest()
if deps.get("source_archive_plus_patch_sha256") != source_patch_sha: raise SystemExit("receipt source dependency digest mismatch")
if r.get("temp_root_policy") != "${XDG_CACHE_HOME:-$HOME/.cache}/overdeck/tests/subrouter/<unique-run>":
    raise SystemExit("receipt temp-root policy mismatch")
module_basetemp = pathlib.Path(r.get("module_basetemp", ""))
if not module_basetemp.is_absolute(): raise SystemExit("receipt module basetemp is not absolute")
try: module_basetemp.resolve().relative_to(root)
except ValueError: pass
else: raise SystemExit("receipt module basetemp is inside checkout")
binary_sha = hashlib.sha256(binary.read_bytes()).hexdigest()
if binary_sha != r.get("binary_sha256"):
    raise SystemExit("binary digest mismatch")
candidate_hash = hashlib.sha256()
for value in (tree_key, m["revision"], m["archive_sha256"], patch_sha, m["go"]):
    candidate_hash.update(value.encode() + b"\0")
candidate_hash.update(bytes.fromhex(binary_sha))
if candidate_hash.hexdigest() != artifact.name:
    raise SystemExit("candidate content digest mismatch")
for phase in ("focused", "static", "module", "full"):
    if r.get("exits", {}).get(phase) != 0: raise SystemExit(f"phase not green: {phase}")
    item = r.get("logs", {}).get(phase, {})
    log = artifact / item.get("path", "")
    try: log.resolve().relative_to(artifact)
    except ValueError: raise SystemExit(f"log escapes artifact: {phase}")
    if not log.is_file() or hashlib.sha256(log.read_bytes()).hexdigest() != item.get("sha256"):
        raise SystemExit(f"log mismatch: {phase}")
expected_tree = {"bin", "bin/subrouter", "logs", "receipt.json", "manifest.json"}
expected_tree.update(r["logs"][phase]["path"] for phase in expected_commands)
expected_tree.update(f"worker-{phase}.json" for phase in expected_commands)
expected_tree.update(f"dispatch-{phase}.json" for phase in expected_commands)
actual_tree = {path.relative_to(artifact).as_posix() for path in artifact.rglob("*")}
if actual_tree != expected_tree:
    raise SystemExit("artifact tree does not exactly match receipt")
PY
}

require_manifest
validate_patch_scope
TREE_KEY=$(input_digest)
TREE_DIFF=$(tree_diff_digest)
ARTIFACT="$ARTIFACT_ROOT/.work-$TREE_KEY"

case "$PHASE" in
  __worker)
    [[ $# -eq 4 ]] || die 'invalid worker invocation'
    worker_phase "$2" "$3" "$4"
    ;;
  focused)
    rm -rf -- "$ARTIFACT"
    run_remote_phase focused "$TREE_KEY"
    validate_worker_record "$ARTIFACT" focused
    ;;
  static)
    [[ -d "$ARTIFACT" ]] || die 'focused result is missing for this exact tree'
    validate_worker_record "$ARTIFACT" focused
    run_remote_phase static "$TREE_KEY"
    validate_worker_record "$ARTIFACT" static
    ;;
  module)
    [[ -d "$ARTIFACT" ]] || die 'focused and static results are missing for this exact tree'
    validate_worker_record "$ARTIFACT" focused
    validate_worker_record "$ARTIFACT" static
    run_remote_phase module "$TREE_KEY"
    validate_module_record "$ARTIFACT"
    ;;
  full)
    [[ -d "$ARTIFACT" ]] || die 'focused, static, and module results are missing for this exact tree'
    validate_worker_record "$ARTIFACT" focused
    validate_worker_record "$ARTIFACT" static
    validate_module_record "$ARTIFACT"
    run_remote_phase full "$TREE_KEY"
    validate_worker_record "$ARTIFACT" full
    [[ -f "$ARTIFACT/bin/subrouter" ]] || die 'full worker produced no binary'
    CANDIDATE_KEY=$(candidate_digest "$ARTIFACT" "$TREE_KEY")
    CANDIDATE_ARTIFACT="$ARTIFACT_ROOT/$CANDIDATE_KEY"
    [[ ! -e "$CANDIDATE_ARTIFACT" ]] || die 'content-addressed candidate already exists; refusing replacement'
    rm -f -- "$ARTIFACT/.go-sum.sha256" "$ARTIFACT/bin/subrouter.sha256" \
      "$ARTIFACT/logs/dispatch-focused.log" "$ARTIFACT/logs/dispatch-static.log" \
      "$ARTIFACT/logs/dispatch-module.log" "$ARTIFACT/logs/dispatch-full.log"
    write_final_receipt "$ARTIFACT" "$TREE_KEY" "$CANDIDATE_KEY"
    mv -- "$ARTIFACT" "$CANDIDATE_ARTIFACT"
    seal_artifact "$CANDIDATE_ARTIFACT"
    sync -f "$ARTIFACT_ROOT"
    ARTIFACT="$CANDIDATE_ARTIFACT"
    validate_artifact "$ARTIFACT" "$TREE_KEY"
    ;;
  path)
    ARTIFACT=$(find_candidate)
    validate_worker_record "$ARTIFACT" focused
    validate_worker_record "$ARTIFACT" static
    validate_module_record "$ARTIFACT"
    validate_worker_record "$ARTIFACT" full
    validate_artifact "$ARTIFACT" "$TREE_KEY"
    printf '%s\n' "$ARTIFACT"
    ;;
  *) die 'usage: verify-candidate focused|static|module|full|path' ;;
esac
