#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Mechanical validator for the Agentic SDLC family — the shared core.

This module is the SPINE: it is authored once here and shipped verbatim in every
distribution of the family (code, knowledge, marketing). It carries nothing that
belongs to a single domain. Each distribution ships a thin entry point beside it —
`sdlc_check.py` for code, `mkt_check.py` for marketing — which names the domain it
implements and delegates everything else here. A drift guard fails CI when the
copies diverge, so do not fork this file: fix it once and copy it.

It is also runnable on its own (`python sdlc_core.py check`) for the same reason
the entry points are thin: the behaviour is here, not in them.

Commands:
  check      single closure gate: validate + stale in one command (exit 1 if either fails)
  validate   verify the structural coherence of the docs root (default ai_docs/; exit 1 on
             errors; --strict also fails on warnings or on a missing docs root, for CI)
  index      regenerate the generated indexes: strategic/features_history.md (from the
             frontmatter of ANALYSIS_*.md files) and ai_docs/INDEX.md (manifest of canonical docs)
  stale      list areas modified after the last analysis recorded in audit_plan.md (exit 1 if any)
  mark       record paths as ANALYZED with the current reference (git hash, else UTC timestamp)
  gate       PreToolUse hook: block writes on protected paths without an IN_PROGRESS ANALYSIS (exit 2)
  verdict    PreToolUse hook: refuse an edit when the session declared no guide-router
             verdict, or never read a guide it names (JSON deny on stdout; always exit 0)

Hybrid/devPNT mode: pass --hybrid explicitly on check/stale (skips audit-plan
staleness, delegated to devPNT/KL) and on gate (also unlocks when an approved
E-TDD shadow, solutions/SHADOW_*tdd*.md, exists).

Canonical language is English. Legacy Italian frontmatter keys (stato, livello,
data_inizio, data_fine) and section headings are still accepted for existing projects,
but are deprecated: new documents should use the English forms.

Standard library only (Python >= 3.8). Windows and POSIX compatible.
"""
import argparse
import base64
import hashlib
import json
import os
import re
import subprocess
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path

VALID_STATES = {"PLANNED", "IN_PROGRESS", "COMPLETED", "CANCELLED"}
VALID_LEVELS = {"L1", "L2", "L3", "SPIKE"}
VISION_FILES = ("project_vision.md", "roadmap.md", "principles.md")
SKIP_DIRS = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv",
             "dist", "build", ".idea", ".vs"}  # the docs root is excluded separately: its
# name is resolved per invocation, so it cannot live in a frozen set (see docs_dir()).
INDEX_HEADER = ("<!-- GENERATED by sdlc_check.py index - do not edit by hand. "
                "Source of truth: frontmatter of the ANALYSIS_*.md files -->")
def manifest_header():
    return ("<!-- GENERATED by sdlc_check.py index - do not edit by hand. "
            f"Source of truth: the headers of the canonical documents in {docs_dir()}/. -->")
# Directories whose .md files are durable canonical documents: manifested in INDEX.md.
# audit/ and solutions/ stay discovery-by-grep (session / process artifacts), not manifested.
MANIFEST_DIRS = ("vision", "reference", "architecture", "functional", "strategic")
# Recognized states: canonical docs (CURRENT/SUPERSEDED/...), vision (DRAFT/APPROVED),
# ADR (Accepted/Proposed/Rejected). Union, to avoid false warnings on conventions in use.
CANONICAL_STATES = {"CURRENT", "SUPERSEDED", "DRAFT", "DEPRECATED",
                    "APPROVED", "ACCEPTED", "PROPOSED", "REJECTED"}
GENERATED_DOCS = {"features_history.md", "INDEX.md"}  # generated: never manifest entries
MTIME_GRACE = timedelta(seconds=2)
def guide_index_header():
    return ("<!-- GENERATED by sdlc_check.py index - do not edit by hand. "
            f"Source of truth: the headers of the GUIDE_*.md files in {docs_dir()}/reference/. -->")
GUIDE_PROVENANCE_KEYS = ("source", "distilled_from", "source_hash")  # source_version optional
# a guide section is "covered" when it carries a source marker or an explicit gap marker
GUIDE_MARKER_RE = re.compile(r"\[(?:source:[^\]]+|not covered by source)\]")
# Agent-global KB (Feature B unit 2): ONE client-agnostic root under home.
# AGENTIC_SDLC_KB_ROOT env var is a TEST/CI seam only (scenario battery must
# not touch the real user KB); the documented product path is fixed.
DEFAULT_KB_ROOT = Path(os.environ.get("AGENTIC_SDLC_KB_ROOT", "")) if os.environ.get("AGENTIC_SDLC_KB_ROOT") else Path.home() / ".agentic-sdlc"
# Subagent Execution (Feature A): a PLAN_[feature].md task must carry these keys,
# plus at least one of paths/produces (checked separately in cmd_plan).
PLAN_TASK_REQUIRED = ("id", "title", "verify")

# Deprecated Italian frontmatter keys, mapped to the canonical English ones.
LEGACY_KEYS = {"stato": "status", "livello": "level",
               "data_inizio": "start_date", "data_fine": "end_date"}

# Architect pass (F-020): the Capability Ledger is due for ACTIVE L3 analyses
# born on/after the day the pass shipped. Grandfathering by start_date -- an
# in-flight analysis from before the pass existed never nags (same lazy-convert
# doctrine as the pre-1.17 narrative handoff).
ARCHITECT_PASS_EPOCH = "2026-07-28"
# Design-review gate (F-021): an L3 started on/after this date owes a REVIEW_LOG
# row. Same grandfathering discipline as the pass above -- never nag work that
# predates the rule.
DESIGN_REVIEW_EPOCH = "2026-07-28"
# Chronology (F-073): an L3 ANALYSIS started, or an L3 HANDOFF updated, on/after
# this date is read for undated Diary text and a multi-step `next:`. Advisories,
# like the two gates above: a fixed epoch cannot protect a late upgrader, so a
# warning here would redden --strict CI on work written before the upgrade.
CHRONOLOGY_EPOCH = "2026-10-18"
# Guide check (F-078): an L3 code ANALYSIS started on/after this date owes a
# filled '## Guide check'. The day AFTER the rule was written, so the analyses
# opened that day by parallel units (which never saw the template) stay quiet.
GUIDE_CHECK_EPOCH = "2026-10-24"
# Owner design approval (F-087): an L3 started on/after this date owes a request-
# record entry labelled `design approved` before implementation. The day AFTER the
# rule was written, like GUIDE_CHECK_EPOCH.
DESIGN_APPROVAL_EPOCH = "2026-10-31"
NEXT_MAX_CHARS = 240        # this repository's longest `next:` was 214 at the epoch
ID_SCAN_MAX_REFS = 300      # A3 is skipped above it (one advisory says so, T9)
ID_SCAN_REFS_PER_CALL = 50  # keeps one git command line far below 32k chars
def review_log_rel():
    return f"{docs_dir()}/audit/reviews/REVIEW_LOG.md"
# Component Map 'Where' refs: a dotted token counts as a path only with one of
# these suffixes. Deliberately a closed list -- a generic ".\w{1,5}$" turns
# `app.core`, `OrderStore.save` and `1.18.0` into "the map is rotting".
FILE_SUFFIXES = ("md", "py", "js", "mjs", "cjs", "ts", "tsx", "jsx", "json", "yaml",
                 "yml", "toml", "ini", "cfg", "sh", "bat", "ps1", "go", "rs", "java",
                 "kt", "rb", "php", "cs", "swift", "c", "h", "cpp", "hpp", "sql",
                 "css", "scss", "html", "vue", "svelte", "tf", "proto", "txt")

# ANALYSIS sections: (canonical English heading, legacy Italian heading).
SECURITY_SECTION = ("## Security", "## Sicurezza")
ANALYSIS_SECTIONS = (
    ("## Objective", "## Obiettivo"),
    ("## Feature Vision", "## Vision della Feature"),
    ("## Impact", "## Impatto"),
    ("## Action Plan", "## Piano d'Azione"),
    ("## Test Strategy", "## Strategia di Test"),
    ("## Diary", "## Diario"),
)

# ------------------------------------------------------------------- docs root
# `ai_docs/` is the ONE surviving documentation root and the default everywhere.
# The name is a parameter for exactly two reasons, both temporary by nature: a
# project that predates the convention has to be READ before it can be migrated,
# and the migration tool has to see both sides. It is not an invitation to keep a
# second permanent root -- which is why `init.js` has no rename knob.
DEFAULT_DOCS_DIR = "ai_docs"
DOCS_DIR_CANDIDATES = ("ai_docs", "mkt_docs")
DOCS_DIR_ENV = "AGENTIC_SDLC_DOCS_DIR"  # test/CI seam, read per invocation
_DOCS_DIR = {"name": DEFAULT_DOCS_DIR}


def docs_dir():
    """The resolved documentation root NAME for this invocation."""
    return _DOCS_DIR["name"]


def set_docs_dir(name):
    _DOCS_DIR["name"] = name or DEFAULT_DOCS_DIR


def ai_path(root, *parts):
    """A path inside the resolved documentation root."""
    return Path(root).joinpath(docs_dir(), *parts)


def resolve_docs_dir(args=None, start=None):
    """Explicit beats guessed, exactly like --hybrid.

    Order: --docs-dir, then the env seam (read now, not at import, or it could not
    be varied by a test), then discovery, then the default. Returns (root, name);
    the root is None when discovery did not run.
    """
    explicit = getattr(args, "docs_dir", None) or os.environ.get(DOCS_DIR_ENV)
    if explicit:
        return None, explicit
    return discover_docs_root(start)


def discover_docs_root(start=None):
    """Walk up looking for a candidate root. PER LEVEL: the nearest one wins.

    Two candidates at the SAME level is the shape of a half-migrated project.
    Returning either would validate half of it and print a verdict, so it refuses
    -- naming both -- and the caller exits without a verdict.
    """
    cur = Path(start or os.getcwd()).resolve()
    for p in [cur] + list(cur.parents):
        found = [c for c in DOCS_DIR_CANDIDATES if (p / c).is_dir()]
        if len(found) > 1:
            raise AmbiguousDocsRoot(p, found)
        if found:
            return p, found[0]
    return None, DEFAULT_DOCS_DIR


class AmbiguousDocsRoot(Exception):
    """Two documentation roots side by side: a verdict here would be a guess."""

    def __init__(self, where, found):
        self.where = where
        self.found = found
        super().__init__(
            f"{where} contains more than one documentation root ({', '.join(found)}): "
            "refusing to guess which one this project uses. Pass --docs-dir <name> "
            "to say which, or finish the migration so only one remains.")


# --------------------------------------------------------------------- domains
# One entry per lens of the family. The DATA lives here, in the shared core, so a
# mixed tree is validated identically from every installed distribution: an entry
# point never picks rules, it only declares which portable checks it can run.
#
# The exclusive part of a rule set -- template, mandatory sections, the risk slot
# -- has exactly one owner per document. It is the part that never composes:
# unioning it would demand every domain's ceremony of every document, intersecting
# it would demand nothing. The risk slot is translated per domain, never dropped.
DOMAINS = {
    "code": {
        "risk_section": SECURITY_SECTION,
        "risk_label": "## Security and Threat Model",
        "id_prefix": "F-",
    },
    "knowledge": {
        "risk_section": ("## Sources and Verification",),
        "risk_label": "## Sources and Verification",
        "id_prefix": "K-",
    },
    "marketing": {
        "risk_section": ("## Threat Map / Plan Risks", "## Threat Map"),
        "risk_label": "## Threat Map / Plan Risks",
        "id_prefix": "M-",
    },
    "course": {
        "risk_section": ("## Learning and Content Risks",),
        "risk_label": "## Learning and Content Risks",
        "id_prefix": "C-",
    },
}
# Absent everything -- no `default_domain:` line, no `domain:` field -- a project is
# `code`. That is what every project created before this field existed already is,
# so the default is chosen to leave them untouched, not because code is special.
DEFAULT_DOMAIN = "code"

# Portable checks: composable, opt-in per document via `checks:`. An imported check
# may only ADD findings, never relax what the owning domain requires -- monotonic, so
# importing one is safe by construction. Registered by name `<domain>.<check>`.
PORTABLE_CHECKS = {}
# Which check namespaces this distribution actually carries. Set by the entry point;
# a `checks:` entry outside it WARNS visibly rather than passing silently.
_ENTRY_POINT = {"domain": DEFAULT_DOMAIN, "provides": (), "script": "sdlc_check.py"}
# "script" is what generated headers tell the reader to RUN. Declared, never
# derived from sys.argv: the generated bytes must not depend on how the command
# was invoked, or the alignment check would fail on the invocation instead of on
# the content.


# --- distribution profile ----------------------------------------------------
# Each distribution declares what it carries. The battery reads this instead of
# assuming the code overlay, which is what lets one shared battery run in three
# distributions without either failing on files a domain legitimately does not have
# or quietly excusing a domain from doctrine it owes.
#
# REQUIRED_CAPABILITIES is the spine: process discipline that is domain-neutral, so
# no distribution may drop it. A profile missing one fails a shared test -- editing
# your own profile is therefore NOT a way out of the doctrine, only a way to declare
# an overlay you genuinely do not have.
REQUIRED_CAPABILITIES = frozenset({
    "triage",              # Rule Zero, with the router verdict as a declared output
    "write_triggers",      # one event, one destination
    "workstream_registry", # audit/handoff.md as a parallel-safe registry
    "vision_gate",         # DRAFT informs, APPROVED binds, blind check before promotion
    "design_review_gate",  # a design reviewed by somebody other than its author
    "guide_router",        # the mandatory pre-work lookup
    "worktree_hygiene",    # isolate the work
})
# Optional overlays: real capabilities that a domain may legitimately not have.
# Listed here so "this distribution does not claim it" is a visible decision.
OPTIONAL_CAPABILITIES = frozenset({
    "architect_pass",         # does the component already exist? (code overlay)
    "interaction_contract",   # actor-facing surface spec between use cases and solution (code overlay)
    "preservation_constraints",  # the Impact's P table, and validate's note on its absence (code overlay)
    "taxonomy_pass",          # do the categories/topics already exist? (knowledge overlay)
    "comprehension_guides",   # source_kind: code maps of complex components
    "tdd",                    # test-first discipline
    "subagent_dispatch",      # opt-in PLAN_[feature].md execution
    "legacy_narrative_handoff",  # published before the registry format: owes a migration clause
    "question_discipline",    # when a question to the user is legal (elicitation.md);
                              # spine candidate once every sibling's elicitation carries it
})
# `unit_noun` is vocabulary, not structure: the code domain works on a "feature",
# the knowledge domain on a "topic". The shared battery asserts the SHAPE
# (HANDOFF_[<unit>].md) and reads the word from here, so a domain keeps its own
# language without either weakening the assertion or forking the test.
# `design_gate_between` is the pair of SKILL.md headings the design review must sit
# between: after the design exists, before the work is executed. The headings are each
# domain's own wording -- the code overlay runs five phases, the marketing overlay nine
# -- so the battery asserts the ORDER, never a shared phase name.
_PROFILE = {
    "skill_name": "agentic-sdlc",
    "unit_noun": "feature",
    "support_files": (),
    "capabilities": frozenset(),
    "design_gate_between": (),
    "remind_line": "",
}


def set_profile(skill_name, support_files=(), capabilities=(), unit_noun="feature",
                design_gate_between=(), remind_line=""):
    _PROFILE.update(skill_name=skill_name,
                    unit_noun=unit_noun,
                    support_files=tuple(support_files),
                    capabilities=frozenset(capabilities),
                    design_gate_between=tuple(design_gate_between),
                    remind_line=remind_line)


def profile():
    return dict(_PROFILE)


def has_capability(name):
    return name in _PROFILE["capabilities"]


def portable_check(name):
    """Register a portable check. The callable takes (rel, meta, text) and returns
    a list of (severity, message) with severity in {'error', 'warning', 'advisory'}."""
    def register(fn):
        PORTABLE_CHECKS[name] = fn
        return fn
    return register


def set_entry_point(domain, provides=(), script=None):
    """Declare which domain this distribution is and which check namespaces it ships."""
    _ENTRY_POINT["domain"] = domain
    _ENTRY_POINT["provides"] = tuple(provides)
    if script:
        _ENTRY_POINT["script"] = script


def entry_script():
    """The command name a generated header tells the reader to run."""
    return _ENTRY_POINT["script"]


def project_default_domain(root):
    """The project's answer for every artifact that declares no `domain:`.

    Read once from `ai_docs/README.md`'s frontmatter. Project-level ON PURPOSE: a
    per-distribution default would give the same tree two different verdicts
    depending on which lens the agent happened to load."""
    readme = ai_path(root, "README.md")
    if not readme.is_file():
        return DEFAULT_DOMAIN
    meta = load_frontmatter(read_text(readme).splitlines())
    declared = (meta.get("default_domain") or "").strip().strip("'\"").lower()
    return declared if declared in DOMAINS else DEFAULT_DOMAIN


def resolve_domain(meta, default):
    """(domain, declared_but_unknown) for one artifact. The field RECORDS the answer;
    it never invents one, and an unrecognized value is reported, not obeyed."""
    declared = (meta.get("domain") or "").strip().strip("'\"").lower()
    if not declared:
        return default, None
    if declared not in DOMAINS:
        return default, declared
    return declared, None


def declared_checks(meta):
    """The `checks:` list, accepted as `[a, b]` or as a comma-separated string."""
    raw = (meta.get("checks") or "").strip()
    if not raw:
        return []
    return [c.strip().strip("'\"") for c in raw.strip("[]").split(",") if c.strip()]


def run_portable_checks(rel, meta, text, errors, warnings, advisories):
    """Run the checks a document imported. Findings are ADDED to the owning domain's;
    an unavailable check is a visible warning -- never a silent pass."""
    for name in declared_checks(meta):
        namespace = name.split(".", 1)[0]
        if name not in PORTABLE_CHECKS:
            if namespace in _ENTRY_POINT["provides"]:
                warnings.append(f"{rel}: check '{name}' is unknown (no such portable check)")
            else:
                warnings.append(
                    f"{rel}: check '{name}' is not available in this distribution "
                    f"(it ships {', '.join(_ENTRY_POINT['provides']) or 'no checks'}): "
                    "the document was NOT checked against it")
            continue
        for severity, message in PORTABLE_CHECKS[name](rel, meta, text) or []:
            {"error": errors, "warning": warnings}.get(severity, advisories).append(
                f"{rel}: [{name}] {message}")


try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass


# --- orient (SessionStart hook) ---
# Fixed, hard-coded doc set (label, path-relative-to-root). No content- or
# user-derived paths -> no traversal input (P-TM T3); confine_under is
# defense-in-depth. Emitted at session start by the orient subcommand.
def orient_docs():
    d = docs_dir()
    return [
        ("Reading guide (README)", f"{d}/README.md"),
        ("Canonical manifest (INDEX)", f"{d}/INDEX.md"),
        ("Guide router (when-to-consult)", f"{d}/reference/INDEX.md"),
        ("Last session handoff", f"{d}/audit/handoff.md"),
    ]
# F-075: the WHOLE output -- the knowledge layer's append included -- stays under
# Claude Code's 10,000-character hook cap. Above it the client saves the output
# to a file and injects a 2,000-character preview, and the agent never opens the
# file: the router printed third, after README and INDEX, never reached a session.
ORIENT_MAX_TOTAL_CHARS = 9500   # whole output (P-TM T2)
ORIENT_APPEND_RESERVE = 2000    # left for the knowledge layer's append, which cuts itself to it
ORIENT_ROUTER_CHARS = 3000      # ~20 guides; the full router stays one read away
ORIENT_REGISTRY_CHARS = 2600    # registry rows + project-wide notes
ORIENT_TRIAGE_LINE = ("Triage every request (Rule Zero): L1 trivial - L2 small - L3 significant "
                      "- Spike. Declare the level with the guide-router verdict (a guide below, "
                      "or \"no match\"). When in doubt, pick the higher level.")


# ----------------------------------------------------------------- utilities

def utc_now_iso():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def find_project_root(start=None):
    cur = Path(start or os.getcwd()).resolve()
    for p in [cur] + list(cur.parents):
        if (p / docs_dir()).is_dir():
            return p
    return cur


def require_ai_docs(root, command):
    """Fail fast when the docs root is missing: prevents silently creating a second
    documentation root in the wrong working directory."""
    if not ai_path(root).is_dir():
        print(f"[ERROR] {ai_path(root)} not found: refusing to run '{command}' here. "
              "Run agentic-sdlc-init first, or pass --root <project_root>.")
        return False
    return True


def confine_under(base, rel):
    """Fail-closed path confinement: resolve `rel` under `base` and require the
    result to stay inside `base`. Returns None (reject) if `rel` is absolute,
    contains a '..' part, or resolves outside `base` (including an OSError
    during resolution, e.g. an unresolvable/reparse-point path on Windows).
    Single source for path confinement (T2/T3): reused by check_kb_collisions'
    `overrides:` check and cmd_validate's `distilled_from` check, and by the
    new `plan` command's paths/consumes/produces/guides confinement."""
    p = Path(rel)
    if p.is_absolute() or ".." in p.parts:
        return None
    try:
        t = (base / rel).resolve()
        t.relative_to(base.resolve())
        return t
    except (ValueError, OSError):
        return None


def read_text(path):
    # utf-8-sig: strips a leading BOM (files authored on Windows) so the
    # frontmatter '---' on line 0 stays recognizable; reads plain utf-8 otherwise.
    return path.read_text(encoding="utf-8-sig", errors="replace")


def sha256_file(path):
    # CRLF->LF before hashing: a Windows checkout with core.autocrlf=true
    # rewrites snapshot files, and a raw-byte hash would flag every guide
    # [stale] on a fresh clone. Recorded hashes are LF-based, so normalizing
    # maps CRLF copies back to the same digest.
    h = hashlib.sha256()
    h.update(path.read_bytes().replace(b"\r\n", b"\n"))
    return h.hexdigest()


def parse_iso(value):
    if not value:
        return None
    try:
        dt = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo=timezone.utc)
        return dt
    except ValueError:
        return None


def norm_text(s):
    return "\n".join(line.rstrip() for line in s.strip().splitlines())


def load_frontmatter(lines):
    meta = {}
    if not lines or lines[0].strip() != "---":
        return meta
    for line in lines[1:60]:
        if line.strip() == "---":
            break
        m = re.match(r"^([A-Za-z_][\w-]*):\s*(.*)$", line)
        if m:
            meta[m.group(1).strip().lower()] = m.group(2).strip()
    # Legacy Italian keys: accepted, normalized to canonical English (deprecated).
    for legacy, canon in LEGACY_KEYS.items():
        if legacy in meta and canon not in meta:
            meta[canon] = meta[legacy]
    return meta


def is_shadow(path, first_line):
    """A shadow mirror of a devPNT-governed document, not an authoritative ANALYSIS.
    Recognized by filename (SHADOW_*) or by the marker comment on the FIRST line
    (legacy shadows saved under an ANALYSIS_* name)."""
    return path.name.startswith("SHADOW") or first_line.lstrip().startswith("<!-- SHADOW")


def list_analyses(root):
    """Returns [(path, frontmatter, text)] for the ANALYSIS_*.md files (shadows excluded)."""
    sol = ai_path(root, "solutions")
    out = []
    if not sol.is_dir():
        return out
    for p in sorted(sol.glob("ANALYSIS_*.md")):
        text = read_text(p)
        first_line = text.splitlines()[0] if text else ""
        if is_shadow(p, first_line):
            continue
        out.append((p, load_frontmatter(text.splitlines()), text))
    return out


def has_etdd_shadow(root):
    """True if an E-TDD shadow exported from devPNT exists in solutions/.
    In Hybrid mode the approved E-TDD (exported BEFORE implementation) is the
    design authorization that replaces the IN_PROGRESS ANALYSIS."""
    sol = ai_path(root, "solutions")
    if not sol.is_dir():
        return False
    return any("tdd" in p.name.lower() for p in sol.glob("SHADOW_*.md"))


def newest_shadow(solutions_dir, doc_key):
    """The newest devPNT shadow of `doc_key` in `solutions_dir`, or None.
    Only `SHADOW_<doc_key>_v<N>[.<N>...].md` counts -- the exact key, so
    `<doc_key>_extra` is another key -- and versions compare number by number
    (v1.10 above v1.9, v1.0 above v1). Names outside that rule are ignored.
    F-081: the Hybrid target of a claim marker; reusable by any consumer."""
    if not Path(solutions_dir).is_dir():
        return None
    best = None
    for p in Path(solutions_dir).iterdir():
        v = _shadow_version(p.name, doc_key)
        if v is not None and p.is_file():
            if best is None or v > best[0]:
                best = (v, p)
    return best[1] if best else None


def _shadow_version(name, doc_key):
    """The version tuple of `SHADOW_<doc_key>_v<N>[.<N>...].md`, else None."""
    m = re.match(r"^SHADOW_%s_v(\d+(?:\.\d+)*)\.md$" % re.escape(doc_key), name)
    return tuple(int(x) for x in m.group(1).split(".")) if m else None


def stray_shadow(solutions_dir, doc_key):
    """A file of the same exact key that `newest_shadow` does not read
    (`SHADOW_<doc_key>.md`, `..._v1.2a.md`), or None -- the name a user needs
    to see when no shadow resolves. A longer key is never a stray."""
    if not Path(solutions_dir).is_dir():
        return None
    rx = re.compile(r"^SHADOW_%s(?:_v[^_]*)?\.md$" % re.escape(doc_key))
    return next((p.name for p in sorted(Path(solutions_dir).iterdir())
                 if rx.match(p.name) and _shadow_version(p.name, doc_key) is None),
                None)


def skip_dir(name):
    """The one definition of a directory that holds no project files: VCS and
    dependency/build directories, every dot-directory, and the docs root (by
    name, at any depth). `iter_files` and the knowledge layer's inventory both
    walk by it, so the two can never disagree about what the project is."""
    return name in SKIP_DIRS or name == docs_dir() or name.startswith(".")


def iter_files(target):
    if target.is_file():
        yield target
        return
    for dirpath, dirnames, filenames in os.walk(target):
        dirnames[:] = [d for d in dirnames if not skip_dir(d)]
        for name in filenames:
            yield Path(dirpath) / name


# ---------------------------------------------------------------------- git

def git_available(root):
    try:
        r = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"],
                           cwd=str(root), capture_output=True, text=True, timeout=10)
        return r.returncode == 0 and r.stdout.strip() == "true"
    except Exception:
        return False


def git_head(root):
    try:
        r = subprocess.run(["git", "rev-parse", "--short=12", "HEAD"],
                           cwd=str(root), capture_output=True, text=True, timeout=10)
        return r.stdout.strip() if r.returncode == 0 else ""
    except Exception:
        return ""


def git_has_changes(root, rel_path):
    """True if there are tracked/untracked changes under rel_path."""
    try:
        rel = rel_path.replace("\\", "/")
        r = subprocess.run(["git", "status", "--porcelain", "--", rel],
                           cwd=str(root), capture_output=True, text=True, timeout=30)
        return r.returncode == 0 and bool(r.stdout.strip())
    except Exception:
        return False


def git_changed_since(root, ref, rel_path):
    """Files changed (tracked + untracked) under rel_path since ref. None if ref unresolvable."""
    try:
        r = subprocess.run(["git", "diff", "--name-only", ref, "--", rel_path],
                           cwd=str(root), capture_output=True, text=True, timeout=30)
        if r.returncode != 0:
            return None
        changed = [l.strip() for l in r.stdout.splitlines() if l.strip()]
        r2 = subprocess.run(["git", "ls-files", "--others", "--exclude-standard", "--", rel_path],
                            cwd=str(root), capture_output=True, text=True, timeout=30)
        if r2.returncode == 0:
            changed += [l.strip() for l in r2.stdout.splitlines() if l.strip()]
        return sorted(set(changed))
    except Exception:
        return None


def git_ref_state(root, ref):
    """Where a recorded commit stands against HEAD (F-056).

    'ancestor' -- in HEAD's history; 'orphan' -- a commit HEAD's history does not
    contain (amended, rebased or squash-merged away, or marked on another branch:
    it stops resolving once pruned, and on any fresh clone); 'missing' -- not a
    commit in this repository; 'unknown' -- git gave no yes/no answer.
    Callers pass a hash-shaped ref only: that check is what keeps document
    content from reaching git's argv as an option."""
    try:
        r = subprocess.run(["git", "cat-file", "-e", ref + "^{commit}"],
                           cwd=str(root), capture_output=True, text=True, timeout=30)
        if r.returncode != 0:
            return "missing"
        r = subprocess.run(["git", "merge-base", "--is-ancestor", ref, "HEAD"],
                           cwd=str(root), capture_output=True, text=True, timeout=30)
    except Exception:
        return "unknown"
    return {0: "ancestor", 1: "orphan"}.get(r.returncode, "unknown")


def git_is_shallow(root):
    try:
        r = subprocess.run(["git", "rev-parse", "--is-shallow-repository"],
                           cwd=str(root), capture_output=True, text=True, timeout=10)
        return r.returncode == 0 and r.stdout.strip() == "true"
    except Exception:
        return False


# -------------------------------------------------------------------- index

def build_index(root):
    analyses = list_analyses(root)
    # SYNTACTIC predicate, on purpose: the column appears when some analysis WRITES
    # a `domain:` field, not when one resolves to a domain (every analysis does).
    # So the generated file is a function of the tree alone -- identical from every
    # entry point, and byte-identical on every tree that predates the field.
    tagged = any((meta.get("domain") or "").strip() for _, meta, _ in analyses)
    default_domain = project_default_domain(root) if tagged else None
    rows = []
    for p, meta, _ in analyses:
        row = [
            meta.get("id", "?"),
            meta.get("feature", p.stem.replace("ANALYSIS_", "")),
            meta.get("level", ""),
            meta.get("status", "?"),
            meta.get("start_date", ""),
            meta.get("end_date", ""),
            "solutions/" + p.name,
        ]
        if tagged:
            row.insert(2, resolve_domain(meta, default_domain)[0])
        rows.append(tuple(row))
    rows.sort(key=lambda r: r[0])
    header = "| ID | Feature | Level | Status | Started | Finished | Doc |"
    sep = "|---|---|---|---|---|---|---|"
    if tagged:
        header = "| ID | Feature | Domain | Level | Status | Started | Finished | Doc |"
        sep = "|---|---|---|---|---|---|---|---|"
    lines = [INDEX_HEADER,
             "# Feature History (generated)",
             "",
             header,
             sep]
    for r in rows:
        lines.append("| " + " | ".join(r) + " |")
    return "\n".join(lines) + "\n"


# "Status:"/"Stato:" line in the body (with or without ** **), prefix before the description
_STATUS_LINE = re.compile(r"^\**\s*(?:status|stato)\s*\**\s*:\s*\**\s*([A-Za-z][\w-]*)", re.I)
# pure metadata lines to skip when picking the fallback description
_META_LINE = re.compile(r"^\**\s*(date|data|task ref|version|versione|owner|autore|branch|agente|agent|created|creato|updated|aggiornato)\b", re.I)


def extract_doc_meta(path):
    """(title, description, status, supersedes) of a canonical doc.

    Recognizes TWO header conventions: the YAML-lite frontmatter
    (description/status/supersedes/title) and the in-body `**Status:** X`
    line (used by ADRs and legacy docs). As a fallback it derives the title
    from the first '# H1' and the description from the first prose line,
    skipping metadata lines.
    """
    text = read_text(path)
    lines = text.splitlines()
    meta = load_frontmatter(lines)
    body = lines
    if lines and lines[0].strip() == "---":
        for i in range(1, min(len(lines), 60)):
            if lines[i].strip() == "---":
                body = lines[i + 1:]
                break

    title = meta.get("title", "")
    if not title:
        for line in body:
            m = re.match(r"^#\s+(.*)$", line)
            if m:
                title = m.group(1).strip()
                break
    title = title or path.stem

    status = meta.get("status", "").upper()
    if not status:
        for line in body[:25]:
            m = _STATUS_LINE.match(line.strip())
            if m:
                status = m.group(1).upper()
                break

    desc = meta.get("description", "")
    if not desc:
        in_comment = False
        for line in body:
            s = line.strip()
            # track HTML-comment state across lines: skipping only the OPENING
            # line made line 2 of a multi-line comment the manifest description
            # (the shipped vision template opens with a 3-line comment, so the
            # most-read row of the manifest read '... -->')
            if in_comment:
                if "-->" in s:
                    in_comment = False
                    s = s.split("-->", 1)[1].strip()
                    if not s:
                        continue
                else:
                    continue
            elif s.startswith("<!--"):
                if "-->" not in s:
                    in_comment = True
                    continue
                s = s.split("-->", 1)[1].strip()
                if not s:
                    continue
            # a table row or a bare bullet is not a description: the manifest is
            # the first thing an agent reads to orient, and '| Milestone | ... |'
            # in that column is a row carrying no information
            if (not s or s.startswith("#") or s.startswith("|") or s.startswith("---")
                    or re.match(r"^[-*+]\s", s) or _META_LINE.match(s)):
                continue
            if s.startswith(">"):
                s = s.lstrip(">").strip()
            m = _STATUS_LINE.match(s)
            if m:
                # "Status: X — description": keep the part after the status; if empty, skip
                rest = s[m.end():].strip(" *—–-:.")
                if not rest:
                    continue
                s = rest
            if s:
                desc = s
                break
    desc = re.sub(r"\s+", " ", desc).strip()
    if len(desc) > 160:
        desc = desc[:157].rstrip() + "..."
    return title, desc, status, meta.get("supersedes", "").strip()


def list_canonical_docs(root):
    """[(rel_to_ai_docs, path, (title, desc, status, supersedes))] for canonical docs."""
    ai = ai_path(root)
    out = []
    for d in MANIFEST_DIRS:
        base = ai / d
        if not base.is_dir():
            continue
        for p in sorted(base.rglob("*.md")):
            rel_parts = p.relative_to(base).parts
            if any(part.startswith(".") for part in rel_parts[:-1]):
                continue  # dot-subdirs (e.g. reference/.sources/) are never canonical
            if p.name in GENERATED_DOCS or p.name == "README.md":
                continue
            out.append((p.relative_to(ai).as_posix(), p, extract_doc_meta(p)))
    return out


def build_manifest(root):
    docs = list_canonical_docs(root)
    lines = [manifest_header(),
             f"# `{docs_dir()}/` document index (generated)",
             "",
             "Complete manifest of the canonical documents. For the reading priority",
             "(must-reads) see the hand-curated `README.md`. The ANALYSIS history is in",
             "`strategic/features_history.md`. `audit/` and `solutions/` are discovery-by-grep,",
             "not manifested here."]
    by_dir = {}
    for rel, _, meta in docs:
        by_dir.setdefault(rel.split("/", 1)[0], []).append((rel, meta))
    for top in MANIFEST_DIRS:
        rows = by_dir.get(top)
        if not rows:
            continue
        lines += ["", f"## {top}/", "",
                  "| Document | Status | Description |", "|---|---|---|"]
        for rel, (title, desc, status, _sup) in rows:
            d = (desc or title).replace("|", "\\|")
            lines.append(f"| `{rel}` | {status or '-'} | {d} |")
    return "\n".join(lines).rstrip() + "\n"


# ------------------------------------------------- workstream registry (F-028)
# audit/handoff.md is GENERATED from one source file per open workstream, so two
# writers working two workstreams touch two different files. Row-per-workstream
# alone was not enough -- F-019 had that and the file still conflicted twice,
# because a file-global `Date:` header defeats row-level ownership. The header is
# now DERIVED, so no writer touches it.

REGISTRY_COLUMNS = ("Workstream", "Level", "Branch", "Status", "Since",
                    "Next step", "Details")
REGISTRY_KEYS = ("workstream", "level", "branch", "status", "since", "next")
REGISTRY_CAP = 20               # a signal, never a truncation (see cmd_index)
PROJECT_NOTES = "project_notes.md"   # NOT handoff_notes.md: the HANDOFF_*.md
# glob is case-insensitive on Windows, and that name would be collected as a
# source. The trap is real; the name is the fix.


def registry_header():
    return (f"<!-- GENERATED by {entry_script()} index - do not edit by hand. "
            f"Source of truth: the HANDOFF_*.md files in {docs_dir()}/audit/. -->")


def list_workstreams(root):
    """[(path, meta)] for audit/HANDOFF_*.md carrying registry frontmatter.

    Opt-in by the presence of `workstream:` -- a project whose handoff is still
    hand-written has no sources, so nothing generates and nothing errors (the
    F-019 migration lesson). Sorted by workstream id: the alignment check is a
    byte comparison, and glob order differs across filesystems."""
    aud = ai_path(root, "audit")
    out = []
    if not aud.is_dir():
        return out
    for p in sorted(aud.glob("HANDOFF_*.md")):
        meta = load_frontmatter(read_text(p).splitlines())
        if str(meta.get("workstream") or "").strip():
            out.append((p, meta))
    out.sort(key=lambda pm: (str(pm[1].get("workstream")).strip().lower(), pm[0].name))
    return out


def _registry_cell(value):
    text = str(value if value is not None else "").strip()
    return text.replace("|", "\\|") or "-"


def build_registry(root):
    """The generated registry, or "" when there is no source to build it from.

    Deterministic by construction: sorted rows, and a `Date:` taken from the
    newest `updated:` VALUE written inside the sources -- never a filesystem
    timestamp. Git does not preserve mtimes, so an mtime-derived header would
    regenerate differently in every fresh clone and the alignment check would
    fire on a tree nobody touched."""
    rows = list_workstreams(root)
    if not rows:
        return ""
    stamp = max(str(m.get("updated") or m.get("since") or "").strip() or "0000-00-00"
                for _p, m in rows)
    return _render_registry(root, rows, stamp)


def _render_registry(root, rows, stamp):
    lines = ["# Handoff — workstream registry",
             f"Date: {stamp} (UTC)",
             "",
             registry_header(),
             "",
             "| " + " | ".join(REGISTRY_COLUMNS) + " |",
             "|" + "---|" * len(REGISTRY_COLUMNS)]
    for p, meta in rows:
        extra = str(meta.get("details") or "").strip()
        details = f"{p.name} · {extra}" if extra else p.name
        cells = [_registry_cell(meta.get(k)) for k in REGISTRY_KEYS]
        lines.append("| " + " | ".join(cells) + f" | {_registry_cell(details)} |")
    notes = ai_path(root, "audit", PROJECT_NOTES)
    if notes.is_file():
        body = read_text(notes).strip()
        if body:
            lines += ["", "## Project-wide notes", "", body]
    return "\n".join(lines) + "\n"


def parse_registry_rows(text):
    """Workstream ids in a registry table, hand-written or generated."""
    ids = []
    for line in text.splitlines():
        cells = _table_cells(line)
        if not cells:
            continue
        first = cells[0]
        if first and first.lower() != "workstream":
            ids.append(first)
    return ids


def is_generated_registry(text):
    # "Ours" = written by ANY family entry point: the header is WRITTEN with
    # entry_script(), so recognition must not hard-code one distribution's
    # script name (a registry generated by mkt_check.py is just as generated).
    return bool(re.search(r"GENERATED by \S+ index - do not edit by hand", text))


def generated_registry_rows(text):
    """Workstream rows of a generated registry, ignoring the project notes
    (free text that may carry tables of its own)."""
    return parse_registry_rows(text.split("\n## Project-wide notes", 1)[0])


def build_empty_registry(root, existing):
    """The generated registry once the last source is gone (F1, found by F-068).

    Only for a registry that is already ours: a hand-written handoff with no
    sources is a project that never converted, and stays untouched. The Date is
    kept while the view is already empty -- re-running index on a clean tree
    must not change it -- and becomes today's when rows are being dropped:
    there is no source left whose `updated:` could date the closure."""
    m = re.search(r"Date:\s*(\d{4}-\d{2}-\d{2})", existing)
    if m and not generated_registry_rows(existing):
        stamp = m.group(1)
    else:
        stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    return _render_registry(root, [], stamp)


def registry_conversion_blockers(root):
    """What stops `index` from writing over a hand-written handoff.md.

    The mixed state is the trap this exists for: converting one row at a time
    leaves a project at one source file and five hand-written rows, and
    regenerating from the one source DELETES the other five -- silently, in the
    file whose whole purpose is not losing them. So conversion is per project.
    Empty list = writing is safe."""
    hand = ai_path(root, "audit", "handoff.md")
    if not hand.is_file():
        return []
    text = read_text(hand)
    if is_generated_registry(text):
        return []
    blockers = []
    known = {str(m.get("workstream")).strip() for _p, m in list_workstreams(root)}
    orphans = [r for r in parse_registry_rows(text) if r not in known]
    if orphans:
        blockers.append("rows no HANDOFF_*.md accounts for: " + ", ".join(orphans))
    # Everything else in the file must have a home too, or it is lost on write:
    # a pre-1.17 narrative handoff carries no table at all, so orphan rows alone
    # would not notice it.
    notes_ok = ai_path(root, "audit", PROJECT_NOTES).is_file()
    leftovers, in_notes = [], False
    for line in text.splitlines():
        s = line.strip()
        if not s or s.startswith("|") or s.startswith("<!--"):
            continue
        if s.startswith("# ") or re.match(r"^(?:Date|Data):", s):
            continue
        if re.match(r"^##\s+Project-wide notes\s*$", s):
            in_notes = True
            continue
        if s.startswith("## "):
            in_notes = False
        if in_notes and notes_ok:
            continue
        leftovers.append(s)
    if leftovers:
        blockers.append("content outside the table with nowhere to go (%d line(s), first: %r) "
                        "-- project-wide notes belong in audit/%s"
                        % (len(leftovers), leftovers[0][:60], PROJECT_NOTES))
    return blockers


def list_guides(root):
    """[(rel_to_ai_docs, path, meta, text)] for ai_docs/reference/GUIDE_*.md."""
    ref = ai_path(root, "reference")
    out = []
    if not ref.is_dir():
        return out
    for p in sorted(ref.glob("GUIDE_*.md")):
        text = read_text(p)
        out.append((p.relative_to(ai_path(root)).as_posix(), p,
                    load_frontmatter(text.splitlines()), text))
    return out


def check_kb_collisions(root, project_guides, errors, warnings):
    """Cross-root awareness (unit 2): project-wins precedence, declared via 'overrides:'."""
    kb_root = DEFAULT_KB_ROOT
    # The agent-global KB is client-agnostic and shared across lenses: it keeps its
    # own fixed layout and NEVER follows a project's docs-root name (TS16).
    kb_ref = (kb_root / "ai_docs" / "reference")
    try:
        if root.resolve() == kb_root.resolve():
            return  # validating the KB itself: no self-comparison
    except OSError:
        return
    if not kb_ref.is_dir():
        return  # no KB on this machine: zero behavior change
    kb_names = {p.name for _, p, _, _ in list_guides(kb_root)}
    for rel, p, meta, _ in project_guides:
        ov = (meta.get("overrides") or "").strip()
        if ov:
            # T6: untrusted cross-root pointer — distilled_from parity, fail closed
            target = confine_under(kb_ref, ov)
            if target is None:
                errors.append(f"{rel}: overrides '{ov}' is absolute, contains '..', or escapes the KB "
                              "reference dir — rejected (fail closed)")
                continue
            if not target.is_file():
                warnings.append(f"{rel}: overrides target '{ov}' not found in KB ({kb_ref})")
        if p.name in kb_names and ov != p.name:
            warnings.append(f"{rel}: undeclared collision with KB guide '{p.name}' (project wins) — declare overrides: {p.name}")


def build_guide_index(root):
    lines = [guide_index_header(),
             "# Operative guides (generated router)",
             "",
             "One row per guide. `description` is the when-to-consult line; provenance",
             "shows what the guide was distilled from. Freshness: run `sdlc_check.py stale`.",
             "",
             "| Guide | Status | When to consult | Source | Source version |",
             "|---|---|---|---|---|"]
    for rel, p, meta, _ in list_guides(root):
        lines.append("| `{}` | {} | {} | {} | {} |".format(
            p.name, meta.get("status", "-") or "-",
            (meta.get("description", "") or "-").replace("|", "\\|"),
            (meta.get("source", "") or "-").replace("|", "\\|"),
            meta.get("source_version", "") or "-"))
    return "\n".join(lines) + "\n"


def cmd_index(root):
    if not require_ai_docs(root, "index"):
        return 1
    hist = ai_path(root, "strategic", "features_history.md")
    hist.parent.mkdir(parents=True, exist_ok=True)
    hist.write_text(build_index(root), encoding="utf-8")
    print(f"[ok] ANALYSIS index regenerated: {hist}")
    # INDEX.md only if canonical docs exist: no empty manifest on minimal projects
    if list_canonical_docs(root):
        manifest = ai_path(root, "INDEX.md")
        manifest.write_text(build_manifest(root), encoding="utf-8")
        print(f"[ok] document manifest regenerated: {manifest}")
    else:
        print("[info] no canonical documents: INDEX.md not generated")
    guides = list_guides(root)
    gidx = ai_path(root, "reference", "INDEX.md")
    if guides:
        gidx.write_text(build_guide_index(root), encoding="utf-8")
        print(f"[ok] guide router regenerated: {gidx}")
    else:
        # An EMPTY router still gets written: Rule Zero makes reading it a
        # mandatory, declared step, and `no match` may not be faked. Without the
        # stub, the required verdict is unsatisfiable on every new project --
        # and a rule that cannot be obeyed on first contact gets discarded.
        gidx.parent.mkdir(parents=True, exist_ok=True)
        gidx.write_text(guide_index_header() + "\n# Operative guides (generated router)\n\n"
                        "No guides in this project yet. This file exists so the Rule Zero "
                        "router lookup has something to read: the honest verdict here is "
                        "`router: no match`.\n\n"
                        "A guide is written when the user hands over indications to follow "
                        "(`source_kind: document`), or when a high-complexity component needs "
                        "a comprehension map (`source_kind: code`) -- see `guides.md`.\n",
                        encoding="utf-8")
        print(f"[ok] guide router regenerated (empty stub): {gidx}")
    return max(rc_registry(root), 0)


def rc_registry(root):
    """Write the generated workstream registry, or refuse and say why (F-028)."""
    ws = list_workstreams(root)
    hand = ai_path(root, "audit", "handoff.md")
    if not ws:
        # No sources: a hand-written handoff is untouched; a generated one is
        # emptied, or the last closed workstream would stay listed forever.
        if not hand.is_file():
            return 0
        existing = read_text(hand)
        if not is_generated_registry(existing):
            return 0
        empty = build_empty_registry(root, existing)
        if norm_text(existing) != norm_text(empty):
            hand.write_text(empty, encoding="utf-8")
            print(f"[ok] workstream registry emptied (no open workstreams): {hand}")
        return 0
    blockers = registry_conversion_blockers(root)
    if blockers:
        print(f"[ERROR] {docs_dir()}/audit/handoff.md NOT regenerated -- it still holds "
              "state no source accounts for:")
        for b in blockers:
            print(f"          - {b}")
        print("          Convert the whole registry at once (templates.md): converting "
              "one row at a time is the state that loses the others.")
        return 1
    hand.parent.mkdir(parents=True, exist_ok=True)
    hand.write_text(build_registry(root), encoding="utf-8")
    print(f"[ok] workstream registry regenerated: {hand}")
    if len(ws) > REGISTRY_CAP:
        print(f"[warn] {len(ws)} open workstreams: the registry is meant to stay under "
              f"{REGISTRY_CAP}. Nothing was truncated -- closing one is the fix.")
    return 0


# ----------------------------------------------------------------- validate

def has_section(text, aliases):
    return any(a in text for a in aliases)


def section_body(text, aliases):
    """The body of the first matching `## ` section, or None if no alias is present.

    Portable checks read a section rather than the whole document, so a phrase that
    happens to appear elsewhere cannot satisfy a check about this section."""
    lines = text.splitlines()
    for i, line in enumerate(lines):
        if not any(line.startswith(a) for a in aliases):
            continue
        body = []
        for nxt in lines[i + 1:]:
            if nxt.startswith("## "):
                break
            body.append(nxt)
        return "\n".join(body).strip()
    return None


def section_lines(text, aliases):
    """(heading_line, body) for the first matching `## ` section, or None: the
    body NOT stripped, so body line n is file line heading_line + n, and an
    indented first line keeps its indentation. The readers below use it; a
    stripped body would shift every line number and move `  - DATE` to column 0."""
    lines = (text or "").splitlines()
    for i, line in enumerate(lines):
        if any(line.startswith(a) for a in aliases):
            body = []
            for nxt in lines[i + 1:]:
                if nxt.startswith("## "):
                    break
                body.append(nxt)
            return i + 1, "\n".join(body)
    return None


# ---------------------------------------------------------------- chronology
# One grammar for a dated entry (F-073), read by the validator and by any
# consumer that lists events (F-072's chronology): both call these readers, so
# they cannot disagree on what an event is. The readers return openers only --
# date, label, line -- and format nothing for display.

DIARY_SECTION = next(s for s in ANALYSIS_SECTIONS if s[0] == "## Diary")
_ISO = r"\d{4}-\d{2}-\d{2}"
# At column 0: optional list marker, optional `###`/`####`, optional bold, then
# the ISO date and a word boundary. The date FIRST is the rule; markup is
# tolerated so the dated forms already written stay readable with no migration.
ENTRY_OPENER = re.compile(r"^(?:([-*]) |(#{3,4}) )?(\*\*)?(" + _ISO + r")\b(.*)$")
_LABEL_SEP = re.compile(r"^(?:\*\*)?\s*(?:[—–:-])?\s*")
_REQUEST_HEADING = re.compile(r"^### (R\d+) [—–-] (" + _ISO + r") [—–-] (.+)$")
_ADR_BODY_DATE = re.compile(r"^\**Date:\**\s*(" + _ISO + r")\b", re.M)
_ADR_NAME_DATE = re.compile(r"^ADR_(" + _ISO + r")_", re.I)
UNIT_ID_RE = re.compile(r"\b([A-Z]-\d{3,})\b")


def _entry_label(bold, rest):
    rest = _LABEL_SEP.sub("", rest, count=1)
    if bold and "**" in rest:
        rest = rest.split("**", 1)[0]
    else:
        rest = re.split(r"(?<=[.!?])\s", rest, maxsplit=1)[0]
    return rest.strip(" .:—–-*")[:120]


def _opener_at(lines, i):
    """The match when lines[i] opens an entry. It must also START A BLOCK -- the
    line above is blank, absent or a heading, or the line is itself a list item
    or a heading -- so a hard-wrapped prose line that happens to begin with a
    date is never an event. (A separator after the date is NOT required: real
    openers read `DATE (qualifier)` and `DATE word`.)"""
    m = ENTRY_OPENER.match(lines[i])
    if not m:
        return None
    prev = lines[i - 1] if i else ""
    if not prev.strip() or prev.startswith("#") or m.group(1) or m.group(2):
        return m
    return None


def malformed_openers(body):
    """[(line, text)] -- dated openers whose bold does not pair: `**DATE …` with no
    closing `**` on the line, or a bare `DATE …` that closes one. Either way the
    chronology shows a label running into the entry's body (field case 2026-10-19:
    two release notes in project_notes.md)."""
    lines = _blank_comments(body).splitlines()
    out = []
    for i in range(len(lines)):
        m = _opener_at(lines, i)
        if m and bool(m.group(3)) != ("**" in m.group(5)):
            out.append((i + 1, lines[i]))
    return out


def entry_openers(body):
    """[(date, label, line)] -- one per dated entry opener; line is 1-based
    within `body`. An undated paragraph belongs to the entry above it. Comments
    are blanked first, exactly as `undated_diary_lines` does, so an entry
    written under the template's comment is an event to both."""
    lines = _blank_comments(body).splitlines()
    out = []
    for i in range(len(lines)):
        m = _opener_at(lines, i)
        if m:
            out.append((m.group(4), _entry_label(m.group(3), m.group(5)), i + 1))
    return out


def _blank_comments(text):
    # comments become blank lines, so line numbers still point at the file's lines
    return re.sub(r"<!--.*?-->", lambda m: "\n" * m.group(0).count("\n"), text or "",
                  flags=re.S)


def undated_diary_lines(body):
    """[(line, text)] a Diary body cannot date: text before the first opener,
    and any `### ` heading that is not an opener. `####` and deeper headings are
    sub-structure of an entry and stay legal. Comments are ignored."""
    lines = _blank_comments(body).splitlines()
    out, seen_opener = [], False
    for i, line in enumerate(lines):
        if _opener_at(lines, i):
            seen_opener = True
        elif line.startswith("### "):
            out.append((i + 1, line.strip()))
        elif not seen_opener and line.strip():
            out.append((i + 1, line.strip()))
    return out


def request_entries(text):
    """(entries, unparsed) for a request record: entries are
    [(rid, date, label, line)]; a `### ` heading that does not match
    `### R<n> — YYYY-MM-DD — <label>` is returned in unparsed as (line, text),
    never dropped."""
    entries, unparsed = [], []
    for i, line in enumerate((text or "").splitlines()):
        if not line.startswith("### "):
            continue
        m = _REQUEST_HEADING.match(line.rstrip())
        if m:
            entries.append((m.group(1), m.group(2), m.group(3).strip(), i + 1))
        else:
            unparsed.append((i + 1, line.rstrip()))
    return entries, unparsed


def adr_date(name, text):
    """An ADR's date: `**Date:** YYYY-MM-DD` in the body, else the
    `ADR_YYYY-MM-DD_*` file name, else None."""
    m = _ADR_BODY_DATE.search(text or "") or _ADR_NAME_DATE.match(name or "")
    return m.group(1) if m else None


def _meta_date(meta, key):
    return parse_iso(str(meta.get(key) or "").strip().strip("'\"")[:10])


def chronology_advisories(root):
    """A1 (undated Diary text) and A2 (`next:` is not one step), as advisory
    strings. Gated on `level: L3` and on a date the file carries -- never an
    mtime -- so L1/L2 work and anything written before the epoch see nothing."""
    epoch = parse_iso(CHRONOLOGY_EPOCH)
    out = []
    for p, meta, text in list_analyses(root):
        started = _meta_date(meta, "start_date")
        if str(meta.get("level", "")).upper() != "L3" or not started or started < epoch:
            continue
        section = section_lines(text, DIARY_SECTION)
        if section is None:
            continue
        head, body = section
        rel = "solutions/" + p.name
        lines = undated_diary_lines(body)
        preface = [(n, t) for n, t in lines if not t.startswith("### ")]
        if preface:
            out.append(f"{rel}: line {head + preface[0][0]}: Diary text '{preface[0][1][:60]}' "
                       "comes before the first dated entry -- open entries with "
                       "**YYYY-MM-DD — label.**, and write the current state as the latest "
                       "dated entry")
        for n, t in lines:
            if t.startswith("### "):
                out.append(f"{rel}: line {head + n}: Diary heading '{t[:60]}' is not a dated "
                           "entry -- open entries with **YYYY-MM-DD — label.**")
    for p, meta in list_workstreams(root):
        updated = _meta_date(meta, "updated")
        if str(meta.get("level", "")).upper() != "L3" or not updated or updated < epoch:
            continue
        nxt = str(meta.get("next") or "").strip()
        if len(nxt) > NEXT_MAX_CHARS:
            out.append(f"audit/{p.name}: next: is {len(nxt)} chars (> {NEXT_MAX_CHARS}): one "
                       "next step here, the state goes to the Diary as a dated entry")
    notes = ai_path(root, "audit", PROJECT_NOTES)
    if notes.is_file():
        for n, t in malformed_openers(read_text(notes)):
            out.append(f"audit/{PROJECT_NOTES}: line {n}: dated entry '{t[:60]}' has unpaired "
                       "bold -- open entries with **YYYY-MM-DD — label.**")
    return out


def _open_units(root):
    """{id: {analysis name}} for the tree's open L3 units: an L3 ANALYSIS that is
    PLANNED or IN_PROGRESS, or a request record (L3 only, r26) whose `analysis:`
    is absent from the tree or names such an open ANALYSIS. A closed unit's
    record, kept forever, does not count."""
    units, present, open_names = {}, set(), set()
    for p, meta, _ in list_analyses(root):
        present.add(p.name)
        if (str(meta.get("level", "")).upper() == "L3"
                and meta.get("status") in ("PLANNED", "IN_PROGRESS")):
            m = UNIT_ID_RE.search(str(meta.get("id") or ""))
            if m:
                open_names.add(p.name)
                units.setdefault(m.group(1), set()).add(p.name)
    req = ai_path(root, "audit", "requests")
    if req.is_dir():
        for p in sorted(req.glob("REQUEST_*.md")):
            meta = load_frontmatter(read_text(p).splitlines())
            name = str(meta.get("analysis") or "").strip().strip("'\"`")
            m = UNIT_ID_RE.search(str(meta.get("unit") or meta.get("id") or ""))
            if m and name and (name not in present or name in open_names):
                units.setdefault(m.group(1), set()).add(name)
    return units


def _git_out(root, *args, timeout=30, env=None):
    # `env` is merged into the inherited environment, never a replacement: a bare
    # dict would drop PATH and fail silently on Windows.
    r = subprocess.run(["git", *args], cwd=str(root), capture_output=True, text=True,
                       encoding="utf-8", errors="replace", timeout=timeout,
                       env={**os.environ, **env} if env else None)
    return r.stdout if r.returncode == 0 else None


def ids_on_other_refs(root, max_refs=ID_SCAN_MAX_REFS):
    """[(id, mine, theirs, [refs])] -- an open unit's id that another ref (heads,
    remotes, tags) uses for a DIFFERENT analysis. Identity is the ANALYSIS file
    name, declared by the ANALYSIS or announced by a request record's
    `analysis:`. One `git grep` over local refs, fixed arguments only (T8);
    as fresh as the last fetch. [] with no open L3 unit or no git; None when
    skipped -- above `max_refs` refs, or git failed or timed out -- so the
    caller can say the check did not run instead of reporting it clean."""
    mine = _open_units(root)
    if not mine or not git_available(root):
        return []
    try:
        head = (_git_out(root, "rev-parse", "HEAD") or "").strip()
        listing = _git_out(root, "for-each-ref",
                           "--format=%(objectname) %(objecttype) %(*objecttype) %(refname)",
                           "refs/heads", "refs/remotes", "refs/tags")
        if listing is None:
            return None
        refs = []
        for line in listing.split("\n"):
            parts = line.split(" ")
            if len(parts) == 3:                     # %(*objecttype) empty: not a tag
                parts.insert(2, "")
            if len(parts) != 4:
                continue
            sha, kind, peeled, ref = parts
            # only refs that resolve to a commit can be grepped (a tag on a blob
            # would fail the whole batch); the tree's own commit is not "another
            # ref"; symbolic HEADs repeat a branch
            if "commit" not in (kind, peeled) or ref.endswith("/HEAD") or sha == head:
                continue
            refs.append(ref)
        if not refs:
            return []
        if len(refs) > max_refs:
            return None
        # Pathspecs are relative to cwd=root, so a docs root inside a monorepo
        # subdirectory is found. -z keeps a path with ':' or non-ASCII intact
        # (quotePath off); -n plus the fence lines confine hits to frontmatter.
        docs = docs_dir()
        chunks = []
        for i in range(0, len(refs), ID_SCAN_REFS_PER_CALL):   # command-line length
            r = subprocess.run(
                ["git", "-c", "core.quotePath=false", "grep", "-z", "-n", "-I", "-E",
                 r"^(id|unit|analysis):|^---\s*$", *refs[i:i + ID_SCAN_REFS_PER_CALL],
                 "--", f"{docs}/solutions/ANALYSIS_*.md", f"{docs}/audit/requests/REQUEST_*.md"],
                cwd=str(root), capture_output=True, text=True, encoding="utf-8",
                errors="replace", timeout=60)
            if r.returncode not in (0, 1):                     # 1 = no match
                return None
            chunks.append(r.stdout)
    except Exception:
        return None
    per = {}
    for line in "".join(chunks).split("\n"):     # not splitlines: \x1c.. are content
        parts = line.split("\0")
        if len(parts) != 3 or ":" not in parts[0] or not parts[1].isdigit():
            continue
        ref, path = parts[0].split(":", 1)          # a ref name cannot hold ':'
        content = parts[2].rstrip("\r")
        st = per.setdefault((ref, path), {"fences": 0, "kv": {}})
        if int(parts[1]) == 1 and content.strip() == "---":
            st["fences"] = 1                        # frontmatter opens on line 1
        elif st["fences"] == 1 and content.strip() == "---":
            st["fences"] = 2                        # ...and closes here
        elif st["fences"] == 1:
            key, _, val = content.partition(":")
            st["kv"].setdefault(key, val.strip())
    found = {}
    for (ref, path), st in per.items():
        kv = st["kv"]
        fname = path.replace("\\", "/").rsplit("/", 1)[-1]
        name = fname if fname.startswith("ANALYSIS_") else kv.get("analysis", "").strip("'\"`")
        m = UNIT_ID_RE.search(kv.get("id") or kv.get("unit") or "")
        if not (m and name) or m.group(1) not in mine or name in mine[m.group(1)]:
            continue
        short = re.sub(r"^refs/(heads|remotes|tags)/", "", ref)
        found.setdefault((m.group(1), name), [])
        if short not in found[(m.group(1), name)]:
            found[(m.group(1), name)].append(short)
    return sorted((fid, ", ".join(sorted(mine[fid])), theirs, sorted(refs_))
                  for (fid, theirs), refs_ in found.items())


def id_advisories(root):
    """A3 as advisory strings, for every entry point's `check`."""
    hits = ids_on_other_refs(root)
    if hits is None:
        return [f"id check skipped (more than {ID_SCAN_MAX_REFS} refs, or git grep failed "
                "or timed out) -- choose a new unit's id after fetching, as the first id "
                "free on every ref"]
    out = []
    for fid, mine, theirs, refs in hits:
        more = f" (+{len(refs) - 1} more)" if len(refs) > 1 else ""
        out.append(f"id {fid} ({mine}) is also used by {theirs} on {refs[0]}{more}: choose "
                   "the first id free on every ref -- if this is the same unit under its "
                   "old name, ignore it")
    return out


def _l3_in_work_since(meta, epoch):
    """True when an L3 ANALYSIS is in implementation or done and began on/after
    `epoch` (an ISO date string)."""
    if meta.get("level", "").upper() != "L3":
        return False
    if meta.get("status") not in ("IN_PROGRESS", "COMPLETED"):
        return False
    started = parse_iso((meta.get("start_date") or "").strip().strip("'\""))
    return started is not None and started >= parse_iso(epoch)


def design_review_due(meta):
    """True when an L3 ANALYSIS owes a design-review row (review.md moment 1):
    implementation has started or finished, and it began on/after the gate
    shipped. PLANNED is exempt -- the review is due at the END of Phase 3, so an
    analysis still being drafted is not late."""
    return _l3_in_work_since(meta, DESIGN_REVIEW_EPOCH)


def design_approval_due(meta):
    """True when an L3 ANALYSIS owes the owner's design approval (review.md
    section When a review is due): in implementation or done, begun on/after
    DESIGN_APPROVAL_EPOCH. PLANNED is exempt -- the question comes after the PASS."""
    return _l3_in_work_since(meta, DESIGN_APPROVAL_EPOCH)


def requests_naming(root, analysis_name):
    """The request records whose `analysis:` field names this ANALYSIS file."""
    req = ai_path(root, "audit", "requests")
    if not req.is_dir():
        return []
    return [r for r in sorted(req.glob("REQUEST_*.md"))
            if str(load_frontmatter(read_text(r).splitlines()).get("analysis") or "")
            .strip().strip("'\"`") == analysis_name]


def design_approval_logged(root, analysis_name):
    """True when a request record naming this ANALYSIS has an entry whose LABEL
    begins `design approved` (case-insensitive). Only the label is read, never
    the quoted words: a quotation is data, and a 'design approved?' inside a
    refusal approves nothing."""
    return any(label.lower().startswith("design approved")
               for r in requests_naming(root, analysis_name)
               for _, _, label, _ in request_entries(read_text(r))[0])


def review_logged(root, analysis_name):
    """True when REVIEW_LOG.md carries a design-moment row naming this ANALYSIS.
    The filename matches anywhere in the row (loose on purpose: a freshness
    signal must not turn a formatting slip into a false 'you skipped the
    review'), but the moment is read from the `tier` COLUMN -- the schema
    reserves it for exactly this, and matching 'design' anywhere in the row let
    a CLOSURE row saying 'conformance to the design' satisfy the check."""
    log = root / review_log_rel()
    if not log.is_file():
        return False
    stem = analysis_name[:-3] if analysis_name.endswith(".md") else analysis_name
    # match the filename on a word boundary: a plain substring lets a longer
    # sibling (ANALYSIS_vision_clarity) satisfy a shorter one (ANALYSIS_vision)
    name_re = re.compile(r"(?<![\w-])" + re.escape(stem) + r"(?![\w-])")
    tier_idx = None
    for line in read_text(log).splitlines():
        line = line.strip()
        if not line.startswith("|"):
            continue
        cells = [c.strip() for c in line.strip("|").split("|")]
        if tier_idx is None:
            lowered = [c.lower() for c in cells]
            if "tier" in lowered:          # header found: trust it over position
                tier_idx = lowered.index("tier")
                continue
        if not name_re.search(line):
            continue
        # schema: | date | doc_key | tier | reviewer | raised | real | verdict | rounds |
        idx = tier_idx if tier_idx is not None else 2
        if len(cells) > idx and re.match(r"design\b", cells[idx], re.I):
            return True
    return False


def has_ledger_heading(text):
    """True when a REAL '## Capability Ledger' heading exists: fenced code
    blocks are removed first, then HTML comments. An unterminated '<!--' only
    opens a comment at the start of a line -- nuking to EOF on an inline
    mention (or an unclosed example inside a fence) made a document that
    HAS its ledger get told it has none."""
    return bool(re.search(r"^##[ \t]+Capability Ledger[ \t]*$", strip_non_prose(text), re.M))


def strip_non_prose(text):
    """Text without fenced code blocks and HTML comments (see has_ledger_heading)."""
    stripped = re.sub(r"^(```|~~~).*?^\1", "", text, flags=re.M | re.S)
    stripped = re.sub(r"<!--.*?-->", "", stripped, flags=re.S)
    return re.sub(r"^[ \t]*<!--(?!.*?-->).*\Z", "", stripped, flags=re.M | re.S)


def has_guide_check(text):
    """True when a real '## Guide check' heading carries an answer: the template's
    comment alone answers nothing, so a copied-but-unfilled section still owes it."""
    m = re.search(r"^##[ \t]+Guide check[ \t]*$(.*?)(?=^#{1,2}[ \t]|\Z)",
                  strip_non_prose(text), re.M | re.S)
    return bool(m and m.group(1).strip())


def guide_check_due(meta, domain):
    """True when an ANALYSIS owes the Phase-3 guide question (SKILL.md): a code-lens
    L3 started on/after GUIDE_CHECK_EPOCH. Same grandfathering as ledger_due."""
    return domain == "code" and ledger_due(meta) and (
        parse_iso((meta.get("start_date") or "").strip().strip("'\""))
        >= parse_iso(GUIDE_CHECK_EPOCH))


def ledger_due(meta):
    """True when an ANALYSIS owes a '## Capability Ledger' (architect.md):
    an L3 started on/after the day the pass shipped. Grandfathered by
    start_date ALONE -- deliberately NOT by status: closure flips the ANALYSIS
    to COMPLETED before `check` runs (SKILL.md phase 5), so a status filter
    would silence the backstop at the only moment the process mandates the
    validator. A malformed/absent start_date is not due (fail-open: cmd_validate
    already errors on a missing one, and guessing an epoch from garbage would
    nag projects the pass never reached)."""
    if meta.get("level", "").upper() != "L3":
        return False
    if meta.get("status") == "CANCELLED":
        return False   # abandoned work has no legitimate way to satisfy this
    started = parse_iso((meta.get("start_date") or "").strip().strip("'\""))
    return started is not None and started >= parse_iso(ARCHITECT_PASS_EPOCH)


MAP_SECTION_RE = re.compile(r"^#{2,3}[ \t]+Component Map\b.*?$(.*?)(?=^#{1,3}[ \t]+\S|\Z)",
                            re.M | re.S | re.I)


def map_where_refs(arch_text):
    """Normalized, symbol-stripped paths from the Component Map's 'Where' column
    ONLY -- never from the whole document. Harvesting the whole file let the
    canonical template's own '## Directory Structure' backticks satisfy the check
    and silently disable it on every project that fills that section in.
    Returns None when the document has no Component Map at all."""
    m = MAP_SECTION_RE.search(arch_text)
    if not m:
        return None
    refs, where_idx = [], None
    for ln in m.group(1).splitlines():
        ln = ln.strip()
        if not ln.startswith("|"):
            continue
        cells = [c.strip() for c in ln.strip("|").split("|")]
        if len(cells) < 2 or not cells[0] or set(cells[0]) <= {"-", ":"}:
            continue
        if where_idx is None:
            lowered = [c.lower() for c in cells]
            if "where" not in lowered:
                return []          # no Where column: nothing is mapped
            where_idx = lowered.index("where")
            continue
        if where_idx < len(cells):
            for _ref, path_part, _sym in _map_refs(cells[where_idx]):
                refs.append(path_part.lstrip("./").strip("/"))
    return refs


def _map_refs(where):
    """Backticked refs in a 'Where' cell that are file paths: they contain a
    separator, or end in a KNOWN source-file suffix. Windows separators are
    normalized. Everything else in that cell is prose and must stay silent --
    a false 'the map is rotting' teaches readers to ignore the output, which is
    worse than the rot. `app.core`, `OrderStore.save` and `1.18.0` are prose."""
    out = []
    for ref in re.findall(r"`([^`]+)`", where):
        path_part, _, symbol = ref.partition("#")
        path_part = path_part.replace("\\", "/").strip()
        if not path_part or "://" in path_part:
            continue  # a URL is not a repo path
        # A slash-less token counts only if it looks like a FILENAME. The one
        # real false-positive class is `Next.js` / `Node.js` / `Vue.js`: a
        # CamelCase stem with a `.js` tail is a framework name, not a file.
        # The exclusion is scoped to that suffix ON PURPOSE -- a blanket
        # CamelCase rule would silence `App.tsx`, `Program.cs`, `Main.java`,
        # which are exactly what React/C#/Java projects put in a Where cell.
        stem, _, suffix = path_part.rsplit("/", 1)[-1].rpartition(".")
        framework_name = (suffix.lower() == "js"
                          and bool(re.fullmatch(r"[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*", stem)))
        looks_like_path = "/" in path_part or (
            bool(re.search(r"\.(" + "|".join(FILE_SUFFIXES) + r")$", path_part, re.I))
            and not framework_name)
        if looks_like_path:
            out.append((ref, path_part, symbol.strip()))
    return out


def check_component_map(root, text, advisories):
    """Anti-rot for the '## Component Map' of strategic/architecture.md
    (architect.md): every path-shaped backticked ref in the 'Where' column must
    still resolve on disk, and its '#symbol' must still appear as a whole word
    in a matched file. This is the map's equivalent of the guides' source_hash.
    ADVISORY: a freshness signal, never a gate -- not even under --strict (the
    accepted ceremony budget was a warning, not a blocked pipeline)."""
    m = MAP_SECTION_RE.search(text)   # one regex for both checks: they cannot drift
    if not m:
        return
    rows = [ln.strip() for ln in m.group(1).splitlines() if ln.strip().startswith("|")]
    where_idx, header_cells, checked, data_rows, ragged = None, 0, 0, 0, 0
    for row in rows:
        cells = [c.strip() for c in row.strip("|").split("|")]
        if len(cells) < 2 or not cells[0] or set(cells[0]) <= {"-", ":"}:
            continue
        if where_idx is None:  # the first non-separator row is the header
            lowered = [c.lower() for c in cells]
            if "where" not in lowered:
                advisories.append("strategic/architecture.md: Component Map has no 'Where' "
                                  "column in its header -- the anti-rot check cannot run; "
                                  "give the table a Where column of `path/to/file#Symbol` refs")
                return
            where_idx, header_cells = lowered.index("where"), len(cells)
            continue
        if all(c in ("", "...", "…") for c in cells):
            continue                      # untouched template placeholder row
        data_rows += 1
        if len(cells) != header_cells:    # ragged: never silently unchecked
            ragged += 1
            continue
        component, where = cells[0], cells[where_idx]
        for ref, path_part, symbol in _map_refs(where):
            checked += 1
            if confine_under(root, re.sub(r"[*?\[\]]", "x", path_part)) is None:
                advisories.append(f"strategic/architecture.md: Component Map row '{component}': "
                                  f"ref '{ref}' escapes the project root: rejected")
                continue
            target = root / path_part
            try:
                if target.exists():          # literal first: `app/[id]/page.tsx` is a real path
                    matches = [target]
                elif any(c in path_part for c in "*?["):
                    matches = list(root.glob(path_part))
                else:
                    matches = []
            except (ValueError, OSError):
                matches = []
            if not matches:
                advisories.append(f"strategic/architecture.md: Component Map row '{component}': "
                                  f"'{path_part}' no longer exists -- the map is rotting, "
                                  "update the row or drop it")
                continue
            files = [f for f in matches if f.is_file()]
            if symbol and files:
                word = re.compile(r"(?<![A-Za-z0-9_])" + re.escape(symbol) + r"(?![A-Za-z0-9_])")
                if not any(word.search(read_text(f)) for f in files):
                    advisories.append(f"strategic/architecture.md: Component Map row '{component}': "
                                      f"symbol '{symbol}' not found in '{path_part}' -- renamed or "
                                      "removed, update the row")
    if ragged:
        advisories.append(f"strategic/architecture.md: Component Map has {ragged} row(s) whose "
                          "column count differs from the header -- unchecked; an escaped '|' in "
                          "a cell shifts the columns")
    if data_rows and not checked and not ragged:
        # only once the map claims real components: a freshly seeded project
        # carries the template placeholder and must NOT be nagged on day zero
        advisories.append("strategic/architecture.md: Component Map has rows but no checkable "
                          "path in its 'Where' column -- the anti-rot check is inert; write refs "
                          "as `path/to/file#Symbol`")


def cmd_validate(root, strict=False, hybrid=False):
    # advisories: architect-pass freshness signals. Reported, never escalated by
    # --strict -- the accepted ceremony budget (project_vision.md "no ceremony
    # ratchet") was a warning, and a warning that reddens CI is a gate.
    errors, warnings, advisories = [], [], []
    ai = ai_path(root)
    if not ai.is_dir():
        if strict:
            print(f"[ERROR] {ai} does not exist: nothing to validate. In --strict mode this "
                  "fails so a wrong working directory cannot produce a green pipeline.")
            return 1
        print(f"[info] {ai} does not exist: nothing to validate (project without SDLC docs).")
        return 0

    # Vision: presence and declared state
    for name in VISION_FILES:
        f = ai / "vision" / name
        if not f.is_file():
            warnings.append(f"vision/{name} missing")
            continue
        head = "\n".join(read_text(f).splitlines()[:12])
        m = re.search(r"(?:Status|Stato):\s*(DRAFT|APPROVED)", head)
        if not m:
            errors.append(f"vision/{name}: missing 'Status: DRAFT|APPROVED' in the first lines")
        elif m.group(1) == "DRAFT":
            # advisory, not a warning: bootstrap MANDATES DRAFT, so a warning here
            # makes `validate --strict` red on every freshly bootstrapped project
            # until a human runs the blind check -- and teams delete the CI step
            # rather than block on it. DRAFT is a state, not a defect.
            advisories.append(f"vision/{name} is DRAFT: not a gating authority, "
                              "have the user validate it")

    # ANALYSIS: frontmatter and mandatory sections
    # Ids are unique WITHIN a domain (prefixes F-/K-/M-/C- keep them apart in practice):
    # two lenses over one tree must not collide on a number neither of them chose.
    seen_ids = {}
    default_domain = project_default_domain(root)
    analyses = list_analyses(root)
    for p, meta, text in analyses:
        rel = "solutions/" + p.name
        if not meta:
            errors.append(f"{rel}: frontmatter missing")
            continue
        domain, unknown_domain = resolve_domain(meta, default_domain)
        if unknown_domain:
            warnings.append(f"{rel}: domain '{unknown_domain}' not recognized "
                            f"({'/'.join(sorted(DOMAINS))}): validated as '{domain}'")
        fid = meta.get("id")
        if not fid:
            errors.append(f"{rel}: 'id' field missing")
        elif (domain, fid) in seen_ids:
            errors.append(f"{rel}: id '{fid}' duplicated (already used in {seen_ids[(domain, fid)]})")
        else:
            seen_ids[(domain, fid)] = rel
        status = meta.get("status", "")
        if status not in VALID_STATES:
            errors.append(f"{rel}: status '{status}' not valid ({'/'.join(sorted(VALID_STATES))})")
        if not meta.get("start_date"):
            errors.append(f"{rel}: 'start_date' missing")
        if status == "COMPLETED" and not meta.get("end_date"):
            errors.append(f"{rel}: COMPLETED without 'end_date'")
        level = meta.get("level")
        if level and level.upper() not in VALID_LEVELS:
            warnings.append(f"{rel}: level '{level}' not recognized ({'/'.join(sorted(VALID_LEVELS))})")
        # The risk slot is translated per domain, never dropped: whichever lens owns
        # the document, it owes ITS account of what could go wrong.
        rules = DOMAINS[domain]
        if not has_section(text, rules["risk_section"]):
            errors.append(f"{rel}: section '{rules['risk_label']}' missing (mandatory)")
        for en, it in ANALYSIS_SECTIONS:
            if not has_section(text, (en, it)):
                warnings.append(f"{rel}: section '{en}' missing")
        run_portable_checks(rel, meta, text, errors, warnings, advisories)
        if not level and (parse_iso((meta.get("start_date") or "").strip().strip("'\"")) or
                          parse_iso("1970-01-01")) >= parse_iso(ARCHITECT_PASS_EPOCH):
            # advisory + epoch-gated, exactly like the check it guards: a warning
            # here would redden --strict CI on every pre-1.18 analysis that never
            # carried the optional field. (Same defect the advisories bucket was
            # invented to prevent -- reintroduced once, caught in review.)
            advisories.append(f"{rel}: 'level' missing (L1/L2/L3/Spike) -- risk-proportional "
                              "checks cannot apply, and dropping the line is cheaper than "
                              "doing the work it triggers")
        # comment-stripped, anchored: a '<!-- TODO: the ## Capability Ledger -->'
        # must not read as the section being present
        # Hybrid: the design lives in devPNT, and the agent review of it (the
        # same review.md review, run before the proposal) logs a row keyed on
        # its e_isp_/e_tdd_ doc_key, not on this filename -- so firing here
        # would be a permanent, unfixable false positive.
        if not hybrid and design_review_due(meta) and not review_logged(root, p.name):
            advisories.append(f"{rel}: L3 in implementation with no design-review row in "
                              f"{review_log_rel()} -- the design was reviewed by nobody but its "
                              "author before code was written (review.md moment 1)")
        if (not hybrid and design_approval_due(meta)
                and not design_approval_logged(root, p.name)):
            advisories.append(f"{rel}: L3 in implementation with no design approval in its "
                              "request record (no entry whose label begins 'design approved') -- the "
                              "owner never said the design was what they meant before the "
                              "work started (review.md, When a review is due)")
        if ledger_due(meta) and not has_ledger_heading(text):
            advisories.append(f"{rel}: L3 without '## Capability Ledger' -- the architect pass "
                              "left no record (architect.md); run it before the Impact")
        if guide_check_due(meta, domain) and not has_guide_check(text):
            advisories.append(f"{rel}: L3 without a filled '## Guide check' -- does a CURRENT "
                              "guide cover what this touches, and did understanding it force "
                              "a model of a complex component no guide covers (guides.md, section 1)?")
        # F-085 FS7: code lens only (R12: the lens, not merely the domain -- a kb
        # install validating a code-domain unit sees no change), open L3 only, a
        # note and never an error, so no `--strict` exit changes (P5).
        impact = section_body(text, IMPACT_SECTION)
        if (has_capability("preservation_constraints") and domain == "code"
                and str(level or "").upper() == "L3"
                and status in ("PLANNED", "IN_PROGRESS")
                and impact is not None and not has_preservation_record(impact)):
            advisories.append(f"{rel}: open L3 whose '## Impact' has neither the "
                              f"'{PRESERVATION_HEADING}' table nor the line "
                              f"'{NO_SYMBOL_LINE}' -- what existing code must keep "
                              "doing is not extractable (templates.md)")

    # Generated index aligned
    hist = ai / "strategic" / "features_history.md"
    if analyses:
        if not hist.is_file():
            errors.append("strategic/features_history.md missing: run 'sdlc_check.py index'")
        elif norm_text(read_text(hist)) != norm_text(build_index(root)):
            errors.append("strategic/features_history.md not aligned with the ANALYSIS files: run 'sdlc_check.py index'")

    # Canonical document manifest aligned (Poka-Yoke: unindexed file = dirty closure)
    docs = list_canonical_docs(root)
    manifest = ai / "INDEX.md"
    if docs:
        if not manifest.is_file():
            errors.append(f"{docs_dir()}/INDEX.md missing: run 'sdlc_check.py index'")
        elif norm_text(read_text(manifest)) != norm_text(build_manifest(root)):
            errors.append(f"{docs_dir()}/INDEX.md not aligned with the canonical documents: run 'sdlc_check.py index'")

    # Canonical document lifecycle: declared status + supersedes coherence
    canon_status = {rel: meta[2] for rel, _, meta in docs}
    for rel, _, (title, desc, status, supersedes) in docs:
        if not status:
            warnings.append(f"{rel}: missing 'status:' in the header (CURRENT/SUPERSEDED/DRAFT/DEPRECATED)")
        elif status not in CANONICAL_STATES:
            warnings.append(f"{rel}: status '{status}' not recognized ({'/'.join(sorted(CANONICAL_STATES))})")
        if supersedes:
            base = os.path.basename(supersedes)
            for other, ost in canon_status.items():
                if (other == supersedes or other.endswith("/" + supersedes)
                        or os.path.basename(other) == base) and ost == "CURRENT":
                    warnings.append(f"{other}: still CURRENT but superseded by {rel} (set status: SUPERSEDED)")

    # Component Map anti-rot (architect.md): rows must still resolve on disk
    arch = ai / "strategic" / "architecture.md"
    if arch.is_file():
        arch_text = read_text(arch)
        check_component_map(root, arch_text, advisories)
        # the missing half of the loop: `mark` asserts an area was read closely
        # enough to name its capability owners, and nothing verified that claim.
        # An ANALYZED area with no map row is how the brownfield guard is
        # disarmed -- the area looks read, so the map's silence becomes groundable.
        _, _, plan_rows = parse_audit_plan(root)
        mapped = map_where_refs(arch_text)
        if plan_rows and mapped is not None:
            for prow in plan_rows:
                if prow["status"] != "ANALYZED":
                    continue
                if confine_under(root, prow["path"]) is None:
                    continue                     # stale already rejects these
                if re.search(r"owns no component", prow.get("note", ""), re.I):
                    continue                     # declared, not forgotten: the opt-out
                area = prow["path"].replace("\\", "/").strip("/")
                if area.startswith("./"):
                    area = area[2:]
                if area in ("", "."):
                    continue                     # the whole root: every row is inside it
                if not (root / area).exists():
                    continue                     # gone from disk: not a mapping gap
                if not any(mp == area or mp.startswith(area + "/") for mp in mapped):
                    advisories.append(
                        f"strategic/architecture.md: '{prow['path']}' is ANALYZED in the audit "
                        "plan but owns no Component Map row -- marking asserts the area was read "
                        "closely enough to name what it owns, and the map's silence there is now "
                        "groundable for a MISSING verdict (architect.md). If it genuinely owns no "
                        "component, say so in the audit plan's Notes column: 'owns no component'")

    # Guide checks (ai_docs/reference/GUIDE_*.md): structure only — freshness is stale's job
    guides = list_guides(root)
    for rel, p, meta, text in guides:
        missing = [k for k in GUIDE_PROVENANCE_KEYS if not meta.get(k)]
        if missing:
            warnings.append(f"{rel}: guide missing provenance key(s): {', '.join(missing)}")
        # (b) per-section fidelity markers: every '## ' section body must carry a marker
        body = text.split("---", 2)[-1]
        sections = re.split(r"^##\s+", body, flags=re.M)[1:]
        unmarked = [s.splitlines()[0].strip() for s in sections if not GUIDE_MARKER_RE.search(s)]
        if unmarked:
            warnings.append(f"{rel}: section(s) without [source: ...] / [not covered by source] marker: "
                            + "; ".join(unmarked[:5]))
        # (c) distilled_from confinement — fail closed (P-TM T6, distilled_from vector)
        df = meta.get("distilled_from", "")
        if df and confine_under(root, df) is None:
            errors.append(f"{rel}: distilled_from '{df}' is absolute, contains '..', or resolves "
                          "outside the project root: rejected")
    check_kb_collisions(root, guides, errors, warnings)
    # guide-router alignment (mirror of the root-manifest check)
    gidx = ai_path(root, "reference", "INDEX.md")
    if not gidx.is_file() and not guides:
        # zero guides: the stub is a convenience for the mandatory Rule Zero read
        advisories.append(f"{docs_dir()}/reference/INDEX.md missing: Rule Zero requires reading the "
                          "guide router and forbids faking its verdict, so the router exists "
                          "even with zero guides -- run 'sdlc_check.py index'")
    if guides:
        if not gidx.is_file():
            # guides EXIST and the router does not: the agent's mandatory lookup
            # finds nothing and legally declares 'absent', so the guide that
            # governs the work is never consulted. An absent router must not be
            # graded below a merely stale one.
            errors.append(f"{docs_dir()}/reference/INDEX.md missing while GUIDE_*.md files exist: "
                          "the router is the only thing that routes work to them -- "
                          "run 'sdlc_check.py index'")
        elif norm_text(read_text(gidx)) != norm_text(build_guide_index(root)):
            errors.append(f"{docs_dir()}/reference/INDEX.md not aligned with the guides: run 'sdlc_check.py index'")

    # Handoff: alignment with its sources (F-028), then header and freshness
    hand = ai / "audit" / "handoff.md"
    workstreams = list_workstreams(root)
    if workstreams:
        if not hand.is_file():
            errors.append(f"{docs_dir()}/audit/handoff.md missing while HANDOFF_*.md sources "
                          "exist: the registry is the only place a cold agent sees the open "
                          "workstreams -- run 'sdlc_check.py index'")
        elif norm_text(read_text(hand)) != norm_text(build_registry(root)):
            errors.append(f"{docs_dir()}/audit/handoff.md not aligned with its HANDOFF_*.md "
                          "sources: run 'sdlc_check.py index'. A merge resolved by hand is "
                          "exactly what this catches")
        if len(workstreams) > REGISTRY_CAP:
            warnings.append(f"{len(workstreams)} open workstreams: the registry is meant to "
                            f"stay under {REGISTRY_CAP}")
        # Two files claiming one workstream is the collision this design does NOT
        # fix (two people opening the same work under different file names). It
        # would otherwise show up as two identical-looking rows and nothing else.
        seen = {}
        for p, meta in workstreams:
            wid = str(meta.get("workstream")).strip()
            if wid in seen:
                warnings.append(f"{docs_dir()}/audit/{p.name} and {seen[wid]} both claim "
                                f"workstream '{wid}': the registry shows two rows for one "
                                "workstream — decide which file owns it")
            else:
                seen[wid] = p.name
    elif hand.is_file():
        text = read_text(hand)
        if is_generated_registry(text) and generated_registry_rows(text):
            errors.append(f"{docs_dir()}/audit/handoff.md lists workstreams no HANDOFF_*.md "
                          "source exists for any more: run 'sdlc_check.py index' to drop "
                          "the closed rows")
    if hand.is_file():
        m = re.search(r"(?:Date|Data):\s*(\d{4}-\d{2}-\d{2})", read_text(hand))
        if not m:
            warnings.append("audit/handoff.md without a 'Date: YYYY-MM-DD' header")
        else:
            try:
                stamp = datetime.strptime(m.group(1), "%Y-%m-%d").replace(tzinfo=timezone.utc)
                age = (datetime.now(timezone.utc) - stamp).days
                if age > 14:
                    warnings.append(f"audit/handoff.md is {age} days old: treat it as history, not current state")
            except ValueError:
                warnings.append("audit/handoff.md: date not parseable")

    advisories.extend(chronology_advisories(root))   # A1, A2 (F-073)
    for a in advisories:
        print(f"[note]  {a}")
    for w in warnings:
        print(f"[warn]  {w}")
    for e in errors:
        print(f"[ERROR] {e}")
    print(f"\nValidation: {len(errors)} errors, {len(warnings)} warnings, "
          f"{len(advisories)} advisories.")
    if advisories:
        print("[note] advisories are freshness signals: never fail a build, not even --strict.")
    if strict and warnings and not errors:
        print("[strict] warnings are failures in --strict mode.")
    return 1 if errors or (strict and warnings) else 0


# ------------------------------------------------------------- audit_plan

def parse_audit_plan(root):
    f = ai_path(root, "audit", "audit_plan.md")
    rows, lines = [], []
    if f.is_file():
        lines = read_text(f).splitlines()
        for i, line in enumerate(lines):
            if not line.strip().startswith("|"):
                continue
            cells = [c.strip() for c in line.strip().strip("|").split("|")]
            if len(cells) < 2:
                continue
            if cells[0].lower() in ("path", "percorso") or set(cells[0]) <= set("-: "):
                continue
            rows.append({
                "line": i,
                "path": cells[0],
                "status": cells[1].upper(),
                "ref": cells[2] if len(cells) > 2 else "",
                "note": cells[3] if len(cells) > 3 else "",
            })
    return f, lines, rows


def cmd_stale(root, hybrid=False):
    rc = 0
    # --- guide freshness (source_hash vs snapshot) — runs in EVERY mode
    drifted = []
    for rel, p, meta, _ in list_guides(root):
        df, rec = meta.get("distilled_from", ""), meta.get("source_hash", "")
        if not df or not rec:
            continue  # structure problems are validate's job
        src = root / df
        if not src.is_file():
            print(f"[warn]  {rel}: distilled_from '{df}' not found — snapshot missing")
            rc = 1
            continue
        if sha256_file(src) != rec:
            drifted.append((rel, df))
    for rel, df in drifted:
        print(f"[stale] {rel}: source snapshot '{df}' changed since distillation — regenerate the guide")
    if drifted:
        rc = 1
    # --- audit-plan staleness — delegated to devPNT/KL in hybrid
    if hybrid:
        print("[info] hybrid mode: audit-plan staleness is delegated to devPNT/KL, skipping.")
        return rc                                  # was: implicit skip-all; guide rc survives
    f, _, rows = parse_audit_plan(root)
    if not rows:
        print(f"[info] no rows in {f}: nothing to check "
              "(audit not initialized, or Hybrid mode where mapping is delegated to devPNT).")
        return rc                                  # was: return 0 — MUST carry guide rc
    use_git = git_available(root)
    entry = entry_script()
    # The audit plan records the marks: its own edits are not a change to the area
    # that contains it. Counting them made a committed hash mark of that area
    # stale again, and every re-mark repeated the loop.
    try:
        plan_rel = f.resolve().relative_to(Path(root).resolve()).as_posix()
    except ValueError:
        plan_rel = None
    # F-056: an ANALYZED row whose reference cannot be evaluated is UNVERIFIED,
    # never fresh. Each `continue` below that skips such a row records it here;
    # skipping silently is how a pruned reference printed `[ok]` over three areas.
    unverifiable = []
    stale = []
    for row in rows:
        if row["status"] != "ANALYZED":
            continue
        rel, ref = row["path"], row["ref"]
        # Confine BEFORE touching the filesystem: audit_plan.md is document
        # content, so an absolute row ('/'), a drive-relative one or a '..'
        # escape would otherwise walk outside the project (P-TM T2/T3). A bare
        # '/' is the row init.js used to seed, and `root / "/"` is the drive.
        target = confine_under(root, rel)
        if target is None:
            print(f"[warn]  {rel}: path is absolute, contains '..', or resolves outside "
                  "the project root: rejected (use a project-relative path, '.' for the root)")
            continue
        if not target.exists():
            print(f"[warn]  {rel}: path does not exist")
            continue
        changed = []
        remark = f"re-analyze the area, then run: {entry} mark {rel}"
        if re.fullmatch(r"[0-9a-fA-F]{7,40}", ref or ""):
            if not use_git:
                print(f"[stale] {rel}: reference '{ref}' is a git commit, but git is not usable "
                      "here (not a git work tree, git missing, or the repository refused): its "
                      "freshness cannot be evaluated. Run stale inside the git work tree, or "
                      + remark)
                unverifiable.append(rel)
                continue
            state = git_ref_state(root, ref)
            if state == "missing":
                shallow = (" This clone is shallow: full history may hold it "
                           "(git fetch --unshallow)." if git_is_shallow(root) else "")
                print(f"[stale] {rel}: git ref '{ref}' is not a commit in this repository "
                      "(amended, rebased or squash-merged away and pruned, or never fetched "
                      f"here): its freshness cannot be evaluated.{shallow} To fix, " + remark)
                unverifiable.append(rel)
                continue
            if state == "orphan":
                print(f"[warn]  {rel}: git ref '{ref}' is not an ancestor of HEAD (amended, "
                      "rebased, squash-merged, or marked on another branch): it stops "
                      "resolving once git prunes it, and on any fresh clone. Re-mark now: "
                      f"{entry} mark {rel}")
            res = git_changed_since(root, ref, rel.replace("\\", "/"))
            if res is None:
                print(f"[stale] {rel}: git could not compare against ref '{ref}': its "
                      "freshness cannot be evaluated. To fix, " + remark)
                unverifiable.append(rel)
                continue
            changed = res
        else:
            ts = parse_iso(ref)
            if ts is None:
                print(f"[stale] {rel}: reference '{ref}' is neither a git commit nor an ISO "
                      "UTC timestamp: its freshness cannot be evaluated. To fix, " + remark)
                unverifiable.append(rel)
                continue
            for fp in iter_files(target):
                mtime = datetime.fromtimestamp(fp.stat().st_mtime, tz=timezone.utc)
                if mtime > ts + MTIME_GRACE:
                    try:
                        name = str(fp.relative_to(root)).replace("\\", "/")
                    except ValueError:   # symlink out of the tree: report absolute, never crash
                        name = str(fp)
                    changed.append(name)
        docs_rel = docs_root_rel(root)
        changed = [c for c in changed if c != plan_rel and not _in_docs_root(c, docs_rel)]
        if changed:
            stale.append((rel, changed))

    if unverifiable:
        rc = 1                                     # unverified is not fresh (F-056)
    if not stale:
        if not unverifiable:
            print("[ok] no analyzed area was modified after its last recorded analysis.")
        return rc                                  # was: return 0 — MUST carry guide rc
    print("Areas modified after the last recorded analysis:")
    for rel, changed in stale:
        print(f"  {rel}  ({len(changed)} files)")
        for c in changed[:10]:
            print(f"    - {c}")
        if len(changed) > 10:
            print(f"    ... and {len(changed) - 10} more")
    print(f"\nAfter re-analyzing, record it with: {entry} mark <path>")
    return 1                                       # stale areas dominate: rc already implied


def add_dated_note(root, note, day=None):
    """Write `**DAY — note.**` into audit/project_notes.md, above the newest dated
    entry (below any undated preface), so the note opens with the shared grammar and
    the chronology reads it. The day defaults to today (local)."""
    import datetime as _dt
    day = day or _dt.date.today().isoformat()
    entry = "**%s — %s.**" % (day, note.strip().rstrip("."))
    f = ai_path(root, "audit", PROJECT_NOTES)
    if not f.is_file():
        f.parent.mkdir(parents=True, exist_ok=True)
        f.write_text(entry + "\n", encoding="utf-8")
        return entry
    raw = f.read_bytes()
    crlf = b"\r\n" in raw
    lines = raw.decode("utf-8", errors="replace").replace("\r\n", "\n").split("\n")
    at = next((i for i in range(len(lines)) if _opener_at(lines, i)), None)
    if at is None:
        while lines and not lines[-1].strip():
            lines.pop()
        lines += ["", entry, ""] if lines else [entry, ""]
    else:
        lines[at:at] = [entry, ""]
    text = "\n".join(lines)
    f.write_bytes((text.replace("\n", "\r\n") if crlf else text).encode("utf-8"))
    return entry


def docs_root_rel(root):
    """The docs root (ai_docs/, mkt_docs/ ...) relative to the project root, or None.
    It is governance, not an analyzable area: `validate` checks it directly, so `stale`
    never counts its files and `mark` never records it."""
    try:
        return ai_path(root).resolve().relative_to(Path(root).resolve()).as_posix()
    except ValueError:
        return None


def _in_docs_root(rel, docs_rel):
    rel = rel.replace("\\", "/").rstrip("/")
    return bool(docs_rel) and (rel == docs_rel or rel.startswith(docs_rel + "/"))


def cmd_mark(root, paths, note=None):
    if not require_ai_docs(root, "mark"):
        return 1
    if note is not None and (not note.strip() or "**" in note or "\n" in note):
        print("[ERROR] --note must be one line of text without '**'. Nothing was written.")
        return 1
    f, lines, rows = parse_audit_plan(root)
    use_git_ref = git_available(root) and not any(
        git_has_changes(root, raw.replace("\\", "/").rstrip("/")) for raw in paths
    )
    ref = git_head(root) if use_git_ref else utc_now_iso()
    by_path = {r["path"].replace("\\", "/").rstrip("/"): r for r in rows}

    if not lines:
        lines = ["# Audit Plan", "",
                 "| Path | Status | Reference | Notes |",
                 "|---|---|---|---|"]
        rows = []

    def row_text(path, note):
        return f"| {path} | ANALYZED | {ref} | {note} |"

    # validate EVERY path before printing or mutating anything: a rejection
    # after an '[ok] ... added as ANALYZED' line is a lie the agent will act on
    keys = []
    for raw in paths:
        key = raw.replace("\\", "/").rstrip("/") or "."
        if confine_under(root, key) is None:
            print(f"[ERROR] {raw}: absolute, '..'-escaping, or outside the project root: "
                  "refusing to mark (use a project-relative path, '.' for the root). "
                  "Nothing was written.")
            return 1
        if _in_docs_root(key, docs_root_rel(root)):
            print(f"[note] {raw}: the docs root is not an area to mark -- `validate` checks it "
                  "directly. Skipped.")
            continue
        keys.append(key)

    appended = []
    for key in keys:
        display = key + ("/" if (root / key).is_dir() and key != "." else "")
        existing = by_path.get(key)
        if existing:
            lines[existing["line"]] = row_text(existing["path"], existing["note"])
            print(f"[ok] {existing['path']} -> ANALYZED ({ref})")
        else:
            appended.append(row_text(display, ""))
            print(f"[ok] {display} added as ANALYZED ({ref})")

    if appended:
        insert_at = (max(r["line"] for r in rows) + 1) if rows else len(lines)
        lines[insert_at:insert_at] = appended

    f.parent.mkdir(parents=True, exist_ok=True)
    f.write_text("\n".join(lines) + "\n", encoding="utf-8")
    if note is not None:
        print(f"[ok] dated entry added to audit/{PROJECT_NOTES}: {add_dated_note(root, note)}")
    elif not _open_units(root):
        # no open unit's Diary covers this work: a release, a fix after closure
        print(f"[note] no open unit records this work. If it is a release or a change worth "
              f"finding later, re-run with --note \"<what was done>\": mark writes the "
              f"dated entry in audit/{PROJECT_NOTES} for you.")
    if use_git_ref:
        # F-056: the reference is born here, so this is where the gestures that
        # orphan it are named. An amend was the observed one.
        print(f"[info] {ref} is the current HEAD. Commit this audit plan change as a new "
              "commit: amending, rebasing or squash-merging that commit orphans the "
              f"reference, and `{entry_script()} stale` fails once it no longer resolves. "
              "After a squash or rebase merge, re-mark on the integration branch.")
    return 0


# ------------------------------------------------- orientation-hook wiring
# F-041: read-only mirror of the installer-side detection in lib.js
# (findOrientHook + orientHookValidator). The JS owns WRITING hooks, with its
# injection guards; this side only DETECTS, at `check`, so a project whose
# sessions start unoriented hears about it in-project (ENFORCEMENT par.4: the
# hook is wired at init only -- pre-F-036 and agent-bootstrapped projects never
# got it, and a wired-but-dead hook is "the worst of the three states").
# The file list is a SUPERSET of the JS one: .codex/hooks.json is documented in
# ENFORCEMENT par.4 but never written by init. Pinned equal on both sides:
# the entry-point names, and (F-042) the user-settings path derivation --
# CLAUDE_CONFIG_DIR when set, else <home>/.claude -- empty-string env falsy
# on both sides.
ORIENT_HOOK_ENTRY_POINTS = ("sdlc_check.py", "mkt_check.py")
ORIENT_HOOK_CONFIG_FILES = (".claude/settings.json",
                            ".claude/settings.local.json",
                            ".codex/hooks.json")
ORIENT_HOOK_CONFIG_CAP = 1024 * 1024  # settings are tiny; cap pathological files
_ORIENT_HOOK_CMD_RE = re.compile(r" orient(\s|$)")
_ORIENT_HOOK_TOKEN_RE = re.compile(r'"([^"]*)"|(\S+)')

# Same fixed, versioned carrier as scripts/lib.js; only JSON data is decoded.
_CODEX_HOOK_WRAPPER = "import base64,json,subprocess,sys;d=json.loads(base64.b64decode(sys.argv[2]));subprocess.run([sys.executable,d['validator'],*d['argv']],input=sys.stdin.buffer.read())"


def _decode_hook_invocation(command):
    middle = ' -c "' + _CODEX_HOOK_WRAPPER + '" agentic-sdlc-hook-v1 '
    if not isinstance(command, str) or middle not in command:
        return None
    prefix, encoded = command.split(middle, 1)
    if not re.fullmatch(r'[\w.-]+|"[^"$`\r\n]+"', prefix):
        return None
    try:
        data = json.loads(base64.b64decode(encoded, validate=True))
        if (not isinstance(data, dict) or data.get("client") != "codex"
                or not isinstance(data.get("validator"), str)
                or not isinstance(data.get("argv"), list) or not data["argv"]
                or not all(isinstance(a, str) for a in data["argv"])
                or data["argv"][0] not in ("orient", "remind", "verdict", "constraints")):
            return None
        return data
    except (ValueError, TypeError):
        return None


def _orient_entries_in(p):
    """Yield the SessionStart commands invoking an orient entry point from ONE
    client config file. Fail-open: an unreadable, oversized, malformed or
    directory-shaped file contributes nothing. Reads are utf-8-sig -- a BOM'd
    settings.json (PowerShell/Notepad) must not read as unwired (declared
    divergence from Node's JSON.parse)."""
    try:
        if not p.is_file() or p.stat().st_size > ORIENT_HOOK_CONFIG_CAP:
            return
        if p.suffix == ".toml":
            import tomllib
            data = tomllib.loads(p.read_text(encoding="utf-8-sig"))
        else:
            data = json.loads(p.read_text(encoding="utf-8-sig"))
    except Exception:
        return
    if not isinstance(data, dict):
        return
    features = data.get("features")
    if p.name in ("hooks.json", "config.toml") and (
            isinstance(features, dict) and features.get("hooks") is False
            or data.get("allow_managed_hooks_only") is True):
        return
    hooks = data.get("hooks")
    groups = hooks.get("SessionStart") if isinstance(hooks, dict) else None
    if groups is None:
        groups = data.get("SessionStart")  # the .codex/hooks.json shape
    if not isinstance(groups, list):
        return
    for group in groups:
        if not isinstance(group, dict):
            continue
        codex = p.name in ("hooks.json", "config.toml")
        if codex and group.get("enabled") is False:
            continue
        inner = group.get("hooks")
        for h in inner if isinstance(inner, list) else [group]:
            if codex and (not isinstance(h, dict) or h.get("enabled") is False or h.get("type") != "command"):
                continue
            cmd = h.get("command") if isinstance(h, dict) else None
            if isinstance(h, dict) and p.name in ("hooks.json", "config.toml") and os.name == "nt":
                cmd = h.get("commandWindows") or h.get("command_windows") or cmd
            invocation = _decode_hook_invocation(cmd)
            if ((invocation and invocation["argv"][0] == "orient") or
                    (isinstance(cmd, str) and any(n in cmd for n in ORIENT_HOOK_ENTRY_POINTS)
                     and _ORIENT_HOOK_CMD_RE.search(cmd))):
                yield cmd


def _orient_user_settings_path():
    """The machine-global settings file (F-042 wires it at install time).

    Read at CALL time -- a DECLARED divergence from AGENTIC_SDLC_KB_ROOT's
    import-time read: unittest imports this module once before any test runs,
    so an import-time seam would be frozen before the matrix could set it.
    AGENTIC_SDLC_USER_SETTINGS is the test-isolation seam (python-side only);
    the production derivation mirrors lib.js: CLAUDE_CONFIG_DIR || ~/.claude."""
    seam = os.environ.get("AGENTIC_SDLC_USER_SETTINGS")
    if seam:
        return Path(seam)
    cfg = os.environ.get("CLAUDE_CONFIG_DIR")
    return (Path(cfg) if cfg else Path.home() / ".claude") / "settings.json"


def _codex_hook_config(root):
    """Observable Codex policy across sources; no trust or execution assertion."""
    home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
    disabled, unverified, disabled_entries = False, False, False
    for directory in (home, Path(root) / ".codex"):
        for name in ("hooks.json", "config.toml"):
            p = directory / name
            if not p.exists():
                continue
            try:
                if not p.is_file() or p.stat().st_size > ORIENT_HOOK_CONFIG_CAP:
                    raise ValueError("unreadable configuration")
                text = p.read_text(encoding="utf-8-sig")
                if p.suffix == ".toml":
                    import tomllib
                    data = tomllib.loads(text)
                else:
                    data = json.loads(text)
                if not isinstance(data, dict):
                    raise ValueError("unknown configuration shape")
                features = data.get("features", {})
                hooks = data.get("hooks", {})
                if not isinstance(features, dict) or not isinstance(hooks, dict):
                    raise ValueError("unknown policy or hooks shape")
                disabled |= features.get("hooks") is False or data.get("allow_managed_hooks_only") is True
                groups = hooks.get("SessionStart", data.get("SessionStart", []))
                if not isinstance(groups, list):
                    raise ValueError("unknown hook groups")
                for group in groups:
                    if not isinstance(group, dict):
                        raise ValueError("unknown hook group")
                    inner = group.get("hooks", [group])
                    if not isinstance(inner, list) or not all(isinstance(h, dict) for h in inner):
                        raise ValueError("unknown handlers")
                    disabled_entries |= group.get("enabled") is False or any(h.get("enabled") is False for h in inner)
            except Exception:
                unverified = True
    policy = "disabled-by-policy" if disabled else "unverified" if unverified else "enabled"
    return {"policy": policy, "disabled_entries": disabled_entries}


def _orient_hook_commands(root):
    """Yield (command, at_user_level, place) across every known client config:
    the three project-relative files, then the machine-global user settings --
    the file the installer wires (F-042), without which a fixed machine's
    projects would read as unwired forever. `place` is a display label, never a
    home path (F-075 prints it)."""
    codex_policy = _codex_hook_config(root)["policy"]
    for rel in ORIENT_HOOK_CONFIG_FILES:
        if rel.startswith(".codex/") and codex_policy != "enabled":
            continue
        for cmd in _orient_entries_in(Path(root) / rel):
            yield cmd, False, rel
    for cmd in _orient_entries_in(_orient_user_settings_path()):
        yield cmd, True, "user settings"
    if codex_policy != "enabled":
        return
    home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
    for name in ("hooks.json", "config.toml"):
        for cmd in _orient_entries_in(home / name):
            yield cmd, True, "codex user " + name
        for cmd in _orient_entries_in(Path(root) / ".codex" / name) if name == "config.toml" else ():
            yield cmd, False, ".codex/" + name


def _orient_entry_live(root, cmd, at_user_level):
    """True unless the entry names a validator that does not resolve.

    A matching entry whose tokens name no validator is "cannot tell" and counts
    as live (the lib.js contract: never report broken on cannot-tell). Relative
    tokens resolve against the project root (the vendored-validator
    convention); a USER-level relative token has no cwd to resolve against and
    is treated as cannot-tell."""
    invocation = _decode_hook_invocation(cmd)
    token = invocation["validator"] if invocation else None
    for m in _ORIENT_HOOK_TOKEN_RE.finditer(cmd):
        tok = m.group(1) if m.group(1) is not None else m.group(2)
        if any(tok.endswith(n) for n in ORIENT_HOOK_ENTRY_POINTS):
            token = tok
            break
    if token is None:
        return True
    tp = Path(token)
    if not tp.is_absolute():
        if at_user_level:
            return True
        tp = Path(root) / tp
    return tp.exists()


def orient_wiring(root):
    """{client: {command: place}} for the LIVE orient entries, per client.

    Per client because two clients never read each other's settings: a Codex
    entry beside a Claude Code one is two clients oriented once each, not one
    session oriented twice. Identical command strings count once. A dead entry
    delivers no copy and is left out (F-075 FS3)."""
    out = {}
    for cmd, at_user_level, place in _orient_hook_commands(root):
        if not _orient_entry_live(root, cmd, at_user_level):
            continue
        client = "codex" if place.startswith((".codex", "codex ")) else "claude"
        out.setdefault(client, {}).setdefault(cmd.strip(), place)
    return out


def orient_hook_state(root):
    """'wired' | 'dead' | 'unwired'.

    A matching entry whose tokens name no validator is "cannot tell" and counts
    as wired (the lib.js contract: never report broken on cannot-tell). 'dead'
    requires every matching entry to name a validator that does not resolve:
    the client runs ALL SessionStart hooks -- project-level AND user-level
    merge -- so one live entry at either level still orients the session
    (any-resolves aggregation across levels). Relative tokens resolve against
    the project root (the vendored-validator convention); a USER-level relative
    token has no cwd to resolve against and is treated as cannot-tell."""
    matched = False
    for cmd, at_user_level, _place in _orient_hook_commands(root):
        matched = True
        if _orient_entry_live(root, cmd, at_user_level):
            return "wired"
    return "dead" if matched else "unwired"


def print_orient_hook_note(root):
    """Print the FS-A wiring note (unwired / dead), or nothing when wired.

    Informational only, by contract: never an exit code, never a validate
    warning (--strict CI must not fail on a hook that legitimately lives in
    git-ignored settings.local.json). Called by the spine's cmd_check AND by
    an overlay that replaces check with its own pipeline (the marketing lens
    does): the note is check-layer behaviour, whoever owns the check."""
    try:
        state = orient_hook_state(root)
        codex = _codex_hook_config(root)
        if codex["policy"] != "enabled" or codex["disabled_entries"]:
            detail = codex["policy"] if codex["policy"] != "enabled" else "disabled definitions present"
            print(f"[note] Codex hook configuration: {detail}. Disabled or unverified "
                  "definitions are excluded from wiring counts; trust and native delivery are not verified.")
            if state == "unwired":
                return
        if state == "unwired":
            print("[note] agent sessions start without automatic orientation on this "
                  "machine (no session-orientation hook found at project or user level). "
                  "Fix once: update or reinstall the skill npm package (on Claude Code "
                  "with Python it wires the hook machine-wide), or wire it per "
                  "ENFORCEMENT.md par.4")
        elif state == "dead":
            print("[note] a session-orientation hook is configured but points at a "
                  "validator that no longer exists, so sessions start unoriented. Fix: "
                  "update or reinstall the skill npm package, or correct the command. "
                  "Details: ENFORCEMENT.md par.4")
    except Exception:
        pass  # detection must never break check


def cmd_check(root, strict=False, hybrid=False, extra_validate=None, extra_sections=()):
    """An overlay adds its checks through the two hooks, never after the call:
    the summary line is the verdict, so every check that can fail runs before
    it. `extra_validate()` folds into the validate stage; each
    (title, fn) in `extra_sections` gets its own banner and summary rc."""
    print("===== validate =====")
    rc_v = cmd_validate(root, strict=strict, hybrid=hybrid)
    if extra_validate is not None:
        rc_v = max(rc_v, extra_validate())
    # A3 (F-073): check only -- it reads git refs, and validate stays file-local.
    # Advisory: printed, never part of any rc.
    for a in id_advisories(root):
        print(f"[note]  {a}")
    print("\n===== stale =====")
    rc_s = cmd_stale(root, hybrid=hybrid)
    rcs = [("validate", rc_v), ("stale", rc_s)]
    for title, fn in extra_sections:
        print(f"\n===== {title} =====")
        rcs.append((title, fn()))
    failed = any(rc for _, rc in rcs)
    print(f"\ncheck: {'NOT CLEAN' if failed else 'CLEAN'} "
          f"({', '.join(f'{title} rc={rc}' for title, rc in rcs)})")
    print_check_notes(root)
    return 1 if failed else 0


def _attr_pattern(path):
    """A .gitattributes pattern matching exactly `path`. Order matters (probed):
    a backslash, glob characters and a leading `#` or `!` (comment, negation)
    are escaped first, then the result is C-quoted when it holds whitespace,
    `"` or a backslash."""
    p = re.sub(r"([\\\[*?])", r"\\\1", path)
    if p.startswith(("#", "!")):
        p = "\\" + p
    if re.search(r'[\s"\\]', p):
        p = '"' + p.replace("\\", "\\\\").replace('"', '\\"') + '"'
    return p


def review_log_union_note(root):
    """F-090: the note for a review log git would not merge with union, or None.

    Git itself is asked (`check-attr`), so patterns and nested files count;
    personal and system attribute files do not, so the answer is the one a
    teammate's clone gets. Only `unspecified` is a gap: `union` or any other
    driver is a choice. Residual: `.git/info/attributes` is still read. Any
    failure -- no git, not a work tree, timeout -- is no note: `check` never
    breaks on it."""
    try:
        log = ai_path(root, "audit", "reviews", "REVIEW_LOG.md")
        if not log.is_file():
            return None
        prefix = _git_out(root, "rev-parse", "--show-prefix", timeout=3)
        if prefix is None:
            return None
        rel = log.resolve().relative_to(Path(root).resolve()).as_posix()
        out = _git_out(root, "-c", "core.attributesFile=", "check-attr", "-z", "merge",
                       "--", rel, timeout=3, env={"GIT_ATTR_NOSYSTEM": "1"})
        if out is None:
            return None
        fields = out.split("\0")
        if len(fields) < 3 or fields[2] != "unspecified":
            return None
        path = prefix.rstrip("\r\n") + rel  # a folder may begin with a space
        return (f"[note] {path} has no merge attribute: two branches that both add review "
                "rows conflict when merged. Fix: add this line to .gitattributes at the "
                f"repository root: {_attr_pattern(path)} merge=union")
    except Exception:
        return None


def print_check_notes(root):
    """Every check-layer note, informational and never an exit code. The one
    place an overlay that replaces `check` calls, so a new note cannot miss it."""
    print_orient_hook_note(root)
    note = review_log_union_note(root)
    if note:
        print(note)


# --------------------------------------------------------------------- gate

# --- UserPromptSubmit reminder hook (F-046) --------------------------------
# `orient` fires once per session and decays; a session that never invokes the
# skill never had the protocol at all. Measured 2026-09-06: a release ran in
# this repo against a `GUIDE_release.md` the session never consulted, because
# SKILL.md -- where the duty is written -- had not been read.
#
# The carrier is kb's (F-041 item B), lifted here so all three lenses share one
# machine instead of two that do the same thing. Its contract is kept: the line
# is CONSTANT and reads NOTHING repo- or session-controlled (F-093 / r44: it does
# read which family lenses the machine has installed, names only) -- nothing
# repo- or session-controlled may ride
# text injected every turn, and zero reads is what keeps the per-turn cost flat.
# What changed is the payload's first duty and the wiring. First duty: decide
# whether the skill governs this work and, if it does, read it once -- an
# unread protocol cannot be applied, which is the failure above. Wiring: a
# default instead of opt-in, on the owner's explicit acceptance of the per-turn
# cost (`vision/rulings.md` r19; the "no ceremony ratchet" Non-Goal admits a
# never-zero cost by that acceptance, and a trivial turn pays a yes/no
# judgement, never a load).

REMIND_FALLBACK = (
    "decide whether the {skill} skill governs this work; if it does, load it "
    "once before acting -- an unread protocol cannot be applied."
)


# F-075: constant, for every lens -- with sibling lenses installed nothing per
# turn said to choose the lens. r19's bound rose to 600 for it (r32, owner).
REMIND_LENS_SUFFIX = (" Above L1, with sibling lenses installed: choose the lens with "
                      "routing.md and declare it.")

# F-093: the family wires ONE shared reminder, the first installer's, so its
# own text led a knowledge task to the code lens. With siblings installed the
# suffix names every installed lens and its domain. The owner accepted the cost
# (REQUEST_family_hook_wiring.md R3, rulings r19/r32 amended): the skills
# directories are read each turn, names only, filtered by routing.md's table.
REMIND_LENS_NAMED = (" Installed lenses: {lenses}. Above L1, choose the one that "
                     "governs this work with routing.md, load it and declare it.")


def remind_lens_suffix():
    """The lens-choice suffix: the constant one on a single-lens install, the
    named one when a sibling lens is installed. Never raises."""
    try:
        siblings = installed_sibling_lenses()
        if not siblings:
            return REMIND_LENS_SUFFIX
        family = lens_table()
        names = sorted(set(siblings) | {profile()["skill_name"]})
        return REMIND_LENS_NAMED.format(lenses=", ".join(
            f"{n} ({family[n]})" if n in family else n for n in names))
    except Exception:
        return REMIND_LENS_SUFFIX


def cmd_remind(args):
    """UserPromptSubmit hook: print the lens's per-turn line. Always 0.

    argv is ignored whole and nothing repo- or session-controlled is read: a
    hook surface must not fail, and a flag typo must not cost a turn's context.
    The one input is which family lenses this machine has installed (F-093)."""
    try:
        prof = profile()
        line = prof.get("remind_line") or REMIND_FALLBACK.format(skill=prof["skill_name"])
        print(f"{prof['skill_name']}: {line}{remind_lens_suffix()}")
    except Exception:
        pass
    return 0

def read_hook_payload():
    """The hook event JSON on stdin as a dict, or None when it cannot be read.

    bytes -> utf-8-sig: the payload is UTF-8 JSON regardless of the console code
    page; '-sig' strips the BOM (PowerShell pipes)."""
    try:
        raw = sys.stdin.buffer.read().decode("utf-8-sig", errors="replace")
        payload = json.loads(raw)
    except Exception:
        return None
    return payload if isinstance(payload, dict) else None


def hook_project(target, root=None, docs_name=None):
    """The project root an edit hook judges, with its docs root name set, or None
    when two docs roots sit side by side. The hook runs in the session's current
    directory, which a `cd` moves (live probe 2026-10-27): the project AND its docs
    root name are the ones holding the edited file, never the ones around the
    working directory. An explicit root (--root) is kept as given."""
    start = Path(root) if root is not None else Path(target).resolve().parent
    try:
        found_root, name = resolve_docs_dir(argparse.Namespace(docs_dir=docs_name), start)
    except AmbiguousDocsRoot:
        return None
    set_docs_dir(name)
    if root is not None:
        return Path(root)
    if found_root is not None:
        return found_root
    found_root = find_project_root(start)  # an explicit name: discovery did not run
    # No docs root above the edited file: the session's own project, as before the
    # hook resolved from the file -- the file's folder would unprotect a gated path.
    return found_root if ai_path(found_root).is_dir() else find_project_root()


def cmd_gate(args):
    file_path = args.file or ""
    if args.hook:
        payload = read_hook_payload()
        try:
            file_path = (payload.get("tool_input") or {}).get("file_path") or ""
        except AttributeError:
            return 0  # unparseable input: do not block
    if not isinstance(file_path, str) or not file_path:
        return 0
    root = hook_project(file_path, Path(args.root).resolve() if args.root else None,
                        getattr(args, "docs_dir", None))
    if root is None:
        return 0  # two docs roots side by side: cannot tell which governs
    try:
        rel = str(Path(file_path).resolve().relative_to(root)).replace("\\", "/")
    except ValueError:
        return 0  # outside the project: not this gate's concern
    if rel.startswith((docs_dir() + "/", "tests/", "test/")):
        return 0
    protected = [p.strip().replace("\\", "/").rstrip("/")
                 for p in (args.protected or "").split(";") if p.strip()]
    if not protected:
        return 0
    if not any(rel == p or rel.startswith(p + "/") for p in protected):
        return 0
    for _, meta, _ in list_analyses(root):
        if meta.get("status") == "IN_PROGRESS":
            return 0
    if args.hybrid and has_etdd_shadow(root):
        return 0  # Hybrid design gate: an approved E-TDD shadow authorizes the change
    if args.hybrid:
        sys.stderr.write(
            f"[sdlc gate] '{rel}' is on a protected path but no E-TDD shadow "
            "(solutions/SHADOW_*tdd*.md) exists and no ANALYSIS_*.md is IN_PROGRESS. "
            "In Hybrid mode, export the approved E-TDD shadow from devPNT before implementing.\n")
        return 2
    sys.stderr.write(
        f"[sdlc gate] '{rel}' is on a protected path but no ANALYSIS_*.md is IN_PROGRESS. "
        "If your analysis already exists, set its frontmatter to 'status: IN_PROGRESS' "
        "(that flip is what opens the gate; at L3, only after the owner's design approval, "
        "review.md); otherwise write it first (Phase 3).\n")
    return 2


# ------------------------------------------------------------------ verdict
# F-076: Rule Zero's router verdict, checked at the edit. A field agent edited
# without declaring one and said nothing stopped it. This reads the session
# transcript the client hands every hook and refuses the edit (JSON deny, exit
# 0) only on certainty; whatever it cannot tell resolves to silence. It never
# prints `allow` -- that would skip the user's permission prompt. Owner: block
# (REQUEST_guide_verdict_check.md R3), wired by default (R4, rulings.md r34).
#
# F-094: a named guide counts as read only when the session read EVERY line of
# it. Before, the guide's name anywhere in a non-edit tool's input was a read, so
# `Read offset=1 limit=130` of a 225-line guide, `head -30` or a Grep on it all
# passed (field scan: 157 partial Reads of guides against 118 whole ones), and
# the agent applied the part it had seen. A read is now a line span: a Read call
# (offset is the 1-based first line, probed 2026-11-12; no limit = the client's
# READ_DEFAULT_LIMIT), a literal shell `cat`/`Get-Content` (whole, or its
# -TotalCount), a get_file_content (whole). Grep, head, sed, an Agent prompt
# naming the guide: no span. The guide is read when the spans cover 1..its last
# line. Owner: REQUEST_whole_guide_read.md R1.

VERDICT_EDIT_TOOLS = ("Edit", "Write", "MultiEdit", "NotebookEdit")
READ_DEFAULT_LIMIT = 2000   # Claude Code's Read without `limit` stops at line 2000
GUIDE_COUNT_MAX = 8 * 1024 * 1024  # a larger guide: cannot afford to count its lines
VERDICT_MAX_BYTES = 256 * 1024 * 1024  # a larger transcript: cannot afford to tell
VERDICT_LINE_MAX = 1024 * 1024         # assistant lines are small; skip the rest unparsed
# Markdown emphasis between the word and the colon ("**router**: no match") and
# "Router verdict:" are the same declaration.
_VERDICT_ROUTER_RE = re.compile(r"router(?:[\s*_`]+verdict)?[\s*_`]*:(.*)", re.IGNORECASE)
# A declaration line may open with markdown: emphasis, quote, heading, bullet or a
# numbered item ("## Level: L1", "1. Level: L1", "• router: no match").
_LINE_OPEN = r"^[ \t>*_`#+•-]*(?:\d+[.)][ \t*_`]*)?"
_LEVEL_WORD = r"(?:level|livello|niveau|nivel|stufe)\b[ \t*_`:·—–-]*(?:è[ \t]+)?"
# ...and only on a line that opens with `router` or with a level (`L2`, `Spike`): a
# verdict quoted inside a sentence is not one.
_VERDICT_LINE_RE = re.compile(
    _LINE_OPEN + r"(?:router\b|" + _LEVEL_WORD + r"(?:(?:research[ \t]+)?spike|[A-Z][123])\b)", re.IGNORECASE)
_VERDICT_NONE_RE = re.compile(r"[\s`*_\"'(]*(no match|absent)", re.IGNORECASE)
# A level is DECLARED by a line that opens with the level word, in the form Rule
# Zero prescribes -- level 1 alone, 2/3 with `router` on the same line -- so a level
# quoted inside a sentence is not one. The letter is the lens's own (`L1`, `E1`):
# groups are (letter, "1" or "", "2"/"3" or "").
_DECLARATION_RE = re.compile(
    _LINE_OPEN + _LEVEL_WORD +
    r"([A-Z])(?:(1)\b|([23])\b(?=[^\n]*\brouter\b))", re.IGNORECASE | re.MULTILINE)
_GUIDE_NAME_RE = re.compile(r"GUIDE_[A-Za-z0-9_-]+\.md")


def _hint_path(value, cwd):
    if not isinstance(value, str) or not value:
        return None
    p = Path(value)
    if not p.is_absolute():
        if not cwd or not Path(cwd).is_absolute():
            return None
        p = Path(cwd) / p
    return str(p.resolve())


def hook_edits(payload):
    """Parse the complete native apply_patch syntax without executing it.

    Unknown or incomplete input yields no partial target set. Move checks both
    the old and new paths; file membership is evaluated by the existing gate.
    """
    command = (payload.get("tool_input") or {}).get("command")
    if not isinstance(command, str) or len(command.encode("utf-8")) > VERDICT_LINE_MAX:
        return None
    lines = command.strip().splitlines()
    if not lines or lines[0] != "*** Begin Patch" or lines[-1] != "*** End Patch":
        return None
    edits, current, mode, changed = [], None, None, False
    for line in lines[1:-1]:
        match = re.fullmatch(r"\*\*\* (Add|Update|Delete) File: (.+)", line)
        if match:
            if current is not None and mode != "Delete" and not changed:
                return None
            mode, value = match.groups()
            target = _hint_path(value, payload.get("cwd"))
            if not target:
                return None
            current = {"path": target, "new_text": ""}
            edits.append(current)
            changed = False
        elif line.startswith("*** Move to: ") and current is not None and mode == "Update" and not changed:
            target = _hint_path(line[len("*** Move to: "):], payload.get("cwd"))
            if not target:
                return None
            current = {"path": target, "new_text": ""}
            edits.append(current)
        elif current is not None and mode != "Delete" and (
                line.startswith(("+", "-", " ", "@@")) or line == "*** End of File"):
            if mode == "Add" and not line.startswith("+"):
                return None
            if line.startswith(("+", "-")):
                changed = True
            if line.startswith("+"):
                current["new_text"] += line[1:] + "\n"
        else:
            return None
    if current is not None and mode != "Delete" and not changed:
        return None
    return edits or None


def shell_read_paths(command, cwd, workdir=None):
    """Literal Get-Content/cat reads only: no shell expansion or execution."""
    found = shell_read(command, cwd, workdir)
    return found[0] if found else None


def shell_read(command, cwd, workdir=None):
    """(paths, line count or None) of a literal Get-Content/cat read, else None.
    The count is Get-Content's -TotalCount (F-094): those lines only, not the file."""
    if not isinstance(command, str) or re.search(r"[$`\r\n;|&<>\x00]", command):
        return None
    token_re = re.compile(r"\s*(?:'([^']*)'|\"([^\"]*)\"|([^\s'\"]+))")
    tokens, pos = [], 0
    while pos < len(command.rstrip()):
        match = token_re.match(command, pos)
        if not match:
            return None
        token = next(x for x in match.groups() if x is not None)
        tokens.append(token)
        pos = match.end()
    if not tokens or tokens[0].lower() not in ("get-content", "cat"):
        return None
    paths, i, count = [], 1, None
    while i < len(tokens):
        token = tokens[i]
        if tokens[0].lower() == "get-content" and token.lower() in ("-literalpath", "-path", "-raw"):
            if token.lower() != "-raw" and i + 1 == len(tokens):
                return None
        elif tokens[0].lower() == "get-content" and token.lower() == "-totalcount":
            i += 1
            if i == len(tokens) or not tokens[i].isdigit():
                return None
            count = int(tokens[i])
        elif tokens[0] == "cat" and token == "--":
            pass
        elif token.startswith("-") or re.search(r"[*?\[\],]", token):
            return None
        else:
            base = _hint_path(workdir, cwd) if workdir else cwd
            resolved = _hint_path(token, base)
            if not resolved:
                return None
            paths.append(resolved)
        i += 1
    return (paths, count) if paths else None


def _codex_literal_calls(code):
    """Recognize a small non-executable JS carrier grammar, otherwise nothing."""
    if not isinstance(code, str):
        return []
    calls, pos = [], 0
    pattern = re.compile(r"\s*(?:text\(\s*)?await\s+tools\.exec_command\((\{.*?\})\)\s*\)?\s*;?", re.DOTALL)
    field = re.compile(r'\s*(?:"(cmd|workdir)"|(cmd|workdir))\s*:\s*("(?:[^"\\]|\\.)*")\s*(,|$)')
    while pos < len(code.rstrip()):
        match = pattern.match(code, pos)
        if not match:
            return []
        obj, off, args = match[1][1:-1], 0, {}
        while off < len(obj.rstrip()):
            item = field.match(obj, off)
            if not item or (item[1] or item[2]) in args:
                return []
            try:
                args[item[1] or item[2]] = json.loads(item[3])
            except ValueError:
                return []
            off = item.end()
        if "cmd" not in args:
            return []
        calls.append(args)
        pos = match.end()
    return calls


def transcript_events(path):
    """Yield legacy assistant blocks, plus normalized recognized Codex blocks.

    This is read-only and bounded by the existing transcript limits. Historical
    cwd is taken from host metadata, never guessed from the present process.
    """
    cwd = None
    with Path(path).open("rb") as fh:
        for raw in fh:
            if len(raw) > VERDICT_LINE_MAX:
                continue
            try:
                entry = json.loads(raw.decode("utf-8", errors="replace"))
            except ValueError:
                continue
            if not isinstance(entry, dict):
                continue
            if entry.get("type") == "assistant":
                yield entry
                continue
            data = entry.get("payload")
            if not isinstance(data, dict):
                continue
            if entry.get("type") in ("session_meta", "turn_context"):
                if isinstance(data.get("cwd"), str):
                    cwd = data["cwd"]
                continue
            if entry.get("type") != "response_item":
                continue
            blocks = []
            if data.get("type") == "message" and data.get("role") == "assistant":
                blocks = [{"type": "text", "text": x.get("text", "")}
                          for x in (data.get("content") if isinstance(data.get("content"), list) else []) if isinstance(x, dict) and x.get("type") == "output_text"]
            elif data.get("type") in ("function_call", "custom_tool_call"):
                name = data.get("name")
                calls = []
                if name in ("exec_command", "Bash"):
                    try:
                        args = json.loads(data.get("arguments", "{}"))
                    except (ValueError, TypeError):
                        args = None
                    if isinstance(args, dict):
                        calls = [args]
                elif name == "exec":
                    calls = _codex_literal_calls(data.get("input"))
                elif name == "apply_patch":
                    command = data.get("input")
                    if command is None:
                        try:
                            command = json.loads(data.get("arguments", "{}" )).get("command")
                        except (ValueError, TypeError, AttributeError):
                            pass
                    for edit in hook_edits({"tool_input": {"command": command}, "cwd": cwd}) or []:
                        blocks.append({"type": "tool_use", "name": "Write", "input": {"file_path": edit["path"]}})
                for args in calls:
                    found = shell_read(args.get("cmd", args.get("command")), cwd, args.get("workdir"))
                    for target in (found[0] if found else []):
                        # F-094: the shell read is whole (no limit) unless -TotalCount
                        inp = {"file_path": target}
                        inp.update({"limit": found[1]} if found[1] is not None else {"whole": True})
                        blocks.append({"type": "tool_use", "name": "Read", "input": inp})
            if blocks:
                yield {"type": "assistant", "isSidechain": bool(entry.get("agent_id") or data.get("agent_id")),
                       "message": {"content": blocks}}


def transcript_facts(path):
    """What the session transcript shows about the verdict duty, or None when it
    cannot be read within the bounds.

    Returns {"assistant": entries parsed, "sidechain": a subagent's own transcript
    (Claude Code marks every entry of one `isSidechain`), "declared": a router verdict seen,
    "trivial": a level-1 declaration seen (`Level: L1`, `E1`), "named": guides the verdicts name,
    "read": guide name -> the line spans the session read of it (F-094, _read_spans)}."""
    facts = {"assistant": 0, "sidechain": False, "declared": False, "trivial": False,
             "named": set(), "read": {}}
    try:
        p = Path(path)
        if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
            return None
        for entry in transcript_events(p):
                if not isinstance(entry, dict) or entry.get("type") != "assistant":
                    continue
                content = (entry.get("message") or {}).get("content")
                if not isinstance(content, list):
                    continue
                facts["assistant"] += 1
                if entry.get("isSidechain") is True:
                    facts["sidechain"] = True
                for block in content:
                    if not isinstance(block, dict):
                        continue
                    if block.get("type") == "text":
                        for line in str(block.get("text") or "").splitlines():
                            d = _DECLARATION_RE.match(line)
                            if d and d.group(2):
                                facts["trivial"] = True
                            m = _VERDICT_ROUTER_RE.search(line)
                            if m and (d or _VERDICT_LINE_RE.match(line)):
                                facts["declared"] = True
                                if not _VERDICT_NONE_RE.match(m.group(1)):
                                    facts["named"].update(_GUIDE_NAME_RE.findall(m.group(1)))
                    elif block.get("type") == "tool_use":
                        base = entry.get("cwd") if isinstance(entry.get("cwd"), str) else None
                        for name, span in _read_spans(block, base or str(p.parent)):
                            facts["read"].setdefault(name, []).append(span)
    except (OSError, ValueError, TypeError, AttributeError):
        return None
    return facts


def _read_spans(block, cwd):
    """(guide name, (first line, last line or None = end of file)) for each guide
    this tool call read (F-094). Only reads that return the file's lines count; a
    search, an excerpt command or a prompt naming the guide reads nothing. `cwd`
    only anchors a relative shell path: the guide is matched by its name."""
    name, inp = block.get("name"), block.get("input")
    if not isinstance(inp, dict):
        return []
    if name == "Read" and isinstance(inp.get("file_path"), str):
        if inp.get("whole") is True:
            span = (1, None)
        else:
            offset, limit = inp.get("offset"), inp.get("limit")
            for v in (offset, limit):  # present but not a plain int: cannot tell, no credit
                if v is not None and (not isinstance(v, int) or isinstance(v, bool)):
                    return []
            if limit is not None and limit <= 0:
                return []
            first = offset if offset is not None and offset > 1 else 1
            count = limit if limit is not None else READ_DEFAULT_LIMIT
            span = (first, first + count - 1)
        return [(g, span) for g in _GUIDE_NAME_RE.findall(Path(inp["file_path"]).name)]
    if name in ("Bash", "PowerShell"):
        found = shell_read(inp.get("command"), cwd)
        if not found:
            return []
        span = (1, found[1]) if found[1] is not None else (1, None)
        return [(g, span) for path in found[0] for g in _GUIDE_NAME_RE.findall(Path(path).name)]
    if isinstance(name, str) and name.endswith("get_file_content"):
        paths = inp.get("paths") if isinstance(inp.get("paths"), list) else []
        return [(g, (1, None)) for path in paths if isinstance(path, str)
                for g in _GUIDE_NAME_RE.findall(Path(path).name)]
    return []


def _guide_lines(path):
    """The guide's line count, or None when it cannot be counted within the bounds."""
    try:
        if path.stat().st_size > GUIDE_COUNT_MAX:
            return None
        text = path.read_bytes()
    except OSError:
        return None
    return text.count(b"\n") + (0 if not text or text.endswith(b"\n") else 1)


def _read_whole(spans, lines):
    """True when the spans cover lines 1..lines. Unknown size: any read counts."""
    if not spans:
        return False
    if lines is None:
        return True
    reached = 0
    for first, last in sorted(spans, key=lambda s: s[0]):
        if first > reached + 1:
            break
        reached = max(reached, lines if last is None else last)
    return reached >= lines


def verdict_reason(payload, root=None, docs_name=None):
    """The refusal line for this edit event, or None when the edit may proceed.
    Without a root, the project is the one holding the edited file (hook_project)."""
    if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
        for edit in hook_edits(payload) or []:
            reason = verdict_reason({**payload, "tool_name": "Edit", "tool_input": {
                "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
            if reason:
                return reason
        return None
    if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
        return None
    tool_input = payload.get("tool_input") or {}
    target = tool_input.get("file_path") or tool_input.get("notebook_path")
    transcript = payload.get("transcript_path")
    if not isinstance(target, str) or not target or not transcript:
        return None
    root = hook_project(target, root, docs_name)
    if root is None:
        return None  # two docs roots side by side: cannot tell which governs
    try:
        Path(target).resolve().relative_to(root)
    except (ValueError, OSError):
        return None  # outside the project: not this check's concern
    ref = ai_path(root, "reference")
    if not ref.is_dir():
        return None
    guides = {g.name for g in ref.glob("GUIDE_*.md") if g.is_file()}
    if not guides:
        return None
    facts = transcript_facts(transcript)
    if not facts or not facts["assistant"]:
        return None  # unreadable, oversized or an unknown format: cannot tell
    if facts["sidechain"]:
        return None  # a subagent works under its orchestrator's verdict
    if not (facts["declared"] or facts["trivial"]):
        return ("[sdlc verdict] No guide-router verdict in this session; this project has "
                f"guides ({docs_dir()}/reference/INDEX.md). Declare it with the level, e.g. "
                "\"Level: L2 · router: no match\" or \"router: GUIDE_x.md -> read\" "
                "(L1: \"Level: L1\"), then retry.")
    unread = sorted(g for g in facts["named"] & guides
                    if not _read_whole(facts["read"].get(g), _guide_lines(ref / g)))
    if unread:
        return (f"[sdlc verdict] The router verdict names {', '.join(unread)}, not read "
                "whole in this session. Read every line (no offset or limit; past the read "
                "cap, in chunks to the end), then retry.")
    return None


def cmd_verdict(args):
    """PreToolUse hook: print a JSON refusal or nothing. Always 0 -- exit 2 would
    block blind, and the wired command adds `; exit 0` for validators that cannot
    run this at all (missing, or older than it)."""
    if not args.hook:
        return 0
    try:
        payload = read_hook_payload()
        if payload is None:
            return 0
        root = Path(args.root).resolve() if args.root else None
        reason = verdict_reason(payload, root, getattr(args, "docs_dir", None))
        if reason:
            print(json.dumps({"hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": reason}}, ensure_ascii=False))
    except Exception:
        pass
    return 0


# -------------------------------------------------------------- constraints
# F-085: the constraint reader. It reads what an ANALYSIS already states in
# extractable form -- id'd use cases, spec items and threats, and the rows of
# the `### Preservation constraints` table -- and binds each to the files it
# names. It names no feature and computes nothing: no count, rank or marker
# reaches the output, and every view ends with CONSTRAINTS_SENTENCE naming what
# it could not extract, so a short view never reads as a complete one.

CONSTRAINT_SECTIONS = (("## Use Cases",), ("## Functional Spec",), SECURITY_SECTION)
INTERFACE_SECTION = ("## Interface Contract",)
IMPACT_SECTION = ANALYSIS_SECTIONS[2]
PRESERVATION_HEADING = "### Preservation constraints"
NO_SYMBOL_LINE = "No existing symbol changed."
CONSTRAINTS_SENTENCE = ("This view shows only the constraints written in extractable "
                        "form and never replaces the ANALYSIS")
CONSTRAINT_LINE_MAX = 300

_ITEM_RE = re.compile(r"^\s*([-*+]\s+|#{3,4}\s+|\|\s*)(?:\*\*|__)?(?:UC|FS|T)\d+\b")
_P_ROW_RE = re.compile(r"^\|\s*(?:\*\*)?(P\d+)\b")
_ITEM_ID_RE = re.compile(r"(UC|FS|T)\d+")
_CITE_RE = re.compile(r"\b(UC|FS|T)(\d+)(?:\s*[–-]\s*(?:UC|FS|T)?(\d+))?\b")
_BACKTICK_RE = re.compile(r"`([^`\n]+)`")
_PATH_TOKEN_RE = re.compile(r"^[A-Za-z0-9_.\-/]+(?:::[A-Za-z0-9_.]+)?$")
_PATH_EXT_RE = re.compile(r"[^./]\.[A-Za-z0-9]+$")
_SENTENCE_END_RE = re.compile(r"[.!?](?=\s|$)")
_CELL_SPLIT_RE = re.compile(r"(?<!\\)\|")
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]")


def _norm_rel(path):
    """Repository-relative, forward slashes, case-folded where the filesystem is."""
    p = path.replace("\\", "/")
    while p.startswith("./"):
        p = p[2:]
    return p.casefold() if os.name == "nt" else p


def _path_tokens(text, need_slash):
    """The backticked file paths in `text`; `path::symbol` yields its path. An elided
    (`...`), globbed, placeholder or parent-relative path binds nothing; in prose
    (`need_slash`) a bare file name is a mention, not a binding."""
    out = set()
    for token in _BACKTICK_RE.findall(text or ""):
        t = token.strip()
        if "..." in t or "*" in t or t.startswith("/") or not _PATH_TOKEN_RE.match(t):
            continue
        path = t.split("::", 1)[0]
        while path.startswith("./"):
            path = path[2:]
        if ".." in path.split("/") or not _PATH_EXT_RE.search(path):
            continue
        if need_slash and "/" not in path:
            continue
        out.add(_norm_rel(path))
    return out


def _first_sentence(text):
    """Up to the first sentence end outside a backticked span (so `a.py` never ends
    one); a bold title such as `**FS1 Ids.**` ends nothing either."""
    masked = _BACKTICK_RE.sub(lambda m: "`" + "x" * len(m.group(1)) + "`", text)
    m = _SENTENCE_END_RE.search(masked)
    return text[:m.end()] if m else text


def _cells(row):
    return [c.strip() for c in _CELL_SPLIT_RE.split(row.strip().strip("|"))]


def _cited_ids(text):
    """Ids cited in `text`, a range such as `FS3–FS7` expanded."""
    out = set()
    for prefix, start, end in _CITE_RE.findall(text or ""):
        a = int(start)
        b = int(end) if end else a
        if b < a or b - a > 50:
            b = a
        out.update(f"{prefix}{n}" for n in range(a, b + 1))
    return out


def parse_constraints(text):
    """Every constraint `text` states in extractable form, in document order: a dict
    with `id`, `kind` (`item` or `P`), `section` (its `## ` heading), `line`
    (1-based), `statement`, `bindings` (normalized paths), `evidence` and
    `released` (a P row's release reference, or None)."""
    lines = (text or "").splitlines()
    items, impact_rows = [], []
    section, extracted, impact, preservation = None, False, False, False
    for n, line in enumerate(lines):
        if line.startswith("## "):
            section = line.strip()
            extracted = any(line.startswith(a) for s in CONSTRAINT_SECTIONS for a in s)
            impact = any(line.startswith(a) for a in IMPACT_SECTION)
            preservation = False
            continue
        if impact:
            if line.startswith("### "):
                preservation = line.strip().lower() == PRESERVATION_HEADING.lower()
                continue
            if not line.lstrip().startswith("|"):
                continue
            cells = _cells(line)
            if preservation:
                m = _P_ROW_RE.match(line.strip())
                if m and len(cells) >= 5:
                    must = cells[3]
                    released = None
                    if must.startswith("RELEASED (") and ")" in must:
                        released = must[len("RELEASED ("):must.index(")")]
                    items.append({"id": m.group(1), "kind": "P", "section": section,
                                  "line": n + 1, "statement": must,
                                  "bindings": _path_tokens(cells[1], False),
                                  "evidence": cells[4], "released": released})
            elif cells:
                paths = _path_tokens(cells[0], False)
                if paths:
                    impact_rows.append((paths, _cited_ids(" | ".join(cells[1:]))))
            continue
        if not extracted:
            continue
        m = _ITEM_RE.match(line)
        if not m:
            continue
        marker = m.group(1).strip()
        body = []
        if not marker.startswith("|"):
            for nxt in lines[n + 1:]:
                if nxt.startswith("#") or _ITEM_RE.match(nxt):
                    break
                if marker.startswith("#"):
                    if nxt.strip():
                        body.append(nxt.strip())
                elif nxt.strip() and nxt[:1].isspace():
                    body.append(nxt.strip())
                else:
                    break
        if marker.startswith("|"):
            statement = _first_sentence(" | ".join(_cells(line)))
            whole = line
        elif marker.startswith("#"):
            title = line.lstrip("#").strip()
            rest = " ".join(body)
            statement = title + (" — " + _first_sentence(rest) if rest else "")
            whole = " ".join([line] + body)
        else:
            joined = " ".join([line.strip()[len(marker):].strip()] + body)
            statement = _first_sentence(joined)
            whole = joined
        items.append({"id": _ITEM_ID_RE.search(line).group(0), "kind": "item",
                      "section": section, "line": n + 1, "statement": statement,
                      "bindings": _path_tokens(whole, True), "evidence": None,
                      "released": None})
    for paths, ids in impact_rows:
        for c in items:
            if c["kind"] == "item" and c["id"] in ids:
                c["bindings"] |= paths
    return items


def has_preservation_record(impact_body):
    """True when an Impact body holds the preservation table or the no-symbol line."""
    return any(b.strip().lower() == PRESERVATION_HEADING.lower() or b.strip() == NO_SYMBOL_LINE
               for b in (impact_body or "").splitlines())


def unread_sections(text, items=None):
    """The `## ` headings the view could not extract, in document order: the
    Interface Contract (its items carry no id), an extracted section holding prose
    but no id'd item, and an Impact with neither the preservation table nor the
    no-symbol line."""
    items = parse_constraints(text) if items is None else items
    homes = {c["section"] for c in items if c["kind"] == "item"}
    lines = (text or "").splitlines()
    names = []
    for i, line in enumerate(lines):
        if not line.startswith("## "):
            continue
        body = []
        for nxt in lines[i + 1:]:
            if nxt.startswith("## "):
                break
            body.append(nxt)
        heading = line.strip()
        if any(line.startswith(a) for a in INTERFACE_SECTION):
            names.append(heading)
        elif any(line.startswith(a) for s in CONSTRAINT_SECTIONS for a in s):
            if any(b.strip() for b in body) and heading not in homes:
                names.append(heading)
        elif any(line.startswith(a) for a in IMPACT_SECTION):
            if not has_preservation_record("\n".join(body)):
                names.append(heading)
    return names


def constraints_sentence(names):
    if not names:
        return CONSTRAINTS_SENTENCE + "."
    return CONSTRAINTS_SENTENCE + "; read in full: " + ", ".join(f"`{n}`" for n in names) + "."


def _clip(line):
    line = _CONTROL_RE.sub("", line)
    return line if len(line) <= CONSTRAINT_LINE_MAX else line[:CONSTRAINT_LINE_MAX - 1] + "…"


def constraint_lines(home, items, grouped):
    """FS4's lines: `ID — statement — home:line`, a P row followed by its evidence;
    `grouped` puts each home heading before its first item."""
    out, current = [], None
    for c in items:
        if grouped and c["section"] != current:
            current = c["section"]
            out.append(_clip(current))
        out.append(_clip(f"{c['id']} — {c['statement']} — {home}:{c['line']}"))
        if c["kind"] == "P" and c["evidence"]:
            out.append(_clip(f"    evidence: {c['evidence']}"))
    return out


def unit_constraints(root, unit):
    """[(path, meta, items, unread)] for the ANALYSIS files of `unit` -- an id such
    as F-001, or a file name with or without `.md`; [] when none matches."""
    key = str(unit or "").strip()
    name = key if key.endswith(".md") else key + ".md"
    out = []
    for p, meta, text in list_analyses(root):
        m = UNIT_ID_RE.search(str(meta.get("id") or ""))
        if p.name == name or (m and m.group(1) == key):
            items = parse_constraints(text)
            out.append((p, meta, items, unread_sections(text, items)))
    return out


def project_relative(root, path):
    """`path` relative to `root`, normalized as bindings are, or None outside it."""
    raw = str(path or "").replace("\\", "/")
    if not raw:
        return None
    p = Path(raw)
    if not p.is_absolute():
        p = Path.cwd() / p
    try:
        rel = p.resolve().relative_to(Path(root).resolve())
    except (ValueError, OSError):
        return None
    return _norm_rel(rel.as_posix())


def open_code_units(root):
    """[(path, meta, text)] for the tree's open L3 units of the code domain. Open
    units come from `_open_units`, unchanged (P1)."""
    if not ai_path(root).is_dir():
        return []
    open_names = {n for names in _open_units(root).values() for n in names}
    if not open_names:
        return []
    default = project_default_domain(root)
    return [(p, meta, text) for p, meta, text in list_analyses(root)
            if p.name in open_names
            and str(meta.get("level", "")).upper() == "L3"
            and meta.get("status") in ("PLANNED", "IN_PROGRESS")
            and resolve_domain(meta, default)[0] == "code"]


def file_constraints(root, path):
    """[(path, meta, bound items, unread)] for each open L3 unit of the code domain
    with an unreleased constraint bound to `path`."""
    rel = project_relative(root, path)
    if rel is None:
        return []
    out = []
    for p, meta, text in open_code_units(root):
        items = parse_constraints(text)
        bound = [c for c in items if not c["released"] and rel in c["bindings"]]
        if bound:
            out.append((p, meta, bound, unread_sections(text, items)))
    return out


# The recall hook (FS6). It informs, never decides: its JSON carries no
# `permissionDecision`, so the user's permission flow is the one without it
# (P6). A level is read with the verdict hook's `_DECLARATION_RE`; only the code
# lens's `L` levels count here.
CONSTRAINTS_HOOK_LINES = 15
_WORK_TOOLS = VERDICT_EDIT_TOOLS + ("Read",)


def transcript_work(path):
    """What the session transcript shows about the work, or None when it cannot be
    read within the verdict hook's bounds: {"assistant": entries parsed,
    "sidechain": a subagent's transcript, "level": the last declared level ("1",
    "2", "3") or None, "touched": normalized absolute paths this session read or
    wrote}."""
    work = {"assistant": 0, "sidechain": False, "level": None, "touched": set()}
    try:
        p = Path(path)
        if not p.is_file() or p.stat().st_size > VERDICT_MAX_BYTES:
            return None
        for entry in transcript_events(p):
                if not isinstance(entry, dict) or entry.get("type") != "assistant":
                    continue
                content = (entry.get("message") or {}).get("content")
                if not isinstance(content, list):
                    continue
                work["assistant"] += 1
                if entry.get("isSidechain") is True:
                    work["sidechain"] = True
                for block in content:
                    if not isinstance(block, dict):
                        continue
                    if block.get("type") == "text":
                        for letter, one, other in _DECLARATION_RE.findall(
                                str(block.get("text") or "")):
                            if letter.upper() == "L":
                                work["level"] = one or other
                    elif block.get("type") == "tool_use" and block.get("name") in _WORK_TOOLS:
                        inp = block.get("input") or {}
                        target = inp.get("file_path") or inp.get("notebook_path")
                        if isinstance(target, str) and target:
                            try:
                                work["touched"].add(_norm_rel(Path(target).resolve().as_posix()))
                            except (OSError, ValueError):
                                pass
    except (OSError, ValueError, TypeError, AttributeError):
        return None
    return work


def _hook_new_text(tool_input):
    """The text an edit is about to write: Edit, Write, MultiEdit, NotebookEdit."""
    parts = [tool_input.get(k) for k in ("new_string", "content", "new_source")]
    for e in tool_input.get("edits") or []:
        if isinstance(e, dict):
            parts.append(e.get("new_string"))
    return "\n".join(x for x in parts if isinstance(x, str))


def _unit_documents(root, p):
    """Normalized absolute paths of a unit's ANALYSIS, request records and handoff:
    reading or writing any of them is working on the unit."""
    slug = p.stem[len("ANALYSIS_"):]
    docs = {p, ai_path(root, "audit", f"HANDOFF_{slug}.md")}
    for r in requests_naming(root, p.name):
        docs.add(r)
        docs.add(ai_path(root, "audit", f"HANDOFF_{r.stem[len('REQUEST_'):]}.md"))
    return {_norm_rel(d.resolve().as_posix()) for d in docs}


def constraints_hook_context(payload, root=None, docs_name=None):
    """The context to recall before this edit, or None (FS6): an edit tool, outside
    a subagent, on a file of a project whose open L3 code unit binds it (or the
    unit's own ANALYSIS, about to name a path a P row binds -- UC6), by a session
    that worked on that unit and last declared L3."""
    if payload.get("tool_name") == "apply_patch" and not payload.get("agent_id"):
        lines = []
        for edit in hook_edits(payload) or []:
            context = constraints_hook_context({**payload, "tool_name": "Edit", "tool_input": {
                "file_path": edit["path"], "new_string": edit["new_text"]}}, root, docs_name)
            for line in (context or "").splitlines():
                if line not in lines:
                    lines.append(line)
        if len(lines) > CONSTRAINTS_HOOK_LINES:
            lines = lines[:CONSTRAINTS_HOOK_LINES - 1] + [lines[-1]]
        return "\n".join(lines) or None
    if payload.get("tool_name") not in VERDICT_EDIT_TOOLS or payload.get("agent_id"):
        return None
    tool_input = payload.get("tool_input") or {}
    target = tool_input.get("file_path") or tool_input.get("notebook_path")
    transcript = payload.get("transcript_path")
    if not isinstance(target, str) or not target or not transcript:
        return None
    root = hook_project(target, root, docs_name)
    if root is None or not ai_path(root, "solutions").is_dir():
        return None
    found = file_constraints(root, target)
    rel = project_relative(root, target)
    named = _path_tokens(_hook_new_text(tool_input), False)
    if named and rel and rel.startswith(_norm_rel(f"{docs_dir()}/solutions/ANALYSIS_")):
        for p, meta, text in open_code_units(root):
            if _norm_rel(f"{docs_dir()}/solutions/{p.name}") != rel:
                continue
            items = parse_constraints(text)
            bound = [c for c in items if c["kind"] == "P"
                     and not c["released"] and c["bindings"] & named]
            if bound and not any(f[0] == p for f in found):
                found.append((p, meta, bound, unread_sections(text, items)))
    if not found:
        return None
    work = transcript_work(transcript)
    if not work or not work["assistant"] or work["sidechain"] or work["level"] != "3":
        return None
    # One budget for the whole recall, whatever the number of units; a P line and
    # its evidence line are kept together or left out together.
    out, budget = [], CONSTRAINTS_HOOK_LINES
    for p, meta, items, unread in found:
        if not (_unit_documents(root, p) & work["touched"]):
            continue
        home = f"solutions/{p.name}"
        unit = meta.get("id") or p.stem
        out.append(_clip(f"[sdlc constraints] {unit} — {home}"))
        shown = 0
        for c in items:
            chunk = constraint_lines(home, [c], False)
            if len(chunk) > budget:
                break
            out.extend(chunk)
            budget -= len(chunk)
            shown += 1
        if shown < len(items):
            out.append(_clip(f"More: sdlc_check.py constraints --unit {unit}"))
        out.append(_clip(constraints_sentence(unread)))
    return "\n".join(out) if out else None


def cmd_constraints_hook(args):
    """PreToolUse hook: print a context-only JSON or nothing. Always 0 -- exit 2
    would block the edit, and the wired command adds `; exit 0` for validators
    that cannot run this at all (T2)."""
    try:
        payload = read_hook_payload()
        if payload is None:
            return 0
        root = Path(args.root).resolve() if args.root else None
        context = constraints_hook_context(payload, root, getattr(args, "docs_dir", None))
        if context:
            print(json.dumps({"hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "additionalContext": context}}, ensure_ascii=False))
    except Exception:
        pass
    return 0


def cmd_constraints(root, args):
    if args.unit:
        found = unit_constraints(root, args.unit)
        if not found:
            print(f"[ERROR] unknown unit '{args.unit}': give an id such as F-001 "
                  "or an ANALYSIS file name")
            return 1
        groups = [(p, meta, items, unread, True) for p, meta, items, unread in found]
    else:
        groups = [(p, meta, items, unread, False)
                  for p, meta, items, unread in file_constraints(root, args.file)]
    for p, meta, items, unread, grouped in groups:
        home = f"solutions/{p.name}"
        print(_clip(f"{meta.get('id') or p.stem} — {home}"))
        for line in constraint_lines(home, items, grouped):
            print(line)
        print(_clip(constraints_sentence(unread)))
    return 0


# --------------------------------------------------------------------- plan
# Subagent Execution (Feature A). Zero-execution surface: this section and
# everything it calls MUST NOT spawn a process (no subprocess/os.system/eval/
# exec, no git_* helper). It validates a PLAN_[feature].md and prints a task
# brief as text; the orchestrator (dispatch.md) is the sole executor.

_PLAN_JSON_RE = re.compile(r"```json\s*\n(.*?)```", re.DOTALL)


def extract_plan_json(text):
    """Extract the first fenced ```json block from a PLAN_[feature].md body.
    Returns (data, "") on success, or (None, reason) on any failure. Never
    raises: a malformed or missing block is a validation failure, not a crash."""
    m = _PLAN_JSON_RE.search(text or "")
    if not m:
        return None, "no fenced ```json block found in the plan file"
    try:
        data = json.loads(m.group(1))
    except (ValueError, TypeError) as e:
        return None, f"malformed JSON in the plan block: {e}"
    if not isinstance(data, dict):
        return None, "plan JSON block must be a JSON object"
    return data, ""


def load_ledger(path):
    """Read the sidecar ledger {"<task_id>": {"status", "verify_result",
    "timestamp"}}. Absent file -> ({}, ""). Malformed/unreadable -> ({}, reason).
    Never raises, never hangs: the ledger is untrusted state read on every call."""
    if not path.is_file():
        return {}, ""
    try:
        raw = read_text(path)
        data = json.loads(raw)
    except (ValueError, TypeError, OSError) as e:
        return {}, f"ledger '{path}' unreadable/malformed, treating as empty: {e}"
    if not isinstance(data, dict):
        return {}, f"ledger '{path}' is not a JSON object, treating as empty"
    return data, ""


def _confine_or_reject(base, rel, label, rel_label, errors):
    t = confine_under(base, rel)
    if t is None:
        errors.append(f"{rel_label}: {label} '{rel}' is absolute, contains '..', or escapes "
                      f"'{base}' — rejected (fail closed)")
    return t


def _validate_plan_tasks(root, data, rel_label, errors, warnings):
    """Shared core of `plan validate`/`plan brief`: schema + confinement checks.
    Returns the task list (possibly empty) on success; errors/warnings are
    appended in place. Callers decide the exit code."""
    tasks = data.get("tasks")
    if not isinstance(tasks, list) or not tasks:
        errors.append(f"{rel_label}: 'tasks' must be a non-empty JSON array")
        return []
    ref_dir = ai_path(root, "reference")
    kb_ref = DEFAULT_KB_ROOT / "ai_docs" / "reference"
    seen_ids = set()
    for i, task in enumerate(tasks):
        loc = f"{rel_label}: task[{i}]"
        if not isinstance(task, dict):
            errors.append(f"{loc}: not a JSON object")
            continue
        missing = [k for k in PLAN_TASK_REQUIRED if not task.get(k)]
        if missing:
            errors.append(f"{loc}: missing required field(s): {', '.join(missing)}")
        if not task.get("paths") and not task.get("produces"):
            errors.append(f"{loc}: must declare at least one of 'paths'/'produces'")
        tid = task.get("id")
        if tid:
            if tid in seen_ids:
                errors.append(f"{loc}: duplicate task id '{tid}'")
            seen_ids.add(tid)
        for key in ("paths", "consumes", "produces"):
            for p in (task.get(key) or []):
                _confine_or_reject(root, p, key, loc, errors)
        for g in (task.get("guides") or []):
            in_project = confine_under(ref_dir, g)
            in_kb = confine_under(kb_ref, g)
            if in_project is None and in_kb is None:
                errors.append(f"{loc}: guide '{g}' is not confined under the project reference "
                              f"dir ({ref_dir}) or the agent KB reference dir ({kb_ref}) — rejected")
    return tasks


def cmd_plan(root, args):
    """Zero-execution: validates/briefs a PLAN_[feature].md. Never spawns a
    process, never calls a git_* helper, never runs the opaque `verify` text —
    it is printed, not executed."""
    plan_path = Path(args.file)
    if not plan_path.is_absolute():
        plan_path = root / plan_path
    if not plan_path.is_file():
        sys.stderr.write(f"[plan] plan file not found: {plan_path}\n")
        return 2
    rel_label = str(plan_path)
    data, reason = extract_plan_json(read_text(plan_path))
    if data is None:
        sys.stderr.write(f"[plan] {rel_label}: {reason}\n")
        return 2

    errors, warnings = [], []
    tasks = _validate_plan_tasks(root, data, rel_label, errors, warnings)

    ledger_path = plan_path.with_name(plan_path.stem + ".ledger.json")
    ledger, ledger_reason = load_ledger(ledger_path)
    if ledger_reason:
        warnings.append(ledger_reason)
    if not errors:
        task_ids = {t.get("id") for t in tasks if isinstance(t, dict)}
        for lid in ledger:
            if lid not in task_ids:
                warnings.append(f"ledger id '{lid}' not found in {rel_label}: orphaned entry (not fatal)")

    for w in warnings:
        sys.stderr.write(f"[warn] {w}\n")
    for e in errors:
        sys.stderr.write(f"[ERROR] {e}\n")

    if args.plan_cmd == "validate":
        if errors:
            sys.stderr.write(f"\n[plan] validate: {len(errors)} errors, {len(warnings)} warnings.\n")
            return 2
        print(f"[ok] {rel_label}: plan valid ({len(tasks)} task(s), {len(warnings)} warning(s)).")
        return 0

    # brief
    if errors:
        sys.stderr.write(f"\n[plan] brief: plan is invalid, refusing to brief ({len(errors)} errors).\n")
        return 2
    target = None
    for t in tasks:
        if isinstance(t, dict) and t.get("id") == args.task:
            target = t
            break
    if target is None:
        sys.stderr.write(f"[plan] brief: task id '{args.task}' not found in {rel_label}\n")
        return 2

    print(f"# Task: {target.get('id')} — {target.get('title', '')}")
    print()
    print("## Task block")
    print(json.dumps(target, indent=2))
    print()
    print("## Produces of prior-order tasks (interfaces)")
    prior_produces = []
    for t in tasks:
        if not isinstance(t, dict):
            continue
        if t.get("id") == target.get("id"):
            break
        prior_produces.extend(t.get("produces") or [])
    if prior_produces:
        for p in prior_produces:
            print(f"- {p}")
    else:
        print("(none)")
    print()
    print("## Guide pointers (paths, not content)")
    guides = target.get("guides") or []
    if guides:
        for g in guides:
            print(f"- {g}")
    else:
        print("(none)")
    print()
    print("## Verify (opaque text — orchestrator runs this out of band, NOT executed here)")
    print(target.get("verify", ""))
    return 0


# --- F-050: the benefit report -------------------------------------------
# The process's central claim is that it makes divergence visible BEFORE
# implementation. That claim lived in prose for four months while the evidence
# for it sat unread in REVIEW_LOG. This reads it.
#
# Columns are resolved BY HEADER NAME, never by width. `templates.md` states
# that contract ("extra or reordered columns are fine -- but the header must
# say `tier`") and three widths are legal today: the original 8, Standalone's 9
# (F-048 added `model`), and Hybrid's 10 (`instrument` + `notes`, and no
# `reviewer` at all). A width whitelist reads none of the last, and silently
# reports a devPNT-governed project as having no data at all.
#
# Two honesty rules, both learned from this unit's own review: whatever cannot
# be read is COUNTED and NAMED, at the row level AND at the cell level. A ratio
# over a silently shrunken denominator is worse than no ratio.
REVIEW_CORE = ("date", "doc_key", "tier", "findings_real", "verdict")
REVIEW_POSITIONAL = {
    8: ("date", "doc_key", "tier", "reviewer", "findings_raised",
        "findings_real", "verdict", "revise_rounds"),
    9: ("date", "doc_key", "tier", "model", "reviewer", "findings_raised",
        "findings_real", "verdict", "revise_rounds"),
    10: ("date", "doc_key", "tier", "model", "instrument", "findings_raised",
         "findings_real", "verdict", "revise_rounds", "notes"),
}


_UNESCAPED_PIPE_RE = re.compile(r"(?<!\\)\|")


def _table_cells(line):
    """Cells of a Markdown table row, or None when the line is not one.
    Separator rows (---, :---:, any alignment colons) are not data. A cell may
    carry an escaped pipe (`\\|`, as `index` writes them): it does not split the
    row, and it reads back as `|` (F-075)."""
    s = line.strip()
    if not s.startswith("|"):
        return None
    if set(s) <= set("|-: "):
        return None
    body = s[1:]
    if body.endswith("|") and not body.endswith("\\|"):
        body = body[:-1]
    return [c.strip().replace("\\|", "|") for c in _UNESCAPED_PIPE_RE.split(body)]


def parse_review_log(text):
    """-> (rows, unparsed). Columns come from the header when there is one.

    Falls back to the positional maps only for a table with no header, so a
    hand-kept log still reads. A row whose cell count does not match the
    header's is unparsed and named -- never dropped."""
    rows, unparsed, names = [], [], None
    for n, line in enumerate(text.splitlines(), 1):
        cells = _table_cells(line)
        if cells is None:
            continue
        lowered = [c.lower() for c in cells]
        if names is None and "tier" in lowered and "verdict" in lowered:
            names = lowered                      # the header IS the column map
            continue
        # The header supplies the map -- that is what makes reordered and extra
        # columns readable. But a log legitimately carries MIXED widths (F-048
        # widened the schema and did not rewrite history), so a row that does
        # not match the header is read by the positional map for its own width
        # before it is given up on. Only a width no map knows is unparsed.
        if names is not None and len(cells) == len(names):
            row = dict(zip(names, cells))
        else:
            positional = REVIEW_POSITIONAL.get(len(cells))
            if positional is None:
                unparsed.append((n, "%d cells: %s" % (
                    len(cells),
                    "header declares %d and no positional map fits"
                    % len(names) if names else "no header, and no map fits")))
                continue
            row = dict(zip(positional, cells))
        missing = [c for c in REVIEW_CORE if c not in row]
        if missing:
            unparsed.append((n, "no %s column" % "/".join(missing)))
            continue
        if not re.match(r"^\d{4}-\d{2}-\d{2}$", row["date"]):
            unparsed.append((n, "date cell %r is not a date" % row["date"][:24]))
            continue
        rows.append(row)
    return rows, unparsed


def review_findings(value):
    """The count in a `findings_real` cell, or None when it states no number.

    None is NOT zero. `all` and `VOID -- instrument error` appear in real logs,
    and counting them as zero findings silently deflates the one ratio this
    report exists to state. Anchored at the START of the cell so a prose cell
    like `R1 4 BLOCK + 8 WARN` does not yield a confident 4."""
    m = re.match(r"^(\d+)\b", (value or "").strip())
    return int(m.group(1)) if m else None


def _is_fail(verdict):
    """FAIL as a WORD, so `PASS (no failures)` is not counted as a failure."""
    return re.search(r"\bFAIL\b", (verdict or "").upper()) is not None


def _is_pass(verdict):
    return re.search(r"\bPASS\b", (verdict or "").upper()) is not None


def _is_not_due(verdict):
    """A review ruled not due (review.md, a delta that only restates judged
    work): logged so a skip stays visible, but it is neither a review nor a
    finding, so it stays out of every count below (F-071)."""
    return (verdict or "").strip().upper().startswith("NOT DUE")


def _print_read_cost():
    """The cost side, printed with the benefit and NEVER without it: a catch
    rate with no cost term justifies unbounded doctrine, and a cost term with
    no catch rate justifies deleting the process. When it cannot be measured
    the line still prints, saying so -- silence here IS the catch rate quoted
    alone, which is the thing this report exists to prevent."""
    skill_dir = Path(__file__).resolve().parent.parent
    contract = skill_dir / "SKILL.md"
    print()
    if not contract.is_file():
        print("Read cost: unavailable -- SKILL.md not found beside this "
              "validator (%s)" % skill_dir)
        return
    files = [p for p in sorted(skill_dir.glob("*.md")) if p.name != "SKILL.md"]
    support = sum(p.stat().st_size for p in files)
    head = contract.stat().st_size
    # The TOTAL, and the files itemised. Printing only the two terms lets the
    # one that fell be quoted while the one that grew stays lumped -- which is
    # exactly how a -7.8% headline coexisted with a read surface that grew.
    print("Read cost of %s: SKILL.md %d bytes (every session) + %d bytes "
          "across %d support files (read on trigger) = %d bytes total"
          % (skill_dir.name, head, support, len(files), head + support))
    for p in files:
        print("    %-24s %8d" % (p.name, p.stat().st_size))


def cmd_benefit(root):
    """Report what the process caught, beside what it costs to read.

    ALWAYS exits 0 and emits no warning or advisory. This number is the
    criterion future units are judged by; a measurement that can fail a build
    becomes a target, and a targeted measurement stops measuring."""
    log = root / review_log_rel()
    print("=== benefit: what the process caught, and what it costs to read ===")
    if not log.is_file():
        print("[info] no %s yet: nothing to report. The number appears once "
              "reviews are logged." % review_log_rel())
        _print_read_cost()
        return 0
    rows, unparsed = parse_review_log(read_text(log))
    not_due = [r for r in rows if _is_not_due(r["verdict"])]
    rows = [r for r in rows if not _is_not_due(r["verdict"])]
    # F-085 FS10: a `post-merge` row is the owner's report of a defect that got
    # past every review -- not a review, so it stays out of every review figure.
    post_merge = [r for r in rows if r["tier"].lower().startswith("post-merge")]
    rows = [r for r in rows if not r["tier"].lower().startswith("post-merge")]
    # `tier` carries the MOMENT in Standalone (design / closure) and the
    # reviewer WEIGHT in Hybrid (deep / light / code / guide / vision). A
    # Hybrid row is a real review whose moment this column does not state, so
    # it is counted and named, never folded into a moment by guesswork.
    moments = {"design": [], "closure": []}
    unstated = {}
    unstated_found = unstated_code = unstated_uncounted = 0
    for r in rows:
        tier = r["tier"].lower()
        if tier.startswith("design"):
            moments["design"].append(r)
        elif tier.startswith("closure"):
            moments["closure"].append(r)
        else:
            unstated[tier] = unstated.get(tier, 0) + 1
            n = review_findings(r["findings_real"])
            if n is None:
                unstated_uncounted += 1
            else:
                unstated_found += n
                if tier.startswith("code"):
                    unstated_code += n
    classified = moments["design"] + moments["closure"]
    print("rows parsed: %d   rows unparsed: %d%s"
          % (len(rows) + len(not_due) + len(post_merge), len(unparsed),
             ("  -> " + "; ".join("line %d: %s" % u for u in unparsed[:5]))
             if unparsed else ""))
    print("reviews ruled not due (logged, counted in no figure below): %d"
          % len(not_due))
    if post_merge:
        print("defects reported after merge (tier post-merge, not reviews, "
              "counted in no figure below): %d" % len(post_merge))
    print("reviews with a stated moment: %d   moment not stated by `tier`: %d%s"
          % (len(classified), sum(unstated.values()),
             ("  (" + ", ".join("%s x%d" % (t, n) for t, n
                                in sorted(unstated.items())) + ")")
             if unstated else ""))
    if not classified:
        _print_read_cost()
        return 0
    dates = sorted(r["date"] for r in classified)
    print("span of the reviews counted below: %s -> %s" % (dates[0], dates[-1]))

    print()
    print("%-9s %6s %10s %11s %10s" % ("moment", "rows", "findings",
                                       "FAIL verdict", "per review"))
    totals, uncounted = {}, 0
    for m in ("design", "closure"):
        rs = moments[m]
        counts = [review_findings(r["findings_real"]) for r in rs]
        uncounted += sum(1 for c in counts if c is None)
        found = sum(c for c in counts if c is not None)
        failed = sum(1 for r in rs if _is_fail(r["verdict"]))
        totals[m] = found
        print("%-9s %6d %10d %11d %10.1f"
              % (m, len(rs), found, failed, (found / len(rs)) if rs else 0.0))
    total = sum(totals.values())
    if uncounted:
        print("findings cells stating no number: %d (counted as unknown, "
              "never as zero)" % uncounted)
    if total:
        print()
        print("Caught BEFORE the code existed: %d / %d findings = %.0f%%"
              % (totals["design"], total, 100.0 * totals["design"] / total))
        # The residue, stated as a BOUND rather than as a direction. The
        # sentence this replaces claimed the share was "a floor, not a
        # ceiling" because `code` rows are post-implementation -- which is
        # backwards, since folding them LOWERS the design share. But the fact
        # was right and only the direction wrong, so `code` findings sit on
        # the closure side of the upper bound instead of being discarded with
        # it. No direction is printed at all: the unstated set pushes both
        # ways, and only an interval is true of all of it.
        if unstated_found:
            denom = total + unstated_found
            print("Bounded by the %d findings in rows whose moment `tier` "
                  "does not state: %.0f%%-%.0f%% (`code` rows are "
                  "post-implementation by definition, so their findings sit "
                  "on the closure side of the upper bound)"
                  % (unstated_found, 100.0 * totals["design"] / denom,
                     100.0 * (totals["design"] + unstated_found - unstated_code)
                     / denom))
        if unstated_uncounted:
            print("%d unstated rows state no findings count (`all`, `VOID`): "
                  "neither zero nor countable, so they lie outside both "
                  "bounds" % unstated_uncounted)
    failed_all = sum(1 for r in classified if _is_fail(r["verdict"]))
    inconclusive = sum(1 for r in classified if not _is_fail(r["verdict"])
                       and not _is_pass(r["verdict"]))
    print("Reviews whose verdict contains FAIL: %d / %d = %.0f%%%s"
          % (failed_all, len(classified), 100.0 * failed_all / len(classified),
             ("   (+%d inconclusive)" % inconclusive) if inconclusive else ""))
    print("(both figures are over the %d reviews whose moment `tier` states)"
          % len(classified))
    _print_read_cost()
    return 0


# --- orient helpers (F-075) ---------------------------------------------------
SKILL_MD_CAP = 64 * 1024        # a SKILL.md is read for its name only


def orient_fit(lines, budget, rel):
    """The lines that fit `budget` characters (one newline each), cut at a line
    boundary and closed by a pointer to the file holding the rest. A single line
    wider than the room left shows its head. Never raises."""
    out, used = [], 0
    for i, line in enumerate(lines):
        if used + len(line) + 1 <= budget:
            out.append(line)
            used += len(line) + 1
            continue
        rest = len(lines) - i

        def ptr(n):
            return f"(+{n} more lines -- read {rel})"
        room = budget - used - len(ptr(rest)) - 1
        if room > 40:
            head = line[:room - 4] + "..."
            out.append(head)
            used += len(head) + 1
        while out and used + len(ptr(rest)) + 1 > budget:
            used -= len(out.pop()) + 1
            rest += 1
        out.append(ptr(rest))
        return out
    return out


def lens_table(skill_dir=None):
    """{skill_name: lens} from the running skill's own `routing.md` par.0 table.

    The Python twin of lib.js `lensTable()`, same parse: a row whose lens cell is
    `[a-z]+` and whose skill cell is a backticked `[a-z0-9-]+`. `routing.md` is a
    byte-identical shared file, so the family list cannot drift between
    distributions -- a literal list here is how kb and mkt once announced
    themselves as the code lens. Fail-open: {} on any failure."""
    try:
        base = Path(skill_dir) if skill_dir else Path(__file__).resolve().parent.parent
        table = {}
        for line in read_text(base / "routing.md").splitlines():
            cells = [c.strip() for c in line.split("|")]
            if len(cells) < 4:
                continue
            lens, skill = cells[1], cells[2]
            if re.fullmatch(r"[a-z]+", lens) and re.fullmatch(r"`[a-z0-9-]+`", skill):
                table.setdefault(skill[1:-1], lens)
        return table
    except Exception:
        return {}


def _skills_dirs():
    """The two places a sibling lens is installed: beside the running skill, and
    the user's Claude skills directory. AGENTIC_SDLC_SKILLS_DIRS (os.pathsep
    list; empty = none) is the test seam, like AGENTIC_SDLC_USER_SETTINGS."""
    seam = os.environ.get("AGENTIC_SDLC_SKILLS_DIRS")
    if seam is not None:
        return [Path(s) for s in seam.split(os.pathsep) if s]
    cfg = os.environ.get("CLAUDE_CONFIG_DIR")
    return [Path(__file__).resolve().parents[2],
            (Path(cfg) if cfg else Path.home() / ".claude") / "skills"]


def installed_sibling_lenses():
    """Names of the family's other lenses installed on this machine (sorted).

    Only a name that appears in `lens_table()` AND equals a `SKILL.md` `name:`
    exactly can come out -- no text of a sibling's files reaches the output
    (P-TM T3). Fail-open: [] on any failure."""
    try:
        own = profile()["skill_name"]
        family = lens_table()
        found = set()
        for base in _skills_dirs():
            if not base.is_dir():
                continue
            for sub in base.iterdir():
                f = sub / "SKILL.md"
                try:
                    if not f.is_file() or f.stat().st_size > SKILL_MD_CAP:
                        continue
                    m = re.search(r"^name:\s*(\S+)", read_text(f), re.M)
                except OSError:
                    continue
                if m and m.group(1) in family and m.group(1) != own:
                    found.add(m.group(1))
        return sorted(found)
    except Exception:
        return []


def _orient_router_lines(text):
    """One line per guide from the generated router; a hand-written one as written."""
    if not re.search(r"GENERATED by \S+ index - do not edit by hand", text):
        return text.splitlines()
    rows = []
    for line in text.splitlines():
        cells = _table_cells(line)
        if not cells or len(cells) < 3 or cells[0] == "Guide":
            continue
        rows.append(f"- {cells[0]} ({cells[1]}) -- {cells[2]}")
    return rows or ['no guides yet -- the router verdict is "no match"']


def _orient_registry_lines(text):
    """One line per workstream plus the project-wide notes from the generated
    registry; a hand-written handoff as written."""
    if not is_generated_registry(text):
        return text.splitlines()
    table, _, notes = text.partition("\n## Project-wide notes")
    lines = []
    for line in table.splitlines():
        c = _table_cells(line)
        if not c or len(c) < 6 or c[0].lower() == "workstream":
            continue
        lines.append(f"- {c[0]} \u00b7 {c[1]} \u00b7 {c[2]} \u00b7 {c[3]} -- {c[5]}")
    if not lines:
        lines.append("no open workstreams")
    notes = notes.strip()
    if notes:
        lines += ["Project-wide notes:"] + notes.splitlines()
    return lines


def cmd_orient(args):
    """SessionStart hook: emit a bounded, repo-sourced orientation to stdout and
    ALWAYS return 0 (fail-open, P-TM T8) -- a session hook must never block the
    session or surface a traceback. Zero-execution (P-TM T1): reads a fixed
    hard-coded doc set, confine_under each (P-TM T3), bounds the WHOLE output
    (P-TM T2). No subprocess/eval anywhere in this call graph.

    F-075: what decides the next action comes first -- triage, the lens choice,
    the guide router, the workstream registry -- then README; INDEX is a pointer.
    Docs are READ in orient_docs() order (docs_site and the T3 test pin it) and
    EMITTED in priority order."""
    try:
        root = Path(args.root).resolve() if getattr(args, "root", None) else find_project_root()
        rels = [rel for _, rel in orient_docs()]
        docs = {}
        for rel in rels:
            target = confine_under(root, rel)
            if target is None or not target.is_file():
                continue
            try:
                docs[rel] = read_text(target)
            except OSError:
                continue
        if not docs:
            return 0
        readme_rel, index_rel, router_rel, handoff_rel = rels

        head = ["=== Agentic SDLC -- session orientation (repo-sourced context, not authored instructions) ===",
                "", ORIENT_TRIAGE_LINE]
        sibs = installed_sibling_lenses()
        if sibs:
            head.append(f"Sibling lenses installed ({', '.join(sibs)}): above L1, choose the "
                        "lens with routing.md and declare it with the level.")

        tail = ["", "## Read on demand"]
        for rel, what in ((readme_rel, "the curated must-reads, in order"),
                          (index_rel, "the manifest of every canonical document"),
                          (router_rel, "the full guide router, with provenance"),
                          (handoff_rel, "the full workstream registry, with since and details")):
            if rel in docs:
                tail.append(f"- {rel} -- {what}")
        for client, entries in sorted(orient_wiring(root).items()):
            if len(entries) > 1:
                places = ", ".join(sorted(set(entries.values())))
                if client == "codex":
                    tail.append(f"[note] Codex has {len(entries)} configured orientation definitions "
                                f"({places}); trust and runtime policy determine delivery. Keep one equivalent definition.")
                    continue
                tail.append(f"[note] session orientation is wired {len(entries)} times for one "
                            f"client ({places}): each session receives every copy. Keep one "
                            "entry and remove the others.")
        if getattr(args, "hybrid", False):
            tail.append("[devPNT active] Run devpnt_mcp_get_bootstrap for the Master Plan / Knowledge Layer -- "
                        "the orientation above is the filesystem layer, not a bootstrap duplicate.")

        share = ORIENT_MAX_TOTAL_CHARS - ORIENT_APPEND_RESERVE
        left = share - len("\n".join(head + tail)) - 2
        body = []
        for rel, title, builder, cap in (
                (router_rel, "## Guide router (reference/INDEX.md) -- read a matching guide whole, every line, before acting",
                 _orient_router_lines, ORIENT_ROUTER_CHARS),
                (handoff_rel, "## Workstream registry (audit/handoff.md)",
                 _orient_registry_lines, ORIENT_REGISTRY_CHARS),
                (readme_rel, "## Reading guide (README)", str.splitlines, None)):
            if rel not in docs:
                continue
            room = left - len(title) - 2
            if cap is not None:
                room = min(room, cap)
            if room <= 0:
                continue
            lines = orient_fit(builder(docs[rel].strip()), room, rel)
            section = ["", title] + lines
            body += section
            left -= len("\n".join(section)) + 1
        print("\n".join(head + body + tail))
        return 0
    except Exception:
        return 0


# --- portable checks carried by the core ------------------------------------
# Portable means portable: a check that any distribution may expose lives HERE, so
# three copies of the same twenty lines cannot drift apart. What a distribution
# actually offers is its `provides` declaration, not what it happens to have copied.
# Domain-specific machinery (mkt's budget and funnel arithmetic) stays in its own
# entry point -- that is the line between portable and proprietary.
# Opt-in per document via `checks:`. They may only ADD findings: a document that
# imports one still owes its own domain everything it owed before, so importing a
# check can never be a way to be validated less.

@portable_check("code.threat_model")
def _code_threat_model(rel, meta, text):
    """The security section names a real surface, or justifies claiming none."""
    section = section_body(text, ("## Security and Threat Model", "## Security"))
    if section is None:
        return []  # the owning domain already reports a missing section; no double finding
    surfaces = ("external input", "authn", "authz", "auth", "crypto", "network",
                "personal data", "filesystem", "supply chain")
    low = section.lower()
    if any(s in low for s in surfaces):
        return []
    if "no security impact" in low or "no new security" in low:
        if len(section.split()) < 15:
            return [("warning", "'no security impact' is declared, not justified: "
                                "say which surfaces you checked and why none is touched")]
        return []
    return [("warning", "no security surface named (external input, authN/authZ, crypto, "
                        "network, personal data, filesystem, supply chain) and no justified "
                        "claim that none is touched")]


@portable_check("knowledge.sources")
def _knowledge_sources(rel, meta, text):
    """A knowledge artifact says what it was written from AND how that was verified."""
    section = section_body(text, ("## Sources and Verification",))
    if section is None:
        return []
    findings = []
    if not re.search(r"(?m)^\s*[-*|]|\bhttps?://|\.(?:md|pdf|docx?|csv|xlsx?)\b", section):
        findings.append(("warning", "no source is named: a distillation whose origin cannot "
                                    "be reopened is model knowledge, not knowledge work"))
    if not re.search(r"verif|cross-check|checked against|confirmed", section, re.I):
        findings.append(("warning", "sources are listed but not verified: say how each was "
                                    "confirmed, or mark explicitly what could not be"))
    return findings


# ------------------------------------------------------------------- migrate

def _migration_plan(root, src_name, dst_name):
    """(files, refs, conflicts) for a docs-root move. Reads only."""
    src = root / src_name
    dst = root / dst_name
    files, refs, conflicts = [], [], []
    if not src.is_dir():
        return None, None, None
    for p in sorted(src.rglob("*")):
        if not p.is_file():
            continue
        rel = p.relative_to(src)
        target = dst / rel
        if target.exists():
            conflicts.append(rel.as_posix())
        files.append(rel.as_posix())
        if p.suffix.lower() in (".md", ".txt", ".json", ".yml", ".yaml"):
            try:
                if f"{src_name}/" in p.read_text(encoding="utf-8", errors="replace"):
                    refs.append(rel.as_posix())
            except OSError:
                pass
    return files, refs, conflicts


def _external_references(root, src_name):
    """Files OUTSIDE both roots that mention the old root.

    Reported, never edited: the protocol pointers (CLAUDE.md, AGENTS.md,
    .cursorrules) are user-authored, and a tool that rewrites them is the one thing
    `init` has refused to do since day one."""
    out = []
    for p in sorted(root.rglob("*")):
        if not p.is_file() or p.suffix.lower() not in (".md", ".txt", ".json", ".yml", ".yaml"):
            continue
        rel = p.relative_to(root)
        if rel.parts and rel.parts[0] in (src_name, ".git"):
            continue
        if any(part in SKIP_DIRS for part in rel.parts):
            continue
        try:
            if f"{src_name}/" in p.read_text(encoding="utf-8", errors="replace"):
                out.append(rel.as_posix())
        except OSError:
            pass
    return out


def cmd_migrate(root, args):
    """Relocate the documentation root. Dry-run by default; never deletes.

    Reversibility is structural, not promised: the old root is COPIED, never moved,
    so undoing the migration is deleting the new directory. Both roots stay
    readable throughout, which is what lets a team switch over one session at a
    time instead of in one jump.
    """
    src_name = args.from_dir
    dst_name = args.to_dir
    if src_name == dst_name:
        print(f"[ERROR] --from and --to are both '{src_name}': nothing to do.")
        return 1
    src = root / src_name
    if not src.is_dir():
        print(f"[ERROR] {src} not found: nothing to migrate.")
        return 1

    files, refs, conflicts = _migration_plan(root, src_name, dst_name)
    external = _external_references(root, src_name)

    print(f"=== migrate {src_name}/ -> {dst_name}/ ===")
    print(f"  {len(files)} file(s) to copy, {len(refs)} carrying '{src_name}/' references")
    for rel in files[:20]:
        print(f"    {src_name}/{rel}  ->  {dst_name}/{rel}")
    if len(files) > 20:
        print(f"    ... and {len(files) - 20} more")
    if conflicts:
        print(f"\n[ERROR] {len(conflicts)} file(s) already exist under {dst_name}/:")
        for rel in conflicts[:10]:
            print(f"    {dst_name}/{rel}")
        print("  Refusing to overwrite. Move them aside, or migrate into an empty root.")
        return 1
    if external:
        print(f"\n[note] {len(external)} file(s) OUTSIDE the docs roots mention "
              f"'{src_name}/'. They are NOT touched -- protocol pointers and READMEs are "
              "yours to edit:")
        for rel in external[:10]:
            print(f"    {rel}")

    if not args.apply:
        print("\n[dry-run] Nothing was written. Re-run with --apply to perform the copy.")
        print("          The old root is kept: this migration is undone by deleting "
              f"{dst_name}/.")
        return 0

    if git_available(root) and git_has_changes(root, "."):
        print("\n[ERROR] the working tree has uncommitted changes. Commit or stash first: "
              "a migration you cannot diff is a migration you cannot review.")
        return 1

    written = 0
    for rel in files:
        source = src / rel
        target = root / dst_name / rel
        target.parent.mkdir(parents=True, exist_ok=True)
        if rel in refs:
            text = source.read_text(encoding="utf-8", errors="replace")
            target.write_text(text.replace(f"{src_name}/", f"{dst_name}/"), encoding="utf-8")
        else:
            target.write_bytes(source.read_bytes())
        written += 1
    print(f"\n[ok] copied {written} file(s) into {dst_name}/. "
          f"{src_name}/ is untouched -- delete it yourself once you are satisfied.")
    print(f"     Next: run `validate --docs-dir {dst_name}` and compare it with "
          f"`validate --docs-dir {src_name}`. They should say the same thing.")
    return 0



# --------------------------------------------------------------------- main

def main(argv=None):
    # `remind` is intercepted BEFORE argparse (kb's F-041 rule, kept): it is a
    # hook surface fired on every prompt, so a stray flag must cost a usage
    # message and a non-zero exit on a turn, not the turn itself.
    if (argv if argv is not None else sys.argv[1:])[:1] == ["remind"]:
        return cmd_remind(None)

    common = argparse.ArgumentParser(add_help=False)
    common.add_argument("--root", help="project root (default: walk up until a docs root is found)")
    common.add_argument("--docs-dir", dest="docs_dir",
                        help="name of the documentation root (default: ai_docs; "
                             "use it to reach a legacy root such as mkt_docs, "
                             "or to disambiguate a half-migrated tree)")

    strict_opt = argparse.ArgumentParser(add_help=False)
    strict_opt.add_argument("--strict", action="store_true",
                            help="fail on warnings and on a missing docs root (for CI)")

    hybrid_opt = argparse.ArgumentParser(add_help=False)
    hybrid_opt.add_argument("--hybrid", action="store_true",
                            help="Hybrid/devPNT mode: audit-plan staleness is delegated to devPNT/KL; "
                                 "the gate also unlocks on an E-TDD shadow")

    ap = argparse.ArgumentParser(prog="sdlc_check.py",
                                 description="Mechanical validator for Agentic SDLC")
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("check", parents=[common, strict_opt, hybrid_opt],
                   help="closure gate: validate + stale in one command")
    sub.add_parser("validate", parents=[common, strict_opt, hybrid_opt],
                   help="verify docs-root coherence")
    sub.add_parser("index", parents=[common], help="regenerate features_history.md + ai_docs/INDEX.md")
    sub.add_parser("stale", parents=[common, hybrid_opt], help="areas modified after the last analysis")
    gp_mig = sub.add_parser("migrate", parents=[common],
                            help="relocate the documentation root (dry-run by default)")
    gp_mig.add_argument("--from", dest="from_dir", required=True,
                        help="current docs root name, e.g. mkt_docs")
    gp_mig.add_argument("--to", dest="to_dir", default=DEFAULT_DOCS_DIR,
                        help=f"target docs root name (default: {DEFAULT_DOCS_DIR})")
    gp_mig.add_argument("--apply", action="store_true",
                        help="actually copy (default is a dry run; never deletes)")

    mp = sub.add_parser("mark", parents=[common], help="record paths as ANALYZED")
    mp.add_argument("paths", nargs="+", help="paths relative to the project root")
    mp.add_argument("--note", help="also write a dated entry in audit/project_notes.md "
                                   "(a release, work outside an open unit)")
    gp = sub.add_parser("gate", parents=[common, hybrid_opt], help="PreToolUse hook (exit 2 = block)")
    gp.add_argument("--hook", action="store_true", help="read the hook JSON payload from stdin")
    gp.add_argument("--file", help="file path to evaluate (alternative to --hook)")
    gp.add_argument("--protected", default="", help="protected prefixes separated by ';' (e.g. \"src/auth;src/crypto\")")

    vp = sub.add_parser("verdict", parents=[common],
                        help="PreToolUse hook: refuse an edit with no router verdict "
                             "or an unread named guide (fail-open, always exit 0)")
    vp.add_argument("--hook", action="store_true", help="read the hook JSON payload from stdin")

    cp = sub.add_parser("constraints", parents=[common],
                        help="print the constraints an ANALYSIS states in extractable "
                             "form: a unit's view, or those bound to a file")
    cg = cp.add_mutually_exclusive_group(required=True)
    cg.add_argument("--unit", help="unit id (e.g. F-001) or ANALYSIS file name")
    cg.add_argument("--file", help="file path: constraints of the open L3 code units bound to it")
    cg.add_argument("--hook", action="store_true",
                    help="PreToolUse hook: read the payload from stdin, print context only "
                         "(fail-open, always exit 0)")

    sub.add_parser("benefit", parents=[common],
                   help="report what the review gates caught (and what the "
                        "doctrine costs to read) -- a report, never a gate: "
                        "always exits 0")

    sub.add_parser("orient", parents=[common, hybrid_opt],
                   help="SessionStart hook: emit docs-root orientation to stdout (fail-open, zero-execution)")

    sub.add_parser("remind", parents=[common],
                   help="UserPromptSubmit hook: print the constant per-turn line "
                        "(fail-open, zero-read, zero-execution)")

    pp = sub.add_parser("plan", parents=[common],
                        help="Subagent Execution: validate/brief a PLAN_[feature].md (zero-execution)")
    pp_sub = pp.add_subparsers(dest="plan_cmd", required=True)
    pv = pp_sub.add_parser("validate", help="schema + confinement + ledger cross-check (exit 2 on error)")
    pv.add_argument("file", help="path to the PLAN_[feature].md file")
    pb = pp_sub.add_parser("brief", help="print a task's brief to stdout (verify text is NOT executed)")
    pb.add_argument("file", help="path to the PLAN_[feature].md file")
    pb.add_argument("--task", required=True, help="task id to brief")

    args = ap.parse_args(argv)

    # F-085: the edit hooks resolve their root and docs root from the edited file
    # (the hook runs in whatever directory the session moved to), so they are
    # dispatched before the working-directory resolution below.
    if args.cmd == "constraints" and args.hook:
        return cmd_constraints_hook(args)
    if args.cmd == "verdict":
        return cmd_verdict(args)
    if args.cmd == "gate":
        return cmd_gate(args)

    # Resolve the documentation root ONCE, before any command runs, so every
    # surface -- paths, messages, generated headers, the gate's exempt prefix --
    # names the same thing.
    try:
        discovered, name = resolve_docs_dir(args, getattr(args, "root", None))
    except AmbiguousDocsRoot as exc:
        if args.cmd == "migrate":
            # A tree with two roots is not an obstacle to `migrate`: it is the state
            # `migrate` exists to resolve, and both names come from --from/--to, so
            # nothing is being guessed. Refusing here would make the guard block the
            # one command that ends the ambiguity.
            discovered, name = None, args.from_dir
        elif args.cmd in ("orient", "remind"):
            # The SessionStart hook is fail-open by contract: it must never block a
            # session, not even on a half-migrated tree. It orients on the default
            # and says so rather than exiting non-zero.
            print(f"[note] {exc}")
            discovered, name = None, DEFAULT_DOCS_DIR
        else:
            print(f"[ERROR] {exc}")
            return 1
    set_docs_dir(name)

    if args.cmd == "orient":
        return cmd_orient(args)
    if args.cmd == "remind":
        return cmd_remind(args)

    root = Path(args.root).resolve() if args.root else (discovered or find_project_root())
    if args.cmd == "check":
        return cmd_check(root, strict=args.strict, hybrid=args.hybrid)
    if args.cmd == "validate":
        return cmd_validate(root, strict=args.strict, hybrid=args.hybrid)
    if args.cmd == "index":
        return cmd_index(root)
    if args.cmd == "stale":
        return cmd_stale(root, hybrid=args.hybrid)
    if args.cmd == "mark":
        return cmd_mark(root, args.paths, args.note)
    if args.cmd == "benefit":
        return cmd_benefit(root)
    if args.cmd == "constraints":
        return cmd_constraints(root, args)
    if args.cmd == "migrate":
        return cmd_migrate(root, args)
    if args.cmd == "plan":
        return cmd_plan(root, args)
    return 0


if __name__ == "__main__":
    sys.exit(main())
