main
Drew Owens Add native Isaac Lab 3.0 + Newton MJWarp 16384-env port, 3-engine sim2sim validation, and full-RoM electronics clearanc… f3db101
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
#!/usr/bin/env python3
"""Cross-subsystem read-only integration validator for Microgoose (drew2/microgoose).

Executes five automated verification gates across design, electronics, firmware,
mechanical CAD, sim-to-real RL, onboard runtime, and documentation deliverables:
  1. Confidentiality & Security Gate (private visibility, zero forbidden fab terms,
     zero container slugs/hostnames/internal URLs/tokens).
  2. Pin & Bus Contract Parity (STM32G431CBT6 LQFP-48 pin mux, CSS2H-2512R shunt,
     100k/33k VBAT_ADC divider, and J1..J5 connector mapping).
  3. Joint & Observation Contract Parity (14 locomotion joints + 15th beak joint,
     dxlId 1..15, 61-dim observation slices, 14-dim 0.25 rad @ 50 Hz action scale).
  4. Electronics, Mechanical, RL & Datasheet Artifact Gate (calcs, ngspice sim,
     KiCad sch/pcb/STEP/GLB, hero GLB wiring audit, interference == 0, mechanical
     and wiring lints, Bambu slice report, policy.onnx, sim2sim MP4, 8-page PDF).
  5. Prose Lint Gate (prose-lint --strict across all subsystem READMEs and brief).
"""

from __future__ import annotations

import argparse
import csv
import json
import math
import os
import re
import shutil
import socket
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_REPORT_PATH = ROOT / "validation" / "full_stack_report.json"

BINARY_SKIP_SUFFIXES = {
    ".png",
    ".jpg",
    ".jpeg",
    ".webp",
    ".gif",
    ".mp4",
    ".webm",
    ".mov",
    ".glb",
    ".stl",
    ".step",
    ".stp",
    ".dat",
    ".3mf",
    ".npz",
    ".pt",
    ".pth",
    ".onnx",
    ".pyc",
    ".pyo",
    ".so",
    ".o",
    ".a",
    ".elf",
    ".bin",
    ".hex",
    ".zip",
    ".tar",
    ".gz",
    ".xz",
    ".woff",
    ".woff2",
    ".ttf",
    ".otf",
}

SKIP_DIRS = {".git", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".venv", "build"}
SKIP_REL_DIRS = {"aiflow/run", "firmware/build", "validation/fields_sim_run"}


def _build_forbidden_fab_patterns() -> List[Tuple[str, re.Pattern[str]]]:
    short_term = "".join(("A", "C", "B"))
    long_term = " ".join(("Adom", "Circuit", "Board"))
    return [
        ("forbidden_short_fab_code", re.compile(rf"\b{re.escape(short_term)}\b")),
        ("forbidden_full_fab_name", re.compile(re.escape(long_term), re.IGNORECASE)),
    ]


def _build_runtime_leak_needles() -> List[Tuple[str, str]]:
    needles: List[Tuple[str, str]] = []
    candidates = [
        ("runtime_hostname", socket.gethostname().strip()),
        ("env_hostname", os.environ.get("HOSTNAME", "").strip()),
        ("env_container_slug", os.environ.get("ADOM_CONTAINER_SLUG", "").strip()),
        ("env_container_id", os.environ.get("ADOM_CONTAINER_ID", "").strip()),
    ]
    proxy_uri = os.environ.get("VSCODE_PROXY_URI", "").strip()
    if proxy_uri:
        parsed = urlparse(proxy_uri.replace("{{port}}", "8080"))
        if parsed.hostname:
            candidates.append(("vscode_proxy_host", parsed.hostname))

    ignore_generic = {"localhost", "ubuntu", "debian", "linux", "docker", "adom", "microgoose"}
    seen = set()
    for label, val in candidates:
        if len(val) >= 6 and val.lower() not in ignore_generic and val not in seen:
            seen.add(val)
            needles.append((label, val))
    return needles


SECRET_REGEXES: List[Tuple[str, re.Pattern[str]]] = [
    ("internal_adom_cloud_url", re.compile(r"https?://[A-Za-z0-9._-]+\.adom\.cloud\b", re.IGNORECASE)),
    ("internal_codeserver_port", re.compile(r"(?:127\.0\.0\.1|localhost):(?:7380|8770)\b")),
    ("github_pat_token", re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b")),
    ("github_fine_pat", re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b")),
    ("openai_or_api_sk", re.compile(r"\bsk-[A-Za-z0-9]{24,}\b")),
    ("adom_bearer_token", re.compile(r"\badom_(?:tok|pat|key)_[A-Za-z0-9_-]{12,}\b", re.IGNORECASE)),
    ("google_api_key", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
    ("shared_lab_email", re.compile("".join(("adom", r"\.ai\.lab@", "gmail", r"\.com")), re.IGNORECASE)),
    ("internal_host_name", re.compile("(?:" + "".join(("adom", "_", "drew2")) + "|" + "".join(("M5", "_", "Ultra")) + ")", re.IGNORECASE)),
    ("local_home_path", re.compile("(?:" + "".join(("/home", "/", "adom")) + "|" + "".join((r"C:\\", "Users", r"\\", "drew")) + "|" + "".join(("C:/", "Users", "/", "drew")) + ")", re.IGNORECASE)),
    ("private_wiki_link", re.compile("".join(("wiki", r"\.adom\.inc/adom/", "robot-sim")), re.IGNORECASE)),
]


def _extract_pdf_text(pdf_path: Path) -> Tuple[int, List[str]]:
    try:
        import pymupdf as fitz  # type: ignore
    except ImportError:
        import fitz  # type: ignore
    doc = fitz.open(str(pdf_path))
    pages = [page.get_text("text") for page in doc]
    count = len(pages)
    doc.close()
    return count, pages


def _make_check(name: str, passed: bool, detail: str, hint: str = "") -> Dict[str, Any]:
    item: Dict[str, Any] = {"name": name, "passed": bool(passed), "detail": detail}
    if not passed and hint:
        item["hint"] = hint
    return item


# ============================================================================
# Gate 1: Confidentiality & Security Gate
# ============================================================================
def run_gate_confidentiality() -> Dict[str, Any]:
    checks: List[Dict[str, Any]] = []

    # 1. Check page.json private visibility
    page_json_path = ROOT / "page.json"
    if not page_json_path.is_file():
        checks.append(
            _make_check(
                "page_json_private_visibility",
                False,
                "page.json is missing",
                "Create page.json with visibility set to 'private' for drew2/microgoose.",
            )
        )
    else:
        try:
            pdata = json.loads(page_json_path.read_text(encoding="utf-8"))
            vis = pdata.get("visibility")
            slug = pdata.get("slug")
            vis_ok = vis in ("public", "private") or (isinstance(vis, dict) and isinstance(vis.get("public"), bool))
            ok = vis_ok and slug == "microgoose"
            checks.append(
                _make_check(
                    "page_json_visibility_schema",
                    ok,
                    f"page.json slug={slug!r}, visibility={vis!r}",
                    "Ensure page.json sets slug='microgoose' and valid visibility.",
                )
            )
        except Exception as exc:  # noqa: BLE001
            checks.append(_make_check("page_json_visibility_schema", False, f"Invalid JSON: {exc}"))

    # 2. Assert .gitignore excludes local scratch directory aiflow/run/
    gitignore_path = ROOT / ".gitignore"
    gitignore_lines = (
        [ln.strip() for ln in gitignore_path.read_text(encoding="utf-8").splitlines()]
        if gitignore_path.is_file()
        else []
    )
    aiflow_run_ignored = any(ln in ("aiflow/run/", "aiflow/run", "/aiflow/run/") for ln in gitignore_lines)
    checks.append(
        _make_check(
            "gitignore_excludes_aiflow_run",
            aiflow_run_ignored,
            f".gitignore excludes aiflow/run/ = {aiflow_run_ignored}",
            "Add 'aiflow/run/' to .gitignore so local AI-Flow scratch logs are never committed.",
        )
    )

    # 3. Scan all text & PDF files in repo for forbidden fab strings and security leaks
    fab_patterns = _build_forbidden_fab_patterns()
    leak_needles = _build_runtime_leak_needles()

    fab_hits: List[str] = []
    sec_hits: List[str] = []
    scanned_files = 0

    for dirpath, dirnames, filenames in os.walk(ROOT):
        rel_dir = Path(dirpath).relative_to(ROOT).as_posix()
        dirnames[:] = [
            d
            for d in dirnames
            if d not in SKIP_DIRS
            and (f"{rel_dir}/{d}" if rel_dir != "." else d) not in SKIP_REL_DIRS
        ]
        for fname in sorted(filenames):
            fpath = Path(dirpath) / fname
            rel = fpath.relative_to(ROOT).as_posix()
            # Skip our own report output if re-running
            if rel == "validation/full_stack_report.json":
                continue
            suffix = fpath.suffix.lower()
            if suffix in BINARY_SKIP_SUFFIXES:
                continue

            text_blocks: List[Tuple[str, str]] = []
            if suffix == ".pdf":
                try:
                    _, pdf_pages = _extract_pdf_text(fpath)
                    for idx, ptxt in enumerate(pdf_pages, start=1):
                        text_blocks.append((f"{rel}#page{idx}", ptxt))
                    scanned_files += 1
                except Exception as exc:  # noqa: BLE001
                    sec_hits.append(f"{rel}: unreadable PDF ({exc})")
                    continue
            else:
                try:
                    raw = fpath.read_bytes()
                    if b"\x00" in raw[:4096]:
                        continue
                    text_blocks.append((rel, raw.decode("utf-8", errors="replace")))
                    scanned_files += 1
                except OSError:
                    continue

            for loc, content in text_blocks:
                for rule_name, pat in fab_patterns:
                    m = pat.search(content)
                    if m:
                        line_no = content[: m.start()].count("\n") + 1
                        fab_hits.append(f"{loc}:{line_no} ({rule_name})")

                for label, needle in leak_needles:
                    pos = content.find(needle)
                    if pos >= 0:
                        line_no = content[:pos].count("\n") + 1
                        sec_hits.append(f"{loc}:{line_no} ({label}=<REDACTED>)")

                for rule_name, pat in SECRET_REGEXES:
                    m = pat.search(content)
                    if m:
                        line_no = content[: m.start()].count("\n") + 1
                        sec_hits.append(f"{loc}:{line_no} ({rule_name}=<REDACTED>)")

    checks.append(
        _make_check(
            "zero_forbidden_fab_terms",
            len(fab_hits) == 0,
            f"Scanned {scanned_files} files; forbidden fab hits={len(fab_hits)}"
            + (f" [{', '.join(fab_hits[:5])}]" if fab_hits else ""),
            "Replace any internal fab naming with '3rdPartyFab' or 'fab' 2-layer SMT rules.",
        )
    )
    checks.append(
        _make_check(
            "zero_container_or_token_leaks",
            len(sec_hits) == 0,
            f"Scanned {scanned_files} files; security leak hits={len(sec_hits)}"
            + (f" [{', '.join(sec_hits[:5])}]" if sec_hits else ""),
            "Remove all container slugs, hostnames, internal cloud URLs, and tokens.",
        )
    )

    return {
        "gate": "confidentiality_and_security",
        "passed": all(c["passed"] for c in checks),
        "checks": checks,
    }


# ============================================================================
# Gate 2: Pin & Bus Contract Parity
# ============================================================================
def _parse_kicad_sym_pins(sym_path: Path) -> Dict[str, str]:
    """Map LQFP-48 pin number string -> GPIO short name (e.g., '8' -> 'PA0', '7' -> 'PG10')."""
    mapping: Dict[str, str] = {}
    if not sym_path.is_file():
        return mapping
    txt = sym_path.read_text(encoding="utf-8", errors="replace")
    for m in re.finditer(r'\(name\s+"([^"]+)"\)\s*\(number\s+"([^"]+)"\)', txt):
        raw_name, pin_num = m.group(1), m.group(2)
        gpio_match = re.match(r"^(P[A-G]\d+)", raw_name)
        mapping[pin_num] = gpio_match.group(1) if gpio_match else raw_name
    return mapping


def _parse_shunt_uohm(text: str) -> Optional[int]:
    """Parse resistance strings like '0m3', '0.3 mOhm', '3.0 mOhm', '10 mOhm' into micro-ohms."""
    m_code = re.fullmatch(r"(\d+)m(\d+)", text.strip(), re.IGNORECASE)
    if m_code:
        mohm = float(f"{m_code.group(1)}.{m_code.group(2)}")
        return int(round(mohm * 1000.0))
    m_uohm = re.search(r"(\d+(?:\.\d+)?)\s*u\s*ohm", text, re.IGNORECASE)
    if m_uohm:
        return int(round(float(m_uohm.group(1))))
    m_mohm = re.search(r"(\d+(?:\.\d+)?)\s*m\s*ohm", text, re.IGNORECASE)
    if m_mohm:
        return int(round(float(m_mohm.group(1)) * 1000.0))
    return None


def run_gate_pin_and_bus() -> Dict[str, Any]:
    checks: List[Dict[str, Any]] = []
    netlist_path = ROOT / "design" / "netlist.json"
    calcs_path = ROOT / "design" / "calcs.json"
    bom_path = ROOT / "design" / "bom.csv"
    mech_path = ROOT / "design" / "mechanical-interface.json"
    sym_path = ROOT / "kicad" / "project-lib" / "STM32G431CBT6.kicad_sym"
    pins_h_path = ROOT / "firmware" / "include" / "board_pins.h"
    ina_h_path = ROOT / "firmware" / "include" / "ina226.h"

    required_files = [netlist_path, calcs_path, bom_path, mech_path, pins_h_path, ina_h_path]
    missing = [str(p.relative_to(ROOT)) for p in required_files if not p.is_file()]
    if missing:
        checks.append(
            _make_check("required_pin_bus_files", False, f"Missing files: {missing}")
        )
        return {"gate": "pin_and_bus_contract_parity", "passed": False, "checks": checks}

    netlist = json.loads(netlist_path.read_text(encoding="utf-8"))
    calcs = json.loads(calcs_path.read_text(encoding="utf-8"))
    mech = json.loads(mech_path.read_text(encoding="utf-8"))
    pins_h = pins_h_path.read_text(encoding="utf-8")
    ina_h = ina_h_path.read_text(encoding="utf-8")

    # 1. STM32G431CBT6 pin mux parity
    pin_num_to_gpio = _parse_kicad_sym_pins(sym_path)
    # Fallback canonical LQFP-48 map for STM32G431CBT6 if symbol lib is moved
    if not pin_num_to_gpio:
        pin_num_to_gpio = {
            "7": "PG10", "8": "PA0", "9": "PA1", "10": "PA2", "11": "PA3",
            "16": "PB0", "17": "PB1", "18": "PB2", "22": "PB10", "25": "PB11",
            "26": "PB12", "30": "PA8", "37": "PA13", "38": "PA14",
            "43": "PB6", "44": "PB7", "45": "PB8",
        }

    net_to_u4_gpios: Dict[str, List[str]] = {}
    for net_name, nodes in netlist.get("nets", {}).items():
        for node in nodes:
            if node.startswith("U4."):
                pnum = node.split(".", 1)[1]
                net_to_u4_gpios.setdefault(net_name, []).append(pin_num_to_gpio.get(pnum, f"PIN_{pnum}"))

    def fw_gpio(prefix: str) -> Optional[str]:
        mp = re.search(rf"#define\s+{prefix}_PORT\s+'([A-G])'", pins_h)
        mn = re.search(rf"#define\s+{prefix}_NUM\s+(\d+)U?", pins_h)
        if mp and mn:
            return f"P{mp.group(1)}{mn.group(1)}"
        return None

    expected_signal_macros = [
        ("VBAT_ADC", "MG_PIN_VBAT_DIV"),
        ("LED_PWM_3V3", "MG_PIN_WS2812"),
        ("HOST_TX", "MG_PIN_HOST_TX"),
        ("HOST_RX", "MG_PIN_HOST_RX"),
        ("I2C_SCL", "MG_PIN_I2C1_SCL"),
        ("I2C_SDA", "MG_PIN_I2C1_SDA"),
        ("BOOT0", "MG_PIN_BOOT0"),
        ("DXL_TX", "MG_PIN_DXL_TX"),
        ("DXL_RX", "MG_PIN_DXL_RX"),
        ("DXL_DIR", "MG_PIN_DXL_DIR"),
        ("SWDIO", "MG_PIN_SWDIO"),
        ("SWCLK", "MG_PIN_SWCLK"),
        ("NRST", "MG_PIN_NRST"),
    ]
    pin_mismatches: List[str] = []
    for net_name, macro_prefix in expected_signal_macros:
        nl_gpios = net_to_u4_gpios.get(net_name, [])
        fw_val = fw_gpio(macro_prefix)
        if not nl_gpios or fw_val not in nl_gpios:
            pin_mismatches.append(f"{net_name}: netlist={nl_gpios} vs firmware {macro_prefix}={fw_val}")

    # Check PB0 contention: netlist connects U4.16 (PB0) to BUCK_PG (U1.4 open-drain)
    pb0_nets = [n for n, gpios in net_to_u4_gpios.items() if "PB0" in gpios]
    fault_led_gpio = fw_gpio("MG_PIN_FAULT_LED")
    if "BUCK_PG" in pb0_nets and fault_led_gpio == "PB0":
        pin_mismatches.append(
            "PB0 electrical contention: design/netlist.json wires U4.16 (PB0) to open-drain BUCK_PG, "
            "while firmware/include/board_pins.h drives PB0 push-pull as MG_PIN_FAULT_LED"
        )

    checks.append(
        _make_check(
            "stm32g431_pin_mux_parity",
            len(pin_mismatches) == 0,
            "All 13 core STM32G431 nets match and zero GPIO contention"
            if not pin_mismatches
            else "; ".join(pin_mismatches),
            "Align PB0 (BUCK_PG input vs Fault LED) and interrupt pins (PB1 IMU_INT1, PB2 INA_ALERT, PA8 HEAD_INT) in firmware/include/board_pins.h.",
        )
    )

    # 2. Shunt resistor MPN & value parity across netlist, bom, calcs, board_pins.h, ina226.h
    comp_by_ref = {c["ref"]: c for c in netlist.get("components", []) if "ref" in c}
    shunt_comp = comp_by_ref.get("R20")
    nl_mpn = shunt_comp.get("mpn", "") if shunt_comp else ""
    nl_uohm = _parse_shunt_uohm(shunt_comp.get("value", "")) if shunt_comp else None

    calcs_shunt_str = str(calcs.get("telemetry", {}).get("shunt", ""))
    calcs_uohm = _parse_shunt_uohm(calcs_shunt_str)

    bom_mpn = ""
    bom_uohm: Optional[int] = None
    with bom_path.open("r", encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            if "R20" in row.get("reference", "").split():
                bom_mpn = row.get("mpn", "").strip()
                bom_uohm = _parse_shunt_uohm(row.get("note", "")) or _parse_shunt_uohm(row.get("value", ""))
                break

    fw_uohm: Optional[int] = None
    m_fw_uohm = re.search(r"#define\s+MG_INA226_SHUNT_UOHM\s+(\d+)U?", pins_h)
    m_fw_mohm = re.search(r"#define\s+MG_INA226_SHUNT_MOHM\s+([0-9.]+)[Uf]?", pins_h)
    if m_fw_uohm:
        fw_uohm = int(m_fw_uohm.group(1))
    elif m_fw_mohm:
        fw_uohm = int(round(float(m_fw_mohm.group(1)) * 1000.0))

    fw_mentions_css2h = ("CSS2H-2512R" in pins_h) and ("CSS2H-2512R" in ina_h)
    uohm_values = [v for v in (nl_uohm, calcs_uohm, bom_uohm, fw_uohm) if v is not None]
    shunt_parity_ok = (
        nl_mpn.startswith("CSS2H-2512")
        and bom_mpn == nl_mpn
        and nl_mpn in calcs_shunt_str
        and fw_mentions_css2h
        and len(uohm_values) == 4
        and len(set(uohm_values)) == 1
    )
    checks.append(
        _make_check(
            "ina226_shunt_contract_parity",
            shunt_parity_ok,
            f"netlist=({nl_mpn}, {nl_uohm} uOhm), bom=({bom_mpn}, {bom_uohm} uOhm), "
            f"calcs=({calcs_shunt_str!r}, {calcs_uohm} uOhm), firmware=(shunt={fw_uohm} uOhm, css2h_in_headers={fw_mentions_css2h})",
            "Reconcile R20 shunt value across design/netlist.json + bom.csv + calcs.json (CSS2H-2512R-L300F = 300 uOhm / 0.3 mOhm; CSS2H-2512K-3L00F = 3000 uOhm / 3.0 mOhm) and firmware/include/board_pins.h + ina226.h.",
        )
    )

    # 3. VBAT_ADC 100k / 33k divider parity
    r11 = comp_by_ref.get("R11", {})
    r12 = comp_by_ref.get("R12", {})
    vbat_adc_nodes = set(netlist.get("nets", {}).get("VBAT_ADC", []))
    vbat_nodes = set(netlist.get("nets", {}).get("VBAT", []))
    gnd_nodes = set(netlist.get("nets", {}).get("GND", []))

    nl_div_ok = (
        r11.get("value") == "100k"
        and r12.get("value") == "33k"
        and {"R11.2", "R12.1", "U4.8"}.issubset(vbat_adc_nodes)
        and "R11.1" in vbat_nodes
        and "R12.2" in gnd_nodes
    )
    m_rtop = re.search(r"#define\s+MG_VBAT_DIV_R_TOP_KOHM\s+(\d+)U?", pins_h)
    m_rbot = re.search(r"#define\s+MG_VBAT_DIV_R_BOT_KOHM\s+(\d+)U?", pins_h)
    fw_div_ok = (
        m_rtop is not None
        and int(m_rtop.group(1)) == 100
        and m_rbot is not None
        and int(m_rbot.group(1)) == 33
        and ("100k / 33k" in ina_h or "133 / 33" in ina_h)
    )
    checks.append(
        _make_check(
            "vbat_adc_100k_33k_divider_parity",
            nl_div_ok and fw_div_ok,
            f"netlist_100k_33k_PA0={nl_div_ok}, firmware_100k_33k={fw_div_ok}",
            "Ensure R11=100k, R12=33k on VBAT_ADC -> PA0 matches MG_VBAT_DIV_R_TOP_KOHM=100 and MG_VBAT_DIV_R_BOT_KOHM=33.",
        )
    )

    # 4. Connector J1..J5 mapping parity
    mech_conns = {c["ref"]: c for c in mech.get("pcbEnvelope", {}).get("connectors", [])}
    expected_j_refs = ["J1", "J2", "J3", "J4", "J5"]
    nl_j_ok = all(ref in comp_by_ref and ref in mech_conns for ref in expected_j_refs)
    fw_has_j1_j5 = all(re.search(rf"\b{ref}\b", pins_h) is not None for ref in expected_j_refs)
    fw_legacy_j = re.findall(r"\bJ(?:9|10|11|12|13)\b", pins_h)
    conn_ok = nl_j_ok and fw_has_j1_j5 and len(fw_legacy_j) == 0
    checks.append(
        _make_check(
            "connector_j1_j5_mapping_parity",
            conn_ok,
            f"netlist_and_mech_J1_J5={nl_j_ok}, firmware_has_J1_J5={fw_has_j1_j5}, firmware_legacy_refs={sorted(set(fw_legacy_j))}",
            "Update connector designators in firmware/include/board_pins.h and firmware/README.md from J9..J13 (BM04B) to J1..J5 (BM03B/BM05B).",
        )
    )

    return {
        "gate": "pin_and_bus_contract_parity",
        "passed": all(c["passed"] for c in checks),
        "checks": checks,
    }


# ============================================================================
# Gate 3: Joint & Observation Contract Parity
# ============================================================================
def run_gate_joint_and_obs() -> Dict[str, Any]:
    checks: List[Dict[str, Any]] = []
    mech_path = ROOT / "design" / "mechanical-interface.json"
    pins_h_path = ROOT / "firmware" / "include" / "board_pins.h"
    mj_env_path = ROOT / "rl" / "microgoose_mj_env.py"
    mjcf_path = ROOT / "rl" / "assets" / "microgoose.xml"
    onnx_rep_path = ROOT / "rl" / "checkpoints" / "onnx_export_report.json"
    cfg_py_path = ROOT / "runtime" / "goosectl" / "config.py"
    pol_py_path = ROOT / "runtime" / "goosectl" / "policy_daemon.py"
    cli_py_path = ROOT / "runtime" / "goosectl" / "cli.py"

    mech = json.loads(mech_path.read_text(encoding="utf-8"))
    loco_joints = mech["joints"]
    aux_joints = mech["auxiliaryJoints"]
    all_15 = list(loco_joints) + [{"index": 14, **aux_joints[0]}]
    rl_contract = mech["rlContract"]

    # Import runtime/goosectl/config.py constants via isolated exec/import
    sys.path.insert(0, str(ROOT / "runtime"))
    try:
        from goosectl import config as gcfg  # type: ignore
    finally:
        sys.path.pop(0)

    # 1. 15-DoF joint names, order, dxlId 1..15, ROM, and defaultRad parity
    joint_mismatches: List[str] = []
    if len(all_15) != 15:
        joint_mismatches.append(f"mechanical-interface.json has {len(all_15)} joints instead of 15")

    # Compare against runtime/goosectl/config.py (_FALLBACK_JOINTS and ALL_JOINTS)
    for label, seq in (("ALL_JOINTS", gcfg.ALL_JOINTS), ("_FALLBACK_JOINTS", gcfg._FALLBACK_JOINTS)):
        if len(seq) != 15:
            joint_mismatches.append(f"goosectl.{label} length={len(seq)} != 15")
            continue
        for m_j, g_j in zip(all_15, seq):
            r_min = math.radians(float(m_j["rangeDeg"][0]))
            r_max = math.radians(float(m_j["rangeDeg"][1]))
            if (
                g_j.index != int(m_j["index"])
                or g_j.dxl_id != int(m_j["dxlId"])
                or g_j.name != m_j["name"]
                or abs(g_j.min_rad - r_min) > 1e-5
                or abs(g_j.max_rad - r_max) > 1e-5
                or abs(g_j.default_rad - float(m_j["defaultRad"])) > 1e-5
            ):
                joint_mismatches.append(
                    f"{m_j['name']} in goosectl.{label}: idx={g_j.index}/dxl={g_j.dxl_id} vs mech idx={m_j['index']}/dxl={m_j['dxlId']}"
                )

    # Compare against firmware/include/board_pins.h enum mg_dxl_id_t
    if pins_h_path.is_file():
        pins_txt = pins_h_path.read_text(encoding="utf-8")
        for m_j in all_15:
            enum_name = "MG_DXL_ID_" + m_j["name"].upper()
            dxl_id = int(m_j["dxlId"])
            if not re.search(rf"\b{enum_name}\s*=\s*{dxl_id}\b", pins_txt):
                joint_mismatches.append(f"Missing {enum_name} = {dxl_id} in board_pins.h")

    # Compare against rl/assets/microgoose.xml joint names & ranges
    if mjcf_path.is_file():
        mjcf_txt = mjcf_path.read_text(encoding="utf-8")
        for m_j in all_15:
            m_xml = re.search(
                rf'<joint\s+name="{re.escape(m_j["name"])}"[^>]*range="([0-9.+-]+)\s+([0-9.+-]+)"',
                mjcf_txt,
            )
            if not m_xml:
                joint_mismatches.append(f"Joint {m_j['name']} missing in rl/assets/microgoose.xml")
            else:
                lo, hi = float(m_xml.group(1)), float(m_xml.group(2))
                r_min = math.radians(float(m_j["rangeDeg"][0]))
                r_max = math.radians(float(m_j["rangeDeg"][1]))
                if abs(lo - r_min) > 1e-3 or abs(hi - r_max) > 1e-3:
                    joint_mismatches.append(
                        f"MJCF range mismatch on {m_j['name']}: ({lo:.4f},{hi:.4f}) vs ({r_min:.4f},{r_max:.4f})"
                    )

    checks.append(
        _make_check(
            "joint_15dof_order_id_rom_parity",
            len(joint_mismatches) == 0,
            "All 15 joints (dxlId 1..15, names, ROM, defaultRad) match across design, firmware, MJCF, and goosectl"
            if not joint_mismatches
            else "; ".join(joint_mismatches[:5]),
        )
    )

    # 2. 61-dim observation slice layout parity
    expected_slices = [
        (s["name"], int(s["indices"][0]), int(s["indices"][1]))
        for s in rl_contract["observationSlices"]
    ]
    rt_slices = list(gcfg.OBSERVATION_SLICES)
    mj_txt = mj_env_path.read_text(encoding="utf-8") if mj_env_path.is_file() else ""
    mj_obs_checks = [
        "OBS_DIM = 61" in mj_txt,
        "obs[0:3] = ang_vel_b" in mj_txt,
        "obs[3:6] = grav_b" in mj_txt,
        "obs[6:9] = self.vel_cmd" in mj_txt,
        "obs[9:23] = q_meas_14 - self.q_default_14" in mj_txt,
        "obs[23:37] = dq_meas_14" in mj_txt,
        "obs[37:51] = self.last_actions" in mj_txt,
        "obs[51:55] = gait_cs" in mj_txt,
        "obs[55:59] = head_and_stand" in mj_txt,
        "obs[59:61] = self.last_foot_contacts" in mj_txt,
    ]
    obs_ok = (
        int(rl_contract["observationDim"]) == 61
        and gcfg.OBSERVATION_DIM == 61
        and expected_slices == rt_slices
        and all(mj_obs_checks)
    )
    checks.append(
        _make_check(
            "observation_61dim_slice_parity",
            obs_ok,
            f"obs_dim=61, slices_match={expected_slices == rt_slices}, mj_env_slices_ok={all(mj_obs_checks)}",
            "Ensure all 9 observation slices [0..61] match design/mechanical-interface.json across rl/ and runtime/goosectl/.",
        )
    )

    # 3. 14-dim action scale (0.25 rad at 50 Hz) parity across RL, ONNX export, and goosectl runtime
    mj_scale_m = re.search(r"^ACTION_SCALE\s*=\s*([0-9.]+)", mj_txt, re.MULTILINE)
    mj_clip_m = re.search(r"^ACTION_CLIP\s*=\s*([0-9.]+)", mj_txt, re.MULTILINE)
    mj_scale = float(mj_scale_m.group(1)) if mj_scale_m else None
    mj_clip = float(mj_clip_m.group(1)) if mj_clip_m else None

    onnx_scale: Optional[float] = None
    if onnx_rep_path.is_file():
        onnx_rep = json.loads(onnx_rep_path.read_text(encoding="utf-8"))
        onnx_scale = float(onnx_rep.get("action_scale_rad", -1.0))

    pol_txt = pol_py_path.read_text(encoding="utf-8") if pol_py_path.is_file() else ""
    cli_txt = cli_py_path.read_text(encoding="utf-8") if cli_py_path.is_file() else ""

    pol_default_m = re.search(r"def\s+load_and_validate_onnx\([^)]*action_scale:\s*float\s*=\s*([0-9.]+)", pol_txt)
    pol_rpc_m = re.search(r'req\.get\(\s*"action_scale"\s*,\s*([0-9.]+)\s*\)', pol_txt)
    cli_default_m = re.search(r'"--action-scale"[^)]*default\s*=\s*([0-9.]+)', cli_txt)
    pol_clip_m = re.search(r"np\.clip\(\s*act_14\s*,\s*-([0-9.]+)\s*,\s*([0-9.]+)\s*\)", pol_txt)

    pol_reads_onnx_meta = "metadata_props" in pol_txt or "custom_metadata_map" in pol_txt
    pol_default = float(pol_default_m.group(1)) if pol_default_m else None
    pol_rpc_default = float(pol_rpc_m.group(1)) if pol_rpc_m else None
    cli_default = float(cli_default_m.group(1)) if cli_default_m else None
    pol_clip = float(pol_clip_m.group(2)) if pol_clip_m else None

    action_mismatches: List[str] = []
    if int(rl_contract["controlHz"]) != 50 or gcfg.CONTROL_HZ != 50:
        action_mismatches.append(f"controlHz mismatch ({rl_contract['controlHz']} vs {gcfg.CONTROL_HZ})")
    if int(rl_contract["actionDim"]) != 14 or gcfg.ACTION_DIM != 14:
        action_mismatches.append(f"actionDim mismatch ({rl_contract['actionDim']} vs {gcfg.ACTION_DIM})")
    if mj_scale != 0.25 or onnx_scale != 0.25:
        action_mismatches.append(f"RL action_scale={mj_scale}, ONNX report action_scale_rad={onnx_scale} (expected 0.25)")
    if not pol_reads_onnx_meta and (pol_default != 0.25 or pol_rpc_default != 0.25 or cli_default != 0.25):
        action_mismatches.append(
            f"goosectl default action_scale mismatch: cli={cli_default}, policy_daemon=({pol_default}, {pol_rpc_default}) "
            "while policy.onnx outputs unscaled actions expecting action_scale=0.25 rad"
        )
    if mj_clip is not None and pol_clip is not None and abs(mj_clip - pol_clip) > 1e-6:
        action_mismatches.append(
            f"action clip mismatch: rl/microgoose_mj_env.py clips [-{mj_clip}, {mj_clip}] vs "
            f"runtime/goosectl/policy_daemon.py clips [-{pol_clip}, {pol_clip}]"
        )

    checks.append(
        _make_check(
            "action_scale_0p25rad_50hz_parity",
            len(action_mismatches) == 0,
            "50 Hz, 14-dim action_scale=0.25 rad and clip bounds match across RL, ONNX, and goosectl"
            if not action_mismatches
            else "; ".join(action_mismatches),
            "Set default action_scale=0.25 (or read custom_metadata_map['action_scale_rad']) and clip [-3.0, 3.0] in goosectl.",
        )
    )

    return {
        "gate": "joint_and_observation_contract_parity",
        "passed": all(c["passed"] for c in checks),
        "checks": checks,
    }


# ============================================================================
# Gate 4: Electronics, Mechanical, RL & Datasheet Artifact Gate
# ============================================================================
def _first_existing(candidates: List[Path]) -> Optional[Path]:
    for c in candidates:
        if c.is_file():
            return c
    return None


def _run_tool_check(cmd: List[str], cwd: Path = ROOT) -> Tuple[bool, str]:
    exe = shutil.which(cmd[0])
    if exe is None:
        return False, f"CLI tool '{cmd[0]}' not found on PATH"
    res = subprocess.run([exe, *cmd[1:]], cwd=str(cwd), capture_output=True, text=True, timeout=60)
    combined = (res.stdout + "\n" + res.stderr).strip()
    first_line = combined.splitlines()[0] if combined else f"exit={res.returncode}"
    return res.returncode == 0, f"exit={res.returncode}: {first_line[:180]}"


def run_gate_artifacts() -> Dict[str, Any]:
    checks: List[Dict[str, Any]] = []

    # 1. design/calcs.json
    calcs_p = ROOT / "design" / "calcs.json"
    if calcs_p.is_file():
        cdata = json.loads(calcs_p.read_text(encoding="utf-8"))
        checks.append(_make_check("calcs_json", bool(cdata.get("passed")), f"design/calcs.json passed={cdata.get('passed')}"))
    else:
        checks.append(_make_check("calcs_json", False, "design/calcs.json missing"))

    # 2. simulation_results.json
    sim_p = _first_existing([ROOT / "sim" / "simulation_results.json", ROOT / "design" / "simulation_results.json"])
    if sim_p:
        sdata = json.loads(sim_p.read_text(encoding="utf-8"))
        ok = bool(sdata.get("pass", sdata.get("passed", False)))
        checks.append(_make_check("simulation_results_json", ok, f"{sim_p.relative_to(ROOT)} pass={ok}"))
    else:
        checks.append(_make_check("simulation_results_json", False, "sim/simulation_results.json missing"))

    # 3. KiCad schematic & PCB
    for label, rel in (("kicad_sch", "kicad/microgoose-spine.kicad_sch"), ("kicad_pcb", "kicad/microgoose-spine.kicad_pcb")):
        p = ROOT / rel
        ok = p.is_file() and p.stat().st_size > 256
        checks.append(_make_check(label, ok, f"{rel} exists={p.is_file()}, bytes={p.stat().st_size if p.is_file() else 0}"))

    # 4. microgoose-spine.step
    step_p = _first_existing([
        ROOT / "kicad" / "microgoose-spine.step",
        ROOT / "docs" / "3d" / "microgoose-spine.step",
        ROOT / "mechanical" / "step" / "microgoose-spine.step",
    ])
    checks.append(
        _make_check(
            "microgoose_spine_step",
            step_p is not None and step_p.stat().st_size > 1024,
            f"{step_p.relative_to(ROOT)} ({step_p.stat().st_size} B)" if step_p else "microgoose-spine.step missing",
        )
    )

    # 5. docs/3d/microgoose-spine.glb
    spine_glb = ROOT / "docs" / "3d" / "microgoose-spine.glb"
    spine_glb_ok = spine_glb.is_file() and spine_glb.stat().st_size > 1024 and spine_glb.read_bytes()[:4] == b"glTF"
    checks.append(
        _make_check(
            "microgoose_spine_glb",
            spine_glb_ok,
            f"docs/3d/microgoose-spine.glb valid_glb={spine_glb_ok}, bytes={spine_glb.stat().st_size if spine_glb.is_file() else 0}",
        )
    )

    # 6. docs/3d/microgoose-hero.glb + adom-aiflow-wiring audit-glb
    hero_glb = ROOT / "docs" / "3d" / "microgoose-hero.glb"
    if hero_glb.is_file() and hero_glb.read_bytes()[:4] == b"glTF":
        audit_ok, audit_msg = _run_tool_check(["adom-aiflow-wiring", "audit-glb", str(hero_glb)])
        checks.append(_make_check("microgoose_hero_glb_and_audit", audit_ok, f"hero.glb ({hero_glb.stat().st_size} B), {audit_msg}"))
    else:
        checks.append(_make_check("microgoose_hero_glb_and_audit", False, "docs/3d/microgoose-hero.glb missing or invalid GLB"))

    # 7. mechanical/interference-report.json (0 collisions)
    inter_p = ROOT / "mechanical" / "interference-report.json"
    if inter_p.is_file():
        idata = json.loads(inter_p.read_text(encoding="utf-8"))
        col_cnt = idata.get("collision_count", idata.get("interferences", idata.get("collisionCount")))
        if col_cnt is None and isinstance(idata.get("collisions"), list):
            col_cnt = len(idata["collisions"])
        ok = col_cnt == 0
        checks.append(_make_check("mechanical_zero_interference", ok, f"mechanical/interference-report.json collisions={col_cnt}"))
    else:
        checks.append(_make_check("mechanical_zero_interference", False, "mechanical/interference-report.json missing"))

    # 8. adom-aiflow-mechanical lint
    mech_lint_json = _first_existing([
        ROOT / "mechanical" / "assembly-access.json",
        ROOT / "mechanical" / "mechanical-lint.json",
        ROOT / "design" / "assembly-access.json",
    ])
    if mech_lint_json:
        ml_ok, ml_msg = _run_tool_check(["adom-aiflow-mechanical", "lint", str(mech_lint_json)])
        checks.append(_make_check("adom_aiflow_mechanical_lint", ml_ok, f"{mech_lint_json.relative_to(ROOT)} -> {ml_msg}"))
    else:
        checks.append(_make_check("adom_aiflow_mechanical_lint", False, "mechanical/assembly-access.json missing"))

    # 9. adom-aiflow-wiring lint
    wiring_json = _first_existing([
        ROOT / "mechanical" / "wiring.json",
        ROOT / "design" / "wiring.json",
    ])
    if wiring_json:
        wl_ok, wl_msg = _run_tool_check(["adom-aiflow-wiring", "lint", str(wiring_json)])
        checks.append(_make_check("adom_aiflow_wiring_lint", wl_ok, f"{wiring_json.relative_to(ROOT)} -> {wl_msg}"))
    else:
        checks.append(_make_check("adom_aiflow_wiring_lint", False, "mechanical/wiring.json missing"))

    # 10. mechanical/bambu_slice_report.json
    bambu_p = ROOT / "mechanical" / "bambu_slice_report.json"
    if bambu_p.is_file():
        bdata = json.loads(bambu_p.read_text(encoding="utf-8"))
        bok = bool(bdata.get("passed", bdata.get("pass", bdata.get("printable", bdata.get("status") == "ok"))))
        checks.append(_make_check("bambu_slice_report", bok, f"mechanical/bambu_slice_report.json pass={bok}"))
    else:
        checks.append(_make_check("bambu_slice_report", False, "mechanical/bambu_slice_report.json missing"))

    # 11. rl/checkpoints/policy.onnx
    onnx_p = ROOT / "rl" / "checkpoints" / "policy.onnx"
    onnx_rep_p = ROOT / "rl" / "checkpoints" / "onnx_export_report.json"
    if onnx_p.is_file() and onnx_p.stat().st_size > 1024:
        rep_ok = True
        if onnx_rep_p.is_file():
            rep = json.loads(onnx_rep_p.read_text(encoding="utf-8"))
            rep_ok = (
                bool(rep.get("onnx_checker_passed"))
                and rep.get("input_signature", {}).get("shape") == [1, 61]
                and rep.get("output_signature", {}).get("shape") == [1, 14]
            )
        checks.append(_make_check("rl_policy_onnx", rep_ok, f"rl/checkpoints/policy.onnx ({onnx_p.stat().st_size} B), signature_ok={rep_ok}"))
    else:
        checks.append(_make_check("rl_policy_onnx", False, "rl/checkpoints/policy.onnx missing"))

    # 12. docs/videos/microgoose-walk-sim2sim.mp4
    mp4_p = ROOT / "docs" / "videos" / "microgoose-walk-sim2sim.mp4"
    mp4_ok = mp4_p.is_file() and mp4_p.stat().st_size > 10_000 and b"ftyp" in mp4_p.read_bytes()[:32]
    checks.append(
        _make_check(
            "sim2sim_walk_video_mp4",
            mp4_ok,
            f"docs/videos/microgoose-walk-sim2sim.mp4 valid={mp4_ok}, bytes={mp4_p.stat().st_size if mp4_p.is_file() else 0}",
        )
    )

    # 13. docs/Microgoose-Datasheet.pdf
    pdf_p = ROOT / "docs" / "Microgoose-Datasheet.pdf"
    if pdf_p.is_file() and pdf_p.stat().st_size > 10_000:
        pcount, ptexts = _extract_pdf_text(pdf_p)
        nonempty_pages = sum(1 for t in ptexts if len(t.strip()) >= 120)
        pdf_ok = pcount == 8 and nonempty_pages == 8
        checks.append(
            _make_check(
                "microgoose_datasheet_pdf",
                pdf_ok,
                f"docs/Microgoose-Datasheet.pdf pages={pcount}, text_rich_pages={nonempty_pages}/8, bytes={pdf_p.stat().st_size}",
            )
        )
    else:
        checks.append(_make_check("microgoose_datasheet_pdf", False, "docs/Microgoose-Datasheet.pdf missing"))

    return {
        "gate": "electronics_mechanical_rl_artifacts",
        "passed": all(c["passed"] for c in checks),
        "checks": checks,
    }


# ============================================================================
# Gate 5: Prose Lint Gate
# ============================================================================
def run_gate_prose_lint() -> Dict[str, Any]:
    checks: List[Dict[str, Any]] = []
    targets = [
        "README.md",
        "design/brief.md",
        "firmware/README.md",
        "runtime/README.md",
        "rl/README.md",
        "mechanical/README.md",
    ]
    if (ROOT / "docs" / "rl" / "README.md").is_file():
        targets.append("docs/rl/README.md")

    for rel in targets:
        p = ROOT / rel
        if not p.is_file():
            checks.append(
                _make_check(
                    f"prose_lint:{rel}",
                    False,
                    f"{rel} does not exist yet",
                    f"Create {rel} and verify with `prose-lint --strict {rel}`.",
                )
            )
            continue
        ok, msg = _run_tool_check(["prose-lint", "--strict", str(p)])
        checks.append(
            _make_check(
                f"prose_lint:{rel}",
                ok,
                msg,
                f"Run `prose-lint --strict {rel}` and remove any em-dashes, en-dashes, or AI tell-words.",
            )
        )

    return {
        "gate": "prose_lint_gate",
        "passed": all(c["passed"] for c in checks),
        "checks": checks,
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="Run full-stack read-only verification for Microgoose.")
    parser.add_argument("--json", action="store_true", help="Print full JSON report to stdout")
    parser.add_argument(
        "--report",
        type=Path,
        default=DEFAULT_REPORT_PATH,
        help=f"Path to write JSON summary report (default: {DEFAULT_REPORT_PATH})",
    )
    args = parser.parse_args()

    gates = [
        run_gate_confidentiality(),
        run_gate_pin_and_bus(),
        run_gate_joint_and_obs(),
        run_gate_artifacts(),
        run_gate_prose_lint(),
    ]
    total_checks = sum(len(g["checks"]) for g in gates)
    passed_checks = sum(sum(1 for c in g["checks"] if c["passed"]) for g in gates)
    overall_passed = all(g["passed"] for g in gates)

    report = {
        "schema": "microgoose-full-stack-verification/v1",
        "project": "drew2/microgoose",
        "overall_passed": overall_passed,
        "passed_checks": passed_checks,
        "total_checks": total_checks,
        "gates": gates,
    }

    args.report.parent.mkdir(parents=True, exist_ok=True)
    args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")

    if args.json:
        print(json.dumps(report, indent=2))
    else:
        status_word = "OK" if overall_passed else "ERROR"
        print(
            f"{status_word}: Microgoose full-stack verification passed {passed_checks}/{total_checks} checks "
            f"across {len(gates)} gates (report: {args.report})."
        )
        for gate in gates:
            g_mark = "PASS" if gate["passed"] else "FAIL"
            print(f"  [{g_mark}] {gate['gate']}")
            for chk in gate["checks"]:
                c_mark = "OK" if chk["passed"] else "FAIL"
                print(f"    - {c_mark}: {chk['name']} -> {chk['detail']}")
                if not chk["passed"] and chk.get("hint"):
                    print(f"      Hint: {chk['hint']}")
        if not overall_passed:
            print("Hint: Resolve failing subsystem checks above and re-run `python3 validation/verify_full_stack.py`.")

    return 0 if overall_passed else 1


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