#!/usr/bin/env bash
set -u

HERE="$(cd "$(dirname "$0")" && pwd)"
SCRIPT="$HERE/deploy-local.sh"
TMP="$(mktemp -d)"
# Agent shells carry PYTHONPYCACHEPREFIX as the literal, unexpanded, RELATIVE string
# '%h/.cache/python-bytecode'. Every python3 the deploy runs then creates a literal '%h/'
# tree in its cwd — the fixture's deploy clone — which has no .gitignore, so deckctl sees
# an untracked path and refuses with "deploy clone is dirty". That killed the first case
# and 20 downstream assertions with it: measured PASS=23/FAIL=21 on this laptop versus
# PASS=44/FAIL=0 on a buildbox, purely because buildboxes do not set the variable. Pin it
# absolute so the suite reports the code, not the shell it happened to run in.
export PYTHONPYCACHEPREFIX="$TMP/pycache"
# Fixture deploys must never reach the owner's Telegram — real "Deploy FAILED at
# no-deploy-clone: ... /tmp.XXXX/absent-clone" messages from this suite did.
export OVERDECK_DEPLOY_NOTIFY=0
# Fixture smokes must exhaust their monotonic budget without real sleeps.
export OVERDECK_SMOKE_READINESS_TIMEOUT=60
export OVERDECK_SMOKE_READINESS_DELAY=1
cleanup() {
  if [[ "${OVERDECK_TEST_KEEP_TMP:-0}" == 1 ]]; then
    printf 'deploy-local test fixture kept at %s\n' "$TMP" >&2
    return
  fi
  chmod -R u+w "$TMP" 2>/dev/null || true
  rm -rf "$TMP"
}
trap cleanup EXIT

PASS=0
FAIL=0

ok() { PASS=$((PASS + 1)); printf 'ok - %s\n' "$1"; }
bad() { FAIL=$((FAIL + 1)); printf 'not ok - %s\n' "$1"; }

run_case() {
  local mode="$1"
  local collector="${2:-reachable}"
  local case_dir="$TMP/$mode"
  local bin="$case_dir/bin"
  local caller="$case_dir/caller"
  local deploy="$case_dir/deploy"
  local fixture_target fixture_ancestor fixture_unrelated fixture_tree
  mkdir -p "$bin" "$caller/packaging/lib" "$deploy/.git" "$deploy/packaging/lib" \
    "$deploy/bin" "$deploy/lib/deckctl" "$deploy/lib/fleet" "$deploy/modules/workstation/manifest" \
    "$deploy/modules/buildbox" "$deploy/modules/fleet" "$deploy/modules/systray" "$deploy/modules/fire-consumer" \
    "$deploy/modules/monitor/systemd/user" "$deploy/modules/workstation/systemd/user" \
    "$case_dir/home/.config/systemd/user/harnessd.service.d" \
    "$case_dir/home/.local/opt/overdeck/harness/current"
  touch "$case_dir/home/.config/systemd/user/harnessd.service.d/override.conf"
  touch "$case_dir/home/.local/opt/overdeck/harness/current/legacy"
  cp "$SCRIPT" "$caller/packaging/deploy-local.sh"
  cp "$SCRIPT" "$deploy/packaging/deploy-local.sh"
  cp "$HERE/../.npmrc" "$deploy/.npmrc"
  cp "$HERE/lib/release-tree.sh" "$caller/packaging/lib/release-tree.sh"
  cp "$HERE/lib/release-tree.sh" "$deploy/packaging/lib/release-tree.sh"
  cp "$HERE/lib/main-checkout-ff-sync.sh" "$caller/packaging/lib/main-checkout-ff-sync.sh"
  cp "$HERE/lib/main-checkout-ff-sync.sh" "$deploy/packaging/lib/main-checkout-ff-sync.sh"
  cp "$HERE/lib/readiness.sh" "$caller/packaging/lib/readiness.sh"
  cp "$HERE/lib/readiness.sh" "$deploy/packaging/lib/readiness.sh"
  cp "$HERE/lib/component-receipts.sh" "$caller/packaging/lib/component-receipts.sh"
  cp "$HERE/lib/component-receipts.sh" "$deploy/packaging/lib/component-receipts.sh"
  cp "$HERE/../bin/deckctl" "$deploy/bin/deckctl.real"
  cat >"$deploy/bin/deckctl" <<'SH'
#!/usr/bin/env bash
[[ -f "$CHECKOUT_MARKER" ]] || exit 93
exec "$(dirname "$0")/deckctl.real" "$@"
SH
  chmod +x "$deploy/bin/deckctl"
  cp "$HERE/../lib/deckctl/sync.sh" "$deploy/lib/deckctl/sync.sh"
  cp -a "$HERE/../lib/fleet/." "$deploy/lib/fleet/"
  cp -a "$HERE/../modules/fleet/." "$deploy/modules/fleet/"
  cp "$HERE/../modules/buildbox/devtools.json" "$deploy/modules/buildbox/devtools.json"
  cp "$HERE/../modules/workstation/manifest/claude.json" "$deploy/modules/workstation/manifest/claude.json"
  cp "$HERE/../modules/workstation/manifest/bin.json" "$deploy/modules/workstation/manifest/bin.json"
  cp "$HERE/../modules/workstation/manifest/pi.json" "$deploy/modules/workstation/manifest/pi.json"
  cp -a "$HERE/../modules/workstation/pi" "$deploy/modules/workstation/pi"
  mkdir -p "$deploy/modules/gptbridge"
  printf '#!/usr/bin/env bash\nexit 0\n' >"$deploy/modules/gptbridge/install.sh"
  chmod +x "$deploy/modules/gptbridge/install.sh"
  cp "$HERE/../modules/workstation/deny.list" "$deploy/modules/workstation/deny.list"
  cp -a "$HERE/../modules/workstation/claude" "$deploy/modules/workstation/claude"
  cp "$HERE/../modules/monitor/systemd/user/agent.slice" "$deploy/modules/monitor/systemd/user/agent.slice"
  cp "$HERE/../modules/workstation/systemd/user/factory-k3s-cleanup.service" \
    "$HERE/../modules/workstation/systemd/user/factory-k3s-cleanup.timer" \
    "$HERE/../modules/workstation/systemd/user/session-transcript-converge.service" \
    "$HERE/../modules/workstation/systemd/user/session-transcript-converge.timer" \
    "$HERE/../modules/workstation/systemd/user/request-evidence-drain.path" \
    "$HERE/../modules/workstation/systemd/user/request-evidence-drain.service" \
    "$HERE/../modules/workstation/systemd/user/request-evidence-drain.timer" \
    "$deploy/modules/workstation/systemd/user/"
  cp "$HERE/overdeck-deploy.path" "$HERE/overdeck-deploy.service" \
    "$HERE/overdeck-web.service" "$HERE/overdeck-web-watchdog.service" \
    "$HERE/overdeck-controller.service" "$HERE/botmaster-proxy.service" \
    "$HERE/actions-gateway.service" \
    "$deploy/packaging/"
  cp -a "$HERE/../modules/fire-consumer/." "$deploy/modules/fire-consumer/"
  mkdir -p "$case_dir/home/.claude"
  ln -s "$deploy/modules/workstation/claude/buildbox-hosts.json" \
    "$case_dir/home/.claude/buildbox-hosts.json"
  cat >"$deploy/modules/systray/install.py" <<'PY'
from os import environ
from pathlib import Path

with Path(environ["INSTALL_LOG"]).open("a", encoding="utf-8") as log:
    log.write(f"deploy-clone:{__file__}\n")
PY
  if [[ "$mode" == "untracked" ]]; then
    printf '#!/usr/bin/env bash\nprintf injected\\n\n' >"$deploy/modules/workstation/claude/bin/untracked-tool"
  fi
  if [[ "$mode" == "modified" ]]; then
    printf 'foreign edit\n' >>"$deploy/modules/workstation/claude/buildbox-hosts.json"
  fi
  if [[ "$mode" == "landed-dirty" ]]; then
    printf 'landed edit\n' >>"$deploy/modules/workstation/claude/buildbox-hosts.json"
  fi
  if [[ "$mode" == "release-state" || "$mode" == "never-ready" ]]; then
    mkdir -p "$deploy/apps/web/.releases/bootstrap-fixture/server"
    touch "$deploy/apps/web/.releases/bootstrap-fixture/server/entry.mjs"
    ln -s bootstrap-fixture "$deploy/apps/web/.releases/current"
  fi
  if [[ "$mode" == "web-unchanged" || "$mode" == "web-changed" ]]; then
    mkdir -p "$deploy/apps/web/.releases/.build-deadbeef-AAAAAA/server" \
      "$deploy/apps/web/.releases/.build-deadbeef-AAAAAA/node_modules"
    touch "$deploy/apps/web/.releases/.build-deadbeef-AAAAAA/server/entry.mjs"
    ln -s .build-deadbeef-AAAAAA "$deploy/apps/web/.releases/current"
  fi
  if [[ "$mode" == "web-unchanged-dangling" ]]; then
    mkdir -p "$deploy/apps/web/.releases"
    ln -s .build-deadbeef-PRUNED "$deploy/apps/web/.releases/current"
  fi

  mkdir -p "$deploy/modules/workstation/claude/workflows/hooks" "$deploy/collector/scripts"
  touch "$deploy/collector/scripts/brief-canary.ts"
  for stub in modules/workstation/claude/bin/shim-drift-check \
    modules/workstation/claude/workflows/hooks/install-land-guard.sh \
    packaging/web-deps-verify.sh; do
    printf '#!/usr/bin/env bash\nexit 0\n' >"$deploy/$stub"
    chmod +x "$deploy/$stub"
  done
  cat >"$deploy/packaging/web-watchdog.sh" <<'SH'
#!/usr/bin/env bash
if [[ "$CASE_MODE" == "delayed-start" ]]; then
  count_file="$CASE_DIR/watchdog-count"
  count=0
  [[ ! -f "$count_file" ]] || read -r count <"$count_file"
  count=$((count + 1))
  printf '%s\n' "$count" >"$count_file"
  (( count >= 25 ))
  exit
fi
exit 0
SH
  chmod +x "$deploy/packaging/web-watchdog.sh"
  cat >"$deploy/packaging/deploy-readiness.sh" <<'SH'
#!/usr/bin/env bash
count_file="$CASE_DIR/collector-count"
count=0
[[ ! -f "$count_file" ]] || read -r count <"$count_file"
count=$((count + 1))
printf '%s\n' "$count" >"$count_file"
case "${COLLECTOR_MODE:-}" in
  reachable) ;;
  delayed-ready) (( count > 19 )) || { printf 'readiness: waiting: collector=transport(rc=7)\n' >&2; exit 1; } ;;
  *) printf 'readiness: waiting: collector=transport(rc=7)\n' >&2; exit 1 ;;
esac
OVERDECK_WEB_URL="${OVERDECK_READINESS_WEB_URL:-http://127.0.0.1:31337}" \
  OVERDECK_WEB_PAGES_DIR="${OVERDECK_READINESS_WEB_PAGES_DIR:-}" \
  bash "$(dirname "$0")/web-watchdog.sh" sweep || exit $?
printf 'readiness: collector=ready controller=ready botmaster=ready web=ready\n'
SH
  chmod +x "$deploy/packaging/deploy-readiness.sh"
  cat >"$deploy/packaging/web-release.sh" <<'SH'
#!/usr/bin/env bash
verify() {
  local timeout="$1" delay="$2" elapsed=0
  # eval, NOT `bash -c`: the real web-release evals the verify cmd in its own process, so a
  # verify cmd that calls bare `exit` kills it after one probe. The stub must be exactly
  # as fragile while advancing a fake monotonic clock instead of sleeping.
  while true; do
    eval "$OVERDECK_WEB_RELEASE_VERIFY_CMD" && return 0
    elapsed=$((elapsed + delay))
    (( elapsed >= timeout )) && return 1
    sleep "$delay"
  done
}

case "${1:-}" in
  promote) exit 0 ;;
  prune) exit 0 ;;
  activate)
    release="$2"
    current="$(dirname "$release")/current"
    previous="$(dirname "$release")/previous"
    old=""
    old_previous=""
    [[ ! -L "$current" ]] || old="$(readlink "$current")"
    [[ ! -L "$previous" ]] || old_previous="$(readlink "$previous")"
    [[ -z "$old" ]] || ln -sfn "$old" "$previous"
    ln -sfn "$release" "$current"
    timeout="${OVERDECK_WEB_RELEASE_VERIFY_TIMEOUT:-1}"
    delay="${OVERDECK_WEB_RELEASE_VERIFY_DELAY:-1}"
    bash -c "$OVERDECK_WEB_RELEASE_RESTART_CMD" && verify "$timeout" "$delay" && exit 0
    [[ -z "$old" ]] && rm -f "$current" || ln -sfn "$old" "$current"
    [[ -z "$old_previous" ]] && rm -f "$previous" || ln -sfn "$old_previous" "$previous"
    bash -c "$OVERDECK_WEB_RELEASE_RESTART_CMD" && verify "$timeout" "$delay" && exit 1
    exit 2
    ;;
  *) exit 2 ;;
esac
SH
  chmod +x "$deploy/packaging/web-release.sh"
  cat >"$deploy/packaging/stage-backend-release.sh" <<'SH'
#!/usr/bin/env bash
component=$1 sha=$2
root="$OVERDECK_BACKEND_RELEASE_ROOT/$component"
release="$root/releases/$sha"
mkdir -p "$release/bin"
printf '{"schema":1,"component":"%s","target_sha":"%s"}\n' "$component" "$sha" >"$release/release.json"
printf '#!/usr/bin/env bash\nexit 0\n' >"$release/bin/start"
chmod +x "$release/bin/start"
printf 'stage-backend:%s:%s\n' "$component" "$sha" >>"$INSTALL_LOG"
printf '%s\n' "$release"
SH
  cat >"$deploy/packaging/backend-release.sh" <<'SH'
#!/usr/bin/env bash
command=$1 component=$2 sha=$3
root="$OVERDECK_BACKEND_RELEASE_ROOT/$component"
case "$command" in
  validate) [[ -f "$root/releases/$sha/release.json" ]] ;;
  seed)
    mkdir -p "$root"
    ln -sfn "releases/$sha" "$root/current"
    printf 'seed-backend:%s:%s\n' "$component" "$sha" >>"$INSTALL_LOG"
    ;;
  inspect)
    service=$3 expected=$4
    [[ "$expected" == inactive ]] && state=dark || state=healthy
    printf '{"schema":1,"component":"%s","service":"%s","expected":"%s","state":"%s","rollback_ready":true}\n' \
      "$component" "$service" "$expected" "$state"
    ;;
  prune)
    printf '{"schema":1,"component":"%s","status":"pruned","removed":0,"retained":2,"skipped":0}\n' "$component"
    ;;
  select-inactive)
    old=$(readlink "$root/current" 2>/dev/null || true)
    [[ -z "$old" || "$old" == "releases/$sha" ]] || ln -sfn "$old" "$root/previous"
    ln -sfn "releases/$sha" "$root/current"
    printf 'select-backend:%s:%s:%s\n' "$component" "$sha" "$4" >>"$INSTALL_LOG"
    ;;
  activate)
    service=$4
    old=$(readlink "$root/current" 2>/dev/null || true)
    ln -sfn "releases/$sha" "$root/current"
    printf 'activate-backend:%s:%s:%s\n' "$component" "$sha" "$service" >>"$INSTALL_LOG"
    systemctl --user restart "$service" || exit 21
    if [[ "$CASE_MODE" == "collector-rollback" ]]; then
      [[ -z "$old" ]] || ln -sfn "$old" "$root/current"
      systemctl --user restart "$service" || exit 21
      exit 20
    fi
    ;;
  *) exit 64 ;;
esac
SH
  cat >"$deploy/packaging/backend-readiness.sh" <<'SH'
#!/usr/bin/env bash
exit 0
SH
  chmod +x "$deploy/packaging/stage-backend-release.sh" \
    "$deploy/packaging/backend-release.sh" "$deploy/packaging/backend-readiness.sh"
  cat >"$deploy/packaging/web-preflight.sh" <<'SH'
#!/usr/bin/env bash
[[ "$CASE_MODE" != "preflight-fail" && "$CASE_MODE" != "queue-preserve" ]]
SH
  chmod +x "$deploy/packaging/web-preflight.sh"

  # The real parity probe reaches every buildbox over ssh; the fixture supplies its verdict.
  cat >"$deploy/modules/workstation/claude/bin/sandbox-provision" <<'SH'
#!/usr/bin/env bash
printf 'sandbox-parity:%s\n' "$*" >>"$INSTALL_LOG"
printf 'debian1 probed\n'
exit "${SANDBOX_PARITY_RC:-0}"
SH
  chmod +x "$deploy/modules/workstation/claude/bin/sandbox-provision"

  for installer in install-kanboard.sh install-controller.sh install.sh install-botmaster-proxy.sh install-botmaster-notify.sh install-web.sh install-buildbox-parity.sh install-actions-gateway.sh; do
    cat >"$caller/packaging/$installer" <<'SH'
#!/usr/bin/env bash
printf 'stale-caller:%s\n' "$0" >>"$INSTALL_LOG"
exit 91
SH
    cat >"$deploy/packaging/$installer" <<'SH'
#!/usr/bin/env bash
[[ -f "$CHECKOUT_MARKER" ]] || exit 92
printf 'deploy-clone:%s\n' "$0" >>"$INSTALL_LOG"
if [[ "$CASE_MODE" == "receipt-resume" ]]; then
  unit_dir="$HOME/.config/systemd/user"
  mkdir -p "$unit_dir"
  case "$(basename "$0")" in
    install-controller.sh)
      sed -e "s#__CONTROLLER_DIR__#$DEPLOY_ROOT/controller#g" \
        -e "s#__BUN_BIN__#$(command -v bun)#g" \
        "$DEPLOY_ROOT/packaging/overdeck-controller.service" \
        >"$unit_dir/overdeck-controller.service"
      ;;
    install-botmaster-proxy.sh)
      sed -e "s#__BUN_BIN__#$(command -v bun)#g" \
        -e "s#__PROXY_SCRIPT__#$DEPLOY_ROOT/packaging/botmaster-proxy.ts#g" \
        "$DEPLOY_ROOT/packaging/botmaster-proxy.service" \
        >"$unit_dir/botmaster-proxy.service"
      ;;
    install-web.sh)
      sed -e "s#__WEB_DIR__#$DEPLOY_ROOT/apps/web#g" \
        -e "s#__WEB_RELEASE_CURRENT__#$DEPLOY_ROOT/apps/web/.releases/current#g" \
        -e "s#__NODE_BIN__#/usr/bin/node#g" \
        "$DEPLOY_ROOT/packaging/overdeck-web.service" \
        >"$unit_dir/overdeck-web.service"
      sed -e "s#__WATCHDOG_BIN__#$HOME/.local/bin/overdeck-web-watchdog#g" \
        -e "s#__PAGES_DIR__#$DEPLOY_ROOT/apps/web/src/pages#g" \
        "$DEPLOY_ROOT/packaging/overdeck-web-watchdog.service" \
        >"$unit_dir/overdeck-web-watchdog.service"
      ;;
  esac
fi
exit 0
SH
    chmod +x "$caller/packaging/$installer" "$deploy/packaging/$installer"
  done

  cat >"$bin/git" <<'SH'
#!/usr/bin/env bash
if [[ "${1:-}" == "fetch" && "$CASE_MODE" == "fetch-fail" ]]; then
  exit 1
fi
if [[ "${1:-}" == "-C" && "${3:-}" == "merge-base" ]]; then
  exec /usr/bin/git "$@"
fi
if [[ "${1:-}" == "status" ]]; then
  if [[ -f "$DEPLOY_ROOT/modules/workstation/claude/bin/untracked-tool" ]]; then
    printf '?? modules/workstation/claude/bin/untracked-tool\n'
  fi
  if grep -q 'foreign edit' "$DEPLOY_ROOT/modules/workstation/claude/buildbox-hosts.json" 2>/dev/null; then
    printf ' M modules/workstation/claude/buildbox-hosts.json\n'
  fi
  if grep -q 'landed edit' "$DEPLOY_ROOT/modules/workstation/claude/buildbox-hosts.json" 2>/dev/null; then
    printf ' M modules/workstation/claude/buildbox-hosts.json\n'
  fi
  if [[ -d "$DEPLOY_ROOT/apps/web/.releases" ]] \
    && ! grep -qxF '/apps/web/.releases/' "$DEPLOY_ROOT/.git/info/exclude" 2>/dev/null; then
    printf '?? apps/web/.releases/current\n'
  fi
elif [[ "${1:-}" == "checkout" && "${2:-}" == "--quiet" && "${3:-}" == "--detach" && "${4:-}" =~ ^[0-9a-f]{40}$ ]]; then
  [[ -w "$DEPLOY_ROOT/packaging/deploy-local.sh" ]] || exit 94
  printf 'deploy-tree-writable-at-checkout\n' >>"$INSTALL_LOG"
  # real git refuses to switch with a dirty tree, even when dirty bytes match the target
  if grep -q 'landed edit' "$DEPLOY_ROOT/modules/workstation/claude/buildbox-hosts.json" 2>/dev/null; then
    printf 'error: Your local changes to the following files would be overwritten by checkout\n' >&2
    exit 1
  fi
  /usr/bin/git -C "$DEPLOY_ROOT" checkout -q --detach "${4}"
  touch "$CHECKOUT_MARKER"
elif [[ "${1:-}" == "show" && "${2:-}" == *":modules/workstation/claude/buildbox-hosts.json" ]]; then
  [[ "$CASE_MODE" == "landed-dirty" ]] || exit 0
  cat "$DEPLOY_ROOT/modules/workstation/claude/buildbox-hosts.json"
elif [[ "${1:-}" == "reset" && "${2:-}" == "--hard" ]]; then
  sed -i '/^landed edit$/d' "$DEPLOY_ROOT/modules/workstation/claude/buildbox-hosts.json" 2>/dev/null || true
elif [[ "${1:-}" == "rev-parse" ]]; then
  if [[ " $* " == *' --short '* ]]; then
    printf 'deadbeef\n'
  else
    /usr/bin/git -C "$DEPLOY_ROOT" rev-parse "${@:2}"
  fi
elif [[ "${1:-}" == "cat-file" ]]; then
  [[ "$CASE_MODE" != "docsonly-unknown-commit" ]] || exit 1
  exit 0
elif [[ "${1:-}" == "diff" ]]; then
  if [[ " $* " == *" collector/ "* && "${4:-}" != "${5:-}" ]]; then
    exit 1
  fi
  case "$CASE_MODE" in
    web-changed) printf 'apps/web/src/pages/index.astro\n' ;;
    docsonly-skip) printf 'docs/plans/incident-notes.md\nREADME.md\n' ;;
    docsonly-mixed-diff) printf 'docs/incident-notes.md\napps/web/src/pages/index.astro\n' ;;
    docsonly-empty-diff) : ;;
    docsonly-diff-fails) exit 1 ;;
  esac
fi
exit 0
SH
  cat >"$bin/pnpm" <<'JS'
#!/usr/bin/env node
const fs = require('node:fs')
const { execFileSync } = require('node:child_process')
const args = process.argv.slice(2)
const joined = ` ${args.join(' ')} `
const deployRoot = process.env.DEPLOY_ROOT
const installLog = process.env.INSTALL_LOG
const appendInstallLog = (line) => fs.appendFileSync(installLog, `${line}\n`)

if (args[0] === 'config' && args[1] === 'get') {
  process.stdout.write('http://100.101.104.41:4873/\n')
} else if (args[0] === 'view') {
  const tarballs = {
    '@platform-modules/query-react@0.1.0': 'http://100.101.104.41:4873/tarballs/query-react-0.1.0-fixture.tgz',
    '@platform-modules/ui-tokens@0.2.0': 'http://100.101.104.41:4873/tarballs/ui-tokens-0.2.0-fixture.tgz',
  }
  if (!tarballs[args[1]]) process.exit(2)
  process.stdout.write(`${JSON.stringify(tarballs[args[1]])}\n`)
} else if (args[0] === 'install') {
  appendInstallLog('pnpm-install-invoked')
  fs.mkdirSync(`${deployRoot}/node_modules/.pnpm`, { recursive: true })
  for (const specifier of ['astro', '@astrojs/node', '@astrojs/react', '@tailwindcss/vite']) {
    const packageDir = `${deployRoot}/apps/web/node_modules/${specifier}`
    fs.mkdirSync(packageDir, { recursive: true })
    fs.writeFileSync(`${packageDir}/package.json`, JSON.stringify({ name: specifier, main: 'index.js' }))
    fs.writeFileSync(`${packageDir}/index.js`, 'module.exports = {}\n')
  }
} else if (joined.includes(' --filter web build ')) {
  appendInstallLog('pnpm-build-invoked')
  if (process.env.CASE_MODE === 'pin-race') {
    // Advance origin/main without touching the checked-out tree or its recorded pin.
    const git = (...gitArgs) => execFileSync('/usr/bin/git', ['-C', deployRoot, ...gitArgs], { encoding: 'utf8' }).trim()
    const parent = git('rev-parse', 'refs/remotes/origin/main')
    const tree = git('rev-parse', `${parent}^{tree}`)
    const commit = git('-c', 'user.name=Racer', '-c', 'user.email=racer@example.invalid',
      'commit-tree', tree, '-p', parent, '-m', 'concurrent land mid-build')
    git('update-ref', 'refs/remotes/origin/main', commit)
  }
  fs.mkdirSync(`${deployRoot}/apps/web/dist/server`, { recursive: true })
  fs.closeSync(fs.openSync(`${deployRoot}/apps/web/dist/server/entry.mjs`, 'a'))
} else if (joined.includes(' --filter web deploy ')) {
  appendInstallLog('pnpm-deploy-invoked')
  const target = args.at(-1)
  fs.mkdirSync(`${target}/node_modules/pkg`, { recursive: true })
  fs.closeSync(fs.openSync(`${target}/node_modules/pkg/runtime.js`, 'a'))
}
JS
  cat >"$bin/bun" <<'SH'
#!/usr/bin/env bash
[[ "${1:-}" == "scripts/brief-canary.ts" ]] || exit 2
exit 0
SH
  # deckctl's pull-secret scan is a required production guard. The deployment
  # fixture does not exercise scanning itself, so provide the executable it
  # requires and keep the deploy path hermetic.
  cat >"$bin/gitleaks" <<'SH'
#!/usr/bin/env bash
exit 0
SH
  cat >"$bin/od-live-report-refresh" <<'SH'
#!/usr/bin/env bash
if [[ "$CASE_MODE" == "receipt-resume" && ! -e "$CASE_DIR/live-report-failed" ]]; then
  touch "$CASE_DIR/live-report-failed"
  exit 1
fi
exit 0
SH
  cat >"$bin/systemctl" <<'SH'
#!/usr/bin/env bash
printf '%s\n' "$*" >>"$SYSTEMCTL_LOG"
if [[ " $* " == *" is-active "*" actions-gateway.service "* \
  || " $* " == *" is-enabled "*" actions-gateway.service "* ]]; then
  exit 1
fi
if [[ " $* " == *" show -p MainPID --value "* ]]; then
  service="${!#}"
  pid_file="$CASE_DIR/pid-${service//[^a-zA-Z0-9_.-]/_}"
  [[ -f "$pid_file" ]] || printf '1000\n' >"$pid_file"
  cat "$pid_file"
  exit 0
fi
action=""
for arg in "$@"; do
  if [[ "$arg" == restart || "$arg" == try-restart ]]; then
    action=$arg
    continue
  fi
  if [[ -n "$action" && "$arg" == *.service ]]; then
    pid_file="$CASE_DIR/pid-${arg//[^a-zA-Z0-9_.-]/_}"
    pid=1000
    [[ ! -f "$pid_file" ]] || read -r pid <"$pid_file"
    printf '%s\n' "$((pid + 1))" >"$pid_file"
  fi
done
exit 0
SH
  # The notification gate lives at an absolute path this fixture cannot relocate, so the
  # refresh branch would otherwise reach real root on the machine running the test.
  cat >"$bin/deck-sudo" <<'SH'
#!/usr/bin/env bash
printf 'deck-sudo:%s\n' "$*" >>"$INSTALL_LOG"
exit 0
SH
  cat >"$bin/sleep" <<'SH'
#!/usr/bin/env bash
exit 0
SH
  cat >"$bin/curl" <<'SH'
#!/usr/bin/env bash
url="${!#}"
case "$url" in
  *:4873/tarballs/*.tgz) exit 0 ;;
  *:31337/*) printf '200'; exit 0 ;;
  *:31338/*)
    count_file="$CASE_DIR/collector-count"
    count=0
    [[ ! -f "$count_file" ]] || read -r count <"$count_file"
    count=$((count + 1))
    printf '%s\n' "$count" >"$count_file"
    case "${COLLECTOR_MODE:-}" in
      reachable) printf '200'; exit 0 ;;
      delayed-ready)
        (( count > 19 )) && { printf '200'; exit 0; }
        ;;
    esac
    printf '000'
    exit 7
    ;;
  *) exit 2 ;;
esac
SH
  chmod +x "$bin"/*

  /usr/bin/git -C "$deploy" init -q
  printf '/apps/web/dist/\n/apps/web/.releases/\n' >"$deploy/.git/info/exclude"
  /usr/bin/git -C "$deploy" config user.name Fixture
  /usr/bin/git -C "$deploy" config user.email fixture@example.invalid
  /usr/bin/git -C "$deploy" commit --allow-empty -qm "base fixture"
  /usr/bin/git -C "$deploy" add -A
  /usr/bin/git -C "$deploy" commit -qm "fixture"
  fixture_target=$(/usr/bin/git -C "$deploy" rev-parse HEAD)
  fixture_ancestor=$(/usr/bin/git -C "$deploy" rev-parse HEAD^)
  fixture_tree=$(/usr/bin/git -C "$deploy" write-tree)
  fixture_unrelated=$(/usr/bin/git -C "$deploy" commit-tree "$fixture_tree" -m "unrelated fixture")
  /usr/bin/git -C "$deploy" update-ref refs/remotes/origin/main "$fixture_target"
  mkdir -p "$case_dir/home/.local/state/overdeck/deploy-components"
  for component in collector controller botmaster-proxy actions-gateway; do
    printf '{"schema":1,"component":"%s","target_sha":"%s","converged_at":"2026-08-17T00:00:00Z"}\n' \
      "$component" "$fixture_ancestor" \
      >"$case_dir/home/.local/state/overdeck/deploy-components/$component.json"
  done
  case "$mode" in
    docsonly-skip | docsonly-unknown-commit | docsonly-mixed-diff | docsonly-empty-diff | docsonly-diff-fails)
      printf 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n' >"$deploy/.git/harness-deployed-sha" ;;
    docsonly-malformed-stamp)
      printf 'deadbeef\n' >"$deploy/.git/harness-deployed-sha" ;;
  esac
  if [[ "$mode" == "release-state" ]]; then
    mkdir -p "$deploy/modules/workstation/pi/agent"
    printf 'preserved-runtime-auth\n' >"$deploy/modules/workstation/pi/agent/auth.json"
  fi

  if [[ "${QUEUE_SEED:-}" == 1 ]]; then
    mkdir -p "$case_dir/deploy-queue"
    printf '%s\n' "$fixture_target" >"$case_dir/deploy-queue/req-seeded"
  fi
  if [[ "${QUEUE_ANCESTOR_SEED:-}" == 1 ]]; then
    mkdir -p "$case_dir/deploy-queue"
    printf '%s\n' "$fixture_ancestor" >"$case_dir/deploy-queue/req-ancestor"
  fi
  if [[ "${QUEUE_UNRELATED_SEED:-}" == 1 ]]; then
    mkdir -p "$case_dir/deploy-queue"
    printf '%s\n' "$fixture_unrelated" >"$case_dir/deploy-queue/req-unrelated"
  fi
  if [[ "${DEFERRED_SEED:-}" == 1 ]]; then
    mkdir -p "$case_dir/deploy-queue-deferred"
    printf '%s\n' "$fixture_target" >"$case_dir/deploy-queue-deferred/req-deferred"
  fi
  if [[ "${DEFERRED_ANCESTOR_SEED:-}" == 1 ]]; then
    mkdir -p "$case_dir/deploy-queue-deferred"
    printf '%s\n' "$fixture_ancestor" >"$case_dir/deploy-queue-deferred/req-ancestor"
  fi

  # Model the idle state left by the previous successful deploy. The consumer must
  # reopen this tree before its checkout and close it again on success.
  find -P "$deploy" -path "$deploy/.git" -prune -o \( -type d -o -type f \) \
    -exec chmod a-w {} +

  HOME="$case_dir/home" \
    PATH="$bin:$PATH" \
    OVERDECK_DEPLOY_CURL_BIN="$bin/curl" \
    OVERDECK_DEPLOY_DIR="$deploy" \
    OVERDECK_DEPLOY_QUEUE_DIR="$case_dir/deploy-queue" \
    OVERDECK_BACKEND_RELEASE_ROOT="$case_dir/backend" \
    OVERDECK_SMOKE_READINESS_TIMEOUT="${SMOKE_TIMEOUT_OVERRIDE:-$OVERDECK_SMOKE_READINESS_TIMEOUT}" \
    OVERDECK_DEPLOY_TARGET_SHA="${TARGET_OVERRIDE-$fixture_target}" \
    OVERDECK_MAIN_CHECKOUT="$case_dir/main-checkout" \
    OVERDECK_MAIN_CHECKOUT_SYNC_DIR="$case_dir/main-checkout-sync" \
    DEPLOY_ROOT="$deploy" \
    CASE_DIR="$case_dir" \
    CASE_MODE="$mode" \
    COLLECTOR_MODE="$collector" \
    SANDBOX_PARITY_RC="${SANDBOX_PARITY_RC:-0}" \
    CHECKOUT_MARKER="$case_dir/checkout-complete" \
    INSTALL_LOG="$case_dir/install.log" \
    SYSTEMCTL_LOG="$case_dir/systemctl.log" \
    OVERDECK_DEPLOY_CONSUMER=1 \
    bash "$caller/packaging/deploy-local.sh" >"$case_dir/stdout" 2>"$case_dir/stderr"
}

rerun_case() {
  local mode=$1 collector="${2:-$1}" case_dir="$TMP/$1"
  local bin="$case_dir/bin" caller="$case_dir/caller" deploy="$case_dir/deploy" fixture_target
  fixture_target=$(/usr/bin/git -C "$deploy" rev-parse HEAD) || return 1
  HOME="$case_dir/home" \
    PATH="$bin:$PATH" \
    OVERDECK_DEPLOY_CURL_BIN="$bin/curl" \
    OVERDECK_DEPLOY_DIR="$deploy" \
    OVERDECK_DEPLOY_QUEUE_DIR="$case_dir/deploy-queue" \
    OVERDECK_BACKEND_RELEASE_ROOT="$case_dir/backend" \
    OVERDECK_SMOKE_READINESS_TIMEOUT="${SMOKE_TIMEOUT_OVERRIDE:-$OVERDECK_SMOKE_READINESS_TIMEOUT}" \
    OVERDECK_DEPLOY_TARGET_SHA="$fixture_target" \
    OVERDECK_MAIN_CHECKOUT="$case_dir/main-checkout" \
    OVERDECK_MAIN_CHECKOUT_SYNC_DIR="$case_dir/main-checkout-sync" \
    DEPLOY_ROOT="$deploy" \
    CASE_DIR="$case_dir" \
    CASE_MODE="$mode" \
    COLLECTOR_MODE="$collector" \
    SANDBOX_PARITY_RC=0 \
    CHECKOUT_MARKER="$case_dir/checkout-complete" \
    INSTALL_LOG="$case_dir/install.log" \
    SYSTEMCTL_LOG="$case_dir/systemctl.log" \
    OVERDECK_DEPLOY_CONSUMER=1 \
    bash "$caller/packaging/deploy-local.sh" >"$case_dir/retry.stdout" 2>"$case_dir/retry.stderr"
}

if run_case reachable \
  && grep -q '"status":"deployed"' "$TMP/reachable/stdout" \
  && grep -q '"collector_http":"200"' "$TMP/reachable/stdout" \
  && grep -qx 'deploy-tree-writable-at-checkout' "$TMP/reachable/install.log" \
  && [[ ! -w "$TMP/reachable/deploy/packaging/deploy-local.sh" ]] \
  && ! ( : >"$TMP/reachable/deploy/packaging/deploy-local.sh" ) 2>/dev/null; then
  ok "reopens the release tree for checkout and locks it again after deployment"
  ok "requires authenticated collector /health HTTP 200"
else
  printf 'reachable deploy stderr: %s\n' \
    "$(python3 - "$TMP/reachable/stderr" <<'PY'
import pathlib
import sys
path = pathlib.Path(sys.argv[1])
print(path.read_text(encoding="utf-8")[-1200:].replace("\n", " ") if path.exists() else "missing")
PY
)" >&2
  bad "reopens the release tree for checkout and locks it again after deployment"
  bad "requires authenticated collector /health HTTP 200"
fi

if run_case delayed-start reachable \
  && grep -q '"status":"deployed"' "$TMP/delayed-start/stdout" \
  && [[ "$(<"$TMP/delayed-start/watchdog-count")" -eq 25 ]]; then
  ok "waits for the activated web release to become ready"
else
  bad "waits for the activated web release to become ready"
fi

if run_case delayed-collector delayed-ready \
  && grep -q '"status":"deployed"' "$TMP/delayed-collector/stdout" \
  && [[ "$(<"$TMP/delayed-collector/collector-count")" -eq 21 ]]; then
  ok "waits through measured collector cold start without real sleeps"
else
  bad "waits through measured collector cold start without real sleeps"
fi

if run_case release-state reachable \
  && grep -q '"status":"deployed"' "$TMP/release-state/stdout" \
  && grep -qxF '/apps/web/.releases/' "$TMP/release-state/deploy/.git/info/exclude" \
  && grep -qxF '/modules/workstation/pi/agent/auth.json' "$TMP/release-state/deploy/.git/info/exclude" \
  && grep -qxF 'preserved-runtime-auth' "$TMP/release-state/deploy/modules/workstation/pi/agent/auth.json"; then
  ok "accepts generated web releases and runtime auth without weakening the dirty-clone gate"
else
  bad "accepts generated web releases and runtime auth without weakening the dirty-clone gate"
fi

if run_case preflight-fail reachable; then
  bad "removes an immutable release rejected by preflight"
elif grep -q '"status":"web-preflight-failed"' "$TMP/preflight-fail/stderr" \
  && ! compgen -G "$TMP/preflight-fail/deploy/apps/web/.releases/.build-*" >/dev/null; then
  ok "removes an immutable release rejected by preflight"
else
  bad "removes an immutable release rejected by preflight"
fi

if TARGET_OVERRIDE='' run_case direct-target reachable; then
  direct_state="$TMP/direct-target/home/.local/state/overdeck/deploy-status.json"
  direct_target=$(/usr/bin/git -C "$TMP/direct-target/deploy" rev-parse refs/remotes/origin/main)
  if grep -q '"state":"finished","step":"deployed"' "$direct_state" \
    && grep -q "\"target_sha\":\"$direct_target\"" "$direct_state"; then
    ok "fetches the current main target before an explicit targetless deploy"
  else
    bad "fetches the current main target before an explicit targetless deploy"
  fi
else
  bad "fetches the current main target before an explicit targetless deploy"
fi

if run_case fetch-fail reachable; then
  bad "records the exact intended target and transient class before checkout"
else
  fetch_state="$TMP/fetch-fail/home/.local/state/overdeck/deploy-status.json"
  fetch_target=$(/usr/bin/git -C "$TMP/fetch-fail/deploy" rev-parse refs/remotes/origin/main)
  if grep -q '"schema":2' "$fetch_state" \
    && grep -q '"state":"failed","step":"fetch-failed"' "$fetch_state" \
    && grep -q "\"target_sha\":\"$fetch_target\"" "$fetch_state" \
    && grep -q '"failure_class":"transient"' "$fetch_state"; then
    ok "records the exact intended target and transient class before checkout"
  else
    bad "records the exact intended target and transient class before checkout"
  fi
fi

if SANDBOX_PARITY_RC=1 run_case sandboxdrift reachable \
  && grep -q '"reason":"sandbox-image-drift"' "$TMP/sandboxdrift/stderr" \
  && grep -q '"status":"deployed-degraded"' "$TMP/sandboxdrift/stdout"; then
  ok "records sandbox image drift without replaying an otherwise completed deploy"
else
  bad "records sandbox image drift without replaying an otherwise completed deploy"
fi

if SANDBOX_PARITY_RC=4 run_case sandboxunreachable reachable \
  && grep -q '"status":"deployed-degraded"' "$TMP/sandboxunreachable/stdout" \
  && grep -q 'debian1 probed' "$TMP/sandboxunreachable/stderr"; then
  ok "an unreachable buildbox is reported but does not block the deploy"
else
  bad "an unreachable buildbox is reported but does not block the deploy"
fi

if [[ "$(grep -c '^deploy-clone:' "$TMP/reachable/install.log")" -eq 9 ]] \
  && ! grep -q '^stale-caller:' "$TMP/reachable/install.log"; then
  ok "installs all service and command artifacts from the deploy clone, not the stale caller tree"
else
  bad "installs all service and command artifacts from the deploy clone, not the stale caller tree"
fi

if [[ -f "$TMP/reachable/home/.config/systemd/user/agent.slice" ]] \
  && ! grep -q '^CPUQuota=' "$TMP/reachable/home/.config/systemd/user/agent.slice" \
  && grep -qx 'CPUWeight=50' "$TMP/reachable/home/.config/systemd/user/agent.slice" \
  && grep -qx 'TasksMax=16384' "$TMP/reachable/home/.config/systemd/user/agent.slice" \
  && grep -qx -- '--user daemon-reload' "$TMP/reachable/systemctl.log"; then
  ok "installs the non-starving agent scheduling slice without restarting owner scopes"
else
  bad "installs the non-starving agent scheduling slice without restarting owner scopes"
fi

if [[ -f "$TMP/reachable/home/.config/systemd/user/request-evidence-drain.path" ]] \
  && [[ -f "$TMP/reachable/home/.config/systemd/user/request-evidence-drain.service" ]] \
  && [[ -f "$TMP/reachable/home/.config/systemd/user/request-evidence-drain.timer" ]] \
  && grep -qx -- '--user enable --now request-evidence-drain.path request-evidence-drain.timer' "$TMP/reachable/systemctl.log"; then
  ok "installs and enables durable request evidence draining"
else
  bad "installs and enables durable request evidence draining"
fi

if ! grep -qE 'harness-(run|queue|reconcile|watchdog)' "$TMP/reachable/systemctl.log" \
  && [[ ! -e "$TMP/reachable/home/.config/systemd/user/harness-run@.service" ]]; then
  ok "does not install or enable harness coordinator units"
else
  bad "does not install or enable harness coordinator units"
fi

if [[ "$(grep -Ec '^kanboard_status=[$][(]bash "[$][{]DEPLOY[}]/packaging/install-kanboard[.]sh"|^bash "[$][{]DEPLOY[}]/packaging/install-(controller|botmaster-proxy|botmaster-notify|web|buildbox-parity)[.]sh"|^bash "[$][{]DEPLOY[}]/packaging/install[.]sh"' "$SCRIPT")" -eq 7 ]]; then
  ok "all installer commands reference the deploy clone directly"
else
  bad "all installer commands reference the deploy clone directly"
fi

dry_run="$(OVERDECK_DEPLOY_DRY_RUN=1 OVERDECK_DEPLOY_DIR=/tmp/overdeck-deploy-fixture bash "$SCRIPT")"
fire_consumer_dry_line='install-fire-consumer:/tmp/overdeck-deploy-fixture/modules/fire-consumer/overdeck-fire-consumer.{path,service} → $HOME/.config/systemd/user/; systemctl --user enable --now overdeck-fire-consumer.path'
request_evidence_dry_line='install-request-evidence-drain:/tmp/overdeck-deploy-fixture/modules/workstation/systemd/user/request-evidence-drain.{path,service,timer} -> $HOME/.config/systemd/user/; systemctl --user enable --now request-evidence-drain.path request-evidence-drain.timer'
if ! grep -qxF "$fire_consumer_dry_line" <<<"$dry_run"; then
  bad "dry run names the fire consumer install"
fi
if ! grep -qxF "$request_evidence_dry_line" <<<"$dry_run"; then
  bad "dry run names the request evidence drainer install"
fi
# Keep the longstanding full-order assertion below readable; new units have their own
# exact assertions immediately above rather than extending this historical fixture.
dry_run="${dry_run//$'\n'$fire_consumer_dry_line/}"
dry_run="${dry_run//$'\n'$request_evidence_dry_line/}"
if [[ "$dry_run" == $'install-gptbridge-links:/tmp/overdeck-deploy-fixture/modules/gptbridge/install.sh --links-only\nsync-pi-provider:/tmp/overdeck-deploy-fixture/modules/workstation/pi/agent/models.json\ninstall-user-bin:/tmp/overdeck-deploy-fixture/bin/deckctl sync apply bin\ninstall-workstation-bin:/tmp/overdeck-deploy-fixture/bin/deckctl sync apply claude bin\ninstall-workstation-lib:/tmp/overdeck-deploy-fixture/bin/deckctl sync apply claude lib\ninstall-cloudflare-token-registry:/tmp/overdeck-deploy-fixture/bin/deckctl sync apply claude cloudflare-token-targets.json\ninstall-buildbox-registry:/tmp/overdeck-deploy-fixture/bin/deckctl sync apply claude buildbox-hosts.json\ninstall-agent-slice:/tmp/overdeck-deploy-fixture/modules/monitor/systemd/user/agent.slice → $HOME/.config/systemd/user/agent.slice; systemctl --user daemon-reload\ninstall-session-transcript-converge:/tmp/overdeck-deploy-fixture/modules/workstation/systemd/user/session-transcript-converge.{service,timer} → $HOME/.config/systemd/user/; systemctl --user enable --now session-transcript-converge.timer\ninstall-deploy-queue:/tmp/overdeck-deploy-fixture/packaging/overdeck-deploy.{path,service} → $HOME/.config/systemd/user/; systemctl --user enable --now overdeck-deploy.path\ninstall-systray-commands:python3 /tmp/overdeck-deploy-fixture/modules/systray/install.py\ninstall-kanboard:/tmp/overdeck-deploy-fixture/packaging/install-kanboard.sh\ninstall-controller:/tmp/overdeck-deploy-fixture/packaging/install-controller.sh\ninstall-collector:/tmp/overdeck-deploy-fixture/packaging/install.sh\nstage-collector:/tmp/overdeck-deploy-fixture/packaging/stage-backend-release.sh collector <sha>; activate through backend-release.sh with exact-SHA readiness\nstage-controller:/tmp/overdeck-deploy-fixture/packaging/stage-backend-release.sh controller <sha>; activate through backend-release.sh with exact-SHA readiness\nstage-botmaster-proxy:/tmp/overdeck-deploy-fixture/packaging/stage-backend-release.sh botmaster-proxy <sha>; activate through backend-release.sh with exact-SHA readiness\nstage-actions-gateway:/tmp/overdeck-deploy-fixture/packaging/stage-backend-release.sh actions-gateway <sha>; activate through backend-release.sh with exact-SHA authenticated readiness when configured\ninstall-botmaster-proxy:/tmp/overdeck-deploy-fixture/packaging/install-botmaster-proxy.sh\ninstall-botmaster-notify:/tmp/overdeck-deploy-fixture/packaging/install-botmaster-notify.sh\ninstall-web:/tmp/overdeck-deploy-fixture/packaging/install-web.sh\ninstall-buildbox-parity:/tmp/overdeck-deploy-fixture/packaging/install-buildbox-parity.sh\ninstall-actions-gateway:/tmp/overdeck-deploy-fixture/packaging/install-actions-gateway.sh; immutable current/bin/start; configured instances activate with exact-SHA authenticated smoke, absent config stays disabled\nbrief-canary:/tmp/overdeck-deploy-fixture/collector/scripts/brief-canary.ts\nsandbox-image-parity:/tmp/overdeck-deploy-fixture/modules/workstation/claude/bin/sandbox-provision --check --all\nrestart-group:overdeck-web.service overdeck-web-watchdog.service' ]]; then
  ok "dry run reports the complete install and restart order"
else
  bad "dry run reports the complete install and restart order"
fi

if [[ -L "$TMP/reachable/home/.claude/bin" ]] \
  && [[ ! -e "$TMP/reachable/home/.claude/settings.json" ]] \
  && [[ ! -e "$TMP/reachable/home/.claude/skills" ]]; then
  ok "installs no plan launcher on PATH — the factory is the only executor"
else
  bad "installs no plan launcher on PATH — the factory is the only executor"
fi

if [[ -L "$TMP/reachable/home/.claude/lib" ]] \
  && [[ "$(readlink "$TMP/reachable/home/.claude/lib")" == "$TMP/reachable/deploy/modules/workstation/claude/lib" ]] \
  && [[ -L "$TMP/reachable/home/.claude/cloudflare-token-targets.json" ]] \
  && [[ "$(readlink "$TMP/reachable/home/.claude/cloudflare-token-targets.json")" == "$TMP/reachable/deploy/modules/workstation/claude/cloudflare-token-targets.json" ]]; then
  ok "installs token registry runtime files from the deploy clone"
else
  bad "installs token registry runtime files from the deploy clone"
fi

if [[ -L "$TMP/reachable/home/.claude/buildbox-hosts.json" ]] \
  && [[ "$(readlink "$TMP/reachable/home/.claude/buildbox-hosts.json")" == "$TMP/reachable/deploy/modules/workstation/claude/buildbox-hosts.json" ]]; then
  ok "installs the buildbox registry from the deploy clone"
else
  bad "installs the buildbox registry from the deploy clone"
fi

if run_case untracked; then
  bad "rejects untracked binaries before workstation install"
elif grep -q '"status":"deploy-clone-dirty"' "$TMP/untracked/stderr" \
  && [[ ! -e "$TMP/untracked/home/.claude/bin" ]]; then
  ok "rejects untracked binaries before workstation install"
else
  bad "rejects untracked binaries with deploy-clone-dirty status"
fi

# The adoption stage must clear byte-matching dirt and re-pin; later stages still
# fail in this fixture (deckctl sync uses /usr/bin/git against the fake .git — a
# pre-existing suite gap), so assert the stage outcome, not whole-run success.
run_case landed-dirty || true
if ! grep -q '"status":"deploy-clone-dirty"' "$TMP/landed-dirty/stderr" \
  && ! grep -q 'post-adoption re-pin failed' "$TMP/landed-dirty/stderr" \
  && ! grep -q 'landed edit' "$TMP/landed-dirty/deploy/modules/workstation/claude/buildbox-hosts.json" \
  && [[ -f "$TMP/landed-dirty/checkout-complete" ]]; then
  ok "self-heals dirt that byte-matches origin/main (reset before checkout)"
else
  bad "self-heals dirt that byte-matches origin/main (reset before checkout): $(tail -2 "$TMP/landed-dirty/stderr" 2>/dev/null | tr '\n' ' ')"
fi

if run_case modified; then
  bad "rejects a modified tracked file and names it"
elif grep -q '"status":"deploy-clone-dirty"' "$TMP/modified/stderr" \
  && grep -q 'M modules/workstation/claude/buildbox-hosts.json' "$TMP/modified/stderr" \
  && [[ ! -e "$TMP/modified/home/.claude/bin" ]]; then
  ok "rejects a modified tracked file and names it"
else
  bad "rejects a modified tracked file and names it"
fi

run_case pin-race reachable || true
pinned_sha="$(cat "$TMP/pin-race/deploy/.git/deploy-pinned-sha" 2>/dev/null)"
head_sha="$(/usr/bin/git -C "$TMP/pin-race/deploy" rev-parse --verify HEAD 2>/dev/null)"
if [[ -n "$pinned_sha" && "$pinned_sha" == "$head_sha" ]] \
  && ! grep -q 'not pinned to its recorded checkout' "$TMP/pin-race/stderr" \
  && ! grep -q 'refuse pull: deploy clone is not pinned' "$TMP/pin-race/stderr"; then
  ok "a ref that moves mid-build never fails deckctl's pin check — it verifies against the recorded checkout, not live origin/main"
else
  bad "a ref that moves mid-build never fails deckctl's pin check: pinned=$pinned_sha head=$head_sha $(tail -3 "$TMP/pin-race/stderr" | tr '\n' ' ')"
fi

# A pin file that no longer matches HEAD (the clone was hand-edited, or its pin is stale)
# must still refuse — the fix that tolerates a moved origin/main must NOT also tolerate a
# genuinely wrong checkout.
printf 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n' >"$TMP/pin-race/deploy/.git/deploy-pinned-sha"
tamper_out=$(HOME="$TMP/pin-race/home" PATH="$TMP/pin-race/bin:$PATH" \
  OVERDECK_DEPLOY_DIR="$TMP/pin-race/deploy" \
  "$TMP/pin-race/deploy/bin/deckctl.real" sync apply claude bin 2>&1)
tamper_rc=$?
if [[ $tamper_rc -ne 0 ]] && grep -q 'not pinned to its recorded checkout' <<<"$tamper_out"; then
  ok "a tampered/stale pin file is still refused"
else
  bad "a tampered/stale pin file is still refused: rc=$tamper_rc output=$tamper_out"
fi

if SMOKE_TIMEOUT_OVERRIDE=1 run_case never-ready never-ready; then
  bad "rejects a collector that never becomes ready within the smoke budget"
elif grep -q '"status":"smoke-failed-rolled-back"' "$TMP/never-ready/stderr" \
  && grep -q 'collector=transport(rc=7)' "$TMP/never-ready/home/.local/state/overdeck/deploy-status.smoke.log" \
  && grep -qE 'last smoke: .*collector=transport[(]rc=7[)]' "$TMP/never-ready/stderr" \
  && [[ "$(<"$TMP/never-ready/collector-count")" -ge 2 ]] \
  && [[ "$(grep -cx -- '--user restart overdeck-web.service overdeck-web-watchdog.service' "$TMP/never-ready/systemctl.log")" -eq 2 ]] \
  && [[ "$(grep -cx -- '--user restart overdeck-collector.service' "$TMP/never-ready/systemctl.log")" -eq 1 ]] \
  && [[ "$(grep -cx -- '--user restart overdeck-controller.service' "$TMP/never-ready/systemctl.log")" -eq 1 ]] \
  && [[ "$(grep -cx -- '--user restart botmaster-proxy.service' "$TMP/never-ready/systemctl.log")" -eq 1 ]] \
  && [[ "$(readlink "$TMP/never-ready/deploy/apps/web/.releases/current")" == "bootstrap-fixture" ]] \
  && [[ -f "$TMP/never-ready/home/.local/state/overdeck/deploy-components/dependencies.json" ]] \
  && grep -q '"target_sha"' "$TMP/never-ready/home/.local/state/overdeck/deploy-components/collector.json" \
  && [[ ! -e "$TMP/never-ready/home/.local/state/overdeck/deploy-components/web.json" ]]; then
  ok "rolls back the grouped release while preserving independently proven collector convergence"
else
  bad "rolls back the grouped release while preserving independently proven collector convergence"
fi

if run_case collector-rollback reachable; then
  bad "restores the prior immutable collector when candidate readiness fails"
else
  rollback_ancestor=$(/usr/bin/git -C "$TMP/collector-rollback/deploy" rev-parse HEAD^)
  rollback_target=$(/usr/bin/git -C "$TMP/collector-rollback/deploy" rev-parse HEAD)
  if grep -q '"status":"collector-candidate-failed-rolled-back"' "$TMP/collector-rollback/stderr" \
    && [[ "$(readlink "$TMP/collector-rollback/backend/collector/current")" == "releases/$rollback_ancestor" ]] \
    && [[ "$(grep -cx -- '--user restart overdeck-collector.service' "$TMP/collector-rollback/systemctl.log")" -eq 2 ]] \
    && grep -q "\"target_sha\":\"$rollback_ancestor\"" "$TMP/collector-rollback/home/.local/state/overdeck/deploy-components/collector.json" \
    && ! grep -q "\"target_sha\":\"$rollback_target\"" "$TMP/collector-rollback/home/.local/state/overdeck/deploy-components/collector.json"; then
    ok "restores the prior immutable collector when candidate readiness fails"
  else
    bad "restores the prior immutable collector when candidate readiness fails"
  fi
fi

# Single standing consumer: a hand caller (no consumer env/flag) must enqueue and return
# immediately, never take the lock or run the deploy body itself. Only the consumer flag
# (set by overdeck-deploy.service) or the explicit --now escape hatch reaches it.
QUEUE_TEST_TARGET="dddddddddddddddddddddddddddddddddddddddd"
hand_queue="$TMP/hand-caller-queue"
mkdir -p "$hand_queue"
hand_out="$(OVERDECK_DEPLOY_DIR="$TMP/hand-caller-clone" OVERDECK_DEPLOY_QUEUE_DIR="$hand_queue" \
  OVERDECK_DEPLOY_TARGET_SHA="$QUEUE_TEST_TARGET" \
  OVERDECK_DEPLOY_STATE_FILE="$TMP/hand-caller-state.json" bash "$SCRIPT" 2>&1)"
hand_request=$(find "$hand_queue" -maxdepth 1 -name 'req-*' -print -quit)
if grep -q '"status":"deploy-requested"' <<<"$hand_out" \
  && [[ -n "$hand_request" && "$(<"$hand_request")" == "$QUEUE_TEST_TARGET" ]] \
  && [[ "$(find "$hand_queue" -maxdepth 1 -name 'req-*' | wc -l)" -eq 1 ]] \
  && [[ ! -d "$TMP/hand-caller-clone" ]]; then
  ok "a hand invocation (no consumer flag) enqueues a request and never runs the deploy"
else
  bad "a hand invocation (no consumer flag) enqueues a request and never runs the deploy: $hand_out"
fi

consumer_out="$(OVERDECK_DEPLOY_DIR="$TMP/absent-clone-consumer" OVERDECK_DEPLOY_QUEUE_DIR="$TMP/consumer-queue" \
  OVERDECK_DEPLOY_TARGET_SHA="$QUEUE_TEST_TARGET" OVERDECK_DEPLOY_CONSUMER=1 bash "$SCRIPT" 2>&1)"
if grep -q '"status":"no-deploy-clone"' <<<"$consumer_out"; then
  ok "the consumer flag reaches the real deploy path past the enqueue short-circuit"
else
  bad "the consumer flag reaches the real deploy path past the enqueue short-circuit: $consumer_out"
fi

now_out="$(OVERDECK_DEPLOY_DIR="$TMP/absent-clone-now" OVERDECK_DEPLOY_QUEUE_DIR="$TMP/now-queue" \
  OVERDECK_DEPLOY_TARGET_SHA="$QUEUE_TEST_TARGET" bash "$SCRIPT" --now 2>&1)"
if grep -q '"status":"no-deploy-clone"' <<<"$now_out"; then
  ok "the --now flag reaches the real deploy path past the enqueue short-circuit"
else
  bad "the --now flag reaches the real deploy path past the enqueue short-circuit: $now_out"
fi

lock="$TMP/deploy.lock"
queue="$TMP/deploy-queue"
lock_run() {
  OVERDECK_DEPLOY_DIR="$TMP/absent-clone" OVERDECK_DEPLOY_LOCK="$lock" \
    OVERDECK_DEPLOY_QUEUE_DIR="$queue" OVERDECK_DEPLOY_TARGET_SHA="$QUEUE_TEST_TARGET" \
    OVERDECK_DEPLOY_CONSUMER=1 \
    OVERDECK_DEPLOY_LOCK_WAIT="$1" bash "$SCRIPT" 2>&1
}

if lock_run 1 | grep -q '"status":"no-deploy-clone"'; then
  ok "an uncontended deploy takes the lock and proceeds"
else
  bad "an uncontended deploy takes the lock and proceeds"
fi

flock "$lock" -c 'sleep 6' &
holder=$!
sleep 1
if lock_run 2 | grep -q '"status":"deploy-lock-timeout"'; then
  ok "a deploy that cannot take the lock fails loudly instead of racing the holder"
else
  bad "a deploy that cannot take the lock fails loudly instead of racing the holder"
fi
if compgen -G "$queue/req-*" >/dev/null; then
  ok "a timed-out request persists in the queue for the next drainer"
else
  bad "a timed-out request persists in the queue for the next drainer"
fi
rm -f "$queue"/req-*
if lock_run 30 | grep -q '"status":"no-deploy-clone"'; then
  ok "a deploy waits for the holder and then runs, rather than being skipped"
else
  bad "a deploy waits for the holder and then runs, rather than being skipped"
fi
if compgen -G "$queue-deferred/req-*" >/dev/null \
  && ! compgen -G "$queue/req-*" >/dev/null; then
  ok "a requester that becomes the holder defers its failed request outside the active queue"
else
  bad "a requester that becomes the holder defers its failed request outside the active queue"
fi
rm -f "$queue"/req-*
wait "$holder"

flock "$lock" -c 'sleep 30' &
holder=$!
sleep 1
lock_run 30 >"$TMP/coalesced.out" 2>&1 &
requester=$!
for _ in $(seq 50); do
  compgen -G "$queue/req-*" >/dev/null && break
  sleep 0.1
done
rm -f "$queue"/req-*
if wait "$requester" && grep -q '"status":"deployed-coalesced"' "$TMP/coalesced.out"; then
  ok "a queued request exits 0 once a successful deploy drains it"
else
  bad "a queued request exits 0 once a successful deploy drains it"
fi
kill "$holder" 2>/dev/null
wait "$holder" 2>/dev/null

if run_case receipt-resume reachable; then
  receipt_target=$(/usr/bin/git -C "$TMP/receipt-resume/deploy" rev-parse HEAD)
  receipts_complete=1
  for component in dependencies kanboard reaper-notifier collector web controller botmaster-proxy web-watchdog; do
    receipt="$TMP/receipt-resume/home/.local/state/overdeck/deploy-components/$component.json"
    [[ -f "$receipt" ]] && grep -q "\"target_sha\":\"$receipt_target\"" "$receipt" \
      || receipts_complete=0
  done
  if grep -q '"reason":"live-report-refresh-failed"' "$TMP/receipt-resume/stderr" \
    && grep -q '"status":"deployed-degraded"' "$TMP/receipt-resume/stdout" \
    && [[ "$(<"$TMP/receipt-resume/deploy/.git/harness-deployed-sha")" == "$receipt_target" ]] \
    && [[ "$receipts_complete" == 1 ]]; then
    ok "a late report failure preserves completed receipts and commits the deployed target"
  else
    bad "a late report failure preserves completed receipts and commits the deployed target"
  fi
else
  receipt_target=$(/usr/bin/git -C "$TMP/receipt-resume/deploy" rev-parse HEAD)
  bad "a late report failure preserves completed receipts and commits the deployed target"
fi
receipt_pids_before=$(for service in overdeck-collector.service overdeck-web.service overdeck-controller.service botmaster-proxy.service overdeck-web-watchdog.service; do
  printf '%s:%s\n' "$service" "$(<"$TMP/receipt-resume/pid-$service")"
done)

if rerun_case receipt-resume reachable; then retry_rc=0; else retry_rc=1; fi
receipt_pids_after=$(for service in overdeck-collector.service overdeck-web.service overdeck-controller.service botmaster-proxy.service overdeck-web-watchdog.service; do
  printf '%s:%s\n' "$service" "$(<"$TMP/receipt-resume/pid-$service")"
done)
if [[ "$retry_rc" == 0 ]] \
  && grep -q '"status":"deployed-docs-only"' "$TMP/receipt-resume/retry.stdout" \
  && [[ "$(<"$TMP/receipt-resume/deploy/.git/harness-deployed-sha")" == "$receipt_target" ]] \
  && [[ "$(grep -c '^pnpm-install-invoked$' "$TMP/receipt-resume/install.log")" == 1 ]] \
  && [[ "$(grep -c -- '--user restart overdeck-collector.service' "$TMP/receipt-resume/systemctl.log")" == 1 ]] \
  && [[ "$(grep -c -- '--user restart overdeck-controller.service' "$TMP/receipt-resume/systemctl.log")" == 1 ]] \
  && [[ "$(grep -c -- '--user restart botmaster-proxy.service' "$TMP/receipt-resume/systemctl.log")" == 1 ]] \
  && [[ "$(grep -c -- '--user restart overdeck-web.service overdeck-web-watchdog.service' "$TMP/receipt-resume/systemctl.log")" == 1 ]] \
  && [[ "$receipt_pids_after" == "$receipt_pids_before" ]]; then
  ok "retry recognizes the committed target without repeating dependencies or changing service PIDs"
else
  printf 'receipt-resume: retry_rc=%s\nbefore:\n%s\nafter:\n%s\n' \
    "$retry_rc" "$receipt_pids_before" "$receipt_pids_after" >&2
  bad "retry recognizes the committed target without repeating dependencies or changing service PIDs"
fi

if QUEUE_SEED=1 QUEUE_ANCESTOR_SEED=1 \
  DEFERRED_SEED=1 DEFERRED_ANCESTOR_SEED=1 \
  run_case queue-drain reachable \
  && grep -q '"status":"deployed"' "$TMP/queue-drain/stdout" \
  && [[ ! -e "$TMP/queue-drain/deploy-queue/req-seeded" ]] \
  && [[ ! -e "$TMP/queue-drain/deploy-queue/req-ancestor" ]] \
  && [[ ! -e "$TMP/queue-drain/deploy-queue-deferred/req-deferred" ]] \
  && [[ ! -e "$TMP/queue-drain/deploy-queue-deferred/req-ancestor" ]]; then
  ok "a successful deploy drains exact and ancestor active/deferred requests"
else
  bad "a successful deploy drains exact and ancestor active/deferred requests"
fi

if QUEUE_SEED=1 QUEUE_ANCESTOR_SEED=1 QUEUE_UNRELATED_SEED=1 \
  run_case queue-preserve; then
  bad "a failed deploy defers covered requests without consuming unrelated work"
elif grep -q '"status":"web-preflight-failed"' "$TMP/queue-preserve/stderr" \
  && [[ ! -e "$TMP/queue-preserve/deploy-queue/req-seeded" ]] \
  && [[ ! -e "$TMP/queue-preserve/deploy-queue/req-ancestor" ]] \
  && [[ -e "$TMP/queue-preserve/deploy-queue/req-unrelated" ]] \
  && [[ -e "$TMP/queue-preserve/deploy-queue-deferred/req-seeded" ]] \
  && [[ -e "$TMP/queue-preserve/deploy-queue-deferred/req-ancestor" ]] \
  && [[ "$(<"$TMP/queue-preserve/deploy-queue-deferred/req-seeded")" =~ ^[0-9a-f]{40}$ ]] \
  && [[ "$(<"$TMP/queue-preserve/deploy-queue-deferred/req-ancestor")" =~ ^[0-9a-f]{40}$ ]]; then
  ok "a failed deploy defers covered requests without consuming unrelated work"
else
  bad "a failed deploy defers covered requests without consuming unrelated work"
fi

if [[ -f "$TMP/queue-drain/home/.config/systemd/user/overdeck-deploy.path" ]] \
  && [[ -f "$TMP/queue-drain/home/.config/systemd/user/overdeck-deploy.service" ]] \
  && grep -q '^DirectoryNotEmpty=%h/.local/share/overdeck/deploy-queue$' \
    "$TMP/queue-drain/home/.config/systemd/user/overdeck-deploy.path" \
  && grep -q '^TimeoutStartSec=0$' "$TMP/queue-drain/home/.config/systemd/user/overdeck-deploy.service" \
  && grep -q '^StartLimitIntervalSec=15min$' "$TMP/queue-drain/home/.config/systemd/user/overdeck-deploy.service" \
  && grep -q '^StartLimitBurst=20$' "$TMP/queue-drain/home/.config/systemd/user/overdeck-deploy.service" \
  && grep -q '^ExecStart=%h/.local/share/overdeck/deploy/packaging/deploy-local.sh$' \
    "$TMP/queue-drain/home/.config/systemd/user/overdeck-deploy.service" \
  && grep -qx -- '--user enable --now overdeck-deploy.path' "$TMP/queue-drain/systemctl.log"; then
  ok "installs and enables the systemd queue drain units"
else
  bad "installs and enables the systemd queue drain units"
fi

if [[ -f "$TMP/queue-drain/home/.config/systemd/user/overdeck-fire-consumer.path" ]] \
  && [[ -f "$TMP/queue-drain/home/.config/systemd/user/overdeck-fire-consumer.service" ]] \
  && grep -qx 'PathChanged=%h/.local/state/overdeck/requests.sqlite' "$TMP/queue-drain/home/.config/systemd/user/overdeck-fire-consumer.path" \
  && grep -qx 'PathChanged=%h/.local/state/overdeck/requests.sqlite-wal' "$TMP/queue-drain/home/.config/systemd/user/overdeck-fire-consumer.path" \
  && grep -qx 'ExecStart=%h/.local/share/overdeck/deploy/modules/fire-consumer/bin/fire-consumer' "$TMP/queue-drain/home/.config/systemd/user/overdeck-fire-consumer.service" \
  && grep -qx -- '--user enable --now overdeck-fire-consumer.path' "$TMP/queue-drain/systemctl.log"; then
  ok "installs and enables the fire consumer path unit"
else
  bad "installs and enables the fire consumer path unit"
fi

if run_case web-unchanged reachable \
  && grep -q '"status":"deployed"' "$TMP/web-unchanged/stdout" \
  && ! grep -qx 'pnpm-build-invoked' "$TMP/web-unchanged/install.log" \
  && ! grep -qx 'pnpm-deploy-invoked' "$TMP/web-unchanged/install.log" \
  && [[ "$(readlink -f "$TMP/web-unchanged/deploy/apps/web/.releases/current")" \
        == "$TMP/web-unchanged/deploy/apps/web/.releases/.build-deadbeef-AAAAAA" ]]; then
  ok "skips the web build and reuses the current release when nothing web-relevant changed"
else
  bad "skips the web build and reuses the current release when nothing web-relevant changed"
fi

if run_case web-changed reachable \
  && grep -q '"status":"deployed"' "$TMP/web-changed/stdout" \
  && grep -qx 'pnpm-build-invoked' "$TMP/web-changed/install.log" \
  && grep -qx 'pnpm-deploy-invoked' "$TMP/web-changed/install.log"; then
  ok "still rebuilds when web-relevant files changed since the last release"
else
  bad "still rebuilds when web-relevant files changed since the last release"
fi

if run_case web-unchanged-dangling reachable \
  && grep -q '"status":"deployed"' "$TMP/web-unchanged-dangling/stdout" \
  && grep -qx 'pnpm-build-invoked' "$TMP/web-unchanged-dangling/install.log" \
  && grep -qx 'pnpm-deploy-invoked' "$TMP/web-unchanged-dangling/install.log"; then
  ok "rebuilds instead of skipping when current points at a pruned/missing release"
else
  bad "rebuilds instead of skipping when current points at a pruned/missing release"
fi

if QUEUE_SEED=1 run_case docsonly-skip reachable \
  && grep -q '"stage":"deploy-local","status":"deployed-docs-only"' "$TMP/docsonly-skip/stdout" \
  && grep -q '"base":"aaaaaaa"' "$TMP/docsonly-skip/stdout" \
  && [[ "$(wc -l <"$TMP/docsonly-skip/stdout")" -eq 1 ]] \
  && [[ ! -e "$TMP/docsonly-skip/install.log" ]] \
  && [[ ! -e "$TMP/docsonly-skip/systemctl.log" ]] \
  && [[ ! -e "$TMP/docsonly-skip/deploy-queue/req-seeded" ]]; then
  ok "skips the deploy and drains the queue when every changed path is documentation, including nested docs/**"
else
  bad "skips the deploy and drains the queue when every changed path is documentation, including nested docs/**"
fi

if run_case docsonly-empty-diff reachable \
  && grep -q '"status":"deployed-docs-only"' "$TMP/docsonly-empty-diff/stdout"; then
  ok "skips the deploy when nothing changed since the last successful deploy"
else
  bad "skips the deploy when nothing changed since the last successful deploy"
fi

# Each inconclusive docs-only mode must take the full deployment path, not merely avoid
# the skip. A successful full deploy replaces its old stamp only after every gate passes.
for docs_fail_mode in docsonly-missing-stamp docsonly-malformed-stamp \
  docsonly-mixed-diff docsonly-diff-fails; do
  stamp_path="$TMP/$docs_fail_mode/deploy/.git/harness-deployed-sha"
  run_case "$docs_fail_mode" reachable
  run_rc=$?
  expected_stamp="$(/usr/bin/git -C "$TMP/$docs_fail_mode/deploy" rev-parse HEAD 2>/dev/null)"
  if [[ "$run_rc" -eq 0 ]] \
    && grep -q '"status":"deployed"' "$TMP/$docs_fail_mode/stdout" \
    && ! grep -q 'deployed-docs-only' "$TMP/$docs_fail_mode/stdout" \
    && [[ "$(<"$stamp_path")" == "$expected_stamp" ]] \
    && [[ -s "$TMP/$docs_fail_mode/install.log" ]]; then
    ok "forces a full deploy and writes its success stamp: $docs_fail_mode"
  else
    bad "forces a full deploy and writes its success stamp: $docs_fail_mode"
  fi
done

# A selected target that disappeared from the fetched repository cannot be substituted
# with moving origin/main. Preserve the old stamp and classify the target error permanent.
if run_case docsonly-unknown-commit reachable; then
  bad "refuses an unavailable immutable target without replacing the deployed stamp"
else
  unknown_state="$TMP/docsonly-unknown-commit/home/.local/state/overdeck/deploy-status.json"
  unknown_target=$(/usr/bin/git -C "$TMP/docsonly-unknown-commit/deploy" rev-parse HEAD)
  if grep -q '"state":"failed","step":"deployment-target-missing"' "$unknown_state" \
    && grep -q "\"target_sha\":\"$unknown_target\"" "$unknown_state" \
    && grep -q '"failure_class":"permanent"' "$unknown_state" \
    && [[ "$(<"$TMP/docsonly-unknown-commit/deploy/.git/harness-deployed-sha")" == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ]]; then
    ok "refuses an unavailable immutable target without replacing the deployed stamp"
  else
    bad "refuses an unavailable immutable target without replacing the deployed stamp"
  fi
fi

# Final success is durable only after the atomic stamp and covered-request acknowledgement.
# Prove the fail-closed ordering inside finalize_deploy_success and its call immediately
# before the final deployed report.
stamp_write_line="$(grep -n '^  publish_deploy_stamp' "$SCRIPT" | head -1 | cut -d: -f1)"
drain_line="$(grep -nF '  acknowledge_deploy_requests "${queue_snapshot[@]}"' "$SCRIPT" | head -1 | cut -d: -f1)"
finalize_line="$(grep -n '^finalize_deploy_success$' "$SCRIPT" | tail -1 | cut -d: -f1)"
deployed_line="$(grep -n 'deploy_state finished "[$]terminal_status"' "$SCRIPT" | tail -1 | cut -d: -f1)"
if [[ -n "$stamp_write_line" && -n "$drain_line" && -n "$finalize_line" && -n "$deployed_line" ]] \
  && (( stamp_write_line < drain_line && drain_line < finalize_line && finalize_line < deployed_line )); then
  ok "the deployed-commit stamp and covered requests commit before reporting success"
else
  bad "the deployed-commit stamp and covered requests commit before reporting success"
fi

printf 'PASS=%s FAIL=%s\n' "$PASS" "$FAIL"
[[ "$FAIL" -eq 0 ]]
