import re
#!/usr/bin/env python3
"""
We The People Platform — Audit Script

Implements the standard four-phase harden cycle audit per the procedure codified
in item 80 (Iterative Hardening Process Documentation). Provides a reproducible,
canonical implementation of the audit logic that has been refined across the
hardening cycle's iterations.

Usage:
    python3 audit_script.py [package_root]
    
If package_root is omitted, uses the script's parent directory.

Requirements:
    - Python 3.8+
    - python-docx package (pip install python-docx)

Outputs:
    Console report categorizing findings as:
        SIG  Significant — blocks the iteration; must be fixed
        MIN  Minor — should be fixed in current iteration
        OBS  Observation — audit-script note, not a content finding

Audit-script improvement candidates addressed in this implementation:
    1. Narrative-block literal-text detection (from iteration 19) —
       implemented in audit_narrative_locations(), checks current-iteration
       narratives for literal patterns that match audit detection patterns
    2. Section self-check heuristic harmonization (from iteration 26) —
       implemented in audit_section_self_check(), applies the same
       [HISTORICAL] heuristic as the full sweep
    3. Anchored regex for whitelist entry detection (from iteration 33) —
       implemented in parse_whitelist(), uses ^TEXT_START$ regex on each
       line rather than substring match across the whole block

This script should be run once per iteration during Phase 1 (Audit) of the
codified harden cycle procedure.
"""

import os
import sys
import json
import glob
from pathlib import Path

# v3.7.588: force UTF-8 stdout/stderr so Unicode in the audit's own output (e.g.
# the "->" arrow in the Pillar-reference check) doesn't crash on a Windows cp1252
# console. .reconfigure() is Python 3.7+ and may be absent on redirected/non-tty
# streams, so guard it. (Mirrors the guard in tools/deploy_to_github.py.)
for _stream in (sys.stdout, sys.stderr):
    try:
        _stream.reconfigure(encoding="utf-8")
    except (AttributeError, OSError):
        pass

try:
    from docx import Document
except ImportError:
    print("=" * 72, file=sys.stderr)
    print("ERROR: python-docx package not installed", file=sys.stderr)
    print("=" * 72, file=sys.stderr)
    print("", file=sys.stderr)
    print("This script needs python-docx to read .docx files. Install with:", file=sys.stderr)
    print("", file=sys.stderr)
    print("    pip install python-docx", file=sys.stderr)
    print("", file=sys.stderr)
    print("(Use 'pip3' instead of 'pip' if needed. If you get an", file=sys.stderr)
    print("'externally-managed-environment' error on Linux, try:", file=sys.stderr)
    print("    pip install --user python-docx", file=sys.stderr)
    print("or use a virtual environment.)", file=sys.stderr)
    print("=" * 72, file=sys.stderr)
    sys.exit(2)


# === WHITELIST PARSING ===

# ============================================================================
# v3.7.90 — Audit-cache layer (item 6 of v3.7.78 review)
#
# Caches file reads across check functions so each file is read at most once
# per audit run, even if multiple checks consume it. Previously the catalog
# was loaded 6× per audit, site HTML pages re-parsed 5×, etc.
#
# Accessors are lazy: first call loads, subsequent calls return cached value.
# Behavior change: NONE. Same checks, same findings, same output.
# Performance gain: ~50% faster audit runs (15s → ~8s on this hardware).
# ============================================================================

_audit_catalog_cache = None
_audit_docx_cache = {}
_audit_text_cache = {}
_audit_all_docx_paths_cache = None
_audit_site_html_cache = None

def get_catalog():
    """Load platform_catalog.json once, return cached on subsequent calls."""
    global _audit_catalog_cache
    if _audit_catalog_cache is None:
        import json as _json
        try:
            with open("00_GUI_Files/platform_catalog.json", encoding="utf-8", errors="replace") as f:
                _audit_catalog_cache = _json.load(f)
        except Exception:
            _audit_catalog_cache = {}
    return _audit_catalog_cache

def get_docx(path):
    """Open a docx via python-docx Document() once per path, return cached."""
    if path not in _audit_docx_cache:
        try:
            import os as _os
            if _os.path.basename(path).startswith("~$"):
                # v3.7.592: Office owner/lock files (~$*.docx) are not real
                # documents and cannot be parsed; treat as a clean None so
                # callers skip them instead of crashing.
                _audit_docx_cache[path] = None
            else:
                from docx import Document as _Document
                _audit_docx_cache[path] = _Document(path)
        except Exception:
            _audit_docx_cache[path] = None
    return _audit_docx_cache[path]

def get_text_file(path):
    """Read a text file once per path, return cached content."""
    if path not in _audit_text_cache:
        try:
            with open(path, encoding="utf-8", errors="replace") as f:
                _audit_text_cache[path] = f.read()
        except Exception:
            _audit_text_cache[path] = ""
    return _audit_text_cache[path]



def get_combined_css_for_page(page_path):
    """v3.7.104: Return concatenated CSS for a page, including:
    - All inline <style> blocks
    - All linked stylesheets (<link rel="stylesheet" href="...">) that point
      to local files (not external URLs)
    Used by CSS audit checks so the shared-CSS architecture is recognized.
    """
    import os, re
    if not os.path.exists(page_path):
        return ""
    try:
        c = get_text_file(page_path)
    except Exception:
        with open(page_path, encoding="utf-8", errors="replace") as f: c = f.read()
    # Inline styles
    inline = "\n".join(re.findall(r'<style[^>]*>(.*?)</style>', c, re.DOTALL))
    # Linked stylesheets (local files only)
    # v3.7.325: regex accepts any attribute order between <link and href= so
    # that <link rel="stylesheet" id="X" href="..."> (post-CSS-externalization
    # form with id preserved for traceability) matches too. Also resolves
    # absolute paths (/wtpp-btn-system.css) as relative to the package root
    # rather than the filesystem root.
    linked_parts = []
    page_dir = os.path.dirname(page_path)
    for m in re.finditer(r'<link\b[^>]*\brel="stylesheet"[^>]*\bhref="([^"]+)"', c):
        href = m.group(1)
        if href.startswith('http') or href.startswith('//'):
            continue
        # v3.7.329: strip ?v=<version> query string before existence
        # check. Without this, cache-busted hrefs like
        # /wtpp-btn-system.css?v=3.7.329 fail the existence check
        # (there's no file named "wtpp-btn-system.css?v=3.7.329")
        # and the auditor falsely believes the linked CSS is missing.
        clean_href = href.split('?')[0].split('#')[0]
        if clean_href.startswith('/'):
            css_path = clean_href.lstrip('/')
        else:
            css_path = os.path.normpath(os.path.join(page_dir, clean_href))
        if os.path.exists(css_path):
            try:
                with open(css_path, encoding="utf-8", errors="replace") as f: linked_parts.append(f.read())
            except Exception:
                pass
    return inline + "\n\n/* linked */\n\n" + "\n".join(linked_parts)

def get_all_docx_paths():
    """Walk the package once, return all .docx paths (excludes _web_html and archives)."""
    global _audit_all_docx_paths_cache
    if _audit_all_docx_paths_cache is None:
        import os as _os
        paths = []
        for root, dirs, files in _os.walk("."):
            if any(x in root for x in ["_web_html", "_downloads", "__pycache__", "_data_archive", ".git", "_audio"]):
                continue
            for f in files:
                if f.endswith(".docx"):
                    paths.append(_os.path.join(root, f).lstrip("./"))
        _audit_all_docx_paths_cache = paths
    return _audit_all_docx_paths_cache

def get_site_html_pages():
    """Read all 7 site HTML pages once, return dict page_name → content."""
    global _audit_site_html_cache
    if _audit_site_html_cache is None:
        pages = ["index.html", "about.html", "contact.html", "privacy.html",
                 "downloads.html", "platform_index.html", "sla.html"]
        _audit_site_html_cache = {p: get_text_file(p) for p in pages}
    return _audit_site_html_cache

def reset_audit_caches():
    """Clear all caches (used in testing / sanity-tests)."""
    global _audit_catalog_cache, _audit_all_docx_paths_cache, _audit_site_html_cache
    _audit_catalog_cache = None
    _audit_docx_cache.clear()
    _audit_text_cache.clear()
    _audit_all_docx_paths_cache = None
    _audit_site_html_cache = None


def get_all_package_files(extension):
    """One os.walk of the package, returning files with the given extension.

    Caches per extension to avoid repeated traversals. Excludes _web_html,
    _downloads, __pycache__, _data_archive, .git, and microsimulation (the last
    is a bundled code asset — a standalone tool shipped with the package, not
    platform document/page content, so it is not subject to TOC/manifest checks).
    """
    import os as _os
    key = ".all_files_" + extension.lstrip(".")
    if key not in _audit_text_cache:
        results = []
        for root, dirs, files in _os.walk("."):
            if any(x in root for x in ["_web_html", "_downloads", "__pycache__", "_data_archive", ".git", "microsimulation", "_audio"]):
                continue
            for f in files:
                if f.endswith(extension) and not f.startswith("~$"):  # v3.7.592: ignore Office lock files
                    results.append(_os.path.join(root, f).lstrip("./"))
        _audit_text_cache[key] = results
    return _audit_text_cache[key]


def parse_whitelist(filepath):
    """Parse audit_whitelist.txt into list of entry dicts.
    
    Uses anchored regex (^TEXT_START$ on its own line) to identify entries,
    avoiding false positives from documentation header text that mentions
    'TEXT_START' as part of format documentation.
    
    Returns list of {file, category, reason, stability, added, text} dicts.
    """
    if not os.path.exists(filepath):
        return []
    
    content = get_text_file(filepath)  # v3.7.90 cached
    
    entries = []
    blocks = content.split("#####")
    for block in blocks:
        # Use anchored regex to find TEXT_START on its own line
        # (multiline mode; matches as line content, not substring)
        if not re.search(r'^TEXT_START$', block, re.MULTILINE):
            continue
        
        file_match = re.search(r'^FILE:\s*(.+)$', block, re.MULTILINE)
        cat_match = re.search(r'^CATEGORY:\s*(.+)$', block, re.MULTILINE)
        reason_match = re.search(r'^REASON:\s*(.+?)$', block, re.MULTILINE)
        stab_match = re.search(r'^STABILITY:\s*(.+)$', block, re.MULTILINE)
        added_match = re.search(r'^ADDED:\s*(.+)$', block, re.MULTILINE)
        text_match = re.search(r'^TEXT_START$\n(.*?)\n^TEXT_END$', block, re.DOTALL | re.MULTILINE)
        
        scope_match = re.search(r'^SCOPE:\s*(.+)$', block, re.MULTILINE)
        if file_match and text_match:
            entries.append({
                'scope': scope_match.group(1).strip().lower() if scope_match else 'paragraph',
                'file': file_match.group(1).strip(),
                'category': cat_match.group(1).strip() if cat_match else '',
                'reason': reason_match.group(1).strip() if reason_match else '',
                'stability': stab_match.group(1).strip() if stab_match else '',
                'added': added_match.group(1).strip() if added_match else '',
                'text': text_match.group(1)
            })
    return entries


def normalize_version_bumped_text(text):
    """Normalize text for version-bumped whitelist matching.
    
    Replaces version patterns (vN.N or vN.N.N) with a wildcard placeholder
    and strips trailing 'Updated for v...' suffixes that accumulate across
    routine version bumps. This allows whitelist entries marked
    STABILITY: version-bumped to remain valid across version bumps without
    requiring whitelist edits each iteration.
    
    Introduced in v2.30.41 to address recurring whitelist maintenance burden
    on iterations that bump Item 80's version line.
    """
    import re as _re
    # Replace version patterns with placeholder
    normalized = _re.sub(r'\bv\d+\.\d+(?:\.\d+)?\b', 'vN', text)
    # Strip from the first "· Updated" onwards (keeps the Created clause and
    # earlier stable content; removes routine update suffixes)
    normalized = _re.sub(r'\s*\u00B7\s*Updated.*$', '', normalized)
    return normalized.strip()


def is_paragraph_whitelisted(file_path, paragraph_text, whitelist_entries):
    """Check if paragraph matches any whitelist entry for this file.
    
    Matching strategies:
    1. Exact text match (default for all entries)
    2. Version-bumped normalization (only for entries with STABILITY: version-bumped)
       — strips version numbers and trailing 'Updated for v...' clauses before
       comparing, making the match robust to routine version bumps.
    """
    fname = file_path.replace("\\", "/").split("/")[-1]  # v3.7.593: handle Windows backslash paths
    para_normalized = paragraph_text.strip()
    for entry in whitelist_entries:
        if entry['file'] != fname:
            continue
        # Strategy 0 (v3.8.251): WHOLE-DOCUMENT SCOPE, for historical records.
        # A changelog is a record of what was believed at each release; judging its
        # entries against today's figures would mark true history as false.
        # Paragraph-level whitelisting cannot express that -- the package version
        # document is 236,000 words across 548 version entries, and enumerating them
        # as exact text would put a second copy of the document inside the whitelist.
        # THE AUTHOR'S RULING, v3.8.251: documents produced for public consumption go
        # through all audit checks; a changelog may be exempted from most of them; and
        # IT IS NOT REMOVED, because the platform is a complete encapsulation of the
        # work, downloadable and reviewable by anyone.
        # THE EXEMPTION IS DECLARED, NOT SILENT: check_historical_exemption requires a
        # recorded reason AND a visible banner in the document itself.
        if entry.get('scope') == 'whole-document':
            return True, entry
        # Strategy 1: exact match
        if entry['text'].strip() == para_normalized:
            return True, entry
        # Strategy 2: version-bumped normalized match
        if entry.get('stability', '').lower() == 'version-bumped':
            if normalize_version_bumped_text(entry['text']) == normalize_version_bumped_text(paragraph_text):
                return True, entry
    return False, None


# === HISTORICAL HEURISTIC ===

HISTORICAL_KEYWORDS = [
    "occurrence", "recurred", "across the cycle", "ten prior", "eleven times",
    "twenty-seven", "twenty-eight", "twenty-nine", "thirty",
    "thirty-one", "thirty-two", "thirty-three", "thirty-four",
    "iter 21", "iter 18", "iter 19", "iteration 22's",
    "eleventh occurrence", "tenth occurrence",
    "documented eleven", "recurred eleven",
    "previous", "old", "changed from", "predates", "pre-",
    "before open-1", "earlier formulation", "stale",
    "the older simplified", "outdated",
]


def is_paragraph_historical(paragraph_text):
    """Apply [HISTORICAL] heuristic: paragraph contains keywords indicating
    it documents historical context rather than asserting a current claim."""
    ctx = paragraph_text.lower()
    return any(kw in ctx for kw in HISTORICAL_KEYWORDS)


# === DOCUMENT LOADING ===

def load_all_docs(package_root):
    """Load all .docx files from package, returning {path: full_text} dict."""
    all_docs = {}
    for root, dirs, files in os.walk(package_root):
        for f in files:
            if f.endswith(".docx"):
                path = os.path.relpath(os.path.join(root, f), package_root)
                try:
                    doc = get_docx(os.path.join(root, f))
                    text = "\n".join(p.text for p in doc.paragraphs)
                    for t in doc.tables:
                        for r in t.rows:
                            for c in r.cells:
                                text += "\n" + c.text
                    all_docs[path] = text
                except Exception:
                    pass
    return all_docs


# === STANDARD CHECKS ===

def audit_cross_references(all_docs, valid_range=(1, 81)):
    """Check that all 'item N' references fall in valid range."""
    findings = []
    all_refs = set()
    for path, text in all_docs.items():
        for m in re.finditer(r'item\s+(\d+)\b', text):
            all_refs.add(int(m.group(1)))
    invalid = [n for n in all_refs if n < valid_range[0] or n > valid_range[1]]
    if invalid:
        findings.append(("SIG", "INVALID-REF", "various", f"Invalid item refs: {invalid}"))
    return findings, len(all_refs), invalid


def audit_manifest_integrity(package_root, pv_doc):
    """Check that all package files appear in the Package Version doc manifest."""
    findings = []
    all_files = []
    for root, dirs, files in os.walk(package_root):
        # Skip _web_html (generated deployment artifacts) and __pycache__
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
        for f in files:
            if any(f.endswith(ext) for ext in [".docx", ".html", ".pptx", ".pdf", ".csv", ".xlsx"]) and not f.startswith("~$"):  # v3.7.592: ignore Office lock files
                all_files.append(f)
    
    manifest_filenames = set()
    for table in pv_doc.tables:
        for row in table.rows:
            if len(row.cells) >= 4:
                text = row.cells[0].text
                for line in text.split("\n"):
                    line = line.strip()
                    if line and any(line.endswith(ext) for ext in [".docx", ".html", ".pptx", ".pdf", ".csv", ".xlsx"]):
                        manifest_filenames.add(line)
    
    # v3.7.241: design system verification page intentionally excluded
    # from PV manifest (it's a tool, not a platform document)
    # v3.7.555: third Gemini scoping review (Jun 12, 2026). Filed in
    # 07_External_Reviews and tracked authoritatively in the External Review
    # Register (Kind E); intentionally not registered as a numbered catalog
    # document. Surfacing it publicly later would add it to the catalog/TOC
    # and move the public document count from 126 to 127.
    MANIFEST_EXCLUDE = {"STATUS_REPORT.html",  # v3.8.513: private generated status report, not a package document
                        "style_guide.html", "ui_lexicon.html", "colorblind_simulation.html",
                        # v3.8.496: the author's own senator letter, private, same basis.
                        "02_Outreach_Constituent_Letter_Author.docx",
                        "02_Outreach_Tracker.xlsx",
                        # v3.8.18: private classroom handout. Catalogued with
                        # private:true and excluded from the Package Version
                        # manifest on the same basis as the outreach tracker: it is
                        # a working communication artifact rather than a numbered
                        # package document a reader is invited to review.
                        "02_Classroom_Handout_Grade6.html",
                        # v3.8.132: second handout series, same private basis --
                        # a working communication artifact, not a numbered
                        # package document a reader is invited to review.
                        "02_Classroom_Handout_HowToCheckANumber_v1.html",
                        # v3.7.727: Audio Companions — auxiliary site page (reading-path
                        # narrations), reached by direct link; a site page, not a numbered
                        # Package-Version document. Handled like downloads.html / share.html.
                        "audio.html",
                        # v3.8.130: Assumptions — auxiliary site page, generated by
                        # tools/build_assumptions_page.py from the assumptions registry.
                        # A site page reached by direct link, not a numbered Package-Version
                        # document. Handled like audio.html / downloads.html / share.html.
                        "assumptions.html",
                        "07_Gemini_Review_of_v3_7_550.pdf",
                        # v3.7.726: fourth Gemini scoping review (Jul 11, 2026; of the
                        # live v3.7.716 site). Catalog-listed and tracked in the External
                        # Review Register (Kind E), same as the prior reviews; not a
                        # numbered Package-Version-manifest document.
                        "07_Gemini_Review_of_v3_7_716.pdf"}
    orphans = [f for f in all_files if f not in manifest_filenames and f not in MANIFEST_EXCLUDE]
    if orphans:
        findings.append(("MIN", "MANIFEST-ORPHAN", "Package Version doc", f"Files not in manifest: {orphans}"))
    return findings, len(all_files), len(manifest_filenames), orphans


def audit_version_sync(pv_doc, expected_versions):
    """Check that manifest entries match expected per-doc versions."""
    findings = []
    for table in pv_doc.tables:
        for row in table.rows:
            cell0 = row.cells[0].text
            for fname, exp in expected_versions.items():
                if fname in cell0:
                    actual = row.cells[1].text.strip()
                    if actual != exp:
                        findings.append(("MIN", "VER-MISMATCH", fname, f"manifest={actual}, expected={exp}"))
    return findings


def audit_tracked_issues_count_drift(package_root):
    """Verify the OPEN tracked-issues count is in sync across the three
    places that publish it:

      (a) OIR table 0 'Current Status' column starts with 'OPEN:'
      (b) manifest.json totals.tracked_issues.open
      (c) build_site_header.py constant TRACKED_ISSUES_OPEN

    Added v3.7.415 after a near-miss in v3.7.414 where the OPEN count
    was almost mis-derived (joining all row cells and matching 'OPEN'
    anywhere picks up the word inside descriptions of CLOSED items).
    The correct count is the number of rows whose Current Status cell
    text starts with 'OPEN'. This audit operationalizes that source-
    of-truth choice.

    Severity: MIN. Drift is a real consistency bug but doesn't break
    rendering.
    """
    findings = []

    # (a) Authoritative count from OIR table
    oir_path = os.path.join(package_root, "09_Meta_Tracking",
                             "09_Open_Issues_Registry.docx")
    try:
        oir = get_docx(oir_path)
    except Exception:
        return findings  # OIR not present; nothing to check
    if not oir.tables:
        return findings
    tbl = oir.tables[0]
    if len(tbl.rows) < 2 or len(tbl.rows[0].cells) < 3:
        return findings

    oir_open_count = 0
    oir_closed_count = 0
    for row in tbl.rows[1:]:
        status = row.cells[2].text.strip().upper()
        if status.startswith("OPEN"):
            oir_open_count += 1
        elif status.startswith("CLOSED"):
            oir_closed_count += 1

    # (b) manifest.json count
    manifest_open = None
    manifest_closed = None
    manifest_as_of = None
    manifest_path = os.path.join(package_root, "manifest.json")
    if os.path.exists(manifest_path):
        try:
            import json as _json
            with open(manifest_path, "r", encoding="utf-8") as f:
                m = _json.load(f)
            ti = m.get("totals", {}).get("tracked_issues", {}) or {}
            manifest_open = ti.get("open")
            manifest_closed = ti.get("closed")
            manifest_as_of = ti.get("as_of_version")
        except Exception:
            pass

    # (c) build_site_header.py constant
    bsh_open = None
    bsh_closed = None
    bsh_path = os.path.join(package_root, "build_site_header.py")
    if os.path.exists(bsh_path):
        try:
            with open(bsh_path, "r", encoding="utf-8") as f:
                bsh = f.read()
            m_open = re.search(r'"TRACKED_ISSUES_OPEN"\s*:\s*"(\d+)"', bsh)
            m_closed = re.search(r'"TRACKED_ISSUES_CLOSED"\s*:\s*"(\d+)"', bsh)
            if m_open:
                bsh_open = int(m_open.group(1))
            if m_closed:
                bsh_closed = int(m_closed.group(1))
        except Exception:
            pass

    # Compare
    if manifest_open is not None and manifest_open != oir_open_count:
        findings.append((
            "MIN", "TRACKED-ISSUES-COUNT-DRIFT", "manifest.json",
            f"manifest.json totals.tracked_issues.open={manifest_open} "
            f"but OIR table has {oir_open_count} OPEN items "
            f"(as_of_version={manifest_as_of!r}; update both to match)"
        ))
    if bsh_open is not None and bsh_open != oir_open_count:
        findings.append((
            "MIN", "TRACKED-ISSUES-COUNT-DRIFT", "build_site_header.py",
            f"build_site_header.py TRACKED_ISSUES_OPEN={bsh_open} "
            f"but OIR table has {oir_open_count} OPEN items "
            f"(this constant drives every page's header injection)"
        ))
    if manifest_closed is not None and manifest_closed != oir_closed_count:
        findings.append((
            "MIN", "TRACKED-ISSUES-COUNT-DRIFT", "manifest.json",
            f"manifest.json totals.tracked_issues.closed={manifest_closed} "
            f"but OIR table has {oir_closed_count} CLOSED items"
        ))
    if bsh_closed is not None and bsh_closed != oir_closed_count:
        findings.append((
            "MIN", "TRACKED-ISSUES-COUNT-DRIFT", "build_site_header.py",
            f"build_site_header.py TRACKED_ISSUES_CLOSED={bsh_closed} "
            f"but OIR table has {oir_closed_count} CLOSED items"
        ))

    return findings


def audit_rendered_mirror_header_counts(package_root):
    """v3.7.661: Verify rendered _web_html mirror headers show the CURRENT
    open tracked-issues count. Closes the blind spot where build_web_html
    skips unchanged mirrors, freezing stale counts in doc-page headers even
    though the source constants (checked elsewhere) are correct. Fix is a
    clean _web_html regeneration. Severity MIN (display drift)."""
    import glob as _glob
    findings = []
    mpath = os.path.join(package_root, "manifest.json")
    if not os.path.exists(mpath):
        return findings
    try:
        with open(mpath, encoding="utf-8") as f:
            m = json.load(f)
        exp_open = m.get("totals", {}).get("tracked_issues", {}).get("open")
    except Exception:
        return findings
    if exp_open is None:
        return findings
    bad = {}
    for mf in _glob.glob(os.path.join(package_root, "_web_html", "**", "*.html"), recursive=True):
        try:
            txt = open(mf, encoding="utf-8").read()
        except Exception:
            continue
        mo = re.search(r"recruit\.html[^>]*>\s*(\d+)\s*open", txt)
        if mo and int(mo.group(1)) != exp_open:
            bad[mo.group(1)] = bad.get(mo.group(1), 0) + 1
    if bad:
        findings.append((
            "MIN", "MIRROR-HEADER-COUNT-DRIFT", "_web_html",
            f"rendered doc-page headers show open-count {dict(bad)} but manifest "
            f"open={exp_open}; run a clean _web_html regeneration (rm -rf _web_html "
            f"then build_web_html.py --refresh-content)"
        ))
    return findings


def audit_important_hardcoded_color_combinations(package_root):
    """v3.7.417 \u2014 Detect CSS declarations combining `!important` with a
    hardcoded color value (not a `var()` reference).

    v3.7.420 refinement: programmatic KEEP-pattern exclusions + explicit
    allowlist for deferred REVIEW items + severity upgrade OBS \u2192 MIN.

    The pattern caught: a rule like `color: #1a1814 !important;` or
    `background: rgba(255,255,255,0.9) !important;` defeats the theme-
    aware token system. When the page switches to dark mode, the `var(--X)`-
    based rules apply the dark-mode override, but this hardcoded rule
    overrides them due to `!important`, causing the light-mode color
    (or whatever was hardcoded) to persist in dark mode \u2014 the silent-
    dysfunction class that took multiple iterations to surface in earlier
    bug-hunts.

    Scope: scans external .css files (incl _templates/*.css) AND inline
    `<style>` blocks in top-level *.html, 06_Presentation_Materials/*.html,
    and bots/*.html and bots/**/*.html. Skips _web_html.

    KEEP-pattern programmatic exclusions (added v3.7.420; expanded v3.7.421):
    A finding is auto-excluded if its context matches any of:
      (1) Selector includes `html[data-theme="dark"]` \u2014 the rule IS the
          dark-mode override (theme-branched by selector)
      (2) Rule is inside `@media (prefers-color-scheme: dark)` \u2014 auto
          dark variant
      (3) Selector includes `data-tone=` \u2014 tone-branched override
      (4) Rule is inside `@media print` \u2014 print is always light;
          theme variation not applicable
      (5) File is wtpp-v310-active-contrast.css \u2014 explicitly named for
          a11y-priority active-state contrast; defeats theme by design
      (6) File is wtpp-v277-active-paragraph-highlight.css or
          wtpp-v279-active-paragraph-blue.css \u2014 reading-position
          highlights are theme-neutral for accessibility
      (7) File is wtpp-v238-fixes.css or wtpp-v292-theme-tone-fixes.css
          \u2014 header overlay gradient files have paired light/dark rules
      (8) Selector includes tricolor-band/flag-bg/flag-overlay \u2014 flag
          rendering requires exact red/white/blue
      (9) Selector includes 'tts-bar' AND property is a shadow \u2014 depth
          shadow rgba black/white is not color-as-content
      (10) File is 06_Platform_Architecture.html \u2014 architecture diagram
           needs exact colors regardless of theme

    These patterns are determined from the WTPP_Important_Hardcoded_Color_
    Categorization document (v3.7.418) which categorized 38 of 68 baseline
    findings as KEEP. v3.7.419 then tokenized 26 of the 30 REVIEW findings
    (search-input bucket), leaving 6 deferred REVIEW items.

    Allowlist (added v3.7.420):
    Six explicit (source, prop, value) signatures representing deferred
    REVIEW items that are documented as known technical debt but not
    scheduled for remediation. They remain on the allowlist until either
    remediated (allowlist entry removed) or formally categorized as
    intentional (moved to KEEP patterns). See
    WTPP_Important_Hardcoded_Color_Categorization v3.7.418 for context.

    Severity: MIN (upgraded v3.7.420). At v3.7.417 launch this shipped
    as OBS because the audit was a one-time inventory \u2014 most findings
    were intentional. After three iterations of categorization and
    cleanup (v3.7.418-420), the audit is now a regression guard: any
    NEW !important + hardcoded color combination not matching a KEEP
    pattern and not on the allowlist is a real consistency bug worth
    flagging at MIN severity.
    """
    findings = []

    COLOR_PROPS = {
        'color', 'background', 'background-color',
        'border', 'border-color',
        'border-top', 'border-bottom', 'border-left', 'border-right',
        'border-top-color', 'border-bottom-color',
        'border-left-color', 'border-right-color',
        'outline', 'outline-color',
        'fill', 'stroke',
        'box-shadow', 'text-shadow',
        'caret-color', 'accent-color',
        'column-rule', 'column-rule-color',
    }
    NAMED_COLORS = (
        'red', 'blue', 'green', 'black', 'white', 'gray', 'grey',
        'navy', 'gold', 'silver', 'maroon', 'olive', 'purple',
        'teal', 'aqua', 'fuchsia', 'lime', 'orange', 'pink', 'brown',
        'beige', 'cyan', 'magenta',
    )
    HEX_RE = re.compile(r'#[0-9a-fA-F]{3,8}\b')
    RGB_RE = re.compile(r'\brgba?\s*\(', re.IGNORECASE)
    HSL_RE = re.compile(r'\bhsla?\s*\(', re.IGNORECASE)
    NAMED_RES = [re.compile(rf'\b{n}\b', re.IGNORECASE) for n in NAMED_COLORS]
    DECL_RE = re.compile(
        r'([a-zA-Z\-]+)\s*:\s*([^;{}]*?!important[^;{}]*?)\s*(?:;|(?=\}))',
        re.IGNORECASE
    )

    # KEEP-pattern files (whole-file exclusions)
    KEEP_FILES = {
        'wtpp-v310-active-contrast.css',
        'wtpp-v277-active-paragraph-highlight.css',
        'wtpp-v279-active-paragraph-blue.css',
        'wtpp-v238-fixes.css',
        'wtpp-v292-theme-tone-fixes.css',
        '06_Presentation_Materials/06_Platform_Architecture.html',
    }

    # Allowlist of deferred REVIEW items.
    # v3.7.418-420 created this allowlist with 6 entries for documented
    # technical debt not yet remediated. v3.7.421 remediated all 6:
    #   \u2022 5 via tokenization or template fix (entries removed)
    #   \u2022 1 (CALC-OTHER inline-style-attribute patch) reclassified to
    #     KEEP via new programmatic rule (see _is_keep_pattern below)
    # The allowlist is preserved as an empty set for future use if any
    # genuinely-deferred items emerge.
    DEFERRED_ALLOWLIST = set()

    def _has_color_literal(value):
        if HEX_RE.search(value):
            return True
        if RGB_RE.search(value):
            return True
        if HSL_RE.search(value):
            return True
        for nre in NAMED_RES:
            if nre.search(value):
                return True
        return False

    def _find_rule_selector(text, decl_pos):
        """Return the selector preceding this declaration's rule open-brace."""
        open_brace = text.rfind('{', 0, decl_pos)
        if open_brace < 0:
            return ''
        prev_close = text.rfind('}', 0, open_brace)
        if prev_close < 0:
            prev_close = 0
        sel = text[prev_close + 1:open_brace].strip()
        return ' '.join(sel.split())[-200:]

    def _find_media_wrapper(text, decl_pos):
        """Detect if declaration is inside an @media block; return the
        @media query text if so, empty string otherwise."""
        depth = 0
        i = decl_pos - 1
        while i > 0:
            c = text[i]
            if c == '}':
                depth += 1
            elif c == '{':
                if depth == 0:
                    back = max(0, i - 200)
                    snip = ' '.join(text[back:i].split())
                    if '@media' in snip:
                        m = re.search(r'@media[^{}]*$', snip)
                        if m:
                            return m.group(0).strip()
                    depth = 0
                else:
                    depth -= 1
            i -= 1
        return ''

    def _is_keep_pattern(source, selector, media, prop):
        """Return True if this finding matches a KEEP-pattern auto-exclusion."""
        # File-level exclusions
        if source in KEEP_FILES:
            return True
        # Selector-based exclusions
        if 'data-theme="dark"' in selector:
            return True
        if 'data-tone=' in selector:
            return True
        if 'tricolor-band' in selector or 'flag-bg' in selector or 'flag-overlay' in selector:
            return True
        # Media-based exclusions
        if 'prefers-color-scheme: dark' in media:
            return True
        if '@media print' in media:
            return True
        # Property + selector combination exclusions
        if 'tts-bar' in selector and 'shadow' in prop:
            return True
        # Inline-style-attribute-override rules (v3.7.421): selectors that
        # target elements via [style*="..."] are correcting hardcoded inline
        # styles on HTML elements (typically accessibility-priority overrides
        # that boost contrast on broken inline styles). Theme-stable by
        # necessity since they react to inline-style attribute values that
        # exist regardless of theme.
        if 'style*=' in selector:
            return True
        return False

    def _scan(css_text, source):
        for m in DECL_RE.finditer(css_text):
            prop = m.group(1).lower()
            value = m.group(2)
            if 'var(' in value:
                continue
            if prop not in COLOR_PROPS:
                continue
            if not _has_color_literal(value):
                continue
            value_clean = re.sub(r'\s+', ' ', value).strip()

            # KEEP-pattern exclusion
            selector = _find_rule_selector(css_text, m.start())
            media = _find_media_wrapper(css_text, m.start())
            if _is_keep_pattern(source, selector, media, prop):
                continue

            # Allowlist exclusion
            if (source, prop, value_clean) in DEFERRED_ALLOWLIST:
                continue

            # Format display value
            value_display = value_clean
            if len(value_display) > 70:
                value_display = value_display[:67] + '...'

            findings.append((
                "MIN", "IMPORTANT-HARDCODED-COLOR", source,
                f"`{prop}: {value_display}` uses !important with a hardcoded "
                f"color value (no var()) \u2014 defeats theme-aware token system "
                f"in dark mode. Not matching any KEEP pattern (theme-branched, "
                f"print, a11y-priority, flag, diagram) and not on the deferred "
                f"allowlist; treat as new technical debt"
            ))

    # Scan external CSS files
    for cssf in (glob.glob(os.path.join(package_root, '*.css')) +
                 glob.glob(os.path.join(package_root, '_templates', '*.css'))):
        try:
            with open(cssf, 'r', encoding='utf-8') as f:
                _scan(f.read(), os.path.relpath(cssf, package_root))
        except Exception:
            continue

    # Scan inline styles in HTML
    page_patterns = [
        os.path.join(package_root, '*.html'),
        os.path.join(package_root, '06_Presentation_Materials', '*.html'),
        os.path.join(package_root, 'bots', '*.html'),
        os.path.join(package_root, 'bots', '**', '*.html'),
    ]
    pages_seen = set()
    for pat in page_patterns:
        for ph in glob.glob(pat, recursive=True):
            if '_web_html' in ph or ph in pages_seen:
                continue
            pages_seen.add(ph)
            try:
                with open(ph, 'r', encoding='utf-8') as f:
                    html = f.read()
            except Exception:
                continue
            styles = "\n".join(
                re.findall(r'<style[^>]*>(.*?)</style>', html, re.DOTALL)
            )
            if styles:
                _scan(styles, os.path.relpath(ph, package_root))

    return findings


def audit_rendered_invariants(package_root):
    """v3.7.425 \u2014 Detect rendering regressions in built HTML pages and
    canonical CSS files. Lightweight alternative to full visual regression
    testing (which would require headless-browser infrastructure).

    Catches: missing critical CSS link references, missing required theme
    tokens, missing canonical class definitions, missing essential meta
    tags. Does NOT catch: actual layout breaks, font-loading issues,
    image rendering issues, browser-specific quirks (those require true
    visual regression with headless browsers, deferred to a future
    infrastructure project).

    Three categories of invariant checks:

    (1) Per-page CSS link inventory:
        Every top-level page should reference the platform's essential
        CSS files. If a page is missing wtpp-theme-styles.css, the theme
        breaks. If it's missing wtpp-btn-system.css, buttons lose
        styling. Etc. The check verifies REQUIRED_CSS_FILES are all
        referenced in each page's <link> tags.

    (2) Per-page essential meta tags:
        Every page should have og:image, og:title, viewport meta tags.
        Missing these silently degrades sharing and mobile rendering.

    (3) Canonical CSS file content integrity:
        Critical tokens (--paper, --ink, --red, --green, --red-bg) must
        be defined in wtpp-theme-styles.css. Critical classes
        (.wtpp-btn, .tricolor-band) must be defined in their canonical
        files. If any of these go missing (e.g., a refactor accidentally
        removes a token), the platform's rendering breaks visibly.

    Severity: OBS for first launch. Three category-3 audits before this
    started at OBS and upgraded to MIN after baseline cleanup; same
    pattern here.

    First-run finding count: 0 expected if all canonical assets are in
    place. The check is a regression guard for future asset drift.
    """
    findings = []

    # (1) Required CSS files \u2014 every top-level page should reference these
    REQUIRED_CSS_FILES = (
        'wtpp-theme-styles.css',
        'wtpp-site-header.css',
        'wtpp-btn-system.css',
        'wtpp-muted-palette.css',
    )

    # (2) Required meta tags \u2014 every shareable page should have these
    REQUIRED_META_PATTERNS = (
        (r'<meta\s+name=["\']viewport["\']', 'viewport'),
        (r'<meta\s+property=["\']og:image["\']', 'og:image'),
        (r'<meta\s+property=["\']og:title["\']', 'og:title'),
    )

    # (3) Required CSS file content \u2014 critical tokens and classes
    REQUIRED_CSS_CONTENT = (
        ('wtpp-theme-styles.css',  r'--paper:',     '--paper token'),
        ('wtpp-theme-styles.css',  r'--ink:',       '--ink token'),
        ('wtpp-theme-styles.css',  r'--red:',       '--red token'),
        ('wtpp-theme-styles.css',  r'--green:',     '--green token'),
        ('wtpp-muted-palette.css', r'--red-bg:',    '--red-bg token'),
        ('wtpp-btn-system.css',    r'\.wtpp-btn\b', '.wtpp-btn class'),
        ('wtpp-site-header.css',   r'\.tricolor-band\b',
                                                    '.tricolor-band class'),
    )

    # Pages to skip: noindex internal-reference pages don't follow the
    # standard CSS+meta invariants (style_guide.html is a self-contained
    # design reference with inline styles).
    NOINDEX_META_RE = re.compile(r'<meta\s+name=["\']robots["\'][^>]*noindex',
                                  re.IGNORECASE)

    # Pages to check (top-level only; calculators and bots have their own
    # link structures and aren't relevant to this check)
    SHARED_PAGES = sorted(glob.glob(os.path.join(package_root, '*.html')))

    # (1) Per-page CSS link inventory
    for ph in SHARED_PAGES:
        if '_web_html' in ph:
            continue
        try:
            with open(ph, 'r', encoding='utf-8') as f:
                html = f.read()
        except Exception:
            continue
        # Skip noindex internal-reference pages
        if NOINDEX_META_RE.search(html):
            continue
        rel = os.path.relpath(ph, package_root)
        missing_css = []
        for css_file in REQUIRED_CSS_FILES:
            if css_file not in html:
                missing_css.append(css_file)
        if missing_css:
            findings.append((
                "OBS", "RENDERED-INVARIANT", rel,
                f"page missing required CSS link references: "
                f"{', '.join(missing_css)}. These canonical CSS files "
                f"are essential for theme tokens, header styling, button "
                f"styling, and color palette. Pages missing them will "
                f"render with broken or fallback styling."
            ))

        # (2) Per-page essential meta tags
        missing_meta = []
        for pat, label in REQUIRED_META_PATTERNS:
            if not re.search(pat, html):
                missing_meta.append(label)
        if missing_meta:
            findings.append((
                "OBS", "RENDERED-INVARIANT", rel,
                f"page missing essential meta tags: {', '.join(missing_meta)}. "
                f"These meta tags affect social sharing previews (og:*) and "
                f"mobile rendering (viewport). Pages missing them degrade "
                f"silently \u2014 the page loads but appears broken when "
                f"shared or viewed on mobile."
            ))

    # (3) Canonical CSS file content integrity
    for css_file, pattern, label in REQUIRED_CSS_CONTENT:
        css_path = os.path.join(package_root, css_file)
        if not os.path.exists(css_path):
            findings.append((
                "OBS", "RENDERED-INVARIANT", css_file,
                f"canonical CSS file is missing entirely. Pages that "
                f"reference it will fail to load it (404), causing "
                f"styling to break."
            ))
            continue
        try:
            with open(css_path, 'r', encoding='utf-8') as f:
                css_text = f.read()
        except Exception:
            continue
        if not re.search(pattern, css_text):
            findings.append((
                "OBS", "RENDERED-INVARIANT", css_file,
                f"canonical content missing: {label} (pattern "
                f"`{pattern}` not found in file). The token/class is "
                f"referenced by many pages and other CSS files; missing "
                f"definition would cause silent rendering regression."
            ))

    return findings


def audit_js_clean_url_assumptions(package_root):
    """v3.7.423 \u2014 Detect JavaScript files that compare URLs against
    paths ending in `.html` without also handling Cloudflare Pages's
    clean-URL form (where /about.html is served at /about).

    The bug pattern (v3.7.405): a JS file checks
    `location.pathname === '/about.html'`, expecting the URL to include
    the .html extension. Cloudflare Pages serves the same content at
    `/about` (no extension), so the equality check fails and downstream
    behavior breaks (nav highlighting, active-page detection, recent-
    pages tracking, etc.).

    Canonical fix patterns observed in the codebase:
      \u2022 Extension stripping: `file.replace(/\\.html$/, '')` then
        compare against extension-less names (wtpp-nav-menu.js v3.7.405)
      \u2022 Multi-form check: `url === '/' || url === '/index.html' ||
        url === 'index.html' || url.endsWith('/index.html')`
        (wtpp-bookmark.js)
      \u2022 indexOf with extension-less search: `file.indexOf('Calculator')`
        which matches both `/Calculator.html` and `/Calculator`

    Audit heuristic:
      A JS file is FLAGGED if all of these are true:
        (a) Uses location.pathname / window.location / location.href
        (b) Has `.html` string literals in comparison contexts
            (===, !==, endsWith, indexOf)
        (c) Lacks ALL of these safety indicators:
            \u2022 `.replace(/.html/...)` extension-stripping pattern
            \u2022 Comparison against `'/'` (clean root URL form)
            \u2022 endsWith('.html') followed by `||` (multi-form fallback)
            \u2022 Both `'index'` and `'index.html'` literals (handles both
              extension-less and extension-bearing forms)

    Scope: external .js files at the package root only. Skips
    minified bundles, third-party libraries (none expected in the
    platform's current architecture), and test fixtures.

    Severity: OBS for first launch. Heuristic-based detection has
    edge cases; after confidence builds (no false positives over
    several iterations) severity can upgrade to MIN.

    First-run finding count: 0 expected. Platform has been disciplined
    about clean-URL handling since v3.7.405 fixed the original bug;
    this audit functions purely as a regression guard for future code.
    """
    findings = []

    # JS files at package root only
    js_files = sorted(glob.glob(os.path.join(package_root, '*.js')))

    # Patterns
    URL_USAGE_RE = re.compile(
        r'\b(?:location\.pathname|window\.location|location\.href)\b'
    )
    HTML_COMPARE_RE = re.compile(
        r"""(?:===|!==|==|!=|endsWith\s*\(|indexOf\s*\()\s*['"][^'"]*\.html['"]"""
    )
    HAS_NORMALIZE_RE = re.compile(r"\.replace\s*\(\s*[/'\"]\s*\\?\.html")
    HAS_ROOT_COMPARE_RE = re.compile(r"""===?\s*['"]/['"]""")
    HAS_MULTI_FORM_RE = re.compile(
        r"endsWith\s*\(\s*['\"]\.html['\"][^)]*\)\s*\|\|"
    )
    BARE_INDEX_RE = re.compile(r"['\"]index['\"]")
    INDEX_HTML_RE = re.compile(r"['\"]index\.html['\"]")

    for js_path in js_files:
        try:
            with open(js_path, 'r', encoding='utf-8') as f:
                text = f.read()
        except Exception:
            continue

        # (a) Does the file process URLs?
        if not URL_USAGE_RE.search(text):
            continue

        # (b) Does it have .html in comparison contexts?
        if not HTML_COMPARE_RE.search(text):
            continue

        # (c) Does it have ANY safety indicator?
        has_normalize = bool(HAS_NORMALIZE_RE.search(text))
        has_root_compare = bool(HAS_ROOT_COMPARE_RE.search(text))
        has_multi_form = bool(HAS_MULTI_FORM_RE.search(text))
        has_both_forms = bool(BARE_INDEX_RE.search(text)) and \
                         bool(INDEX_HTML_RE.search(text))

        if has_normalize or has_root_compare or has_multi_form or has_both_forms:
            continue  # safe

        # Flag the file
        rel_path = os.path.relpath(js_path, package_root)
        compare_count = len(HTML_COMPARE_RE.findall(text))
        findings.append((
            "OBS", "JS-CLEAN-URL-ASSUMPTION", rel_path,
            f"JS file uses location.pathname/window.location AND has "
            f"{compare_count} comparison(s) against .html-ending strings, "
            f"but no detected safety indicator (no .replace(/\\.html/) "
            f"normalization, no comparison against '/' clean-root URL, no "
            f"multi-form endsWith pattern, no both-forms 'index'+'index.html' "
            f"pair). Cloudflare Pages serves .html files at clean URLs "
            f"(e.g., /about.html at /about), so .html-extension-only "
            f"comparisons will fail for visitors arriving via clean URLs. "
            f"See wtpp-nav-menu.js getActivePage() for the canonical "
            f"normalization pattern."
        ))

    return findings


def audit_warm_tone_dark_token_completeness(package_root):
    """v3.7.416 \u2014 Detect color CSS tokens defined in light-mode :root
    but missing dark-mode override.

    The recurring "token gap" failure pattern: a token gets a color value
    defined in `:root { --X: #color }` (light default) and gets used via
    `var(--X)` in styled CSS, but no `html[data-theme=\"dark\"]` block
    overrides it. In dark mode the token falls through to its light-mode
    value, producing contrast failures (light text on light backgrounds,
    light rules on light surfaces, etc.). This pattern caused multiple
    bug-fix iterations in the v3.7.6x-7x era and shows up in memory as
    a known technical debt category.

    Scope: scans external .css files (incl _templates/*.css) AND inline
    `<style>` blocks in top-level *.html, 06_Presentation_Materials/*.html,
    and bots/*.html. Skips _web_html (generated output).

    Logic:
      (a) Build {token \u2192 sources} where a `:root` block defines the token
          with a value that looks like a color (hex/rgb/rgba/hsl/named).
          Uses the same negative-lookbehind regex as v3.7.415 to avoid
          BEM `.block--modifier:` false positives.
      (b) Build {token \u2192 sources} where any `html[data-theme=\"dark\"]`
          block (with or without `[data-tone=\"...\"]` pairing) defines
          the token. Any value type counts as coverage.
      (c) Build {token \u2192 sources} where the token is referenced via
          `var(--token)` anywhere.
      (d) Flag tokens with: color :root def AND referenced via var() AND
          no dark-mode override anywhere in the package.

    Severity: MIN (upgraded v3.7.418). At v3.7.416 launch this shipped
    as OBS pending review of which findings were intentional. v3.7.418
    remediated all 5 first-run findings by adding explicit dark-mode
    overrides for --accent-faint, --ink-faint, --rule-soft, --green,
    and --green-soft to wtpp-theme-styles.css. With the baseline clean,
    severity upgrades to MIN so any future re-introduction of the
    pattern is treated as a real consistency bug (the check is now a
    regression guard, not an inventory).
    """
    findings = []

    light_defs = {}      # token \u2192 set of source files
    dark_defs = {}       # token \u2192 set of source files
    referenced = {}      # token \u2192 set of source files using var()

    def _is_color_value(val):
        v = val.strip().lower()
        if re.match(r'^#[0-9a-f]{3,8}$', v):
            return True
        if v.startswith(('rgb(', 'rgba(', 'hsl(', 'hsla(')):
            return True
        if v in ('red', 'blue', 'green', 'black', 'white', 'gray', 'grey',
                 'navy', 'gold', 'silver', 'maroon', 'olive', 'purple',
                 'teal', 'aqua', 'fuchsia', 'lime', 'transparent'):
            return True
        return False

    def _scan_css(css_text, source):
        # :root blocks \u2192 light defs
        for m in re.finditer(r':root\s*\{([^}]*)\}', css_text):
            body = m.group(1)
            for vm in re.finditer(
                r'(?<![\w-])--([\w-]+)\s*:\s*([^;]+);', body
            ):
                name, val = vm.group(1), vm.group(2).strip()
                if _is_color_value(val):
                    light_defs.setdefault(name, set()).add(source)
        # html[data-theme="dark"] blocks (optionally paired with [data-tone="..."]) \u2192 dark defs
        for m in re.finditer(
            r'html(?:\[data-tone="[^"]*"\])?\[data-theme="dark"\]'
            r'(?:\[[^\]]*\])?\s*\{([^}]*)\}',
            css_text
        ):
            body = m.group(1)
            for vm in re.finditer(
                r'(?<![\w-])--([\w-]+)\s*:\s*([^;]+);', body
            ):
                dark_defs.setdefault(vm.group(1), set()).add(source)
        # var() references
        for vm in re.finditer(r'var\(\s*--([\w-]+)', css_text):
            referenced.setdefault(vm.group(1), set()).add(source)

    # Scan external CSS files
    for cssf in (glob.glob(os.path.join(package_root, '*.css')) +
                 glob.glob(os.path.join(package_root, '_templates', '*.css'))):
        try:
            with open(cssf, 'r', encoding='utf-8') as f:
                _scan_css(f.read(), os.path.relpath(cssf, package_root))
        except Exception:
            continue

    # Scan inline styles in HTML
    page_patterns = [
        os.path.join(package_root, '*.html'),
        os.path.join(package_root, '06_Presentation_Materials', '*.html'),
        os.path.join(package_root, 'bots', '*.html'),
        os.path.join(package_root, 'bots', '**', '*.html'),
    ]
    pages_seen = set()
    for pat in page_patterns:
        for ph in glob.glob(pat, recursive=True):
            if '_web_html' in ph or ph in pages_seen:
                continue
            pages_seen.add(ph)
            try:
                with open(ph, 'r', encoding='utf-8') as f:
                    html = f.read()
            except Exception:
                continue
            styles = "\n".join(
                re.findall(r'<style[^>]*>(.*?)</style>', html, re.DOTALL)
            )
            if styles:
                _scan_css(styles, os.path.relpath(ph, package_root))

    # Identify gap tokens
    gap_tokens = []
    for token in sorted(light_defs):
        if token in referenced and token not in dark_defs:
            gap_tokens.append(token)

    for token in gap_tokens:
        usage_sources = sorted(referenced[token])
        usage_summary = usage_sources[0] if len(usage_sources) == 1 else (
            f"{usage_sources[0]} (+{len(usage_sources)-1} more)"
        )
        findings.append((
            "MIN", "WARM-TONE-DARK-TOKEN-GAP", usage_sources[0],
            f"--{token} has a color value in :root and is used via var() in "
            f"[{usage_summary}] but has no html[data-theme=\"dark\"] override "
            f"\u2014 falls through to light value in dark mode (visual contrast "
            f"risk)"
        ))

    return findings


def audit_header_structural_integrity(package_root):
    """Verify every static HTML page closes the page-sticky-wrap div after
    the site-header block.

    Canonical pattern (from 10+ pages including accessibility, about,
    contact, privacy, sla, errata, downloads, historical-tradition,
    index, 404):

        <!-- SITE_HEADER:END -->
        </div>          <-- closes page-sticky-wrap

        <main class="page" id="main">

    If </div> is missing, the browser auto-closes at end-of-document,
    leaving <main> (and the entire page body) nested INSIDE
    <div class="page-sticky-wrap">. That wrapper has position:sticky,
    z-index:50, and background:var(--paper). The malformed nesting
    causes incorrect rendering in dark mode (page body appears lighter
    than its child cards, inverting the intended --paper < --paper-shade
    color hierarchy).

    Added v3.7.414 after v3.7.413's investigation found share.html and
    recruit.html missing this </div> for likely ~370 iterations
    (paired with the body-level flag-bg IMG drift that v3.7.408 fixed).
    Per the v3.7.413 diagnostic lesson: when CSS rules look correct
    but rendering is wrong, check HTML structural integrity. This
    audit operationalizes that lesson.

    Scans top-level .html files plus subfolder pages in
    06_Presentation_Materials and bots/. Skips the template file
    (_templates/site_page_template.html) and any _web_html doc
    mirrors (regenerated artifacts).
    """
    findings = []

    candidate_files = []
    # Top-level HTML files
    for entry in sorted(os.listdir(package_root)):
        full = os.path.join(package_root, entry)
        if os.path.isfile(full) and entry.endswith('.html'):
            candidate_files.append(full)
    # Subfolder HTML files known to carry the site header
    for subdir in ['06_Presentation_Materials', 'bots']:
        d = os.path.join(package_root, subdir)
        if os.path.isdir(d):
            for entry in sorted(os.listdir(d)):
                full = os.path.join(d, entry)
                if os.path.isfile(full) and entry.endswith('.html'):
                    candidate_files.append(full)

    marker = '<!-- SITE_HEADER:END -->'

    for filepath in candidate_files:
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                content = f.read()
        except Exception:
            continue

        # Skip templates and generated artifacts
        rel = os.path.relpath(filepath, package_root)
        if rel.startswith('_templates' + os.sep) or rel.startswith('_web_html' + os.sep):
            continue

        idx = content.find(marker)
        if idx < 0:
            # No site header on this page; skip silently
            continue

        # Find the next <main element after the marker
        after = content[idx + len(marker):]
        main_match = re.search(r'<main\b', after)
        if not main_match:
            # No <main> follows the header; very unusual but not this
            # audit's concern (would surface as a different issue).
            continue

        between = after[:main_match.start()]
        # Strip whitespace and ignore HTML comments inside the gap
        stripped = re.sub(r'<!--.*?-->', '', between, flags=re.DOTALL).strip()

        # The stripped gap should be exactly '</div>' (the close of
        # page-sticky-wrap). Anything else is suspicious; specifically
        # an empty gap means </div> is missing entirely.
        if stripped == '':
            findings.append((
                "MIN", "HEADER-STRUCTURE", rel,
                "Missing </div> between <!-- SITE_HEADER:END --> and <main> "
                "(needed to close page-sticky-wrap; nested <main> causes "
                "incorrect dark-mode rendering)"
            ))
        elif '</div>' not in stripped:
            findings.append((
                "MIN", "HEADER-STRUCTURE", rel,
                f"Expected </div> between <!-- SITE_HEADER:END --> and <main>, "
                f"found {stripped[:60]!r} instead (closes page-sticky-wrap)"
            ))
        # If </div> is present, structure is correct; no finding.

    return findings


# === PATTERN-MATCH CHECKS ===

def audit_pattern_sweep(all_docs, pattern_regex, pattern_name, wl_entries):
    """Sweep all docx paragraphs for pattern, applying whitelist + heuristic.
    
    Returns (findings, stats) where stats = (whitelisted_count, historical_count, flagged_count).
    """
    findings = []
    flagged_count = 0
    whitelisted_count = 0
    historical_count = 0
    
    for path, text in all_docs.items():
        try:
            doc = get_docx(path) if os.path.isabs(path) else get_docx(path)
        except:
            try:
                doc = get_docx(path)
            except:
                continue
        for i, p in enumerate(doc.paragraphs):
            if not re.search(pattern_regex, p.text):
                continue
            wl, _ = is_paragraph_whitelisted(path, p.text, wl_entries)
            if wl:
                whitelisted_count += 1
                continue
            if is_paragraph_historical(p.text):
                historical_count += 1
            else:
                flagged_count += 1
                findings.append(("MIN", f"PATTERN-{pattern_name}", path,
                                f"p{i}: {p.text[:200]}"))
    return findings, (whitelisted_count, historical_count, flagged_count)


# === SECTION SELF-CHECK (with heuristic harmonization, fix #2) ===

def audit_section_self_check(oir_doc, section_num, pattern_regex, pattern_name, wl_entries):
    """Check a specific OIR section for forward refs and pattern matches.
    
    Applies the [HISTORICAL] heuristic (matches behavior of full sweep,
    addressing audit-script improvement candidate #2 from iteration 26).
    """
    findings = []
    
    # Find LAST occurrence of "Section N:" (ignore version-line metadata)
    section_starts = {}
    for i, p in enumerate(oir_doc.paragraphs):
        text = p.text.strip()
        m = re.match(r'^Section (\d+):', text)
        if m:
            section_starts[int(m.group(1))] = i
    
    if section_num not in section_starts:
        return findings
    
    end = min((s for n, s in section_starts.items() if n > section_num), default=len(oir_doc.paragraphs))
    section_paragraphs = oir_doc.paragraphs[section_starts[section_num]:end]
    
    for p in section_paragraphs:
        # Forward refs (items 82-99)
        fwd_refs = re.findall(r'\bitem\s+(8[2-9]|[9]\d)\b', p.text)
        if fwd_refs:
            findings.append(("SIG", f"FWD-REF-SEC{section_num}", "OIR",
                            f"Forward refs: {fwd_refs}"))
        
        # Pattern check with heuristic
        if re.search(pattern_regex, p.text):
            wl, _ = is_paragraph_whitelisted("09_Open_Issues_Registry.docx", p.text, wl_entries)
            if wl:
                continue
            if is_paragraph_historical(p.text):
                continue
            findings.append(("MIN", f"PATTERN-SEC{section_num}-{pattern_name}", "OIR",
                            f"{p.text[:200]}"))
    
    return findings


# === NARRATIVE LOCATION CHECK (literal-text detection, fix #1) ===

def audit_narrative_locations(package_root, version_str, pattern_regex, pattern_name):
    """Check current-iteration narrative locations for literal-text patterns.
    
    Addresses audit-script improvement candidate #1 from iteration 19:
    catches the recursive meta-trigger pattern at write-time before shipping
    by checking specific narrative locations for literal patterns.
    
    Locations checked:
    - README.txt entry for the version
    - VERSIONLOG.txt entry for the version
    - Package Version doc changelog entry for the version
    - OIR Section corresponding to the iteration (if known)
    
    Findings are flagged as MIN — should be reviewed before shipping the
    iteration's release.
    """
    findings = []
    
    # README
    readme_path = os.path.join(package_root, "README.txt")
    if os.path.exists(readme_path):
        with open(readme_path, encoding="utf-8", errors="replace") as f:
            readme = f.read()
        # Find this version's entry (next entry from preceding version)
        prev_v = ".".join(version_str.split(".")[:-1] + [str(int(version_str.split(".")[-1]) - 1)])
        m = re.search(rf'(v{re.escape(version_str)} \(May[\s\S]+?)(?=v{re.escape(prev_v)} \(May|\Z)', readme)
        if m:
            entry_text = m.group(1)
            matches = re.findall(pattern_regex, entry_text)
            if matches:
                findings.append(("MIN", f"NARRATIVE-{pattern_name}", "README", 
                                f"v{version_str} entry has {len(matches)} literal-text occurrences"))
    
    # VERSIONLOG
    vlog_path = os.path.join(package_root, "VERSIONLOG.txt")
    if os.path.exists(vlog_path):
        with open(vlog_path, encoding="utf-8", errors="replace") as f:
            vlog = f.read()
        prev_v = ".".join(version_str.split(".")[:-1] + [str(int(version_str.split(".")[-1]) - 1)])
        m = re.search(rf'(VERSION {re.escape(version_str)}[\s\S]+?)(?=VERSION {re.escape(prev_v)}|\Z)', vlog)
        if m:
            entry_text = m.group(1)
            matches = re.findall(pattern_regex, entry_text)
            if matches:
                findings.append(("MIN", f"NARRATIVE-{pattern_name}", "VERSIONLOG",
                                f"v{version_str} entry has {len(matches)} literal-text occurrences"))
    
    return findings


# === MAIN ===



# === RECURSIVE META-TRIGGER DETECTION ===
#
# Patterns that document "fixes already applied" — if these literal
# texts appear in NEW narrative entries (current iteration), they constitute
# recursive meta-triggers (the iteration that documents the fix has reintroduced
# the literal text being fixed).
#
# Each entry: (regex pattern, human-readable description)
# Add new patterns when a new meta-trigger pattern is discovered. Keep entries
# specific (avoid over-broad patterns that would false-flag normal narrative).
#
# Categorical references (the abstracted-language form) for each pattern are
# documented here so authors of narrative entries have explicit guidance:
#   "4 percent employer"   -> "literal headline contribution rate text"
#   "2 percent employee"   -> "literal headline contribution rate text"
#   "$14,600"              -> "literal outdated baseline figure"
#   "twelve iterations"    -> "literal historical iteration count"
#
META_TRIGGER_PATTERNS = [
    (r'\b4\s+percent\s+employer\b', 'literal headline contribution rate text (employer)'),
    (r'\b2\s+percent\s+employee\b', 'literal headline contribution rate text (employee)'),
    (r'\b6\s+percent\s+(?:combined|total)\b', 'literal headline combined contribution rate text'),
    (r'\$14,600\b', 'literal outdated healthcare baseline figure'),
    (r'\btwelve iterations\b', 'literal historical iteration count'),
    (r'\beleven\s+occurrences\b', 'literal historical occurrence count'),
]

# Acronyms tracked for the undefined-acronym expanded-scope audit.
# Format: acronym -> full form. Add to this list as new acronyms emerge.
ACRONYMS_REGISTRY = {
    "BLS": "Bureau of Labor Statistics",
    "CMS": "Centers for Medicare and Medicaid Services",
    "CBO": "Congressional Budget Office",
    "GAO": "Government Accountability Office",
    "CRS": "Congressional Research Service",
    "JCT": "Joint Committee on Taxation",
    "TPC": "Tax Policy Center",
    "OEWS": "Occupational Employment and Wage Statistics",
    "FFIA": "Federal Fiscal Impact Analysis",
    "OIR": "Open Issues Registry",
    "FIF": "Federal Infrastructure Fee",
    "USF": "Universal Service Fund",
    "FEHB": "Federal Employees Health Benefits",
    "TANF": "Temporary Assistance for Needy Families",
    "CCP": "Community Contribution Plan",
    "NHE": "National Health Expenditure",
    "TCJA": "Tax Cuts and Jobs Act",
    "FCC": "Federal Communications Commission",
    "PUC": "Public Utility Commission",
    "REIT": "Real Estate Investment Trust",
    "NCAI": "National Congress of American Indians",    "AARP": "American Association of Retired Persons",
    "ACA": "Affordable Care Act",
    "ACP": "Affordable Connectivity Program",
    "ASCE": "American Society of Civil Engineers",
    "BEAD": "Broadband Equity, Access, and Deployment",
    "CCRC": "Continuing Care Retirement Community",
    "CHIP": "Children's Health Insurance Program",
    "CISA": "Cybersecurity and Infrastructure Security Agency",
    "CSRS": "Civil Service Retirement System",
    "EITC": "Earned Income Tax Credit",
    "EPA": "Environmental Protection Agency",
    "ETI": "Elasticity of Taxable Income",
    "FDR": "Franklin D. Roosevelt",
    "FERC": "Federal Energy Regulatory Commission",
    "FERS": "Federal Employees Retirement System",
    "FICA": "Federal Insurance Contributions Act",
    "FPL": "Federal Poverty Level",
    "FWA": "Fixed Wireless Access",
    "GKV": "Gesetzliche Krankenversicherung",
    "GPFG": "Government Pension Fund Global",
    "HCBS": "Home and Community-Based Services",
    "HUD": "Department of Housing and Urban Development",
    "IIJA": "Infrastructure Investment and Jobs Act",
    "IMLS": "Institute of Museum and Library Services",
    "IRA": ("Individual Retirement Account", "Inflation Reduction Act"),  # Multiple expansions: audit accepts any
    "IRS": "Internal Revenue Service",
    "ISP": "Internet Service Provider",
    "LEO": "Low Earth Orbit",
    "LMR": "Land Mobile Radio",
    "LTC": "Long-Term Care",
    "MFJ": "Married Filing Jointly",
    "NTIA": "National Telecommunications and Information Administration",
    "PACE": "Programs of All-inclusive Care for the Elderly",
    "PFAS": "Per- and polyfluoroalkyl substances",
    "PHA": "Public Housing Authority",
    "PII": "Personally Identifiable Information",
    "PMHNP": "Psychiatric-Mental Health Nurse Practitioner",
    "POTS": "Plain Old Telephone Service",
    "PSAP": "Public Safety Answering Point",
    "SMS": "Short Message Service",
    "SNAP": "Supplemental Nutrition Assistance Program",
    "SOC": "Standard Occupational Classification",
    "SRF": "State Revolving Fund",
    "SSA": "Social Security Administration",
    "SSDI": "Social Security Disability Insurance",
    "SSI": "Supplemental Security Income",
    "USDA": "United States Department of Agriculture",
    "USDS": "United States Digital Service",
    "USPS": "United States Postal Service",
    "USVI": "United States Virgin Islands",
    "VA": "Department of Veterans Affairs",

}

# Files excluded from the undefined-acronym scan because they don't need
# first-use full-form definitions (registries, indexes, version docs).
ACRONYMS_SCAN_EXCLUDE = {
    "01_Platform_Package_Version.docx",
    "09_Open_Issues_Registry.docx",
    "09_Iterative_Hardening_Process_Documentation.docx",
    "09_Readers_Path_Synthesis.docx",
    "09_Readers_Path_Scoping.docx",
    "09_Persona_Simulations_P2_P6.docx",
}



# === v3.7.437 AUDIT ALLOWLISTS (regression-guard suppression of known-benign OBS) ===
# These three allowlists suppress the specific, intentional, known-benign OBS findings
# catalogued at v3.7.436 (audit baseline 0 SIG / 0 MIN / 23 OBS) so the audit reports a
# clean 0/0/0 baseline. They are NOT blanket pattern suppression: each check still fires
# on any NEW occurrence outside its allowlist, so each remains a live regression guard.
# Fail-open by design: if a whitelisted string is later reworded, the entry simply stops
# matching and the OBS reappears for re-evaluation rather than being silently lost.

# PILLAR-REF-HISTORICAL: (path, pillar_number, captured_label) tuples that are legitimate
# historical/contextual pillar references (old pre-renumber names, or descriptive phrases
# that follow "Pillar N"). A mismatch in a HISTORICAL_FILES doc NOT in this set still
# surfaces as OBS; a mismatch in any non-historical doc still surfaces as MIN.
PILLAR_REF_ALLOWLIST = {
    ('01_Start_Here/01_Platform_Package_Version.docx', 1, 'sovereign fund'),
    ('01_Start_Here/01_Platform_Package_Version.docx', 6, 'Mental Health 0.5/0.3'),
    ('01_Start_Here/01_Platform_Package_Version.docx', 6, 'Mental Health Access'),
    ('01_Start_Here/01_Platform_Package_Version.docx', 7, 'Physical Civic Infrastructure'),
    ('01_Start_Here/01_Platform_Package_Version.docx', 9, 'Universal Paid Family Time'),
    ('09_Meta_Tracking/09_OIR_Iteration_Archive.docx', 1, 'sovereign fund'),
    ('09_Meta_Tracking/09_OIR_Iteration_Archive.docx', 2, 'for occupation-specific stipend levels'),
    ('09_Meta_Tracking/09_OIR_Iteration_Archive.docx', 6, 'for mental-health counselor delivery infrastructure'),
    ('09_Meta_Tracking/09_OIR_Iteration_Archive.docx', 7, 'Education Trust'),
    ('09_Meta_Tracking/09_OIR_Iteration_Archive.docx', 10, 'Environmental Stewardship'),
    ('09_Meta_Tracking/09_Open_Issues_Registry.docx', 4, "'Universal Healthcare Access' substantiation"),
    ('09_Meta_Tracking/09_Open_Issues_Registry.docx', 6, "'Universal Mental Health Access' substantiation"),
    ('09_Meta_Tracking/09_Open_Issues_Registry.docx', 9, 'Universal Paid Family Time'),
    ('09_Meta_Tracking/09_Open_Issues_Registry.docx', 10, 'Housing'),
}

# EXPANDED-OIR / EXPANDED-README / EXPANDED-VERSIONLOG: (finding_type, location,
# raw_descriptor) tuples for historical changelog entries that legitimately contain
# meta-trigger phrasing (contribution-rate text, historical counts) predating the
# abstracted-language discipline, or that legitimately quote those values. This is the
# FULL-HISTORY scan only; the separate current-iteration meta-trigger sweep is untouched,
# so the live recursive-language guardrail is not weakened. New version entries with
# trigger phrasing still surface.
EXPANDED_SCOPE_ALLOWLIST = {
    ("EXPANDED-README", "README v2.30.16", "literal historical occurrence count"),
    ("EXPANDED-VERSIONLOG", "VERSIONLOG v2.30.42", "literal headline combined contribution rate text"),
    ("EXPANDED-VERSIONLOG", "VERSIONLOG v2.30.12", "literal historical iteration count"),
    ("EXPANDED-VERSIONLOG", "VERSIONLOG v2.26.3", "literal headline contribution rate text (employer)"),
    ("EXPANDED-VERSIONLOG", "VERSIONLOG v2.26.3", "literal headline contribution rate text (employee)"),
    ("EXPANDED-VERSIONLOG", "VERSIONLOG v2.26.3", "literal headline combined contribution rate text"),
}

# SECTION-NUMBER-GAP: {docx_basename: set_of_intentionally_missing_section_numbers}. The
# numbering carries a deliberate gap (v3.x iteration narratives start at 209, leaving
# 9-208 unused; the archive reserves 1-8). Only gaps OUTSIDE the expected set are flagged,
# so a genuinely unexpected skipped number (e.g. Section 545 shipped without 544) still
# surfaces. Duplicate-section detection is a separate check and is untouched.
EXPECTED_SECTION_GAPS = {
    "09_OIR_Iteration_Archive.docx": set(range(1, 9)),
    "09_Open_Issues_Registry.docx": set(range(9, 209)),
}


def get_latest_versionlog_entry(package_root):
    """Extract the latest VERSION X.Y.Z entry from VERSIONLOG.txt.
    
    Returns the text of the most recent VERSION header block (from the
    version line through the next "=" separator before the next VERSION
    header), or None if VERSIONLOG.txt doesn't exist.
    """
    path = os.path.join(package_root, "VERSIONLOG.txt")
    if not os.path.exists(path):
        return None
    content = get_text_file(path)  # v3.7.90 cached
    # Find first "VERSION X.Y.Z" header (most recent in this file's ordering)
    m = re.search(r'(VERSION \d+\.\d+(?:\.\d+)?\b.*?)(?=\nVERSION \d+\.\d+|\Z)',
                  content, re.DOTALL)
    return m.group(1) if m else None


def get_latest_readme_entry(package_root):
    """Extract the latest vX.Y.Z entry from README.txt."""
    path = os.path.join(package_root, "README.txt")
    if not os.path.exists(path):
        return None
    content = get_text_file(path)  # v3.7.90 cached
    # README entries: "vX.Y.Z (date): ..." at line start — find the first one.
    # Both the match start and the lookahead must allow optional third version
    # segment (vX.Y.Z) and require an opening paren after the version, to avoid
    # matching wrapped continuation lines that start with "vX.Y.Z [text]".
    m = re.search(r'(^v\d+\.\d+(?:\.\d+)?\s*\([^)]*\):.*?)(?=^v\d+\.\d+(?:\.\d+)?\s*\(|\Z)',
                  content, re.DOTALL | re.MULTILINE)
    return m.group(1) if m else None


def get_latest_oir_section(package_root):
    """Extract the latest Section N text from the Open Issues Registry."""
    path = os.path.join(package_root, "09_Meta_Tracking/09_Open_Issues_Registry.docx")
    if not os.path.exists(path):
        return None
    try:
        doc = get_docx(path)
    except Exception:
        return None
    # Find the highest section number and capture from there until "Closing" or next section
    section_starts = {}
    for i, p in enumerate(doc.paragraphs):
        m = re.match(r'^Section (\d+):', p.text.strip())
        if m:
            section_starts[int(m.group(1))] = i
    if not section_starts:
        return None
    max_n = max(section_starts.keys())
    start = section_starts[max_n]
    # Capture paragraphs from start until Closing or next section
    text_parts = []
    for i in range(start, len(doc.paragraphs)):
        p = doc.paragraphs[i]
        s = p.text.strip()
        if i > start and s == "Closing":
            break
        if i > start and re.match(r'^Section \d+:', s):
            break
        text_parts.append(p.text)
    return "\n".join(text_parts)


def get_latest_pv_changelog(package_root):
    """Extract the latest Version X.Y.Z changelog entry from the Package Version document."""
    path = os.path.join(package_root, "01_Start_Here/01_Platform_Package_Version.docx")
    if not os.path.exists(path):
        return None
    try:
        doc = get_docx(path)
    except Exception:
        return None
    # Find first H2 "Version X.Y.Z" — that's the most recent (first in document order)
    in_latest = False
    text_parts = []
    for p in doc.paragraphs:
        style = p.style.name if p.style else ""
        is_version_h2 = (style == "Heading 2"
                         and re.match(r'^Version \d+\.\d+', p.text.strip()))
        if is_version_h2:
            if not in_latest:
                in_latest = True
                text_parts.append(p.text)
            else:
                break  # next version found; stop
        elif in_latest:
            text_parts.append(p.text)
    return "\n".join(text_parts) if text_parts else None


def audit_current_iteration_narratives(package_root):
    """Check current iteration's narrative entries for recursive meta-trigger patterns.
    
    Identifies the most recent narrative entry in each of:
      - VERSIONLOG.txt (most recent VERSION X.Y.Z entry)
      - README.txt (most recent vX.Y.Z entry)
      - OIR (highest-numbered Section N)
      - Package Version document (most recent "Version X.Y.Z" H2 changelog)
    
    For each, scans for literal audit-pattern text from META_TRIGGER_PATTERNS.
    Any match is a recursive-meta-trigger candidate — the iteration that
    documents the fix has reintroduced the literal text.
    
    The check's value: catches at iteration time what the abstracted-language
    discipline is supposed to prevent manually. Returns list of finding tuples
    (severity, type, location, description).
    """
    findings = []
    
    sources = [
        ("VERSIONLOG.txt latest entry", get_latest_versionlog_entry(package_root)),
        ("README.txt latest entry", get_latest_readme_entry(package_root)),
        ("OIR latest section", get_latest_oir_section(package_root)),
        ("Package Version doc latest changelog", get_latest_pv_changelog(package_root)),
    ]
    
    for source_name, text in sources:
        if not text:
            continue
        for pattern, descriptor in META_TRIGGER_PATTERNS:
            for m in re.finditer(pattern, text, re.IGNORECASE):
                # Build short context for finding (60 chars before/after)
                start = max(0, m.start() - 60)
                end = min(len(text), m.end() + 60)
                context = text[start:end].replace("\n", " ").strip()
                desc = (f"{descriptor} found in current iteration narrative; "
                        f"consider abstracted language. Context: ...{context}...")
                findings.append(("MIN", "RECURSIVE-META-TRIGGER", source_name, desc))
    
    return findings




def audit_expanded_scope(package_root):
    """Expanded-scope audits — full-document scans for meta-trigger patterns.
    
    Distinct from audit_current_iteration_narratives, which inspects only the
    LATEST narrative entry in each location. This function runs full-document
    scans (all OIR sections, all README entries, all VERSIONLOG entries) for
    the same meta-trigger patterns.
    
    Findings are reported as OBS (observation) severity — informational
    rather than blocking. Most occurrences will be HISTORICAL ACCURATE
    (legitimate documentation of fixes from their own iterations); the
    iteration author classifies any unexpected occurrence in Phase 1.3.
    
    Cadence: run FIRST in the harden cycle process (per OIR Section 71
    formalization); required before any external engagement initiation.
    
    Returns list of findings (severity, type, location, description).
    """
    findings = []
    
    # Full OIR scan (all sections, not just latest)
    oir_path = os.path.join(package_root,
                            "09_Meta_Tracking/09_Open_Issues_Registry.docx")
    if os.path.exists(oir_path):
        try:
            doc = get_docx(oir_path)
            section_paras = {}
            current_section = None
            for p in doc.paragraphs:
                m = re.match(r'^Section (\d+):', p.text.strip())
                if m:
                    current_section = int(m.group(1))
                    section_paras[current_section] = []
                elif current_section is not None and p.text.strip() != "Closing":
                    section_paras[current_section].append(p.text)
            
            for sec_n, paras in sorted(section_paras.items()):
                section_text = "\n".join(paras)
                for pattern, descriptor in META_TRIGGER_PATTERNS:
                    if re.search(pattern, section_text, re.IGNORECASE):
                        loc = f"OIR Section {sec_n}"
                        if ("EXPANDED-OIR", loc, descriptor) in EXPANDED_SCOPE_ALLOWLIST:
                            continue
                        findings.append(("OBS", "EXPANDED-OIR",
                                       loc,
                                       f"{descriptor} occurs (likely HISTORICAL ACCURATE)"))
        except Exception:
            pass
    
    # Full README scan (all entries, not just latest)
    readme_path = os.path.join(package_root, "README.txt")
    if os.path.exists(readme_path):
        try:
            with open(readme_path, encoding="utf-8", errors="replace") as f:
                readme = f.read()
            entries = re.findall(
                r'(^v\d+\.\d+(?:\.\d+)?\s*\([^)]*\):.*?)(?=^v\d+\.\d+(?:\.\d+)?\s*\(|\Z)',
                readme, re.DOTALL | re.MULTILINE)
            for entry in entries:
                ver_m = re.match(r'^(v\d+\.\d+(?:\.\d+)?)', entry)
                ver = ver_m.group(1) if ver_m else "?"
                for pattern, descriptor in META_TRIGGER_PATTERNS:
                    if re.search(pattern, entry, re.IGNORECASE):
                        loc = f"README {ver}"
                        if ("EXPANDED-README", loc, descriptor) in EXPANDED_SCOPE_ALLOWLIST:
                            continue
                        findings.append(("OBS", "EXPANDED-README",
                                       loc,
                                       f"{descriptor} occurs (likely HISTORICAL ACCURATE)"))
        except Exception:
            pass
    
    # Full VERSIONLOG scan (all entries, not just latest)
    vlog_path = os.path.join(package_root, "VERSIONLOG.txt")
    if os.path.exists(vlog_path):
        try:
            with open(vlog_path, encoding="utf-8", errors="replace") as f:
                vlog = f.read()
            entries = re.findall(
                r'(VERSION (\d+\.\d+(?:\.\d+)?)\b.*?)(?=\nVERSION \d+\.\d+|\Z)',
                vlog, re.DOTALL)
            for full_entry, ver in entries:
                for pattern, descriptor in META_TRIGGER_PATTERNS:
                    if re.search(pattern, full_entry, re.IGNORECASE):
                        loc = f"VERSIONLOG v{ver}"
                        if ("EXPANDED-VERSIONLOG", loc, descriptor) in EXPANDED_SCOPE_ALLOWLIST:
                            continue
                        findings.append(("OBS", "EXPANDED-VERSIONLOG",
                                       loc,
                                       f"{descriptor} occurs (likely HISTORICAL ACCURATE)"))
        except Exception:
            pass
    
    return findings




def audit_undefined_acronyms(package_root):
    """Expanded-scope audit — scans all docx files for acronyms used
    multiple times without their full-form definition.
    
    Catches the failure mode where an acronym is used multiple times in a
    document but never defined with its full form (e.g., "BLS" appearing 7
    times but "Bureau of Labor Statistics" not appearing anywhere). This
    failure mode was previously caught only via fresh-angle audits in
    Phase 1.2; codified as a permanent expanded-scope audit in v3.1.4.
    
    Cadence: runs as part of the expanded-scope audits per the run-first
    cadence rule. Findings are OBS (observation) severity; iteration
    author classifies in Phase 1.3 (real findings get mitigated, expected
    omissions can be added to ACRONYMS_SCAN_EXCLUDE if appropriate).
    
    Returns list of (severity, type, location, description) tuples.
    """
    findings = []
    
    for root, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
        for f in files:
            if not f.endswith(".docx"):
                continue
            if f in ACRONYMS_SCAN_EXCLUDE:
                continue
            path = os.path.join(root, f)
            try:
                doc = get_docx(path)
                text = "\n".join(p.text for p in doc.paragraphs)
                for table in doc.tables:
                    for row in table.rows:
                        for cell in row.cells:
                            text += "\n" + cell.text
                
                rel_path = os.path.relpath(path, package_root)
                
                for acronym, full_form in ACRONYMS_REGISTRY.items():
                    uses = list(re.finditer(r"\b" + re.escape(acronym) + r"\b", text))
                    if len(uses) < 2:
                        continue
                    # full_form may be a str or tuple of acceptable expansions
                    if isinstance(full_form, str):
                        if full_form in text:
                            continue  # full form present; defined
                        full_form_display = full_form
                    else:
                        if any(ff in text for ff in full_form):
                            continue  # at least one expansion present; defined
                        full_form_display = " or ".join(f"'{ff}'" for ff in full_form)
                    # Acronym used 2+ times, no acceptable full form present
                    findings.append(("OBS", "EXPANDED-ACRONYMS",
                                   rel_path,
                                   f"{acronym} used {len(uses)} times without {full_form_display} definition"))
            except Exception:
                pass
    
    return findings



# === SECTION 47 / OIR REFERENCE INTEGRITY CHECKS ===

# Section 47 ID prefix patterns (extend when new prefixes appear in Section 47).
SECTION_47_ID_PATTERNS = [
    r'PROCESS-\d+',
    r'METHOD-\d+',
    r'PROC-IMP-\d+',
    r'PROC-\d+',
    r'RESEARCH-\d+',
    r'ITEM\d+-Q\d+',
    r'PERSONA-(?:SIG|MIN|OBS)-\d+',
    r'OPEN-\d+',
    r'CON-\d+',
    r'SCOPE-\d+',
    r'COVERAGE-\d+',
    r'EXEMPTION-\d+',
    r'EVOLUTION-\d+',
    r'AUDIT-\d+',
]

SECTION_47_ID_REGEX = re.compile(
    r'\b(?:' + '|'.join(SECTION_47_ID_PATTERNS) + r')\b'
)

# Files excluded from Section 47 ID-reference scanning.
# These docs legitimately reference IDs in non-mitigation contexts
# (changelog narratives, process documentation, persona findings, synthesis, scoping).
SECTION_47_REF_SCAN_EXCLUDE = {
    "09_Open_Issues_Registry.docx",
    "09_OIR_Iteration_Archive.docx",  # added v3.7.81 — iteration archive references S47 IDs in historical context
    "09_Iterative_Hardening_Process_Documentation.docx",
    "01_Platform_Package_Version.docx",
    "09_Persona_Simulations_P2_P6.docx",
    "09_Readers_Path_Synthesis.docx",
    "09_Readers_Path_Scoping.docx",
}


def get_section_47_ids(package_root):
    """Extract Section 47 item IDs from the OIR table.

    Section 47 is an iteration-archive section (Section 47 about expansion was
    documented during a v2.x iteration). Since v3.7.81 the iteration sections
    moved to 09_OIR_Iteration_Archive.docx. The table-based Section 47 entries
    may live in either file. Check OIR first; fall back to the archive.
    """
    candidate_paths = [
        os.path.join(package_root, "09_Meta_Tracking", "09_Open_Issues_Registry.docx"),
        os.path.join(package_root, "09_Meta_Tracking", "09_OIR_Iteration_Archive.docx"),
    ]
    for oir_path in candidate_paths:
        if not os.path.exists(oir_path):
            continue
        try:
            doc = get_docx(oir_path)
            if not doc.tables:
                continue
            table = doc.tables[0]
            ids = set()
            for ri, row in enumerate(table.rows):
                if ri == 0:
                    continue
                cell0 = row.cells[0].text.strip()
                if not cell0:
                    continue
                # v3.7.468: a cell may carry a canonical ID plus a "(formerly OLD)"
                # alias so legacy references still resolve. Add every recognized ID
                # token; fall back to the raw cell text when no pattern matches.
                toks = SECTION_47_ID_REGEX.findall(cell0)
                if toks:
                    ids.update(toks)
                else:
                    ids.add(cell0)
            if ids:
                return ids
        except Exception:
            pass
    return set()


def get_oir_max_section(package_root):
    """Return the highest section number across the OIR + its iteration archive.

    Since v3.7.81, iteration sections were moved from the OIR to a companion
    archive file (09_OIR_Iteration_Archive.docx). Section numbers are globally
    unique across both files. References from other documents to 'OIR Section
    N' may resolve to either file. This function returns the max across both.
    """
    oir_files = [
        os.path.join(package_root, "09_Meta_Tracking", "09_Open_Issues_Registry.docx"),
        os.path.join(package_root, "09_Meta_Tracking", "09_OIR_Iteration_Archive.docx"),
    ]
    max_section = 0
    for oir_path in oir_files:
        if not os.path.exists(oir_path):
            continue
        try:
            doc = get_docx(oir_path)
            for p in doc.paragraphs:
                style = p.style.name if p.style else ""
                if "Heading 1" in style or "Heading1" in style:
                    m = re.match(r'^Section (\d+)', p.text.strip())
                    if m:
                        section_num = int(m.group(1))
                        if section_num > max_section:
                            max_section = section_num
        except Exception:
            pass
    return max_section


def audit_section_47_id_references(package_root):
    """Scan narrative docs for references to Section 47 IDs that don't exist.
    
    Returns list of finding tuples (severity, type, location, description).
    Real finding indicates a stale or typo'd reference to a Section 47 item ID.
    """
    section_47_ids = get_section_47_ids(package_root)
    if not section_47_ids:
        return []
    
    findings = []
    for root, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
        for f in files:
            if not f.endswith(".docx"):
                continue
            if f in SECTION_47_REF_SCAN_EXCLUDE:
                continue
            path = os.path.join(root, f)
            rel_path = os.path.relpath(path, package_root)
            try:
                doc = get_docx(path)
                text = "\n".join(p.text for p in doc.paragraphs)
                for tab in doc.tables:
                    for row in tab.rows:
                        for c in row.cells:
                            text += "\n" + c.text
                
                ids_in_doc = set(SECTION_47_ID_REGEX.findall(text))
                for item_id in ids_in_doc:
                    if item_id not in section_47_ids:
                        findings.append((
                            "MIN", "STALE-SECTION-47-REF", rel_path,
                            f"references Section 47 ID '{item_id}' which does not exist in current Section 47"
                        ))
            except Exception:
                pass
    
    return findings


def audit_section_47_row_consistency(package_root):
    """Check Section 47 rows for well-formedness.
    
    Each row should have non-empty ID, description, valid Status (CLOSED or OPEN
    with explanation), and valid Mitigated (Y, N, or substantive text).
    Returns list of finding tuples.
    """
    oir_path = os.path.join(package_root, "09_Meta_Tracking", "09_Open_Issues_Registry.docx")
    if not os.path.exists(oir_path):
        return []
    
    findings = []
    rel_path = "09_Meta_Tracking/09_Open_Issues_Registry.docx"
    try:
        oir = get_docx(oir_path)
        if not oir.tables:
            return []
        table = oir.tables[0]
        seen_ids = set()
        for ri, row in enumerate(table.rows):
            if ri == 0:
                continue
            cells = row.cells
            if len(cells) < 4:
                findings.append(("MIN", "SECTION-47-MALFORMED", rel_path,
                                f"row {ri}: fewer than 4 cells"))
                continue
            item_id = cells[0].text.strip()
            desc = cells[1].text.strip()
            status = cells[2].text.strip()
            mitigated = cells[3].text.strip()
            
            if not item_id:
                findings.append(("MIN", "SECTION-47-MALFORMED", rel_path,
                                f"row {ri}: empty ID"))
                continue
            if item_id in seen_ids:
                findings.append(("MIN", "SECTION-47-MALFORMED", rel_path,
                                f"row {ri} ({item_id}): duplicate ID"))
            seen_ids.add(item_id)
            if not desc:
                findings.append(("MIN", "SECTION-47-MALFORMED", rel_path,
                                f"row {ri} ({item_id}): empty description"))
            if not (status.startswith("CLOSED") or status.startswith("OPEN")):
                findings.append(("MIN", "SECTION-47-MALFORMED", rel_path,
                                f"row {ri} ({item_id}): unusual Status '{status[:50]}'"))
            if not mitigated:
                findings.append(("MIN", "SECTION-47-MALFORMED", rel_path,
                                f"row {ri} ({item_id}): empty Mitigated"))
            if status.startswith("CLOSED") and mitigated == "N":
                findings.append(("MIN", "SECTION-47-MALFORMED", rel_path,
                                f"row {ri} ({item_id}): CLOSED status with N Mitigated (inconsistent per v3.1.2 criterion)"))
    except Exception:
        pass
    
    return findings


def audit_oir_section_references(package_root):
    """Scan narrative docs for OIR Section references where section number exceeds max.
    
    A reference to 'OIR Section X' where X > current_max_section indicates a
    stale or typo'd reference. Returns list of finding tuples.
    """
    max_section = get_oir_max_section(package_root)
    if max_section == 0:
        return []
    
    findings = []
    for root, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
        for f in files:
            if not f.endswith(".docx"):
                continue
            if f in ("09_Open_Issues_Registry.docx", "09_OIR_Iteration_Archive.docx"):
                continue
            path = os.path.join(root, f)
            rel_path = os.path.relpath(path, package_root)
            try:
                doc = get_docx(path)
                text = "\n".join(p.text for p in doc.paragraphs)
                for tab in doc.tables:
                    for row in tab.rows:
                        for c in row.cells:
                            text += "\n" + c.text
                
                seen = set()
                for m in re.finditer(r'\b(?:OIR\s+)?Section\s+(\d+)\b', text):
                    section_num = int(m.group(1))
                    start = max(0, m.start() - 100)
                    context = text[start:m.end() + 50].lower()
                    is_oir_ref = ("oir" in context or "open issues registry" in context or "open-issues registry" in context)
                    if is_oir_ref and section_num > max_section and section_num not in seen:
                        seen.add(section_num)
                        findings.append((
                            "MIN", "STALE-OIR-SECTION-REF", rel_path,
                            f"references OIR Section {section_num} which exceeds current max ({max_section})"
                        ))
            except Exception:
                pass
    
    return findings



# === MANIFEST + TOC CONSISTENCY CHECKS (added v3.1.9) ===

# Files known to be in package but excluded from user-facing TOC by convention.
# These are auxiliary analytical artifacts (persona simulations, reader-path docs)
# tracked in manifest but not in the TOC's numbered listing.
TOC_EXCLUDE_FILES = {
    "STATUS_REPORT.html",   # v3.8.513: private generated status report (review_comments/), not a document
    # v3.8.506 (decision 3A): the guide's inventory is now generated from the catalog's PUBLIC
    # documents, so the private files the legacy numbered tables used to list drop out of it.
    "02_Outreach_Stewart_Drafts.docx",                 # private:true outreach draft
    "02_Outreach_PodSaveAmerica_Drafts.docx",          # private:true outreach draft (v3.8.602, #4297)
    "02_Tribal_Consultation_Briefing_Document.docx",   # private:true since v3.8.498 (author #3749)
    "09_Long_Term_Design_Claude_Code_on_VM.docx",      # private:true design doc (v3.8.695, author #5095)
    "platform_index.html",                              # the site's own index page, not a catalogued document
    # v3.8.496: the author's own senator letter, private (catalog private:true). Deliberately absent
    # from the public TOC on the same basis as the private handouts; the public citizen template is
    # 02_Constituent_Letter.docx.
    "02_Outreach_Constituent_Letter_Author.docx",
    "assumptions.html",  # generated reader-facing view of the assumptions registry
    # v3.7.658: private outreach tracker (spreadsheet asset, not a TOC document)
    "02_Outreach_Tracker.xlsx",
    # v3.8.18: private classroom handout. Catalogued with private:true and
    # deliberately absent from the public TOC, on the same basis as the outreach
    # material: it is a working communication artifact, not part of the published
    # package a reader is invited to review.
    "02_Classroom_Handout_Grade6.html",
    "02_Classroom_Handout_HowToCheckANumber_v1.html",
    "09_Persona_Simulations_P2_P6.docx",
    "09_Persona_Simulations_P7_P11.docx",
    "09_Readers_Path_Scoping.docx",
    "09_Readers_Path_Synthesis.docx",
    # OIR iteration archive (split from OIR in v3.7.81; tracking/meta doc not
    # in TOC because it duplicates information surfaced via OIR which IS in TOC)
    "09_OIR_Iteration_Archive.docx",
    # v3.7.200 (SITE-35): External Review Register — tracking surface
    # for external reviewer engagements. Tracking/meta doc analogous to
    # OIR iteration archive; not in TOC because it's a structured
    # tracking artifact rather than a numbered analytical content
    # document.
    "09_External_Review_Register.docx",
    # v3.7.555: third Gemini scoping review (Jun 12, 2026; of v3.7.480).
    # Filed in 07_External_Reviews and tracked in the External Review
    # Register (Kind E); not surfaced in the public TOC — that is Jason's
    # call. Surfacing it later would add a numbered TOC entry and move the
    # public document count from 126 to 127, consistent with the other
    # external reviews.
    "07_Gemini_Review_of_v3_7_550.pdf",
    # v3.7.726: fourth Gemini scoping review (Jul 11, 2026; of the live
    # v3.7.716 site) — five reading-path persona matrix + four-point red-team
    # stress test. Filed in 07_External_Reviews and tracked in the External
    # Review Register (Kind E); catalog-listed but TOC-excluded, consistent
    # with the prior Gemini reviews.
    "07_Gemini_Review_of_v3_7_716.pdf",
    # v3.7.389: Platform rebuild plan + patch inventory. Internal-
    # tracking artifact for the parallel-package rebuild path; not
    # user-facing analytical content. Analogous to OIR archive.
    "09_Rebuild_Plan_And_Inventory.docx",
    # Web-deployment auxiliary pages (added v3.7.26 for hosting prep)
    "about.html",
    "disclosure.html",  # v3.8.609: the disclosure page
    "contact.html",
    "privacy.html",
    # v3.7.241: design system verification page; unlinked by design,
    # accessible only by direct URL for QA.
    "style_guide.html",
    # v3.7.196 (SITE-33): errata register page. Excluded from TOC because
    # it's a web-deployment auxiliary page like privacy.html — the TOC
    # lists numbered analytical content documents, not site-policy pages.
    "errata.html",
    # v3.7.198 (SITE-34): policymaker landing page. Excluded from TOC
    # for the same reason — it's an audience-specific landing surface
    # built from existing analytical content, not a new analytical
    # document.
    "policymaker.html",
    # v3.7.539: Common Concerns on-ramp page. Auxiliary audience-facing
    # landing surface like policymaker.html; excluded from the TOC.
    "concerns.html",
    # v3.7.564 (Phase 3 #8): Objections & Responses page. Auxiliary
    # audience-facing landing surface like concerns.html — the stakeholder
    # objection matrix, reached via a contextual link rather than the TOC,
    # which lists numbered analytical content documents, not site pages.
    "objections.html",
    # v3.7.567: Fiscal Control Panel — auxiliary tool page (frames the bundled
    # microsimulation dashboard); a site page in nav, not a numbered TOC document.
    "fiscal-model.html",
    # v3.7.402: Internal UI lexicon — visual reference for design-system
    # vocabulary, lives in _internal/ and is not part of the website
    # navigation. Tracking/meta artifact for shared communication
    # between Jason and Claude during iterations.
    "ui_lexicon.html",
    "colorblind_simulation.html",
    # Downloads landing page (added v3.7.27)
    "downloads.html",
    # v3.7.727: Audio Companions page — auxiliary site page (spoken-word
    # narrations of the reading paths), reached by direct link; not a numbered
    # TOC document. Handled like downloads.html / share.html.
    "audio.html",
    # Root-level deployment files (added v3.7.30)
    "index.html",
    "flag-background.jpg",
    "sla.html",
    "accessibility.html",
    "recruit.html",
    "share.html",
    # v3.7.412: standalone page mapping the platform's relationship to
    # American federal-reform history (Social Security, GI Bill, Civil
    # Rights Act). Excluded from TOC for the same reason as other
    # audience-specific landing surfaces (about.html, recruit.html) —
    # it's not a numbered analytical content document.
    "historical-tradition.html",
    # v3.7.187 (SITE-25): custom 404 page. Excluded from TOC because it's a
    # redirect-hub served only on unmatched routes, never navigated to
    # deliberately. Same rationale as other utility pages (accessibility,
    # privacy, etc).
    "404.html",
    "site_header_template.html",
    "_templates/site_header_template.html",
    "06_Platform_Architecture.html",
}

# Files retired in past versions but legitimately referenced in historical narrative
# sections of OIR/PV/VERSIONLOG (e.g. "v3.7.110 added X; v3.7.112 removed X").
# Cross-ref check skips these — references are historically accurate, not orphan refs.
RETIRED_FILES = {
    # Retired in v3.7.112 (consolidated into Platform Architecture page)
    "06_Platform_At_A_Glance.html",
    # v3.8.45: the nine derivation workbooks cited by figures_registry.json that
    # do not exist and were searched for without success (RESEARCH-26,
    # RESEARCH-34). These are referenced ON PURPOSE, in registry status text and
    # in RECONSTRUCTION_PROTOCOL, precisely to record that they are missing.
    #
    # Without this exemption the cross-reference check fires every time a tracked
    # item describes its own subject accurately, which trains the reader to
    # dismiss the finding. The gap itself stays visible through RESEARCH-26,
    # RESEARCH-34 and the CITATION-DECLARED count; it does not need a second
    # channel that cannot tell a deliberate mention from an accident.
    "04_Absorption_Reconciliation_Model.xlsx",
    "04_Civic_Infrastructure_Model_MultiMethod.xlsx",
    "04_Deficit_Recompute.xlsx",
    "04_Fiscal_Reconciliation_Model.xlsx",
    "04_Pillar_Targets_Benchmarked.xlsx",
    "04_Sovereign_Education_Fund_MultiMethod.xlsx",
    "04_Universal_Childcare_Model_MultiMethod.xlsx",
    "04_Universal_Healthcare_Target_Sensitivity.xlsx",
    "04_Universal_Mental_Health_Model_MultiMethod.xlsx",
}

# Files that ARE in the package (and in the catalog) but whose content is not
# subject to platform content/style audits. Added in v3.7.134 for the conversation
# log: it's an append-only verbatim record of human-AI exchanges, so the audit's
# acronym-expansion, pillar-reference, S47, OIR-section, and cross-reference checks
# do not apply. Manifest/catalog checks DO apply (the entry must be present and
# resolvable). New entries here should be rare — most package files belong in the
# normal audit scope.
TRACKED_NOT_AUDITED = {
    "09_Meta_Tracking/09_Conversation_Log.md",
}



def get_doc_version_from_metadata(file_path):
    """Read document's own version from version-line metadata.
    
    Looks for lines starting with vX.Y followed by metadata indicator (· or |)
    in the first ~15 paragraphs. Returns version string ('v1.0', 'v1.79') or None.
    
    Restrictive pattern avoids false matches on inline version references like
    'reviewing v1.8' (where the version isn't at the start of a metadata line).
    """
    try:
        doc = get_docx(file_path)
        for p in doc.paragraphs[:15]:
            text = p.text.strip()
            m = re.match(r'^v(\d+\.\d+(?:\.\d+)?)\s+[\u00B7\|]', text)
            if m:
                return f"v{m.group(1)}"
        return None
    except Exception:
        return None


def audit_version_json_count_consistency(package_root):
    """version.json totals must agree with the catalog (added v3.7.563).

    version.json is a hand-authored public deploy-status endpoint. It is now synced
    by bump_version.py, but this check is the regression guard: it fails if the
    endpoint's platform_version or document counts drift away from
    platform_catalog.json (the single source of truth), and verifies the
    tracked_issues block is internally consistent (open + closed == total).
    Trigger: v3.7.561 shipped with version.json.totals.documents=114 (docx=95) while
    the catalog held 129 total / 126 public — undetected because nothing audited it.
    """
    findings = []
    vj_path = os.path.join(package_root, "version.json")
    cat_path = os.path.join(package_root, "00_GUI_Files", "platform_catalog.json")
    if not (os.path.exists(vj_path) and os.path.exists(cat_path)):
        return findings
    try:
        with open(vj_path, encoding="utf-8", errors="replace") as f:
            vj = json.load(f)
        cat = get_catalog()
    except Exception:
        return findings

    rel = "version.json"
    # platform_version must match the catalog
    vj_ver = vj.get("platform_version")
    cat_ver = cat.get("platformVersion")
    if vj_ver and cat_ver and vj_ver != cat_ver:
        findings.append(("MIN", "VERSION-JSON-DRIFT", rel,
                         f"platform_version={vj_ver} != catalog.platformVersion={cat_ver}"))

    totals = vj.get("totals", {})
    cat_total = cat.get("totalDocuments")
    cat_public = cat.get("publicDocuments")
    vj_total = totals.get("totalDocuments")
    vj_public = totals.get("publicDocuments", totals.get("documents"))
    if cat_total is not None and vj_total is not None and vj_total != cat_total:
        findings.append(("MIN", "VERSION-JSON-DRIFT", rel,
                         f"totals.totalDocuments={vj_total} != catalog.totalDocuments={cat_total}"))
    if cat_public is not None and vj_public is not None and vj_public != cat_public:
        findings.append(("MIN", "VERSION-JSON-DRIFT", rel,
                         f"totals public count={vj_public} != catalog.publicDocuments={cat_public}"))

    # tracked_issues internal consistency
    ti = totals.get("tracked_issues", {})
    if ti:
        o, c, t = ti.get("open"), ti.get("closed"), ti.get("total")
        if None not in (o, c, t) and o + c != t:
            findings.append(("MIN", "VERSION-JSON-DRIFT", rel,
                             f"tracked_issues open({o}) + closed({c}) != total({t})"))
    return findings


def audit_tracked_issue_count_drift(package_root):
    """Every stated tracked-issue count must match the registry table itself.

    v3.7.775. This is the guard for the defect that prompted it: the platform published TWO
    different counts of its own unresolved work at the same time. index/concerns/about said
    "32 open"; the bot mirror said "30 OPEN items"; the Section 47 summary said 28 "as of
    v3.7.93". Root cause was the count living as data in one place and as prose in several
    others, re-synced by hand and rotting between times.

    Why this rates SIG rather than MIN: the count of what the platform cannot yet defend is
    not decoration, it is the platform's central honesty claim. The bot mirror in particular
    exists to tell AI systems how to describe the platform INCLUDING its limits — and the
    drift ran in the self-flattering direction, understating open work. A platform whose
    pitch is "check the math yourself" cannot miscount its own open questions.

    Ground truth is 09_Open_Issues_Registry.docx (Issue ID / Description / Current Status /
    Mitigated). Everything else must agree with it.
    """
    findings = []
    reg_path = os.path.join(package_root, "09_Meta_Tracking", "09_Open_Issues_Registry.docx")
    if not os.path.exists(reg_path):
        return [("SIG", "TRACKED-ISSUE-COUNT-DRIFT", "09_Open_Issues_Registry.docx",
                 "the Tracked Issues Registry is missing; no count can be verified")]
    try:
        reg = get_docx(reg_path)
        table = reg.tables[0]
        header = [c.text.strip() for c in table.rows[0].cells]
        si = header.index("Current Status")
        mi = header.index("Mitigated") if "Mitigated" in header else None
        total = open_ = closed = mitigated = 0
        for row in table.rows[1:]:
            s = row.cells[si].text.strip().upper()
            total += 1
            if s.startswith("OPEN"):
                open_ += 1
            elif s.startswith("CLOSED"):
                closed += 1
            if mi is not None and row.cells[mi].text.strip().upper().startswith("Y"):
                mitigated += 1
    except Exception as e:  # noqa: BLE001
        return [("SIG", "TRACKED-ISSUE-COUNT-DRIFT", "09_Open_Issues_Registry.docx",
                 f"could not read the registry table to verify counts: {e}")]

    # 1) manifest.json must match the table
    mpath = os.path.join(package_root, "manifest.json")
    if os.path.exists(mpath):
        try:
            with open(mpath, encoding="utf-8") as f:
                man = json.load(f)
            mt = man.get("totals", {}).get("tracked_issues", {})
            if (mt.get("total"), mt.get("open"), mt.get("closed")) != (total, open_, closed):
                findings.append((
                    "SIG", "TRACKED-ISSUE-COUNT-DRIFT", "manifest.json",
                    f"manifest totals.tracked_issues says {mt.get('total')}/{mt.get('open')} "
                    f"open/{mt.get('closed')} closed, but the registry table has "
                    f"{total}/{open_} open/{closed} closed. Rebuild with "
                    f"tools/build_manifest.py (it derives these from the table)."))
            # every prose string in the manifest that states an OPEN count must agree
            blob = json.dumps(man)
            for m in re.finditer(r"(\d+)\s+OPEN items", blob):
                if int(m.group(1)) != open_:
                    findings.append((
                        "SIG", "TRACKED-ISSUE-COUNT-DRIFT", "manifest.json",
                        f"manifest prose says '{m.group(1)} OPEN items' but the registry has "
                        f"{open_}. This prose is published to the bot mirror, which tells AI "
                        f"systems how to describe the platform's limits."))
        except Exception as e:  # noqa: BLE001
            findings.append(("MIN", "TRACKED-ISSUE-COUNT-DRIFT", "manifest.json",
                             f"could not verify manifest counts: {e}"))

    # 2) no served page (or bot page) may state a contradicting OPEN count
    for rel in ("bots/index.html", "bots/tracked-issues-registry.html"):
        p = os.path.join(package_root, rel)
        if not os.path.exists(p):
            continue
        try:
            with open(p, encoding="utf-8") as f:
                html = f.read()
        except OSError:
            continue
        for m in re.finditer(r"(\d+)\s+OPEN items", html):
            if int(m.group(1)) != open_:
                findings.append((
                    "SIG", "TRACKED-ISSUE-COUNT-DRIFT", rel,
                    f"states '{m.group(1)} OPEN items' but the registry has {open_}. "
                    f"Regenerate with tools/build_manifest.py then tools/build_bot_mirror.py."))

    # 3) the Section 47 summary paragraph in the Archive must match
    arch = os.path.join(package_root, "09_Meta_Tracking", "09_OIR_Iteration_Archive.docx")
    if os.path.exists(arch):
        try:
            a = get_docx(arch)
            for p in a.paragraphs:
                t = p.text
                if t.startswith("Summary statistics.") and "tracked issues" in t:
                    nums = re.search(r"contains (\d+) tracked issues", t)
                    dist = re.search(r"distribution is (\d+) CLOSED and (\d+) OPEN", t)
                    if nums and int(nums.group(1)) != total:
                        findings.append((
                            "SIG", "TRACKED-ISSUE-COUNT-DRIFT",
                            "09_OIR_Iteration_Archive.docx",
                            f"Section 47 summary says {nums.group(1)} tracked issues but the "
                            f"registry table has {total}."))
                    if dist and (int(dist.group(1)), int(dist.group(2))) != (closed, open_):
                        findings.append((
                            "SIG", "TRACKED-ISSUE-COUNT-DRIFT",
                            "09_OIR_Iteration_Archive.docx",
                            f"Section 47 summary says {dist.group(1)} CLOSED / "
                            f"{dist.group(2)} OPEN but the registry table has "
                            f"{closed} CLOSED / {open_} OPEN."))
                    # v3.8.503: EVERY COUNT IN THIS PARAGRAPH, not two of them. The paragraph also
                    # stated '85 are Mitigated equals Y' (table: 101) and 'The 53 CLOSED items'
                    # (table: 66) for many releases while this check passed, because it read only
                    # the total and the CLOSED/OPEN distribution. Found by hand at v3.8.503.
                    for _pat, _want, _label in (
                            (r"(\d+) are Mitigated equals Y", mitigated, "Mitigated equals Y"),
                            (r"(\d+) are Mitigated equals N", total - mitigated, "Mitigated equals N"),
                            (r"The (\d+) CLOSED items", closed, "CLOSED items"),
                            (r"The (\d+) OPEN items", open_, "OPEN items")):
                        for _m in re.finditer(_pat, t):
                            if int(_m.group(1)) != _want:
                                findings.append((
                                    "SIG", "TRACKED-ISSUE-COUNT-DRIFT",
                                    "09_OIR_Iteration_Archive.docx",
                                    f"Section 47 summary says {_m.group(1)} {_label} but the "
                                    f"registry table has {_want}."))
                    break
        except Exception as e:  # noqa: BLE001
            findings.append(("MIN", "TRACKED-ISSUE-COUNT-DRIFT",
                             "09_OIR_Iteration_Archive.docx",
                             f"could not verify the Section 47 summary: {e}"))

    # 4) v3.8.489 (R1): version.json is a public deploy-status endpoint. It shipped 102/44/58 for
    #    releases while the table held 118/52/66: its builder could not run (it read the version
    #    as 3.7.657) and the stamp sweep kept its version string current, so it looked fresh.
    #    The older VERSION-JSON-DRIFT check only tested open + closed == total, which 44+58=102 passes.
    vjp = os.path.join(package_root, "version.json")
    if os.path.exists(vjp):
        try:
            vti = json.load(open(vjp, encoding="utf-8")).get("totals", {}).get("tracked_issues", {})
            if (vti.get("total"), vti.get("open"), vti.get("closed")) != (total, open_, closed):
                findings.append((
                    "SIG", "TRACKED-ISSUE-COUNT-DRIFT", "version.json",
                    f"version.json totals.tracked_issues says {vti.get('total')}/{vti.get('open')} "
                    f"open/{vti.get('closed')} closed, but the registry table has {total}/{open_} "
                    f"open/{closed} closed. Run tools/rebuild_derived_meta.py."))
        except Exception as e:  # noqa: BLE001
            findings.append(("MIN", "TRACKED-ISSUE-COUNT-DRIFT", "version.json",
                             f"could not verify version.json counts: {e}"))

    # 5) v3.8.489 (R2, counts): 01_What_This_Is states the counts as NUMBER WORDS ("fifty are
    #    OPEN"), which no digit regex above can see. It shipped v3.8.477's fifty / sixty-five for
    #    eleven releases because its builder was in no chain.
    wpath = os.path.join(package_root, "01_Start_Here", "01_What_This_Is.docx")
    if os.path.exists(wpath):
        try:
            import sys as _sys
            _sys.path.insert(0, os.path.join(package_root, "tools"))
            from build_orientation_docs import num_to_words as _w
            wt = " ".join(p.text for p in get_docx(wpath).paragraphs)
            expect = {
                f"contains {_w(total)} items": "total",
                f"{_w(closed)} are CLOSED": "closed",
                f"{_w(open_)} are OPEN": "open",
                f"The {_w(open_)} OPEN items": "open (framing reminder)",
            }
            for phrase, what in expect.items():
                if phrase not in wt:
                    findings.append((
                        "SIG", "TRACKED-ISSUE-COUNT-DRIFT", "01_Start_Here/01_What_This_Is.docx",
                        f"does not state the registry's {what} count as '{phrase}' "
                        f"(registry: {total} total / {open_} OPEN / {closed} CLOSED). "
                        f"Run tools/rebuild_derived_meta.py."))
            if mi is not None and f"All {_w(total)} are Mitigated" in wt and mitigated != total:
                findings.append((
                    "SIG", "TRACKED-ISSUE-COUNT-DRIFT", "01_Start_Here/01_What_This_Is.docx",
                    f"says all {total} are Mitigated, but the registry has {mitigated} of {total}."))
        except Exception as e:  # noqa: BLE001
            findings.append(("MIN", "TRACKED-ISSUE-COUNT-DRIFT", "01_Start_Here/01_What_This_Is.docx",
                             f"could not verify its counts: {e}"))

    # 6) v3.8.489 (R4): a Mitigated claim anywhere in the manifest must match the table. The
    #    registry definition said "all 101 Mitigated = Y" against 118 items: the number was
    #    derived and right, the word "all" was typed and wrong.
    if mi is not None and os.path.exists(mpath):
        try:
            blob = json.dumps(json.load(open(mpath, encoding="utf-8")))
            for m in re.finditer(r"\ball (\d+) Mitigated", blob):
                if int(m.group(1)) != total or mitigated != total:
                    findings.append((
                        "SIG", "TRACKED-ISSUE-COUNT-DRIFT", "manifest.json",
                        f"manifest prose says 'all {m.group(1)} Mitigated' but the registry has "
                        f"{mitigated} Mitigated of {total}."))
            for m in re.finditer(r"(\d+) of (\d+) Mitigated", blob):
                if (int(m.group(1)), int(m.group(2))) != (mitigated, total):
                    findings.append((
                        "SIG", "TRACKED-ISSUE-COUNT-DRIFT", "manifest.json",
                        f"manifest prose says '{m.group(1)} of {m.group(2)} Mitigated' but the "
                        f"registry has {mitigated} of {total}."))
        except Exception as e:  # noqa: BLE001
            findings.append(("MIN", "TRACKED-ISSUE-COUNT-DRIFT", "manifest.json",
                             f"could not verify Mitigated prose: {e}"))
    return findings


def audit_segment_privacy_agreement(package_root, segmenter="tools/build_release_segments.py"):
    """v3.8.491 (D10): the catalog's `private` flag and the release segments must agree.

    The segmenter filed a catalogued PUBLIC document as private because its file name contained
    'Outreach'. The site, its HTML mirror and the download bundles published it; the public core
    zip omitted it; nothing compared the two. Now:
      * catalog private:true but NOT in the private segment -> SIG: a private draft would ship
        in a public package.
      * catalog public but IN the private segment            -> MIN: a published document is
        missing from the package a reviewer downloads.
    """
    import importlib.util as _u
    tool = os.path.join(package_root, segmenter)
    cat_p = os.path.join(package_root, "00_GUI_Files", "platform_catalog.json")
    if not (os.path.exists(tool) and os.path.exists(cat_p)):
        return []
    try:
        s = _u.spec_from_file_location("segs_for_audit", tool)
        m = _u.module_from_spec(s); s.loader.exec_module(m)
        priv = {os.path.normpath(x) for x in m.private_paths(package_root)}
        docs = json.load(open(cat_p, encoding="utf-8")).get("documents") or []
    except Exception as e:  # noqa: BLE001
        return [("MIN", "SEGMENT-PRIVACY-AGREEMENT", segmenter, f"could not verify: {e}")]
    out = []
    for d in docs:
        rel = os.path.normpath(str(d.get("path") or d.get("file") or ""))
        if not rel or rel == "." or not os.path.exists(os.path.join(package_root, rel)):
            continue
        if d.get("private") and rel not in priv:
            out.append(("SIG", "SEGMENT-PRIVACY-AGREEMENT", rel,
                        "catalog says private, but the release segments would ship it in a PUBLIC package"))
        elif not d.get("private") and rel in priv:
            out.append(("MIN", "SEGMENT-PRIVACY-AGREEMENT", rel,
                        "catalog says public (and the site publishes it), but the release segments file it "
                        "PRIVATE, so the public core package omits it"))
    return out


def audit_regional_prose(package_root):
    """v3.8.498: the Regional Variation Examples prose must match its tables and the wage data.

    It drifted twice, in opposite directions (tables stale at v3.8.260, prose stale at v3.8.495).
    Its number-bearing paragraphs are now generated by tools/build_regional_examples.py; this runs
    that tool's --check. MIN: the document is public but its tables, the figures a reader acts on,
    are generated separately and stay right.
    """
    import subprocess as _sp
    tool = os.path.join(package_root, "tools", "build_regional_examples.py")
    if not os.path.exists(tool):
        return []
    r = _sp.run([sys.executable, tool, "--check"], cwd=package_root, capture_output=True, text=True,
                encoding="utf-8", errors="replace")
    if r.returncode != 0:
        return [("MIN", "REGIONAL-PROSE-DRIFT", "02_Vision_and_Communication/02_Wage_Floor_Regional_Variation_Examples.docx",
                 (r.stdout.strip() or r.stderr.strip())[-300:])]
    return []


def audit_session_handoff(package_root):
    """v3.8.505 (ported from the discarded v3.8.503 branch): the session handoff must match the package.
    A new session reads it FIRST; a stale one starts the session from a project that no longer exists.
    Runs build_session_handoff.py --check. MIN: private, never reaches a reader, but steers every session."""
    import subprocess as _sp
    tool = os.path.join(package_root, "tools", "build_session_handoff.py")
    if not os.path.exists(tool):
        return []
    r = _sp.run([sys.executable, tool, "--check"], cwd=package_root, capture_output=True, text=True,
                encoding="utf-8", errors="replace")
    if r.returncode != 0:
        return [("MIN", "HANDOFF-STALE", "09_Meta_Tracking/review_comments/SESSION_HANDOFF.md",
                 (r.stdout.strip() or r.stderr.strip())[-250:])]
    return []


def audit_status_report(package_root):
    """v3.8.513: the private status report must match the package (tools/build_status_report.py --check).
    It is the author's one-page view of where the project stands; a stale one misleads exactly as a stale
    handoff does. MIN, like HANDOFF-STALE: private, never reaches a reader, but steers decisions."""
    import subprocess as _sp
    tool = os.path.join(package_root, "tools", "build_status_report.py")
    if not os.path.exists(tool):
        return []
    r = _sp.run([sys.executable, tool, "--check"], cwd=package_root, capture_output=True, text=True,
                encoding="utf-8", errors="replace")
    if r.returncode != 0:
        return [("MIN", "STATUS-REPORT-STALE", "09_Meta_Tracking/review_comments/STATUS_REPORT.html",
                 (r.stdout.strip() or r.stderr.strip())[-250:])]
    return []


def audit_assumption_classification(package_root):
    """v3.8.513 (author: Option A): every figure that could depend on a judgment must SAY whether it does.
    A figure that is unlinked, derived or model-produced, and carries no needs_assumption, is reported, so the
    status report's 'linked to an assumption' denominator stays a record rather than a guess."""
    sys.path.insert(0, os.path.join(package_root, "tools"))
    try:
        import session_state as _ss
        E = json.load(open(os.path.join(package_root, "00_GUI_Files", "figures_registry.json"), encoding="utf-8"))["entries"]
    except Exception as ex:
        return [("MIN", "FIG-ASSUMPTION-UNCLASSIFIED", "00_GUI_Files/figures_registry.json", f"could not run: {ex}")]
    return [("MIN", "FIG-ASSUMPTION-UNCLASSIFIED", "00_GUI_Files/figures_registry.json",
             f"{e['id']}: set needs_assumption (true/false) with needs_assumption_basis")
            for e in _ss.unclassified_assumption(E)]


def audit_display_canonical_drift(package_root):
    """v3.8.513 (author J7): a bare [[FIG:]] token prints its first narrative example's DISPLAY, not the canonical.
    At v3.8.402 four household canonicals moved and their displays did not; five pages printed retired values for
    111 releases and two whole-document reads marked them clean, because a token looks current by construction.
    This compares each display with the canonical (scaling words and percent handled) and reports a gap over 2%."""
    EXEMPT = {  # each with its reason; an exemption is a decision, not a convenience
    }
    import re as _r
    try:
        E = json.load(open(os.path.join(package_root, "00_GUI_Files", "figures_registry.json"), encoding="utf-8"))["entries"]
    except Exception as ex:
        return [("MIN", "DISPLAY-CANONICAL-DRIFT", "figures_registry.json", f"could not read: {ex}")]
    out = []
    for e in E:
        c = e.get("canonical") or {}; ex0 = (e.get("narrative_examples") or [None])[0]
        cv = c.get("value")
        if not isinstance(ex0, dict) or not ex0.get("display") or not isinstance(cv, (int, float)) or cv == 0:
            continue
        m = _r.search(r"([\d,]+(?:\.\d+)?)\s*(trillion|billion|million|percent|%)?", ex0["display"])
        if not m:
            continue
        dv = float(m.group(1).replace(",", "")); w = (m.group(2) or "").lower()
        cands = [dv, dv * {"million": 1e6, "billion": 1e9, "trillion": 1e12}.get(w, 1)]
        if w in ("percent", "%"):
            cands.append(dv / 100)
        if any(abs(x - cv) / abs(cv) <= 0.02 for x in cands):
            continue
        if e["id"] in EXEMPT:
            continue
        out.append(("MIN", "DISPLAY-CANONICAL-DRIFT", "00_GUI_Files/figures_registry.json",
                    f"{e['id']}: tokens print '{ex0['display']}' but the canonical is {cv}"))
    return out


def audit_household_scenarios(package_root):
    """v3.8.517 (author W11, method A): What This Means For You's tables are COMPUTED by the calculator
    (tools/build_household_scenarios.py). Three disagreeing methods once told readers anything from +$25 to
    +$7,161 for the same household; this fails the gate if the document and the calculator part again."""
    import subprocess as _sp
    tool = os.path.join(package_root, "tools", "build_household_scenarios.py")
    if not os.path.exists(tool):
        return []
    r = _sp.run([sys.executable, tool, "--check"], cwd=package_root, capture_output=True, text=True,
                encoding="utf-8", errors="replace")
    if r.returncode != 0:
        return [("MIN", "HOUSEHOLD-SCENARIOS-DRIFT", "05_Analytical_Framing/05_What_This_Means_For_You.docx",
                 (r.stdout.strip() or r.stderr.strip())[-250:])]
    return []


def audit_fork_check_record(package_root):
    """v3.8.505: the newest VERSIONLOG entry must record its fork check -- a 'FORK CHECK:' line naming its
    own version, saying what search was run for other chats that may already have shipped it. Two chats
    once built different v3.8.503s from the same v3.8.502. tools/build_release_segments.py refuses to
    write a release without this line; the audit flags its absence earlier, while the entry is drafted."""
    vp = os.path.join(package_root, "VERSIONLOG.txt")
    try:
        vt = open(vp, encoding="utf-8").read()
    except OSError:
        return []
    heads = re.findall(r"^VERSION (\d+\.\d+\.\d+)", vt, re.M)
    if not heads:
        return []
    cut = vt.find("VERSION " + heads[1]) if len(heads) > 1 else len(vt)
    newest = vt[:cut]
    if not re.search(r"FORK CHECK:.*" + re.escape(heads[0]), newest):
        return [("MIN", "FORK-CHECK-RECORD", "VERSIONLOG.txt",
                 f"the newest entry (v{heads[0]}) records no 'FORK CHECK: ... {heads[0]} ...' line. Search the "
                 f"author's chats for this version before releasing, and record the result.")]
    return []


def audit_comment_ledger(package_root):
    """v3.8.490: the private comment ledger must be intact and every tag must still resolve.

    09_Meta_Tracking/review_comments/ledger.jsonl is append-only and hash-chained
    (tools/comment_ledger.py). A broken chain, a bad hash or a seq gap means a recorded comment or
    decision was EDITED OR REMOVED after it was written -- the record of what the author asked for
    no longer says what he asked for. That is SIG. A tag that no longer resolves (a file renamed, a
    figure retired) is MIN: the record is intact but one of its trails now leads nowhere.
    """
    import importlib.util as _u
    tool = os.path.join(package_root, "tools", "comment_ledger.py")
    if not os.path.exists(tool):
        return []
    try:
        s = _u.spec_from_file_location("comment_ledger", tool)
        m = _u.module_from_spec(s); s.loader.exec_module(m)
        probs = m.verify(package_root)
    except Exception as e:  # noqa: BLE001
        return [("MIN", "COMMENT-LEDGER", "09_Meta_Tracking/review_comments/ledger.jsonl",
                 f"could not verify: {e}")]
    out = []
    for pr in probs:
        integrity = any(k in pr for k in ("hash does not match", "chain broken", "seq is", "not JSON", "missing '"))
        out.append(("SIG" if integrity else "MIN", "COMMENT-LEDGER",
                    "09_Meta_Tracking/review_comments/ledger.jsonl", pr))
    return out


def audit_figure_source_vintage(package_root):
    """v3.8.489 (R3, and R2's non-count half). A source LABEL must name the release its value is from.

    FIG-healthcare-percapita-baseline moved from the CMS 2023 to the CMS 2024 release at v3.8.406.
    Its `basis` was rewritten; its `name` and `source` kept saying 2023, and so did its
    reproducibility_test note (2023 column, 14,580) -- for eighty-two releases. The label then
    flowed into manifest.json's empirical anchors, the bot mirror and 01_What_This_Is, which
    also kept a hand-typed "thirty-five percent" reduction from the old base.

    Rule: when a figure's `basis` opens by naming a source and a year (the clause before the first
    comma or colon), any year that appears in its `name` or `source` must be that year. Then the
    orientation doc must name the same CMS release as the registry and state the reduction the
    registry implies. MIN: a wrong vintage label is a provenance error, not a wrong number.
    """
    findings = []
    rp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(rp):
        return findings
    try:
        entries = json.load(open(rp, encoding="utf-8")).get("entries", [])
    except Exception as e:  # noqa: BLE001
        return [("MIN", "FIGURE-SOURCE-VINTAGE", "00_GUI_Files/figures_registry.json", f"unreadable: {e}")]
    yr = re.compile(r"\b(19|20)\d{2}\b")
    for e in entries:
        basis = str(e.get("basis") or "")
        lead = re.split(r"[,:;(]", basis, 1)[0]
        bys = {m.group(0) for m in yr.finditer(lead)}
        if len(bys) != 1:
            continue
        by = next(iter(bys))
        src_words = re.sub(yr, "", lead).strip().lower()
        for field in ("name", "source"):
            val = str(e.get(field) or "")
            fys = {m.group(0) for m in yr.finditer(val)}
            # only compare a label that names the SAME source as the basis lead
            same_source = src_words and (src_words[:18] in val.lower() or
                                         any(w in val for w in ("NHE", "OEWS", "CBO", "SSA")) and
                                         any(w in lead for w in ("NHE", "Health Expenditure", "OEWS", "CBO", "SSA")))
            if fys and by not in fys and same_source:
                findings.append((
                    "MIN", "FIGURE-SOURCE-VINTAGE", "00_GUI_Files/figures_registry.json",
                    f"{e.get('id')}: `{field}` names {sorted(fys)} but its basis opens with "
                    f"'{lead.strip()[:70]}' ({by})."))
    # orientation doc: same CMS release and the implied reduction
    wpath = os.path.join(package_root, "01_Start_Here", "01_What_This_Is.docx")
    if os.path.exists(wpath):
        try:
            import sys as _sys
            _sys.path.insert(0, os.path.join(package_root, "tools"))
            from build_manifest import healthcare_baseline_release_label, healthcare_reduction_percent
            from build_orientation_docs import num_to_words as _w
            wt = " ".join(p.text for p in get_docx(wpath).paragraphs)
            lab = healthcare_baseline_release_label()
            if lab not in wt:
                findings.append(("MIN", "FIGURE-SOURCE-VINTAGE", "01_Start_Here/01_What_This_Is.docx",
                                 f"does not name the registry's healthcare source '{lab}'."))
            pct = f"roughly a {_w(healthcare_reduction_percent())} percent"
            if pct not in wt:
                findings.append(("MIN", "FIGURE-SOURCE-VINTAGE", "01_Start_Here/01_What_This_Is.docx",
                                 f"does not state the registry-implied reduction ('{pct}')."))
        except Exception as e:  # noqa: BLE001
            findings.append(("MIN", "FIGURE-SOURCE-VINTAGE", "01_Start_Here/01_What_This_Is.docx",
                             f"could not verify: {e}"))
    # manifest anchor label must equal the methodology source's release
    mp = os.path.join(package_root, "manifest.json")
    if os.path.exists(mp):
        try:
            man = json.load(open(mp, encoding="utf-8"))
            meth = [x.get("source", "") for x in man.get("methodology", []) if "NHE" in x.get("source", "")]
            anch = [x.get("label", "") for x in man.get("empirical_anchors", []) if "Health Expenditure" in x.get("label", "")]
            my = {m.group(0) for s in meth for m in yr.finditer(s)}
            ay = {m.group(0) for s in anch for m in yr.finditer(s)}
            if my and ay and my != ay:
                findings.append(("MIN", "FIGURE-SOURCE-VINTAGE", "manifest.json",
                                 f"methodology names CMS {sorted(my)} but empirical_anchors names {sorted(ay)}."))
        except Exception as e:  # noqa: BLE001
            findings.append(("MIN", "FIGURE-SOURCE-VINTAGE", "manifest.json", f"could not verify: {e}"))
    return findings


def audit_reflow_guard_missing(package_root):
    """The CSS that makes the platform pass WCAG 2.1 SC 1.4.10 (Reflow) must stay put.

    v3.7.776. accessibility.html publicly states the platform reflows at 400% zoom without
    loss of content. That claim is enforced by a handful of specific declarations, each of
    which is easy to "clean up" later without realising it is load-bearing:

      * .wtpp-btn white-space:normal <=480px  — a nowrap button label sets a min-content
        floor that propagates card -> grid -> section -> main. This alone broke the homepage.
      * body overflow-wrap:anywhere <=480px   — document names like 03_Technical_White_Papers
        are single unbreakable tokens. NOTE: 'break-word' does NOT reduce min-content, only
        'anywhere' does, so a well-meaning swap to break-word silently reintroduces the bug.
      * audio {width:100%}                    — a native <audio> asserts ~300px intrinsic width.
      * scroll wrappers contain:inline-size   — overflow-x:auto ALONE does not stop min-content
        propagation. The site shipped a .threshold-table-wrap with overflow-x:auto for months
        that never worked. contain:inline-size is the declaration doing the work.

    SIG, not MIN: this backs a published conformance claim, and every one of these failures
    is invisible at desktop width. Static check by design so it runs without a browser;
    tools/check_reflow.py is the behavioural check.
    """
    findings = []
    required = [
        ("wtpp-btn-system.css", "white-space: normal",
         "button labels must be allowed to wrap at <=480px"),
        ("wtpp-theme-styles.css", "overflow-wrap: anywhere",
         "unbreakable document-name tokens must be breakable at <=480px"),
        ("wtpp-listen-now-styles.css", "width: 100%",
         "native <audio> must not assert its ~300px intrinsic width"),
    ]
    for fname, needle, why in required:
        fpath = os.path.join(package_root, fname)
        if not os.path.exists(fpath):
            continue
        try:
            body = open(fpath, encoding="utf-8").read()
        except Exception:
            continue
        if "1.4.10" not in body or needle not in body:
            findings.append((
                "SIG", "REFLOW-GUARD-MISSING", fname,
                f"The SC 1.4.10 reflow fix is gone from {fname} ({why}). accessibility.html "
                f"claims the platform reflows at 400% zoom; without this declaration that "
                f"claim is false and the failure is invisible at desktop width. "
                f"Re-check with: python3 tools/check_reflow.py --all"))

    # scroll wrappers must keep the declaration that actually severs min-content propagation
    for fname in ("06_Presentation_Materials/06_Wage_Floor_Comparison_Calculator.html",
                  "06_Presentation_Materials/06_We_The_People_Calculator.html"):
        fpath = os.path.join(package_root, fname)
        if not os.path.exists(fpath):
            continue
        try:
            body = open(fpath, encoding="utf-8").read()
        except Exception:
            continue
        if "overflow-x: auto" in body and "contain: inline-size" not in body:
            findings.append((
                "SIG", "REFLOW-GUARD-MISSING", fname,
                "A table scroll wrapper lost contain:inline-size. overflow-x:auto alone does "
                "NOT stop the table's min-content propagating into <main> (measured: no change "
                "at all), so the page will silently fail SC 1.4.10 at 320 CSS px while looking "
                "correct on desktop. Re-check with: python3 tools/check_reflow.py --all"))
    return findings


def audit_orientation_doc_stale(package_root):
    """01_What_This_Is.docx is derived; it must not quote numbers the manifest has moved past.

    v3.7.775. This doc calls itself the single source of truth for orienting outsiders and is
    marked do-not-hand-edit, but tools/build_orientation_docs.py is in no build chain — not
    the deploy's, not the standard rebuild. So it silently held "one-hundred-forty-six
    documents" for six days while the real count was 150, and it is a SERVED page.
    """
    findings = []
    doc = os.path.join(package_root, "01_Start_Here", "01_What_This_Is.docx")
    mpath = os.path.join(package_root, "manifest.json")
    if not (os.path.exists(doc) and os.path.exists(mpath)):
        return []
    try:
        with open(mpath, encoding="utf-8") as f:
            man = json.load(f)
        text = " ".join(p.text for p in get_docx(doc).paragraphs)
    except Exception as e:  # noqa: BLE001
        return [("MIN", "ORIENTATION-DOC-STALE", "01_What_This_Is.docx",
                 f"could not verify: {e}")]

    def words(n):
        ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
                "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
                "sixteen", "seventeen", "eighteen", "nineteen"]
        tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
                "eighty", "ninety"]
        if n < 20:
            return ones[n]
        if n < 100:
            return tens[n // 10] + ("-" + ones[n % 10] if n % 10 else "")
        return ones[n // 100] + "-hundred" + ("-" + words(n % 100) if n % 100 else "")

    # v3.8.491 (D8): the public count, which every public surface reports. The regex also accepts
    # the old wording so a regression to "N documents" is still compared rather than missed.
    expected = words(man["totals"]["publicDocuments"])
    m = re.search(r"contains ([a-z-]+) (?:public )?documents", text)
    if not m:
        findings.append(("MIN", "ORIENTATION-DOC-STALE", "01_Start_Here/01_What_This_Is.docx",
                         "states no document count in the expected form; cannot verify it"))
    elif m.group(1) != expected:
        findings.append((
            "MIN", "ORIENTATION-DOC-STALE", "01_Start_Here/01_What_This_Is.docx",
            f"says the package contains '{m.group(1)}' documents but the manifest's PUBLIC count is "
            f"{man['totals']['publicDocuments']} ('{expected}'). This doc is derived and served; "
            f"regenerate it with: python3 tools/build_orientation_docs.py "
            f"(default skips the private outreach draft)."))
    return findings


def audit_manifest_version_consistency(package_root):
    """Check that manifest cell 1 versions match each doc's actual version line.
    
    Returns list of finding tuples for stale manifest entries (manifest version
    differs from doc actual version).
    """
    pv_path = os.path.join(package_root, "01_Start_Here", "01_Platform_Package_Version.docx")
    if not os.path.exists(pv_path):
        return []
    
    findings = []
    rel_pv_path = "01_Start_Here/01_Platform_Package_Version.docx"
    try:
        pv = get_docx(pv_path)
        for table in pv.tables:
            for ri, row in enumerate(table.rows):
                if len(row.cells) < 2:
                    continue
                cell0_text = row.cells[0].text
                manifest_v = row.cells[1].text.strip()
                
                # Skip if manifest_v doesn't look like a version
                if not manifest_v.startswith("v"):
                    continue
                
                # Extract filenames from cell 0 (multiple lines possible)
                for line in cell0_text.split("\n"):
                    line = line.strip()
                    if not line.endswith(".docx"):
                        continue
                    
                    # Locate the actual file
                    file_path = None
                    for root, dirs, files in os.walk(package_root):
                        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
                        if line in files:
                            file_path = os.path.join(root, line)
                            break
                    
                    if not file_path:
                        continue
                    
                    actual = get_doc_version_from_metadata(file_path)
                    if actual and actual != manifest_v:
                        findings.append((
                            "MIN", "MANIFEST-VERSION-STALE", rel_pv_path,
                            f"{line}: manifest={manifest_v}, doc actual={actual}"
                        ))
    except Exception:
        pass
    
    return findings


def audit_toc_consistency(package_root):
    """Check TOC against actual files in package.
    
    Findings:
      - File in package but not in TOC (and not in TOC_EXCLUDE_FILES)
      - File in TOC but not in package
      - TOC numbering not sequential (missing numbers in expected range)
      - TOC entries with duplicate numbers
    """
    toc_path = os.path.join(package_root, "01_Start_Here", "01_Platform_Package_TOC.docx")
    if not os.path.exists(toc_path):
        return []
    
    rel_toc_path = "01_Start_Here/01_Platform_Package_TOC.docx"
    findings = []
    
    try:
        toc = get_docx(toc_path)
        # TOC structure: each numbered entry is a single-cell single-row table
        toc_entries = []  # list of (number, filename)
        # v3.8.506 (author decision 3A): the numbered single-cell tables were replaced by the
        # GENERATED INVENTORY region (tools/build_package_guide.py), one paragraph per document:
        # "<title> \u2014 <path>. <description>". Read that region when present, numbering entries in
        # order; the table reading below remains the fallback for a guide without the region.
        _ps = [p.text for p in toc.paragraphs]
        _s = next((i for i, x in enumerate(_ps) if x.startswith("=== GENERATED INVENTORY")), None)
        _e = next((i for i, x in enumerate(_ps) if x.strip().startswith("=== GENERATED INVENTORY") and "ends" in x), None)
        if _s is not None and _e is not None and _e > _s:
            for _x in _ps[_s + 1:_e]:
                _m = re.search(r"\u2014 (\S+\.(?:docx|html|xlsx|pdf|pptx))(?:\.|\s|$)", _x)
                if _m:
                    toc_entries.append((len(toc_entries) + 1, os.path.basename(_m.group(1))))
        for ti, t in enumerate(toc.tables if not toc_entries else []):
            if len(t.rows) >= 1 and len(t.rows[0].cells) >= 1:
                cell_text = t.rows[0].cells[0].text
                m = re.match(r'^(\d+)\.\s+', cell_text)
                if m:
                    entry_num = int(m.group(1))
                    file_match = re.search(r'(\S+\.(?:docx|html|xlsx|pdf|pptx))', cell_text)
                    if file_match:
                        fname = os.path.basename(file_match.group(1))
                        toc_entries.append((entry_num, fname))
        
        # Check sequential numbering
        toc_nums = sorted([e[0] for e in toc_entries])
        if toc_nums:
            expected = list(range(1, max(toc_nums) + 1))
            missing_nums = [n for n in expected if n not in toc_nums]
            if missing_nums:
                findings.append((
                    "MIN", "TOC-NUMBERING-GAP", rel_toc_path,
                    f"Missing TOC entry numbers in 1-{max(toc_nums)} range: {missing_nums}"
                ))
        
        # Check for duplicates
        from collections import Counter
        num_counts = Counter([e[0] for e in toc_entries])
        dupes = sorted([n for n, c in num_counts.items() if c > 1])
        if dupes:
            findings.append((
                "MIN", "TOC-DUPLICATE-NUMBER", rel_toc_path,
                f"Duplicate TOC entry numbers: {dupes}"
            ))
        
        # Cross-reference with package files
        toc_filenames = set(e[1] for e in toc_entries)
        package_filenames = set()
        for root, dirs, files in os.walk(package_root):
            dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
            for f in files:
                if any(f.endswith(ext) for ext in [".docx", ".html", ".xlsx", ".pdf", ".pptx"]) and not f.startswith("~$"):  # v3.7.592: ignore Office lock files
                    package_filenames.add(f)
        
        # Files in package but not in TOC (excluding known auxiliary)
        not_in_toc = package_filenames - toc_filenames - TOC_EXCLUDE_FILES
        for f in sorted(not_in_toc):
            findings.append((
                "MIN", "FILE-NOT-IN-TOC", rel_toc_path,
                f"Package file '{f}' is not in TOC and not in TOC_EXCLUDE_FILES"
            ))
        
        # Files in TOC but not in package
        in_toc_not_in_package = toc_filenames - package_filenames
        for f in sorted(in_toc_not_in_package):
            findings.append((
                "MIN", "TOC-FILE-MISSING", rel_toc_path,
                f"TOC references '{f}' but file not in package"
            ))
    except Exception:
        pass
    
    return findings



# === CROSS-REFERENCE RESOLUTION CHECK (added v3.1.12) ===

def audit_pv_count_consistency(package_root):
    """Check that the PV doc's intro count claim matches the actual file count.

    The Platform Package Version document has an intro paragraph stating
    "{N} documents and models" describing the package contents. This count
    can drift stale across iterations as new files are added but the intro
    paragraph isn't updated. This check finds the count claim and verifies
    N matches the actual count of DOCX + XLSX files in the package.

    Added v3.2.4 after a v3.2.3 audit found the count claim stale at "75"
    when the actual count was 89 (was last accurate around v2.x).
    Returns list of finding tuples.
    """
    findings = []

    # Find PV doc
    pv_path = os.path.join(package_root, "01_Start_Here/01_Platform_Package_Version.docx")
    if not os.path.exists(pv_path):
        return findings

    # Count actual DOCX + XLSX in package (excluding hidden dirs and __pycache__)
    actual_count = 0
    for root, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
        for f in files:
            if f.endswith(".docx") or f.endswith(".xlsx"):
                actual_count += 1

    # Find the count claim in PV doc intro paragraphs
    try:
        doc = get_docx(pv_path)
    except Exception:
        return findings

    pattern = re.compile(r'\b(\d{2,3})\s+documents?\s+and\s+models?\b', re.IGNORECASE)
    for i, p in enumerate(doc.paragraphs[:30]):  # Only intro region, not changelog
        m = pattern.search(p.text)
        if m:
            claimed = int(m.group(1))
            if claimed != actual_count:
                findings.append((
                    "MIN", "PV-COUNT-STALE",
                    "01_Start_Here/01_Platform_Package_Version.docx",
                    f"intro claims '{claimed} documents and models' but actual DOCX+XLSX count is {actual_count}"
                ))
            break  # Only check the first occurrence (intro)

    return findings


def audit_cross_reference_resolution(package_root):
    """Check that filename references in document content resolve to actual files.
    
    Scans all docx files for filename references matching the platform's
    XX_*.{ext} pattern (where XX is a 2-digit category prefix). Reports MIN
    finding for any reference that doesn't resolve to a file in the package.
    
    Catches stale references after file renames or removals. Common failure
    modes: changelog entries that mention a file by its old name after rename;
    OIR references with wrong category prefix; cross-document references after
    a file is moved between subdirectories.
    """
    findings = []
    
    # Build set of actual filenames in package (basenames, not paths)
    # Includes _web_html/ auto-generated mirrors — references to those filenames
    # are valid because every docx has an auto-generated HTML version.
    package_filenames = set()
    for root, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_downloads", "_licenses", "_data_archive", "_templates")]
        for f in files:
            if any(f.endswith(ext) for ext in [".docx", ".html", ".xlsx", ".pdf", ".pptx"]):
                package_filenames.add(f)
    
    # Pattern: 2-digit prefix + underscore + identifier + extension
    filename_pattern = re.compile(r'\b\d{2}_[A-Za-z][A-Za-z0-9_]*\.(?:docx|html|xlsx|pdf|pptx)\b')
    
    # Scan all docx files for references
    referenced = {}  # filename -> set of file paths referencing it
    for root, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "_web_html", "_downloads", "_licenses", "_data_archive", "_templates", "bots", "microsimulation", "_audio") and not re.match(r"v\d+_work$", d)]
        for f in files:
            if not f.endswith(".docx"):
                continue
            path = os.path.join(root, f)
            try:
                doc = get_docx(path)
                text = "\n".join(p.text for p in doc.paragraphs)
                for tab in doc.tables:
                    for row in tab.rows:
                        for c in row.cells:
                            text += "\n" + c.text
                
                rel_path = os.path.relpath(path, package_root)
                for m in filename_pattern.finditer(text):
                    fname = m.group(0)
                    if fname not in referenced:
                        referenced[fname] = set()
                    referenced[fname].add(rel_path)
            except Exception:
                continue
    
    # Find unresolved references (skip RETIRED_FILES — historical narrative references)
    for fname, referrers in sorted(referenced.items()):
        if fname not in package_filenames and fname not in RETIRED_FILES:
            for ref in sorted(referrers):
                findings.append((
                    "MIN", "CROSS-REF-UNRESOLVED", ref,
                    f"References '{fname}' which is not a file in the package"
                ))
    
    return findings




# ============================================================================
# v3.7.54 ADDITIONS: Findability and Per-Page Metadata Consistency Checks
# ============================================================================



def check_findability(verbose=False):
    """FINDABILITY check: named interactive tools must have direct links from index.html.
    
    Added in v3.7.54 to prevent regression of the v3.7.53 finding that both
    calculators were only discoverable through the platform_index catalog filter.
    """
    findings = []
    NAMED_TOOLS = [
        ("06_We_The_People_Calculator.html", "We The People Tax Calculator"),
        ("06_Wage_Floor_Comparison_Calculator.html", "Wage Floor Comparison Calculator"),
    ]
    LANDING_PAGE = "index.html"
    
    if not os.path.exists(LANDING_PAGE):
        return findings
    
    with open(LANDING_PAGE, encoding="utf-8", errors="replace") as f:
        content = f.read()
    
    for tool_filename, tool_display_name in NAMED_TOOLS:
        # Check if the tool is referenced directly in the landing page
        # (not just in a script-embedded catalog)
        if tool_filename not in content:
            findings.append((
                "MIN", "FINDABILITY", LANDING_PAGE,
                f"Named tool '{tool_display_name}' ({tool_filename}) not linked from {LANDING_PAGE}"
            ))
        elif verbose:
            print(f"  [FINDABILITY OK] {tool_display_name} linked from {LANDING_PAGE}")
    
    return findings


def check_per_page_metadata_consistency(verbose=False):
    """METADATA-CONSISTENCY check: per-page doc count claims must match catalog.
    
    Added in v3.7.54 to prevent regression of the v3.7.54 finding that index.html
    header showed '109 Documents' while catalog had 112.
    
    Scans each web page for patterns like '<strong>NNN</strong> <em>Documents</em>'
    or 'NNN documents' and verifies the displayed count matches the catalog count.
    Historical references in README.txt and VERSIONLOG.txt are appropriately
    excluded (they reference past iterations and should retain past counts).
    """
    findings = []
    
    catalog_path = "00_GUI_Files/platform_catalog.json"
    if not os.path.exists(catalog_path):
        return findings
    
    cat = get_catalog()  # v3.7.90 cached
    # v3.7.443: display assertions compare to the PUBLIC-facing count (what is
    # shown to readers), not the total. Total is tracked as data elsewhere.
    catalog_count = sum(1 for d in cat.get("documents", []) if not d.get("private")) \
        or len(cat.get("documents", []))
    
    if catalog_count == 0:
        return findings
    
    PAGES_TO_CHECK = ["index.html", "about.html", "downloads.html"]
    
    for page in PAGES_TO_CHECK:
        if not os.path.exists(page):
            continue
        content = get_text_file(page)  # v3.7.90 cached
        
        # Pattern 1: header meta items like '<strong>112</strong> <em>Documents</em>'
        header_matches = re.findall(r'<strong>(\d{2,4})</strong>\s*<em>Documents</em>', content)
        for match in header_matches:
            if int(match) != catalog_count:
                findings.append((
                    "MIN", "METADATA-CONSISTENCY", page,
                    f"header shows '{match} Documents' but catalog has {catalog_count}"
                ))
                break  # Only report first mismatch per page per pattern
        
        # Pattern 2: prose like '112 documents' (in landing copy)
        # Be permissive: only flag if the number is 3 digits and within plausible range
        prose_matches = re.findall(r'\b(\d{2,4})\s+documents\s+organized', content, re.IGNORECASE)
        for match in prose_matches:
            count = int(match)
            if 50 <= count <= 300 and count != catalog_count:
                findings.append((
                    "MIN", "METADATA-CONSISTENCY", page,
                    f"landing copy says '{match} documents organized' but catalog has {catalog_count}"
                ))
                break
    
    return findings





def check_css_insertions(verbose=False):
    """CSS-INSERTION verification check (added v3.7.57).
    
    Verifies that critical CSS rule definitions exist in their expected pages.
    Catches the class of regression where HTML markup uses a class (e.g. .tool-card)
    but the corresponding CSS rule definition is missing from the page's <style>
    block — which previously broke the Interactive Tools cards in v3.7.53 through
    v3.7.55 before being caught by user observation in v3.7.56.
    
    The CRITICAL_CSS_RULES registry below defines which CSS rules MUST exist
    in which pages. Add new entries here whenever a new HTML pattern is added
    that depends on specific CSS rules. The audit will then catch silent
    insertion failures automatically.
    """
    findings = []
    
    # Critical CSS rules per page. Pattern: file_path → list of CSS selectors
    # that must have rule definitions in the page's <style> block.
    CRITICAL_CSS_RULES = {
        "index.html": [
            ".tool-card",
            ".tools-grid",
            ".tool-card-eyebrow",
            ".tool-card-body",
            ".tool-card-cta",
            ".section-lede",
            ".landing-hero",
            ".landing-section",
            ".landing-subhead",
            ".landing-principles",
            ".landing-hero-title",
            ".tricolor-band",
            ".tricolor-band-footer",
            ".header-meta-item",
            ".page-nav-link",
            ".section-eyebrow",
        ],
    }
    
    # Import the helper. Fallback if not available.
    try:
        sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
        from build_helpers import verify_css_insertion_in_file
    except ImportError:
        # Helper not available; emit OBS finding and return
        findings.append((
            "OBS", "CSS-CHECK-UNAVAILABLE", "audit_script.py",
            "build_helpers.verify_css_insertion_in_file not importable; CSS-insertion check skipped"
        ))
        return findings
    
    for page_path, expected_selectors in CRITICAL_CSS_RULES.items():
        if not os.path.exists(page_path):
            continue
        ok, missing, msg = verify_css_insertion_in_file(page_path, expected_selectors)
        if not ok:
            for sel in missing:
                findings.append((
                    "MIN", "CSS-INSERTION-MISSING", page_path,
                    f"CSS rule '{sel}' not defined in <style> block (HTML may use this class but it has no styling)"
                ))
        elif verbose:
            print(f"  [CSS-CHECK OK] {page_path}: {msg}")
    
    return findings




def check_renderCard_simulation(verbose=False):
    """CATALOG-RENDERCARD simulation check (added v3.7.61).
    
    Simulates the field-access pattern that platform_index.html's renderCard() function
    performs on each catalog document, catching the class of bug that brought down the
    Documents page in v3.7.59 and v3.7.60: when a catalog entry lacks fields the JS
    expects (pillars, tags, description, fileType), renderCard throws TypeError mid-loop
    and rendering halts, leaving the 'Loading platform catalog...' message visible.
    
    This check walks the actual catalog data and verifies every document has the fields
    renderCard accesses, catching silent insertion failures at audit time rather than
    when a user reports the symptom.
    
    Required fields based on renderCard analysis:
      - d.num               — for № ${num} display
      - d.title             — for doc-title text
      - d.path              — for href and download
      - d.pillars (array)   — for d.pillars.forEach
      - d.tags (array)      — for d.tags.slice(0, 3).forEach
      - d.description (str) — for d.description.replace(...)
      - d.fileType          — for class name "t-${fileType}"
    """
    findings = []
    
    catalog_path = "00_GUI_Files/platform_catalog.json"
    if not os.path.exists(catalog_path):
        findings.append((
            "OBS", "RENDERCARD-CHECK-SKIPPED", catalog_path,
            "platform_catalog.json not found; renderCard simulation skipped"
        ))
        return findings
    
    try:
        cat = get_catalog()  # v3.7.90 cached
    except (json.JSONDecodeError, Exception) as e:
        findings.append((
            "MIN", "RENDERCARD-CATALOG-UNPARSEABLE", catalog_path,
            f"Catalog JSON unparseable: {e}"
        ))
        return findings
    
    documents = cat.get("documents", [])
    if verbose:
        print(f"  [renderCard-sim] Walking {len(documents)} documents...")
    
    # Required fields and their type validators
    required_field_validators = {
        "num": lambda v: v is not None,
        "title": lambda v: isinstance(v, str) and len(v) > 0,
        "path": lambda v: isinstance(v, str) and len(v) > 0,
        "pillars": lambda v: isinstance(v, list),
        "tags": lambda v: isinstance(v, list),
        "description": lambda v: isinstance(v, str),
        "fileType": lambda v: isinstance(v, str) and len(v) > 0,
    }
    
    for d in documents:
        title = d.get("title", "(no title)")[:60]
        for field, validator in required_field_validators.items():
            if field not in d:
                findings.append((
                    "MIN", "RENDERCARD-FIELD-MISSING", catalog_path,
                    f"Document '{title}' missing field '{field}' (renderCard will crash on d.{field})"
                ))
            elif not validator(d[field]):
                findings.append((
                    "MIN", "RENDERCARD-FIELD-INVALID", catalog_path,
                    f"Document '{title}' field '{field}' has invalid type/value (renderCard will crash on d.{field})"
                ))
        
        # Additional check: tags must be a list (so .slice() works)
        tags = d.get("tags")
        if tags is not None and not isinstance(tags, list):
            findings.append((
                "MIN", "RENDERCARD-TAGS-NOT-LIST", catalog_path,
                f"Document '{title}' tags is not a list (renderCard d.tags.slice() will crash)"
            ))
        
        # Additional check: pillars must be a list (so .forEach() works)
        pillars = d.get("pillars")
        if pillars is not None and not isinstance(pillars, list):
            findings.append((
                "MIN", "RENDERCARD-PILLARS-NOT-LIST", catalog_path,
                f"Document '{title}' pillars is not a list (renderCard d.pillars.forEach will crash)"
            ))
    
    return findings


# === PILLAR REFERENCE CHECK (added v3.7.70 per OIR Section 176 candidate) ===

def check_pillar_references(verbose=False):
    """Walk every "Pillar N (Name)" reference in shipped .docx files and verify
    it matches the canonical pillar name at index N in platform_catalog.json.

    Origin: pillar numbering errors in v3.7.68 (caught in v3.7.69) revealed that
    a stale mental model of pillar architecture had been used during document
    authoring. OIR Section 176 tracked this audit-script extension as a future
    candidate; implemented in v3.7.70."""
    import os, re, json
    from docx import Document

    findings = []

    catalog_path = os.path.join("00_GUI_Files", "platform_catalog.json")
    if not os.path.exists(catalog_path):
        return findings

    try:
        cat = get_catalog()  # v3.7.90 cached
        canonical = {int(p['id']): p['name'] for p in cat.get('pillars', [])}
    except Exception:
        return findings

    if not canonical:
        return findings

    NUM_TO_WORD = {1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",
                   7:"Seven",8:"Eight",9:"Nine",10:"Ten",11:"Eleven",12:"Twelve"}
    WORD_TO_NUM = {v: k for k, v in NUM_TO_WORD.items()}

    ALIASES = {
        "Universal Healthcare Access": ["Universal Healthcare", "Healthcare", "healthcare"],
        "Universal Mental Health Access": ["Universal Mental Health", "Mental Health", "mental health"],
        "Universal Childcare": ["Childcare", "childcare"],
        "Universal Paid Family Time": ["Paid Family Time", "paid family time"],
        "Universal Long-Term Care": ["Long-Term Care", "long-term care", "LTC"],
        "Empirical Wage Floors": ["Wage Floors", "wage floors"],
        "Sovereign Education Fund": ["Sovereign Education", "Education Fund"],
        "Climate Architecture": ["Climate"],
        "Federal Housing Investment": ["Federal Housing", "Housing Investment"],
        "Community Contribution Plan": ["Community Contribution", "CCP"],
        "Civic Infrastructure": [],
        "Immigration Architecture": ["Immigration"],
    }

    HISTORICAL_FILES = {
        "09_Open_Issues_Registry.docx",
        "09_OIR_Iteration_Archive.docx",  # added v3.7.81 — archive contains historical pillar references
        "01_Platform_Package_Version.docx",
    }

    PATTERN_NUM = re.compile(r'Pillar\s+(\d+)\s*\(([^()\n]{2,60}?)\)')
    PATTERN_WORD = re.compile(r'Pillar\s+(One|Two|Three|Four|Five|Six|Seven|Eight|Nine|Ten|Eleven|Twelve)\s*\(([^()\n]{2,60}?)\)')

    def is_numeric_or_cost(text):
        if re.search(r'[\$%]', text): return True
        if re.search(r'\d+[\s\-]', text): return True
        if any(w in text.lower() for w in ['billion', 'million', 'percent', 'trillion']): return True
        return False

    def matches_canonical(label, canonical_name, aliases):
        label_low = label.lower().strip()
        canon_low = canonical_name.lower().strip()
        if label_low == canon_low: return True
        if label_low.startswith("the ") and label_low[4:] == canon_low: return True
        if label_low in [a.lower() for a in aliases]: return True
        if label_low.startswith(canon_low + ",") or label_low.startswith(canon_low + ";"): return True
        for a in aliases:
            a_low = a.lower()
            if label_low.startswith(a_low + ",") or label_low.startswith(a_low + ";"): return True
        return False

    mismatch_count = 0
    historical_count = 0

    for root, dirs, files in os.walk("."):
        if any(skip in root for skip in ["_web_html", "__pycache__", "_downloads"]):
            continue
        for f in files:
            if not f.endswith(".docx"): continue
            path = os.path.join(root, f).lstrip("./")
            try:
                doc = get_docx(path)  # v3.7.90 cached
                text = "\n".join(p.text for p in doc.paragraphs)
                for t in doc.tables:
                    for row in t.rows:
                        for cell in row.cells:
                            text += "\n" + cell.text

                for pat in [PATTERN_NUM, PATTERN_WORD]:
                    for m in pat.finditer(text):
                        num_str = m.group(1)
                        label = m.group(2).strip()
                        num = int(num_str) if num_str.isdigit() else WORD_TO_NUM.get(num_str)
                        if num is None: continue
                        expected = canonical.get(num, "")
                        if not expected: continue
                        aliases = ALIASES.get(expected, [])

                        if matches_canonical(label, expected, aliases): continue
                        if is_numeric_or_cost(label): continue

                        if f in HISTORICAL_FILES:
                            if (path, num, label) in PILLAR_REF_ALLOWLIST:
                                continue
                            findings.append((
                                "OBS", "PILLAR-REF-HISTORICAL", path,
                                f"Pillar {num} ({label!r}) does not match canonical {expected!r} (likely HISTORICAL ACCURATE)"
                            ))
                            historical_count += 1
                        else:
                            findings.append((
                                "MIN", "PILLAR-REF-MISMATCH", path,
                                f"Pillar {num} labeled as {label!r} but canonical is {expected!r}"
                            ))
                            mismatch_count += 1
            except Exception:
                continue

    if verbose:
        print(f"  Pillar reference check: {mismatch_count} mismatches, {historical_count} historical observations")

    return findings


def check_section_number_uniqueness(verbose=False):
    """Detect duplicate Heading 1 section numbers in section-numbered documents.

    A 'section-numbered document' is any .docx file containing 2+ Heading 1
    paragraphs whose text starts with 'Section N:' where N is an integer.
    The OIR (Open Issues Registry) is the primary example. The Platform
    Package TOC is another.

    Reports duplicate section numbers as MIN findings (would break cross-
    references and audit traceability). Also reports gaps in numbering as
    OBS findings (informational; gaps may be intentional from renumbering
    history but are worth surfacing).

    Tracked in OIR Section 184 as future candidate; implemented in v3.7.78.
    The same issue class was found and resolved in v3.7.77 by a local harden-
    cycle check. Promoting to the standard audit means this regression class
    is caught on every audit invocation rather than only periodically.
    """
    import os, re
    findings = []
    duplicate_count = 0
    gap_count = 0

    try:
        from docx import Document
    except ImportError:
        return findings

    # Walk all .docx files looking for section-numbered structure
    for root, dirs, files in os.walk("."):
        if any(x in root for x in ["_web_html", "_downloads", "_data_archive",
                                    "__pycache__", "_templates", ".git"]):
            continue
        for f in files:
            if not f.endswith(".docx") or f.startswith("~$"):
                continue
            path = os.path.join(root, f).lstrip("./")
            try:
                doc = get_docx(path)  # v3.7.90 cached
            except Exception:
                continue
            if doc is None:  # v3.7.592: skip docx that failed to parse (e.g. Office lock files)
                continue

            # Collect H1 paragraphs with "Section N:" pattern
            section_numbers = []
            for p in doc.paragraphs:
                if p.style and p.style.name == "Heading 1":
                    m = re.match(r'^Section (\d+):', p.text.strip())
                    if m:
                        section_numbers.append(int(m.group(1)))

            # Require at least 2 such headings to consider this a section-numbered doc
            if len(section_numbers) < 2:
                continue

            # Check for duplicates
            seen = {}
            for n in section_numbers:
                seen[n] = seen.get(n, 0) + 1
            duplicates = sorted(num for num, count in seen.items() if count > 1)
            for dup in duplicates:
                count = seen[dup]
                findings.append((
                    "MIN", "SECTION-NUMBER-DUPLICATE", path,
                    f"Section {dup} appears {count} times as Heading 1 (cross-references to this section will be ambiguous)"
                ))
                duplicate_count += 1

            # Check for gaps (informational only)
            if section_numbers:
                expected = set(range(1, max(section_numbers) + 1))
                actual = set(section_numbers)
                allowed_gaps = EXPECTED_SECTION_GAPS.get(os.path.basename(path), set())
                gaps = sorted((expected - actual) - allowed_gaps)
                if gaps:
                    # Don't flood — summarize as a single OBS per document
                    gaps_display = ", ".join(str(g) for g in gaps[:10])
                    if len(gaps) > 10:
                        gaps_display += f", ... ({len(gaps)} gaps total)"
                    findings.append((
                        "OBS", "SECTION-NUMBER-GAP", path,
                        f"Section numbering has {len(gaps)} gap(s) in range 1-{max(section_numbers)}: {gaps_display}"
                    ))
                    gap_count += 1

    if verbose:
        print(f"  Section number uniqueness check: {duplicate_count} duplicates, {gap_count} docs with gaps")

    return findings


def check_html_class_css_existence(verbose=False):
    """Verify that every HTML class used on each page is defined by at least
    one CSS rule on that page. Catches the v3.7.71 pattern where landing-*
    HTML classes were used in markup without corresponding CSS rules.

    Reports findings as OBS (informational), not MIN, because many classes are
    legitimately unstyled — JavaScript-targeting selectors, ARIA classes,
    framework hooks, semantic markers. The audit surfaces unstyled classes for
    human review without blocking the build.

    Tracked in OIR Section 182 as future candidate; implemented in v3.7.76.
    """
    import os, re
    findings = []
    unstyled_count = 0

    # v3.7.816: resolve against package_root like every other check. This alone
    # among the 57 checks read relative paths from the current working directory,
    # so it would have silently examined nothing if the audit were ever invoked
    # from elsewhere. Never noticed, because it was never called.
    PAGES = [
        "index.html", "about.html", "contact.html", "privacy.html", "downloads.html",
        "platform_index.html", "sla.html",
        "06_Presentation_Materials/06_We_The_People_Calculator.html",
        "06_Presentation_Materials/06_Wage_Floor_Comparison_Calculator.html",
    ]

    INTENTIONAL_UNSTYLED = {
        "sr-only", "visually-hidden",
        "active", "selected", "hidden", "open", "closed", "disabled", "loading",
        "expanded", "collapsed", "current", "visible",
        # v3.7.262: additional intentionally-unstyled classes
        "nav-toggle-text",   # visually-hidden Menu label inside .nav-toggle button
        "search-input",      # JS-targeted input in search popover; uses input UA default + global
    }

    PAGES = [os.path.join(package_root, p) for p in PAGES]
    for page in PAGES:
        if not os.path.exists(page):
            continue
        c = get_text_file(page)  # v3.7.90 cached

        # Strip <style> and <script> before HTML class extraction
        html_no_style = re.sub(r'<style[^>]*>.*?</style>', '', c, flags=re.DOTALL)
        html_clean = re.sub(r'<script[^>]*>.*?</script>', '', html_no_style, flags=re.DOTALL)

        html_classes = set()
        for m in re.finditer(r'class="([^"]+)"', html_clean):
            for cls in m.group(1).split():
                if "${" in cls: continue
                if cls in INTENTIONAL_UNSTYLED: continue
                html_classes.add(cls)

        # v3.7.104: include linked CSS files (shared-CSS architecture)
        css_combined = get_combined_css_for_page(page)
        css_classes = set()
        for m in re.finditer(r'\.([a-zA-Z][\w\-]*)', css_combined):
            css_classes.add(m.group(1))

        unstyled = html_classes - css_classes
        for cls in sorted(unstyled):
            findings.append((
                "OBS", "HTML-CLASS-NO-CSS", page,
                f"HTML class '{cls}' is used but has no CSS rule defining it (may be JS-targeted, framework-handled, or unstyled by design)"
            ))
            unstyled_count += 1

    if verbose:
        print(f"  HTML class → CSS check: {unstyled_count} classes without CSS rules (informational)")

    return findings


def check_html_structural_consistency(package_root=".", verbose=False):
    """v3.7.107: catch HTML structural drift between pages.
    
    Specifically catches:
      - Duplicate tricolor-band elements (the bug caught in v3.7.107
        where wage_calc had 3 instead of 2, causing visual thickness)
      - main max-width inconsistency between pages
      - Missing page-sticky-wrap wrapper (the bug caught in v3.7.105)
    
    Reports as MIN since these directly affect visual consistency.
    """
    import os, re
    findings = []
    
    PAGES = [
        "index.html", "about.html", "contact.html", "privacy.html",
        "downloads.html", "platform_index.html", "sla.html",
        "06_Presentation_Materials/06_We_The_People_Calculator.html",
        "06_Presentation_Materials/06_Wage_Floor_Comparison_Calculator.html",
        "06_Presentation_Materials/06_Platform_At_A_Glance.html",
    ]
    
    for page in PAGES:
        if not os.path.exists(page):
            continue
        try:
            with open(page, encoding="utf-8", errors="replace") as f: c = f.read()
        except Exception:
            continue
        
        # Check 1: tricolor-band count in PAGE CHROME (exactly 2: header, footer).
        #
        # v3.7.816 SCOPE FIX. This counted EVERY tricolor-band on the page and expected
        # exactly 2. Correct in v3.7.107 when written. Since then pages gained modal
        # dialogs -- the document preview and the concerns panel -- which legitimately
        # carry their own band, so index.html has 4 and platform_index.html has 3 and
        # BOTH ARE CORRECT.
        #
        # The check had never run: defined but never invoked from main(), found during
        # the v3.7.816 scope-completeness sweep. Wiring it in unchanged would have
        # produced two findings against pages that are fine, and the obvious responses
        # -- raise the expected number, or delete the check -- would both have been
        # choosing a value to obtain a pass rather than describing a condition.
        #
        # The scope rule uses the marker structure the site already has rather than
        # inventing modal detection. Page chrome ends at SITE_FOOTER:END; modals are
        # emitted after it. Measured across every page, the count up to that marker is
        # exactly 2 everywhere, including the two pages that fail a naive whole-page
        # count. A first attempt tried to regex-match modal containers and matched
        # nothing, because it guessed at the markup instead of reading it.
        chrome_end = c.find("<!-- SITE_FOOTER:END -->")
        chrome = c if chrome_end < 0 else c[:chrome_end]
        tricolor_count = len(re.findall(r'class="tricolor-band(?:\s|")', chrome))
        if tricolor_count != 2:
            findings.append((
                "MIN", "HTML-TRICOLOR-COUNT", page,
                f"Page has {tricolor_count} tricolor-band elements in page chrome "
                f"(expected 2: one in header, one in footer); duplicates cause visual "
                f"thickening. Bands inside modal dialogs are excluded and are fine."
            ))
        
        # Check 2: page-sticky-wrap presence
        if 'class="page-sticky-wrap"' not in c:
            findings.append((
                "MIN", "HTML-MISSING-STICKY-WRAP", page,
                "Page missing <div class='page-sticky-wrap'> wrapper around header (required for sticky positioning + consistent layout)"
            ))
        
        # Check 3: main max-width (should be consistent across pages; home is canonical)
        # Extract top-level main rule max-width
        styles = "\n".join(re.findall(r'<style[^>]*>(.*?)</style>', c, re.DOTALL))
        # Strip @media for top-level only
        def strip_media(s):
            out = []; i = 0; n = len(s)
            while i < n:
                if s[i:i+6] == '@media':
                    br = s.find('{', i)
                    if br > 0:
                        depth = 1; j = br + 1
                        while j < n and depth > 0:
                            if s[j] == '{': depth += 1
                            elif s[j] == '}': depth -= 1
                            j += 1
                        i = j; continue
                out.append(s[i]); i += 1
            return ''.join(out)
        stripped = strip_media(styles)
        m = re.search(r'(?:^|[\s}])\s*main\s*\{[^}]*max-width\s*:\s*(\d+)px', stripped)
        if m:
            max_w = int(m.group(1))
            if max_w != 1400:
                findings.append((
                    "MIN", "CSS-MAIN-MAXWIDTH", page,
                    f"main max-width is {max_w}px (canonical is 1400px); content area will be wrong size"
                ))
    
    
        # Check 4 (v3.7.109): .header-meta has align-items: baseline
        # Prevents vertical alignment regression caught in v3.7.109 where meta items
        # with mixed <em>/<strong> internal order appeared at different Y positions
        # Check 4b (v3.7.111): .header-meta has explicit line-height
        # Prevents body line-height inheritance differences (e.g. Docs has 1.55,
        # Home has none) causing different meta Y positions across pages.
        m_meta_all = list(re.finditer(r'(?:^|[\s}])\s*\.header-meta\s*\{([^}]+)\}', stripped))
        for m_meta in m_meta_all:
            meta_props = m_meta.group(1)
            # Skip rules that are ONLY layout (e.g. @media variants); check rules with margin-top: 6px
            if 'margin-top: 6px' not in meta_props:
                continue
            if 'align-items' not in meta_props or 'baseline' not in meta_props:
                findings.append((
                    "MIN", "CSS-META-ALIGN", page,
                    ".header-meta missing align-items: baseline (required for consistent vertical alignment of items with mixed em/strong internal order)"
                ))
            if 'line-height' not in meta_props:
                findings.append((
                    "MIN", "CSS-META-LH", page,
                    ".header-meta missing explicit line-height (required to prevent body line-height inheritance from causing inter-page differences)"
                ))
            # Check for duplicate align-items (the wage_calc bug)
            if meta_props.count('align-items:') > 1:
                findings.append((
                    "MIN", "CSS-META-DUP-ALIGN", page,
                    ".header-meta has multiple align-items declarations (later one wins, defeats v3.7.109 baseline fix)"
                ))
        
    if verbose:
        print(f"  HTML structural consistency: {len(findings)} findings")
    return findings



def check_link_resolution(verbose=False):
    """Verify every href and src attribute on each page resolves to an existing
    file (for internal references). Filters out external schemes, JavaScript
    template literals (containing ${...}), pure anchors, and empty values.

    Reports unresolved internal references as MIN findings.

    Tracked in OIR Section 182 as future candidate; implemented in v3.7.76.
    """
    import os, re
    findings = []
    broken_count = 0

    # v3.7.748 hardening: previously a hardcoded 9-page list, which missed 14 served
    # pages (audio.html, recruit, share, errata, both other presentation pages, etc.).
    # A broken link on an unlisted page (e.g. audio.html's not-yet-created MP3s) shipped
    # unflagged. Discover ALL served HTML pages so coverage can't drift as pages are
    # added. Excludes rendered mirrors (_web_html) and the bot mirror, which are
    # generated and checked separately.
    import glob as _glob
    # v3.8.463: resolve from the PACKAGE ROOT, not the process working directory.
    # This check used relative paths, so running `py <pkg>/audit_script.py` from a
    # parent folder reported 114 LINK-BROKEN against a package whose files were all
    # present -- a clean package read as broken because of where the operator stood.
    _root = globals().get("PACKAGE_ROOT") or os.getcwd()
    PAGES = sorted(set(
        _glob.glob(os.path.join(_root, "*.html"))
        + _glob.glob(os.path.join(_root, "06_Presentation_Materials", "*.html"))
    ))

    broken_seen = set()

    for page in PAGES:
        if not os.path.exists(page):
            continue
        c = get_text_file(page)  # v3.7.90 cached

        # Strip <script> — JS template literals (${var}) live in script content
        html = re.sub(r'<script[^>]*>.*?</script>', '', c, flags=re.DOTALL)

        for m in re.finditer(r'(href|src)="([^"]+)"', html):
            attr = m.group(1)
            value = m.group(2)

            if value.startswith(('http://', 'https://', 'mailto:', 'tel:', 'data:', '//')):
                continue
            if "${" in value:
                continue
            if value.startswith('#'):
                continue
            if not value or value == "#":
                continue

            clean_value = value.split('?')[0].split('#')[0]
            if not clean_value:
                continue

            # v3.7.325: absolute paths starting with `/` are web-root-relative
            # (browsers resolve them from the domain root). Treat them as
            # relative to the package root (the audit working directory),
            # not to the filesystem root.
            if clean_value.startswith('/'):
                full_target = os.path.join(_root, clean_value.lstrip('/'))
            else:
                page_dir = os.path.dirname(page)
                full_target = (os.path.normpath(os.path.join(page_dir, clean_value))
                               if page_dir else os.path.join(_root, clean_value))

            if not os.path.exists(full_target):
                key = (page, value)
                if key in broken_seen:
                    continue
                broken_seen.add(key)
                # v3.7.748: the audio companion MP3s under /_audio/ are produced locally
                # by Jason (edge-tts) and are a KNOWN-PENDING item, not a defect — the
                # players/download links point at them ahead of production. Classify these
                # as OBS with an explicit note so the real state is visible (the links WILL
                # 404 on the live site until the MP3s are added) without false-blocking the
                # deploy gate. Any OTHER unresolved link stays MIN.
                # v3.7.767: no longer restricted to audio.html. index.html now carries the
                # gated hero listen-block, and the same rationale applies to any page that
                # points at a locally-produced MP3. Strict enforcement lives in the deploy
                # gate (tools/validate_audio_sync.py), which fails when the audio is live
                # and a referenced MP3 is missing, on ANY page — that is the check that
                # stops a broken player reaching the site, not this one.
                is_pending_audio = ("/_audio/" in value and value.endswith(".mp3"))
                if is_pending_audio:
                    findings.append((
                        "OBS", "LINK-PENDING-AUDIO", page,
                        f"{attr}=\"{value}\" not yet present (pending local MP3 production); "
                        f"this player/link will 404 on the live site until the audio is added"
                    ))
                else:
                    findings.append((
                        "MIN", "LINK-BROKEN", page,
                        f"{attr}=\"{value}\" does not resolve to an existing file (resolved as {full_target})"
                    ))
                    broken_count += 1

    if verbose:
        print(f"  Link resolution check: {broken_count} unresolved internal references")

    return findings


def check_reading_path_catalog_consistency(verbose=False):
    """Verify reading-path documents are consistent with the main catalog.

    Per v3.7.79, reading-path entries are stored per-document in
    doc.audiencePaths = {audienceId: {order, context}, ...} rather than in a
    top-level audiencePaths[].documents[] array. This check verifies:
    1. Each audience ID used in any doc.audiencePaths exists in the top-level
       audiencePaths metadata list. (MIN — broken reference.)
    2. Recently-tagged docs (recency = current version) that aren't in any
       reading path. (OBS — informational.)

    Backward compatibility: if a top-level audiencePaths entry still has a
    legacy .documents array, those entries are also validated (any path that
    doesn't match a catalog document path produces a MIN finding).

    Tracked in OIR Section 182; updated in v3.7.79 for new structure.
    """
    import os, json
    findings = []
    mismatch_count = 0
    orphan_count = 0

    catalog_path = "00_GUI_Files/platform_catalog.json"
    if not os.path.exists(catalog_path):
        return findings

    cat = get_catalog()  # v3.7.90 cached

    current_version = cat.get("platformVersion", "")
    catalog_paths = {d.get("path"): d for d in cat.get("documents", []) if d.get("path")}
    known_audience_ids = {ap.get("id") for ap in cat.get("audiencePaths", []) if ap.get("id")}
    reading_path_doc_paths = set()

    # New structure: walk doc.audiencePaths
    for d in cat.get("documents", []):
        doc_path = d.get("path", "")
        ap_field = d.get("audiencePaths", {})
        if not isinstance(ap_field, dict):
            continue
        for audience_id in ap_field.keys():
            reading_path_doc_paths.add(doc_path)
            if audience_id not in known_audience_ids:
                findings.append((
                    "MIN", "READING-PATH-UNKNOWN-AUDIENCE", catalog_path,
                    f"Document {doc_path} references audience '{audience_id}' which is not in top-level audiencePaths metadata"
                ))
                mismatch_count += 1

    # Legacy structure compatibility: validate any top-level audiencePaths[].documents[] entries
    for ap in cat.get("audiencePaths", []):
        audience_id = ap.get("id", "?")
        legacy_docs = ap.get("documents", [])
        if isinstance(legacy_docs, list):
            for rp_doc in legacy_docs:
                doc_path = rp_doc.get("path", "") if isinstance(rp_doc, dict) else ""
                reading_path_doc_paths.add(doc_path)
                if doc_path and doc_path not in catalog_paths:
                    findings.append((
                        "MIN", "READING-PATH-NOT-IN-CATALOG", catalog_path,
                        f"Reading path '{audience_id}' (legacy entry) references {doc_path} which has no matching catalog document"
                    ))
                    mismatch_count += 1

    # Surface recency orphans (recently-tagged docs not in any reading path).
    # Private documents are exempt: they are never part of public reading paths
    # by design (the same reason the web mirror, public index, sitemap, and bot
    # mirror all skip them), so absence from a reading path is correct, not an orphan.
    for d in cat.get("documents", []):
        recency = d.get("recency")
        if recency != f"v{current_version}":
            continue
        if d.get("private"):
            continue
        doc_path = d.get("path", "")
        if doc_path and doc_path not in reading_path_doc_paths:
            findings.append((
                "OBS", "READING-PATH-NEW-DOC-NOT-INCLUDED", catalog_path,
                f"Recently-added document {doc_path} (recency={recency}) is not yet included in any reading path"
            ))
            orphan_count += 1

    if verbose:
        print(f"  Reading-path catalog check: {mismatch_count} broken references, {orphan_count} new-doc reading-path candidates")

    return findings


def check_css_token_resolution(verbose=False):
    """Verify that every var(--TOKEN) reference in each HTML page's <style>
    blocks has a corresponding --TOKEN definition somewhere on the same page.

    Recognizes the var(--TOKEN, fallback) pattern: when a fallback is present,
    the reference is functionally complete even if the primary token isn't
    defined (the fallback renders correctly). These are reported as OBS rather
    than MIN since the page renders correctly.

    Tracked as future audit-script extension candidate in OIR Section 181;
    implemented in v3.7.75 per OIR Section 182.

    Returns list of findings with severity + finding code + path + message.
    """
    import os, re
    findings = []
    mismatch_count = 0
    fallback_count = 0

    PAGES = [
        "index.html", "about.html", "contact.html", "privacy.html", "downloads.html",
        "platform_index.html", "sla.html",
        "06_Presentation_Materials/06_We_The_People_Calculator.html",
        "06_Presentation_Materials/06_Wage_Floor_Comparison_Calculator.html",
    ]

    for page in PAGES:
        if not os.path.exists(page):
            continue
        c = get_text_file(page)  # v3.7.90 cached

        # Extract all <style> blocks; concatenate
        style_blocks = re.findall(r'<style[^>]*>(.*?)</style>', c, re.DOTALL)
        combined_css = get_combined_css_for_page(page)
        # v3.7.813: strip CSS comments before scanning. The checker previously read
        # comment prose as code, so a stylesheet whose header comment explained the
        # token convention -- and therefore contained the var() syntax as an example
        # -- reported an undefined token named "token". Documentation about the rule
        # tripped the rule. Comments cannot define or reference anything, so they are
        # removed from both the definition scan and the reference scan.
        combined_css = re.sub(r'/\*.*?\*/', ' ', combined_css, flags=re.DOTALL)

        # Find all token DEFINITIONS: --name: value;
        # v3.7.415: negative-lookbehind prevents BEM `.block--modifier:`
        # selectors from matching as CSS variable definitions.
        defined_tokens = set()
        for m in re.finditer(r'(?<![\w\-])--([\w\-]+)\s*:', combined_css):
            defined_tokens.add(m.group(1))

        # Find all token REFERENCES: var(--name) or var(--name, fallback)
        # Capture: (1) token name, (2) optional fallback content
        for m in re.finditer(r'var\(\s*--([\w\-]+)\s*(,\s*([^)]+))?\)', combined_css):
            token_name = m.group(1)
            has_fallback = m.group(2) is not None

            if token_name not in defined_tokens:
                if has_fallback:
                    # Fallback present — page renders correctly. OBS only.
                    findings.append((
                        "OBS", "CSS-TOKEN-UNDEFINED-FALLBACKED", page,
                        f"var(--{token_name}) is referenced without a definition, but a fallback is specified so the page renders correctly"
                    ))
                    fallback_count += 1
                else:
                    # No fallback — broken reference. MIN.
                    findings.append((
                        "MIN", "CSS-TOKEN-UNDEFINED", page,
                        f"var(--{token_name}) is referenced without a definition or fallback; will inherit parent value (likely unintended)"
                    ))
                    mismatch_count += 1

    if verbose:
        print(f"  CSS token resolution check: {mismatch_count} broken references, {fallback_count} with fallbacks (informational)")

    return findings



def check_css_token_definitions(verbose=False):
    """v3.7.93 — Detect CSS tokens defined SOMEWHERE in the package but referenced NOWHERE.

    Inverse of check_css_token_resolution (v3.7.75) which detects var() refs
    missing definitions. This check catches the v3.7.78 issue class: a canonical
    token set over-specified with members that no page actually uses.

    Cross-page semantics (refined v3.7.93): a token is reported as dead only if
    it is defined somewhere in the package but referenced via var() nowhere.
    This avoids false-positives on canonical-consistency tokens (defined on
    every page even when only some pages use them — a legitimate design pattern).

    Severity: OBS (defined-but-unused tokens don't break rendering; they're cruft).

    Uses get_site_html_pages() from the v3.7.90 cache layer + Calculator pages.
    """
    findings = []

    pages = list(get_site_html_pages().keys()) + [
        "06_Presentation_Materials/06_We_The_People_Calculator.html",
        "06_Presentation_Materials/06_Wage_Floor_Comparison_Calculator.html",
    ]

    defined_locations = {}  # token -> set of pages defining it
    referenced_anywhere = set()

    for page in pages:
        html = get_text_file(page)
        if not html:
            continue
        styles = "\n".join(re.findall(r"<style[^>]*>(.*?)</style>", html, re.DOTALL))
        if not styles:
            continue
        # v3.7.415: negative-lookbehind prevents BEM `.block--modifier:`
        # selectors from matching as CSS variable definitions. Without
        # this, `.wtpp-btn--subtle:hover` was producing a false-positive
        # CSS-TOKEN-DEFINED-UNUSED OBS for --subtle.
        for m in re.finditer(r"(?<![\w-])--([\w-]+)\s*:", styles):
            defined_locations.setdefault(m.group(1), set()).add(page)
        for m in re.finditer(r"var\(\s*--([\w-]+)", styles):
            referenced_anywhere.add(m.group(1))

    dead_tokens = set(defined_locations.keys()) - referenced_anywhere
    for token in sorted(dead_tokens):
        defining_pages = sorted(defined_locations[token])
        location_summary = ", ".join(defining_pages[:3])
        if len(defining_pages) > 3:
            location_summary += " (+" + str(len(defining_pages) - 3) + " more)"
        # v3.7.259: pass the first defining page as the doc identifier
        # so the 4-element-tuple expectation of the main report matches.
        primary_doc = defining_pages[0] if defining_pages else "various"
        findings.append(("OBS", "CSS-TOKEN-DEFINED-UNUSED", primary_doc,
            "--" + token + " is defined in [" + location_summary +
            "] but referenced nowhere in the package via var()"))

    if verbose:
        for sev, code, doc_, msg in findings:
            print("  [" + sev + "] " + code + ": " + msg)
    return findings


def audit_assetsignore(package_root):
    """v3.7.159 — ASSETSIGNORE-MISSING check.
    
    Verifies that .assetsignore is present at the repo root and excludes
    .git/ at minimum. If Cloudflare's Workers Builds is ever enabled
    (accidentally or by Cloudflare auto-offering Git integration on a new
    worker), this file prevents the specific failure mode that broke
    v3.7.158: Workers Builds scanning the repo root for assets and
    finding .git/objects/pack/*.pack exceeding the 25 MiB limit.
    
    Findings:
      - MIN if .assetsignore is missing entirely
      - MIN if .assetsignore exists but doesn't exclude .git/
    
    The audit check does not enforce the full list of exclusions — just
    the critical .git/ exclusion that caused the v3.7.158 failure. Other
    exclusions (tools/, _templates/, etc.) are recommended but not
    required.
    """
    findings = []
    assetsignore_path = os.path.join(package_root, ".assetsignore")
    
    if not os.path.exists(assetsignore_path):
        findings.append((
            "MIN", "ASSETSIGNORE-MISSING", ".assetsignore",
            ".assetsignore not present at repo root. If Cloudflare Workers "
            "Builds is enabled (intentionally or auto-detected), deploys may "
            "fail when scanning .git/ for assets (per the v3.7.158 failure). "
            "Create .assetsignore at repo root with at minimum '.git/' on a "
            "line by itself."
        ))
        return findings
    
    try:
        with open(assetsignore_path, encoding="utf-8") as f:
            content = f.read()
    except Exception as e:
        findings.append((
            "MIN", "ASSETSIGNORE-MISSING", ".assetsignore",
            f"Could not read .assetsignore: {e}"
        ))
        return findings
    
    # Check the critical exclusion: .git/ on a non-comment line
    has_git_exclusion = False
    for line in content.splitlines():
        stripped = line.strip()
        if stripped.startswith("#") or not stripped:
            continue
        if stripped == ".git/" or stripped == ".git":
            has_git_exclusion = True
            break
    
    if not has_git_exclusion:
        findings.append((
            "MIN", "ASSETSIGNORE-MISSING", ".assetsignore",
            ".assetsignore exists but does not exclude '.git/'. This was the "
            "specific cause of the v3.7.158 deploy failure (25 MiB pack file "
            "in .git/objects/pack/). Add '.git/' on a line by itself."
        ))
    
    return findings


def audit_readme_integrity(package_root):
    """v3.7.185 (SITE-38) — README per-version paragraph integrity.

    The README.txt accumulated 16 duplicate copies of post-v3.7.151
    content + a chain break between v3.7.175 and v3.7.151 (v3.7.152-174
    paragraphs never inserted at canonical location) before SITE-38
    cleanup in v3.7.185. This audit prevents recurrence:

    1. SIG: per-version paragraph appears more than once → flag the
       version ID and occurrence count.
    2. MIN: total README size exceeds 15,000 lines (post-cleanup
       baseline is ~6,584; growth to 15,000 would indicate accumulating
       duplication or unbounded prose addition that warrants review).

    Pattern detection: a "version-heading line" matches
    `^v\\d+\\.\\d+\\.\\d+\\s+\\([A-Za-z]+ \\d+, \\d+\\)` (the
    canonical version-paragraph opener). Continuation lines inside
    paragraph bodies that happen to start with "v3.7.X" do NOT match
    (they lack the date suffix).
    """
    findings = []
    readme_path = os.path.join(package_root, "README.txt")
    if not os.path.exists(readme_path):
        return findings
    with open(readme_path, encoding="utf-8") as f:
        text = f.read()

    line_count = text.count("\n") + 1

    # Find all version-heading lines and dedup
    version_re = re.compile(r"^v(\d+)\.(\d+)\.(\d+)\s+\([A-Za-z]+ \d+, \d+\)", re.MULTILINE)
    seen = {}
    for m in version_re.finditer(text):
        ver = f"{m.group(1)}.{m.group(2)}.{m.group(3)}"
        seen[ver] = seen.get(ver, 0) + 1

    duplicates = {v: c for v, c in seen.items() if c > 1}
    if duplicates:
        # Report up to 5 worst offenders to keep finding output bounded
        worst = sorted(duplicates.items(), key=lambda kv: -kv[1])[:5]
        for ver, count in worst:
            findings.append((
                "SIG", "README-INTEGRITY", "README.txt",
                f"v{ver} appears {count} times as a version-paragraph heading; expected exactly 1 (post-SITE-38 invariant)"
            ))
        if len(duplicates) > 5:
            findings.append((
                "SIG", "README-INTEGRITY", "README.txt",
                f"and {len(duplicates) - 5} more versions with duplicates (total: {len(duplicates)} versions; max count: {max(duplicates.values())})"
            ))

    # Size sanity check (post-cleanup baseline ~6,584; flag >15,000)
    if line_count > 15000:
        findings.append((
            "MIN", "README-INTEGRITY", "README.txt",
            f"line count {line_count} exceeds 15,000 (post-SITE-38 baseline ~6,584); review for accumulating duplication or unbounded prose"
        ))

    return findings


def audit_wrangler_config(package_root):
    """v3.7.156 — WRANGLER-CONFIG-DRIFT check.
    
    Sanity-checks the Cloudflare Wrangler configuration at
    cloudflare/wrangler.toml. If the file is missing or its expected
    values have drifted, the auto-deploy via GitHub Actions
    (.github/workflows/deploy-cloudflare-worker.yml) may push the wrong
    worker name or route binding to Cloudflare on next deploy.
    
    Expected values:
      - name = "wtpp-bot-greeting"
      - main = "worker.js"
      - route pattern includes "wethepeopleplatform.com"
      - compatibility_date is present
    
    These are sanity checks, not full TOML parsing — the audit script
    avoids adding tomllib/tomli as a hard dependency. Findings are MIN
    severity (drift is recoverable; misconfigured deploy can be fixed
    via wrangler.toml edit + redeploy).
    """
    findings = []
    wrangler_path = os.path.join(package_root, "cloudflare", "wrangler.toml")
    
    if not os.path.exists(wrangler_path):
        findings.append((
            "MIN", "WRANGLER-CONFIG-DRIFT", "cloudflare/wrangler.toml",
            "wrangler.toml not present; auto-deploy workflow will fail "
            "when triggered. Either remove .github/workflows/deploy-"
            "cloudflare-worker.yml or restore wrangler.toml."
        ))
        return findings
    
    try:
        with open(wrangler_path, encoding="utf-8") as f:
            wrangler_text = f.read()
    except Exception as e:
        findings.append((
            "MIN", "WRANGLER-CONFIG-DRIFT", "cloudflare/wrangler.toml",
            f"Could not read wrangler.toml: {e}"
        ))
        return findings
    
    expected_checks = [
        ("name", r'^name\s*=\s*"wtpp-bot-greeting"',
         'name = "wtpp-bot-greeting"'),
        ("main", r'^main\s*=\s*"worker\.js"',
         'main = "worker.js"'),
        ("route pattern", r'wethepeopleplatform\.com',
         'route pattern including wethepeopleplatform.com'),
        ("compatibility_date", r'^compatibility_date\s*=\s*"[0-9]{4}-[0-9]{2}-[0-9]{2}"',
         'compatibility_date = "YYYY-MM-DD"'),
    ]
    
    for label, pattern, expected in expected_checks:
        if not re.search(pattern, wrangler_text, re.MULTILINE):
            findings.append((
                "MIN", "WRANGLER-CONFIG-DRIFT", "cloudflare/wrangler.toml",
                f"missing or non-matching {label}; expected line like {expected!r}"
            ))
    
    return findings


def audit_readme_chain_drift(package_root):
    """v3.7.185 — README-CHAIN-DRIFT check.

    Verifies that every VERSION 3.7.x marker in VERSIONLOG.txt has a
    corresponding `v3.7.x (date) [tag]: ...` paragraph in README.txt at
    the canonical changelog section near the top.

    Catches SITE-38's class of bug: a v3.7.N narrative script's
    update_readme() targets the v3.7.N-1 heading as its insertion
    anchor, but if v3.7.N-1's entry was never actually inserted (perhaps
    because its own script had the same issue), the chain breaks
    silently and each subsequent iteration's script does nothing without
    raising any error.

    Returns MIN findings for each missing version. Does NOT flag
    extra README entries (versions in README but not VERSIONLOG) —
    those would only happen via test data or hand edits.

    The check is scoped to v3.7.x only (the active version family);
    legacy v2.x or v3.0-v3.6 entries are not required to be present.
    """
    findings = []
    readme_path = os.path.join(package_root, "README.txt")
    vl_path = os.path.join(package_root, "VERSIONLOG.txt")
    if not (os.path.exists(readme_path) and os.path.exists(vl_path)):
        return findings

    with open(readme_path, encoding="utf-8") as f:
        readme = f.read()
    with open(vl_path, encoding="utf-8") as f:
        vl = f.read()

    # Extract all v3.7.x versions present in VERSIONLOG
    vl_versions = set()
    for m in re.finditer(r"^VERSION 3\.7\.(\d+)\s", vl, re.MULTILINE):
        vl_versions.add(int(m.group(1)))

    # Extract all v3.7.x entries present in README.
    # v3.7.185: pattern made permissive — [tag] suffix is optional because
    # entries before v3.7.91 used `v3.7.N (Date): Title` without a [tag]
    # marker. The original strict pattern missed all 91 of those entries.
    readme_versions = set()
    for m in re.finditer(r"^v3\.7\.(\d+)\s+\([A-Z][a-z]+ \d+, \d{4}\)(?:\s*\[[^\]]+\])?\s*:", readme, re.MULTILINE):
        readme_versions.add(int(m.group(1)))

    # v3.7.185 (SITE-38): Recognize gap-placeholder paragraphs of the form
    # `v3.7.X — v3.7.Y (Date range): ...` as covering all versions in
    # the [X, Y] inclusive range. The cleanup script inserts one such
    # placeholder for v3.7.152 — v3.7.174 (the iterations whose
    # narratives were never inserted at canonical README location due
    # to the chain-of-targets bug; covered authoritatively in
    # VERSIONLOG.txt + OIR Sections 252-280). The placeholder is the
    # architecturally-correct closure — duplicating ~285 narratives
    # across README and VERSIONLOG would be bad architecture even
    # without the chain break.
    for m in re.finditer(r"^v3\.7\.(\d+)\s*[—–-]\s*v3\.7\.(\d+)\s+\(", readme, re.MULTILINE):
        lo = int(m.group(1))
        hi = int(m.group(2))
        if lo <= hi:
            for v in range(lo, hi + 1):
                readme_versions.add(v)

    # Report missing versions (in VERSIONLOG but not in README).
    # Scoped to v3.7.150+: older entries use a pre-tag README format
    # (`v3.7.X (date): description`, no bracketed `[tag]:`) that the
    # strict pattern above does not match. Back-filling 150 historical
    # entries in modern format provides no value to current readers
    # (the full history is preserved in VERSIONLOG.txt). The cutoff
    # lets the audit run clean for the current era while still
    # catching future chain breaks. Bump the cutoff if/when the
    # README is reformatted to put older entries into modern format.
    SCOPE_CUTOFF = 150
    missing = sorted(v for v in (vl_versions - readme_versions)
                     if v >= SCOPE_CUTOFF)
    for ver in missing:
        findings.append((
            "MIN", "README-CHAIN-DRIFT", "README.txt",
            f"VERSIONLOG.txt has VERSION 3.7.{ver} but README.txt has no matching v3.7.{ver} entry"
        ))

    return findings


def audit_meta_numeric_drift(package_root):
    """v3.7.151 — META-NUMERIC-DRIFT check.
    
    Compares hardcoded platform numerics in known drift-prone files against
    the canonical values in manifest.json. Catches the class of drift where
    a hand-typed number captures the value at write-time and falls out of
    sync with the catalog on subsequent releases.
    
    Files checked:
      - cloudflare/worker.js (PLATFORM_META block)
      - 01_Start_Here/01_What_This_Is.docx
      - 02_Vision_and_Communication/02_Outreach_Stewart_Drafts.docx
      - Stewart drafts catalog description (in platform_index.html and catalog sources)
    
    Numerics checked:
      - platform_version (e.g. '3.7.151')
      - documents (e.g. 126 or 'one-hundred-twenty-six')
      - pillars (e.g. 12 or 'twelve')
      - section_47_tracked_items (e.g. 81 or 'eighty-one')
    
    Returns list of (severity, code, location, message) tuples.
    """
    import json
    findings = []
    
    manifest_path = os.path.join(package_root, "manifest.json")
    if not os.path.exists(manifest_path):
        return findings
    
    try:
        with open(manifest_path, encoding="utf-8") as f:
            manifest = json.load(f)
    except Exception as e:
        findings.append((
            "MIN", "META-NUMERIC-DRIFT", "manifest.json",
            f"Could not parse manifest.json: {e}"
        ))
        return findings
    
    canonical_version = manifest.get("platform_version", "")
    canonical_docs = manifest.get("totals", {}).get("documents", 0)
    # v3.7.443: public-facing count drives DISPLAY text; total drives data.
    canonical_public = manifest.get("totals", {}).get("publicDocuments", canonical_docs)
    canonical_pillars = manifest.get("totals", {}).get("pillars", 0)
    # v3.7.154: tracked_issues is now a structured object with open/closed/total.
    # The deprecated section_47_tracked_items alias is still emitted for one
    # release; check both for backward compatibility but prefer the structured
    # form when present.
    tracked = manifest.get("totals", {}).get("tracked_issues", {})
    canonical_ti_total = tracked.get("total", manifest.get("totals", {}).get("section_47_tracked_items", 0))
    canonical_ti_open = tracked.get("open", 0)
    canonical_ti_closed = tracked.get("closed", 0)
    
    # Check Cloudflare worker.js
    worker_path = os.path.join(package_root, "cloudflare", "worker.js")
    if os.path.exists(worker_path):
        with open(worker_path, encoding="utf-8") as f:
            worker_text = f.read()
        
        checks = [
            ("version", canonical_version, r"version:\s*'([^']*)'"),
            ("totalDocuments", str(canonical_docs), r"totalDocuments:\s*(\d+)"),
            ("publicDocuments", str(canonical_public), r"publicDocuments:\s*(\d+)"),
            ("totalPillars", str(canonical_pillars), r"totalPillars:\s*(\d+)"),
            # v3.7.154: check the new structured fields
            ("trackedIssuesOpen", str(canonical_ti_open), r"trackedIssuesOpen:\s*(\d+)"),
            ("trackedIssuesClosed", str(canonical_ti_closed), r"trackedIssuesClosed:\s*(\d+)"),
            ("trackedIssuesTotal", str(canonical_ti_total), r"trackedIssuesTotal:\s*(\d+)"),
            # Deprecated alias — still must be kept in sync until v3.7.155+
            ("section47Tracked", str(canonical_ti_total), r"section47Tracked:\s*(\d+)"),
        ]
        for key, expected, pattern in checks:
            m = re.search(pattern, worker_text)
            if m and m.group(1) != expected:
                findings.append((
                    "MIN", "META-NUMERIC-DRIFT", "cloudflare/worker.js",
                    f"PLATFORM_META.{key} = {m.group(1)!r} should be {expected!r} per manifest.json"
                ))
    
    # Check orientation docs and Stewart drafts catalog description
    # Word-form numerics to verify
    def num_words(n):
        # Generic int → hyphenated word form (v3.7.152 fix — was hardcoded
        # to only handle 12/81/124/126, returned digit string for anything
        # else which broke equality checks against spelled-out catalog
        # entries when totalDocuments moved to 127).
        _ONES = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
                 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
                 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
        _TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy',
                 'eighty', 'ninety']
        if n < 0 or n >= 1000:
            return str(n)
        if n < 20:
            return _ONES[n]
        if n < 100:
            t, o = divmod(n, 10)
            return _TENS[t] + ("-" + _ONES[o] if o else "")
        h, rest = divmod(n, 100)
        if rest == 0:
            return _ONES[h] + "-hundred"
        if rest < 20:
            return _ONES[h] + "-hundred-" + _ONES[rest]
        t, o = divmod(rest, 10)
        return _ONES[h] + "-hundred-" + _TENS[t] + ("-" + _ONES[o] if o else "")
    
    canonical_doc_words = num_words(canonical_docs)
    canonical_pillar_words = num_words(canonical_pillars)
    # v3.7.154: separate words for total/open/closed for the new vocabulary
    canonical_ti_total_words = num_words(canonical_ti_total)
    canonical_ti_open_words = num_words(canonical_ti_open)
    canonical_ti_closed_words = num_words(canonical_ti_closed)
    
    # Stale word-forms we want to catch
    stale_doc_words_124 = "one-hundred-twenty-four"
    stale_doc_words_125 = "one-hundred-twenty-five"
    
    doc_paths_to_check = [
        ("01_Start_Here/01_What_This_Is.docx", True),
        ("02_Vision_and_Communication/02_Outreach_Stewart_Drafts.docx", True),
        ("02_Vision_and_Communication/02_Outreach_PodSaveAmerica_Drafts.docx", True),
    ]
    
    for rel_path, is_docx in doc_paths_to_check:
        full_path = os.path.join(package_root, rel_path)
        if not os.path.exists(full_path):
            continue
        if is_docx:
            try:
                d = get_docx(full_path)
                text = "\n".join(p.text for p in d.paragraphs)
                for t in d.tables:
                    for r in t.rows:
                        for c in r.cells:
                            text += "\n" + c.text
            except Exception:
                continue
        else:
            with open(full_path, encoding="utf-8") as f:
                text = f.read()
        
        # Check for stale doc-count word forms (relative to canonical)
        # v3.8.562: require the DOCUMENT-count context. The bare word-form also matches other counts -- at
        # v3.8.562 the Tracked Issues Registry itself holds 124 items, and the correct sentence was flagged.
        if canonical_docs != 124 and re.search(re.escape(stale_doc_words_124) + r"\s+(public\s+)?documents", text):
            findings.append((
                "MIN", "META-NUMERIC-DRIFT", rel_path,
                f"contains stale word-form {stale_doc_words_124!r}; expected {canonical_doc_words!r} (docs={canonical_docs})"
            ))
        # v3.8.562: require the DOCUMENT-count context. The bare word-form also matches other counts -- at
        # v3.8.562 the Tracked Issues Registry itself holds 124 items, and the correct sentence was flagged.
        if canonical_docs != 125 and re.search(re.escape(stale_doc_words_125) + r"\s+(public\s+)?documents", text):
            findings.append((
                "MIN", "META-NUMERIC-DRIFT", rel_path,
                f"contains stale word-form {stale_doc_words_125!r}; expected {canonical_doc_words!r} (docs={canonical_docs})"
            ))
    
    # Check Stewart drafts catalog description in platform_index.html and source catalog
    catalog_paths = [
        "platform_index.html",
        "00_GUI_Files/platform_catalog.json",
        "00_GUI_Files/platform_catalog.js",
    ]
    for rel_path in catalog_paths:
        full_path = os.path.join(package_root, rel_path)
        if not os.path.exists(full_path):
            continue
        with open(full_path, encoding="utf-8") as f:
            text = f.read()
        # Look for "twelve pillars, one-hundred-twenty-N documents" patterns
        m = re.search(r"twelve pillars,\s*(one-hundred-twenty-\w+)\s*documents", text)
        if m and m.group(1) != canonical_doc_words:
            findings.append((
                "MIN", "META-NUMERIC-DRIFT", rel_path,
                f"Stewart drafts description: 'twelve pillars, {m.group(1)} documents' should be {canonical_doc_words!r}"
            ))

    # v3.7.179 (SITE-19): Check main HTML pages for hardcoded "N documents"
    # drift. The home page (index.html) and downloads.html embed the catalog
    # count in multiple places (meta description, Open Graph + Twitter Card
    # descriptions, body prose, visible stat displays). v3.7.151's prevention
    # tooling covered the Cloudflare worker meta and the orientation docs but
    # missed the main HTML pages. v3.7.179 closes the gap by adding this
    # check for the "<integer> documents" pattern in any main HTML file.
    # Pattern intentionally simple: catches the visible numeric drift class
    # without trying to parse semantic context.
    # v3.7.181 (SITE-41): extended to also catch "<integer> across <word>
    # folders" pattern, which was missed by the documents-only rule.
    main_html_paths = [
        "index.html",
        "downloads.html",
        "audio.html",
        "about.html",
        "platform_index.html",
        "contact.html",
        "privacy.html",
        "accessibility.html",
        "sla.html",
    ]
    for rel_path in main_html_paths:
        full_path = os.path.join(package_root, rel_path)
        if not os.path.exists(full_path):
            continue
        with open(full_path, encoding="utf-8") as f:
            text = f.read()
        # Find all "N documents" patterns where N is a small integer (catch the
        # exact drift class — not arbitrary numbers in CSS or scripts).
        # Bound: 100 <= N <= 999 to skip irrelevant matches like 1 document.
        for m in re.finditer(r"\b(\d{3})\s+documents\b", text):
            n = int(m.group(1))
            if n != canonical_public:
                findings.append((
                    "MIN", "META-NUMERIC-DRIFT", rel_path,
                    f"contains hardcoded '{n} documents'; expected '{canonical_public} documents' (public-facing count displayed)"
                ))
        # v3.7.181 (SITE-41): also check "N across X folders" pattern. The
        # landing-hero lede on platform_index used the phrasing "118 across
        # nine folders" which the documents-pattern check above missed.
        for m in re.finditer(r"\b(\d{2,3})\s+across\s+\w+\s+folders\b", text):
            n = int(m.group(1))
            if n != canonical_public:
                findings.append((
                    "MIN", "META-NUMERIC-DRIFT", rel_path,
                    f"contains hardcoded '{n} across N folders'; expected '{canonical_public} across N folders' (public-facing count displayed)"
                ))

    return findings


def check_tricolor_drift(verbose=False):
    """TRICOLOR-MIDDLE-STRIPE-DRIFT check (added v3.7.333).

    Catches the regression class fixed in v3.7.332: pages whose
    .tricolor-band span:nth-child(2) rule (the middle stripe of the
    American flag at the bottom of the site header) uses
    var(--paper, ...) as the background. Because --paper is overridden
    in dark mode, this causes the flag's middle stripe to darken when
    the site is viewed in dark mode. The middle stripe should always
    be white regardless of theme — the calc/arch pages had this right
    from inception (hardcoded #ffffff); the canonical pages had drifted
    over many iterations.

    Why a MIN finding rather than SIG: the visual defect is real but
    bounded to dark mode and to one specific UI element; the rest of
    the platform continues to render correctly. Worth catching, but
    not a launch blocker.
    """
    import glob
    findings = []
    # v3.7.456 generalization. Original v3.7.333 guard caught only var(--paper)
    # on the middle stripe in HTML. The v3.7.454 white-stripe regression slipped
    # past it: a different mode-varying token (var(--surface-card)) in a served
    # CSS file (wtpp-v239-fixes.css). This version scans the CSS source-of-truth
    # files (root *.css + _templates) and requires each stripe's background to
    # reference ONLY its pinned, mode-invariant flag token (or a true-flag
    # literal). Any other token (--red, --blue, --paper, --surface-card, ...) on
    # a flag stripe fails. Embedded per-page copies are derived from these
    # sources, so scanning the sources covers them without per-page noise.
    PINNED = {1: "--flag-red", 2: "--pure-white", 3: "--flag-blue"}
    LITERALS = {
        1: {"#b22234"},
        2: {"#fff", "#ffffff", "white", "rgb(255,255,255)"},
        3: {"#3c3b6e"},
    }
    STRIPE = {1: "red", 2: "white", 3: "blue"}
    rule_re = re.compile(
        r"\.tricolor-band\s+span:nth-child\((\d)\)\s*\{[^}]*?background:\s*([^;!}]+)",
        re.IGNORECASE)
    tok_re = re.compile(r"var\(\s*(--[\w-]+)")
    files = sorted(set(glob.glob("*.css") + glob.glob("_templates/*.css")))
    for path in files:
        try:
            content = open(path, encoding="utf-8", errors="ignore").read()
        except (FileNotFoundError, UnicodeDecodeError):
            continue
        for m in rule_re.finditer(content):
            n = int(m.group(1))
            if n not in PINNED:
                continue
            val = m.group(2).strip().rstrip(";")
            toks = tok_re.findall(val)
            ok = False
            if toks:
                ok = all(t == PINNED[n] for t in toks)   # only the pinned token may appear
            else:
                ok = re.sub(r"\s+", "", val).lower() in LITERALS[n]
            if not ok:
                findings.append((
                    "MIN", "TRICOLOR-STRIPE-TOKEN", path,
                    f".tricolor-band span:nth-child({n}) (the {STRIPE[n]} stripe) background "
                    f"'{val}' references a non-pinned/mode-varying value. It must use only "
                    f"var({PINNED[n]}) (or a true-flag literal) so the flag stays true "
                    f"red/white/blue in every theme — the v3.7.454 white-stripe regression class."
                ))
        if verbose:
            print(f"  [TRICOLOR] scanned {path}")
    return findings



# v3.7.438 (Option C companion guard): WEB-DOCX-PARITY. The doc pages are now
# regenerable via build_web_html.py --refresh-content (content-region splice that
# preserves chrome). This check guards against the failure mode that originally
# motivated Option C: docx content changes that never reach the web page. For each
# docx that has a _web_html page, it verifies (a) the page carries the DOCX_BODY
# content-region markers (architecture intact) and (b) every explicitly-styled
# Heading 1/2/3 in the docx appears in the page's body region. Heading text is
# compared after normalizing to lowercase alphanumerics (so pandoc's line-wrapping,
# entity-encoding, smart quotes, and em-dashes don't cause false positives), using
# a distinctive 6-word prefix. Severity OBS: surfaces drift without blocking; the
# remedy is to run `build_web_html.py --refresh-content`.
_PARITY_SKIP_DIRS = {"_web_html", "__pycache__", "07_External_Reviews",
                     "_downloads", "_licenses", "_data_archive", "_templates", "bots"}

def _parity_norm(s):
    s = re.sub(r'<[^>]+>', ' ', s)
    s = re.sub(r'[^a-z0-9 ]+', ' ', s.lower())
    return re.sub(r'\s+', ' ', s).strip()

def check_web_docx_parity(package_root="."):
    """Verify each docx's web page is in content-sync (Option C guard)."""
    findings = []
    for dp, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if d not in _PARITY_SKIP_DIRS and not d.startswith(".")
                   and not re.match(r"v\d+_work$", d)]
        for f in files:
            if not f.endswith(".docx") or f.startswith("~$"):
                continue
            docx = os.path.join(dp, f)
            rel = os.path.relpath(docx, package_root)
            html_path = os.path.join(package_root, "_web_html", rel[:-5] + ".html")
            if not os.path.exists(html_path):
                continue
            try:
                page = get_text_file(html_path)
            except Exception:
                page = open(html_path, encoding="utf-8", errors="ignore").read()
            i = page.find("<!-- DOCX_BODY:START -->")
            j = page.find("<!-- DOCX_BODY:END -->")
            if i == -1 or j == -1:
                findings.append(("OBS", "WEB-DOCX-PARITY", rel,
                    "web page not migrated to content-region markers (run build_web_html.py --refresh-content)"))
                continue
            nbody = _parity_norm(page[i:j])
            try:
                doc = get_docx(docx)
            except Exception:
                continue
            for p in doc.paragraphs:
                st = p.style.name if p.style else ""
                if st in ("Heading 1", "Heading 2", "Heading 3") and p.text.strip():
                    k = " ".join(_parity_norm(p.text).split()[:6])
                    if len(k.split()) >= 3 and k not in nbody:
                        findings.append(("OBS", "WEB-DOCX-PARITY", rel,
                            f"web page missing docx heading {p.text[:60]!r} "
                            "(run build_web_html.py --refresh-content)"))
    return findings



# v3.7.440: DL-PREFIX. Every static, resolvable download link must carry a
# we-the-people- prefixed `download` filename (the no-JS fallback baked at build;
# wtpp-download-naming.js adds the download-action date/timestamp at click). Guards
# the download-naming feature against regression. Dynamic links (href "#", "", a
# ${template}, javascript:/blob:) are skipped — their name is set by JS at runtime
# and normalized by the same handler. Matches the `download` ATTRIBUTE precisely
# (followed by =, whitespace, >, or /) so a class="download-card" token is not
# mistaken for the attribute. Severity MIN.
_DLP_DOWNLOADABLE = re.compile(r"\.(docx|zip|pdf|pptx|xlsx|png|jpg|jpeg|csv|md|txt|json)$", re.I)
_DLP_DYNAMIC = re.compile(r"^\s*$|^#|^javascript:|^blob:|\$\{")
_DLP_SKIP_DIRS = {"_downloads", "__pycache__", "_templates", "node_modules"}

def check_download_prefix(package_root="."):
    findings = []
    for dp, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if d not in _DLP_SKIP_DIRS
                   and not d.startswith(".") and not re.match(r"v\d+_work$", d)]
        for fn in files:
            if not fn.endswith(".html"):
                continue
            path = os.path.join(dp, fn)
            rel = os.path.relpath(path, package_root)
            try:
                html = get_text_file(path)
            except Exception:
                html = open(path, encoding="utf-8", errors="ignore").read()
            for tag in re.findall(r"<a\b[^>]*>", html):
                if not re.search(r"\sdownload(=|\s|>|/)", tag):
                    continue  # no real download attribute
                hm = re.search(r'href="([^"]*)"', tag)
                if not hm:
                    continue
                href = hm.group(1)
                if _DLP_DYNAMIC.match(href):
                    continue
                base = href.split("#")[0].split("?")[0]
                base = base[base.rfind("/") + 1:]
                if not _DLP_DOWNLOADABLE.search(base):
                    continue
                vm = re.search(r'\sdownload="([^"]*)"', tag)
                if not vm:
                    findings.append(("MIN", "DL-PREFIX", rel,
                        f"download link for {base} has no prefixed filename (bare download attribute) "
                        "(in-place patch or build_web_html template should set download=\"we-the-people-...\")"))
                elif not vm.group(1).startswith("we-the-people-"):
                    findings.append(("MIN", "DL-PREFIX", rel,
                        f"download filename lacks we-the-people- prefix: {vm.group(1)}"))
    return findings



# v3.7.441: DOC-COUNT. The footer document-count stat previously drifted
# (footers showed 127/128 while the package held 129) because nothing
# normalized it. normalize_header_version.py now syncs it from the catalog on
# every bump; this check guards that invariant and also covers the Cloudflare
# worker's bot-page count. Targets the site-footer-stat span and the worker's
# totalDocuments field precisely, so historical references in changelog/OIR
# prose are not flagged. Canonical source: platform_catalog.json. Severity MIN.
_DC_SPAN = re.compile(r'<span class="site-footer-stat">(\d+) DOCUMENTS</span>')
_DC_HDR = re.compile(r'<strong>(\d+)</strong> <em>Documents</em>')

def check_doc_count(package_root="."):
    findings = []
    try:
        cat = json.load(open(os.path.join(package_root, "00_GUI_Files", "platform_catalog.json"), encoding="utf-8", errors="replace"))
        total = int(cat["totalDocuments"])
        public = int(cat.get("publicDocuments", total))
        docs = cat.get("documents", [])
        derived_public = sum(1 for d in docs if not d.get("private")) if docs else public
    except Exception as e:
        return [("MIN", "DOC-COUNT", "00_GUI_Files/platform_catalog.json",
                 f"could not read catalog document counts: {e}")]
    # dual-count integrity: public must equal total minus private
    if docs and derived_public != public:
        findings.append(("MIN", "DOC-COUNT", "00_GUI_Files/platform_catalog.json",
            f"publicDocuments {public} != total {total} minus private ({total - derived_public}) = {derived_public}"))
    # manifest must carry both and agree
    mpath = os.path.join(package_root, "manifest.json")
    if os.path.exists(mpath):
        try:
            mt = json.load(open(mpath, encoding="utf-8", errors="replace"))["totals"]
            if int(mt.get("documents", -1)) != total:
                findings.append(("MIN", "DOC-COUNT", "manifest.json",
                    f"manifest totals.documents {mt.get('documents')} != catalog total {total}"))
            if int(mt.get("publicDocuments", -1)) != public:
                findings.append(("MIN", "DOC-COUNT", "manifest.json",
                    f"manifest totals.publicDocuments {mt.get('publicDocuments')} != catalog public {public}"))
        except Exception:
            pass
    # DISPLAYED count (footer) must be the PUBLIC count
    display = str(public)
    for dp, dirs, files in os.walk(package_root):
        dirs[:] = [d for d in dirs if d not in _DLP_SKIP_DIRS
                   and not d.startswith(".") and not re.match(r"v\d+_work$", d)]
        for fn in files:
            if not fn.endswith(".html"):
                continue
            path = os.path.join(dp, fn)
            rel = os.path.relpath(path, package_root)
            try:
                html = get_text_file(path)
            except Exception:
                html = open(path, encoding="utf-8", errors="ignore").read()
            for m in _DC_SPAN.finditer(html):
                if m.group(1) != display:
                    findings.append(("MIN", "DOC-COUNT", rel,
                        f"footer document count {m.group(1)} != public {display}"))
            for m in _DC_HDR.finditer(html):
                if m.group(1) != display:
                    findings.append(("MIN", "DOC-COUNT", rel,
                        f"header document count {m.group(1)} != public {display}"))
    # worker PLATFORM_META: publicDocuments is displayed (must == public); totalDocuments must == total
    wpath = os.path.join(package_root, "cloudflare", "worker.js")
    if os.path.exists(wpath):
        w = open(wpath, encoding="utf-8", errors="ignore").read()
        wp = re.search(r'publicDocuments:\s*(\d+)', w)
        wt = re.search(r'totalDocuments:\s*(\d+)', w)
        if wp and wp.group(1) != display:
            findings.append(("MIN", "DOC-COUNT", "cloudflare/worker.js",
                f"worker bot-page publicDocuments {wp.group(1)} != public {display}"))
        if wt and wt.group(1) != str(total):
            findings.append(("MIN", "DOC-COUNT", "cloudflare/worker.js",
                f"worker totalDocuments {wt.group(1)} != catalog total {total}"))
    return findings



# v3.7.442: DOWNLOAD-SET. The download bundle set had drifted three ways - the
# zips on disk, the entries in _downloads/manifest.json, and the cards linked
# from downloads.html disagreed (32 / 27 / 29), leaving orphaned bundles and an
# incomplete manifest. This check enforces that the three agree exactly, so a
# broken card link, an orphaned bundle, or a stale manifest is caught at ship
# time. Severity MIN.

# v3.7.446: BOT-MIRROR. The /bots/ AI-crawler mirror is generated by
# build_bot_mirror.py from manifest.json. It had frozen at v3.7.174 (124-127
# docs) because the generator was never in the ship pipeline. This check (plus
# wiring the generator into bump_version.py) ensures the mirror's displayed
# version and document count track the platform. Severity MIN.

# v3.7.447: CSS-DEBT-RATCHET. Hardcoded color literals (outside the token
# definition file) defeat the dark-mode theme system, which works by swapping
# token VALUES. This ratchet records a baseline count and fails if the count
# RISES, so the ~595-literal debt can only shrink. Severity MIN.
def check_css_debt_ratchet(package_root="."):
    import glob as _g
    findings = []
    bp = os.path.join(package_root, "tools", "css_debt_baseline.json")
    if not os.path.exists(bp):
        return findings
    base = json.load(open(bp, encoding="utf-8", errors="replace"))["baseline"]
    tot = 0
    for f in _g.glob(os.path.join(package_root, "*.css")):
        if os.path.basename(f) == "site-tokens.css":
            continue
        # count hardcoded literals in USAGES only; token DEFINITION lines
        # (--name: value) are the legitimate home for color literals, not debt
        _raw = open(f, encoding="utf-8", errors="ignore").read()
        # v3.7.469: strip /* */ comments before counting. A hex value mentioned
        # in a comment is documentation, not a theme-defeating usage, so it is
        # not debt; only real declaration usages are counted.
        _raw = re.sub(r"/\*.*?\*/", "", _raw, flags=re.DOTALL)
        for line in _raw.split("\n"):
            if re.match(r"\s*--[\w-]+\s*:", line):
                continue
            tot += len(re.findall(r"#[0-9a-fA-F]{3,8}\b|rgba?\([0-9][^)]*\)", line))
    if tot > base:
        findings.append(("MIN", "CSS-DEBT-RATCHET", "*.css",
            f"hardcoded-color literals rose to {tot} (baseline {base}); tokenize them or lower the baseline intentionally"))
    return findings


def check_bot_mirror(package_root="."):
    findings = []
    bots = os.path.join(package_root, "bots")
    idx = os.path.join(bots, "index.html")
    if not os.path.isdir(bots) or not os.path.exists(idx):
        return findings
    try:
        cat = json.load(open(os.path.join(package_root, "00_GUI_Files", "platform_catalog.json"), encoding="utf-8", errors="replace"))
        ver = cat["platformVersion"]
        public = int(cat.get("publicDocuments", cat["totalDocuments"]))
    except Exception as e:
        return [("MIN", "BOT-MIRROR", "bots", f"could not read platform version/count: {e}")]
    html = open(idx, encoding="utf-8", errors="ignore").read()
    if ver not in html:
        m = re.search(r'VERSION (3\.7\.\d+)', html) or re.search(r'(3\.7\.\d+)', html)
        findings.append(("MIN", "BOT-MIRROR", "bots/index.html",
            f"bot mirror shows version {m.group(1) if m else '?'} but platform is {ver} (run build_bot_mirror.py)"))
    cm = re.search(r'(\d+) DOCUMENTS', html)
    if cm and int(cm.group(1)) != public:
        findings.append(("MIN", "BOT-MIRROR", "bots/index.html",
            f"bot mirror shows {cm.group(1)} DOCUMENTS but public count is {public}"))
    return findings


def check_download_set(package_root="."):
    findings = []
    dl_dir = os.path.join(package_root, "_downloads")
    dh = os.path.join(package_root, "downloads.html")
    if not os.path.isdir(dl_dir) or not os.path.exists(dh):
        return findings
    disk = set(f for f in os.listdir(dl_dir) if f.endswith(".zip"))
    carded = set(re.findall(r'href="_downloads/([^"]+\.zip)"',
                            open(dh, encoding="utf-8", errors="ignore").read()))
    man = set()
    man_path = os.path.join(dl_dir, "manifest.json")
    if os.path.exists(man_path):
        try:
            man = set(d.get("filename") for d in json.load(open(man_path, encoding="utf-8", errors="replace"))["downloads"])
        except Exception:
            findings.append(("MIN", "DOWNLOAD-SET", "_downloads/manifest.json",
                             "manifest.json could not be parsed"))
    for z in sorted(carded - disk):
        findings.append(("MIN", "DOWNLOAD-SET", "downloads.html",
            f"download card links {z} but it is missing from _downloads/ (broken link)"))
    for z in sorted(disk - carded):
        findings.append(("MIN", "DOWNLOAD-SET", "_downloads",
            f"bundle {z} on disk is not linked from downloads.html (orphan)"))
    for z in sorted(disk - man):
        findings.append(("MIN", "DOWNLOAD-SET", "_downloads/manifest.json",
            f"bundle {z} on disk is not registered in the manifest"))
    for z in sorted(man - disk):
        findings.append(("MIN", "DOWNLOAD-SET", "_downloads/manifest.json",
            f"manifest registers {z} but it is missing from disk"))
    return findings


def audit_assumptions_registry_integrity(package_root):
    """v3.7.614 — ASSUMPTIONS-REGISTRY-INTEGRITY check.

    Verifies 00_GUI_Files/assumptions_registry.json (the machine-readable single
    source of truth for the platform's modeling assumptions, consumed by the
    stochastic analysis):
      * the file parses and declares entries (MIN otherwise).
      * each entry has the required fields id, name, category,
        validation_status, monte_carlo_role (MIN on any missing).
      * monte_carlo_role is one of the declared roles, and validation_status is
        one of the declared status values (MIN otherwise).
      * entry ids are unique (MIN on a duplicate).
      * each non-null open_issue_id resolves to a real Issue ID in the Open
        Issues Registry table (MIN on a dangling reference) — so a registry
        entry can never point at a tracked issue that does not exist.

    Prints a by-role / by-status breakdown as an informational line.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json")
    if not os.path.exists(reg_path):
        print("  Assumptions registry: not present (skipped)")
        return findings
    try:
        with open(reg_path, encoding="utf-8") as f:
            reg = json.load(f)
    except Exception as e:
        findings.append(("MIN", "ASSUM-REGISTRY-UNPARSEABLE", "assumptions_registry.json",
            f"could not parse registry: {e}"))
        print("  Assumptions registry: UNPARSEABLE")
        return findings

    entries = reg.get("entries", [])
    allowed_roles = set((reg.get("monte_carlo_roles") or {}).keys())
    allowed_status = set(reg.get("validation_status_values") or [])
    if not entries:
        findings.append(("MIN", "ASSUM-REGISTRY-EMPTY", "assumptions_registry.json",
            "registry declares no entries"))

    # resolve valid Issue IDs from the OIR table
    valid_ids = set()
    try:
        import docx as _docx
        oir = _docx.Document(os.path.join(package_root, "09_Meta_Tracking",
                                          "09_Open_Issues_Registry.docx"))
        for row in oir.tables[0].rows[1:]:
            cid = row.cells[0].text.strip()
            if cid:
                valid_ids.add(cid)
    except Exception:
        valid_ids = None  # cannot verify; skip the cross-reference check

    seen = set()
    from collections import Counter as _Counter
    roles, stats = _Counter(), _Counter()
    for e in entries:
        eid = e.get("id") or "(no-id)"
        for field in ("id", "name", "category", "validation_status", "monte_carlo_role"):
            if not e.get(field):
                findings.append(("MIN", "ASSUM-REGISTRY-FIELD", "assumptions_registry.json",
                    f"entry {eid}: missing required field '{field}'"))
        role = e.get("monte_carlo_role")
        status = e.get("validation_status")
        if role:
            roles[role] += 1
            if allowed_roles and role not in allowed_roles:
                findings.append(("MIN", "ASSUM-REGISTRY-ROLE", "assumptions_registry.json",
                    f"entry {eid}: monte_carlo_role '{role}' not in declared roles"))
        if status:
            stats[status] += 1
            if allowed_status and status not in allowed_status:
                findings.append(("MIN", "ASSUM-REGISTRY-STATUS", "assumptions_registry.json",
                    f"entry {eid}: validation_status '{status}' not in declared values"))
        if eid in seen:
            findings.append(("MIN", "ASSUM-REGISTRY-DUP-ID", "assumptions_registry.json",
                f"duplicate entry id {eid}"))
        seen.add(eid)
        oid = e.get("open_issue_id")
        if oid and valid_ids is not None and oid not in valid_ids:
            findings.append(("MIN", "ASSUM-REGISTRY-DANGLING", "assumptions_registry.json",
                f"entry {eid}: open_issue_id '{oid}' not found in the Open Issues Registry"))

    print(f"  Assumptions registry: {len(entries)} entries | by role {dict(roles)} | "
          f"by status {dict(stats)}")
    return findings


def audit_versionlog_header_fusion(package_root):
    """v3.7.713 — VERSIONLOG-HEADER-FUSION check.

    Guards VERSIONLOG.txt against the header-destruction defect class found
    (by hand) in v3.7.713: an in-session errata splice consumed the
    'VERSION 3.7.NNN' token of the following entry, fusing the errata
    paragraph with the next entry's date/title tail. Three headers
    (3.7.709/710/711) were destroyed this way in the shipped v3.7.712
    package, which also mis-attributed all their erratas to 3.7.712 in
    data/errata.json (build_errata.py tracks 'current version' while
    scanning, so a missing header silently shifts attribution).

    Two invariants (MIN on violation — ship-machinery regression guard):
      * FUSION SIGNATURE: no line may contain '[errata:' together with a
        fused header tail ('  ·  Month D, YYYY  (' on the same line).
        Errata lines end with prose; the date/title tail belongs to a
        VERSION header line.
      * UNDERLINE ORPHAN: every 70-char '=' underline must be immediately
        preceded by a line starting with 'VERSION ' — catching header
        deletion generally, not only the errata-fusion variant.

    Returns a list of (severity, code, location, message) findings.
    """
    findings = []
    vl_path = os.path.join(package_root, "VERSIONLOG.txt")
    if not os.path.exists(vl_path):
        return findings
    with open(vl_path, encoding="utf-8") as f:
        lines = f.read().split("\n")
    fused_re = re.compile(r"\[errata:.*·\s+\w+ \d+, \d{4}\s+\(")
    for i, line in enumerate(lines, start=1):
        if fused_re.search(line):
            findings.append(("MIN", "VERSIONLOG-HEADER-FUSION", f"VERSIONLOG.txt:{i}",
                "errata line fused with the next entry's date/title tail — "
                "a 'VERSION 3.7.NNN' header token has been consumed"))
    for i, line in enumerate(lines):
        if re.fullmatch(r"={70}", line):
            if i == 0 or not lines[i - 1].startswith("VERSION "):
                findings.append(("MIN", "VERSIONLOG-HEADER-FUSION", f"VERSIONLOG.txt:{i + 1}",
                    "entry underline (70 '=') not preceded by a 'VERSION ' header line — "
                    "header missing or destroyed"))
    return findings


def audit_conversation_tracking_integrity(package_root):
    """v3.7.612 — CONVERSATION-TRACKING-INTEGRITY check.

    Guards the two conversation-tracking files against silent corruption or
    drift (the failure class that produced the v3.7.609 remediation, where
    tracking had quietly fallen far behind the platform):

      - 09_Meta_Tracking/09_Conversation_Archive.md
            the export-based, REPLACE-on-refresh, full-fidelity ground truth.
      - 09_Meta_Tracking/09_Conversation_Log.md
            the parallel in-session extracts (forward-only, lower fidelity).

    Archive internal consistency (MIN on mismatch):
      * header '**Conversations included:** N' matches the count of
        '## Conversation K:' sections in the body.
      * each section's metadata '- **Messages:** M' matches the count of
        '### H/A' message headers within that section.
      * the per-section message metadata sums to the total '### H/A' headers.
      * the archive parses to a non-empty set of conversations and messages.

    Log internal consistency (MIN on mismatch):
      * each APPEND_MARKER's declared 'messages=N' matches the count of
        '### H/A' headers in the block that follows it.

    For the message-count comparisons the check flags only a SHORTFALL
    (actual < declared) — that is the truncation/half-write signature. An
    over-count is benign (a conversation body may quote the '### H' header
    format verbatim), so it is not flagged, which keeps the check free of
    false positives on legitimate content.

    Staleness is reported as an INFORMATIONAL line, never a finding: the
    archive is meant to lag between manual exports, so gating on its age
    would break the clean bar. The log's most-recent append iteration is
    printed alongside the current platform version so a growing gap is
    visible without blocking a ship (the deploy gate remains the place that
    acts on log currency).

    Returns a list of (severity, code, location, message) findings.
    """
    findings = []
    meta_dir = os.path.join(package_root, "09_Meta_Tracking")
    archive_path = os.path.join(meta_dir, "09_Conversation_Archive.md")
    log_path = os.path.join(meta_dir, "09_Conversation_Log.md")
    ha_re = re.compile(r'^### [HA]\d+ — ', re.M)

    # current platform version (for the staleness read; best-effort)
    cur_ver = None
    try:
        vj = os.path.join(package_root, "version.json")
        if os.path.exists(vj):
            with open(vj, encoding="utf-8") as f:
                cur_ver = json.load(f).get("platform_version")
    except Exception:
        cur_ver = None

    # --- Archive ---
    # v3.7.780: the archive may be split into size-capped part files
    # (09_Conversation_Archive.md + _part2.md + ...) to stay under Cloudflare's 25 MiB
    # per-file limit. Treat the parts as ONE logical archive: the '**Conversations
    # included:**' header on part 1 states the TOTAL, and the section/message checks sum
    # across every part. This keeps the guard's integrity contract intact (it still catches
    # the truncation/drift signature it was built for) while allowing the split.
    part_paths = []
    if os.path.exists(archive_path):
        part_paths.append(archive_path)
    stem = os.path.splitext(os.path.basename(archive_path))[0]
    extra = sorted(glob.glob(os.path.join(meta_dir, f"{stem}_part*.md")))
    part_paths.extend(extra)

    if part_paths:
        atext_parts = []
        for pp in part_paths:
            with open(pp, encoding="utf-8") as f:
                atext_parts.append(f.read())
        atext = "\n".join(atext_parts)
        # the total count lives on part 1's header; parts 2+ repeat the meta but the
        # canonical total is whichever header states it (they are written identically).
        m = re.search(r'\*\*Conversations included:\*\*\s*(\d+)', atext_parts[0])
        header_n = int(m.group(1)) if m else None
        sec_pos = [mm.start() for mm in re.finditer(r'^## Conversation \d+:', atext, re.M)]
        section_count = len(sec_pos)
        total_ha = len(ha_re.findall(atext))
        if len(part_paths) > 1:
            print(f"    conversation archive: {len(part_paths)} part file(s), "
                  f"{section_count} sections total (split to respect the 25 MiB limit)")

        if header_n is not None and header_n != section_count:
            findings.append(("MIN", "CONV-ARCHIVE-COUNT-DRIFT", "09_Conversation_Archive.md",
                f"header declares {header_n} conversations but body has {section_count} sections"))

        bounds = sec_pos + [len(atext)]
        sum_meta = 0
        for i in range(section_count):
            seg = atext[bounds[i]:bounds[i + 1]]
            first_ha = ha_re.search(seg)
            meta_region = seg[:first_ha.start()] if first_ha else seg
            mm = re.search(r'-\s*\*\*Messages:\*\*\s*([\d,]+)', meta_region)
            claimed = int(mm.group(1).replace(",", "")) if mm else None
            actual = len(ha_re.findall(seg))
            if claimed is not None:
                sum_meta += claimed
                if actual < claimed:
                    findings.append(("MIN", "CONV-ARCHIVE-SECTION-DRIFT", "09_Conversation_Archive.md",
                        f"conversation {i + 1}: metadata declares {claimed} messages "
                        f"but body has only {actual} (possible truncation)"))
        if section_count and sum_meta and total_ha < sum_meta:
            findings.append(("MIN", "CONV-ARCHIVE-TOTAL-DRIFT", "09_Conversation_Archive.md",
                f"section metadata sums to {sum_meta} messages but body has only "
                f"{total_ha} headers (possible truncation)"))
        if section_count == 0 or total_ha == 0:
            findings.append(("MIN", "CONV-ARCHIVE-EMPTY", "09_Conversation_Archive.md",
                "archive parsed to zero conversations or zero messages"))

        rm = re.search(r'\*\*Refreshed:\*\*\s*(.+)', atext)
        refreshed = rm.group(1).strip() if rm else "unknown"
        print(f"  Archive: {section_count} conversation(s), {total_ha} message(s); "
              f"refreshed {refreshed}")
    else:
        print("  Archive: not present (skipped)")

    # --- Log ---
    if os.path.exists(log_path):
        with open(log_path, encoding="utf-8") as f:
            ltext = f.read()
        markers = list(re.finditer(
            r"APPEND_MARKER:[^>]*?iteration='([^']+)'[^>]*?messages=(\d+)", ltext))
        mpos = [mm.start() for mm in markers]
        lbounds = mpos + [len(ltext)]
        for i, mm in enumerate(markers):
            claimed = int(mm.group(2))
            block = ltext[lbounds[i]:lbounds[i + 1]]
            actual = len(ha_re.findall(block))
            if actual < claimed:
                findings.append(("MIN", "CONV-LOG-APPEND-DRIFT", "09_Conversation_Log.md",
                    f"append for v{mm.group(1)} declares {claimed} messages "
                    f"but block has only {actual} (possible truncation)"))
        last_iter = markers[-1].group(1) if markers else None
        gap_note = ""
        if last_iter and cur_ver:
            try:
                lt = tuple(int(x) for x in last_iter.split("."))
                ct = tuple(int(x) for x in cur_ver.split("."))
                if lt < ct:
                    gap_note = f" — lags current platform v{cur_ver} (advisory only)"
                else:
                    gap_note = f" — current with platform v{cur_ver}"
            except ValueError:
                pass
        print(f"  Log: {len(markers)} append block(s); most-recent append for "
              f"v{last_iter}{gap_note}")
    else:
        print("  Log: not present (skipped)")

    return findings


def check_private_leak_guard(package_root="."):
    """Privacy guard for documents flagged private:true in the catalog.

    Mixes deterministic guarantees with one honest heuristic. Per the platform's
    own retrospective ("audits only catch the failure modes you already imagined"),
    the structural guards (A, B) are the real protection; the tripwire (C) is
    explicitly NON-EXHAUSTIVE and labelled OBS.

      A) PRIVATE-MIRROR-LEAK (MIN): a private doc must not have a rendered mirror
         in _web_html, an existing htmlPath mirror, or an entry in sitemap.xml or
         the /bots/ mirror. Catches the v3.7.629 Stewart-class leak (a private doc
         rendered and served publicly).
      B) PRIVATE-DEPLOY-GUARD (MIN): tools/deploy_to_github.py must both DEFINE and
         CALL strip_private_catalog_entries, so the deploy step that strips private
         metadata (titles/descriptions) from the deploy-copy catalog cannot silently
         regress.
      C) PRIVATE-METADATA-TRIPWIRE (OBS): a small, documented, NON-EXHAUSTIVE
         denylist of internal-only phrases must not appear in any public-served
         surface (the _web_html mirrors, the /bots/ mirror, or any public
         (non-private) catalog entry's title/description).
    """
    findings = []
    cat_path = os.path.join(package_root, "00_GUI_Files", "platform_catalog.json")
    try:
        cat = json.load(open(cat_path, encoding="utf-8"))
    except Exception as e:
        return [("MIN", "PRIVATE-LEAK-GUARD", "00_GUI_Files/platform_catalog.json",
                 f"could not read catalog: {e}")]
    docs = cat.get("documents", [])
    private_docs = [d for d in docs if d.get("private")]

    web_root = os.path.join(package_root, "_web_html")
    sitemap = os.path.join(package_root, "sitemap.xml")
    sitemap_txt = open(sitemap, encoding="utf-8", errors="ignore").read() if os.path.exists(sitemap) else ""
    bots_dir = os.path.join(package_root, "bots")
    bots_blob = ""
    if os.path.isdir(bots_dir):
        for r, _, fs in os.walk(bots_dir):
            for f in fs:
                if f.endswith((".html", ".xml", ".txt", ".json")):
                    try:
                        bots_blob += open(os.path.join(r, f), encoding="utf-8", errors="ignore").read()
                    except Exception:
                        pass

    # A) no public rendering / listing of private docs
    for d in private_docs:
        p = d.get("path", "")
        base = os.path.splitext(p)[0]
        if os.path.exists(os.path.join(web_root, base + ".html")):
            findings.append(("MIN", "PRIVATE-MIRROR-LEAK", p,
                f"private doc has a rendered web mirror at _web_html/{base}.html (must not be built/served)"))
        hp = d.get("htmlPath")
        if hp and os.path.exists(os.path.join(package_root, hp)):
            findings.append(("MIN", "PRIVATE-MIRROR-LEAK", p,
                f"private doc htmlPath mirror exists and would be served: {hp}"))
        leaf = (base.split("/")[-1] + ".html") if base else ""
        if leaf and leaf in sitemap_txt:
            findings.append(("MIN", "PRIVATE-MIRROR-LEAK", p,
                f"private doc appears in sitemap.xml ({leaf})"))
        if p and (p in bots_blob or (base and base.split("/")[-1] in bots_blob)):
            findings.append(("MIN", "PRIVATE-MIRROR-LEAK", p,
                "private doc appears in the /bots/ mirror"))

    # B) deploy sanitization must stay wired
    deploy_path = os.path.join(package_root, "tools", "deploy_to_github.py")
    if os.path.exists(deploy_path):
        dtxt = open(deploy_path, encoding="utf-8", errors="ignore").read()
        if not ("def strip_private_catalog_entries" in dtxt and "strip_private_catalog_entries(local" in dtxt):
            findings.append(("MIN", "PRIVATE-DEPLOY-GUARD", "tools/deploy_to_github.py",
                "deploy private-catalog sanitization is not wired (strip_private_catalog_entries must be "
                "DEFINED and CALLED in the Step 5 filter); private catalog metadata could deploy unsanitized"))
        else:
            # v3.7.748 hardening: the strip must cover ALL THREE catalog copies. The
            # AUTHORITATIVE catalog is the inline window.PLATFORM_CATALOG in
            # platform_index.html (the served catalog page reads that inline copy), so
            # if the strip function ever lost its platform_index.html branch, private
            # titles/descriptions (outreach drafts, working docs) would ship in the live
            # page source, hidden only by the client-side !d.private render filter. This
            # verifies the strip function names all three targets so that coverage can't
            # silently regress to json/js only.
            body_start = dtxt.find("def strip_private_catalog_entries")
            body_end = dtxt.find("\ndef ", body_start + 1)
            strip_body = dtxt[body_start: body_end if body_end != -1 else len(dtxt)]
            # Each of the three catalog copies must be WRITTEN by the strip function, not
            # merely mentioned. We check for the write anchor tied to each target so a
            # regression that drops a target's write (leaving a stale log line) is caught.
            target_writes = {
                "platform_catalog.json": "jp.write_text",
                "platform_catalog.js": "jsp.write_text",
                "platform_index.html (inline catalog)": "ip.write_text",
            }
            for target, anchor in target_writes.items():
                if anchor not in strip_body:
                    findings.append(("MIN", "PRIVATE-DEPLOY-GUARD", "tools/deploy_to_github.py",
                        f"strip_private_catalog_entries no longer writes {target} (missing {anchor}): "
                        f"private catalog entries in that copy would deploy unsanitized. The inline "
                        f"platform_index.html catalog is authoritative, so dropping it risks leaking "
                        f"private metadata into the live page source."))

    # B2) the client-side render must keep filtering private docs (defense in depth).
    # Even with the deploy strip, the render code should independently exclude private
    # docs; losing the !d.private filter would be the second line of defense failing.
    pindex = os.path.join(package_root, "platform_index.html")
    if os.path.exists(pindex):
        ptxt = open(pindex, encoding="utf-8", errors="ignore").read()
        if "!d.private" not in ptxt and "d.private" not in ptxt:
            findings.append(("MIN", "PRIVATE-RENDER-FILTER", "platform_index.html",
                "the catalog render code no longer references d.private anywhere; the client-side "
                "private-doc filter (.filter(d => !d.private)) appears to have been removed, which "
                "would list private docs on the live catalog page if the deploy strip ever regressed"))

    # C) tripwire: internal-only phrases must not reach a public surface (NON-EXHAUSTIVE)
    TRIPWIRE = ["privacy near-miss", "deliberately critical", "very long odds"]
    def scan(label, text, where):
        low = text.lower()
        for phrase in TRIPWIRE:
            if phrase in low:
                findings.append(("OBS", "PRIVATE-METADATA-TRIPWIRE", where,
                    f"internal-only phrase '{phrase}' appears in a public-served surface ({label}); "
                    "tripwire only - non-exhaustive"))
    for d in docs:
        if d.get("private"):
            continue
        scan("catalog entry", (d.get("title", "") + " " + d.get("description", "")),
             f"platform_catalog.json#{d.get('num')}")
    if os.path.isdir(web_root):
        for r, _, fs in os.walk(web_root):
            for f in fs:
                if f.endswith(".html"):
                    fp = os.path.join(r, f)
                    try:
                        scan("web mirror", open(fp, encoding="utf-8", errors="ignore").read(),
                             fp.replace(package_root + os.sep, ""))
                    except Exception:
                        pass
    if bots_blob:
        scan("bot mirror", bots_blob, "bots/")
    return findings


def check_date_monotonicity(package_root="."):
    """P1.1 (DATE-MONOTONICITY, MIN): README.txt and VERSIONLOG.txt list newest
    first, so reading top-to-bottom both the version and the date must be
    NON-INCREASING. Equal consecutive versions are allowed (a version may have
    more than one VERSIONLOG entry); only a true inversion (a lower version or an
    earlier date sitting ABOVE a higher/later one) is flagged.

    Cannot catch: whether a date is itself *correct* (only that the sequence is
    ordered) -- see AUDIT_SCOPE_AND_LIMITS.md.
    """
    import re
    from datetime import datetime
    findings = []

    def vt(v):
        try:
            return tuple(int(x) for x in v.split("."))
        except Exception:
            return None

    def parse(text, pat):
        out = []
        for m in re.finditer(pat, text, re.M):
            v, d = m.group(1), m.group(2)
            try:
                dt = datetime.strptime(d, "%b %d, %Y")
            except Exception:
                dt = None
            out.append((v, d, dt))
        return out

    targets = [
        ("README.txt", r'^v(\d+\.\d+\.\d+) \(([A-Za-z]{3} \d{1,2}, \d{4})\):'),
        ("VERSIONLOG.txt", r'^VERSION (\d+\.\d+\.\d+)\s+\u00b7\s+([A-Za-z]{3} \d{1,2}, \d{4})'),
    ]
    for fname, pat in targets:
        p = os.path.join(package_root, fname)
        if not os.path.exists(p):
            continue
        entries = parse(open(p, encoding="utf-8", errors="ignore").read(), pat)
        for i in range(len(entries) - 1):
            v1, d1s, d1 = entries[i]
            v2, d2s, d2 = entries[i + 1]
            t1, t2 = vt(v1), vt(v2)
            if t1 and t2 and t1 < t2:
                findings.append(("MIN", "DATE-MONOTONICITY", fname,
                    f"version order inverted (newest-first expected): {v1} sits above higher version {v2}"))
            if d1 and d2 and d1 < d2:
                findings.append(("MIN", "DATE-MONOTONICITY", fname,
                    f"date increases going down (newest-first expected): {v1} ({d1s}) above {v2} ({d2s})"))
    return findings


def _p1_text_targets(package_root):
    """Shared target set for the P1.2/P1.3 text-quality scans: root .txt and small
    root .md (skip files > 2 MB, e.g. the verbatim conversation archive), the two
    catalog copies, and every rendered _web_html page (which carries the docx text)."""
    targets = []
    for name in os.listdir(package_root):
        fp = os.path.join(package_root, name)
        if os.path.isfile(fp) and name.endswith((".txt", ".md")) and os.path.getsize(fp) <= 2_000_000:
            targets.append(fp)
    for rel in ("00_GUI_Files/platform_catalog.json", "00_GUI_Files/platform_catalog.js"):
        fp = os.path.join(package_root, rel)
        if os.path.exists(fp):
            targets.append(fp)
    web = os.path.join(package_root, "_web_html")
    if os.path.isdir(web):
        for r, _, fs in os.walk(web):
            for f in fs:
                if f.endswith((".html", ".md")):
                    targets.append(os.path.join(r, f))
    return targets


def check_encoding_integrity(package_root="."):
    """P1.2 (ENCODING-INVALID, MIN): served/source text must be valid UTF-8 with no
    decode-loss or mojibake. Flags files that are not strict UTF-8, that contain the
    U+FFFD replacement character, or that contain a classic UTF-8-misdecoded digraph.

    Cannot catch: meaning, or mojibake forms not in the (deliberately tight) list
    -- see AUDIT_SCOPE_AND_LIMITS.md.
    """
    findings = []
    MOJIBAKE = ["\u00c2\u00b7", "\u00e2\u20ac\u2122", "\u00e2\u20ac\u0153",
                "\u00c3\u00a9", "\u00c3\u00a8", "\u00c3\u00a0"]
    for fp in _p1_text_targets(package_root):
        rel = fp.replace(package_root + os.sep, "")
        try:
            t = open(fp, "rb").read().decode("utf-8")
        except UnicodeDecodeError as e:
            findings.append(("MIN", "ENCODING-INVALID", rel, f"not valid UTF-8: {e}"))
            continue
        if "\ufffd" in t:
            findings.append(("MIN", "ENCODING-INVALID", rel, "contains U+FFFD replacement character (decode loss)"))
            continue
        for mj in MOJIBAKE:
            if mj in t:
                findings.append(("MIN", "ENCODING-INVALID", rel, f"contains likely mojibake sequence {mj!r}"))
                break
    return findings


def check_glyph_integrity(package_root="."):
    """P1.3 (GLYPH-BOX, MIN): served/source text must contain no code points that
    typically render as a missing-glyph box -- Private Use Area (U+E000-U+F8FF),
    C0 control characters (other than tab/newline/carriage-return), or Unicode
    noncharacters. Same target set as ENCODING-INVALID.

    Cannot catch: missing glyphs inside binary PDFs (those need visual rendering,
    which is a documented manual step, not a deterministic check) -- see
    AUDIT_SCOPE_AND_LIMITS.md.
    """
    findings = []

    def bad_points(t):
        found = {}
        for ch in t:
            o = ord(ch)
            if 0xE000 <= o <= 0xF8FF:
                found.setdefault("PUA", hex(o))
            elif o < 0x20 and ch not in "\t\n\r":
                found.setdefault("CTRL", hex(o))
            elif 0xFDD0 <= o <= 0xFDEF or (o & 0xFFFE) == 0xFFFE:
                found.setdefault("NONCHAR", hex(o))
        return found

    for fp in _p1_text_targets(package_root):
        rel = fp.replace(package_root + os.sep, "")
        try:
            t = open(fp, encoding="utf-8", errors="ignore").read()
        except Exception:
            continue
        b = bad_points(t)
        if b:
            findings.append(("MIN", "GLYPH-BOX", rel,
                f"box-glyph-prone code point(s) present: {b}"))
    return findings


def check_healthcare_baseline_consistency(package_root="."):
    """P2.1n (BASELINE-CONSISTENCY, MIN): [v3.8.477: findings name the PATH, not the basename -- this check reported "index.html" for a finding that was in bots/index.html, and several files in the package share a name.] the CMS NHE per-capita baseline is $14,570. Any value of
    the form $14,5xx or $14,6xx that appears in a HEALTHCARE-BASELINE context (per-capita / NHE /
    'baseline') but is NOT 14,570 is a typo variant (as found and fixed v3.7.709) -
    which exact-match stale-value guards cannot catch. Excludes the standard-deduction figure (a
    tax-context figure), which is a legitimate and unrelated value."""
    import glob as _g, subprocess as _sp, re as _re
    findings = []
    # v3.8.364: RETIRED_VALUE_SCAN.md is the report of tools/scan_retired_values.py and quotes every
    # retired value by design; flagging it would be flagging the list of things to flag.
    excl = ("RETIRED_VALUE_SCAN", "OIR_Iteration", "Package_Version", "Open_Issues_Registry", "Conversation_Archive",
            "Errata", "Retrospective", "VERSIONLOG", "README")
    files = [x for x in _g.glob(os.path.join(package_root, "**", "*.docx"), recursive=True)
             if "_web_html" not in x and not any(e in x for e in excl)]
    # assumptions.html is GENERATED from the assumptions registry, and one entry's
    # basis text quotes the CMS published series verbatim -- "2023 $14,580" -- as
    # the evidence that the registered 14,570 matches no year. Flagging the
    # correct published value as a typo variant of the questioned one inverts the
    # finding. The page is excluded; the registry entry it renders is the record.
    files += [x for x in _g.glob(os.path.join(package_root, "**", "*.html"), recursive=True)
              if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x and os.path.basename(x) != "assumptions.html"]
    files += [x for x in _g.glob(os.path.join(package_root, "**", "*.pptx"), recursive=True) if "_web_html" not in x]

    def rd(p):
        try:
            if p.endswith(".docx"):
                return _sp.run(["pandoc", "-t", "plain", p], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=25).stdout or ""
            if p.endswith(".pptx"):
                from pptx import Presentation
                return "\n".join(sh.text_frame.text for sl in Presentation(p).slides
                                 for sh in sl.shapes if sh.has_text_frame)
            return open(p, encoding="utf-8").read()
        except Exception:
            return ""

    HEALTH = ("per-capita", "per capita", "national health expenditure", "nhe",
              "healthcare baseline", "health spending", "health-care spending", "per-person health")
    TAXCTX = ("standard deduction", "deduction", "filer", "mfj", "married filing",
              "publication 17", "exemption")
    for p in files:
        t = rd(p)
        low = t.lower()
        for m in _re.finditer(r"14,[56]\d\d", t):
            v = m.group(0)
            # v3.8.294: READ THE REGISTRY, DO NOT HARDCODE. This check hardcoded 14,570
            # and, when the figure was corrected to the sealed 14,580, IT FLAGGED THE
            # CORRECT VALUE AS A TYPO SIX TIMES. Same fault as the sensitivity-parity
            # fallback removed at v3.8.280: a check carrying its own copy of a figure
            # enforces the copy.
            if v.replace(",", "") == str(int(_baseline_canonical(package_root) or 0)):
                continue
            # v3.8.531: whitespace-normalised. pandoc wraps at 72 columns, so a line break could fall inside an
            # exemption phrase ("corrected\nv3.") and change the verdict by where a sentence happened to wrap.
            w = _re.sub(r"\s+", " ", low[max(0, m.start() - 90):m.end() + 60])
            if any(x in w for x in TAXCTX):
                continue
            # v3.8.294: A QUOTATION IS NOT A CLAIM. 07_Response_To_Gemini_Review carries the
            # old baseline inside a quotation from the reviewer; editing it would falsify a
            # record of what was said. The correction belongs beside the quote, not inside it.
            # v3.8.470: THE QUOTATION TEST GETS ITS OWN, WIDER WINDOW. It shared the 90-character
            # context above, and that is too tight to survive a renderer: pandoc lays table cells
            # out at a column width that varies by VERSION, so the same quotation in the same
            # document put its opening quote 90 characters before the value under pandoc 3.1.3 and
            # 97 under 3.9.0.2. THE CHECK PASSED HERE BY ONE CHARACTER AND FAILED ON THE AUTHOR'S
            # MACHINE BY SEVEN, which cost five releases of wrong explanations from me.
            # 400 characters is wider than any cell this renderer wraps, and a quote mark that far
            # back still means the value sits inside quoted text.
            wq = _re.sub(r"\s+", " ", low[max(0, m.start() - 400):m.end() + 120])
            if any(x in wq for x in ("from the gemini review", "the reviewer wrote",
                                     "quoted", "\u201c", '"')):
                continue
            # v3.8.294: A CORRECTION NOTE MUST BE ABLE TO NAME WHAT IT CORRECTED. The same
            # rule RETIRED-VALUE-LIVE applies: an old value appearing INSIDE an explicit
            # correction is disclosure, not drift. Without this the check forbids the
            # platform from saying "corrected from $14,570", which is exactly the sentence
            # a reader needs.
            if any(x in w for x in ("corrected v3.", "corrected from", "superseded",
                                    "previously read", "retired")):
                continue
            if any(x in w for x in HEALTH) or "baseline" in w:
                findings.append(("MIN", "BASELINE-CONSISTENCY", os.path.relpath(p, package_root),
                                 f"'{v}' in a healthcare-baseline context does not match the registered baseline "
                                 f"{_baseline_canonical(package_root)} (typo variant)"))
    # xlsx workbooks: computational models. Cells have no prose context, so flag baseline-adjacent
    # numeric values / formula constants in [14520,14620] that are neither 14570 (correct) nor 14600
    # (the standard deduction, a legitimate unrelated figure). Catches typo variants like 14613.
    try:
        import openpyxl as _oxl
        for xf in [x for x in _g.glob(os.path.join(package_root, "**", "04_*.xlsx"), recursive=True) if "_web_html" not in x]:
            try: wb = _oxl.load_workbook(xf, read_only=True)
            except Exception: continue
            for ws in wb.worksheets:
                for wr in ws.iter_rows():
                    for c in wr:
                        cv = c.value
                        if cv is None: continue
                        nums = []
                        if isinstance(cv, (int, float)): nums = [cv]
                        elif isinstance(cv, str): nums = [int(x) for x in _re.findall(r"\b(14[56]\d\d)\b", cv)]
                        for nv in nums:
                            if 14520 <= nv <= 14620 and nv not in (14570, 14600):
                                findings.append(("MIN", "BASELINE-CONSISTENCY", os.path.relpath(xf, package_root),
                                                 f"workbook value {nv} is a baseline typo variant (should be 14570)"))
            try: wb.close()
            except Exception: pass
    except Exception:
        pass
    return list(dict.fromkeys(findings))


def check_download_bundle_stale(package_root="."):
    """DOWNLOAD-BUNDLE-STALE (MIN): the _downloads/*.zip bundles users download must reflect the
    current package version. build_download_packages.py stamps platform_version into
    _downloads/manifest.json; if it is missing or does not match the catalog, the downloadable
    bundles are stale (users would get pre-correction documents - the class found v3.7.712).
    Regenerate with: python build_download_packages.py"""
    import glob as _g, json as _j
    findings = []
    cat = [x for x in _g.glob(os.path.join(package_root, "**", "platform_catalog.json"), recursive=True) if "_web_html" not in x]
    if not cat:
        return findings
    cur = _j.load(open(cat[0], encoding="utf-8")).get("platformVersion", "")
    dman = os.path.join(package_root, "_downloads", "manifest.json")
    if not os.path.exists(dman):
        findings.append(("MIN", "DOWNLOAD-BUNDLE-STALE", "_downloads", "download bundles missing; run build_download_packages.py"))
        return findings
    try:
        bv = _j.load(open(dman, encoding="utf-8")).get("platform_version", "")
    except Exception:
        bv = ""
    if bv != cur:
        findings.append(("MIN", "DOWNLOAD-BUNDLE-STALE", "_downloads/manifest.json",
                         f"bundles built for {bv or '(unstamped)'} but package is {cur}; regenerate with build_download_packages.py"))
    return findings


def check_orphaned_renderings(package_root="."):
    """v3.8.36: a public document whose HTML rendering exists but is unreachable.

    build_web_html.py converts every .docx it finds, so a rendering can exist on
    disk and be deployed while the catalog entry has no htmlPath. Nothing then
    points at it: it is absent from the sitemap, absent from the documents index,
    and unlinked from any page. The file is served and undiscoverable, and the
    reader is left with the .docx download of a document whose web version was
    built and shipped alongside it.

    Four public documents were in that state when this check was written, found
    by probing sitemap completeness in the REVERSE direction. The deploy smoke
    test asserts every sitemap URL returns 200; nothing asserted that everything
    which should be in the sitemap was. That is the same asymmetry as the private
    paths: the gates confirmed what was listed and could not see what was missing.
    """
    findings = []
    cat_path = os.path.join(package_root, "00_GUI_Files", "platform_catalog.json")
    if not os.path.exists(cat_path):
        return findings
    try:
        with open(cat_path, encoding="utf-8") as f:
            docs = json.load(f).get("documents", [])
    except json.JSONDecodeError:
        return findings
    for d in docs:
        if d.get("private") or d.get("htmlPath"):
            continue
        path = d.get("path", "")
        if not path.lower().endswith(".docx"):
            continue
        cand = "_web_html/" + os.path.splitext(path)[0] + ".html"
        if os.path.exists(os.path.join(package_root, cand)):
            findings.append(("MIN", "ORPHANED-RENDERING", path,
                             f"a rendering exists at {cand} but the catalog entry has no "
                             f"htmlPath, so it is absent from the sitemap and the documents "
                             f"index and cannot be reached from anywhere on the site"))
    return findings


def narrative_examples(entry):
    """v3.8.41: the ONE way to read a figure's narrative examples.

    The registry used two shapes: narrative_example (a single object, 62 entries)
    and narrative_examples (an array, 1 entry). Checks written against one shape
    silently skipped the other, and the entry using the array form was
    FIG-deficit-impact, whose citation names a missing workbook. So the schema
    split was actively hiding a declared reproducibility gap from any check keyed
    to the singular.

    v3.8.41 migrated every entry to the array form, which is a superset and lost
    nothing. This accessor still tolerates the singular, deliberately: an
    exhaustive migration and a tolerant reader are different guarantees, and this
    project's failures have all been enumerations that were complete when written
    and not afterwards. If a singular key reappears, this returns it rather than
    dropping it silently.

    Always returns a list, possibly empty. Callers iterate; nobody indexes.
    """
    if not isinstance(entry, dict):
        return []
    out = []
    single = entry.get("narrative_example")
    if isinstance(single, dict):
        out.append(single)
    many = entry.get("narrative_examples")
    if isinstance(many, list):
        out.extend(x for x in many if isinstance(x, dict))
    return out


def check_stale_open_items(package_root=".", ledger_path=None, versionlog_path=None, registry_path=None):
    """v3.8.643 (author #4531): an item or tracked issue recorded as DONE somewhere but still OPEN where the next
    session reads it. Nine work items were finished but listed open by the session handoff (their completion was not
    written as '<ID> CLOSED'), and three registry issues were closed in releases while their rows still said OPEN --
    the mechanism behind repeated relitigation. Inputs are parameters so the check can be tested on scratch copies."""
    import re as _re, json as _j, sys as _s
    out = []
    L = ledger_path or os.path.join(package_root, "09_Meta_Tracking", "review_comments", "ledger.jsonl")
    V = versionlog_path or os.path.join(package_root, "VERSIONLOG.txt")
    G = registry_path or os.path.join(package_root, "09_Meta_Tracking", "09_Open_Issues_Registry.docx")
    acc_p = os.path.join(package_root, "09_Meta_Tracking", "review_comments", "stale_open_accepts.json")
    acc = _j.load(open(acc_p, encoding="utf-8")) if os.path.exists(acc_p) else {}
    R = [_j.loads(x) for x in open(L, encoding="utf-8") if x.strip()]
    declared = {t[5:] for r in R if r["kind"] == "item" for t in r["tags"] if t.startswith("item:")}
    closed = {m.group(1) for r in R if r["kind"] == "status" for m in [_re.match(r"^((?:[A-Z]{1,2}\d{1,3}|BATCH\d{3})) CLOSED", r["text"])] if m}
    titles = _re.findall(r"^VERSION (3\.\d+\.\d+)  \S  [^(]+\((.+?)\)  \[", open(V, encoding="utf-8").read(), _re.M)
    done_word = r"\b(CLOSED|COMPLETE|COMPLETED|DONE|REGISTERED|RESOLVED|closed|resolved)\b"
    for k in sorted(declared - closed):
        if k in acc: continue
        # v3.8.648: upper-case status words only -- a record that merely mentions another item being 'closed' is not a completion
        # v3.8.651: a status word after GROUP / PART / STEP / PHASE n describes part of an item, not the item
        ev = [r["seq"] for r in R if r["kind"] == "status"
              and (m_ := _re.match(rf"^{k}\b([^.]{{0,40}}?)\b(CLOSED|COMPLETE|COMPLETED|DONE|REGISTERED|RESOLVED)\b", r["text"]))
              and not _re.search(r"\b(GROUP|PART|STEP|PHASE)\s*\w+\s*[,;:]?\s*$", m_.group(1), _re.I)
              # v3.8.654: a status word right after ANOTHER item's id ('W30 STEP 2, RESEARCH-40 CLOSED') is that item's status
              # v3.8.655: any OTHER item's or issue's id between this id and the status word owns that status
              and not _re.search(r"\b(RESEARCH|PERSONA-SIG|METHOD|GUARD|CON)-\d+\b|\b[WJ]\d{1,3}\b|\bPK\d\b", m_.group(1))]
        tv = [v for v, t in titles if _re.search(rf"\b{k}\b[^,;:]{{0,30}}{done_word}", t)]
        if ev or tv:
            out.append(("MIN", "STALE-OPEN-ITEM", "comment ledger",
                        f"{k} is listed OPEN by the session handoff but recorded done (records {ev[-3:]}, releases {tv[-3:]}); close it with tools/comment_ledger.py close {k} --evidence ..."))
    try:
        import docx as _d
        for row in _d.Document(G).tables[0].rows[1:]:
            iid = row.cells[0].text.strip().split()[0]; st = row.cells[2].text.strip().upper()
            if not st.startswith("OPEN") or iid in acc: continue
            tv = [v for v, t in titles if _re.search(rf"\b{_re.escape(iid)}\b[^,;:]{{0,30}}\b(closed|resolved|CLOSED|RESOLVED)\b", t)]
            if tv:
                out.append(("MIN", "STALE-OPEN-ITEM", "Tracked Issues Registry",
                            f"{iid} is OPEN in the registry but releases {tv[-3:]} record it closed or resolved; update its row, or record an accepted exception with its reason"))
    except Exception as ex:
        out.append(("OBS", "STALE-OPEN-ITEM", "Tracked Issues Registry", f"registry not read: {type(ex).__name__}: {ex}"))
    return out


def check_ingestion_stale(package_root="."):
    """v3.8.61: a shipped figure that no longer matches the archive it came from.

    DATA_REPRODUCIBILITY_PLAN.md Phase 0. Two ingestion scripts existed and both
    worked; NEITHER was called by the deploy or the audit. They ran when someone
    remembered, and nothing detected a stale output, so the platform could ship a
    value that no longer matched its own source and every gate would pass.

    This runs each registered ingestion in --verify mode: recompute from the
    archive, compare to what is shipped, write nothing. A non-zero exit means the
    source moved and a figure needs re-deriving.

    MIN severity. A figure that no longer matches its source is a defect, not an
    observation. Bypass with --skip-ingestion-check when the archive is
    deliberately ahead of the shipped values.

    Registered per stage, not per source. The BLS pipeline is two stages
    (build_wage_floor_data reads the national file; build_wage_regional reads the
    MSA and BOS shards and overwrites region factors in the same output), and
    verifying stage 1 against a stage-2 file reports every region differing on
    every run. A check that fails identically every time is a check nobody reads.
    """
    import subprocess as _sp
    findings = []
    INGESTIONS = [
        ("bls-oews (phase 1, national)", [
            sys.executable, os.path.join(package_root, "tools", "build_wage_floor_data.py"),
            "--bls", os.path.join(package_root, "_data_archive",
                                  "2026-07-10_bls_oews_may2025", "national_M2025_dl.xlsx"),
            "--platform-version", "verify", "--verify"]),
        ("assumptions page matches the registry", [
            sys.executable, os.path.join(package_root, "tools", "build_assumptions_page.py"),
            "--package-root", package_root, "--check"]),
        ("figure caveats match the registry", [
            sys.executable, os.path.join(package_root, "tools", "build_figure_caveats.py"),
            "--package-root", package_root, "--check"]),
        ("anchored figures present in their own sealed archive", [
            sys.executable, os.path.join(package_root, "tools",
                                         "test_figure_reproducibility.py"), "--json"]),
        ("release segments partition the tree", [
            sys.executable, os.path.join(package_root, "tools",
                                         "build_release_segments.py"),
            "--package-root", package_root, "--check"]),
        ("derived figures close from their stated inputs", [
            sys.executable, os.path.join(package_root, "tools",
                                         "verify_internal_consistency.py"), "--verify"]),
        ("sourced figures recompute from their archives", [
            sys.executable, os.path.join(package_root, "tools",
                                         "verify_sourced_figures.py"), "--verify"]),
        ("stochastic bridge medians reproduce the published analysis", [
            sys.executable, os.path.join(package_root, "tools",
                                         "montecarlo_bridge_sustainability.py"), "--verify"]),
        ("nbim-gpfg (fund value in NOK)", [
            sys.executable, os.path.join(package_root, "tools",
                                         "ingest_nbim_fund_value.py"), "--verify"]),
        ("peterson-kff (comparable-country peer average)", [
            sys.executable, os.path.join(package_root, "tools", "ingest_kff_peer_health.py"),
            "--verify"]),
        ("cms64-medicaid-2024 (Medicaid total and LTSS share)", [
            sys.executable, os.path.join(package_root, "tools", "ingest_cms64_medicaid.py"),
            "--verify"]),
        ("census-cps-asec-2025 (household panel extract, W42)", [
            sys.executable, os.path.join(package_root, "tools", "ingest_cps_asec2025.py"),
            "--verify"]),
        ("bls-census-occ2018-code-list (occupation floors, W42)", [
            sys.executable, os.path.join(package_root, "tools", "ingest_census_occ2018_floors.py"),
            "--verify"]),
        ("derived: the education model's fund path at 4 percent (W54, v3.8.645)", [
            sys.executable, os.path.join(package_root, "tools", "derive_education_fund_path.py"),
            "--verify"]),
        ("derived: the bridge credit's with-and-without borrowing pair (W48, v3.8.645)", [
            sys.executable, os.path.join(package_root, "tools", "derive_bridge_credit_pair.py"),
            "--verify"]),
        ("checked: every sealed archive against its own checksum list (v3.8.667)", [
            sys.executable, os.path.join(package_root, "tools", "check_sealed_archives.py"),
            "--strict"]),
        ("checked: the Open Issues Registry by rule (W4, v3.8.666)", [
            sys.executable, os.path.join(package_root, "tools", "check_issues_registry.py"),
            "--strict"]),
        ("derived: the account against Social Security, net of services (RESEARCH-21, v3.8.662)", [
            sys.executable, os.path.join(package_root, "tools", "derive_retirement_comparison.py"),
            "--verify"]),
        ("derived: the individual-account illustration at the published return (RESEARCH-21, v3.8.662)", [
            sys.executable, os.path.join(package_root, "tools", "derive_individual_account_illustration.py"),
            "--verify"]),
        ("derived: how far the wage floors sit beyond the minimum-wage evidence (RESEARCH-55, v3.8.661)", [
            sys.executable, os.path.join(package_root, "tools", "derive_wagefloor_evidence_reach.py"),
            "--verify"]),
        ("derived: the wage floor's endogeneity on the sealed BLS data (RESEARCH-28, v3.8.661)", [
            sys.executable, os.path.join(package_root, "tools", "derive_wagefloor_endogeneity.py"),
            "--verify"]),
        ("derived: the pillars' cost the fund cannot yet carry (W57, v3.8.656)", [
            sys.executable, os.path.join(package_root, "tools", "build_pillar_financing_gap.py"),
            "--check"]),
        ("archived sources without bespoke scripts", [
            sys.executable, os.path.join(package_root, "tools", "verify_archived_sources.py")]),
        ("cms-nhe (health baseline per capita)", [
            sys.executable, os.path.join(package_root, "tools", "build_health_baseline_data.py"),
            "--verify"]),
        ("shiller-ie-data (return dispersion)", [
            sys.executable, os.path.join(package_root, "tools", "ingest_shiller_funnel.py"),
            "--source", os.path.join(package_root, "_data_archive",
                                     "2026-07-25_shiller_ie_data", "ie_data.xls"),
            "--verify"]),
        ("ipeds-finance (education cost per FTE)", [
            sys.executable, os.path.join(package_root, "tools", "build_education_cost_data.py"),
            "--verify"]),
    ]
    for label, cmd in INGESTIONS:
        script = cmd[1]
        if not os.path.exists(script):
            continue
        need = [a for a in cmd if a.endswith((".xlsx", ".csv", ".xls"))]
        if any(not os.path.exists(a) for a in need):
            findings.append(("NOTE", "INGESTION-STALE", label,
                             "archive input missing; ingestion NOT verified"))
            continue
        try:
            r = _sp.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=600)
        except Exception as e:
            findings.append(("NOTE", "INGESTION-STALE", label,
                             f"could not run ({type(e).__name__}); NOT verified"))
            continue
        if r.returncode != 0:
            _lines = (r.stdout or "").splitlines()
            # v3.8.687 (#5073): NAME THE CASE. The first VM preflight failed one case here and the log kept only the
            # summary line, so which case drifted could not be found afterwards. Keep each failing case's row (the
            # verifier prints 'FIG-id  FAIL|ERROR|NOT-COMPUTED  target' and the detail on the next line) before it.
            _bad = []
            for _i, _l in enumerate(_lines):
                if re.match(r"^\S+\s+(FAIL|ERROR|NOT-COMPUTED)\s", _l):
                    _bad.append(_l.strip() + (" -- " + _lines[_i + 1].strip() if _i + 1 < len(_lines) else ""))
            detail = " | ".join(_bad + [l.strip() for l in _lines if "[verify]" in l])[:900]
            findings.append(("MIN", "INGESTION-STALE", label,
                             f"shipped data no longer matches its archive: {detail}"))
    return findings


def check_declared_dependency_edges(package_root="."):
    """v3.8.85 (DECLARED-DEPENDENCY-EDGE, SIG): a dependency asserted in prose must
    exist as a structural edge.

    THE FAILURE THIS CLOSES. The registry notes on FIG-existing-programs-absorbed
    stated twice, and 09_Verified_Platform_Status.md stated once, that
    FIG-fund-coverage-share reaches that figure through FIG-total-new-commitments.
    It does not. FIG-total-new-commitments sums nine pillar GROSS commitments and
    its own method says absorption is subtracted separately by
    FIG-net-new-spending. The claim was wrong for several releases, was repeated
    into the file whose entire purpose is to stop rediscovery by guessing, and was
    then repeated back by a session reading that file.

    The mechanism matters, because it is why the error was invisible. Build the
    dependency graph by scanning derivation TEXT and you pick up figure IDs from
    prose inside `method` strings, which produces edges that do not exist. Build it
    from the STRUCTURED fields and you get the real graph. The two disagree, and
    only one of them is the arithmetic.

    So this check does not verify prose against prose. It verifies prose against
    structure: any FIG- id mentioned anywhere in another figure's notes, source or
    derivation.method must either be a real structural input of that figure, or be
    listed in that figure's `mentions_not_dependencies`. The second escape hatch is
    required and deliberate; most prose mentions are commentary rather than claims,
    and a check with no way to say "mentioned, not depended on" would be turned off
    within a release.

    SIG severity. A wrong dependency claim propagates into priority decisions about
    which figure to reconstruct first, which is exactly what it did.
    """
    findings = []
    fr_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fr_path):
        return findings
    with open(fr_path, encoding="utf-8") as f:
        fr = json.load(f)
    entries = fr.get("entries", [])
    ids = {e.get("id") for e in entries if e.get("id")}

    STRUCT_KEYS = ("inputs", "components_gross", "components_net", "numerator",
                   "denominator", "terms", "operands", "depends_on")

    def structural_inputs(entry):
        dv = entry.get("derivation") or {}
        out = set()
        for k in STRUCT_KEYS:
            v = dv.get(k)
            if v is None:
                continue
            items = v if isinstance(v, list) else [v]
            for it in items:
                if isinstance(it, str):
                    out.add(it)
                elif isinstance(it, dict) and isinstance(it.get("fig"), str):
                    out.add(it["fig"])
        for k in STRUCT_KEYS:
            v = entry.get(k)
            if isinstance(v, list):
                out.update(x for x in v if isinstance(x, str))
        return {x for x in out if x in ids}

    struct = {e["id"]: structural_inputs(e) for e in entries if e.get("id")}

    # Scope: a MENTION is not a CLAIM. Naming another figure in commentary is normal
    # and flagging all of it produces a check that gets declared away wholesale, which
    # is worse than no check. What went wrong was a mention wrapped in DEPENDENCY
    # LANGUAGE ("reaches it through", "consumes it as", "terminates in") that no edge
    # supported. So the trigger is a dependency verb within a window of the mention.
    DEP_LANG = re.compile(
        r"\b(reach(?:es|ed|ing)?|depend(?:s|ed|ing)?|deriv(?:es|ed|ing)|"
        r"consum(?:es|ed|ing)|subtract(?:s|ed|ing)?|feeds?|"
        r"rest(?:s|ed|ing)?\s+on|terminat(?:es|ed|ing)\s+in|flows?\s+(?:in)?to|"
        r"input\s+to|computed\s+from|calculated\s+from)\b", re.I)
    WINDOW = 160

    for e in entries:
        fid = e.get("id")
        if not fid:
            continue
        prose = " ".join([
            str(e.get("notes") or ""),
            str(e.get("source") or ""),
            str(((e.get("derivation") or {}).get("method")) or ""),
        ])
        raw = e.get("mentions_not_dependencies") or []
        allowed = set()
        for item in raw:
            if isinstance(item, str):
                allowed.add(item)
            elif isinstance(item, dict) and item.get("fig"):
                if not item.get("why"):
                    findings.append((
                        "MIN", "DECLARED-DEPENDENCY-EDGE", f"figures_registry.json:{fid}",
                        f"mentions_not_dependencies declares {item['fig']} with no 'why'. "
                        f"A bare declaration is a rubber stamp; say why it is a mention."))
                allowed.add(item["fig"])
        # A figure describing what depends on IT is stating a REVERSE edge, which is
        # true and useful commentary. Only forward claims can be wrong here.
        downstream = {other for other in ids if fid in struct.get(other, set())}
        allowed |= downstream
        claimed = set()
        for m in re.finditer(r"FIG-[a-z0-9\-]+", prose):
            other = m.group(0)
            if other == fid or other not in ids:
                continue
            lo = max(0, m.start() - WINDOW)
            hi = min(len(prose), m.end() + WINDOW)
            if DEP_LANG.search(prose[lo:hi]):
                claimed.add(other)
        for other in sorted(claimed - struct.get(fid, set()) - allowed):
            findings.append((
                "SIG", "DECLARED-DEPENDENCY-EDGE", f"figures_registry.json:{fid}",
                f"prose asserts a dependency on {other} but it is not a structural input "
                f"of {fid} and is not listed in mentions_not_dependencies. Either add the "
                f"edge, or declare the mention. A prose dependency with no edge behind it "
                f"is how the FIG-fund-coverage-share claim shipped wrong for several "
                f"releases."
            ))
    return findings


DIVERGENCE_MARKERS = re.compile(
    r"DIVERGENCE|DOES NOT RECONCILE|STATED-RANGE|the models still disagree|does not follow from",
    re.IGNORECASE)


def check_bundle_raw_tokens(package_root="."):
    """v3.8.267 (BUNDLE-RAW-TOKEN, MIN): no downloadable document may contain a raw figure
    token.

    The website resolves [[FIG:...]] tokens and FIGURE-TOKEN-PATTERN guards that path. The
    DOWNLOAD BUNDLES are resolved by a second tool, tools/resolve_docx_tokens.py, and nothing
    guarded it: it carried its own token regex whose label class excluded the dot, so
    [[FIG:FIG-fund-corpus-year60|4.28pct]] shipped RAW inside two bundled documents while the
    same token rendered correctly on the site. TWO RESOLVERS, ONE GUARDED. This checks the
    artefact a reader actually downloads.
    """
    import glob as _g, io as _io, zipfile as _zf
    findings = []
    dl = os.path.join(package_root, "_downloads")
    if not os.path.isdir(dl):
        return findings
    tok = re.compile(r"\[\[FIG:[^\]]+\]\]")
    seen = {}
    for z in _g.glob(os.path.join(dl, "*.zip")):
        try:
            zf = _zf.ZipFile(z)
        except Exception:
            continue
        for n in zf.namelist():
            if not n.endswith(".docx"):
                continue
            try:
                from docx import Document as _D
                d = _D(_io.BytesIO(zf.read(n)))
                text = " ".join(p.text for p in d.paragraphs)
                for tb in d.tables:
                    for row in tb.rows:
                        for c in row.cells:
                            text += " " + c.text
            except Exception:
                continue
            hits = set(tok.findall(text))
            if hits:
                seen.setdefault(os.path.basename(n), set()).update(hits)
    for doc, hits in sorted(seen.items()):
        findings.append(("MIN", "BUNDLE-RAW-TOKEN", doc,
            f"raw figure token(s) in a downloadable document: {sorted(hits)[:3]}. The "
            f"website resolves these; the bundle a reader downloads must too."))
    return findings


def check_document_currency(package_root="."):
    """v3.8.266 (DOC-CURRENCY-STALE, MIN): every versioned document must carry the package
    version it ships in.

    v3.8.282: the stamp now records the release a document's CONTENT last changed, not the
    release it ships in, and tools/stamp_document_currency.py only rewrites documents whose
    content actually moved. The check still calls that tool in --check mode; what it verifies
    is that every document's stamp matches its recorded fingerprint, so a content change with
    no re-stamp fails the gate.

    Twelve documents across four audit batches were found whose version lines trailed the
    package by thirty to a hundred and eighty releases. Those lines are DOCUMENT REVISION
    HISTORY and are correct as history; the defect was that a reader had no other version
    information. tools/stamp_document_currency.py appends one generated clause -- "ships in
    package vX" -- regenerated every release, and this check fails if any stamped document
    disagrees with version.json. Historical records declared in audit_whitelist.txt are
    excluded: a package stamp would contradict their banner.
    """
    import subprocess as _sp, sys as _sys
    tool = os.path.join(package_root, "tools", "stamp_document_currency.py")
    if not os.path.exists(tool):
        return [("MIN", "DOC-CURRENCY-STALE", "tools/stamp_document_currency.py",
                 "the currency stamper is missing; document currency is unchecked")]
    try:
        r = _sp.run([_sys.executable, tool, "--check"], cwd=package_root,
                    capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=900)
    except Exception as e:
        return [("MIN", "DOC-CURRENCY-STALE", "tools/stamp_document_currency.py",
                 f"could not run: {e}")]
    # v3.8.536 (author, option D): documents with no version line carry no stamp. The tool now reports them on every
    # run; surface that as an OBSERVATION -- a missing version line is a content choice, not a defect -- so "every
    # versioned document" can no longer hide the documents that have none.
    out = []
    for line in (r.stdout or "").splitlines():
        if "have no version line and carry no stamp" in line:
            out.append(("OBS", "DOC-CURRENCY-UNSTAMPABLE", "package documents", line.replace("[currency] ", "")[:400]))
    if r.returncode == 0:
        return out
    return out + [("MIN", "DOC-CURRENCY-STALE", "package documents",
                   " ".join(l for l in (r.stdout or "").splitlines() if "have no version line" not in l)[:400])]


def check_wage_tables_current(package_root="."):
    """v3.8.265 (WAGE-TABLE-DRIFT, MIN): the published wage tables must equal the shipped data.

    Four tables across two vision documents carried ILLUSTRATIVE values under prose stating
    they were real BLS figures (found v3.8.259, v3.8.260). They were rebuilt by hand, and a
    hand rebuild is a one-time fix for a recurring failure. tools/build_wage_tables.py
    regenerates them from wage_floor_data.json and the _wage_regional shards; this calls it
    in --check mode so a hand edit that breaks them fails the gate instead of shipping.
    """
    import subprocess as _sp, sys as _sys
    tool = os.path.join(package_root, "tools", "build_wage_tables.py")
    if not os.path.exists(tool):
        return [("MIN", "WAGE-TABLE-DRIFT", "tools/build_wage_tables.py",
                 "the wage-table generator is missing; the tables are unchecked")]
    try:
        r = _sp.run([_sys.executable, tool, "--check"], cwd=package_root,
                    capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=600)
    except Exception as e:
        return [("MIN", "WAGE-TABLE-DRIFT", "tools/build_wage_tables.py", f"could not run: {e}")]
    if r.returncode == 0:
        return []
    detail = " ".join((r.stdout or "").split())[:400]
    return [("MIN", "WAGE-TABLE-DRIFT", "02_Vision_and_Communication (wage tables)",
             f"the published wage tables no longer match the shipped BLS data: {detail}")]


HISTORY_SURFACES = ("_data_archive", "_downloads", "_web_html", "VERSIONLOG.txt",
                    "REVIEW_LOG.md", "Conversation_Archive", "OIR_Iteration_Archive",
                    "Platform_Package_Version", "RECONSTRUCTION_PROTOCOL",
                    "FIX_PHASE_PLAN", "SUBSTANTIATION_FINDINGS", "errata.json",
                    "figures_registry", "numeric_provenance_whitelist", "README.txt",
                    "audit_whitelist.txt", "data_recency.json")


def _baseline_canonical(package_root="."):
    """v3.8.294: the registered healthcare per-capita baseline, read at check time."""
    try:
        fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
        for e in json.load(open(fp, encoding="utf-8"))["entries"]:
            if e["id"] == "FIG-healthcare-percapita-baseline":
                return e["canonical"]["value"]
    except Exception:
        return None
    return None


def check_checklist_log(package_root="."):
    """v3.8.330 (CHECKLIST-LOG, MIN): the response checklist log must be well formed.

    Every reply's checklist is saved to 09_Meta_Tracking/response_checklists/, one file
    per reply, named by UTC timestamp, newest 50 kept. A LOG OF SELF-REPORTED TICKS
    CERTIFIES NOTHING UNLESS A TICK CAN BE FALSIFIED, so:
      - no more than 50 files;
      - every file named YYYY-MM-DDTHH-MM-SSZ[-n]_checklist.md;
      - every [done] line names evidence: a path, a file with an extension, or a
        command in backticks;
      - every [not done] line gives a reason after the dash.
    """
    import re as _re
    findings = []
    d = os.path.join(package_root, "09_Meta_Tracking", "response_checklists")
    if not os.path.isdir(d):
        return findings
    files = sorted(f for f in os.listdir(d) if f.endswith("_checklist.md"))
    if len(files) > 50:
        findings.append(("MIN", "CHECKLIST-LOG", "response_checklists",
                         f"{len(files)} entries; the rolling window is 50. Run tools/log_checklist.py to prune."))
    name_pat = _re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d{6})?Z_checklist\.md$")
    try:                                   # v3.8.519: the logger owns the rule; one definition
        sys.path.insert(0, os.path.join(package_root, "tools"))
        from log_checklist import EVIDENCE as evidence
    except Exception:
        evidence = _re.compile(r"`[^`]+`|[\w\-/]+\.(?:py|xlsx|docx|jsonl|json|md|html|txt|csv|zip|xml)\b|/[\w\-./]+")
    for f in files:
        if not name_pat.match(f):
            findings.append(("MIN", "CHECKLIST-LOG", f, "filename is not a UTC timestamp"))
            continue
        try:
            lines = open(os.path.join(d, f), encoding="utf-8").read().splitlines()
        except Exception:
            continue
        for ln in lines:
            s = ln.strip()
            if s.startswith("[done]"):
                tail = s.split("--", 1)[1] if "--" in s else ""
                if not evidence.search(tail):
                    findings.append(("MIN", "CHECKLIST-LOG", f,
                        f"a line marked done names no file, path or command: {s[:70]}"))
            elif s.startswith("[not done]"):
                tail = s.split("--", 1)[1].strip() if "--" in s else ""
                if len(tail) < 8:
                    findings.append(("MIN", "CHECKLIST-LOG", f,
                        f"a line marked not done gives no reason: {s[:70]}"))
    return findings


def check_fund_draw_params(package_root="."):
    """v3.8.334 (FUND-DRAW-PARAM-DRIFT, MIN): the fund's draw settings live in ONE place.

    The draw cap and payout delay were held in three places -- tools/fund_ledger.py,
    tools/montecarlo_bridge_sustainability.py and 04_Combined_Reform_Model.xlsx -- with nothing
    keeping them in step. The tools now read the assumptions registry; the model is synced by
    tools/sync_fund_draw_params.py. This check fails if the model's cells differ from the registry,
    or if either tool again types its own copy.
    """
    import re as _re
    findings = []
    try:
        import openpyxl
        A = {a["id"]: a["current_value"] for a in json.load(open(os.path.join(package_root, "00_GUI_Files",
             "assumptions_registry.json"), encoding="utf-8"))["entries"]}
        ws = openpyxl.load_workbook(os.path.join(package_root, "04_Mathematical_Models",
             "04_Combined_Reform_Model.xlsx"), data_only=False)["Assumptions"]
        for cell, aid in (("C43", "ASSUM-fund-disbursement-delay"), ("C44", "ASSUM-fund-ceiling-allocation")):
            if aid not in A:
                findings.append(("MIN", "FUND-DRAW-PARAM-DRIFT", aid, "not in the assumptions registry"))
            elif float(ws[cell].value) != float(A[aid]):
                findings.append(("MIN", "FUND-DRAW-PARAM-DRIFT", "04_Combined_Reform_Model.xlsx",
                    f"Assumptions {cell} holds {ws[cell].value} but {aid} is {A[aid]}. Run tools/sync_fund_draw_params.py."))
    except Exception as ex:
        findings.append(("MIN", "FUND-DRAW-PARAM-DRIFT", "fund model", f"could not be read: {ex}"))
    typed = _re.compile(r"^(CEILING|DELAY|DISB_CAP|DISB_START)\s*=\s*[0-9.]+\s*(#.*)?$", _re.M)
    for rel in ("tools/fund_ledger.py", "tools/montecarlo_bridge_sustainability.py"):
        try:
            txt = open(os.path.join(package_root, rel), encoding="utf-8").read()
        except Exception:
            continue
        for m in typed.finditer(txt):
            findings.append(("MIN", "FUND-DRAW-PARAM-DRIFT", rel,
                f"types its own draw setting ({m.group(0).strip()[:40]}) instead of reading the registry"))
    return findings


def check_pillar_ledger(package_root="."):
    """v3.8.336 (PILLAR-LEDGER-DRIFT, CONTRIB-RATE-DRIFT, BUILD-DATE-STALE; all MIN).

    PILLAR-LEDGER-DRIFT: the platform total must be the SUM OF ITS PILLARS. Before v3.8.336 the
    deficit arithmetic took gross cost for every pillar but subtracted only five absorbed items,
    and counted revenue for only some pillars, while the pillars' own documents absorbed and
    raised more. tools/build_pillar_ledger.py computes the totals from the pillars; the registry's
    commitments, absorption, net new spending and non-fund revenue must equal it.

    CONTRIB-RATE-DRIFT: the ten contribution rates are registered once; the models, the calculator
    and calculator_parameters.json must hold the same values.

    BUILD-DATE-STALE: version.json build_date and manifest.json generated_date must be the date of
    the newest VERSIONLOG entry. They read 2026-09-17 and 2026-05-19 at v3.8.335.
    """
    import re as _re, subprocess as _sp, datetime as _dt
    findings = []
    E = {e["id"]: e for e in json.load(open(os.path.join(package_root, "00_GUI_Files", "figures_registry.json"), encoding="utf-8", errors="replace"))["entries"]}
    A = {a["id"]: a["current_value"] for a in json.load(open(os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json"), encoding="utf-8", errors="replace"))["entries"]}
    try:
        out = _sp.run([sys.executable, "-c", "import sys,json;sys.path.insert(0,'tools');sys.argv=['x'];"
                       "import build_pillar_ledger as b;print(json.dumps(b.main()))"],
                      cwd=package_root, capture_output=True, text=True, timeout=120).stdout.strip().splitlines()[-1]
        L = json.loads(out)
        ab = sum(r[2] for r in L["absorbed"] if r[3] in ("counted", "verified", "derived")) / 1000
        nf = sum(r[2] for r in L["revenue"] if r[3] in ("counted", "verified", "derived")) / 1000
        want = {"FIG-total-new-commitments": L["gross"] / 1000, "FIG-existing-programs-absorbed": ab,
                "FIG-net-new-spending": L["gross"] / 1000 - ab}
        for fid, w in want.items():
            got = (E.get(fid, {}).get("canonical") or {}).get("value")
            if got is None or abs(float(got) - w) > 0.0005:
                findings.append(("MIN", "PILLAR-LEDGER-DRIFT", fid, f"registry {got} but the pillar ledger gives {w:.4f}"))
        got = ((E.get("FIG-new-revenue", {}).get("derivation") or {}).get("non_fund_trillion"))
        if got is None or abs(float(got) - nf) > 0.0005:
            findings.append(("MIN", "PILLAR-LEDGER-DRIFT", "FIG-new-revenue", f"non-fund revenue {got} but the ledger gives {nf:.4f}"))
    except Exception as ex:
        findings.append(("MIN", "PILLAR-LEDGER-DRIFT", "tools/build_pillar_ledger.py", f"could not be run: {ex}"))
    try:
        import openpyxl
        cells = [("04_Universal_Healthcare_Model", "C47", "healthcare-employer"), ("04_Universal_Healthcare_Model", "C48", "healthcare-employee"),
                 ("04_Universal_Childcare_Model", "C24", "childcare-employer"), ("04_Universal_Childcare_Model", "C25", "childcare-employee"),
                 ("04_Universal_Mental_Health_Model", "C35", "mentalhealth-employer"), ("04_Universal_Mental_Health_Model", "C36", "mentalhealth-employee")]
        for m, c, k in cells:
            v = openpyxl.load_workbook(os.path.join(package_root, "04_Mathematical_Models", m + ".xlsx"), read_only=True, data_only=False)["Assumptions"][c].value
            if float(v) != float(A[f"ASSUM-contrib-{k}"]):
                findings.append(("MIN", "CONTRIB-RATE-DRIFT", m, f"{c} holds {v} but ASSUM-contrib-{k} is {A['ASSUM-contrib-'+k]}"))
        cp = json.load(open(os.path.join(package_root, "00_GUI_Files", "calculator_parameters.json"), encoding="utf-8", errors="replace"))["calculators"]["06_Presentation_Materials/06_We_The_People_Calculator.html"]
        names = {"healthcare": "HEALTHCARE", "childcare": "CHILDCARE", "mentalhealth": "MENTAL_HEALTH", "paidfamilytime": "FAMILY_TIME", "ltc": "LTC"}
        for k, n in names.items():
            for side in ("employer", "employee"):
                const = f"RATE_{n}_{side.upper()}"
                if const in cp and float(cp[const]) != float(A[f"ASSUM-contrib-{k}-{side}"]):
                    findings.append(("MIN", "CONTRIB-RATE-DRIFT", "calculator_parameters.json", f"{const} is {cp[const]} but the registry says {A['ASSUM-contrib-'+k+'-'+side]}"))
    except Exception as ex:
        findings.append(("MIN", "CONTRIB-RATE-DRIFT", "rates", f"could not be read: {ex}"))
    try:
        top = _re.search(r"^VERSION \S+\s+.\s+(\w{3} \d{1,2}, \d{4})", open(os.path.join(package_root, "VERSIONLOG.txt"), encoding="utf-8").read(), _re.M)
        rel = _dt.datetime.strptime(top.group(1), "%b %d, %Y").strftime("%Y-%m-%d")
        for f, key in (("version.json", "build_date"), ("manifest.json", "generated_date")):
            got = json.load(open(os.path.join(package_root, f), encoding="utf-8", errors="replace")).get(key)
            if got != rel:
                findings.append(("MIN", "BUILD-DATE-STALE", f, f"{key} is {got} but the newest release is dated {rel}"))
    except Exception as ex:
        findings.append(("MIN", "BUILD-DATE-STALE", "dates", f"could not be read: {ex}"))
    return findings


def check_guide_and_version_stamp(package_root="."):
    """v3.8.399 (GUIDE-DRIFT, MIN): the reader's guide inventory and the .docx version stamp.

    Two failures with one cause: nothing generated them. 01_Platform_Package_TOC said the package
    held eighty-one items when it held 143, and 01_Platform_Package_Version stated a package version
    292 releases old, because bump_platform_version.py cannot reach inside Word files. Both now have
    builders, and this runs them in --check mode so the gate fails before a release carries either
    staleness again.
    """
    import subprocess as _sp, sys as _sys
    out = []
    # The paths are written out in full rather than joined from a loop variable, because
    # check_unwired_tools requires an ACTUAL invocation -- os.path.join(..., "tools", "<name>") --
    # and rightly refuses to count a filename that merely appears in this file. My first wiring of
    # check_deck_figures.py used a loop variable and the gate reported it as unwired.
    for path, code in (
        (os.path.join(package_root, "tools", "build_package_guide.py"), "GUIDE-DRIFT"),
        (os.path.join(package_root, "tools", "stamp_docx_version.py"), "DOCX-VERSION-STALE"),
        (os.path.join(package_root, "tools", "check_deck_figures.py"), "DECK-RETIRED-VALUE"),
        (os.path.join(package_root, "tools", "verify_model_figures.py"), "MODEL-FIGURE-MISSING"),
        (os.path.join(package_root, "tools", "check_id_series_collision.py"), "ID-SERIES-COLLISION"),
        (os.path.join(package_root, "tools", "check_catalog_copies.py"), "CATALOG-COPY-DRIFT"),
        (os.path.join(package_root, "tools", "verify_declared_derivations.py"), "DERIVATION-DOES-NOT-CLOSE"),
        (os.path.join(package_root, "tools", "build_funding_architecture.py"), "ARCHITECTURE-DRIFT"),
        (os.path.join(package_root, "tools", "check_literal_targets.py"), "LITERAL-TARGET-DRIFT"),
        (os.path.join(package_root, "tools", "check_encoding_declared.py"), "ENCODING-UNDECLARED"),
        (os.path.join(package_root, "tools", "check_qr_decode.py"), "QR-DECODE"),
        (os.path.join(package_root, "tools", "check_assumption_figure_agreement.py"), "ASSUMPTION-FIGURE-DRIFT"),
        (os.path.join(package_root, "tools", "check_stale_figure_literals.py"), "STALE-FIGURE-LITERAL"),   # v3.8.674 (author #5011)
        (os.path.join(package_root, "tools", "build_portfolio_catalog.py"), "PORTFOLIO-CATALOG-DRIFT"),   # v3.8.679 (author #5055)
        (os.path.join(package_root, "tools", "check_deploy_wrappers.py"), "DEPLOY-WRAPPER-DELETE"),   # v3.8.682 (author #5063)
        (os.path.join(package_root, "tools", "check_deploy_privacy.py"), "DEPLOY-PRIVACY"),   # v3.8.685 (author #5069)
        (os.path.join(package_root, "tools", "test_deploy_pipeline.py"), "DEPLOY-PIPELINE"),   # v3.8.690 (J21, author #5081)
        (os.path.join(package_root, "build_download_packages.py"), "DOWNLOADS-PAGE"),   # v3.8.690: downloads.html cards match the ZIPs
        (os.path.join(package_root, "tools", "sync_document_counts.py"), "DOCUMENT-COUNT-DRIFT"),
    ):
        tool = os.path.basename(path)
        if not os.path.exists(path):
            continue
        try:
            r = _sp.run([_sys.executable, path, "--check"], capture_output=True, text=True, encoding="utf-8", errors="replace",
                        cwd=package_root, timeout=180)
        except Exception as e:
            out.append(("MIN", code, tool, f"could not be run in --check mode: {e}"))
            continue
        if r.returncode != 0:
            msg = (r.stdout or r.stderr).strip().splitlines()
            out.append(("MIN", code, tool, msg[0] if msg else "check failed"))
    return out


def check_cross_sheet_drift(package_root="."):
    """v3.8.363 (CROSS-SHEET-DRIFT, MIN): a model edit that touches one sheet of six.

    RESEARCH-31 happened exactly this way. The band phase-out (v3.8.340) and absorption (v3.8.343)
    were written to Combined Cash Flow only, so the five stress sheets went on modelling the design
    the platform had abandoned -- peaks near $37 trillion against the main sheet's $85.2 trillion --
    and nothing noticed for seventeen releases. This compares each stress sheet's structural formulas
    against the main sheet's, row by row.

    WHAT IS ALLOWED TO DIFFER, because it is what makes a stress test a stress test: column M (each
    scenario's own return lookup), column J on SS-5 (its contribution haircut in years 5-7) and column
    C (the calendar-year label). Everything else must match, or the stress results describe a
    different platform from the one being published.
    """
    import openpyxl as _x
    from openpyxl.utils import get_column_letter as _L
    path = os.path.join(package_root, "04_Mathematical_Models", "04_Combined_Reform_Model.xlsx")
    if not os.path.exists(path):
        return []
    try:
        wb = _x.load_workbook(path, data_only=False)
    except Exception as ex:
        return [("MIN", "CROSS-SHEET-DRIFT", "04_Combined_Reform_Model.xlsx",
                 f"could not be opened ({type(ex).__name__}); stress sheets NOT compared")]
    if "Combined Cash Flow" not in wb.sheetnames:
        return []
    main = wb["Combined Cash Flow"]
    allowed = {"M", "C"}
    findings = []
    for sh in [s for s in wb.sheetnames if s.startswith("SS-")]:
        ws = wb[sh]
        skip = set(allowed) | ({"J"} if "SS-5" in sh else set())
        bad = []
        for row in range(4, 64):
            for col in range(2, 42):
                letter = _L(col)
                if letter in skip:
                    continue
                if str(main.cell(row=row, column=col).value) != str(ws.cell(row=row, column=col).value):
                    bad.append(f"{letter}{row}")
        if bad:
            findings.append(("MIN", "CROSS-SHEET-DRIFT", sh,
                             f"{len(bad)} cell(s) differ from Combined Cash Flow outside the scenario columns, "
                             f"first at {bad[0]}: this sheet is modelling a different design from the one published"))
    return findings


def check_annotation_currency(package_root="."):
    """v3.8.350 (ANNOTATION-STALE, MIN): a correction that has itself gone stale.

    When a figure moves, the documents stating the old value get an annotation carrying the new one.
    Those annotations are prose, linked to nothing, so the next move leaves them wrong -- which the
    document sweeps found twice: a notice in 05_Repairing_The_Past that absorption had superseded, and
    a fund trajectory in the education substantiation retired three releases earlier.
    """
    import importlib.util as _il
    path = os.path.join(package_root, "tools", "check_annotation_currency.py")
    if not os.path.exists(path):
        return []
    spec = _il.spec_from_file_location("annotcur", path)
    mod = _il.module_from_spec(spec)
    try:
        spec.loader.exec_module(mod)
        return mod.run(package_root)
    except Exception as ex:
        return [("MIN", "ANNOTATION-STALE", "tools/check_annotation_currency.py",
                 f"could not be run ({type(ex).__name__}); annotations NOT checked")]


def check_analysis_tools(package_root="."):
    """v3.8.339 (ANALYSIS-TOOL-DRIFT, MIN): the analysis tools must still reproduce the models.

    The lever search and the phase-out order results rest on tools/transition_lever_model.py
    reproducing 04_Combined_Reform_Model.xlsx to the cent. If the workbook changes and the replica
    does not, every result built on it is quietly wrong. Both tools carry a --verify; this runs them.
    """
    import subprocess as _sp
    findings = []
    for rel in ("tools/transition_lever_model.py", "tools/phaseout_order_model.py"):
        try:
            r = _sp.run([sys.executable, os.path.join(package_root, rel), "--verify"],
                        cwd=package_root, capture_output=True, text=True, timeout=240, encoding="utf-8", errors="replace")
            tail = (r.stdout or r.stderr).strip().splitlines()[-1][:160] if (r.stdout or r.stderr) else "no output"
            if r.returncode != 0:
                findings.append(("MIN", "ANALYSIS-TOOL-DRIFT", rel, f"self-check failed: {tail}"))
        except Exception as ex:
            findings.append(("MIN", "ANALYSIS-TOOL-DRIFT", rel, f"could not be run: {ex}"))
    return findings


def check_currency_ledger_honest(package_root="."):
    """v3.8.306 (CURRENCY-LEDGER-FALSE, MIN): the currency ledger must not record a stamp
    the document does not carry.

    Found while reading 09_Iterative_Hardening_Process_Documentation: the ledger said it was
    stamped at v3.8.306 and the document contained no stamp anywhere. EIGHT ENTRIES WERE
    LIKE THAT. The tool wrote the ledger BEFORE attempting the stamp, so documents with no
    version line were recorded as stamped -- and DOC-CURRENCY-STALE trusts the ledger, so it
    passed. A LEDGER THAT RECORDS INTENT RATHER THAN OUTCOME CERTIFIES ITSELF.
    """
    findings = []
    lp = os.path.join(package_root, "00_GUI_Files", "document_currency.json")
    if not os.path.exists(lp):
        return findings
    try:
        led = json.load(open(lp, encoding="utf-8"))
    except Exception:
        return findings
    for key in (led.get("documents") or {}):
        if not key.endswith(".docx"):
            continue
        path = os.path.join(package_root, key)
        if not os.path.exists(path):
            continue
        try:
            from docx import Document as _D
            text = " ".join(p.text for p in _D(path).paragraphs)
        except Exception:
            continue
        if "content last changed" not in text:
            findings.append(("MIN", "CURRENCY-LEDGER-FALSE", os.path.basename(key),
                "the currency ledger records a stamp for this document, but the document "
                "carries none. Move it to the ledger's `unstampable` block with a reason, or "
                "give it a version line."))
    return findings


def check_model_cached_values(package_root="."):
    """v3.8.323 (MODEL-NO-CACHED-VALUES, MIN): a shipped model must carry computed values,
    not just formulas.

    Excel stores a cached result beside each formula. A workbook saved without them shows
    BLANK CELLS to anyone who opens it in a viewer that does not recalculate -- Google
    Sheets preview, GitHub, LibreOffice in some modes, python readers, and every
    accessibility tool. THREE OF TWENTY-FOUR MODELS SHIP THIS WAY, including
    04_Universal_Childcare_Model.xlsx, WHICH IS ITEM 7 ON THE POLICY PROFESSIONAL READING
    PATH. A reviewer sent to it sees a dashboard of empty cells.
    """
    import glob as _g
    findings = []
    for f in sorted(_g.glob(os.path.join(package_root, "04_Mathematical_Models", "*.xlsx"))):
        try:
            import openpyxl
            wv = openpyxl.load_workbook(f, data_only=False, read_only=True)
            wc = openpyxl.load_workbook(f, data_only=True, read_only=True)
        except Exception:
            continue
        form = cached = 0
        for sh in wv.sheetnames[:8]:
            try:
                rv = wv[sh].iter_rows(max_row=60, max_col=12, values_only=True)
                rc = wc[sh].iter_rows(max_row=60, max_col=12, values_only=True)
            except Exception:
                continue
            for row_v, row_c in zip(rv, rc):
                for a, b in zip(row_v, row_c):
                    if isinstance(a, str) and a.startswith("="):
                        form += 1
                        if b is not None:
                            cached += 1
        if form and cached == 0:
            findings.append(("MIN", "MODEL-NO-CACHED-VALUES", os.path.basename(f),
                f"{form} formula cells and no cached results: the workbook shows blank "
                f"cells to any reader whose tool does not recalculate. Open it in Excel, "
                f"let it compute, and save."))
    return findings


def check_wage_calculator_counts(package_root="."):
    """v3.8.320 (WAGE-COUNTS-STALE, MIN): the wage calculator's occupation counts must
    match the data it loads.

    Its header said "865 BLS SOC detailed codes; 800 carry real BLS ... 3 are
    BLS-suppressed ... and 53 are illustrative". 800 + 3 + 53 = 856. THE PAGE DID NOT ADD
    UP TO ITS OWN TOTAL, and the shipped data holds 62 illustrative -- the count moved when
    v3.8.265 regenerated the wage tables and merged the aide rows onto the BLS combined SOC.
    Now generated by tools/build_canonical_counts.py.
    """
    findings = []
    wf = os.path.join(package_root, "06_Presentation_Materials",
                      "06_Wage_Floor_Comparison_Calculator.html")
    dp = os.path.join(package_root, "06_Presentation_Materials", "wage_floor_data.json")
    if not (os.path.exists(wf) and os.path.exists(dp)):
        return findings
    try:
        occ = json.load(open(dp, encoding="utf-8"))["occupations"]
        text = open(wf, encoding="utf-8", errors="ignore").read()
    except Exception:
        return findings
    want = {
        "total": len(occ),
        "bls": sum(1 for o in occ if str(o.get("data_source", "")).startswith("BLS_OEWS")),
        "suppressed": sum(1 for o in occ if "suppress" in str(o.get("data_source", "")).lower()),
        "illustrative": sum(1 for o in occ if "illustr" in str(o.get("data_source", "")).lower()),
    }
    pats = {
        "total": r"from (\d+) BLS SOC detailed codes",
        "bls": r"\b(\d+) carry real BLS",
        "suppressed": r"\b(\d+) are BLS-suppressed",
        "illustrative": r"\b(\d+) are illustrative",
    }
    for key, pat in pats.items():
        m = re.search(pat, text)
        if m and int(m.group(1)) != want[key]:
            findings.append(("MIN", "WAGE-COUNTS-STALE", "06_Wage_Floor_Comparison_Calculator.html",
                f"page states {m.group(1)} for '{key}'; the shipped data holds {want[key]}. "
                f"Run tools/build_canonical_counts.py."))
    if want["bls"] + want["suppressed"] + want["illustrative"] != want["total"]:
        findings.append(("MIN", "WAGE-COUNTS-STALE", "wage_floor_data.json",
            "the three data_source categories do not sum to the occupation total"))
    return findings


def check_figures_coverage_claim(package_root="."):
    """v3.8.317 (FIGURES-COVERAGE-STALE, MIN): the figures-coverage sentence on any page
    must match the registry.

    06_Platform_Architecture.html -- item 1 on every reading path, the first thing a
    first-time visitor reads -- stated "27 of the platform's 72 registered figures trace
    all the way to a sealed federal source" while the registry held 28 of 73. Both numbers
    were typed by hand, and both drifted within three releases of being written.
    The sentence is now generated by tools/build_canonical_counts.py. This is the guard.
    """
    import glob as _g
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fp):
        return findings
    try:
        E = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception:
        return findings
    sealed, figs = sum(1 for e in E if e.get("source_id")), len(E)
    pat = re.compile(r"(\d+)\s+of the platform(?:&rsquo;s|'s|\u2019s)?\s+(\d+)\s+registered figures")
    for f in sorted(set(_g.glob(os.path.join(package_root, "*.html"))
                        + _g.glob(os.path.join(package_root, "0*", "*.html")))):
        if "_web_html" in f or "_downloads" in f:
            continue
        try:
            text = open(f, encoding="utf-8", errors="ignore").read()
        except Exception:
            continue
        for m in pat.finditer(text):
            if (int(m.group(1)), int(m.group(2))) != (sealed, figs):
                findings.append(("MIN", "FIGURES-COVERAGE-STALE", os.path.basename(f),
                    f"page says {m.group(1)} of {m.group(2)} registered figures trace to a "
                    f"sealed source; the registry holds {sealed} of {figs}. Run "
                    f"tools/build_canonical_counts.py."))
    return findings


def check_reading_paths_generated(package_root="."):
    """v3.8.315 (READING-PATH-DRIFT, MIN): the reading-path guides must match what the
    catalog would generate.

    00_Reading_Paths/README.md claimed "Generated from platform_catalog.json" from
    v3.7.606 and THE GENERATOR DID NOT SHIP -- it was a one-off from that release, and
    tools/ keeps 329 one-offs but not that one. So the guides were hand-maintained files
    wearing a generated file's clothes, and they drifted twice over: six dead links fixed
    at v3.8.314, and stale CONTENT found when the generator was finally rebuilt at
    v3.8.315 -- "81 issues" against a catalog saying 102, "53 CLOSED, 29 OPEN" against
    58 and 44.
    """
    findings = []
    tool = os.path.join(package_root, "tools", "build_reading_paths.py")
    if not os.path.exists(tool):
        return findings
    import subprocess as _sp, sys as _sys
    try:
        r = _sp.run([_sys.executable, tool, "--check"], capture_output=True,
                           text=True, encoding="utf-8", errors="replace", cwd=package_root, timeout=180)
    except Exception as e:
        return [("MIN", "READING-PATH-DRIFT", "build_reading_paths.py",
                 f"could not run the generator in --check mode: {e}")]
    if r.returncode != 0:
        findings.append(("MIN", "READING-PATH-DRIFT", "00_Reading_Paths",
            (r.stdout or r.stderr or "").strip().splitlines()[0][:200]
            if (r.stdout or r.stderr) else "guides no longer match the catalog"))
    return findings


def check_reading_path_resolves(package_root="."):
    """v3.8.314 (READING-PATH-BROKEN, MIN): every document a reading path sends a reader
    to must exist at the path given.

    The reading paths are the platform's own routing -- the five audiences it defines, and
    the only route most readers take. SIX ENTRIES POINTED AT FILES THAT DO NOT EXIST,
    missing their folder prefixes: the wage-floor calculator, the regional variation
    examples and the data-sources methodology, across the Skeptical Reader, Policy
    Professional and Household Curious paths. The catalog is the source and the markdown
    files are generated from it, SO BOTH CARRIED THE SAME SIX BREAKS. A reader on the
    skeptical path hit a dead link at step three.
    """
    import glob as _g
    findings = []
    cat_p = os.path.join(package_root, "00_GUI_Files", "platform_catalog.json")
    if os.path.exists(cat_p):
        try:
            cat = json.load(open(cat_p, encoding="utf-8"))
        except Exception:
            cat = {}
        for key, path_obj in (cat.get("readingPaths") or {}).items():
            docs = path_obj.get("documents")
            if not isinstance(docs, list):
                continue        # deep_dive carries a sentinel string, not a list
            for it in docs:
                rel = it.get("path") if isinstance(it, dict) else it
                if not rel:
                    continue
                if not os.path.exists(os.path.join(package_root, rel)):
                    findings.append(("MIN", "READING-PATH-BROKEN", key,
                        f"reading path sends a reader to '{rel}', which does not exist"))
    for f in _g.glob(os.path.join(package_root, "00_Reading_Paths", "*.md")):
        try:
            text = open(f, encoding="utf-8", errors="ignore").read()
        except Exception:
            continue
        for m in re.finditer(r"`([^`]+\.(?:docx|html|xlsx|pdf|md))`", text):
            if not os.path.exists(os.path.join(package_root, m.group(1))):
                findings.append(("MIN", "READING-PATH-BROKEN", os.path.basename(f),
                    f"reading path lists '{m.group(1)}', which does not exist"))
    return findings


def check_calibration_named(package_root="."):
    """v3.8.298 (CALIBRATION-UNNAMED, MIN): an assumption pending EXTERNAL calibration must
    name the discipline that could settle it and what would settle it.

    Twelve of twenty-five carried the label with NO role and NO settling source. That is a
    claim that someone else's expertise is needed, without saying whose or what evidence
    would close it -- and it inflates the count of things the platform says it cannot do
    for itself. Three of the twelve turned out not to be external questions at all: one was
    a platform DECISION that must precede any costing, one was a DUPLICATE of another
    entry, and one was CONDITIONAL on a decision already taken.
    """
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json")
    if not os.path.exists(fp):
        return findings
    try:
        entries = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception:
        return findings
    for e in entries:
        if e.get("validation_status") != "pending_external_calibration":
            continue
        if not e.get("roles_that_could_advance_it"):
            findings.append(("MIN", "CALIBRATION-UNNAMED", e.get("id", "?"),
                "pending external calibration with no discipline named. Say who could settle "
                "it, or reclassify: it may be a decision, a duplicate, or already conditional "
                "on something settled."))
        if not e.get("settling_sources"):
            findings.append(("MIN", "CALIBRATION-UNNAMED", e.get("id", "?"),
                "pending external calibration with no settling source named. Say what evidence "
                "would close it."))
    return findings


def check_retired_values_live(package_root="."):
    """v3.8.281 (RETIRED-VALUE-LIVE, MIN): a value the platform has withdrawn must not
    appear unannotated in a current document.

    A MANUAL SWEEP AT v3.8.280 FOUND FOUR, and the sweep only happened because v3.8.279
    noticed that a stale registry and a stale site agreed with each other so no gate fired.
    Among them: a sixth-grade handout showing three superseded wage figures, and a
    WITHDRAWN fund value serving as an acceptance criterion in the Open Issues Registry.
    That class needs a guard, not a good memory.

    Retired values are structured data -- figures_registry.json entries carry
    `retired_values` with the release that retired each and what replaced it. History
    surfaces are excluded BY NAME: the archives, the changelog, the review log and the
    declared historical records carry these numbers on purpose.
    """
    import glob as _g
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fp):
        return findings
    try:
        entries = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception:
        return findings
    retired = []
    for e in entries:
        for rv in (e.get("retired_values") or []):
            # v3.8.294: COLLISIONS. The same digits can mean something else entirely --
            # $14,570 is both a superseded healthcare baseline and a standard deduction in
            # two tax-comparison tables, and $43B was both a fraud baseline and a paid family
            # time cost model (v3.8.240, where a blind replace corrupted the wrong one).
            # A collision is DECLARED PER FILE WITH A REASON, not silently skipped.
            retired.append((e.get("id"), str(rv.get("value")), rv.get("replaced_by", ""),
                            {c.get("file"): c.get("reason") for c in (rv.get("collisions") or [])}))
    if not retired:
        return findings
    # v3.8.295: RECOMPUTED and RECONCILED are correction markers this platform uses in
    # release notes and inline annotations. Omitting them meant a properly annotated
    # correction still failed the guard, which pushes an author toward rewording a good
    # note rather than keeping it.
    ANN = re.compile(r"SUPERSEDED|CORRECTED|RETIRED|RE-DERIVED|RECOMPUTED|RECONCILED"
                     r"|earlier|previously|formerly|was\b|old\b|history", re.I)
    files = []
    for f in _g.glob(os.path.join(package_root, "0*", "*.docx")):
        if any(h in f for h in HISTORY_SURFACES):
            continue
        try:
            from docx import Document as _D
            doc = _D(f)
            t = " ".join(p.text for p in doc.paragraphs)
            for tb in doc.tables:
                for row in tb.rows:
                    for c in row.cells:
                        t += " " + c.text
            files.append((f, t))
        except Exception:
            continue
    # v3.8.506: root pages added ("*.html"). policymaker.html carried two retired spending values
    # in its gross/net figure and caption for releases because only index.html was read here.
    for pat in ("0*/*.html", "0*/*.md", "*.html", "*.md"):
        for f in _g.glob(os.path.join(package_root, pat)):
            # v3.8.364: the retired-value scan report quotes every retired value by design.
            if os.path.basename(f) == "RETIRED_VALUE_SCAN.md":
                continue
            if any(h in f for h in HISTORY_SURFACES):
                continue
            try:
                files.append((f, open(f, encoding="utf-8", errors="ignore").read()))
            except Exception:
                continue
    # v3.8.316: THE DATA SURFACES, WHICH THIS CHECK HAS NEVER SCANNED. It read documents,
    # pages and markdown -- not the four files that DEFINE the values. That blind spot let
    # $14,570 survive in eight places inside figures_registry.json after v3.8.294 corrected
    # it everywhere a reader looks, and let the retired $122 trillion sit in three
    # platform_catalog.json descriptions that drive the website until v3.8.315.
    # A guard against stale values that cannot see the value definitions is half a guard.
    # v3.8.316, SECOND ATTEMPT. Scanning these files WHOLE was wrong: their notes are a
    # RECORD OF PAST STATE by design -- prior test details, quotations of document prose,
    # findings that say "the published figure is wrong" -- and flagging those is the same
    # error as sweeping VERSIONLOG. What matters is the fields that RENDER: a value a
    # reader can meet. So only those are scanned.
    #   figures_registry   canonical, narrative_examples display/value, public_note,
    #                      public_label
    #   catalog            document descriptions and reading-path context strings
    def _render_text(rel):
        f = os.path.join(package_root, rel)
        if not os.path.exists(f):
            return None
        try:
            blob = json.load(open(f, encoding="utf-8"))
        except Exception:
            return None
        parts = []
        if "figures_registry" in rel or "assumptions_registry" in rel:
            for e in blob.get("entries", []):
                parts.append(json.dumps(e.get("canonical")))
                parts.append(str(e.get("public_note") or ""))
                parts.append(str(e.get("public_label") or ""))
                for x in (e.get("narrative_examples") or []):
                    parts.append(str(x.get("display") or ""))
                    parts.append(str(x.get("value") or ""))
                parts.append(str(e.get("current_value") or ""))
                parts.append(json.dumps(e.get("range")))
        else:
            for d in blob.get("documents") or []:
                parts.append(str(d.get("description") or ""))
                parts.append(str(d.get("summary") or ""))
            for pth in (blob.get("readingPaths") or {}).values():
                docs = pth.get("documents")
                if isinstance(docs, list):
                    for it in docs:
                        if isinstance(it, dict):
                            parts.append(str(it.get("context") or ""))
        return " \u2026 ".join(p for p in parts if p and p != "null")

    for rel in ("00_GUI_Files/platform_catalog.json",
                "00_GUI_Files/figures_registry.json",
                "00_GUI_Files/assumptions_registry.json"):
        txt = _render_text(rel)
        if txt:
            files.append((os.path.join(package_root, rel), txt))
    for fid, val, repl, collisions in retired:
        for f, text in files:
            if os.path.basename(f) in collisions:
                continue
            # v3.8.629: never match inside a larger number ('4.2 trillion' inside '$84.2 trillion')
            for m in re.finditer(r'(?<![\d.,])' + re.escape(val), text):
                window = text[max(0, m.start() - 110):m.end() + 110]
                if ANN.search(window):
                    continue
                findings.append(("MIN", "RETIRED-VALUE-LIVE", os.path.basename(f),
                    f"'{val}' was retired from {fid} and appears here unannotated. "
                    f"Replaced by: {repl}"))
                break
    return findings


def check_public_label_numbers(package_root="."):
    """v3.8.506 (PUBLIC-LABEL-NUMBER, MIN): a number inside a figure's public_label must match
    that figure's canonical value.

    The registry's own convention says a public_label is "A LABEL, NOT A CLAIM". Three labels
    embedded values instead -- "$1.4976 trillion", "$3.5024 trillion", "54 percent" -- set when
    those were the values (v3.8.201). The figures moved (v3.8.337, v3.8.409) and the labels did
    not, so tools/build_figure_caveats.py printed the retired numbers onto policymaker.html, one
    sentence calling net new spending $3.5024 trillion "around the published $2.8 trillion".
    check_retired_values_live could not see it: it does not read root .html pages, and the old
    values were never registered as retired. This checks the SOURCE, so the output cannot drift.
    A label number passes if it rounds to the canonical value, a band end or any scenario value at
    the precision the label states.
    """
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    try:
        entries = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception as e:
        return [("MIN", "PUBLIC-LABEL-NUMBER", "00_GUI_Files/figures_registry.json", f"could not read: {e}")]
    for e in entries:
        lab = e.get("public_label") or ""
        # a duration ("60-year size") names the horizon, not the value
        nums = re.findall(r"\d[\d,]*(?:\.\d+)?(?![\d.,]*[- ]?years?\b)", lab)
        if not nums:
            continue
        c = e.get("canonical") or {}
        cands = [c.get(k) for k in ("value", "band_low", "band_high")]
        cands += list((c.get("by_scenario") or {}).values())
        cands = [float(x) for x in cands if isinstance(x, (int, float))]
        for n in nums:
            dec = len(n.split(".")[1]) if "." in n else 0
            v = float(n.replace(",", ""))
            if not any(round(x, dec) == v or abs(x - v) <= 0.5 * 10 ** -dec for x in cands):
                findings.append(("MIN", "PUBLIC-LABEL-NUMBER", "00_GUI_Files/figures_registry.json",
                    f"{e.get('id')}: public_label states {n}, which matches none of its canonical "
                    f"values {cands}. Labels name a figure; they must not restate a value that can move."))
    return findings


def check_guide_prose(package_root="."):
    """v3.8.506 (GUIDE-PROSE-STALE, MIN): the hand-written part of 01_Platform_Package_TOC.docx
    must not cite documents by item number, and every path it names must exist.

    The v3.8.399 split generated the guide's inventory and left its prose hand-written. The
    prose then carried 'item 53'-style references and 133 numbered tables, last renumbered for
    v2.23, with 11 paths to files that no longer existed; GUIDE-STAMP only checked the region.
    Replaced at v3.8.506 (author decision 3A) by reading paths that name documents by title.
    """
    findings = []
    rel = "01_Start_Here/01_Platform_Package_TOC.docx"
    fp = os.path.join(package_root, rel)
    if not os.path.exists(fp):
        return findings
    try:
        from docx import Document as _D
        d = _D(fp)
    except Exception as e:
        return [("MIN", "GUIDE-PROSE-STALE", rel, f"could not read: {e}")]
    ps = [p.text for p in d.paragraphs]
    end = next((i for i, t in enumerate(ps) if t.startswith("=== GENERATED INVENTORY")), len(ps))
    txt = " ".join(ps[:end]) + " " + " ".join(c.text for tb in d.tables for r in tb.rows for c in r.cells)
    refs = re.findall(r"\bitems? \d+", txt)
    if refs:
        findings.append(("MIN", "GUIDE-PROSE-STALE", rel,
            f"hand-written prose cites documents by item number ({', '.join(sorted(set(refs))[:5])}); name them by title"))
    for pth in sorted(set(re.findall(r"\b(?:0\d|_\w+)[\w]*/[\w\-.]+\.(?:docx|xlsx|pdf|pptx|html|md|json)", txt))):
        if not os.path.exists(os.path.join(package_root, pth)):
            findings.append(("MIN", "GUIDE-PROSE-STALE", rel, f"hand-written prose names a path that does not exist: {pth}"))
    return findings


# v3.8.508 (author decision F3): figures whose display deliberately differs from canonical, each with its reason.
NARRATIVE_DISPLAY_EXEMPT = {
    # v3.8.699 (author #5109): the four household entries removed. Their reason, the W7 deferral, ended when W7 closed at v3.8.522
    # (#3928), but the exemption stayed, so the current-tax display kept printing $33,159 after its canonical moved to 33,103 at
    # v3.8.662. NARRATIVE-EXEMPT-STALE (below) now fails an exemption whose reason names a closed work item.
    "FIG-civic-infrastructure-gap": "documented deliberate retier; session_state lists it as the one documented failing figure",
    "FIG-education-fund-gross": "ASSUM-education-gross-construction is awaiting the author's decision; the display is that span's top end",
    "FIG-us-population": "unit scaling: the display is in millions, the canonical value in persons",
    "FIG-pillar-financing-gap": "the display names three canonical fields -- the uncovered total, the borrowing peak (debt_peak) and its year (debt_peak_year) -- written from them by its tool; approved wording, author #4646",
}


def check_narrative_display_drift(package_root="."):
    """v3.8.508 (NARRATIVE-DISPLAY-DRIFT, MIN): a bare [[FIG:id]] token prints the figure's first
    narrative_examples display, NOT its canonical value, and nothing compared the two. Fifteen displays
    had fallen behind restatements of their own figures -- the deficit effect printed $2.64T against
    2.7225, transition borrowing $35T against 91.75, the healthcare baseline $14,570 against 15,474 --
    so a correctly tokenised sentence printed a wrong number. A display number must match the figure's
    canonical value, a band end or a scenario value at the precision shown. Durations, four-digit years
    and rates are not values and are skipped; deliberate exceptions live in NARRATIVE_DISPLAY_EXEMPT
    with their reason.
    """
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    try:
        entries = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception as e:
        return [("MIN", "NARRATIVE-DISPLAY-DRIFT", "00_GUI_Files/figures_registry.json", f"could not read: {e}")]
    for e in entries:
        if e.get("id") in NARRATIVE_DISPLAY_EXEMPT:
            continue
        ne = (e.get("narrative_examples") or [None])[0]
        if not isinstance(ne, dict) or not ne.get("display"):
            continue
        c = e.get("canonical") or {}
        vals = [c.get(k) for k in ("value", "band_low", "band_high")] + list((c.get("by_scenario") or {}).values())
        vals = [abs(float(x)) for x in vals if isinstance(x, (int, float))]
        if not vals:
            continue
        pct_unit = "percent" in str(c.get("unit", "")).lower()
        for m in re.finditer(r"(\d[\d,]*(?:\.\d+)?)(\s*(?:-|\s)?(?:percent|%|years?|year)\b)?", ne["display"]):
            n, tail = m.group(1), (m.group(2) or "")
            if re.fullmatch(r"(19|20)\d\d,?", n):
                continue
            if tail and ("year" in tail or not pct_unit):
                continue
            v = float(n.replace(",", "").rstrip(","))
            dec = len(n.split(".")[1]) if "." in n else 0
            if not any(abs(x - v) <= 0.5 * 10 ** -dec + 1e-9 for x in vals):
                findings.append(("MIN", "NARRATIVE-DISPLAY-DRIFT", "00_GUI_Files/figures_registry.json",
                    f"{e.get('id')}: its token prints '{n}' ({ne['display'][:70]}), which matches none of its "
                    f"canonical values {[round(x, 4) for x in vals][:4]}. Re-synchronise the display, or record a reason in NARRATIVE_DISPLAY_EXEMPT."))
    return findings


# v3.8.699 (author #5109, R6a): figures whose headline is not at the platform's published 4 percent return, each with its reason.
HEADLINE_RETURN_EXEMPT = {}   # v3.8.700 (author #5113, R3a): both borrowing figures now carry a 4 percent case


def check_figure_value_agreement(package_root="."):
    """v3.8.699 (author #5109, R6a). Three ways a figure's own record fell out of step without a message (review #5108):
    NARRATIVE-EXEMPT-STALE  an exemption from NARRATIVE-DISPLAY-DRIFT whose reason names a work item the decision index records as
                            CLOSED. The household exemptions cited the W7 deferral for 177 releases after W7 closed (v3.8.522), and
                            the current-tax display printed $33,159 against a canonical 33,103 the whole time.
    NARRATIVE-VALUE-DRIFT   a narrative example's stored value that is not the canonical (unlabelled) or the 4 percent case (a
                            baseline or short example of a figure with return scenarios). Nine held superseded numbers; any tool
                            that read them would print an old figure.
    HEADLINE-RETURN         a figure with fund-return scenarios and no 4 percent case: its headline cannot be at the platform's
                            published return. Cumulative borrowing ($91T, 4.28 percent) sat beside the fund ($154T, 4 percent) in
                            one sentence of the Manifesto."""
    findings = []
    try:
        entries = json.load(open(os.path.join(package_root, "00_GUI_Files", "figures_registry.json"), encoding="utf-8"))["entries"]
    except Exception as e:
        return [("MIN", "NARRATIVE-VALUE-DRIFT", "00_GUI_Files/figures_registry.json", f"could not read: {e}")]
    closed = set()
    try:
        for line in open(os.path.join(package_root, "09_Meta_Tracking", "decision_index.jsonl"), encoding="utf-8"):
            rec = json.loads(line)
            if rec.get("kind") == "closure":
                closed |= set(rec.get("keys") or [])
    except Exception:
        pass
    for fid, why in NARRATIVE_DISPLAY_EXEMPT.items():
        for item in re.findall(r"\b(W\d+|J\d+)\b", why):
            if item in closed:
                findings.append(("MIN", "NARRATIVE-EXEMPT-STALE", "audit_script.py",
                    f"{fid} is exempt from NARRATIVE-DISPLAY-DRIFT because of {item}, which the decision index records as CLOSED; "
                    f"re-synchronise its display and remove the exemption, or give a current reason"))
    for e in entries:
        c = e.get("canonical") or {}
        bys = c.get("by_scenario") if isinstance(c.get("by_scenario"), dict) else None
        for ex in e.get("narrative_examples") or []:
            if not isinstance(ex, dict) or not isinstance(ex.get("value"), (int, float)):
                continue
            lab = ex.get("label")
            if not lab and isinstance(c.get("value"), (int, float)):
                want = [c["value"]]
            elif bys and "4pct" in bys and (not lab or lab in ("baseline", "short", "short4")):
                want = [bys["4pct"], -bys["4pct"]]
            else:
                continue
            if not any(abs(ex["value"] - w) <= 1e-6 * max(1, abs(w)) for w in want):
                findings.append(("MIN", "NARRATIVE-VALUE-DRIFT", "00_GUI_Files/figures_registry.json",
                    f"{e['id']}: narrative example {lab or '(first)'} stores {ex['value']}, not the registered {want[0]}"))
        if bys and c.get("scenario_assumption") == "ASSUM-fund-real-return" and e["id"] not in HEADLINE_RETURN_EXEMPT:
            if not any(re.fullmatch(r"4(\.0+)?pct", k) for k in bys):
                findings.append(("MIN", "HEADLINE-RETURN", "00_GUI_Files/figures_registry.json",
                    f"{e['id']} has return scenarios {sorted(bys)} but no 4 percent case, so its headline is not at the platform's "
                    f"published return"))
    for fid in HEADLINE_RETURN_EXEMPT:
        if not any(e["id"] == fid for e in entries):
            findings.append(("MIN", "HEADLINE-RETURN", "audit_script.py", f"HEADLINE_RETURN_EXEMPT names {fid}, which is not a registered figure"))
    return findings


def check_rendered_value_wording(package_root="."):
    """v3.8.701 (author #5115). Read the pages AS A READER SEES THEM -- tokens resolved -- for two faults the source cannot show:
    RETURN-ATTRIBUTION  a value printed 'at a 4 percent return' tied in the same sentence to the sourced 4.28 percent (or the
                        reverse). The Community Contribution Plan white paper read 'At the sourced 4.28 percent baseline real
                        return the fund grows to approximately about $154 trillion at a 4 percent return' (#5114).
    DOUBLED-HEDGE       'approximately about', 'about about': a hedge typed before a token whose display already carries one.
                        Twenty-three were fixed across sixteen documents at v3.8.701; records are skipped."""
    import glob as _g, html as _h
    findings = []
    p1 = re.compile(r"\b(approximately|about|roughly|around|nearly) (about|approximately|roughly|around)\b", re.I)
    p2 = re.compile(r"4\.28 percent[^.;]{0,160}?at a 4 percent return|at a 4 percent return[^.;]{0,160}?at the (?:sourced |realized )?4\.28 percent", re.I)
    pages = _g.glob(os.path.join(package_root, "*.html")) + _g.glob(os.path.join(package_root, "_web_html", "**", "*.html"), recursive=True)
    for p in sorted(pages):
        rel = os.path.relpath(p, package_root)
        if os.path.basename(p) in ("style_guide.html", "ui_lexicon.html", "colorblind_simulation.html"):
            continue
        # Records keep their wording: a CLOSED registry row never changes (decision index D6), and version history is history.
        if re.search(r"Open_Issues_Registry|OIR_Iteration|Package_Version|Conversation|Gemini_Review", rel):
            continue
        try:
            t = open(p, encoding="utf-8", errors="ignore").read()
        except Exception:
            continue
        t = re.sub(r"<script.*?</script>|<style.*?</style>", "", t, flags=re.S)
        t = re.sub(r"\s+", " ", _h.unescape(re.sub(r"<[^>]+>", " ", t)))
        for rx, code in ((p2, "RETURN-ATTRIBUTION"), (p1, "DOUBLED-HEDGE")):
            for m in rx.finditer(t):
                findings.append(("MIN", code, rel, "..." + t[max(0, m.start() - 70): m.end() + 40].strip() + "..."))
    return findings


def check_orphan_figures(package_root="."):
    """v3.8.276 (ORPHAN-FIGURE, MIN): a registered figure must appear somewhere a reader
    looks, or the registry must say why it does not.

    FIG-wagefloor-weighted-average was found at v3.8.275 to exist ONLY in its own registry
    entry -- no document, no page, nothing a reader opens. A sweep then found one more,
    FIG-ltc-funding-gap, a $124.3 billion annual shortfall the financing workbook documents
    in its own words and no reader-facing file mentioned. A FIGURE THE PLATFORM PUBLISHES
    TO ITSELF IS NOT PUBLISHED. The escape hatch is a declaration with a reason, not silence:
    set divergence.no_document_states_this_figure with divergence.reason.
    """
    import glob as _g
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fp):
        return findings
    try:
        entries = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception:
        return findings
    texts = []
    for f in _g.glob(os.path.join(package_root, "0*", "*.docx")):
        try:
            from docx import Document as _D
            doc = _D(f)
            t = " ".join(p.text for p in doc.paragraphs)
            for tb in doc.tables:
                for row in tb.rows:
                    for c in row.cells:
                        t += " " + c.text
            texts.append(t)
        except Exception:
            continue
    for pat in ("_web_html/*.html", "0*/*.md", "*.md"):
        for f in _g.glob(os.path.join(package_root, pat)):
            try:
                texts.append(open(f, encoding="utf-8", errors="ignore").read())
            except Exception:
                continue
    for e in entries:
        div = e.get("divergence") or {}
        if div.get("no_document_states_this_figure"):
            if not div.get("reason"):
                findings.append(("MIN", "ORPHAN-FIGURE", e.get("id", "?"),
                    "declared as stated in no document, but no reason is recorded"))
            continue
        can = e.get("canonical") or {}
        toks = [e.get("id")]
        for v in (can.get("value"), can.get("low"), can.get("high")):
            if isinstance(v, (int, float)):
                toks += [f"{v:,}", str(v)]
        if not any(tok and any(tok in t for t in texts) for tok in toks):
            findings.append(("MIN", "ORPHAN-FIGURE", e.get("id", "?"),
                "registered but stated in no document, page or markdown file a reader opens. "
                "Surface it, or declare divergence.no_document_states_this_figure with a reason."))
    return findings


def check_divergence_surfaced(package_root="."):
    """v3.8.262 (DIVERGENCE-NOT-SURFACED, MIN): a divergence the registry records must be
    VISIBLE IN THE DOCUMENT THAT STATES THE FIGURE.

    The rule exists because of a shape the exhaustive audit hit repeatedly: THE REGISTRY
    KNEW SOMETHING THE READER-FACING DOCUMENT DID NOT. The clearest case was
    FIG-paidfamilytime-commitment-gross, where the platform triangulated its own stated
    $40-60B range to $33.5-54.8B at v3.8.10, recorded the disagreement in the registry,
    and left the pillar paper saying $40-60B with no caveat for eight months. A reader
    opening that document had no way to learn what the platform already knew.

    THE RULE: if a figure's notes record a divergence, the entry must carry a
    `divergence` block naming `surfaced_in` -- the document(s) stating the figure -- and
    each of those documents must actually contain a visible divergence marker. Recording
    a disagreement is not disclosing it.
    """
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fp):
        return findings
    try:
        entries = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception as e:
        return [("MIN", "DIVERGENCE-NOT-SURFACED", "figures_registry.json", f"unreadable: {e}")]
    for e in entries:
        fid = e.get("id", "?")
        blob = " ".join(str(e.get(k, "")) for k in ("notes", "public_note"))
        if not DIVERGENCE_MARKERS.search(blob):
            continue
        div = e.get("divergence")
        # v3.8.275: A FIGURE NO DOCUMENT STATES HAS NOWHERE TO BE SURFACED. The registry may
        # declare that, with a reason, and the check accepts it -- what it will not accept is
        # silence. FIG-wagefloor-weighted-average is the case that forced this: its only
        # occurrence in the entire package is its own registry entry.
        if isinstance(div, dict) and div.get("no_document_states_this_figure"):
            if not div.get("reason"):
                findings.append(("MIN", "DIVERGENCE-NOT-SURFACED", fid,
                    "declared as stated in no document, but no reason is recorded"))
            continue
        if not isinstance(div, dict) or not div.get("surfaced_in"):
            findings.append(("MIN", "DIVERGENCE-NOT-SURFACED", fid,
                "the registry records a divergence for this figure but no `divergence` block "
                "names the document(s) where a reader can see it. Recording is not disclosing."))
            continue
        for rel in div["surfaced_in"]:
            path = os.path.join(package_root, rel)
            if not os.path.exists(path):
                findings.append(("MIN", "DIVERGENCE-NOT-SURFACED", fid,
                    f"divergence declared surfaced in {rel}, which is not in the package"))
                continue
            try:
                if rel.lower().endswith(".docx"):
                    from docx import Document as _D
                    doc = _D(path)
                    text = " ".join(p.text for p in doc.paragraphs)
                    for tb in doc.tables:
                        for row in tb.rows:
                            for c in row.cells:
                                text += " " + c.text
                else:
                    text = open(path, encoding="utf-8", errors="ignore").read()
            except Exception as ex:
                findings.append(("MIN", "DIVERGENCE-NOT-SURFACED", fid,
                    f"could not read {rel} to confirm the divergence is visible: {ex}"))
                continue
            # v3.8.275: THE DOCUMENT MUST ALSO CONTAIN THE FIGURE. The first version of this
            # check accepted ANY divergence/superseded/corrected marker anywhere in the named
            # file, so a block pointing at a document that does not state the figure at all
            # passed -- which happened to FIG-wagefloor-weighted-average in this very release.
            # A disclosure rule is satisfied by a reader seeing the caveat beside the number,
            # not by a field naming a file.
            can = e.get("canonical") or {}
            vals = [can.get("value"), can.get("low"), can.get("high")]
            # v3.8.275: the SUPERSEDED value counts too. A document carrying the old number
            # beside its correction is exactly where the divergence belongs, and testing only
            # against the CURRENT canonical would reject it -- which it did for
            # FIG-fund-corpus-year60, whose annotation sits next to the retired $122T.
            vals += re.findall(r"\d[\d,.]*", str(div.get("summary") or ""))
            mentions = fid in text or any(
                v is not None and (str(v) in text or f"{v:,}" in text) for v in vals)
            if not mentions:
                findings.append(("MIN", "DIVERGENCE-NOT-SURFACED", fid,
                    f"{rel} is declared as the place this divergence is surfaced, but the "
                    f"document does not state this figure at all"))
            elif not DIVERGENCE_MARKERS.search(text) and "SUPERSEDED" not in text.upper() \
                    and "CORRECTED" not in text.upper():
                findings.append(("MIN", "DIVERGENCE-NOT-SURFACED", fid,
                    f"{rel} is declared as the place this divergence is surfaced, but the "
                    f"document carries no visible divergence, superseded or corrected marker"))
    return findings


def check_typed_figures(package_root="."):
    """v3.8.565 (W37a, TYPED-FIGURE, MIN): a model must READ a registered figure, not type it.

    microsimulation/reform/robustness.py typed the bridge credit (115e9, 76e9) and kept the retired profile after the
    register's source was superseded. Any UPPER-CASE constant in the model code whose value equals a registered figure
    (within 0.5 percent, at the figure's unit) fails: read it from 00_GUI_Files/figures_registry.json instead.
    """
    import json as _j, os as _o, re as _r, glob as _g
    try:
        E = _j.load(open(_o.path.join(package_root, "00_GUI_Files", "figures_registry.json"), encoding="utf-8"))["entries"]
    except Exception:
        return []
    vals = []
    for e in E:
        c = e.get("canonical", {}) or {}; u = str(c.get("unit", ""))
        sc = 1e9 if "billion" in u else (1e12 if "trillion" in u else 1)
        for v in [c.get("value"), c.get("representative")] + list((c.get("by_year") or {}).values()) + list((c.get("by_scenario") or {}).values()):
            if isinstance(v, (int, float)) and v and v * sc >= 1e6:
                vals.append((e["id"], float(v) * sc))
    out = []
    for f in sorted(_g.glob(_o.path.join(package_root, "microsimulation", "reform", "*.py"))):
        for i, line in enumerate(open(f, encoding="utf-8"), 1):
            m = _r.match(r"\s*([A-Z][A-Z0-9_]+)\s*=\s*([0-9.]+e[0-9]+|[0-9][0-9_.]*)\b", line)
            if not m:
                continue
            x = float(m.group(2).replace("_", ""))
            for fid, v in vals:
                if abs(x - v) / v <= 0.005:
                    out.append(("MIN", "TYPED-FIGURE", _o.path.relpath(f, package_root),
                                f"line {i}: {m.group(1)} = {m.group(2)} types {fid}; read it from the register"))
                    break
    return out


def check_retired_as_canonical(package_root="."):
    """v3.8.565 (W37b, RETIRED-AS-CANONICAL, MIN): a value listed as retired must not remain a register value.

    tools/scan_retired_values.py listed '$115B bridge peak -> about $86 billion in year 17' as retired, yet
    FIG-transition-bridge-credit-cost kept 'about $115 billion at peak' as its display for thirteen months: the retired
    scan reads live text, never the register. This check matches each retired pattern against every figure's displays,
    but only where the figure is about the retired value's subject (the label's first word, e.g. 'bridge'), so the
    legitimate $115B obligations target is not confused with the bridge peak.
    """
    import json as _j, os as _o, re as _r, sys as _s
    _s.path.insert(0, _o.path.join(package_root, "tools"))
    try:
        from scan_retired_values import RETIRED
        E = _j.load(open(_o.path.join(package_root, "00_GUI_Files", "figures_registry.json"), encoding="utf-8"))["entries"]
    except Exception:
        return []
    out = []
    for label, pat, repl in RETIRED:
        subj = _r.sub(r"[^a-z ]", " ", label.split(":", 1)[-1].lower()).split()
        subj = [w for w in subj if len(w) > 3][:1]
        if not subj:
            continue
        for e in E:
            about = (e.get("id", "") + " " + e.get("name", "")).lower()
            if subj[0] not in about:
                continue
            for x in e.get("narrative_examples", []) or []:
                if _r.search(pat, str(x.get("display", ""))):
                    out.append(("MIN", "RETIRED-AS-CANONICAL", "00_GUI_Files/figures_registry.json",
                                f"{e['id']} displays '{x.get('display')}', which the retired-values list retires ('{label}' -> '{repl}')"))
    return out


def check_private_draft_pins(package_root="."):
    """v3.8.580 (PRIVATE-DRAFT-PIN, MIN): private drafts are never altered without the author's explicit instruction.
    Every catalog private:true document is pinned by MD5 in 09_Meta_Tracking/private_draft_pins.json; a change, a missing
    document or an unpinned private document fails. Re-pin only with tools/pin_private_drafts.py --repin <path>
    --instruction <ledger number>. Added after the Stewart draft's July-pinned hash was found changed with no record."""
    import os as _o, sys as _s
    _s.path.insert(0, _o.path.join(package_root, "tools"))
    try:
        import importlib, pin_private_drafts as P
        importlib.reload(P)
        return [("MIN", "PRIVATE-DRAFT-PIN", path, why) for path, why in P.check()]
    except Exception as ex:
        return [("MIN", "PRIVATE-DRAFT-PIN", "tools/pin_private_drafts.py", f"pin check could not run: {ex}")]


def check_superseded_source(package_root="."):
    """v3.8.564 (SUPERSEDED-SOURCE, MIN): a registered figure or assumption must not rest on a superseded source.

    The bridge credit's figure was sourced to 04_Refundable_Transition_Bridge_Credit_Cost_Model.xlsx for thirteen months
    after v3.8.357 found that workbook superseded by the Combined Reform Model; the release restated a document and
    changed no figure, so the register, the robustness model and the consistency check kept the retired profile. The
    catalog now marks superseded documents ('SUPERSEDED' at the start of the description); this check fails any
    register entry whose source names one.
    """
    import json as _j, os as _o
    root = package_root
    try:
        cat = _j.load(open(_o.path.join(root, "00_GUI_Files", "platform_catalog.json"), encoding="utf-8"))
    except Exception:
        return []
    sup = {_o.path.basename(d.get("path", "")) for d in cat.get("documents", [])
           if str(d.get("description", "")).lstrip().upper().startswith("SUPERSEDED")}
    out = []
    for reg, key in (("figures_registry.json", "entries"), ("assumptions_registry.json", None)):
        try:
            R = _j.load(open(_o.path.join(root, "00_GUI_Files", reg), encoding="utf-8"))
        except Exception:
            continue
        rows = R.get("entries") or R.get("assumptions") or []
        for e in rows:
            src = _j.dumps(e.get("source", "")) + _j.dumps(e.get("sources", ""))
            hit = [b for b in sup if b and b in src]
            if hit:
                out.append(("MIN", "SUPERSEDED-SOURCE", reg,
                            f"{e.get('id')} is sourced to {hit[0]}, which the catalog marks SUPERSEDED. Re-source it to "
                            f"the model the platform runs, update its value, and record the change in its notes."))
    return out


def check_calculator_parameters(package_root="."):
    """v3.8.254 (CALCULATOR-PARAM-DRIFT, MIN): the citizen-facing calculators carry their
    own copies of the platform's contribution rates, and until now NOTHING CHECKED THEM.

    A reader can be shown a rate the platform no longer states and no gate would fire.
    This compares every `const RATE_* = value` in each declared calculator against
    00_GUI_Files/calculator_parameters.json, in both directions: a value that differs is
    a finding, AND a constant present in the calculator but absent from the manifest is a
    finding, so a new parameter cannot enter a citizen-facing tool undeclared. It also
    enforces the arithmetic the manifest declares: employer + employee == combined.
    """
    import glob as _g
    findings = []
    mf = os.path.join(package_root, "00_GUI_Files", "calculator_parameters.json")
    if not os.path.exists(mf):
        return [("MIN", "CALCULATOR-PARAM-DRIFT", "calculator_parameters.json",
                 "the calculator parameter manifest is missing; calculator rates are unchecked")]
    try:
        man = json.load(open(mf, encoding="utf-8"))
    except Exception as e:
        return [("MIN", "CALCULATOR-PARAM-DRIFT", "calculator_parameters.json", f"unreadable: {e}")]
    for rel, params in (man.get("calculators") or {}).items():
        path = os.path.join(package_root, rel)
        if not os.path.exists(path):
            findings.append(("MIN", "CALCULATOR-PARAM-DRIFT", rel,
                             "declared calculator is not in the package"))
            continue
        html = open(path, encoding="utf-8", errors="ignore").read()
        found = dict(re.findall(r"const\s+(RATE_[A-Z_]+)\s*=\s*([0-9.]+)", html))
        for name, want in params.items():
            if name not in found:
                findings.append(("MIN", "CALCULATOR-PARAM-DRIFT", rel,
                    f"{name} is declared in the manifest but no longer present in the calculator"))
                continue
            got = float(found[name])
            if abs(got - float(want)) > 1e-9:
                findings.append(("MIN", "CALCULATOR-PARAM-DRIFT", rel,
                    f"{name}: calculator has {got}, the platform's declared value is {want}"))
        for name in found:
            if name not in params:
                findings.append(("MIN", "CALCULATOR-PARAM-DRIFT", rel,
                    f"{name} is in the calculator but UNDECLARED in the manifest; a "
                    f"citizen-facing parameter with no recorded source"))
        # employer + employee == combined, per pillar
        stems = sorted({n[len("RATE_"):].rsplit("_", 1)[0] for n in params
                        if n.endswith(("_EMPLOYER", "_EMPLOYEE", "_COMBINED"))})
        for stem in stems:
            er, ee, cb = (params.get(f"RATE_{stem}_EMPLOYER"), params.get(f"RATE_{stem}_EMPLOYEE"),
                          params.get(f"RATE_{stem}_COMBINED"))
            if None in (er, ee, cb):
                continue
            if abs((er + ee) - cb) > 1e-9:
                findings.append(("MIN", "CALCULATOR-PARAM-DRIFT", rel,
                    f"{stem}: employer {er} + employee {ee} = {er + ee}, but combined is {cb}"))
    return findings


def check_historical_exemption(package_root="."):
    """v3.8.251 (HISTORICAL-EXEMPTION, MIN): a whole-document audit exemption must be
    DECLARED and VISIBLE.

    An exemption that is only configured is a silent one. Every whole-document exemption
    must name a reason in the whitelist AND the document must carry a banner telling a
    reader it is a historical record, so the exemption is discoverable from the document
    rather than only from the tooling.
    """
    import glob as _glob
    findings = []
    wl = os.path.join(package_root, "audit_whitelist.txt")
    if not os.path.exists(wl):
        return findings
    for e in [x for x in parse_whitelist(wl) if x.get("scope") == "whole-document"]:
        fname = e["file"]
        if not e.get("reason"):
            findings.append(("MIN", "HISTORICAL-EXEMPTION", fname,
                "whole-document audit exemption with no REASON recorded"))
        hits = _glob.glob(os.path.join(package_root, "**", fname), recursive=True)
        if not hits:
            findings.append(("MIN", "HISTORICAL-EXEMPTION", fname,
                "whole-document exemption names a file that is not in the package"))
            continue
        try:
            from docx import Document as _Doc
            head = " ".join(p.text for p in _Doc(hits[0]).paragraphs[:40]).upper()
        except Exception as ex:
            findings.append(("MIN", "HISTORICAL-EXEMPTION", fname,
                f"could not read the document to verify its banner: {ex}"))
            continue
        if "HISTORICAL RECORD" not in head:
            findings.append(("MIN", "HISTORICAL-EXEMPTION", fname,
                "exempted from the audit's paragraph sweeps but carries no HISTORICAL "
                "RECORD banner in its opening paragraphs. A reader must be able to see "
                "the exemption from the document, not only from audit_whitelist.txt."))
    return findings


def check_comparison_method_recorded(package_root="."):
    """v3.8.228 (COMPARISON-METHOD, MIN): a figure carrying a P2 delta must name the
    route and method that produced it. A delta with no method is a number with no
    derivation, which is the failure class this programme exists to remove -- the
    same shape as check_substantiation_coverage's rule that `compared` without a
    delta_pct is a claim with no evidence. Also catches the reverse: a comparison
    record claiming a route that produced no delta and gave no reason."""
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fp):
        return findings
    try:
        entries = json.load(open(fp, encoding="utf-8"))["entries"]
    except Exception as e:
        return [("MIN", "COMPARISON-METHOD", "figures_registry.json", f"unreadable: {e}")]
    for e in entries:
        fid = e.get("id", "?")
        c = e.get("comparison") or {}
        if e.get("delta_pct") is not None:
            if not c.get("route") or not c.get("method"):
                findings.append(("MIN", "COMPARISON-METHOD", f"figures_registry.json:{fid}",
                    "carries a delta_pct with no recorded comparison route/method. A delta "
                    "with no method is a number with no derivation."))
        elif c and not (c.get("notes") or "").strip():
            findings.append(("MIN", "COMPARISON-METHOD", f"figures_registry.json:{fid}",
                f"comparison recorded on route {c.get('route')!r} with no delta and no "
                f"reason. Why a figure could not be compared is itself the finding."))
    return findings


def check_substantiation_coverage(package_root="."):
    """v3.8.85 (SUBSTANTIATION-COVERAGE): report where the substantiation programme
    actually stands, and enforce the fields each stage requires.

    SUBSTANTIATION_PROGRAM.md deliberately records no phase marker, because a marker
    that can rot reads as authority; the same reasoning that keeps a version number
    out of the working-rules file. The phase is DERIVED from this distribution
    instead, so the distribution has to be printed somewhere a person will see it.

    OBS for the census. MIN where a stage's required field is missing, because a
    figure claiming `compared` with no delta recorded is a claim with no evidence,
    which is the failure class this whole programme exists to remove.
    """
    findings = []
    fr_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fr_path):
        return findings
    with open(fr_path, encoding="utf-8") as f:
        fr = json.load(f)
    entries = fr.get("entries", [])
    valid = set(fr.get("substantiation_values") or [])
    counts = {}
    for e in entries:
        s = e.get("substantiation")
        counts[s] = counts.get(s, 0) + 1
        fid = e.get("id", "?")
        if s is None:
            findings.append(("MIN", "SUBSTANTIATION-COVERAGE", f"figures_registry.json:{fid}",
                             "no substantiation value. Every figure carries one; the "
                             "default is 'unexamined'."))
            continue
        if valid and s not in valid:
            findings.append(("MIN", "SUBSTANTIATION-COVERAGE", f"figures_registry.json:{fid}",
                             f"substantiation {s!r} is not in substantiation_values."))
            continue
        if s in ("compared", "reconciled") and e.get("delta_pct") is None:
            findings.append(("MIN", "SUBSTANTIATION-COVERAGE", f"figures_registry.json:{fid}",
                             f"substantiation is {s!r} but no delta_pct is recorded. A "
                             f"comparison with no delta is not a comparison."))
        if s == "reconciled" and not e.get("disposition"):
            findings.append(("MIN", "SUBSTANTIATION-COVERAGE", f"figures_registry.json:{fid}",
                             "substantiation is 'reconciled' but no disposition is "
                             "recorded (adopt / retain_disclosed / retire)."))
        if s == "not_applicable" and not e.get("substantiation_note"):
            findings.append(("MIN", "SUBSTANTIATION-COVERAGE", f"figures_registry.json:{fid}",
                             "substantiation is 'not_applicable' but no reason is given "
                             "in substantiation_note."))

    census = ", ".join(f"{k}={v}" for k, v in sorted(counts.items(), key=lambda kv: str(kv[0])))
    findings.append(("OBS", "SUBSTANTIATION-COVERAGE", "00_GUI_Files/figures_registry.json",
                     f"substantiation census of {len(entries)} figures: {census}. "
                     f"P1 is live while anything reads unexamined or sourced; P2 while "
                     f"anything reproducible is not yet compared; P3 while any compared "
                     f"figure lacks a disposition. See SUBSTANTIATION_PROGRAM.md."))
    return findings


def check_substantiation_monotonic(package_root="."):
    """v3.8.85 (SUBSTANTIATION-REGRESSION, SIG): substantiation moves forward, or it
    records why it moved back.

    A pass looks complete when nothing is left at an early stage. That creates a
    quiet incentive to move an entry backwards out of scope rather than finish it,
    and a backwards move leaves no trace unless something looks for one.

    Compares the shipped registry against the previous release's copy under
    _internal/ if one is present. When no baseline exists the check is a no-op
    rather than a failure, because absence of history is not evidence of
    regression.
    """
    findings = []
    ORDER = {"unexamined": 0, "sourced": 1, "reproducible": 2, "unreconstructible": 2,
             "compared": 3, "reconciled": 4, "not_applicable": 4}
    cur_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    base_path = os.path.join(package_root, "_internal", "figures_registry.baseline.json")
    if not (os.path.exists(cur_path) and os.path.exists(base_path)):
        return findings
    with open(cur_path, encoding="utf-8") as f:
        cur = {e["id"]: e for e in json.load(f).get("entries", []) if e.get("id")}
    with open(base_path, encoding="utf-8") as f:
        base = {e["id"]: e for e in json.load(f).get("entries", []) if e.get("id")}
    for fid, e in cur.items():
        if fid not in base:
            continue
        now = ORDER.get(e.get("substantiation"), 0)
        was = ORDER.get(base[fid].get("substantiation"), 0)
        if now < was and "REGRESSION" not in str(e.get("substantiation_note") or "").upper():
            findings.append((
                "SIG", "SUBSTANTIATION-REGRESSION", f"figures_registry.json:{fid}",
                f"substantiation moved backwards, {base[fid].get('substantiation')!r} -> "
                f"{e.get('substantiation')!r}, with no reason recorded. A backwards move "
                f"is allowed; an unexplained one is not. Put REGRESSION and the reason in "
                f"substantiation_note."))
    return findings


def check_phase_claim(package_root="."):
    """v3.8.85 (PHASE-CLAIM-UNSOURCED, MIN): a count or a completion claim in a
    shipped document must carry the command that produced it.

    THE FAILURE THIS CLOSES. SOURCE_RETRIEVAL_PLAN.md still opens with "23 external
    sources. Three are archived" after five more were archived, because the sentence
    was true when written and nothing re-checks prose. The same class produced a
    paused-build marker that survived twenty-five active releases.

    The rule is the one already applied to conversation: a number with no command
    beside it came from memory and should be distrusted on sight. This makes it
    apply to files, where it matters more, because a file is read by people who were
    not in the conversation.

    Scope is deliberately narrow: only files that opt in via a
    `<!-- phase-claims-checked -->` marker are scanned, so this does not fire across
    every prose document in the package on the day it lands. Files are added to the
    scanned set as they are brought into compliance.
    """
    findings = []
    MARK = "<!-- phase-claims-checked -->"
    CLAIM_RE = re.compile(
        r"^(?![>|].*)(?P<line>.*\b(\d+)\s+(?:of\s+\d+\s+)?"
        r"(sources?|figures?|entries|items|documents?|workbooks?|assumptions?)\b.*)$",
        re.M | re.I)
    for root, _dirs, files in os.walk(package_root):
        if any(seg in root for seg in ("/_web_html", "/node_modules", "/.git", "/_downloads")):
            continue
        for fn in files:
            if not fn.endswith(".md"):
                continue
            path = os.path.join(root, fn)
            try:
                with open(path, encoding="utf-8") as f:
                    text = f.read()
            except Exception:
                continue
            if MARK not in text:
                continue
            # A fenced block anywhere in the file counts as the command evidence for
            # claims in the section that follows it; we check per-section, split on H2.
            for section in re.split(r"^## ", text, flags=re.M):
                if "```" in section:
                    continue
                for m in CLAIM_RE.finditer(section):
                    line = m.group("line").strip()
                    if len(line) > 200:
                        continue
                    # A VERSION NUMBER IS NOT A COUNT. "v3.8.84 assumption basis"
                    # parses as "84 assumptions" under a rule that only looks for
                    # a digit next to a noun. Same failure shape as the loose
                    # token matching that produced a wrong archived-source count
                    # at v3.8.58: matching on adjacency rather than on meaning.
                    if re.search(r"v?\d+\.\d+\.$", section[:m.start(2)]):
                        continue
                    rel = os.path.relpath(path, package_root)
                    findings.append((
                        "MIN", "PHASE-CLAIM-UNSOURCED", rel,
                        f"count claim with no command in the same section: {line[:120]!r}. "
                        f"Add the command that produced it, in a fenced block, or move the "
                        f"claim to a section that has one."))
    return findings


def check_p1_no_adoption(package_root="."):
    """v3.8.85 (P1-ADOPTION, MIN): no figure value changes while the sourcing pass is
    still running, unless the release calls it an error correction.

    SUBSTANTIATION_PROGRAM.md sets the order: source everything, compare the set,
    then decide. Adopting one recomputed value early destroys the baseline the
    comparison needs and decides without knowing whether that figure is typical.
    One sourced lever has moved 39 percent so far, which is a sample of one.

    The narrow exception is a demonstrable error rather than a disagreement: a
    transcription slip, a wrong unit, a wrong vintage. The test is whether anyone
    would defend the old value having seen the evidence. To use it, the release
    narrative for the current version must contain the words "error correction".

    Compares against the previous release's registry under _internal/ when present,
    same as the regression check. No baseline means no-op.
    """
    findings = []
    cur_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    base_path = os.path.join(package_root, "_internal", "figures_registry.baseline.json")
    ver_path = os.path.join(package_root, "version.json")
    log_path = os.path.join(package_root, "VERSIONLOG.txt")
    if not all(os.path.exists(p) for p in (cur_path, base_path, ver_path, log_path)):
        return findings
    with open(cur_path, encoding="utf-8") as f:
        curdoc = json.load(f)
    cur = {e["id"]: e for e in curdoc.get("entries", []) if e.get("id")}
    with open(base_path, encoding="utf-8") as f:
        base = {e["id"]: e for e in json.load(f).get("entries", []) if e.get("id")}

    p1_live = any(e.get("substantiation") in ("unexamined", "sourced") for e in cur.values())
    if not p1_live:
        return findings

    with open(ver_path, encoding="utf-8") as f:
        version = json.load(f).get("platform_version", "")
    with open(log_path, encoding="utf-8") as f:
        head = f.read(20000)
    m = re.search(r"^VERSION\s+" + re.escape(version) + r"\b(.*?)(?=^VERSION\s)",
                  head, re.M | re.S)
    narrative = (m.group(1) if m else "").lower()
    excused = "error correction" in narrative

    for fid, e in cur.items():
        if fid not in base:
            continue
        a, b = base[fid].get("canonical"), e.get("canonical")
        if a != b and not excused:
            findings.append((
                "MIN", "P1-ADOPTION", f"figures_registry.json:{fid}",
                f"canonical value changed while the sourcing pass is still running "
                f"({a} -> {b}). Under SUBSTANTIATION_PROGRAM.md, adoption is a P3 act. "
                f"If this is a demonstrable error rather than a disagreement, say "
                f"'error correction' in the release narrative and it will pass."))
    return findings


def check_uncertainty_propagation(package_root="."):
    """v3.8.86 (UNCERTAINTY-PROPAGATION): declared uncertainty must actually propagate.

    THE GAP THIS CLOSES. The platform declared uncertainty everywhere and
    propagated it nowhere. 15 range figures, 4 scenario figures, a monte_carlo_role
    on every assumption and a documented vocabulary for those roles, and not one
    line of code consumed any of it. FIG-net-new-spending shipped as the scalar 3.0
    while five of the nine components reaching it carry declared low-high bands. A
    reader was told the inputs were uncertain and handed a point estimate.

    Two conditions, reported separately because they need different fixes.

      1. RESULTS STALE OR ABSENT. tools/propagate_uncertainty.py --verify recomputes
         from the registry and compares against propagated_uncertainty. MIN, because
         a recorded band that no longer follows from the registry is a claim with no
         derivation, which is the failure class the whole programme exists to remove.

      2. COVERAGE. How many propagable-role assumptions carry a usable distribution.
         OBS. This number is EXPECTED TO BE LOW and is not a defect to fix by
         inventing distributions: 16 of 17 are pending_external_calibration under the
         no-fabrication rule, and manufacturing a shape for them would buy a
         spuriously precise band. It is reported so the gap stays visible while it
         waits for the calibration that closes it honestly.

    The check does NOT verify that a canonical value sits inside its propagated
    band. It sometimes will not, legitimately: a canonical pinned to one scenario is
    a stated choice, not an error, and FIG-fund-coverage-share is exactly that.
    Turning that into a finding would push toward widening bands until they cover
    whatever was published, which is tuning to the target with extra steps.
    """
    import subprocess as _sp
    findings = []
    tool = os.path.join(package_root, "tools", "propagate_uncertainty.py")
    fr_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not (os.path.exists(tool) and os.path.exists(fr_path)):
        return findings
    with open(fr_path, encoding="utf-8") as f:
        fr = json.load(f)
    rec = fr.get("propagated_uncertainty")
    if not rec:
        findings.append(("MIN", "UNCERTAINTY-PROPAGATION", "00_GUI_Files/figures_registry.json",
                         "no propagated_uncertainty recorded, but the tool exists. Run "
                         "tools/propagate_uncertainty.py --write."))
        return findings

    cmd = [sys.executable, tool, "--verify",
           "--seed", str(rec.get("seed", 20260828)),
           "--draws", str(rec.get("draws", 20000)),
           "--shape", str(rec.get("shape", "uniform"))]
    if rec.get("honor_scenario_pins"):
        cmd.append("--honor-scenario-pins")
    try:
        r = _sp.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=900)
    except Exception as e:
        findings.append(("NOTE", "UNCERTAINTY-PROPAGATION", "tools/propagate_uncertainty.py",
                         f"could not run ({type(e).__name__}); NOT verified"))
        return findings
    if r.returncode != 0:
        detail = " | ".join(l.strip() for l in (r.stdout or "").splitlines()
                            if "[verify]" in l or "DRIFT" in l)[:400]
        findings.append(("MIN", "UNCERTAINTY-PROPAGATION", "00_GUI_Files/figures_registry.json",
                         f"recorded propagated results no longer follow from the registry: "
                         f"{detail}"))

    a_path = os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json")
    if os.path.exists(a_path):
        with open(a_path, encoding="utf-8") as f:
            a = json.load(f)
        roles = [x for x in a.get("entries", [])
                 if x.get("monte_carlo_role") in ("driver", "sensitivity")]
        def _has(x):
            d = x.get("distribution")
            return isinstance(d, dict) and d.get("type") not in (None, "pending")
        cov = [x for x in roles if _has(x)]
        n_res = len(rec.get("results", {}))
        findings.append((
            "OBS", "UNCERTAINTY-PROPAGATION", "00_GUI_Files/assumptions_registry.json",
            f"{len(cov)} of {len(roles)} propagable-role assumption(s) carry a usable "
            f"distribution; {len(roles) - len(cov)} are pending external calibration and "
            f"are deliberately NOT invented. {n_res} figure(s) currently carry a "
            f"propagated band. Coverage rises when calibration lands, not before."))
    return findings


def check_disclosure_freshness(package_root="."):
    """v3.8.87 (DISCLOSURE-STALE, MIN): the public-facing disclosure files must not
    contradict the generated counts, and their links must resolve.

    THE FAILURE THIS CLOSES. 00_Deployment_Bundle/disclosure.md is the page a
    skeptical reader opens first. At v3.8.86 it carried five hand-maintained counts
    and FOUR WERE WRONG: "nine pillars" against a manifest 12 with housing, climate
    and immigration missing from its own list; "eight layers and sixteen check
    operations" against 74 check functions; "more than fifty consecutive iterations"
    against 1,048 VERSION entries; a "four-phase iteration cycle" against the
    eight-step cycle PROJECT_SKILL.md documents.

    Worse than the counts, it carried THREE DEAD LINKS and FOUR DANGLING
    IDENTIFIERS. It linked to /05_Open_Issues_Registry and
    /05_Iterative_Hardening_Process_Documentation, neither of which is a served
    path (both documents live under _web_html/09_Meta_Tracking/), and to /bio,
    which does not exist. It named RESEARCH-8, PERSONA-SIG-3, PERSONA-SIG-5 and
    ITEM79-Q3 as open items; none resolves to an entry in the registry.

    Every one of those was true when written. That is the whole problem: prose
    counts and hand-written links rot silently while the thing they describe moves,
    and nothing re-reads them. The rest of the package solved this by generating
    counts from manifest.json; this file was never brought into that discipline.

    Three conditions:

      1. COUNT DRIFT. A pillar, document or tracked-issue count stated in prose,
         in digits or in words, that disagrees with manifest.json.
      2. DEAD LINK. A wethepeopleplatform.com link that resolves to neither a
         <loc> in sitemap.xml nor a file present in the package.
      3. DANGLING IDENTIFIER. A RESEARCH-n / PERSONA-SIG-n / PROC-n / ARC-n style
         id cited in a disclosure file that does not appear in the Tracked Issues
         Registry. The correct fix is almost always to delete the list and link
         the registry, which is the one place the ids are maintained.

    MIN severity. These are public-facing accuracy defects on the artifact whose
    entire purpose is accuracy about the platform, but they mislead a reader rather
    than corrupting a figure.

    Scope is 00_Deployment_Bundle/*.md. Those files are the outsider-facing
    disclosure set and are small enough to hold to this standard; widening it to
    every prose document in the package is a separate decision.
    """
    findings = []
    bundle = os.path.join(package_root, "00_Deployment_Bundle")
    manifest_path = os.path.join(package_root, "manifest.json")
    if not (os.path.isdir(bundle) and os.path.exists(manifest_path)):
        return findings
    with open(manifest_path, encoding="utf-8") as f:
        totals = (json.load(f).get("totals") or {})
    ti = totals.get("tracked_issues") or {}

    WORDS = {
        1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven",
        8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen",
        14: "fourteen", 15: "fifteen", 16: "sixteen", 17: "seventeen",
        18: "eighteen", 19: "nineteen", 20: "twenty",
    }
    WORD_VAL = {v: k for k, v in WORDS.items()}

    # (noun the count attaches to, expected value from manifest)
    SUBJECTS = [
        (r"pillars?", totals.get("pillars")),
        (r"public documents?", totals.get("publicDocuments")),
        (r"tracked issues?", ti.get("total")),
    ]

    sitemap = ""
    sm_path = os.path.join(package_root, "sitemap.xml")
    if os.path.exists(sm_path):
        with open(sm_path, encoding="utf-8") as f:
            sitemap = f.read()

    registry_text = ""
    reg_path = os.path.join(package_root, "09_Meta_Tracking", "09_Open_Issues_Registry.docx")
    if os.path.exists(reg_path):
        try:
            import docx as _docx
            registry_text = "\n".join(p.text for p in _docx.Document(reg_path).paragraphs)
        except Exception:
            registry_text = ""

    for fn in sorted(os.listdir(bundle)):
        if not fn.endswith(".md"):
            continue
        rel = f"00_Deployment_Bundle/{fn}"
        with open(os.path.join(bundle, fn), encoding="utf-8") as f:
            text = f.read()

        # --- 1. count drift -------------------------------------------------
        for noun, expected in SUBJECTS:
            if expected is None:
                continue
            pat = re.compile(r"\b([a-z]+|\d+)\s+(?:" + noun + r")\b", re.I)
            for m in pat.finditer(text):
                tok = m.group(1).lower()
                val = int(tok) if tok.isdigit() else WORD_VAL.get(tok)
                if val is None:
                    continue
                if val != expected:
                    findings.append((
                        "MIN", "DISCLOSURE-STALE", rel,
                        f"states {m.group(0)!r} but manifest.json says {expected}. "
                        f"Public-facing counts must match the generated manifest, or "
                        f"be replaced by a pointer to it."))

        # --- 2. dead links --------------------------------------------------
        for path in set(re.findall(r"https://wethepeopleplatform\.com/([^\s\)\]\"'>]*)", text)):
            path = path.rstrip(".,;")
            if not path:
                continue
            in_sitemap = f"wethepeopleplatform.com/{path}<" in sitemap
            on_disk = os.path.exists(os.path.join(package_root, path))
            if not (in_sitemap or on_disk):
                findings.append((
                    "MIN", "DISCLOSURE-STALE", rel,
                    f"links to /{path}, which is neither a <loc> in sitemap.xml nor a "
                    f"file in the package. A dead link on the disclosure page is the "
                    f"cheapest possible thing for a hostile reader to find."))

        # --- 2b. relative links -------------------------------------------
        # RESOLUTION RULE, and it has to be stated because the bundle genuinely
        # uses both roots IN THE SAME FILE. README_PUBLIC.md links
        # ./citation.bib, which sits beside it in 00_Deployment_Bundle, and
        # ./05_Analytical_Framing/... which is relative to the PACKAGE ROOT.
        # Neither is wrong: the bundle is read both as a folder handed to
        # someone and as part of the extracted package.
        #
        # So a relative link is valid if it resolves under EITHER root, and a
        # finding is raised only when it resolves under neither. That is
        # deliberately permissive. A stricter rule would have to pick a root
        # and would then report a large number of working links as broken,
        # which is how a check earns its way into being switched off.
        for m in re.finditer(r"\]\((\.{0,2}/?[^)#\s]+)\)", text):
            tgt = m.group(1)
            if tgt.startswith(("http://", "https://", "mailto:", "#")):
                continue
            from_file = os.path.normpath(
                os.path.join(os.path.dirname(os.path.join(bundle, fn)), tgt))
            from_root = os.path.normpath(
                os.path.join(package_root, tgt.lstrip("./")))
            if not (os.path.exists(from_file) or os.path.exists(from_root)):
                findings.append((
                    "MIN", "DISCLOSURE-STALE", rel,
                    f"relative link to {tgt!r} resolves to no file, either beside "
                    f"{fn} or from the package root. This is the class that sent "
                    f"academic readers to ./05_Analytical_Framing/ for a document "
                    f"filed under 09_Meta_Tracking/, and it was found by accident."))

        # --- 3. dangling tracked-issue identifiers --------------------------
        if registry_text:
            for ident in sorted(set(re.findall(
                    r"\b(?:RESEARCH|PERSONA-SIG|PERSONA-MIN|PROC|PROCESS|SCOPE|CON|ARC|GUARD)-\d+\b",
                    text))):
                if not re.search(r"\b" + re.escape(ident) + r"\b", registry_text):
                    findings.append((
                        "MIN", "DISCLOSURE-STALE", rel,
                        f"cites {ident}, which does not appear in the Tracked Issues "
                        f"Registry. Maintaining the id list in two places is what made "
                        f"it drift; link the registry instead of reproducing it."))
    return findings


def check_absence_claim(package_root="."):
    """v3.8.102 (ABSENCE-CLAIM-UNVERIFIED, MIN): an absence claim in a shipped
    document must carry the preflight that established it.

    check_phase_claim already requires a command beside a COUNT. This applies the
    same rule to the other class of claim that is cheap to make and expensive to
    be wrong about: an assertion that something does NOT exist, HAS NOT been
    done, or appears NOWHERE.

    THE FAILURE THIS CLOSES. A session asserted that model-input provenance had
    never been examined by the platform. MODEL_INPUT_INVARIANT.md had governed it
    since v3.8.49, the worked example in that document was the exact case being
    'discovered', and it was tracked as RESEARCH-35. One
    `verify_finding.py history-claim` refuted it in seconds. The same session had
    recommended running that tool two responses earlier and did not.

    FINDING_TRACE_PROTOCOL.md names the class: searches fail on their definition
    of what to look at, not on their logic. AUDIT_SCOPE_AND_LIMITS.md item 7 says
    an audit cannot see omission. Neither could make a claim of absence cost
    anything to assert.

    Scope is opt-in via the same `<!-- phase-claims-checked -->` marker, because
    a file already accepting the count rule is a file whose author accepts this
    one. A claim passes when a fenced command block appears in the same section:
    the same evidence standard, applied to a different sentence shape.
    """
    findings = []
    MARK = "<!-- phase-claims-checked -->"
    ABSENCE_RE = re.compile(
        r"^(?![>|].*)(?P<line>.*\b("
        r"do(?:es)? not exist|has never|have never|never been|"
        r"no surviving|appears? nowhere|found nowhere|exists? nowhere|"
        r"is not recorded anywhere|recorded nowhere|documented nowhere|"
        r"itemised nowhere|itemized nowhere|nothing (?:in|addresses|covers)"
        r")\b.*)$", re.M | re.I)
    for root, _dirs, files in os.walk(package_root):
        if any(seg in root for seg in ("/_web_html", "/node_modules", "/.git", "/_downloads")):
            continue
        for fn in files:
            if not fn.endswith(".md"):
                continue
            path = os.path.join(root, fn)
            try:
                with open(path, encoding="utf-8") as f:
                    text = f.read()
            except Exception:
                continue
            if MARK not in text:
                continue
            for section in re.split(r"^## ", text, flags=re.M):
                if "```" in section:
                    continue
                for m in ABSENCE_RE.finditer(section):
                    line = " ".join(m.group("line").split())
                    if len(line) > 240:
                        continue
                    rel = os.path.relpath(path, package_root)
                    findings.append((
                        "MIN", "ABSENCE-CLAIM-UNVERIFIED", rel,
                        f"absence claim with no preflight in the same section: "
                        f"{line[:130]!r}. Run tools/verify_finding.py "
                        f"(absence-claim or history-claim) and quote it, or move the "
                        f"claim to a section that carries one."))
    return findings


def check_unwired_tools(package_root="."):
    """v3.8.104 (TOOL-UNWIRED, MIN): a tool that should run must be reachable
    from this file, or it does not exist in practice.

    THE MEASUREMENT THAT PRODUCED THIS. At v3.8.103 the package held 48
    non-legacy tools. TWELVE were invoked by the audit. THIRTY-SIX WERE NOT,
    including `exhaustive_audit.py` (a second audit engine that "cross-checks
    every value in a set of files against the figures registry... detects
    typo/near-miss variants of load-bearing figures, re-derives arithmetic where
    detectable"), `trace_finding.py` (the executable half of
    FINDING_TRACE_PROTOCOL.md), three test-suite runners, and three files whose
    names begin with `check_`.

    WHY THAT MATTERS MORE THAN A TIDINESS COMPLAINT. The audit is the only thing
    that runs on every release. Anything outside it depends on a session
    remembering it, and a session that has never read the file cannot remember
    it. This is not the "unimagined failure" of AUDIT_SCOPE_AND_LIMITS.md item 5
    — it is worse, because the work was imagined, built, and then left
    unconnected. `$14,570` against a published `$14,580` is exactly the near-miss
    variant `exhaustive_audit.py` was written to detect, and it went unnoticed
    for eighteen clean releases while that tool sat unrun.

    Scope: tools whose names promise they verify something — check_*, verify_*,
    test_*, run_*, and anything containing `audit`. Builders and one-shot
    generators are out of scope: they run when a person builds. Legacy
    `_v3_7_*` one-shots are excluded wholesale.

    An entry may be declared in EXCLUDED with a REASON. A bare exclusion is not
    accepted; the reason is the point, because "we decided not to run this" and
    "nobody ever wired this" are different states and only one of them is a
    decision.
    """
    findings = []
    tools_dir = os.path.join(package_root, "tools")
    audit_path = os.path.join(package_root, "audit_script.py")
    if not (os.path.isdir(tools_dir) and os.path.exists(audit_path)):
        return findings
    with open(audit_path, encoding="utf-8") as f:
        audit_src = f.read()

    # Declared exclusions. The reason is required and is the whole value of the
    # list: it records a DECISION rather than an oversight.
    EXCLUDED = {
        "run_all_self_tests.py": "invokes --self-test on build helpers; run at ship time by the build chain, not per-audit (slow)",
        "run_integration_tests.py": "end-to-end suite; run before a deploy, not on every audit iteration",
        "smoke_test.py": "pre-deploy smoke; belongs to the deploy path",
        "test_rocker_egg.py": "easter-egg regression test; cosmetic scope",
        "test_sender_request.py": "outreach-form test; requires network, cannot run in the audit sandbox",
        "check_color_accessibility.py": "contrast simulation; slow and stable, run on CSS change",
        "check_text_spacing.py": "typography scan; run on CSS change",
        "check_reflow.py": "WCAG reflow check; needs a rendering pass, run on CSS change",
        "check_data_recency.py": "ship-time advisory invoked by bump_version.py, not per-audit",
        "measure_architecture_from_persons.py": "the extract now SHIPS in _data_archive/2026-09-29_ipums_cps_asec2024 with its codebook and required citation; this tool reads it on demand rather than every build, since assembling 131.9 million returns takes minutes. v3.8.438 wrongly said the licence forbids redistribution -- it forbids CHARGING for it",
        "sweep_wage_floor_parameters.py": "needs the sealed CPS extract, which the author fetches and the package does not ship; it computes the cost and above-threshold count for any exemption design when that data is present",
        "estimate_wage_floor_cost.py": "needs the sealed CPS extract, which the author fetches and the package does not ship; it derives the exemption cost household by household when that data is present",
        "recalc_fund_scenarios.py": "six headless LibreOffice recalculations take about a minute; the fast exact check at 6 percent lives in verify_internal_consistency.py and this is the on-demand tool for when the model changes",
        "inspect_wealth_base_sensitivity.py": "needs the sealed SCF extract, which the author fetches and the package does not ship; it reports what the wealth base estimate rests on rather than producing a number, so it is run when a decision depends on it",
        "inventory_untokenised_figures.py": "a triage aid for deferred item O, read when a document is being reviewed; it lists money literals and the figures whose values they match, and deliberately rewrites nothing because a value match is not a mandate",
        "check_wealth_tax_base.py": "needs the sealed SCF extract, which is fetched by the author and is not part of the shipped package; it measures a floor on the wealth tax base when that data is present",
        "test_guard_efficacy.py": "RECURSIVE: it injects a defect and runs the FULL audit to prove each guard fires. Cannot run inside the audit it invokes; belongs to the ship path",
        "verify_finding.py": "INTERACTIVE PREFLIGHT. Takes a human's claim as an argument; there is no claim to test on an unattended run",
        "trace_finding.py": "INTERACTIVE. Same reason: it searches for a topic a human names",
    }

    PROMISES_VERIFICATION = ("check_", "verify_", "test_", "run_")
    for fn in sorted(os.listdir(tools_dir)):
        if not fn.endswith(".py"):
            continue
        if fn.startswith("_"):          # legacy one-shots and templates
            continue
        promises = fn.startswith(PROMISES_VERIFICATION) or "audit" in fn
        if not promises:
            continue
        # MENTIONED IS NOT INVOKED. The first version of this check tested for the
        # filename anywhere in audit_script.py, and its OWN DOCSTRING — which
        # names exhaustive_audit.py as the motivating example — made that tool
        # pass. Require an actual invocation: the file named inside a
        # subprocess-style path join, not merely discussed.
        invoked = re.search(r'"tools",\s*"' + re.escape(fn) + r'"', audit_src) \
            or re.search(r'tools/' + re.escape(fn) + r'["\']', audit_src)
        if invoked:
            continue
        if fn in EXCLUDED:
            continue
        findings.append((
            "MIN", "TOOL-UNWIRED", f"tools/{fn}",
            f"{fn} promises verification but is not invoked by audit_script.py and "
            f"is not declared in EXCLUDED with a reason. A tool nothing runs is a "
            f"tool that does not exist: wire it in, or record why it is excluded."))

    # A declared exclusion for a tool that no longer exists is its own rot.
    for fn in EXCLUDED:
        if not os.path.exists(os.path.join(tools_dir, fn)):
            findings.append((
                "MIN", "TOOL-UNWIRED", "audit_script.py",
                f"EXCLUDED names {fn}, which is not in tools/. Remove the entry."))
    return findings


def check_protocol_indexed(package_root="."):
    """v3.8.104 (PROTOCOL-UNINDEXED, MIN): a governing document must be reachable
    from the document a session reads first.

    THE FAILURE THIS CLOSES. PROJECT_SKILL.md governs how a session works on this
    platform. At v3.8.103 it referenced NONE of the five protocol documents:
    RECONSTRUCTION_PROTOCOL.md (v3.7.x), FINDING_TRACE_PROTOCOL.md (v3.8.11),
    MODEL_INPUT_INVARIANT.md (v3.8.49), AUDIT_SCOPE_AND_LIMITS.md, or
    SUBSTANTIATION_PROGRAM.md. Each was added and never wired back into the
    onboarding file.

    The consequence was not hypothetical. A session asserted that model-input
    provenance had never been examined; MODEL_INPUT_INVARIANT.md had governed it
    for fifty releases, and the worked example inside it was the exact case being
    "discovered".

    Nothing here can make a session READ them. It can make their absence from the
    index fail the build, so the next protocol added cannot go unindexed the way
    these five did.
    """
    findings = []
    skill = os.path.join(package_root, "PROJECT_SKILL.md")
    if not os.path.exists(skill):
        return findings
    with open(skill, encoding="utf-8") as f:
        text = f.read()

    GOVERNING = [
        "RECONSTRUCTION_PROTOCOL.md",
        "FINDING_TRACE_PROTOCOL.md",
        "MODEL_INPUT_INVARIANT.md",
        "AUDIT_SCOPE_AND_LIMITS.md",
        "SUBSTANTIATION_PROGRAM.md",
        "IMPLEMENTATION_PLAN.md",
        "SUBSTANTIATION_FINDINGS.md",
        "RETRIEVAL_RUNBOOK.md",
    ]
    for doc in GOVERNING:
        if not os.path.exists(os.path.join(package_root, doc)):
            continue
        if doc not in text:
            findings.append((
                "MIN", "PROTOCOL-UNINDEXED", "PROJECT_SKILL.md",
                f"{doc} governs how work on this platform is done and is not "
                f"referenced by PROJECT_SKILL.md, the file a session reads first. "
                f"A protocol nobody is pointed at is a protocol nobody follows."))
    return findings


def check_exhaustive_audit_layer1(package_root="."):
    """v3.8.104 (EXHAUSTIVE-LAYER1): run the second audit engine and report it.

    tools/exhaustive_audit.py was added long before this check and NOTHING EVER
    RAN IT. It cross-checks every value in a file set against the figures
    registry and detects near-miss variants of load-bearing figures. Pointed at a
    single document it immediately reported `value 14570 within 1% of
    FIG-per-citizen-net-benefit-weighted canonical 14583` — a near-miss on the
    exact figure that eighteen clean releases did not surface, from a tool that
    had been sitting in tools/ the whole time.

    REPORTING, NOT BLOCKING, and deliberately. Across the three figure-bearing
    folders it produces 161 A2 (near-miss) and 24 C3 (unresolved token)
    findings. Much of A2 is expected: illustrative household figures legitimately
    sit within 1% of a canonical value. Failing the build on 185 findings would
    get this check disabled within a release, which is how the tool became
    unused the first time.

    So it reports counts as OBS. Triaging A2 into "rounded illustration" and
    "typo variant" is real work with a real payoff and it is recorded in
    SUBSTANTIATION_FINDINGS.md rather than pretended away here.
    """
    import subprocess as _sp
    findings = []
    tool = os.path.join(package_root, "tools", "exhaustive_audit.py")
    if not os.path.exists(tool):
        return findings
    targets = [os.path.join(package_root, d) for d in
               ("05_Analytical_Framing", "04_Mathematical_Models", "08_Pillar_Substantiation")]
    targets = [t for t in targets if os.path.isdir(t)]
    if not targets:
        return findings
    try:
        r = _sp.run([sys.executable, tool] + targets,
                    capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=1800)
    except Exception as e:
        findings.append(("NOTE", "EXHAUSTIVE-LAYER1", "tools/exhaustive_audit.py",
                         f"could not run ({type(e).__name__}); NOT verified this build"))
        return findings
    head = ""
    per = {}
    for line in (r.stdout or "").splitlines():
        m = re.match(r"=== EXHAUSTIVE AUDIT Layer 1: (\d+) files, (\d+) findings ===", line)
        if m:
            head = f"{m.group(1)} files, {m.group(2)} findings"
        m2 = re.match(r"\[([A-Z]\d)\] (\d+) finding", line)
        if m2:
            per[m2.group(1)] = int(m2.group(2))
    detail = ", ".join(f"{k}={v}" for k, v in sorted(per.items())) or "no findings"
    findings.append((
        "OBS", "EXHAUSTIVE-LAYER1", "tools/exhaustive_audit.py",
        f"Layer 1 ran: {head or 'no summary line'} ({detail}). A2 = value within 1% "
        f"of a canonical figure (near-miss or rounded illustration; needs triage). "
        f"C3 = unresolved FIG token. Reporting only — see SUBSTANTIATION_FINDINGS.md."))
    return findings


def check_conversion_declared(package_root="."):
    """v3.8.107 (CONVERSION-UNDECLARED, MIN): a converted value must declare its
    conversion, and the declaration must be complete enough to reproduce it.

    THE FAILURE THIS CLOSES. FIG-gpfg-fund-size was registered as $2.2 trillion
    USD from a publisher that reports only in kroner. No exchange rate and no
    conversion date existed anywhere in the package, so the figure could not be
    regenerated from any archived artifact even in principle. Sealing the source
    document did not help, because the missing input was in none of the
    documents. It took a re-anchor to the publisher's own currency to fix.

    A CONVERSION IS A DERIVATION. In MODEL_INPUT_INVARIANT.md's vocabulary a
    converted value is COMPUTED, not SOURCED, and a computation must declare its
    inputs. This check enforces that for the one class of input the platform had
    been treating as free.

    TWO METHODS, AND THEY NEED DIFFERENT FIELDS.

      market_fx  one currency into another at a moment. Needs rate, rate_date and
                 a rate_source_id that is itself a registered source, so the rate
                 is archivable rather than transcribed.

      ppp        purchasing power parity: an OECD methodology, not a rate. Needs
                 the methodology and its vintage, because PPP series are revised
                 and two compilations of the same year can differ. That is why
                 the OECD reports US per-capita health spending at 14,885 where
                 the Peterson-KFF tracker reports 14,775 for the same year: two
                 PPP compilations, not a disagreement.

    `method: none` is a legitimate and required declaration. "This publisher
    reports in the currency we state" is a fact worth recording, because an
    absent conversion block and a deliberate absence of conversion look identical
    otherwise, and this session has repeatedly shown that absence is the thing
    the platform is worst at reading.

    NOTE, NOT MIN, for a source that has no conversion block at all: most sources
    are percentages, counts or ratios where the question does not arise, and
    demanding a declaration from all 28 would produce noise rather than coverage.
    MIN is reserved for a block that is present and INCOMPLETE, which is a
    conversion someone started to document and left unreproducible.
    """
    findings = []
    path = os.path.join(package_root, "data_recency.json")
    if not os.path.exists(path):
        return findings
    with open(path, encoding="utf-8") as f:
        srcs = json.load(f).get("sources", [])

    REQUIRED = {
        "market_fx": ("source_currency", "stated_currency", "rate", "rate_date", "rate_source_id"),
        "ppp": ("source_currency", "stated_currency", "methodology", "methodology_vintage"),
        "none": ("source_currency", "stated_currency"),
    }
    known = {s["id"] for s in srcs}
    declared = 0
    for s in srcs:
        conv = s.get("conversion")
        if not conv:
            continue
        declared += 1
        sid = s["id"]
        method = conv.get("method")
        if method not in REQUIRED:
            findings.append((
                "MIN", "CONVERSION-UNDECLARED", "data_recency.json",
                f"{sid}: conversion.method is {method!r}; expected one of "
                f"{', '.join(sorted(REQUIRED))}."))
            continue
        for field in REQUIRED[method]:
            if not conv.get(field):
                findings.append((
                    "MIN", "CONVERSION-UNDECLARED", "data_recency.json",
                    f"{sid}: conversion.method is {method!r} but {field!r} is missing. "
                    f"An incomplete conversion is one nobody can reproduce, which is "
                    f"the defect this declaration exists to prevent."))
        # a rate must point at something archivable, not a typed-in number
        rsid = conv.get("rate_source_id")
        if method == "market_fx" and rsid and rsid not in known:
            findings.append((
                "MIN", "CONVERSION-UNDECLARED", "data_recency.json",
                f"{sid}: rate_source_id {rsid!r} is not a registered source. The rate "
                f"must be archivable like any other input."))
    findings.append((
        "OBS", "CONVERSION-UNDECLARED", "data_recency.json",
        f"{declared} of {len(srcs)} source(s) declare a conversion basis. Most of the "
        f"remainder are percentages, counts or ratios where no conversion arises; a "
        f"declaration is required only where the platform states a currency the "
        f"publisher does not use."))
    return findings


def check_discrepancy_claim(package_root="."):
    """v3.8.119 (DISCREPANCY-CLAIM-UNTRACED, MIN): a claim that two of the
    platform's own numbers disagree must carry the trace that establishes it.

    THE GAP THIS CLOSES. check_phase_claim requires evidence beside a COUNT.
    check_absence_claim requires it beside an assertion that something DOES NOT
    EXIST. NEITHER COVERS THE SHAPE THAT HAS FAILED MOST OFTEN HERE: "X is $839B
    and Y is $1,037.3B, a gap of $198B."

    That is a DISCREPANCY claim. It asserts nothing missing and counts nothing,
    so both existing gates pass it. Six such claims have been recorded and later
    corrected -- the ASCE gap at v3.8.96, the component sum at v3.8.110, the
    Monte Carlo medians at v3.8.115, the health base and the Medicare basis at
    v3.8.118, and the LTC subtraction at v3.8.120. IN EVERY CASE THE EXPLANATION
    WAS IN THE PROSE OR THE SESSION RECORD, and in every case only the structured
    data had been searched.

    REBUILT v3.8.121 AFTER ITS OWN FIXTURE FAILED IT. Shipped at v3.8.119 with no
    fixture proof, in violation of release-discipline rule 3, which the same
    author wrote. Running one afterwards found three defects:

      PHRASING. It matched "a gap of $198B" but not "a $198B gap" -- one of the
      two claims it was built for. A magnitude can precede or follow the noun, so
      the noun is now matched on its own.

      SCOPE, AND THIS WAS THE SERIOUS ONE. It scanned opted-in .md files only.
      THE CLAIMS IT WAS BUILT FOR WERE RECORDED IN figures_registry.json, WHICH
      IT NEVER READ. Most durable claims in this platform live in registry note
      fields, not in prose. The three registries are now scanned unconditionally;
      they carry no opt-in marker and need none, because a note field is not
      narrative.

      SEVERITY OF THE MISS. A claim in a registry note is MORE durable than one
      in a document, because it is what future sessions read first.

    WHAT IT STILL CANNOT DO, stated plainly so nobody relies on it further than
    it goes: it fires when a claim is WRITTEN DOWN. It cannot catch a claim made
    in conversation and never recorded, and it cannot run the trace. It narrows
    the window between forming a wrong finding and publishing one; it does not
    close it.
    """
    findings = []
    MARK = "<!-- phase-claims-checked -->"
    DISCREPANCY_RE = re.compile(
        r"^(?![>|].*)(?P<line>.*\b("
        r"gap|delta|shortfall|discrepanc|does not reconcile|do(?:es)? not match|"
        r"disagree(?:s|ment)?|inconsistent with|contradict(?:s|ed|ion)?|"
        r"matches neither|matches no single|"
        r"against a (?:registered|published|stated)|"
        r"(?:higher|lower|larger|smaller) than (?:the )?(?:registered|published|stated)"
        r")\b.*)$", re.M | re.I)
    NUMERIC = re.compile(r"[\d,]+\.?\d*\s*(?:billion|trillion|percent|%|B\b|T\b)|\$[\d,]")
    # A trace or a command in the same section satisfies the gate.
    EVIDENCE = re.compile(r"```|trace_finding\.py|verify_finding\.py")

    targets = []
    for reg in ("00_GUI_Files/figures_registry.json",
                "00_GUI_Files/assumptions_registry.json",
                "data_recency.json"):
        p = os.path.join(package_root, reg)
        if os.path.exists(p):
            targets.append((p, True))
    for root, _dirs, files in os.walk(package_root):
        if any(seg in root for seg in ("/_web_html", "/node_modules", "/.git", "/_downloads")):
            continue
        for fn in files:
            if fn.endswith(".md"):
                targets.append((os.path.join(root, fn), False))

    for path, is_registry in targets:
        try:
            with open(path, encoding="utf-8") as f:
                text = f.read()
        except Exception:
            continue
        if not is_registry and MARK not in text:
            continue
        if is_registry:
            # PER-ENTRY, NOT PER-FILE. Treating a registry as one section meant a
            # single mention of verify_finding.py anywhere in it exempted EVERY
            # claim in the file -- which is what happened on the first run, and it
            # made the scope extension illusory. Each entry is its own section, so
            # evidence must sit with the claim it supports.
            try:
                doc = json.loads(text)
            except Exception:
                continue
            items = doc.get("entries") or doc.get("sources") or []
            # ONE FIELD PER LINE. Dumping an entry as a single JSON line put every
            # claim on one line, which the 240-character cap then discarded --
            # silently returning zero. The cap exists to skip prose paragraphs,
            # not to skip registry entries for being long.
            sections = []
            for it in items:
                if not isinstance(it, dict):
                    continue
                lines = []
                for k, v in it.items():
                    if isinstance(v, str):
                        lines.append(f"{k}: {v}")
                    elif isinstance(v, (dict, list)):
                        lines.append(f"{k}: {json.dumps(v, ensure_ascii=False)}")
                sections.append("\n".join(lines))
        else:
            sections = re.split(r"^## ", text, flags=re.M)
        for section in sections:
            if EVIDENCE.search(section):
                continue
            for m in DISCREPANCY_RE.finditer(section):
                line = " ".join(m.group("line").split())
                if len(line) > 240 or not NUMERIC.search(line):
                    continue
                rel = os.path.relpath(path, package_root)
                findings.append((
                    "MIN", "DISCREPANCY-CLAIM-UNTRACED", rel,
                    f"discrepancy claim with no trace in the same section: "
                    f"{line[:120]!r}. Run tools/trace_finding.py on the topic and "
                    f"quote it, or quote the command that establishes the gap. Six "
                    f"such claims have been recorded and later corrected."))
    return findings


def check_note_field_singular(package_root="."):
    """v3.8.122 (NOTE-FIELD-SPLIT, MIN): a record carries `note` or `notes`, never
    both, and never only the plural.

    THE FAILURE THIS CLOSES. data_recency.json carried BOTH spellings: 26 sources
    used `note`, 3 used `notes`, and 3 CARRIED BOTH WITH DIFFERENT CONTENT.
    Anything reading one silently lost the other.

    That is not hypothetical. A session queried `note` on swf-payout-rules, got an
    empty string, and reported the source as contentless -- while its `notes` held
    the Norway 3-percent structural cap and the Alaska 5-percent POMV rule, which
    are the entire justification for the platform's 1.2 percent education draw
    being conservative rather than arbitrary. The source was nearly retired on the
    strength of a field-name mismatch.

    A SPLIT KEY IS WORSE THAN A MISSING ONE. A missing key returns nothing and the
    caller notices. A split key returns SOMETHING, which reads as complete.

    Checked on the source register and both figure registries, because the same
    two spellings are available everywhere and nothing prevented the drift from
    recurring.
    """
    findings = []
    for rel, key in (("data_recency.json", "sources"),
                     ("00_GUI_Files/figures_registry.json", "entries"),
                     ("00_GUI_Files/assumptions_registry.json", "entries")):
        path = os.path.join(package_root, rel)
        if not os.path.exists(path):
            continue
        try:
            with open(path, encoding="utf-8") as f:
                doc = json.load(f)
        except Exception:
            continue
        items = doc.get(key) or []
        singular = sum(1 for it in items if isinstance(it, dict) and "note" in it)
        plural = [it.get("id", "?") for it in items
                  if isinstance(it, dict) and "notes" in it]
        both = [it.get("id", "?") for it in items
                if isinstance(it, dict) and "note" in it and "notes" in it]
        # A registry that has settled on the plural everywhere is consistent and
        # is left alone; the defect is MIXTURE, not the choice of spelling.
        if both:
            findings.append((
                "MIN", "NOTE-FIELD-SPLIT", rel,
                f"{len(both)} record(s) carry BOTH `note` and `notes`: "
                f"{', '.join(both[:5])}. Anything reading one loses the other. "
                f"Merge them; do not drop either, because each was written by a "
                f"different session for a different reason."))
        elif plural and singular:
            findings.append((
                "MIN", "NOTE-FIELD-SPLIT", rel,
                f"{singular} record(s) use `note` and {len(plural)} use `notes`: "
                f"{', '.join(plural[:5])}. One spelling per registry, or a reader "
                f"querying the wrong one gets an empty string and reports the "
                f"record as contentless."))
    return findings


def check_source_archived(package_root="."):
    """v3.8.58: a registered source that is cited but not archived cannot survive
    a reload. SOURCE_RETRIEVAL_PLAN.md governs closing this.

    data_recency.json records 23 external sources with URLs and vintages. Five
    have their raw data in _data_archive with checksums; eighteen are a URL, a
    vintage, and a value someone read once. For those eighteen nothing in the
    package can confirm the recorded value still matches the publication, and
    nothing regenerates the figures resting on it.

    That is the difference between SOURCED and REPRODUCIBLE. The determinism work
    proved the platform produces identical output from identical inputs; this
    check measures how many of those inputs the platform actually holds.

    Reports two conditions separately, because they need different fixes:
      - a source feeding figures but not archived (retrieval)
      - a source feeding NO figure (a decision: narrative support, or an orphan)

    OBS severity. A cited source is not a defect; it is a weaker form of evidence
    than an archived one, and the register should say which it is.
    """
    findings = []
    dp = os.path.join(package_root, "data_recency.json")
    ad = os.path.join(package_root, "_data_archive")
    if not os.path.exists(dp):
        return findings
    try:
        with open(dp, encoding="utf-8") as _f:
            data = json.load(_f)
    except json.JSONDecodeError:
        return findings
    srcs = data.get("sources") or data.get("entries") or []
    archived_dirs = os.listdir(ad) if os.path.isdir(ad) else []

    cited_feeding, orphans = [], []
    for s in srcs:
        sid = s.get("id") or ""
        if not sid:
            continue
        feeds = s.get("feeds_figures") or []
        # v3.8.58: an EXPLICIT link only. Two false positives were found writing
        # this check. Loose token matching on the source id matched "2025" inside
        # "may2025" and "ed" inside almost anything, which reported five archived
        # sources when there are three. And retrieved_via records HOW a value was
        # looked up ("web_search 2026-07-08" for 14 of 23 entries), which is the
        # OPPOSITE of evidence that raw data is held.
        #
        # A source counts as archived only if archive_dir names a real directory
        # under _data_archive. That field has to be set deliberately, which is
        # the point: archiving is an act, not an inference.
        ad_name = s.get("archive_dir")
        is_arch = bool(ad_name) and ad_name in archived_dirs
        if is_arch:
            continue
        (cited_feeding if feeds else orphans).append((sid, len(feeds)))

    if cited_feeding:
        names = ", ".join(f"{i}({n})" for i, n in sorted(cited_feeding))
        findings.append(("OBS", "SOURCE-NOT-ARCHIVED", "data_recency.json",
                         f"{len(cited_feeding)} source(s) feed figures but have no raw data in "
                         f"_data_archive, so the figures resting on them cannot be re-derived: "
                         f"{names}. See SOURCE_RETRIEVAL_PLAN.md."))
    if orphans:
        findings.append(("OBS", "SOURCE-FEEDS-NOTHING", "data_recency.json",
                         f"{len(orphans)} registered source(s) feed no figure: "
                         f"{', '.join(i for i, _ in sorted(orphans))}. Either narrative support, "
                         f"in which case say so, or an orphan entry to remove."))
    return findings


def _retired_models(package_root="."):
    """v3.8.648 (W32): workbooks the catalog marks RETIRED (their description begins 'RETIRED'), read from the catalog so a
    model retired later is exempted without editing this check."""
    try:
        docs = json.load(open(os.path.join(package_root, "00_GUI_Files", "platform_catalog.json"), encoding="utf-8"))["documents"]
    except Exception:
        return set()
    return {os.path.basename(d["path"]) for d in docs if d.get("path", "").endswith(".xlsx") and str(d.get("description", "")).startswith("RETIRED")}


_PROVENANCE_CITED = __import__("re").compile(
    r"\b(CMS|NHEA|NHE|CRS|KFF|AARP|JRC|BLS|OEWS|Census|CPS|ACS|CBO|IRS|SOI|OMB|SSA|Federal Reserve|SCF|IPEDS|NCES|"
    r"Treasury|GAO|NBER|HUD|USDA|FCC|_data_archive|sealed|DERIVED)\b")


def check_model_input_provenance(package_root="."):
    """v3.8.49: a numeric literal in an Assumptions sheet that is really another
    model's output. MODEL_INPUT_INVARIANT.md governs this.

    Sourcing checks the OUTER boundary, where a value enters from the world.
    data_recency.json and DATA-SOURCE-LINK already do that and work. This checks
    the INNER boundary, where one model's output enters another model's inputs,
    and nothing checked it before RESEARCH-35.

    The failure it catches: 04_Education_Fund_Cost_Based_Pricing_Model
    interpolates the retirement fund's balance across hardcoded milestones in its
    own Assumptions sheet. Those milestones match the projecting model's HEADLINE
    year-60 corpus to within 0.06 percent (122.00T against 121.93T) and exceed its
    year-10 value by 8x. They were anchored to the headline and the intervening
    decades drawn as a straight line, on a curve that is convex. Every input was
    defensible; the path between them was invented.

    DELIBERATELY NARROW. A general "literals in Assumptions" check would flag
    every legitimate assumption in the package. This flags only the specific
    signature: a literal in an Assumptions-like sheet that MATCHES a value
    computed elsewhere in the package to within 1 percent, which is what
    distinguishes a pasted output from an independent estimate. Round numbers
    alone are not evidence; matching another model's output is.

    OBS severity. A match may be legitimate (two models agreeing on a shared
    anchor is not a defect) so this reports for a human to judge rather than
    blocking. Raise to MIN once the known cases are resolved.
    """
    findings = []
    try:
        import openpyxl
    except ImportError:
        return [("NOTE", "MODEL-INPUT-PROVENANCE", "04_Mathematical_Models",
                 "openpyxl not installed; model input provenance NOT checked")]
    import glob as _glob
    models = sorted(_glob.glob(os.path.join(package_root, "04_Mathematical_Models", "*.xlsx")))
    # Collect computed outputs: values living in non-Assumptions sheets.
    # Workbooks that READ another model's series rather than computing their own
    # must not seed the index: they re-export the originating trajectory, so
    # every assumption matching the original also matches the reader, and the
    # finding names the wrong source. 04_CCP_Transition_Cost_Model reads
    # Combined Reform's Old Sys Net by design and stated intent.
    READER_MODELS = {"04_CCP_Transition_Cost_Model.xlsx"}
    computed = {}
    for f in models:
        if os.path.basename(f) in READER_MODELS:
            continue
        try:
            wb = openpyxl.load_workbook(f, data_only=True, read_only=True)
        except Exception:
            continue
        base = os.path.basename(f)
        for sn in wb.sheetnames:
            if any(k in sn.lower() for k in ("assum", "input", "source", "readme")):
                continue
            try:
                for row in wb[sn].iter_rows(values_only=True):
                    for v in row:
                        if isinstance(v, (int, float)) and abs(v) >= 1e11:
                            computed.setdefault(round(float(v)), (base, sn))
            except Exception:
                continue
    # Now scan Assumptions sheets for literals matching a computed value.
    hits = {}
    for f in models:
        try:
            wbf = openpyxl.load_workbook(f, data_only=False, read_only=True)
            wbv = openpyxl.load_workbook(f, data_only=True, read_only=True)
        except Exception:
            continue
        base = os.path.basename(f)
        if base in _retired_models(package_root):   # v3.8.648 (W32, author #4580, option a): a retired model is a record, not a live input
            continue
        for sn in wbf.sheetnames:
            if not any(k in sn.lower() for k in ("assum", "input")):
                continue
            try:
                rowsf = list(wbf[sn].iter_rows())
                rowsv = list(wbv[sn].iter_rows(values_only=True))
            except Exception:
                continue
            for ri, rowf in enumerate(rowsf):
                for ci, cell in enumerate(rowf):
                    lit = cell.value
                    # only hand-entered numbers, not formulas
                    if not isinstance(lit, (int, float)) or abs(lit) < 1e11:
                        continue
                    # v3.8.648 (W32, author #4589, option A): an input whose own row cites an external source or a
                    # derivation is a sourced value that matched a model output by chance, not a pasted output
                    row_text = " ".join(str(c.value) for c in rowf if isinstance(c.value, str))
                    if _PROVENANCE_CITED.search(row_text):
                        continue
                    for cv, (src_file, src_sheet) in computed.items():
                        if src_file == base:
                            continue
                        if cv and abs(float(lit) - cv) / max(abs(cv), 1) < 0.01:
                            hits.setdefault((base, sn, cell.column_letter, src_file), []).append(
                                (cell.coordinate, lit))
                            break

    # A SINGLE match is not evidence. Any large round number will coincide with
    # something in a sixty-year model, and the first version of this check
    # reported 61 findings that were almost all coincidence. The signature of a
    # pasted trajectory is a SERIES: three or more literals in the same column,
    # each matching a value computed in the SAME other model. That is what
    # C53-C58 of the education model looks like, and coincidence does not line up
    # three deep in one column against one source.
    for (base, sn, col, src_file), cells in sorted(hits.items()):
        if len(cells) < 3:
            continue
        coords = ", ".join(c for c, _ in cells[:6])
        findings.append((
            "OBS", "MODEL-INPUT-PROVENANCE",
            f"04_Mathematical_Models/{base}",
            f"{sn} column {col} holds {len(cells)} literals ({coords}) that each match values "
            f"computed in {src_file} to within 1%. A series this consistent is that model's "
            f"output pasted as assumptions, not independent estimates. Declare it COMPUTED with "
            f"a pointer to the source sheet, or state why the values are independent. "
            f"See MODEL_INPUT_INVARIANT.md."))
    return findings


def check_registration_completeness(package_root="."):
    """v3.8.31: the checking apparatus checks the platform; this checks the apparatus.

    Adding a check here means touching FOUR places, and nothing said so. Three
    consecutive releases each shipped a capability with one registration missing,
    and every one was found by a deploy failing rather than by the package:

      v3.8.29  SEC-10 was added to CHECKS and not to the self-test fixtures.
      v3.8.29  SEC-10 returned 4-tuples where the runner unpacks 3, crashing the
               deploy mid-run.
      v3.8.30  SEC-10's pypdf dependency was declared in requirements.txt and not
               to the deploy preflight, so the gate ran unable to read any PDF.

    Worse, and the reason this check exists rather than a checklist: SEC-7 had no
    fixture AND had been broken since the catalog schema changed. It matched a
    "filename" key the catalog no longer uses, found zero of thirteen private
    documents, and reported [OK] on every deploy for months, INCLUDING EVERY
    DEPLOY DURING WHICH A PRIVATE ARCHIVE WAS SERVED PUBLICLY. A check with no
    fixture and no findings is indistinguishable from a check that works.

    Checks three invariants:
      1. every registered security check has a self-test fixture
      2. every check function defined is reachable (registered or called)
      3. every non-stdlib import inside a check body is declared in
         requirements.txt

    OBS severity. It reports on the apparatus, not the platform, and a missing
    fixture is a gap in assurance rather than a defect in the content.
    """
    import ast as _ast
    findings = []
    sr_path = os.path.join(package_root, "tools", "security_review.py")
    if os.path.exists(sr_path):
        with open(sr_path, encoding="utf-8") as f:
            sr = f.read()
        registered = re.findall(r'^\s{4}\("(SEC-\d+)[^"]*",\s*(\w+)\)', sr, re.M)
        fixtures = set(re.findall(r'^\s{8}\("(SEC-\d+)"', sr, re.M))
        for code, fn in registered:
            if code not in fixtures:
                findings.append(("OBS", "REGISTRATION-NO-FIXTURE", "tools/security_review.py",
                                 f"{code} ({fn}) is registered in CHECKS but has no self-test "
                                 f"fixture. Until it does, nothing proves it can fire, and a "
                                 f"check that cannot fire reports OK forever."))

    aud_path = os.path.join(package_root, "audit_script.py")
    if os.path.exists(aud_path):
        with open(aud_path, encoding="utf-8") as f:
            aud = f.read()
        defined = set(re.findall(r"^def (check_\w+)\(", aud, re.M))
        extended = set(re.findall(r"all_findings\.extend\((check_\w+)\(", aud))
        for fn in sorted(defined - extended):
            if fn.endswith("_DUMMY"):
                continue
            body = aud.replace(f"def {fn}(", "")
            if not re.search(re.escape(fn) + r"\(", body):
                findings.append(("OBS", "REGISTRATION-UNREACHABLE", "audit_script.py",
                                 f"{fn} is defined but never registered or called. It cannot "
                                 f"report anything."))

    # Third-party imports inside check bodies must be declared.
    req = ""
    req_path = os.path.join(package_root, "requirements.txt")
    if os.path.exists(req_path):
        with open(req_path, encoding="utf-8") as f:
            req = f.read().lower()
    STDLIB = {"os", "re", "sys", "json", "ast", "glob", "csv", "io", "math", "time",
              "shutil", "hashlib", "pathlib", "datetime", "subprocess", "zipfile",
              "collections", "itertools", "typing", "importlib", "textwrap", "html",
              "urllib", "functools", "argparse", "tempfile", "difflib", "unicodedata",
              "xml", "base64", "random", "statistics", "string", "warnings", "copy"}
    for src in (sr_path, aud_path):
        if not os.path.exists(src):
            continue
        with open(src, encoding="utf-8") as f:
            text = f.read()
        try:
            tree = _ast.parse(text)
        except SyntaxError:
            continue
        for node in _ast.walk(tree):
            if not (isinstance(node, _ast.FunctionDef) and node.name.startswith("check_")):
                continue
            for sub in _ast.walk(node):
                mods = []
                if isinstance(sub, _ast.Import):
                    mods = [a.name.split(".")[0] for a in sub.names]
                elif isinstance(sub, _ast.ImportFrom) and sub.module:
                    mods = [sub.module.split(".")[0]]
                for mod in mods:
                    if mod in STDLIB or mod.startswith("_"):
                        continue
                    # Local modules are not dependencies. build_helpers sits
                    # beside these scripts; demanding it appear in
                    # requirements.txt would be asking pip to install the
                    # package's own source file.
                    if (os.path.exists(os.path.join(package_root, mod + ".py")) or
                            os.path.exists(os.path.join(package_root, "tools", mod + ".py")) or
                            os.path.isdir(os.path.join(package_root, mod))):
                        continue
                    if mod.lower().replace("_", "-") not in req.replace("_", "-"):
                        findings.append(("OBS", "REGISTRATION-UNDECLARED-IMPORT",
                                         os.path.basename(src),
                                         f"{node.name} imports {mod!r}, which is not in "
                                         f"requirements.txt. On a machine without it the "
                                         f"check degrades or fails."))
    return findings


def check_tracked_issues_naming(package_root="."):
    """v3.8.23: 'Section 47' must not appear in outsider-facing material.

    The registry's public name is 'Tracked Issues Registry'. 'Section 47' is an
    internal shorthand and a historical heading, and an outsider reading
    '(PERSONA-SIG-10 in Section 47)' has no way to know what it refers to.

    The rule already existed; nothing enforced it, so compliance depended on
    someone remembering to grep, and that triage repeatedly cost more time than
    the defect - most hits are LEGITIMATE and must not be touched.

    Three categories are exempt, for different reasons:
      - The verbatim conversation archives and log. These are historical record.
        Rewriting them would falsify what was actually said.
      - exhaustive_audit/ working records. Internal process documents where the
        internal name is the correct name.
      - The OIR iteration archive, which preserves the literal section heading
        as its canonical historical source.

    Anything else that is public-facing is a real violation.
    """
    import re as _re
    findings = []
    # v3.8.25: the first run reported 16 files and NONE of them were violations.
    # Reviewing them one by one produced three legitimate patterns, and reporting
    # a legitimate pattern as a finding is how a guard trains its reader to
    # ignore it.
    #
    #   1. CITATIONS OF THE LITERAL HEADING. The OIR Iteration Archive really
    #      does contain a section titled "Section 47", and the bot mirror and
    #      manifest point readers at it: "Canonical historical source: Section 47
    #      of the OIR Iteration Archive." Renaming that would make the citation
    #      FALSE, since no section by the new name exists in that document. This
    #      is the opposite of the defect the rule targets.
    #   2. INTERNAL MAINTAINER AND TOOLING FILES, where the internal name is the
    #      correct name. PROJECT_SKILL.md goes further and discusses the naming
    #      itself, which cannot be done without using both names.
    #   3. HISTORICAL RECORD, where the text reports what a prior version said.
    exempt_substrings = (
        "09_Conversation_Archive", "09_Conversation_Log",
        "review_comments/",  # v3.8.513: private ledger, handoff and status report; never outsider-facing
        "response_checklists/",  # v3.8.608: private per-reply checklist logs; never outsider-facing
        "exhaustive_audit/", "exhaustive_audit\\",
        "09_OIR_Iteration_Archive", "09_Open_Issues_Registry",
        "VERSIONLOG.txt", "REVIEW_LOG", "_data_archive",
        # internal maintainer / tooling / historical files
        "PROJECT_SKILL.md", "AUDIT_SCOPE_AND_LIMITS.md", "CLOSEOUT_PLAN.md",
        "audit_whitelist.txt", "data/errata.json", "README.txt",
        "figures_registry.json", "substantiation_template_schema.json",
        "SUBSTANTIATION_TEMPLATE.md", "cloudflare/README.md",
        "FINDING_TRACE_PROTOCOL.md", "RECONSTRUCTION_PROTOCOL.md",
        # v3.8.85: the release-baseline snapshot of the figures registry. The live
        # registry is already exempt on this list, and a frozen copy of it is the
        # same content under a different name; exempting one and not the other
        # reports a file for text it inherited rather than text anyone wrote.
        "_internal/figures_registry.baseline.json",
        # v3.8.607 (W47, author #4320): Word documents are now read too. These three are HISTORICAL RECORDS
        # (the package-version changelog and two dated process records); their wording is kept as written and
        # each carries a first-use note naming the registry's current name.
        "01_Platform_Package_Version.docx", "09_Iterative_Hardening_Process_Documentation",
        "09_Persona_Simulations_P7_P11",
        # v3.8.607: a generated report that QUOTES other documents verbatim (its one hit quotes the exempt
        # OIR iteration archive); it had fired as a standing OBS on that quotation every release.
        "RETIRED_VALUE_SCAN.md",
    )
    # Phrases where "Section 47" names the literal heading being cited. Removed
    # before counting, so a file is reported only for occurrences that USE the
    # term as a name rather than CITE it as a location.
    citation_patterns = (
        # \s+ rather than a literal space: these strings are wrapped across
        # lines in the generated HTML, and a citation split by a newline is
        # still a citation. The first version of this pattern missed exactly
        # one occurrence for that reason.
        r"Section\s+47\s+of\s+the\s+OIR\s+Iteration\s+Archive",
        r"canonical\s+(?:historical\s+)?source[^.]{0,40}Section\s+47",
        r"Section\s+47\s*\(Comprehensive Issue Status Summary\)",
    )
    # v3.8.607 (W47): .docx added -- before this the check never read a Word document, so 593 occurrences in
    # 16 public documents never surfaced.
    exts = (".html", ".md", ".txt", ".json", ".js", ".docx")
    for dirpath, dirnames, filenames in os.walk(package_root):
        dirnames[:] = [d for d in dirnames
                       if d not in ("_web_html", "__pycache__", ".git", "_downloads")
                       and not d.startswith(".")]
        for fn in filenames:
            if not fn.endswith(exts):
                continue
            full = os.path.join(dirpath, fn)
            rel = os.path.relpath(full, package_root).replace("\\", "/")
            if any(x.replace("\\", "/") in rel for x in exempt_substrings):
                continue
            try:
                if fn.endswith(".docx"):
                    import zipfile as _zf
                    with _zf.ZipFile(full) as _z:
                        text = _re.sub(r"<[^>]+>", "", _z.read("word/document.xml").decode("utf-8", "ignore"))
                else:
                    with open(full, encoding="utf-8", errors="ignore") as f:
                        text = f.read()
            except Exception:
                continue
            scrubbed = text
            for cp in citation_patterns:
                scrubbed = _re.sub(cp, "", scrubbed, flags=_re.I)
            n = len(_re.findall(r"\bSection 47\b", scrubbed))
            if n:
                # Severity OBS, deliberately. The first run found 16 files
                # beyond the one a manual grep had identified, and they are not
                # all violations: README.txt is a per-version changelog quoting
                # historical entries, audit_whitelist.txt is functional, and the
                # catalog/manifest carry document titles. Scoping which of these
                # should change is the maintainer's call, not the gate's, and
                # blocking a deploy on an unmade scope decision would be the
                # wrong default. Raise to MIN once the scope is settled.
                findings.append(("OBS", "TRACKED-ISSUES-NAMING", rel,
                                 f"{n} occurrence(s) of 'Section 47' in outsider-facing "
                                 f"material; use 'Tracked Issues Registry'"))
    return findings


def check_readme_stale_version(package_root="."):
    """P2.1m (README-STALE-VERSION, MIN): the README intro (everything above the changelog)
    must not hardcode a platform version other than the current one. Catches orphaned
    'updated for vN.N.NNN' / 'through vN.N.NNN' intro lines that bump_version does not touch.

    v3.8.20: the changelog anchor was hardcoded to `^v3\\.7\\.` and the comparison stripped the
    literal prefix '3.7.'. Once the 3.8 family opened, no 3.8.x changelog line matched the
    anchor, so EVERY 3.8.x entry was treated as intro and every 3.7.x version number inside one
    would flag. It had not fired only because no 3.8.x entry had yet mentioned an older version;
    the first one that did (the v3.8.20 entry, citing when the archive split was introduced)
    surfaced it. Anchor and comparison are now family-agnostic."""
    import glob as _g, re as _re
    findings=[]
    rp=[x for x in _g.glob(os.path.join(package_root,"**","README.txt"),recursive=True) if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x]
    cp=[x for x in _g.glob(os.path.join(package_root,"**","platform_catalog.json"),recursive=True) if "_web_html" not in x]
    if not (rp and cp): return findings
    try:
        r=open(rp[0],encoding="utf-8").read()
        cur=json.load(open(cp[0],encoding="utf-8")).get("platformVersion","")
    except Exception: return findings
    m=_re.search(r"(?m)^v\d+\.\d+\.\d+ \(", r)      # first changelog entry, ANY version family
    intro=r[:m.start()] if m else r
    for mm in _re.finditer(r"(?<![\d.])(\d+\.\d+\.\d+)(?!\d)", intro):
        if mm.group(1)!=cur:
            ctx=intro[max(0,mm.start()-40):mm.end()+10].replace(chr(10)," ").strip()
            findings.append(("MIN","README-STALE-VERSION","README.txt",f"intro references {mm.group(1)} (current is {cur}): ...{ctx}..."))
    return list(dict.fromkeys(findings))


def check_msa_shard_integrity(package_root="."):
    """Fast build-time gate on the per-state MSA shards.

    The raw BLS metro file is served split by state (it exceeds Cloudflare's 25 MiB
    limit). Splitting source data creates a standing obligation that the shards stay
    faithful to the original. This gate runs on every audit and cheaply confirms the
    shards have not drifted since creation:
      - every shard file's SHA-256 matches the snapshot MANIFEST,
      - the master file's SHA-256 matches the MANIFEST,
      - the manifest's per-shard row counts sum to the recorded total,
      - no manifest-listed shard is missing on disk (and vice-versa).
    The heavier row-by-row PROOF that the shards reproduce the original exactly lives
    in tools/validate_msa_shards.py (run it on demand, or in CI); it is too slow
    (~30s reading 150k rows) to run on every audit. A checksum match here guarantees
    the shards are byte-identical to the versions that full-validator last certified.
    """
    findings = []
    base = os.path.join(package_root, "_data_archive")
    if not os.path.isdir(base):
        return findings
    import hashlib
    # find snapshot(s) that have an MSA_by_state dir
    for name in sorted(os.listdir(base)):
        snap = os.path.join(base, name)
        shard_dir = os.path.join(snap, "MSA_by_state")
        manifest_path = os.path.join(snap, "MANIFEST.json")
        if not os.path.isdir(shard_dir):
            continue
        rel = f"_data_archive/{name}"
        if not os.path.exists(manifest_path):
            findings.append(("SIG", "MSA-SHARD-INTEGRITY", rel,
                "MSA_by_state/ exists but the snapshot MANIFEST.json is missing"))
            continue
        try:
            manifest = json.load(open(manifest_path, encoding="utf-8"))
        except Exception as e:
            findings.append(("SIG", "MSA-SHARD-INTEGRITY", rel, f"could not read MANIFEST.json: {e}"))
            continue
        rs = manifest.get("regional_shards", {})
        recorded = {s["file"].split("/")[-1]: s for s in rs.get("shards", [])}
        if not recorded:
            findings.append(("MIN", "MSA-SHARD-INTEGRITY", rel,
                "MSA_by_state/ exists but MANIFEST has no regional_shards record to validate against"))
            continue

        def _sha(p):
            h = hashlib.sha256()
            with open(p, "rb") as f:
                for chunk in iter(lambda: f.read(1 << 20), b""):
                    h.update(chunk)
            return h.hexdigest()

        # master checksum
        master = os.path.join(snap, "MSA_M2025_dl.xlsx")
        if os.path.exists(master):
            mrec = manifest.get("files", {}).get("MSA_M2025_dl.xlsx", {}).get("sha256")
            if mrec and _sha(master) != mrec:
                findings.append(("SIG", "MSA-SHARD-INTEGRITY", f"{rel}/MSA_M2025_dl.xlsx",
                    "master file SHA-256 does not match MANIFEST — the sealed original may have changed"))

        on_disk = set(f for f in os.listdir(shard_dir) if f.endswith(".xlsx"))
        # checksum every shard against the manifest
        for fn, rec in recorded.items():
            fp = os.path.join(shard_dir, fn)
            if not os.path.exists(fp):
                findings.append(("SIG", "MSA-SHARD-INTEGRITY", f"{rel}/MSA_by_state/{fn}",
                    "manifest lists this shard but it is missing on disk"))
                continue
            if _sha(fp) != rec.get("sha256"):
                findings.append(("SIG", "MSA-SHARD-INTEGRITY", f"{rel}/MSA_by_state/{fn}",
                    "shard SHA-256 does not match MANIFEST — shard has drifted/corrupted since validation"))
        # any shard on disk not in the manifest?
        for fn in on_disk:
            if fn not in recorded:
                findings.append(("MIN", "MSA-SHARD-INTEGRITY", f"{rel}/MSA_by_state/{fn}",
                    "shard file present on disk but not recorded in MANIFEST regional_shards"))
        # counts add up
        recorded_total = rs.get("total_data_rows")
        summed = sum(s.get("rows", 0) for s in rs.get("shards", []))
        if recorded_total is not None and summed != recorded_total:
            findings.append(("SIG", "MSA-SHARD-INTEGRITY", rel,
                f"manifest shard row counts sum to {summed} != recorded total {recorded_total}"))
    return findings


def check_cloudflare_file_size(package_root="."):
    """Flag any file at/over Cloudflare Pages' 25 MiB per-file limit.

    Cloudflare Pages hard-rejects the WHOLE deployment if a single served file
    exceeds 25 MiB (26,214,400 bytes). This froze the live site on an old version:
    the git push succeeded every time, but every Pages build failed at asset
    validation because 09_Conversation_Archive.md (private, but present on the
    unfiltered branch) and the raw BLS source spreadsheet MSA_M2025_dl.xlsx had
    each grown past the limit. The deploy tool now strips oversized files from the
    deploy copy (Step 5b), but this build-time gate surfaces the problem far
    earlier — as soon as a file crosses the threshold — with an explicit note about
    whether it's private (auto-filtered) or public (will break the deploy).
    Threshold here is 25 MiB exactly (Cloudflare's stated ceiling); the deploy tool
    uses a slightly lower 24 MiB safety margin.
    """
    findings = []
    CF_LIMIT = 25 * 1024 * 1024  # 25 MiB — Cloudflare Pages per-file ceiling
    root = os.path.abspath(package_root)
    # which paths are private (auto-filtered from the deploy branch)?
    private_paths = set()
    cat_path = os.path.join(root, "00_GUI_Files", "platform_catalog.json")
    if os.path.exists(cat_path):
        try:
            _c = json.load(open(cat_path, encoding="utf-8"))
            for d in _c.get("documents", []):
                if d.get("private"):
                    if d.get("path"):
                        private_paths.add(d["path"])
                    if d.get("htmlPath"):
                        private_paths.add(d["htmlPath"])
        except Exception:
            pass

    # gather all served HTML once so we can tell whether an oversized file is
    # actually *linked* from the public site (a broken link after the deploy tool
    # strips it) versus merely present as source/provenance (safely deploy-excluded).
    served_html_blob = ""
    for dirpath, _dn, filenames in os.walk(root):
        parts = dirpath.split(os.sep)
        if ".git" in parts or "__pycache__" in parts:
            continue
        for fn in filenames:
            if fn.endswith(".html"):
                try:
                    served_html_blob += open(os.path.join(dirpath, fn), encoding="utf-8", errors="ignore").read()
                except OSError:
                    pass

    for dirpath, dirnames, filenames in os.walk(root):
        if ".git" in dirpath.split(os.sep) or "__pycache__" in dirpath:
            continue
        for fn in filenames:
            fp = os.path.join(dirpath, fn)
            try:
                sz = os.path.getsize(fp)
            except OSError:
                continue
            if sz >= CF_LIMIT:
                rel = os.path.relpath(fp, root).replace(os.sep, "/")
                is_private = rel in private_paths
                mib = sz / 1048576
                # is the oversized file linked from any served HTML? (basename match
                # is a deliberately loose net — a false "referenced" is safer than a
                # missed broken link.)
                referenced = (rel in served_html_blob) or (("/" + fn) in served_html_blob) or (('"' + fn) in served_html_blob)
                if is_private:
                    # auto-filtered from the deploy branch, so it cannot break the
                    # build and is not a defect. Informational only (OBS) — a MIN
                    # here would wrongly block the deploy gate, which aborts on MIN.
                    # It stays visible so the file's growth is on the radar.
                    findings.append(("OBS", "CLOUDFLARE-FILE-SIZE", rel,
                        f"private file is {mib:.1f} MiB (>= Cloudflare 25 MiB limit); "
                        f"auto-filtered from the deploy branch (never served), so this is "
                        f"informational — but keep an eye on its growth"))
                elif referenced:
                    # public, oversized, AND linked from the site: the deploy tool
                    # will strip it, leaving a broken link. This blocks a clean release.
                    findings.append(("SIG", "CLOUDFLARE-FILE-SIZE", rel,
                        f"public file is {mib:.1f} MiB (>= Cloudflare 25 MiB limit) and is LINKED "
                        f"from served HTML; Cloudflare rejects it and the deploy tool strips it, "
                        f"leaving a broken link. Split/compress the file or remove the public link."))
                else:
                    # public, oversized, but not linked anywhere (e.g. raw BLS source
                    # spreadsheet kept as provenance with a MANIFEST checksum): the
                    # deploy tool's Step 5b safely excludes it from the deploy branch,
                    # and nothing on the live site points to it. Informational only.
                    findings.append(("OBS", "CLOUDFLARE-FILE-SIZE", rel,
                        f"file is {mib:.1f} MiB (>= Cloudflare 25 MiB limit) but is not linked from any "
                        f"served page; the deploy tool auto-excludes files >=24 MiB from the deploy "
                        f"branch, so it stays in source/provenance only. No action needed."))
    return findings


def check_generated_file_source_backing(package_root="."):
    """GENERATED-SOURCE-BACKING (v3.7.745): systemic guard against the class of drift
    that silently dropped the Direction F thresholds.

    Root lesson from that incident: a data/config value that lives ONLY in a generated
    build artifact (with no source file backing it) is inherently fragile — a
    regeneration can drop it and no parity/registry check will notice, because there is
    nothing to compare against. This check maintains an explicit registry of the
    platform's generated data files and the source each must be built from, and fails
    if a declared source is missing. It turns 'is this generated file backed by a
    source?' from an ad-hoc question into a standing invariant. Adding a new generated
    data file should mean adding a row here (and, ideally, a parity check).

    Registry format: generated_path -> (source_path_or_None, note). A source of None
    means 'this generated file is intentionally self-contained / derived only from
    other in-tree files' and is allowed, but flagged as OBS so the decision stays
    visible."""
    findings = []
    root = package_root
    # (generated file, its authoritative source, note). Paths relative to package root.
    REGISTRY = {
        "wtpp-wage-data.js": ("06_Presentation_Materials/wage_floor_data.json",
            "WAGE_DATA incl. metadata.thresholds must come from the source JSON (see WAGE-DATA-INTEGRITY)"),
        "wtpp-i18n.js": ("i18n/strings.en.json",
            "UI strings generated from the English source strings"),
        "00_GUI_Files/platform_catalog.json": ("platform_index.html",
            "catalog mirror of the inline window.PLATFORM_CATALOG (authoritative in platform_index.html)"),
        "00_GUI_Files/platform_catalog.js": ("platform_index.html",
            "catalog mirror of the inline window.PLATFORM_CATALOG (authoritative in platform_index.html)"),
    }
    # FOLLOW-UP (logged v3.7.745, not yet actioned): the We_The_People_Calculator
    # embeds policy constants inline (BRACKETS, STD_DEDUCTION, OCCUPATION_FLOORS,
    # HIGH_EARNER_BRACKETS). These are NOT the orphaned-generated-config pattern this
    # check guards (the calculator HTML is hand-authored and declares itself the
    # "authoritative implementation", so it IS the source). But they are unaudited
    # policy figures that could drift from the platform's canonical values over time.
    # A future hardening step would register them (e.g. federal brackets vs. an IRS
    # baseline, occupation floors vs. wage_floor_data.json) under a figure-registry
    # style check. Tracked here so the coverage gap stays visible.
    for gen, (src, note) in REGISTRY.items():
        gen_p = os.path.join(root, gen)
        if not os.path.exists(gen_p):
            # generated file absent is handled by other checks; skip here
            continue
        if src is None:
            findings.append(("OBS", "GENERATED-SOURCE-BACKING", gen,
                f"generated file is intentionally self-contained (no source): {note}"))
            continue
        src_p = os.path.join(root, src)
        if not os.path.exists(src_p):
            findings.append(("SIG", "GENERATED-SOURCE-BACKING", gen,
                f"generated data file has NO source backing on disk: expected source '{src}' is missing. "
                f"A regeneration would rebuild this file from a source that does not exist, risking silent "
                f"data loss (this is the failure mode that dropped the Direction F thresholds). {note}"))
    return findings


def check_wage_data_integrity(package_root="."):
    """P2.1w (WAGE-DATA-INTEGRITY): guards the real-BLS wage ingestion (v3.7.717+).
    Verifies (a) wage_floor_data.json's internal platform_version matches the catalog,
    (b) wtpp-wage-data.js WAGE_DATA matches wage_floor_data.json on occupation p25 and
    region factors (parity), (c) the _wage_regional shard index matches the regions
    flagged has_regional_shard, and (d) no impossible values (duplicate SOCs, p25>median,
    empty/negative shard p25). MIN severity: drift here silently corrupts the calculator."""
    import glob as _g, re as _re
    findings=[]
    wfd_p=os.path.join(package_root,"06_Presentation_Materials","wage_floor_data.json")
    cat_p=[x for x in _g.glob(os.path.join(package_root,"**","platform_catalog.json"),recursive=True) if "_web_html" not in x]
    if not (os.path.exists(wfd_p) and cat_p): return findings
    try:
        d=json.load(open(wfd_p,encoding="utf-8"))
        cur=json.load(open(cat_p[0],encoding="utf-8")).get("platformVersion","")
    except Exception: return findings
    # (a) version stamp
    pv=d.get("metadata",{}).get("platform_version","")
    if pv and cur and pv!=cur:
        findings.append(("MIN","WAGE-DATA-INTEGRITY",wfd_p,f"wage_floor_data platform_version={pv} != catalog {cur}"))
    # (d) impossible values
    seen={}
    for o in d.get("occupations",[]):
        seen[o.get("soc")]=seen.get(o.get("soc"),0)+1
        p,m=o.get("national_p25"),o.get("national_median")
        if isinstance(p,(int,float)) and isinstance(m,(int,float)) and p>m:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wage_floor_data.json",f"{o.get('soc')} p25>{m} median"))
        # sanity band: a real annual 25th-percentile wage sits well inside (0, 1,000,000].
        if isinstance(p,(int,float)) and (p<=0 or p>1_000_000):
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wage_floor_data.json",f"{o.get('soc')} national_p25={p} out of sane range (0,1000000]"))
    dups={k:v for k,v in seen.items() if v>1}
    if dups:
        findings.append(("SIG","WAGE-DATA-INTEGRITY","wage_floor_data.json",f"duplicate SOC codes: {list(dups)[:5]}"))
    # region factors must sit in a plausible band. Real empirical factors span ~0.60-1.35;
    # anything outside [0.3, 3.0] indicates corruption, not a real regional differential.
    for r in d.get("regions",[]):
        fac=r.get("factor")
        if isinstance(fac,(int,float)) and not (0.3<=fac<=3.0):
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wage_floor_data.json",f"region {r.get('id')} factor={fac} out of sane range [0.3,3.0]"))
    # (t) Direction F thresholds (v3.7.743): the calculator's Direction F table reads
    # WAGE_DATA.metadata.thresholds.direction_f_thresholds. This config block was
    # historically JS-ONLY (not in the source JSON), so a regeneration of the JS from
    # the JSON silently dropped it — the table then threw and (once an unrelated syntax
    # error was cleared) broke the calculator. No existing check covered it because it
    # was never in the source and never registered as a tracked figure. This guard
    # makes the loss detectable: the thresholds MUST exist in the source JSON, be a
    # non-empty list of fractions in (0,1], and (below, in the JS block) match the JS.
    _thr = d.get("metadata", {}).get("thresholds", {}).get("direction_f_thresholds")
    if _thr is None:
        findings.append(("SIG", "WAGE-DATA-INTEGRITY", "wage_floor_data.json",
            "metadata.thresholds.direction_f_thresholds is MISSING from the source JSON — "
            "the calculator's Direction F table depends on it (this is the field whose loss "
            "silently broke the calculator; it must live in source, not only in the generated JS)"))
    elif not (isinstance(_thr, list) and _thr and
              all(isinstance(x, (int, float)) and 0 < x <= 1 for x in _thr)):
        findings.append(("SIG", "WAGE-DATA-INTEGRITY", "wage_floor_data.json",
            f"direction_f_thresholds is malformed: {_thr!r} (expected a non-empty list of "
            f"fractions in (0,1], e.g. [0.60, 0.65, 0.70])"))

    # (b) JS/JSON parity
    js_p=[x for x in _g.glob(os.path.join(package_root,"**","wtpp-wage-data.js"),recursive=True) if "_web_html" not in x]
    if js_p:
        # (b0) JS VALIDITY (v3.7.741): the file must be parseable JavaScript, not just
        # contain a JSON-looking object. A prior bug left the header /* ... */ comment
        # unterminated (its '*/' was sliced off during regeneration because the comment
        # text itself contained 'window.WAGE_DATA = {'), so the browser threw
        # "Uncaught SyntaxError: Invalid or unexpected token", WAGE_DATA was never set,
        # and the calculator dropdowns were empty. The old regex still matched the object,
        # so the bug shipped clean. These checks catch that class of corruption:
        try:
            _src = open(js_p[0], encoding="utf-8").read()
            # unterminated block comment
            if "/*" in _src:
                _o = _src.find("/*"); _c = _src.find("*/", _o + 2)
                if _c == -1:
                    findings.append(("SIG","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",
                        "unterminated /* */ header comment: the whole file parses as a comment, "
                        "so window.WAGE_DATA is never set and the calculator breaks"))
            # the REAL assignment must exist OUTSIDE the header comment
            _comment_end = (_src.find("*/") + 2) if _src.lstrip().startswith("/*") and "*/" in _src else 0
            if _src.find("window.WAGE_DATA", _comment_end) == -1:
                findings.append(("SIG","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",
                    "no 'window.WAGE_DATA' assignment outside the header comment: the file "
                    "will not define WAGE_DATA at runtime"))
            # try a real JS parse when node is available (definitive)
            import shutil as _sh, subprocess as _sp
            _node = _sh.which("node")
            if _node:
                _chk = _sp.run([_node, "-e",
                    "const fs=require('fs'),vm=require('vm');const s=fs.readFileSync(process.argv[1],'utf8');"
                    "const c={window:{}};vm.createContext(c);new vm.Script(s).runInContext(c);"
                    "if(!c.window.WAGE_DATA||!c.window.WAGE_DATA.occupations)throw new Error('WAGE_DATA not set');",
                    js_p[0]], capture_output=True, text=True, timeout=30, encoding="utf-8", errors="replace")
                if _chk.returncode != 0:
                    _msg = (_chk.stderr or _chk.stdout or "").strip().splitlines()
                    _msg = _msg[-1] if _msg else "unknown JS parse/run error"
                    findings.append(("SIG","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",
                        f"file does not parse/run as JavaScript: {_msg[:160]}"))
        except Exception as _e:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",f"JS validity check error: {_e}"))
        try:
            jm=_re.search(r"window\.WAGE_DATA\s*=\s*(\{.*\})\s*;",open(js_p[0],encoding="utf-8").read(),_re.S)
            if jm:
                jd=json.loads(jm.group(1))
                jo={o.get("soc"):o.get("national_p25") for o in jd.get("occupations",[])}
                Jo={o.get("soc"):o.get("national_p25") for o in d.get("occupations",[])}
                mm=sum(1 for s in Jo if jo.get(s)!=Jo[s])
                if mm: findings.append(("MIN","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",f"JS/JSON p25 parity: {mm} occupation mismatches"))
                jr={r.get("id"):r.get("factor") for r in jd.get("regions",[])}
                Jr={r.get("id"):r.get("factor") for r in d.get("regions",[])}
                rmm=sum(1 for s in Jr if jr.get(s)!=Jr[s])
                if rmm: findings.append(("MIN","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",f"JS/JSON factor parity: {rmm} region mismatches"))
                # thresholds parity (v3.7.743): the JS must carry the same Direction F
                # thresholds as the source JSON, and must not be missing them.
                _jthr=jd.get("metadata",{}).get("thresholds",{}).get("direction_f_thresholds")
                _Jthr=d.get("metadata",{}).get("thresholds",{}).get("direction_f_thresholds")
                if _Jthr is not None and _jthr is None:
                    findings.append(("SIG","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",
                        "generated JS is MISSING metadata.thresholds.direction_f_thresholds that is present "
                        "in the source JSON — regeneration dropped it (the exact failure that broke the calculator)"))
                elif _jthr is not None and _Jthr is not None and list(_jthr)!=list(_Jthr):
                    findings.append(("SIG","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",
                        f"JS/JSON direction_f_thresholds mismatch: JS={_jthr} vs JSON={_Jthr}"))
            else:
                findings.append(("SIG","WAGE-DATA-INTEGRITY","wtpp-wage-data.js","WAGE_DATA object not found (file may be corrupt/empty)"))
        except Exception as e:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wtpp-wage-data.js",f"parse error: {e}"))
    # (h) the metadata.counts must be internally consistent AND match the actual data, so the
    # data-bound calculator prose (which renders these) can never state a self-contradictory
    # coverage figure. Verify the parts sum to the totals and match a live recount.
    _c=d.get("metadata",{}).get("counts",{})
    if _c:
        _ot=_c.get("occupations"); _rt=_c.get("regions")
        _op=(_c.get("real_bls_p25_occupations",0)+_c.get("unmatched_illustrative",0)
             +_c.get("bls_suppressed",0)+_c.get("flagged_soc_restructure",0))
        if _ot is not None and _op!=_ot:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wage_floor_data.json",
                f"occupation counts don't sum: real+illus+suppressed+flagged={_op} != {_ot}"))
        _rp=_c.get("regions_real_bls",0)+_c.get("regions_flagged",0)
        if _rt is not None and _rp!=_rt:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wage_floor_data.json",
                f"region counts don't sum: real+flagged={_rp} != {_rt}"))
        # live recount vs claimed
        _actual_occ=sum(1 for o in d.get("occupations",[]) if str(o.get("data_source","")).startswith("BLS_OEWS_May2025"))
        if _c.get("real_bls_p25_occupations") is not None and _actual_occ!=_c["real_bls_p25_occupations"]:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wage_floor_data.json",
                f"real_bls_p25_occupations={_c['real_bls_p25_occupations']} != actual {_actual_occ}"))
        _actual_reg=sum(1 for r in d.get("regions",[]) if r.get("has_regional_shard"))
        if _c.get("regions_real_bls") is not None and _actual_reg!=_c["regions_real_bls"]:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","wage_floor_data.json",
                f"regions_real_bls={_c['regions_real_bls']} != actual {_actual_reg}"))

    # (f) the wage calculator's coverage prose must be DATA-BOUND, not hardcoded. Coverage
    # counts drift every time the data changes; binding them to WAGE_DATA.metadata.counts via
    # data-wage-count spans keeps prose and data in lockstep. Flag any reintroduced hardcoded
    # "N of 866" / "N of 452" coverage number in the calculator source.
    calc_g=_g.glob(os.path.join(package_root,"06_Presentation_Materials","*Wage_Floor_Comparison_Calculator.html"))
    for cp in calc_g:
        try:
            ctxt=open(cp,encoding="utf-8").read()
            for mm in _re.finditer(r"\d{2,3}\s+of\s+(?:866|452)\b", ctxt):
                findings.append(("MIN","WAGE-DATA-INTEGRITY",cp,
                    f"hardcoded coverage count '{mm.group(0)}' - use a data-wage-count span bound to metadata.counts"))
        except Exception:
            pass

    # (g) wage docx coverage counts must not contradict the live data. docx prose cannot be
    # runtime-bound like the calculator HTML, so instead we flag any "<N> of 866" occupation
    # count or "<N> of 452" region count in the wage docs that disagrees with metadata.counts.
    real_occ=d.get("metadata",{}).get("counts",{}).get("real_bls_p25_occupations")
    real_reg=d.get("metadata",{}).get("counts",{}).get("regions_real_bls")
    if real_occ or real_reg:
        try:
            from docx import Document as _Doc
        except Exception:
            _Doc=None
        if _Doc:
            wage_docx=(_g.glob(os.path.join(package_root,"02_Vision_and_Communication","*Wage*.docx"))
                       +_g.glob(os.path.join(package_root,"06_Presentation_Materials","*Data_Sources*.docx")))
            for dp in wage_docx:
                if "_web_html" in dp: continue
                try:
                    full=" ".join(p.text for p in _Doc(dp).paragraphs)
                except Exception:
                    continue
                for mm in _re.finditer(r"(\d{2,3})\s+of\s+(?:the\s+)?866\b", full):
                    if real_occ and int(mm.group(1))!=real_occ:
                        findings.append(("MIN","WAGE-DATA-INTEGRITY",dp,
                            f"stale occupation count '{mm.group(0)}' (data says {real_occ} of 866)"))
                for mm in _re.finditer(r"(\d{2,3})\s+of\s+452\b", full):
                    if real_reg and int(mm.group(1))!=real_reg:
                        findings.append(("MIN","WAGE-DATA-INTEGRITY",dp,
                            f"stale region count '{mm.group(0)}' (data says {real_reg} of 452)"))

    # (e) data-archive MANIFEST checksums must match the files on disk (the checksummed-
    # snapshot promise: a reviewer can sha256 each file and match the manifest). Stale
    # checksums after a dataset regeneration would fail an external verification.
    import hashlib as _hl
    man_glob=_g.glob(os.path.join(package_root,"_data_archive","*","MANIFEST.json"))
    for man_p in man_glob:
        try:
            man=json.load(open(man_p,encoding="utf-8"))
            base=os.path.dirname(man_p)
            for fn,meta in man.get("files",{}).items():
                fp=os.path.join(base,fn)
                if not os.path.exists(fp):
                    findings.append(("MIN","WAGE-DATA-INTEGRITY",man_p,f"manifest file missing on disk: {fn}"))
                    continue
                claimed=meta.get("sha256")
                if claimed:
                    _h=_hl.sha256()
                    with open(fp,"rb") as _f:
                        for _c in iter(lambda:_f.read(65536),b""): _h.update(_c)
                    if _h.hexdigest()!=claimed:
                        findings.append(("MIN","WAGE-DATA-INTEGRITY",man_p,f"stale checksum for {fn} (manifest != file)"))
        except Exception:
            pass

    # (c) shard index vs region flags
    idx_p=os.path.join(package_root,"_wage_regional","index.json")
    if os.path.exists(idx_p):
        try:
            idx=json.load(open(idx_p,encoding="utf-8"))
            idx_regs=set(idx.get("regions",{}).keys())
            flagged_has=set(r.get("id") for r in d.get("regions",[]) if r.get("has_regional_shard"))
            if idx_regs!=flagged_has:
                findings.append(("MIN","WAGE-DATA-INTEGRITY","_wage_regional/index.json",
                    f"shard index ({len(idx_regs)}) != regions has_regional_shard ({len(flagged_has)})"))
            # spot: does each indexed shard file exist?
            missing=sum(1 for rid in idx_regs if not os.path.exists(os.path.join(package_root,"_wage_regional",rid+".json")))
            if missing:
                findings.append(("SIG","WAGE-DATA-INTEGRITY","_wage_regional",f"{missing} indexed shards missing on disk"))
        except Exception as e:
            findings.append(("MIN","WAGE-DATA-INTEGRITY","_wage_regional/index.json",f"parse error: {e}"))
    return list(dict.fromkeys(findings))


def check_readme_stale_version_DUMMY():pass

def check_factual_coverage(package_root="."):
    """P2.1l (FACTUAL-COVERAGE, MIN): factual_anchors.json registers load-bearing non-$/% facts
    (years, report vintages) tied to a source. For each anchor, scan documents/slideshows/pages
    for any `stale` value; if it appears with a context_term nearby and no exclude_term, flag it -
    a document still carrying a superseded fact in the anchor's context. Makes data refreshes
    guard-assisted (e.g. the SSA 2033->2032 refresh): update the anchor, the guard finds any miss."""
    import glob as _g, json as _j, subprocess as _sp, re as _re
    findings=[]
    ap=[x for x in _g.glob(os.path.join(package_root,"**","factual_anchors.json"),recursive=True) if "_web_html" not in x]
    if not ap: return findings
    try: anchors=_j.load(open(ap[0],encoding="utf-8")).get("anchors",[])
    except Exception: return findings
    if not anchors: return findings
    excl=("Package_Version","Open_Issues_Registry","OIR_Iteration_Archive","Open_Decisions","Conversation","Errata","Retrospective")
    files=[x for x in _g.glob(os.path.join(package_root,"**","*.docx"),recursive=True) if "_web_html" not in x and not any(e in x for e in excl)]
    files+=[x for x in _g.glob(os.path.join(package_root,"**","*.pptx"),recursive=True) if "_web_html" not in x]
    files+=[x for x in _g.glob(os.path.join(package_root,"**","*.html"),recursive=True) if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x]  # incl bots/ mirror pages, where generator drift surfaces
    def rd(p):
        try:
            if p.endswith(".docx"): return _sp.run(["pandoc","-t","plain",p],capture_output=True,text=True, encoding="utf-8", errors="replace",timeout=25).stdout
            if p.endswith(".pptx"):
                from pptx import Presentation
                return "\n".join(sh.text_frame.text for sl in Presentation(p).slides for sh in sl.shapes if sh.has_text_frame)
            return open(p,encoding="utf-8").read()
        except Exception: return ""
    for p in files:
        t=rd(p); low=t.lower()
        for a in anchors:
            cts=[c.lower() for c in a.get("context_terms",[])]; exs=[e.lower() for e in a.get("exclude_terms",[])]
            for sval in a.get("stale",[]):
                for m in _re.finditer(_re.escape(sval), t):
                    w=low[max(0,m.start()-80):m.end()+80]
                    if any(e in w for e in exs): continue
                    if any(c in w for c in cts):
                        findings.append(("MIN","FACTUAL-COVERAGE",os.path.basename(p),f"stale '{sval}' in {a['id']} context (current '{a['current']}'); update or add an exclude_term"))
                        break
    return list(dict.fromkeys(findings))


def check_derivations(package_root="."):
    """P2.1k (DERIVATION-TRACE, MIN): every registry figure carrying a `derivation` block must
    recompute from its input figures to its stated `expected` value and its own canonical - so a
    derived figure cannot silently diverge from the figures it is built from. Machine-checkable
    provenance chain for the derivable fiscal figures."""
    import glob as _g, json as _j
    findings=[]
    rp=[x for x in _g.glob(os.path.join(package_root,"**","figures_registry.json"),recursive=True) if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x]
    if not rp: return findings
    try: reg={e["id"]:e for e in _j.load(open(rp[0],encoding="utf-8"))["entries"]}
    except Exception: return findings
    def scalar(e, scenario=None):
        c=e.get("canonical",{})
        if isinstance(c,dict):
            if scenario and isinstance(c.get("by_scenario"),dict) and scenario in c["by_scenario"]: return c["by_scenario"][scenario]
            if "value" in c: return c["value"]
            if "low" in c and "high" in c: return (c["low"]+c["high"])/2
        return None
    for fid,e in reg.items():
        d=e.get("derivation")
        if not d: continue
        op=d.get("op"); total=None; ok=True
        if op=="signed_sum":
            total=0.0
            for inp in d.get("inputs",[]):
                ie=reg.get(inp.get("fig"))
                if ie is None: findings.append(("MIN","DERIVATION-TRACE",fid,f"input {inp.get('fig')} not in registry")); ok=False; break
                v=scalar(ie, inp.get("scenario"))
                if v is None: findings.append(("MIN","DERIVATION-TRACE",fid,f"input {inp.get('fig')} has no scalar value")); ok=False; break
                total+=inp.get("sign",1)*v
        elif op=="ratio":
            num=d.get("numerator",{}); den=d.get("denominator",{})
            ne=reg.get(num.get("fig")); de=reg.get(den.get("fig"))
            nv=scalar(ne,num.get("scenario")) if ne else None
            dv=scalar(de,den.get("scenario")) if de else None
            if nv is None or dv in (None,0): findings.append(("MIN","DERIVATION-TRACE",fid,"ratio inputs missing or zero denominator")); ok=False
            else: total=(nv/dv)*d.get("scale",1)
        else: continue
        if not ok or total is None: continue
        exp=d.get("expected"); own=scalar(e)
        if exp is not None and abs(total-exp)>max(0.01,abs(exp)*0.001):
            findings.append(("MIN","DERIVATION-TRACE",fid,f"recompute {total:g} != expected {exp} from inputs"))
        if own is not None and abs(total-own)>max(0.01,abs(own)*0.001):
            findings.append(("MIN","DERIVATION-TRACE",fid,f"recompute {total:g} != canonical {own}"))
    return findings


def check_numeric_coverage(package_root="."):
    """P2.1j (NUMERIC-COVERAGE): numeric_provenance_whitelist.json documents every scope
    carrying example/derivation values not individually source-linked. This gate (a) confirms
    each whitelist entry references valid registry figures [MIN if stale], and (b) flags a scope
    for RE-REVIEW [OBS] when any of its review_trigger figures has changed from the recorded
    snapshot - i.e. 'whitelisted to pass, but flagged when the values it depends on change.'"""
    import glob as _g, json as _j
    findings=[]
    wp=[x for x in _g.glob(os.path.join(package_root,"**","numeric_provenance_whitelist.json"),recursive=True) if "_web_html" not in x]
    rp=[x for x in _g.glob(os.path.join(package_root,"**","figures_registry.json"),recursive=True) if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x]
    if not (wp and rp): return findings
    try:
        wl=_j.load(open(wp[0],encoding="utf-8")); reg={e["id"]:e for e in _j.load(open(rp[0],encoding="utf-8"))["entries"]}
    except Exception: return findings
    for e in wl.get("entries",[]):
        scope=e.get("scope","?")
        for fid in e.get("review_triggers",[]):
            if fid not in reg:
                findings.append(("MIN","NUMERIC-COVERAGE",scope,f"whitelist references unknown figure {fid} (registry changed; refresh whitelist)"))
        snap=e.get("trigger_snapshot",{})
        for fid,val in snap.items():
            if fid in reg and reg[fid].get("canonical")!=val:
                findings.append(("OBS","NUMERIC-COVERAGE",scope,f"review needed: {fid} changed since snapshot; re-verify this scope's example values, then re-run build_numeric_whitelist.py RESNAPSHOT=1"))
    # coverage: every current doc/pptx/canonical scope must have been scanned into the whitelist
    scanned=set(wl.get("scanned_scopes",[]))
    if scanned:
        import glob as _g2
        excl=("Package_Version","Open_Issues_Registry","OIR_Iteration_Archive","Open_Decisions","Conversation","Errata","Retrospective")
        cur=[x for x in _g2.glob(os.path.join(package_root,"**","*.docx"),recursive=True) if "_web_html" not in x and not any(e in x for e in excl)]
        cur+=[x for x in _g2.glob(os.path.join(package_root,"**","*.pptx"),recursive=True) if "_web_html" not in x]
        for c in cur:
            rel=os.path.relpath(c,package_root)
            if rel not in scanned and c not in scanned and os.path.basename(c) not in {os.path.basename(x) for x in scanned}:
                findings.append(("MIN","NUMERIC-COVERAGE",os.path.basename(c),"new scope not in numeric whitelist; run tools/build_numeric_whitelist.py to classify its values"))
    return findings


def check_canonical_figures(package_root="."):
    """P2.1i (CANONICAL-FIGURE, MIN): dollar/scale values baked into canonical HTML/SVG
    illustrations must match their registry figures, so hand-coded illustration numbers
    cannot drift from the single source (as the counts had). Each mapping ties an SVG value
    to a registry figure; the guard derives the expected number from the registry and fails
    if the page no longer contains it."""
    import glob, re as _re
    findings=[]
    rp=[x for x in glob.glob(os.path.join(package_root,"**","figures_registry.json"),recursive=True) if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x]
    if not rp: return findings
    try: reg={e["id"]:e for e in json.load(open(rp[0],encoding="utf-8"))["entries"]}
    except Exception: return findings
    def rgetval(fid, path):
        e=reg.get(fid);
        if not e: return None
        c=e.get("canonical",{})
        for k in path: c=c.get(k) if isinstance(c,dict) else None
        return c
    # (page_substr, figure_id, value_path, [display variants as f-strings of v])
    MAP=[
      ("06_Platform_Architecture.html","FIG-healthcare-percapita-target",["value"], lambda v:[f"{v:,.0f}"]),
      ("index.html","FIG-fund-corpus-year60",["by_scenario","6pct"], lambda v:[f"{v:.0f}T",f"{v:.0f} trillion"]),
      ("06_Platform_Architecture.html","FIG-fund-corpus-year60",["by_scenario","6pct"], lambda v:[f"{v:.0f}T",f"{v:.0f} trillion"]),
      ("index.html","FIG-household-net-benefit",["representative"], lambda v:[f"{v:,.0f}",f"{v/1000:.0f}K"]),
      ("index.html","FIG-household-median-current-tax",["value"], lambda v:[f"{v:,.0f}"]),
      ("index.html","FIG-household-median-platform-tax",["value"], lambda v:[f"{v:,.0f}"]),
    ]
    from collections import defaultdict as _dd
    pages=_dd(list)
    for x in [x for x in glob.glob(os.path.join(package_root,"**","*.html"),recursive=True) if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x]:
        pages[os.path.basename(x)].append(x)
    for page,fid,path,fmt in MAP:
        plist=pages.get(page,[])
        if not plist: continue
        v=rgetval(fid,path)
        if v is None: continue
        variants=fmt(v)
        found=False
        for p in plist:
            try: t=open(p,encoding="utf-8").read()
            except Exception: continue
            if any(var in t for var in variants): found=True; break
        if not found:
            findings.append(("MIN","CANONICAL-FIGURE",page,f"{fid} value {v} (expected one of {variants}) not found in SVG; illustration may have drifted"))
    return list(dict.fromkeys(findings))


def check_canonical_counts(package_root="."):
    """P2.1h (CANONICAL-COUNT, MIN): count values baked into canonical HTML (open tracked
    issues; substantiation-document count) must match manifest/catalog, so marketing/SVG
    copy cannot drift from the data (as '29 open' and '109 documents' had). Data-driven by
    tools/build_canonical_counts.py; this gate catches any residual/hand-edited drift."""
    import glob, re as _re
    findings=[]
    mp=[x for x in glob.glob(os.path.join(package_root,"**","manifest.json"),recursive=True) if "_web_html" not in x]
    cp=[x for x in glob.glob(os.path.join(package_root,"**","platform_catalog.json"),recursive=True) if "_web_html" not in x]
    if not (mp and cp): return findings
    try:
        man=json.load(open(mp[0],encoding="utf-8")); cat=json.load(open(cp[0],encoding="utf-8"))
    except Exception: return findings
    tr=man.get("transparency",{}); op=tr.get("tracked_issues_open")
    pub=cat.get("publicDocuments") or cat.get("totalDocuments")
    pages=[x for x in glob.glob(os.path.join(package_root,"**","*.html"),recursive=True) if "_web_html" not in x and "_data_archive" not in x and "_downloads" not in x]
    for p in pages:
        try: t=open(p,encoding="utf-8").read()
        except Exception: continue
        for m in _re.finditer(r"\b(\d+)\s+open\b", t):
            w=t[max(0,m.start()-60):m.end()+60]
            if _re.search(r"issue|tracked|registry|documents|pillars|review", w, _re.I) and isinstance(op,int) and int(m.group(1))!=op:
                findings.append(("MIN","CANONICAL-COUNT",os.path.basename(p),f"'{m.group(1)} open' != manifest open {op} (stale)"))
        for m in _re.finditer(r"\b(\d+)\s+substantiation documents\b", t):
            # v3.7.713: skip historically-anchored characterizations (e.g. the Gemini
            # second-review description quoting what the reviewer saw "at v3.7.121") —
            # rewriting/flagging those against the CURRENT count would make a dated
            # historical record factually wrong. Anchor = explicit version reference
            # in the local window.
            w=t[max(0,m.start()-250):m.end()+250]
            if _re.search(r"at v3\.\d+\.\d+|\(v3\.\d+\.\d+\)", w):
                continue
            if isinstance(pub,int) and int(m.group(1))!=pub:
                findings.append(("MIN","CANONICAL-COUNT",os.path.basename(p),f"'{m.group(1)} substantiation documents' != publicDocuments {pub} (stale)"))
        # v3.7.727: also gate the platform-wide public-document count wherever it appears
        # in canonical prose. These are tightly-anchored to the specific platform-wide
        # phrasings so genuinely per-category counts (a bundle's "All N documents", a
        # pillar's "(N documents)") are never falsely flagged. "Browse all N documents"
        # links to the full browse page (platform_index.html) and IS the platform-wide
        # public count, so it is gated here too (it had drifted stale in 404.html).
        # Data-driven by tools/build_canonical_counts.py; this gate catches hand-edited drift.
        if isinstance(pub,int):
            _prose_pats=[
                r"consists of (\d+) documents organized",
                r"pillars\.\s*(\d+) documents\b",
                r"\b(\d+) across \w+ folders\b",
                r"All (\d+) documents in the We The People",
                r"Browse all (\d+) documents\b",
            ]
            for _pat in _prose_pats:
                for m in _re.finditer(_pat, t):
                    w=t[max(0,m.start()-250):m.end()+250]
                    if _re.search(r"at v3\.\d+\.\d+|\(v3\.\d+\.\d+\)", w):
                        continue
                    if int(m.group(1))!=pub:
                        findings.append(("MIN","CANONICAL-COUNT",os.path.basename(p),
                            f"'{m.group(0).strip()}' != publicDocuments {pub} (stale platform-wide count)"))
    return list(dict.fromkeys(findings))


def check_reviewer_doc_counts(package_root="."):
    """P2.1g (REVIEWER-COUNT, MIN): the Reviewer Recruitment Brief states the open/total
    tracked-issue counts in prose; any '<number-word> open' / '<number-word> tracked'
    phrase must match manifest.json, so the outreach brief cannot silently go stale as the
    registry changes. Same single-source discipline we apply to figures, for prose counts."""
    import glob, subprocess, re as _re
    findings=[]
    mp=[x for x in glob.glob(os.path.join(package_root,"**","manifest.json"),recursive=True) if "_web_html" not in x]
    bp=[x for x in glob.glob(os.path.join(package_root,"**","05_Reviewer_Recruitment_Brief.docx"),recursive=True) if "_web_html" not in x]
    if not (mp and bp): return findings
    try: man=json.load(open(mp[0],encoding="utf-8"))
    except Exception: return findings
    tr=man.get("transparency",{}); to=(man.get("totals",{}) or {}).get("tracked_issues",{})
    op=tr.get("tracked_issues_open", to.get("open"))
    tot=tr.get("tracked_issues_total", to.get("total"))
    if not (isinstance(op,int) and isinstance(tot,int)): return findings
    TENS={"twenty":20,"thirty":30,"forty":40,"fifty":50,"sixty":60,"seventy":70,"eighty":80,"ninety":90}
    UNITS={"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9}
    def parse(word):
        word=word.lower().strip()
        if "-" in word:
            t,u=word.split("-",1); return TENS.get(t,0)+UNITS.get(u,0)
        return TENS.get(word,0)
    try: txt=subprocess.run(["pandoc","-t","plain",bp[0]],capture_output=True,text=True, encoding="utf-8", errors="replace",timeout=25).stdout
    except Exception: return findings
    # open-count phrases: '<word> open' or '<word> remain open' or '<word> open items'
    for m in _re.finditer(r"\b((?:twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)(?:-(?:one|two|three|four|five|six|seven|eight|nine))?)\s+(?:remain\s+)?open\b", txt, _re.I):
        n=parse(m.group(1))
        if n and n!=op:
            findings.append(("MIN","REVIEWER-COUNT","05_Reviewer_Recruitment_Brief.docx",
                f"brief says '{m.group(1)} open' but manifest open count is {op} (stale)"))
    for m in _re.finditer(r"\b((?:twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)(?:-(?:one|two|three|four|five|six|seven|eight|nine))?)\s+tracked\b", txt, _re.I):
        n=parse(m.group(1))
        if n and n!=tot:
            findings.append(("MIN","REVIEWER-COUNT","05_Reviewer_Recruitment_Brief.docx",
                f"brief says '{m.group(1)} tracked' but manifest total is {tot} (stale)"))
    # de-duplicate
    return list(dict.fromkeys(findings))


def check_migration_log(package_root="."):
    """P2.1f (MIGRATION-LOG, MIN): keeps figure_migration_log.json honest -- every
    entry references a real registry figure, uses a valid terminal_state from the SOP
    vocabulary, and any DEFERRED entry records a reason. See FIGURE_MIGRATION_PROCESS.md."""
    findings=[]
    lp=os.path.join(package_root,"figure_migration_log.json")
    rp=os.path.join(package_root,"00_GUI_Files","figures_registry.json")
    if not (os.path.exists(lp) and os.path.exists(rp)): return findings
    try:
        log=json.load(open(lp,encoding="utf-8")); reg=json.load(open(rp,encoding="utf-8"))
    except Exception as e:
        return [("MIN","MIGRATION-LOG","figure_migration_log.json",f"parse error: {e}")]
    figids={e.get("id") for e in reg.get("entries",[])}
    figids|={r.get("id") for r in reg.get("retired_figures",[])}   # v3.8.699: a retired figure keeps its migration history
    VALID={"TOKENIZED-ANCHORED","TOKENIZED-BENCHMARKED","TOKENIZED-DERIVED","TOKENIZED-PENDING","DEFERRED-COLLISION","DEFERRED-UNSUBSTANTIATED","NOT-A-CANDIDATE","NO-DISPLAY"}
    for en in log.get("entries",[]):
        fid=en.get("figure_id")
        if fid not in figids:
            findings.append(("MIN","MIGRATION-LOG","figure_migration_log.json",f"entry '{fid}' is not a registry figure id"))
        if en.get("terminal_state") not in VALID:
            findings.append(("MIN","MIGRATION-LOG","figure_migration_log.json",f"entry '{fid}' invalid terminal_state '{en.get('terminal_state')}'"))
        if str(en.get("terminal_state","")).startswith("DEFERRED") and not (en.get("note") or en.get("disambiguation")):
            findings.append(("MIN","MIGRATION-LOG","figure_migration_log.json",f"DEFERRED entry '{fid}' records no reason"))
    return findings


def check_data_source_linkage(package_root="."):
    """P2.1e (DATA-SOURCE-LINK, MIN): every registry figure's source_id must resolve to a
    data_recency.json source; that source must list the figure back in feeds_figures
    (reciprocity); and every feeds_figures id must be a real registry figure. This makes each
    externally-sourced number traceable to a timestamped provenance record (value, URL,
    verified_on, vintage) and refreshable by documented process. See REFRESH_DATA_SOURCES.md."""
    findings = []
    rp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    dp = os.path.join(package_root, "data_recency.json")
    if not (os.path.exists(rp) and os.path.exists(dp)):
        return findings
    try:
        reg = json.load(open(rp, encoding="utf-8")); dr = json.load(open(dp, encoding="utf-8"))
    except Exception as e:
        return [("MIN", "DATA-SOURCE-LINK", "data_recency.json", f"parse error: {e}")]
    src = {s.get("id"): s for s in dr.get("sources", [])}
    figids = {e.get("id") for e in reg.get("entries", [])}
    for e in reg.get("entries", []):
        sid = e.get("source_id")
        if sid:
            if sid not in src:
                findings.append(("MIN", "DATA-SOURCE-LINK", "00_GUI_Files/figures_registry.json",
                    f"{e.get('id')} source_id '{sid}' not in data_recency.json"))
            elif e.get("id") not in (src[sid].get("feeds_figures") or []):
                findings.append(("MIN", "DATA-SOURCE-LINK", "data_recency.json",
                    f"source '{sid}' omits {e.get('id')} from feeds_figures (reciprocity)"))
    for s in dr.get("sources", []):
        for fid in (s.get("feeds_figures") or []):
            if fid not in figids:
                findings.append(("MIN", "DATA-SOURCE-LINK", "data_recency.json",
                    f"source '{s.get('id')}' feeds_figures '{fid}' is not a registry figure id"))
    # --- documented: required fields on every source record ---
    import datetime as _dt
    REQ = ("id", "name", "url", "cited_vintage", "verified_on", "feeds_figures")  # value optional (dataset sources)
    today = _dt.date.today()
    recheck = int(dr.get("recheck_days", 90) or 90)
    reg_by_id = {e.get("id"): e for e in reg.get("entries", [])}
    for s in dr.get("sources", []):
        sid = s.get("id", "<no-id>")
        for rf in REQ:
            if rf not in s or s.get(rf) in (None, ""):
                findings.append(("MIN", "DATA-SOURCE-FIELD", "data_recency.json",
                    f"source '{sid}' missing required field '{rf}'"))
        # accurate: verified_on is a valid ISO date, not in the future
        vo = s.get("verified_on")
        if vo:
            try:
                d0 = _dt.date.fromisoformat(str(vo))
                if d0 > today:
                    findings.append(("MIN", "DATA-SOURCE-DATE", "data_recency.json",
                        f"source '{sid}' verified_on '{vo}' is in the future"))
                elif (today - d0).days > recheck:
                    findings.append(("OBS", "DATA-SOURCE-STALE", "data_recency.json",
                        f"source '{sid}' verified_on '{vo}' is older than recheck_days ({recheck}); re-verify"))
            except ValueError:
                findings.append(("MIN", "DATA-SOURCE-DATE", "data_recency.json",
                    f"source '{sid}' verified_on '{vo}' is not a valid YYYY-MM-DD date"))
        # accurate: for a direct-anchor source, the fed figure's canonical value must equal the source value
        af = s.get("anchor_figure")
        if af and af in reg_by_id and isinstance(s.get("value"), (int, float)):
            can = reg_by_id[af].get("canonical", {})
            cv = can.get("value")
            if isinstance(cv, (int, float)):
                denom = abs(cv) or 1
                if abs(cv - s["value"]) / denom > 0.01:
                    findings.append(("MIN", "DATA-SOURCE-VALUE", "data_recency.json",
                        f"source '{sid}' value {s['value']} != anchored figure {af} canonical {cv}"))
    # documented: every 'anchored' registry figure must carry a source_id
    for e in reg.get("entries", []):
        if e.get("validation_status") == "anchored" and not e.get("source_id"):
            findings.append(("MIN", "DATA-SOURCE-COVERAGE", "00_GUI_Files/figures_registry.json",
                f"anchored figure {e.get('id')} has no source_id (no provenance record)"))
    return findings


AUDIT_FIGURE_TOKEN_PATTERN = r"\[\[FIG:[^\]]+\]\]"


def check_figure_tokens(package_root="."):
    """P2.1d (FIGURE-TOKEN-UNRESOLVED, MIN): after build_figure_tokens.py runs, no
    [[FIG:id]] token may remain in the rendered mirrors. A residual token means a
    dangling id (not in figures_registry with a narrative_example) or a build that
    skipped substitution -- either way prose would show raw markup. This is the
    enforcement half of the narrative-example lookup: tokenized prose cannot
    disagree with the lookup, and a bad token id cannot ship silently."""
    import glob as _glob
    findings = []
    # v3.8.226 (FIGURE-TOKEN-PATTERN, SIG): the builder must match exactly what this
    # check matches. Through v3.8.225 the builder's label class excluded '.', so
    # '[[FIG:...|4.28pct]]' was invisible to it: it reported zero unresolved while
    # this check raised MIN. Runs even when no mirror exists.
    try:
        import importlib.util as _ilu
        _bp = os.path.join(package_root, "tools", "build_figure_tokens.py")
        _spec = _ilu.spec_from_file_location("_bft_parity", _bp)
        _mod = _ilu.module_from_spec(_spec); _spec.loader.exec_module(_mod)
        _bpat = getattr(_mod, "TOKEN_PATTERN", None)
        if _bpat != AUDIT_FIGURE_TOKEN_PATTERN:
            findings.append(("SIG", "FIGURE-TOKEN-PATTERN", "tools/build_figure_tokens.py",
                f"token builder pattern {_bpat!r} differs from the audit's "
                f"{AUDIT_FIGURE_TOKEN_PATTERN!r}; tokens the audit flags can be "
                f"invisible to the builder"))
    except Exception as _e:
        findings.append(("SIG", "FIGURE-TOKEN-PATTERN", "tools/build_figure_tokens.py",
                         f"could not load the token builder to compare patterns: {_e}"))
    web = os.path.join(package_root, "_web_html")
    if not os.path.isdir(web):
        return findings
    tok = re.compile(AUDIT_FIGURE_TOKEN_PATTERN)
    for fp in _glob.glob(os.path.join(web, "**", "*.html"), recursive=True):
        hits = tok.findall(open(fp, encoding="utf-8").read())
        if hits:
            findings.append(("MIN", "FIGURE-TOKEN-UNRESOLVED", os.path.basename(fp),
                f"unresolved figure token(s): {sorted(set(hits))[:5]}"))
    return findings


def check_figures_registry(package_root="."):
    """P2.1a (FIGURE-REGISTRY-*, MIN): structural integrity of figures_registry.json,
    the canonical derived-figure registry. Verifies it parses; that every entry has the
    required fields, a valid kind and validation_status, and a canonical block whose shape
    matches its kind; that ids are unique and FIG-prefixed; and that every depends_on /
    scenario_assumption resolves to a real id in assumptions_registry.json (no second source
    of truth for input assumptions). Does NOT scan prose for agreement -- that is FIGURE-DRIFT
    (plan P2.1b). See AUDIT_SCOPE_AND_LIMITS.md.
    """
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(fp):
        return findings  # registry optional until populated
    try:
        reg = json.load(open(fp, encoding="utf-8"))
    except Exception as e:
        return [("MIN", "FIGURE-REGISTRY-UNPARSEABLE", "00_GUI_Files/figures_registry.json", f"could not parse: {e}")]

    # valid ASSUM ids from the assumptions registry (the single source of truth for inputs)
    valid_assum = set()
    ap = os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json")
    if os.path.exists(ap):
        try:
            valid_assum = {e.get("id") for e in json.load(open(ap, encoding="utf-8")).get("entries", [])}
        except Exception:
            pass

    valid_status = set(reg.get("validation_status_values", []))
    valid_kinds = {"scalar", "scenario", "range", "trajectory"}
    REQUIRED = ("id", "name", "category", "kind", "canonical", "source", "validation_status")
    seen = set()
    for e in reg.get("entries", []):
        eid = e.get("id", "<no-id>")
        for f in REQUIRED:
            if f not in e:
                findings.append(("MIN", "FIGURE-REGISTRY-FIELD", "00_GUI_Files/figures_registry.json",
                    f"entry {eid} missing required field '{f}'"))
        if not str(eid).startswith("FIG-"):
            findings.append(("MIN", "FIGURE-REGISTRY-FIELD", "00_GUI_Files/figures_registry.json",
                f"entry id '{eid}' must start with 'FIG-'"))
        if eid in seen:
            findings.append(("MIN", "FIGURE-REGISTRY-DUP-ID", "00_GUI_Files/figures_registry.json", f"duplicate id {eid}"))
        seen.add(eid)
        kind = e.get("kind")
        if kind not in valid_kinds:
            findings.append(("MIN", "FIGURE-REGISTRY-KIND", "00_GUI_Files/figures_registry.json",
                f"entry {eid} has invalid kind {kind!r}"))
        if e.get("validation_status") not in valid_status:
            findings.append(("MIN", "FIGURE-REGISTRY-STATUS", "00_GUI_Files/figures_registry.json",
                f"entry {eid} has invalid validation_status {e.get('validation_status')!r}"))
        c = e.get("canonical", {})
        if isinstance(c, dict):
            if kind == "scalar" and not ("value" in c and "unit" in c):
                findings.append(("MIN", "FIGURE-REGISTRY-CANONICAL", "00_GUI_Files/figures_registry.json",
                    f"entry {eid} (scalar) canonical needs value+unit"))
            if kind == "scenario":
                if not (isinstance(c.get("by_scenario"), dict) and c.get("by_scenario") and "unit" in c and c.get("scenario_assumption")):
                    findings.append(("MIN", "FIGURE-REGISTRY-CANONICAL", "00_GUI_Files/figures_registry.json",
                        f"entry {eid} (scenario) canonical needs unit+by_scenario+scenario_assumption"))
                elif c.get("scenario_assumption") not in valid_assum:
                    findings.append(("MIN", "FIGURE-REGISTRY-DANGLING", "00_GUI_Files/figures_registry.json",
                        f"entry {eid} scenario_assumption '{c.get('scenario_assumption')}' not in assumptions_registry"))
            if kind == "range":
                if not all(k in c for k in ("low", "high", "unit")):
                    findings.append(("MIN", "FIGURE-REGISTRY-CANONICAL", "00_GUI_Files/figures_registry.json",
                        f"entry {eid} (range) canonical needs low+high+unit"))
                elif c["low"] > c["high"]:
                    findings.append(("MIN", "FIGURE-REGISTRY-CANONICAL", "00_GUI_Files/figures_registry.json",
                        f"entry {eid} (range) low {c['low']} > high {c['high']}"))
            if kind == "trajectory" and not (isinstance(c.get("by_year"), dict) and c.get("by_year") and "unit" in c):
                findings.append(("MIN", "FIGURE-REGISTRY-CANONICAL", "00_GUI_Files/figures_registry.json",
                    f"entry {eid} (trajectory) canonical needs unit+by_year"))
        else:
            findings.append(("MIN", "FIGURE-REGISTRY-CANONICAL", "00_GUI_Files/figures_registry.json",
                f"entry {eid} canonical must be an object"))
        for dep in e.get("depends_on", []):
            if valid_assum and dep not in valid_assum:
                findings.append(("MIN", "FIGURE-REGISTRY-DANGLING", "00_GUI_Files/figures_registry.json",
                    f"entry {eid} depends_on '{dep}' not in assumptions_registry"))
        # P2.1c FIGURE-REGISTRY-NARRATIVE: narrative_example lookup integrity + pending-status discipline
        _nes = narrative_examples(e)
        for _ne in _nes:
            if not isinstance(_ne, dict):
                findings.append(("MIN", "FIGURE-REGISTRY-NARRATIVE", "00_GUI_Files/figures_registry.json",
                    f"entry {eid} narrative_example must be an object")); continue
            for _rf in ("value", "unit", "end", "rationale", "citation", "status"):
                if _rf not in _ne:
                    findings.append(("MIN", "FIGURE-REGISTRY-NARRATIVE", "00_GUI_Files/figures_registry.json",
                        f"entry {eid} narrative_example missing '{_rf}'"))
            _st = str(_ne.get("status", ""))
            if "pending" in _st.lower() and not re.search(r"(RESEARCH|METHOD|GUARD|PERSONA-SIG)-\d+", _st):
                findings.append(("MIN", "FIGURE-REGISTRY-NARRATIVE", "00_GUI_Files/figures_registry.json",
                    f"entry {eid} narrative_example status is 'pending' but cites no tracked item (RESEARCH-N/METHOD-N)"))
    return findings


FIGURE_DRIFT_EXCLUDE = ("Package_Version", "Open_Issues_Registry", "OIR_Iteration_Archive",
                        "Conversation_", "Open_Decisions_Registry")


def _live_catalog_docx(package_root):
    """Catalog .docx that are neither private nor a changelog/archive surface (which
    legitimately record superseded figures). Shared by FIGURE-DRIFT and the maintainer
    disagreement-scan tool."""
    out = []
    cat_path = os.path.join(package_root, "00_GUI_Files", "platform_catalog.json")
    try:
        cat = json.load(open(cat_path, encoding="utf-8"))
    except Exception:
        return out
    for d in cat.get("documents", []):
        p = d.get("path", "")
        if not p.endswith(".docx") or d.get("private"):
            continue
        if any(x in p for x in FIGURE_DRIFT_EXCLUDE):
            continue
        fp = os.path.join(package_root, p)
        if os.path.exists(fp):
            out.append(fp)
    return out


def _variant_regex(value, unit):
    import re as _re
    u = (unit or "").lower()
    vs = ("%g" % value).lstrip("-")
    if "trillion" in u:
        return _re.compile(r'\$?~?\s*' + _re.escape(vs) + r'\s*(?:trillion|T)\b', _re.I)
    if "billion" in u:
        return _re.compile(r'\$?~?\s*' + _re.escape(vs) + r'\s*(?:billion|B)\b', _re.I)
    try:
        commad = format(int(round(value)), ",")
        return _re.compile(r'\$?\s*' + _re.escape(commad) + r'\b')
    except Exception:
        return None


def check_figure_drift(package_root="."):
    """P2.1b (FIGURE-DRIFT, MIN): a figure value the maintainer has already RESOLVED in
    figures_registry.json (a known_variant with status RESOLVED -- a stale/incorrect value
    reconciled to canonical) must not reappear in any LIVE document (catalog .docx that are
    not private and not a changelog/archive surface). This permanently locks in every
    reconciliation, deterministically and with no false positives.

    Deliberately NARROW. Exhaustive cross-prose value extraction (does every appearance of
    every concept equal canonical?) is NOT an audit gate here: the P2.1b probe showed even the
    most distinctively-anchorable figures sit next to legitimately-different neighbouring values
    (current-vs-target, sensitivity cases, per-profile numbers), so an equality scan would be a
    false-positive generator. That proactive, judgement-laden scan lives in
    tools/figure_disagreement_scan.py as a human-in-the-loop advisory tool, per the blind-spots
    register. See AUDIT_SCOPE_AND_LIMITS.md.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(reg_path):
        return findings
    try:
        reg = json.load(open(reg_path, encoding="utf-8"))
    except Exception:
        return findings  # FIGURE-REGISTRY owns parse errors

    resolved = []  # (figure_id, value, unit, regex)
    for e in reg.get("entries", []):
        for kv in e.get("known_variants", []):
            if str(kv.get("status", "")).upper() == "RESOLVED" and "value" in kv:
                rx = _variant_regex(kv["value"], kv.get("unit", ""))
                if rx:
                    resolved.append((e["id"], kv["value"], kv.get("unit", ""), rx))
    if not resolved:
        return findings

    try:
        from docx import Document
    except Exception:
        return findings
    for fp in _live_catalog_docx(package_root):
        rel = fp.replace(package_root + os.sep, "")
        try:
            text = "\n".join(p.text for p in Document(fp).paragraphs)
        except Exception:
            continue
        for fid, val, unit, rx in resolved:
            if rx.search(text):
                findings.append(("MIN", "FIGURE-DRIFT", rel,
                    f"resolved/superseded value '{val} {unit}' (figure {fid}) reappears in a live "
                    f"document; it was reconciled to canonical and should not be restated here"))
    return findings


def check_sensitivity_parity(package_root="."):
    """P3.1 (SENSITIVITY-PARITY, MIN): enforces the platform's own stated honesty norm --
    the headline sovereign-fund figure should be presented alongside its conservative scenario,
    not as the sole quantitative case. Precisely scoped to avoid false positives: it fires only
    when a live document makes the FULL quantitative claim -- it asserts the 6% base-case fund
    value AND invokes the 6% real-return basis -- yet nowhere acknowledges the conservative (4% /
    Norway) scenario. A brief narrative mention of the fund figure that does not invoke the
    return basis is NOT a full quantitative claim and is intentionally not flagged.

    The base/conservative fund values are read from figures_registry.json (FIG-fund-corpus-year60),
    so the check stays in sync with the registry. Extension to other scenario figures is possible;
    the fund is the platform's flagship, explicitly-named sensitivity. See AUDIT_SCOPE_AND_LIMITS.md.
    """
    import re as _re
    findings = []
    # registry-grounded base/conservative fund values.
    # v3.8.280: THE FALLBACK USED TO BE 122 / 62.5 -- BOTH RETIRED. 122 was superseded by the
    # band at v3.8.233 and 62.5 was withdrawn entirely after it was found to reproduce only at
    # a 2.72 percent return. They were only a fallback, and the registry read overrides them,
    # but a check whose default is a pair of withdrawn numbers WILL SILENTLY ENFORCE THEM the
    # day the registry read fails. There is now no default: if the registry cannot be read the
    # check reports that and does not pretend to have run.
    base_v = cons_v = None
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if os.path.exists(reg_path):
        try:
            reg = json.load(open(reg_path, encoding="utf-8"))
            for e in reg.get("entries", []):
                if e.get("id") == "FIG-fund-corpus-year60":
                    bs = e.get("canonical", {}).get("by_scenario", {})
                    base_v = bs.get("6pct", base_v); cons_v = bs.get("4pct", cons_v)
        except Exception:
            pass
    if base_v is None or cons_v is None:
        return [("MIN", "SENSITIVITY-PARITY", "figures_registry.json",
                 "could not read FIG-fund-corpus-year60's 6pct/4pct scenarios, so the "
                 "sensitivity-parity check did not run. It has no hardcoded fallback by "
                 "design (v3.8.280): silence beats enforcing a retired value.")]

    base_pat = _re.compile(r'\$?\s*' + _re.escape("%g" % base_v) + r'\s*trillion', _re.I)
    basis6 = _re.compile(r'6\s*(?:%|percent)\s*real|6\s*(?:%|percent)[^.]{0,30}return', _re.I)
    ack4 = _re.compile(r'\$?\s*' + _re.escape("%g" % cons_v) + r'\s*trillion|\b4\s*(?:%|percent)\b|Norway|conservative scenario|parallel scenario', _re.I)

    try:
        from docx import Document
    except Exception:
        return findings
    for fp in _live_catalog_docx(package_root):
        rel = fp.replace(package_root + os.sep, "")
        try:
            text = "\n".join(p.text for p in Document(fp).paragraphs)
        except Exception:
            continue
        if base_pat.search(text) and basis6.search(text) and not ack4.search(text):
            findings.append(("MIN", "SENSITIVITY-PARITY", rel,
                f"states the ${'%g' % base_v}T fund figure on the 6% real-return basis but does not present "
                f"the conservative (4% / Norway, ~${'%g' % cons_v}T) scenario alongside it, contrary to the "
                f"platform's stated honest-range norm"))
    return findings


def check_source_baseline(package_root="."):
    """P3.2 (SOURCE-BASELINE-MISSING, MIN): the platform's LOAD-BEARING fiscal-derivation
    documents -- the ones whose numbers underpin everything else -- must remain traceable to a
    sources baseline: they must reference the derivation convention, a 'Sources Baseline', the
    data-sources-and-methodology document, or named canonical sources (IRS/CMS/BLS/CBO/Census...).

    Scoped to an explicit maintainer-curated designation rather than 'every numeric doc', because
    the P3.2 probe showed that applying the norm to all numeric-heavy documents over-reaches
    (narrative pieces, architectural framing, and even a hosting-setup reference contain numbers
    but are not derivation docs). This is therefore a regression guard on the designated set; the
    broader 'should this narrative doc also be sourced?' question is an editorial judgement left to
    the maintainer (see AUDIT_SCOPE_AND_LIMITS.md). Extend DESIGNATED as new load-bearing docs ship.
    """
    import re as _re
    DESIGNATED = [
        "05_Analytical_Framing/05_Federal_Fiscal_Impact_Analysis.docx",
        "05_Analytical_Framing/05_Sovereign_Fund_Governance_Design.docx",
        "05_Analytical_Framing/05_Per_Citizen_Benefits_and_Costs.docx",
        "05_Analytical_Framing/05_Combined_Reform_Model_Audit_Scope.docx",
        "05_Analytical_Framing/05_Sources_And_Derivation_Convention.docx",
        "05_Analytical_Framing/05_Federal_Income_Tax_Revenue_Modified_Architecture.docx",
        "05_Analytical_Framing/05_Refundable_Transition_Bridge_Credit.docx",
        "06_Presentation_Materials/06_Data_Sources_And_Methodology.docx",
        # v3.7.649: 14 numeric docs given an explicit sources baseline; now regression-guarded too.
        "05_Analytical_Framing/05_What_Changes_Milestones.docx",
        "05_Analytical_Framing/05_Repairing_The_Past.docx",
        "05_Analytical_Framing/05_Path_To_Reality.docx",
        "05_Analytical_Framing/05_Narrative_Example_100K_Tax_Comparison.docx",
        "05_Analytical_Framing/05_Civic_Infrastructure_Architectural_Framing.docx",
        "05_Analytical_Framing/05_Coalition_Mathematics.docx",
        "05_Analytical_Framing/05_Federal_Program_Integration_Plan.docx",
        "05_Analytical_Framing/05_Non_Citizens_And_Platform_Eligibility.docx",
        "05_Analytical_Framing/05_Public_Sector_Worker_Transitions.docx",
        "05_Analytical_Framing/05_TANF_And_Cash_Assistance.docx",
        "05_Analytical_Framing/05_US_Territories.docx",
        "05_Analytical_Framing/05_Climate_Policy_Beyond_Grid_Modernization.docx",
        "05_Analytical_Framing/05_Emergency_Services_Communications.docx",
        "05_Analytical_Framing/05_Federal_Infrastructure_Fee_Transition_Mechanics.docx",
    ]
    src = _re.compile(r'Sources_And_Derivation_Convention|Sources?\s+Baseline|Data_Sources_And_Methodology|canonical sources', _re.I)
    canon = _re.compile(r'\bIRS\b|\bCMS\b|\bBLS\b|\bCBO\b|Census|National Health Expenditure|Survey of Consumer Finances|\bSOI\b|derivation', _re.I)
    findings = []
    try:
        from docx import Document
    except Exception:
        return findings
    for rel in DESIGNATED:
        fp = os.path.join(package_root, rel)
        if not os.path.exists(fp):
            continue
        try:
            t = "\n".join(p.text for p in Document(fp).paragraphs)
        except Exception:
            continue
        if not (src.search(t) or canon.search(t)):
            findings.append(("MIN", "SOURCE-BASELINE-MISSING", rel,
                "load-bearing fiscal-derivation document no longer references the derivation "
                "convention / a sources baseline / named canonical sources; its numbers must stay traceable"))
    return findings


def _oir_status_map(package_root):
    """Map each tracked-item ID -> its OIR 'Current Status' cell text (first OIR table)."""
    import re as _re
    out = {}
    oir_path = os.path.join(package_root, "09_Meta_Tracking", "09_Open_Issues_Registry.docx")
    if not os.path.exists(oir_path):
        return out
    try:
        from docx import Document
        t = Document(oir_path).tables[0]
        hdr = [c.text.strip().lower() for c in t.rows[0].cells]
        sc = next((i for i, h in enumerate(hdr) if "status" in h), 2)
        for row in t.rows[1:]:
            cell0 = row.cells[0].text.strip()
            status = row.cells[sc].text.strip() if sc < len(row.cells) else ""
            for tok in _re.findall(r'\b(?:RESEARCH|COST|OPEN|GUARD)-\d+\b', cell0):
                out[tok] = status
    except Exception:
        pass
    return out


def check_falsifiability_drift(package_root="."):
    """P3.3 (FALSIFIABILITY-DRIFT, MIN): status parity between the Falsifiability Register and
    the Open Issues Registry. Every tracked item the register presents as a live falsifiable
    prediction must still be OPEN in the OIR; if the OIR has marked it resolved/closed/withdrawn/
    superseded, the register must acknowledge that resolution (carry resolution language near the
    id) rather than continuing to present a settled item as an open test.

    Deliberately NON-DUPLICATIVE: STALE-SECTION-47-REF already guards dangling references (a register
    id that no longer exists in the canonical Section-47 set) and TRACKED-ISSUES-COUNT-DRIFT guards
    the aggregate counts. This check adds the orthogonal guarantee that an item cannot be silently
    resolved out from under the register's epistemic commitments. It fires only on the primary drift
    direction (OIR-resolved but register-not-updated); 'register claims resolved while OIR still open'
    is left to human review as judgement-laden. See AUDIT_SCOPE_AND_LIMITS.md.
    """
    import re as _re
    findings = []
    reg_path = os.path.join(package_root, "05_Analytical_Framing", "05_Falsifiability_Register.docx")
    if not os.path.exists(reg_path):
        return findings
    try:
        from docx import Document
        reg_text = "\n".join(p.text for p in Document(reg_path).paragraphs)
    except Exception:
        return findings

    status_map = _oir_status_map(package_root)
    if not status_map:
        return findings
    resolved_lang = _re.compile(r'resolv|closed|confirmed|disconfirmed|superseded|withdrawn|settled|validated', _re.I)
    cited = list(_re.finditer(r'\b(?:RESEARCH|COST|OPEN|GUARD)-\d+\b', reg_text))
    for m in cited:
        cid = m.group(0)
        status = status_map.get(cid, "")
        if not status or status.upper().startswith("OPEN"):
            continue  # still open (or unknown) -> no parity obligation
        # OIR marks it resolved/closed: register must acknowledge near the citation
        window = reg_text[max(0, m.start() - 220):m.end() + 220]
        if not resolved_lang.search(window):
            findings.append(("MIN", "FALSIFIABILITY-DRIFT", "05_Analytical_Framing/05_Falsifiability_Register.docx",
                f"falsifiable item {cid} is no longer OPEN in the OIR (status: '{status[:40]}') but the "
                f"register still presents it as a live prediction without acknowledging the resolution"))
    return findings


def _served_html_files(package_root):
    """All served .html (GUI/nav layer + _web_html content pages), excluding build templates
    and work dirs. Used by LINK-FRAGMENT."""
    import glob as _glob
    out = []
    for h in [x for x in _glob.glob(os.path.join(package_root, "**", "*.html"), recursive=True) if "_data_archive" not in x]:   # v3.8.686: as the skip below, but visible to GLOB-RESOLVES-TO-ARCHIVE
        rp = os.path.relpath(h, package_root)
        if "/_templates/" in "/" + rp.replace(os.sep, "/") or rp.endswith("_template.html"):
            continue
        if rp.replace(os.sep, "/").startswith("_data_archive/"):   # v3.8.659: sealed sources are kept byte-identical, not served
            continue
        if re.match(r"v\d+_work", rp.split(os.sep)[0]):
            continue
        out.append(h)
    return out


def check_link_fragment(package_root="."):
    """P4.1 (LINK-FRAGMENT, MIN): every SAME-PAGE fragment link (href="#x") in a served HTML page
    must resolve to a static anchor (id="x" or name="x") in that same page. Catches broken
    in-page navigation and broken 'skip to main content' accessibility links.

    Deliberately scoped to SAME-PAGE fragments, which are deployment-independent and not subject
    to runtime anchor generation in this codebase (verified: the only broken same-page fragment
    was a single skip-link, since fixed). CROSS-PAGE links and fragments are intentionally NOT
    gated here: the P4.1 probe showed they carry heavy false-positive risk from site-root-absolute
    paths (/foo.html), the bots/ deployment mount, and JS-generated anchors (e.g. platform_index
    builds its audience-* anchors at runtime). That cross-page integrity is surfaced by the
    advisory tool tools/link_integrity_scan.py instead. See AUDIT_SCOPE_AND_LIMITS.md.
    """
    findings = []
    SKIP = {"", "top"}
    for h in _served_html_files(package_root):
        rp = os.path.relpath(h, package_root)
        try:
            s = open(h, encoding="utf-8", errors="replace").read()
        except Exception:
            continue
        ids = set(re.findall(r'\bid="([^"]+)"', s)) | set(re.findall(r'\bname="([^"]+)"', s))
        for frag in re.findall(r'href="#([^"]*)"', s):
            if frag.lower() in SKIP:
                continue
            if frag not in ids:
                findings.append(("MIN", "LINK-FRAGMENT", rp,
                    f'same-page link href="#{frag}" has no matching id/name anchor in the page'))
    return findings


def check_a11y(package_root="."):
    """P4.2 (A11Y-IMG-ALT / A11Y-LANG, MIN): two robust, deterministic accessibility invariants
    over served HTML --
      * every real <img> element carries an alt attribute (alt="" is valid for decorative images);
      * every page's <html> element declares a lang attribute.

    The <img> scan first strips HTML comments and <style>/<script> blocks, because the codebase's
    flag-background construct is DESCRIBED in a CSS comment that contains the literal text '<img>';
    a naive scan would otherwise report ~288 phantom images that are really comment text (the probe
    confirmed this). After stripping, the only real image per generated page is the decorative flag
    <picture>, which is aria-hidden and carries alt, so the check is clean.

    Two WCAG concerns are deliberately NOT gated here, per AUDIT_SCOPE_AND_LIMITS.md: colour-contrast
    ratios (depend on rendered CSS cascade and cannot be computed reliably from static markup) and
    heading-order skips (frequently a legitimate design choice; one internal reference page skips and
    is left to human judgement). These are documentation-grade limits, not deterministic invariants.
    """
    findings = []

    def strip_noise(s):
        s = re.sub(r'<!--.*?-->', '', s, flags=re.S)
        s = re.sub(r'<style\b[^>]*>.*?</style>', '', s, flags=re.S | re.I)
        s = re.sub(r'<script\b[^>]*>.*?</script>', '', s, flags=re.S | re.I)
        return s

    for h in _served_html_files(package_root):
        rp = os.path.relpath(h, package_root)
        try:
            s = open(h, encoding="utf-8", errors="replace").read()
        except Exception:
            continue
        mhtml = re.search(r'<html\b[^>]*>', s, re.I)
        if mhtml and not re.search(r'\blang\s*=', mhtml.group(0), re.I):
            findings.append(("MIN", "A11Y-LANG", rp, "<html> element has no lang attribute"))
        for tag in re.findall(r'<img\b[^>]*?/?>', strip_noise(s), re.I):
            if not re.search(r'\balt\s*=', tag, re.I):
                findings.append(("MIN", "A11Y-IMG-ALT", rp,
                    f'image element missing alt attribute: {tag[:80]}'))
    return findings


def _dryrun_tree_snapshot(package_root="."):
    """v3.8.226: path -> (size, mtime_ns) for the trees a web build can touch.
    Directories are recorded too, so a created-but-empty folder is caught."""
    snap = {}
    for top in ("_web_html",) + tuple(d for d in os.listdir(package_root)
                                      if d.startswith("0") and
                                      os.path.isdir(os.path.join(package_root, d))):
        base = os.path.join(package_root, top)
        if not os.path.exists(base):
            continue
        for root, dirs, files in os.walk(base):
            dirs[:] = [d for d in dirs if d != "__pycache__"]
            snap[os.path.relpath(root, package_root) + "/"] = ("dir", 0)
            for fn in files:
                fp = os.path.join(root, fn)
                try:
                    st = os.stat(fp)
                except OSError:
                    continue
                snap[os.path.relpath(fp, package_root)] = (st.st_size, st.st_mtime_ns)
    for fn in os.listdir(package_root):
        fp = os.path.join(package_root, fn)
        if fn.endswith(".html") and os.path.isfile(fp):
            st = os.stat(fp)
            snap[fn] = (st.st_size, st.st_mtime_ns)
    return snap


def check_mirror_stale(package_root="."):
    """P5.1 (MIRROR-STALE, OBS / advisory as of v3.7.656): detects drift between a source .docx and
    its served _web_html page. Catches the case where someone edits a document but forgets to rebuild
    the site, so the published page no longer reflects the source.

    ADVISORY, NOT A GATE: docx->HTML conversion is not byte-reproducible across environments/library
    versions, so running this on a machine other than the one that built the committed mirrors reports
    cosmetic differences (line endings, escaping) as CONTENT-CHANGED. It therefore emits a single OBS
    finding rather than per-page MIN findings, so it never false-blocks a cross-platform deploy gate.
    At ship time the mirrors are rebuilt immediately before auditing, so genuine edit-without-rebuild
    is still caught there (clean by construction).

    Implemented by driving the build's own content-comparison dry-run
    (build_web_html.py --refresh-content --dry-run), which re-splices each page's body from the
    current .docx and compares it to the committed page WITH VERSION STAMPS STRIPPED. This is why
    the check is content-based rather than mtime-based: the build itself documents that mtimes are
    unreliable for content sync (version bumps touch HTML mtimes), so only the stamp-stripped body
    comparison reliably distinguishes a genuinely stale page (CONTENT-CHANGED) from version-only or
    no-change pages. Any page the dry-run reports as CONTENT-CHANGED is flagged.

    Fail-open: if the builder is absent or errors, the check returns no findings rather than
    blocking a ship on a tooling hiccup (the ship pipeline rebuilds immediately before auditing, so
    this check is clean by construction there; its value is catching an edit-without-rebuild in any
    other invocation). See AUDIT_SCOPE_AND_LIMITS.md.
    """
    import subprocess as _sp, sys as _sys
    findings = []
    script = os.path.join(package_root, "build_web_html.py")
    if not os.path.exists(script):
        return findings
    # v3.8.226 (DRYRUN-WROTE, MIN): the dry run must leave the tree byte-identical.
    # Through v3.8.225 it wrote a full mirror whenever pages were missing, so this
    # read-only check created _web_html part-way through the gate and every check
    # that ran before it saw a different package from every check that ran after.
    # Proven on the planted case: the v3.8.225 builder, a tree with no mirror.
    _snap_before = _dryrun_tree_snapshot(package_root)
    try:
        r = _sp.run([_sys.executable, "build_web_html.py", "--refresh-content", "--dry-run"],
                    cwd=package_root, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=600)
        out = (r.stdout or "") + "\n" + (r.stderr or "")
    except Exception:
        return findings  # fail-open on tooling error
    _snap_after = _dryrun_tree_snapshot(package_root)
    if _snap_before != _snap_after:
        _added = sorted(set(_snap_after) - set(_snap_before))
        _gone = sorted(set(_snap_before) - set(_snap_after))
        _chg = sorted(k for k in set(_snap_before) & set(_snap_after)
                      if _snap_before[k] != _snap_after[k])
        findings.append(("MIN", "DRYRUN-WROTE", "build_web_html.py",
            f"build_web_html.py --refresh-content --dry-run modified the package: "
            f"{len(_added)} added, {len(_chg)} changed, {len(_gone)} removed "
            f"(first: {(_added + _chg + _gone)[:3]}). A dry run must write nothing; "
            f"every check after this point audited a different tree."))
    changed = []
    for line in out.splitlines():
        if "CONTENT-CHANGED" in line:
            toks = line.split()
            changed.append(toks[-1] if toks else line.strip())
    if changed:
        # v3.7.656: advisory (OBS), not a gate. The docx->HTML build is NOT
        # byte-reproducible across environments/library versions (line endings,
        # character escaping, python-docx version), so re-running the converter on
        # a different machine than the one that built the committed mirrors reports
        # cosmetic differences as CONTENT-CHANGED even when the content is identical.
        # This surfaced as 44 false "stale" findings inside the cross-platform deploy
        # gate while the same package audited 0/0/0 in its build environment. At ship
        # time the mirrors are rebuilt immediately before auditing, so a genuine
        # edit-without-rebuild is still caught there; emitting MIN here only produced
        # false deploy-blocking failures. Collapsed to a single advisory finding.
        findings.append(("OBS", "MIRROR-STALE", f"{len(changed)} page(s)",
            f"{len(changed)} served _web_html page(s) differ from a fresh rebuild in THIS "
            "environment. Advisory only: docx->HTML conversion is not byte-reproducible across "
            "machines/library versions, so a re-run away from the build environment flags cosmetic "
            "(not content) drift. If publishing from this environment, run: "
            "python3 build_web_html.py --refresh-content"))
    return findings


def check_doc_dup_paragraph(package_root="."):
    """DOC-DUP-PARAGRAPH (MIN): flags two consecutive non-blank paragraphs with identical text in a
    catalog .docx -- the accidental-duplication class (e.g. a programmatic insert that ran twice).
    Threshold: identical stripped text of at least 40 characters, which the probe showed catches the
    real cases (a duplicated changelog line) with no false positives from short repeated labels.
    Blank paragraphs between two identical ones do not suppress the match; a non-blank paragraph
    does (only truly consecutive duplicates flag). See AUDIT_SCOPE_AND_LIMITS.md.
    """
    findings = []
    MIN_LEN = 40
    cat_path = os.path.join(package_root, "00_GUI_Files", "platform_catalog.json")
    try:
        cat = json.load(open(cat_path, encoding="utf-8"))
    except Exception:
        return findings
    try:
        from docx import Document
    except Exception:
        return findings
    for d in cat.get("documents", []):
        rel = d.get("path", "")
        if not rel.endswith(".docx"):
            continue
        fp = os.path.join(package_root, rel)
        if not os.path.exists(fp):
            continue
        try:
            paras = [p.text.strip() for p in Document(fp).paragraphs]
        except Exception:
            continue
        prev = None
        for t in paras:
            if not t:
                continue
            if t == prev and len(t) >= MIN_LEN:
                findings.append(("MIN", "DOC-DUP-PARAGRAPH", rel,
                    f"two consecutive identical paragraphs (accidental duplication?): \"{t[:60]}...\""))
            prev = t
    return findings


def check_bot_mirror_link(package_root="."):
    """BOT-MIRROR-LINK (MIN): within the bot mirror subtree (bots/), every non-external
    link must resolve to a file or directory that exists on disk. The bots/ subtree is
    deliberately pure static HTML -- no JavaScript templating and no deployment routing --
    and is served at exactly its on-disk paths, so unlike the rest of the site its relative
    links ARE deterministically resolvable. This is the gate form of the advisory
    link-integrity tool, scoped to the one subtree where resolution is unambiguous; it would
    have caught the v3.7.651 defect (pillar pages linking to ../../ one level too shallow).
    Skips external URLs, fragments, query-only, javascript:/data:/mailto:/tel:, and any href
    containing { } (template placeholders). Absolute /paths resolve against the package root;
    relative paths against the linking file's directory. See AUDIT_SCOPE_AND_LIMITS.md.
    """
    findings = []
    href_re = re.compile(r'href\s*=\s*"([^"]+)"', re.I)
    bots_dir = os.path.join(package_root, "bots")
    if not os.path.isdir(bots_dir):
        return findings
    for fp in glob.glob(os.path.join(bots_dir, "**", "*.html"), recursive=True):
        try:
            s = open(fp, encoding="utf-8", errors="replace").read()
        except Exception:
            continue
        d = os.path.dirname(fp)
        for raw in href_re.findall(s):
            h = raw.strip()
            if (not h or h[0] == "#" or h.startswith(("mailto:", "tel:", "http://", "https://",
                    "//", "javascript:", "data:")) or "{" in h or "}" in h):
                continue
            h = h.split("#", 1)[0].split("?", 1)[0]
            if not h:
                continue
            base = package_root if h.startswith("/") else d
            tgt = os.path.normpath(os.path.join(base, h.lstrip("/") if h.startswith("/") else h))
            ok = os.path.isdir(tgt) if (h.endswith("/") or os.path.isdir(tgt)) else os.path.exists(tgt)
            if not ok:
                rel = os.path.relpath(fp, package_root)
                findings.append(("MIN", "BOT-MIRROR-LINK", rel,
                    f"link target does not exist on disk: \"{raw}\" -> {os.path.relpath(tgt, package_root)}"))
    return findings



def check_count_wordform(package_root="."):
    """COUNT-WORDFORM (SIG): a spelled-out numeral must not carry a tracked-issue count.

    tools/build_canonical_counts.py data-drives digit counts from manifest.json on every
    build, using r'\\b\\d+(\\s+open\\b)'. Digits are therefore owned and cannot drift.
    Spelled-out numerals are invisible to it. In v3.7.803 nineteen occurrences of
    "twenty-nine open" / "eighty-two tracked" were found across six pages while every page
    header correctly read 32 -- including three <meta> descriptions on recruit.html and six
    share-copy templates designed to be pasted onto other sites.

    SIG because the drift ran in the self-flattering direction: it understated the volume of
    open analytical work on a platform whose credibility rests on publishing exactly that.

    Fix is always the same: write the digit and let build_canonical_counts.py own it.
    """
    findings = []
    words = (r"twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety")
    ones = r"(?:one|two|three|four|five|six|seven|eight|nine)"
    wpat = re.compile(r"\b((?:%s)(?:-%s)?)\b" % (words, ones), re.I)
    cue = re.compile(r"open (?:item|question|analytical|opportunit)|tracked (?:analytical )?"
                     r"issue|items? (?:are )?flagged|remain open|registry-tracked|"
                     r"open analytical", re.I)
    for fp in sorted(glob.glob(os.path.join(package_root, "*.html"))):
        try:
            raw = open(fp, encoding="utf-8", errors="replace").read()
        except Exception:
            continue
        for m in wpat.finditer(raw):
            window = raw[max(0, m.start() - 260):m.end() + 260]
            window = re.sub(r"<[^>]+>", " ", window)
            if cue.search(window):
                findings.append(("SIG", "COUNT-WORDFORM", os.path.basename(fp),
                    f"spelled-out count \"{m.group(1)}\" sits next to a tracked-issue cue; "
                    f"build_canonical_counts.py cannot own a word. Write the digit."))
    return findings







def check_versionlog_orphan_entry(package_root="."):
    """VERSIONLOG-ORPHAN (MIN): a log entry for a version that never shipped.

    Added v3.8.167. VERSIONLOG.txt carried entries for BOTH v3.8.165 and v3.8.166
    describing the same double-conversion fix, with different narratives. No
    package was ever built as 3.8.165: version.json, manifest.json, the registry
    stamps and the README all said 3.8.166. THE SAME WORK WAS RECORDED TWICE.

    I then reported 'v3.8.165' to the author twice while the package said
    otherwise. A version log that records one fix under two numbers is the same
    class of defect as the version sweep fixed at v3.8.144: THE RECORD NO LONGER
    DESCRIBES WHAT HAPPENED.

    THE TEST. Every VERSION heading in the log must be either the current
    platform version, or lower than it, or explicitly marked RETRACTED. A heading
    at or above the current version that is not a retraction is an entry for a
    release that did not happen.

    This cannot catch a duplicate written for a version BELOW the current one --
    the shipped release moves on and both look historical. What it does catch is
    the case that actually occurred: an entry written, the bump run twice, and the
    superseded entry left behind at the version the package never carried.
    """
    import json as _j
    import re as _re
    findings = []
    lp = os.path.join(package_root, "VERSIONLOG.txt")
    vp = os.path.join(package_root, "version.json")
    if not (os.path.exists(lp) and os.path.exists(vp)):
        return findings
    try:
        cur = _j.load(open(vp, encoding="utf-8")).get("platform_version")
        text = open(lp, encoding="utf-8", errors="ignore").read()
    except Exception:
        return findings
    if not cur:
        return findings

    def key(v):
        try:
            return tuple(int(x) for x in v.split("."))
        except ValueError:
            return (0,)

    curk = key(cur)
    for m in _re.finditer(r"^VERSION\s+(\d+\.\d+\.\d+)\s*(.*)$", text, _re.M):
        ver, rest = m.group(1), m.group(2)
        if key(ver) <= curk:
            continue
        if "RETRACT" in rest.upper():
            continue
        findings.append((
            "MIN", "VERSIONLOG-ORPHAN", ver,
            f"VERSIONLOG carries an entry for {ver} but the package is {cur}. No release exists "
            f"at that version. Either the bump did not complete or the same work was recorded "
            f"twice. Mark the entry RETRACTED and preserve its text, as v3.8.165 was."))
    return findings







def check_generated_text_overwrote_authored(package_root="."):
    """GENERATED-OVERWROTE-AUTHORED (MIN): a generator replacing written analysis.

    Added v3.8.185. At v3.8.184 a criticality generator was introduced to fix one
    false statement -- "a factor of -0.5", a ratio across zero -- and it
    REGENERATED 24 ENTRIES, OVERWRITING 21 HAND-WRITTEN CRITICALITIES.

    ASSUM-existing-programs-absorbed went from a paragraph explaining that the
    half-trillion gap had been closed and 0.05T of spread remained, to "a factor
    of 1.0": arithmetically true and saying nothing.

    THE FIX WAS WORSE THAN THE DEFECT for twenty of the twenty-one.

    THIS IS THE THIRD OCCURRENCE OF ONE SHAPE. The version sweep at v3.8.144
    rewrote historical stamps. The triage write path at v3.8.146 destroyed the
    key its own read fix depended on. This overwrote authored prose. Each time a
    write path ran over content it did not author, and each time nothing checked.

    The check is narrow and cheap: an entry marked as generated whose text
    matches the generator's own template, where the entry ALSO carries a
    substantive `basis`, is a generated sentence sitting where written analysis
    belongs. A GENERATED SENTENCE IS A FLOOR, NOT A CEILING.
    """
    import json as _j
    import re as _re
    findings = []
    ap = os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json")
    if not os.path.exists(ap):
        return findings
    try:
        rows = _j.load(open(ap, encoding="utf-8")).get("entries") or []
    except Exception:
        return findings
    TEMPLATE = _re.compile(
        r"^The published figure spans .* Any reader quoting a single number", _re.S)
    for x in rows:
        if not x.get("criticality_generated"):
            continue
        crit = (x.get("criticality") or "").strip()
        if not TEMPLATE.match(crit):
            continue
        if len(str(x.get("basis") or "")) < 200:
            continue          # nothing richer was displaced
        findings.append((
            "MIN", "GENERATED-OVERWROTE-AUTHORED", x.get("id", "?"),
            f"carries generated criticality over a basis of {len(str(x.get('basis')))} characters. "
            f"A generator should FILL AN EMPTY FIELD, NOT REPLACE A WRITTEN ONE. Restore the "
            f"authored text or reconstruct it from the surviving basis."))
    return findings


def check_glob_resolves_to_archive(package_root="."):
    """GLOB-RESOLVES-TO-ARCHIVE (MIN): a check reading a sealed copy, not the live file.

    Added v3.8.188. At v3.8.187 four checks globbed for figures_registry.json and
    took the first match -- the SEALED v3.8.85 REFERENCE added at v3.8.144 to
    recover from a corruption. They had been validating against an August
    snapshot for 42 releases, hiding two stale derivation expectations and a
    stale value on two reader-facing pages.

    THAT WAS FIXED BY EDITING FOUR FILTERS. THIS CLOSES THE CLASS INSTEAD.

    It parses this file for every recursive glob, resolves each against the live
    package, and fails if the FIRST match -- which is what `rp[0]` takes -- lands
    inside an archived or downloadable copy.

    IT CHECKS RESOLUTION, NOT SHAPE. Of the 25 recursive globs at v3.8.187, 22
    lacked the archive exclusion and only ONE target resolved to an archived copy.
    A gate on shape would have produced 22 findings and 21 of them noise; a gate
    on resolution produces only the ones that are actually wrong.

    Exposure survives even where no check globs today: assumptions_registry.json,
    version.json, data_recency.json and README.txt all have archived twins, and
    README.txt sorts correctly ONLY BY PATH ORDERING, not by guarantee.
    """
    import glob as _g
    import re as _re
    findings = []
    # WIDENED TO tools/ AT v3.8.189, after measuring rather than assuming.
    # I had held this back saying "many of those 411 scripts are one-offs" as
    # though the noise risk came from volume. IT DOES NOT: only 8 of 406 tools
    # contain a recursive glob, 10 sites in total, and ZERO would fire.
    #
    # But zero is LUCK, NOT SAFETY. NOT ONE tool glob excludes _data_archive.
    # They resolve live because the archive happens to hold few .docx and .html
    # files -- a property of what has been sealed, not of the code. Seal one
    # .docx-heavy source and three scan tools start reading sealed copies.
    sources = [os.path.join(package_root, "audit_script.py")]
    sources += sorted(_g.glob(os.path.join(package_root, "tools", "*.py")))
    src = ""
    for sp in sources:
        if not os.path.exists(sp):
            continue
        try:
            src += "\n" + open(sp, encoding="utf-8", errors="ignore").read()
        except Exception:
            continue
    if not src:
        return findings

    SHIELDED = ("_data_archive", "_downloads", "_web_html")
    # Every recursive glob against package_root, whatever the module alias.
    # THE FILTER MATTERS AS MUCH AS THE TARGET. A first draft of this gate
    # resolved each target WITHOUT the exclusions its own comprehension applies,
    # and flagged figures_registry.json -- whose glob had been fixed one release
    # earlier and already excludes the archive. A gate that ignores the guard it
    # is checking reports the fix as the defect.
    # TWO IDIOMS, v3.8.189. The tools use both os.path.join(root,"**",t) and the
    # bare "**/t" form. A measurement caught both; the first version of this
    # pattern matched only the former, so WIDENING WITHOUT EXTENDING IT WOULD
    # HAVE GIVEN FALSE CONFIDENCE -- the same failure this gate's draft already
    # made once by ignoring each glob's own filter.
    pat = _re.compile(
        r'\.glob\(\s*os\.path\.join\(\s*[a-z_]*root[a-z_]*\s*,\s*"\*\*"\s*,\s*'
        r'"([^"]+)"\s*\)\s*,\s*recursive=True\s*\)\s*(?:if\s+([^\]]{0,300}))?'
        r'|'
        r'\.glob\(\s*[\'"]\*\*/([^\'"]+)[\'"]\s*,\s*recursive=True\s*\)\s*(?:if\s+([^\]]{0,300}))?')
    # v3.8.686 (#5071): THE BARE "**/t" IDIOM NOW CARRIES ITS FILTER TOO. It was matched without one, so a glob that
    # excluded the archive in its own comprehension was judged as if it did not -- invisible while the disk listed live
    # files first, a false MIN under the opposite order (shown by sorting sealed copies first).
    seen = set()
    for _a, filt, _b, filt2 in pat.findall(src):
        target = _a or _b
        filt = filt or filt2
        key = (target, filt.strip())
        if key in seen:
            continue
        seen.add(key)
        # Apply the same exclusions the comprehension applies.
        excl = [s for s in ("_web_html", "_data_archive", "_downloads") if s in filt]
        if "_web_html" not in excl:
            excl.append("_web_html")
        matches = [x for x in _g.glob(os.path.join(package_root, "**", target), recursive=True)
                   if not any(s in x for s in excl)]
        if not matches:
            continue
        first = matches[0]
        shield = next((s for s in SHIELDED if s in first), None)
        if not shield:
            # SECOND CONDITION, v3.8.189. First-match resolution is not the only
            # failure. tools/check_color_accessibility.py globs "*.xlsx" and
            # iterates ALL matches -- 72 of 100 of which are archived. It does
            # not MISRESOLVE, so the rule above cannot see it; it just scans 72
            # sealed workbooks it has no reason to read.
            #
            # Reported as OBS, not MIN: scanning extra files is wasteful rather
            # than incorrect, and a wasteful glob that is one sealing away from
            # a correctness problem is worth seeing without failing a build.
            arch = [x for x in matches if "_data_archive" in x]
            if matches and len(arch) > len(matches) / 2:
                findings.append((
                    "OBS", "GLOB-MOSTLY-ARCHIVED", target,
                    f"a recursive glob for {target!r} matches {len(matches)} files of which "
                    f"{len(arch)} are inside _data_archive. It resolves live only because it "
                    f"iterates every match; a variant taking the first would read a sealed copy."))
            continue
        live = [x for x in matches if not any(s in x for s in SHIELDED)]
        findings.append((
            "MIN", "GLOB-RESOLVES-TO-ARCHIVE", target,
            f"a recursive glob for {target!r} resolves FIRST to {first} -- inside {shield}. "
            f"A check taking the first match reads a sealed or downloadable copy instead of "
            f"{live[0] if live else 'the live file'}. Exclude {shield} in that filter."))
    return findings


def check_ratio_across_zero(package_root="."):
    """RATIO-ACROSS-ZERO (MIN): a stored factor whose endpoints differ in sign.

    Added v3.8.184. ASSUM-deficit-impact printed "a factor of -0.5" to readers on
    the assumptions page. That is 0.3 / -0.6: A RATIO ACROSS ZERO, UNDEFINED. It
    is not a small factor, it is a meaningless one.

    ONE ENTRY WHEN THIS WAS WRITTEN. The check exists because the sentence was
    STORED rather than generated, so nothing recomputed it when the range was
    registered, and the same defect would appear for any future range that
    straddles zero.

    The generator added at v3.8.184 no longer produces this, but a stored
    criticality can still be written by hand into the registry, which is what this
    guards.
    """
    import json as _j
    import re as _re
    findings = []
    ap = os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json")
    if not os.path.exists(ap):
        return findings
    try:
        rows = _j.load(open(ap, encoding="utf-8")).get("entries") or []
    except Exception:
        return findings
    for x in rows:
        r = x.get("range") or {}
        lo, hi = r.get("low"), r.get("high")
        crit = str(x.get("criticality") or "")
        if lo is None or hi is None:
            continue
        if not (lo < 0 < hi):
            continue
        if _re.search(r"factor of\s*-?[\d.]+", crit):
            findings.append((
                "MIN", "RATIO-ACROSS-ZERO", x.get("id", "?"),
                f"range is {lo} to {hi}, which crosses zero, but its criticality reports a "
                f"factor. A RATIO BETWEEN ENDPOINTS OF OPPOSITE SIGN IS UNDEFINED. State that "
                f"the range crosses zero, or -- if the dependent figure is kind='scenario' -- "
                f"name the assumption the value is conditional on."))
    return findings


def check_termination_opened_the_artifact(package_root="."):
    """TERMINATION-WITHOUT-ARTIFACT (MIN): unreconstructible needs the file opened.

    Added v3.8.180, after FIG-deficit-mature-projected was labelled
    `unreconstructible` at v3.8.179 and rebuilt at v3.8.180 from the very archive
    it was declared unrebuildable from.

    THE TERMINATION WAS REACHED FROM THE MANIFEST LOCATOR, NOT THE ARTIFACT. The
    locator recorded the deficit shares from sheet 1 and stopped. The workbook has
    23 SHEETS: sheet 1 also carries the GDP level, and sheet 12 carries the price
    index. The chain ran cleanly through three sheets.

    THE LOCATOR WAS ACCURATE AND INCOMPLETE, and accuracy at the locator level
    said nothing about what the artifact contains.

    SUBSTANTIATION_PROGRAM.md permits termination -- "A terminated reconstruction
    is a completed P1 outcome, not a failed one, PROVIDED THE TERMINATION AND ITS
    EVIDENCE ARE RECORDED". This check enforces the proviso: the evidence must
    name the artifact, not the entry.

    A termination whose recorded reason names no file, sheet, table or page is a
    conclusion about a registry entry rather than about a source.
    """
    import json as _j
    import re as _re
    findings = []
    p = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(p):
        return findings
    try:
        rows = _j.load(open(p, encoding="utf-8")).get("entries") or []
    except Exception:
        return findings
    ARTIFACT = _re.compile(
        r"\.xlsx|\.pdf|\.csv|\.docx|\bsheet\b|\btable\b|\bpage\b|\bp\d+\b|\btab\b",
        _re.I)
    for e in rows:
        if e.get("substantiation") != "unreconstructible":
            continue
        evidence = " ".join(str(e.get(k) or "") for k in ("substantiation_note", "notes"))
        evidence += " " + str((e.get("reproducibility_test") or {}).get("how") or "")
        if ARTIFACT.search(evidence):
            continue
        findings.append((
            "MIN", "TERMINATION-WITHOUT-ARTIFACT", e.get("id", "?"),
            "is labelled 'unreconstructible' but its recorded evidence names no file, sheet, "
            "table or page. A termination reached from a registry entry or a manifest locator is "
            "not a termination: state which artifact was opened and what was looked for in it."))
    return findings


def check_cited_only_role(package_root="."):
    """CITED-ONLY-UNEXPLAINED (MIN): a source with no archive and no stated role.

    Added v3.8.178. SOURCE_RETRIEVAL_PLAN.md asks, of a source that feeds no
    figure, whether it is narrative support or an orphan to be removed -- and
    calls that "a decision, not a retrieval".

    Reviewing the six at v3.8.178 found A THIRD ANSWER THE PLAN DID NOT
    ANTICIPATE: entries that exist to DOCUMENT A GAP. norges-bank-fx records that
    a published USD figure cannot be rebuilt because no rate and date are held.
    ipeds-hd-directory records that a live source infers a field the directory
    publishes directly. swf-payout-rules bounds an assumption the register had no
    way to express.

    NONE OF THE SIX WAS AN ORPHAN. I recommended removing ipeds-hd-directory and
    WAS WRONG -- the recommendation came from reading its value field rather than
    its note, and removing it would have deleted a known weakness in another
    source.

    So the check does not ask whether a cited-only source should be removed. It
    asks that its ROLE BE STATED, because 'cited-only' had come to mean two
    different things: awaiting retrieval, and never intended for retrieval.
    """
    import json as _j
    findings = []
    p = os.path.join(package_root, "data_recency.json")
    if not os.path.exists(p):
        return findings
    try:
        rows = _j.load(open(p, encoding="utf-8")).get("sources") or []
    except Exception:
        return findings
    for s in rows:
        if s.get("archive_dir"):
            continue
        if s.get("feeds_figures"):
            continue          # awaiting retrieval: a different condition
        if (s.get("register_role") or "").strip():
            continue
        findings.append((
            "MIN", "CITED-ONLY-UNEXPLAINED", s.get("id", "?"),
            "is cited-only and feeds no figure, but states no register_role. Record what it is "
            "for -- bounds_assumption, documents_irreproducibility, "
            "documents_incomplete_archive, or narrative_context -- so 'cited-only' does not mean "
            "both 'awaiting retrieval' and 'never intended for retrieval'."))
    return findings


def check_declared_driver_reaches_nothing(package_root="."):
    """DRIVER-REACHES-NOTHING (MIN): a declared driver that moves no banded figure.

    Added v3.8.175, after the author asked whether the platform's Monte Carlo
    already handled the transition borrowing rate. IT DOES NOT, AND THE PROBLEM
    IS NOT LIMITED TO THAT ONE ASSUMPTION.

    32 assumptions declare monte_carlo_role 'driver' or 'sensitivity'. ONLY 9
    REACH A FIGURE THAT ACTUALLY RECEIVES A PROPAGATED BAND. The role label
    promises a connection that does not exist, and a reviewer changing a range
    and re-running would see nothing move.

    THREE DISTINCT CAUSES, and they need different fixes:

      no dependents listed                        4
      dependents are PROSE, not figure ids       10
      figure exists but has NO derivation block   9
      reaches a banded figure                     9

    The prose case is the most misleading: ASSUM-fund-real-return lists
    '60-year fund-balance projection' and 'bridge-financing sunset feasibility'
    -- readable, accurate, and unresolvable by any tool.

    The derivation case is the borrowing rate's: FIG-ss-sunset-peak-borrowing is
    a scalar from a spreadsheet with no component block, so propagation cannot
    enter it however well the assumption is wired.

    THIS CHECK DOES NOT DEMAND THAT EVERY ASSUMPTION PROPAGATE. Some genuinely
    cannot -- a value that comes whole from a model has no parts to sample. What
    it demands is that the ROLE LABEL NOT CLAIM OTHERWISE: an assumption that
    reaches nothing should say so in monte_carlo_role rather than assert 'driver'.
    """
    import json as _j
    findings = []
    fp = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    ap = os.path.join(package_root, "00_GUI_Files", "assumptions_registry.json")
    if not (os.path.exists(fp) and os.path.exists(ap)):
        return findings
    try:
        d = _j.load(open(fp, encoding="utf-8"))
        A = _j.load(open(ap, encoding="utf-8")).get("entries") or []
    except Exception:
        return findings
    E = {e["id"]: e for e in d.get("entries", []) if e.get("id")}
    banded = set((d.get("propagated_uncertainty") or {}).get("results") or {})
    if not banded:
        return findings

    for a in A:
        role = a.get("monte_carlo_role")
        if role not in ("driver", "sensitivity"):
            continue
        if "REACHES NOTHING" in str(a.get("propagation_note") or "").upper():
            continue
        deps = a.get("dependents") or []
        real = [x for x in deps if x in E]
        reach = False
        for x in real:
            if x in banded:
                reach = True
                break
            for b in banded:
                dv = (E.get(b) or {}).get("derivation") or {}
                comps = sum([v for k, v in dv.items() if isinstance(v, list)], [])
                # v3.8.279: DICT-FORM REFERENCES COUNT TOO. A derivation names a figure
                # either in a list (components_gross, inputs) or as a single dict --
                # {"fig": ..., "scenario": ...} for a ratio's numerator or denominator.
                # Reading only the list form made ASSUM-fund-real-return look like it
                # reached nothing, when FIG-fund-disbursements-mature is the numerator of
                # FIG-fund-coverage-share, a propagated result. THE WIRING WAS THERE AND THE
                # CHECK COULD NOT SEE IT.
                comps = comps + [v.get("fig") for v in dv.values()
                                 if isinstance(v, dict) and v.get("fig")]
                if x in comps:
                    reach = True
                    break
            if reach:
                break
        if reach:
            continue
        if not deps:
            why = "it lists no dependents"
        elif not real:
            why = "its dependents are prose descriptions, not figure ids"
        else:
            why = (f"its dependent figure(s) carry no derivation block, so propagation "
                   f"cannot enter them")
        findings.append((
            "MIN", "DRIVER-REACHES-NOTHING", a.get("id", "?"),
            f"declares monte_carlo_role {role!r} but reaches no figure that receives a "
            f"propagated band, because {why}. A reviewer changing this range and re-running "
            f"would see nothing move. Either connect it or record REACHES NOTHING and why "
            f"in propagation_note."))
    return findings


def check_duplicate_figures(package_root="."):
    """DUPLICATE-FIGURE (MIN): two entries for the same quantity, unconnected.

    Added v3.8.163, after FIG-household-median-savings and FIG-household-net-savings
    were found to be THE SAME QUANTITY UNDER TWO IDS. A convention change at
    v3.8.162 moved one and not the other, which is the only reason it surfaced.
    The first entry CARRIED NO NOTES AT ALL, so nothing connected them.

    A correction applied to one would have left the other stale, and neither would
    have flagged it. That is the same failure class as the version sweep and the
    triage overwrite: SILENT UNTIL SOMETHING MOVED.

    THE SIGNAL, chosen by measuring rather than guessing:

      same canonical VALUE  +  overlapping name tokens  +  no cross-reference

    Unit is deliberately NOT part of the key. The pair that prompted this check
    had DIFFERENT units -- 'USD/yr' against 'USD/household/yr' -- so a value+unit
    match would have missed the very case it exists to catch.

    Name-token overlap is what separates duplicates from coincidence. Measured on
    the live registry: three value collisions exist, and only one has overlapping
    tokens. FIG-new-revenue and FIG-civic-infrastructure-gap both sit at 3.6;
    FIG-housing-net-new and FIG-education-absorbed both sit at 75. Neither pair
    shares a name token and neither is a duplicate.

    A CROSS-REFERENCE CLEARS THE FINDING. Two entries that name each other -- in
    notes, derived_from or depends_on -- are a deliberate relationship, not a
    duplication, and the check says so rather than nagging.
    """
    import json as _j
    import re as _re
    import collections as _c
    findings = []
    p = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(p):
        return findings
    try:
        rows = _j.load(open(p, encoding="utf-8")).get("entries") or []
    except Exception:
        return findings

    STOP = {"the", "of", "a", "net", "new", "total", "fund", "fig"}

    def toks(fid):
        return set(_re.split(r"[-_]", fid.replace("FIG-", ""))) - STOP

    by = _c.defaultdict(list)
    for e in rows:
        v = (e.get("canonical") or {}).get("value")
        # 0, 1 and 100 collide for structural reasons (shares, percentages) and
        # carry no signal.
        if isinstance(v, (int, float)) and v not in (0, 1, 100):
            by[v].append(e)

    for v, group in by.items():
        if len(group) < 2:
            continue
        for i in range(len(group)):
            for j in range(i + 1, len(group)):
                a, b = group[i], group[j]
                shared = toks(a["id"]) & toks(b["id"])
                if not shared:
                    continue
                aj, bj = _j.dumps(a), _j.dumps(b)
                if b["id"] in aj or a["id"] in bj:
                    continue          # they reference each other: deliberate
                findings.append((
                    "MIN", "DUPLICATE-FIGURE", f"{a['id']} / {b['id']}",
                    f"both carry canonical value {v} and share the name token(s) "
                    f"{sorted(shared)}, and NEITHER REFERENCES THE OTHER. If they are the same "
                    f"quantity, a correction to one will leave the other stale silently. Either "
                    f"cross-reference them or record why they are distinct."))
    return findings


def check_test_result_without_reason(package_root="."):
    """TEST-RESULT-UNEXPLAINED (MIN): a FAIL must say why, beside the result.

    Added v3.8.154, after the author asked whether the platform already held
    answers I had described as missing. IT DID, for two of them -- and I had not
    seen it because BOTH CARRIED A `result` WITH AN EMPTY `how`.

    FIG-civic-infrastructure-gap was resolved at v3.8.143 and the reason sits in
    its `retier` field: ASCE publishes 3.7, and the platform's 3.6 is a
    subtraction it performs itself. FIG-healthcare-percapita-baseline is
    explained in the cms-nhe source note: the 2023 vintage is a deliberate
    conservative choice. Neither was undiagnosed. BOTH READ AS UNDIAGNOSED.

    27 entries carry a result with no `how`. Most PASS, so the gap is invisible --
    which is precisely the danger: the next failure among them will read as
    unexamined work, and someone will redo an analysis that was already done.

    THIS CHECK IS NARROW ON PURPOSE. It fires only on a FAILING result with no
    reason, because that is the case where the absence actively misleads. A
    passing test that does not explain itself costs nothing today; a failing one
    costs the next person a day.
    """
    import json as _j
    findings = []
    p = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(p):
        return findings
    try:
        rows = _j.load(open(p, encoding="utf-8")).get("entries") or []
    except Exception:
        return findings
    for e in rows:
        rt = e.get("reproducibility_test") or {}
        res = str(rt.get("result") or "")
        if not res.upper().startswith("FAIL"):
            continue
        if (rt.get("how") or "").strip():
            continue
        findings.append((
            "MIN", "TEST-RESULT-UNEXPLAINED", e.get("id", "?"),
            f"result is '{res[:50]}' with an empty `how`. A failing test that does not say why "
            f"reads as undiagnosed even when the diagnosis exists elsewhere in the entry "
            f"(retier, notes) or in a source note. State it beside the result."))
    return findings


def check_triage_reclassification_preserved(package_root="."):
    """TRIAGE-RECLASSIFICATION-LOST (MIN): a hand reclassification must survive.

    Added v3.8.146, because the v3.8.145 fix for this SHIPPED NON-FUNCTIONAL AND
    WAS REPORTED AS WORKING.

    What happened: classify() was changed to honour a recorded reclassification
    before running its keyword heuristic. On the same run, the --write path
    REPLACED the whole triage dict -- destroying the `reclassified` key that the
    fix reads. A read-side fix is worthless when the write side overwrites its
    input, and nothing checked, so the package shipped with the bug intact and my
    summary said it was fixed.

    THE TEST: every figure carrying triage.reclassified must also carry the class
    that reclassification assigned, and that class must not be the one the
    heuristic would produce. If the marker is gone, or the class has reverted, a
    human judgement has been silently discarded.

    This is the smallest possible gate for the largest possible category: WORK
    THAT LOOKS DONE AND IS NOT.
    """
    import json as _j
    findings = []
    p = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(p):
        return findings
    try:
        rows = _j.load(open(p, encoding="utf-8")).get("entries") or []
    except Exception:
        return findings

    for e in rows:
        tr = e.get("triage") or {}
        if not tr:
            continue
        if tr.get("reclassified") and not tr.get("class"):
            findings.append((
                "MIN", "TRIAGE-RECLASSIFICATION-LOST", e.get("id", "?"),
                "carries triage.reclassified but no class -- the hand judgement was recorded "
                "and then partially overwritten"))
        # a reclassified entry whose meaning reverted to a heuristic string is the
        # signature of the write path clobbering it
        if tr.get("reclassified") and tr.get("meaning", "").startswith("arithmetic stated"):
            findings.append((
                "MIN", "TRIAGE-RECLASSIFICATION-LOST", e.get("id", "?"),
                f"reclassified by hand to class {tr.get('class')} but meaning reverted to the "
                f"heuristic -- run tools/triage_unexamined.py --write and confirm the "
                f"classification survives, per the v3.8.145 regression"))
    return findings


def check_version_stamp_inflation(package_root="."):
    """VERSION-STAMP-INFLATION (MIN): a release must not claim work it did not do.

    Added v3.8.144. The release sequence swept the previous version string to the
    new one across all JSON. _data_archive was excluded; THE REGISTRIES WERE NOT.
    So any registry stamp naming the immediately-prior release was dragged
    forward, and a record reading "ARCHIVED v3.8.85" came to read
    "ARCHIVED v3.8.143" -- attributing work to a release that did not do it.

    Seven records were affected, measured against a v3.8.85 reference copy.
    tools/bump_platform_version.py now makes the registries unreachable from a
    bump. THIS CHECK IS THE SECOND LINE: it catches the pattern returning by any
    other route -- a hand edit, a new script, a merge.

    THE TEST: count records in each registry whose text names the CURRENT
    version. A release that legitimately touches forty records is fine. A release
    whose registry claims a hundred while its VERSIONLOG entry describes eight is
    the signature of a sweep, and the threshold is set well above normal release
    volume so it fires on inflation rather than on activity.
    """
    import json as _j
    findings = []
    ver = None
    try:
        ver = _j.load(open(os.path.join(package_root, "version.json"),
                           encoding="utf-8")).get("platform_version")
    except Exception:
        return findings
    if not ver:
        return findings

    # 25 is above a normal release's registry volume -- the heaviest legitimate
    # release this session touched 8 figure entries -- and far below the 63 the
    # sweep produced. Calibrated against measured data, not chosen to pass.
    THRESHOLD = 25
    for rel, key in (("00_GUI_Files/figures_registry.json", "entries"),
                     ("data_recency.json", "sources"),
                     ("00_GUI_Files/assumptions_registry.json", "entries")):
        p = os.path.join(package_root, rel)
        if not os.path.exists(p):
            continue
        try:
            rows = _j.load(open(p, encoding="utf-8")).get(key) or []
        except Exception:
            continue
        # reproducibility_test.platform_version tracks the CURRENT build -- it is
        # refreshed every release by design and naming the current version is
        # correct there. Counting it would make the gate fire on every release and
        # be switched off, which is worse than not having it.
        def _strip_live(r):
            c = _j.loads(_j.dumps(r))
            rt = c.get("reproducibility_test")
            if isinstance(rt, dict):
                rt.pop("platform_version", None)
            return c

        hits = sum(1 for r in rows if ver in _j.dumps(_strip_live(r)))
        if hits > THRESHOLD:
            findings.append((
                "MIN", "VERSION-STAMP-INFLATION", os.path.basename(rel),
                f"{hits} of {len(rows)} records name the current version {ver}, above the "
                f"threshold of {THRESHOLD}. That is the signature of a version sweep dragging "
                f"historical stamps forward. Bump with tools/bump_platform_version.py, which "
                f"cannot reach the registries, and check against VERSIONLOG.txt for what this "
                f"release actually did."))
    return findings


def check_scenario_unqualified(package_root="."):
    """SCENARIO-UNQUALIFIED (SIG): a scenario-status figure must not be asserted as fact.

    Connects figures_registry.json validation_status to the prose that renders it. A figure
    registered "scenario", or whose narrative_example status says "illustrative pending
    validation", is a projection under stated assumptions. Printing it flat converts a
    projection into a measurement.

    The v3.7.803 case: FIG-fund-corpus-year60 ($122T) is the DETERMINISTIC path at a 6% real
    return with zero volatility, registered scenario / pending RESEARCH-5. The platform's own
    stochastic analysis puts the median at $73T at the realized 4.28% return, 5th-95th of
    roughly $32T-$255T. Ten of fifteen public occurrences carried no qualifier at all,
    including the homepage lede and three share-copy templates.

    Deliberately loose about WHICH qualifier appears. Policing house style is not this
    check's job; it only insists that a projection is not printed as a measurement.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(reg_path):
        return findings
    try:
        reg = json.load(open(reg_path, encoding="utf-8"))
    except Exception:
        return findings
    qual = re.compile(r"project|scenario|base case|base-case|assum|illustrat|estimate|"
                      r"modell?ed|under a|at a \d|median|pending validation", re.I)
    watched = []
    for e in reg.get("entries", []):
        status = (e.get("validation_status") or "").lower()
        _nx = narrative_examples(e)
        nstat = ((_nx[0].get("status") if _nx else "") or "").lower()
        if status != "scenario" and "pending validation" not in nstat and "illustrative" not in nstat:
            continue
        can = e.get("canonical") or {}
        unit = (can.get("unit") or "")
        if "trillion" not in unit.lower():
            continue
        # v3.7.803 efficacy fix: canonical carries scenario figures under by_scenario
        # (and trajectories under by_year), NOT under a scalar "value". Reading only
        # "value" silently skipped FIG-fund-corpus-year60 -- the $122T figure this
        # check was written for. Collect every numeric the entry can render.
        vals = []
        if isinstance(can.get("value"), (int, float)):
            vals.append(can["value"])
        for key in ("by_scenario", "by_year"):
            for v in (can.get(key) or {}).values():
                if isinstance(v, (int, float)):
                    vals.append(v)
        _nx2 = narrative_examples(e)
        ne_val = _nx2[0].get("value") if _nx2 else None
        if isinstance(ne_val, (int, float)):
            vals.append(ne_val)
        # v3.8.1: WORD FORMS TOO.
        #
        # Found by the guard-efficacy test written for this check. It only matched
        # digit forms -- $122T and $122 trillion -- so stripping the qualifier from
        # the homepage lede, which spells the figure out as "one-hundred-twenty-two
        # trillion dollars", produced NO finding. The single most-read sentence
        # carrying the platform's headline projection was outside the guard that
        # exists to protect exactly that sentence.
        #
        # This is the identical blind spot the count guard had before v3.7.803, in a
        # check written after that lesson. Digit-only matching is apparently the
        # default assumption even for someone who has just fixed it elsewhere.
        _ONES = {0:"", 1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six",
                 7:"seven", 8:"eight", 9:"nine", 10:"ten", 11:"eleven", 12:"twelve",
                 13:"thirteen", 14:"fourteen", 15:"fifteen", 16:"sixteen",
                 17:"seventeen", 18:"eighteen", 19:"nineteen"}
        _TENS = {2:"twenty", 3:"thirty", 4:"forty", 5:"fifty", 6:"sixty",
                 7:"seventy", 8:"eighty", 9:"ninety"}

        def _spell(n):
            """Hyphenated word form matching the platform's house style."""
            n = int(n)
            if n < 20:
                return _ONES.get(n, "")
            if n < 100:
                t, o = divmod(n, 10)
                return _TENS[t] + ("-" + _ONES[o] if o else "")
            if n < 1000:
                h, r = divmod(n, 100)
                out = _ONES[h] + "-hundred"
                return out + ("-" + _spell(r) if r else "")
            return ""

        pats = []
        for val in sorted(set(vals)):
            g = "%g" % val
            pats.append(re.compile(r"\$%s\s*T\b" % re.escape(g), re.I))
            pats.append(re.compile(r"\$%s\s+trillion" % re.escape(g), re.I))
            if float(val).is_integer():
                w = _spell(val)
                if w:
                    # Tolerate hyphen-or-space between the words, since prose varies.
                    flex = re.escape(w).replace(r"\-", r"[\s-]")
                    pats.append(re.compile(r"\b%s\s+trillion" % flex, re.I))
        if pats:
            watched.append((e["id"], pats))
    for fp in sorted(glob.glob(os.path.join(package_root, "*.html"))):
        try:
            raw = open(fp, encoding="utf-8", errors="replace").read()
        except Exception:
            continue
        for fid, pats in watched:
            for pat in pats:
                for m in pat.finditer(raw):
                    window = raw[max(0, m.start() - 260):m.end() + 260]
                    window = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", window, flags=re.S | re.I)
                    window = re.sub(r"<[^>]+>", " ", window)
                    if not qual.search(window):
                        findings.append(("SIG", "SCENARIO-UNQUALIFIED", os.path.basename(fp),
                            f"{m.group(0)} renders {fid}, registry status 'scenario', with no "
                            f"projection qualifier nearby"))
    return findings



def check_citation_exists(package_root="."):
    """CITATION-EXISTS (SIG): every cited file must resolve on disk.

    figures_registry.json entries name the workbook or document a figure was derived
    from, in `source` and `citation` fields. Those names were never checked against
    the filesystem. As of v3.7.806, nine cited files did not exist in the package,
    affecting thirteen figures including the headline fiscal set: $5.0T gross
    commitments, $2.0T absorbed, $3.0T net, and the healthcare per-capita target.

    This is not fabrication. The derivations exist and the entries carry rationale.
    But a citation that looks checkable and is not undermines the platform's central
    promise, which is that a reader does not have to trust it. For those figures,
    currently, they do.

    Three legitimate resolutions per missing file, all of which satisfy this check:
      SHIP     - add the workbook to the package
      REPOINT  - correct the citation to the file that now holds the derivation
      DECLARE  - say so in the citation text, e.g. "derived in an unshipped working
                 model; not independently reproducible from this package". Ugly, and
                 far better than a citation that cannot be followed.

    Filenames matched case-sensitively by basename, since the package is deployed to
    a case-sensitive filesystem.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(reg_path):
        return findings
    try:
        reg = json.load(open(reg_path, encoding="utf-8"))
    except Exception:
        return findings

    ondisk = set()
    for dirpath, dirnames, filenames in os.walk(package_root):
        dirnames[:] = [d for d in dirnames if d not in ("_web_html", "_downloads",
                                                        "__pycache__", ".git")]
        for fn in filenames:
            ondisk.add(fn)

    # KNOWN BACKLOG, dated and scheduled rather than silently tolerated.
    # These eight were found in v3.7.806 and cannot be resolved without knowing
    # which of them still exist outside the package. Each needs a SHIP, REPOINT or
    # DECLARE decision, tracked as RESEARCH-26 and scheduled for v3.7.808.
    # They are demoted to MIN, not suppressed: the count stays visible on every
    # run so the backlog cannot quietly become permanent. Any citation NOT on this
    # list fails as SIG, which is the guard's actual job.
    KNOWN_BACKLOG_v3_7_807 = {
        "04_Absorption_Reconciliation_Model.xlsx",
        "04_Civic_Infrastructure_Model_MultiMethod.xlsx",
        "04_Deficit_Recompute.xlsx",
        "04_Fiscal_Reconciliation_Model.xlsx",
        "04_Sovereign_Education_Fund_MultiMethod.xlsx",
        "04_Universal_Childcare_Model_MultiMethod.xlsx",
        "04_Universal_Healthcare_Target_Sensitivity.xlsx",
        "04_Universal_Mental_Health_Model_MultiMethod.xlsx",
    }

    pat = re.compile(r"[\w./-]+\.(?:xlsx|xlsm|docx|csv|pdf)")
    missing = {}

    def scan(obj, fid):
        if isinstance(obj, dict):
            for k, v in obj.items():
                if k in ("citation", "source") and isinstance(v, str):
                    low = v.lower()
                    # An explicit DECLARE is a resolution, not a defect.
                    if "not independently reproducible" in low or "unshipped" in low:
                        continue
                    for f in pat.findall(v):
                        base = os.path.basename(f)
                        if base not in ondisk:
                            missing.setdefault(base, set()).add(fid)
                else:
                    scan(v, fid)
        elif isinstance(obj, list):
            for v in obj:
                scan(v, fid)

    for e in reg.get("entries", []):
        scan(e, e.get("id", "?"))

    for base, fids in sorted(missing.items()):
        # v3.7.810 SEVERITY CORRECTION. These were demoted SIG -> MIN in v3.7.807 so
        # the release could ship. That did nothing: the deploy gate in
        # tools/deploy_to_github.py aborts on SIG **or MIN**, so the backlog blocked
        # every deploy from v3.7.807 onward while three releases reported "0 SIG" and
        # were read as shippable. They were not. The deploy of v3.7.809 failed on
        # exactly this.
        #
        # OBS is the correct severity, and not merely the convenient one. MIN means a
        # minor defect that ought to be fixed before shipping. This is not an
        # unresolved defect: it is a known gap, tracked as RESEARCH-26, scheduled, and
        # waiting on information about which working files still exist outside the
        # package, which no amount of building can supply. That is the definition of
        # an advisory observation, and it is the same class as the standing
        # colour-checker REVIEW prompt and MIRROR-STALE.
        #
        # The backlog stays fully visible in every audit run and is named in the
        # message, so it cannot quietly become permanent. Any citation NOT on the
        # dated list below still fails as SIG, which is the guard's actual job.
        sev = "OBS" if base in KNOWN_BACKLOG_v3_7_807 else "SIG"
        note = (" [known backlog, RESEARCH-26, awaiting decision D-2; not a new defect]"
                if sev == "OBS" else "")
        findings.append((sev, "CITATION-EXISTS", "00_GUI_Files/figures_registry.json",
            f"cited file \"{base}\" does not exist in the package; cited by "
            f"{', '.join(sorted(fids))}. Ship it, repoint it, or declare it "
            f"unshipped in the citation text.{note}"))
    return findings



def check_guard_efficacy_inflight(package_root="."):
    """GUARD-EFFICACY-INFLIGHT (SIG): the tree must not hold an interrupted meta-test.

    tools/test_guard_efficacy.py works by INJECTING defects into real files and
    restoring them in a finally block. A SIGKILL bypasses finally, leaving the
    injected defect in the tree. That has happened: a killed run left
    FIG-healthcare-percapita-target at 9111 instead of 9500.

    Before v3.7.807 the only protection was a backup directory in /tmp, checked by
    the meta-test itself on next start. That protection had the wrong lifetime: the
    backups were in /tmp, the corruption in the repository. Clearing /tmp destroyed
    the evidence while leaving the defect, and the corruption then became
    indistinguishable from real content.

    The marker now lives in the package, so this check sees it regardless of what
    /tmp did, and it fails the deploy rather than relying on anyone remembering to
    run the meta-test again. Recovery: tools/test_guard_efficacy.py --restore
    """
    findings = []
    marker = os.path.join(package_root, ".guard_efficacy_inflight.json")
    if not os.path.exists(marker):
        return findings
    detail = ""
    try:
        m = json.load(open(marker, encoding="utf-8"))
        detail = " Files under injection: %s" % ", ".join(sorted(m.get("files", {})))
    except Exception:
        detail = " (marker present but unreadable, which is itself suspicious)"
    findings.append(("SIG", "GUARD-EFFICACY-INFLIGHT", ".guard_efficacy_inflight.json",
        "a guard-efficacy run was interrupted and the tree may still contain an "
        "INJECTED DEFECT. Do not ship. Run: python3 tools/test_guard_efficacy.py "
        "--restore" + detail))
    return findings



def check_docx_count_drift(package_root="."):
    """DOCX-COUNT-DRIFT (MIN): registered Word-document counts must match the manifest.

    build_canonical_counts.py owns every count in HTML and JSON. It has never read
    .docx, so counts written into Word documents were owned by nobody. The same ones
    were hand-corrected in v3.7.804, v3.7.806 and v3.7.807 and drifted again each
    time, because hand-correction fixes an instance and never the cause.

    v3.7.808 added tools/sync_docx_counts.py, which rewrites only locations
    explicitly registered in docx_count_registry.json. Registration rather than
    pattern-sweeping is deliberate: a sweep was attempted in v3.7.804 and rewrote a
    historical sentence into nonsense, touched unrelated documents, and modified a
    private draft under a standing do-not-touch instruction. A regex cannot tell a
    current count from a historical one, and both occur in the same sentence.

    This check calls that tool in --check mode so drift is caught by the gate even
    when nobody remembers to run the sync.

    MIN rather than SIG: the fix is mechanical and the tool is one command away.
    """
    findings = []
    tool = os.path.join(package_root, "tools", "sync_docx_counts.py")
    if not os.path.exists(tool):
        return findings
    try:
        import subprocess
        p = subprocess.run([sys.executable, tool, "--check",
                            "--package-root", package_root],
                           capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300)
    except Exception as exc:                                          # noqa: BLE001
        findings.append(("OBS", "DOCX-COUNT-DRIFT", "tools/sync_docx_counts.py",
                         f"could not run: {str(exc)[:70]}"))
        return findings
    for line in p.stdout.splitlines():
        m = re.match(r"\s+\[(DRIFT|MISSING|AMBIGUOUS|NOTFOUND)\s*\]\s+(\S+)\s+(.*)",
                     line)
        if m:
            kind, rel, detail = m.group(1), m.group(2), m.group(3).strip()
            # v3.8.557: a rule that matches NOTHING (or is missing/ambiguous) means a count has silently
            # stopped updating -- 09_Readers_Path_Scoping sat at "114 issues ... 49 open" from v3.8.410 to
            # v3.8.556 as an OBS nobody read. Structural problems are now MIN, the same as drift.
            sev = "MIN"
            findings.append((sev, "DOCX-COUNT-DRIFT", rel,
                             f"{kind}: {detail[:170]}. Fix with "
                             f"python3 tools/sync_docx_counts.py --sync"))
    return findings



def check_citation_declared(package_root="."):
    """CITATION-DECLARED (OBS): count figures whose derivation is not reproducible.

    CITATION-EXISTS treats an explicit declaration as a valid resolution, which it is:
    a citation saying plainly that the working model was lost is honest, where one
    pointing at a file that does not exist is not. But that means declaring a file
    makes it VANISH from the audit, and in v3.7.807 the stated reason for demoting
    rather than suppressing the backlog was that it must not quietly become permanent.
    A resolution that removes the number from view defeats that.

    So the count is reported here instead. It never blocks, it simply refuses to let
    the figure disappear: every audit run states how many registry figures rest on a
    derivation nobody can open. It should fall as reconstruction proceeds, and if it
    does not, that is visible.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(reg_path):
        return findings
    try:
        reg = json.load(open(reg_path, encoding="utf-8"))
    except Exception:
        return findings
    declared = set()
    def walk(o, fid):
        if isinstance(o, dict):
            for k, v in o.items():
                if k in ("citation", "source") and isinstance(v, str):
                    if "UNSHIPPED WORKING MODEL" in v or "not independently reproducible" in v.lower():
                        declared.add(fid)
                else:
                    walk(v, fid)
        elif isinstance(o, list):
            for v in o:
                walk(v, fid)
    for e in reg.get("entries", []):
        walk(e, e.get("id", "?"))
    if declared:
        findings.append(("OBS", "CITATION-DECLARED", "00_GUI_Files/figures_registry.json",
            f"{len(declared)} figure(s) rest on a derivation that is NOT independently "
            f"reproducible from this package: {', '.join(sorted(declared))}. Declared "
            f"honestly rather than left dangling. RESEARCH-26 (closed) recorded the original loss; "
            f"a figure leaves this count when it is reproduced from the register and its "
            f"citation restated as historical provenance (see RECONSTRUCTION_PROTOCOL.md)."))
    return findings



def check_page_config_coverage(package_root="."):
    """PAGE-CONFIG-COVERAGE (MIN): every page with shared markers must be registered.

    build_site_includes.py iterates PAGE_CONFIG and injects the shared header, footer
    and CSS block into each page it names. A page carrying the SITE_* markers but
    absent from that dict is silently skipped forever: the builder reports nothing,
    because it never knew the page existed.

    historical-tradition.html did exactly this. It has carried all six markers the
    whole time and was never registered, so its chrome froze at v3.7.411 -- twenty-six
    releases serving a stale version string to anyone who followed the link from the
    document catalogue. It was found by accident while chasing a stale count, not by
    any check.

    This is a different shape of defect from the rest of the audit. Every other check
    verifies the CONTENT of things in scope. This one verifies that the scope itself
    is complete, which is the gap that let a public page rot in plain sight.

    MIN, not SIG: the page still serves and its content is correct. Only its chrome
    is stale, and the fix is one line.
    """
    findings = []
    try:
        import importlib.util
        spec = importlib.util.spec_from_file_location(
            "_bsh", os.path.join(package_root, "build_site_header.py"))
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        registered = set(mod.PAGE_CONFIG)
    except Exception as exc:                                          # noqa: BLE001
        findings.append(("OBS", "PAGE-CONFIG-COVERAGE", "build_site_header.py",
                         f"could not read PAGE_CONFIG: {str(exc)[:70]}"))
        return findings

    for fp in sorted(glob.glob(os.path.join(package_root, "*.html"))):
        rel = os.path.basename(fp)
        if rel in registered:
            continue
        try:
            txt = open(fp, encoding="utf-8", errors="replace").read()
        except Exception:
            continue
        markers = [m for m in ("SITE_HEADER:START", "SITE_FOOTER:START",
                               "SITE_CSS:START") if "<!-- %s -->" % m in txt]
        if markers:
            findings.append(("MIN", "PAGE-CONFIG-COVERAGE", rel,
                f"page carries shared markers ({', '.join(markers)}) but is not in "
                f"PAGE_CONFIG, so build_site_includes.py skips it and its chrome will "
                f"never update. Add an entry in build_site_header.py."))
    return findings



def check_audio_script_mtime(package_root="."):
    """AUDIO-SCRIPT-MTIME (OBS): a script newer than its MP3 forces a rebuild every deploy.

    _audio/build_all_audio.py decides staleness with a plain mtime comparison:
    getmtime(script) > getmtime(mp3). If a shipped package contains a script whose
    mtime is newer than its MP3, then EVERY deploy regenerates that episode through
    edge-tts, and re-extracting the zip next time restores the same mtimes, so the
    loop never ends.

    Two episodes were in this state and nobody noticed, because the deploy log
    reports the rebuild as normal activity rather than as a problem. It cost between
    62 and 248 seconds per deploy depending on machine load, and it fed a race that
    failed the rocker-egg integration gate twice: the test fetches a file written
    seconds earlier with preload="none" against a cold cache.

    OBS, not MIN. The rebuild produces correct audio and validate-audio passes, so
    nothing ships broken. What is wrong is that the work is repeated forever and
    silently. If the MP3 genuinely predates a script edit the rebuild is doing real
    work and should happen once; if it does not, the mtimes should be corrected.
    Either way it should not recur every single deploy unremarked.

    ENVIRONMENT-DEPENDENT, AND THAT IS THE POINT. This check reports what it sees in
    the tree it is run against. In the v3.7.813 package extracted on Linux with unzip,
    every script was ~37 hours OLDER than its MP3 and nothing was stale. On the deploy
    machine, extracting the same zip with Windows tar, two episodes rebuilt on every
    run. The archive is identical; the restored timestamps are not. A staleness rule
    built on mtime is therefore not portable across extraction tools, which is the
    deeper defect. The durable fix is to compare a content hash of the script against
    one recorded beside the MP3, which is deterministic everywhere. Not attempted here.
    """
    findings = []
    adir = os.path.join(package_root, "_audio")
    if not os.path.isdir(adir):
        return findings
    stale = []
    for fn in sorted(os.listdir(adir)):
        if not fn.endswith("_script.txt"):
            continue
        name = fn[:-len("_script.txt")]
        mp3 = os.path.join(adir, "audio_%s.mp3" % name)
        script = os.path.join(adir, fn)
        if not os.path.exists(mp3):
            continue
        try:
            if os.path.getmtime(script) > os.path.getmtime(mp3):
                stale.append(name)
        except OSError:
            continue
    if stale:
        findings.append(("OBS", "AUDIO-SCRIPT-MTIME", "_audio",
            f"{len(stale)} episode script(s) are newer than their MP3 and will be "
            f"rebuilt on the next deploy run with --build-audio (a deploy without it ships the stale MP3s): {', '.join(stale)}. Either rebuild the MP3 "
            f"once and ship it, or correct the mtimes. Left as-is this repeats the "
            f"text-to-speech step indefinitely and feeds the cold-cache race that "
            f"failed the rocker-egg gate in v3.7.813."))
    return findings



def check_dependency_completeness(package_root="."):
    """DEPENDENCY-UNDECLARED (MIN): every imported package must be installable.

    tools/check_dependencies.py was written in v3.7.815 and no gate consulted it,
    which is the same defect the v3.7.816 audit-coverage sweep was hunting. Two
    instances of it were created in this session while documenting that very
    failure, which is worth stating plainly: writing about a defect class is not
    protection against introducing it.

    Only the DIRECT-import half is gated. The runtime half -- packages another
    library loads on your behalf, such as a spreadsheet engine -- has no import
    statement and cannot be discovered, so it stays a hand-maintained list reported
    by the tool rather than a gate condition. Gating on a list that only grows when
    someone remembers to add to it would imply a completeness it does not have.
    """
    findings = []
    tool = os.path.join(package_root, "tools", "check_dependencies.py")
    if not os.path.exists(tool):
        return findings
    try:
        import subprocess
        p = subprocess.run([sys.executable, tool, "--package-root", package_root],
                           capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180)
    except Exception as exc:                                          # noqa: BLE001
        findings.append(("OBS", "DEPENDENCY-UNDECLARED", "tools/check_dependencies.py",
                         f"could not run: {str(exc)[:70]}"))
        return findings
    in_direct = False
    for line in p.stdout.splitlines():
        if line.startswith("DIRECT imports"):
            in_direct = True
            continue
        if line.startswith("RUNTIME dependencies"):
            in_direct = False
        if in_direct and "[MIN]" in line:
            findings.append(("MIN", "DEPENDENCY-UNDECLARED", "requirements.txt",
                             line.strip().replace("[MIN]", "").strip() +
                             ". A clean machine will fail on this import."))
    return findings



def check_derivation_sums(package_root="."):
    """DERIVATION-SUM-DRIFT (SIG): a figure with a derivation block must equal its parts.

    v3.8.7. FIG-total-new-commitments gained a derivation block defining it as the
    signed sum of ten registry figures. That block is only worth having if something
    verifies it, otherwise it is a claim about arithmetic rather than a check of it,
    and a component figure could move without the total following.

    This is the mechanism that retires the figure's dependence on
    04_Absorption_Reconciliation_Model.xlsx, which does not ship. Before v3.8.7 the
    headline rested solely on a lost workbook; it now rests on ten figures a reader
    can open, and this check is what keeps that true.

    SIG because the components are the platform's per-pillar costs and the total is
    its single most-quoted number. A silent divergence between them would mean the
    headline and the pillars describe different proposals.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(reg_path):
        return findings
    try:
        reg = json.load(open(reg_path, encoding="utf-8"))
    except Exception:
        return findings
    by_id = {e["id"]: e for e in reg.get("entries", [])}

    def scalar(fid):
        e = by_id.get(fid)
        if not e:
            return None
        c = e.get("canonical") or {}
        v = c.get("value")
        if v is None and "low" in c and "high" in c:
            v = (c["low"] + c["high"]) / 2.0
        if not isinstance(v, (int, float)):
            return None
        return v / 1000.0 if "billion" in (c.get("unit") or "") else v

    for e in reg.get("entries", []):
        d = e.get("derivation") or {}
        parts = (d.get("components_gross") or []) + (d.get("components_net") or [])
        if not parts:
            continue
        total = scalar(e["id"])
        if total is None:
            continue
        missing = [f for f in parts if scalar(f) is None]
        if missing:
            findings.append(("SIG", "DERIVATION-SUM-DRIFT", e["id"],
                f"derivation names component(s) that are missing or non-numeric: "
                f"{', '.join(missing)}. The sum cannot be verified."))
            continue
        got = sum(scalar(f) for f in parts)

        # v3.8.8: the tolerance is read FROM THE BLOCK, not fixed at 0.5.
        #
        # A hardcoded tolerance forces a choice between two bad outcomes when a
        # derivation legitimately does not reconcile: loosen the number until it
        # passes, or leave a permanent failure that trains people to ignore the
        # check. Both are ways of not saying what is true.
        #
        # FIG-total-new-commitments is exactly that case. Restated gross-throughout
        # in v3.8.8 it sums to 5.079 against a registered 5.0, because one component
        # (CCP) is a net figure whose gross does not exist anywhere in the package.
        # The gap is real, disclosed in the block's known_inconsistency field, and
        # tracked as RESEARCH-31. Closing it would mean inventing the missing gross,
        # and whatever value was invented would be the one that made the total
        # reconcile.
        #
        # So the block declares its own tolerance and the check enforces THAT. A
        # figure may state a wide tolerance only by writing it down where a reader
        # sees it, which is a different act from a checker quietly widening.
        tol = 0.5
        raw = d.get("tolerance")
        if isinstance(raw, str):
            m = re.search(r"([\d.]+)\s*percent", raw)
            if m:
                tol = float(m.group(1))
        elif isinstance(raw, (int, float)):
            tol = float(raw)
        pct = abs(got - total) / total * 100 if total else 0
        if pct > tol:
            findings.append(("SIG", "DERIVATION-SUM-DRIFT", e["id"],
                f"components sum to {got:.4f} but the canonical value is {total:.4f} "
                f"({pct:.2f}% apart, declared tolerance {tol}%). Either a component moved "
                f"without the total, the total was edited without its parts, or the "
                f"declared tolerance no longer matches reality."))
    return findings



def check_docx_untokenised_figures(package_root="."):
    """DOCX-FIGURE-UNTOKENISED (OBS): a registry value stated raw where a token belongs.

    v3.8.9. Word documents can reference a registry figure two ways: through a
    [[FIG:...]] token that resolves at build time, or as a literal number typed
    into the prose. Twenty-seven documents already use tokens, so the mechanism
    exists and is understood. Where a literal is used instead, the value is frozen
    at the moment it was typed and no guard can see it drift.

    That is not hypothetical. v3.8.6 found four reader-facing documents carrying
    superseded figures -- including the constituent letter intended for elected
    officials, which led with a fund figure demoted eight releases earlier and a
    deficit figure superseded fourteen months before that. Every figure correction
    in this project has reached the registry and the website while leaving Word
    documents behind, because the guards read HTML and JSON.

    The rule here is deliberately narrow to stay believable. A figure is only
    checked if it is ALREADY TOKENISED somewhere in the package: that proves the
    token exists, is spelled correctly, and is the intended way to reference it. A
    raw occurrence of the same value elsewhere is then a drift risk rather than a
    coincidence. Figures never tokenised anywhere are ignored, because there is no
    evidence a token was intended.

    OBS rather than MIN. Some raw statements are legitimate -- historical
    narrative, a superseded value being explicitly discussed, a figure quoted
    inside a correction notice. The check reports and a human decides. Making it
    blocking would guarantee suppression rather than tokenisation, which is how a
    guard becomes noise.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    if not os.path.exists(reg_path):
        return findings
    try:
        import docx as _docx
        reg = json.load(open(reg_path, encoding="utf-8"))
    except Exception:
        return findings

    scalars = {}
    for e in reg.get("entries", []):
        c = e.get("canonical") or {}
        v, u = c.get("value"), (c.get("unit") or "")
        if isinstance(v, (int, float)) and ("trillion" in u or "billion" in u):
            scalars[e["id"]] = (v, "trillion" if "trillion" in u else "billion")

    # Documents whose PURPOSE is to record or define figures are excluded. This is a
    # role exclusion, not a threshold tuned until the output looked clean:
    #   Open_Issues_Registry      records historical values in its issue descriptions
    #   Sources_And_Derivation    defines the figures and their provenance
    #   Comprehensive_Verification a verification log, quoting values it checked
    # A literal in those is the content, not a drift risk. Everything else -- letters,
    # white papers, analyses, the manifesto -- should tokenise.
    skip = ("_web_html", "_downloads", "Archive", "Package_Version", "Outreach",
            "Stewart", "Universal_Care", "Open_Issues_Registry",
            "Sources_And_Derivation", "Comprehensive_Verification")
    docs = [f for f in glob.glob(os.path.join(package_root, "**", "*.docx"),
                                 recursive=True)
            if not any(k in f for k in skip) and not os.path.basename(f).startswith("~$")]

    texts = {}
    for f in docs:
        try:
            texts[f] = " ".join(p.text for p in _docx.Document(f).paragraphs)
        except Exception:
            continue

    # A figure counts as "tokenised somewhere" only if a real token references it.
    tokenised = set()
    for t in texts.values():
        for m in re.finditer(r"\[\[FIG:([A-Za-z0-9_-]+)\]\]", t):
            tokenised.add(m.group(1))

    for f, t in texts.items():
        rel = os.path.relpath(f, package_root)
        stripped = re.sub(r"\[\[FIG:[^\]]+\]\]", " ", t)   # ignore correct usages
        for fid, (v, unit) in scalars.items():
            if fid not in tokenised:
                continue
            num = ("%g" % v)
            # v3.8.10: VALUE ALONE IS NOT ENOUGH. The first version matched on the
            # number and produced false positives that would have been actively
            # harmful if acted on:
            #   $100 billion -> flagged as the CCP figure in two documents where it
            #                   was the economic burden of identity theft, and
            #                   current federal IT spending
            #   $250 billion -> flagged as the education figure where it was the
            #                   long-term care payroll revenue operating range
            # Tokenising those would have made three unrelated facts resolve to the
            # wrong registry figures and drift whenever those figures moved. Worse
            # than the problem the check exists to solve.
            #
            # A subject word from the figure's own name must now appear within 120
            # characters. Crude, and it will miss some real cases -- a false negative
            # here costs a missed tokenisation, while a false positive costs a
            # corrupted document, so the asymmetry is deliberate.
            # v3.8.16: skip a literal that is ALREADY EXPLAINED next to a token, or
            # that is explicitly an aside about a different quantity.
            #
            # Reviewing all ten reported cases one by one, EIGHT were false
            # positives and the reasons cluster:
            #
            #   - the same number naming a different thing entirely: $100B as the
            #     economic burden of identity theft, as federal IT spending, as
            #     transportation infrastructure, and as the platform's deficit
            #     reduction; $145B as a wage-floor exemption revenue cost; $2.2T as
            #     the GPFG's actual holdings, which is a real-world observation and
            #     not a platform figure at all
            #   - a literal appearing as a PARENTHETICAL GLOSS beside a correct
            #     token, e.g. "[[FIG:FIG-mentalhealth-commitment]] (multi-method
            #     central approximately $145 billion...)". Tokenising that would
            #     make the sentence resolve the same figure twice.
            #
            # Only two of ten were genuine. A check reporting eight false findings
            # trains its reader to skip it, which is worse than not having it, so
            # the gloss case is excluded here and the value-collision cases are
            # recorded in RESEARCH-33 as needing per-case judgement no regex will
            # supply.
            stop = {"fig", "the", "and", "for", "new", "net", "gross", "total",
                    "annual", "per", "year", "commitment", "revenue", "size", "fund"}
            subject = [w for w in re.split(r"[-_]", fid.replace("FIG-", "").lower())
                       if w not in stop and len(w) > 3]
            pat = re.compile(r"\$\s?" + re.escape(num) + r"\s*" + unit, re.I)
            hits = 0
            # v3.8.558 FIX: positions were found in `stripped` (tokens removed) but the gloss test below
            # read the RAW text `t` at those same positions -- offset by every token removed before the
            # match, so the more a document was tokenised the more literals were silently skipped. Matches
            # are now found in the raw text; tokens are removed only inside the subject window.
            for m in pat.finditer(t):
                window = re.sub(r"\[\[FIG:[^\]]+\]\]", " ",
                                t[max(0, m.start() - 120):m.end() + 120]).lower()
                if not subject or not any(w in window for w in subject):
                    continue
                # v3.8.17: REVIEWED AND FOUND LEGITIMATE. Each of the four residual
                # cases was read in context and is a distinct quantity that happens
                # to share a number with a registry figure, or a value being
                # decomposed rather than asserted:
                #
                #   $2.2T  in 02_Wage_Floor_Concept_Analysis is Norway's ACTUAL
                #          GPFG holdings, an observation about the world
                #   $145B  in 05_Pillars_Borrow_Independently is the wage-floor
                #          exemption's gross revenue cost, not the housing figure
                #   $145B  in 05_Federal_Fiscal_Impact_Analysis appears twice: once
                #          as a gloss beside the mental-health token, once as the
                #          housing aggregate in prose that decomposes it into $70B
                #          absorbed plus $75B net new -- explained, not asserted
                #   $225B  in 05_Wage_Floors_As_Tax_Architecture cites a revenue
                #          projection with its own version provenance
                #
                # RESEARCH-33 closes on that basis. Recorded here rather than in a
                # suppression file so the reasoning travels with the code: a future
                # reader who re-adds these will find out why they were removed
                # instead of finding a bare list of exclusions.
                REVIEWED_LEGITIMATE = {
                    ("02_Wage_Floor_Concept_Analysis_v02.docx", "2.2"),
                    ("05_Pillars_Borrow_Independently.docx", "145"),
                    ("05_Federal_Fiscal_Impact_Analysis.docx", "145"),
                    ("05_Wage_Floors_As_Tax_Architecture.docx", "225"),
                    # v3.8.558 (W31, author-approved review): $250B in 05_Federal_Program_Integration_Plan is
                    # STATE MEDICAID spending, a different quantity that shares a number with the income
                    # surcharge; $13.3006T in the FFIA sits inside a restatement note recording how the covered
                    # wage base was fixed -- history, not a live claim. The four $73T cases are NOT listed: they
                    # are current claims awaiting a rewording that fits their token (W32).
                    ("05_Federal_Program_Integration_Plan.docx", "250"),
                    ("05_Federal_Fiscal_Impact_Analysis.docx", "13.3006"),
                }
                if (os.path.basename(rel), num) in REVIEWED_LEGITIMATE:
                    continue

                # A literal inside a parenthetical immediately following a token is
                # a gloss on that token, not an untokenised claim.
                raw_before = t[max(0, m.start() - 260):m.start()]
                if "[[fig:" in raw_before.lower() and "(" in raw_before[-140:]:
                    continue
                hits += 1
            if hits:
                findings.append(("OBS", "DOCX-FIGURE-UNTOKENISED", rel,
                    f"states ${num} {unit} literally {hits} time(s) where {fid} is "
                    f"tokenised elsewhere. A literal cannot drift-check; if this is a "
                    f"current claim use [[FIG:{fid}]], if it is historical say so."))
    return findings



def check_unregistered_analysis(package_root="."):
    """UNREGISTERED-ANALYSIS (OBS): a shipped model whose outputs reach no registry.

    v3.8.12, RESEARCH-30. The COST-1..COST-6 benchmark series shipped for months
    without appearing in any machine-readable registry. No guard could check those
    figures, no drift detection applied, and a substantiation document misstated
    its own model's conclusion with nothing to catch it.

    Registering those six raised the general question: how much else is in that
    state. The answer, on first sweep, was 19 of 26 shipped workbooks cited by no
    registry figure. Most are working models with no synthesis output and nothing
    to register. Four carry an explicit synthesis or summary sheet, which is the
    signature of a model that reached a conclusion.

    One of those four states a year-60 sovereign fund balance of $146.7T. The
    registry carries $122T at 6% and $84.5T at the anchored return. Different
    models with different assumptions, not necessarily a contradiction -- but a
    shipped figure 20% above the platform's own optimistic case, invisible to every
    check, is precisely the condition this reports.

    THE RULE THIS ENFORCES: a workbook that reaches a conclusion should have that
    conclusion in the register, or should say why not. A model with no synthesis
    sheet is working material and is not flagged.

    OBS, not blocking. Some conclusions are superseded, exploratory, or deliberately
    excluded, and a blocking check would produce deletion or suppression rather than
    registration. What it prevents is the state where nobody knows the divergence
    exists.
    """
    findings = []
    reg_path = os.path.join(package_root, "00_GUI_Files", "figures_registry.json")
    models_dir = os.path.join(package_root, "04_Mathematical_Models")
    if not (os.path.exists(reg_path) and os.path.isdir(models_dir)):
        return findings
    try:
        from openpyxl import load_workbook
        raw = open(reg_path, encoding="utf-8").read()
    except Exception:
        return findings

    cited = {os.path.basename(m) for m in re.findall(r"[\w./-]+\.xlsx", raw)}
    for f in sorted(glob.glob(os.path.join(models_dir, "*.xlsx"))):
        base = os.path.basename(f)
        if base in cited or base.startswith("~$"):
            continue
        try:
            wb = load_workbook(f, data_only=True, read_only=True)
            # v3.8.13: "analysis" and "outputs" added. The first version matched
            # synth/summary/result/headline/verdict and therefore MISSED
            # 04_Hybrid_Retirement_System_Model.xlsx, whose concluding sheet is
            # named "Combined Analysis". That workbook states a year-60 fund
            # balance, which is exactly the kind of output this check exists to
            # surface, and it was reported as clean.
            #
            # Same failure as everywhere else in this project: the check's logic
            # was right and its enumeration of what to look at was short. A
            # keyword list is a scope declaration, and scope is where these fail.
            concluding = [s for s in wb.sheetnames
                          if any(k in s.lower() for k in
                                 ("synth", "summary", "result", "headline", "verdict",
                                  "analysis", "outputs"))]
        except Exception:                                             # noqa: BLE001
            continue
        if concluding:
            findings.append(("OBS", "UNREGISTERED-ANALYSIS",
                             os.path.relpath(f, package_root),
                             f"ships with concluding sheet(s) {', '.join(concluding)} but is "
                             f"cited by no registry figure, so its outputs are invisible to "
                             f"every check. Register them, or record why they are excluded."))
    return findings


def main(package_root):
    """Run the standard audit and report findings."""
    package_root = os.path.abspath(package_root)
    print(f"Auditing package at: {package_root}")
    print()
    
    # Load whitelist
    wl_path = os.path.join(package_root, "audit_whitelist.txt")
    wl_entries = parse_whitelist(wl_path)
    print(f"Loaded {len(wl_entries)} whitelist entries from audit_whitelist.txt")
    
    # Load all docx files
    all_docs = {}
    for root, dirs, files in os.walk(package_root):
        for f in files:
            if f.endswith(".docx"):
                path = os.path.join(root, f)
                rel_path = os.path.relpath(path, package_root)
                try:
                    doc = get_docx(path)  # v3.7.90 cached
                    text = "\n".join(p.text for p in doc.paragraphs)
                    for t in doc.tables:
                        for r in t.rows:
                            for c in r.cells:
                                text += "\n" + c.text
                    all_docs[path] = text
                except:
                    pass
    print(f"Loaded {len(all_docs)} docx files")
    print()
    
    all_findings = []
    
    # CHECK (run FIRST per cadence): Expanded-scope audits
    print("=" * 70)
    print("CHECK: Expanded-scope audits (run first per harden cycle cadence)")
    print("=" * 70)
    expanded_findings = audit_expanded_scope(package_root)
    obs_oir = sum(1 for f in expanded_findings if f[1] == "EXPANDED-OIR")
    obs_readme = sum(1 for f in expanded_findings if f[1] == "EXPANDED-README")
    obs_vlog = sum(1 for f in expanded_findings if f[1] == "EXPANDED-VERSIONLOG")
    print(f"  Full-OIR scan: {obs_oir} occurrences (informational, mostly HISTORICAL ACCURATE)")
    print(f"  Full-README scan: {obs_readme} occurrences (informational, mostly HISTORICAL ACCURATE)")
    print(f"  Full-VERSIONLOG scan: {obs_vlog} occurrences (informational, mostly HISTORICAL ACCURATE)")
    print(f"  Total: {len(expanded_findings)} OBS findings")
    print(f"  (OBS findings are informational and do not affect audit pass/fail)")
    acronym_findings = audit_undefined_acronyms(package_root)
    obs_acronyms = sum(1 for f in acronym_findings if f[1] == "EXPANDED-ACRONYMS")
    print(f"  Undefined-acronym scan: {obs_acronyms} occurrences (real findings if non-zero)")
    all_findings.extend(acronym_findings)
    all_findings.extend(expanded_findings)
    
    # CHECK: Section 47 reference integrity (added v3.1.7)
    s47_id_findings = audit_section_47_id_references(package_root)
    s47_row_findings = audit_section_47_row_consistency(package_root)
    oir_section_findings = audit_oir_section_references(package_root)
    print(f"  Section 47 ID reference integrity: {len(s47_id_findings)} findings")
    print(f"  Section 47 row consistency: {len(s47_row_findings)} findings")
    print(f"  OIR Section reference integrity (max: {get_oir_max_section(package_root)}): {len(oir_section_findings)} findings")
    all_findings.extend(s47_id_findings)
    all_findings.extend(s47_row_findings)
    all_findings.extend(oir_section_findings)
    
    # CHECK: Manifest + TOC consistency (added v3.1.9)
    manifest_v_findings = audit_manifest_version_consistency(package_root)
    ti_drift_findings = audit_tracked_issue_count_drift(package_root)
    orient_findings = audit_orientation_doc_stale(package_root)
    vintage_findings = audit_figure_source_vintage(package_root)   # v3.8.489 R2/R3
    ledger_findings = audit_comment_ledger(package_root)            # v3.8.490
    segpriv_findings = audit_segment_privacy_agreement(package_root)  # v3.8.491 D10
    regional_findings = audit_regional_prose(package_root)          # v3.8.498
    handoff_findings = audit_session_handoff(package_root)          # v3.8.505
    status_findings = audit_status_report(package_root)             # v3.8.513
    assumclass_findings = audit_assumption_classification(package_root)  # v3.8.513
    displaydrift_findings = audit_display_canonical_drift(package_root)  # v3.8.513
    household_findings = audit_household_scenarios(package_root)    # v3.8.517
    forkrec_findings = audit_fork_check_record(package_root)        # v3.8.505
    reflow_guard_findings = audit_reflow_guard_missing(package_root)
    print(f"  Tracked-issue count drift: {len(ti_drift_findings)} findings")
    print(f"  Orientation doc staleness: {len(orient_findings)} findings")
    print(f"  Figure source vintage: {len(vintage_findings)} findings")
    print(f"  Comment ledger integrity: {len(ledger_findings)} findings")
    print(f"  Segment privacy agreement: {len(segpriv_findings)} findings")
    print(f"  Regional prose generated: {len(regional_findings)} findings")
    print(f"  Session handoff current: {len(handoff_findings)} findings")
    print(f"  Status report current: {len(status_findings)} findings")
    print(f"  Assumption classification: {len(assumclass_findings)} findings")
    print(f"  Display vs canonical: {len(displaydrift_findings)} findings")
    print(f"  Household scenarios vs calculator: {len(household_findings)} findings")
    print(f"  Fork check recorded: {len(forkrec_findings)} findings")
    print(f"  Reflow guard (SC 1.4.10): {len(reflow_guard_findings)} findings")
    toc_findings = audit_toc_consistency(package_root)
    print(f"  Manifest version consistency: {len(manifest_v_findings)} findings")
    print(f"  TOC consistency: {len(toc_findings)} findings")
    all_findings.extend(manifest_v_findings)
    all_findings.extend(ti_drift_findings)
    all_findings.extend(orient_findings)
    all_findings.extend(vintage_findings)
    all_findings.extend(ledger_findings)
    all_findings.extend(segpriv_findings)
    all_findings.extend(regional_findings)
    all_findings.extend(handoff_findings)
    all_findings.extend(status_findings)
    all_findings.extend(assumclass_findings)
    all_findings.extend(displaydrift_findings)
    all_findings.extend(household_findings)
    all_findings.extend(forkrec_findings)
    all_findings.extend(reflow_guard_findings)
    all_findings.extend(toc_findings)
    
    # CHECK: Cross-reference resolution (added v3.1.12)
    xref_findings = audit_cross_reference_resolution(package_root)
    print(f"  Cross-reference resolution: {len(xref_findings)} findings")
    all_findings.extend(xref_findings)

    # CHECK: PV doc count claim consistency (added v3.2.4)
    pv_count_findings = audit_pv_count_consistency(package_root)
    print(f"  PV doc count-claim consistency: {len(pv_count_findings)} findings")
    all_findings.extend(pv_count_findings)
    # CHECK: version.json count consistency vs catalog (added v3.7.563)
    vj_count_findings = audit_version_json_count_consistency(package_root)
    print(f"  version.json count consistency: {len(vj_count_findings)} findings")
    all_findings.extend(vj_count_findings)
    print()
    
    # CHECK: META-NUMERIC-DRIFT (added v3.7.151)
    print("=" * 70)
    print("CHECK: META-NUMERIC-DRIFT (hardcoded numerics vs manifest.json)")
    print("=" * 70)
    meta_drift_findings = audit_meta_numeric_drift(package_root)
    print(f"  META-NUMERIC-DRIFT check: {len(meta_drift_findings)} findings")
    all_findings.extend(meta_drift_findings)
    print()

    # CHECK: README-CHAIN-DRIFT (added v3.7.185)
    print("=" * 70)
    print("CHECK: README-CHAIN-DRIFT (README.txt vs VERSIONLOG.txt version chain)")
    print("=" * 70)
    readme_chain_findings = audit_readme_chain_drift(package_root)
    print(f"  README-CHAIN-DRIFT check: {len(readme_chain_findings)} findings")
    all_findings.extend(readme_chain_findings)
    print()

    # CHECK: VERSIONLOG-HEADER-FUSION (added v3.7.713)
    print("=" * 70)
    print("CHECK: VERSIONLOG-HEADER-FUSION (errata-splice header destruction guard)")
    print("=" * 70)
    vl_fusion_findings = audit_versionlog_header_fusion(package_root)
    print(f"  VERSIONLOG-HEADER-FUSION check: {len(vl_fusion_findings)} findings")
    all_findings.extend(vl_fusion_findings)
    print()

    # CHECK: CONVERSATION-TRACKING-INTEGRITY (added v3.7.612)
    print("=" * 70)
    print("CHECK: CONVERSATION-TRACKING-INTEGRITY (archive/log internal consistency + staleness read)")
    print("=" * 70)
    conv_integrity_findings = audit_conversation_tracking_integrity(package_root)
    print(f"  CONVERSATION-TRACKING-INTEGRITY check: {len(conv_integrity_findings)} findings")
    all_findings.extend(conv_integrity_findings)
    print()

    # CHECK: ASSUMPTIONS-REGISTRY-INTEGRITY (added v3.7.614)
    print("=" * 70)
    print("CHECK: ASSUMPTIONS-REGISTRY-INTEGRITY (registry well-formed + open-issue cross-refs)")
    print("=" * 70)
    assum_findings = audit_assumptions_registry_integrity(package_root)
    print(f"  ASSUMPTIONS-REGISTRY-INTEGRITY check: {len(assum_findings)} findings")
    all_findings.extend(assum_findings)
    print()

    # CHECK: WRANGLER-CONFIG-DRIFT (added v3.7.156)
    print("=" * 70)
    print("CHECK: WRANGLER-CONFIG-DRIFT (cloudflare/wrangler.toml sanity)")
    print("=" * 70)
    wrangler_findings = audit_wrangler_config(package_root)
    print(f"  WRANGLER-CONFIG-DRIFT check: {len(wrangler_findings)} findings")
    all_findings.extend(wrangler_findings)
    print()

    # CHECK: README-INTEGRITY (added v3.7.185 for SITE-38)
    print("=" * 70)
    print("CHECK: README-INTEGRITY (per-version paragraph dedup + chain)")
    print("=" * 70)
    readme_findings = audit_readme_integrity(package_root)
    print(f"  README-INTEGRITY check: {len(readme_findings)} findings")
    all_findings.extend(readme_findings)
    print()

    # CHECK: ASSETSIGNORE-MISSING (added v3.7.159)
    print("=" * 70)
    print("CHECK: ASSETSIGNORE-MISSING (.assetsignore safety net for Workers Builds)")
    print("=" * 70)
    assetsignore_findings = audit_assetsignore(package_root)
    print(f"  ASSETSIGNORE-MISSING check: {len(assetsignore_findings)} findings")
    all_findings.extend(assetsignore_findings)
    print()

    # CHECK: HEADER-STRUCTURE — page-sticky-wrap closing </div> (added v3.7.414)
    # Operationalizes the v3.7.413 diagnostic lesson: when CSS looks
    # correct but rendering is wrong, check HTML structural integrity.
    # Would have caught the share.html/recruit.html missing-</div> bug
    # at v3.7.39 (and again at v3.7.408's flag-bg cleanup).
    print("=" * 70)
    print("CHECK: HEADER-STRUCTURE (page-sticky-wrap closing </div> after SITE_HEADER:END)")
    print("=" * 70)
    header_structure_findings = audit_header_structural_integrity(package_root)
    print(f"  HEADER-STRUCTURE check: {len(header_structure_findings)} findings")
    all_findings.extend(header_structure_findings)
    print()

    # CHECK: TRACKED-ISSUES-COUNT-DRIFT — count consistency across OIR /
    # manifest.json / build_site_header.py (added v3.7.415). Catches the
    # class of drift that almost shipped in v3.7.414 from a mis-derived
    # count. The OIR table 'Current Status' column is the source of truth.
    print("=" * 70)
    print("CHECK: TRACKED-ISSUES-COUNT-DRIFT (OIR vs manifest.json vs build_site_header.py)")
    print("=" * 70)
    tracked_count_findings = audit_tracked_issues_count_drift(package_root)
    mirror_count_findings = audit_rendered_mirror_header_counts(package_root)
    print(f"  TRACKED-ISSUES-COUNT-DRIFT check: {len(tracked_count_findings)} findings")
    all_findings.extend(tracked_count_findings)
    all_findings.extend(mirror_count_findings)
    print()

    # CHECK: WARM-TONE-DARK-TOKEN-GAP — color tokens with :root definition
    # but no html[data-theme="dark"] override (added v3.7.416). Operation-
    # alizes the recurring "token gap" pattern: dark-mode contrast failures
    # caused by tokens falling through to light-mode values.
    print("=" * 70)
    print("CHECK: WARM-TONE-DARK-TOKEN-GAP (color tokens with :root def but no dark override)")
    print("=" * 70)
    token_gap_findings = audit_warm_tone_dark_token_completeness(package_root)
    print(f"  WARM-TONE-DARK-TOKEN-GAP check: {len(token_gap_findings)} findings")
    all_findings.extend(token_gap_findings)
    print()

    # CHECK: IMPORTANT-HARDCODED-COLOR \u2014 !important + hardcoded color
    # literals that defeat the theme-aware token system (added v3.7.417).
    # One-time baseline inventory; many findings may be intentional.
    print("=" * 70)
    print("CHECK: IMPORTANT-HARDCODED-COLOR (!important + hardcoded color, no var())")
    print("=" * 70)
    important_color_findings = audit_important_hardcoded_color_combinations(package_root)
    print(f"  IMPORTANT-HARDCODED-COLOR check: {len(important_color_findings)} findings")
    all_findings.extend(important_color_findings)
    print()

    # CHECK: JS-CLEAN-URL-ASSUMPTION \u2014 JavaScript files comparing URLs
    # against .html-ending strings without clean-URL handling (added
    # v3.7.423). Operationalizes the v3.7.405 bug pattern (Cloudflare
    # Pages serves /about.html at /about, breaking strict .html
    # comparisons). Regression guard.
    print("=" * 70)
    print("CHECK: JS-CLEAN-URL-ASSUMPTION (.html comparisons without clean-URL handling)")
    print("=" * 70)
    js_url_findings = audit_js_clean_url_assumptions(package_root)
    print(f"  JS-CLEAN-URL-ASSUMPTION check: {len(js_url_findings)} findings")
    all_findings.extend(js_url_findings)
    print()

    # CHECK: RENDERED-INVARIANT \u2014 critical rendering invariants in built
    # HTML pages and canonical CSS files (added v3.7.425). Lightweight
    # alternative to full visual regression testing; verifies essential
    # CSS link references, meta tags, theme tokens, and canonical class
    # definitions remain present. Regression guard.
    print("=" * 70)
    print("CHECK: RENDERED-INVARIANT (critical CSS/meta/token presence in built pages)")
    print("=" * 70)
    rendered_inv_findings = audit_rendered_invariants(package_root)
    print(f"  RENDERED-INVARIANT check: {len(rendered_inv_findings)} findings")
    all_findings.extend(rendered_inv_findings)
    print()

    # CHECK: WEB-DOCX content parity (added v3.7.438, Option C companion guard)
    print("=" * 70)
    print("CHECK: WEB-DOCX-PARITY (docx headings present in regenerable web body)")
    print("=" * 70)
    parity_findings = check_web_docx_parity(package_root)
    print(f"  WEB-DOCX-PARITY check: {len(parity_findings)} findings")
    all_findings.extend(parity_findings)
    print()

    # CHECK: download-filename prefix (added v3.7.440)
    print("=" * 70)
    print("CHECK: DL-PREFIX (downloadable files carry we-the-people- prefix)")
    print("=" * 70)
    dlp_findings = check_download_prefix(package_root)
    print(f"  DL-PREFIX check: {len(dlp_findings)} findings")
    all_findings.extend(dlp_findings)
    print()

    # CHECK: document-count consistency (added v3.7.441)
    print("=" * 70)
    print("CHECK: DOC-COUNT (footer + bot-page document count matches catalog)")
    print("=" * 70)
    dc_findings = check_doc_count(package_root)
    print(f"  DOC-COUNT check: {len(dc_findings)} findings")
    all_findings.extend(dc_findings)
    print()

    # CHECK: download bundle set consistency (added v3.7.442)
    print("=" * 70)
    print("CHECK: DOWNLOAD-SET (disk = manifest = downloads.html cards)")
    print("=" * 70)
    ds_findings = check_download_set(package_root)
    print(f"  DOWNLOAD-SET check: {len(ds_findings)} findings")
    all_findings.extend(ds_findings)
    print()

    # CHECK: bot mirror freshness (added v3.7.446)
    print("=" * 70)
    print("CHECK: BOT-MIRROR (/bots/ version + count track the platform)")
    print("=" * 70)
    bm_findings = check_bot_mirror(package_root)
    print(f"  BOT-MIRROR check: {len(bm_findings)} findings")
    all_findings.extend(bm_findings)
    print()

    # CHECK: private-doc leak guard (added v3.7.634) — mirror/sitemap/bot leak,
    # deploy-sanitization wiring, and an internal-only-phrase tripwire
    print("=" * 70)
    print("CHECK: PRIVATE-LEAK-GUARD (private docs never reach a public surface)")
    print("=" * 70)
    plg_findings = check_private_leak_guard(package_root)
    print(f"  PRIVATE-LEAK-GUARD check: {len(plg_findings)} findings")
    all_findings.extend(plg_findings)
    print()

    # CHECK: date/version monotonicity in README + VERSIONLOG (added v3.7.636, plan P1.1)
    print("=" * 70)
    print("CHECK: DATE-MONOTONICITY (README/VERSIONLOG ordered newest-first)")
    print("=" * 70)
    dm_findings = check_date_monotonicity(package_root)
    print(f"  DATE-MONOTONICITY check: {len(dm_findings)} findings")
    all_findings.extend(dm_findings)
    print()

    # CHECK: encoding / mojibake integrity (added v3.7.637, plan P1.2)
    print("=" * 70)
    print("CHECK: ENCODING-INVALID (valid UTF-8, no decode loss / mojibake)")
    print("=" * 70)
    enc_findings = check_encoding_integrity(package_root)
    print(f"  ENCODING-INVALID check: {len(enc_findings)} findings")
    all_findings.extend(enc_findings)
    print()

    # CHECK: box-glyph / PUA / control-char scan (added v3.7.638, plan P1.3)
    print("=" * 70)
    print("CHECK: GLYPH-BOX (no PUA / control / noncharacter code points)")
    print("=" * 70)
    glyph_findings = check_glyph_integrity(package_root)
    print(f"  GLYPH-BOX check: {len(glyph_findings)} findings")
    all_findings.extend(glyph_findings)
    print()

    # CHECK: figures registry structural integrity (added v3.7.639, plan P2.1a)
    print("=" * 70)
    print("CHECK: FIGURE-REGISTRY (canonical derived-figure registry integrity)")
    print("=" * 70)
    fr_findings = check_figures_registry(package_root)
    all_findings.extend(fr_findings)
    all_findings.extend(check_figure_tokens(package_root))
    all_findings.extend(check_data_source_linkage(package_root))
    all_findings.extend(check_migration_log(package_root))
    all_findings.extend(check_reviewer_doc_counts(package_root))
    all_findings.extend(check_canonical_counts(package_root))
    all_findings.extend(check_canonical_figures(package_root))
    all_findings.extend(check_numeric_coverage(package_root))
    all_findings.extend(check_derivations(package_root))
    all_findings.extend(check_factual_coverage(package_root))
    all_findings.extend(check_orphaned_renderings(package_root))
    all_findings.extend(check_ingestion_stale(package_root))
    all_findings.extend(check_stale_open_items(package_root))
    all_findings.extend(check_source_archived(package_root))
    all_findings.extend(check_model_input_provenance(package_root))
    all_findings.extend(check_declared_dependency_edges(package_root))
    all_findings.extend(check_substantiation_coverage(package_root))
    all_findings.extend(check_comparison_method_recorded(package_root))
    all_findings.extend(check_historical_exemption(package_root))
    all_findings.extend(check_calculator_parameters(package_root))
    all_findings.extend(check_superseded_source(package_root))
    all_findings.extend(check_private_draft_pins(package_root))
    all_findings.extend(check_typed_figures(package_root))
    all_findings.extend(check_retired_as_canonical(package_root))
    all_findings.extend(check_divergence_surfaced(package_root))
    all_findings.extend(check_orphan_figures(package_root))
    all_findings.extend(check_retired_values_live(package_root))
    all_findings.extend(check_public_label_numbers(package_root))
    all_findings.extend(check_guide_prose(package_root))
    all_findings.extend(check_narrative_display_drift(package_root))
    all_findings.extend(check_figure_value_agreement(package_root))   # v3.8.699 (author #5109, R6a)
    all_findings.extend(check_rendered_value_wording(package_root))   # v3.8.701 (author #5115)
    all_findings.extend(check_calibration_named(package_root))
    all_findings.extend(check_checklist_log(package_root))
    all_findings.extend(check_fund_draw_params(package_root))
    all_findings.extend(check_pillar_ledger(package_root))
    all_findings.extend(check_analysis_tools(package_root))
    all_findings.extend(check_annotation_currency(package_root))
    all_findings.extend(check_cross_sheet_drift(package_root))
    all_findings.extend(check_guide_and_version_stamp(package_root))
    all_findings.extend(check_reading_path_resolves(package_root))
    all_findings.extend(check_reading_paths_generated(package_root))
    all_findings.extend(check_figures_coverage_claim(package_root))
    all_findings.extend(check_wage_calculator_counts(package_root))
    all_findings.extend(check_model_cached_values(package_root))
    all_findings.extend(check_currency_ledger_honest(package_root))
    all_findings.extend(check_wage_tables_current(package_root))
    all_findings.extend(check_document_currency(package_root))
    all_findings.extend(check_bundle_raw_tokens(package_root))
    all_findings.extend(check_substantiation_monotonic(package_root))
    all_findings.extend(check_phase_claim(package_root))
    all_findings.extend(check_absence_claim(package_root))
    all_findings.extend(check_discrepancy_claim(package_root))
    all_findings.extend(check_note_field_singular(package_root))
    all_findings.extend(check_unwired_tools(package_root))
    all_findings.extend(check_protocol_indexed(package_root))
    all_findings.extend(check_conversion_declared(package_root))
    all_findings.extend(check_exhaustive_audit_layer1(package_root))
    all_findings.extend(check_p1_no_adoption(package_root))
    all_findings.extend(check_uncertainty_propagation(package_root))
    all_findings.extend(check_disclosure_freshness(package_root))
    all_findings.extend(check_registration_completeness(package_root))
    all_findings.extend(check_tracked_issues_naming(package_root))
    all_findings.extend(check_readme_stale_version(package_root))
    all_findings.extend(check_download_bundle_stale(package_root))
    all_findings.extend(check_msa_shard_integrity(package_root))
    all_findings.extend(check_cloudflare_file_size(package_root))
    all_findings.extend(check_wage_data_integrity(package_root))
    all_findings.extend(check_generated_file_source_backing(package_root))
    all_findings.extend(check_healthcare_baseline_consistency(package_root))
    print(f"  FIGURE-REGISTRY check: {len(fr_findings)} findings")
    all_findings.extend(fr_findings)
    print()

    # CHECK: figure drift -- resolved variants must not reappear in live docs (v3.7.641, plan P2.1b)
    print("=" * 70)
    print("CHECK: FIGURE-DRIFT (reconciled figures must not reappear in live docs)")
    print("=" * 70)
    fd_findings = check_figure_drift(package_root)
    print(f"  FIGURE-DRIFT check: {len(fd_findings)} findings")
    all_findings.extend(fd_findings)
    print()

    # CHECK: sensitivity-disclosure parity for the headline fund figure (v3.7.642, plan P3.1)
    print("=" * 70)
    print("CHECK: SENSITIVITY-PARITY ($122T/6% claims present the 4% scenario)")
    print("=" * 70)
    sp_findings = check_sensitivity_parity(package_root)
    print(f"  SENSITIVITY-PARITY check: {len(sp_findings)} findings")
    all_findings.extend(sp_findings)
    print()

    # CHECK: load-bearing fiscal docs keep a sources baseline (v3.7.643, plan P3.2)
    print("=" * 70)
    print("CHECK: SOURCE-BASELINE-MISSING (load-bearing docs stay source-traceable)")
    print("=" * 70)
    sb_findings = check_source_baseline(package_root)
    print(f"  SOURCE-BASELINE-MISSING check: {len(sb_findings)} findings")
    all_findings.extend(sb_findings)
    print()

    # CHECK: falsifiability register stays in status-parity with the OIR (v3.7.644, plan P3.3)
    print("=" * 70)
    print("CHECK: FALSIFIABILITY-DRIFT (register vs OIR status parity)")
    print("=" * 70)
    fdr_findings = check_falsifiability_drift(package_root)
    print(f"  FALSIFIABILITY-DRIFT check: {len(fdr_findings)} findings")
    all_findings.extend(fdr_findings)
    print()

    # CHECK: same-page fragment-link integrity in served HTML (v3.7.645, plan P4.1)
    print("=" * 70)
    print("CHECK: LINK-FRAGMENT (same-page #anchors resolve)")
    print("=" * 70)
    lf_findings = check_link_fragment(package_root)
    print(f"  LINK-FRAGMENT check: {len(lf_findings)} findings")
    all_findings.extend(lf_findings)
    print()

    # CHECK: deterministic accessibility invariants (img alt, html lang) (v3.7.646, plan P4.2)
    print("=" * 70)
    print("CHECK: A11Y (img alt-text + html lang attribute)")
    print("=" * 70)
    a11y_findings = check_a11y(package_root)
    print(f"  A11Y check: {len(a11y_findings)} findings")
    all_findings.extend(a11y_findings)
    print()

    # CHECK: served HTML mirror is content-synced with source docx (v3.7.647, plan P5.1 CAPSTONE)
    print("=" * 70)
    print("CHECK: MIRROR-STALE (served pages match source .docx content)")
    print("=" * 70)
    ms_findings = check_mirror_stale(package_root)
    print(f"  MIRROR-STALE check: {len(ms_findings)} findings")
    all_findings.extend(ms_findings)
    print()

    # CHECK: accidental consecutive-duplicate paragraphs in docx (v3.7.652)
    print("=" * 70)
    print("CHECK: DOC-DUP-PARAGRAPH (no accidental consecutive duplicate paragraphs)")
    print("=" * 70)
    dup_findings = check_doc_dup_paragraph(package_root)
    print(f"  DOC-DUP-PARAGRAPH check: {len(dup_findings)} findings")
    all_findings.extend(dup_findings)
    print()

    # CHECK: bot-mirror subtree links resolve on disk (v3.7.654)
    print("=" * 70)
    print("CHECK: BOT-MIRROR-LINK (bots/ subtree links resolve on disk)")
    print("=" * 70)
    bml_findings = check_bot_mirror_link(package_root)
    print(f"  BOT-MIRROR-LINK check: {len(bml_findings)} findings")
    all_findings.extend(bml_findings)
    print()

    # CHECK: Word-document count drift (v3.7.808)
    print("=" * 70)
    print("CHECK: DOCX-COUNT-DRIFT (counts in Word files are owned too)")
    print("=" * 70)
    dcd_findings = check_docx_count_drift(package_root)
    print(f"  DOCX-COUNT-DRIFT check: {len(dcd_findings)} findings")
    all_findings.extend(dcd_findings)
    print()

    # CHECK: interrupted guard-efficacy run (v3.7.807)
    print("=" * 70)
    print("CHECK: GUARD-EFFICACY-INFLIGHT (tree must not hold an injected defect)")
    print("=" * 70)
    gei_findings = check_guard_efficacy_inflight(package_root)
    print(f"  GUARD-EFFICACY-INFLIGHT check: {len(gei_findings)} findings")
    all_findings.extend(gei_findings)
    print()

    # CHECK: every imported package is declared (v3.7.817)
    print("=" * 70)
    print("CHECK: DEPENDENCY-UNDECLARED (a clean machine must be able to run this)")
    print("=" * 70)
    dep_findings = check_dependency_completeness(package_root)
    print(f"  DEPENDENCY-UNDECLARED check: {len(dep_findings)} findings")
    all_findings.extend(dep_findings)
    print()

    # CHECK: HTML structural consistency (v3.7.107, first wired in v3.7.816)
    print("=" * 70)
    print("CHECK: HTML-STRUCTURAL (chrome bands, sticky wrap, main max-width)")
    print("=" * 70)
    hsc_findings = check_html_structural_consistency(package_root)
    print(f"  HTML-STRUCTURAL check: {len(hsc_findings)} findings")
    all_findings.extend(hsc_findings)
    print()

    # CHECK: audio scripts newer than their MP3s (v3.7.814)
    print("=" * 70)
    print("CHECK: AUDIO-SCRIPT-MTIME (work that repeats every deploy, silently)")
    print("=" * 70)
    asm_findings = check_audio_script_mtime(package_root)
    print(f"  AUDIO-SCRIPT-MTIME check: {len(asm_findings)} findings")
    all_findings.extend(asm_findings)
    print()

    # CHECK: pages with shared markers must be registered (v3.7.813)
    print("=" * 70)
    print("CHECK: PAGE-CONFIG-COVERAGE (a builder cannot report a page it never knew about)")
    print("=" * 70)
    pcc_findings = check_page_config_coverage(package_root)
    print(f"  PAGE-CONFIG-COVERAGE check: {len(pcc_findings)} findings")
    all_findings.extend(pcc_findings)
    print()

    # CHECK: shipped models whose conclusions reach no registry (v3.8.12)
    print("=" * 70)
    print("CHECK: UNREGISTERED-ANALYSIS (a conclusion nobody can check is not a result)")
    print("=" * 70)
    ua_findings = check_unregistered_analysis(package_root)
    print(f"  UNREGISTERED-ANALYSIS check: {len(ua_findings)} findings")
    all_findings.extend(ua_findings)
    print()

    # CHECK: registry values stated raw in Word documents (v3.8.9)
    print("=" * 70)
    print("CHECK: DOCX-FIGURE-UNTOKENISED (a literal in prose cannot drift-check)")
    print("=" * 70)
    dfu_findings = check_docx_untokenised_figures(package_root)
    print(f"  DOCX-FIGURE-UNTOKENISED check: {len(dfu_findings)} findings")
    all_findings.extend(dfu_findings)
    print()

    # CHECK: derivation blocks must equal their components (v3.8.7)
    print("=" * 70)
    print("CHECK: DERIVATION-SUM-DRIFT (a derived total must equal its parts)")
    print("=" * 70)
    dsd_findings = check_derivation_sums(package_root)
    print(f"  DERIVATION-SUM-DRIFT check: {len(dsd_findings)} findings")
    all_findings.extend(dsd_findings)
    print()

    # CHECK: figures resting on an unreproducible derivation (v3.7.812)
    print("=" * 70)
    print("CHECK: CITATION-DECLARED (a declared gap must stay countable)")
    print("=" * 70)
    cdl_findings = check_citation_declared(package_root)
    print(f"  CITATION-DECLARED check: {len(cdl_findings)} findings")
    all_findings.extend(cdl_findings)
    print()

    # CHECK: cited files must exist (v3.7.807)
    print("=" * 70)
    print("CHECK: CITATION-EXISTS (a citation that cannot be followed is not a citation)")
    print("=" * 70)
    ce_findings = check_citation_exists(package_root)
    print(f"  CITATION-EXISTS check: {len(ce_findings)} findings")
    all_findings.extend(ce_findings)
    print()

    # CHECK: spelled-out tracked-issue counts (v3.7.803)
    print("=" * 70)
    print("CHECK: COUNT-WORDFORM (spelled-out counts escape the canonical-count build)")
    print("=" * 70)
    cwf_findings = check_count_wordform(package_root)
    print(f"  COUNT-WORDFORM check: {len(cwf_findings)} findings")
    all_findings.extend(cwf_findings)
    print()

    # CHECK: scenario figures asserted without a qualifier (v3.7.803)
    print("=" * 70)
    print("CHECK: SCENARIO-UNQUALIFIED (projections must not be printed as measurements)")
    print("=" * 70)
    vlo_findings = check_versionlog_orphan_entry(package_root)
    all_findings.extend(vlo_findings)
    print("\n" + "=" * 70)
    print("CHECK: VERSIONLOG-ORPHAN (an entry for a release that never shipped)")
    print("=" * 70)
    print(f"  VERSIONLOG-ORPHAN check: {len(vlo_findings)} findings")

    gra_findings = check_glob_resolves_to_archive(package_root)
    all_findings.extend(gra_findings)
    print("\n" + "=" * 70)
    print("CHECK: GLOB-RESOLVES-TO-ARCHIVE (a check must read the live file)")
    print("=" * 70)
    print(f"  GLOB-RESOLVES-TO-ARCHIVE check: {len(gra_findings)} findings")

    gow_findings = check_generated_text_overwrote_authored(package_root)
    all_findings.extend(gow_findings)
    print("\n" + "=" * 70)
    print("CHECK: GENERATED-OVERWROTE-AUTHORED (a generator must not replace written text)")
    print("=" * 70)
    print(f"  GENERATED-OVERWROTE-AUTHORED check: {len(gow_findings)} findings")

    raz_findings = check_ratio_across_zero(package_root)
    all_findings.extend(raz_findings)
    print("\n" + "=" * 70)
    print("CHECK: RATIO-ACROSS-ZERO (no factor between endpoints of opposite sign)")
    print("=" * 70)
    print(f"  RATIO-ACROSS-ZERO check: {len(raz_findings)} findings")

    twa_findings = check_termination_opened_the_artifact(package_root)
    all_findings.extend(twa_findings)
    print("\n" + "=" * 70)
    print("CHECK: TERMINATION-WITHOUT-ARTIFACT (unreconstructible needs the file opened)")
    print("=" * 70)
    print(f"  TERMINATION-WITHOUT-ARTIFACT check: {len(twa_findings)} findings")

    cor_findings = check_cited_only_role(package_root)
    all_findings.extend(cor_findings)
    print("\n" + "=" * 70)
    print("CHECK: CITED-ONLY-UNEXPLAINED (a source with no archive must say what it is for)")
    print("=" * 70)
    print(f"  CITED-ONLY-UNEXPLAINED check: {len(cor_findings)} findings")

    drn_findings = check_declared_driver_reaches_nothing(package_root)
    all_findings.extend(drn_findings)
    print("\n" + "=" * 70)
    print("CHECK: DRIVER-REACHES-NOTHING (a declared driver must move something)")
    print("=" * 70)
    print(f"  DRIVER-REACHES-NOTHING check: {len(drn_findings)} findings")

    dup_findings = check_duplicate_figures(package_root)
    all_findings.extend(dup_findings)
    print("\n" + "=" * 70)
    print("CHECK: DUPLICATE-FIGURE (two entries for one quantity, unconnected)")
    print("=" * 70)
    print(f"  DUPLICATE-FIGURE check: {len(dup_findings)} findings")

    tru_findings = check_test_result_without_reason(package_root)
    all_findings.extend(tru_findings)
    print("\n" + "=" * 70)
    print("CHECK: TEST-RESULT-UNEXPLAINED (a failing test must say why)")
    print("=" * 70)
    print(f"  TEST-RESULT-UNEXPLAINED check: {len(tru_findings)} findings")

    trp_findings = check_triage_reclassification_preserved(package_root)
    all_findings.extend(trp_findings)
    print("\n" + "=" * 70)
    print("CHECK: TRIAGE-RECLASSIFICATION-LOST (a hand judgement must survive a write)")
    print("=" * 70)
    print(f"  TRIAGE-RECLASSIFICATION-LOST check: {len(trp_findings)} findings")

    vsi_findings = check_version_stamp_inflation(package_root)
    all_findings.extend(vsi_findings)
    print("\n" + "=" * 70)
    print("CHECK: VERSION-STAMP-INFLATION (a release must not claim work it did not do)")
    print("=" * 70)
    print(f"  VERSION-STAMP-INFLATION check: {len(vsi_findings)} findings")

    squ_findings = check_scenario_unqualified(package_root)
    print(f"  SCENARIO-UNQUALIFIED check: {len(squ_findings)} findings")
    all_findings.extend(squ_findings)
    print()

    # CHECK: CSS hardcoded-color debt ratchet (added v3.7.447)
    print("=" * 70)
    print("CHECK: CSS-DEBT-RATCHET (hardcoded color literals can only shrink)")
    print("=" * 70)
    cd_findings = check_css_debt_ratchet(package_root)
    print(f"  CSS-DEBT-RATCHET check: {len(cd_findings)} findings")
    all_findings.extend(cd_findings)
    print()

    # CHECK: Findability — named tools must have direct nav from landing page (added v3.7.54)
    print("=" * 70)
    print("CHECK: Findability (named tools linked from landing page)")
    print("=" * 70)
    fnd_findings = check_findability()
    print(f"  Findability check: {len(fnd_findings)} findings")
    all_findings.extend(fnd_findings)

    # CHECK: Pillar reference verification (added v3.7.70 per OIR S176)
    print("=" * 70)
    print("CHECK: Pillar reference verification (Pillar N (Name) → canonical)")
    print("=" * 70)
    pillar_findings = check_pillar_references(verbose=True)
    print(f"  Pillar reference check: {len(pillar_findings)} findings")
    all_findings.extend(pillar_findings)
    print()

    # CHECK: CSS token resolution (added v3.7.75 per OIR S181)
    print("=" * 70)
    print("CHECK: CSS token resolution (every var(--TOKEN) has a definition)")
    print("=" * 70)
    css_token_findings = check_css_token_resolution(verbose=True)
    print(f"  CSS token resolution check: {len(css_token_findings)} findings")
    all_findings.extend(css_token_findings)
    print()

    # CHECK: CSS tokens defined but never used (added v3.7.93 — inverse of v3.7.75)
    print("=" * 70)
    print("CHECK: CSS tokens defined but never referenced (CSS-TOKEN-DEFINED-UNUSED)")
    print("=" * 70)
    css_definitions_findings = check_css_token_definitions(verbose=True)
    print(f"  CSS token definitions check: {len(css_definitions_findings)} findings")
    all_findings.extend(css_definitions_findings)
    print()

    # CHECK: HTML class → CSS rule existence (added v3.7.76 per OIR S182)
    print("=" * 70)
    print("CHECK: HTML class → CSS rule existence (catches v3.7.71 pattern)")
    print("=" * 70)
    class_css_findings = check_html_class_css_existence(verbose=True)
    print(f"  HTML class → CSS check: {len(class_css_findings)} findings")
    all_findings.extend(class_css_findings)
    print()

    # CHECK: Link/src resolution (added v3.7.76 per OIR S182)
    print("=" * 70)
    print("CHECK: Internal link/src resolution (filters JS template literals)")
    print("=" * 70)
    link_findings = check_link_resolution(verbose=True)
    print(f"  Link resolution check: {len(link_findings)} findings")
    all_findings.extend(link_findings)
    print()

    # CHECK: Reading-path catalog consistency (added v3.7.76 per OIR S182)
    print("=" * 70)
    print("CHECK: Reading-path documents are in catalog + new-doc orphans")
    print("=" * 70)
    rp_findings = check_reading_path_catalog_consistency(verbose=True)
    print(f"  Reading-path catalog check: {len(rp_findings)} findings")
    all_findings.extend(rp_findings)
    print()

    # CHECK: Section number uniqueness in section-numbered docs (added v3.7.78 per OIR S184)
    print("=" * 70)
    print("CHECK: Section number uniqueness in section-numbered docs (OIR, TOC)")
    print("=" * 70)
    section_num_findings = check_section_number_uniqueness(verbose=True)
    print(f"  Section number uniqueness check: {len(section_num_findings)} findings")
    all_findings.extend(section_num_findings)
    print()

    # CHECK: Catalog metadata consistency — totalDocuments, folders array (added v3.7.87 per OIR S194)
    print("=" * 70)
    print("CHECK: Catalog metadata consistency (totalDocuments, folders array)")
    print("=" * 70)
    catmeta_findings = check_catalog_metadata_consistency(verbose=True)
    print(f"  Catalog metadata check: {len(catmeta_findings)} findings")
    all_findings.extend(catmeta_findings)
    print()

    print()

    # CHECK: Per-page metadata consistency — doc counts must match catalog (added v3.7.54)
    print("=" * 70)
    print("CHECK: Per-page metadata consistency (page doc counts match catalog)")
    print("=" * 70)
    meta_findings = check_per_page_metadata_consistency()
    print(f"  Metadata consistency check: {len(meta_findings)} findings")
    all_findings.extend(meta_findings)
    print()

    # CHECK: renderCard simulation — catalog docs must have all fields the JS accesses (added v3.7.61)
    print("=" * 70)
    print("CHECK: renderCard simulation (catalog field completeness for JS rendering)")
    print("=" * 70)
    rc_findings = check_renderCard_simulation()
    print(f"  renderCard simulation: {len(rc_findings)} findings")
    all_findings.extend(rc_findings)
    print()

    # CHECK: CSS-insertion verification — critical CSS rules must be present (added v3.7.57)
    print("=" * 70)
    print("CHECK: CSS-insertion verification (critical CSS rules present)")
    print("=" * 70)
    css_findings = check_css_insertions()
    print(f"  CSS-insertion check: {len(css_findings)} findings")
    all_findings.extend(css_findings)
    print()

    # CHECK: Tricolor middle stripe drift — added v3.7.333 in response to v3.7.332 bug
    print("=" * 70)
    print("CHECK: Tricolor middle stripe drift (no var(--paper) on flag's white stripe)")
    print("=" * 70)
    tricolor_findings = check_tricolor_drift()
    print(f"  Tricolor drift check: {len(tricolor_findings)} findings")
    all_findings.extend(tricolor_findings)
    print()

    
    # CHECK: Cross-references valid
    print("=" * 70)
    print("CHECK: Cross-references valid (1-81)")
    print("=" * 70)
    findings, n_refs, invalid = audit_cross_references(all_docs)
    print(f"  Refs found: {n_refs} unique, invalid: {invalid}")
    all_findings.extend(findings)
    
    # CHECK: Manifest integrity
    pv_path = os.path.join(package_root, "01_Start_Here/01_Platform_Package_Version.docx")
    if os.path.exists(pv_path):
        pv_doc = get_docx(pv_path)  # v3.7.90 cached
        print()
        print("=" * 70)
        print("CHECK: Manifest integrity")
        print("=" * 70)
        findings, n_files, n_manifest, orphans = audit_manifest_integrity(package_root, pv_doc)
        print(f"  Files: {n_files}, manifest: {n_manifest}, orphans: {orphans}")
        all_findings.extend(findings)
    
    # CHECK: Iteration-count pattern sweep
    print()
    print("=" * 70)
    print("CHECK: Iteration-count pattern sweep with whitelist + heuristic")
    print("=" * 70)
    pattern = r'[Tt]welve [Ii]terations'
    findings, (wl_n, hist_n, flag_n) = audit_pattern_sweep(all_docs, pattern, "ITER-COUNT", wl_entries)
    print(f"  Whitelisted (exact-match): {wl_n}")
    print(f"  Historical (heuristic): {hist_n}")
    print(f"  Flagged: {flag_n}")
    all_findings.extend(findings)
    
    # CHECK: Whitelist robustness — all entries find paragraphs
    print()
    print("=" * 70)
    print("CHECK: Whitelist robustness")
    print("=" * 70)
    for entry in wl_entries:
        # v3.8.251: a whole-document exemption carries no paragraph text to match, by
        # design -- its TEXT block is a placeholder. Checking it here would report a MISS
        # forever. Its own integrity (reason recorded, banner present in the document) is
        # enforced by check_historical_exemption instead.
        if entry.get('scope') == 'whole-document':
            print(f"  [SCOPE] {entry['file'][:50]} (whole-document; see HISTORICAL-EXEMPTION)")
            continue
        found = False
        for path in all_docs.keys():
            if entry['file'] in path.replace("\\", "/").split("/")[-1]:  # v3.7.593: handle Windows backslash paths
                doc = get_docx(path)  # v3.7.90 cached
                if doc is None:  # v3.7.592: skip docx that failed to parse
                    continue
                # v3.8.536: compare with the generated currency stamp removed. The stamp is regenerated each
                # release and appended to version lines, so a whitelist entry quoting a version line would stop
                # matching the moment its document was stamped (09_Iterative_Hardening_Process_Documentation,
                # first stamped v3.8.536). Same pattern as tools/stamp_document_currency.py.
                _nostamp = lambda t: re.sub(r"\s*·\s*(?:ships in package|content last changed) v[\d.]+", "", t).strip()
                for p in doc.paragraphs:
                    if _nostamp(p.text) == _nostamp(entry['text']):
                        found = True
                        break
                # v3.8.469: TABLE CELLS COUNT TOO. The scanners read documents through pandoc,
                # which renders tables; this matcher read only paragraphs. So a false positive
                # living in a table could be found by the audit AND NEVER WHITELISTED -- the
                # entry would be reported as not matching anything. That is what happened to the
                # verbatim Gemini quotation in table 12 of 07_Response_To_Gemini_Review.docx.
                if not found:
                    for table in doc.tables:
                        for row in table.rows:
                            for cell in row.cells:
                                if _nostamp(cell.text) == _nostamp(entry['text']):
                                    found = True
                                    break
                            if found:
                                break
                        if found:
                            break
                break
        status = "OK" if found else "MISS"
        print(f"  [{status}] {entry['file'][:50]} ({entry['stability']})")
        if not found:
            all_findings.append(("MIN", "WL-NOT-FOUND", entry['file'],
                                f"Entry text doesn't match any paragraph (likely needs version-bumped maintenance)"))
    
    # CHECK: Recursive meta-trigger patterns in current iteration narratives
    print()
    print("=" * 70)
    print("CHECK: Recursive meta-trigger patterns in current iteration narratives")
    print("=" * 70)
    narrative_findings = audit_current_iteration_narratives(package_root)
    if narrative_findings:
        print(f"  Flagged: {len(narrative_findings)} occurrences across narrative locations")
    else:
        print(f"  Clean: all current iteration narratives use abstracted language")
    all_findings.extend(narrative_findings)
    
    # FINAL REPORT
    print()
    print("=" * 70)
    sig = sum(1 for f in all_findings if f[0] == "SIG")
    min_ = sum(1 for f in all_findings if f[0] == "MIN")
    obs = sum(1 for f in all_findings if f[0] == "OBS")
    print(f"AUDIT COMPLETE: {len(all_findings)} findings ({sig} SIG, {min_} MIN, {obs} OBS)")
    print("=" * 70)
    for severity, fid, doc_, desc in all_findings:
        # v3.8.468: THE FINAL REPORT IS THE ONE EVERY OPERATOR READS, and it dropped doc_ --
        # the file, path or id that says WHERE the finding is. Every check records it; this
        # line unpacked four fields and printed three. A BASELINE-CONSISTENCY finding told the
        # author a wrong value existed somewhere among 160 documents and left him to search.
        # v3.8.467 fixed a DIFFERENT printer -- one check's own verbose loop -- and changed
        # nothing he could see, which is why this is a second release on one defect.
        where = f"  [{doc_}]" if doc_ and str(doc_) not in desc[:200] else ""
        print(f"  [{severity}] {fid}: {desc[:200]}{where}")
    
    return all_findings



def check_catalog_metadata_consistency(verbose=False):
    """v3.7.87 — Detect stale/inconsistent catalog metadata fields.

    Catches the v3.7.86 class of issue where totalDocuments=115 when
    the documents array has 118 entries, and where folders array is
    missing entries for folders that have docs. Does not check
    generatedDate (it legitimately drifts between bump runs).
    """
    import json
    from collections import Counter

    findings = []
    catalog_path = "00_GUI_Files/platform_catalog.json"
    try:
        cat = get_catalog()  # v3.7.90 cached
    except Exception as e:
        if verbose: print(f"  Could not read catalog: {e}")
        return findings

    actual_count = len(cat.get("documents", []))
    declared_count = cat.get("totalDocuments")
    # v3.7.259: pass catalog_path as the doc identifier so the main
    # report's 4-element-tuple expectation matches.
    if declared_count is not None and declared_count != actual_count:
        findings.append(("MIN", "CATALOG-METADATA-STALE", catalog_path,
            "totalDocuments=" + str(declared_count) + " but documents array has " + str(actual_count) + " entries"))

    declared_folders = set()
    for f in cat.get("folders", []):
        if isinstance(f, dict) and "id" in f:
            declared_folders.add(f["id"])

    actual_folders = set(
        d.get("folder", "") for d in cat.get("documents", [])
        if d.get("folder") and d.get("folder") != "(root)"
    )
    missing_from_array = actual_folders - declared_folders
    extra_in_array = declared_folders - actual_folders
    if missing_from_array:
        findings.append(("MIN", "CATALOG-METADATA-STALE", catalog_path,
            "folders array missing entries for: " + str(sorted(missing_from_array))))
    if extra_in_array:
        findings.append(("MIN", "CATALOG-METADATA-STALE", catalog_path,
            "folders array has stale entries: " + str(sorted(extra_in_array))))

    for folder in cat.get("folders", []):
        if isinstance(folder, dict) and folder.get("label") == folder.get("id"):
            findings.append(("MIN", "CATALOG-METADATA-STALE", catalog_path,
                "folder " + repr(folder.get("id")) + " has label equal to id (missing human-readable label)"))

    if verbose:
        for sev, code, doc_, msg in findings:
            print(f"  [{sev}] {code}: {msg}"
                      # v3.8.467: the label is WHERE the finding is, and the printer dropped it.
                      # Every check records a file or an id as its third element and no operator
                      # ever saw one: a BASELINE-CONSISTENCY finding said a wrong value existed
                      # somewhere in 160 documents and left the author to search for it.
                      + (f"  [{doc_}]" if doc_ and str(doc_) not in msg else ""))
    return findings


def audit_meta_drift(package_root):
    """v3.7.235: Detect meta-files drifting behind PV doc version.

    Checks manifest.json platform_version and cloudflare/worker.js
    PLATFORM_META.version. Flags MIN if either is more than 1 patch
    version behind PV. Catches the class of drift that accumulated
    to ~60 iterations behind before discovery in v3.7.234.
    """
    findings = []

    # 1. Get PV version (authoritative)
    pv_path = os.path.join(package_root, "01_Start_Here",
                           "01_Platform_Package_Version.docx")
    try:
        from docx import Document as _Doc
        d = _Doc(pv_path)
        pv_version = None
        for p in d.paragraphs[:100]:
            m = re.match(r"Version (3\.7\.(\d+))", p.text)
            if m:
                pv_version = (m.group(1), int(m.group(2)))
                break
        if pv_version is None:
            return findings
    except Exception:
        return findings

    pv_str, pv_patch = pv_version

    # 2. Check manifest.json
    manifest_path = os.path.join(package_root, "manifest.json")
    if os.path.exists(manifest_path):
        try:
            import json as _json
            with open(manifest_path, encoding="utf-8") as f:
                m = _json.load(f)
            mv = m.get("platform_version", "")
            mm = re.match(r"3\.7\.(\d+)", mv)
            if mm:
                manifest_patch = int(mm.group(1))
                drift = pv_patch - manifest_patch
                if drift > 1:
                    findings.append((
                        "MIN", "META-DRIFT-STALE", "manifest.json",
                        f"manifest.json platform_version is {mv} but PV is {pv_str} ({drift} versions behind). Run tools/build_manifest.py."
                    ))
        except Exception:
            pass

    # 3. Check cloudflare/worker.js PLATFORM_META
    worker_path = os.path.join(package_root, "cloudflare", "worker.js")
    if os.path.exists(worker_path):
        try:
            with open(worker_path, encoding="utf-8") as f:
                wtext = f.read()
            wm = re.search(r"version:\s*'(3\.7\.(\d+))'", wtext)
            if wm:
                worker_v = wm.group(1)
                worker_patch = int(wm.group(2))
                drift = pv_patch - worker_patch
                if drift > 1:
                    findings.append((
                        "MIN", "META-DRIFT-STALE", "cloudflare/worker.js",
                        f"worker PLATFORM_META.version is {worker_v} but PV is {pv_str} ({drift} versions behind). Run tools/build_cloudflare_worker_meta.py."
                    ))
        except Exception:
            pass

    # 4. Check version.json
    vjson_path = os.path.join(package_root, "version.json")
    if os.path.exists(vjson_path):
        try:
            import json as _json
            with open(vjson_path, encoding="utf-8") as f:
                v = _json.load(f)
            vv = v.get("platform_version", "")
            vm = re.match(r"3\.7\.(\d+)", vv)
            if vm:
                version_json_patch = int(vm.group(1))
                drift = pv_patch - version_json_patch
                if drift > 1:
                    findings.append((
                        "MIN", "META-DRIFT-STALE", "version.json",
                        f"version.json platform_version is {vv} but PV is {pv_str} ({drift} versions behind). Run tools/build_version_json.py."
                    ))
        except Exception:
            pass

    return findings



if __name__ == "__main__":
    package_root = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.abspath(__file__))
    globals()["PACKAGE_ROOT"] = os.path.abspath(package_root)
    findings = main(package_root)
    # Exit with non-zero if SIG findings present
    sig_findings = [f for f in findings if f[0] == "SIG"]
    sys.exit(1 if sig_findings else 0)
