#!/usr/bin/env bash
# okf-check — one gate over the OKF toolchain.
#
#   L0  doctor       runtimes + dependencies + version pins
#   L1  conformance  is this valid OKF?         (vendored okf_validate.py, spec layer)
#   L2  profile      is this valid OUR OKF?     (okflint + okf-base.yaml, house layer)
#   L3  staleness    is it still true?          (stale_after vs today)
#
#   The modes and flags (--selftest, --preflight, --install-deps, --duplicates, --conserve ...) are listed once, in okf_help below,
#   which is what --help prints.
#
# WHY ONE ENTRY POINT
# Three tools that must be remembered get remembered zero times. The measured
# failure of every knowledge store on this machine was never the format — it was
# the absence of something that runs without being chosen.
#
# PORTABILITY (assume a brand-new machine, assume nothing is installed)
#   - bash 3.2 only: no `declare -A`, no `mapfile`, no `${var^^}` (macOS ships 3.2)
#   - BSD and GNU `stat` both handled
#   - `jq` is OPTIONAL — JSON is parsed with python3, which L1 already requires
#   - `okflint` is OPTIONAL — L2 is SKIPPED WITH A STATED REASON, never silently
#   - the conformance checker is VENDORED — no clone, no network, no install
#
# EXIT CODES — by PRECEDENCE, not by numeric maximum.
#   5  --selftest failure            — A GATE STOPPED FIRING (the worst outcome)
#   1  L1 OKF conformance ERROR      — the bundle is not conformant OKF; or an okf_check house-rule
#                                      error (deprecated_requires, require_owner, size)
#   3  L2 house-profile ERROR        — your own rules are broken
#   2  L0/L1/L2 could not run        — a gate was unable to reach a verdict
#   6  bundle changed mid-scan       — only with --fail-on-change
#   4  L3 stale concepts             — only with --fail-stale
#   0  all gates pass
#  64  usage error                  — no bundle, an unknown flag, or a path that is not a folder
# 130  interrupted (INT)            — stopped by Ctrl-C; no verdict
# 143  terminated (TERM)            — stopped from outside; no verdict
#
# `max(rc)` was WRONG and is why this list is ordered. A bundle with a real §11
# conformance error AND an unusable manifest returned 2 — documented as "could
# not run" — so CI would retry or reinstall instead of failing the bundle. A
# verdict that was REACHED always outranks a gate that could not reach one.
#
# Usage: see okf_help below (the one list of modes and flags; plugin.test.sh S51 checks it against the argument loop).
set -uo pipefail
unset CDPATH   # an exported CDPATH makes `cd -P` print and redirect: the script lost its own lib (ticket 08)

VERSION="0.9.59"
EXIT_OK=0; EXIT_CONFORM=1; EXIT_DEP=2; EXIT_PROFILE=3; EXIT_STALE=4; EXIT_SELFTEST=5
EXIT_CHANGED=6   # bundle mutated mid-scan; only with --fail-on-change
CONCURRENT=0; FAIL_ON_CHANGE=0
# Initialised HERE, not in main(): --selftest calls the layer functions directly
# and never enters main, so declaring these there left them unbound under `set -u`.
# (Regression introduced by the summary-counter change; caught by okf-check.test.sh.)
# advise <source> <n>: count n advisories of one source. The summary line names each source's share: one finding can be
# listed by two layers (a broken link is an L1 warning and an L2 L002) and is then counted once per layer.
ADV_SRC=(); ADV_N=()
advise() {
  local i=0
  case "${2:-}" in ''|*[!0-9]*|0) return 0 ;; esac
  ADVISORIES=$((ADVISORIES + $2))
  while [ "$i" -lt "${#ADV_SRC[@]}" ]; do
    [ "${ADV_SRC[$i]}" = "$1" ] && { ADV_N[$i]=$((ADV_N[$i] + $2)); return 0; }
    i=$((i + 1))
  done
  ADV_SRC+=("$1"); ADV_N+=("$2")
}
# The sentence under a Trust finding, in the text report and as `trust_note` in --json: it is one fact, said in both places.
TRUST_NOTE='okf-check cannot prove who a person is. A human: entry is a claim in the file.'
# Said once: an .okfignore that leaves no note in means nothing was looked at, in the gate and in the conservation report.
IGNORE_ALL_WHY='.okfignore excludes every note - nothing was checked (not a pass)'
ADVISORIES=0; SKIPPED=0; TRUST_RAN=1; TRUST_FINDINGS=0; TRUST_POLICY_FAIL=0; L2_PROFILE=ran

# ---------------------------------------------------------------- locate self
# Symlink-safe without readlink -f (absent on macOS): walk the link chain. At most 40 links, as okf_real_path and
# ignore-lib.sh: bash refuses a cyclic link at exec, but $0 is read again here, so a link swapped after the start would spin.
_self="$0"; _hops=0
while [ -L "$_self" ]; do
  _hops=$((_hops + 1))
  [ "$_hops" -le 40 ] || { echo "okf-check: $0 leads through more than 40 symbolic links (a loop?) - cannot find the plugin folder" >&2; exit $EXIT_DEP; }
  _dir=$(cd -P "$(dirname "$_self")" && pwd)
  _self=$(readlink "$_self")
  case "$_self" in /*) ;; *) _self="$_dir/$_self" ;; esac
done
HERE=$(cd -P "$(dirname "$_self")" && pwd)
# A gate that cannot load its helper must not reach a verdict: with the lib absent the awk
# program failed, stderr went to /dev/null, and the empty report read as "PASS nothing expired".
# l3-lib.sh and ignore-lib.sh source note-guard-lib.sh, the one rule for which note files may be opened.
[ -r "$HERE/note-guard-lib.sh" ] || { echo "okf-check: $HERE/note-guard-lib.sh is missing - cannot tell which notes are safe to open; reinstall the plugin" >&2; exit $EXIT_DEP; }
[ -r "$HERE/l3-lib.sh" ] || { echo "okf-check: $HERE/l3-lib.sh is missing - cannot run L3; reinstall the plugin" >&2; exit $EXIT_DEP; }
. "$HERE/l3-lib.sh"
[ -z "$L3_STATUS_ERR" ] || { echo "okf-check: $L3_STATUS_ERR - cannot run L3; reinstall the plugin" >&2; exit $EXIT_DEP; }
[ -r "$HERE/ignore-lib.sh" ] || { echo "okf-check: $HERE/ignore-lib.sh is missing - cannot read .okfignore; reinstall the plugin" >&2; exit $EXIT_DEP; }
. "$HERE/ignore-lib.sh"
# The okf_check rules (successor, owner, duplicates) import their note reader from okf_notes.py inside a try: without the
# file they would switch themselves off with exit 0 (LT-56m).
[ -r "$HERE/okf_guard.py" ] || { echo "okf-check: $HERE/okf_guard.py is missing - cannot tell which notes are safe to open; reinstall the plugin" >&2; exit $EXIT_DEP; }
[ -r "$HERE/okf_notes.py" ] || { echo "okf-check: $HERE/okf_notes.py is missing - cannot run the okf_check rules; reinstall the plugin" >&2; exit $EXIT_DEP; }
# okflint runs under okf-limit.py (time, memory, the whole process tree): without it L2 failed as "manifest rejected by okflint".
[ -r "$HERE/okf-limit.py" ] || { echo "okf-check: $HERE/okf-limit.py is missing - cannot run okflint under its limits; reinstall the plugin" >&2; exit $EXIT_DEP; }
ROOT=$(cd -P "$HERE/.." && pwd)
VALIDATOR="$ROOT/vendor/okf_validate.py"
# PyYAML is vendored (pure-python, no C extension) so L1 needs nothing installed.
#
# NOT exported. `export PYTHONPATH` leaked the vendored copy into every CHILD
# process — including okflint, which ships its own newer, COMPILED PyYAML.
# Measured: okflint standalone loaded libyaml=True from its own site-packages;
# as a child of okf-check it loaded the vendored libyaml=False copy instead.
# Python resolves PYTHONPATH ahead of site-packages regardless of where the entry
# sits within the variable, so "appended" bought nothing for children.
#
# The earlier claim that "a system PyYAML wins if present" was verified only for
# this script's own import, never for anything it spawns. It is now applied per
# invocation, to the validator alone. Covered by G-2.
#
# PREPENDED, not appended. Python searches PYTHONPATH left to right, so an entry
# already in the variable outranked the vendored copy. A `yaml` module on an
# inherited PYTHONPATH then replaced the parser this gate's verdict rests on —
# G-7 demonstrates a decoy that reports every file as conformant, turning a
# bundle with no `type` key into a PASS. The pin exists to make the verdict
# reproducible; ambient environment is exactly the variance it must outrank.
# Measured cost of the pure-python loader at this scale: none (46 frontmatter
# blocks, libyaml=True 10.7 ms vs libyaml=False 10.6 ms).
VENDOR_PY="$ROOT/vendor/pyyaml"
py_with_vendor() {  # run $PY with the vendored PyYAML visible to IT ONLY
  # No bytecode: a python3 that caches beside the module (Linux does) left scripts/__pycache__/ in the installed
  # plugin, which plugin.test.sh Z-2 then reported as a dead file (0.9.9 Debian gate).
  if [ -d "$VENDOR_PY" ]; then
    PYTHONDONTWRITEBYTECODE=1 PYTHONPATH="$VENDOR_PY${PYTHONPATH:+:$PYTHONPATH}" "$PY" "$@"
  else
    PYTHONDONTWRITEBYTECODE=1 "$PY" "$@"
  fi
}
PINS="${OKF_PINNED_VERSIONS:-$ROOT/config/pinned-versions.txt}"
TEMPLATE="$ROOT/config/okf-base.yaml.template"

# What `okf-check --help` prints. It is the user's page: every mode and flag, the exit codes, the OKF_* variables the tool reads, one
# example. The maintainer notes stay in the comment at the top of this file. Not listed on purpose: --fingerprint, the seam the tests use
# to watch the change detection (plugin.test.sh S51 holds the list of what is kept out and why).
okf_help() {
  cat <<'HELP'
okf-check - check an OKF bundle: a folder of markdown notes with YAML frontmatter.

Usage:
  okf-check <bundle> [--json] [--fail-stale] [--strict-trust] [--fail-on-change]
  okf-check <bundle> --file <note>
  okf-check <bundle> --duplicates | --duplicates-body
  okf-check <bundle> --facts [NAME]
  okf-check <bundle> --conserve <ref> [--fail-lost] [--deleted FILE]
  okf-check --init-house-rules <bundle>   |   --init-ignore <bundle>
  okf-check --doctor | --selftest | --preflight | --install-deps [--yes] [--latest]

Without a mode flag, okf-check runs every layer on <bundle>:
  L0 doctor (runtimes, dependencies, version pins), L1 conformance (valid OKF), L2 house profile
  (okflint + okf-base.yaml; skipped, with the reason, when either is missing), L3 staleness
  (stale_after against today), and Trust (is a "verified by a human" claim backed up).

Checks of a bundle:
  --json              print one JSON document instead of the text report
  --fail-stale        a stale note blocks (exit 4); without it staleness is a warning
  --strict-trust      an unproven human verification and a near-miss actor (Human:dana) block (exit 1);
                      alias: --strict. Severity only: the findings are the same without it
  --fail-on-change    a bundle that changes during the scan blocks (exit 6)
  --changed <git-ref> the same checks as --file on every note changed since <git-ref> (committed, staged or untracked),
                      whoever wrote it: L1, Trust and the note-local L2 checks per changed note, and the declared counts
                      once when any markdown file of the bundle changed or was deleted; exit 2 outside a git repository
                      or for an unknown ref
  --file <note>       L1, Trust and the note-local L2 checks for one note: its house-profile findings (undeclared
                      type, a missing required key, a status outside the type's values, and R001 on the root
                      index.md) and the counts index.md declares; one line per finding, nothing when clean
                      (for edit hooks). Exits 3 where it used to exit 0
  --duplicates        list candidate duplicate notes (advisory, exit 0)
  --duplicates-body   the same, plus notes whose bodies are similar (MinHash, time-boxed)
  --facts [NAME]      list every place the okf_check.facts (or the fact NAME) are stated; a dry run, exit 0
  --conserve <ref>    every line removed since git ref <ref> must reappear: MOVED, CHANGED or LOST (advisory)
  --fail-lost         with --conserve: a LOST line blocks (exit 1)
  --deleted FILE      with --conserve: FILE declares the deletions that are intended

One run does one thing: a flag the mode you gave never reads is refused (exit 64) instead of dropped.
A gate flag is one of --fail-stale, --strict-trust and --fail-on-change; --json is not one, because it
changes the form of the report, not the verdict. A report mode (--duplicates, --duplicates-body,
--facts, --conserve) runs instead of the gate, so a gate flag beside one is refused, and so is a
second mode (a flag typed twice, and --duplicates with --duplicates-body, are one mode). --file checks
one note: it reads --strict-trust and refuses --fail-stale and --fail-on-change. --doctor, --selftest,
--preflight, --init-ignore, --init-house-rules and --install-deps run no gate, so a gate flag with one
of them is refused too. --fail-lost and --deleted are refused without --conserve for the same reason.
Two modes: the message names them in the order typed. A gate flag with a mode: the message names the
gate flag first, because the gate flag is the one that would be read by nothing. Three modes: it names
the first and the last distinct one (a repeat at the end is not a new mode); remove one and
run again.

Set-up and the machine:
  --init-house-rules <bundle>   write a starter <bundle>/okf-base.yaml (never overwrites)
  --init-ignore <bundle>        write a starter <bundle>/.okfignore (never overwrites)
  --doctor            what is installed, and whether okflint behaves
  --selftest          re-prove that every gate still fires on input that should trip it
  --preflight         the session-start check: silent when python3 and okflint are fine, else one line; never fails
  --install-deps      print the plan to install the supported okflint (changes nothing)
  --yes               with --install-deps: run the plan
  --latest            with --install-deps: the newest release instead of the pinned one
  --version, -h, --help

Exit codes (in order of precedence: a verdict that was reached outranks a gate that could not run):
    5  --selftest failed: a gate stopped firing
    1  L1 not conformant, or an okf_check house-rule error, or (with --strict-trust) a trust failure;
       also --init-ignore / --init-house-rules refusing to overwrite a file
    3  L2 house-profile error
    2  a layer could not run (a missing runtime, a timeout, an unreadable folder)
    6  the bundle changed mid-scan (only with --fail-on-change)
    4  stale notes (only with --fail-stale)
    0  every gate passed
   64  usage error: no bundle, an unknown flag, a path that is not a folder, a gate flag the given
       mode cannot read, or a second mode
  130  interrupted (Ctrl-C), no verdict
  143  terminated, no verdict

Environment variables (all optional):
  OKF_L1_TIMEOUT      120      seconds L1's validator may run in all; past it L1 is COULD NOT RUN (exit 2)
  OKF_LAYER_TIMEOUT   300      seconds the Python layers (Trust, Successor, Owner, Size, L3, --duplicates,
                               --file) may run in all; 0 or a non-number means the default, 1 is refused (exit 64)
  OKF_L2_TIMEOUT      120      seconds before a hung okflint is cut off in L2 (exit 2)
  OKF_L2_MAX_RSS_MB   2048     megabytes okflint and its children may hold before they are stopped (exit 2)
  OKF_L2_ISOLATE_MAX  200      when okflint crashes on a bundle of at most this many notes, L2 names the crashing notes
  OKF_FACTS_TIMEOUT   60       seconds the okf_check.facts patterns may run before the Facts line says COULD NOT RUN
  OKF_MEMORY_BIN      okf on PATH   the okf-memory binary for the L2 graph layer; setting it also turns the layer on
  OKF_GRAPH_TIMEOUT   60       seconds okf-memory may run before the L2 graph line says COULD NOT RUN
  OKF_SEARCH_BIN      okf on PATH   the okf search binary --doctor reports (the doc-reuse reminder uses it too)
  OKF_INSTALL_TIMEOUT 200      seconds before --install-deps stops the installer
  OKF_AUTO_INSTALL    off      1 lets --preflight run the install plan itself

Example:
  okf-check ./notes --fail-stale --strict-trust --json

See also: okf-verify (do the commits and paths a note cites still exist?) and okf-export (a vault of
[[wikilinks]] to a bundle). The README has the full reference.
HELP
}

BUNDLE=""; MODE="check"; DUP_BODY=0; JSON=0; FAIL_STALE=0; STRICT_TRUST=0; ASSUME_YES=0; USE_LATEST=0
# Initialised here too: a variable this script reads but never sets would take its value from the caller's environment,
# so an exported FAIL_LOST or DELETED_GIVEN would refuse or change a plain run the user never asked to change.
FAIL_LOST=0; DELETED_GIVEN=0
# The mode flags as the user typed them, in order. The refusal below counts DISTINCT modes, so a flag typed twice is one
# mode (`--duplicates --duplicates --duplicates` runs once, as it did before) and `--duplicates` with `--duplicates-body`
# is one mode with its body variant, a documented pair. MODE itself keeps its old meaning (the last one wins).
# MODE_FLAG_LAST is set only for a mode not seen before, so a repeat at the end of a long command line cannot make the
# message name a mode against itself (`--doctor --selftest --preflight --doctor` names --doctor and --preflight).
MODE_FLAG1=""; MODE_FLAG2=""; MODE_FLAG_LAST=""; MODE_FLAG_N=0; MODE_SEEN=" "
mode_typed() {  # <spelling as typed>
  local key="$1"
  case "$1" in --duplicates|--duplicates-body) key="the duplicates family" ;; esac
  case "$MODE_SEEN" in *" $key "*) return 0 ;; esac
  MODE_SEEN="$MODE_SEEN$key "
  MODE_FLAG_LAST="$1"
  MODE_FLAG_N=$((MODE_FLAG_N + 1))
  if [ "$MODE_FLAG_N" = 1 ]; then MODE_FLAG1="$1"; elif [ "$MODE_FLAG_N" = 2 ]; then MODE_FLAG2="$1"; fi
}
for a in "$@"; do
  case "$a" in
    --doctor)      MODE="doctor"; mode_typed "--doctor" ;;
    --selftest)    MODE="selftest"; mode_typed "--selftest" ;;
    --json)        JSON=1 ;;
    --fail-stale)  FAIL_STALE=1 ;;
    --strict-trust|--strict) STRICT_TRUST=1 ;;   # --strict: the spelling okf-verify uses for the same idea
    --file)        if [ "${_want_file:-0}" = 1 ] || [ -n "${SCOPED_FILE:-}" ]; then echo "error: --file given twice - check one note at a time" >&2; exit 64; fi
                   MODE="scoped"; mode_typed "--file"; _want_file=1 ;;   # its value is the next argument (run_scoped)
    --changed)     if [ "${_want_chref:-0}" = 1 ] || [ -n "${CHANGED_REF:-}" ]; then echo "error: --changed given twice - one ref at a time" >&2; exit 64; fi
                   MODE="changed"; mode_typed "--changed"; _want_chref=1 ;;   # its <git-ref> is the next bare argument
    --fail-on-change) FAIL_ON_CHANGE=1 ;;
    --fingerprint) MODE="fingerprint"; mode_typed "--fingerprint" ;;
    --ignore-filter) MODE="ignore-filter"; mode_typed "--ignore-filter" ;;   # internal seam: which of these note paths .okfignore excludes (okf-conserve)
    --duplicates)  MODE="duplicates"; mode_typed "--duplicates" ;;
    --duplicates-body) MODE="duplicates"; mode_typed "--duplicates-body"; DUP_BODY=1 ;;
    --facts)       MODE="facts"; mode_typed "--facts"; _want_fact=1 ;;   # an optional NAME: the next bare argument once the bundle is known
    --conserve)    MODE="conserve"; mode_typed "--conserve"; _want_ref=1 ;;  # its <ref> is the next bare argument once the bundle is known
    --fail-lost)   FAIL_LOST=1 ;;
    --deleted)     _want_del=1; DELETED_GIVEN=1 ;;
    --preflight)   MODE="preflight"; mode_typed "--preflight" ;;
    --init-ignore) MODE="init-ignore"; mode_typed "--init-ignore" ;;
    --init-house-rules) MODE="init-house-rules"; mode_typed "--init-house-rules" ;;
    --install-deps) MODE="install-deps"; mode_typed "--install-deps" ;;
    --yes)         ASSUME_YES=1 ;;
    --latest)      USE_LATEST=1 ;;
    --version)     if [ "${_want_chref:-0}" = 1 ]; then CHANGED_REF="$a"; _want_chref=0; continue; fi   # --changed --version: the ref
                   echo "okf-check $VERSION"; exit 0 ;;
    -h|--help)     if [ "${_want_chref:-0}" = 1 ]; then CHANGED_REF="$a"; _want_chref=0; continue; fi   # --changed --help: the ref is named --help
                   okf_help; exit 0 ;;
    -*)            if [ "${_want_file:-0}" = 1 ] && [ -f "$a" ]; then SCOPED_FILE="$a"; _want_file=0; continue; fi   # a note named -d.md
                   if [ "${_want_chref:-0}" = 1 ]; then CHANGED_REF="$a"; _want_chref=0; continue; fi   # a ref named -x
                   echo "unknown flag: $a" >&2; exit 64 ;;
    *)             if [ "${_want_file:-0}" = 1 ]; then SCOPED_FILE="$a"; _want_file=0; continue; fi
                   if [ "${_want_chref:-0}" = 1 ] && [ -n "$BUNDLE" ]; then CHANGED_REF="$a"; _want_chref=0; continue; fi
                   if [ "${_want_fact:-0}" = 1 ] && [ -n "$BUNDLE" ]; then FACT_NAME="$a"; _want_fact=0; continue; fi
                   if [ "${_want_del:-0}" = 1 ]; then DELETED_FILE="$a"; _want_del=0; continue; fi
                   if [ "${_want_ref:-0}" = 1 ] && [ -n "$BUNDLE" ]; then CONSERVE_REF="$a"; _want_ref=0; continue; fi
                   # A second positional silently replaced the first, so
                   # `okf-check <FAILING> <CLEAN>` examined only the last and
                   # exited 0. A glob over several bundles checked one. (R-9)
                   if [ -n "$BUNDLE" ]; then
                     echo "error: more than one bundle given ('$BUNDLE' and '$a') — check them one at a time" >&2
                     exit 64
                   fi
                   BUNDLE="$a" ;;
  esac
done

# A flag the given mode never reads used to be dropped in silence: `okf-check B --duplicates --fail-stale` ran the report
# and exited 0, and `okf-check B --fail-lost` without --conserve ran the whole gate and exited 0 with the flag unread. To
# the user both read as "the gate I asked for passed", the one answer this tool may not give wrongly. Refused at the
# command line, before any layer runs.
report_mode=""
case "$MODE" in
  duplicates) if [ "$DUP_BODY" = 1 ]; then report_mode="--duplicates-body"; else report_mode="--duplicates"; fi ;;
  facts)      report_mode="--facts" ;;
  conserve)   report_mode="--conserve" ;;
  ignore-filter) report_mode="--ignore-filter" ;;   # internal, not a user mode: a gate flag beside it would be unread
esac
# <flag> <report mode>: the flag decides a gate verdict and the mode only reports, so together the flag would be read by
# nothing. The name printed is the one the tool reads, not the spelling typed: --strict prints --strict-trust.
refuse_with_report() {
  echo "error: $1 cannot be combined with $2: a report mode replaces the gate run, so $1 would be read by nothing — run the gate and the report as two commands" >&2
  exit 64
}
# <flag> [<report mode>]: work only --conserve does (the lines that vanished since a ref). Given anywhere else the flag
# was read by nothing and the run still exited 0. These are not gate flags, so "run the gate" is the wrong advice: the
# flag needs the conservation report, and the second sentence says so.
refuse_without_conserve() {
  echo "error: $1 only works with --conserve${2:+, not with $2}: run --conserve <ref> $1, or drop the flag" >&2
  exit 64
}
# The same class one step earlier: a second mode used to replace the first in silence (`okf-check B --duplicates --facts`
# printed only the facts line and exited 0, and `--facts --duplicates` only the duplicates report), and a gate flag beside
# a mode that reads no gate flag was read by nothing (`--doctor --fail-stale` judged no freshness and exited 0; it was the
# last open item of this class in the 0.9.56 changelog). Refused at the command line, by flag TYPE and not by argument
# order, so one command line always gets one answer: a second mode first, then a gate flag with --file, then a gate flag
# with an action mode, and only then the --fail-lost / --deleted and report-mode refusals below.
# <first> <second>: the run would keep the LAST mode and drop the first, so the message names the first as the one that
# would be read by nothing.
refuse_one_run() {
  echo "error: $1 cannot be combined with $2: a run does one thing, so $1 would be read by nothing — run them as two commands" >&2
  exit 64
}
# <gate flag>: --file is a scoped gate, not a report. It checks one note and passes --strict-trust to its layer, but reads
# no other gate flag, so the report-mode text above ("a report mode replaces the gate run") would be wrong here.
refuse_gate_with_changed() {
  echo "error: $1 cannot be combined with --changed: --changed checks the changed notes and reads no gate flag, so $1 would be read by nothing — run the gate on the bundle and --changed on the commit" >&2
  exit 64
}
refuse_gate_with_file() {
  echo "error: $1 cannot be combined with --file: --file checks one note and reads no gate flag, so $1 would be read by nothing — run the gate on the bundle and --file on the note" >&2
  exit 64
}
# Two distinct modes cannot both run (the distinct count above already treats a repeated flag and the --duplicates /
# --duplicates-body pair as one mode). Two modes: the names are the two typed spellings in the order typed, the first
# being the one the run would drop. Three or more: the FIRST and the LAST distinct one typed, which is a true pair (the
# first is dropped, the last wins) and keeps the message short; a command line that long is a mistake, not a habit.
if [ "$MODE_FLAG_N" -gt 2 ]; then
  refuse_one_run "$MODE_FLAG1" "$MODE_FLAG_LAST"
elif [ "$MODE_FLAG_N" -eq 2 ]; then
  refuse_one_run "$MODE_FLAG1" "$MODE_FLAG2"
fi
# A gate flag with --file. A second mode was refused above, so MODE_FLAG1 is the only mode flag here.
if [ "$MODE_FLAG1" = "--file" ]; then
  [ "$FAIL_STALE" = 1 ]     && refuse_gate_with_file "--fail-stale"
  [ "$FAIL_ON_CHANGE" = 1 ] && refuse_gate_with_file "--fail-on-change"
fi
# A gate flag with --changed. --changed is a scoped gate over several notes: it passes --strict-trust through to
# each note's check, exactly as --file does, and reads no other gate flag.
if [ "$MODE_FLAG1" = "--changed" ]; then
  [ "$FAIL_STALE" = 1 ]     && refuse_gate_with_changed "--fail-stale"
  [ "$FAIL_ON_CHANGE" = 1 ] && refuse_gate_with_changed "--fail-on-change"
fi
# --changed prints text lines, one per finding; a JSON document cannot carry them (the --file rule).
[ "$MODE" = changed ] && [ "$JSON" = 1 ] && { echo "error: --changed prints text lines; --json is not supported with it" >&2; exit 64; }
# A gate flag with any other mode that reads no gate flag. The report modes keep the text below, which explains that the
# report replaces the gate run, and --file is handled above (it reads --strict-trust, so that one is never refused).
case "$MODE_FLAG1" in
  ""|"--duplicates"|"--duplicates-body"|"--facts"|"--conserve"|"--ignore-filter"|"--file"|"--changed") ;;
  *) [ "$FAIL_STALE" = 1 ]     && refuse_one_run "--fail-stale" "$MODE_FLAG1"
     [ "$STRICT_TRUST" = 1 ]   && refuse_one_run "--strict-trust" "$MODE_FLAG1"
     [ "$FAIL_ON_CHANGE" = 1 ] && refuse_one_run "--fail-on-change" "$MODE_FLAG1" ;;
esac
if [ "$MODE" != conserve ]; then
  [ "$FAIL_LOST" = 1 ]     && refuse_without_conserve "--fail-lost" "$report_mode"
  [ "$DELETED_GIVEN" = 1 ] && refuse_without_conserve "--deleted" "$report_mode"
fi
if [ -n "$report_mode" ]; then
  [ "$FAIL_STALE" = 1 ]     && refuse_with_report "--fail-stale" "$report_mode"
  [ "$STRICT_TRUST" = 1 ]   && refuse_with_report "--strict-trust" "$report_mode"
  [ "$FAIL_ON_CHANGE" = 1 ] && refuse_with_report "--fail-on-change" "$report_mode"
fi

PY=""
for c in python3 python; do command -v "$c" >/dev/null 2>&1 && { PY="$c"; break; }; done

# MIRROR_ROOT is set only when a .okfignore made the layers read a filtered copy; the report must
# name the bundle the user pointed at, never the temp copy.
MIRROR_ROOT=""
L2_MIRROR_ROOT=""
L2_SRC=""   # the bundle as the user gave it: where L2 looks for dangling links when LAYER_BUNDLE is a copy
# esc_line <text> — prints the text and a newline, with every byte that is not UTF-8, every control character (ESC, CR, TAB,
# the C1 set) and every bidi control (U+061C, U+200E/F, U+202A-E, U+2066-9) spelled \xNN, as okf_guard.shown spells a note name in --json. A note name can hold both, and an ESC byte from a
# name would reach the terminal as an escape sequence. The common line (printable ASCII and well-formed UTF-8 without C1
# controls; line breaks stay) is printed as it is, by one regex in the C locale; any other goes through `okf_guard.py show`.
# Without python the controls become `?` (a byte that is not UTF-8 stays). A regex the shell cannot compile fails the match,
# which sends the line down the slow path: never a raw line by mistake.
printf -v OKF_PLAIN_RE '^([ -~\n]|\xc2[\xa0-\xbf]|[\xc3-\xd7\xd9-\xdf][\x80-\xbf]|\xd8[\x80-\x9b\x9d-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|\xe2\x80[\x80-\x8d\x90-\xa9\xaf-\xbf]|\xe2\x81[\x80-\xa5\xaa-\xbf]|\xe2[\x82-\xbf][\x80-\xbf]|[\xe1\xe3-\xec\xee\xef][\x80-\xbf][\x80-\xbf]|\xed[\x80-\x9f][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf3][\x80-\xbf][\x80-\xbf][\x80-\xbf]|\xf4[\x80-\x8f][\x80-\xbf][\x80-\xbf])*$'
esc_line() {
  local LC_ALL=C
  if [[ $1 =~ $OKF_PLAIN_RE ]]; then printf '%s\n' "$1"
  elif [ -n "${PY:-}" ] && [ -r "$HERE/okf_guard.py" ]; then printf '%s\n' "$1" | "$PY" "$HERE/okf_guard.py" show
  else printf '%s\n' "$1" | tr '\000-\011\013-\037\177' '?'; fi
}
# say also notes the layer of every "<layer>   COULD NOT RUN" line, for --json layers_not_run (the layer column ends at two spaces).
say()  { case "$*" in "  "[!\ ]*"  COULD NOT RUN"*) local _l="${*#  }"; record notrun "${_l%%  *}" ;; esac
  [ "$JSON" -eq 1 ] && return 0; local m="$*" _r _rr
  # The copy is named by its real path in okflint's messages (macOS: /var is a link to /private/var). That spelling goes first:
  # cutting the linked spelling out of it left a leading /private in front of the bundle's path.
  for _r in "$MIRROR_ROOT" "$L2_MIRROR_ROOT"; do
    [ -n "$_r" ] || continue
    _rr=${TMP_REAL:-$TMP}${_r#"$TMP"}
    m=${m//"$_rr"/"$BUNDLE"}; m=${m//"$_r"/"$BUNDLE"}
  done
  esc_line "$m"; }
# record <kind> <text> — one finding for --json (kind: error, stale, l2, skipped). Appends to a file, so it also works
# inside `| while read` pipelines. The text lines of the human report stay untouched.
record() { printf '%s\t%s\n' "$1" "$(printf '%s' "$2" | tr '\n\t' '  ')" >> "$TMP/findings.tsv" 2>/dev/null; return 0; }
# emit_json <exit> — the ONE place --json is printed, so every exit path carries the same keys. The bundle path
# goes through a real JSON encoder: a path with a double quote used to produce invalid JSON.
emit_json() {
  local code="$1" _cd _ign _w _t _b _f
  if   [ "${FP_DEGRADED:-0}" -eq 1 ]; then _cd=degraded
  elif [ "${CONCURRENT:-0}"  -eq 1 ]; then _cd=changed
  else _cd=ok; fi
  _ign=""; [ -n "${IGNORED:-}" ] && _ign=",\"ignored\":$IGNORED"
  _w="[]"; [ -s "$TMP/l1warn.json" ] && _w=$(cat "$TMP/l1warn.json")
  # Warnings other layers recorded (the Size layer's) follow the L1 ones in the same list; nothing recorded, nothing changes.
  if [ -n "$PY" ] && awk -F'\t' '$1=="warning"{f=1} END{exit !f}' "$TMP/findings.tsv" 2>/dev/null; then
    _w=$(OKF_SCRIPTS_DIR="$HERE" "$PY" - "$_w" "$TMP/findings.tsv" <<'PY'
import json, os, sys
sys.path.insert(0, os.environ["OKF_SCRIPTS_DIR"])
from okf_guard import shown
out = json.loads(sys.argv[1])
# surrogateescape + shown: a note name that is not UTF-8 reads as `\xff` here, not as U+FFFD (errors="replace")
for line in open(sys.argv[2], encoding="utf-8", errors="surrogateescape").read().splitlines():
    kind, _, text = line.partition("\t")
    if kind == "warning":
        out.append(shown(text))
print(json.dumps(out))
PY
)
  fi
  _t="[]"; [ -s "$TMP/trust.json" ] && _t=$(cat "$TMP/trust.json"); [ "${TRUST_RAN:-1}" -eq 0 ] && _t=null
  _tn=""; [ "${TRUST_FINDINGS:-0}" -gt 0 ] && _tn=",\"trust_note\":\"$TRUST_NOTE\""   # present only beside a human: finding, as the text line is
  if [ -n "$PY" ]; then
    _b=$(printf '%s' "$BUNDLE" | "$PY" -c 'import json,sys; sys.path.insert(0, sys.argv[1]); from okf_guard import shown; sys.stdout.write(json.dumps(shown(sys.stdin.read())))' "$HERE")
    _f=$(OKF_SCRIPTS_DIR="$HERE" OKF_SIZES_JSONL="$TMP/sizes.jsonl" OKF_FACTS_JSONL="$TMP/facts.jsonl" OKF_SYMLINKED_LST="$TMP/symlinked-folders.lst" OKF_GRAPH_JSON="$TMP/graph.json" OKF_STOP_WHY="${STOP_WHY:-}" OKF_L2_CRASHED="${#L2_CRASHED[@]}" "$PY" - "$TMP/findings.tsv" "$TMP/l2parsed.txt" "${L2_PROFILE:-ran}" "$BUNDLE" "${MIRROR_ROOT:-}" "${L2_MIRROR_ROOT:-}" <<'PY'
import json, os, sys
sys.path.insert(0, os.environ["OKF_SCRIPTS_DIR"])
from okf_guard import shown
# Layers that read a filtered copy (.okfignore, crash isolation) hand okflint the copy's path, and some of its messages
# print it (R201: "reserved file missing in <root>"). The report names the bundle the user pointed at; the copy is
# also spelled by its real path (macOS /var -> /private/var), so both spellings go.
roots = set()
for r in sys.argv[5:]:
    if r:
        roots.update((r, os.path.realpath(r)))
def unmirror(t):
    for r in sorted(roots, key=len, reverse=True):
        t = t.replace(r, sys.argv[4])
    return t
out = {"errors": [], "stale": [], "l2_findings": [], "skipped": [], "lifecycle": [], "l2_warnings": None, "l2_by_rule": {}, "l2_advisories": [], "layers_not_run": []}
key = {"error": "errors", "stale": "stale", "l2": "l2_findings", "skipped": "skipped", "lifecycle": "lifecycle", "notrun": "layers_not_run"}
# The L2 advisory totals the text prints ("138 warning(s), by rule: S202 x136, L002 x2"); null when L2 did not run (okf-knowledge-gate#2).
# l2_profile stays could_not_run when okflint crashed on some notes, but the text still lists the advisories of the notes it checked, so --json does too.
if sys.argv[3] == "ran" or int(os.environ.get("OKF_L2_CRASHED") or 0) > 0:
    try:
        rows = open(sys.argv[2], encoding="utf-8", errors="replace").read().splitlines()
        out["l2_warnings"] = int(rows[0].split()[1])
        for r in rows[1:]:
            if r.startswith("C|"):
                _, code, n = r.split("|")
                out["l2_by_rule"][code] = int(n)
            elif r.startswith("W|"):
                out["l2_advisories"].append(r[2:])
            elif r.startswith("H|"):
                out["l2_hint"] = r[2:]   # present only when the text prints a wikilink_root hint
        # A cut is announced with its count, like the text report's "and N more" lines (G-11); l2_warnings keeps the total.
        # 200: a CI job reads this key whole, and the other detail dumps cut at 3 to 12 lines.
        cap = 200
        if len(out["l2_advisories"]) > cap:
            n = len(out["l2_advisories"]) - cap
            out["l2_advisories"] = out["l2_advisories"][:cap] + ["... and %d more (l2_warnings has the total)" % n]
    except (OSError, IndexError, ValueError):
        pass
try:
    lines = open(sys.argv[1], encoding="utf-8", errors="surrogateescape").read().splitlines()
except OSError:
    lines = []
misplaced = []
for line in lines:
    kind, _, text = line.partition("\t")
    if kind in key:
        if kind != "notrun" or text not in out["layers_not_run"]:   # a layer that prints COULD NOT RUN twice is named once
            out[key[kind]].append(text)
    elif kind == "misplaced":
        misplaced.append(text)
for k, v in out.items():
    if isinstance(v, list):
        out[k] = [shown(unmirror(t)) for t in v]
# Present only when a key was found, so a report without one is unchanged.
if misplaced:
    out["misplaced_keys"] = [{"key": m, "belongs": "okf_check." + m} for m in misplaced]
# Present only when okf_check.size is on: each measured note's body size and the limits (okf-knowledge-gate#17).
try:
    rows = open(os.environ.get("OKF_SIZES_JSONL", ""), encoding="utf-8").read().splitlines()
    out["sizes"] = [json.loads(r) for r in rows if r]
except (OSError, ValueError):
    pass
# Present only when the optional okf-memory layer ran: its orphans and broken concept links.
try:
    out["l2_graph"] = json.load(open(os.environ.get("OKF_GRAPH_JSON", ""), encoding="utf-8"))
except (OSError, ValueError):
    pass
# Present only when a symlinked folder was left out: the paths the text report names on its symlinks line (F-6).
try:
    rows = open(os.environ.get("OKF_SYMLINKED_LST", ""), encoding="utf-8", errors="surrogateescape").read().splitlines()
    if rows:
        out["symlinked_folders"] = [shown(r) for r in rows]
except OSError:
    pass
# Present only when okf_check.facts is set: every statement of a declared fact and whether it agrees (okf-knowledge-gate#15).
try:
    rows = open(os.environ.get("OKF_FACTS_JSONL", ""), encoding="utf-8").read().splitlines()
    out["facts"] = [json.loads(r) for r in rows if r]
except (OSError, ValueError):
    pass
# Present only on a run that stopped before its layers (stop_json): why.
if os.environ.get("OKF_STOP_WHY"):
    out["reason"] = os.environ["OKF_STOP_WHY"]
print(json.dumps(out)[1:-1])
PY
)
  else
    _b="\"${BUNDLE//\"/\\\"}\""
    _f='"errors":[],"stale":[],"l2_findings":[],"skipped":[],"lifecycle":[],"l2_warnings":null,"l2_by_rule":{},"l2_advisories":[],"layers_not_run":[]'
    [ -z "${STOP_WHY:-}" ] || _f="${_f%\"layers_not_run\":[]}\"layers_not_run\":[\"$STOP_LAYER\"],\"reason\":\"$STOP_WHY\""   # fixed texts without a quote or a backslash
  fi
  printf '{"bundle":%s,"exit":%d,"l1_errors":%s,"l1_warnings":%s,"concepts":%s,"change_detection":"%s"%s,"warnings":%s,"trust_findings":%s%s,"l2_profile":"%s",%s}\n' \
    "$_b" "$code" "${L1_ERR:-null}" "${L1_WARN:-null}" "${L1_CONCEPTS:-null}" "$_cd" "$_ign" "$_w" "$_t" "$_tn" "${L2_PROFILE:-ran}" "$_f"
}
# say_capped <limit> <indent>  — lines on stdin, capped, and HONEST about it.
# Four dumps cut at 10-12 lines with no note of the cut: a reader sees twelve
# §11 errors and concludes there are twelve. Same silent-cap defect fixed in
# okf-verify's no-claims list (D-13) and never applied here. Everything still
# goes through say(), so --json stays clean (R-3). (G-11)
say_capped() {
  local limit="$1" indent="$2" buf total line _grc
  buf="$TMP/capped.$$"
  cat > "$buf"
  # `grep -c` PRINTS 0 and EXITS 1 when nothing matches, so `|| echo 0` appended a
  # second zero and `[ "$total" -gt ... ]` died with "integer expression expected".
  # grep exits 1 for "no match" and 2 for "could not read" — one variable was
  # carrying both, so a grep that FAILED became "0 lines" and silently suppressed
  # the "and N more" line. That is lessons/shell-or-swallows-errors.md exactly:
  # one exit code with two meanings, failing OPEN in the direction of looking
  # clean. Branch on the code; never infer a count from an empty stdout.
  total=$(grep -c . "$buf" 2>/dev/null); _grc=$?
  case "$_grc" in
    0) ;;                 # matched: $total is the real count
    1) total=0 ;;         # genuinely empty
    *) total=-1 ;;        # grep itself failed — we do NOT know the count
  esac
  while IFS= read -r line; do say "${indent}${line}"; done < <(head -"$limit" "$buf")
  if [ "$total" -lt 0 ]; then
    say "${indent}... and an unknown number more — the detail buffer could not be read"
  elif [ "$total" -gt "$limit" ]; then
    say "${indent}... and $((total - limit)) more (use --json for all of them)"
  fi
  rm -f "$buf"
  return 0
}
# err_capped — say_capped's twin for STDERR. The readability guards fire before
# any layer runs, so their output is not part of the --json report and must not
# go through say(); the honesty rule is identical. (U-1)
err_capped() {
  local limit="$1" indent="$2" buf total line _grc
  buf="$TMP/errcapped.$$"
  cat > "$buf"
  # grep exits 1 for "no match" and 2 for "could not read" — one variable was
  # carrying both, so a grep that FAILED became "0 lines" and silently suppressed
  # the "and N more" line. That is lessons/shell-or-swallows-errors.md exactly:
  # one exit code with two meanings, failing OPEN in the direction of looking
  # clean. Branch on the code; never infer a count from an empty stdout.
  total=$(grep -c . "$buf" 2>/dev/null); _grc=$?
  case "$_grc" in
    0) ;;                 # matched: $total is the real count
    1) total=0 ;;         # genuinely empty
    *) total=-1 ;;        # grep itself failed — we do NOT know the count
  esac
  while IFS= read -r line; do esc_line "$indent$line" >&2; done < <(head -"$limit" "$buf")
  # only the leading WHITESPACE of the item prefix, never the label itself:
  # "unreadable: ... and 2 more" reads as a filename called "... and 2 more".
  if [ "$total" -lt 0 ]; then
    printf '%s... and an unknown number more — the detail buffer could not be read\n' "${indent%%[! ]*}" >&2
  elif [ "$total" -gt "$limit" ]; then
    printf '%s... and %s more\n' "${indent%%[! ]*}" "$((total - limit))" >&2
  fi
  rm -f "$buf"
  return 0
}
pin_of() { [ -f "$PINS" ] && awk -v k="$1" '$1==k{print $2; exit}' "$PINS"; }

# --- concurrency detection (E-7) --------------------------------------------
# The layers run in sequence, so a write landing between them yields ONE report
# built from TWO different bundle states. Proven reproducibly: on a 40-concept
# bundle a file written 0.2s in was counted by L3 and missed by L1, and the
# report claimed a stable verdict anyway.
#
# We cannot lock another agent's writes and should not try. What we CAN do is
# refuse to present a point-in-time reading as a stable one — the same rule
# lessons/negative-claims-state-scope.md applies to negatives: state the scope.
# R-6 made the bundle ROOT fail closed and stopped there. Every scan below then
# used `find … 2>/dev/null`, which swallows a permission error in any SUBTREE:
# L1 counted the concepts it could see, L3 announced "nothing expired", and the
# run exited 0 over a directory nobody was allowed to read — with a concept
# expired since 2000 sitting inside it. A partial read presented as a verdict.
#
# Tests -r AND -x: a directory needs both to be listed and descended.
#
# Uses find's own LISTING, not its stderr. With `-L`, a dangling symlink also
# writes to stderr, and E-7a requires those to be skipped rather than fatal —
# keying on stderr would trade this fail-open for that regression. (G-8)
# NUL-delimited: reading newline-delimited split a directory whose NAME contains
# a newline into fragments, none of which exist, so every such bundle was
# declared unreadable and failed closed — R-7's own scenario, broken by the fix
# for G-8. Caught by R-7 before it shipped, which is what R-7 is for.
unreadable_dirs() {
  find -H "$1" -type d -print0 2>/dev/null | while IFS= read -r -d '' d; do   # -H: the folders the layers read (okf_md_files)
    { [ -r "$d" ] && [ -x "$d" ]; } || printf '%s\n' "$d"
  done | sort          # find's order varies run to run; a gate's output should not
}

# not_a_dir <bundle>: the error and exit for a <bundle> that `[ -d ]` refused. `[ -d ]` is false both for a missing path and for
# a path below a folder nobody may enter; ls says which. The second is "not readable", exit 2 as an unreadable bundle is (R-6);
# a missing path stays "not a directory", exit 64.
not_a_dir() {
  case $(LC_ALL=C ls -d -- "$1" 2>&1 >/dev/null) in   # not a pipe into grep -q: pipefail would read ls's own failure
    *'Permission denied'*)
      esc_line "error: $1 is not readable — cannot reach a verdict (this is not a pass)" >&2
      exit $EXIT_DEP;;
  esac
  esc_line "error: $1 is not a directory" >&2
  exit 64
}

# report_folder_links <bundle>: name the symlinked folders no layer enters (okf_md_files in l3-lib.sh, S8-N1), so
# notes behind them are left out on the record, never silently. Silent when there are none.
report_folder_links() {
  local links n l
  links=$(okf_folder_links "$1")
  # A folder link that .okfignore excludes is out of the bundle on purpose: not named (F-6).
  if [ -n "$links" ] && okfignore_present "$1" && { okfignore_load "$1" 2>/dev/null; [ $? -ne 2 ]; }; then
    links=$(printf '%s\n' "$links" | while IFS= read -r l; do okfignore_match "$l" dir || printf '%s\n' "$l"; done)
  fi
  [ -n "$links" ] || return 0
  printf '%s\n' "$links" > "$TMP/symlinked-folders.lst"   # --json symlinked_folders
  n=$(printf '%s\n' "$links" | grep -c .)
  say "  symlinks         $n symlinked folder(s) not entered (an alias of a folder in the bundle, or outside it):"
  printf '%s\n' "$links" | say_capped 10 "                   "
}

# resolve_note_cap <bundle>: put the effective okf_check.max_note_bytes in OKF_MAX_NOTE_BYTES for every layer and helper
# (the bundle's setting, else the default in config/okf-check-block.json). The value is recomputed, never trusted from the
# caller's environment. A schema that cannot be read is exit 2: without the cap no note can be judged safe to open.
resolve_note_cap() {
  local cap
  [ -n "$PY" ] || { echo "okf-check: python3 is missing - the note size cap cannot be resolved" >&2; return $EXIT_DEP; }
  cap=$(OKF_SCRIPTS_DIR="$HERE" OKF_VENDOR_DIR="$ROOT/vendor" py_with_vendor -c '
import os, sys
sys.path[:0] = [os.environ["OKF_SCRIPTS_DIR"], os.environ["OKF_VENDOR_DIR"]]
import okf_guard
print(okf_guard.note_cap(sys.argv[1], env=False))' "$1" 2>/dev/null)
  case "$cap" in ''|*[!0-9]*) echo "okf-check: cannot read okf_check.max_note_bytes (config/okf-check-block.json is unreadable)" >&2; return $EXIT_DEP ;; esac
  OKF_MAX_NOTE_BYTES="$cap"; export OKF_MAX_NOTE_BYTES
}

# report_refused <list>: the one place a refused note is reported (okf_refused_notes writes the list). They are findings of
# their own, not L1 errors of a layer, because no layer opened them: each is named once, exit 1 like any bundle defect.
# A FOLDER named like a note is not a defect (it cannot hang a reader and is not a note): it is a WARN line and an advisory,
# and the exit code does not change (lead decision).
report_refused() {
  local rec why rel nfail=0 nwarn=0
  [ -s "$1" ] || return 0
  : > "$TMP/refused.fail"; : > "$TMP/refused.warn"
  while IFS= read -r -d '' rec; do
    why=${rec%%$'\t'*}; rel=${rec#*$'\t'}
    rel=$(printf '%s' "$rel" | tr '\n\r\t' '   ')
    if [ "$why" = "$OKF_FOLDER_WHY" ]; then
      nwarn=$((nwarn+1)); printf '%s — %s: skipped\n' "$rel" "$why" >> "$TMP/refused.warn"
    elif [ "$why" = "$OKF_OUTSIDE_WHY" ]; then   # the wording of the finding is "points outside the bundle: not read"
      nfail=$((nfail+1)); record error "$rel — $why: not read"; printf '%s — %s: not read\n' "$rel" "$why" >> "$TMP/refused.fail"
    else
      nfail=$((nfail+1)); record error "$rel — $why: skipped"; printf '%s — %s: skipped\n' "$rel" "$why" >> "$TMP/refused.fail"
    fi
  done < "$1"
  if [ "$nfail" -gt 0 ]; then
    say "  Refused notes    FAIL   $nfail path(s) no layer opened (not a regular file, over $OKF_MAX_NOTE_BYTES bytes, or outside the bundle):"
    say_capped 12 "                   " < "$TMP/refused.fail"
    worse_other $EXIT_CONFORM
  fi
  if [ "$nwarn" -gt 0 ]; then
    advise "Skipped folders" "$nwarn"
    say "  Skipped folders  WARN   $nwarn folder(s) named like a note are not notes and were skipped (the exit code is unchanged):"
    say_capped 12 "                   " < "$TMP/refused.warn"
  fi
}

# rank: the precedence of two exit codes, not max() (#R-4). `worst=max(rc)` returned 2 ("could not run") for a bundle that
# had BOTH a real §11 conformance error and an unusable manifest, so CI would retry or reinstall instead of failing the
# bundle. A verdict that was REACHED always outranks a gate that could not reach one. Used by the whole-bundle gate and by
# `--file`, which combines three verdicts.
rank() { case "$1" in 0) echo 0;; 4) echo 1;; 6) echo 2;; 2) echo 3;; 3) echo 4;; 1) echo 5;; 5) echo 6;; *) echo 7;; esac; }
# worst_rc <code...>: the highest-precedence code of the list.
worst_rc() { local w=0 c; for c in "$@"; do [ "$(rank "$c")" -gt "$(rank "$w")" ] && w=$c; done; echo "$w"; }

# scoped_profile <bundle> <rel>: the house-profile findings of ONE note (part a). okflint runs on a mirror holding the
# bundle's okf-base.yaml and this one note, so another note's findings cannot leak in and the run stays small (86-89 ms on
# 168- and 1000-note bundles, second Mac). Prints one "<rel>: L2 profile error: <code> <message>" line per finding, which
# keeps okflint's own code and wording. Exit 0 nothing to report, 3 findings, 2 could not reach a verdict (stderr says why).
scoped_profile() {
  local bundle="$1" rel="$2" manifest="$1/okf-base.yaml" rc mir out
  [ -f "$manifest" ] || return 0                 # no house rules: nothing to check
  if ! command -v okflint >/dev/null 2>&1; then
    echo "okf-check: okflint is not installed, so the house profile of $(rel_shown "$rel") was not checked" >&2
    return 0
  fi
  mir="$TMP/scoped-l2"; rm -rf "$mir"; mkdir -p "$mir"
  cp "$manifest" "$mir/okf-base.yaml"
  mkdir -p "$(dirname "$mir/$rel")" && cp "$bundle/$rel" "$mir/$rel" || return 2
  local l2limit="${OKF_L2_TIMEOUT:-120}"; case "$l2limit" in ''|*[!0-9]*|0) l2limit=120;; esac
  run_limited "$l2limit" "$TMP/scoped-l2.out" sh -c 'cd "$1" && exec okflint validate . --manifest okf-base.yaml --json' _ "$mir"; rc=$?
  cat "$TMP/scoped-l2.out" "$TMP/scoped-l2.out.err" > "$TMP/scoped-l2.txt" 2>/dev/null
  [ -s "$TMP/scoped-l2.out.limit" ] && { echo "okf-check: okflint was stopped on $rel (time or memory)" >&2; return 2; }
  case "$rc" in
    0|1) ;;
    *)   echo "okf-check: okflint exited $rc on $(rel_shown "$rel"), so its house profile was not checked" >&2; return 2 ;;
  esac
  out=$(PYTHONDONTWRITEBYTECODE=1 OKF_SCRIPTS_DIR="$HERE" "$PY" - "$TMP/scoped-l2.txt" "$rel" "$rc" <<'PYEOF'
import json, os, sys
sys.path.insert(0, os.environ["OKF_SCRIPTS_DIR"])
from okf_guard import shown
rel, okrc = sys.argv[2], int(sys.argv[3]) if len(sys.argv) > 3 else 0
raw = open(sys.argv[1], encoding="utf-8", errors="surrogateescape").read()
# okflint may print a banner before the JSON; try every candidate start until one yields a LIST (the rule __l2_core uses).
# No list at all is NOT "no findings": the tool said it had a verdict and printed something else (a version-skewed format,
# a crash's banner). Exit 3 for that, so the caller fails closed instead of reading a non-report as a clean note.
doc, i, parsed = [], raw.find("["), False
while i != -1:
    try:
        doc = json.loads(raw[i:])
        parsed = isinstance(doc, list)
        break
    except ValueError:
        i = raw.find("[", i + 1)
    doc = []
# The gate's own rule, not a second one: a report is a findings list only when EVERY entry is a finding (code, tier, file),
# and exit 1 with an empty list said there WERE findings, so an empty parse is a non-report too (the gate says "reported
# findings (exit 1) but none parsed as errors" and fails closed there).
entries = doc if parsed else []
well = all(isinstance(e, dict) and all(k in e for k in ("code", "tier", "file")) for e in entries)
if not parsed or not well or (okrc == 1 and not entries):
    sys.exit(3)
found = 0
for e in entries:
    code, tier, f, msg = e.get("code"), e.get("tier"), e.get("file"), e.get("message")
    # The note's own profile-tier findings, plus okflint's R001 on the root index.md (tier core): --file must never pass
    # what the gate fails (lead decision 3).
    if (f == rel and tier == "profile") or (rel == "index.md" and code == "R001"):
        print(f"{shown(rel)}: L2 profile error: {shown(code)} {shown(msg)}")
        found = 1
sys.exit(found)
PYEOF
  ); rc=$?
  [ -n "$out" ] && printf '%s\n' "$out"
  case "$rc" in
    0) return 0 ;;
    1) return $EXIT_PROFILE ;;
    3) echo "okf-check: okflint printed no findings list for $(rel_shown "$rel"), so its house profile was not checked" >&2; return 2 ;;
    *) echo "okf-check: the house profile of $(rel_shown "$rel") could not be read (exit $rc)" >&2; return 2 ;;
  esac
}

# scoped_index <bundle> <rel> [keep-list] [ignored-list]: the note-local index findings (part a): the declared counts, in the gate's own wording.
# The "is this note listed in index.md" check was dropped after three review rounds of link-syntax false verdicts (lead
# decision, round 3): the gate has no listed check either, and the count already catches a note added without its line.
# Prints "index.md: L2 index error: ..." lines. Exit 0 clean, 3 findings, 2 the counts were not evaluated.
scoped_index() {
  local bundle="$1" rel="$2" keep="${3:-}" ig="${4:-}" out ec l n first
  # A folder, a device or a DANGLING SYMLINK (-L: -e alone says "nothing here") named index.md leaves the counts
  # unevaluated: say so by name rather than reading "no index.md I can parse" as "nothing to report". The gate fails such
  # a bundle (its profile reports the reserved file missing, exit 3); --file has no note-local claim to make, so it is
  # exit 2 ("not checked"), not 3.
  if { [ -e "$bundle/index.md" ] || [ -L "$bundle/index.md" ]; } && [ ! -f "$bundle/index.md" ]; then
    echo "okf-check: $bundle/index.md is not a regular file, so the index checks for $rel were not run" >&2
    return 2
  fi
  [ -f "$bundle/index.md" ] || return 0
  [ -n "$PY" ] || return 0
  # Under the watchdog with the okflint budget: the edit hook kills the whole check at its own 4 s and goes silent — a
  # limit here names itself instead.
  local l2limit="${OKF_L2_TIMEOUT:-120}"; case "$l2limit" in ''|*[!0-9]*|0) l2limit=120;; esac
  # The keep-list is the set .okfignore keeps — the same notes the gate counts on its mirror, so the two runs cannot
  # disagree about a count that covers an ignored note.
  local -a rec=( "$HERE/okf-index-reconcile.py" "$bundle" "--scan" )
  [ -n "$keep" ] && rec+=( "$keep" )
  [ -n "$keep" ] && [ -n "$ig" ] && rec+=( "$ig" )
  run_limited "$l2limit" "$TMP/scoped-index.out" "$PY" "${rec[@]}"; ec=$?
  out=""
  [ -f "$TMP/scoped-index.out" ] && out=$(<"$TMP/scoped-index.out")
  # ANOMALY: the count set is not certain (a note the full run refuses or aliases, not excluded by the ignore rules).
  # One named line, exit 2 — fail closed, never a wrong verdict (review redesign).
  case "$out" in ANOMALY\ *)
    n=${out#ANOMALY *}; first=${n#* }; n=${n%% *}
    echo "okf-check: $n note(s) the full run refuses or aliases (first: $(rel_shown "$first")), so the declared counts for $(rel_shown "$rel") were not checked" >&2
    return 2 ;;
  esac
  case "$ec" in
    0|1) : ;;
    143|137) echo "okf-check: $(rel_shown "$rel") was not checked (the index reconciler passed the OKF_L2_TIMEOUT limit)" >&2; return 2 ;;
    *) echo "okf-check: $(rel_shown "$rel") was not checked (the index reconciler could not read index.md, exit $ec)" >&2; return 2 ;;
  esac
  # Exit 1 with no MISMATCH printed is a crash, not a verdict — the same rule run_scoped applies to an L1 run (r3).
  if [ "$ec" -eq 1 ] && ! grep -q '^MISMATCH ' <<<"$out"; then
    echo "okf-check: $(rel_shown "$rel") was not checked (the index reconciler exited 1 and printed no count)" >&2
    return 2
  fi
  printf '%s\n' "$out" | while IFS= read -r l; do
    case "$l" in
      MISMATCH\ *) esc_line "index.md: L2 index error: ${l#MISMATCH }" ;;
    esac
  done
  [ "$ec" -eq 1 ] && return $EXIT_PROFILE
  return 0
}

# changed_one <path-relative-to-repo-root> [deleted]: fold one git-changed path into the run's lists. Sets CH_MD (a
# markdown file of the bundle changed or was deleted), CH_FIRST (the first such path, for the count check's messages) and
# appends existing notes to CH_NOTES. Every path arrives inside the bundle (both streams carry the bundle pathspec and
# ls-files lists only the cwd subtree); -z keeps every odd name intact.
changed_one() {
  local rel="$1"
  # Both git streams carry the bundle pathspec, and ls-files lists only the cwd subtree, so every path arrives inside
  # the bundle; the strip makes it bundle-relative. A markdown check then keeps notes only.
  case "$rel" in "$CH_PREFIX"*) rel=${rel#"$CH_PREFIX"} ;; esac
  case "$rel" in *.md) ;; *) return 0 ;; esac
  CH_MD=1
  [ -n "$CH_FIRST" ] || CH_FIRST="$rel"
  [ -f "$CH_BUNDLE/$rel" ] && CH_NOTES+=( "$rel" )
  return 0
}

# chg_git: every git call --changed makes. The bundle's own config is attacker-chosen (an extracted archive can carry
# core.fsmonitor, which runs a program on any worktree scan, or filter drivers assigned by an attribute file), so the
# monitor is off, the diff consults no external diff drivers or textconv, and attribute lookup is pinned: GIT_ATTR_SOURCE
# points it at the empty tree (no per-directory .gitattributes is read), core.attributesFile at /dev/null,
# GIT_ATTR_NOSYSTEM kills the system file, and the diff ignores submodules (their own config with them). The residual a
# repository can still plant is a filter in .git/config assigned by $GIT_DIR/info/attributes — no flag or environment
# closes that path; the README says so. GIT_OPTIONAL_LOCKS=0 is best-effort only: `git diff <commit>` still refreshes
# the stat cache and rewrites .git/index under its own lock when a tracked file is stat-dirty.
# GIT_DIR/GIT_WORK_TREE from the caller's environment are unset: --changed always reads the repository the bundle lives
# in, never one the environment points at (GIT_INDEX_FILE is kept — a pre-commit hook needs it, and it names an index
# file inside that same repository).
chg_git() {
  env -u GIT_DIR -u GIT_WORK_TREE \
    GIT_ATTR_SOURCE=4b825dc642cb6eb9a060e54bf8d69288fbee4904 GIT_ATTR_NOSYSTEM=1 \
    GIT_OPTIONAL_LOCKS=0 git -c core.fsmonitor=false -c core.attributesFile=/dev/null -C "$CH_BUNDLE" "$@"
}

# run_changed <bundle> <ref>: `--changed` mode. The same note-local checks `--file` gives (part a) on every
# note changed since <ref> — committed, staged or untracked, whoever wrote it — plus the declared counts ONCE when any
# markdown file of the bundle changed or was deleted (lead decision 2: a commit that touches no note stays quiet even
# when the count is already stale). Deleted notes are not checked as notes (a deleted file has nothing to check); a
# rename is a delete plus an add, so the note is checked under its new name. Exit 2 outside a git repository, for an
# unknown ref, for a range (one commit-ish is required), when the resolved work tree does not contain the bundle
# (GIT_DIR/GIT_WORK_TREE pointing elsewhere), or when git itself fails (a corrupt or unreadable index) — never a
# silent "nothing changed". 64 for a usage error.
run_changed() {
  local bundle ref sha prefix st p rel nrc irc keep ig worst firstmd top vrc n inside
  ref="$2"
  [ -n "$ref" ] || { echo "usage: okf-check <bundle> --changed <git-ref>" >&2; return 64; }
  case "$ref" in *$'
'*) esc_line "error: --changed: a newline in the ref cannot name a git ref" >&2; return 64 ;; esac
  bundle=$(cd -P "$1" && pwd) || return 64
  [ -n "$PY" ] || { esc_line "okf-check: python3 is missing - the changed notes cannot be checked" >&2; return $EXIT_DEP; }
  # GIT_ATTR_SOURCE (the attribute pinning above) needs git >= 2.40; older git ignores it SILENTLY, which would reopen
  # the attribute vectors, so an older git is refused by name instead of trusted. A version string that is not
  # numeric major.minor is 'unknown', never string-compared into running.
  gitver=$(git --version 2>/dev/null | awk '{print $3}')
  if ! [[ "$gitver" =~ ^[0-9]+\.[0-9]+ ]]; then
    esc_line "okf-check: --changed needs git >= 2.40 (attribute hardening); this git is unknown - the changed notes cannot be listed" >&2
    return $EXIT_DEP
  fi
  git40=$(awk -v v="$gitver" 'BEGIN { split(v, a, "."); print (a[1]+0 > 2 || (a[1]+0 == 2 && a[2]+0 >= 40)) ? 1 : 0 }')
  [ "$git40" = 1 ] || { esc_line "okf-check: --changed needs git >= 2.40 (attribute hardening); this git is $gitver - the changed notes cannot be listed" >&2; return $EXIT_DEP; }
  # A range (a..b, a...b, the CI form origin/main..HEAD) is refused up front: one commit-ish is required. Checking it
  # here, before rev-parse, keeps the named line the same whether the endpoints exist or not.
  case "$ref" in *..*) esc_line "okf-check: --changed needs a single commit-ish, not a range: '$ref' - the changed notes cannot be listed" >&2; return $EXIT_DEP ;; esac
  CH_BUNDLE="$bundle"
  # The environment can point GIT_DIR/GIT_WORK_TREE at another repository; --changed must never read that one. The work
  # tree git resolves has to contain the bundle (GIT_INDEX_FILE is kept: a pre-commit hook needs it).
  top=$(chg_git rev-parse --show-toplevel 2>/dev/null)
  if [ -z "$top" ]; then
    esc_line "okf-check: $bundle is not inside a git repository, so --changed cannot run" >&2; return $EXIT_DEP
  fi
  inside=1
  case "$bundle" in "$top"|"$top"/*) ;; *) inside=0 ;; esac
  if [ "$inside" = 0 ]; then
    esc_line "okf-check: the git work tree '$top' does not contain $bundle - the changed notes cannot be listed" >&2
    return $EXIT_DEP
  fi
  # --end-of-options: a ref may start with '-'; after it git treats the word as a ref, never as a flag. A range
  # (a..b) is not one commit: rev-parse prints two endpoints (or fails) — either way it is refused, exit 2.
  sha=$(chg_git rev-parse --verify -q --end-of-options "$ref^{commit}" 2>/dev/null); vrc=$?
  if [ -z "$sha" ]; then
    esc_line "okf-check: unknown git ref '$ref' - the changed notes cannot be listed" >&2; return $EXIT_DEP
  fi
  set -- $sha; n=$#
  if [ "$vrc" -ne 0 ] || [ "$n" -gt 1 ]; then
    esc_line "okf-check: --changed needs a single commit-ish, not a range: '$ref' - the changed notes cannot be listed" >&2
    return $EXIT_DEP
  fi
  prefix=$(chg_git rev-parse --show-prefix)
  # The changed set: what git diff --no-renames lists for tracked files (worktree against the ref, staged included), plus
  # untracked files git does not ignore (-z everywhere; core.quotepath never bites). --full-name prints repo-root-relative
  # paths, the shape changed_one's prefix filter expects, also for a bundle in a sub-folder. A git failure here (a corrupt
  # or unreadable index) is exit 2 with a named line, never a silent empty set.
  CH_PREFIX="$prefix"; CH_MD=0; CH_FIRST=""; CH_NOTES=()
  chg_git diff --name-status -z --no-renames --no-ext-diff --no-textconv --ignore-submodules=all "$sha" -- . > "$TMP/changed.raw" 2>/dev/null
  if [ $? -ne 0 ]; then
    esc_line "okf-check: git diff $ref failed - the changed notes cannot be listed" >&2; return $EXIT_DEP
  fi
  while IFS= read -r -d '' st && IFS= read -r -d '' p; do
    case "$st" in C*) IFS= read -r -d '' _ ;; esac   # a copy carries a second path
    changed_one "$p"
  done < "$TMP/changed.raw"
  chg_git ls-files --others --exclude-standard -z --full-name -- . > "$TMP/untracked.raw" 2>/dev/null
  if [ $? -ne 0 ]; then
    esc_line "okf-check: git ls-files failed - the changed notes cannot be listed" >&2; return $EXIT_DEP
  fi
  while IFS= read -r -d '' p; do changed_one "$p"; done < "$TMP/untracked.raw"
  if okfignore_present "$bundle"; then
    okfignore_load "$bundle"; [ $? -eq 2 ] && return $EXIT_DEP
  fi
  resolve_note_cap "$bundle" || return $EXIT_DEP
  build_scoped_lists "$bundle"; keep="$SCOPED_KEEP"; ig="$SCOPED_IG"
  worst=0
  # bash 3.2 + set -u: an empty array is unbound in for; the guard keeps a clean bundle on the fast path
  if [ "${#CH_NOTES[@]}" -gt 0 ]; then
  for rel in "${CH_NOTES[@]}"; do
    if okfignore_present "$bundle" && okfignore_match "$rel"; then
      esc_line "$(rel_shown "$rel"): not checked (.okfignore excludes it)"
      continue
    fi
    note_checks "$bundle" "$rel" "$keep"; nrc=$?
    worst=$(worst_rc "$worst" "$nrc")
  done
  fi
  # The declared counts, once, in the gate's own wording — only when a markdown file changed (lead decision 2). The
  # message names the first changed markdown path; when only deletions changed, index.md stands in.
  if [ "$CH_MD" = 1 ]; then
    firstmd="$CH_FIRST"; [ -n "$firstmd" ] || firstmd="index.md"
    scoped_index "$bundle" "$firstmd" "$keep" "$ig" > "$TMP/scoped-index.txt" 2> "$TMP/scoped-index.err"; irc=$?
    [ -s "$TMP/scoped-index.err" ] && esc_line "$(<"$TMP/scoped-index.err")" >&2
    [ -s "$TMP/scoped-index.txt" ] && esc_line "$(<"$TMP/scoped-index.txt")"
    if [ "$irc" -eq 2 ]; then
      [ -s "$TMP/scoped-index.err" ] || esc_line "okf-check: the changed notes were not checked (index.md could not be read)" >&2
      irc=$EXIT_DEP
    fi
    worst=$(worst_rc "$worst" "$irc")
  fi
  return "$worst"
}

# rel_shown <name>: the display copy of a note name (shown() from okf_guard: C0/C1, bidi, U+2028/9 and bad bytes
# spelled \xNN). The RAW name stays in every file operation, comparison and argument; only printed lines use this.
rel_shown() { PYTHONDONTWRITEBYTECODE=1 OKF_SCRIPTS_DIR="$HERE" "$PY" - "$1" <<'PYS'
import os, sys
sys.path.insert(0, os.environ["OKF_SCRIPTS_DIR"])
from okf_guard import shown
print(shown(sys.argv[1]))
PYS
}

# run_scoped <bundle> <note>: `--file` mode (the edit hook calls it). L1 and Trust for one note through
# okf-scoped.py: one line per finding, nothing for a clean note, no other layer. Exit codes keep their meaning:
# 1 an L1 error (or, with --strict-trust, a Trust warning or advisory, or a near-miss actor), 0 otherwise, 2 could not
# run,
# 64 the note is missing, not .md, or outside the bundle.
# build_scoped_lists <bundle>: the keep list and the ignored list the note-local checks share (part a; runs
# them once for a whole commit instead of once per note). Sets keep and ig; empty when no .okfignore exists.
build_scoped_lists() {
  local bundle="$1" f igrel
  SCOPED_KEEP=""; SCOPED_IG=""
  if okfignore_present "$bundle"; then
    okfignore_list "$bundle" > "$TMP/scoped-keep.lst" 2>/dev/null && SCOPED_KEEP="$TMP/scoped-keep.lst"
    SCOPED_IG="$TMP/scoped-ignored.lst"; : > "$SCOPED_IG"
    # NOT rel: rel is the note under the check, and this loop walks the whole bundle
    while IFS= read -r -d '' f; do
      igrel=${f#"$bundle"/}
      okfignore_match "$igrel" && printf '%s\0' "$igrel"
    done < <(find -H "$bundle" -name .git -prune -o -name '*.md' -print0 2>/dev/null) > "$SCOPED_IG"
    okf_reap_procsub
  fi
}

# note_checks <bundle> <rel> [keep]: L1, Trust and the note-local profile findings for ONE note (part a; calls
# it per changed note). Prints its findings; returns the worst of its own outcomes by rank. The declared-count check is
# NOT here: --file runs it once for its note, --changed once for the whole commit (lead decision 2).
note_checks() {
  local bundle="$1" rel="$2" keep="${3:-}" out rc prc vrc
  OKF_KEEP_LIST="$keep" run_layer "Scoped check" "$HERE/okf-scoped.py" "$bundle" "$rel" $([ "$STRICT_TRUST" -eq 1 ] && echo --strict-trust); rc=$?
  if layer_stopped "$rc" >&2; then echo "okf-check: $(rel_shown "$rel") was not checked" >&2; return $EXIT_DEP; fi   # stderr: stdout is findings only
  out=$(<"$TMP/layer.out")
  [ -n "$out" ] && esc_line "$out"
  case "$rc" in
    0) vrc=0 ;;
    1) [ -n "$out" ] && vrc=$EXIT_CONFORM ;;   # exit 1 with no finding printed is a crash, not a verdict
  esac
  if [ -z "${vrc:-}" ]; then
    esc_line "okf-check: the scoped check could not run (exit $rc) - $(rel_shown "$rel") was not checked" >&2
    return $EXIT_DEP
  fi
  scoped_profile "$bundle" "$rel" > "$TMP/scoped-profile.txt" 2> "$TMP/scoped-profile.err"; prc=$?
  [ -s "$TMP/scoped-profile.err" ] && esc_line "$(<"$TMP/scoped-profile.err")" >&2
  [ -s "$TMP/scoped-profile.txt" ] && esc_line "$(<"$TMP/scoped-profile.txt")"
  case "$prc" in 0|$EXIT_PROFILE) ;; *) esc_line "okf-check: $rel was not checked (the house profile could not run)" >&2; prc=$EXIT_DEP ;; esac
  return "$(worst_rc "$vrc" "$prc")"
}

run_scoped() {
  local bundle note rel out rc keep f ig
  [ "${_want_file:-0}" = 1 ] && { echo "usage: okf-check <bundle> --file <note>" >&2; return 64; }
  [ "$JSON" -eq 1 ] && { echo "error: --file prints text lines; --json is not supported with it" >&2; return 64; }
  case "$2" in *$'\n'*) echo "error: --file: a newline in the note name would split a finding over two lines" >&2; return 64 ;; esac
  [ -f "$2" ] || { esc_line "error: --file '$2' is not a file" >&2; return 64; }
  case "$2" in *.md) ;; *) esc_line "error: --file '$2' is not a .md note" >&2; return 64 ;; esac
  bundle=$(cd -P "$1" && pwd) || return 64
  note="$(cd -P "$(dirname -- "$2")" && pwd)/$(basename -- "$2")"
  case "$note" in "$bundle"/*) rel=${note#"$bundle"/} ;; *) esc_line "error: --file '$2' is not inside $1" >&2; return 64 ;; esac
  if okfignore_present "$bundle"; then
    okfignore_load "$bundle"; [ $? -eq 2 ] && return $EXIT_DEP
    okfignore_match "$rel" && { esc_line "$(rel_shown "$rel"): not checked (.okfignore excludes it)"; return 0; }
  fi
  [ -n "$PY" ] || { esc_line "okf-check: python3 is missing - $rel was not checked" >&2; return $EXIT_DEP; }
  resolve_note_cap "$bundle" || return $EXIT_DEP
  # The full run checks links against the notes .okfignore keeps (a filtered mirror), so the scoped run does too.
  # The keep list exists only when an .okfignore does (no ignore file: the reconciler walks the bundle itself, one Python
  # pass, which is the fast path). Beside it, the ignored list — the *.md the ignore rules DO exclude — so the reconciler
  # can tell an anomalous note that is the bundle's business from one the full run never sees.
  build_scoped_lists "$bundle"; keep="$SCOPED_KEEP"; ig="$SCOPED_IG"
  # Note-local L2 (part a). Order: the L1 and Trust lines, then the profile findings, then the index findings; the
  # hook ticket counts on that order. A hygiene finding stays out: it is not local to one note.
  local prc irc
  note_checks "$bundle" "$rel" "$keep"; prc=$?
  scoped_index "$bundle" "$rel" "$keep" "$ig" > "$TMP/scoped-index.txt" 2> "$TMP/scoped-index.err"; irc=$?
  [ -s "$TMP/scoped-index.err" ] && esc_line "$(<"$TMP/scoped-index.err")" >&2
  [ -s "$TMP/scoped-index.txt" ] && esc_line "$(<"$TMP/scoped-index.txt")"
  if [ "$irc" -eq 2 ]; then
    [ -s "$TMP/scoped-index.err" ] || esc_line "okf-check: $rel was not checked (index.md could not be read)" >&2
    irc=$EXIT_DEP
  fi
  return "$(worst_rc "$prc" "$irc")"
}

_stat_flavor=""
bundle_fingerprint() {
  # "size mtime name" per concept, sorted. Sub-second mtime where the platform
  # offers it (BSD %Fm / GNU %y) — 1-second granularity hid a real stale index
  # at an equal-second boundary once already.
  #
  # KNOWN LIMIT: a modification keeping byte-size AND timestamp identical is
  # invisible here. Sub-second mtime makes that vanishingly unlikely, and hashing
  # every file twice costs more than the residual risk is worth.
  #
  # NUL-delimited, and NEVER through a shell variable. The list used to be
  # captured newline-separated, which split a filename containing a literal
  # newline into two nonexistent fragments — the file vanished from the
  # fingerprint with no warning, taking its mid-scan change detection with it.
  # `$(...)` cannot carry the fix either: command substitution STRIPS NUL bytes,
  # so -print0 into a variable loses every delimiter and yields one giant
  # argument. It goes to a file instead. (V-4, same bug class as G-8 next door)
  #
  # No `xargs -r`: that flag is GNU-only. The `-s` test on the file is the
  # portable equivalent, and keeps stat from being invoked with zero arguments.
  local list="$TMP/fingerprint.files"
  okf_md_files "$1" > "$list"
  [ -s "$list" ] || return 0
  if [ -z "$_stat_flavor" ]; then
    if stat -f '%z' /dev/null >/dev/null 2>&1; then _stat_flavor=bsd; else _stat_flavor=gnu; fi
  fi
  # `stat -L` follows the link. Without it `find -L` yielded a symlinked
  # concept's path and stat described the LINK — so rewriting the TARGET left the
  # fingerprint byte-identical and a mid-scan edit to a symlinked concept went
  # undetected. Caught by E-9c. (Reviewer-reported blind spot in E-7.)
  if [ "$_stat_flavor" = bsd ]; then
    xargs -0 stat -L -f '%z %Fm %N' < "$list" 2>/dev/null | sort
  else
    xargs -0 stat -L -c '%s %y %n' < "$list" 2>/dev/null | sort
  fi
}

# okflint has no `--version` flag (that invocation errors with a usage dump, which
# an earlier version of this script happily captured AS the version). Ask the
# package metadata instead, via whichever interpreter actually owns the binary —
# survives uv-tool, pipx, pip --user and venv layouts alike.
okflint_version() {
  local bin py v
  if command -v uv >/dev/null 2>&1; then
    # pipefail-safe: only the value is used; the status of this assignment is never tested.
    v=$(uv tool list 2>/dev/null | awk '/^okflint /{print $2}' | tr -d 'v' | head -1)
    [ -n "$v" ] && { printf '%s' "$v"; return 0; }
  fi
  bin=$(command -v okflint 2>/dev/null) || { printf 'unknown'; return 1; }
  py=$(head -1 "$bin" 2>/dev/null | sed 's/^#!//')
  case "$py" in
    *[!a-zA-Z0-9/_.@-]*|"") py="" ;;
  esac
  if [ -n "$py" ] && [ -x "$py" ]; then
    v=$("$py" -c 'import importlib.metadata as m; print(m.version("okflint"))' 2>/dev/null)
    [ -n "$v" ] && { printf '%s' "$v"; return 0; }
  fi
  printf 'unknown'
}

# ------------------------------------------------------------------ L0 doctor
# Returns 0 if L1 can run at all. The DOCTOR never installs anything: it names the command (installing is `--install-deps`)
# and stops. (Same read/write split as code-knowledge-graphs:ask — a tool that
# installs on its own initiative cannot be audited before it acts.)
# ------------------------------------------------- prerequisites
# Install is explicit, not silent: a plugin that runs `uv tool install` on every session start
# is a supply-chain risk. `--preflight` only REPORTS; `--install-deps` prints a plan and acts
# only with --yes; OKF_AUTO_INSTALL=1 is the owner's opt-in to let the preflight act.
okflint_target() {  # prints: <spec>|<where it comes from>   (exit 2: pins unreadable or spec unsafe)
  local want src
  if [ "$USE_LATEST" -eq 1 ]; then printf '%s|%s' "okflint" "PyPI, latest release"; return 0; fi
  # A pins file we cannot read must not turn into an unpinned install (fail closed).
  if [ ! -r "$PINS" ]; then printf 'pins file unreadable: %s' "$PINS"; return 2; fi
  want=$(pin_of okflint); src=$(pin_of okflint_source)
  if [ -n "$src" ]; then
    # Only a PyPI name or an https git URL: a value starting with "-" would be read by uv as an option.
    case "$src" in
      okflint|okflint==[0-9]*|git+https://[A-Za-z0-9]*) ;;
      *) printf 'refusing an unsafe okflint_source: %s' "$src"; return 2 ;;
    esac
    case "$src" in *[!A-Za-z0-9._~:/@%+=-]*) printf 'refusing an unsafe okflint_source: %s' "$src"; return 2 ;; esac
    printf '%s|%s' "$src" "pinned source (carries the okflint#11 fixes)"
  elif [ -n "$want" ]; then printf '%s|%s' "okflint==$want" "PyPI, supported version"
  else printf '%s|%s' "okflint" "PyPI, latest release"; fi
}

# okflint_install_hint: the package an install hint should name, or "!" followed by the reason nothing can be named.
# Two states must never print the unpinned build: a pins file that names no okflint (okflint_target falls back to bare
# `okflint`) and any refusal by okflint_target (an unreadable file, an unsafe okflint_source, whose own message is the
# reason). Bare `okflint` is printed only when --latest asked for it.
okflint_install_hint() {
  local t t_rc; t=$(okflint_target 2>/dev/null); t_rc=$?
  if [ "$t_rc" -ne 0 ]; then printf '!%s' "$t"; return 0; fi
  t=${t%%|*}
  if [ "$t" = okflint ] && [ "$USE_LATEST" -eq 0 ]; then printf '!%s names no okflint' "$PINS"; return 0; fi
  printf '%s' "$t"
}

preflight() {
  local issues="" want got=""
  [ -n "$PY" ] || issues="$issues python3 is missing (L1 needs it);"
  [ -r "$PINS" ] || issues="$issues the pins file is unreadable ($PINS), so nothing can be checked;"
  want=$(pin_of okflint)
  if ! command -v okflint >/dev/null 2>&1; then
    issues="$issues okflint is not installed, so L2 is skipped (supported: ${want:-any});"
  else
    got=$(okflint_version)
    if [ -n "$want" ] && [ "$got" != "$want" ]; then
      issues="$issues okflint $got is not the supported $want;"
    fi
  fi
  # Same version number, wrong build. The supported build is the PATCHED one when a source is pinned,
  # and stock PyPI okflint prints the same version, so one BOM probe tells them apart (~0.5 s).
  # Inconclusive output (no report, hung) stays silent: a preflight must not nag on a guess.
  if [ -z "$issues" ] && [ -n "$(pin_of okflint_source)" ] && [ -f "$TEMPLATE" ] && command -v okflint >/dev/null 2>&1; then
    local pf="$TMP/preflight-probe"
    rm -rf "$pf"; mkdir -p "$pf"
    sed 's/^  name: CHANGE ME/  name: Probe/' "$TEMPLATE" > "$pf/okf-base.yaml"
    printf -- '\357\273\277---\ntype: Lesson\ntitle: Probe\n---\nbody\n' > "$pf/probe-bom.md"
    run_limited 8 "$TMP/preflight.out" sh -c 'cd "$1" && exec okflint validate . --manifest okf-base.yaml --json' _ "$pf"
    if grep -q '"F001"' "$TMP/preflight.out" 2>/dev/null; then
      issues="$issues okflint $got is the stock build (it rejects a BOM note); the supported build carries the okflint#11 fixes;"
    fi
  fi
  [ -z "$issues" ] && return 0
  if [ "${OKF_AUTO_INSTALL:-0}" = "1" ]; then
    install_deps yes; return $?
  fi
  printf 'okf preflight:%s run: bash %s/okf-check --install-deps   (shows the plan; add --yes to install)\n' "$issues" "$HERE"
}

install_deps() {  # install_deps [yes]  — "yes" is the caller's consent (the OKF_AUTO_INSTALL opt-in)
  local go="$ASSUME_YES" target spec where prev have_uv=0 rc tdir bdir limit="${OKF_INSTALL_TIMEOUT:-200}"
  [ "${1:-}" = "yes" ] && go=1
  JSON=0   # an install request always shows its plan and result
  target=$(okflint_target); rc=$?
  if [ "$rc" -ne 0 ]; then
    say "okf-check $VERSION — prerequisites"
    say "  okflint   $target"
    say "  result    NOT RUN (exit 2): fix the pins file or use --latest"
    return $EXIT_DEP
  fi
  spec=${target%%|*}; where=${target#*|}
  command -v uv >/dev/null 2>&1 && have_uv=1
  prev=""; command -v okflint >/dev/null 2>&1 && prev=$(okflint_version)
  say "okf-check $VERSION — prerequisites"
  if [ -n "$PY" ]; then say "  python3   present ($($PY -V 2>&1))"
  else say "  python3   MISSING — install Python 3 (https://www.python.org/downloads/); okf-check cannot install it"; fi
  say "  pyyaml    vendored, nothing to install"
  if [ "$have_uv" -eq 1 ]; then say "  uv        present (the installer)"
  else say "  uv        MISSING — okflint is installed with uv: https://docs.astral.sh/uv/getting-started/installation/"; fi
  say "  okflint   ${prev:-not installed} -> $spec   [$where]"
  if [ "$USE_LATEST" -eq 1 ]; then
    say "  note      the newest PyPI okflint may lack fixes this gate was verified against;"
    say "            --doctor reports what it finds, and a later preflight with the pin reinstalls the pinned build"
  fi
  if command -v jq >/dev/null 2>&1; then say "  jq        present (optional)"
  else say "  jq        absent (optional): doc-reuse-guard.sh is off without it; install with your package manager"; fi
  say "  plan      uv tool install --force $spec"
  if [ -z "$PY" ] || [ "$have_uv" -eq 0 ]; then
    [ "$go" -eq 1 ] && { say "  result    NOT RUN: a prerequisite the installer needs is missing (exit 2)"; return $EXIT_DEP; }
    say "  dry run   nothing was changed"; return 0
  fi
  if [ "$go" -ne 1 ]; then
    say "  dry run   nothing was changed; add --yes to run the plan"; return 0
  fi
  # Keep the exact previous tool directory: `uv tool install --force` can remove the old install
  # before it fails, and a PyPI reinstall of "the same version" would swap a fork build for stock.
  tdir=$(uv tool dir 2>/dev/null)/okflint; bdir=$(uv tool dir --bin 2>/dev/null)
  rm -rf "$TMP/okflint.bak"
  [ -d "$tdir" ] && cp -R "$tdir" "$TMP/okflint.bak" 2>/dev/null
  run_limited "$limit" "$TMP/install.out" uv tool install --force "$spec"; rc=$?
  if [ "$rc" -eq 0 ]; then
    say "  result    installed: $spec"
    doctor; return $?
  fi
  if [ "$rc" -eq 143 ]; then say "  result    INSTALL TIMED OUT after ${limit}s (exit 143)"
  else say "  result    INSTALL FAILED (exit $rc): $(tail -1 "$TMP/install.out.err" 2>/dev/null | cut -c1-140)"; fi
  if [ -d "$TMP/okflint.bak" ]; then
    rm -rf "$tdir" && mv "$TMP/okflint.bak" "$tdir" \
      && [ -n "$bdir" ] && [ -x "$tdir/bin/okflint" ] && ln -sf "$tdir/bin/okflint" "$bdir/okflint" 2>/dev/null
    say "  restore   the previous okflint ($prev) was put back exactly"
  elif [ -n "$prev" ]; then
    say "  restore   nothing to put back; reinstall with: okf-check --install-deps --yes"
  fi
  return $EXIT_DEP
}

# run_limited SECS OUTFILE CMD...: run CMD, stdout in OUTFILE and stderr in OUTFILE.err; stop it after SECS, or when its
# process tree holds more than OKF_L2_MAX_RSS_MB (default 2048). (A crash is "no stdout"; merging stderr would make a
# traceback look like a verdict.) macOS has no `timeout`. Returns CMD's status, 143 when it was stopped for time and 137 when
# it was stopped for memory; OUTFILE.limit then says `timeout` or `rss <held> <limit>`.
# okf-limit.py does the work: it puts CMD in its own process group and stops the WHOLE group (okflint starts through a uv
# shim, so the python that holds the memory can be a grandchild: killing the direct child left it running), and it
# stops the group when okf-check goes away. RL_PID lets the exit trap stop it when okf-check itself is told to stop.
RL_PID=""
run_limited() {
  local secs="$1" out="$2" rss="${OKF_L2_MAX_RSS_MB:-2048}" rc
  shift 2
  case "$rss" in ''|*[!0-9]*|0) rss=2048 ;; esac
  rm -f "$out.limit"
  "$PY" "$HERE/okf-limit.py" "$secs" "$rss" "$out" -- "$@" &
  RL_PID=$!
  wait "$RL_PID" 2>/dev/null; rc=$?
  RL_PID=""
  return $rc
}
# stop_limited: on any way out, stop the limited command's tree. okf-limit.py stops its own group on TERM and waits for it.
stop_limited() {
  [ -n "$RL_PID" ] || return 0
  kill -TERM "$RL_PID" 2>/dev/null
  local i=0
  while [ "$i" -lt 30 ] && kill -0 "$RL_PID" 2>/dev/null; do sleep 0.1; i=$((i+1)); done
  kill -KILL "$RL_PID" 2>/dev/null
  RL_PID=""
}

# The Python layers (Trust, Successor, Owner, Size, derived L3, --duplicates, and the scoped --file check) read the notes, and
# the first four parse every note's frontmatter: 3.6 to 7.7 s per MB in PyYAML, linear, and a parse cannot be stopped from
# inside Python. So each runs under the watchdog (run_limited), as L1 does. OKF_LAYER_TIMEOUT seconds is ONE budget for all of
# them together (LAYER_SPENT_MS): a layer with no time left is not started. Size parses no YAML but reads every note whole;
# it costs 54 to 74 ms on a 4.5 MB note, so it stays in the budget, which only a bundle of many large notes would use up.
# Called from the main shell, never from $(...): LAYER_SPENT_MS must survive.
# Default 300: a note of 4.5 MB (the cap is 5 MB) costs one parsing layer 16 s on a fast Mac and 35 s on a slower one, so the
# four layers need 64 to 140 s of the budget at the cap while L1 alone needs 16 to 36 s of its own 120 s. 120 would answer
# exit 2 for a bundle that L1 passes.
LAYER_LIMIT="${OKF_LAYER_TIMEOUT:-300}"; case "$LAYER_LIMIT" in ''|*[!0-9]*|0) LAYER_LIMIT=300 ;; esac
LAYER_SPENT_MS=0; LAYER_NAME=""
# 1 s is not a safe OKF_LAYER_TIMEOUT: Trust alone takes 0.11 to 0.2 s and a whole healthy run 0.55 to 0.7 s at a load of 10, so the
# same bundle would get different verdicts. A usage error (64) before any layer runs; 0 and a non-number still mean the default.
layer_floor() {
  [ "$LAYER_LIMIT" -ge 2 ] && return 0
  echo "okf-check: OKF_LAYER_TIMEOUT=$LAYER_LIMIT is below 2 seconds, the smallest limit that gives a bundle the same verdict every time" >&2
  exit 64
}
# run_layer NAME CMD...: run one layer; its stdout is left in $TMP/layer.out (a file: --duplicates --json prints over 100 MB, which
# a shell variable made 5 s slower), its stderr goes to ours, and the status is its own (143 when stopped for time, as
# run_limited). NAME is what layer_stopped calls it. A first CMD word of `-` is the python script on stdin: the watchdog
# gives its command no stdin, so the script is put in a file first. The budget counts the milliseconds okf-limit.py
# measured (<out>.ms), not $SECONDS: whole seconds counted a 0.2 s layer as 0 or 1 s, so one healthy bundle got
# different verdicts at a 1 s limit.
run_layer() {
  local f="$TMP/layer.out" t0=$SECONDS rc left ms
  LAYER_NAME="$1"; shift
  if [ "$1" = - ]; then cat > "$TMP/layer.py"; set -- "$TMP/layer.py" "${@:2}"; fi
  left=$((LAYER_LIMIT * 1000 - LAYER_SPENT_MS))
  if [ "$left" -le 0 ]; then : > "$f"; echo timeout > "$f.limit"; return 143; fi   # as l1_validate
  run_limited "$((left / 1000)).$(printf %03d $((left % 1000)))" "$f" env PYTHONDONTWRITEBYTECODE=1 PYTHONPATH="$VENDOR_PY${PYTHONPATH:+:$PYTHONPATH}" "$PY" "$@"; rc=$?
  ms=$(cat "$f.ms" 2>/dev/null); case "$ms" in ''|*[!0-9]*) ms=$(( (SECONDS - t0) * 1000 )) ;; esac
  LAYER_SPENT_MS=$((LAYER_SPENT_MS + ms))
  cat "$f.err" >&2 2>/dev/null
  return $rc
}
# layer_stopped STATUS: right after run_layer, say that the watchdog stopped the layer and return 0; 1 when it did not.
# The reason is left in LAYER_WHY: say is silent under --json, so a mode that prints a JSON document needs it.
layer_stopped() {
  local why f="$TMP/layer.out"
  if l1_timed_out "$1" "$f"; then why="the $LAYER_LIMIT s time limit shared by the Python layers (OKF_LAYER_TIMEOUT) is used up"
  elif [ "$1" -eq 137 ] && grep -q '^rss' "$f.limit" 2>/dev/null; then why="it was stopped for memory (OKF_L2_MAX_RSS_MB)"
  else return 1; fi
  LAYER_WHY="$why"
  say "  $(printf '%-16s' "$LAYER_NAME") COULD NOT RUN — $why; not a pass"
}
# json_not_run LAYER WHY: for a mode whose stdout is ONE JSON document (--duplicates --json): when its layer could not run, still
# print a document, shaped like the main --json (exit, layers_not_run) plus the reason, and say the reason on stderr.
json_not_run() {
  if [ -n "$PY" ]; then
    "$PY" -c 'import json, sys; print(json.dumps({"bundle": sys.argv[1], "exit": 2, "layers_not_run": [sys.argv[2]], "reason": sys.argv[3]}))' "$BUNDLE" "$1" "$2"
  else   # no encoder: the layer and the reason are fixed texts without a quote or a backslash
    printf '{"bundle": "%s", "exit": 2, "layers_not_run": ["%s"], "reason": "%s"}\n' "${BUNDLE//\"/\\\"}" "$1" "$2"
  fi
  echo "okf-check: $1 COULD NOT RUN — $2" >&2
}
# stop_json LAYER WHY: a run that ends with exit 2 before its report. Under --json stdout still gets ONE document, never nothing
# (say is quiet under --json, so a stop that only said its reason left a CI caller an empty stdout and, for some stops, no
# message at all): the main run's own (emit_json, plus layers_not_run and reason), --duplicates' (json_not_run), and
# {bundle, exit, error} for --conserve and --fingerprint. The reason is on stderr. LAYER is the tag the text report uses for
# the step. The other modes have no JSON document (--file refuses --json; --facts and --doctor print text), so there is nothing to print.
stop_json() {
  [ "$JSON" -eq 1 ] || return 0
  case "$MODE" in
    check)      record notrun "$1"; STOP_LAYER="$1"; STOP_WHY="$2"; emit_json "$EXIT_DEP"; echo "okf-check: $1 COULD NOT RUN — $2" >&2 ;;
    duplicates) json_not_run "$1" "$2" ;;
    conserve|fingerprint)
      if [ -n "$PY" ]; then
        "$PY" -c 'import json, sys; print(json.dumps({"bundle": sys.argv[1], "exit": 2, "error": sys.argv[2]}))' "$BUNDLE" "$2"
      else
        printf '{"bundle": "%s", "exit": 2, "error": "%s"}\n' "${BUNDLE//\"/\\\"}" "$2"
      fi
      echo "okf-check: $2" >&2 ;;
  esac
}

doctor() {
  local fatal=0 okflint_state="MISSING"
  say "okf-check $VERSION — doctor"

  if [ -n "$PY" ]; then
    say "  python3            $($PY -V 2>&1)"
  else
    say "  python3            MISSING   <- install: https://www.python.org/downloads/"
    fatal=1
  fi

  # PyYAML is vendored, so this reports WHICH copy is in play rather than whether
  # one exists. It is no longer fatal: a stock machine with no site-packages now
  # runs L1 from the vendored pure-python copy.
  if [ -n "$PY" ] && py_with_vendor -c 'import yaml' >/dev/null 2>&1; then
    local ysrc ylibyaml
    ysrc=$(py_with_vendor -c 'import yaml,os;print(os.path.dirname(yaml.__file__))' 2>/dev/null)
    ylibyaml=$(py_with_vendor -c 'import yaml;print(yaml.__with_libyaml__)' 2>/dev/null)
    case "$ysrc" in
      "$VENDOR_PY"/*) say "  pyyaml             vendored (pure python, libyaml=$ylibyaml)" ;;
      *)              say "  pyyaml             system: $ysrc (libyaml=$ylibyaml)" ;;
    esac
  elif [ -n "$PY" ]; then
    say "  pyyaml             MISSING and the vendored copy did not import"
    say "                     <- reinstall okf-check, or: $PY -m pip install pyyaml"
    fatal=1
  fi

  # The doc-reuse reminder can name the closest existing notes when a search binary (`okf`) is on PATH or in
  # OKF_SEARCH_BIN. okf-check never installs it, so say whether the hint is on (okf-knowledge-gate#7).
  local _sb="${OKF_SEARCH_BIN:-}"; [ -n "$_sb" ] || _sb=$(command -v okf 2>/dev/null)
  if [ -n "$_sb" ] && [ -x "$_sb" ]; then
    say "  okf search         present ($_sb): doc-reuse reminders name the closest notes"
  else
    say "  okf search         absent (optional): doc-reuse reminders work without it but cannot name the closest notes; okf-check never installs it"
  fi

  if [ -f "$VALIDATOR" ]; then
    say "  okf_validate.py    vendored @ $(pin_of okf_validate | cut -c1-12) + local patch (bounded YAML loader)"
  else
    say "  okf_validate.py    MISSING from $VALIDATOR  <- reinstall okf-check"
    fatal=1
  fi

  if command -v okflint >/dev/null 2>&1; then
    local got want
    got=$(okflint_version)
    want=$(pin_of okflint)
    if [ "$got" = "$want" ]; then
      okflint_state="OK"; say "  okflint            $got  (pinned $want)"
    else
      okflint_state="SKEW"
      say "  okflint            $got  (gate verified against $want)"
      say "                     VERSION-SKEW — rule codes and exit semantics unverified here."
      say "                     run: okf-check --selftest"
    fi
    # BEHAVIOUR, not version: the patched okflint (mattdav/okflint#11) and stock 0.5.0 print the
    # same version string, so a pin cannot tell them apart. The probes run okflint on small
    # notes. They run ONLY under an explicit `--doctor` (every normal run calls doctor first, and
    # a hung okflint made every run stall), each bounded by a timeout.
    if [ "$MODE" = "doctor" ]; then
      if [ ! -f "$TEMPLATE" ]; then
        say "  okflint behaviour  UNKNOWN   (config/okf-base.yaml.template is missing: probes skipped)"
        say "  okflint manifest check  UNAVAILABLE   (template missing)"
      else
        local probe="$TMP/okflint-probe" pout prc bad="" ctl_ok=1
        _okflint_probe() {  # name | printf format of the note
          rm -rf "$probe"; mkdir -p "$probe"
          sed 's/^  name: CHANGE ME/  name: Probe/' "$TEMPLATE" > "$probe/okf-base.yaml"
          printf -- "$2" > "$probe/probe-$1.md"
          run_limited 8 "$TMP/probe.out" sh -c 'cd "$1" && exec okflint validate . --manifest okf-base.yaml --json' _ "$probe"; prc=$?
          pout=$(cat "$TMP/probe.out" 2>/dev/null)
          [ -s "$probe/probe-$1.md" ] || pout=""   # an empty fixture proves nothing
        }
        # Control first: a clean note must get a verdict. If it does not, okflint itself is not
        # working here (bad template, wrong flags, hung) and the three probes prove nothing.
        _okflint_probe ctl '---\ntype: Lesson\ntitle: Probe\n---\nbody\n'
        if [ -z "$pout" ] || [ "$prc" -gt 1 ]; then
          ctl_ok=0
          say "  okflint behaviour  UNKNOWN   (okflint gave no verdict on a clean note; probes inconclusive)"
          say "                     reason: $(cat "$TMP/probe.out.err" "$TMP/probe.out" 2>/dev/null | grep -v '^[[:space:]]*$' | tail -1 | cut -c1-140)"
        fi
        if [ "$ctl_ok" -eq 1 ]; then
          _okflint_probe bom '\357\273\277---\ntype: Lesson\ntitle: Probe\n---\nbody\n'
          if [ -z "$pout" ] || grep -q '"F001"' <<<"$pout"; then bad="$bad a BOM note (okflint#8),"; fi
          _okflint_probe latin1 '---\ntype: Lesson\ntitle: caf\351\n---\nbody\n'
          if [ -z "$pout" ] || [ "$prc" -gt 1 ]; then bad="$bad a non-UTF-8 note (okflint#9),"; fi
          _okflint_probe baddate '---\ntype: Lesson\ntitle: Probe\ndecided: 2026-02-30\n---\nbody\n'
          if [ -z "$pout" ] || [ "$prc" -gt 1 ]; then bad="$bad an impossible date (okflint#10),"; fi
          if [ -z "$bad" ]; then
            say "  okflint behaviour  PATCHED   (BOM, non-UTF-8 and impossible-date probes all reach a verdict)"
          else
            say "  okflint behaviour  UNPATCHED — fails on:${bad%,}"
            say "                     fixes: mattdav/okflint#11 (merged; shipped in 0.5.1). Install the build this pin names:"
            say "                     okf-check --install-deps --yes"
            say "                     advisory only: okf-check still names a crashing note (exit 2)."
          fi
        fi
        unset -f _okflint_probe
        # okflint >= 0.4.0 can check a manifest without scanning (validate-manifest). Run it on the
        # template we ship: proves the command exists here and that the template still passes
        # THIS okflint. Advisory: the bundle's own manifest is checked by `okflint validate`.
        run_limited 8 "$TMP/help.out" okflint --help
        if grep -q 'validate-manifest' "$TMP/help.out" 2>/dev/null; then
          local mf="$TMP/doctor-manifest.yaml" mrc
          sed 's/^  name: CHANGE ME/  name: Doctor/' "$TEMPLATE" > "$mf"
          run_limited 8 "$TMP/manifest.out" okflint validate-manifest "$mf"; mrc=$?
          if [ "$mrc" -eq 0 ]; then
            say "  okflint manifest check  OK   (validate-manifest accepts the shipped okf-base template)"
          else
            # pipefail-safe: a message line for the reader; the status of the assignment is never tested.
            local mwhy; mwhy=$(cat "$TMP/manifest.out.err" "$TMP/manifest.out" 2>/dev/null | grep -i 'error' | head -1)
            # pipefail-safe: the same message fallback; its status is never tested.
            [ -n "$mwhy" ] || mwhy=$(cat "$TMP/manifest.out.err" "$TMP/manifest.out" 2>/dev/null | grep -v '^[[:space:]]*$' | head -1)
            say "  okflint manifest check  REJECTED — $(printf '%s' "$mwhy" | cut -c1-140)"
            say "                     the shipped template no longer passes this okflint; advisory only."
          fi
        else
          say "  okflint manifest check  UNAVAILABLE   (this okflint has no validate-manifest; added in 0.4.0)"
        fi
      fi
    fi
  else
    # The PINNED package, not bare okflint: plain `uv tool install okflint` installs whatever PyPI calls latest, so a
    # reader lands on a build this gate was never verified against (0.5.0 drew a false S204 on a datetime stale_after,
    #). A pins file that names no okflint, or one okflint_target refuses, names no package at all and says why.
    local hint; hint=$(okflint_install_hint)
    case "$hint" in
      '!'*) say "  okflint            MISSING   <- ${hint#!}: fix that before installing a build nobody verified" ;;
      *)    say "  okflint            MISSING   <- install: uv tool install $hint   (or: pip install $hint)" ;;
    esac
    say "                     L2 (house profile) will be SKIPPED, not silently passed."
  fi

  command -v jq >/dev/null 2>&1 && say "  jq                 present (optional)" || say "  jq                 absent (optional — not required)"
  local omb
  # Only on an explicit --doctor: every run calls doctor(), and a binary on PATH is never started for a run that did not opt in.
  if [ "$MODE" != doctor ]; then :
  elif omb=$(okf_memory_bin); then
    "$PY" "$HERE/okf-limit.py" 10 512 "$TMP/okfmem-version.out" -- "$omb" version >/dev/null 2>&1
    say "  okf-memory         $(head -1 "$TMP/okfmem-version.out" 2>/dev/null | sed 's/^okf version //')  (optional: L2 graph with okf_check.graph: true)"
  else
    say "  okf-memory         absent (optional — L2 graph, orphans and broken concept links; set OKF_MEMORY_BIN)"
  fi
  # Explicit --doctor only (a normal run calls doctor() too and starts no python for this). Names a switched-on edit hook
  # whose config it cannot read: the hook is fail-open, so it would otherwise just stay silent.
  if [ "$MODE" = doctor ] && [ -n "$PY" ] && [ -f "$HERE/okf-edit-hook.py" ]; then
    local hook_line; hook_line=$(py_with_vendor "$HERE/okf-edit-hook.py" --doctor "${BUNDLE:-$PWD}" 2>/dev/null)
    [ -z "$hook_line" ] || say "$hook_line"
  fi
  say ""
  OKFLINT_STATE="$okflint_state"
  # EXIT_DEP, not a bare 1: `1` is EXIT_CONFORM, so returning it here made
  # "the bundle is not conformant" and "the gate could not run" indistinguishable
  # to CI — the exact confusion the layered exit codes exist to prevent.
  # Caught by okf-check.test.sh N-13/N-14.
  [ "$fatal" -eq 0 ] || return $EXIT_DEP
  return 0
}

# ------------------------------------------------------- L1 spec conformance
# The count alone named nothing: a reader had to run the validator by hand to see what the warnings
# were. List them, capped and honest about the cap (say_capped). 50 shows the pattern of a repeated
# mistake without scrolling the verdict off the screen; the full list is in `--json`.
l1_list_warnings() {
  grep -a '^W|' "$TMP/l1.txt" | sed 's/^W|//' | say_capped 50 "                   "
}
# Delegates to the vendored checker and reads its --json report through python3
# rather than jq, so a machine without jq still gets a real verdict.
# One note the vendored validator crashes on (a `status` list, an impossible date: upstream
# okf-skills#62/#63) used to blank the whole L1 verdict and name nothing (ticket 11).
# Isolation: run the validator on each note alone, name the ones that die, validate the rest.
# l1_validate <dir> <outfile>: the vendored validator under the watchdog (okf-limit.py, as okflint). Its cost grows with
# frontmatter size (a 0.4 MB list took 8 s, 1.0 MB 18 s; a note may hold 5 MB) and a parse cannot be stopped from inside
# Python. OKF_L1_TIMEOUT seconds, default 120 (L2's default), for ALL of L1: the runs that isolate a crashing note share
# it (L1_DEADLINE), or N notes could take N times the limit. A run with no budget left is not started: it writes the
# watchdog's own `timeout` marker and returns 143, so one test (l1_timed_out) covers both.
L1_LIMIT="${OKF_L1_TIMEOUT:-120}"; case "$L1_LIMIT" in ''|*[!0-9]*|0) L1_LIMIT=120 ;; esac
L1_DEADLINE=""
l1_validate() {
  local left=$(( ${L1_DEADLINE:-$((SECONDS + L1_LIMIT))} - SECONDS ))
  [ "$left" -ge 1 ] || { : > "$2"; echo timeout > "$2.limit"; return 143; }
  run_limited "$left" "$2" env PYTHONDONTWRITEBYTECODE=1 PYTHONPATH="$VENDOR_PY${PYTHONPATH:+:$PYTHONPATH}" \
    "$PY" "$VALIDATOR" "$1" --json
}
# l1_timed_out <status> <outfile>: the budget ran out. The status alone is not enough: a validator that ends itself with
# TERM exits 143 too, and one may exit with any code; only the watchdog's `timeout` marker says it was the limit.
l1_timed_out() { [ "$1" -eq 143 ] && grep -q '^timeout' "$2.limit" 2>/dev/null; }
# l1_stopped <status> <outfile>: the reason the watchdog stopped the validator, or status 1 when it did not.
l1_stopped() {
  if l1_timed_out "$1" "$2"; then echo "the validator timed out after $L1_LIMIT s (OKF_L1_TIMEOUT)"
  elif [ "$1" -eq 137 ] && grep -q '^rss' "$2.limit" 2>/dev/null; then echo "the validator was stopped for memory (OKF_L2_MAX_RSS_MB)"
  else return 1; fi
}
run_conformance() {
  local bundle="$1" out probe="$TMP/l1probe" mirror="$TMP/l1mirror" f rel why ncrash=0 rc k
  local -a crashed_rel=() crashed_why=()
  # `a/b/` and `a/b` must behave the same: find prints one slash, so a trailing one breaks
  # the relative-name strip below.
  while [ "${#bundle}" -gt 1 ] && [ "${bundle%/}" != "$bundle" ]; do bundle=${bundle%/}; done
  L1_DEADLINE=$((SECONDS + L1_LIMIT))
  l1_validate "$bundle" "$TMP/l1.out"; rc=$?
  if why=$(l1_stopped "$rc" "$TMP/l1.out"); then say "  L1 conformance   COULD NOT RUN — $why; not a pass"; return $EXIT_DEP; fi
  out=$(cat "$TMP/l1.out" 2>/dev/null)
  if [ -z "$out" ]; then
    # Pass 1: find the notes the validator dies on, one note per run.
    local -a keep=()
    while IFS= read -r -d '' f; do
      rel=${f#"$bundle"/}
      rm -rf "$probe"; mkdir -p "$probe"; cp "$f" "$probe/note.md" 2>/dev/null || continue
      l1_validate "$probe" "$TMP/l1probe.out"; rc=$?
      if l1_timed_out "$rc" "$TMP/l1probe.out"; then
        say "  L1 conformance   COULD NOT RUN — $(l1_stopped "$rc" "$TMP/l1probe.out"), while finding the notes the validator fails on; not a pass"
        return $EXIT_DEP
      fi
      if [ ! -s "$TMP/l1probe.out" ]; then
        why=$(l1_stopped "$rc" "$TMP/l1probe.out") || why=$(tail -1 "$TMP/l1probe.out.err" 2>/dev/null)
        [ -n "$why" ] || why="exit status $rc, no message"   # killed by a signal, or silent
        crashed_rel+=("$rel"); crashed_why+=("$why"); ncrash=$((ncrash+1))
      else
        keep+=("$rel")
      fi
    done < <(okf_md_files "$bundle")
    if [ "$ncrash" -eq 0 ]; then
      say "  L1 conformance   COULD NOT RUN (validator produced no output)"; return $EXIT_DEP
    fi
    # Pass 2: a mirror made of COPIES of the surviving notes only. Nothing is ever deleted: an
    # earlier cp -R + rm -f followed a symlinked directory and removed files outside the bundle.
    rm -rf "$mirror"; mkdir -p "$mirror"
    for rel in "${keep[@]+"${keep[@]}"}"; do
      mkdir -p "$mirror/$(dirname "$rel")" && cp "$bundle/$rel" "$mirror/$rel" 2>/dev/null
    done
    say "  L1 conformance   COULD NOT RUN on $ncrash note(s) — the vendored validator crashed on:"
    for k in "${!crashed_rel[@]}"; do
      # Display only: control characters in a name must not break the report layout.
      say "                   $(printf '%s' "${crashed_rel[$k]}" | tr '\n\r\t' '   '): ${crashed_why[$k]}"
    done
    say "                   (a validator bug, not a verdict on the note; fix or quote the field)"
    say "                   the other notes were checked:"
    __l1_core "$mirror"; rc=$?
    [ "$rc" -eq "$EXIT_CONFORM" ] && return $EXIT_CONFORM
    return $EXIT_DEP
  fi
  __l1_core "$bundle" "$out"
}

__l1_core() {
  local bundle="$1" out="${2:-}"
  local rc why
  if [ -z "$out" ]; then
    l1_validate "$bundle" "$TMP/l1.out"; rc=$?
    if why=$(l1_stopped "$rc" "$TMP/l1.out"); then say "  L1 conformance   COULD NOT RUN — $why; not a pass"; return $EXIT_DEP; fi
    out=$(cat "$TMP/l1.out" 2>/dev/null)
  fi
  [ -n "$out" ] || { say "  L1 conformance   COULD NOT RUN (validator produced no output)"; return $EXIT_DEP; }
  printf '%s' "$out" > "$TMP/l1.json"
  # SHAPE-CHECKED, not just parsed. `d.get("errors",[])` turned any valid JSON
  # of the wrong shape — `{}`, or a validator that renamed its keys across an
  # upgrade — into "0 errors" and a confident PASS. This is G-4 exactly, one
  # layer up: parsed is not understood, and a checker that cannot fail is
  # worthless. Silence about a missing key is the failure mode, so say so. (G-9)
  OKF_SCRIPTS_DIR="$HERE" "$PY" - "$TMP/l1.json" "$TMP/l1warn.json" <<'PY' > "$TMP/l1.txt" 2>/dev/null
import json, os, sys
sys.path.insert(0, os.environ["OKF_SCRIPTS_DIR"])
from okf_guard import shown
try:
    d = json.load(open(sys.argv[1]))
except Exception:
    print("SHAPE|not parseable as JSON"); raise SystemExit(0)
if not isinstance(d, dict) or "errors" not in d or "warnings" not in d:
    print("SHAPE|report has no 'errors'/'warnings' key — schema changed?"); raise SystemExit(0)
# PRESENT is not WELL-FORMED. len() and `for..in` both work on a str, so
# {"errors": ""} counted zero errors and printed PASS — the exact case the
# key-presence guard was added to stop. A str of length 10 became "10 error(s)"
# with ten single-character messages; a dict became one error named after its
# key. Fabricated detail is worse than a refusal. (V-1..V-3)
if not isinstance(d["errors"], list) or not isinstance(d["warnings"], list):
    print("SHAPE|'errors'/'warnings' is not a list — schema changed?"); raise SystemExit(0)
print(len(d["errors"]), len(d["warnings"]), d.get("counts", {}).get("concepts", 0))
for e in d["errors"]: print("E|" + e)
# One line per warning (a newline inside a message would split it into two). The list is also
# written as JSON for --json, where `l1_warnings` has only ever been a count.
ws = [str(w).replace("\n", " ") for w in d["warnings"]]
for w in ws: print("W|" + w)
json.dump([shown(w) for w in ws], open(sys.argv[2], "w"))   # a name that is not UTF-8 reads \xff in --json, not a lone surrogate
PY
  if grep -q '^SHAPE|' "$TMP/l1.txt" 2>/dev/null; then
    say "  L1 conformance   COULD NOT RUN — $(sed -n 's/^SHAPE|//p' "$TMP/l1.txt" | head -1)"  # pipefail-safe: a message line; the status of a substitution inside an argument is never read.
    say "                   run: okf-check --selftest"
    return $EXIT_DEP
  fi
  L1_ERR=$(head -1 "$TMP/l1.txt" | awk '{print $1}')
  L1_WARN=$(head -1 "$TMP/l1.txt" | awk '{print $2}')
  L1_CONCEPTS=$(head -1 "$TMP/l1.txt" | awk '{print $3}')
  case "$L1_ERR" in
    ''|*[!0-9]*) say "  L1 conformance   COULD NOT RUN (unreadable validator report)"; return $EXIT_DEP ;;
  esac
  # The L1 warnings are advisories like the L2 ones: the summary line counts every warning the sections above list.
  advise L1 "$L1_WARN"
  if [ "${L1_ERR:-1}" -eq 0 ]; then
    say "  L1 conformance   PASS   ${L1_CONCEPTS} concepts, 0 errors, ${L1_WARN} warning(s)"
    l1_list_warnings
    return 0
  fi
  # The warning count rides on the FAIL line: the warning lines print under the error lines at the
  # same indent, and "1 error(s)" above five unlabelled lines hid which of them were warnings.
  say "  L1 conformance   FAIL   ${L1_ERR} error(s), ${L1_WARN} warning(s) — bundle is not conformant OKF"
  # Through say(), not raw stdout: these detail lines used to bypass it and
  # corrupt --json on every non-clean bundle. E-4 only ever tested a CLEAN
  # bundle, so the suite was green over it. (R-3)
  # grep -a: as in L3, a note name with a byte that is not UTF-8 makes grep read the line as binary under a UTF-8 locale
  # and drop it from the list while the count above still holds it (S30-CF-L1v).
  grep -a '^E|' "$TMP/l1.txt" | sed 's/^E|//' | while IFS= read -r _e; do record error "$_e"; done
  grep -a '^E|' "$TMP/l1.txt" | sed 's/^E|//' | say_capped 12 "                   "
  l1_list_warnings
  return $EXIT_CONFORM
}

# ------------------------------------------------------- Trust (C4): unauthenticated human verification
# OKF v0.2 records `verified: by: human:<id>` and cannot authenticate it. okf-trust.py reports the
# cases where that claim is visibly unsafe (a draft, or changed after the review) as warnings and the
# honest-looking "agent drafts, person reviews later" case as an advisory. Both count into the final
# advisory tally; neither fails the run (exit stays 0). The identity line prints once per run.
run_trust() {
  local bundle="$1" out nw na nt sum why ec
  run_layer "Trust (C4)" "$HERE/okf-trust.py" "$bundle" "$TMP/trust.json" 2>"$TMP/trust.err"; ec=$?; out=$(<"$TMP/layer.out")
  if layer_stopped "$ec"; then TRUST_RAN=0; return $EXIT_DEP; fi
  if [ "$ec" -ne 0 ]; then
    # Unknown is not clean: --json gets null (not []), and the helper's own last error line is shown.
    TRUST_RAN=0; why=$(tail -1 "$TMP/trust.err" 2>/dev/null)
    say "  Trust (C4)       COULD NOT RUN (okf-trust.py failed${why:+: $why}; check python3 and PyYAML with: okf-check --doctor)"
    return $EXIT_DEP
  fi
  nw=$(printf '%s\n' "$out" | grep -c '^W|'); na=$(printf '%s\n' "$out" | grep -c '^A|'); nt=$(printf '%s\n' "$out" | grep -c '^T|')
  if [ "$nw" -eq 0 ] && [ "$na" -eq 0 ] && [ "$nt" -eq 0 ]; then
    say "  Trust (C4)       PASS   no unauthenticated human verification"
    return 0
  fi
  [ "$((nw + na))" -eq 0 ] || { advise Trust $((nw + na)); TRUST_FINDINGS=$((nw + na)); }
  if [ "$nt" -gt 0 ]; then
    # T: a note the loader refused for its size, so its trust claims are unread: not "no unauthenticated human verification".
    sum="$nt note(s) too large to read"; [ "$((nw + na))" -eq 0 ] || sum="$sum; ${nw} warning(s), ${na} advisory(ies)"
    say "  Trust (C4)       FAIL   $sum"
    printf '%s\n' "$out" | sed -n 's/^T|//p' | while IFS= read -r l; do record error "$l"; say "                   $l"; done
  else
    say "  Trust (C4)       WARN   ${nw} warning(s), ${na} advisory(ies)"
  fi
  printf '%s\n' "$out" | sed -n 's/^[WA]|//p' | say_capped 50 "                   "
  [ "$((nw + na))" -eq 0 ] || say "                   $TRUST_NOTE"
  [ "$nt" -eq 0 ] || return $EXIT_CONFORM
  return 0
}

# ------------------------------------------------------- okf_check: options block
# okf-check's own options live in ONE `okf_check:` block of okf-base.yaml. okflint ignores keys it does not know
# (okflint 0.5.0 manifest.py reads named keys only; the L2 count with and without the block is equal, LT-51b), so the
# block is not stripped. A block of the wrong shape or a key nobody knows is a typo that would switch an option off in
# silence: exit 2. The rules live ONCE, in config/okf-check-block.json, and okf-verify enforces them; this calls it
# (`okf-verify --check-config`), so the two tools cannot disagree (LT-52 is the parity table). No okf-base.yaml or
# no block: nothing is printed (LT-51c).
run_config() {   # $1 the real bundle (paths in the block resolve against it), $2 the frozen copy whose manifest is read
  local out rc key
  [ -f "${2:-$1}/okf-base.yaml" ] && [ -n "$PY" ] || return 0
  out=$(py_with_vendor "$ROOT/scripts/okf-verify" --check-config "$1" --manifest-dir "${2:-$1}" 2>&1); rc=$?
  if [ "$rc" -eq 0 ]; then
    # An okf_check option written at the top level of okf-base.yaml is ignored by every tool: the option is off and no
    # other line says so. One advisory per key; the exit code does not change.
    while IFS=$'\t' read -r key dup; do
      [ -n "$key" ] || continue
      advise Config 1; record misplaced "$key"
      if [ -n "$dup" ]; then
        say "  Config           WARN   \`$key\` is at the top level of okf-base.yaml and also inside okf_check:; okf-check reads \`$key\` only inside okf_check: delete the top-level copy"
      else
        say "  Config           WARN   \`$key\` is at the top level of okf-base.yaml, outside okf_check:; okf-check reads \`$key\` only inside okf_check: move it to okf_check.$key"
      fi
    done <<< "$(printf '%s\n' "$out" | awk -F'\t' '$1=="misplaced"{print $2 "\t" $3}')"
    return 0
  fi
  out=$(printf '%s' "$out" | tail -n 1)
  if [ ! -f "$ROOT/scripts/okf-verify" ]; then
    # The checker itself is gone: python's "can't open file" is not a fault of okf-base.yaml.
    out="the config check cannot run: $ROOT/scripts/okf-verify is missing (reinstall the plugin)"
  elif [ "$rc" -eq 2 ] && [ "${out#error: }" != "$out" ]; then
    # The shortest prefix: a value that itself names okf-base.yaml must stay in the message.
    out=${out#error: }; out="okf-base.yaml: ${out#*okf-base.yaml }"
  else
    out="the config check failed (okf-verify --check-config exit $rc${out:+: $out})"
  fi
  say "  Config           COULD NOT RUN — $out"
  record error "$out"
  CONFIG_WHY="$out"   # for stop_json (--duplicates --json)
  return $EXIT_DEP
}

# ------------------------------------------------------- deprecation names a successor (okf-knowledge-gate#9)
# With okf_check.deprecated_requires: superseded_by, every `status: deprecated` note names its successor in
# superseded_by. A violation is a house-rule error (exit 1). Option off: nothing is printed.
run_successor() {
  local bundle="$1" out ec n ne nt sum
  [ -f "$bundle/okf-base.yaml" ] && [ -n "$PY" ] || return 0
  OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" run_layer Successor - "$bundle" "$bundle/okf-base.yaml" <<'PYEOF'
import os, pathlib, sys
try:
    sys.path[:0] = [os.environ["OKF_SCRIPTS_DIR"], os.environ["OKF_VENDOR_DIR"]]
    from okf_validate import load_frontmatter
    from okf_notes import meta, resolve, read_manifest, read_note, TooLarge, shown
    # The bounded loader for the manifest too: an alias bomb in okf-base.yaml must not expand here (LT-35a), and a bounded
    # read under the manifest's own limit (a device, or a file over it, is not read; okf_check.max_note_bytes does not apply).
    cfg = load_frontmatter(read_manifest(sys.argv[2], "utf-8", "replace", root=os.path.dirname(sys.argv[2])))
except Exception:
    sys.exit(0)
opt = (cfg.get("okf_check") or {}) if isinstance(cfg, dict) else {}
# The value itself is checked once, by the shared schema (config/okf-check-block.json via run_config): any other
# value is that layer's exit 2, so this rule just stays off.
if not isinstance(opt, dict) or opt.get("deprecated_requires") != "superseded_by":
    sys.exit(0)
bundle = pathlib.Path(sys.argv[1])

root = os.path.realpath(str(bundle))

n = 0
for p in sorted(bundle.rglob("*.md")):
    if p.name in ("index.md", "log.md") or not p.is_file():   # a dangling link is no note (okf_md_files)
        continue
    m = meta(p, too_large=True, root=str(bundle))
    if isinstance(m, TooLarge):   # its status is unknown: not "no deprecated notes" (the loader's size cap, as in the Owner layer)
        print("T|%s: the note was too large to read, so its successor was not checked: %s" % (shown(str(p.relative_to(bundle))), m.why))
        continue
    if m.get("status") != "deprecated":
        continue
    n += 1
    rel = str(p.relative_to(bundle))
    sb = m.get("superseded_by")
    if not sb:
        print("E|%s: status deprecated but no superseded_by names its successor" % rel)
        continue
    for ref in (sb if isinstance(sb, list) else [sb]):
        ref = str(ref)
        q = resolve(ref, p, root)
        if q is None:
            print("E|%s: superseded_by %s: successor not found" % (rel, ref))
        elif os.path.basename(q) in ("index.md", "log.md"):
            # reserved files are not notes (the scan above skips them too): review F-C
            print("E|%s: superseded_by %s: successor is not a note (index.md and log.md are reserved files)" % (rel, ref))
        elif q == os.path.realpath(str(p)):
            print("E|%s: superseded_by %s: a note cannot supersede itself" % (rel, ref))
        else:
            mq = meta(q, too_large=True, root=str(bundle))
            if isinstance(mq, TooLarge):
                print("T|%s: superseded_by %s: the successor was too large to read, so whether it is deprecated was not checked: %s" % (rel, ref, mq.why))
            elif mq.get("status") == "deprecated":
                # One hop, no chains (decided): name the note that replaced the successor.
                print("E|%s: superseded_by %s is deprecated too: point at the final successor, not a deprecated one" % (rel, ref))
print("N|%d" % n)
PYEOF
  ec=$?; out=$(<"$TMP/layer.out")
  layer_stopped "$ec" && return $EXIT_DEP
  [ "$ec" -eq 0 ] || { say "  Successor        COULD NOT RUN — the successor check exited $ec"; return $EXIT_DEP; }
  n=$(printf '%s\n' "$out" | sed -n 's/^N|//p')
  [ -n "$n" ] || return 0
  if grep -q '^[ET]|' <<<"$out"; then   # not printf | grep -q: under pipefail a long $out read as no error (PF-1, PF-2)
    # T: a note (or a successor) the loader refused for its size: whether it is deprecated, or live, is not known, so not a PASS.
    ne=$(printf '%s\n' "$out" | grep -c '^E|'); nt=$(printf '%s\n' "$out" | grep -c '^T|'); sum=""
    [ "$ne" -eq 0 ] || sum="$ne error(s): a deprecated note must name its successor in superseded_by"
    [ "$nt" -eq 0 ] || sum="${sum:+$sum; }$nt note(s) too large to read"
    say "  Successor        FAIL   $sum"
    printf '%s\n' "$out" | sed -n 's/^[ET]|//p' | while IFS= read -r l; do record error "$l"; say "                   $l"; done
    return $EXIT_CONFORM
  fi
  if [ "$n" -eq 0 ]; then say "  Successor        PASS   no deprecated notes"
  else say "  Successor        PASS   ${n} deprecated note(s) name a valid successor"; fi
  return 0
}

# ------------------------------------------------------- ownership (okf-knowledge-gate#11)
# With okf_check.require_owner: true every note has an owner: its own `owner` key, else the folder default from
# okf_check.owners. A note with neither is a house-rule error (exit 1). Option off: nothing is printed.
run_owner() {
  local bundle="$1" out ec pats f rel def pat own ne nt sum
  [ -f "$bundle/okf-base.yaml" ] && [ -n "$PY" ] || return 0
  # An okf_check block that failed the schema is already the Config line's exit 2. Its owners are not trusted:
  # a folder default of 3 would otherwise become an owner error that outranks that exit 2 (LT-52 own-int).
  [ "${CONFIG_RC:-0}" -eq 0 ] || return 0
  # Folder defaults: okf_check.owners maps a glob to an owner, in file order. The globs are matched by the .okfignore
  # matcher (ignore-lib.sh), so the two cannot disagree about what a pattern covers; the LAST matching pattern wins.
  pats=$(OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" py_with_vendor - "$bundle/okf-base.yaml" <<'PY' 2>/dev/null
import os, sys
sys.path[:0] = [os.environ["OKF_SCRIPTS_DIR"], os.environ["OKF_VENDOR_DIR"]]
from okf_validate import load_frontmatter   # bounded: an alias bomb in okf-base.yaml must not expand (LT-35a)
from okf_notes import read_manifest   # and so is the read itself: bounded by the manifest limit, not the note cap
d = load_frontmatter(read_manifest(sys.argv[1], "utf-8", "replace", root=os.path.dirname(sys.argv[1])))
o = (d.get("okf_check") or {}) if isinstance(d, dict) else {}
w = o.get("owners") if isinstance(o, dict) and o.get("require_owner") is True else None
for k, v in (w.items() if isinstance(w, dict) else []):
    if not any(c in str(k) + str(v) for c in "\t\n"):
        print("%s\t%s" % (k, v))
PY
)
  : > "$TMP/owner-defaults.tsv"
  if [ -n "$pats" ]; then
    # SHORTCUT: one matcher call per note and pattern, in bash. Fine for a few hundred notes; move the loop into
    # ignore-lib.sh's matcher (one pass per pattern) if a bundle with thousands of notes makes this slow.
    # A subshell, so OKFIGNORE_PATTERNS (the loaded .okfignore) is untouched outside it.
    ( while IFS= read -r -d '' f; do
        rel=${f#"$bundle"/}; def=""
        case "$rel" in *$'\t'*|*$'\n'*) continue;; esac
        while IFS=$'\t' read -r pat own; do
          OKFIGNORE_PATTERNS=("$pat"); okfignore_match "$rel" && def=$own
        done <<< "$pats"
        [ -n "$def" ] && printf '%s\t%s\n' "$rel" "$def"
      done < <(okf_md_files "$bundle") ) > "$TMP/owner-defaults.tsv"
  fi
  # $TMP/owners.tsv (relative path, TAB, owner) is what L3 reads to show the owner on its findings.
  OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" run_layer Owner - "$bundle" "$bundle/okf-base.yaml" "$TMP/owners.tsv" "$TMP/owner-defaults.tsv" <<'PYEOF'
import json, os, pathlib, sys
try:
    sys.path[:0] = [os.environ["OKF_SCRIPTS_DIR"], os.environ["OKF_VENDOR_DIR"]]
    from okf_validate import load_frontmatter, check_actor, Report
    from okf_notes import meta, INVALID, TooLarge, read_manifest, read_note, refusal, shown
    cfg = load_frontmatter(read_manifest(sys.argv[2], "utf-8", "replace", root=os.path.dirname(sys.argv[2])))
except Exception:
    sys.exit(0)
opt = (cfg.get("okf_check") or {}) if isinstance(cfg, dict) else {}
# The values are checked once, by the shared schema (config/okf-check-block.json via run_config); this rule does not
# run when that check failed (CONFIG_RC), so here only "on or off" is read.
if not isinstance(opt, dict) or opt.get("require_owner") is not True:
    sys.exit(0)
bundle = pathlib.Path(sys.argv[1])

defaults = dict(l.rstrip("\n").split("\t", 1) for l in open(sys.argv[4], encoding="utf-8", errors="surrogateescape") if "\t" in l)
n, rows = 0, []
for p in sorted(bundle.rglob("*.md")):
    if p.name in ("index.md", "log.md") or not p.is_file():   # a dangling link is no note (okf_md_files)
        continue
    if refusal(p, root=bundle):   # --duplicates runs this on the bundle itself: a link out of it is not read
        continue
    n += 1
    rel = str(p.relative_to(bundle))
    m = meta(p, invalid=INVALID, too_large=True, root=str(bundle))
    if isinstance(m, TooLarge):   # the loader's size cap, not invalid YAML and not a missing owner (L1 reports the cap too)
        print("T|%s: the note was too large to read, so its owner was not checked: %s" % (shown(rel), m.why))
        continue
    if m is INVALID:
        print("E|%s: the frontmatter is not valid YAML, so its owner cannot be read (L1 reports the YAML error)" % shown(rel))
        continue
    raw = m.get("owner")
    if raw is not None and not isinstance(raw, str):
        # a list, a number or a boolean is not an actor; shown as JSON, never as a Python repr (0.9.8 review G-3)
        print("E|%s: owner `%s` is not an allowed actor form (an owner is one string, such as team:docs)" % (shown(rel), json.dumps(raw)))
        continue
    # The note's own owner beats a folder default.
    own = (raw or "").strip() or defaults.get(rel, "").strip()
    shape = Report()
    if own:
        check_actor(own, "owner", rel, shape)   # section 7, the same check L1 runs on generated.by
    if not own:
        print("E|%s: no owner (no owner key and no okf_check.owners default matches)" % shown(rel))
    elif shape.warnings:
        print("E|%s: owner `%s` is not an allowed actor form (section 7: human:<id>, process:<id>, <prefix>:<id> or <producer>/<version>)" % (shown(rel), own))
    elif not any(c in rel + own for c in "\t\n"):
        rows.append("%s\t%s\n" % (rel, own))
open(sys.argv[3], "w", encoding="utf-8", errors="surrogateescape").write("".join(rows))   # owners.tsv holds the real name
print("N|%d" % n)
PYEOF
  ec=$?; out=$(<"$TMP/layer.out")
  layer_stopped "$ec" && return $EXIT_DEP
  [ "$ec" -eq 0 ] || { say "  Owner            COULD NOT RUN — the owner check exited $ec"; return $EXIT_DEP; }
  [ -n "$(printf '%s\n' "$out" | sed -n 's/^N|//p')" ] || return 0
  if grep -q '^[ET]|' <<<"$out"; then   # not printf | grep -q: under pipefail a long $out read as no error (PF-1, PF-2)
    # E: a note with no owner or a bad one. T: a note the loader refused for its size, so its owner is not known: not a missing owner.
    ne=$(printf '%s\n' "$out" | grep -c '^E|'); nt=$(printf '%s\n' "$out" | grep -c '^T|'); sum=""
    [ "$ne" -eq 0 ] || sum="$ne error(s): every note needs an owner"
    [ "$nt" -eq 0 ] || sum="${sum:+$sum; }$nt note(s) too large to read"
    say "  Owner            FAIL   $sum"
    printf '%s\n' "$out" | sed -n 's/^[ET]|//p' | while IFS= read -r l; do record error "$l"; say "                   $l"; done
    return $EXIT_CONFORM
  fi
  say "  Owner            PASS   $(printf '%s\n' "$out" | sed -n 's/^N|//p') note(s) have an owner"
  return 0
}

# ------------------------------------------------------- body-size budget (okf-knowledge-gate#17)
# With okf_check.size: {max_body_chars: N} a note whose BODY (the text after the frontmatter) is longer than N characters
# is a house-rule error (exit 1, like require_owner: the bundle breaks a rule it declared; exit 2 stays "could not run"
# or "the config is wrong"). index.md and log.md are measured like any note: an agent reads them whole too, and a
# log that only ever grows is the case the budget exists for; a bundle that wants one left out lists it in .okfignore.
# Option off: nothing is printed.
run_size() {
  local bundle="$1" out ec
  [ -f "$bundle/okf-base.yaml" ] && [ -n "$PY" ] || return 0
  # A block that failed the schema is already the Config line's exit 2; its numbers are not trusted here (as run_owner).
  [ "${CONFIG_RC:-0}" -eq 0 ] || return 0
  # The notes by the one rule every walker shares (okf_md_files), so a symlinked folder is not entered.
  okf_md_files "$bundle" > "$TMP/size-files.lst" 2>/dev/null
  # okf_check.size.exclude (okf-knowledge-gate#17): globs whose notes are not measured, matched by the .okfignore matcher
  # (ignore-lib.sh) as the owners defaults are, so the three cannot disagree about what a pattern covers. The schema has
  # already refused a negated pattern. One more python only when the manifest mentions the key.
  local excl=0 pats
  if grep -q 'exclude' "$bundle/okf-base.yaml" 2>/dev/null; then
    pats=$(OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" py_with_vendor - "$bundle/okf-base.yaml" <<'PY' 2>/dev/null
import os, sys
sys.path[:0] = [os.environ["OKF_SCRIPTS_DIR"], os.environ["OKF_VENDOR_DIR"]]
from okf_validate import load_frontmatter
from okf_notes import read_manifest
d = load_frontmatter(read_manifest(sys.argv[1], "utf-8", "replace", root=os.path.dirname(sys.argv[1])))
o = (d.get("okf_check") or {}) if isinstance(d, dict) else {}
z = o.get("size") if isinstance(o, dict) else None
for p in ((z.get("exclude") or []) if isinstance(z, dict) else []):
    p = p.strip() if isinstance(p, str) else ""   # as .okfignore trims each line (ignore-lib.sh)
    if p and not any(c in p for c in "\t\n"):
        print(p)
PY
)
    if [ -n "$pats" ]; then
      # A subshell, so OKFIGNORE_PATTERNS (the loaded .okfignore) is untouched outside it; it prints the excluded count
      # and writes the notes it keeps.
      : > "$TMP/size-files.kept"
      excl=$( n=0; OKFIGNORE_PATTERNS=()
        while IFS= read -r p; do OKFIGNORE_PATTERNS+=("$p"); done <<< "$pats"
        while IFS= read -r -d '' f; do
          if okfignore_match "${f#"$bundle"/}"; then n=$((n + 1)); else printf '%s\0' "$f" >> "$TMP/size-files.kept"; fi
        done < "$TMP/size-files.lst"
        echo "$n" )
      mv "$TMP/size-files.kept" "$TMP/size-files.lst"
    fi
  fi
  OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" run_layer Size - "$bundle" "$bundle/okf-base.yaml" "$TMP/size-files.lst" <<'PYEOF'
import json, os, sys
try:
    sys.path[:0] = [os.environ["OKF_SCRIPTS_DIR"], os.environ["OKF_VENDOR_DIR"]]
    from okf_validate import load_frontmatter
    from okf_notes import body_chars, read_manifest, read_note, shown
    cfg = load_frontmatter(read_manifest(sys.argv[2], "utf-8", "replace", root=os.path.dirname(sys.argv[2])))
except Exception:
    sys.exit(0)
opt = (cfg.get("okf_check") or {}) if isinstance(cfg, dict) else {}
size = opt.get("size") if isinstance(opt, dict) else None
lim = {k: (size.get(k) if isinstance(size, dict) else None) for k in ("max_body_chars", "warn_body_chars")}
mx, wn = lim["max_body_chars"], lim["warn_body_chars"]
if not any(isinstance(v, int) and not isinstance(v, bool) for v in (mx, wn)):
    sys.exit(0)   # the values are checked once, by the shared schema (run_config)
fix = "(fix: split or move a section to a companion note; do not compress)"
bundle = sys.argv[1]
files = [f for f in open(sys.argv[3], "rb").read().decode("utf-8", "surrogateescape").split("\0") if f]
n = 0
for f in sorted(files):
    c = body_chars(f, root=bundle)
    if c is None:
        continue
    n += 1
    rel = shown(os.path.relpath(f, bundle)).replace("\n", " ").replace("\t", " ")
    # One row per measured note for --json sizes[] (okf-knowledge-gate#17): the trend shows before a note breaks.
    print("S|" + json.dumps({"note": rel, "body_chars": c, "max_body_chars": mx if isinstance(mx, int) else None,
                             "warn_body_chars": wn if isinstance(wn, int) else None}))
    if isinstance(mx, int) and c > mx:
        print("E|%s: body is %d characters, above okf_check.size.max_body_chars %d %s" % (rel, c, mx, fix))
    elif isinstance(wn, int) and c > wn:
        print("W|%s: body is %d characters, above okf_check.size.warn_body_chars %d %s" % (rel, c, wn, fix))
print("N|%d" % n)
PYEOF
  ec=$?; out=$(<"$TMP/layer.out")
  layer_stopped "$ec" && return $EXIT_DEP
  [ "$ec" -eq 0 ] || { say "  Size             COULD NOT RUN — the size check exited $ec"; return $EXIT_DEP; }
  [ -n "$(printf '%s\n' "$out" | sed -n 's/^N|//p')" ] || return 0
  printf '%s\n' "$out" | sed -n 's/^S|//p' > "$TMP/sizes.jsonl"
  local ne nw xs=""
  [ "$excl" -gt 0 ] && xs=", $excl excluded by okf_check.size.exclude"
  ne=$(printf '%s\n' "$out" | grep -c '^E|'); nw=$(printf '%s\n' "$out" | grep -c '^W|')
  if [ "$ne" -gt 0 ]; then
    say "  Size             FAIL   ${ne} note(s) over the body budget, ${nw} over the warning limit$xs"
  elif [ "$nw" -gt 0 ]; then
    say "  Size             WARN   ${nw} note(s) over the warning limit (advisory)$xs"
  else
    say "  Size             PASS   $(printf '%s\n' "$out" | sed -n 's/^N|//p') note(s) within the body budget$xs"
    return 0
  fi
  advise Size "$nw"
  printf '%s\n' "$out" | grep '^[EW]|' | while IFS= read -r l; do
    case "${l%%|*}" in E) record error "${l#?|}";; W) record warning "${l#?|}";; esac
    say "                   ${l#?|}"
  done
  [ "$ne" -eq 0 ] || return $EXIT_CONFORM
  return 0
}

# ------------------------------------------------------- declared facts (okf-knowledge-gate#15)
# With okf_check.facts a note that states a declared fact with another value is a FACT-CONFLICT: a house-rule error (exit 1,
# like require_owner and size). The patterns were checked by the shared schema (run_config). Option off: nothing is printed.
run_facts() {
  local bundle="$1" out ec nc
  [ -f "$bundle/okf-base.yaml" ] && [ -n "$PY" ] || return 0
  [ "${CONFIG_RC:-0}" -eq 0 ] || return 0
  grep -q 'facts' "$bundle/okf-base.yaml" 2>/dev/null || return 0   # no python unless the manifest mentions the key
  okf_md_files "$bundle" > "$TMP/facts-files.lst" 2>/dev/null
  # Under the watchdog (okf-limit.py, as okflint): a pattern from okf-base.yaml can backtrack for ever on a long line, and a
  # regular expression cannot be stopped from inside Python. OKF_FACTS_TIMEOUT seconds, default 60.
  local secs="${OKF_FACTS_TIMEOUT:-60}"; case "$secs" in ''|*[!0-9]*|0) secs=60 ;; esac
  run_limited "$secs" "$TMP/facts.out" env PYTHONDONTWRITEBYTECODE=1 PYTHONPATH="$VENDOR_PY${PYTHONPATH:+:$PYTHONPATH}" \
    OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" "$PY" "$HERE/okf-facts.py" "$bundle" "$bundle/okf-base.yaml" "$TMP/facts-files.lst" check
  ec=$?; out=$(cat "$TMP/facts.out" 2>/dev/null)
  [ "$ec" -ne 143 ] || { say "  Facts            COULD NOT RUN — the facts patterns timed out after $secs s (a pattern that backtracks? OKF_FACTS_TIMEOUT)"; return $EXIT_DEP; }
  [ "$ec" -eq 0 ] || { say "  Facts            COULD NOT RUN — okf-facts.py exited $ec"; return $EXIT_DEP; }
  [ -n "$(printf '%s\n' "$out" | sed -n 's/^N|//p')" ] || return 0
  printf '%s\n' "$out" | sed -n 's/^S|//p' > "$TMP/facts.jsonl"
  nc=$(printf '%s\n' "$out" | grep -c '^E|')
  if [ "$nc" -gt 0 ]; then
    say "  Facts            FAIL   $nc conflict(s) with okf_check.facts"
    printf '%s\n' "$out" | sed -n 's/^E|//p' | while IFS= read -r l; do record error "$l"; say "                   $l"; done
    return $EXIT_CONFORM
  fi
  say "  Facts            PASS   $(printf '%s\n' "$out" | sed -n 's/^N|//p' | awk -F'|' '{print $1 " fact(s), " $2 " statement(s) agree"}')"
  return 0
}

# ------------------------------------------------------- L2 graph (optional okf-memory layer, the okf-memory ecosystem)
# okf-memory (github.com/okf-memory/okf-agent-memory, MIT) finds what no layer here looks for: notes no other note links to
# (orphans) and concept links whose target is gone. Opt-in: okf_check.graph: true in okf-base.yaml, or OKF_MEMORY_BIN set.
# Only its read-only `validate` is run, on the frozen copy, under the watchdog; its findings are advisories (exit code
# unchanged). Never installed or downloaded here.
# okf_memory_bin: OKF_MEMORY_BIN, else `okf` on PATH when its help names "OKF Agent Memory": other tools are called okf too.
okf_memory_bin() {
  local b="${OKF_MEMORY_BIN:-}"
  [ -n "$b" ] || b=okf
  case "$b" in */*) ;; *) b=$(command -v "$b" 2>/dev/null) || return 1 ;; esac   # a bare name is looked up on PATH
  [ -x "$b" ] && [ -n "$PY" ] || return 1
  "$PY" "$HERE/okf-limit.py" 10 512 "$TMP/okfmem-help.out" -- "$b" --help >/dev/null 2>&1
  grep -q 'OKF Agent Memory' "$TMP/okfmem-help.out" 2>/dev/null || return 1
  printf '%s' "$b"
}
graph_wanted() {
  [ -n "${OKF_MEMORY_BIN:-}" ] && return 0
  [ -f "$1/okf-base.yaml" ] && grep -q 'graph' "$1/okf-base.yaml" 2>/dev/null || return 1   # no python unless the manifest names it
  py_with_vendor - "$1/okf-base.yaml" "$ROOT/vendor" <<'PY' 2>/dev/null
import sys
sys.path.insert(0, sys.argv[2])
from okf_validate import load_frontmatter
d = load_frontmatter(open(sys.argv[1], encoding="utf-8").read()) or {}
sys.exit(0 if isinstance(d, dict) and isinstance(d.get("okf_check"), dict) and d["okf_check"].get("graph") is True else 1)
PY
}
run_graph() {
  local bundle="$1" bin secs ec nb no
  [ "${CONFIG_RC:-0}" -eq 0 ] && graph_wanted "$bundle" || return 0
  if ! bin=$(okf_memory_bin); then
    SKIPPED=$((${SKIPPED:-0} + 1)); record skipped "L2 graph: okf-memory not found"
    say "  L2 graph         SKIPPED — okf-memory not found (set OKF_MEMORY_BIN, or put its \`okf\` on PATH): orphans and broken concept links are UNCHECKED"
    return 0
  fi
  secs="${OKF_GRAPH_TIMEOUT:-60}"; case "$secs" in ''|*[!0-9]*|0) secs=60 ;; esac
  run_limited "$secs" "$TMP/graph.out" "$bin" validate "$bundle" --json; ec=$?
  # Exit 0 or 1 (okf-memory exits 1 on a non-conformant bundle, with its report) and both keys present, else no verdict:
  # an error exit, or a changed output format, must not read as a clean graph (review 0.9.35).
  if [ "$ec" -gt 1 ] || ! OKF_SCRIPTS_DIR="$HERE" "$PY" - "$TMP/graph.out" "$TMP/graph.json" "$TMP/graph.txt" <<'PY' 2>/dev/null; then
import json, os, sys
sys.path.insert(0, os.environ["OKF_SCRIPTS_DIR"])
from okf_guard import shown
d = json.load(open(sys.argv[1], encoding="utf-8", errors="surrogateescape"))
# Both keys must be there; okf-memory v0.6.2 writes null for an empty list (review 0.9.35 round 2).
if not (isinstance(d, dict) and all(k in d and (d[k] is None or isinstance(d[k], list)) for k in ("broken_links", "orphans"))):
    sys.exit(1)
# names: spelled \xNN when they hold a control character or a byte that is not UTF-8 (shown), in the text and in --json
broken = [shown("%s -> %s" % (b.get("source_concept"), b.get("target_href"))) for b in d.get("broken_links") or []]
orphans = [shown(str(o)) for o in d.get("orphans") or []]
json.dump({"broken_links": broken, "orphans": orphans}, open(sys.argv[2], "w"))
with open(sys.argv[3], "w") as f:
    f.write("%d %d\n" % (len(broken), len(orphans)))
    f.writelines("broken link: %s\n" % b for b in broken)
    f.writelines("orphan: %s\n" % o for o in orphans)
PY
    advise "L2 graph" 1
    if [ "$ec" -eq 143 ]; then say "  L2 graph         COULD NOT RUN — okf-memory timed out after $secs s (OKF_GRAPH_TIMEOUT); not a pass"
    elif [ "$ec" -gt 1 ]; then say "  L2 graph         COULD NOT RUN — okf-memory exited $ec; not a pass"
    else say "  L2 graph         COULD NOT RUN — okf-memory exited $ec without a readable report; not a pass"; fi
    record skipped "L2 graph: okf-memory gave no readable report"
    return 0
  fi
  read -r nb no < "$TMP/graph.txt"
  if [ "$nb" -eq 0 ] && [ "$no" -eq 0 ]; then
    say "  L2 graph         PASS   no orphan note, no broken concept link (okf-memory)"
    return 0
  fi
  advise "L2 graph" $((nb + no))
  say "  L2 graph         WARN   $nb broken concept link(s), $no orphan(s) (okf-memory; advisory)"
  tail -n +2 "$TMP/graph.txt" | say_capped 20 "                   "
  return 0
}

# --facts [NAME] (okf-knowledge-gate#15): every statement of the declared facts, before an owner changes a value. A report: exit 0.
run_facts_list() {
  local bundle="$1"
  [ -n "$PY" ] || { echo "okf-check: --facts needs python3" >&2; return $EXIT_DEP; }
  run_config "$bundle" >/dev/null; CONFIG_RC=$?
  [ "$CONFIG_RC" -eq 0 ] || { run_config "$bundle"; return $EXIT_DEP; }
  okf_md_files "$bundle" > "$TMP/facts-files.lst" 2>/dev/null
  # A note whose real path is outside the bundle is not listed (okf_md_files) and is named here, on stderr.
  local rec
  while IFS= read -r -d '' rec; do
    if [ "${rec%%$'\t'*}" = "$OKF_OUTSIDE_WHY" ]; then esc_line "okf-check: --facts: ${rec#*$'\t'} — $OKF_OUTSIDE_WHY: not read" >&2; fi
  done < <(okf_refused_notes "$bundle" 2>/dev/null)
  if okfignore_present "$bundle"; then
    okfignore_load "$bundle"; [ $? -eq 2 ] && { echo "okf-check: .okfignore could not be applied, so --facts cannot run" >&2; return $EXIT_DEP; }
    okfignore_list "$bundle" | while IFS= read -r -d '' f; do printf '%s\0' "$bundle/$f"; done > "$TMP/facts-files.lst"
  fi
  [ -f "$bundle/okf-base.yaml" ] || { echo "no okf-base.yaml in $bundle: nothing to list"; return 0; }
  local secs="${OKF_FACTS_TIMEOUT:-60}" ec; case "$secs" in ''|*[!0-9]*|0) secs=60 ;; esac
  run_limited "$secs" "$TMP/facts.out" env PYTHONDONTWRITEBYTECODE=1 PYTHONPATH="$VENDOR_PY${PYTHONPATH:+:$PYTHONPATH}" \
    OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" "$PY" "$HERE/okf-facts.py" "$bundle" "$bundle/okf-base.yaml" "$TMP/facts-files.lst" list ${FACT_NAME:+"$FACT_NAME"}
  ec=$?; cat "$TMP/facts.out" 2>/dev/null
  [ "$ec" -ne 143 ] || { echo "okf-check: --facts: the patterns timed out after $secs s (OKF_FACTS_TIMEOUT)" >&2; return $EXIT_DEP; }
  return $ec
}

# ------------------------------------------------------- --duplicates (okf-knowledge-gate#10)
# Candidate duplicate pairs: the same normalized title, the same sources[].resource, or descriptions whose word overlap
# reaches okf_check.duplicates.threshold. Advisory: exit 0. A block that fails the schema is exit 2, as in a check.
run_duplicates() {
  local bundle="$1" rc
  [ -n "$PY" ] || { echo "okf-check: --duplicates needs python3" >&2; stop_json Duplicates "python3 is missing"; return $EXIT_DEP; }
  say "okf-check $VERSION — duplicates in $bundle"
  run_config "$bundle"; CONFIG_RC=$?
  [ "$CONFIG_RC" -eq 0 ] || { stop_json Config "${CONFIG_WHY:-okf-base.yaml could not be checked}"; return $EXIT_DEP; }
  # The owner check writes the effective owners ($TMP/owners.tsv) when require_owner is on; its report is not wanted here.
  run_owner "$bundle" >/dev/null 2>&1
  # .okfignore: the notes it leaves in, NUL-separated, as the L3 derived layer reads them (OKF_KEEP_LIST).
  local keep=""
  if okfignore_present "$bundle"; then
    okfignore_load "$bundle"; [ $? -eq 2 ] && { say "  Duplicates       COULD NOT RUN — .okfignore could not be applied (see the message above)"; stop_json Duplicates ".okfignore could not be applied (see the message above)"; return $EXIT_DEP; }
    okfignore_list "$bundle" > "$TMP/dup-keep.lst" 2>/dev/null && keep="$TMP/dup-keep.lst"
  fi
  OKF_KEEP_LIST="$keep" OKF_OWNERS_TSV="$TMP/owners.tsv" OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" run_layer Duplicates "$HERE/okf-duplicates.py" "$bundle" "$ROOT/config/okf-check-block.json" "$JSON" "$DUP_BODY"
  rc=$?
  if layer_stopped "$rc"; then stop_json Duplicates "$LAYER_WHY"; return $EXIT_DEP; fi
  # A script that failed may have printed half a document: under --json the stop is the document.
  if [ "$rc" -ne 0 ] && [ "$JSON" -eq 1 ]; then stop_json Duplicates "okf-duplicates.py exited $rc"; return $EXIT_DEP; fi
  cat "$TMP/layer.out"
  [ "$rc" -eq 0 ] || { say "  Duplicates       COULD NOT RUN — okf-duplicates.py exited $rc"; return $EXIT_DEP; }
  return 0
}

# ------------------------------------------------------- L2 house profile
# l2_dangling <bundle> [all]: the dangling *.md symlinks okflint cannot walk past, root-relative, NUL-separated, sorted. The same
# link set L1 and L3 skip (okf_md_files), minus what .okfignore excludes unless "all" (an ignored link still crashes okflint
# when the ignore mirror is not built). A loop (a.md -> a.md) fails -e too, so it is listed.
l2_dangling() {
  local root="${1%/}" f
  okfignore_load "$root" >/dev/null 2>&1
  # The loop runs in the left subshell of the pipe. Its find ends at the moment the loop sees end of input, and bash 4.4+
  # leaves a subshell without reaping it: the orphan stays defunct under a PID 1 that never reaps (a container with no
  # init), 10-12 per --selftest, and the run's exit trap never sees it (measured 2026-10-24: every defunct find of a
  # --selftest came from this loop). So the subshell waits for its own find; `wait` of a pid that is not its child ends at once.
  { while IFS= read -r -d '' f; do
    [ -e "$f" ] && continue
    [ -z "${2:-}" ] && okfignore_match "${f#"$root"/}" && continue
    printf '%s\0' "${f#"$root"/}"
  done < <(find -H "$root" -name .git -prune -o -type l -name '*.md' -print0 2>/dev/null)
  wait "$!" 2>/dev/null; } | sort -z
}
# l2_say_dangling <list>: one advisory line per dangling link, capped and honest about the cap by say_capped.
l2_say_dangling() {
  local f
  [ -s "$1" ] || return 0
  while IFS= read -r -d '' f; do
    printf '%s — dangling symlink: the link target does not exist\n' "$(printf '%s' "$f" | tr '\n\r\t' '   ')"
  done < "$1" | say_capped 12 "                   "
}

# l2_say_stopped <exit status>: okflint ended with 143 or 137. Only okf-limit.py's own marker proves a time limit; an exit
# without it is a kill from outside (the kernel's out-of-memory killer, a cgroup limit, an operator), and "timed out" would
# send the reader to the wrong setting.
l2_say_stopped() {
  if grep -q '^timeout' "$TMP/l2.out.limit" 2>/dev/null; then
    say "  L2 profile       COULD NOT RUN — okflint timed out after ${l2limit} s (set OKF_L2_TIMEOUT to raise the limit)"
  else
    say "  L2 profile       COULD NOT RUN — okflint was killed (out of memory or time limit); exit status $1 (OKF_L2_TIMEOUT and OKF_L2_MAX_RSS_MB set the limits okf-check itself applies)"
  fi
}

# l2_isolate: okflint crashed on the whole bundle. Find the notes it crashes on (one run per note,
# time-bounded), copy the rest into a mirror and run okflint once on that. Only for bundles of at
# most OKF_L2_ISOLATE_MAX notes (default 200): each run is about 0.2 s. Sets, in the CALLER's
# scope (bash dynamic scoping): bundle, ec, and the global L2_CRASHED. Returns 1 when it did not
# help (too many notes, no single note to blame, or the rerun crashed too).
l2_isolate() {
  local max="${OKF_L2_ISOLATE_MAX:-200}" f rel n=0 probe="$TMP/l2probe" mirror="$TMP/l2mirror" prc plimit surv=0 start=$SECONDS c skip
  local -a crashed=()
  case "$max" in ''|*[!0-9]*) max=200;; esac
  while IFS= read -r -d '' f; do n=$((n+1)); done < <(okf_md_files "$bundle")
  [ "$n" -gt 0 ] && [ "$n" -le "$max" ] || return 1
  plimit=8; [ "$l2limit" -lt "$plimit" ] && plimit="$l2limit"
  L2_CRASHED=()
  # Pass 1: which notes does okflint crash on (one run each). The whole pass shares ONE budget,
  # OKF_L2_TIMEOUT: a slow okflint must not turn into minutes of waiting.
  while IFS= read -r -d '' f; do
    [ $((SECONDS - start)) -lt "$l2limit" ] || return 1
    rel=${f#"$bundle"/}
    rm -rf "$probe"; mkdir -p "$probe/$(dirname "$rel")"
    cp "$bundle/okf-base.yaml" "$probe/" 2>/dev/null; cp "$f" "$probe/$rel" 2>/dev/null
    run_limited "$plimit" "$TMP/l2probe.out" sh -c 'cd "$1" && exec okflint validate . --manifest okf-base.yaml --json' _ "$probe"; prc=$?
    case "$prc" in
      0|1) case "${rel##*/}" in index.md|log.md) ;; *) surv=$((surv+1));; esac ;;   # concepts only
      *)   crashed+=("$rel") ;;
    esac
  done < <(okf_md_files "$bundle")
  [ "${#crashed[@]}" -gt 0 ] && [ "$surv" -gt 0 ] || return 1
  # Pass 2: a full COPY of the bundle without the crashed notes (reserved files, manifest and assets
  # stay, so okflint sees the same tree), then one run on it.
  rm -rf "$mirror"; mkdir -p "$mirror"
  while IFS= read -r -d '' f; do
    [ -f "$f" ] || continue   # cp would read a device or pipe behind a link for ever: a file, or nothing
    rel=${f#"$bundle"/}; skip=0
    for c in "${crashed[@]}"; do [ "$c" = "$rel" ] && { skip=1; break; }; done
    [ "$skip" -eq 1 ] && continue
    mkdir -p "$mirror/$(dirname "$rel")" && cp -pP "$f" "$mirror/$rel" 2>/dev/null   # -P: a link in the frozen copy (an image) stays a link, never read through
  done < <(find -H "$bundle" -name .git -prune -o \( -type f -o -type l \) -print0 2>/dev/null)   # -H, links: as okf_md_files
  okf_reap_procsub
  run_limited "$l2limit" "$TMP/l2.out" sh -c 'cd "$1" && exec okflint validate . --manifest okf-base.yaml --json' _ "$mirror"; ec=$?
  cat "$TMP/l2.out" "$TMP/l2.out.err" > "$TMP/l2.txt" 2>/dev/null
  case "$ec" in
    0|1) bundle="$mirror"; L2_MIRROR_ROOT="$mirror"
         while IFS= read -r c; do [ -n "$c" ] && L2_CRASHED+=("$c"); done < <(printf '%s\n' "${crashed[@]}" | sort)
         return 0;;
  esac
  return 1
}

# l2_wikilink_root <bundle>: okf_check.wikilink_root of the bundle's okf-base.yaml as an absolute path, else nothing. The
# value is read through okf-verify's load_block, the same schema check as run_config, so a value that failed it (exit 2
# there) is not used here.
l2_wikilink_root() {   # $1 the real bundle (the root is resolved against it), $2 the frozen copy (the manifest is read there)
  grep -qs 'wikilink_root' "${2:-$1}/okf-base.yaml" || return 0
  OKF_SCRIPTS_DIR="$HERE" py_with_vendor - "$1" "${2:-$1}" <<'PYEOF' 2>/dev/null
import importlib.util, os, sys
from importlib.machinery import SourceFileLoader
from pathlib import Path
try:
    loader = SourceFileLoader("okf_verify", os.path.join(os.environ["OKF_SCRIPTS_DIR"], "okf-verify"))
    verify = importlib.util.module_from_spec(importlib.util.spec_from_loader("okf_verify", loader))
    loader.exec_module(verify)
    rel = verify.load_block(Path(sys.argv[1]), Path(sys.argv[2])).get("wikilink_root")
    if rel:
        print(os.path.realpath(os.path.join(sys.argv[1], rel)))
except Exception:
    pass
PYEOF
}

L2_CRASHED=()
# run_profile: the L2 core, plus the crashed-note report and its exit status.
run_profile() {
  local rc k
  L2_CRASHED=()
  __l2_core "$@"; rc=$?
  if [ "${#L2_CRASHED[@]}" -gt 0 ]; then
    say "  L2 profile       COULD NOT RUN on ${#L2_CRASHED[@]} note(s) - okflint crashed on:"
    for k in "${!L2_CRASHED[@]}"; do say "                   $(printf '%s' "${L2_CRASHED[$k]}" | tr '\n\r\t' '   ')"; done
    say "                   (a validator bug, not a verdict on the note; the other notes were checked above)"
    [ "$rc" -eq "$EXIT_PROFILE" ] || rc=$EXIT_DEP
    L2_PROFILE=could_not_run
  fi
  # A layer that returned "could not run" reached no verdict: --json must not say it ran.
  [ "$rc" -eq "$EXIT_DEP" ] && [ "$L2_PROFILE" != skipped ] && L2_PROFILE=could_not_run
  return $rc
}

__l2_core() {
  # Two statements on purpose: `local a="$1" b="$a/x"` expands $a BEFORE it is
  # assigned, which under `set -u` is a fatal unbound-variable error. Caught by
  # --selftest, which is the entire reason --selftest exists.
  local bundle="$1"
  local manifest="$bundle/okf-base.yaml"
  if ! command -v okflint >/dev/null 2>&1; then
    SKIPPED=$((${SKIPPED:-0} + 1)); L2_PROFILE=skipped; record skipped "L2 profile: okflint not installed"
    # The pinned package, as --doctor names it: bare `uv tool install okflint` is the unpinned build that drew a false
    # S204 on a datetime stale_after. A pins file that names no okflint, or one okflint_target refuses, names no
    # package at all and says why.
    local l2_hint; l2_hint=$(okflint_install_hint)
    case "$l2_hint" in
      '!'*) say "  L2 profile       SKIPPED — okflint not installed, and ${l2_hint#!}" ;;
      *)    say "  L2 profile       SKIPPED — okflint not installed (install: uv tool install $l2_hint)" ;;
    esac
    say "                   house rules are NOT enforced — this is a skip, not a pass."
    # Two things are missing here, and the person needs both: the tool and the rules file.
    [ -f "$manifest" ] || say "                   there is no okf-base.yaml yet either: create a starter with: okf-check --init-house-rules '$bundle'"
    return 0
  fi
  if [ ! -f "$manifest" ]; then
    SKIPPED=$((${SKIPPED:-0} + 1))
    L2_PROFILE=skipped; record skipped "L2 profile: no okf-base.yaml in the bundle"
    say "  L2 profile       SKIPPED — no okf-base.yaml in $bundle"
    say "                   house rules are NOT enforced. Create a starter file with: okf-check --init-house-rules '$bundle'"
    say "                   (or copy $TEMPLATE)"
    return 0
  fi
  # okflint is an external tool and expands a YAML alias bomb exactly as the validator used to (935 MB in 5 s,
  # unbounded until OKF_L2_TIMEOUT). L1 has already refused such notes, so do not hand them to okflint: say so,
  # now, instead of letting it eat memory. A reached L1 verdict (exit 1) still outranks this.
  local _nbomb _nbig _what
  # The validator's own message (an error for a note, a warning for the root index.md), not a note's PATH.
  _nbomb=$(grep -Ec '^[EW]\|.*frontmatter is not valid YAML: the YAML document (expands to more than|is nested too deeply)' "$TMP/l1.txt" 2>/dev/null); _nbomb=${_nbomb:-0}
  # One huge plain value is no alias bomb (nothing expands), but okflint would read it into memory all the same: say which it is.
  _nbig=$(grep -Ec '^[EW]\|.*frontmatter is not valid YAML: the YAML document holds a single scalar' "$TMP/l1.txt" 2>/dev/null); _nbig=${_nbig:-0}
  if [ $((_nbomb + _nbig)) -gt 0 ]; then
    L2_PROFILE=could_not_run
    _what=""
    [ "$_nbomb" -gt 0 ] && _what="${_nbomb} note(s) as YAML alias bombs"
    [ "$_nbig" -gt 0 ] && _what="${_what:+$_what and }${_nbig} note(s) for one YAML value over the size limit"
    _why="expand in memory"; [ "$_nbomb" -eq 0 ] && _why="read whole into memory"
    say "  L2 profile       COULD NOT RUN — okflint was not run: L1 rejected ${_what}, which okflint would ${_why}"
    return $EXIT_DEP
  fi
  # --json, not the human output. Counting '❌' meant that an okflint whose
  # format differs — precisely the VERSION-SKEW the doctor warns about — had
  # every error rendered invisible and L2 reported PASS. Fails OPEN, in both
  # directions (a WARNING containing ❌ used to be counted as an error). The
  # documented contract is: 0 clean, 1 findings, 2 bad manifest. (R-2)
  local out ec
  # Time-bounded: a hung okflint used to stall the run for as long as it hung.
  local l2limit="${OKF_L2_TIMEOUT:-120}"
  case "$l2limit" in ''|*[!0-9]*|0) l2limit=120;; esac
  # okflint raises FileNotFoundError on a dangling *.md link and reaches no verdict. Run it on a mirror without the
  # link (the .okfignore mirror skips dangling links) and report each link below. No dangling link: no mirror, same run.
  local dlst="$TMP/l2dangling.lst" _src="${L2_SRC:-$bundle}"
  l2_dangling "$_src" > "$dlst"
  if [ "$(l2_dangling "$bundle" all | tr -d '\0' | head -c 1)" ]; then   # the ignore mirror holds none, so it needs no second one  # pipefail-safe: only the value (the first byte) is tested; the status of the substitution is never read.
    if ! okfignore_mirror "$bundle" "$TMP/l2dangling" >/dev/null 2>"$TMP/l2dangling.err"; then
      L2_PROFILE=could_not_run
      say "  L2 profile       COULD NOT RUN — the dangling symlink(s) could not be set aside for okflint: $(head -1 "$TMP/l2dangling.err" | cut -c1-160)"
      return $EXIT_DEP
    fi
    bundle="$TMP/l2dangling"; L2_MIRROR_ROOT="$bundle"
  fi
  run_limited "$l2limit" "$TMP/l2.out" sh -c 'cd "$1" && exec okflint validate . --manifest okf-base.yaml --json' _ "$bundle"; ec=$?
  cat "$TMP/l2.out" "$TMP/l2.out.err" > "$TMP/l2.txt" 2>/dev/null

  # ANY status outside the documented set means okflint did not reach a verdict —
  # a missing binary (127), a signal, an internal error. Previously only `2` was
  # handled, so a crashed validator produced "L2 PASS" and ALL GATES PASS. That
  # is lessons/shell-or-swallows-errors.md: one status carrying two meanings. (R-1)
  if [ -s "$TMP/l2.out.limit" ] && grep -q '^rss ' "$TMP/l2.out.limit"; then
    L2_PROFILE=could_not_run
    read -r _ _rss_held _rss_cap < "$TMP/l2.out.limit"
    say "  L2 profile       COULD NOT RUN — okflint exceeded ${_rss_cap} MB of memory (it held ${_rss_held} MB) and was stopped; the limit is OKF_L2_MAX_RSS_MB"
    say "                   NOT a pass: house rules were never evaluated."
    return $EXIT_DEP
  fi
  case "$ec" in
    0|1) ;;
    2)   say "  L2 profile       COULD NOT RUN — manifest rejected by okflint"
         say_capped 3 "                   " < "$TMP/l2.txt"
         return $EXIT_DEP ;;
    143|137) l2_say_stopped "$ec"
         say "                   NOT a pass: house rules were never evaluated."
         return $EXIT_DEP ;;
    *)   if l2_isolate; then :   # ec/bundle now describe the survivors; the crashed notes are in L2_CRASHED
         else
         case "$ec" in
           143|137) l2_say_stopped "$ec";;
           *)       say "  L2 profile       COULD NOT RUN — okflint exited $ec (crashed or missing)";;
         esac
         say "                   NOT a pass: house rules were never evaluated."
         say_capped 3 "                   " < "$TMP/l2.txt"
         return $EXIT_DEP
         fi ;;
  esac

  # Parse the structured report. If okflint signalled findings (exit 1) but we
  # cannot parse them, that is COULD NOT RUN — never a pass.
  local counts errs warns
  counts=$(OKF_SCRIPTS_DIR="$HERE" "$PY" - "$TMP/l2.txt" "$bundle" "$dlst" "$(l2_wikilink_root "$_src" "$bundle")" "$_src" <<'PY' 2>/dev/null
import json, os, re, sys
sys.path.insert(0, os.environ["OKF_SCRIPTS_DIR"])
from okf_guard import obsidian_path, shown
# surrogateescape: okflint prints a note name that is not UTF-8 as the raw byte; shown() below spells it \xff in the text and
# --json (errors="replace" made it U+FFFD)
raw = open(sys.argv[1], encoding="utf-8", errors="surrogateescape").read()

# `raw.find("[")` grabbed the FIRST bracket anywhere — including one inside
# okflint's pre-JSON banner (`unknown okf_version=[0.3]`), which then made the
# real report unparseable. Try every candidate start until one yields a LIST. (G-5)
doc = None
for i, ch in enumerate(raw):
    if ch != "[":
        continue
    try:
        cand = json.loads(raw[i:])
    except ValueError:
        continue
    if isinstance(cand, list):
        doc = cand
        break
# The body must be a LIST of findings. A dict (`{"findings": []}`) or anything
# else is a report we do not understand — and an unrecognised shape must never be
# summarised as "reported nothing". (G-4a)
if doc is None:
    sys.exit(1)

def sev(x):
    return str(x.get("severity", "")).lower() if isinstance(x, dict) else ""

# okflint 0.5.0 resolves a wikilink by FILE NAME only, so [[sub/b]] is reported as L001 "broken" although sub/b.md
# exists (okf-knowledge-gate#1: 2,368 of 2,477 L001 findings on one real bundle). OKF section 6.1 defines markdown links only,
# so how a wikilink resolves is a house convention, and this one matches Obsidian: a path from the bundle root, or from
# the note's own folder, with or without .md; each name spelled exactly so, else the one name equal to it under lower()
# (okf-export's case rule) and NFC (okf-export's resolve() reads both names in NFC too), on every disk and decided by that rule, not by
# the disk's own folding (okf_guard.obsidian_path: [[Sub/S]] names sub/s.md on Linux as on macOS, [[STRASSE]] never
# names straße.md). An L001 whose target is such a file is dropped and COUNTED, never hidden.
_root = os.path.realpath(sys.argv[2])
_wl_root = sys.argv[4]
def _target(x):
    """The path an L001 wikilink names, or "" for another finding."""
    if not (isinstance(x, dict) and x.get("code") == "L001"):
        return ""
    m = re.search(r"\[\[(.*)\]\]", str(x.get("message", "")))
    return m.group(1).split("|")[0].split("#")[0].strip().lstrip("/") if m else ""
def _resolves(x):
    target = _target(x)
    if not target:
        return False
    note_dir = os.path.dirname(os.path.join(_root, str(x.get("file", ""))))
    for base in (_root, note_dir):
        for cand in (target, target + ".md"):
            p = obsidian_path(base, cand)
            p = p and os.path.realpath(p)
            if p and (p == _root or p.startswith(_root + os.sep)) and os.path.isfile(p) and p.endswith(".md"):
                return True
    if _wl_root:
        for cand in (target, target + ".md"):
            lex = os.path.normpath(os.path.join(_wl_root, cand))
            if not lex.startswith(_wl_root + os.sep):
                continue
            # The names as they are on disk (Obsidian's rule), so the folder-link test below looks at real entries.
            lex = obsidian_path(_wl_root, os.path.relpath(lex, _wl_root))
            if not lex:
                continue
            # A folder link is not entered (as find -H elsewhere): no step of the path below the root may be a symlink
            # to a folder, and a note that is itself a link must stay inside the root.
            steps = os.path.relpath(os.path.dirname(lex), _wl_root).split(os.sep)
            walk = _wl_root
            for st in ([] if steps == ["."] else steps):
                walk = os.path.join(walk, st)
                if os.path.islink(walk):
                    break
            else:
                p = os.path.realpath(lex)
                if p.startswith(_wl_root + os.sep) and os.path.isfile(p) and p.endswith(".md"):
                    return True
    return False
dropped = [x for x in doc if _resolves(x)]
dropped_err = sum(1 for x in dropped if sev(x) == "error")
doc = [x for x in doc if not _resolves(x)]

# A wikilink_root one folder too shallow left every vault link an L001 with nothing to say why: name the closest folder
# above the root that holds the target. The walk stops at the home folder and the file system root, the values
# okf-verify refuses as too broad (check_node).
from collections import Counter
_above = Counter()
if _wl_root:
    _home = os.path.realpath(os.path.expanduser("~"))
    for x in doc:
        t = _target(x)
        anc = os.path.dirname(_wl_root) if t else os.sep
        while anc != os.sep and anc != _home and not _home.startswith(anc + os.sep):
            if any(c.endswith(".md") and os.path.isfile(obsidian_path(anc, c) or "") for c in (t, t + ".md")):
                _above[anc] += 1
                break
            anc = os.path.dirname(anc)

# A finding with NO severity key is not a warning — it is a finding we cannot
# classify. Counting it as a warning let okflint exit 1 while L2 said PASS. (G-4b)
errors  = [x for x in doc if sev(x) == "error"]
unknown = [x for x in doc if isinstance(x, dict) and "severity" not in x]
others  = [x for x in doc if sev(x) not in ("error",) and x not in unknown]
# One advisory per dangling *.md link okf-check set aside before okflint ran.
try:
    dangling = [d for d in open(sys.argv[3], encoding="utf-8", errors="surrogateescape").read().split("\0") if d]
except OSError:
    dangling = []
others += [{"code": "DANGLING_MD", "severity": "warning", "file": d} for d in dangling]
print(len(errors), len(others), len(unknown), len(dropped), dropped_err)
for x in errors + unknown:
    print(shown("E|%s %s — %s" % (x.get("code", "?"), x.get("file", "?"), x.get("message", ""))))
# Advisory findings grouped by rule code, most frequent first (ecosystem ticket 01): a flat
# "226 warnings" hides which okflint rule family produced them.
from collections import Counter
for code, n in sorted(Counter(str(x.get("code", "?")) for x in others).items(), key=lambda kv: (-kv[1], kv[0])):
    print("C|%s|%d" % (code.replace("|", "/"), n))
# The advisories themselves, same text format as the E rows, for `l2_advisories` in --json (okf-knowledge-gate#2). One row per
# finding, so the text is flattened: a newline in a file name or message must not forge a C| or E| row.
# Sorted: okflint reports in the disk's listing order, which differs between macOS and Linux, and --json keeps only the
# first 200, so the same bundle listed different advisories on the two systems. Code points, not a locale.
for w in sorted(shown(re.sub(r"[\r\n\t]", " ", "%s %s \u2014 %s" % (x.get("code", "?"), x.get("file", "?"), x.get("message", "")))) for x in others):
    print("W|" + w)
if _above:
    anc, n = _above.most_common(1)[0]
    src = os.path.realpath(sys.argv[5])
    print("H|%d L001 link(s) resolve from %s, a folder above wikilink_root %s" % (n, os.path.relpath(anc, src), os.path.relpath(_wl_root, src)))
PY
  ) || counts=""
  if [ -z "$counts" ]; then
    # Previously an exit-0 run with an unparseable body printed "PASS 0 errors
    # (okflint reported nothing)" — indistinguishable from a genuinely clean run.
    # An unrecognised report means house rules were NOT evaluated, whatever the
    # exit status said. (G-4a)
    say "  L2 profile       COULD NOT RUN — okflint exited $ec and its report was not a findings list"
    say "                   reason: $(grep -v '^[[:space:]]*$' "$TMP/l2.txt" | tail -1 | cut -c1-160)"
    say "                   NOT a pass: treat house rules as unevaluated."
    return $EXIT_DEP
  fi
  printf '%s' "$counts" > "$TMP/l2parsed.txt"
  errs=$(head -1 "$TMP/l2parsed.txt" | awk '{print $1}')
  warns=$(head -1 "$TMP/l2parsed.txt" | awk '{print $2}')
  unknown=$(head -1 "$TMP/l2parsed.txt" | awk '{print $3}')
  local dropped dropped_err hint
  dropped=$(head -1 "$TMP/l2parsed.txt" | awk '{print $4+0}')
  dropped_err=$(head -1 "$TMP/l2parsed.txt" | awk '{print $5+0}')
  # okflint's EXIT STATUS is authoritative about whether findings exist. If it
  # said 1 and we parsed zero errors, our classification is wrong — not okflint.
  # Failing open here is how R-2 happened. (G-4b)
  if [ "$ec" -eq 1 ] && [ "${errs:-0}" -eq 0 ] && [ "${unknown:-0}" -eq 0 ] && [ "${dropped_err:-0}" -eq 0 ]; then
    say "  L2 profile       COULD NOT RUN — okflint reported findings (exit 1) but none parsed as errors"
    say "                   NOT a pass: its report format may have changed (see VERSION-SKEW in --doctor)."
    return $EXIT_DEP
  fi
  if [ "${unknown:-0}" -gt 0 ]; then
    say "  L2 profile       FAIL   ${unknown} finding(s) with no severity — treated as errors, not warnings"
    grep '^E|' "$TMP/l2parsed.txt" | sed 's/^E|//' | while IFS= read -r _e; do record l2 "$_e"; done
    grep '^E|' "$TMP/l2parsed.txt" | sed 's/^E|//' | say_capped 12 "                   "
    return $EXIT_PROFILE
  fi
  # The L2 warnings are advisories like the Size and Trust ones: the summary line counts what the sections above list.
  advise L2 "${warns:-0}"
  # "by rule: S208 x12, S209 x4": top six codes, then a remainder count.
  local bycode
  bycode=$(awk -F'|' '$1=="C"{ if (n<6) printf "%s%s x%s", (n?", ":""), $2, $3; n++ } END { if (n>6) printf " (+%d more codes)", n-6 }' "$TMP/l2parsed.txt")
  if [ "${errs:-0}" -eq 0 ]; then
    say "  L2 profile       PASS   0 errors, ${warns:-0} warning(s) (advisory)"
    [ -n "$bycode" ] && say "                   by rule: $bycode"
    l2_say_dangling "$dlst"
    [ "${dropped:-0}" -gt 0 ] && say "                   ${dropped} path wikilink(s) resolved by okf-check (okflint reports them as L001 although the note exists)"
    hint=$(sed -n 's/^H|//p' "$TMP/l2parsed.txt"); [ -z "$hint" ] || say "                   hint: $hint"
    return 0
  fi
  say "  L2 profile       FAIL   ${errs} house-rule error(s)"
  [ -n "$bycode" ] && say "                   advisory by rule: $bycode"
  l2_say_dangling "$dlst"
  [ "${dropped:-0}" -gt 0 ] && say "                   ${dropped} path wikilink(s) resolved by okf-check (okflint reports them as L001 although the note exists)"
  hint=$(sed -n 's/^H|//p' "$TMP/l2parsed.txt"); [ -z "$hint" ] || say "                   hint: $hint"
  grep '^E|' "$TMP/l2parsed.txt" | sed 's/^E|//' | while IFS= read -r _e; do record l2 "$_e"; done
  grep '^E|' "$TMP/l2parsed.txt" | sed 's/^E|//' | say_capped 12 "                   "
  return $EXIT_PROFILE
}

# ------------------------------------------------------- L3 staleness
# One awk pass. `find` not a bare glob: an empty dir must yield an empty loop,
# not a shell error (lessons/monitor-zsh-glob-trap.md).
# ------------------------------------------------- L2 index self-consistency
# index.md is the only file in a bundle that ASSERTS a fact ABOUT the bundle,
# and it was the one file nothing checked. Measured on ~/.claude/lessons in this
# session: it claimed 43 concepts, then claimed 0 lessons in all three families,
# and this gate exited 0 both times. It is wrong again as this is written —
# "51 concepts" over a directory holding 50 — because the hand count followed
# table ROWS and one lesson is deliberately cross-listed under two families.
#
# NATIVE, not an okflint rule. L2 profile SKIPS entirely when okflint is not
# installed, and the brand-new machine this project exists to serve does not
# have it. A check that only runs where an optional dependency happens to be
# present cannot be the thing that catches a lying index.
#
# Only an explicit BOLD summary line is read. A first attempt matched any
# "<n> <word>s" in prose and mis-fired immediately on "Three families cover 37
# of the 48 lessons" — a true sentence about a subset. Verifying a declared
# total is the job; counting sentences is not.
run_index() {
  local bundle="$1"
  [ -f "$bundle/index.md" ] || { SKIPPED=$((${SKIPPED:-0} + 1)); record skipped "L2 index: no index.md in this bundle"; say "  L2 index         SKIPPED — no index.md in this bundle"; return $EXIT_OK; }
  if [ -z "$PY" ]; then
    SKIPPED=$((${SKIPPED:-0} + 1)); record skipped "L2 index: no python3"
    say "  L2 index         SKIPPED — no python3; declared counts are NOT verified"
    say "                   this is a skip, not a pass."
    return $EXIT_OK
  fi
  local out ec
  # "$PY" directly, not py_with_vendor: this reconciler reads frontmatter with a
  # regex and parses no YAML, so it needs nothing from the vendored PyYAML and
  # should not depend on it being present.
  # The reconciler lives in its own file because `--file` reads the same lines for one note; its output and status
  # are unchanged here: MISMATCH/OK/UNVERIFIABLE/SKIP lines, exit 1 when a count does not match.
  out=$("$PY" "$HERE/okf-index-reconcile.py" "$bundle"); ec=$?
  if [ "$ec" -ne 0 ] && [ "$ec" -ne 1 ]; then
    say "  L2 index         COULD NOT RUN — the reconciler exited $ec"
    say "                   NOT a pass: declared counts were never evaluated."
    return $EXIT_DEP
  fi
  local n_bad
  n_bad=$(printf '%s\n' "$out" | grep -c '^MISMATCH ' 2>/dev/null); [ -n "$n_bad" ] || n_bad=0
  if [ "$n_bad" -gt 0 ]; then
    say "  L2 index         FAIL   index.md does not describe this bundle"
    printf '%s\n' "$out" | while IFS= read -r l; do
      case "$l" in MISMATCH\ *) say "                   ${l#MISMATCH }" ;; esac
    done
    return $EXIT_PROFILE
  fi
  case "$out" in
    SKIP\ *) SKIPPED=$((${SKIPPED:-0} + 1)); record skipped "L2 index: ${out#SKIP }"; say "  L2 index         SKIPPED — ${out#SKIP }" ;;
    *)       say "  L2 index         PASS   $(printf '%s\n' "$out" | grep -c '^OK ') declared count(s) match the files on disk"
             printf '%s\n' "$out" | while IFS= read -r l; do
               case "$l" in UNVERIFIABLE\ *) say "                   not derivable from any type: \"${l#UNVERIFIABLE }\"" ;; esac
             done ;;
  esac
  return $EXIT_OK
}

# -------------------------------------------------- L3 staleness, DERIVED
# `stale_after` is a date somebody typed — a promise, not a measurement. A
# concept stamped 2099 reads as fresh forever even if the artefact it describes
# changed yesterday, so L3 has been checking the promise and calling it
# staleness.
#
# OKF v0.2 already models the measurement and nothing was using it: §5.1
# `sources[]` carries a required `resource` and an optional ISO `last_modified`,
# so a concept can record which artefact it was written against and when. No
# concept in either bundle on this machine declares one — the mechanism existed
# unused. So this is strictly opt-in: a bundle without `sources` behaves exactly
# as before.
#
# Advisory unless --fail-stale, matching declared staleness. Sources that are
# not local files (URLs, opaque identifiers) are UNMEASURABLE and said so —
# never silently counted as verified, which is the failure this layer exists to
# remove. Nothing here touches the network.
run_derived_stale() {
  local bundle="$1"   # the frozen copy: every note is read there. Sources are resolved against the real bundle ($BUNDLE).
  if [ -z "$PY" ]; then
    say "  L3 derived       SKIPPED — no python3; recorded sources are NOT compared"
    return $EXIT_OK
  fi
  local out ec
  # py_with_vendor, unlike the index reconciler: `sources` is nested structure,
  # and hand-rolling a YAML list-of-mappings parser with regexes is how a gate
  # starts quietly disagreeing with the validator standing above it.
  OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" run_layer "L3 derived" - "$bundle" "${REAL_BUNDLE:-$bundle}" <<'PYEOF'
import datetime, pathlib, sys
sys.path.insert(0, __import__("os").environ["OKF_SCRIPTS_DIR"])
from okf_guard import case_exact
try:
    import yaml
    # The bounded loader of the vendored validator: a YAML alias bomb in sources[].resource must not expand here either.
    sys.path.insert(0, __import__("os").environ["OKF_VENDOR_DIR"])
    from okf_validate import AliasBombError, load_frontmatter
except Exception:
    print("NOYAML")
    sys.exit(0)

frozen = pathlib.Path(sys.argv[1])   # where the notes are read
bundle = pathlib.Path(sys.argv[2])   # where sources are looked for
RESERVED = {"index.md", "log.md"}
stale, unmeasurable, linked, too_large = [], [], set(), []
# .okfignore: the notes it leaves in (NUL-separated, relative). Sources are resolved against the REAL bundle, the notes
# are read from the frozen copy, which holds only the notes .okfignore keeps.
import os
_kl = os.environ.get("OKF_KEEP_LIST")
keep = None
if _kl:
    try:
        keep = {x for x in open(_kl, encoding="utf-8", errors="surrogateescape").read().split("\0") if x}
    except OSError:
        keep = None

for p in sorted(frozen.rglob("*.md")):
    if p.name in RESERVED or not p.is_file():
        continue
    if keep is not None and str(p.relative_to(frozen)) not in keep:
        continue
    try:
        text = p.read_text(encoding="utf-8-sig", errors="replace")   # a regular file of at most the cap: the frozen copy holds nothing else; utf-8-sig: a BOM before the fence is no content, as L1 reads it
    except OSError:
        continue
    if not text.startswith("---"):
        continue
    end = text.find("\n---", 3)
    if end < 0:
        continue
    try:
        meta = load_frontmatter(text[3:end]) or {}
    except AliasBombError as e:   # the loader's size cap: its sources are unread, which is not "no sources" (L1 reports the cap too)
        too_large.append((str(p.relative_to(frozen)), str(e)))
        continue
    except Exception:
        continue
    if not isinstance(meta, dict):
        continue
    srcs = meta.get("sources")
    if not isinstance(srcs, list):
        continue
    rel = str(p.relative_to(frozen))
    for src in srcs:
        if not isinstance(src, dict):
            continue
        res = str(src.get("resource", "")).strip()
        recorded = src.get("last_modified")
        if not res or recorded is None:
            # Nothing to compare against. Not a finding — a concept may cite a
            # source without dating it, and guessing would invent staleness.
            continue
        cand = [(bundle / rel).parent / res, bundle / res, pathlib.Path(res)]
        # Case-exact, the citation rule of okf-verify (D-11): on a case-insensitive disk SRC.txt was measured through
        # src.txt, on Linux it was not. Only the cited part below the folder it shares with the bundle is judged.
        target = next((c for c in cand if c.is_file() and case_exact(c, bundle)), None)
        if target is None:
            # Name a link only when it is the cause: every name is there as written, a link lies on the path inside the
            # bundle, and the path does not resolve case-exact through it (its target is missing, or spelled in another
            # case where the disk ignores case). "not a local file" is false for the second. A wrong name below a correct
            # link (`dok/F.TXT`) or a missing file keeps the plain message.
            if any(case_exact(c, bundle, False) and not (c.exists() and case_exact(c, bundle))
                   and any(q.is_symlink() for q in (c, *c.parents) if bundle in q.parents) for c in cand):
                linked.add((rel, res))
            unmeasurable.append((rel, res))
            continue
        try:
            mtime = datetime.date.fromtimestamp(target.stat().st_mtime)
            rec = datetime.date.fromisoformat(str(recorded))
        except (OSError, ValueError):
            unmeasurable.append((rel, res))
            continue
        if mtime > rec:
            stale.append((rel, res, str(rec), mtime.isoformat()))

for rel, res, rec, mt in stale:
    print(f"STALE {rel}: {res} changed {mt}, but this concept records it as of {rec}")
for rel, res in unmeasurable:
    why = "is a link whose target is missing or spelled in another case" if (rel, res) in linked else "is not a local file"
    print(f"UNMEASURABLE {rel}: {res} {why} — freshness could not be measured")
for rel, why in too_large:
    print(f"TOOLARGE {rel}: the note was too large to read, so its sources were not compared: {why}")
sys.exit(1 if stale else 0)
PYEOF
  ec=$?; out=$(<"$TMP/layer.out")
  layer_stopped "$ec" && return $EXIT_DEP
  if [ "$ec" -ne 0 ] && [ "$ec" -ne 1 ]; then
    say "  L3 derived       COULD NOT RUN — the source comparison exited $ec"
    say "                   NOT a pass: recorded sources were never compared."
    return $EXIT_DEP
  fi
  case "$out" in
    NOYAML*) say "  L3 derived       SKIPPED — PyYAML unavailable; sources NOT compared"; return $EXIT_OK ;;
    "")      return $EXIT_OK ;;   # no concept declares sources: silent by design
  esac
  local n_stale
  n_stale=$(printf '%s\n' "$out" | grep -c '^STALE ' 2>/dev/null); [ -n "$n_stale" ] || n_stale=0
  # TOOLARGE: a note the loader refused for its size, so its sources are unread: the layer fails (as Owner), --fail-stale or not.
  local n_big
  n_big=$(printf '%s\n' "$out" | grep -c '^TOOLARGE ' 2>/dev/null); [ -n "$n_big" ] || n_big=0
  if [ "$n_big" -gt 0 ]; then
    say "  L3 derived       FAIL   $n_big note(s) too large to read"
    printf '%s\n' "$out" | sed -n 's/^TOOLARGE //p' | while IFS= read -r l; do record error "$l"; say "                   $l"; done
  fi
  printf '%s\n' "$out" | while IFS= read -r l; do
    case "$l" in
      STALE\ *)        say "  L3 derived       ${l#STALE }" ;;
      UNMEASURABLE\ *) say "  L3 derived       ${l#UNMEASURABLE }" ;;
    esac
  done
  if [ "$n_stale" -gt 0 ]; then
    if [ "$FAIL_STALE" -eq 1 ]; then
      say "                   a recorded source has moved since the concept was written"
      return $EXIT_STALE
    fi
    say "                   advisory; use --fail-stale to make this blocking"
  fi
  [ "$n_big" -eq 0 ] || return $EXIT_CONFORM
  return $EXIT_OK
}

run_staleness() {
  local bundle="$1" today report scan_rc
  # OKF_TODAY pins "now" for tests. A value that is not YYYY-MM-DD is refused: applied as-is,
  # "zzz" flags everything and "1999-01-01" hides every expiry with nothing in the output.
  today=${OKF_TODAY:-$(date -u +%Y-%m-%d)}
  case "$today" in
    [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]) ;;
    *) say "  L3 staleness     COULD NOT RUN (OKF_TODAY='$today' is not YYYY-MM-DD)"; return $EXIT_DEP ;;
  esac
  [ -z "${OKF_TODAY:-}" ] || say "  L3 staleness     NOTE   date pinned by OKF_TODAY=$today"
  # NO `-maxdepth 1`: L1 walks the whole tree (`rglob`), so bounding L3 to the top
  # level made every NESTED concept invisible to staleness while L1 counted it —
  # the E-6b bug one level deeper, and worse. This repo's own .okf keeps all its
  # concepts in subdirectories, so L3 was scanning ZERO of them and reporting
  # "nothing expired" from an empty set. Caught by E-9.
  #
  # okf_md_files (l3-lib.sh), not a bare `find -type f`: a SYMLINK to a .md never matches `-type f`, so L3
  # silently skipped symlinked concepts that L1 counted (python is_file() follows links), and an expired
  # symlinked concept read as "nothing expired". It also drops broken links (they cannot be read) and does
  # not enter symlinked FOLDERS, as the validator does. Same class as lessons/readdir-symlink-dirent-trap.md.
  # Caught by E-6b.
  # `find -print0` piped straight to xargs -0. The previous `find | tr '\n' '\0'`
  # split on newlines, so a bundle path CONTAINING a newline was cut into
  # fragments and L3 silently scanned nothing — same class as E-2b, which had
  # only ever covered spaces. (R-7)
  #
  # `b` keeps the path RELATIVE TO THE BUNDLE rather than a basename: now that
  # the scan is recursive, two expired `notes.md` in different directories
  # rendered as two identical, unactionable lines. Introduced by the E-9 fix
  # itself. (R-8)
  # root travels via the ENVIRONMENT, not `-v`: awk rejects a newline in a -v
  # assignment outright ("awk: newline in string"), which killed L3 for any
  # bundle path containing one. ENVIRON has no such restriction. (R-7)
  # Prefix-assigned on the xargs stage, NOT exported: `export` here leaked the
  # name into every process spawned afterwards, the same shape as G-2's
  # PYTHONPATH. No consumer reads it today — G-2 was also harmless until okflint
  # silently changed parser. xargs passes its environment to awk, so ENVIRON
  # still sees it and R-7 (newline-safe root) is preserved. (G-12)
  # A byte order mark at the head of a note is NOT content: L1, Trust and the derived L3 read every note as utf-8-sig
  # (okf_notes.py). Without the same strip here the opening fence reads as a mark and "---", l3_begin answers "nofm",
  # and an expired note leaves the scan without a line — so --fail-stale exited 0 on it.
  # LC_ALL=C: this scan compares bytes; in the C locale every awk counts the mark's three bytes as three characters,
  # the same count the shell's printf gives the -v value, so index() finds the mark at position 1 and substr() drops
  # exactly it. In a UTF-8 locale a multibyte-aware awk counts it as one character on both sides, which agrees too;
  # under C both sides are bytes by POSIX, so the strip does not depend on which awk the host ships.
  report=$(okf_md_files "$bundle" | OKF_L3_ROOT="$bundle/" xargs -0 env LC_ALL=C awk -v today="$today" -v bom="$(printf '\357\273\277')" "$L3_AWK_LIB"'
    BEGIN { root = ENVIRON["OKF_L3_ROOT"] }
    { sub(/\r$/, "") }   # CRLF notes: "---\r" never equalled "---" (LT-02)
    FNR==1 { if (index($0, bom) == 1) $0 = substr($0, length(bom) + 1)
             # the mark is not content: dropped before the fence test, as every other layer reads a note
             b=FILENAME; n=index(b,root); if (n==1) b=substr(b,length(root)+1)
             base=b; sub(/^.*\//,"",base)
             skip=(l3_begin($0, base=="index.md"||base=="log.md") != "open"); next }
    skip { next }
    l3_line($0) {
      if (L3_sa!="" && !okfisdate(L3_sa)) printf "  malformed %s (stale_after %s is not a date)\n", b, L3_sa   # LT-03d
      else if (L3_sa!="" && L3_sa<today) printf "  expired  %s (stale_after %s)\n", b, L3_sa
      if (L3_st!="" && !okfstatusok(L3_st)) printf "  status   %s (%s)\n", b, L3_st
    }
  ' 2>/dev/null; exit "${PIPESTATUS[1]}")
  scan_rc=$?
  # A crashed awk printed nothing and nothing read as "PASS nothing expired" (ticket 07).
  if [ "$scan_rc" -ne 0 ]; then say "  L3 staleness     COULD NOT RUN (the awk/xargs scan exited $scan_rc)"; return $EXIT_DEP; fi
  if [ -z "$report" ]; then say "  L3 staleness     PASS   nothing expired"; return 0; fi
  # Ownership: each finding ends with its note's owner, so the text and --json stale[]/lifecycle[] both carry it.
  # The path is everything between the kind word and the LAST " (", so a path with spaces or brackets survives.
  if [ -s "$TMP/owners.tsv" ]; then
    report=$(printf '%s\n' "$report" | awk -F'\t' 'NR==FNR { o[$1]=$2; next }
      { s=$0; sub(/^ +[a-z]+ +/, "", s); pos=0; t=s
        while ((j=index(t, " (")) > 0) { pos+=j; t=substr(t, j+1) }
        rel=(pos > 0) ? substr(s, 1, pos-1) : s
        if ((rel in o) && o[rel] != "") $0 = $0 " owner " o[rel]
        print }' "$TMP/owners.tsv" -)
  fi
  # "expired" and "malformed stale_after" are STALENESS. A status outside draft/stable/deprecated (OKF 5.4) is a lifecycle
  # finding that L1 also warns about: counting it as "need attention" beside the expired notes made 4 overdue notes read as
  # 84, and made --fail-stale exit 4 on a bundle in which nothing had expired (okf-knowledge-gate#3).
  local n_stale n_status
  # grep -a: a note name may hold a byte that is not UTF-8. Under a UTF-8 locale grep reads that line as binary and
  # drops it from its output while -c still counts it: "3 concept(s) need attention" listed 2 (S30-CF-L1u).
  n_stale=$(printf '%s\n' "$report" | grep -aEc '^ +(expired|malformed) '); n_status=$(printf '%s\n' "$report" | grep -aEc '^ +status ')
  advise L3 $((n_stale + n_status))
  if [ "$n_stale" -gt 0 ]; then
    say "  L3 staleness     ${n_stale} concept(s) need attention"
    # through say(), or --json is corrupted by the detail lines (R-3)
    printf '%s\n' "$report" | grep -aE '^ +(expired|malformed) ' | sed 's/^ *//' | while IFS= read -r _e; do record stale "$_e"; done
    printf '%s\n' "$report" | grep -aE '^ +(expired|malformed) ' | say_capped 10 ""
  else
    say "  L3 staleness     PASS   nothing expired"
  fi
  if [ "$n_status" -gt 0 ]; then
    say "  L3 lifecycle     ${n_status} concept(s) have a status outside ${L3_STATUS//,/, } (OKF 5.4; L1 warns about them too)"
    printf '%s\n' "$report" | grep -aE '^ +status ' | sed 's/^ *//' | while IFS= read -r _e; do record lifecycle "$_e"; done
    printf '%s\n' "$report" | grep -aE '^ +status ' | say_capped 10 ""
  fi
  [ "$FAIL_STALE" -eq 1 ] && [ "$n_stale" -gt 0 ] && return $EXIT_STALE
  return 0
}

# ------------------------------------------------------------------ selftest
# A gate is only verified when you have watched it FAIL. Each probe plants a
# defect that MUST be caught, and the baseline must be clean — so a probe that
# passes for the wrong reason (a gate that fires on everything) also fails here.
selftest() {
  local fails=0 b="$TMP/selftest-bundle" skipped=""
  mkdir -p "$b"
  printf -- '---\nokf_version: "0.2"\n---\n# Selftest\n' > "$b/index.md"
  printf -- '# Log\n\n## 2026-01-01\n* created\n' > "$b/log.md"
  printf -- '---\ntype: Lesson\ntitle: Baseline\ndescription: Clean concept.\nstatus: stable\ntags: [t]\ngenerated:\n  by: human:selftest\n  at: "2026-01-01"\nstale_after: "2099-01-01"\n---\n\nbody\n' > "$b/good.md"
  [ -f "$TEMPLATE" ] && sed 's/^  name: CHANGE ME/  name: Selftest/' "$TEMPLATE" > "$b/okf-base.yaml"

  probe() { # name | expect-marker | layer-fn | file | content
    local name="$1" marker="$2" fn="$3" f="$4" content="$5" out
    # A probe on a file the baseline has (index.md) puts the original back, so later probes see a clean bundle.
    # An empty file name plants nothing (the L0 probe breaks the install, not the bundle).
    [ -n "$f" ] && [ -f "$b/$f" ] && cp -p "$b/$f" "$TMP/selftest.keep"
    [ -n "$f" ] && printf '%b' "$content" > "$b/$f"
    out=$("$fn" "$b" 2>&1; true)          # do NOT set JSON=1 here: say() would
    [ -n "$f" ] && rm -f "$b/$f"           # swallow the very output we grep
    [ -f "$TMP/selftest.keep" ] && mv "$TMP/selftest.keep" "$b/$f"
    # A here-string, never `printf | grep -q`: under pipefail that pipe is false when grep exits at its match before printf
    # has written everything (SIGPIPE, PIPESTATUS "141 0"), so a gate that fired read as NOT FIRED under CPU load (H-3b).
    if grep -q "$marker" <<<"$out"; then
      say "    FIRED      $name"
    else
      say "    NOT FIRED  $name  (expected to match: $marker)"
      # Through say(), like every other line here. Inert today — the `selftest)`
      # dispatch forces JSON=0 (R-5) — but a raw write is only safe BECAUSE of
      # that line. Lift it and this dump corrupts --json output again (R-3). No
      # runtime test can reach this: the two flags cannot coexist. (G-6)
      printf '%s\n' "$out" | say_capped 4 "               "
      fails=$((fails+1))
    fi
  }

  say "okf-check $VERSION — selftest (each gate must catch input that should trip it)"
  say "  baseline must be clean first:"
  local base; base=$(run_conformance "$b" 2>&1)
  if grep -q "PASS" <<<"$base"; then say "    CLEAN    baseline bundle passes L1"
  else say "    BASELINE DIRTY — probes below prove nothing"; say "$base"; fails=$((fails+1)); fi

  say "  L0 (doctor):"
  # The doctor must notice a missing vendored validator: point it at a path that does not exist (bash dynamic scope).
  _l0_probe() { local VALIDATOR="$1/no-such-okf_validate.py"; doctor; }
  probe "validator missing" "MISSING from" _l0_probe "" ""

  say "  L1 (spec conformance):"
  probe "no frontmatter -> §11.1" "11.1" run_conformance "bad.md" 'no frontmatter here\n'
  probe "empty type -> §11.2"     "11.2" run_conformance "bad.md" '---\ntype: ""\n---\nbody\n'

  if command -v okflint >/dev/null 2>&1 && [ -f "$b/okf-base.yaml" ]; then
    say "  L2 (house profile):"
    probe "missing stale_after -> F102"  "F102" run_profile "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\n---\nbody\n'
    probe "status outside vocab -> F105" "F105" run_profile "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: current\nstale_after: "2099-01-01"\n---\nbody\n'
    # L2 runs on the .okfignore mirror, which must still hold the non-markdown files a note links to. The control
    # (a link to a missing file must give L002) keeps the probe from passing because the L002 check went dead.
    _mirror_probe() {
      local src="$TMP/selftest-ign" mir="$TMP/selftest-ign-mirror" img l2n ctl
      rm -rf "$src"; mkdir -p "$src/archive" "$src/img"
      cp -p "$1/index.md" "$1/log.md" "$1/okf-base.yaml" "$src/"
      printf 'png' > "$src/img/pic.png"; printf 'old\n' > "$src/archive/old.md"; printf 'archive/\n' > "$src/.okfignore"
      for img in pic missing; do
        printf -- '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2099-01-01"\n---\n\n![x](img/%s.png)\n' "$img" > "$src/n.md"
        okfignore_mirror "$src" "$mir" >/dev/null 2>&1 || return 1
        run_profile "$mir" >/dev/null 2>&1
        if [ "$img" = pic ]; then l2n=$(grep -Ec '"code": *"L002"' "$TMP/l2.txt"); else ctl=$(grep -Ec '"code": *"L002"' "$TMP/l2.txt"); fi
      done
      [ "${l2n:-1}" -eq 0 ] && [ "${ctl:-0}" -gt 0 ] && echo "linked file kept in the mirror"
    }
    probe "ignored folder and a linked image" "linked file kept in the mirror" _mirror_probe "" ""
    # a bundle inside a larger vault with okf_check.wikilink_root must resolve a vault-root link to an existing note
    # and still report one to a missing note (the control: a probe that only drops every L001 would pass the first half).
    _wikilink_root_probe() {
      local vault="$TMP/selftest-wr" bun="$TMP/selftest-wr/p/bundle" tgt hit miss
      rm -rf "$vault"; mkdir -p "$bun"
      printf '# R\n' > "$vault/p/README.md"
      cp -p "$1/index.md" "$1/log.md" "$bun/"
      { cat "$1/okf-base.yaml"; printf 'okf_check:\n  wikilink_root: ../..\n'; } > "$bun/okf-base.yaml"
      for tgt in README MISSING; do
        printf -- '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2099-01-01"\n---\n\n[[p/%s]]\n' "$tgt" > "$bun/n.md"
        if [ "$tgt" = README ]; then hit=$(run_profile "$bun" 2>&1); else miss=$(run_profile "$bun" 2>&1); fi
      done
      grep -q 'resolved by okf-check' <<<"$hit" && ! grep -q 'L001 x' <<<"$hit" \
        && grep -q 'L001 x1' <<<"$miss" && echo "wikilink_root resolves an existing target only"
    }
    probe "wikilink_root resolves an existing target only" "wikilink_root resolves an existing target only" _wikilink_root_probe "" ""
  else
    say "  L2 (house profile): SKIPPED — okflint absent, so its gates are UNVERIFIED here"
    skipped="$skipped, L2 (house profile)"
  fi

  if _omb=$(okf_memory_bin); then
    say "  L2 graph (okf-memory):"
    _graph_probe() { local OKF_MEMORY_BIN="$_omb"; run_graph "$1"; }
    probe "broken concept link" "broken link: bad.md -> missing.md" _graph_probe "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2099-01-01"\n---\nSee [x](missing.md).\n'
  else
    say "  L2 graph (okf-memory): SKIPPED — okf-memory absent (optional, opt-in layer)"
  fi

  say "  L2 (index):"
  # The baseline holds one concept; an index.md that declares five does not describe it.
  probe "index.md count wrong" "does not describe this bundle" run_index "index.md" '---\nokf_version: "0.2"\n---\n# Selftest\n\n**5 notes**\n'

  say "  Trust (C4):"
  # A trust layer that stops firing must fail the selftest too: a gate that cannot fail is worthless.
  probe "draft + human verifier -> C4" "draft with human verification" run_trust "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: draft\ngenerated:\n  by: agent/1\n  at: "2026-01-01"\nverified:\n  - by: human:selftest\n    at: "2026-02-01"\nstale_after: "2099-01-01"\n---\nbody\n'

  probe "lookalike human: -> named" "only looks like \`human:\`" run_trust "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\ngenerated:\n  by: agent/1\n  at: "2026-01-01"\nverified:\n  - by: "\\u04bb\\u03c5\\u043c\\u0430\\u043f:selftest"\n    at: "2026-02-01"\nstale_after: "2099-01-01"\n---\nbody\n'
  # A zero-width space inside the prefix: it renders as nothing, so the claim reads as human: while no tool does.
  probe "invisible character in human: -> named" "only looks like \`human:\`" run_trust "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\ngenerated:\n  by: agent/1\n  at: "2026-01-01"\nverified:\n  - by: "hu\\u200bman:selftest"\n    at: "2026-02-01"\nstale_after: "2099-01-01"\n---\nbody\n'

  say "  Config (okf_check block):"
  # A block the schema refuses must stop the run (exit 2), never be read as "nothing declared".
  _cfg_probe() {
    local had=0; [ -f "$1/okf-base.yaml" ] && had=1 && cp -p "$1/okf-base.yaml" "$TMP/selftest-cfg.keep"
    printf 'okf_check:\n  no_such_option: true\n' >> "$1/okf-base.yaml"
    run_config "$1"
    if [ "$had" = 1 ]; then mv "$TMP/selftest-cfg.keep" "$1/okf-base.yaml"; else rm -f "$1/okf-base.yaml"; fi
  }
  probe "unknown okf_check option" "no_such_option is not a known key" _cfg_probe "" ""

  say "  L3 (staleness):"
  # Marker is "need attention", NOT "expired": the PASS line reads "nothing
  # expired", so grepping for "expired" matches success and failure alike — a
  # tautological probe that can never fail. Found by mutation-testing.
  probe "expired stale_after" "need attention" run_staleness "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2000-01-01"\n---\nbody\n'

  say "  L3 (derived staleness):"
  # good.md was written seconds ago; a note that records it as of 2000-01-01 cites a source that has moved since.
  probe "recorded source changed" "records it as of" run_derived_stale "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2099-01-01"\nsources:\n  - resource: good.md\n    last_modified: "2000-01-01"\n---\nbody\n'

  say "  Successor (deprecated_requires):"
  # The option is switched on for this probe only: the manifest is put back before the next probe (review F-A).
  _succ_probe() {
    local BUNDLE="$1" rc
    [ -f "$1/okf-base.yaml" ] && cp -p "$1/okf-base.yaml" "$TMP/selftest.base"
    printf 'okf_check:\n  deprecated_requires: superseded_by\n' >> "$1/okf-base.yaml"
    run_successor "$1"; rc=$?
    if [ -f "$TMP/selftest.base" ]; then mv "$TMP/selftest.base" "$1/okf-base.yaml"; else rm -f "$1/okf-base.yaml"; fi
    return $rc
  }
  probe "deprecated, no superseded_by" "no superseded_by names its successor" _succ_probe "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: deprecated\nstale_after: "2099-01-01"\n---\nbody\n'

  say "  Owner (require_owner):"
  # require_owner is switched on for this probe only, like the Successor probe (the 0.9.7 review rule).
  _owner_probe() {
    local BUNDLE="$1" CONFIG_RC=0 rc
    [ -f "$1/okf-base.yaml" ] && cp -p "$1/okf-base.yaml" "$TMP/selftest.base"
    printf 'okf_check:\n  require_owner: true\n' >> "$1/okf-base.yaml"
    run_owner "$1"; rc=$?
    if [ -f "$TMP/selftest.base" ]; then mv "$TMP/selftest.base" "$1/okf-base.yaml"; else rm -f "$1/okf-base.yaml"; fi
    return $rc
  }
  probe "note without an owner" "bad.md: no owner" _owner_probe "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2099-01-01"\n---\nbody\n'

  say "  Size (okf_check.size):"
  # The limit is set for this probe only (50 characters; the baseline notes are shorter), like the Owner probe.
  _size_probe() {
    local BUNDLE="$1" CONFIG_RC=0 rc
    [ -f "$1/okf-base.yaml" ] && cp -p "$1/okf-base.yaml" "$TMP/selftest.base"
    printf 'okf_check:\n  size:\n    max_body_chars: 50\n' >> "$1/okf-base.yaml"
    local o; o=$(run_size "$1"; echo "rc=$?")
    printf '%s\n' "$o"
    rc=${o##*rc=}
    if [ -f "$TMP/selftest.base" ]; then mv "$TMP/selftest.base" "$1/okf-base.yaml"; else rm -f "$1/okf-base.yaml"; fi
    # Control leg: only bad.md may be listed. A rule that flags every note also "finds" bad.md.
    if [ "$(printf '%s\n' "$o" | grep -c 'body is ')" -eq 1 ] && grep -q 'bad.md: body is 60 characters' <<<"$o"; then
      echo "size probe: bad.md listed, the notes under the limit are not"
    fi
    return $rc
  }
  probe "body over the limit" "size probe: bad.md listed, the notes under the limit are not" _size_probe "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2099-01-01"\n---\n123456789012345678901234567890123456789012345678901234567890'

  say "  Facts (okf_check.facts):"
  # A fact is declared for this probe only, and the planted note states another value (okf-knowledge-gate#15).
  _facts_probe() {
    local BUNDLE="$1" CONFIG_RC=0 rc
    [ -f "$1/okf-base.yaml" ] && cp -p "$1/okf-base.yaml" "$TMP/selftest.base"
    printf 'okf_check:\n  facts:\n    probe.count:\n      value: "7"\n      patterns: ["probe count: (\\\\d+)"]\n' >> "$1/okf-base.yaml"
    run_facts "$1"; rc=$?
    if [ -f "$TMP/selftest.base" ]; then mv "$TMP/selftest.base" "$1/okf-base.yaml"; else rm -f "$1/okf-base.yaml"; fi
    return $rc
  }
  probe "a note states another value" 'bad.md:8: FACT-CONFLICT probe.count states "5"' _facts_probe "bad.md" '---\ntype: Lesson\ntitle: T\ndescription: D\nstatus: stable\nstale_after: "2099-01-01"\n---\nThe probe count: 5\n'

  say "  Duplicates (--duplicates):"
  # A note titled like the baseline note (good.md, "Baseline") must be listed as a same-title pair.
  _dup_probe() { local DUP_BODY=0; run_duplicates "$1"; }
  probe "same title" "title 1.00" _dup_probe "bad.md" '---\ntype: Lesson\ntitle: baseline!\ndescription: Another text.\nstatus: stable\nstale_after: "2099-01-01"\n---\nother body\n'

  say "  Duplicates (--duplicates-body):"
  # A note whose body equals the baseline note's ("body") must be listed as a body pair.
  # Two notes with one body of at least 5 words (a shorter body is a stub, never a body signal): the planted note and a
  # copy under another title and description, so only the body can pair them.
  _body_probe() {
    local DUP_BODY=1
    sed -e 's/^title: .*/title: Copy/' -e 's/^description: .*/description: Third text./' "$1/bad.md" > "$1/bad-copy.md"
    run_duplicates "$1"; rm -f "$1/bad-copy.md"
  }
  probe "same body" "body 1.00" _body_probe "bad.md" '---\ntype: Lesson\ntitle: Other\ndescription: Another text.\nstatus: stable\nstale_after: "2099-01-01"\n---\nthe same body text in both notes\n'

  say "  Scoped (--file):"
  # The edit hook reads "nothing printed" as a clean note, so a helper that loses its findings must fail here.
  _scoped_probe() { run_scoped "$1" "$1/bad.md"; }
  probe "note without frontmatter" "bad.md: L1 error: " _scoped_probe "bad.md" 'no frontmatter here\n'
  # --file runs the note-local house-profile check against the bundle's okf-base.yaml. A --file that stops reading it
  # would go silent on exactly the note the release gate fails, so the probe plants a type the profile does not declare.
  # Guarded as the L2 (house profile) probes are: without okflint the profile is SKIPPED above, and a probe that cannot
  # fire would turn a skip into exit 5.
  if command -v okflint >/dev/null 2>&1; then
    probe "note whose type the house profile does not declare" "bad.md: L2 profile error: F101" _scoped_probe "bad.md" '---\ntype: notatype\ntitle: T\ndescription: D\ntags: [t]\nstatus: stable\ngenerated:\n  by: human:t\n  at: "2026-01-01"\nstale_after: "2099-01-01"\n---\nbody\n'
  fi

  say "  Refused notes:"
  # A note that is a device, a pipe or a folder is named and never listed for a layer. The probe plants /dev/null behind a
  # link (it returns EOF at once) and a folder named x.md, and reads NEITHER: it asks only for the lists. The control leg:
  # the regular notes stay listed, so a rule that refuses everything does not pass.
  _refuse_probe() {
    local d="$TMP/selftest-refuse" named listed
    rm -rf "$d"; mkdir -p "$d/dir.md"
    cp -p "$1/index.md" "$1/good.md" "$d/"; "$PY" -c 'import os, sys; os.symlink("/dev/null", sys.argv[1])' "$d/dev.md"   # no `ln` on a minimal PATH
    named=$(okf_refused_notes "$d" | tr '\0' '\n'); listed=$(okf_md_files "$d" | tr '\0' '\n')
    grep -q 'not a regular file.*dev.md' <<<"$named" && grep -q "$OKF_FOLDER_WHY.*dir.md" <<<"$named" \
      && ! grep -q 'good.md' <<<"$named" && ! grep -q 'dev.md' <<<"$listed" && grep -q 'good.md' <<<"$listed" \
      && echo "refusal probe: device and folder named and not listed, regular notes listed"
  }
  probe "device and folder refused" "refusal probe: device and folder named and not listed, regular notes listed" _refuse_probe "" ""

  say ""
  # A skipped probe is a gate nobody watched fire: the verdict names it instead of saying "every gate" (S3-E1).
  if [ "$fails" -eq 0 ] && [ -n "$skipped" ]; then
    say "  SELFTEST PASS — every probed gate fires; SKIPPED, so UNVERIFIED here: ${skipped#, }"; return 0
  fi
  if [ "$fails" -eq 0 ]; then say "  SELFTEST PASS — every gate still fires"; return 0; fi
  say "  SELFTEST FAIL — $fails gate(s) stopped firing. Do NOT trust a green okf-check run."
  return $EXIT_SELFTEST
}

# ---------------------------------------------------------------------- main
TMP=$(mktemp -d 2>/dev/null || mktemp -d -t okfcheck)
TMP_REAL=$(cd -P "$TMP" 2>/dev/null && pwd) || TMP_REAL=$TMP   # say() cuts the copies out of a message under both spellings
# Before anything writes "$TMP/...": with an empty TMP each of those paths is at the filesystem root (/refused.lst).
[ -n "$TMP" ] && [ -d "$TMP" ] || { echo "okf-check: cannot make a temporary folder (TMPDIR=${TMPDIR:-unset}) - no verdict is possible" >&2; exit $EXIT_DEP; }
# On every way out, including an outside TERM or Ctrl-C, the limited command's tree is stopped first.
trap 'stop_limited; rm -rf "$TMP"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

case "$MODE" in
  # Prints the E-7 change-detection fingerprint. Exists so that detection can be
  # tested DETERMINISTICALLY: the race-based test could only SKIP when it missed
  # its window, and a mutation re-adding `-maxdepth 1` to the fingerprint slipped
  # through exactly that way. Also answers "why did it say CONCURRENT?".
  fingerprint) [ -n "$BUNDLE" ] || { echo "usage: okf-check --fingerprint <bundle>" >&2; exit 64; }
               [ -d "$BUNDLE" ] || not_a_dir "$BUNDLE"
               # The R-6 fail-closed guard was added to the normal path in the
               # same commit that introduced this mode, and not ported here: an
               # unreadable directory produced empty output and exit 0, a silent
               # clean read of a path we were never allowed to see. (G-3)
               ls "$BUNDLE" >/dev/null 2>&1 || {
                 esc_line "error: $BUNDLE is not readable — cannot fingerprint it (this is not 'unchanged')" >&2
                 stop_json "Bundle read" "the bundle cannot be read, so it cannot be fingerprinted"
                 exit $EXIT_DEP; }
               # ...and every directory below it, or a fingerprint taken over a
               # subtree we cannot see compares equal to itself forever. (G-8)
               _u=$(unreadable_dirs "$BUNDLE")
               [ -z "$_u" ] || {
                 esc_line "error: $BUNDLE contains unreadable directories — a fingerprint over them is not 'unchanged'" >&2
                 printf '%s\n' "$_u" | err_capped 3 "  unreadable: "
                 stop_json "Bundle read" "the bundle holds a folder this process cannot read, so it cannot be fingerprinted"
                 exit $EXIT_DEP; }
               # `--json` used to print raw `size mtime path` lines here and exit
               # 0 — the R-3 defect, in the mode added after R-3 was fixed. (G-10)
               if [ "$JSON" -eq 1 ]; then
                 [ -n "$PY" ] || { echo '{"error":"python3 required for --fingerprint --json"}'; exit $EXIT_DEP; }
                 bundle_fingerprint "$BUNDLE" | "$PY" -c 'import json,sys
sys.path.insert(0, sys.argv[2])
from okf_guard import shown
print(json.dumps({"bundle": shown(sys.argv[1]),
                  "fingerprint": [shown(l.rstrip("\n")) for l in sys.stdin if l.strip()]}))' "$BUNDLE" "$HERE"
               elif [ -n "$PY" ]; then
                 # Names are spelled for the reader here too; the run's own change detection compares bundle_fingerprint
                 # directly (FP_BEFORE / FP_AFTER), never this output.
                 bundle_fingerprint "$BUNDLE" | "$PY" "$HERE/okf_guard.py" show
               else
                 bundle_fingerprint "$BUNDLE" | tr '\000-\011\013-\037\177' '?'
               fi
               exit 0;;
  init-house-rules) # The ONLY writer of okf-base.yaml, and only on this explicit request. L2 reads
                # <bundle>/okf-base.yaml, so that is where the starter goes. The placeholder name is set
                # from the folder name so the file works as written; a name with anything but
                # letters, digits, dot, dash, underscore or space falls back to "bundle". The value is written
                # in double quotes: a folder named yes, null or 123 would otherwise be a YAML boolean, null or
                # integer. The allowed characters need no escaping inside the quotes.
                [ -n "$BUNDLE" ] || { echo "usage: okf-check --init-house-rules <bundle>" >&2; exit 64; }
                [ -d "$BUNDLE" ] || { echo "okf-check: $BUNDLE is not a directory" >&2; exit 64; }
                [ -f "$TEMPLATE" ] || { echo "okf-check: starter template missing: $TEMPLATE" >&2; exit $EXIT_DEP; }
                if [ -e "$BUNDLE/okf-base.yaml" ] || [ -L "$BUNDLE/okf-base.yaml" ]; then
                  echo "okf-check: $BUNDLE/okf-base.yaml already exists - not overwritten" >&2; exit 1
                fi
                _bn=$(basename "$(cd "$BUNDLE" && pwd -P)")
                case "$_bn" in *[!A-Za-z0-9._\ -]*|"") _bn=bundle ;; esac
                sed "s/^  name: CHANGE ME/  name: \"$_bn\"/" "$TEMPLATE" > "$BUNDLE/okf-base.yaml" 2>/dev/null \
                  || { echo "okf-check: cannot write $BUNDLE/okf-base.yaml" >&2; rm -f "$BUNDLE/okf-base.yaml"; exit $EXIT_DEP; }
                echo "wrote $BUNDLE/okf-base.yaml (starter; edit it, then re-run okf-check)"; exit 0;;
  init-ignore)  # The ONLY writer of .okfignore, and only on this explicit request.
                [ -n "$BUNDLE" ] && [ -d "$BUNDLE" ] || { echo "usage: okf-check --init-ignore <bundle>" >&2; exit 64; }
                if [ -e "$BUNDLE/.okfignore" ] || [ -L "$BUNDLE/.okfignore" ]; then
                  echo "okf-check: $BUNDLE/.okfignore already exists - not overwritten" >&2; exit 1
                fi
                okfignore_starter > "$BUNDLE/.okfignore" || exit $EXIT_DEP
                echo "wrote $BUNDLE/.okfignore (starter; edit it, then re-run okf-check)"; exit 0;;
  preflight)    preflight; exit 0;;   # a SessionStart hook must never fail the session
  install-deps) install_deps; exit $?;;
  doctor)   JSON=0   # a report, not a data feed: under --json say is quiet and the report was empty
            doctor; exit $?;;
  selftest) # The probes read the layers' HUMAN output, which say() suppresses
            # under --json. With `--selftest --json` every probe saw nothing,
            # reported a dead gate and exited 5 — the code documented as the
            # worst outcome — on entirely healthy code. A false alarm on the one
            # signal that must never lie. selftest is a report, not a data feed;
            # force human output for it. (R-5)
            JSON=0
            layer_floor
            doctor >/dev/null 2>&1 || { doctor; echo "cannot selftest: dependencies missing" >&2; exit $EXIT_DEP; }
            selftest; exit $?;;
esac

[ -n "$BUNDLE" ] || { echo "usage: okf-check <bundle> [--doctor|--selftest|--json|--fail-stale|--strict-trust]" >&2; exit 64; }
[ -d "$BUNDLE" ] || not_a_dir "$BUNDLE"
layer_floor   # before every mode that runs a layer, --file included
# An UNREADABLE directory used to yield "L1 PASS 0 concepts" and exit 0 — a
# permission problem, or a typo'd path, read as a clean bill of health. The
# fail-closed principle E-7b enforces for a single unreadable FILE was simply
# absent for the DIRECTORY. (R-6)
if ! ls "$BUNDLE" >/dev/null 2>&1; then
  echo "error: $BUNDLE is not readable — cannot reach a verdict (this is not a pass)" >&2
  stop_json "Bundle read" "the bundle cannot be read, so no verdict is possible"
  exit $EXIT_DEP
fi
# ...and the same question about every directory BELOW it. (G-8)
_unreadable=$(unreadable_dirs "$BUNDLE")
if [ -n "$_unreadable" ]; then
  echo "error: $BUNDLE contains directories this process cannot read — no verdict is possible" >&2
  printf '%s\n' "$_unreadable" | err_capped 3 "  unreadable: "
  echo "  a partial scan is not a pass; fix the permissions or point at a subtree you can read" >&2
  stop_json "Bundle read" "the bundle holds a folder this process cannot read, so no verdict is possible"
  exit $EXIT_DEP
fi
# --file reads the other notes of the bundle for its link check, so it stops at the same unreadable folder: a folder it
# cannot enter would otherwise read as "link target not found", or as a PermissionError before Python 3.14. The edit hook
# runs this and treats exit 2 as "could not check": it stays silent (fail-open).
[ "$MODE" = scoped ] && { run_scoped "$BUNDLE" "${SCOPED_FILE:-}"; exit $?; }
[ "$MODE" = changed ] && { run_changed "$BUNDLE" "${CHANGED_REF:-}"; exit $?; }
# INTERNAL, not a user mode (no help line, the list is in plugin.test.sh S51): stdin is a NUL-separated list of note paths
# relative to the bundle, and the paths .okfignore excludes come back NUL-separated. The conservation report asks it about the notes the
# ref still had, because its list of counted notes comes from the files on disk: a note that was deleted is on no disk
# listing, and answering about the PATH keeps a deleted counted note a LOST line while an ignored one is not read at all.
# One matcher answers — this one — so the report cannot drift from the layers.
if [ "$MODE" = ignore-filter ]; then
  okfignore_load "$BUNDLE"; [ $? -eq 2 ] && { echo "okf-check: .okfignore could not be applied, so which notes it excludes cannot be told" >&2; exit $EXIT_DEP; }
  while IFS= read -r -d '' _rel; do
    [ -n "$_rel" ] && okfignore_match "$_rel" && printf '%s\0' "$_rel"
  done
  exit 0
fi

if ! doctor >/dev/null 2>&1; then
  doctor; echo "L1 cannot run — fix the above." >&2
  stop_json Doctor "python3 or its PyYAML is missing or broken (okf-check --doctor says which), so no layer can run"
  exit $EXIT_DEP
fi
resolve_note_cap "$BUNDLE" || { stop_json "Note cap" "okf_check.max_note_bytes cannot be read, so no note can be judged safe to open"; exit $EXIT_DEP; }   # every layer and helper below judges a note by this one cap
# --duplicates is a report of its own, not a gate: it runs instead of the layers and always exits 0 once it ran.
# Its readers are all bounded (okf_notes.read_note), and the manifest is judged first: a device or pipe named okf-base.yaml
# is refused up front, never opened (the plain open().read() of review round 1 ran a real /dev/zero out of memory).
# --conserve <ref> (okf-knowledge-gate#16): a report of its own, read from git and the notes on disk; it runs instead of the layers.
# It is not under OKF_LAYER_TIMEOUT because it never parses frontmatter (okf-conserve.py compares text and calls neither
# yaml nor the validator's loader), so a hostile frontmatter cannot stall it.
if [ "$MODE" = conserve ]; then
  [ -n "${CONSERVE_REF:-}" ] || { echo "usage: okf-check <bundle> --conserve <ref> [--fail-lost] [--deleted FILE]" >&2; exit 64; }
  # .okfignore decides what counts as a note for every layer, so it decides it for this report too: a line that now lives
  # only in an ignored note is not in the bundle any more, and reads LOST like a deletion. The list of counted notes comes
  # from okfignore_list — the one matcher the layers and --duplicates read, negation rule, note cap, refusal rules and
  # outside-the-bundle links included — not from a second matcher written for this mode.
  conserve_keep=""
  if okfignore_present "$BUNDLE"; then
    okfignore_load "$BUNDLE"
    [ $? -eq 2 ] && { echo "okf-check: .okfignore could not be applied, so --conserve cannot run" >&2; stop_json Conserve ".okfignore could not be applied (see the message above)"; exit $EXIT_DEP; }
    # A list that could not be written is NOT "no ignore file": an empty OKF_KEEP_LIST would count every note and quietly
    # restore the false pass this mode is fixing.
    okfignore_list "$BUNDLE" > "$TMP/conserve-keep.lst" \
      || { echo "okf-check: the notes .okfignore leaves in could not be listed, so --conserve cannot run" >&2; stop_json Conserve "the notes .okfignore leaves in could not be listed"; exit $EXIT_DEP; }
    conserve_keep="$TMP/conserve-keep.lst"
  fi
  OKF_KEEP_LIST="$conserve_keep" OKF_CHECK_BIN="$HERE/okf-check" OKF_IGNORE_ALL_WHY="$IGNORE_ALL_WHY" OKF_VENDOR_DIR="$ROOT/vendor" OKF_SCRIPTS_DIR="$HERE" py_with_vendor "$HERE/okf-conserve.py" "$BUNDLE" "$CONSERVE_REF" "$VERSION" "$JSON" "$FAIL_LOST" ${DELETED_FILE:+"$DELETED_FILE"}
  exit $?
fi
if [ "$MODE" = facts ]; then
  JSON=0   # --facts has no JSON document; under --json say was quiet and a stop left both streams empty
  _mwhy=$(okf_note_refusal "$BUNDLE/okf-base.yaml" "$BUNDLE")
  [ -z "$_mwhy" ] || { echo "okf-check: $BUNDLE/okf-base.yaml — $_mwhy: not read, so --facts cannot run" >&2; exit $EXIT_DEP; }
  run_facts_list "$BUNDLE"; exit $?
fi
if [ "$MODE" = duplicates ]; then
  _mwhy=$(okf_note_refusal "$BUNDLE/okf-base.yaml" "$BUNDLE")
  [ -z "$_mwhy" ] || { echo "okf-check: $BUNDLE/okf-base.yaml — $_mwhy: not read, so --duplicates cannot run" >&2; stop_json Config "okf-base.yaml is not a note this tool may open ($_mwhy), so --duplicates cannot run"; exit $EXIT_DEP; }
  run_duplicates "$BUNDLE"; exit $?
fi

say "okf-check $VERSION — $BUNDLE"
report_folder_links "$BUNDLE"
worst=0
# E-7 change detection starts BEFORE the frozen copy is made: a write that lands while it is copied is a change too.
FP_BEFORE=$(bundle_fingerprint "$BUNDLE")
# A fingerprint that comes back EMPTY over a bundle that has concepts means the
# comparison below is ""=="" — E-7 change detection silently OFF, every mid-scan
# write reading as "unchanged", and the run still printing ALL GATES PASS. Found
# by mutating the GNU branch to emit nothing: the gate never noticed. A broken
# `stat`, an unsupported format string, or a platform branch nobody has run all
# produce it. State it; a lane that quietly stopped working is the defect this
# whole tool exists to catch. (Z-3)
FP_DEGRADED=0
if [ -z "$FP_BEFORE" ] && [ -n "$(okf_md_files "$BUNDLE" | tr -d '\0' | head -c 1)" ]; then  # pipefail-safe: only the value (the first byte) is tested; the status of the substitution is never read.
  FP_DEGRADED=1
fi
# Paths no layer may open: found by stat alone, before any layer reads the bundle.
okf_refused_notes "$BUNDLE" > "$TMP/refused.lst" 2>/dev/null
# THE FROZEN COPY (round 2). Every layer reads a copy of the notes and config that okf_guard.py made with a bounded
# read judged on the opened descriptor, never the bundle itself: the pre-scan above judges a path by stat, and a note that
# turned into a link to /dev/zero a moment later was read for ever by L1 (container case C9). The copy also leaves out what
# .okfignore excludes and every refused path, so L1 and okflint (which walk the folder themselves) never meet them. The
# bundle itself is never touched. It costs one python start and one copy of the notes (measured in the commit message).
LAYER_BUNDLE="$BUNDLE"; IGNORED=""; REAL_BUNDLE="$BUNDLE"
_ml=$(okfignore_mirror "$BUNDLE" "$TMP/okfmirror"); _mrc=$?
if [ "$_mrc" -ne 0 ]; then
  if okfignore_present "$BUNDLE"; then say "  IGNORE           could not apply .okfignore (see the message above) - no verdict is possible"
  else say "  FREEZE           could not copy the bundle for the layers (see the message above) - no verdict is possible"; fi
  if okfignore_present "$BUNDLE"; then stop_json IGNORE ".okfignore could not be applied (see the message above), so no verdict is possible"
  else stop_json FREEZE "the bundle could not be copied for the layers (see the message above), so no verdict is possible"; fi
  exit $EXIT_DEP
fi
read -r _kept _exnotes _exall <<< "$_ml"
cat "$TMP/okfmirror.refused" >> "$TMP/refused.lst" 2>/dev/null   # refused while copying: the same report as the pre-scan's
if okfignore_present "$BUNDLE"; then
  IGNORED="$_exall"
  if [ "${_exall:-0}" -gt 0 ]; then
    say "  ignore           .okfignore: $IGNORED file(s) excluded, $_kept checked"
  elif [ -s "$TMP/refused.lst" ]; then
    say "  ignore           .okfignore: no file matched its patterns (the path(s) named below are left out for their own reason)"
  else
    say "  ignore           .okfignore: 0 file(s) excluded"
  fi
fi
if [ "${_exall:-0}" -gt 0 ] || [ -s "$TMP/refused.lst" ]; then   # an ignore file that excludes nothing changes nothing
  okfignore_list "$BUNDLE" > "$TMP/keep.lst" 2>/dev/null
  export OKF_KEEP_LIST="$TMP/keep.lst"
fi
LAYER_BUNDLE="$TMP/okfmirror"; MIRROR_ROOT="$LAYER_BUNDLE"
if okfignore_present "$BUNDLE" && [ "${_kept:-0}" -eq 0 ] && [ "${_exnotes:-0}" -gt 0 ]; then
  say "  IGNORE           $IGNORE_ALL_WHY"
  [ "$JSON" -eq 1 ] && emit_json "$EXIT_DEP"
  exit $EXIT_DEP
fi
# rank() and its reason live above run_scoped: `--file` combines three verdicts with them too.
worse() { [ "$(rank "$1")" -gt "$(rank "$worst")" ] && worst="$1"; return 0; }
# worse_other: like worse, and remembers that something OTHER than the trust policy failed, so the final
# summary never blames trust alone for an exit that another layer also earned.
OTHER_FAIL=0
worse_other() { [ "$1" -ne 0 ] && OTHER_FAIL=1; worse "$1"; }

report_refused "$TMP/refused.lst"
run_config "$BUNDLE" "$LAYER_BUNDLE"; CONFIG_RC=$?; worse_other $CONFIG_RC
run_conformance "$LAYER_BUNDLE"; worse_other $?
run_trust       "$LAYER_BUNDLE"; worse_other $?
# --strict-trust: severity only. A C4 finding or an L1 near-miss actor warning becomes blocking (exit 1).
# The near-miss count reads the validator's own warning text (NEAR_MISS_WORDING in okf_validate.py, the one copy;
# anchored on a warning line, so a warning that merely quotes those words in an actor does not count: LT-27i).
if [ "$STRICT_TRUST" -eq 1 ]; then
  _nmtext=$(py_with_vendor -c 'import sys; sys.path.insert(0, sys.argv[1]); import okf_validate; print(okf_validate.NEAR_MISS_WORDING)' "$ROOT/vendor" 2>/dev/null)
  if [ -n "$_nmtext" ]; then
    _nm=$(NM_TEXT="$_nmtext" awk 'substr($0, 1, 2) == "W|" && index($0, ENVIRON["NM_TEXT"]) { n++ } END { print n + 0 }' "$TMP/l1.txt" 2>/dev/null); _nm=${_nm:-0}
  else   # fail closed: a near-miss that cannot be counted is not "none"
    say "  Trust policy     COULD NOT RUN   the validator's near-miss wording could not be read (reinstall the plugin)"
    _nm=0; worse $EXIT_DEP
  fi
  _strict_n=$((TRUST_FINDINGS + _nm))
  if [ "$_strict_n" -gt 0 ]; then
    say "  Trust policy     FAIL   ${_strict_n} finding(s) under --strict-trust (human verification the tool cannot authenticate, or a near-miss actor)"
    TRUST_POLICY_FAIL=1; worse $EXIT_CONFORM
  fi
fi
L2_SRC="$BUNDLE"
run_profile     "$LAYER_BUNDLE"; worse_other $?
run_index       "$LAYER_BUNDLE"; worse_other $?
run_graph       "$LAYER_BUNDLE"; worse_other $?
run_successor   "$LAYER_BUNDLE"; worse_other $?
run_owner       "$LAYER_BUNDLE"; worse_other $?
run_size        "$LAYER_BUNDLE"; worse_other $?
run_facts       "$LAYER_BUNDLE"; worse_other $?
run_staleness   "$LAYER_BUNDLE"; worse_other $?
run_derived_stale "$LAYER_BUNDLE"; worse_other $?
FP_AFTER=$(bundle_fingerprint "$BUNDLE")

# The readability guard is check-then-act: it walks the tree once, and the layers
# read it afterwards. A directory locked in that gap is invisible to both — the
# guard already passed, and L1's own scan drops unreadable subtrees in silence.
# Reproduced with the window widened: a concept vanished and the run printed
# "PASS 0 concepts", exit 0. The natural window is tens of milliseconds and no
# accident will hit it, but "narrow" is not "closed" and this is the exact
# fail-open class R-6 and G-8 exist to stop.
#
# The race cannot be removed — another agent owns its own writes, the same
# constraint E-7 documents. So it is DETECTED and STATED, which is what E-7 does
# for content. The fingerprint cannot cover it: that stats *.md size and mtime,
# never a directory's permission bits. (T-1)
_unreadable_after=$(unreadable_dirs "$BUNDLE")
if [ -n "$_unreadable_after" ]; then
  say "  UNREADABLE       a directory became unreadable DURING this scan"
  say "                   The layers above read a tree they were no longer allowed"
  say "                   to read in full. This is not a verdict."
  printf '%s\n' "$_unreadable_after" | err_capped 3 "  unreadable: "
  worse $EXIT_DEP
fi

# E-7. The layers ran against whatever was on disk at the moment each one looked.
# If that moved, this verdict is a point-in-time reading and must not be
# presented as a stable one.
if [ "$FP_DEGRADED" -eq 1 ]; then
  advise DEGRADED 1
  say "  DEGRADED         change detection is OFF — the fingerprint came back empty"
  say "                   on a bundle that has concepts. \`stat\` may be missing or"
  say "                   unsupported here; run: okf-check --doctor"
    # `--fail-on-change` is a CI caller stating "a mid-scan write must fail this
    # run". With the fingerprint degraded that detection is OFF and exit 6 is
    # UNREACHABLE, so the run used to exit 0 — the safety net silently absent
    # while the flag requesting it was set. Asking for a guarantee this tool
    # cannot currently provide is COULD NOT RUN, which is what every other
    # layer here returns when it cannot reach a verdict. (Z-8)
    if [ "$FAIL_ON_CHANGE" -eq 1 ]; then
      say "                   --fail-on-change was requested but cannot be honoured."
      worse $EXIT_DEP
    fi
elif [ "$FP_BEFORE" != "$FP_AFTER" ]; then
  CONCURRENT=1
  advise CONCURRENT 1
  say "  CONCURRENT       the bundle CHANGED during this scan"
  say "                   Layers run in sequence, so this report may mix two states."
  say "                   The verdict is a point-in-time reading, not a snapshot — re-run"
  say "                   when writers are idle if you need a stable answer."
  # THROUGH `worse`, not a raw numeric compare. `[ $worst -lt 6 ]` was ALWAYS
  # true — the three gates only ever return 0..4 — so a mid-scan write silently
  # overwrote a real conformance failure with exit 6. That is R-4's "verdict
  # masked by an unrelated code" defect, reintroduced by the same commit that
  # fixed R-4 for the other gates. A REACHED verdict outranks a disturbed one. (G-1)
  [ "$FAIL_ON_CHANGE" -eq 1 ] && worse $EXIT_CHANGED
fi

if [ "$JSON" -eq 1 ]; then
  # `change_detection` exists because the DEGRADED warning goes through say(), which --json suppresses by design (R-3):
  # a machine consumer would read {"exit":0,...} with no hint that the E-7 lane was off. It is emitted on EVERY run.
  # `warnings` is the list behind `l1_warnings`, then the okf_check.size warnings (which `l1_warnings` does not count); errors, stale, l2_findings and skipped list the findings behind the
  # other counts and the layers that did not run. Every exit path that prints JSON uses emit_json.
  emit_json "$worst"
fi
say ""
# Never print a bare pass while the body reported something. A summary that
# contradicts its own output is how a gate stops being read.
if [ "$worst" -ne 0 ]; then
  # Exit 1 means "L1 error". When no layer failed except the trust policy, that is the only way to get it, so say so.
  if [ "$TRUST_POLICY_FAIL" -eq 1 ] && [ "$OTHER_FAIL" -eq 0 ] && [ "$worst" -eq "$EXIT_CONFORM" ]; then
    say "  FAILED (exit $worst) — trust policy failure (--strict-trust)"
  else
    say "  FAILED (exit $worst)"
  fi
elif [ "$ADVISORIES" -gt 0 ] || [ "$SKIPPED" -gt 0 ]; then
  _by=""; _i=0
  while [ "$_i" -lt "${#ADV_SRC[@]}" ]; do _by="${_by:+$_by + }${ADV_SRC[$_i]} ${ADV_N[$_i]}"; _i=$((_i + 1)); done
  say "  PASS — no blocking errors, but ${ADVISORIES} advisory(ies) and ${SKIPPED} skipped layer(s) above${_by:+ (advisories: $_by)}"
else
  say "  ALL GATES PASS"
fi
exit $worst
