#!/usr/bin/env bash
# lane doctor — is the guard healthy, AND is it actually wired into every session?
#
#   guard-check         the evidence, in a few lines
#   guard-check -v      the same, plus every wiring location and the full test suite
#   guard-check -q      one line, for the top of the board; the detail appears only if it fails
#   guard-check --fix   in a workspace: repair what can be repaired safely first (asks before editing CLAUDE.md;
#                       --yes answers yes)
#
# Exits non-zero, and explains, if any of it is wrong. Used by status-all and by `lane doctor`.
#
# Three different claims, all checked here:
#   1. guard.py compiles.
#   2. it still answers a set of named probes the way it is supposed to — including one probe
#      that must NOT be refused, because a guard that denies everything is also broken.
#   2b. every project rule in registry/rules.yaml still refuses its own `example:` — and is
#      refused BY that rule, not incidentally by a built-in.
#   3. every lane and worktree still points at it. A session whose settings.local.json
#      lost its hooks is unguarded even though guard.py is perfectly healthy.
# And three things that are not claims and never fail the command, each with the one command
# that clears it: lanes nobody has touched in `stale_days` (registry/config.yml, 21); a managed
# GitHub repo whose real branch protection hasn't been checked in `protection: sync_days` (7);
# and a repo with candidate secret/credential filenames nobody has reviewed with `lane secrets`.
set -u
VERBOSE=0; QUIET=0; FIX=0; YES=0
for a in "$@"; do
  case "$a" in -v|--verbose) VERBOSE=1 ;; -q|--quiet) QUIET=1 ;; --fix) FIX=1 ;; -y|--yes) YES=1 ;;
    -h|--help) sed -n '2,10p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "guard-check: unknown option '$a' (try -v)" >&2; exit 2 ;; esac
done

# PRODUCT holds guard.py, AD is the workspace it guards: one folder in a clone. scripts/roots.sh decides both and every
# data path, and guard.py resolves them the same way (scripts/roots.py), so the probes judge the workspace whose wiring
# is checked here.
PRODUCT="${LANE_PRODUCT:-$(dirname "$(dirname "$(dirname "$(python3 -c 'import os,sys;print(os.path.realpath(sys.argv[1]))' "$0")")")")}"
source "$PRODUCT/scripts/roots.sh"; lane_resolve_roots
# The product is only read: no __pycache__ beside guard.py or the modules it imports, whoever runs this.
export PYTHONDONTWRITEBYTECODE=1
G="$PRODUCT/scripts/hooks/guard.py"

# A workspace (an installed product) has its own wiring to check before the guard's: that the hooks can reach `lane` at
# all, CLAUDE.md's import line, the hooks themselves, the rule files' version, the registration, every lane's settings
# (scripts/workspace.py). Its problems make the exit status non-zero even when every probe below passes.
WS_RC=0
if [ "$LANE_MODE" = workspace ]; then
  ws_flags=""; [ "$FIX" = 1 ] && ws_flags="$ws_flags --fix"; [ "$YES" = 1 ] && ws_flags="$ws_flags --yes"
  if [ "$QUIET" = 1 ]; then
    # one line, and only when something is wrong; the board's line is about the guard, so it keeps the guard's status
    python3 -B "$PRODUCT/scripts/workspace.py" doctor "$AD" --quiet || :
  else
    python3 -B "$PRODUCT/scripts/workspace.py" doctor "$AD" $ws_flags || WS_RC=1
  fi
elif [ "$FIX" = 1 ] && [ "$QUIET" = 0 ]; then
  echo "lane doctor --fix: a clone has nothing to repair automatically; the checks below say what to run"
fi

if ! python3 -B -c 'import sys; compile(open(sys.argv[1]).read(), sys.argv[1], "exec")' "$G" 2>"${TMPDIR:-/tmp}/guard-syntax.$$.txt"; then
  echo "!! scripts/hooks/guard.py does not compile — EVERY rule is currently off:"
  sed 's/^/     /' "${TMPDIR:-/tmp}/guard-syntax.$$.txt"
  exit 1
fi

# The probes. Every one runs from the control plane root, so they answer the same on a fresh
# clone as on a machine full of lanes — the claim has to be checkable before there is any work.
ask(){ printf '%s' "$1" | python3 -B "$G" 2>&1 | grep -o '"permissionDecision": "[a-z]*"' | cut -d'"' -f4; }
bash_probe(){ printf '{"hook_event_name":"PreToolUse","tool_name":"Bash","cwd":"%s","tool_input":{"command":%s}}' \
  "$AD" "$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$1")"; }
file_probe(){ printf '{"hook_event_name":"PreToolUse","tool_name":"%s","cwd":"%s","tool_input":{"file_path":"%s"}}' "$1" "$AD" "$2"; }

n=0; good=0; lines=""
probe(){ # probe <want> <label> <json>
  n=$((n+1)); got=$(ask "$3"); got=${got:-pass}
  if [ "$got" = "$1" ]; then good=$((good+1)); lines="$lines$(printf '  %-6s %s' "$got" "$2")
"
  else lines="$lines$(printf '  !! %-4s %s — wanted %s' "$got" "$2" "$1")
"; fi
}
probe deny "a worktree with no lane named"        '{"hook_event_name":"PreToolUse","tool_name":"EnterWorktree","cwd":"'"$AD"'","tool_input":{}}'
probe deny "a worktree opened by path"            '{"hook_event_name":"PreToolUse","tool_name":"EnterWorktree","cwd":"'"$AD"'","tool_input":{"path":"'"$AD"'/lanes/x"}}'
probe deny "reading a .env"                       "$(file_probe Read "$REPOS/any/.env")"
probe deny "a shell that prints a .env"           "$(bash_probe 'cat .env')"
probe deny "writing a memory directly"            "$(file_probe Write "$MEMORY_DIR/brand-new-thing.md")"
probe deny "a push to a default branch"           "$(bash_probe 'git push origin main')"
probe deny "rewriting the git remote"             "$(bash_probe 'git remote set-url origin git@github.com:x/y.git')"
probe deny "a push to main, written differently"  "$(bash_probe "git push origin 'main';")"
probe deny "grepping a .env (Grep reaches it)"    '{"hook_event_name":"PreToolUse","tool_name":"Grep","cwd":"'"$AD"'","tool_input":{"pattern":"x","path":"'"$REPOS"'/any/.env"}}'
probe deny "deleting a GitHub repo"               "$(bash_probe 'gh repo delete your-org/api --yes')"
# The control: ordinary work must come back undecided. A guard that refuses everything passes
# every deny probe above and is still useless.
probe pass "ordinary work is untouched"           "$(bash_probe 'git status')"

# Project rules (registry/rules.yaml), if this plane has any. The built-in probes above cover
# the rules that ship; nothing covers a project's own, and a rule that quietly stopped matching —
# after a refactor of the matching internals, say — is a rule that is gone. So every rule states
# an `example:` it must refuse, and every example is fed through the guard here, the same way.
# The guard itself is asked what it loaded, so the doctor and the hook cannot disagree.
RULES_ERR="${TMPDIR:-/tmp}/guard-rules.$$.txt"
RULES_JSON=$(python3 "$G" --rules 2>"$RULES_ERR") || :
if [ -s "$RULES_ERR" ]; then
  echo "!! registry/rules.yaml — these project rules are NOT being enforced:"
  sed 's/^!! //; s/^/     /' "$RULES_ERR"
  echo "     the built-in rules are unaffected; fix the file and run lane doctor again"
  rules_broken=1
fi
rm -f "$RULES_ERR"
rn=0; rgood=0; rlines=""
while IFS="$(printf '\t')" read -r rid rjson; do
  [ -n "$rid" ] || continue
  rn=$((rn+1))
  if [ "$rjson" = "@noexample" ]; then
    rlines="$rlines$(printf "  !! %-4s project rule '%s' — no example: for the doctor to check it with" "skip" "$rid")
"
    continue
  fi
  reason=$(printf '%s' "$rjson" | python3 "$G" 2>&1 | python3 -c 'import json,sys
try: d = json.load(sys.stdin)["hookSpecificOutput"]
except Exception: print("pass|"); raise SystemExit
print(d.get("permissionDecision","pass") + "|" + (d.get("permissionDecisionReason") or ""))')
  got=${reason%%|*}; why=${reason#*|}
  # deny alone is not enough: a built-in could be refusing the example for its own reasons while
  # the project rule itself no longer matches anything. The refusal has to name the rule.
  case "$got|$why" in
    deny*"'$rid'"*) rgood=$((rgood+1)); rlines="$rlines$(printf "  %-6s project rule '%s'" "deny" "$rid")
" ;;
    deny*) rlines="$rlines$(printf "  !! %-4s project rule '%s' — refused, but by a built-in, not by this rule" "deny" "$rid")
" ;;
    *) rlines="$rlines$(printf "  !! %-4s project rule '%s' — its own example was NOT refused" "$got" "$rid")
" ;;
  esac
done <<EOF
$(python3 - "$AD" "${RULES_JSON:-[]}" <<'PYR'
import json, sys
# The rules arrive as an argument, not on stdin: this script is itself read from stdin.
ad = sys.argv[1]
try: rules = json.loads(sys.argv[2]) or []
except Exception: rules = []
for r in rules:
    rid = r.get("id", "?")
    ex, tool = r.get("example"), r["when"]["tool"]
    if not ex:
        print(rid + "\t@noexample"); continue
    if isinstance(ex, str):
        ti = {"command": ex} if tool == "Bash" else {"file_path": ex}
    else:
        ti = {"command": ex.get("command", "")} if tool == "Bash" else {"file_path": ex.get("path", "")}
    print(rid + "\t" + json.dumps({"hook_event_name": "PreToolUse", "tool_name": tool, "cwd": ad, "tool_input": ti}))
PYR
)
EOF
if [ "$rn" -gt 0 ]; then n=$((n+rn)); good=$((good+rgood)); lines="$lines$rlines"; fi

if [ "$good" -eq "$n" ]; then
  [ "$QUIET" = 1 ] || { echo "guard.py compiles; $good/$n probes answered as they should$( [ "$rn" -gt 0 ] && printf " (%s of them this plane's own project rules)" "$rn" ):"; printf '%s' "$lines"; }
else
  echo "!! guard.py compiles but is not enforcing — $good/$n probes answered as they should:"; printf '%s' "$lines"
fi
[ "$good" -eq "$n" ] || { echo "   a rule that stopped refusing is a rule that is gone. Check recent edits to scripts/hooks/guard.py (the built-ins) or registry/rules.yaml (this plane's own)."; exit 1; }

# lane rules pull (docs/extending.md): the shared, SHA-pinned rules source has drifted from what
# is pinned in registry/config.yml. Cheap (`git ls-remote`, no clone), advisory-only like every
# other check below it, never auto-pulls — but printed here, first and with a stronger prefix,
# because a team's shared guard rules silently drifting is a different severity of problem than
# one person's stale branch-protection cache. Prints nothing if shared_rules isn't configured.
if [ "$QUIET" = 0 ] && [ -f "$CONFIG_FILE" ] && grep -q '^shared_rules:' "$CONFIG_FILE" 2>/dev/null; then
  SR_URL=$(sed -n '/^shared_rules:/,/^[a-z]/p' "$CONFIG_FILE" | sed -n 's/^[[:space:]]*url:[[:space:]]*//p' | head -1 | tr -d '"'"'"' ')
  SR_SHA=$(sed -n '/^shared_rules:/,/^[a-z]/p' "$CONFIG_FILE" | sed -n 's/^[[:space:]]*pinned_sha:[[:space:]]*//p' | head -1 | tr -d '"'"'"' ')
  if [ -n "$SR_URL" ]; then
    SR_REMOTE=$(git ls-remote "$SR_URL" HEAD 2>/dev/null | awk '{print $1}')
    if [ -n "$SR_REMOTE" ] && [ -n "$SR_SHA" ] && [ "$SR_REMOTE" != "$SR_SHA" ]; then
      echo
      echo "!! shared rules (lane rules) are pinned at $SR_SHA but $SR_URL is now at $SR_REMOTE — run: lane rules pull --latest (after reviewing what changed)"
    elif [ -z "$SR_REMOTE" ]; then
      echo
      echo "!! shared rules (lane rules) — could not reach $SR_URL to check for drift"
    fi
  fi
fi

# Is it in force where it matters?
report=$(python3 - "$AD" "$VERBOSE" <<'PY'
import json, os, sys
ad, verbose = sys.argv[1], sys.argv[2] == "1"
# The root config refers to the guard through $CLAUDE_PROJECT_DIR while the
# generated per-lane ones use an absolute path, so match on the suffix.
guard = "scripts/hooks/guard.py"
problems, seen = [], []
def is_guard(cmd):
    """A hook command that runs the guard: by its path (a clone), or `lane hook <event>` for any event the guard handles."""
    w = cmd.split()
    return guard in cmd or (w[:2] == ["lane", "hook"] and len(w) > 2 and w[2] != "session-start")

def covers_search(hooks):
    """Does the PreToolUse matcher that points at the guard include Glob and Grep? (No matcher at all means every tool.)"""
    for m in hooks.get("PreToolUse") or []:
        if not any(is_guard(h.get("command") or "") for h in m.get("hooks", [])):
            continue
        pat = m.get("matcher")
        if not pat or {"Glob", "Grep"} <= set(pat.split("|")):
            return True
    return False

def check(path, label):
    seen.append(label)
    if not os.path.exists(path):
        problems.append(f"{label}: no .claude/settings.local.json — run `lane resume` to rewrite it")
        return
    try:
        d = json.load(open(path))
    except Exception as e:
        problems.append(f"{label}: settings.local.json is not valid JSON ({e.__class__.__name__})")
        return
    hooks = d.get("hooks") or {}
    wired = any(is_guard(h.get("command") or "")
                for arr in hooks.values() for m in arr for h in m.get("hooks", []))
    if not wired:
        problems.append(f"{label}: hooks do not point at guard.py — this session is UNGUARDED")
    elif not covers_search(hooks):
        problems.append(f"{label}: the PreToolUse matcher predates Glob/Grep, so searches skip the guard — run `lane resume` to rewrite it")

lanes = f"{ad}/lanes"
n_lanes = n_trees = 0
if os.path.isdir(lanes):
    for w in sorted(os.listdir(lanes)):
        d = f"{lanes}/{w}"
        if not os.path.isdir(d):
            continue
        n_lanes += 1
        check(f"{d}/.claude/settings.local.json", f"lanes/{w}")
        for r in sorted(os.listdir(d)):
            rp = f"{d}/{r}"
            if os.path.exists(f"{rp}/.git"):
                n_trees += 1
                check(f"{rp}/.claude/settings.local.json", f"lanes/{w}/{r}")

root = f"{ad}/.claude/settings.json"
if os.path.exists(root):
    seen.append("the control plane root")
    try:
        d = json.load(open(root))
        hooks = d.get("hooks") or {}
        if not any(is_guard(h.get("command") or "")
                   for arr in hooks.values() for m in arr for h in m.get("hooks", [])):
            problems.append("the control plane root: hooks do not point at guard.py")
        elif not covers_search(hooks):
            problems.append("the control plane root: the PreToolUse matcher predates Glob/Grep, so searches skip the guard — update .claude/settings.json")
    except Exception:
        problems.append("the control plane root: .claude/settings.json is not valid JSON")

bad = {p.split(":")[0] for p in problems}
ok = len(seen) - len(bad)
if n_lanes:
    print(f"@wired {ok}/{len(seen)} places point at guard.py: {n_lanes} lane(s), {n_trees} worktree(s), the root")
else:
    print(f"@wired no lanes yet — nothing to wire but the root ({ok}/{len(seen)} ok)")
if verbose:
    for s in seen:
        print("@ok   " + s) if s not in bad else None
print("\n".join(problems))
PY
)
if [ "$QUIET" = 1 ]; then
  echo "guard: $good/$n probes answered as they should, $(printf '%s\n' "$report" | sed -n 's/^@wired //p')  —  lane doctor for the evidence"
else
  printf '%s\n' "$report" | sed -n 's/^@wired //p'
fi
[ "$VERBOSE" = 1 ] && printf '%s\n' "$report" | sed -n 's/^@ok   /  ok     /p'
bad=$(printf '%s\n' "$report" | grep -v '^@' | sed '/^$/d')
if [ -n "$bad" ]; then
  echo "!! the guard is healthy but NOT in force everywhere:"
  printf '%s\n' "$bad" | sed 's/^/     /'
  echo "   fix with: lane resume <id>   (rewrites the guard for that lane)"
  exit 1
fi

if [ "${rules_broken:-0}" = 1 ]; then
  echo "   registry/rules.yaml has rules that could not be loaded (above); the guard is running without them."
  exit 1
fi

# Lanes nobody has touched in a while. Not a health failure — the guard is fine — so this never
# changes the exit code. It is the other half of the same question `lane audit` asks of the
# mirrors' branches, asked of the lanes themselves: what is still sitting here, and what clears it.
# Detection is automatic; acting on it is always a command someone types.
STALE_DAYS=$(sed -n 's/^[[:space:]]*stale_days:[[:space:]]*//p' "$CONFIG_FILE" 2>/dev/null | head -1 | tr -d '"'"'"' ')
case "${STALE_DAYS:-}" in ''|*[!0-9]*) STALE_DAYS=21 ;; esac
if [ "$QUIET" = 0 ] && [ "$STALE_DAYS" != 0 ]; then
python3 - "$AD" "$STALE_DAYS" "$VERBOSE" "$LANES_DIR" <<'PY'
import datetime, os, re, subprocess, sys
ad, days, verbose = sys.argv[1], int(sys.argv[2]), sys.argv[3] == "1"
today = datetime.date.today()

def git(d, *a):
    try:
        return subprocess.run(["git", "-C", d, *a], capture_output=True, text=True).stdout.strip()
    except Exception:
        return ""

def head(text, key):
    m = re.search(r"^%s: *(.*)$" % key, text, re.M)
    return m.group(1).strip() if m else ""

rows = []
lanes_dir = sys.argv[4]
for f in sorted(os.listdir(lanes_dir) if os.path.isdir(lanes_dir) else []):
    if not f.endswith(".md"):
        continue
    lid = f[:-3]
    front = open(f"{lanes_dir}/{f}").read().split("\n---\n", 1)[0]
    try:
        age = (today - datetime.date.fromisoformat(head(front, "updated"))).days
    except ValueError:
        continue                      # no usable `updated:` — say nothing rather than guess
    if age < days:
        continue
    repos = [(m.group(1), m.group(2), m.group(3) or "")
             for m in re.finditer(r"^  - repo: (\S+)\n    branch: (\S+)(?:\n    base: (\S+))?", front, re.M)]
    trees = [(r, b, base) for r, b, base in repos if os.path.isdir(f"{ad}/lanes/{lid}/{r}")]
    if not trees:
        continue                      # no worktree: nothing is sitting on disk, nothing to clear
    dirty = unpushed = own = 0
    contained = tracked = True
    for repo, branch, base in trees:
        d = f"{ad}/lanes/{lid}/{repo}"
        dirty += len(git(d, "status", "--porcelain").splitlines())
        base_ref = base or "main"
        for cand in (f"origin/{base_ref}", base_ref):
            if git(d, "rev-parse", "-q", "--verify", cand + "^{commit}"):
                base_ref = cand
                break
        ahead_base = git(d, "rev-list", "--count", f"{base_ref}..HEAD") or "0"
        if ahead_base != "0":
            contained = False
        # Work happened here if the branch is ahead of its base, or was pushed at some point.
        if ahead_base != "0" or git(d, "rev-parse", "-q", "--verify", f"refs/remotes/origin/{branch}"):
            own += 1
        # The shared definition (scripts/gitstate.sh lane_unpushed): commits on HEAD that no origin/* branch
        # has. Not @{u}: a lane branch is cut from origin/<base>, so its upstream is the base branch.
        if not git(d, "remote", "get-url", "origin"):
            tracked = False           # no origin at all: `lane done` will refuse it, so never suggest it
        else:
            ahead_up = git(d, "rev-list", "--count", "HEAD", "--not", "--remotes=origin") or "0"
            if ahead_up != "0":
                unpushed += int(ahead_up)
                tracked = False
            # (HEAD already on some origin/* branch: nothing is unpushed, whatever the upstream says)
    clean = dirty == 0 and unpushed == 0
    if contained and clean and tracked and own:
        bucket, why, cmd = "finished", "merged into its base and fully pushed", f"lane done {lid}"
    elif contained and clean and tracked:
        bucket, why, cmd = "empty", "nothing was ever done on it", f"lane done {lid} --delete-branches"
    else:
        what = []
        if not contained: what.append("not merged")
        if dirty: what.append(f"{dirty} uncommitted file(s)")
        if unpushed: what.append(f"{unpushed} unpushed commit(s)")
        if not tracked and "not merged" not in what: what.append("never pushed")
        bucket, why = "work", ", ".join(what)
        cmd = f'lane park {lid} "<where it stands, next step>"'
    size = ""
    try:
        du = subprocess.run(["du", "-sh", f"{ad}/lanes/{lid}"], capture_output=True, text=True, timeout=3)
        size = du.stdout.split("\t")[0].strip()
    except Exception:
        pass
    rows.append((lid, age, bucket, why, cmd, size))

if rows:
    print()
    print(f"{len(rows)} lane(s) untouched for {days}+ days (nothing has been changed — run the command to clear one):")
    for lid, age, bucket, why, cmd, size in rows:
        print("  %-22s %4s  %6s  %s" % (lid, "%dd" % age, size or "-", why))
        print("  %-22s %4s  %6s  run: %s" % ("", "", "", cmd))
    print("  the threshold is registry/config.yml `lanes: stale_days:` (0 turns this off)")
elif verbose:
    print()
    print(f"no lane has been untouched for {days}+ days (registry/config.yml `lanes: stale_days:`)")
PY
fi

# Repos whose real GitHub branch protection has never been checked, or was checked too long
# ago. Purely informational, like the stale-lane report above: never blocks the exit code,
# never runs `lane sync` itself, never touches anything. registry/repos.yaml is per-machine
# and not guaranteed to exist yet, so a missing file is silently nothing to report, not a failure.
SYNC_DAYS=$(sed -n 's/^[[:space:]]*sync_days:[[:space:]]*//p' "$CONFIG_FILE" 2>/dev/null | head -1 | tr -d '"'"'"' ')
case "${SYNC_DAYS:-}" in ''|*[!0-9]*) SYNC_DAYS=7 ;; esac
if [ "$QUIET" = 0 ] && [ "$SYNC_DAYS" != 0 ] && [ -f "$REGISTRY/repos.yaml" ]; then
python3 - "$AD" "$SYNC_DAYS" "$REGISTRY" <<'PY'
import datetime, os, re, sys
ad, days = sys.argv[1], int(sys.argv[2])
today = datetime.date.today()
text = open(f"{sys.argv[3]}/repos.yaml").read()
rows = []
for m in re.finditer(r"(?:^|\n)  ([\w.-]+):\n((?:    .*\n)*)", text):
    repo, block = m.group(1), m.group(2)
    om = re.search(r"^    origin:\s*(\S+)", block, re.M)
    origin = om.group(1) if om else ""
    if "github.com" not in origin:
        continue                      # not on GitHub — nothing for lane sync to check there
    sm = re.search(r"^    protection_synced:\s*(\S+)", block, re.M)
    if not sm:
        rows.append((repo, "never checked"))
        continue
    try:
        age = (today - datetime.date.fromisoformat(sm.group(1))).days
    except ValueError:
        rows.append((repo, "never checked"))
        continue
    if age >= days:
        rows.append((repo, f"{age} days stale"))
if rows:
    print()
    print(f"{len(rows)} repo(s) with branch protection not checked recently:")
    for repo, why in rows:
        print(f"  {repo}: branch protection not checked ({why}) — run: lane sync {repo}")
    print("  the threshold is registry/config.yml `protection: sync_days:` (0 turns this off)")
PY
fi

# Repos with candidate secret/credential filenames (scripts/repo-secrets scan) that nobody has
# reviewed yet -- neither denied with `lane secrets <repo> add` nor dismissed with
# `lane secrets <repo> ignore`. Pure local filesystem scan -- unlike the GitHub protection check
# above, this needs no staleness/cache, it is cheap enough to just re-run every time. Advisory
# only, like everything else here: never blocks, never denies or ignores anything itself.
if [ "$QUIET" = 0 ] && [ -f "$REGISTRY/repos.yaml" ]; then
python3 - "$AD" "$PRODUCT" "$REGISTRY" "$REPOS" <<'PY'
import os, re, subprocess, sys
ad, product, registry, repos_dir = sys.argv[1:5]
text = open(f"{registry}/repos.yaml").read()
rs = f"{product}/scripts/repo-secrets"
rows = []
for m in re.finditer(r"(?:^|\n)  ([\w.-]+):\n", text):
    repo = m.group(1)
    if not os.path.exists(f"{repos_dir}/{repo}/.git"):
        continue                      # no local mirror yet -- nothing to scan
    scanned = [p for p in subprocess.run([rs, repo, "scan"], capture_output=True, text=True).stdout.splitlines() if p]
    if not scanned:
        continue
    declared = {p for p in subprocess.run([rs, repo, "list"], capture_output=True, text=True).stdout.splitlines() if p}
    undeclared = [p for p in scanned if p not in declared]
    if undeclared:
        rows.append((repo, undeclared))
if rows:
    print()
    print(f"{len(rows)} repo(s) with unreviewed candidate secret/credential file(s):")
    for repo, paths in rows:
        shown = ", ".join(paths[:4]) + ("..." if len(paths) > 4 else "")
        print(f"  {repo}: {len(paths)} candidate(s) ({shown}) — most of these are typically ordinary source,")
        print(f"    not secrets. Review them, then either:")
        print(f"    deny a real secret (unreadable to every future session): lane secrets {repo} add {' '.join(paths)}")
        print(f"    dismiss a false positive (no deny rule written):         lane secrets {repo} ignore {' '.join(paths)}")
PY
fi

# Is the `lane` on PATH the stable, multi-plane-aware dispatcher, and does this checkout show up
# correctly in its registry? `~/.local/bin/lane` used to be a symlink at ONE specific checkout
# (only one plane usable machine-wide at a time — see CONTRIBUTING.md's incident writeup); it is
# now a generic router over ~/.local/share/lane/planes.json, installed by `lane install` and never
# repointed again. Three advisory-only checks, in order:
#   (a) is `lane` on PATH actually that stable dispatcher, not a stale direct-symlink from before
#       this fix (or missing entirely)
#   (b) is THIS checkout registered in planes.json at all
#   (c) if it is registered, does resolving from inside it actually pick it — this should be
#       impossible if the resolver is correct, so a mismatch here is a canary, not an expected case
if [ "$QUIET" = 0 ] && [ "$LANE_MODE" != workspace ]; then
  found=$(command -v lane 2>/dev/null || true)
  PLANES_PY="$HOME/.local/share/lane/planes.py"
  if [ -z "$found" ]; then
    echo
    echo "no \`lane\` found on PATH — run: lane install"
  elif ! grep -q "stable, multi-plane-aware dispatcher" "$found" 2>/dev/null; then
    echo
    echo "the installed \`lane\` command ($found) is not the stable multi-plane dispatcher yet — run: lane install"
  elif [ ! -f "$PLANES_PY" ]; then
    echo
    echo "repolane's plane registry helper is missing (~/.local/share/lane/planes.py) — run: lane install"
  else
    status=$(python3 "$PLANES_PY" doctor "$AD" "$AD" 2>/dev/null)
    case "$status" in
      NOT_REGISTERED)
        echo
        echo "this checkout ($AD) is not registered as a plane — run: lane install" ;;
      MISMATCH:*)
        reg="${status#MISMATCH:}"; reg="${reg%%:*}"
        picked="${status##*:}"
        echo
        echo "this checkout is registered as '$reg', but resolving lane from inside it currently"
        echo "  picks '$picked' instead — this should never happen; check ~/.local/share/lane/planes.json" ;;
    esac
  fi
fi

# The control plane's own push remote (docs/concepts.md — "the clone is the control plane"):
# still pointed at the public template it was cloned from? `lane init` disables the push side by
# default now, but this is a safety net for anyone who set up before that fix existed, or ran
# `lane init --check` (which never gets this far). Advisory only, never touches the remote itself.
if [ "$QUIET" = 0 ] && git -C "$AD" remote get-url origin >/dev/null 2>&1; then
  ORIGIN_FETCH=$(git -C "$AD" remote get-url origin 2>/dev/null || echo "")
  ORIGIN_PUSH=$(git -C "$AD" remote get-url --push origin 2>/dev/null || echo "")
  case "$ORIGIN_FETCH" in
    https://github.com/aj-oss-tools/repolane|https://github.com/aj-oss-tools/repolane.git| \
    git@github.com:aj-oss-tools/repolane|git@github.com:aj-oss-tools/repolane.git)
      if [ "$ORIGIN_PUSH" = "$ORIGIN_FETCH" ]; then
        echo
        echo "!! origin's push URL still points at the public template ($ORIGIN_FETCH) — a plain"
        echo "   \`git push\` from here would publish registry/config.yml and old-checkouts.json to it."
        echo "   run: git remote set-url --push origin DISABLED-set-a-private-remote-first"
        echo "   (or point origin at your own private repo — see docs/concepts.md)"
      fi
      ;;
  esac
fi

# Is `gh` around and authenticated? Informational only — it affects `lane sync`, `lane gh`, and
# anything else that shells out to it, but nothing here runs it or fixes it.
if [ "$QUIET" = 0 ]; then
  if ! command -v gh >/dev/null 2>&1; then
    echo
    echo "gh is not installed — some commands (lane sync, lane gh) will not work until it is"
  elif ! gh auth status >/dev/null 2>&1; then
    echo
    echo "gh is not authenticated — some commands (lane sync, lane gh) will not work until: gh auth login"
  fi
fi

# Worktree-vs-spec-file drift: does what an active lane's own frontmatter says it contains
# (repo:/branch: pairs) match what is actually checked out under lanes/<id>/ on disk? Reuses the
# same frontmatter parsing as the stale-lane report above. Advisory only — names the lane and the
# specific mismatch, never touches anything.
if [ "$QUIET" = 0 ]; then
python3 - "$AD" "$LANES_DIR" <<'PY'
import os, re, subprocess, sys
ad = sys.argv[1]
lanes_dir = sys.argv[2]
def git(d, *a):
    try:
        return subprocess.run(["git", "-C", d, *a], capture_output=True, text=True).stdout.strip()
    except Exception:
        return ""
rows = []
for f in sorted(os.listdir(lanes_dir) if os.path.isdir(lanes_dir) else []):
    if not f.endswith(".md"):
        continue
    lid = f[:-3]
    front = open(f"{lanes_dir}/{f}").read().split("\n---\n", 1)[0]
    spec = {m.group(1): m.group(2)
            for m in re.finditer(r"^  - repo: (\S+)\n    branch: (\S+)", front, re.M)}
    if not spec:
        continue
    lane_dir = f"{ad}/lanes/{lid}"
    on_disk = set(os.listdir(lane_dir)) if os.path.isdir(lane_dir) else set()
    on_disk = {r for r in on_disk if os.path.isdir(f"{lane_dir}/{r}") and os.path.exists(f"{lane_dir}/{r}/.git")}
    problems = []
    for repo, branch in spec.items():
        if repo not in on_disk:
            problems.append(f"{repo}: in spec (branch {branch}) but missing on disk")
            continue
        actual = git(f"{lane_dir}/{repo}", "branch", "--show-current")
        if actual and actual != branch:
            problems.append(f"{repo}: spec says {branch}, worktree is on {actual}")
    for repo in on_disk - set(spec):
        problems.append(f"{repo}: checked out on disk but not listed in the spec")
    if problems:
        rows.append((lid, problems))
if rows:
    print()
    print(f"{len(rows)} lane(s) where the spec and the worktree disagree:")
    for lid, problems in rows:
        for p in problems:
            print(f"  {lid}: {p}")
PY
fi

# scripts/local/<name> (docs/extending.md) shadowed by a built-in of the same name — it would
# never run, `lane <name>` always resolves to the built-in first. Advisory only, cheap, local.
if [ "$QUIET" = 0 ] && [ -d "$DATA/scripts/local" ]; then
  for f in "$DATA/scripts/local"/*; do
    [ -x "$f" ] && [ ! -d "$f" ] || continue
    b=$(basename "$f")
    case "$b" in
      init|add|start|resume|park|done|status|brief|board|with|run|gh|ref|note|merge|plan|find|\
      sessions|audit|workspace|env|keys|secrets|sync|doctor|upgrade|import|nested|menu|help|\
      install|version|rules)
        echo
        echo "scripts/local/$b is shadowed by the built-in $b command and will never run."
        ;;
    esac
  done
fi

if [ "$VERBOSE" = 1 ]; then
  echo
  echo "the full suite (it builds its own throwaway control plane; your lanes are not touched):"
  # the suite's own exit status, not sed's: a failing suite must fail `lane doctor -v`
  suite_rc=0; bash "$(dirname "$G")/test-guard.sh" > "${TMPDIR:-/tmp}/guard-suite.$$.txt" 2>&1 || suite_rc=$?
  sed 's/^/  /' "${TMPDIR:-/tmp}/guard-suite.$$.txt"; rm -f "${TMPDIR:-/tmp}/guard-suite.$$.txt"
  [ "$suite_rc" = 0 ] || exit "$suite_rc"
elif [ "$QUIET" = 0 ]; then
  echo "hundreds more cases behind this (the whole suite):  lane doctor -v"
fi
# a git-clone install at 0.10 or later: what moves it to the package and a workspace (never a failure)
[ "$QUIET" = 0 ] && lane_migrate_steps
if [ "$WS_RC" != 0 ] && [ "$QUIET" = 0 ]; then
  echo
  echo "!! this workspace has problems that are not fixed (listed at the top) — run: lane doctor --fix"
fi
exit "$WS_RC"
