#!/usr/bin/env python3
# /// script
# requires-python = ">=3.9"
# dependencies = ["pyyaml>=6"]
# ///
"""okf-verify — L4: is what this bundle SAYS still true?

L1 answers "is this valid OKF?" and L2 "is this valid OUR OKF?". Both are
questions about FORM. A concept citing a commit that no longer exists is
perfectly conformant and quietly wrong — and that is not hypothetical: a history
rewrite on 2026-07-30 orphaned every SHA one lesson cited, while the fix it
described was still running in production.

Nothing else in the OKF ecosystem checks this. The upstream validator says so
itself: a target outside the bundle is "legitimate and unverifiable from here".

THE LOAD-BEARING DISTINCTION
----------------------------
    CONFIRMED   the claim was checked and holds
    REFUTED     the claim was checked and does NOT hold
    UNRESOLVED  the claim could NOT be checked

UNRESOLVED is not a soft REFUTED. Collapsing the two would make this tool
actively harmful: it would report a corpus as false when the truth is that
nobody looked. Same rule as negative-claims-state-scope.md — a negative is only
as strong as the scope actually searched, and the scope is printed with it.

Which is why SHAs and paths are treated ASYMMETRICALLY:

  * A missing FILE PATH can be REFUTED — but only when its parent directory
    exists. Then we know we searched the right place and the file is genuinely
    absent. If the parent is missing too, this is a different machine or layout:
    UNRESOLVED.

  * A missing SHA is NEVER refuted. It depends entirely on which repositories
    were searched, and it does not survive a history rewrite. Absence here is
    ignorance, not falsehood. When a commit whose message contains a quoted
    SUBJECT is found, the detail names three explanations: a rewritten history,
    a repository that was not searched, or an unrelated match (okf-knowledge-gate#6).

Usage:
    okf-verify <bundle> [--repo DIR]... [--json] [--strict]
    okf-verify <bundle> --check-config    only validate the okf_check block of okf-base.yaml
    Only the repositories given with --repo are searched. Since 0.9.50 a repository named in
    okf-base.yaml (okf_check.verify.repos) is not searched; each is reported with the --repo to pass.
    --strict  also fail on UNRESOLVED (for a corpus that must stay checkable)
"""
from __future__ import annotations

import argparse
import bisect
import json
import os
import re
import subprocess
import sys
import threading
from pathlib import Path

CONFIRMED, REFUTED, UNRESOLVED = "CONFIRMED", "REFUTED", "UNRESOLVED"

# A bare 7-40 hex run matches far too much ordinary prose ("deadbeef", "acceded",
# a CSS colour, a checksum). Require a git-ish context: backticked, or adjacent to
# a commit word. Precision over recall — a false claim of verification is worse
# than a missed one.
SHA_CTX = re.compile(
    r"(?:`([0-9a-f]{7,40})`"
    r"|(?:commit|sha|rev|fix(?:ed)?\s+in)\s+[`']?([0-9a-f]{7,40})[`']?"
    # A commit URL is the commonest citation form in the wild and matched nothing:
    # the context word had to be followed by whitespace, and a URL uses a slash.
    # Covers github/gitlab `/commit/<sha>` and `/commits/<sha>`. (D-8)
    r"|/commits?/([0-9a-f]{7,40})\b)",
    re.I,
)
# The closing delimiter is a BACKREFERENCE, not another character class. The
# unpaired form accepted `` `/x/y.md' `` — a backtick opening and an apostrophe
# closing — so an apostrophe landing after an inline-code span turned ordinary
# prose into a cited path. That path is then absent, and the run manufactures a
# REFUTED: the one verdict this tool exists to never invent. (D-12)
PATH_RE = re.compile(r"([`\"'])((?:~|/)[A-Za-z0-9._/ -]*[A-Za-z0-9._-]\.[A-Za-z0-9]{1,6})\1")
# `path:line[-line] @sha` and `path:line[-line] at sha` -- one claim: this file, at this commit. The path is repo-relative
# (an absolute path is a PATH_RE claim); the lookbehind keeps a match from starting mid-token, so a Windows path (`C:\x\y.py:3`)
# or a URL is not cut into a citation of its last piece. A path cut at a SPACE cannot be told from prose here: check_citation
# answers UNRESOLVED when the cut is the end of a longer file name.
CITE_RE = re.compile(r"(?<![\w./\\-])([A-Za-z0-9_][A-Za-z0-9_./-]*\.[A-Za-z0-9]{1,8}):(\d+)(?:-(\d+))?`?(?:[ \t]+|[ \t]*\r?\n[ \t]*)(?:@|at(?:[ \t]+|[ \t]*\r?\n[ \t]*))`?([0-9a-f]{7,40})\b`?(?:[ \t]+[\"“]([^\"”\n]{1,200})[\"”])?", re.I)
# The gap between `path:line` and `@sha` may hold ONE line break (a wrapped line) but never a blank line: across a paragraph break the two
# are separate statements and one was read as the other's citation. (found by a review of the citation parser)
# The same claim with a path that holds a space, QUOTED: the quotes say where the path starts, so nothing is cut and nothing is guessed.
QCITE_RE = re.compile(r"(?<![\w./\\-])([`\"'])(\w[\w./-]*(?: [\w./-]+)+\.[A-Za-z0-9]{1,8})\1:(\d+)(?:-(\d+))?`?(?:[ \t]+|[ \t]*\r?\n[ \t]*)(?:@|at(?:[ \t]+|[ \t]*\r?\n[ \t]*))`?([0-9a-f]{7,40})\b`?(?:[ \t]+[\"“]([^\"”\n]{1,200})[\"”])?", re.I)
# A line citation into a living document, with no commit (okf-knowledge-gate#14): `decision-12.md:94`, `spec.md:40-42`. The
# lookbehind keeps a URL, a Windows path or a glued token from being cut into a citation of its tail; the lookahead lets a
# sentence's full stop follow (`spec.md:42.`) but not a longer token (`d.md:3x`, `d.md:3:4`).
LINE_RE = re.compile(r"(?<![\w./\\:-])((?:\.{1,2}/)*[A-Za-z0-9_][A-Za-z0-9_./-]*\.md):(\d+)(?:-(\d+))?(?![\w:/-]|\.\w)(?:[ \t]+[\"“]([^\"”\n]{1,200})[\"”])?")
# The short form `decision-12:94` names a note by its file name. Prose holds the same shape (`Step:2`, `localhost:8080`), so
# it is a claim only when a note of that name exists in the bundle; a time (`10:30`) has no letter and never matches.
NAME_RE = re.compile(r"(?<![\w./\\:-])([A-Za-z0-9_-]{1,120}):(\d+)(?:-(\d+))?(?![\w:/-]|\.\w)(?:[ \t]+[\"“]([^\"”\n]{1,200})[\"”])?")
# The same, with a name that holds a space, QUOTED (`my w.md`:10): the quotes say where the name starts, so nothing is cut or guessed.
# A name may hold any letter (\w), as the words before an unquoted citation can.
QLINE_RE = re.compile(r"(?<![\w./\\-])([`\"'])(\w[\w./-]*(?: [\w./-]+)+\.md)\1:(\d+)(?:-(\d+))?(?![\w:/-]|\.\w)(?:[ \t]+[\"“]([^\"”\n]{1,200})[\"”])?")
# The short form, QUOTED (`"Handbook for agents":10`): a claim when a note of that name exists, as the unquoted short form is, and never cut at a space.
QNAME_RE = re.compile(r"(?<![\w./\\:-])([`\"'])(\w(?:[\w -]{0,118}\w)?)\1:(\d+)(?:-(\d+))?(?![\w:/-]|\.\w)(?:[ \t]+[\"“]([^\"”\n]{1,200})[\"”])?")
# What a writer may have meant as a citation, counted for a note with no checkable claim so the writer learns which forms
# are checkable (okf-knowledge-gate#14, part 3). A hint, never a verdict.
LOOKS_TOKEN = re.compile(r"[^`'\"()\[\]<>:]{1,120}:\d+(?:-\d+)?")   # one whitespace-separated token; see looks_like()
# A content anchor (slice b): the quoted text after a citation must be on the cited lines. Elsewhere in the same file the
# citation is MOVED (checked: the text is there, the line number is wrong, and the new one is known); nowhere, REFUTED. A
# citation pinned to a commit is history: its anchor is checked at that commit, on its lines, and it is never MOVED.
MOVED = "MOVED"
QUOTED = re.compile(r"[\"“]([^\"”\n]{12,120})[\"”]")
RESERVED = {"index.md", "log.md"}
FENCE = re.compile(r"^(\s*)(`{3,}|~{3,})")
INDENTED = re.compile(r"^(?: {4,}|\t)")
# Transient by definition. Absence in one of these proves nothing about whether
# the claim was ever true, so they can never be REFUTED — only UNRESOLVED.
# /private/var/... is what realpath() returns for /var/... on macOS; omitting the
# canonical form let the same directory be judged two different ways. (D-3)
EPHEMERAL = ("/tmp/", "/private/tmp/", "/var/folders/", "/private/var/folders/",
             "/var/tmp/", "/private/var/tmp/", "/dev/shm/")


def strip_code_fences(body: str, seams: set | None = None) -> tuple[str, bool]:
    """Drop code blocks before extracting claims.

    A path inside a code block is a LITERAL — `const LOG = '/tmp/net-spy.log'`
    tells you where to write output; it does not assert the file exists. Live-firing
    produced exactly that false REFUTED, and a tool that cries wolf gets ignored.

    CommonMark rules, because the naive version was demonstrably wrong (D-4/D-5):
      * a fence is closed only by the SAME character, at least as long as the
        opener. Toggling on any fence meant a ``~~~`` block DOCUMENTING a ``` fence
        untoggled at the inner fence and leaked its literals — the precise
        cry-wolf failure this function exists to prevent.
      * 4-space / tab indented blocks are code too, and were not handled at all.

    `seams` receives the index of each line of the result that follows dropped code: text on the two sides of a code block
    is not one paragraph.
    """
    out, fence_char, fence_len = [], "", 0
    for line in body.split("\n"):
        m = FENCE.match(line)
        if fence_char:
            # only a matching, at-least-as-long fence of the same char closes it
            if m and m.group(2)[0] == fence_char and len(m.group(2)) >= fence_len:
                fence_char, fence_len = "", 0
            continue
        if m:
            fence_char, fence_len = m.group(2)[0], len(m.group(2))
            if seams is not None:
                seams.add(len(out))
            continue
        if INDENTED.match(line):
            if seams is not None:
                seams.add(len(out))
            continue
        out.append(line)
    # An unclosed fence runs to end-of-document under CommonMark, so the parse is
    # CORRECT — but every claim after it is silently swallowed. Correct is not the
    # same as safe: return the fact so the caller can say so. (D-6)
    return "\n".join(out), bool(fence_char)


def frontmatter_end(text: str) -> int:
    if not text.startswith("---\n"):
        return 0
    e = text.find("\n---\n", 3)
    return e + 5 if e != -1 else 0


# Returned by git() when the command could not be RUN to a conclusion, as
# opposed to running and finding nothing. Those were the same value (1, "")
# until now: TimeoutExpired is a subclass of SubprocessError, so a git call that
# blew its deadline on a loaded machine looked exactly like a clean "no match",
# and the caller went on to state "not found in the searched repos" — a claim
# about a search that never happened. Seen twice in review as an intermittent
# 4-failure run and never reproducible on demand, because it needed real load.
#
# In production it silently downgrades CONFIRMED to UNRESOLVED: "checked and
# true" becoming "nobody checked", inside the one layer built to keep those
# apart. See lessons/shell-or-swallows-errors.md — one value, two meanings. (Z-4)
# -1000, not -1. subprocess returns the NEGATED signal number when a child is
# killed, so a git killed by SIGHUP returns exactly -1 — measured, not assumed —
# and would have been indistinguishable from this sentinel. The outcome happened
# to be right (both mean "could not run to a conclusion"), but a sentinel that
# collides with real data is a trap waiting for the next reader. Signal deaths
# are -1..-64, so -1000 cannot collide.
GIT_UNAVAILABLE = -1000


_GIT_ANSWERS: dict[tuple, tuple[int, str]] = {}


def git(repo: Path, *args: str) -> tuple[int, str]:
    """Run git. GIT_UNAVAILABLE means it could not be RUN — not that it found nothing.

    Every caller only reads (rev-parse, cat-file, ls-tree, log, remote get-url), and a run does not change the repositories
    it looks at, so one question is asked once: a note with 100 citations of one commit spawned about 600 git processes.
    A git that could not run is never kept: the next citation asks again.
    """
    key = (str(repo), args)
    if key in _GIT_ANSWERS:
        return _GIT_ANSWERS[key]
    try:
        p = subprocess.run(["git", "-C", str(repo), *args],
                           capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15)
    except subprocess.TimeoutExpired:
        return GIT_UNAVAILABLE, "git timed out"
    except (OSError, subprocess.SubprocessError):
        return GIT_UNAVAILABLE, "git could not be executed"
    if p.returncode < 0:
        return GIT_UNAVAILABLE, f"git killed by signal {-p.returncode}"
    _GIT_ANSWERS[key] = (p.returncode, p.stdout.strip())
    return _GIT_ANSWERS[key]


def repo_usable(repo: Path) -> tuple[bool, str]:
    """Can git run here, and is this actually a repository? Asked ONCE per repo.

    Exit 128 is overloaded: `cat-file -e` returns it for an ABSENT object, and
    git returns it for "not a repository" and for assorted real errors. The code
    alone cannot separate them, so an earlier attempt to treat "not 0 or 1" as a
    failure turned every genuinely-absent SHA into "could not query" — the same
    false claim as before, pointing the other way.

    Establishing usability up front makes a later 128 unambiguous: git works and
    the repository is valid, therefore the object is absent. Two questions, two
    checks, instead of one exit code carrying both. (Z-5)
    """
    rc, out = git(repo, "rev-parse", "--git-dir")
    if rc == GIT_UNAVAILABLE:
        return False, out
    if rc != 0:
        return False, "not a usable git repository"
    return True, ""


def forge_of(repo: Path):
    """(kind, host, path) of the repository's `origin` when it is on GitHub or GitLab, else None (okf-knowledge-gate#6).

    The host is matched exactly: github.com, gitlab.com, or a self-hosted GitLab named in OKF_GITLAB_HOSTS (comma-separated).
    A name that only contains "gitlab" (gitlab.com.evil.com, an ssh alias) is not a forge: it is not asked and gets no token.
    """
    rc, url = git(repo, "remote", "get-url", "origin")
    if rc != 0 or not url:
        return None
    m = (re.match(r"^(?:https?|ssh|git)://(?:[^@/]+@)?([^/:]+)(?::\d+)?/(.+?)(?:\.git)?/?$", url)
         or re.match(r"^(?:[^@/]+@)?([^/:]+):(.+?)(?:\.git)?/?$", url))
    if not m or not re.fullmatch(r"[A-Za-z0-9._/-]+", m.group(2)) or ".." in m.group(2):
        return None
    host, path = m.group(1).lower(), m.group(2)
    gitlabs = {"gitlab.com"} | {h.strip().lower() for h in os.environ.get("OKF_GITLAB_HOSTS", "").split(",") if h.strip()}
    if host == "github.com" and path.count("/") == 1:
        return "github", host, path
    if host in gitlabs:
        return "gitlab", host, path
    return None


_REMOTE: dict = {}
_DEAD_HOSTS: dict = {}   # a host whose lookup failed: not asked again in this run (a dead network would cost 10 s per SHA)


def remote_commit(forge: tuple, sha: str):
    """Ask the forge's API, read-only, for one commit: ("found", title, date), ("absent",) or ("failed", why).

    The clone is never fetched into. GITHUB_TOKEN or GH_TOKEN goes to github.com only, GITLAB_TOKEN to a GitLab host only, and
    a redirect is refused, so no header follows it elsewhere. A 200 counts only when its body names this commit.
    OKF_FORGE_API_BASE replaces the API host, for tests; tokens go to it only when it is this machine (127.0.0.1, localhost).
    """
    import http.client
    import urllib.error
    import urllib.parse
    import urllib.request
    key = (forge, sha)
    if key in _REMOTE:
        return _REMOTE[key]
    kind, host, path = forge
    if host in _DEAD_HOSTS:
        return ("failed", f"{_DEAD_HOSTS[host]}, earlier in this run")
    override = os.environ.get("OKF_FORGE_API_BASE")
    base = override or ("https://api.github.com" if kind == "github" else f"https://{host}")
    local = urllib.parse.urlparse(base).hostname in ("127.0.0.1", "localhost")
    send_tokens = not override or local
    headers = {"User-Agent": "okf-verify"}
    if kind == "github":
        url = f"{base}/repos/{path}/commits/{sha}?per_page=1"   # one page of files: a commit with a large diff fits the read
        headers["Accept"] = "application/vnd.github+json"
        token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
        if token and send_tokens:
            headers["Authorization"] = f"Bearer {token}"
    else:
        url = f"{base}/api/v4/projects/{urllib.parse.quote(path, safe='')}/repository/commits/{sha}"
        token = os.environ.get("GITLAB_TOKEN")
        if token and send_tokens:
            headers["PRIVATE-TOKEN"] = token

    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, hdrs, newurl):
            raise urllib.error.HTTPError(req.full_url, code, "redirect", hdrs, fp)
    handlers = [NoRedirect()] + ([urllib.request.ProxyHandler({})] if local else [])
    try:
        with urllib.request.build_opener(*handlers).open(urllib.request.Request(url, headers=headers), timeout=10) as r:
            body = json.loads(r.read(5_000_000).decode("utf-8", "replace"))
        if not isinstance(body, dict):
            out = ("failed", "the answer is not a commit")
        elif kind == "github" and str(body.get("sha", "")).lower().startswith(sha):
            c = body.get("commit") if isinstance(body.get("commit"), dict) else {}
            date = ((c.get("committer") if isinstance(c.get("committer"), dict) else {}).get("date") or "")
            out = ("found", str(c.get("message") or "").split("\n")[0], str(date)[:10])
        elif kind == "gitlab" and str(body.get("id", "")).lower().startswith(sha):
            out = ("found", str(body.get("title") or ""), str(body.get("committed_date") or "")[:10])
        else:
            out = ("failed", "the answer does not name this commit")
    except urllib.error.HTTPError as e:
        if e.code in (404, 422):
            out = ("absent",)
        elif 300 <= e.code < 400:
            out = ("failed", f"redirect {e.code}, not followed")
        else:
            out = ("failed", f"HTTP {e.code}")
    except Exception as e:   # a dead network, a bad TLS handshake, a broken answer: nobody could look, never a crash
        out = ("failed", type(e).__name__)
        if not isinstance(e, (ValueError, http.client.IncompleteRead)):
            _DEAD_HOSTS[host] = type(e).__name__
    if out[0] == "failed" and out[1].startswith("HTTP 5"):
        _DEAD_HOSTS[host] = out[1]
    _REMOTE[key] = out
    return out


def remote_sha(sha: str, usable: list[Path]):
    """--remote (okf-knowledge-gate#6): (CONFIRMED, detail) when a searched repository's forge has the commit, else (None, note)."""
    notes = []
    for r in usable:
        forge = forge_of(r)
        if forge is None:
            notes.append(f"{r.name} has no GitHub or GitLab origin to ask")
            continue
        where = f"{forge[1]}/{forge[2]}"
        got = remote_commit(forge, sha)
        if got[0] == "found":
            return CONFIRMED, (f"not in the local clone {r.name}, but on the remote {where}: {got[1][:60]}"
                               f"{' (' + got[2] + ')' if got[2] else ''}; the local clone {r.name} is behind (git fetch)")
        notes.append(f"not on the remote {where} either (or not visible without a token)" if got[0] == "absent"
                     else f"remote lookup on {where} failed ({got[1]})")
    return None, "; ".join(notes)


def check_sha(sha: str, repos: list[Path], subjects: list[str], remote: bool = False):
    """A SHA is CONFIRMED or UNRESOLVED. Never REFUTED — see the module docstring."""
    v, d = _check_sha(sha, repos, subjects)
    if v != CONFIRMED and remote and repos:
        usable = [r for r in repos if repo_usable(r)[0]]
        rv, note = remote_sha(sha, usable)
        if rv == CONFIRMED:
            return rv, note
        if note:
            return v, f"{d}; {note}"
    return v, d


def _check_sha(sha: str, repos: list[Path], subjects: list[str]):
    if not repos:
        return UNRESOLVED, "no repository searched (pass --repo to check SHAs)"

    unavailable: list[str] = []
    usable: list[Path] = []
    for r in repos:
        ok_, why = repo_usable(r)
        (usable if ok_ else unavailable).append(r if ok_ else f"{r.name} ({why})")

    for r in usable:
        rc, _ = git(r, "cat-file", "-e", f"{sha}^{{commit}}")
        if rc == 0:
            # The follow-up subject lookup can fail on its own, and its return
            # code used to be discarded — so its ERROR STRING was rendered as
            # the commit subject: "resolves in repo: git exited 128". The
            # verdict was right and the evidence beside it was fabricated,
            # which is the more corrosive half. The SHA is already confirmed
            # here; a missing subject is a missing subject, not a wrong one.
            src, subj = git(r, "log", "-1", "--format=%s", sha)
            if src != 0 or not subj:
                return CONFIRMED, f"resolves in {r.name} (subject unavailable)"
            return CONFIRMED, f"resolves in {r.name}: {subj[:60]}"

    # Not found. Before shrugging, look for a surviving commit SUBJECT quoted in
    # the same concept — that is the signature of a rewritten history, and it
    # tells the reader the claim is probably TRUE with a dead anchor.
    for subj in subjects:
        for r in usable:
            rc, out = git(r, "log", "--all", "--format=%h|%s", f"--grep={subj[:60]}", "-F", "-1")
            if rc != 0:
                # `log --grep` exits 0 even when nothing matches, so non-zero here
                # is a real failure. The first version of this fix `continue`d
                # without recording it, so a subject search that never ran still
                # produced "not found in the searched repos". (Z-5)
                entry = f"{r.name} (subject search failed)"
                if entry not in unavailable:
                    unavailable.append(entry)
                continue
            if out:
                # A match does not prove a rewrite (okf-knowledge-gate#6): `log --grep -F` finds the text anywhere in a commit
                # MESSAGE, so a commit in a repository nobody searched, or an unrelated commit that happens to contain a short
                # subject, looks the same. All three are named, with what was searched and what could not be.
                new_sha, found = (out.split("|", 1) + [""])[:2]
                searched = ", ".join(x.name for x in usable) + (f"; could not query {'; '.join(unavailable)}" if unavailable else "")
                return UNRESOLVED, (f"SHA absent, but a commit whose message contains the quoted subject is in {r.name} as "
                                    f"{new_sha}: the history was rewritten (the claim is then probably true with a dead "
                                    f"anchor), or the commit lives in a repository that was not searched, or the match is "
                                    f"unrelated (searched: {searched})")

    # Never claim a completed search that did not complete.
    if unavailable:
        where = ", ".join(r.name for r in usable) or "none"
        return UNRESOLVED, (f"could not query {'; '.join(unavailable)} — that lookup did not run, "
                            f"which is not the same as absent (searched: {where})")
    searched = ", ".join(r.name for r in usable)
    shallow = [r.name for r in usable if git(r, "rev-parse", "--is-shallow-repository") == (0, "true")]
    note = (f"; {', '.join(shallow)} is a shallow clone, so older commits are missing "
            f"(git fetch --unshallow, or actions/checkout with fetch-depth: 0)") if shallow else ""
    return UNRESOLVED, f"not found in the searched repos ({searched}); other repos not searched{note}"


def line_no(digits: str):
    """The value of a line number written as `digits`, or None when it has more than 9 significant digits.

    Zeros in front carry no value: `0000000003` is line 3. int() of thousands of digits raises on current Pythons and
    aborted the whole run, and no file has 10^9 lines, so a number that long is out of range.
    """
    sig = digits.lstrip("0") or "0"
    return int(sig) if len(sig) <= 9 else None


def line_span(lines: str):
    """(first, last) of `N` or `N-M`, the larger number last (`20-10` is read as up to 20), or None when a number is out of range."""
    lo, _, hi = lines.partition("-")
    first, end = line_no(lo), line_no(hi or lo)
    if first is None or end is None:
        return None
    return first, max(first, end)


_BLOB_LINES: dict[tuple, tuple] = {}


def blob_lines(repo: Path, sha: str, path: str):
    """Line count of `path` at `sha`: (count, "") or (None, why). Bytes, not text: a source file need not be UTF-8.

    A NUL in the first 8000 bytes is git's own test for a binary file; its "lines" are not a thing to check.
    Asked once per file and commit (only the count is kept, not the blob); an answer given by a git that could not run is not kept.
    """
    key = (str(repo), sha, path)
    if key not in _BLOB_LINES:
        count, why, answered = _blob_lines(repo, sha, path)
        if answered:
            _BLOB_LINES[key] = (count, why)
        return count, why
    return _BLOB_LINES[key]


def _stream_blob(repo: Path, sha: str, path: str, feed):
    """Run `git cat-file blob` and hand its output to `feed` in 64 KB pieces, so memory does not grow with the blob.

    `feed(chunk)` returns True to stop early. Returns (returncode, timed_out, stopped); a run past 15 s is killed, as `git()` is.
    """
    p = subprocess.Popen(["git", "-C", str(repo), "cat-file", "blob", f"{sha}:{path}"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
    late = []

    def kill():
        late.append(True)
        p.kill()
    timer = threading.Timer(15, kill)
    timer.start()
    stopped = False
    try:
        for chunk in iter(lambda: p.stdout.read(65536), b""):
            if feed(chunk):
                stopped = True
                p.kill()
                break
        p.wait()
    finally:
        timer.cancel()
        p.kill()   # an exception in `feed` or a Ctrl-C must not leave git running
        p.wait()
        p.stdout.close()
    return p.returncode, bool(late), stopped


def _blob_lines(repo: Path, sha: str, path: str):
    """blob_lines without the memo: (count, why, answered); answered is False when git could not run to an answer."""
    # A symlink's blob is the LINK TEXT: counting it reports "1 lines" for a link to a 20-line file. The tree entry's mode says which it is.
    rc, entry = git(repo, "ls-tree", sha, "--", path)
    if rc == GIT_UNAVAILABLE:
        return None, entry, False
    if entry.split(" ", 1)[0] == "120000":
        return None, f"{path} is a symlink, so its lines cannot be checked", True
    seen = {"bytes": 0, "newlines": 0, "last": b"", "binary": False}

    def feed(chunk):
        if seen["bytes"] < 8000 and b"\0" in chunk[:8000 - seen["bytes"]]:
            seen["binary"] = True
            return True
        seen["bytes"] += len(chunk)
        seen["newlines"] += chunk.count(b"\n")
        seen["last"] = chunk[-1:]
        return False
    try:
        rc, late, _ = _stream_blob(repo, sha, path, feed)
    except (OSError, subprocess.SubprocessError):
        return None, "git could not be executed", False
    if late:
        return None, "git timed out", False
    if seen["binary"]:
        return None, f"{path} is a binary file, so its lines cannot be checked", True
    if rc != 0:
        return None, f"{path} at {sha} is not a regular file", rc > 0   # a negative code is a signal: git did not answer
    return seen["newlines"] + (1 if seen["bytes"] and seen["last"] != b"\n" else 0), "", True


SPAN_LIMIT = int(os.environ.get("OKF_VERIFY_SPAN_LIMIT") or 16 * 1024 * 1024)   # bytes of the cited lines of a blob to hold for a quoted text


def blob_span(repo: Path, sha: str, path: str, first: int, last: int):
    """The text of lines `first`..`last` of `path` at `sha`: (text, "") or (None, why). Only those lines are kept, not the blob."""
    out, size, at = [], [0], [1]

    def feed(chunk):
        parts = chunk.split(b"\n")
        for i, part in enumerate(parts):
            if i:
                at[0] += 1
            if at[0] > last:
                return True
            if at[0] >= first:
                out.append(part + (b"\n" if i < len(parts) - 1 else b""))
                size[0] += len(part) + 1
        return size[0] > SPAN_LIMIT
    try:
        rc, late, stopped = _stream_blob(repo, sha, path, feed)
    except (OSError, subprocess.SubprocessError):
        return None, "git did not run"
    if size[0] > SPAN_LIMIT:
        return None, f"the cited lines are more than {SPAN_LIMIT} bytes"
    if late or (rc != 0 and not stopped):
        return None, "git did not answer"
    return b"".join(out).decode("utf-8", "replace"), ""


_BLANK_LINE = re.compile(r"(?s).*\n[ \t\r\f\v]*\n")   # up to the last blank line of a text: the end of the paragraph before
_TAIL = re.compile(r"\s(\S+)\Z")
_QUOTE_OPEN = "`\"'([<"


WALK_LIMIT = int(os.environ.get("OKF_VERIFY_WALK_LIMIT") or 100000)   # entries of a searched repository to look at when git cannot list it


def walk_docs(root: Path):
    """The `.md` files of a folder, as paths below it, or None past WALK_LIMIT entries (files and folders; `.git` is not entered)."""
    out, seen = [], 0
    for dp, dns, fns in os.walk(root):
        dns[:] = [d for d in dns if d != ".git"]
        seen += len(dns) + len(fns)
        if seen > WALK_LIMIT:
            return None
        out += [os.path.relpath(os.path.join(dp, f), root) for f in fns if f.endswith(".md")]
    return out


def tail_index(names):
    """The names that hold whitespace, by their text after the last whitespace: `my big w.py` is found under `w.py`.

    A name that starts with whitespace or an opening quote is left out: the words before a citation are read from the word's first
    letter, so no such name is ever spelled.
    """
    t: dict[str, list[str]] = {}
    for n in names:
        m = _TAIL.search(n)
        if m and not n[0].isspace() and n[0] not in _QUOTE_OPEN:
            t.setdefault(m.group(1), []).append(n)
    return t


def spaced_names(path: str, prefix: str, tails: dict):
    """The names the writer's own words could spell if the cut at a space was wrong: `my big w.py:3` -> `big w.py`, `my big w.py`.

    `prefix` is the text before the citation in its paragraph and `tails` (`tail_index`) the names there are: a name is spelled when
    the prefix ends with the words of its start, taken from a word's first letter, as written (a double space, a tab and a no-break
    space count) or with each line break read as one space (a soft-wrapped name: markdown shows the line break as a space).
    Any number of words may belong to it. As written first, then shortest first.
    """
    window = prefix[-4096:]
    cut = len(window) < len(prefix)
    collapsed = None
    out = []
    for n in tails.get(path, ()):
        x = n[:len(n) - len(path)]
        exact = window.endswith(x) and _word_start(window, len(window) - len(x), cut)
        if not exact:
            collapsed = re.sub(r"[ \t]*\r?\n[ \t]*", " ", window) if collapsed is None else collapsed
        if exact or (collapsed.endswith(x) and _word_start(collapsed, len(collapsed) - len(x), cut)):
            out.append((not exact, len(n), n))
    return [n for _, _, n in sorted(out)]


def _word_start(text: str, at: int, cut: bool) -> bool:
    """Is `at` the first letter of a word of `text` (an opening quote or bracket before it does not count)? `cut`: `text` starts mid-text."""
    while at > 0 and text[at - 1] in _QUOTE_OPEN:
        at -= 1
    return text[at - 1].isspace() if at > 0 else not cut


_TREES: dict[tuple[str, str], tuple[int, list[str]]] = {}


def tree_listing(repo: Path, sha: str):
    """`git ls-tree -r` of one commit, read once per run: it ran per citation and grew the spawns with the citations. Only a success is kept.

    On success the second value is the list of names. They are read NUL-separated: git writes a name with a tab, a quote or a
    non-ASCII letter in quotes and escapes otherwise, and such a name could never equal the one the writer typed.
    """
    k = (str(repo), sha)
    if k not in _TREES:
        rc, out = git(repo, "ls-tree", "-r", "--name-only", "-z", sha)
        if rc != 0:
            return rc, out
        _TREES[k] = (rc, [n for n in out.split("\0") if n])
    return _TREES[k]


_TREE_TAILS: dict[tuple[str, str], tuple[dict, dict]] = {}


def tree_tails(repo: Path, sha: str, names: list[str]):
    """(tail_index, ends) of one commit's names, once per run: `ends` maps each end of a path, from a "/" on, to the names that end so.

    Only an end that holds whitespace can be spelled by the words before a citation, so only those are kept.
    """
    k = (str(repo), sha)
    if k not in _TREE_TAILS:
        ends: dict[str, list[str]] = {}
        for n in names:
            if re.search(r"\s", n):
                for i in [-1] + [j for j, ch in enumerate(n) if ch == "/"]:
                    ends.setdefault(n[i + 1:], []).append(n)
        _TREE_TAILS[k] = (tail_index(ends), ends)
    return _TREE_TAILS[k]


def check_citation(path: str, lines: str, sha: str, repos: list[Path], subjects: list[str], prefix: str = "",
                   quoted: bool = False, named: list | None = None, anchor: str | None = None):
    """`path:lines @sha`: the sha must resolve, then the path must exist in THAT commit's tree.

    REFUTED only when the commit was found and its tree lacks the path: then we looked in the right place. A sha that
    resolves nowhere stays UNRESOLVED, as for a bare SHA claim. A line (or the end of a range) past the end of the
    file at that commit is REFUTED too: same commit, same file, so the claim is known false.

    `prefix` is the text before the path in its paragraph: the words that may spell a name (`spaced_names`); a `quoted` path is never cut.
    """
    v, d = check_sha(sha, repos, subjects)
    if v != CONFIRMED:
        return v, f"sha part: {d}"
    found, absent, cut, spaced, spaced_as = [], [], [], [], []
    for r in repos:
        rc, out = git(r, "cat-file", "-e", f"{sha}^{{commit}}")
        if rc == GIT_UNAVAILABLE:
            return UNRESOLVED, f"could not query {r.name}: {out}"
        if rc != 0:
            continue
        rc, _ = git(r, "cat-file", "-e", f"{sha}:{path}")
        exact = rc == 0
        if exact:
            found.append((r, path))
        if exact and (quoted or not prefix.strip()):
            continue
        rc, out = tree_listing(r, sha)
        if rc != 0:
            return UNRESOLVED, f"could not list {sha} in {r.name}: {out}"
        # `my w.py:3` may name the file `my w.py`, whose end `w.py` is another file: the words before the cut decide nothing alone.
        tails, ends = tree_tails(r, sha, out)
        for c in () if quoted else spaced_names(path, prefix, tails):
            spaced.extend((r, n) for n in ends[c])
            spaced_as.extend([c] * len(ends[c]))
        if exact:
            continue
        hits = [n for n in out if n.endswith("/" + path)]
        found.extend((r, n) for n in hits)
        if not hits:
            # `my dir/w.py` cited with its space reads as `dir/w.py`: the end of a longer name, not at a "/". Not a missing file.
            longer = [n for n in out if n.endswith(" " + path)]
            (cut.extend(longer) if longer and not quoted else absent.append(r.name))
    if spaced:
        names = sorted({n for _, n in found} | {n for _, n in spaced})
        if found or len({n for _, n in spaced}) > 1:
            if named is not None:
                named.append(spaced_as[0])  # the claim reads as the writer spelled it, not as the bare name that is another file
            return UNRESOLVED, (f"the cited path is ambiguous: {path} with the words before it can name {' or '.join(names[:4])} "
                                f"at {sha}, so no file was checked")
        found = spaced
        if named is not None:
            named.append(spaced[0][1])  # the caller prints the file that was checked, not the cut tail
    if len({n for _, n in found}) > 1:
        names = sorted({n for _, n in found})
        return UNRESOLVED, (f"path part is ambiguous: {len(names)} files at {sha} end with {path} "
                            f"({', '.join(names[:3])}{', ...' if len(names) > 3 else ''})")
    if found:
        r, n = found[0]
        count, why = blob_lines(r, sha, n)
        if count is None:
            return UNRESOLVED, f"sha {sha} and path {n} exist in {r.name}, but line {lines} was not checked: {why}"
        span = line_span(lines)
        if span is None:
            return REFUTED, f"line part failed: line number out of range ({n} has {count} lines at {sha})"
        first, last = span
        if first < 1 or last > count:
            return REFUTED, (f"line part failed: {n} has {count} lines at {sha}, line {lines} "
                             f"{'does not exist (lines start at 1)' if first < 1 else 'is past the end'}")
        if anchor:
            text, why = blob_span(r, sha, n, first, last)
            if text is None:
                return UNRESOLVED, f"sha {sha} and path {n} exist in {r.name}, but the quoted text was not checked ({why})"
            want = " ".join(anchor.split())
            if want in " ".join(text.split()):
                return CONFIRMED, f"{n} at {sha}: the quoted text is on line {lines}"
            return REFUTED, f"{n} at {sha}: the quoted text \"{want}\" is not on line {lines} (pinned to a commit: never moved)"
        return CONFIRMED, f"sha {sha} resolves in {r.name}; path {n} has {count} lines at that commit; line {lines} is within it"
    if cut:
        return UNRESOLVED, (f"{path} is the end of {cut[0]} at {sha}, not a whole path: the cited path may be cut at a space "
                            f"in a directory name, so it was not checked")
    if not absent:  # the sha resolved a moment ago and now nowhere: a failed look is not a missing path
        return UNRESOLVED, f"{sha} no longer resolves in the searched repos"
    return REFUTED, f"path part failed: {path} does not exist at {sha} in {', '.join(absent)}"


def looks_like(body: str) -> list:
    """The tokens of `body` that look like a citation (`word:12`) but matched no checkable form (okf-knowledge-gate#14, part 3), in order.

    A token scan, not a regular expression over the body: the pattern it replaced backtracked cubically on a long line (a
    20 KB inline image took minutes)."""
    out = []
    for tok in body.split():
        tok = tok.strip("(").rstrip(".,;)")
        if LOOKS_TOKEN.fullmatch(tok) and any(c.isalpha() for c in tok.split(":")[0]):
            out.append(tok)
    return out


def real_inside(p, roots) -> bool:
    """Is the REAL path of `p` (symlinks resolved) inside one of `roots` (also resolved)? A link in the bundle that points
    outside it must not be read: an anchor would make CONFIRMED / REFUTED an oracle on the target's text (review B1)."""
    rp = os.path.realpath(str(p))
    for r in roots:
        rr = os.path.realpath(str(r))
        if rp == rr or rp.startswith(rr.rstrip(os.sep) + os.sep):
            return True
    return False


def line_range(lines: str, count: int, shown: str):
    """The verdict of `lines` (`N` or `N-M`) against a file of `count` lines; `shown` names the file in the detail."""
    span = line_span(lines)
    if span is None:
        return REFUTED, f"line part failed: line number out of range ({shown} has {count} lines)"
    first, last = span
    if first < 1 or last > count:
        return REFUTED, (f"{shown} has {count} lines, line {lines} "
                         f"{'does not exist (lines start at 1)' if first < 1 else 'is past the end'}")
    return CONFIRMED, f"{shown} has {count} lines; line {lines} is within it"


def anchor_check(text: str, lines: str, anchor: str, shown: str, may_move: bool = True):
    """The verdict of a content anchor: (verdict, detail, moved_to). Whitespace is compared collapsed, case as written."""
    want = " ".join(anchor.split())
    rows = text.split("\n")
    if text.endswith("\n"):
        rows = rows[:-1]
    lo, _, hi = lines.partition("-")
    first = line_no(lo)
    first = 10 ** 9 if first is None else first
    last = max(first, line_no(hi) or first) if hi else first
    span = min(last - first + 1, max(len(rows), 1))
    if 1 <= first and last <= len(rows) and want in " ".join(" ".join(rows[first - 1:last]).split()):
        return CONFIRMED, f"{shown}: the quoted text is on line {lines}", None
    if not may_move:
        return REFUTED, f"{shown}: the quoted text \"{want}\" is not on line {lines} (pinned to a commit: never moved)", None
    starts = [i + 1 for i in range(len(rows) - span + 1) if want in " ".join(" ".join(rows[i:i + span]).split())]
    if not starts:
        # The text may wrap over more lines than the citation names: look in the whole file, collapsed, and name the line
        # it starts on (review S2).
        parts = [" ".join(r.split()) for r in rows]
        offs, pos = [], 0
        for part in parts:
            offs.append(pos)
            pos += len(part) + 1
        joined, k = " ".join(parts), 0
        while True:
            k = joined.find(want, k)
            if k < 0:
                break
            line = max(i for i, o in enumerate(offs) if o <= k) + 1
            if line not in starts:
                starts.append(line)
            k += 1
    if not starts:
        return REFUTED, f"{shown}: the quoted text \"{want}\" is not in the file", None
    at = [str(i) if span == 1 else f"{i}-{i + span - 1}" for i in starts]
    shown_at = " or ".join(at[:3]) + (f" (and {len(at) - 3} more)" if len(at) > 3 else "")
    return MOVED, f"{shown}: the quoted text is not on line {lines}; it is now on line {shown_at}", at[0]


def since_check(found: Path, text: str, lines: str, since: tuple):
    """--since (okf-knowledge-gate#14, slice c): did the cited lines of `found` move or change since the ref? ("moved", [starts]), ("changed", None) or None.

    The cited block is taken from the blob `<ref>:<path>`, read in pieces (not stripped: a stripped leading blank line would shift every
    line number) and looked for in the file as it is now, compared with whitespace collapsed.
    """
    top, ref = since[0], since[1]
    rel = os.path.relpath(os.path.realpath(str(found)), os.path.realpath(str(top)))
    if rel.startswith(".."):
        return None
    span = line_span(lines)
    if span is None:
        return None
    first, last = span
    count, why = blob_lines(top, ref, rel)   # streamed, and None for a file that is new since the ref: nothing to compare
    if count is None and ("binary file" in why or "symlink" in why):
        return ("uncompared", None)
    if count is None or first < 1 or last > count:
        return None   # a citation already outside the file at the ref is not compared either
    old_text, _ = blob_span(top, ref, rel, first, last)
    if old_text is None:
        return None
    def rows(t):
        r = t.split("\n")
        return r[:-1] if t.endswith("\n") else r
    new = rows(text)
    norm = lambda block: [" ".join(x.split()) for x in block]
    cited = norm(rows(old_text))
    if norm(new[first - 1:last]) == cited:
        return None
    span = last - first + 1
    starts = [i + 1 for i in range(len(new) - span + 1) if norm(new[i:i + span]) == cited]
    return ("moved", starts) if starts else ("changed", None)


_LINE_DOCS: dict[tuple, tuple] = {}


def find_line_doc(target: str, by_name: bool, note_dir: Path, bundle: Path, repos: list[Path], docs: dict):
    """`_find_line_doc`, asked once per name and folder in a run: the words before a citation give it many names to try."""
    key = (target, by_name, str(note_dir), str(bundle), tuple(map(str, repos)))
    if key not in _LINE_DOCS:
        try:
            _LINE_DOCS[key] = _find_line_doc(target, by_name, note_dir, bundle, repos, docs)
        except OSError as e:   # a folder of a searched repository that nobody may enter: nobody could look, so not "not found"
            _LINE_DOCS[key] = (None, None, (UNRESOLVED, f"cannot be looked up: {target} ({e.strerror or type(e).__name__})"))
    return _LINE_DOCS[key]


def _find_line_doc(target: str, by_name: bool, note_dir: Path, bundle: Path, repos: list[Path], docs: dict):
    """Where the document a line citation names is: (found, shown, None); (None, None, (verdict, detail)) when it is not found,
    ambiguous or outside; (None, None, None) when a short-form name matches no note, which is prose.

    `target` is a path (`notes/d.md`) or, with `by_name`, a note's file name without `.md`. A path is read from the citing
    note's folder, then the bundle root, then as the end of one bundle path, then from the root of each searched repository.
    A hit counts only in the case it is written: `is_file()` answers yes for `spec.md` beside `Spec.md` on a case-insensitive disk.
    `docs` maps each end of a bundle document's path, from a "/" on (and the whole path), to the documents that end so.
    """
    found = None
    roots = [bundle, *repos]
    outside_msg = "outside the bundle and the searched repositories, so it was not looked up"
    if by_name:
        hits = [d for d in docs.get(target + ".md", ()) if os.path.basename(d) == target + ".md"]
        if not hits:
            return None, None, None
        if len(hits) > 1:
            return None, None, (UNRESOLVED, f"ambiguous: {len(hits)} notes are named {target}.md ({', '.join(sorted(hits)[:3])})")
        if not real_inside(bundle / hits[0], roots):
            return None, None, (UNRESOLVED, outside_msg)
        found, shown = bundle / hits[0], hits[0]
    else:
        outside = False
        for base in (note_dir, bundle):   # an exact path from the note's folder or the bundle root decides
            p = Path(os.path.normpath(str(base / target)))
            if not inside_any(str(p), [bundle]) or not real_inside(p, roots):
                outside = True
                continue
            if _guard().path_is_file(p) and _guard().case_exact(p, base):
                found, shown = p, os.path.relpath(p, bundle)
                break
        if found is None:
            # Otherwise the end of a bundle path, or a document of a searched repository: one candidate in all, or ambiguous.
            cands = []
            if not target.startswith("../"):
                cands += [(bundle / d, d) for d in docs.get(target, ())]
            for r in repos:
                p = Path(os.path.normpath(str(r / target)))
                if inside_any(str(p), [r]) and real_inside(p, roots) and _guard().path_is_file(p) and _guard().case_exact(p, r):
                    cands.append((p, f"{r.resolve().name or r}/{os.path.relpath(p, r)}"))
            cands = [(p, n) for p, n in cands if real_inside(p, roots)]
            if len(cands) > 1:
                return None, None, (UNRESOLVED, f"ambiguous: {len(cands)} documents match {target} "
                                                f"({', '.join(sorted(n for _, n in cands)[:3])})")
            if cands:
                found, shown = cands[0]
        if found is None:
            if outside and not any(inside_any(os.path.normpath(str(r / target)), [r]) for r in repos):
                return None, None, (UNRESOLVED, outside_msg)
            where = ", ".join(r.resolve().name or str(r) for r in repos)   # `--repo .` has no name of its own
            return None, None, (UNRESOLVED, f"not found in the bundle{' or the searched repositories (' + where + ')' if repos else ''}")
    return found, shown, None


def check_line(target: str, lines: str, by_name: bool, note_dir: Path, bundle: Path, repos: list[Path],
               docs: dict, guard, anchor: str | None = None, since: tuple | None = None,
               generated: frozenset = frozenset(), cands: list[str] = (), quoted: bool = False, named: list | None = None):
    """A line citation into a living document (okf-knowledge-gate#14): the file must exist with that many lines.

    `find_line_doc` says which file `target` is. REFUTED only when the file was found and is shorter. A file that is missing or
    ambiguous is UNRESOLVED, and a path that leaves the bundle and every searched repository is not even looked up: a bundle you
    did not write must not learn, through this check, which files exist on your machine. Returns None when a short-form name
    matches no note: it is prose.

    The cut at a space (`my w.md:10` is read as `w.md:10`) is repaired as for a pinned citation (RV-27): the words before it may
    spell the name (`cands`, from `spaced_names`: names of documents there are). If they do, that file is the one checked, unless the bare name is a file too, or
    the words fit two files: then no file is checked. A QUOTED name (`quoted`) is never cut. `named` receives the file that was
    checked, or, when none was, the name as the writer spelled it.
    """
    found, shown, early = find_line_doc(target, by_name, note_dir, bundle, repos, docs)
    spaced = []
    for c in cands:
        f, n, e = find_line_doc(c, by_name, note_dir, bundle, repos, docs)
        if f is not None:
            spaced.append((f, n, c))
        elif e and e[1].startswith("ambiguous"):
            if named is not None:
                named.append(c)
            return e
    if spaced:
        names = sorted({n for _, n, _ in spaced} | ({shown} if found is not None else set()))
        if found is not None or len(names) > 1:
            if named is not None:
                named.append(spaced[0][2])   # the claim reads as the writer spelled it, not as the bare name that is another file
            return UNRESOLVED, (f"the cited path is ambiguous: {target} with the words before it can name {' or '.join(names[:4])}, "
                                f"so no file was checked")
        (found, shown, _), early = spaced[0], None
        if named is not None:
            named.append(shown)   # the caller prints the file that was checked, not the cut tail
    if early:
        return early
    if found is None:
        return None
    # A cited note of the bundle whose real path is outside it is not opened; a file of a searched repository outside
    # the bundle is judged as before.
    note_root = None if os.path.relpath(found, bundle).split(os.sep)[0] == ".." else bundle
    why = guard.refusal(found, root=note_root)
    if why:
        return UNRESOLVED, f"{shown} was not opened: {why}"
    try:
        text = guard.read_note(found, "utf-8", "replace", root=note_root)
    except OSError as e:
        return UNRESOLVED, f"{shown} cannot be read ({type(e).__name__})"
    count = text.count("\n") + (1 if text and not text.endswith("\n") else 0)
    extra = {}
    try:
        in_bundle = os.path.relpath(found, bundle)
    except ValueError:
        in_bundle = ".."
    if not anchor and in_bundle in generated:
        extra["warning"] = (f"{shown} is a generated note (okf_check.verify.generated): its line numbers change on every "
                            f"rebuild, so add a quoted anchor to the citation")
    if anchor:
        v, d, extra["moved_to"] = anchor_check(text, lines, anchor, shown)
        return v, d, extra
    v, d = line_range(lines, count, shown)
    # Only a citation the note already had at the ref: one the branch corrected along with the move is right as it is (B2).
    had = since[2](f"{target}:{lines}") if since else False   # None: the note at the ref was too large to read
    shifted = since_check(found, text, lines, since) if had else None
    if had is None:
        extra["warning"] = f"not compared: note at {since[1]} too large to compare, so whether it cited {target}:{lines} is not known"
    if shifted and shifted[0] == "uncompared":
        extra["warning"] = f"not compared: binary or symlink at {since[1]}"
    elif shifted and shifted[0] == "moved":
        first, last = line_span(lines)
        at = [str(i) if last == first else f"{i}-{i + last - first}" for i in shifted[1]]
        extra["moved_to"] = at[0]
        return MOVED, (f"{shown}: the cited text was on line {lines} at {since[1]} and is now on line "
                       f"{' or '.join(at[:3])}"), extra
    elif shifted:
        extra["warning"] = (f"the cited line {lines} of {shown} changed since {since[1]}: check that the citation still says "
                            f"what it meant")
    return v, d, extra


_ROOT_FORMS: dict[str, tuple] = {}


def resolved_root(p: Path) -> Path:
    """`p` as an absolute path for reading a bundle or a `--repo`, with `..` collapsed only where the system collapses it
    the same way.

    A `..` after a link names two folders: `link/..` taken off the spelling is the folder that holds the link, while the
    system follows the link first and steps up from there. Collapsing it lexically before the read therefore changes
    which folder is searched, or which bundle is opened, and an invocation that worked stops working. The lexical answer
    counts only when both spellings name the same folder; otherwise the path is joined with the working directory and
    left as written, and the system resolves it. `realpath` is asked about the roots, never reported: the report names
    the path the user typed.
    """
    collapsed = Path(os.path.abspath(p))
    if os.path.realpath(collapsed) == os.path.realpath(p):
        return collapsed
    return p if os.path.isabs(p) else Path(os.getcwd()) / p


def root_forms(r) -> tuple:
    """The spellings of the root folder `r` that a path written in a note can be inside of.

    Its own (normpath) and its real location (realpath). One more: the folder as the shell spells it (`$PWD`). That spelling
    serves a relative root and an absolute one alike: `--repo repo` run from a macOS temp folder is `/private/var/...` for the
    system but `/var/...` for a note that was written there, and a root resolved before searching meets the same split.
    Only the root side is looked at on disk, once per root, and the spelling counts only when it names the same folder as the
    root itself.
    """
    key = str(r)
    if key not in _ROOT_FORMS:
        forms = [os.path.normpath(key), os.path.realpath(key)]
        pwd = os.environ.get("PWD", "")
        if os.path.isabs(pwd):
            try:
                if os.path.samefile(pwd, os.getcwd()):   # $PWD can be stale: it counts only while it names the folder we are in
                    # The spelling $PWD gives this root: the shell's name for the folder we are in, then the rest of the path.
                    logical = os.path.normpath(os.path.join(pwd, os.path.relpath(forms[0], os.getcwd())))
                    # normpath takes `..` off the spelling (`L/..` is `.` there) while the system takes it off the real folder: a
                    # `..` under a linked $PWD names two different folders. The spelling counts only when it is the same one.
                    if os.path.realpath(logical) == forms[1]:
                        forms.append(logical)
            except (OSError, ValueError):   # relpath answers ValueError for two paths on two drives
                pass
        _ROOT_FORMS[key] = tuple(dict.fromkeys(forms))
    return _ROOT_FORMS[key]


def root_of(p: str, roots: list[Path]):
    """The spelling of the root that the normalised path `p` is inside of, or None. Lexical: `p` is read as written and is never
    touched on disk (a path under `/net/<host>` would make macOS mount that host), so asking costs no stat on `p`. The roots are
    looked at instead, in every spelling `root_forms` gives."""
    for r in roots:
        for form in root_forms(r):
            if p == form or p.startswith(form.rstrip(os.sep) + os.sep):
                return form
    return None


def inside_any(p: str, roots: list[Path]) -> bool:
    """Is the normalised path `p` inside one of `roots`? See `root_of`."""
    return root_of(p, roots) is not None


def check_path(raw: str, bundle: Path, roots: list[Path] | None = None, host_paths: bool = False):
    """A path CAN be refuted — but only where we know we looked in the right place."""
    p = Path(os.path.expanduser(raw))
    if not p.is_absolute():
        p = bundle / raw
    # `..` and `.` are resolved lexically before anything else: `case_exact` (okf_guard) lists directories and `..` is in none.
    p = Path(os.path.normpath(str(p)))
    # A bundle is untrusted input. Probing arbitrary host paths answers "does this key file exist on the runner?" in
    # a CI log, so only paths inside the bundle or a --repo folder are looked up unless --host-paths says otherwise.
    root = root_of(str(p), [bundle, *(roots or [])])
    if roots is not None and not host_paths and root is None:
        # A folder written in another case than the note spells it is outside, as written: say so, the cause is not obvious.
        folded = str(p).lower()
        case = any(folded.startswith(f.lower().rstrip(os.sep) + os.sep) for r in [bundle, *roots] for f in root_forms(r))
        return UNRESOLVED, ("outside the bundle and the --repo folders, so it was not looked up "
                            "(pass --host-paths to check paths on this machine)"
                            + ("; the bundle or --repo folder is typed in another case than this path" if case else ""))

    # EXISTENCE IS CHECKED FIRST. An earlier draft tested `ephemeral` before
    # `exists()`, which made a file that demonstrably EXISTS in a temp directory
    # report UNRESOLVED — caught by V-2. Ephemerality is only relevant to
    # ABSENCE: it says "gone from here proves nothing", never "present here
    # proves nothing".
    #
    # `exists() == False` is THREE states, not one, and only the last justifies
    # REFUTED. Conflating them was the root cause of the refuted central claim:
    #   raises OSError  -> unreadable (EACCES); we were not allowed to look
    #   lexists()       -> the entry EXISTS but does not resolve (ELOOP, dangling)
    #   neither         -> genuinely absent
    try:
        if _guard().path_exists(p):
            # UNRESOLVED, not REFUTED: the file is plainly there under another
            # case, so the claim is not false — it is unverified as written.
            # Only the part below the root is the citation: how the root was typed is not (`okf-verify repo/b` for the folder `Repo/b`).
            if not _guard().case_exact(p, root):
                return UNRESOLVED, ("only a case-variant of this path exists and the "
                                    "filesystem is case-insensitive — present, but not "
                                    "as written, which is not the same as confirmed")
            return CONFIRMED, "exists"
    except OSError as e:                                                  # (D-2)
        return UNRESOLVED, (f"cannot stat ({type(e).__name__}) — unreadable, "
                            f"which is not the same as absent")
    if os.path.lexists(p):                                                # (D-1)
        return UNRESOLVED, ("a directory entry exists but does not resolve "
                            "(looping or dangling symlink) — unresolvable, not absent")

    # Now that absence is established: was it ever reasonable to expect the file
    # to still be there? Canonicalise first — realpath($TMPDIR) on macOS is
    # /private/var/folders/..., so a prefix test on the raw string let the
    # CANONICAL form of the very same directory fall through to REFUTED, two
    # verdicts for one byte-identical location. (D-3)
    try:
        real = os.path.realpath(p)
    except OSError:
        real = str(p)
    if str(real).startswith(EPHEMERAL) or str(p).startswith(EPHEMERAL):
        return UNRESOLVED, "ephemeral location — absence here proves nothing about the claim"
    try:
        parent_exists = _guard().path_exists(p.parent)
    except OSError as e:
        return UNRESOLVED, f"parent unreadable ({type(e).__name__}) — could not check"
    if parent_exists:
        return REFUTED, f"parent {p.parent} exists but the file does not"
    return UNRESOLVED, f"parent {p.parent} does not exist either — different machine or layout"


class BaseConfigError(Exception):
    """The okf_check block of okf-base.yaml cannot be used."""


def check_node(value, node: dict, where: str, bundle: Path | None = None) -> None:
    """Check `value` against one node of config/okf-check-block.json (the schema both okf-check and okf-verify obey)."""
    if "keys" in node:
        if not isinstance(value, dict):
            raise BaseConfigError(f"{where} must be a mapping")
        known = sorted(node["keys"])
        for k in value:
            if str(k) not in node["keys"]:
                raise BaseConfigError(f"{where}.{k} is not a known key (known: {', '.join(known)})")
        for k in node.get("required", []):   # {required: [names]} (okf_check.facts, okf-knowledge-gate#15)
            if k not in value:
                raise BaseConfigError(f"{where} needs {k}")
        for k, v in value.items():
            check_node(v, node["keys"][str(k)], f"{where}.{k}", bundle)
            # {requires: {sibling: value}}: this key only makes sense when a sibling key has that value.
            for sib, want in node["keys"][str(k)].get("requires", {}).items():
                if value.get(sib) != want:
                    shown = "true" if want is True else "false" if want is False else want
                    raise BaseConfigError(f"{where}.{k} needs {where}.{sib}: {shown}")
        # {below: sibling}: when that sibling is set, this value is smaller than it. After every value is checked, so
        # the comparison only ever sees numbers (a warn limit at or above the maximum would never fire).
        for k, v in value.items():
            other = node["keys"][str(k)].get("below")
            if other in value and not v < value[other]:
                raise BaseConfigError(f"{where}.{k} must be below {where}.{other}")
    elif "map" in node:
        # A mapping whose keys are free (each a non-empty string, e.g. a folder glob); each value is checked against node.
        if not isinstance(value, dict):
            raise BaseConfigError(f"{where} must be a mapping")
        for k, v in value.items():
            if not isinstance(k, str) or not k:
                raise BaseConfigError(f"{where} has a key that is not a non-empty string: {k}")
            # {key_no_prefix: "!"}: the owners globs use the .okfignore syntax, which has no negation; a "!x" pattern
            # would be inert, so it is refused rather than ignored (0.9.8 review G-2)
            if node.get("key_no_prefix") and k.startswith(node["key_no_prefix"]):
                raise BaseConfigError(f"{where}.{k}: a pattern that starts with {node['key_no_prefix']} (negation) is not supported")
            check_node(v, node["map"], f"{where}.{k}", bundle)
    elif node.get("type") == "number":
        # {type: number, min, max}: a number within the bounds (inclusive). `default` is read by the option's user.
        if isinstance(value, bool) or not isinstance(value, (int, float)) or not node["min"] <= value <= node["max"]:
            raise BaseConfigError(f"{where} must be a number from {node['min']} to {node['max']}")
    elif node.get("type") == "folder":
        # {type: folder}: a path relative to the bundle that names an existing folder (wikilink_root).
        if not isinstance(value, str) or not value:
            raise BaseConfigError(f"{where} must be a non-empty string")
        if value != value.strip():
            # realpath would turn " .." into a missing step and the option would do nothing in silence
            raise BaseConfigError(f"{where}: {json.dumps(value)} must not start or end with a space")
        if bundle is None:
            raise BaseConfigError(f"{where} cannot be checked without the bundle folder")
        if os.path.isabs(value):
            raise BaseConfigError(f"{where} must be a path relative to the bundle, not an absolute path: {value}")
        target = os.path.realpath(os.path.join(bundle, value))
        if not os.path.exists(target):
            raise BaseConfigError(f"{where}: {value} does not exist")
        if not os.path.isdir(target):
            raise BaseConfigError(f"{where}: {value} is not a folder")
        # The vault root holds the bundle: a folder that is not the bundle or one of its parents would let a link resolve
        # against an unrelated project, and the file system root or the home folder (or a folder above it) is not a
        # vault but "everything", so a typo such as ../../../../.. would silently accept any link.
        here = os.path.realpath(bundle)
        if here != target and not here.startswith(target.rstrip(os.sep) + os.sep):
            raise BaseConfigError(f"{where}: {value} must be the bundle folder or one of its parent folders")
        home = os.path.realpath(os.path.expanduser("~"))
        if target == os.sep or home == target or home.startswith(target + os.sep):
            raise BaseConfigError(f"{where}: {value} is too broad: the file system root, the home folder and the folders above it are refused")
    elif node.get("type") == "integer":
        # {type: integer, min, max}: a whole number within the bounds (inclusive); 40.5 and true are not.
        if isinstance(value, bool) or not isinstance(value, int) or not node["min"] <= value <= node["max"]:
            raise BaseConfigError(f"{where} must be a whole number from {node['min']} to {node['max']}")
    elif node.get("type") == "regex":
        # {type: regex}: a pattern that finds a statement; group 1 is the stated value (okf_check.facts)
        if not isinstance(value, str) or not value:
            raise BaseConfigError(f"{where} must be a non-empty string")
        try:
            groups = re.compile(value).groups
        except re.error as e:
            raise BaseConfigError(f"{where}: {json.dumps(value)} is not a regular expression ({e})")
        if groups < 1:
            raise BaseConfigError(f"{where}: {json.dumps(value)} needs a capture group (group 1 is the stated value)")
    elif node.get("type") == "boolean":
        if not isinstance(value, bool):
            raise BaseConfigError(f"{where} must be true or false")
    elif "list" in node:
        if not isinstance(value, list):
            raise BaseConfigError(f"{where} must be a list")
        if len(value) < node.get("min", 0):
            raise BaseConfigError(f"{where} needs at least {node['min']} item(s)")
        for i, v in enumerate(value):
            check_node(v, node["list"], f"{where}[{i}]", bundle)
            # {item_no_prefix: "!"}: list items that are .okfignore globs (size.exclude) have no negation, as map keys (owners).
            # Spaces around an item are dropped, as .okfignore drops them; a tab or a line break cannot be in a path, and the
            # reader would drop such an item in silence, so it is refused here.
            if node.get("item_no_prefix") and isinstance(v, str):
                if v.strip().startswith(node["item_no_prefix"]):
                    raise BaseConfigError(f"{where}[{i}]: a pattern that starts with {node['item_no_prefix']} (negation) is not supported")
                if "\t" in v or "\n" in v:
                    raise BaseConfigError(f"{where}[{i}]: a pattern may not hold a tab or a line break")
    elif "enum" in node:
        if not isinstance(value, str) or value not in node["enum"]:
            # JSON, not a Python repr: a YAML user wrote true/null/"x ", not True/None (review F-D)
            raise BaseConfigError(f"{where}: {json.dumps(value)} is not one of: {', '.join(node['enum'])}")
    elif not isinstance(value, str) or not value:
        raise BaseConfigError(f"{where} must be a non-empty string")


def _guard():
    """okf_guard, the bounded note reader shared with okf-check. Imported late; the vendored PyYAML is put on the path for the manifest."""
    here = Path(__file__).resolve().parent
    vendor = here.parent / "vendor"
    sys.dont_write_bytecode = True   # an import must not leave scripts/__pycache__ in the installed plugin (plugin.test.sh Z-2)
    sys.path[:0] = [str(here)] + ([str(vendor)] if "yaml" in sys.modules else [str(vendor / "pyyaml"), str(vendor)])
    import okf_guard
    return okf_guard


def load_manifest(bundle: Path, source: Path | None = None) -> tuple[dict, dict]:
    """The parsed okf-base.yaml and the okf_check schema: ({}, {}) when there is no manifest.

    `source` names a folder holding a copy of the manifest to read instead (okf-check reads its frozen copy).
    A file that cannot be read, is not UTF-8 or YAML, or whose top level is not a mapping raises BaseConfigError.
    """
    base = (source or bundle) / "okf-base.yaml"
    try:
        present = _guard().path_is_file(base)
    except OSError as e:   # a folder that nobody may enter: no manifest is not the same as a manifest nobody could look for
        raise BaseConfigError(f"cannot read: {e.strerror or type(e).__name__}")
    if not present:
        return {}, {}
    if _guard().outside(base, source or bundle):   # a manifest whose real path is outside the bundle is not read
        raise BaseConfigError(f"{_guard().OUTSIDE_WHY}: not read")
    # PyYAML and the bounded loader ship beside the scripts in the plugin. The loader refuses a YAML alias bomb (a
    # small file whose aliases nest into billions of items) as an ordinary YAML error, as it does for L1 and the trust helper.
    vendor = Path(__file__).resolve().parent.parent / "vendor"
    sys.path[:0] = [str(vendor)] if "yaml" in sys.modules else [str(vendor / "pyyaml"), str(vendor)]
    import yaml
    from okf_validate import load_frontmatter
    schema_file = Path(__file__).resolve().parent.parent / "config" / "okf-check-block.json"
    try:
        schema = json.loads(schema_file.read_text(encoding="utf-8"))
    except (OSError, ValueError) as e:
        raise BaseConfigError(f"cannot be checked: the schema {schema_file} is unreadable ({type(e).__name__})")
    try:
        text = _guard().read_manifest(base, "utf-8", "strict", root=base.parent)   # bounded by the manifest's own limit, not the note cap
        data = load_frontmatter(text)
    except OSError as e:
        raise BaseConfigError(f"cannot read: {e.strerror or str(e) or type(e).__name__}")
    except UnicodeDecodeError:
        raise BaseConfigError("is not valid UTF-8")
    except yaml.YAMLError as e:
        mark = getattr(e, "problem_mark", None)
        where = f"line {mark.line + 1}: " if mark else ""
        raise BaseConfigError(f"is not valid YAML ({where}{getattr(e, 'problem', None) or str(e).splitlines()[0]})")
    if data is None:
        return {}, schema
    if not isinstance(data, dict):
        raise BaseConfigError("the top level must be a mapping")
    # YAML keeps the last of two equal keys and drops the first without a word: `wikilink_root: ../..` then
    # `wikilink_root: ../../..` ran with the second. Inside okf_check, or okf_check itself, that is a config error naming
    # the key's path. The document parsed above with the bounded loader, so composing it again cannot run away.
    loader = yaml.SafeLoader(text)
    try:
        twice = _written_twice(loader, loader.get_single_node())
    finally:
        loader.dispose()
    if twice:
        raise BaseConfigError(f"has `{twice}` written twice: YAML keeps the last one and drops the first; write it once")
    return data, schema


def _written_twice(loader, top) -> str | None:
    """The path of a key written twice in the okf_check block (`okf_check` when the block itself is), else None.

    Keys are compared as YAML reads them, value and type: `1` and `"1"` are an integer and a string, two keys. Merge
    keys (`<<`) may repeat. Other top-level blocks belong to other tools and are not looked at.
    """
    import yaml
    stack, seen = [(top, "")], set()
    while stack:
        node, path = stack.pop()
        if id(node) in seen:
            continue
        seen.add(id(node))
        if isinstance(node, yaml.MappingNode):
            keys = set()
            for k, v in node.value:
                if not isinstance(k, yaml.ScalarNode) or k.tag == "tag:yaml.org,2002:merge":
                    continue
                key = loader.construct_object(k)
                if not path and key != "okf_check":
                    continue
                where = f"{path}.{k.value}" if path else "okf_check"
                if (type(key), key) in keys:
                    return where
                keys.add((type(key), key))
                stack.append((v, where))
        elif isinstance(node, yaml.SequenceNode) and path:
            stack.extend((v, f"{path}[{i}]") for i, v in enumerate(node.value))
    return None


def load_block(bundle: Path, source: Path | None = None) -> dict:
    """The validated okf_check block of <bundle>/okf-base.yaml ({} when there is none).

    `source` names a folder holding a copy of the manifest to read instead (okf-check reads its frozen copy); paths the
    block names, such as wikilink_root, are still resolved against `bundle`.

    A file that cannot be read, a block of the wrong shape and a key nobody knows all raise BaseConfigError:
    ignoring any of them reads as "nothing was declared". A typo such as `verify.repo` ran with "repos searched:
    NONE" and exit 0. okf-check validates the same block by calling `okf-verify --check-config`.
    """
    data, schema = load_manifest(bundle, source)
    if "okf_check" not in data:
        return {}
    check_node(data["okf_check"], schema, "okf_check", bundle)
    yaml11_booleans((source or bundle) / "okf-base.yaml", schema)
    return data["okf_check"]


YAML11_WORDS = re.compile(r"(?i)^(yes|no|on|off)$")


def okf_check_text(text: str) -> str:
    """The lines of the top-level okf_check block, comments removed: a comment or another block's `remote: no` is not an
    okf_check option (review 0.9.35). The block runs from `okf_check:` to the next line that starts in column 0."""
    out, inside, depth = [], False, 0   # depth: open { or [ of a flow mapping, which may wrap to column 0
    for line in text.splitlines():
        if re.match(r"^okf_check\s*:", line):
            inside, depth = True, 0
        elif inside and depth <= 0 and line[:1] not in ("", " ", "\t", "#"):
            inside = False
        if inside:
            # Quoted text out first: a bracket in a value (a facts pattern) does not open anything (review 0.9.35 round 3).
            bare = re.sub(r"(^|\s)#.*$", "", re.sub(r"'(?:[^']|'')*'|\"(?:[^\"\\]|\\.)*\"", "''", line))
            depth += bare.count("{") + bare.count("[") - bare.count("}") - bare.count("]")
        if inside:
            out.append(re.sub(r"(^|\s)#.*$", "", line))   # a YAML comment starts at a # after whitespace
    return "\n".join(out)


def yaml11_booleans(base: Path, schema: dict) -> None:
    """Refuse `edit_hook: yes` and its kin for the true/false options (B-7).

    The loader is YAML 1.1, so an unquoted yes, no, on or off arrives as a boolean and passes the type check, while a
    YAML 1.2 reader (and anyone reading the file) sees a word. Only `true` and `false` say the same thing everywhere.
    """
    names = {}
    def walk(node, where):
        for k, sub in (node.get("keys") or {}).items():
            if sub.get("type") == "boolean":
                names[k] = f"{where}.{k}"
            walk(sub, f"{where}.{k}")
    walk(schema, "okf_check")
    if not names:
        return
    text = okf_check_text(_guard().read_manifest(base, "utf-8", "replace", root=base.parent))
    key = "|".join(re.escape(k) for k in names)
    for m in re.finditer(rf"(?m)(?:^|[{{,\s])({key})\s*:[ \t]*([A-Za-z]+)[ \t]*(?=$|[,}}#])", text):
        if YAML11_WORDS.match(m.group(2)):
            raise BaseConfigError(f"{names[m.group(1)]} must be true or false: write true or false, not {m.group(2)} "
                                  "(this reader takes it as a boolean, other YAML readers as a word)")


def misplaced_keys(data: dict, schema: dict) -> list[str]:
    """The okf_check options written at the top level of okf-base.yaml instead of inside okf_check:, in file order.

    Every tool ignores such a key, so the option it names is off and nothing else says so.
    """
    return [k for k in data if k in schema.get("keys", {})]


def misplaced_hints(bundle: Path) -> list[str]:
    """One line per okf_check option written at the top level of okf-base.yaml: okf-check prints the same advice (Config WARN),
    but a user who runs okf-verify alone (the Action's verify, the pre-commit hook) only saw `repos searched: NONE`."""
    data, schema = load_manifest(bundle)
    inside = data.get("okf_check") if isinstance(data.get("okf_check"), dict) else {}
    return [f"`{k}` is at the top level of okf-base.yaml" + (" and also inside okf_check:" if k in inside else ", outside okf_check:")
            + f"; okf-verify reads `{k}` only inside okf_check: "
            + ("delete the top-level copy" if k in inside else f"move it to okf_check.{k}") for k in misplaced_keys(data, schema)]


def declared_repos(bundle: Path, given: list[Path]) -> list[dict]:
    """One UNRESOLVED finding per repository okf-base.yaml names (okf_check.verify.repos) that `given` (--repo) does not.

    Since 0.9.50 only --repo is searched: okf-base.yaml arrives with the bundle, so a repository it names is not
    the user's choice (the trust model of git's safe.directory). Nothing in the entry's repository is read; it is
    named with the flag to use instead, never dropped: a silent drop would read as "no repository declared".
    Reversal: search these again behind an explicit --trust-config flag.
    """
    def key(p) -> str:
        # Spelling only, never the disk: an entry's path is not looked at, not even to follow a symlink. os.path's
        # expanduser leaves `~nosuchuser` as it is instead of raising (a crash is exit 1, "a claim was REFUTED").
        return os.path.normpath(os.path.abspath(os.path.expanduser(str(p))))
    searched = {key(r) for r in given}
    problems = []
    for e in load_block(bundle).get("verify", {}).get("repos", []):
        raw = e["path"]
        p = Path(raw) if raw.startswith(("/", "~")) else bundle / raw
        if key(p) in searched:
            continue
        problems.append({"concept": "okf-base.yaml", "kind": "repo", "claim": raw, "verdict": UNRESOLVED,
                         "detail": f"okf_check.verify.repos is not searched since 0.9.50; to search it, pass --repo {p}"})
    return problems


class IgnoreRefused(Exception):
    """The .okfignore was refused (not read); the message is ignore-lib.sh's reason."""


def not_ignored(bundle: Path):
    """The set of notes .okfignore leaves in, from the one shared matcher (ignore-lib.sh), so L4
    and okf-check cannot disagree. None = no .okfignore, or the matcher could not run (then
    nothing is excluded: a broken matcher must not hide a note). Raises IgnoreRefused when the file was refused."""
    if not (bundle / ".okfignore").is_file():
        return None
    lib = Path(__file__).resolve().parent / "ignore-lib.sh"
    try:
        r = subprocess.run(["bash", str(lib), "--list", str(bundle)], capture_output=True, timeout=60)
    except (OSError, subprocess.SubprocessError):
        return None
    if r.returncode == 2:   # the .okfignore was refused (its reason is on ignore-lib.sh's stderr): no verdict, as for okf-base.yaml
        raise IgnoreRefused(r.stderr.decode("utf-8", "replace").strip() or ".okfignore could not be applied")
    if r.returncode != 0:
        return None
    return {x for x in r.stdout.decode("utf-8", "surrogateescape").split("\0") if x}   # names: surrogateescape, as rglob reads them


def generated_notes(bundle: Path, docs: list[str]) -> frozenset:
    """The notes okf_check.verify.generated names (okf-knowledge-gate#14, slice c), through the shared .okfignore matcher (ignore-lib.sh --match)."""
    pats = [p.strip() for p in (load_block(bundle).get("verify", {}).get("generated") or []) if isinstance(p, str) and p.strip()]
    if not pats or not docs:
        return frozenset()
    lib = Path(__file__).resolve().parent / "ignore-lib.sh"
    try:
        r = subprocess.run(["bash", str(lib), "--match", *pats], input="\0".join(docs).encode("utf-8", "surrogateescape") + b"\0",
                           capture_output=True, timeout=60)
    except (OSError, subprocess.SubprocessError):
        return frozenset()
    return frozenset(x for x in r.stdout.decode("utf-8", "surrogateescape").split("\0") if x)


def verify(bundle: Path, repos: list[Path], host_paths: bool = False, since: tuple | None = None, remote: bool = False):
    results, no_claims, unrecognized = [], [], []
    guard = _guard()
    keep = not_ignored(bundle)
    # The bundle's documents, the targets of line citations: every *.md, ignored or not (an ignored note still exists).
    docs = sorted(str(f.relative_to(bundle)) for f in bundle.rglob("*.md") if f.is_file())
    names = {os.path.basename(d) for d in docs}
    ends: dict[str, list[str]] = {}   # each end of a document's path, from a "/" on (and the whole), -> the documents that end so
    for d in docs:
        for k in [-1] + [i for i, ch in enumerate(d) if ch == "/"]:
            ends.setdefault(d[k + 1:], []).append(d)
    spelled_by: list = []
    def doc_tails():
        """The documents whose names hold whitespace, for the words before a line citation to spell (`spaced_names`): path form, name form.
        The bundle's, and each searched repository's. Read at the first line citation."""
        if not spelled_by:
            repo_docs, unseen = [], []
            for r in repos:
                rc, out = git(r, "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "*.md")
                found_md = out.split("\0") if rc == 0 else walk_docs(r)   # git did not answer: walk the folder
                if found_md is None:
                    unseen.append(r.resolve().name or str(r))
                else:
                    repo_docs += [n for n in found_md if n]
            doubt = (f"git could not list {', '.join(unseen)} and it holds more than {WALK_LIMIT} entries, so a file with a space in its name "
                     f"there could not be ruled out") if unseen else ""
            spelled_by.append((tail_index({*ends, *repo_docs}), tail_index({os.path.basename(d)[:-3] for d in docs}), doubt))
        return spelled_by[0]
    generated = generated_notes(bundle, docs)
    for f in sorted(bundle.rglob("*.md")):
        if f.name in RESERVED:
            continue
        if keep is not None:
            try:
                if str(f.relative_to(bundle)) not in keep:
                    continue
            except ValueError:
                pass
        # relative to the bundle, not a basename: two `notes.md` in different
        # subdirectories were indistinguishable in the report
        try:
            rel = str(f.relative_to(bundle))
        except ValueError:
            rel = f.name
        why = guard.refusal(f, root=bundle)
        if why:   # a link out of the bundle, a device, pipe, folder or oversize file is never opened; nobody looked, so UNRESOLVED
            results.append({"concept": rel, "kind": "file", "claim": str(f), "verdict": UNRESOLVED,
                            "detail": f"refused: {why}"})
            continue
        if not f.is_file():
            continue   # a dangling link
        try:
            text = guard.read_note(f, "utf-8-sig", "strict", root=bundle)   # a BOM before the fence is no content, so frontmatter_end finds the fence
        except (OSError, UnicodeDecodeError):
            results.append({"concept": rel, "kind": "file", "claim": str(f),
                            "verdict": UNRESOLVED, "detail": "unreadable"})
            continue
        seams: set = set()
        body, unclosed = strip_code_fences(text[frontmatter_end(text):], seams)
        if unclosed:
            results.append({"concept": rel, "kind": "parse", "claim": "unclosed code fence",
                            "verdict": UNRESOLVED,
                            "detail": ("an unclosed code fence swallowed the rest of this "
                                       "concept — any claim after it was NOT checked")})
        # The words before a citation, in its paragraph: `my w.md:10` is matched as `w.md:10`, and they may be the start of its name (RV-27).
        # The paragraph ends at a blank line and at dropped code; `spaced_names` reads no more than 4096 characters of it.
        seam_at = []   # where the code dropped by strip_code_fences was, as offsets into the body
        if seams:
            starts = [0] + [i + 1 for i, ch in enumerate(body) if ch == "\n"]
            seam_at = sorted(starts[i] for i in seams if i < len(starts))
        def before(m):
            lo = max(0, m.start() - 4096)
            chunk = m.string[lo:m.start()]
            blank = _BLANK_LINE.match(chunk)
            start = blank.end() if blank else 0
            k = bisect.bisect_right(seam_at, m.start())
            return chunk[max(start, seam_at[k - 1] - lo if k else 0):]
        # A citation is ONE claim: blank it out before the SHA and path scans so its sha is not also counted on its own.
        cites = []
        def take(m):
            g = m.groups()
            quoted = len(g) == 6   # QCITE_RE has the quote character first; both end with the optional anchor
            core = g[1:5] if quoted else g[0:4]
            cites.append(core + ("" if quoted else before(m)[-4096:], quoted, g[-1]))
            return " " * len(m.group(0))
        body = CITE_RE.sub(take, QCITE_RE.sub(take, body))
        # Line citations into living documents, after the pinned ones above have been blanked out.
        lcites = []
        def take_qline(m):
            lcites.append((m.group(2), m.group(3), m.group(4), False, m.group(5), [], True, ""))
            return " " * len(m.group(0))
        def take_line(m):
            pre, tails = before(m), doc_tails()
            cands = spaced_names(m.group(1), pre, tails[0])
            # words that may spell a file there is no list of (git could not list a repository): the verdict on the bare name is not safe
            lcites.append((m.group(1), m.group(2), m.group(3), False, m.group(4), cands, False, tails[2] if pre.strip() and not cands else ""))
            return " " * len(m.group(0))
        def take_qname(m):
            if m.group(2) + ".md" not in names or not any(c.isalpha() for c in m.group(2)):
                return m.group(0)   # names no note: prose, left for the hint below
            lcites.append((m.group(2), m.group(3), m.group(4), True, m.group(5), [], True, ""))
            return " " * len(m.group(0))
        def take_name(m):
            cands = spaced_names(m.group(1), before(m), doc_tails()[1])
            if not any(c.isalpha() for c in m.group(1)) or not any(n + ".md" in names for n in [m.group(1), *cands]):
                return m.group(0)   # names no note: prose, left for the hint below
            lcites.append((m.group(1), m.group(2), m.group(3), True, m.group(4), cands, False, ""))
            return " " * len(m.group(0))
        body = NAME_RE.sub(take_name, QNAME_RE.sub(take_qname, LINE_RE.sub(take_line, QLINE_RE.sub(take_qline, body))))
        # Commit subjects quoted in the note, for the rewrite hint: after the citations are blanked, so an anchor is not one.
        subjects = QUOTED.findall(body)
        found = 0
        seen: set[tuple] = set()
        checked: dict = {}
        old_note: list = []
        def had_at_ref(claim):
            """Did this note already cite `claim` at the --since ref? (Read once per note, only when asked.)"""
            if not old_note:
                rel_top = os.path.relpath(os.path.realpath(str(f)), os.path.realpath(str(since[0])))
                t, why = blob_span(since[0], since[1], rel_top, 1, 10 ** 12)   # the whole note, up to SPAN_LIMIT
                old_note.append(t if t is not None else None if "more than" in why else "")
            if old_note[0] is None:
                return None
            return re.search(r"(?<![\w./-])" + re.escape(claim) + r"(?![\d-])", old_note[0]) is not None

        for target, lo, hi, by_name, anchor, cands, quoted, doubt in lcites:
            lines = f"{lo}-{hi}" if hi else lo
            claim = f"{target}:{lines}"
            # The words before the cut can change which file is named, so they are part of what makes two citations the same claim.
            lk = ("line", claim, anchor, tuple(cands), doubt)   # two anchors are two claims
            if lk in seen:
                continue
            seen.add(lk)
            note_since = (since[0], since[1], had_at_ref) if since else None
            named: list = []
            v, d, extra = (check_line(target, lines, by_name, f.parent, bundle, repos, ends, guard, anchor, note_since, generated,
                                      cands, quoted, named) + ({},))[:3]
            if doubt:
                v, d, extra = UNRESOLVED, (f"{d} ({doubt})" if v == UNRESOLVED else doubt), {}
            if named:
                claim = f"{named[0]}:{lines}"
            if ("line", claim, anchor, v, d) in seen:
                continue
            seen.add(("line", claim, anchor, v, d))
            found += 1
            res = {"concept": rel, "kind": "line", "claim": claim, "verdict": v, "detail": d}
            if extra.get("moved_to"):
                res["moved_to"] = extra["moved_to"]   # the line number a tool or a person can write instead
            if extra.get("warning"):
                res["warning"] = extra["warning"]
            results.append(res)

        for path, lo, hi, sha, prefix, quoted, anchor in cites:
            sha = sha.lower()
            lines = f"{lo}-{hi}" if hi else lo
            claim = f"{path}:{lines} @{sha}"
            # The words before the cut can change which file is named, so only the RESULT can say two citations are the same claim.
            ck = (claim, quoted, prefix, anchor)   # the words before the path decide which file is named, with the tree
            if ck not in checked:
                named: list = []
                checked[ck] = (*check_citation(path, lines, sha, repos, subjects, prefix, quoted, named, anchor), named)
            v, d, named = checked[ck]
            if named:
                claim = f"{named[0]}:{lines} @{sha}"
            key = (claim, v, d)
            if key in seen:
                continue
            seen.add(key)
            found += 1
            results.append({"concept": rel, "kind": "citation", "claim": claim,
                            "verdict": v, "detail": d})

        for m in SHA_CTX.finditer(body):
            # group(1) is the BARE backticked form; groups 2 and 3 carry an
            # explicit signal — a commit/sha/fix-in keyword, or a /commit/ URL.
            bare = m.group(1) is not None
            sha = (m.group(1) or m.group(2) or m.group(3) or "").lower()
            # NO digit at all is an English word or a sentinel — `defaced`,
            # `effaced`, `acceded`, `deadbeef`, `cafebabe`, `feedface` all
            # satisfy the hex charset. A real 7-char SHA has no digit with
            # probability (6/16)^7 ≈ 0.1%, so requiring one costs almost nothing
            # and removes the whole false-positive class. (D-7)
            #
            # ALL digits is different, and rejecting it outright was a real bug.
            # A 7-char abbreviation is all digits with probability (10/16)^7 ≈
            # 3.7% — 37x more likely than the case the rule above was written
            # for — so roughly one citation in twenty-seven was silently dropped
            # as "no checkable claim". That is what the intermittent five-failure
            # run in this suite's own fixtures was, blamed on machine load
            # through three review rounds. The comment did the arithmetic for one
            # case and never for the other.
            #
            # The disambiguator is CONTEXT, not charset: `commit 1234567` and
            # `/commit/1234567` are unambiguous. A bare backticked `1234567` is
            # not — it is as likely an issue number — so only that stays
            # rejected. (Z-11)
            if (not sha or not any(c.isdigit() for c in sha)
                    or (bare and sha.isdigit())
                    or ("sha", sha) in seen):
                continue
            seen.add(("sha", sha))
            found += 1
            v, d = check_sha(sha, repos, subjects, remote)
            res = {"concept": rel, "kind": "sha", "claim": sha, "verdict": v, "detail": d}
            if remote and v == CONFIRMED and d.startswith("not in the local clone"):
                res["source"] = "remote"   # CONFIRMED (remote): the local copy is behind
            results.append(res)

        for _delim, raw in PATH_RE.findall(body):
            if ("path", raw) in seen:
                continue
            seen.add(("path", raw))
            found += 1
            v, d = check_path(raw, bundle, repos, host_paths)
            results.append({"concept": rel, "kind": "path", "claim": raw,
                            "verdict": v, "detail": d})

        if found == 0:
            no_claims.append(rel)
            looks = looks_like(body)
            if looks:
                unrecognized.append({"concept": rel, "count": len(looks), "examples": looks[:3]})
    return results, no_claims, unrecognized


HELP_TOP = """\
okf-verify - check that what the notes of a bundle cite still exists (layer L4).

It reads each note for four kinds of claim (a commit SHA, a file path, a line citation, a quoted text)
and answers one verdict per claim:
  CONFIRMED   the commit, path or line is there
  REFUTED     it is not there: the note is wrong
  UNRESOLVED  it could not be checked (no repository holds the SHA, no network): NOT a soft REFUTED
  MOVED       a cited line's text is still in the file, at another line (with --since)
"""

HELP_END = """\
Exit codes:
  0  no claim is REFUTED or MOVED (with --strict: and none is UNRESOLVED or uncheckable)
  1  a claim is REFUTED or MOVED, or --strict found one UNRESOLVED or a note with no checkable claim
  2  no verdict was possible: the bundle is not a readable folder, a --repo that is not a directory,
     an okf-base.yaml that cannot be read, an unknown --since ref, an .okfignore that excludes every note;
     also a command-line error

Environment variables (all optional):
  OKF_GITLAB_HOSTS         (none)    comma-separated self-hosted GitLab hosts that --remote may ask,
                                     next to github.com and gitlab.com
  OKF_VERIFY_WALK_LIMIT    100000    entries of a searched repository to look at when git cannot list it;
                                     past it the walk stops, and a cited file with a space in its name
                                     is reported as not ruled out
  OKF_VERIFY_SPAN_LIMIT    16777216  bytes of a cited file's lines to hold when a quoted text is compared;
                                     past it the claim is UNRESOLVED
  GITHUB_TOKEN, GH_TOKEN   (none)    --remote sends it to GitHub only; without one the lookup is anonymous
                                     (GitHub allows 60 an hour)
  GITLAB_TOKEN             (none)    --remote sends it to GitLab only

Example:
  okf-verify ./notes --repo . --since main --strict

See also: okf-check (the gate over the whole bundle). The README has the full reference.
"""


def main() -> int:
    ap = argparse.ArgumentParser(
        prog="okf-verify", usage="okf-verify <bundle> [--repo DIR]... [--strict] [--json] [--remote] [--since REF] [--host-paths]",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description=HELP_TOP, epilog=HELP_END)
    try:   # the plugin's version (.claude-plugin/plugin.json), the one place bump-version.sh moves for this tool
        _v = json.loads((Path(__file__).resolve().parent.parent / ".claude-plugin" / "plugin.json").read_text(encoding="utf-8"))["version"]
    except (OSError, ValueError, KeyError):
        _v = "unknown"
    ap.add_argument("--version", action="version", version=f"okf-verify {_v}", help="print the version and exit")
    ap.add_argument("bundle", type=Path, help="the folder of notes to verify")
    # str, not Path: `Path("")` is `.`, so an empty value — an unset shell variable in `--repo "$REPO"` — would arrive as
    # the folder the shell is in. It is read as the string typed here and turned into a Path below, after the check.
    ap.add_argument("--repo", type=str, action="append", default=[], metavar="DIR",
                    help="repository to resolve cited SHAs in (repeatable; the only repositories searched)")
    ap.add_argument("--host-paths", action="store_true",
                    help="also look up cited absolute paths outside the bundle and the --repo folders")
    ap.add_argument("--json", action="store_true", help="print one JSON document instead of the text report")
    # INTERNAL, hidden from --help: okf-check runs `okf-verify --check-config <bundle> --manifest-dir <frozen copy>` to read the
    # okf_check block of okf-base.yaml with this tool's own reader, so the two tools cannot disagree about it (LT-52). Exit 0 when the
    # block is fine, else one error line and exit 2; one "misplaced<TAB>key<TAB>[duplicate]" line per okf_check option written
    # outside the block (duplicate: the block holds it too). --manifest-dir reads okf-base.yaml from that folder (okf-check's frozen
    # copy) while the paths it names are still resolved against the bundle.
    ap.add_argument("--check-config", action="store_true", help=argparse.SUPPRESS)
    ap.add_argument("--manifest-dir", type=Path, default=None, help=argparse.SUPPRESS)
    ap.add_argument("--strict", action="store_true",
                    help="also fail (exit 1) on UNRESOLVED and on a note with no checkable claim (alias: --strict-trust, okf-check's name for the same idea)")
    ap.add_argument("--remote", action="store_true",
                    help="ask the GitHub or GitLab API (read-only) for a SHA no searched clone holds; also okf_check.verify.remote")
    ap.add_argument("--since", metavar="REF", default=None,
                    help="compare each line citation into a file changed since this git ref with the file at the ref: "
                         "text that moved is MOVED, text that changed in place gets a warning")
    # --strict-trust is okf-check's spelling of --strict. It is rewritten here and not registered: a second option string with the
    # same prefix made the abbreviations --str, --stri and --stric "ambiguous", and they worked before. Arguments after "--" are left alone.
    argv = sys.argv[1:]
    end = argv.index("--") if "--" in argv else len(argv)
    a = ap.parse_args(["--strict" if x == "--strict-trust" else x for x in argv[:end]] + argv[end:])

    typed_bundle = a.bundle
    try:
        is_dir = _guard().path_is_dir(a.bundle)
    except OSError as e:   # a folder above it that nobody may enter: stat raises instead of answering
        print(f"error: {typed_bundle} cannot be read ({e.strerror or type(e).__name__})", file=sys.stderr)
        return 2
    if not is_dir:
        print(f"error: {typed_bundle} is not a directory", file=sys.stderr)
        return 2

    # A --repo the tool cannot use stops the run: a mistyped repository must never give a green run. The bundle is asked
    # first, as it was, so a run with both a missing bundle and a missing --repo still names the bundle. The value is
    # read as the string that was typed, because the folder it would become is not the one anybody asked for: `--repo ""`
    # (an unset shell variable) is empty, and `Path("")` is `.`, which would search the folder the shell is in. A folder
    # that is there but holds no repository is a different mistake and stays a skip with its printed reason, so only a
    # definite answer refuses here; one this process may not enter raises and the run names it 'cannot read, skipped'.
    # This path is stated twice — here, and again by git_dir() when the repository is opened — on purpose: the answer
    # decides the exit code here, and the second look is what the report lists.
    for spelled in a.repo:
        if not spelled:
            print("error: --repo is empty: pass the folder that holds the repository, or drop the flag", file=sys.stderr)
            return 2
        try:
            usable = _guard().path_is_dir(Path(spelled))
        except OSError:
            continue
        if not usable:
            print(f"error: --repo {spelled} is not a directory", file=sys.stderr)
            return 2

    # The bundle and every --repo are resolved before any layer reads them (`resolved_root`). `root_of` compares a path
    # with the root's spellings lexically, and a path under a root spelled `.` normalises to `d.md`, which never starts
    # with `./`: an unpinned line citation under that root read UNRESOLVED (exit 0) and a document name that exists twice
    # read ambiguous, where the absolute spelling gave the right verdict. The spelling the user typed stays in the
    # report: the error lines, the skipped line and the `--json` bundle field all name what was asked for.
    a.repo = [Path(spelled) for spelled in a.repo]
    typed_repos = list(a.repo)
    a.bundle = resolved_root(a.bundle)
    a.repo = [resolved_root(r) for r in a.repo]
    as_typed = {str(r): str(t) for t, r in zip(typed_repos, a.repo)}   # the report names the typed path, not the resolved one

    if a.check_config:
        try:
            data, schema = load_manifest(a.bundle, a.manifest_dir)
            if "okf_check" in data:
                check_node(data["okf_check"], schema, "okf_check", a.bundle)
                yaml11_booleans((a.manifest_dir or a.bundle) / "okf-base.yaml", schema)
        except BaseConfigError as e:
            print(f"error: {typed_bundle / 'okf-base.yaml'} {e}", file=sys.stderr)
            return 2
        inside = data.get("okf_check") if isinstance(data.get("okf_check"), dict) else {}
        for key in misplaced_keys(data, schema):
            print(f"misplaced\t{key}\t{'duplicate' if key in inside else ''}")
        return 0

    # `rglob` skips a directory it cannot read, without a word. A concept whose
    # claim was REFUTED simply vanished and the run printed "no refuted claims"
    # and exited 0 — the worst possible shape of this failure in the one tool
    # whose entire job is to separate "checked and false" from "not checked".
    # Same defect okf-check carries as G-8; found by sweeping for siblings. (G-13)
    # os.path.isdir, not Path.is_dir(): a child of a folder that lists but cannot be entered (mode 0400) made it raise, up to 3.13.
    unreadable = sorted(
        str(d) for d in [a.bundle, *(p for p in a.bundle.rglob("*") if os.path.isdir(p))]
        if not os.access(d, os.R_OK | os.X_OK)
    )
    if unreadable:
        print(f"error: {typed_bundle} contains directories this process cannot read — "
              f"no verdict is possible", file=sys.stderr)
        for d in unreadable[:3]:
            print(f"  unreadable: {d}", file=sys.stderr)
        # D-13 removed exactly this silent cap from the no-claims list, and the
        # commit that copied G-8's guard across put it straight back. (U-3)
        if len(unreadable) > 3:
            print(f"  ... and {len(unreadable) - 3} more", file=sys.stderr)
        print("  a partial scan is not 'no refuted claims'", file=sys.stderr)
        return 2

    try:
        # One cap for this process and for ignore-lib.sh, which not_ignored() runs: the bundle's setting, else the default.
        os.environ["OKF_MAX_NOTE_BYTES"] = str(_guard().note_cap(a.bundle))
    except BaseConfigError as e:
        print(f"error: {typed_bundle / 'okf-base.yaml'} {e}", file=sys.stderr)
        return 2
    def git_dir(r: Path):
        """(True, "") when `r` holds a .git; else (False, why it could not be looked at, or "" for a folder without one)."""
        try:
            return _guard().path_exists(r / ".git"), ""
        except OSError as e:   # a folder above it that nobody may enter: stat raises instead of answering
            return False, e.strerror or type(e).__name__
    looked = [(r, *git_dir(r)) for r in a.repo]
    try:
        declared_problems = declared_repos(a.bundle, [r for r, found, _ in looked if found])
        hints = misplaced_hints(a.bundle)
    except BaseConfigError as e:
        print(f"error: {a.bundle / 'okf-base.yaml'} {e}", file=sys.stderr)
        return 2
    repos, seen_repos = [], set()
    for r in (r for r, found, _ in looked if found):
        if r.resolve() not in seen_repos:  # passed twice with --repo: searched once
            seen_repos.add(r.resolve())
            repos.append(r)
    skipped = [as_typed.get(str(r), str(r)) for r, found, why in looked if not found and not why]
    unreadable = [{"path": as_typed.get(str(r), str(r)), "why": why} for r, found, why in looked if why]
    try:
        keep = not_ignored(a.bundle)
    except IgnoreRefused as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    if keep is not None:
        total = sum(1 for f in a.bundle.rglob("*.md") if f.is_file() and f.name not in RESERVED)
        left = sum(1 for k in keep if Path(k).name not in RESERVED)
        print(f"ignore: {total - left} file(s) excluded by .okfignore, {left} verified", file=sys.stderr)
        if left == 0:
            print("error: .okfignore excludes every note - nothing was verified (not a pass)", file=sys.stderr)
            return 2
    since = None
    if a.since:
        rc, top = git(a.bundle, "rev-parse", "--show-toplevel")
        if rc != 0 or not top:
            print(f"error: --since needs the bundle inside a git repository: {a.bundle} is not inside one", file=sys.stderr)
            return 2
        rc, _ = git(Path(top), "rev-parse", "--verify", "--quiet", f"{a.since}^{{commit}}")
        if rc != 0:
            print(f"error: --since {a.since}: not a commit in {top}", file=sys.stderr)
            return 2
        since = (Path(top), a.since)
    remote = a.remote or load_block(a.bundle).get("verify", {}).get("remote") is True
    results, no_claims, unrecognized = verify(a.bundle, repos, a.host_paths, since, remote)
    results = [*declared_problems, *results]

    counts = {v: sum(1 for r in results if r["verdict"] == v)
              for v in (CONFIRMED, REFUTED, UNRESOLVED)}
    moved = sum(1 for r in results if r["verdict"] == MOVED)
    if moved:   # present only when an anchored citation moved, so a report without one is unchanged
        counts[MOVED] = moved
    # --strict is sold as "for a corpus that must stay checkable", yet a corpus
    # with NOTHING checkable passed it — precisely the corpus it exists to catch.
    # Under --strict an unverifiable concept is a failure, not a free pass. (D-9)
    failed = (counts[REFUTED] > 0 or moved > 0
              or (a.strict and (counts[UNRESOLVED] > 0 or bool(no_claims))))

    shown = _guard().shown   # a name or a text field that holds a byte that is not UTF-8, a control character or a bidi control is spelled \xNN; never a whole line (its line breaks and indent are layout)

    def spelled(x):
        """--json: only a byte that is not UTF-8 is spelled (a lone surrogate is not valid JSON text); a control character in a
        quoted claim keeps its JSON escape, as before."""
        if isinstance(x, str):
            return shown(x, False)
        if isinstance(x, list):
            return [spelled(v) for v in x]
        if isinstance(x, dict):
            return {k: spelled(v) for k, v in x.items()}
        return x

    if a.json:
        report = {"bundle": str(typed_bundle), "counts": counts,
                  "no_checkable_claims": no_claims,
                  "repos_searched": [as_typed.get(str(r), str(r)) for r in repos],
                  "repos_skipped_not_git": skipped,
                  "passed": not failed, "results": results}
        if hints:   # present only when okf-base.yaml has an okf_check option outside okf_check:
            report["config_warnings"] = hints
        if unreadable:   # present only when a --repo could not be looked at: it is not "not a git repo"
            report["repos_unreadable"] = unreadable
        if unrecognized:   # present only when a no-claim note holds citation-shaped text (okf-knowledge-gate#14, part 3)
            report["unrecognized_citations"] = unrecognized
        report = spelled(report)
        # The names are spelled in full, as okf-check spells them in --json: the notes, and the path a refused file is cited by.
        report["no_checkable_claims"] = [shown(n) for n in report["no_checkable_claims"]]
        for r in report["results"]:
            r["concept"] = shown(r["concept"])
            if r["kind"] == "file":
                r["claim"] = shown(r["claim"])
        for u in report.get("unrecognized_citations", []):
            u["concept"] = shown(u["concept"])
        print(json.dumps(report, indent=2))
        return 0 if not failed else 1

    print(f"okf-verify — {shown(str(a.bundle))}")
    print(f"  repos searched: {', '.join(shown(r.name) for r in repos) if repos else 'NONE (SHAs cannot be checked)'}")
    for h in hints:
        print(f"  ! {shown(h)}")
    for s in skipped:
        print(f"  ! not a git repo, skipped: {shown(s)}")
    for u in unreadable:
        print(f"  ! cannot read, skipped: {shown(u['path'])} ({shown(u['why'])})")
    for r in results:
        mark = {CONFIRMED: "ok  ", REFUTED: "REFUTED", UNRESOLVED: "unresolved", MOVED: "MOVED"}[r["verdict"]]
        # Ellipsis, not a bare cut: a claim sliced at 48 characters read as the
        # whole claim, which matters when the reader is deciding whether the
        # verdict addressed what they wrote. (U-4)
        claim = r["claim"] if len(r["claim"]) <= 48 else r["claim"][:47] + "…"
        print(f"  {mark:11s} {shown(r['concept'])}  [{r['kind']}] {shown(claim)}")
        if r["verdict"] != CONFIRMED:
            print(f"              {shown(r['detail'])}")
        if r.get("warning"):
            print(f"              ! {shown(r['warning'])}")
    if no_claims:
        print(f"  {len(no_claims)} concept(s) carry no checkable claim — unverifiable, not verified:")
        hint = {u["concept"]: u for u in unrecognized}
        for n in no_claims[:8]:
            u = hint.get(n)
            print(f"              {shown(n)}" + (f"  ({u['count']} string(s) look like citations but match no checkable form, "
                                                  f"e.g. {shown(u['examples'][0])})" if u else ""))
        # A list that stops at 8 without saying so reads as the whole list.
        # Same class as a gate that skips a layer silently. (D-13)
        if len(no_claims) > 8:
            print(f"              ... and {len(no_claims) - 8} more "
                  f"(use --json for the full list)")
    print(f"\n  CONFIRMED {counts[CONFIRMED]}   REFUTED {counts[REFUTED]}   UNRESOLVED {counts[UNRESOLVED]}"
          + (f"   MOVED {moved}" if moved else ""))
    if counts[UNRESOLVED]:
        print("  UNRESOLVED means NOT CHECKED — it is not a soft REFUTED and must not be read as one.")
    print("  FAILED" if failed else "  no refuted claims")
    return 0 if not failed else 1


if __name__ == "__main__":
    raise SystemExit(main())
