Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

78.2 KB
Raw Blame
"""Tier 2 E2E Tests: Variants, Edge Cases & Negative/Error Paths (95 tests = 5 per feature #2-#20)."""

from __future__ import annotations

import json
import pathlib
import re
import shutil
import sqlite3
import xml.etree.ElementTree as ET
import zipfile

import helpers as h


def _load_software() -> list[dict]:
    return h.load_jsonl(h.require_research_file("corpus/software.jsonl"))


def _load_manufacturers() -> list[dict]:
    return h.load_jsonl(h.require_research_file("corpus/manufacturers.jsonl"))


def _load_papers() -> list[dict]:
    return h.load_jsonl(h.require_research_file("corpus/papers.jsonl"))


def _by_category_or_text(records: list[dict], needles: tuple[str, ...]) -> list[dict]:
    out = []
    for r in records:
        ident = f"{r.get('id', '')} {r.get('name', '')}".lower()
        ident_norm = re.sub(r"[-_\s]+", "", ident)
        if any(n in ident or re.sub(r"[-_\s]+", "", n) in ident_norm for n in needles):
            out.append(r)
    return out


def _assert_no_empty_str_items(val: object, context: str) -> None:
    if isinstance(val, list):
        for idx, item in enumerate(val):
            if isinstance(item, str):
                assert item.strip() != "", f"Empty string element at {context}[{idx}]"
            else:
                _assert_no_empty_str_items(item, f"{context}[{idx}]")
    elif isinstance(val, dict):
        for k, v in val.items():
            _assert_no_empty_str_items(v, f"{context}.{k}")


def _run_validate_kb_on_mutated_copy(mutator) -> None:
    src_research = h.require_research_file("scripts/validate_kb.py").parents[1]
    with h.temp_dir(prefix="forma_kb_neg_") as td:
        dst_research = pathlib.Path(td) / "research"
        shutil.copytree(src_research, dst_research)
        mutator(dst_research)
        proc = h.run_cmd(["python3", str(dst_research / "scripts" / "validate_kb.py")], cwd=dst_research.parent)
        assert proc.returncode != 0, (
            f"Expected validate_kb.py to fail on corrupted copy, but it exited 0!\n"
            f"STDOUT: {proc.stdout}\nSTDERR: {proc.stderr}"
        )


def _run_query_rag_raw(query: str, *, domain: str | None = None, top_k: int = 5, db_path: pathlib.Path | None = None):
    script = h.require_research_file("rag/query_rag.py")
    help_proc = h.run_cmd(["python3", str(script), "--help"])
    help_text = (help_proc.stdout + "\n" + help_proc.stderr).lower()
    cmd = ["python3", str(script)]
    if "--query" in help_text:
        cmd.extend(["--query", query])
    elif "-q " in help_text or "-q," in help_text:
        cmd.extend(["-q", query])
    else:
        cmd.append(query)
    if domain is not None:
        if "--domain" in help_text:
            cmd.extend(["--domain", domain])
        elif "--source" in help_text:
            cmd.extend(["--source", domain])
        elif "--type" in help_text:
            cmd.extend(["--type", domain])
    if "--top-k" in help_text:
        cmd.extend(["--top-k", str(top_k)])
    elif "--limit" in help_text:
        cmd.extend(["--limit", str(top_k)])
    elif "-k " in help_text:
        cmd.extend(["-k", str(top_k)])
    if db_path is not None and "--db" in help_text:
        cmd.extend(["--db", str(db_path)])
    if "--json" in help_text:
        cmd.append("--json")
    return h.run_cmd(cmd)


def _git_merge_base_main() -> str:
    mb = h.run_cmd(["git", "merge-base", "main", "HEAD"])
    assert mb.returncode == 0 and mb.stdout.strip(), (
        f"Failed to compute git merge-base main HEAD: rc={mb.returncode}, stderr={mb.stderr}"
    )
    base = mb.stdout.strip()
    assert re.fullmatch(r"[0-9a-f]{40}", base), f"Unexpected merge-base SHA: {base!r}"
    return base


def _canonical_bench_json(doc: dict) -> dict:
    out = json.loads(json.dumps(doc))
    out.pop("total_benchmark_duration_s", None)
    mcp = out.get("mcp", {})
    for srv_key in ("core_forma_mcp", "opt_in_forma_print_mcp"):
        srv = mcp.get(srv_key, {})
        for k in ("initialize_ms", "tools_list_ms", "handshake_total_ms"):
            srv.pop(k, None)
    sess = mcp.get("live_session_upside_down_t", {})
    for tool_name, entry in sess.items():
        if isinstance(entry, dict):
            entry.pop("latency_ms", None)
            if tool_name in ("print_check", "print_export"):
                entry.pop("response_o200k_tokens", None)
    for item in out.get("cli_benchmarks", {}).get("benchmarks", []):
        if isinstance(item, dict):
            item.pop("timing", None)
    rag = out.get("rag_benchmarks", {})
    rag.pop("cold_open_samples_ms", None)
    for k_stats in rag.get("by_top_k", {}).values():
        if isinstance(k_stats, dict):
            k_stats.pop("timing", None)
    for tr in rag.get("trace_top_k_5", []):
        if isinstance(tr, dict):
            tr.pop("latency_ms", None)
    return out


# ===========================================================================
# #2: R1.1 OSS Slicers boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-02-1", tier=2, feature_id="#2", title="All slicer records have valid http(s) URLs", requires=("research",))
def t2_02_1() -> None:
    slicers = _by_category_or_text(_load_software(), ("orcaslicer", "prusaslicer", "bambu studio", "cura", "superslicer", "slic3r"))
    assert len(slicers) >= 5
    for rec in slicers:
        urls = h.extract_urls_from_record(rec)
        assert urls and all(h.is_valid_http_url(u) for u in urls), f"Invalid/missing URLs in {rec}"


@h.test_case(id="T2-02-2", tier=2, feature_id="#2", title="Slicer input/output format arrays non-empty", requires=("research",))
def t2_02_2() -> None:
    slicers = _by_category_or_text(_load_software(), ("orcaslicer", "prusaslicer", "bambu studio", "cura"))
    assert len(slicers) >= 4
    for rec in slicers:
        in_f = rec.get("input_formats", [])
        out_f = rec.get("output_formats", [])
        assert isinstance(in_f, list) and len(in_f) >= 1 and all(isinstance(x, str) and x.strip() for x in in_f)
        assert isinstance(out_f, list) and len(out_f) >= 1 and all(isinstance(x, str) and x.strip() for x in out_f)
        fmt_blob = " ".join([*in_f, *out_f]).lower()
        assert any(ext in fmt_blob for ext in ("3mf", "stl", "obj", "gcode")), f"Missing formats in {rec}"


@h.test_case(id="T2-02-3", tier=2, feature_id="#2", title="Slicer CLI capabilities documented", requires=("research",))
def t2_02_3() -> None:
    slicers = _by_category_or_text(_load_software(), ("orcaslicer", "prusaslicer", "curaengine"))
    assert len(slicers) >= 3
    for rec in slicers:
        flags = rec.get("cli_or_api_flags", [])
        assert isinstance(flags, list) and len(flags) >= 1
        flags_blob = " ".join(str(x) for x in flags).lower()
        assert "--" in flags_blob or "slice" in flags_blob or "cli" in flags_blob, f"Missing CLI flags in {rec}"


@h.test_case(id="T2-02-4", tier=2, feature_id="#2", title="Slicer 3MF/metadata architectural lessons populated", requires=("research",))
def t2_02_4() -> None:
    slicers = _by_category_or_text(_load_software(), ("orcaslicer", "prusaslicer", "bambu studio"))
    assert len(slicers) >= 3
    for rec in slicers:
        schema_notes = str(rec.get("three_mf_metadata_schema", ""))
        lessons = str(rec.get("architectural_lessons_for_forma_print", ""))
        assert len(schema_notes.strip()) >= 50, f"Empty/short three_mf_metadata_schema in {rec.get('id')}"
        assert any(k in schema_notes.lower() for k in ("metadata/", "3d/3dmodel.model", "model_settings", "slic3r_pe")), (
            f"Missing 3MF metadata schema details in {rec.get('id')}: {schema_notes!r}"
        )
        assert len(lessons.strip()) >= 50, f"Empty/short architectural_lessons_for_forma_print in {rec.get('id')}"


@h.test_case(id="T2-02-5", tier=2, feature_id="#2", title="No duplicate IDs across software.jsonl", requires=("research",))
def t2_02_5() -> None:
    recs = _load_software()
    assert len(recs) >= 20
    ids = [str(r.get("id") or r.get("name")).strip().lower() for r in recs]
    assert len(ids) == len(set(ids)), "Duplicate software IDs detected"


# ===========================================================================
# #3: R1.2 Mesh repair & analysis libs boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-03-1", tier=2, feature_id="#3", title="Mesh library records pass software.schema.json", requires=("research",))
def t2_03_1() -> None:
    schema = json.loads(h.require_research_file("schemas/software.schema.json").read_text(encoding="utf-8"))
    libs = _by_category_or_text(_load_software(), ("lib3mf", "manifold", "meshlab", "trimesh", "meshoptimizer", "uvtools", "cgal", "libigl"))
    assert len(libs) >= 6
    for idx, rec in enumerate(libs):
        errs = h.validate_json_schema_subset(rec, schema)
        assert not errs, f"Mesh lib #{idx} schema violation: {errs}"


@h.test_case(id="T2-03-2", tier=2, feature_id="#3", title="Mesh library license & language fields non-empty", requires=("research",))
def t2_03_2() -> None:
    libs = _by_category_or_text(_load_software(), ("lib3mf", "manifold", "trimesh", "meshoptimizer", "uvtools"))
    assert len(libs) >= 5
    for rec in libs:
        lic = str(rec.get("license", "")).lower()
        langs = {str(x).strip().lower() for x in rec.get("languages", [])}
        assert any(k in lic for k in ("mit", "apache", "bsd", "gpl", "lgpl", "mpl")), f"Missing OSS license in {rec}"
        assert langs & {"c++", "cpp", "python", "c#", "rust", "c"}, f"Missing implementation language in {rec}"


@h.test_case(id="T2-03-3", tier=2, feature_id="#3", title="Mesh library capabilities & formats non-empty", requires=("research",))
def t2_03_3() -> None:
    libs = _by_category_or_text(_load_software(), ("lib3mf", "manifold", "meshlab", "trimesh", "meshoptimizer"))
    assert len(libs) >= 5
    for rec in libs:
        _assert_no_empty_str_items(rec, "mesh_lib")
        assert isinstance(rec.get("capabilities"), list) and len(rec["capabilities"]) >= 2
        assert isinstance(rec.get("input_formats"), list) and len(rec["input_formats"]) >= 1
        assert isinstance(rec.get("output_formats"), list) and len(rec["output_formats"]) >= 1


@h.test_case(id="T2-03-4", tier=2, feature_id="#3", title="Mesh library architectural lessons populated", requires=("research",))
def t2_03_4() -> None:
    libs = _by_category_or_text(_load_software(), ("lib3mf", "manifold", "trimesh", "meshoptimizer", "uvtools"))
    assert len(libs) >= 5
    for rec in libs:
        lessons = str(rec.get("architectural_lessons_for_forma_print", ""))
        assert len(lessons.strip()) >= 80, f"Short architectural lessons in {rec.get('id')}"
        assert any(k in lessons.lower() for k in ("forma", "3mf", "manifold", "repair", "rust", "msla")), (
            f"Missing domain content in architectural lessons for {rec.get('id')}"
        )


@h.test_case(id="T2-03-5", tier=2, feature_id="#3", title="Mesh library primary source URLs valid", requires=("research",))
def t2_03_5() -> None:
    libs = _by_category_or_text(_load_software(), ("lib3mf", "manifold", "meshlab", "trimesh", "meshoptimizer", "uvtools"))
    assert len(libs) >= 6
    for rec in libs:
        urls = h.extract_urls_from_record(rec)
        assert urls and all(h.is_valid_http_url(u) for u in urls)


# ===========================================================================
# #4: R1.3 Host, fleet & spool controllers boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-04-1", tier=2, feature_id="#4", title="Host/fleet protocol/API fields non-empty", requires=("research",))
def t2_04_1() -> None:
    hosts = _by_category_or_text(_load_software(), ("octoprint", "moonraker", "mainsail", "fluidd", "prusalink", "spoolman", "obico", "chitui"))
    assert len(hosts) >= 6
    for rec in hosts:
        val_blob = " ".join([
            *[str(x) for x in rec.get("capabilities", [])],
            *[str(x) for x in rec.get("workflows", [])],
            *[str(x) for x in rec.get("input_formats", [])],
            *[str(x) for x in rec.get("output_formats", [])],
            *[str(x) for x in rec.get("cli_or_api_flags", [])],
        ]).lower()
        assert any(k in val_blob for k in ("http", "rest", "websocket", "json-rpc", "json_rpc", "api", "mqtt")), (
            f"Missing protocol/API details in {rec.get('id')}"
        )


@h.test_case(id="T2-04-2", tier=2, feature_id="#4", title="Host/fleet supported firmware/printers populated", requires=("research",))
def t2_04_2() -> None:
    hosts = _by_category_or_text(_load_software(), ("octoprint", "moonraker", "mainsail", "fluidd", "prusalink"))
    assert len(hosts) >= 5
    for rec in hosts:
        val_blob = " ".join([
            *[str(x) for x in rec.get("capabilities", [])],
            *[str(x) for x in rec.get("workflows", [])],
            *[str(x) for x in rec.get("input_formats", [])],
            *[str(x) for x in rec.get("output_formats", [])],
            str(rec.get("relevance_to_forma_print", "")),
        ]).lower()
        assert any(k in val_blob for k in ("klipper", "marlin", "prusa", "gcode", "fdm", "sla", "msla")), (
            f"Missing supported firmware/printer details in {rec.get('id')}"
        )


@h.test_case(id="T2-04-3", tier=2, feature_id="#4", title="Host/fleet primary URLs valid", requires=("research",))
def t2_04_3() -> None:
    hosts = _by_category_or_text(_load_software(), ("octoprint", "moonraker", "mainsail", "fluidd", "spoolman"))
    assert len(hosts) >= 5
    for rec in hosts:
        urls = h.extract_urls_from_record(rec)
        assert urls and all(h.is_valid_http_url(u) for u in urls)


@h.test_case(id="T2-04-4", tier=2, feature_id="#4", title="Host/fleet lessons for forma-print populated", requires=("research",))
def t2_04_4() -> None:
    hosts = _by_category_or_text(_load_software(), ("octoprint", "moonraker", "prusalink", "spoolman"))
    assert len(hosts) >= 4
    for rec in hosts:
        assert len(str(rec.get("architectural_lessons_for_forma_print", "")).strip()) >= 80
        assert len(str(rec.get("relevance_to_forma_print", "")).strip()) >= 40


@h.test_case(id="T2-04-5", tier=2, feature_id="#4", title="No empty string elements inside host/fleet arrays", requires=("research",))
def t2_04_5() -> None:
    hosts = _by_category_or_text(_load_software(), ("octoprint", "moonraker", "mainsail", "fluidd", "spoolman", "obico", "chitui"))
    assert len(hosts) >= 7
    for rec in hosts:
        _assert_no_empty_str_items(rec, "host_record")


# ===========================================================================
# #5: R1.4 Printer firmware boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-05-1", tier=2, feature_id="#5", title="Firmware G-code/kinematics capabilities populated", requires=("research",))
def t2_05_1() -> None:
    fw = _by_category_or_text(_load_software(), ("klipper", "marlin", "reprapfirmware", "buddy", "smoothieware", "fluidnc"))
    assert len(fw) >= 4
    for rec in fw:
        val_blob = " ".join([
            *[str(x) for x in rec.get("capabilities", [])],
            *[str(x) for x in rec.get("input_formats", [])],
            *[str(x) for x in rec.get("output_formats", [])],
        ]).lower()
        assert any(k in val_blob for k in ("gcode", "g-code", "kinematics", "corexy", "input shaper", "pressure advance"))


@h.test_case(id="T2-05-2", tier=2, feature_id="#5", title="Firmware host/protocol fields non-empty", requires=("research",))
def t2_05_2() -> None:
    fw = _by_category_or_text(_load_software(), ("klipper", "marlin", "reprapfirmware"))
    assert len(fw) >= 3
    for rec in fw:
        val_blob = " ".join([
            *[str(x) for x in rec.get("capabilities", [])],
            *[str(x) for x in rec.get("workflows", [])],
            *[str(x) for x in rec.get("input_formats", [])],
            *[str(x) for x in rec.get("output_formats", [])],
            *[str(x) for x in rec.get("cli_or_api_flags", [])],
            str(rec.get("architectural_lessons_for_forma_print", "")),
        ]).lower()
        assert any(k in val_blob for k in ("moonraker", "serial", "usb", "http", "rest", "octoprint", "gcode"))


@h.test_case(id="T2-05-3", tier=2, feature_id="#5", title="Firmware primary source URLs valid", requires=("research",))
def t2_05_3() -> None:
    fw = _by_category_or_text(_load_software(), ("klipper", "marlin", "reprapfirmware", "buddy"))
    assert len(fw) >= 4
    for rec in fw:
        urls = h.extract_urls_from_record(rec)
        assert urls and all(h.is_valid_http_url(u) for u in urls)


@h.test_case(id="T2-05-4", tier=2, feature_id="#5", title="Firmware lessons populated", requires=("research",))
def t2_05_4() -> None:
    fw = _by_category_or_text(_load_software(), ("klipper", "marlin", "reprapfirmware"))
    assert len(fw) >= 3
    for rec in fw:
        assert len(str(rec.get("architectural_lessons_for_forma_print", "")).strip()) >= 80
        assert len(str(rec.get("relevance_to_forma_print", "")).strip()) >= 40


@h.test_case(id="T2-05-5", tier=2, feature_id="#5", title="Schema conformance across all firmware entries", requires=("research",))
def t2_05_5() -> None:
    schema = json.loads(h.require_research_file("schemas/software.schema.json").read_text(encoding="utf-8"))
    fw = _by_category_or_text(_load_software(), ("klipper", "marlin", "reprapfirmware", "buddy", "smoothieware", "fluidnc"))
    assert len(fw) >= 6
    for idx, rec in enumerate(fw):
        errs = h.validate_json_schema_subset(rec, schema)
        assert not errs, f"Firmware #{idx} schema error: {errs}"


# ===========================================================================
# #6: R1.5 Programmatic CAD & CLI boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-06-1", tier=2, feature_id="#6", title="Programmatic CAD language & export formats populated", requires=("research",))
def t2_06_1() -> None:
    cad = _by_category_or_text(_load_software(), ("openscad", "cadquery", "build123d", "bosl2", "fornjot", "kcl"))
    assert len(cad) >= 5
    for rec in cad:
        fmt_blob = " ".join([
            *[str(x) for x in rec.get("input_formats", [])],
            *[str(x) for x in rec.get("output_formats", [])],
        ]).lower()
        assert any(ext in fmt_blob for ext in ("stl", "step", "3mf", "obj", "glb", "scad"))


@h.test_case(id="T2-06-2", tier=2, feature_id="#6", title="Programmatic CAD parametric/CLI capabilities listed", requires=("research",))
def t2_06_2() -> None:
    cad = _by_category_or_text(_load_software(), ("openscad", "cadquery", "build123d", "bosl2"))
    assert len(cad) >= 4
    for rec in cad:
        assert isinstance(rec.get("capabilities"), list) and len(rec["capabilities"]) >= 2
        flags = rec.get("cli_or_api_flags", [])
        assert isinstance(flags, list) and len(flags) >= 1 and all(len(str(x).strip()) >= 5 for x in flags)


@h.test_case(id="T2-06-3", tier=2, feature_id="#6", title="Programmatic CAD architectural lessons populated", requires=("research",))
def t2_06_3() -> None:
    cad = _by_category_or_text(_load_software(), ("openscad", "cadquery", "build123d", "bosl2"))
    assert len(cad) >= 4
    for rec in cad:
        lessons = str(rec.get("architectural_lessons_for_forma_print", ""))
        assert len(lessons.strip()) >= 80
        assert any(k in lessons.lower() for k in ("forma", "cad", "clearance", "step", "3mf"))


@h.test_case(id="T2-06-4", tier=2, feature_id="#6", title="Programmatic CAD primary source URLs valid", requires=("research",))
def t2_06_4() -> None:
    cad = _by_category_or_text(_load_software(), ("openscad", "cadquery", "build123d", "bosl2", "fornjot"))
    assert len(cad) >= 5
    for rec in cad:
        urls = h.extract_urls_from_record(rec)
        assert urls and all(h.is_valid_http_url(u) for u in urls)


@h.test_case(id="T2-06-5", tier=2, feature_id="#6", title="No malformed JSONL lines across software.jsonl", requires=("research",))
def t2_06_5() -> None:
    recs = _load_software()
    assert len(recs) >= 20


# ===========================================================================
# #7: R1.6 nurb inspection boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-07-1", tier=2, feature_id="#7", title="nurb inspection cites https://github.com/Shpigford/nurb", requires=("research",))
def t2_07_1() -> None:
    text = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8")
    assert "https://github.com/Shpigford/nurb" in text


@h.test_case(id="T2-07-2", tier=2, feature_id="#7", title="nurb inspection covers tech stack accurately", requires=("research",))
def t2_07_2() -> None:
    text = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8").lower()
    assert any(k in text for k in ("python", "cli", "toml", "build123d", "cad"))


@h.test_case(id="T2-07-3", tier=2, feature_id="#7", title="nurb inspection covers gap/lesson comparison with forma-print", requires=("research",))
def t2_07_3() -> None:
    text = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8").lower()
    assert "forma-print" in text


@h.test_case(id="T2-07-4", tier=2, feature_id="#7", title="nurb inspection contains zero placeholder/TBD markers", requires=("research",))
def t2_07_4() -> None:
    text = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8")
    assert not re.search(r"\b(TBD|TODO|FIXME|PLACEHOLDER)\b", text), "Placeholder marker found in nurb_inspection.md"


@h.test_case(id="T2-07-5", tier=2, feature_id="#7", title="nurb inspection content indexed in RAG DB", requires=("research",))
def t2_07_5() -> None:
    proc = _run_query_rag_raw("nurb checks.py printers.toml", top_k=5)
    assert proc.returncode == 0, f"query_rag failed: {proc.stderr}"
    data = json.loads(proc.stdout)
    results = data.get("results", [])
    assert isinstance(results, list) and 1 <= len(results) <= 5, f"Unexpected RAG results: {data}"
    assert any(r.get("entity_id") == "nurb_inspection" or r.get("domain") == "report" for r in results)
    assert "nurb" in json.dumps(results).lower()


# ===========================================================================
# #8: R2.1-R2.4 Manufacturer sweep boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-08-1", tier=2, feature_id="#8", title="Direct local/cloud comms explicitly recorded on every manufacturer", requires=("research",))
def t2_08_1() -> None:
    recs = _load_manufacturers()
    assert len(recs) >= 19
    allowed_status = {"open_official", "gated_local_or_community_re", "cloud_first_limited_local", "closed_or_usb_only"}
    for idx, rec in enumerate(recs):
        dc = rec.get("direct_communication")
        assert isinstance(dc, dict), f"Manufacturer #{idx} missing direct_communication dict"
        for lk in ("local_protocols", "cloud_protocols", "ports", "upload_print_control_endpoints"):
            arr = dc.get(lk)
            assert isinstance(arr, list) and len(arr) >= 1, f"Manufacturer #{idx} missing/empty {lk}: {arr!r}"
            assert all(isinstance(x, str) and len(x.strip()) >= 2 for x in arr), f"Manufacturer #{idx} invalid {lk}: {arr!r}"
        assert isinstance(dc.get("auth_and_modes"), str) and len(dc["auth_and_modes"].strip()) >= 5
        assert isinstance(dc.get("offline_capable"), bool)
        assert isinstance(dc.get("offline_mode_notes"), str) and len(dc["offline_mode_notes"].strip()) >= 5
        assert dc.get("status") in allowed_status, f"Manufacturer #{idx} invalid status: {dc.get('status')!r}"


@h.test_case(id="T2-08-2", tier=2, feature_id="#8", title="Monitoring/sensors telemetry explicitly recorded on every manufacturer", requires=("research",))
def t2_08_2() -> None:
    recs = _load_manufacturers()
    assert len(recs) >= 19
    sensor_keys = (
        "thermal_sensors",
        "cameras",
        "lidar_and_ai_inspection",
        "filament_and_spool_systems",
        "accelerometers_input_shaper",
        "bed_probes",
        "status_error_feeds",
    )
    for idx, rec in enumerate(recs):
        ms = rec.get("monitoring_and_sensors")
        assert isinstance(ms, dict), f"Manufacturer #{idx} missing monitoring_and_sensors dict"
        for sk in sensor_keys:
            val = ms.get(sk)
            assert isinstance(val, str) and len(val.strip()) >= 3, f"Manufacturer #{idx} missing/short {sk}: {val!r}"


@h.test_case(id="T2-08-3", tier=2, feature_id="#8", title="Troubleshooting/fault codes explicitly recorded on every manufacturer", requires=("research",))
def t2_08_3() -> None:
    recs = _load_manufacturers()
    assert len(recs) >= 19
    for idx, rec in enumerate(recs):
        tf = rec.get("troubleshooting_and_faults")
        assert isinstance(tf, dict), f"Manufacturer #{idx} missing troubleshooting_and_faults dict"
        assert isinstance(tf.get("fault_code_taxonomy"), str) and len(tf["fault_code_taxonomy"].strip()) >= 5
        assert isinstance(tf.get("diagnostic_logs"), str) and len(tf["diagnostic_logs"].strip()) >= 5
        faults = tf.get("example_fault_codes")
        assert isinstance(faults, list) and len(faults) >= 1
        for f in faults:
            assert isinstance(f, dict)
            assert isinstance(f.get("code"), str) and len(f["code"].strip()) >= 1
            assert isinstance(f.get("description"), str) and len(f["description"].strip()) >= 5
            assert h.is_valid_http_url(str(f.get("kb_url", "")))
        kb_urls = tf.get("official_kb_urls")
        assert isinstance(kb_urls, list) and len(kb_urls) >= 1 and all(h.is_valid_http_url(str(u)) for u in kb_urls)


@h.test_case(id="T2-08-4", tier=2, feature_id="#8", title="No empty/null protocol or telemetry values without explicit marker", requires=("research",))
def t2_08_4() -> None:
    recs = _load_manufacturers()
    assert len(recs) >= 19
    for idx, rec in enumerate(recs):
        _assert_no_empty_str_items(rec, f"manufacturer[{idx}]")


@h.test_case(id="T2-08-5", tier=2, feature_id="#8", title="Valid primary source URLs on every manufacturer entry", requires=("research",))
def t2_08_5() -> None:
    recs = _load_manufacturers()
    assert len(recs) >= 19
    for idx, rec in enumerate(recs):
        urls = h.extract_urls_from_record(rec)
        assert urls and all(h.is_valid_http_url(u) for u in urls), f"Manufacturer #{idx} invalid/missing URLs"


# ===========================================================================
# #9: R3.1-R3.7 Academic papers boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-09-1", tier=2, feature_id="#9", title="Valid DOI/arXiv/URL on every paper", requires=("research",))
def t2_09_1() -> None:
    recs = _load_papers()
    assert len(recs) >= 10
    cite_re = re.compile(r"^(?:10\.\d{4,9}/\S+|(?:arXiv:)?\d{4}\.\d{4,5}(?:v\d+)?)$", re.I)
    for idx, rec in enumerate(recs):
        assert h.is_valid_http_url(str(rec.get("url", ""))), f"Paper #{idx} invalid url: {rec.get('url')!r}"
        cite = str(rec.get("doi_or_arxiv_id", "")).strip()
        assert cite_re.match(cite), f"Paper #{idx} invalid doi_or_arxiv_id: {cite!r}"


@h.test_case(id="T2-09-2", tier=2, feature_id="#9", title="Authors, year, and venue non-empty on every paper", requires=("research",))
def t2_09_2() -> None:
    recs = _load_papers()
    assert len(recs) >= 10
    for idx, rec in enumerate(recs):
        authors = rec.get("authors")
        year = rec.get("year")
        venue = rec.get("venue")
        assert isinstance(authors, list) and len(authors) >= 1 and all(isinstance(a, str) and a.strip() for a in authors), (
            f"Paper #{idx} invalid authors: {authors!r}"
        )
        assert isinstance(year, int) and 1990 <= year <= 2030, f"Paper #{idx} invalid year {year!r}"
        assert isinstance(venue, str) and len(venue.strip()) >= 2, f"Paper #{idx} missing/empty venue: {venue!r}"


@h.test_case(id="T2-09-3", tier=2, feature_id="#9", title="Structured summary & algorithmic relevance populated on every paper", requires=("research",))
def t2_09_3() -> None:
    recs = _load_papers()
    assert len(recs) >= 10
    for idx, rec in enumerate(recs):
        assert len(str(rec.get("summary", "")).strip()) >= 30, f"Paper #{idx} lacks detailed summary"
        assert len(str(rec.get("key_algorithm", "")).strip()) >= 30, f"Paper #{idx} lacks key_algorithm"
        assert len(str(rec.get("relevance_to_forma_print", "")).strip()) >= 20, f"Paper #{idx} lacks relevance_to_forma_print"


@h.test_case(id="T2-09-4", tier=2, feature_id="#9", title="100% of papers.jsonl passes papers.schema.json", requires=("research",))
def t2_09_4() -> None:
    schema = json.loads(h.require_research_file("schemas/papers.schema.json").read_text(encoding="utf-8"))
    recs = _load_papers()
    assert len(recs) >= 10
    for idx, rec in enumerate(recs):
        errs = h.validate_json_schema_subset(rec, schema)
        assert not errs, f"Paper #{idx} schema error: {errs}"


@h.test_case(id="T2-09-5", tier=2, feature_id="#9", title="No duplicate paper IDs or titles", requires=("research",))
def t2_09_5() -> None:
    recs = _load_papers()
    ids = [str(r.get("id") or r.get("title")).strip().lower() for r in recs]
    assert len(ids) == len(set(ids)), "Duplicate paper IDs/titles"


# ===========================================================================
# #10: R4.1-R4.2 RAG DB & chunking boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-10-1", tier=2, feature_id="#10", title="FTS5 + BM25/TF-IDF query returns ranked results", requires=("research",))
def t2_10_1() -> None:
    proc = _run_query_rag_raw("overhang angle support", top_k=5)
    assert proc.returncode == 0, f"query_rag failed: {proc.stderr}"
    data = json.loads(proc.stdout)
    results = data.get("results", [])
    assert isinstance(results, list) and 1 <= len(results) <= 5, f"Unexpected results: {data}"
    scores = []
    for r in results:
        assert isinstance(r.get("chunk_id"), str) and r["chunk_id"].strip()
        assert isinstance(r.get("entity_id"), str) and r["entity_id"].strip()
        assert isinstance(r.get("domain"), str) and r["domain"].strip()
        assert isinstance(r.get("snippet"), str) and r["snippet"].strip()
        scores.append(float(r["score"]))
    assert scores == sorted(scores, reverse=True) and scores[0] > 0.0, f"Non-monotonic scores: {scores}"
    res_blob = json.dumps(results).lower()
    assert "overhang" in res_blob or "support" in res_blob


@h.test_case(id="T2-10-2", tier=2, feature_id="#10", title="Domain and top-k filter flags restrict results cleanly", requires=("research",))
def t2_10_2() -> None:
    p1 = _run_query_rag_raw("printer telemetry", domain="manufacturer", top_k=2)
    assert p1.returncode == 0 and p1.stdout.strip(), f"query_rag failed: rc={p1.returncode}, stderr={p1.stderr}"
    d1 = json.loads(p1.stdout)
    assert d1.get("filters", {}).get("domain") == "manufacturer"
    res1 = d1.get("results", [])
    assert isinstance(res1, list) and 1 <= len(res1) <= 2, f"Expected 1..2 results, got {res1}"
    for r in res1:
        assert r.get("domain") == "manufacturer", f"Unexpected domain in {r}"
        assert isinstance(r.get("chunk_id"), str) and r["chunk_id"].strip()
        assert isinstance(r.get("entity_id"), str) and r["entity_id"].strip()
        assert isinstance(r.get("snippet"), str) and r["snippet"].strip()
        assert h.is_valid_http_url(str(r.get("source_url", ""))), f"Invalid source_url in {r}"
    res_blob = json.dumps(res1).lower()
    assert any(k in res_blob for k in ("telemetry", "sensor", "mqtt", "http", "status", "printer"))

    p_k1 = _run_query_rag_raw("printer telemetry", domain="manufacturer", top_k=1)
    assert p_k1.returncode == 0
    assert len(json.loads(p_k1.stdout).get("results", [])) == 1

    p_bad = _run_query_rag_raw("printer telemetry", domain="manufacturers", top_k=2)
    assert p_bad.returncode != 0, "Expected plural --domain manufacturers to be rejected"


@h.test_case(id="T2-10-3", tier=2, feature_id="#10", title="Empty or nonsense RAG query handled gracefully without crash", requires=("research",))
def t2_10_3() -> None:
    for q in ("", "qxqz_nonexistent_xylophobe_zz77"):
        proc = _run_query_rag_raw(q, top_k=3)
        assert proc.returncode == 0, f"query_rag failed on {q!r}: {proc.stderr}"
        data = json.loads(proc.stdout)
        assert data.get("results") == [], f"Expected empty results for {q!r}, got {data}"
        assert data.get("total_candidates") == 0, f"Expected 0 candidates for {q!r}, got {data}"


@h.test_case(id="T2-10-4", tier=2, feature_id="#10", title="Deterministic top-k ordering across repeated runs", requires=("research",))
def t2_10_4() -> None:
    p1 = _run_query_rag_raw("Klipper Moonraker upload", top_k=5)
    p2 = _run_query_rag_raw("Klipper Moonraker upload", top_k=5)
    assert p1.returncode == 0 and p2.returncode == 0
    d1 = json.loads(p1.stdout)
    d2 = json.loads(p2.stdout)
    assert d1.get("total_candidates", 0) > 0
    assert len(d1.get("results", [])) == 5
    assert d1["total_candidates"] == d2["total_candidates"]
    assert d1["results"] == d2["results"], f"Results drifted across runs:\n{d1['results']}\nvs\n{d2['results']}"
    scores = [float(r["score"]) for r in d1["results"]]
    assert scores == sorted(scores, reverse=True)


@h.test_case(id="T2-10-5", tier=2, feature_id="#10", title="build_rag.py rebuilds SQLite index cleanly into temp DB", requires=("research",))
def t2_10_5() -> None:
    build_script = h.require_research_file("rag/build_rag.py")
    help_text = h.run_cmd(["python3", str(build_script), "--help"]).stdout.lower()
    with h.temp_dir() as td:
        tmp_db = pathlib.Path(td) / "test_kb.sqlite"
        if "--out" in help_text:
            proc = h.run_cmd(["python3", str(build_script), "--out", str(tmp_db)])
        elif "--db" in help_text:
            proc = h.run_cmd(["python3", str(build_script), "--db", str(tmp_db)])
        else:
            src_research = build_script.parents[1]
            copy_r = pathlib.Path(td) / "research"
            shutil.copytree(src_research, copy_r)
            proc = h.run_cmd(["python3", str(copy_r / "rag" / "build_rag.py")])
            tmp_db = copy_r / "rag" / "forma_print_kb.sqlite"
        assert proc.returncode == 0, f"build_rag.py failed: {proc.stdout}\n{proc.stderr}"
        assert tmp_db.is_file() and tmp_db.stat().st_size > 0
        conn = sqlite3.connect(str(tmp_db))
        try:
            chunks_cnt = conn.execute("SELECT COUNT(*) FROM chunks").fetchone()[0]
            fts_cnt = conn.execute("SELECT COUNT(*) FROM chunks_fts").fetchone()[0]
        finally:
            conn.close()
        assert chunks_cnt >= 400 and fts_cnt == chunks_cnt, f"Unexpected counts: chunks={chunks_cnt}, fts={fts_cnt}"
        q_proc = _run_query_rag_raw("Bambu Lab MQTT", top_k=3, db_path=tmp_db)
        assert q_proc.returncode == 0, f"query_rag on temp DB failed: {q_proc.stderr}"
        q_data = json.loads(q_proc.stdout)
        q_res = q_data.get("results", [])
        assert 1 <= len(q_res) <= 3, f"Unexpected results count: {q_data}"
        top = q_res[0]
        assert top.get("entity_id") == "bambu_lab", f"Expected entity_id='bambu_lab', got {top}"
        assert top.get("domain") == "manufacturer", f"Expected domain='manufacturer', got {top}"
        assert str(top.get("chunk_id", "")).startswith("mf:bambu_lab:"), f"Unexpected chunk_id: {top}"
        assert float(top.get("score", 0.0)) > 0.0, f"Expected positive score, got {top}"
        assert h.is_valid_http_url(str(top.get("source_url", ""))), f"Invalid source_url: {top}"
        assert "mqtt" in json.dumps(top).lower(), f"Expected MQTT content in top hit: {top}"
        for r in q_res:
            assert isinstance(r.get("chunk_id"), str) and r["chunk_id"].strip()
            assert float(r.get("score", 0.0)) > 0.0

        # Prove --db actually selects the supplied database (not hardcoded default DB or echo stub)
        empty_db = pathlib.Path(td) / "empty.sqlite"
        sqlite3.connect(str(empty_db)).close()
        q_empty = _run_query_rag_raw("Bambu Lab MQTT", top_k=3, db_path=empty_db)
        if q_empty.returncode == 0:
            assert json.loads(q_empty.stdout).get("results") == [], (
                f"Expected no hits on empty SQLite DB, got: {q_empty.stdout}"
            )

        zero_db = pathlib.Path(td) / "zero_rows.sqlite"
        shutil.copy2(tmp_db, zero_db)
        zconn = sqlite3.connect(str(zero_db))
        try:
            zconn.execute("DELETE FROM chunks")
            zconn.execute("DELETE FROM chunks_fts")
            zconn.commit()
        finally:
            zconn.close()
        q_zero = _run_query_rag_raw("Bambu Lab MQTT", top_k=3, db_path=zero_db)
        assert q_zero.returncode == 0, f"query_rag failed on zero-row DB: {q_zero.stderr}"
        d_zero = json.loads(q_zero.stdout)
        assert d_zero.get("total_candidates") == 0 and d_zero.get("results") == [], (
            f"Expected 0 hits on zero-row DB (--db ignored?), got: {d_zero}"
        )


# ===========================================================================
# #11: R4.3 Automated KB & RAG validation boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-11-1", tier=2, feature_id="#11", title="Validator catches corrupted JSONL record", requires=("research",))
def t2_11_1() -> None:
    def corrupt(rdir: pathlib.Path) -> None:
        p = rdir / "corpus" / "software.jsonl"
        p.write_text(p.read_text(encoding="utf-8") + "\n{broken json\n", encoding="utf-8")

    _run_validate_kb_on_mutated_copy(corrupt)


@h.test_case(id="T2-11-2", tier=2, feature_id="#11", title="Validator catches missing required field", requires=("research",))
def t2_11_2() -> None:
    def drop_field(rdir: pathlib.Path) -> None:
        p = rdir / "corpus" / "papers.jsonl"
        lines = [ln for ln in p.read_text(encoding="utf-8").splitlines() if ln.strip()]
        obj = json.loads(lines[0])
        for k in ("title", "id", "authors"):
            obj.pop(k, None)
        lines[0] = json.dumps(obj)
        p.write_text("\n".join(lines) + "\n", encoding="utf-8")

    _run_validate_kb_on_mutated_copy(drop_field)


@h.test_case(id="T2-11-3", tier=2, feature_id="#11", title="Validator catches invalid URL format", requires=("research",))
def t2_11_3() -> None:
    def bad_url(rdir: pathlib.Path) -> None:
        p = rdir / "corpus" / "manufacturers.jsonl"
        text = p.read_text(encoding="utf-8")
        text = re.sub(r"https?://[^\s\"']+", "not_a_valid_url", text, count=5)
        p.write_text(text, encoding="utf-8")

    _run_validate_kb_on_mutated_copy(bad_url)


@h.test_case(id="T2-11-4", tier=2, feature_id="#11", title="Validator exits non-zero on missing/corrupt SQLite DB", requires=("research",))
def t2_11_4() -> None:
    def break_db(rdir: pathlib.Path) -> None:
        db = rdir / "rag" / "forma_print_kb.sqlite"
        db.write_bytes(b"corrupt sqlite header")

    _run_validate_kb_on_mutated_copy(break_db)


@h.test_case(id="T2-11-5", tier=2, feature_id="#11", title="Validator reports structured summary counts", requires=("research",))
def t2_11_5() -> None:
    p = h.require_research_file("scripts/validate_kb.py")
    proc = h.run_cmd(["python3", str(p), "--json"])
    assert proc.returncode == 0, f"validate_kb.py --json failed: {proc.stderr}"
    report = json.loads(proc.stdout)
    assert report.get("status") == "pass"
    assert report.get("errors") == []
    assert report.get("total_chunks", 0) > 0
    assert report.get("db_size_bytes", 0) > 0
    counts = report.get("counts", {})
    for k in ("software", "manufacturers", "papers"):
        assert isinstance(counts.get(k), int) and counts[k] > 0, f"Missing/zero count for {k}: {counts}"
    checks = report.get("checks", [])
    assert len(checks) >= 5 and all(c.get("passed") is True for c in checks), f"Failed check in {checks}"


# ===========================================================================
# #12: R5.1-R5.2 Efficiency & justification boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-12-1", tier=2, feature_id="#12", title="Efficiency analysis distinguishes measured vs estimated metrics", requires=("research",))
def t2_12_1() -> None:
    raw = h.require_research_file("analysis/efficiency_justification.md").read_text(encoding="utf-8")
    assert len(raw.strip()) >= 2500, "efficiency_justification.md unexpectedly short"
    text = raw.lower()
    assert "tier a" in text and "tier b" in text and "tier c" in text, (
        "Expected explicit Tier A/B/C evidence attribution separating measured, baseline, and estimated metrics"
    )
    assert "no external fable 5.2" in text or ("fable 5.2" in text and "not fabricated" in text), (
        "Expected explicit disclosure that no external Fable 5.2 runs were fabricated/executed locally"
    )
    assert "measur" in text and ("estimat" in text or "analytical" in text)
    assert re.search(r"\bp50\b|\bp95\b", text) and re.search(r"\d+(?:\.\d+)?\s*ms", text), (
        "Expected measured ms latency percentiles in efficiency_justification.md"
    )
    assert any(k in text for k in ("bytes/token", "multiplier", "formula", "assumption")), (
        "Expected explicit assumptions/formulas for analytical estimates"
    )


@h.test_case(id="T2-12-2", tier=2, feature_id="#12", title="bench_efficiency.py outputs structured JSON or tabular metrics", requires=("research",))
def t2_12_2() -> None:
    p = h.require_research_file("scripts/bench_efficiency.py")
    proc = h.run_cmd(["python3", str(p), "--runs", "3", "--rag-runs", "3", "--json"], timeout=120.0)
    assert proc.returncode == 0, f"bench_efficiency.py --json failed: {proc.stderr}"
    data = json.loads(proc.stdout)
    assert data.get("tokenizer") == "o200k_base"
    art_bytes = data.get("artifacts", {}).get("bytes", {})
    for k in ("forma", "forma_mcp", "forma_print", "forma_wasm", "rag_sqlite"):
        assert isinstance(art_bytes.get(k), int) and art_bytes[k] > 0, f"Invalid artifact bytes for {k}: {art_bytes}"
    core_tok = data.get("mcp", {}).get("core_forma_mcp", {}).get("tools_compact_o200k_tokens", 0)
    assert 0 < core_tok < 800, f"core_forma_mcp tokens out of budget: {core_tok}"
    cli_benches = data.get("cli_benchmarks", {}).get("benchmarks", [])
    assert isinstance(cli_benches, list) and len(cli_benches) >= 10
    rag_b = data.get("rag_benchmarks", {})
    assert rag_b.get("corpus_totals", {}).get("total_chunks", 0) > 0
    assert rag_b.get("by_top_k", {}).get("5", {}).get("rank1_hits", 0) >= 18


@h.test_case(id="T2-12-3", tier=2, feature_id="#12", title="Efficiency analysis covers DFM geometry + RAG lookup + token savings", requires=("research",))
def t2_12_3() -> None:
    raw = h.require_research_file("analysis/efficiency_justification.md").read_text(encoding="utf-8")
    text = raw.lower()
    for term in (
        "dfm",
        "rag",
        "token",
        "accuracy",
        "latency",
        "deterministic",
        "o200k",
        "bench_efficiency.py",
        "validate_kb.py",
    ):
        assert term in text, f"efficiency_justification.md missing required topic/tool {term!r}"
    # Explicit non-replacement scope boundaries
    for sys_term in ("orcaslicer", "prusaslicer", "klipper", "octoprint"):
        assert sys_term in text, f"Missing non-replacement reference system {sys_term!r}"
    assert "not a replacement" in text or "does not replace" in text, (
        "Expected explicit non-replacement boundary statement"
    )
    # Cross-check live KB counts cited in the analysis
    conn = sqlite3.connect(str(h.require_research_file("rag/forma_print_kb.sqlite")))
    try:
        chunk_cnt = conn.execute("SELECT COUNT(*) FROM chunks").fetchone()[0]
    finally:
        conn.close()
    rec_cnt = sum(
        len(h.load_jsonl(h.require_research_file(p)))
        for p in ("corpus/software.jsonl", "corpus/manufacturers.jsonl", "corpus/papers.jsonl")
    )
    digits_norm = raw.replace(",", "")
    assert str(chunk_cnt) in digits_norm, f"Analysis missing live RAG chunk count {chunk_cnt}"
    assert str(rec_cnt) in digits_norm, f"Analysis missing live corpus record count {rec_cnt}"
    assert "18/18" in digits_norm and "100%" in digits_norm, "Expected 18/18 (100%) RAG rank-1 accuracy metric"


@h.test_case(id="T2-12-4", tier=2, feature_id="#12", title="Efficiency analysis contains zero placeholder/TBD markers", requires=("research",))
def t2_12_4() -> None:
    doc_path = h.require_research_file("analysis/efficiency_justification.md")
    text = doc_path.read_text(encoding="utf-8")
    assert len(text.strip()) >= 2000, "efficiency_justification.md unexpectedly short"
    assert not re.search(
        r"\b(TBD|TODO|FIXME|PLACEHOLDER|XXX|WIP|COMING\s+SOON|TO\s+BE\s+DETERMINED)\b",
        text,
        flags=re.I,
    ), "Placeholder marker found in efficiency_justification.md"
    assert not re.search(
        r"\bN/A\b|\[(?:insert|todo|tbd|placeholder)[^\]]*\]|<(?:tbd|todo|placeholder)[^>]*>",
        text,
        flags=re.I,
    ), "Template placeholder found in efficiency_justification.md"
    for lineno, ln in enumerate(text.splitlines(), start=1):
        if ln.strip().startswith("|"):
            cells = [c.strip() for c in ln.strip().strip("|").split("|")]
            bad_cells = [c for c in cells if not c or c in ("-", "—", "N/A", "...")]
            assert not bad_cells, f"Empty/placeholder table cell at line {lineno}: {cells}"
    for link in re.findall(r"\[[^\]]+\]\(([^)#]+)\)", text):
        if link.startswith(("http://", "https://")):
            continue
        target = (doc_path.parent / link).resolve()
        assert target.exists(), f"Broken relative link in efficiency_justification.md: {link!r} -> {target}"


@h.test_case(id="T2-12-5", tier=2, feature_id="#12", title="bench_efficiency.py deterministic output keys across repeated runs", requires=("research",))
def t2_12_5() -> None:
    p = h.require_research_file("scripts/bench_efficiency.py")
    p1 = h.run_cmd(["python3", str(p), "--json"], timeout=120.0)
    p2 = h.run_cmd(["python3", str(p), "--json"], timeout=120.0)
    assert p1.returncode == 0 and p2.returncode == 0
    d1 = json.loads(p1.stdout)
    d2 = json.loads(p2.stdout)
    assert _canonical_bench_json(d1) == _canonical_bench_json(d2), "Deterministic benchmark JSON drifted across runs"
    assert d1.get("artifacts", {}).get("bytes")
    mcp = d1.get("mcp", {})
    assert 0 < mcp.get("core_forma_mcp", {}).get("tools_compact_o200k_tokens", 0) < 800
    assert mcp.get("opt_in_forma_print_mcp", {}).get("tools_compact_o200k_tokens", 0) > 0
    sess = mcp.get("live_session_upside_down_t", {})
    assert sess and all(isinstance(v, dict) and v.get("response_bytes", 0) > 0 for v in sess.values())
    cli_benches = d1.get("cli_benchmarks", {}).get("benchmarks", [])
    assert len(cli_benches) >= 10 and all(
        isinstance(b.get("deterministic"), dict) and len(b["deterministic"]) > 0 for b in cli_benches
    )
    k5 = d1.get("rag_benchmarks", {}).get("by_top_k", {}).get("5", {})
    assert k5.get("queries_total", 0) > 0 and k5.get("rank1_hits") == k5.get("queries_total")


# ===========================================================================
# #13: R6.1 Workspace & zero-bloat isolation boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-13-1", tier=2, feature_id="#13", title="Cargo.lock adds 0 new external crates", requires=("core_baseline",))
def t2_13_1() -> None:
    base = _git_merge_base_main()
    diff = h.run_cmd(["git", "diff", base, "--", "Cargo.lock"])
    assert diff.returncode == 0
    added = [ln for ln in diff.stdout.splitlines() if ln.startswith("+name = ") and 'forma-print' not in ln]
    assert not added, f"Unexpected new crates added to Cargo.lock: {added}"


@h.test_case(id="T2-13-2", tier=2, feature_id="#13", title="Core crates unmodified vs main", requires=("core_baseline",))
def t2_13_2() -> None:
    base = _git_merge_base_main()
    diff = h.run_cmd([
        "git",
        "diff",
        base,
        "--",
        "crates/forma-core",
        "crates/forma-lang",
        "crates/forma-cli",
        "crates/forma-mcp",
        "crates/forma-wasm",
    ])
    assert diff.returncode == 0
    assert diff.stdout.strip() == "", f"Core crates modified vs merge-base {base}:\n{diff.stdout[:800]}"


@h.test_case(id="T2-13-3", tier=2, feature_id="#13", title="Core forma & forma-mcp release binary sizes match baseline (0 bloat)", requires=("core_baseline",))
def t2_13_3() -> None:
    forma_sz = h.find_forma_bin().stat().st_size
    mcp_sz = h.find_forma_mcp_bin().stat().st_size
    assert forma_sz == h.BASELINE_SIZES["forma"], f"forma size changed: {forma_sz} != {h.BASELINE_SIZES['forma']}"
    assert mcp_sz == h.BASELINE_SIZES["forma-mcp"], f"forma-mcp size changed: {mcp_sz} != {h.BASELINE_SIZES['forma-mcp']}"


@h.test_case(id="T2-13-4", tier=2, feature_id="#13", title="wasm/forma.wasm size matches baseline (< 800 KB, 0 bloat)", requires=("core_baseline",))
def t2_13_4() -> None:
    wasm_path = h.REPO_ROOT / "wasm" / "forma.wasm"
    assert wasm_path.is_file(), "Missing wasm/forma.wasm"
    sz = wasm_path.stat().st_size
    assert sz == h.BASELINE_SIZES["wasm"] and sz < 800 * 1024, f"wasm/forma.wasm size={sz}"


@h.test_case(id="T2-13-5", tier=2, feature_id="#13", title="Core workspace cargo test --release passes 100%", requires=("core_baseline",))
def t2_13_5() -> None:
    proc = h.run_cmd(["cargo", "test", "--manifest-path", str(h.REPO_ROOT / "Cargo.toml"), "--release"], timeout=180.0)
    assert proc.returncode == 0, f"Core cargo test --release failed:\n{proc.stdout}\n{proc.stderr}"


# ===========================================================================
# #14: R6.2 Printer & filament profile boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-14-1", tier=2, feature_id="#14", title="All 18 printer build volumes match spec", requires=("forma_print",))
def t2_14_1() -> None:
    _, data = h.run_forma_print_json(["profiles"])
    by_id = {h.printer_id_of(p): p for p in h.extract_printers(data)}
    for pid, expected in h.EXPECTED_PRINTER_VOLUMES_MM.items():
        assert pid in by_id, f"Missing printer {pid}"
        vol = h.printer_volume_of(by_id[pid])
        assert all(abs(vol[i] - expected[i]) < 0.05 for i in range(3)), f"{pid}: expected {expected}, got {vol}"


@h.test_case(id="T2-14-2", tier=2, feature_id="#14", title="Unknown --tech foo exits non-zero", requires=("forma_print",))
def t2_14_2() -> None:
    proc = h.run_forma_print(["profiles", "--tech", "unknown_tech_foo"])
    assert proc.returncode != 0


@h.test_case(id="T2-14-3", tier=2, feature_id="#14", title="Unknown --printer bar on check exits non-zero", requires=("forma_print",))
def t2_14_3() -> None:
    proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", "unknown_printer_bar"])
    assert proc.returncode != 0


@h.test_case(id="T2-14-4", tier=2, feature_id="#14", title="Unknown --material baz on check exits non-zero", requires=("forma_print",))
def t2_14_4() -> None:
    proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--material", "UNOBTANIUM_99"])
    assert proc.returncode != 0


@h.test_case(id="T2-14-5", tier=2, feature_id="#14", title="Printer tech-specific wall/overhang thresholds differ cleanly (FDM vs SLA vs SLS)", requires=("forma_print",))
def t2_14_5() -> None:
    _, fdm = h.run_forma_print_json(["profiles", "--tech", "fdm"])
    _, sla = h.run_forma_print_json(["profiles", "--tech", "sla"])
    _, sls = h.run_forma_print_json(["profiles", "--tech", "sls"])
    fdm_list = h.extract_printers(fdm)
    sla_list = h.extract_printers(sla)
    sls_list = h.extract_printers(sls)
    assert fdm_list and sla_list and sls_list

    # 1. Require tech-specific threshold/process metadata in profiles --json (fail bare {id, tech, build_volume} stubs)
    thresh_re = re.compile(r"(wall|overhang|angle|clearance|nozzle|xy_res|resolution|layer|min_|max_|support|bridge)")

    def _thresh_sig(p: dict) -> dict:
        return {
            k: v
            for k, v in p.items()
            if thresh_re.search(k.lower()) and k.lower() not in ("id", "name", "tech", "technology")
        }

    fdm_by_id = {h.printer_id_of(p): p for p in fdm_list}
    sla_by_id = {h.printer_id_of(p): p for p in sla_list}
    sls_by_id = {h.printer_id_of(p): p for p in sls_list}
    assert "bambu_x1c" in fdm_by_id and "elegoo_saturn_4_ultra" in sla_by_id and "formlabs_fuse_1p" in sls_by_id

    fdm_sig = _thresh_sig(fdm_by_id["bambu_x1c"])
    sla_sig = _thresh_sig(sla_by_id["elegoo_saturn_4_ultra"])
    sls_sig = _thresh_sig(sls_by_id["formlabs_fuse_1p"])
    assert fdm_sig and sla_sig and sls_sig, (
        f"profiles --json missing tech-specific threshold metadata: fdm={fdm_sig}, sla={sla_sig}, sls={sls_sig}"
    )
    assert len({json.dumps(fdm_sig, sort_keys=True), json.dumps(sla_sig, sort_keys=True), json.dumps(sls_sig, sort_keys=True)}) >= 2, (
        f"Expected FDM/SLA/SLS threshold metadata to differ: {fdm_sig} vs {sla_sig} vs {sls_sig}"
    )

    # 2. Behavioral differentiation on 56.31 deg overhang_cone.forma: FDM & SLA flag overhang; SLS (powder bed) does not
    _, fdm_rep = h.run_forma_print_json(
        ["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--printer", "bambu_x1c", "--material", "PLA"],
        allow_nonzero=True,
    )
    h.assert_check_flags(fdm_rep, ("overhang", "angle", "support"), "FDM overhang_cone")

    _, sla_rep = h.run_forma_print_json(
        ["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--printer", "elegoo_saturn_4_ultra", "--material", "RESIN_STD"],
        allow_nonzero=True,
    )
    h.assert_check_flags(sla_rep, ("overhang", "angle", "support"), "SLA overhang_cone")

    _, sls_rep = h.run_forma_print_json(
        ["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--printer", "formlabs_fuse_1p", "--material", "SLS_PA12"],
        allow_nonzero=True,
    )
    sls_issues = "\n".join(h.extract_issue_texts(sls_rep))
    assert not any(k in sls_issues for k in ("overhang", "angle")), (
        f"SLS (powder bed) must not flag overhang on overhang_cone.forma: {sls_rep}"
    )
    h.assert_check_clean(sls_rep, "SLS overhang_cone")


# ===========================================================================
# #15: R6.3 Unit bridge boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-15-1", tier=2, feature_id="#15", title="Invalid --unit km exits non-zero", requires=("forma_print",))
def t2_15_1() -> None:
    proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "km"])
    assert proc.returncode != 0


@h.test_case(id="T2-15-2", tier=2, feature_id="#15", title="Negative --scale -1.0 exits non-zero", requires=("forma_print",))
def t2_15_2() -> None:
    proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--scale", "-1.0"])
    assert proc.returncode != 0


@h.test_case(id="T2-15-3", tier=2, feature_id="#15", title="Zero --scale 0 exits non-zero", requires=("forma_print",))
def t2_15_3() -> None:
    proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--scale", "0"])
    assert proc.returncode != 0


@h.test_case(id="T2-15-4", tier=2, feature_id="#15", title="Non-numeric --scale abc exits non-zero", requires=("forma_print",))
def t2_15_4() -> None:
    proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--scale", "abc"])
    assert proc.returncode != 0


@h.test_case(id="T2-15-5", tier=2, feature_id="#15", title="Sub-meter .stl with --unit auto vs --unit mm behaves deterministically", requires=("forma_print",))
def t2_15_5() -> None:
    with h.temp_dir() as td:
        stl_m = h.write_binary_box_stl(pathlib.Path(td) / "submeter.stl", (0.04, 0.03, 0.02))
        _, d_auto1 = h.run_forma_print_json(["check", str(stl_m), "--unit", "auto"], allow_nonzero=True)
        _, d_auto2 = h.run_forma_print_json(["check", str(stl_m), "--unit", "auto"], allow_nonzero=True)
        _, d_mm = h.run_forma_print_json(["check", str(stl_m), "--unit", "mm"], allow_nonzero=True)
        assert h.extract_bbox_size_mm(d_auto1) == h.extract_bbox_size_mm(d_auto2)
        sz_auto = h.extract_bbox_size_mm(d_auto1)
        sz_mm = h.extract_bbox_size_mm(d_mm)
        assert sz_auto is not None and sz_mm is not None
        assert max(sz_auto) > max(sz_mm), f"Expected --unit auto on submeter STL to scale to mm: auto={sz_auto}, mm={sz_mm}"


# ===========================================================================
# #16: R6.4 BVH & DFM audit boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-16-1", tier=2, feature_id="#16", title="bambu_p1s front-left 18x28 mm cutter exclusion zone flagged", requires=("forma_print",))
def t2_16_1() -> None:
    _, p1s_rep = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "p1s_cutter_zone.forma"), "--printer", "bambu_p1s"], allow_nonzero=True)
    h.assert_check_flags(p1s_rep, ("cutter", "exclusion", "zone", "bound", "fit", "corner"), "p1s cutter exclusion")


@h.test_case(id="T2-16-2", tier=2, feature_id="#16", title="bambu_h2d_dual (300 mm) vs bambu_h2d_single (325 mm) X-reach difference", requires=("forma_print",))
def t2_16_2() -> None:
    _, single_rep = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "h2d_dual_span.forma"), "--printer", "bambu_h2d_single"])
    h.assert_check_clean(single_rep, "320mm span on bambu_h2d_single")
    _, dual_rep = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "h2d_dual_span.forma"), "--printer", "bambu_h2d_dual"], allow_nonzero=True)
    h.assert_check_flags(dual_rep, ("volume", "bound", "fit", "zone", "exceed", "x", "dual"), "320mm span on bambu_h2d_dual")


@h.test_case(id="T2-16-3", tier=2, feature_id="#16", title="Tall unstable part tipping / bed adhesion flagged", requires=("forma_print",))
def t2_16_3() -> None:
    _, rep = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "tall_unstable.forma"), "--printer", "bambu_a1_mini"], allow_nonzero=True)
    h.assert_check_flags(rep, ("tip", "stabil", "adhes", "aspect", "com", "center", "bed", "contact"), "tall_unstable")


@h.test_case(id="T2-16-4", tier=2, feature_id="#16", title="Multi-part collision and tight SLS clearance (<0.5 mm) flagged", requires=("forma_print",))
def t2_16_4() -> None:
    _, col = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "multi_part_collision.forma"), "--printer", "bambu_x1c"], allow_nonzero=True)
    h.assert_check_flags(col, ("clear", "collid", "intersect", "overlap", "gap"), "multi_part_collision")
    _, sls_gap = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "multi_part_clear.forma"), "--printer", "formlabs_fuse_1p", "--material", "SLS_PA12"], allow_nonzero=True)
    h.assert_check_flags(sls_gap, ("clear", "gap", "powder", "fuse", "spacing"), "0.30mm gap on SLS")


@h.test_case(id="T2-16-5", tier=2, feature_id="#16", title="Multi-material .forma reports >0 AMS swaps/waste", requires=("forma_print",))
def t2_16_5() -> None:
    _, rep = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "multi_color_ams.forma"), "--printer", "bambu_x1c", "--material", "PLA"])
    swaps = h.extract_numeric_field(rep, ("ams_swaps", "swaps", "tool_changes", "color_changes", "filament_changes", "purge_grams"))
    assert swaps is not None and swaps > 0, f"Expected >0 AMS swaps/waste metric, got {rep}"


# ===========================================================================
# #17: R6.5 Diagnostic heatmap boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-17-1", tier=2, feature_id="#17", title="Unwritable --heatmap /nonexistent/dir/out.png exits non-zero", requires=("forma_print",))
def t2_17_1() -> None:
    proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--heatmap", "/nonexistent_e2e_dir_12345/sub/out.png"])
    assert proc.returncode != 0


@h.test_case(id="T2-17-2", tier=2, feature_id="#17", title="Empty or non-manifold STL fails gracefully", requires=("forma_print",))
def t2_17_2() -> None:
    for bad in ("empty.stl", "corrupt_truncated.stl", "non_manifold.stl"):
        proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / bad), "--json"])
        assert "panicked at" not in proc.stderr.lower(), f"Rust panic on {bad}:\n{proc.stderr}"
        if proc.returncode == 0:
            # If check emits structured fail JSON for non_manifold, verify it flagged non-manifold
            assert bad == "non_manifold.stl", f"Expected non-zero exit for {bad}, got rc=0"
            data = json.loads(proc.stdout)
            h.assert_check_flags(data, ("manifold", "watertight", "boundary"), bad)
        else:
            assert proc.returncode > 0, f"Process killed by signal ({proc.returncode}) on {bad}:\n{proc.stderr}"
            if bad == "non_manifold.stl":
                combined = (proc.stdout + "\n" + proc.stderr).lower()
                assert any(
                    k in combined for k in ("manifold", "watertight", "boundary", "non-manifold", "open", "edge")
                ), f"Expected non_manifold.stl error to mention manifold/watertightness, got:\n{combined}"


@h.test_case(id="T2-17-3", tier=2, feature_id="#17", title="Multi-material part heatmap renders cleanly without panic", requires=("forma_print",))
def t2_17_3() -> None:
    with h.temp_dir() as td:
        out = pathlib.Path(td) / "ams_hm.png"
        proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "multi_color_ams.forma"), "--heatmap", str(out)])
        assert proc.returncode == 0
        assert h.inspect_png(out)["width"] >= 128


@h.test_case(id="T2-17-4", tier=2, feature_id="#17", title="Repeated heatmap runs produce byte-identical PNGs", requires=("forma_print",))
def t2_17_4() -> None:
    with h.temp_dir() as td:
        p1 = pathlib.Path(td) / "hm1.png"
        p2 = pathlib.Path(td) / "hm2.png"
        r1 = h.run_forma_print(["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--heatmap", str(p1)])
        r2 = h.run_forma_print(["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--heatmap", str(p2)])
        assert r1.returncode in (0, 3) and r2.returncode in (0, 3)
        assert "panicked at" not in r1.stderr.lower() and "panicked at" not in r2.stderr.lower()
        assert p1.read_bytes() == p2.read_bytes()


@h.test_case(id="T2-17-5", tier=2, feature_id="#17", title="Heatmap PNG contains multiple distinct severity/edge RGB colors", requires=("forma_print",))
def t2_17_5() -> None:
    with h.temp_dir() as td:
        out = pathlib.Path(td) / "sev.png"
        proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--heatmap", str(out)])
        assert proc.returncode in (0, 3)
        assert "panicked at" not in proc.stderr.lower()
        info = h.inspect_png(out)
        assert info["distinct_colors_sampled"] >= 3, f"Expected multi-color heatmap, got {info}"


# ===========================================================================
# #18: R6.6 Auto-orientation solver boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-18-1", tier=2, feature_id="#18", title="Already-optimal cube preserves z0=0 orientation", requires=("forma_print",))
def t2_18_1() -> None:
    with h.temp_dir() as td:
        out = pathlib.Path(td) / "cube_orient.stl"
        _, data = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "box_meters.forma"), "--out", str(out)])
        assert data.get("rotated_from_input") is False, f"Expected cube not rotated, got {data}"
        assert data.get("report", {}).get("printable") is True, f"Expected cube printable, got {data}"
        info = h.inspect_stl(out)
        assert abs(info["bbox_min"][2]) < 1e-2


@h.test_case(id="T2-18-2", tier=2, feature_id="#18", title="Flared cone prefers wide flat base over narrow tip", requires=("forma_print",))
def t2_18_2() -> None:
    with h.temp_dir() as td:
        out = pathlib.Path(td) / "cone_orient.stl"
        h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--out", str(out)])
        info = h.inspect_stl(out)
        assert abs(info["bbox_min"][2]) < 1e-2
        _, rep = h.run_forma_print_json(["check", str(out), "--unit", "mm", "--printer", "bambu_x1c"])
        h.assert_check_clean(rep, "flipped cone on wide base")


@h.test_case(id="T2-18-3", tier=2, feature_id="#18", title="Invalid --printer on orient exits non-zero", requires=("forma_print",))
def t2_18_3() -> None:
    proc = h.run_forma_print(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--printer", "nonexistent_printer_99"])
    assert proc.returncode != 0


@h.test_case(id="T2-18-4", tier=2, feature_id="#18", title="Missing input file on orient exits non-zero", requires=("forma_print",))
def t2_18_4() -> None:
    proc = h.run_forma_print(["orient", str(h.FIXTURES_DIR / "does_not_exist.forma")])
    assert proc.returncode != 0


@h.test_case(id="T2-18-5", tier=2, feature_id="#18", title="Oriented upside_down_t passes check without overhang issues", requires=("forma_print",))
def t2_18_5() -> None:
    with h.temp_dir() as td:
        out = pathlib.Path(td) / "t_orient.stl"
        h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--out", str(out)])
        _, rep = h.run_forma_print_json(["check", str(out), "--unit", "mm", "--printer", "bambu_x1c"])
        h.assert_check_clean(rep, "oriented upside_down_t")


# ===========================================================================
# #19: R6.7 Export .3mf & .step boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-19-1", tier=2, feature_id="#19", title="Multi-color mat() populates basematerials, colorgroup, filament_colour[], & 1-indexed extruders", requires=("forma_print",))
def t2_19_1() -> None:
    with h.temp_dir() as td:
        out = pathlib.Path(td) / "multi.3mf"
        h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "multi_color_ams.forma"), "--out", str(out)])
        info = h.inspect_3mf(out)
        assert info["colorgroups"] >= 1 or info["basematerials"] >= 1
        colors = info["project_settings"].get("filament_colour", [])
        assert isinstance(colors, list) and len(colors) >= 3, f"Expected >=3 filament colours, got {colors}"
        assert "extruder" in info["model_settings_xml"].lower()
        assert "extruder" in info["slic3r_pe_xml"].lower()


def _extract_3mf_world_vertices(path: pathlib.Path) -> list[tuple[float, float, float]]:
    ident = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0)

    def _parse_mat(attr: str | None) -> tuple[float, ...]:
        if not attr or not attr.strip():
            return ident
        vals = [float(x) for x in attr.strip().split()]
        assert len(vals) == 12, f"Invalid 3MF transform: {attr!r}"
        return tuple(vals)

    def _compose(loc: tuple[float, ...], par: tuple[float, ...]) -> tuple[float, ...]:
        a = ((loc[0], loc[1], loc[2], 0.0), (loc[3], loc[4], loc[5], 0.0), (loc[6], loc[7], loc[8], 0.0), (loc[9], loc[10], loc[11], 1.0))
        b = ((par[0], par[1], par[2], 0.0), (par[3], par[4], par[5], 0.0), (par[6], par[7], par[8], 0.0), (par[9], par[10], par[11], 1.0))
        return tuple(sum(a[r][k] * b[k][c] for k in range(4)) for r in range(4) for c in range(3))

    def _apply(m: tuple[float, ...], pt: tuple[float, float, float]) -> tuple[float, float, float]:
        x, y, z = pt
        return (x * m[0] + y * m[3] + z * m[6] + m[9], x * m[1] + y * m[4] + z * m[7] + m[10], x * m[2] + y * m[5] + z * m[8] + m[11])

    with zipfile.ZipFile(path, "r") as zf:
        root = ET.fromstring(zf.read("3D/3dmodel.model").decode("utf-8"))

    objs: dict[str, dict[str, list]] = {}
    items: list[tuple[str | None, tuple[float, ...]]] = []
    for el in root.iter():
        tag = el.tag.split("}")[-1]
        if tag == "object":
            oid = el.attrib.get("id")
            verts: list[tuple[float, float, float]] = []
            comps: list[tuple[str, tuple[float, ...]]] = []
            for sub in el.iter():
                stag = sub.tag.split("}")[-1]
                if stag == "vertex":
                    verts.append((float(sub.attrib["x"]), float(sub.attrib["y"]), float(sub.attrib["z"])))
                elif stag == "component" and sub.attrib.get("objectid"):
                    comps.append((sub.attrib["objectid"], _parse_mat(sub.attrib.get("transform"))))
            if oid:
                objs[oid] = {"v": verts, "c": comps}
        elif tag == "item":
            items.append((el.attrib.get("objectid"), _parse_mat(el.attrib.get("transform"))))

    pts: list[tuple[float, float, float]] = []

    def _walk(oid: str, mat: tuple[float, ...], seen: set[str]) -> None:
        if oid in seen or oid not in objs:
            return
        seen.add(oid)
        for v in objs[oid]["v"]:
            pts.append(_apply(mat, v))
        for cid, cmat in objs[oid]["c"]:
            _walk(cid, _compose(cmat, mat), seen)
        seen.remove(oid)

    for oid, imat in items:
        if oid:
            _walk(oid, imat, set())
    return pts


@h.test_case(id="T2-19-2", tier=2, feature_id="#19", title="export --orient rotates part onto wide base and z0=0 before writing .3mf", requires=("forma_print",))
def t2_19_2() -> None:
    def _xy_span_at_z(pts: list[tuple[float, float, float]], z_target: float) -> tuple[float, float]:
        sub = [(x, y) for x, y, z in pts if abs(z - z_target) < 0.5]
        assert len(sub) >= 3, f"Expected >=3 vertices near z={z_target}, got {len(sub)}"
        xs = [p[0] for p in sub]
        ys = [p[1] for p in sub]
        return (max(xs) - min(xs), max(ys) - min(ys))

    with h.temp_dir() as td:
        td_p = pathlib.Path(td)
        no_ori = td_p / "no_orient.3mf"
        ori = td_p / "oriented.3mf"
        _, no_json = h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--out", str(no_ori)])
        _, ori_json = h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--orient", "--out", str(ori)])
        assert no_json.get("oriented") is False, f"Expected oriented=false without --orient: {no_json}"
        assert ori_json.get("oriented") is True, f"Expected oriented=true with --orient: {ori_json}"

        info_ori = h.inspect_3mf(ori)
        assert abs(info_ori["bbox_min"][2]) < 0.5, f"Expected z0=0 in oriented .3mf, got {info_ori['bbox_min']}"

        no_pts = _extract_3mf_world_vertices(no_ori)
        ori_pts = _extract_3mf_world_vertices(ori)
        no_bed_span = _xy_span_at_z(no_pts, min(z for _, _, z in no_pts))
        ori_bed_span = _xy_span_at_z(ori_pts, min(z for _, _, z in ori_pts))
        ori_top_span = _xy_span_at_z(ori_pts, max(z for _, _, z in ori_pts))
        assert no_bed_span[0] * no_bed_span[1] < 500.0, f"Expected narrow unoriented bed footprint, got {no_bed_span}"
        assert ori_bed_span[0] >= 59.0 and ori_bed_span[1] >= 59.0, (
            f"Expected --orient to flip 60x60 flange to z=0 (no-op --orient?), got bed span {ori_bed_span}"
        )
        assert ori_top_span[0] * ori_top_span[1] < 500.0, f"Expected narrow stem at top after orient, got {ori_top_span}"

        # Also prove an elevated z0=0.05 m part drops to z0=0 mm under --orient
        elev_script = "part = box(0.02, 0.02, 0.02, z0=0.05)\n"
        elev_no = td_p / "elev_no.3mf"
        elev_ori = td_p / "elev_ori.3mf"
        h.run_forma_print_json(["export", "-", "--out", str(elev_no)], stdin_text=elev_script)
        _, elev_ori_json = h.run_forma_print_json(["export", "-", "--orient", "--out", str(elev_ori)], stdin_text=elev_script)
        assert elev_ori_json.get("oriented") is True
        assert h.inspect_3mf(elev_no)["bbox_min"][2] > 45.0
        assert abs(h.inspect_3mf(elev_ori)["bbox_min"][2]) < 0.5


@h.test_case(id="T2-19-3", tier=2, feature_id="#19", title="Unsupported --out foo.xyz exits non-zero", requires=("forma_print",))
def t2_19_3() -> None:
    with h.temp_dir() as td:
        proc = h.run_forma_print(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--out", str(pathlib.Path(td) / "bad.xyz")])
        assert proc.returncode != 0


@h.test_case(id="T2-19-4", tier=2, feature_id="#19", title="Missing or invalid syntax input on export exits non-zero", requires=("forma_print",))
def t2_19_4() -> None:
    with h.temp_dir() as td:
        p1 = h.run_forma_print(["export", str(h.FIXTURES_DIR / "missing_xyz.forma"), "--out", str(pathlib.Path(td) / "a.3mf")])
        p2 = h.run_forma_print(["export", str(h.FIXTURES_DIR / "invalid_syntax.forma"), "--out", str(pathlib.Path(td) / "b.3mf")])
        assert p1.returncode != 0 and p2.returncode != 0


@h.test_case(id="T2-19-5", tier=2, feature_id="#19", title="Deflate .3mf is significantly smaller than uncompressed entries", requires=("forma_print",))
def t2_19_5() -> None:
    with h.temp_dir() as td:
        out = pathlib.Path(td) / "hp.3mf"
        h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "high_poly.forma"), "--out", str(out)])
        info = h.inspect_3mf(out)
        assert info["total_compressed"] < info["total_uncompressed"] * 0.6


# ===========================================================================
# #20: R6.8 CLI & --mcp error boundaries (5 tests)
# ===========================================================================

@h.test_case(id="T2-20-1", tier=2, feature_id="#20", title="MCP malformed JSON-RPC returns -32700/-32600 and stays alive", requires=("forma_print",))
def t2_20_1() -> None:
    bin_path = h.require_forma_print()
    with h.McpClient([str(bin_path), "--mcp"]) as mcp:
        resp = mcp.send_raw("{not valid json", expect_response=True)
        assert resp.get("jsonrpc") == "2.0" and resp.get("id") is None, f"Unexpected envelope: {resp}"
        assert resp.get("error", {}).get("code") == -32700, f"Expected -32700, got {resp}"
        assert isinstance(resp["error"].get("message"), str) and resp["error"]["message"].strip()

        bad_req = mcp.send_raw("[1, 2, 3]", expect_response=True)
        assert bad_req.get("jsonrpc") == "2.0" and bad_req.get("id") is None, f"Unexpected envelope: {bad_req}"
        assert bad_req.get("error", {}).get("code") == -32600, f"Expected -32600, got {bad_req}"

        assert "protocolVersion" in mcp.initialize()
        assert mcp.ping() == {}


@h.test_case(id="T2-20-2", tier=2, feature_id="#20", title="MCP unknown method returns -32601 and invalid params -32602", requires=("forma_print",))
def t2_20_2() -> None:
    bin_path = h.require_forma_print()
    with h.McpClient([str(bin_path), "--mcp"]) as mcp:
        mcp.initialize()
        resp = mcp.request("nonexistent/method_xyz")
        assert resp.get("jsonrpc") == "2.0" and "result" not in resp, f"Unexpected response: {resp}"
        assert resp.get("error", {}).get("code") == -32601, f"Expected -32601, got {resp}"
        assert isinstance(resp["error"].get("message"), str) and resp["error"]["message"].strip()

        r_no_params = mcp.request("tools/call")
        assert r_no_params.get("error", {}).get("code") == -32602, f"Expected -32602, got {r_no_params}"
        r_empty_name = mcp.request("tools/call", {"name": " ", "arguments": {}})
        assert r_empty_name.get("error", {}).get("code") == -32602, f"Expected -32602, got {r_empty_name}"
        assert mcp.ping() == {}


@h.test_case(id="T2-20-3", tier=2, feature_id="#20", title="MCP notifications & blank lines produce zero output without breaking session", requires=("forma_print",))
def t2_20_3() -> None:
    bin_path = h.require_forma_print()
    with h.McpClient([str(bin_path), "--mcp"]) as mcp:
        mcp.initialize()
        assert mcp.notify("notifications/cancelled", {"requestId": 999}) is None
        assert mcp.notify("notifications/roots/list_changed") is None
        assert mcp.send_raw("   ", expect_response=False, wait=0.15) is None
        assert mcp.proc is not None and mcp.proc.poll() is None, "MCP server exited after notifications"
        assert mcp.ping() == {}


@h.test_case(id="T2-20-4", tier=2, feature_id="#20", title="MCP tool error boundaries return isError: true with diagnostics and recover", requires=("forma_print",))
def t2_20_4() -> None:
    bin_path = h.require_forma_print()
    with h.temp_dir() as td, h.McpClient([str(bin_path), "--mcp"]) as mcp:
        mcp.initialize()
        bad_xyz = str(pathlib.Path(td) / "bad.xyz")
        bad_calls = [
            ("unknown_tool_xyz", {}),
            ("print_check", {}),
            ("print_check", {"input": "box(0.02,0.02,0.02)", "printer": "nonexistent_printer_99"}),
            ("print_check", {"input": "box(0.02,0.02,0.02)", "scale": -1.0}),
            ("print_check", {"input": "box(0.02,0.02,0.02)", "unit": "km"}),
            ("print_export", {"input": "box(0.02,0.02,0.02)"}),
            ("print_export", {"input": "box(0.02,0.02,0.02)", "out": bad_xyz}),
            ("print_profiles", {"tech": "bogus_tech"}),
            ("print_check", ["not", "an", "object"]),
        ]
        for tool_name, args in bad_calls:
            res = mcp.tools_call(tool_name, args)  # type: ignore[arg-type]
            assert res.get("isError") is True, f"Expected isError=true for {tool_name}({args}), got {res}"
            content = res.get("content", [])
            assert isinstance(content, list) and len(content) >= 1 and content[0].get("type") == "text"
            assert str(content[0].get("text", "")).strip(), f"Empty error text for {tool_name}({args})"

        ok_res = mcp.tools_call("print_profiles", {"tech": "sls"})
        assert ok_res.get("isError") is False, f"Server failed to recover after tool errors: {ok_res}"


@h.test_case(id="T2-20-5", tier=2, feature_id="#20", title="forma-print CLI stdin (-) works for check/orient/export with exact dims and rejects empty stdin", requires=("forma_print",))
def t2_20_5() -> None:
    script = (h.FIXTURES_DIR / "box_meters.forma").read_text(encoding="utf-8")
    with h.temp_dir() as td:
        out_3mf = pathlib.Path(td) / "stdin.3mf"
        _, chk = h.run_forma_print_json(["check", "-", "--printer", "bambu_x1c"], stdin_text=script)
        h.assert_check_clean(chk, "stdin check")
        sz_chk = h.extract_bbox_size_mm(chk)
        assert sz_chk is not None and all(abs(a - b) < 0.5 for a, b in zip(sorted(sz_chk), [20.0, 30.0, 40.0])), (
            f"Expected 40x30x20 mm from stdin check, got {sz_chk}"
        )

        _, ori = h.run_forma_print_json(["orient", "-", "--printer", "bambu_x1c"], stdin_text=script)
        assert ori.get("rotated_from_input") is False and ori.get("report", {}).get("printable") is True

        h.run_forma_print_json(["export", "-", "--out", str(out_3mf)], stdin_text=script)
        info = h.inspect_3mf(out_3mf)
        assert info["unit"] == "millimeter"
        assert all(abs(a - b) < 0.5 for a, b in zip(sorted(info["size"]), [20.0, 30.0, 40.0])), (
            f"Expected 40x30x20 mm in stdin .3mf, got {info['size']}"
        )

        empty_proc = h.run_forma_print(["check", "-", "--json"], stdin_text="")
        assert empty_proc.returncode != 0 and "panicked at" not in empty_proc.stderr.lower()