#!/usr/bin/env bash
# Zero-dep regression tests for finish-branch.sh. Builds throwaway git repos (main + worktree, some
# with a bare origin) and asserts each gate FIRES on its bad input and PASSES on good input. Every
# assert encodes a real failure the primitive exists to catch — especially the irreversible ones
# (gated ff to main, cleanup ordering, asset-destruction guard). Run: bash test-finish-branch.sh
set -uo pipefail
LIB="$(cd "$(dirname "$0")" && pwd)/finish-branch.sh"
TEST_GATE_LOG=$(mktemp /tmp/fb-local-gate-log-XXXX)
TEST_GATE_BIN=$(mktemp /tmp/fb-local-gate-bin-XXXX)
cat > "$TEST_GATE_BIN" <<'EOF'
#!/usr/bin/env bash
{
  printf 'called'
  printf ' %q' "$@"
  printf '\n'
} >> "$FINISH_BRANCH_GATE_TEST_LOG"
while [[ $# -gt 0 && "$1" != "--" ]]; do shift; done
[[ ${1:-} == "--" ]] && shift
exec "$@"
EOF
chmod +x "$TEST_GATE_BIN"
export FINISH_BRANCH_LOCAL_GATE="$TEST_GATE_BIN" FINISH_BRANCH_GATE_TEST_LOG="$TEST_GATE_LOG"
PASS=0; FAIL=0
ok()  { PASS=$((PASS+1)); printf '  ok   %s\n' "$1"; }
bad() { FAIL=$((FAIL+1)); printf '  FAIL %s\n     %s\n' "$1" "$2"; }
jget() { printf '%s' "$1" | python3 -c "import sys,json;d=json.load(sys.stdin);print($2)"; }
run() { bash "$LIB" "$@"; }
gconf() { git -C "$1" config user.email t@t.t; git -C "$1" config user.name t; git -C "$1" config commit.gpgsign false; }

# Build: bare origin + main clone (seeded file.txt='base', pushed) + a worktree on branch 'feat'.
# Echoes "MAIN|WT|BRANCH". feat starts level with main.
mkproj() {
  local bare work wt
  bare=$(mktemp -d /tmp/fb-bare-XXXX); git -C "$bare" init -q --bare -b main
  work=$(mktemp -d /tmp/fb-work-XXXX); git -C "$work" init -q -b main; gconf "$work"
  printf 'wtree/\n' > "$work/.gitignore"   # mirror multideal: worktrees live in a gitignored path
  printf 'base\n' > "$work/file.txt"; printf 'keep\n' > "$work/other.txt"
  git -C "$work" add -A; git -C "$work" commit -q -m seed
  git -C "$work" remote add origin "$bare"; git -C "$work" push -q -u origin main 2>/dev/null
  wt="$work/wtree"; git -C "$work" worktree add -q "$wt" -b feat 2>/dev/null
  printf '%s|%s|%s' "$work" "$wt" "feat"
}
# commit on the branch worktree
wt_commit() { local wt=$1 f=$2 c=$3 m=$4; printf '%s\n' "$c" > "$wt/$f"; git -C "$wt" add -A; git -C "$wt" commit -q -m "$m"; }
# commit on main
main_commit() { local main=$1 f=$2 c=$3 m=$4; printf '%s\n' "$c" > "$main/$f"; git -C "$main" add -A; git -C "$main" commit -q -m "$m"; }
cleanproj() { local main=$1; rm -rf "$main"; }
optin() { git -C "$1" config harness.landQueue stage-a; }
advance_origin() {
  local main=$1 file=$2 content=$3 message=$4 bare tmp
  bare=$(git -C "$main" remote get-url origin)
  tmp=$(mktemp -d /tmp/fb-advance-XXXX)
  git clone -q "$bare" "$tmp/repo"; gconf "$tmp/repo"
  printf '%s\n' "$content" > "$tmp/repo/$file"
  git -C "$tmp/repo" add -A; git -C "$tmp/repo" commit -q -m "$message"
  git -C "$tmp/repo" push -q origin main 2>/dev/null
  rm -rf "$tmp"
}

echo "finish-branch tests:"

# ── preflight ──────────────────────────────────────────────────────────────────────────────
# 1. clean main → ready=true, no blockers
IFS='|' read -r M W B <<<"$(mkproj)"
j=$(run preflight "$M" "$B" "$W")
[[ "$(jget "$j" 'd["ready"]')" == "True" && "$(jget "$j" 'len(d["blockers"])')" == "0" ]] \
  && ok "preflight: clean main → ready" || bad "preflight clean" "$j"
cleanproj "$M"

# 2. dirty tracked file on main → dirty-main-worktree fires, ready=false
IFS='|' read -r M W B <<<"$(mkproj)"
printf 'contaminated\n' > "$M/file.txt"   # modified tracked, uncommitted
j=$(run preflight "$M" "$B" "$W")
[[ "$(jget "$j" 'd["ready"]')" == "False" \
   && "$(jget "$j" 'any(x["name"]=="dirty-main-worktree" for x in d["blockers"])')" == "True" ]] \
  && ok "preflight: dirty main fires" || bad "preflight dirty" "$j"
cleanproj "$M"

# 3. pending merge on main → pending-merge-on-main fires
IFS='|' read -r M W B <<<"$(mkproj)"
git -C "$M" checkout -q -b other; main_commit "$M" file.txt other-line "other"; git -C "$M" checkout -q main
main_commit "$M" file.txt main-line "main"
git -C "$M" merge other >/dev/null 2>&1   # conflicts → leaves MERGE_HEAD
j=$(run preflight "$M" "$B" "$W")
[[ "$(jget "$j" 'any(x["name"]=="pending-merge-on-main" for x in d["blockers"])')" == "True" ]] \
  && ok "preflight: pending merge fires" || bad "preflight pending-merge" "$j"
cleanproj "$M"

# ── sync-base ──────────────────────────────────────────────────────────────────────────────
# 4. branch already current with base → up-to-date
IFS='|' read -r M W B <<<"$(mkproj)"
j=$(run sync-base "$M" "$B" main "$W")
[[ "$(jget "$j" 'd["status"]')" == "up-to-date" ]] \
  && ok "sync-base: up-to-date when base is ancestor" || bad "sync-base up-to-date" "$j"
cleanproj "$M"

# 5. base advanced on a DIFFERENT file → clean merge into branch
IFS='|' read -r M W B <<<"$(mkproj)"
main_commit "$M" other.txt main-only-change "main advances other.txt"
wt_commit "$W" file.txt branch-change "branch edits file.txt"
j=$(run sync-base "$M" "$B" main "$W")
[[ "$(jget "$j" 'd["status"]')" == "clean" ]] \
  && ok "sync-base: clean merge on disjoint files" || bad "sync-base clean" "$j"
cleanproj "$M"

# 6. base and branch edit the SAME line → conflict, files listed, merge left in progress
IFS='|' read -r M W B <<<"$(mkproj)"
main_commit "$M" file.txt main-line "main edits file.txt"
wt_commit "$W" file.txt branch-line "branch edits file.txt"
j=$(run sync-base "$M" "$B" main "$W")
[[ "$(jget "$j" 'd["status"]')" == "conflict" \
   && "$(jget "$j" '"file.txt" in d["files"]')" == "True" \
   && -f "$W/.git" || -d "$W" ]] \
  && ok "sync-base: conflict surfaced, files listed" || bad "sync-base conflict" "$j"
# merge must be LEFT in progress for the agent (markers present)
git -C "$W" grep -q '^<<<<<<< ' -- file.txt 2>/dev/null \
  && ok "sync-base: conflict left in worktree for agent" || bad "sync-base leaves conflict" "no markers"
cleanproj "$M"

# ── land-merge ─────────────────────────────────────────────────────────────────────────────
# 7. happy: branch ahead, clean, tests pass → landed, main fast-forwarded to branch head
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
bh=$(git -C "$W" rev-parse HEAD)
j=$(run land-merge "$M" "$B" main "$W" true)
[[ "$(jget "$j" 'd["status"]')" == "landed" \
   && "$(git -C "$M" rev-parse HEAD)" == "$bh" ]] \
  && ok "land-merge: gated ff lands verified head on main" || bad "land-merge happy" "$j / main=$(git -C "$M" rev-parse HEAD) bh=$bh"
cleanproj "$M"

# 8. tests FAIL → no land; main must be UNCHANGED (the core guarantee)
IFS='|' read -r M W B <<<"$(mkproj)"
m0=$(git -C "$M" rev-parse HEAD)
wt_commit "$W" file.txt branch-feature "feat work"
j=$(run land-merge "$M" "$B" main "$W" false)
[[ "$(jget "$j" 'd["status"]')" == "tests-failed" \
   && "$(git -C "$M" rev-parse HEAD)" == "$m0" ]] \
  && ok "land-merge: failing tests block ff, main untouched" || bad "land-merge tests-failed" "$j / main moved?"
cleanproj "$M"

# 9. conflict markers in a committed file (tree clean) → conflict-markers fires before tests
IFS='|' read -r M W B <<<"$(mkproj)"
printf 'a\n<<<<<<< HEAD\nb\n>>>>>>> x\n' > "$W/file.txt"; git -C "$W" add -A; git -C "$W" commit -q -m "oops committed markers"
m0=$(git -C "$M" rev-parse HEAD)
j=$(run land-merge "$M" "$B" main "$W" true)
[[ "$(jget "$j" 'd["status"]')" == "conflict-markers" \
   && "$(git -C "$M" rev-parse HEAD)" == "$m0" ]] \
  && ok "land-merge: conflict markers block ff" || bad "land-merge markers" "$j"
cleanproj "$M"

# 10. dirty worktree (unresolved index) → dirty-tree fires
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
printf 'uncommitted edit\n' > "$W/file.txt"   # dirty, uncommitted
j=$(run land-merge "$M" "$B" main "$W" true)
[[ "$(jget "$j" 'd["status"]')" == "dirty-tree" ]] \
  && ok "land-merge: dirty worktree blocks ff" || bad "land-merge dirty-tree" "$j"
cleanproj "$M"

# 11. base not an ancestor (branch never synced, main advanced) → not-ff fires
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
main_commit "$M" other.txt main-diverges "main advances independently"
j=$(run land-merge "$M" "$B" main "$W" true)
[[ "$(jget "$j" 'd["status"]')" == "not-ff" ]] \
  && ok "land-merge: non-ancestor base → not-ff (sync first)" || bad "land-merge not-ff" "$j"
cleanproj "$M"

# ── land-pr fail-closed gates (real gh PR creation not exercised — no GitHub throwaway) ──────
# 12. no origin remote → no-remote fires, main never touched
IFS='|' read -r M W B <<<"$(mkproj)"
git -C "$M" remote remove origin
wt_commit "$W" file.txt branch-feature "feat work"
j=$(run land-pr "$M" "$B" main "$W" true)
[[ "$(jget "$j" 'd["status"]')" == "no-remote" ]] \
  && ok "land-pr: missing remote fails closed" || bad "land-pr no-remote" "$j"
cleanproj "$M"

# Existing PRs must still run the gate and push the current branch head.
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
GHBIN=$(mktemp -d /tmp/fb-ghbin-XXXX)
cat > "$GHBIN/gh" <<'EOF'
#!/usr/bin/env bash
case "$1 $2" in
  "auth status") exit 0;;
  "pr list") printf '42\n'; exit 0;;
  "pr create") exit 99;;
  *) exit 0;;
esac
EOF
chmod +x "$GHBIN/gh"
branch_head=$(git -C "$W" rev-parse HEAD)
out=$(PATH="$GHBIN:$PATH" run land-pr "$M" "$B" main "$W" true 2>/dev/null)
remote_head=$(git -C "$M" rev-parse --verify "origin/$B" 2>/dev/null || true)
[[ "$(printf '%s' "$out" | grep -c '"status":"pr-exists"')" == "1" \
   && "$(jget "$out" 'd["number"]')" == "42" \
   && "$remote_head" == "$branch_head" ]] \
  && ok "land-pr: existing PR branch is tested and updated" \
  || bad "land-pr existing PR update" "status=$out remote_head=$remote_head branch_head=$branch_head"
rm -rf "$GHBIN"; cleanproj "$M"

# 13. dirty worktree → dirty-tree fires before any push
IFS='|' read -r M W B <<<"$(mkproj)"
printf 'uncommitted\n' > "$W/file.txt"
j=$(run land-pr "$M" "$B" main "$W" true)
[[ "$(jget "$j" 'd["status"]')" == "dirty-tree" ]] \
  && ok "land-pr: dirty worktree fails closed" || bad "land-pr dirty-tree" "$j"
cleanproj "$M"

# ── cleanup ──────────────────────────────────────────────────────────────────────────────────
# gh pr list timeout fails closed with a diagnostic instead of continuing to tests/push.
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
GHBIN=$(mktemp -d /tmp/fb-ghbin-XXXX)
cat > "$GHBIN/gh" <<'EOF'
#!/usr/bin/env bash
case "$1 $2" in
  "auth status") exit 0;;
  "pr list") sleep 2;;
esac
EOF
chmod +x "$GHBIN/gh"
j=$(PATH="$GHBIN:$PATH" FINISH_BRANCH_GH_TIMEOUT_SECONDS=1 run land-pr "$M" "$B" main "$W" true 2>/dev/null)
[[ "$(jget "$j" 'd["status"]')" == "pr-list-failed" \
   && "$(jget "$j" '"timed out" in d["detail"]')" == "True" ]] \
  && ok "land-pr: gh pr list timeout fails closed" || bad "land-pr pr-list timeout" "$j"
rm -rf "$GHBIN"; cleanproj "$M"

# Captured test gate is bounded and reports timeout without moving main.
IFS='|' read -r M W B <<<"$(mkproj)"
m0=$(git -C "$M" rev-parse HEAD)
wt_commit "$W" file.txt branch-feature "feat work"
j=$(FINISH_BRANCH_TEST_TIMEOUT_SECONDS=1 run land-merge "$M" "$B" main "$W" 'sleep 2' 2>/dev/null)
[[ "$(jget "$j" 'd["status"]')" == "tests-failed" \
   && "$(jget "$j" '"timed out" in d["detail"]')" == "True" \
   && "$(git -C "$M" rev-parse HEAD)" == "$m0" ]] \
  && ok "land-merge: captured test timeout fails closed" || bad "land-merge test timeout" "$j"
cleanproj "$M"

# 14. asset guard: worktree tmp/ holds files → assets-present, worktree NOT removed
IFS='|' read -r M W B <<<"$(mkproj)"
mkdir -p "$W/tmp"; printf 'expensive\n' > "$W/tmp/cache.bin"
j=$(run cleanup "$M" "$B" "$W")
[[ "$(jget "$j" 'd["status"]')" == "assets-present" && -d "$W" ]] \
  && ok "cleanup: asset guard blocks irreversible remove" || bad "cleanup assets-present" "$j / wt gone?"
cleanproj "$M"

# 15. happy: land then cleanup → worktree removed AND branch deleted, in order
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
run land-merge "$M" "$B" main "$W" true >/dev/null
j=$(run cleanup "$M" "$B" "$W")
gone_wt=$([[ -d "$W" ]] && echo no || echo yes)
gone_br=$(git -C "$M" rev-parse --verify --quiet "$B" >/dev/null 2>&1 && echo no || echo yes)
[[ "$(jget "$j" 'd["status"]')" == "cleaned" && "$gone_wt" == "yes" && "$gone_br" == "yes" ]] \
  && ok "cleanup: worktree removed + branch deleted (ordered)" || bad "cleanup happy" "$j / wt_gone=$gone_wt br_gone=$gone_br"
cleanproj "$M"

# 16. --keep-branch (PR mode): worktree removed but branch KEPT
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
j=$(run cleanup "$M" "$B" "$W" --keep-branch --no-push)
kept=$(git -C "$M" rev-parse --verify --quiet "$B" >/dev/null 2>&1 && echo yes || echo no)
[[ "$(jget "$j" 'd["status"]')" == "cleaned" && "$kept" == "yes" && ! -d "$W" ]] \
  && ok "cleanup: --keep-branch keeps branch (PR mode)" || bad "cleanup keep-branch" "$j / kept=$kept"
cleanproj "$M"

# 17. --assets-ok bypasses the guard even with assets present
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature "feat work"
run land-merge "$M" "$B" main "$W" true >/dev/null
mkdir -p "$W/tmp"; printf 'x\n' > "$W/tmp/c"
j=$(run cleanup "$M" "$B" "$W" --assets-ok)
[[ "$(jget "$j" 'd["status"]')" == "cleaned" && ! -d "$W" ]] \
  && ok "cleanup: --assets-ok bypasses guard" || bad "cleanup assets-ok" "$j"
cleanproj "$M"

# ── drift (frozen-fact validation) ────────────────────────────────────────────────────────────
lastline() { printf '%s' "$1" | tail -1; }
# D1. merge-to-main + deploy anchor file present → drift ok (exit 0)
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/deploy.yml"
if run drift --root "$M" --base main --mode merge-to-main --anchor "deploy:deploy.yml" >/dev/null 2>&1; then ok "drift: deploy anchor present → ok"; else bad "drift deploy ok" "exit!=0"; fi
cleanproj "$M"
# D2. deploy anchor file gone → exit 3, stage drift
IFS='|' read -r M W B <<<"$(mkproj)"
out=$(run drift --root "$M" --base main --mode merge-to-main --anchor "deploy:deploy.yml" 2>/dev/null); rc=$?
[[ $rc -eq 3 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "drift" ]] && ok "drift: missing deploy signal → exit3" || bad "drift deploy missing" "rc=$rc $out"
cleanproj "$M"
# D3. pr + remote anchor matching origin → ok
IFS='|' read -r M W B <<<"$(mkproj)"; URL=$(git -C "$M" remote get-url origin)
if run drift --root "$M" --base main --mode pr --anchor "remote:$URL" >/dev/null 2>&1; then ok "drift: remote anchor matches → ok"; else bad "drift remote ok" "exit!=0"; fi
cleanproj "$M"
# D4. pr + remote anchor mismatched → exit 3
IFS='|' read -r M W B <<<"$(mkproj)"
out=$(run drift --root "$M" --base main --mode pr --anchor "remote:https://github.com/x/y" 2>/dev/null); rc=$?
[[ $rc -eq 3 ]] && ok "drift: remote moved → exit3" || bad "drift remote moved" "rc=$rc"
cleanproj "$M"
# D5. unknown mode → exit 3
IFS='|' read -r M W B <<<"$(mkproj)"
if run drift --root "$M" --base main --mode bogus 2>/dev/null; then bad "drift bad-mode exit0" ""; else ok "drift: unknown mode → exit3"; fi
cleanproj "$M"
# D6. base no longer resolves → exit 3
IFS='|' read -r M W B <<<"$(mkproj)"
if run drift --root "$M" --base nope --mode pr 2>/dev/null; then bad "drift bad-base exit0" ""; else ok "drift: base unresolved → exit3"; fi
cleanproj "$M"

# ── land (orchestrator) ─────────────────────────────────────────────────────────────────────
# L1. merge happy path: base diverged → sync(clean) → dep(marker) → gate(pass) → ff → cleanup. exit0.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/deploy.yml"
wt_commit "$W" b.txt x branchwork    # commit MESSAGE = branchwork (asserted via main log)
main_commit "$M" m.txt mainwork mw   # base ahead on a different file → clean merge
out=$(run land --root "$M" --base main --mode merge-to-main --anchor "deploy:deploy.yml" \
       --testcmd true --depcmd "touch $W/.dep_ran" -- feat "$W" 2>/dev/null); rc=$?
# worktree is removed on success, so assert the landed outcome via main's history, not the wt marker.
[[ $rc -eq 0 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "landed" \
   && "$(git -C "$M" log --oneline | grep -c branchwork)" == "1" ]] \
  && ok "land merge: happy path lands to main" || bad "land merge happy" "rc=$rc $out"
cleanproj "$M"
# L2. dep refresh fails → exit 20 stage deps-refresh, main NOT advanced, gate never ran.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/deploy.yml"
wt_commit "$W" b.txt bw bw; main_commit "$M" m.txt mw mw
out=$(run land --root "$M" --base main --mode merge-to-main --anchor "deploy:deploy.yml" \
       --testcmd true --depcmd false -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "deps-refresh" \
   && "$(git -C "$M" log --oneline | grep -c bw)" == "0" ]] \
  && ok "land merge: dep-fail → exit20, main untouched" || bad "land dep-fail" "rc=$rc $out"
cleanproj "$M"
# L3. gate fails → exit 20 stage land-merge, main NOT advanced.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/deploy.yml"
wt_commit "$W" b.txt bw bw; main_commit "$M" m.txt mw mw
out=$(run land --root "$M" --base main --mode merge-to-main --anchor "deploy:deploy.yml" \
       --testcmd false --depcmd "touch $W/.dep_ran" -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "land-merge" \
   && -f "$W/.dep_ran" && "$(git -C "$M" log --oneline | grep -c bw)" == "0" ]] \
  && ok "land merge: gate-fail → exit20 (dep ran first), main untouched" || bad "land gate-fail" "rc=$rc $out"
cleanproj "$M"
# L4. PR mode, conflict markers in wt → land-pr fails closed BEFORE gh → exit20 stage land-pr, main untouched. (hermetic)
IFS='|' read -r M W B <<<"$(mkproj)"; URL=$(git -C "$M" remote get-url origin)
printf '<<<<<<< HEAD\nx\n>>>>>>> y\n' > "$W/conf.txt"; git -C "$W" add -A; git -C "$W" commit -q -m markers
out=$(run land --root "$M" --base main --mode pr --anchor "remote:$URL" --testcmd true -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "land-pr" \
   && "$(git -C "$M" log --oneline | grep -c markers)" == "0" ]] \
  && ok "land pr: conflict-markers → exit20 land-pr, main untouched" || bad "land pr markers" "rc=$rc $out"
cleanproj "$M"
# L5. PR mode, clean branch + DIVERGED base + DIRTY main → no preflight-block, no base-sync (HEAD unchanged).
#     Reaches gh and fails at create (local remote ≠ GitHub) → exit20 land-pr. gh-guarded.
if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then
  IFS='|' read -r M W B <<<"$(mkproj)"; URL=$(git -C "$M" remote get-url origin)
  wt_commit "$W" b.txt prwork pr
  main_commit "$M" m.txt ahead ahead; git -C "$M" push -q origin main 2>/dev/null
  printf 'wip\n' > "$M/file.txt"   # dirty main (must NOT block a PR)
  before=$(git -C "$W" rev-parse HEAD)
  out=$(run land --root "$M" --base main --mode pr --anchor "remote:$URL" --testcmd true -- feat "$W" 2>/dev/null); rc=$?
  after=$(git -C "$W" rev-parse HEAD)
  [[ "$before" == "$after" \
     && "$(printf '%s' "$out" | grep -c '"stage":"preflight"')" == "0" \
     && "$(jget "$(lastline "$out")" 'd["stage"]')" == "land-pr" \
     && "$(git -C "$M" log --oneline | grep -c prwork)" == "0" ]] \
    && ok "land pr: no preflight-block, no base-sync, main untouched" || bad "land pr invariants" "rc=$rc before=$before after=$after $out"
  cleanproj "$M"
else
  ok "land pr invariants (SKIPPED — gh not authed)"
fi

# L6. cwd-independence (REGRESSION): gh resolves repo + --fill reads local refs from CWD. The
#     orchestrator runs land-pr from the AGENT's cwd (any repo) — so land-pr MUST run every gh call
#     inside $main, else gh targets the wrong repo / "ambiguous argument base...branch". Hermetic:
#     stub gh to log "$1$2:$PWD"; origin = local bare (push works, slug non-empty, stub ignores -R);
#     invoke from an UNRELATED repo cwd; assert pr-list AND pr-create both ran with cwd == $main.
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" feat.txt change pr-work
GHBIN=$(mktemp -d /tmp/fb-ghbin-XXXX); GHLOG=$(mktemp /tmp/fb-ghlog-XXXX)
cat > "$GHBIN/gh" <<EOF
#!/usr/bin/env bash
printf '%s %s:%s\n' "\$1" "\$2" "\$PWD" >> "$GHLOG"
case "\$1 \$2" in
  "auth status") exit 0;;
  "pr list")     printf '' ; exit 0;;          # no existing PR
  "pr create")   printf 'https://example.invalid/pr/1\n'; exit 0;;
  *) exit 0;;
esac
EOF
chmod +x "$GHBIN/gh"
OTHER=$(mktemp -d /tmp/fb-other-XXXX); git -C "$OTHER" init -q -b main   # unrelated repo as caller cwd
out=$( cd "$OTHER" && PATH="$GHBIN:$PATH" bash "$LIB" land-pr "$M" "$B" main "$W" true 2>&1 )
createpwd=$(grep '^pr create:' "$GHLOG" | head -1 | sed 's/^pr create://')
listpwd=$(grep '^pr list:' "$GHLOG" | head -1 | sed 's/^pr list://')
[[ "$(printf '%s' "$out" | grep -c '"status":"pr-opened"')" == "1" \
   && "$createpwd" == "$M" && "$listpwd" == "$M" ]] \
  && ok "land-pr: gh runs in \$main (cwd-independent), not the caller's cwd" \
  || bad "land-pr cwd-independence" "status=$out create_pwd=$createpwd list_pwd=$listpwd main=$M"
rm -rf "$GHBIN" "$GHLOG" "$OTHER"; cleanproj "$M"

# L7. PR-mode cleanup must SURFACE assets-present (exit 20 stage cleanup), not swallow it → return 0.
#     Else the worktree leaks silently and --assets-ok is unreachable. Then prove the re-entry: same
#     command WITH --assets-ok cleans + returns 0. gh stubbed to pr-opened; asset = non-empty tmp/.
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" feat.txt change pr-work
mkdir -p "$W/tmp"; printf 'expensive\n' > "$W/tmp/cache.bin"   # gitignored asset only in the worktree
GHBIN=$(mktemp -d /tmp/fb-ghbin-XXXX)
cat > "$GHBIN/gh" <<'EOF'
#!/usr/bin/env bash
case "$1 $2" in
  "auth status") exit 0;; "pr list") printf ''; exit 0;;
  "pr create") printf 'https://example.invalid/pr/1\n'; exit 0;; *) exit 0;;
esac
EOF
chmod +x "$GHBIN/gh"
ANCH="remote:$(git -C "$M" remote get-url origin)"
out=$( PATH="$GHBIN:$PATH" bash "$LIB" land --root "$M" --base "$B" --mode pr --anchor "$ANCH" --testcmd true -- "$B" "$W" 2>&1 ); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "cleanup" \
   && "$(printf '%s' "$out" | grep -c '"status":"pr-opened"')" == "1" && -d "$W" ]] \
  && ok "land pr: cleanup assets-present surfaced as exit20 (not swallowed), worktree preserved" \
  || bad "land pr cleanup surfacing" "rc=$rc wt_exists=$([[ -d $W ]] && echo y) $out"
# re-entry with --assets-ok → cleaned, exit 0, worktree removed (flag now reachable in PR mode)
out2=$( PATH="$GHBIN:$PATH" bash "$LIB" land --root "$M" --base "$B" --mode pr --anchor "$ANCH" --testcmd true -- "$B" "$W" --assets-ok 2>&1 ); rc2=$?
[[ $rc2 -eq 0 && ! -d "$W" ]] \
  && ok "land pr: --assets-ok re-entry cleans + exit0 (flag reachable)" \
  || bad "land pr assets-ok re-entry" "rc=$rc2 wt_exists=$([[ -d $W ]] && echo y) $out2"
rm -rf "$GHBIN"; cleanproj "$M"

# L-CWD1. caller cwd INSIDE the worktree → exit 3 BEFORE anything destructive: wt intact, branch
# alive, main untouched. Without this the land succeeds but leaves the caller in a deleted dir,
# whose next `pwd` fails and turns a clean land into a reported failure.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/deploy.yml"
wt_commit "$W" b.txt x branchwork
out=$( cd "$W" && bash "$LIB" land --root "$M" --base main --mode merge-to-main \
       --anchor "deploy:deploy.yml" --testcmd true -- feat "$W" 2>&1 ); rc=$?
[[ $rc -eq 3 && "$(printf '%s' "$out" | grep -c 'cwd is inside the worktree')" == "1" \
   && -d "$W" && -n "$(git -C "$M" branch --list feat)" \
   && "$(git -C "$M" log --oneline | grep -c branchwork)" == "0" ]] \
  && ok "land: cwd inside worktree → exit3, nothing destroyed" \
  || bad "land cwd-inside-worktree" "rc=$rc wt_exists=$([[ -d $W ]] && echo y) $out"
# L-CWD2. same land from a cwd OUTSIDE the worktree → exit 0 (the guard gates on cwd, not on the
# root, which is the normal place to land from).
out=$( cd "$M" && bash "$LIB" land --root "$M" --base main --mode merge-to-main \
       --anchor "deploy:deploy.yml" --testcmd true -- feat "$W" 2>/dev/null ); rc=$?
[[ $rc -eq 0 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "landed" && ! -d "$W" ]] \
  && ok "land: cwd at root → exit0 (guard does not fire)" \
  || bad "land cwd-at-root" "rc=$rc $out"
cleanproj "$M"

# ── deploy-verify primitives ──────────────────────────────────────────────────────────────────
# DV1. deploy-preview: deploycmd writes URL to .ship-preview-url → deployed, url surfaced
IFS='|' read -r M W B <<<"$(mkproj)"
j=$(run deploy-preview "$W" 'echo https://prev-1.test > .ship-preview-url')
[[ "$(jget "$j" 'd["status"]')" == "deployed" && "$(jget "$j" 'd["url"]')" == "https://prev-1.test" ]] \
  && ok "deploy-preview: captures URL from .ship-preview-url" || bad "deploy-preview deployed" "$j"
cleanproj "$M"
# DV2. deploy-preview: deploy exits 0 but writes NO url → no-url (fail-closed)
IFS='|' read -r M W B <<<"$(mkproj)"
j=$(run deploy-preview "$W" 'true')
[[ "$(jget "$j" 'd["status"]')" == "no-url" ]] \
  && ok "deploy-preview: no URL written → no-url (fail-closed)" || bad "deploy-preview no-url" "$j"
cleanproj "$M"
# DV3. deploy-preview: deploy command itself fails → deploy-failed
IFS='|' read -r M W B <<<"$(mkproj)"
j=$(run deploy-preview "$W" 'false')
[[ "$(jget "$j" 'd["status"]')" == "deploy-failed" ]] \
  && ok "deploy-preview: nonzero deploy → deploy-failed" || bad "deploy-preview deploy-failed" "$j"
cleanproj "$M"
# DV4. e2e-gate: e2ecmd sees PREVIEW_URL and passes → passed
IFS='|' read -r M W B <<<"$(mkproj)"
j=$(run e2e-gate "$W" 'test "$PREVIEW_URL" = https://prev.test' https://prev.test)
[[ "$(jget "$j" 'd["status"]')" == "passed" ]] \
  && ok "e2e-gate: PREVIEW_URL plumbed, pass → passed" || bad "e2e-gate passed" "$j"
cleanproj "$M"
# DV5. e2e-gate: nonzero e2e → failed
IFS='|' read -r M W B <<<"$(mkproj)"
j=$(run e2e-gate "$W" 'false' https://prev.test)
[[ "$(jget "$j" 'd["status"]')" == "failed" ]] \
  && ok "e2e-gate: nonzero e2e → failed" || bad "e2e-gate failed" "$j"
cleanproj "$M"

# ── deploy-verify drift ─────────────────────────────────────────────────────────────────────
# DV6. deploy-verify + deploy anchor present → drift ok
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/wrangler.toml"
if run drift --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" >/dev/null 2>&1; then ok "drift: deploy-verify anchor present → ok"; else bad "drift dv ok" "exit!=0"; fi
cleanproj "$M"
# DV7. deploy-verify + anchor gone → exit 3
IFS='|' read -r M W B <<<"$(mkproj)"
out=$(run drift --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" 2>/dev/null); rc=$?
[[ $rc -eq 3 ]] && ok "drift: deploy-verify missing anchor → exit3" || bad "drift dv missing" "rc=$rc"
cleanproj "$M"

# ── deploy-verify land orchestrator ─────────────────────────────────────────────────────────
# DV-L1. happy: deploy writes url → e2e (sees PREVIEW_URL) passes → promote merge-to-main → ff + cleanup. exit0.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/wrangler.toml"
wt_commit "$W" b.txt x branchwork
out=$(run land --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" \
       --testcmd true --deploycmd 'echo https://prev.test > .ship-preview-url' \
       --e2ecmd 'test "$PREVIEW_URL" = https://prev.test' --promote merge-to-main -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 0 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "landed" \
   && "$(git -C "$M" log --oneline | grep -c branchwork)" == "1" ]] \
  && ok "land deploy-verify: deploy→e2e(pass)→promote lands to main" || bad "land dv happy" "rc=$rc $out"
cleanproj "$M"
# DV-L2. e2e FAILS → exit20 stage e2e-gate, main NOT advanced (NEVER promote an unverified build).
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/wrangler.toml"
wt_commit "$W" b.txt x branchwork
out=$(run land --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" \
       --testcmd true --deploycmd 'echo https://prev.test > .ship-preview-url' \
       --e2ecmd 'false' --promote merge-to-main -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "e2e-gate" \
   && "$(git -C "$M" log --oneline | grep -c branchwork)" == "0" ]] \
  && ok "land deploy-verify: e2e-fail → exit20, NOT promoted, main untouched" || bad "land dv e2e-fail" "rc=$rc $out"
cleanproj "$M"
# DV-L3. deploy yields no URL → exit20 stage deploy-preview, e2e NEVER runs (marker absent), main untouched.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/wrangler.toml"
wt_commit "$W" b.txt x branchwork
out=$(run land --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" \
       --testcmd true --deploycmd 'true' \
       --e2ecmd "touch $W/.e2e_ran" --promote merge-to-main -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "deploy-preview" \
   && ! -f "$W/.e2e_ran" && "$(git -C "$M" log --oneline | grep -c branchwork)" == "0" ]] \
  && ok "land deploy-verify: no-url → exit20 deploy-preview, e2e never ran" || bad "land dv no-url" "rc=$rc e2e_ran=$([[ -f $W/.e2e_ran ]] && echo y) $out"
cleanproj "$M"
# DV-L4. missing --promote → usage fault (exit 3), nothing deployed.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/wrangler.toml"
wt_commit "$W" b.txt x branchwork
if run land --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" \
     --testcmd true --deploycmd 'echo x > .ship-preview-url' --e2ecmd true -- feat "$W" 2>/dev/null; then
  bad "land dv missing-promote exit0" ""
else ok "land deploy-verify: missing --promote → exit3 (fail-closed)"; fi
cleanproj "$M"
# DV-L5. promote=merge-to-main: base advanced → branch MUST be synced BEFORE deploy, so e2e verifies the
#        EXACT head that lands (never promote an unverified build). deploycmd ASSERTS the base file is
#        present in the worktree (proves sync ran first); only the fixed pre-deploy-sync ordering passes.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/wrangler.toml"
wt_commit "$W" b.txt x branchwork
main_commit "$M" base-only.txt y "base advances on disjoint file"
out=$(run land --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" \
       --testcmd true --deploycmd 'test -f base-only.txt && echo https://prev.test > .ship-preview-url' \
       --e2ecmd 'test "$PREVIEW_URL" = https://prev.test' --promote merge-to-main -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 0 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "landed" \
   && "$(git -C "$M" log --oneline | grep -c branchwork)" == "1" ]] \
  && ok "land deploy-verify(mtm): synced BEFORE deploy → e2e verifies the landed head" || bad "land dv pre-sync" "rc=$rc $out"
cleanproj "$M"
# DV-L6. promote=merge-to-main: pre-deploy sync CONFLICTS → exit20 stage sync-base, deploy NEVER ran
#        (marker absent), main untouched. Verify gate is reached only on a current head.
IFS='|' read -r M W B <<<"$(mkproj)"; touch "$M/wrangler.toml"
main_commit "$M" file.txt main-line "main edits file.txt"
wt_commit "$W" file.txt branch-line "branch edits same line"
out=$(run land --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" \
       --testcmd true --deploycmd "touch $W/.deploy_ran; echo x > .ship-preview-url" \
       --e2ecmd true --promote merge-to-main -- feat "$W" 2>/dev/null); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "sync-base" \
   && ! -f "$W/.deploy_ran" && "$(git -C "$M" log --oneline | grep -c branch-line)" == "0" ]] \
  && ok "land deploy-verify(mtm): pre-deploy sync conflict → exit20, deploy never ran" || bad "land dv pre-sync conflict" "rc=$rc deploy_ran=$([[ -f $W/.deploy_ran ]] && echo y) $out"
cleanproj "$M"

# ── Stage A serialized candidate landing ─────────────────────────────────────────────────────
# SA1. Remote main, not stale local main, is the integration base. Local main remains untouched.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
local_main=$(git -C "$M" rev-parse main)
wt_commit "$W" source.txt source source-work
source_sha=$(git -C "$W" rev-parse HEAD)
advance_origin "$M" remote.txt remote remote-work
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
[[ $rc -eq 0 && "$(git -C "$M" rev-parse main)" == "$local_main" \
   && "$(git -C "$M" show refs/remotes/origin/main:source.txt)" == "source" \
   && "$(git -C "$M" show refs/remotes/origin/main:remote.txt)" == "remote" \
   && "$(git -C "$M" merge-base --is-ancestor "$source_sha" refs/remotes/origin/main; echo $?)" == "0" \
   && ! -d "$W" \
   && "$(git -C "$M" rev-parse --verify --quiet "$B" >/dev/null 2>&1; echo $?)" != "0" ]] \
  && ok "stage-a: stale local main ignored; remote + source both land" \
  || bad "stage-a stale local main" "rc=$rc local=$(git -C "$M" rev-parse main) expected=$local_main wt=$([[ -d $W ]] && echo present) br=$(git -C "$M" rev-parse --verify --quiet "$B" 2>/dev/null || echo gone) $out"
cleanproj "$M"

# SA1b. A dangling unrelated branch poisons shared-root fetch but not isolated conductor landing.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source isolated-source
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
mkdir -p "$common/refs/heads/wt" "$common/harness"
printf 'stale\n' > "$common/harness/source-stale.bundle"
printf '%040d\n' 1 > "$common/refs/heads/wt/missing-object"
git -C "$M" fetch --quiet --no-tags origin refs/heads/main:refs/remotes/origin/main \
  >/dev/null 2>&1; poisoned_fetch_rc=$?
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
remote_head=$(git --git-dir="$(git -C "$M" remote get-url origin)" rev-parse refs/heads/main)
[[ $poisoned_fetch_rc -ne 0 && $rc -eq 0 \
   && "$(git --git-dir="$(git -C "$M" remote get-url origin)" show "$remote_head:source.txt")" == source \
   && -f "$common/refs/heads/wt/missing-object" && ! -e "$common/harness/source-stale.bundle" ]] \
  && ok "stage-a: unrelated dangling ref cannot block isolated landing" \
  || bad "stage-a dangling-ref containment" "fetch_rc=$poisoned_fetch_rc land_rc=$rc $out"
cleanproj "$M"

# SA1c. Candidate publication preserves every configured origin push URL.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" multi.txt multi multi-push
primary=$(git -C "$M" remote get-url origin)
secondary=$(mktemp -d /tmp/fb-bare-secondary-XXXX); rm -rf "$secondary"
git clone -q --bare "$primary" "$secondary"
git -C "$M" config --add remote.origin.pushurl "$primary"
git -C "$M" config --add remote.origin.pushurl "$secondary"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
[[ $rc -eq 0 && "$(git --git-dir="$primary" show refs/heads/main:multi.txt)" == multi \
   && "$(git --git-dir="$secondary" show refs/heads/main:multi.txt)" == multi ]] \
  && ok "stage-a: isolated publication preserves multiple push URLs" \
  || bad "stage-a multiple push URLs" "rc=$rc $out"
rm -rf "$secondary"; cleanproj "$M"

# SA1d. Publisher fetch preserves repository-local upload-pack transport configuration.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" transport.txt transport custom-upload-pack
upload_pack=$(mktemp /tmp/fb-upload-pack-XXXX); upload_seen=$(mktemp /tmp/fb-upload-seen-XXXX); rm -f "$upload_seen"
cat > "$upload_pack" <<EOF
#!/usr/bin/env bash
printf 'seen\n' > '$upload_seen'
exec git-upload-pack "\$@"
EOF
chmod +x "$upload_pack"
git -C "$M" config remote.origin.uploadpack "$upload_pack"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
[[ $rc -eq 0 && "$(cat "$upload_seen" 2>/dev/null)" == seen ]] \
  && ok "stage-a: isolated publisher preserves custom upload-pack transport" \
  || bad "stage-a custom upload-pack" "rc=$rc seen=$(cat "$upload_seen" 2>/dev/null) $out"
rm -f "$upload_pack" "$upload_seen"; cleanproj "$M"

# SA2. Two landers sharing one common-dir serialize the whole candidate gate and both land.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
git -C "$W" branch -m feat-a; B=feat-a
wt_commit "$W" a.txt a land-a
W2=$(mktemp -d /tmp/fb-wt2-XXXX); rmdir "$W2"
git -C "$M" worktree add -q "$W2" -b feat-b main 2>/dev/null
wt_commit "$W2" b.txt b land-b
METRICS=$(mktemp -d /tmp/fb-metrics-XXXX)
cat > "$METRICS/gate.sh" <<'EOF'
#!/usr/bin/env bash
set -eu
d=$1
while ! mkdir "$d/mutex" 2>/dev/null; do sleep 0.01; done
current=0; [[ -f "$d/current" ]] && current=$(cat "$d/current")
current=$((current+1)); printf '%s\n' "$current" > "$d/current"
maximum=0; [[ -f "$d/maximum" ]] && maximum=$(cat "$d/maximum")
(( current > maximum )) && printf '%s\n' "$current" > "$d/maximum"
rmdir "$d/mutex"
sleep 1
while ! mkdir "$d/mutex" 2>/dev/null; do sleep 0.01; done
current=$(cat "$d/current"); printf '%s\n' "$((current-1))" > "$d/current"
rmdir "$d/mutex"
EOF
chmod +x "$METRICS/gate.sh"
bash "$LIB" land --root "$M" --base main --mode merge-to-main \
  --testcmd "bash '$METRICS/gate.sh' '$METRICS'" -- feat-a "$W" >"$METRICS/a.out" 2>&1 & p1=$!
bash "$LIB" land --root "$M" --base main --mode merge-to-main \
  --testcmd "bash '$METRICS/gate.sh' '$METRICS'" -- feat-b "$W2" >"$METRICS/b.out" 2>&1 & p2=$!
wait "$p1"; rc1=$?; wait "$p2"; rc2=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
[[ $rc1 -eq 0 && $rc2 -eq 0 && "$(cat "$METRICS/maximum")" == "1" \
   && "$(git -C "$M" log --format=%s refs/remotes/origin/main | grep -c land-a)" == "1" \
   && "$(git -C "$M" log --format=%s refs/remotes/origin/main | grep -c land-b)" == "1" ]] \
  && ok "stage-a: parallel landers serialize (critical max=1) and both land" \
  || bad "stage-a parallel serialization" "rc1=$rc1 rc2=$rc2 max=$(cat "$METRICS/maximum" 2>/dev/null) a=$(cat "$METRICS/a.out") b=$(cat "$METRICS/b.out")"
rm -rf "$METRICS"; cleanproj "$M"

# SA3. Remote movement after attempt one discards the candidate and reruns the gate.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source source-work
bare=$(git -C "$M" remote get-url origin)
ADV=$(mktemp -d /tmp/fb-churn-XXXX); git clone -q "$bare" "$ADV/repo"; gconf "$ADV/repo"
cat > "$ADV/gate.sh" <<'EOF'
#!/usr/bin/env bash
set -eu
state=$1 repo=$2
n=0; [[ -f "$state/count" ]] && n=$(cat "$state/count")
n=$((n+1)); printf '%s\n' "$n" > "$state/count"
if [[ $n -eq 1 ]]; then
  printf 'advanced\n' > "$repo/advanced.txt"
  git -C "$repo" add -A; git -C "$repo" commit -q -m remote-during-gate
  git -C "$repo" push -q origin main
fi
EOF
chmod +x "$ADV/gate.sh"
out=$(run land --root "$M" --base main --mode merge-to-main \
  --testcmd "bash '$ADV/gate.sh' '$ADV' '$ADV/repo'" -- "$B" "$W" 2>/dev/null); rc=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
[[ $rc -eq 0 && "$(cat "$ADV/count")" == "2" \
   && "$(git -C "$M" show refs/remotes/origin/main:advanced.txt)" == "advanced" \
   && "$(git -C "$M" show refs/remotes/origin/main:source.txt)" == "source" ]] \
  && ok "stage-a: remote movement rebuilds candidate; gate reaches attempt 2" \
  || bad "stage-a remote rebuild" "rc=$rc attempts=$(cat "$ADV/count" 2>/dev/null) $out"
rm -rf "$ADV"; cleanproj "$M"

# SA4. Candidate merge conflict preserves source and rescue ref, and returns agent-action exit 20.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" file.txt source-line source-conflict
source_sha=$(git -C "$W" rev-parse HEAD)
advance_origin "$M" file.txt remote-line remote-conflict
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
rescue=$(git -C "$M" for-each-ref --format='%(objectname)' refs/rescue/land/ | grep -F "$source_sha" || true)
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "candidate-conflict" \
   && -d "$W" && "$(git -C "$M" rev-parse "$B")" == "$source_sha" && "$rescue" == "$source_sha" ]] \
  && ok "stage-a: candidate conflict preserves source + rescue ref" \
  || bad "stage-a candidate conflict" "rc=$rc rescue=$rescue wt=$([[ -d $W ]] && echo present) $out"
cleanproj "$M"

# SA5. Source branch movement during candidate gate lands snapshot but retains moved branch/worktree.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source source-snapshot
source_sha=$(git -C "$W" rev-parse HEAD)
MOVE=$(mktemp -d /tmp/fb-move-XXXX)
cat > "$MOVE/gate.sh" <<'EOF'
#!/usr/bin/env bash
set -eu
wt=$1 state=$2
if mkdir "$state/once" 2>/dev/null; then
  printf 'moved\n' > "$wt/moved.txt"
  git -C "$wt" add -A; git -C "$wt" commit -q -m source-moved
fi
EOF
chmod +x "$MOVE/gate.sh"
out=$(run land --root "$M" --base main --mode merge-to-main \
  --testcmd "bash '$MOVE/gate.sh' '$W' '$MOVE'" -- "$B" "$W" 2>/dev/null); rc=$?
moved_sha=$(git -C "$M" rev-parse "$B")
git -C "$M" fetch -q origin main:refs/remotes/origin/main
git -C "$M" merge-base --is-ancestor "$source_sha" refs/remotes/origin/main; snapshot_landed=$?
git -C "$M" merge-base --is-ancestor "$moved_sha" refs/remotes/origin/main; moved_landed=$?
[[ $rc -eq 0 && $snapshot_landed -eq 0 && $moved_landed -ne 0 && "$moved_sha" != "$source_sha" && -d "$W" ]] \
  && ok "stage-a: moved source retained; exact snapshot lands" \
  || bad "stage-a moved source" "rc=$rc snapshot_landed=$snapshot_landed moved_landed=$moved_landed wt=$([[ -d $W ]] && echo present) $out"
rm -rf "$MOVE"; cleanproj "$M"

# SA6. Config absent preserves legacy output and local-main fast-forward behavior byte-for-byte.
IFS='|' read -r M W B <<<"$(mkproj)"
wt_commit "$W" file.txt branch-feature legacy-land
expected='{"stage":"landed","status":"done","next":"none","detail":"merged to main, pushed, worktree removed, branch deleted"}'
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
[[ $rc -eq 0 && "$out" == "$expected" && "$(git -C "$M" log --format=%s -1 main)" == "legacy-land" ]] \
  && ok "legacy: absent opt-in preserves exact output + local fast-forward" \
  || bad "legacy byte identity" "rc=$rc expected=$expected actual=$out"
cleanproj "$M"

# SA7. Deploy/e2e verified source tree cannot promote a different candidate tree.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; touch "$M/wrangler.toml"
wt_commit "$W" source.txt source source-work
source_sha=$(git -C "$W" rev-parse HEAD)
advance_origin "$M" remote.txt remote remote-work
out=$(run land --root "$M" --base main --mode deploy-verify --anchor "deploy:wrangler.toml" \
  --testcmd true --deploycmd 'echo https://prev.test > .ship-preview-url' --e2ecmd true \
  --promote merge-to-main -- "$B" "$W" 2>/dev/null); rc=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
git -C "$M" merge-base --is-ancestor "$source_sha" refs/remotes/origin/main; source_landed=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "e2e-stale-base" && $source_landed -ne 0 && -d "$W" ]] \
  && ok "stage-a deploy-verify: differing candidate tree fails e2e-stale-base" \
  || bad "stage-a e2e stale base" "rc=$rc source_landed=$source_landed $out"
cleanproj "$M"

# SA8. Tracked source edits not represented by the snapshot block landing and destructive cleanup.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt committed source-work
remote_before=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
printf 'uncommitted\n' > "$W/source.txt"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
remote_after=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "source-dirty-tree" \
   && "$remote_after" == "$remote_before" && -d "$W" && "$(cat "$W/source.txt")" == "uncommitted" ]] \
  && ok "stage-a: dirty source blocks land and preserves worktree" \
  || bad "stage-a dirty source" "rc=$rc remote_before=$remote_before remote_after=$remote_after $out"
cleanproj "$M"

# SA9. Candidate push alone receives a matching 0600 authority nonce; rejection still removes it.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source source-work
bare=$(git -C "$M" remote get-url origin)
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
candidate=$( set +u; source "$LIB" >/dev/null 2>&1; _stage_a_candidate_dir "$M" )
SEEN=$(mktemp /tmp/fb-authority-seen-XXXX); rm -f "$SEEN"
cat > "$bare/hooks/pre-receive" <<EOF
#!/usr/bin/env bash
set -eu
authority="$candidate/.git/harness/land-authority.\${HARNESS_LAND_TOKEN:-none}"
[[ "\${HARNESS_LAND_TOKEN:-}" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ ]]
[[ -f "\$authority" && "\$(stat -c %a "\$authority")" == 600 ]]
printf 'seen\n' > '$SEEN'
exit 1
EOF
chmod +x "$bare/hooks/pre-receive"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "push-failed" \
   && "$(cat "$SEEN" 2>/dev/null)" == "seen" && ! -d "$candidate" \
   && -z "$(find "$common/harness" -maxdepth 1 -name 'land-authority.*' 2>/dev/null)" && -d "$W" ]] \
  && ok "stage-a: scoped 0600 authority nonce removed after rejected push" \
  || bad "stage-a authority lifecycle" "rc=$rc seen=$(cat "$SEEN" 2>/dev/null) authority=$(find "$common/harness" -maxdepth 1 -name 'land-authority.*') $out"
rm -f "$SEEN"; cleanproj "$M"

# SA10. Push failure before merge preserves source branch/worktree; successful land cleans afterward.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source source-work
source_sha=$(git -C "$W" rev-parse HEAD)
remote_before=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
bare=$(git -C "$M" remote get-url origin)
cat > "$bare/hooks/pre-receive" <<'EOF'
#!/usr/bin/env bash
exit 1
EOF
chmod +x "$bare/hooks/pre-receive"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
remote_after=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
rescue=$(git -C "$M" for-each-ref --format='%(objectname)' refs/rescue/land/ | grep -F "$source_sha" || true)
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "push-failed" \
   && "$remote_after" == "$remote_before" && -d "$W" \
   && "$(git -C "$M" rev-parse "$B")" == "$source_sha" && "$rescue" == "$source_sha" ]] \
  && ok "stage-a: push failure preserves source branch, worktree, and rescue ref" \
  || bad "stage-a push failure preservation" "rc=$rc remote_before=$remote_before remote_after=$remote_after rescue=$rescue wt=$([[ -d $W ]] && echo present) $out"
rm -f "$bare/hooks/pre-receive"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
[[ $rc -eq 0 && ! -d "$W" \
   && "$(git -C "$M" rev-parse --verify --quiet "$B" >/dev/null 2>&1; echo $?)" != "0" \
   && "$(git -C "$M" show refs/remotes/origin/main:source.txt)" == "source" ]] \
  && ok "stage-a: successful land cleans source after merge" \
  || bad "stage-a successful cleanup" "rc=$rc wt=$([[ -d $W ]] && echo present) br=$(git -C "$M" rev-parse --verify --quiet "$B" 2>/dev/null || echo gone) $out"
cleanproj "$M"

# SA11b. The candidate push holds harness/land.lock. The guarded-trunk pre-push hook rejects a main
#        update whenever it can take that lock itself, so a lander that does not hold it cannot land
#        at all. Mirrors the guard's probe on the receiving side: a fresh open of the same file is a
#        distinct lock owner, so flock -n succeeds exactly when the lander dropped the lock.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source source-work
bare=$(git -C "$M" remote get-url origin)
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
mkdir -p "$common/harness"
cat > "$bare/hooks/pre-receive" <<EOF
#!/usr/bin/env bash
exec {probe}>'$common/harness/land.lock'
if flock -n "\$probe"; then
  printf 'push reached main outside the land lock\n' >&2
  exit 1
fi
exit 0
EOF
chmod +x "$bare/hooks/pre-receive"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
[[ $rc -eq 0 && "$(jget "$(lastline "$out")" 'd["stage"]')" == "landed" \
   && "$(git -C "$M" show refs/remotes/origin/main:source.txt)" == "source" ]] \
  && ok "stage-a: candidate push holds the land lock the pre-push guard requires" \
  || bad "stage-a land lock held across push" "rc=$rc $out"
cleanproj "$M"

# SA11. worktree remove that prunes the branch ref is idempotent cleaned, not branch-delete-failed.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source source-work
source_sha=$(git -C "$W" rev-parse HEAD)
ORIGPATH=$PATH
GITWRAP=$(mktemp -d /tmp/fb-gitwrap-XXXX)
cat > "$GITWRAP/git" <<EOF
#!/usr/bin/env bash
if [[ "\$1" == "-C" && "\$3" == "worktree" && "\$4" == "remove" ]]; then
  repo="\$2"; wt="\$5"
  br=\$(env PATH="$ORIGPATH" git -C "\$repo" worktree list --porcelain 2>/dev/null | awk -v p="\$wt" '
    \$1=="worktree"&&\$2==p{f=1; next} f&&\$1=="branch"{sub(/^refs\\/heads\\//,""); print; exit}')
  env PATH="$ORIGPATH" git "\$@" || exit \$?
  [[ -n "\$br" ]] && env PATH="$ORIGPATH" git -C "\$repo" update-ref -d "refs/heads/\$br" 2>/dev/null || true
  exit 0
fi
exec env PATH="$ORIGPATH" git "\$@"
EOF
chmod +x "$GITWRAP/git"
j=$(PATH="$GITWRAP:$PATH" bash -c 'source "'"$LIB"'"; _stage_a_cleanup "'"$M"'" "'"$B"'" "'"$W"'" "'"$source_sha"'" ""')
[[ "$(jget "$j" 'd["status"]')" == "cleaned" && ! -d "$W" \
   && "$(git -C "$M" rev-parse --verify --quiet "$B" >/dev/null 2>&1; echo $?)" != "0" ]] \
  && ok "stage-a cleanup: pruned branch after worktree remove → cleaned (idempotent)" \
  || bad "stage-a cleanup idempotent" "$j wt=$([[ -d $W ]] && echo present) br=$(git -C "$M" rev-parse --verify --quiet "$B" 2>/dev/null || echo gone)"
rm -rf "$GITWRAP"; cleanproj "$M"

# ── usage faults ──────────────────────────────────────────────────────────────────────────────
# 18. unknown subcommand → non-zero
if run bogus 2>/dev/null; then bad "usage: unknown subcommand non-zero" "exit 0"; else ok "usage: unknown subcommand → non-zero"; fi
# 19. not a git repo → non-zero (usage/env fault, not a JSON gate result)
if run preflight /tmp/fb-nope-$$ x /tmp/fb-nope2-$$ 2>/dev/null; then bad "usage: non-repo non-zero" "exit 0"; else ok "usage: non-repo → non-zero"; fi
[[ $(wc -l < "$TEST_GATE_LOG") -gt 0 ]] \
  && ok "test gate: routes through local-gate seam" \
  || bad "test gate remote routing" "local-gate seam was not called"
grep -Fq -- ' --remote-env CI=true -- ' "$TEST_GATE_LOG" \
  && ok "test gate: marks remote execution as CI" \
  || bad "test gate remote env" "local-gate seam did not receive --remote-env CI=true"

# ── docs lane: the gate's cost is derived from the diff ───────────────────────────────────────
# The DANGEROUS branch is "took the fast lane"; every case below either proves the full gate ran
# (local-gate seam called) or proves a docs check actually fired.
REPO_ROOT=$(cd "$(dirname "$0")/../../../../.." && pwd)
DOCS_MDCLI="$REPO_ROOT/node_modules/.bin/markdownlint-cli2"
[[ -x "$DOCS_MDCLI" ]] \
  && ok "docs lane: markdownlint-cli2 devDependency present" \
  || bad "docs lane tooling" "missing $DOCS_MDCLI — run pnpm install"
export FINISH_BRANCH_MARKDOWNLINT="$DOCS_MDCLI"

gate_reset() { : > "$TEST_GATE_LOG"; }
gate_called() { [[ $(wc -l < "$TEST_GATE_LOG") -gt 0 ]]; }
stamps_of() { printf '%s' "$1/.git/harness/land-stamps.jsonl"; }
stamp_q() { # <stampfile> <python-expr over list `s`>
  python3 -c "import sys,json;s=[json.loads(l) for l in open(sys.argv[1]) if l.strip()];print($2)" "$1"
}
docs_commit() { local wt=$1 rel=$2 body=$3 m=$4; mkdir -p "$wt/$(dirname "$rel")"; printf '%s' "$body" > "$wt/$rel"; git -C "$wt" add -A; git -C "$wt" commit -q -m "$m"; }

AGENT_MD=$'---\nname: canary-agent\nmodel: claude-fable-5\neffort: xhigh\n---\n\nbody\n'

# DL1. docs-only path set → docs lane, build/test never invoked, deliberate skip is STAMPED.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
docs_commit "$W" docs/note.md $'# note\n\ntext\n' docs-only
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd 'exit 7' -- "$B" "$W" 2>/dev/null); rc=$?
S=$(stamps_of "$M")
[[ $rc -eq 0 ]] && ! gate_called \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="path-classification"][0]')" == "pass" ]] \
  && [[ "$(stamp_q "$S" '[x["canary_detected"] for x in s if x["gate"]=="path-classification"][0]')" == "True" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="typecheck"][0]')" == "could-not-run" ]] \
  && [[ "$(stamp_q "$S" '[x["discharged_by"] for x in s if x["gate"]=="typecheck"][0]')" == "path-classification" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="test"][0]')" == "could-not-run" ]] \
  && [[ "$(stamp_q "$S" '[x["applicability"] for x in s if x["gate"]=="test"][0]')" == "not-applicable" ]] \
  && [[ "$(stamp_q "$S" '[x["discharged_by"] for x in s if x["gate"]=="test"][0]')" == "path-classification" ]] \
  && [[ "$(stamp_q "$S" 'len({x["inputs_hashed"] for x in s})')" == "1" ]] \
  && ok "docs lane: docs-only set skips build/test, skip stamped not-applicable + discharged" \
  || bad "docs lane docs-only" "rc=$rc gate_called=$? $(cat "$S" 2>/dev/null)"
cleanproj "$M"

# DL2. ONE .ts added to an otherwise docs-only set → full gate. The dangerous branch.
# Package must declare typecheck (and be green) — full gate now typechecks touched packages.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
_TSC_BIN="$(cd "$(dirname "$0")/../../../../.." && pwd)/node_modules/.bin"
[[ -x "$_TSC_BIN/tsc" ]] && export PATH="$_TSC_BIN:$PATH"
docs_commit "$W" docs/note.md $'# note\n\ntext\n' docs-part
mkdir -p "$W/pkg"
printf '%s\n' '{"name":"pkg","private":true,"scripts":{"typecheck":"tsc --noEmit --pretty false --strict --skipLibCheck index.ts"}}' > "$W/pkg/package.json"
printf 'export const x: number = 1;\n' > "$W/pkg/index.ts"
git -C "$W" add -A; git -C "$W" commit -q -m code-part
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
S=$(stamps_of "$M")
[[ $rc -eq 0 ]] && gate_called \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="path-classification"][0]')" == "pass" ]] \
  && [[ "$(stamp_q "$S" '[x["lane"] for x in s if x["gate"]=="path-classification"][0]')" == "full" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="typecheck"][0]')" == "pass" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="test"][0]')" == "pass" ]] \
  && ok "docs lane: one .ts in the set forces the full gate" \
  || bad "docs lane ts escape" "rc=$rc $(cat "$S" 2>/dev/null)"
cleanproj "$M"

# DL2b. Package-local binaries installed by depcmd are available to typecheck scripts.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
mkdir -p "$W/pkg"
printf '%s\n' '{"name":"pkg","private":true,"scripts":{"typecheck":"local-typecheck"}}' > "$W/pkg/package.json"
printf 'export const x: number = 1;\n' > "$W/pkg/index.ts"
git -C "$W" add -A; git -C "$W" commit -q -m local-typecheck
local_bin_depcmd='mkdir -p pkg/node_modules/.bin && printf '\''#!/usr/bin/env bash\nexit 0\n'\'' > pkg/node_modules/.bin/local-typecheck && chmod +x pkg/node_modules/.bin/local-typecheck'
out=$(run land --root "$M" --base main --mode merge-to-main --depcmd "$local_bin_depcmd" --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
S=$(stamps_of "$M")
[[ $rc -eq 0 ]] && gate_called \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="typecheck"][0]')" == "pass" ]] \
  && ok "typecheck floor: package-local binaries resolve after dependency install" \
  || bad "typecheck floor local binary" "rc=$rc $out stamps=$(cat "$S" 2>/dev/null)"
cleanproj "$M"

# TC1. Deliberate type error in a real source file + testcmd=true → RED, nothing lands.
# This is the land-gate hole: before the typecheck floor, --testcmd true published tsc-red commits.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
_TSC_BIN="$(cd "$(dirname "$0")/../../../../.." && pwd)/node_modules/.bin"
[[ -x "$_TSC_BIN/tsc" ]] && export PATH="$_TSC_BIN:$PATH"
mkdir -p "$W/pkg"
printf '%s\n' '{"name":"pkg","private":true,"scripts":{"typecheck":"tsc --noEmit --pretty false --strict --skipLibCheck index.ts"}}' > "$W/pkg/package.json"
printf 'export const broken: string = 42;\n' > "$W/pkg/index.ts"
git -C "$W" add -A; git -C "$W" commit -q -m 'deliberate type error'
before=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
after=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
S=$(stamps_of "$M")
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "candidate-typecheck-failed" && "$before" == "$after" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="typecheck"][0]')" == "fail" ]] \
  && ok "typecheck floor: deliberate tsc error blocks land (testcmd=true is not enough)" \
  || bad "typecheck floor tsc red" "rc=$rc before=$before after=$after $out stamps=$(cat "$S" 2>/dev/null)"
cleanproj "$M"

# DL3. agent frontmatter change → docs lane, but secret scan AND schema check actually ran.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
docs_commit "$W" modules/x/agents/canary.md "$AGENT_MD" agent-frontmatter
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd 'exit 7' -- "$B" "$W" 2>/dev/null); rc=$?
S=$(stamps_of "$M")
[[ $rc -eq 0 ]] && ! gate_called \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="secret-scan"][0]')" == "pass" ]] \
  && [[ "$(stamp_q "$S" '[x["applicability"] for x in s if x["gate"]=="secret-scan"][0]')" == "applicable" ]] \
  && [[ "$(stamp_q "$S" '[x["canary_detected"] for x in s if x["gate"]=="secret-scan"][0]')" == "True" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="frontmatter-schema"][0]')" == "pass" ]] \
  && [[ "$(stamp_q "$S" '[x["applicability"] for x in s if x["gate"]=="frontmatter-schema"][0]')" == "applicable" ]] \
  && ok "docs lane: agent prompt change skips build/test but runs secret scan + schema check" \
  || bad "docs lane agent frontmatter" "rc=$rc $(cat "$S" 2>/dev/null)"
cleanproj "$M"

# DL4. malformed frontmatter → RED, nothing lands.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
before=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
docs_commit "$W" modules/x/agents/broken.md $'---\nname: broken\neffort: nonsense-effort\n---\n\nbody\n' bad-frontmatter
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
after=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
S=$(stamps_of "$M")
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "candidate-docs-lane-failed" && "$before" == "$after" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="frontmatter-schema"][0]')" == "fail" ]] \
  && ok "docs lane: malformed agent frontmatter is red and lands nothing" \
  || bad "docs lane malformed frontmatter" "rc=$rc before=$before after=$after $out"
cleanproj "$M"

# DL4b. unterminated frontmatter → RED (a malformed block is not the same as no block).
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
before=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
docs_commit "$W" modules/x/skills/y/SKILL.md $'---\nname: y\nmodel: opus\n\nbody with no closing marker\n' unterminated
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
after=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "candidate-docs-lane-failed" && "$before" == "$after" ]] \
  && ok "docs lane: unterminated frontmatter is red" \
  || bad "docs lane unterminated frontmatter" "rc=$rc before=$before after=$after $out"
cleanproj "$M"

# DL4c. a prompt-shaped page with NO frontmatter block asserts nothing about what runs → not a red.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
docs_commit "$W" modules/x/skills/y/SKILL.md $'# plain page\n\ntext\n' no-frontmatter
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd 'exit 7' -- "$B" "$W" 2>/dev/null); rc=$?
S=$(stamps_of "$M")
[[ $rc -eq 0 ]] && ! gate_called \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="frontmatter-schema"][0]')" == "pass" ]] \
  && ok "docs lane: prompt page without a frontmatter block is not a false red" \
  || bad "docs lane no-frontmatter false red" "rc=$rc $(cat "$S" 2>/dev/null)"
cleanproj "$M"

# DL5. planted secret in a docs file → RED. A secret scan that cannot fire is a meaningless green.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
before=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
docs_commit "$W" docs/leak.md "# leak"$'\n\n''    aws_key = "AKIA2E0A8F3B244C9986"'$'\n' planted-secret
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
after=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
S=$(stamps_of "$M")
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "candidate-docs-lane-failed" && "$before" == "$after" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="secret-scan"][0]')" == "fail" ]] \
  && ok "docs lane: planted secret in a docs file is red" \
  || bad "docs lane planted secret" "rc=$rc before=$before after=$after $out"
cleanproj "$M"

# DL6. broken relative link in a changed doc → RED.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
before=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
docs_commit "$W" docs/broken-link.md $'# x\n\n[gone](./__no_such_file__.md)\n' broken-link
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
after=$(git -C "$M" ls-remote origin refs/heads/main | awk '{print $1}')
S=$(stamps_of "$M")
[[ $rc -eq 20 && "$(jget "$(lastline "$out")" 'd["status"]')" == "candidate-docs-lane-failed" && "$before" == "$after" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="link-check"][0]')" == "fail" ]] \
  && ok "docs lane: broken relative link is red" \
  || bad "docs lane broken link" "rc=$rc before=$before after=$after $out"
cleanproj "$M"

# DL7. a docs-lane check binary absent → FULL gate, never a silent pass.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
docs_commit "$W" docs/note.md $'# note\n\ntext\n' docs-only
out=$(FINISH_BRANCH_MARKDOWNLINT=/nonexistent/markdownlint-cli2 \
  run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
S=$(stamps_of "$M")
[[ $rc -eq 0 ]] && gate_called \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="markdown-lint"][0]')" == "could-not-run" ]] \
  && [[ "$(stamp_q "$S" '[x["applicability"] for x in s if x["gate"]=="markdown-lint"][0]')" == "applicable" ]] \
  && [[ "$(stamp_q "$S" '[x["verdict"] for x in s if x["gate"]=="test"][0]')" == "pass" ]] \
  && ok "docs lane: missing check binary falls back to the full gate" \
  || bad "docs lane missing binary" "rc=$rc $(cat "$S" 2>/dev/null)"
cleanproj "$M"

# DL8. symlink under an allowlisted root → full gate (docs by path, but it changes what resolves).
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
mkdir -p "$W/docs"; ln -s ../src "$W/docs/link"; git -C "$W" add -A; git -C "$W" commit -q -m docs-symlink
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
S=$(stamps_of "$M")
[[ $rc -eq 0 ]] && gate_called \
  && [[ "$(stamp_q "$S" '[x["lane"] for x in s if x["gate"]=="path-classification"][0]')" == "full" ]] \
  && ok "docs lane: symlink in the changed set forces the full gate" \
  || bad "docs lane symlink" "rc=$rc $(cat "$S" 2>/dev/null)"
cleanproj "$M"

# DL9-16. classifier unit assertions — it must be able to say NO, and an unresolvable base must not
# resolve to "fast". Sourced directly: there is no flag that can reach this decision from outside.
( set +u; source "$LIB" >/dev/null 2>&1
  _docs_lane_classifier_canary ) \
  && ok "docs lane: classifier canary proves it can refuse" \
  || bad "docs lane classifier canary" "canary did not hold"
dl_deny() {
  ( set +u; source "$LIB" >/dev/null 2>&1; _docs_lane_path_verdict "$1" ) \
    && bad "docs lane path deny" "classified as docs: $1" || ok "docs lane: forces full gate for $1"
}
dl_allow() {
  ( set +u; source "$LIB" >/dev/null 2>&1; _docs_lane_path_verdict "$1" ) \
    && ok "docs lane: allows $1" || bad "docs lane path allow" "rejected: $1"
}
dl_deny 'docs/../src/index.ts'
dl_deny '.claude/skills/x/SKILL.md'
dl_deny 'docs/plans/2026-01-01-x.md'
dl_deny 'packaging/deploy-local.sh'
dl_deny 'docs/run.sh'
dl_deny '/etc/passwd'
dl_deny 'docs/a[b].md'
dl_deny 'docs/!important.md'
dl_deny 'docs/star*.md'
dl_deny 'docs/{a,b}.md'
dl_deny '-rf.md'
dl_deny 'docs/-flag.md'
dl_allow 'docs/note.md'
dl_allow 'modules/x/agents/a.md'
IFS='|' read -r M W B <<<"$(mkproj)"
( set +u; source "$LIB" >/dev/null 2>&1
  _docs_lane_classify "$M" deadbeefdeadbeefdeadbeefdeadbeefdeadbeef HEAD "$M/.git/dl-paths" ) \
  && bad "docs lane unresolvable base" "classified as docs lane" \
  || ok "docs lane: unresolvable base forces the full gate"
cleanproj "$M"

# ── land queue: FIFO tickets + one conductor, no timeout ─────────────────────────────────────
qdir_of() { printf '%s' "$1/.git/harness/landq"; }

# LQ1. Every ticket records its queue depth at arrival and its gate class.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
docs_commit "$W" docs/note.md $'# note\n\ntext\n' docs-only
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
Q=$(qdir_of "$M")
[[ $rc -eq 0 && -f "$Q/log" ]] \
  && [[ "$(jget "$(lastline "$(cat "$Q/log")")" 'd["queue_depth_at_arrival"]')" == "0" ]] \
  && [[ "$(jget "$(lastline "$(cat "$Q/log")")" 'd["gate_class"]')" == "docs" ]] \
  && ok "land queue: ticket logs queue depth at arrival and gate class" \
  || bad "land queue depth log" "rc=$rc $(cat "$Q/log" 2>/dev/null)"
cleanproj "$M"

# LQ2. A head already reachable from origin/main is landed, not re-gated: this is how a successor
# conductor recovers a ticket whose conductor pushed and then died. Derived from git, no journal.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
wt_commit "$W" source.txt source source-work
source_sha=$(git -C "$W" rev-parse HEAD)
git -C "$W" push -q origin HEAD:main
stale_candidate=$( set +u; source "$LIB" >/dev/null 2>&1; _stage_a_candidate_dir "$M" )
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
mkdir -p "$stale_candidate/.git/harness" "$common/harness"
printf 'stale\n' > "$stale_candidate/.git/harness/land-authority.00000000-0000-0000-0000-000000000000"
printf 'stale\n' > "$common/harness/source-crashed.bundle"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd 'exit 7' -- "$B" "$W" 2>/dev/null); rc=$?
[[ $rc -eq 0 ]] && ! gate_called \
  && [[ ! -d "$W" && ! -d "$stale_candidate" && ! -e "$common/harness/source-crashed.bundle" ]] \
  && [[ "$(git -C "$M" rev-parse --verify --quiet "$B" >/dev/null 2>&1; echo $?)" != "0" ]] \
  && ok "land queue: already-reachable head recovers as landed without re-running the gate" \
  || bad "land queue recovery" "rc=$rc wt=$([[ -d $W ]] && echo present) $out"
cleanproj "$M"

# LQ3. A ticket a conductor cannot fully resolve is rejected BY FIELD NAME, never guessed around.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
lq_verdict=$( set +u; source "$LIB" >/dev/null 2>&1
  q=$(_landq_dir "$M"); mkdir -p "$q"
  { printf 'root %s\n' "$(_landq_enc "$M")"; printf 'wt %s\n' "$(_landq_enc "$W")"
    printf 'branch %s\n' "$(_landq_enc "$B")"; printf 'head %s\n' "$(_landq_enc HEAD)"
    printf 'base %s\n' "$(_landq_enc refs/remotes/origin/main)"
    printf 'rescue_ref %s\n' "$(_landq_enc refs/rescue/land/x)"
    printf 'mode %s\n' "$(_landq_enc stage-a)"; printf 'gate_class %s\n' "$(_landq_enc full)"
  } > "$q/ticket.00000000000000000000000000000001.job"
  _landq_serve "$q" ticket.00000000000000000000000000000001
  tail -n +2 "$q/ticket.00000000000000000000000000000001.verdict" )
[[ "$(jget "$lq_verdict" 'd["status"]')" == "ticket-rejected" \
   && "$(jget "$lq_verdict" 'd["detail"]')" == *testcmd* ]] \
  && ok "land queue: unresolvable ticket is rejected naming the missing field" \
  || bad "land queue ticket reject" "$lq_verdict"
cleanproj "$M"

# LQ3b. A missing object rejects only its ticket; the conductor lands the next FIFO ticket.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" source.txt source queue-survivor
good_sha=$(git -C "$W" rev-parse HEAD)
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
Q=$(qdir_of "$M"); mkdir -p "$Q" "$common/refs/rescue/land"
bad_sha=$(printf '%040d' 2)
printf '%s\n' "$bad_sha" > "$common/refs/rescue/land/missing-ticket"
git -C "$M" update-ref refs/rescue/land/good-ticket "$good_sha"
bad=ticket.00000000000000000000000000000002
good=ticket.00000000000000000000000000000003
lq_result=$( set +u; source "$LIB" >/dev/null 2>&1
  write_job() {
    local ticket=$1 head=$2 rescue=$3
    { printf 'root %s\n' "$(_landq_enc "$M")"; printf 'wt %s\n' "$(_landq_enc "$W")"
      printf 'branch %s\n' "$(_landq_enc "$B")"; printf 'head %s\n' "$(_landq_enc "$head")"
      printf 'base %s\n' "$(_landq_enc refs/remotes/origin/main)"
      printf 'rescue_ref %s\n' "$(_landq_enc "$rescue")"
      printf 'mode %s\n' "$(_landq_enc stage-a)"; printf 'testcmd %s\n' "$(_landq_enc true)"
      printf 'gate_class %s\n' "$(_landq_enc full)"
    } > "$Q/$ticket.job"
  }
  write_job "$bad" "$bad_sha" refs/rescue/land/missing-ticket
  write_job "$good" "$good_sha" refs/rescue/land/good-ticket
  printf '%s\n%s\n' "$bad" "$good" > "$Q/queue"
  exec {badfd}>"$Q/$bad.lock"; flock "$badfd"
  exec {goodfd}>"$Q/$good.lock"; flock "$goodfd"
  exec {conductorfd}>"$Q/conductor.lock"; flock "$conductorfd"
  _landq_conduct "$Q"; conduct_rc=$?
  printf '%s|%s|%s|%s|%s\n' "$conduct_rc" \
    "$(head -1 "$Q/$bad.verdict")" "$(jq_status "$(tail -n +2 "$Q/$bad.verdict")")" \
    "$(head -1 "$Q/$good.verdict")" "$(jq_status "$(tail -n +2 "$Q/$good.verdict")")"
)
remote=$(git -C "$M" remote get-url origin)
[[ "$lq_result" == "0|20|source-export-failed|0|pushed" \
   && "$(git --git-dir="$remote" show refs/heads/main:source.txt)" == source ]] \
  && ok "land queue: missing-object ticket rejected; next FIFO ticket lands" \
  || bad "land queue missing-ticket containment" "result=$lq_result"
cleanproj "$M"

# LQ4. A ticket whose owner is gone is pruned, never landed: nobody would run its owner-side cleanup.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"; gate_reset
wt_commit "$W" source.txt source source-work
Q=$(qdir_of "$M"); mkdir -p "$Q"
stale=ticket.0000000000000000000000000000dead
printf '%s\n' "$stale" > "$Q/queue"; : > "$Q/$stale.lock"
printf 'root %s\n' "$(printf '%s' "$M" | base64 -w0)" > "$Q/$stale.job"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
[[ $rc -eq 0 && ! -f "$Q/$stale.lock" && ! -f "$Q/$stale.job" && ! -f "$Q/$stale.verdict" ]] \
  && [[ "$(grep -c . "$Q/queue")" == "0" ]] \
  && [[ "$(git -C "$M" show refs/remotes/origin/main:source.txt)" == "source" ]] \
  && ok "land queue: ownerless ticket is pruned, live ticket still lands" \
  || bad "land queue ownerless prune" "rc=$rc queue=$(cat "$Q/queue" 2>/dev/null) $out"
cleanproj "$M"

# LQ5. Exactly one of two concurrent landers conducts; the other waits for a verdict instead of
# failing on a clock. Both land.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
git -C "$W" branch -m feat-a; B=feat-a
wt_commit "$W" a.txt a land-a
W2=$(mktemp -d /tmp/fb-wt2-XXXX); rmdir "$W2"
git -C "$M" worktree add -q "$W2" -b feat-b main 2>/dev/null
wt_commit "$W2" b.txt b land-b
LQ=$(mktemp -d /tmp/fb-lq-XXXX)
bash "$LIB" land --root "$M" --base main --mode merge-to-main \
  --testcmd 'sleep 8' -- feat-a "$W" >"$LQ/a.out" 2>&1 & p1=$!
bash "$LIB" land --root "$M" --base main --mode merge-to-main \
  --testcmd 'sleep 8' -- feat-b "$W2" >"$LQ/b.out" 2>&1 & p2=$!
wait "$p1"; rc1=$?; wait "$p2"; rc2=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
conductors=$(grep -l 'land queue — conducting' "$LQ/a.out" "$LQ/b.out" 2>/dev/null | wc -l)
waiters=$(grep -L 'land queue — conducting' "$LQ/a.out" "$LQ/b.out" 2>/dev/null \
  | xargs -r grep -l 'waiting for the conductor' | wc -l)
[[ $rc1 -eq 0 && $rc2 -eq 0 && "$conductors" -eq 1 && "$waiters" -eq 1 \
   && "$(git -C "$M" log --format=%s refs/remotes/origin/main | grep -c land-a)" == "1" \
   && "$(git -C "$M" log --format=%s refs/remotes/origin/main | grep -c land-b)" == "1" ]] \
  && ok "land queue: concurrent landers share one conductor and both land" \
  || bad "land queue concurrency" "rc1=$rc1 rc2=$rc2 a=$(cat "$LQ/a.out") b=$(cat "$LQ/b.out")"
rm -rf "$LQ"; cleanproj "$M"

GUARD_INSTALL="$(cd "$(dirname "$0")/../hooks" && pwd)/install-land-guard.sh"

# LG1. With the shipped guard armed, a raw push to main is rejected and a real land still succeeds.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
bash "$GUARD_INSTALL" "$M" >/dev/null
main_commit "$M" raw.txt raw raw-push
raw=$(git -C "$M" push origin main 2>&1); rawrc=$?
git -C "$M" reset -q --hard origin/main
wt_commit "$W" g.txt g guarded-land
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
[[ $rawrc -ne 0 && "$raw" == *"unauthorized main update"* && $rc -eq 0 \
   && "$(git -C "$M" log --format=%s refs/remotes/origin/main | grep -c guarded-land)" == "1" ]] \
  && ok "land guard: raw push rejected, lander push authorized" \
  || bad "land guard raw vs lander" "rawrc=$rawrc raw=$raw rc=$rc $out"
cleanproj "$M"

# LG1b. Isolated candidate preserves the repository's existing pre-push policy chain.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
hooks="$common/custom-hooks"; marker="$common/custom-pre-push-ran"
mkdir -p "$hooks"
cat > "$hooks/policy-helper" <<EOF
#!/usr/bin/env bash
printf 'ran\n' > '$marker'
EOF
cat > "$hooks/pre-push" <<'EOF'
#!/usr/bin/env bash
"$(dirname "$0")/policy-helper"
EOF
chmod +x "$hooks/pre-push" "$hooks/policy-helper"
git -C "$M" config core.hooksPath "$hooks"
wt_commit "$W" policy.txt policy policy-preserved
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
[[ $rc -eq 0 && "$(cat "$marker" 2>/dev/null)" == ran ]] \
  && ok "land guard: isolated candidate preserves existing pre-push policy" \
  || bad "land guard policy preservation" "rc=$rc marker=$(cat "$marker" 2>/dev/null) $out"
cleanproj "$M"

# LG1c. A nonce file left by a dead conductor authorizes nothing after its lock releases.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
bash "$GUARD_INSTALL" "$M" >/dev/null
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
mkdir -p "$common/harness/landq"
lock="$common/harness/landq/conductor.lock"; : > "$lock"
tok=$(< /proc/sys/kernel/random/uuid)
printf '%s\n' "$lock" > "$common/harness/land-authority.$tok"
chmod 0600 "$common/harness/land-authority.$tok"
main_commit "$M" stale.txt stale stale-authority
stale_out=$(HARNESS_LAND_TOKEN="$tok" git -C "$M" push origin main 2>&1); stale_rc=$?
[[ $stale_rc -ne 0 && "$stale_out" == *"stale land authority"* ]] \
  && ok "land guard: released conductor lock invalidates stale authority" \
  || bad "land guard stale authority" "rc=$stale_rc $stale_out"
cleanproj "$M"

# LG2. Two overlapping landers must not reject each other: the authority is named by the nonce, so
# neither can clobber the other's slot.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
bash "$GUARD_INSTALL" "$M" >/dev/null
wt_commit "$W" a.txt a guard-a
W2=$(mktemp -d /tmp/fb-wt2-XXXX); rmdir "$W2"
git -C "$M" worktree add -q "$W2" -b feat-b main 2>/dev/null
wt_commit "$W2" b.txt b guard-b
LQ=$(mktemp -d /tmp/fb-lq-XXXX)
bash "$LIB" land --root "$M" --base main --mode merge-to-main \
  --testcmd 'sleep 5' -- "$B" "$W" >"$LQ/a.out" 2>&1 & p1=$!
bash "$LIB" land --root "$M" --base main --mode merge-to-main \
  --testcmd 'sleep 5' -- feat-b "$W2" >"$LQ/b.out" 2>&1 & p2=$!
wait "$p1"; rc1=$?; wait "$p2"; rc2=$?
git -C "$M" fetch -q origin main:refs/remotes/origin/main
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
[[ $rc1 -eq 0 && $rc2 -eq 0 \
   && "$(git -C "$M" log --format=%s refs/remotes/origin/main | grep -c guard-a)" == "1" \
   && "$(git -C "$M" log --format=%s refs/remotes/origin/main | grep -c guard-b)" == "1" \
   && -z "$(find "$common/harness" -maxdepth 1 -name 'land-authority.*' 2>/dev/null)" ]] \
  && ok "land guard: concurrent landers never reject each other" \
  || bad "land guard concurrency" "rc1=$rc1 rc2=$rc2 a=$(cat "$LQ/a.out") b=$(cat "$LQ/b.out")"
rm -rf "$LQ"; cleanproj "$M"

# LG3. A rejected push carries the remote's reason instead of discarding it.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
wt_commit "$W" s.txt s stderr-land
bare=$(git -C "$M" remote get-url origin)
cat > "$bare/hooks/pre-receive" <<'EOF'
#!/usr/bin/env bash
echo "pre-receive: rejected — canary reason" >&2
exit 1
EOF
chmod +x "$bare/hooks/pre-receive"
out=$(run land --root "$M" --base main --mode merge-to-main --testcmd true -- "$B" "$W" 2>/dev/null); rc=$?
last=$(lastline "$out")
pushline=$(printf '%s\n' "$out" | grep '"status":"push-failed"' | grep '"stderr"' | tail -1)
[[ $rc -eq 20 && "$(jget "$last" 'd["status"]')" == "push-failed" && -n "$pushline" \
   && "$(jget "$pushline" 'd.get("stderr","")')" == *"canary reason"* ]] \
  && ok "land guard: push rejection reason reaches the verdict" \
  || bad "push stderr capture" "rc=$rc $last"
cleanproj "$M"

# LG5. A lander predating the per-nonce authority still lands, but only from a conductor.
IFS='|' read -r M W B <<<"$(mkproj)"; optin "$M"
bash "$GUARD_INSTALL" "$M" >/dev/null
common=$(git -C "$M" rev-parse --path-format=absolute --git-common-dir)
mkdir -p "$common/harness/landq"
tok=$(cat /proc/sys/kernel/random/uuid); printf '%s' "$tok" > "$common/harness/land-authority"
: > "$common/harness/landq/conductor.lock"
main_commit "$M" legacy.txt legacy legacy-shared
free=$(HARNESS_LAND_TOKEN="$tok" git -C "$M" push origin main 2>&1); freerc=$?
held=$(exec {cfd}>"$common/harness/landq/conductor.lock"; flock "$cfd"; \
  HARNESS_LAND_TOKEN="$tok" git -C "$M" push origin main 2>&1); heldrc=$?
rm -f "$common/harness/land-authority"
[[ $freerc -ne 0 && "$free" == *"outside an active land-queue conductor"* && $heldrc -eq 0 ]] \
  && ok "land guard: shared authority accepted only under the conductor lock" \
  || bad "land guard legacy authority" "freerc=$freerc free=$free heldrc=$heldrc held=$held"
cleanproj "$M"

# LG4. A stale installed guard is generation skew, not a runtime surprise: drift faults before land.
IFS='|' read -r M W B <<<"$(mkproj)"
bash "$GUARD_INSTALL" "$M" >/dev/null
hookpath=$(git -C "$M" config --get core.hooksPath)/pre-push
out=$(run drift --root "$M" --base main --mode merge-to-main 2>&1); rc=$?
sed -i 's/^# harness-land-guard v3 BEGIN$/# harness-land-guard v3 BEGIN\n_lg_stale=1/' "$hookpath"
stale=$(run drift --root "$M" --base main --mode merge-to-main 2>&1); srrc=$?
[[ $rc -eq 0 && $srrc -eq 3 && "$stale" == *"different generation"* ]] \
  && ok "land guard: installed-guard generation skew faults drift" \
  || bad "land guard drift skew" "rc=$rc srrc=$srrc $out | $stale"
cleanproj "$M"

# ── land queue: a live owner's ticket is never lost ──────────────────────────────────────────
# Regression for a real incident: a lander waited 810s, conducted, and found no verdict for its
# own ticket. _landq_live was piped into the conductor loop through a process substitution, so a
# lister that failed (open(2) on a ticket lock can fail for real — fd exhaustion, EACCES, ENOSPC)
# was indistinguishable from an empty queue, and "no ticket to serve" is the SUCCESS exit. The
# conductor returned 0 having served nothing, and the owner reported the wrong diagnosis.

# LQ-L1. A lister that fails must never read as a fully served queue.
lqd=$(mktemp -d /tmp/fb-lq-listfail-XXXX); : > "$lqd/queue"
crc=$( source "$LIB"; _landq_live() { return 3; }; _landq_conduct "$lqd" >/dev/null 2>&1; echo $? )
[[ "$crc" -eq 4 ]] \
  && ok "land queue: a failing lister fails the conductor closed" \
  || bad "land queue lister fail-open" "expected rc=4 (queue could not be listed), got rc=$crc — 0 means an unlistable queue read as fully served"
rm -rf "$lqd"

# LQ-L2. Under real fd starvation the conductor must fail closed, leave the live owner's ticket
#        queued and its job intact, and fabricate no verdict.
lqd=$(mktemp -d /tmp/fb-lq-fdstarve-XXXX)
lqt="ticket.$(tr -d - < /proc/sys/kernel/random/uuid)"
printf 'mode %s\n' "$(source "$LIB"; _landq_enc stage-a)" > "$lqd/$lqt.job"
setsid bash -c "exec {f}>'$lqd/$lqt.lock'; flock -n \$f || exit 1; : > '$lqd/held'; exec sleep 20" >/dev/null 2>&1 &
for _ in $(seq 1 200); do [[ -f "$lqd/held" ]] && break; sleep 0.05; done
[[ -f "$lqd/held" ]] || bad "land queue lock holder" "the owner process never acquired its ticket lock"
printf '%s\n' "$lqt" > "$lqd/queue"
crc=$( ulimit -n 12; source "$LIB"; _landq_conduct "$lqd" >/dev/null 2>&1; echo $? )
[[ "$crc" -ne 0 && -f "$lqd/$lqt.job" && ! -f "$lqd/$lqt.verdict" ]] \
  && grep -qFx "$lqt" "$lqd/queue" \
  && ok "land queue: fd-starved lister fails closed; live ticket kept, no verdict invented" \
  || bad "land queue fd-starved conductor" "rc=$crc job=$([[ -f $lqd/$lqt.job ]] && echo present || echo GONE) verdict=$([[ -f $lqd/$lqt.verdict ]] && echo INVENTED || echo absent) queued=$(grep -cFx "$lqt" "$lqd/queue")"
rm -rf "$lqd"

# LQ-L3. A live owner's ticket is never pruned by any lister, and conducting delivers its verdict.
lqd=$(mktemp -d /tmp/fb-lq-liveowner-XXXX)
lqt="ticket.$(tr -d - < /proc/sys/kernel/random/uuid)"
printf 'mode %s\n' "$(source "$LIB"; _landq_enc stage-a)" > "$lqd/$lqt.job"
setsid bash -c "exec {f}>'$lqd/$lqt.lock'; flock -n \$f || exit 1; : > '$lqd/held'; exec sleep 20" >/dev/null 2>&1 &
for _ in $(seq 1 200); do [[ -f "$lqd/held" ]] && break; sleep 0.05; done
[[ -f "$lqd/held" ]] || bad "land queue lock holder" "the owner process never acquired its ticket lock"
printf '%s\n' "$lqt" > "$lqd/queue"
bash -c "source '$LIB'; _landq_live '$lqd' >/dev/null"   # a foreign lister must not prune it
crc=$( source "$LIB"
       _landq_serve() { _landq_verdict_write "$1" "$2" 0 '{"status":"pushed"}'; }
       _landq_conduct "$lqd" >/dev/null 2>&1; echo $? )
[[ "$crc" -eq 0 && -f "$lqd/$lqt.lock" && -f "$lqd/$lqt.job" && -f "$lqd/$lqt.verdict" ]] \
  && grep -qFx "$lqt" "$lqd/queue" \
  && ok "land queue: live owner survives every lister and receives a verdict" \
  || bad "land queue live owner" "rc=$crc lock=$([[ -f $lqd/$lqt.lock ]] && echo present || echo PRUNED) job=$([[ -f $lqd/$lqt.job ]] && echo present || echo PRUNED) verdict=$([[ -f $lqd/$lqt.verdict ]] && echo present || echo MISSING) queued=$(grep -cFx "$lqt" "$lqd/queue")"
rm -rf "$lqd"

rm -f "$TEST_GATE_LOG" "$TEST_GATE_BIN"

echo
echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
