A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
test(e2e): add opaque-box E2E test suite (Tiers 1-4) and fixtures
wrong-nebulac4d877535629
diff --git a/tests/e2e/fixtures/box_meters.forma b/tests/e2e/fixtures/box_meters.formanew file mode 100644index 0000000..f59afad--- /dev/null+++ b/tests/e2e/fixtures/box_meters.forma@@ -0,0 +1,2 @@+part = box(0.04, 0.03, 0.02, z0=0)+ | mat("pla_grey", color=(0.7, 0.7, 0.7))diff --git a/tests/e2e/fixtures/box_mm.forma b/tests/e2e/fixtures/box_mm.formanew file mode 100644index 0000000..c821919--- /dev/null+++ b/tests/e2e/fixtures/box_mm.forma@@ -0,0 +1,2 @@+part = box(40, 30, 20, z0=0)+ | mat("pla_grey", color=(0.7, 0.7, 0.7))diff --git a/tests/e2e/fixtures/bridge_vs_cantilever.forma b/tests/e2e/fixtures/bridge_vs_cantilever.formanew file mode 100644index 0000000..e93df94--- /dev/null+++ b/tests/e2e/fixtures/bridge_vs_cantilever.forma@@ -0,0 +1,4 @@+part = box(0.010, 0.020, 0.022, at=(-0.013, 0, 0), z0=0)+ | add(box(0.010, 0.020, 0.022, at=(0.013, 0, 0), z0=0))+ | add(box(0.062, 0.020, 0.004, at=(0.013, 0, 0), z0=0.021))+ | mat("pla_slate", color=(0.45, 0.5, 0.55))diff --git a/tests/e2e/fixtures/corrupt_truncated.stl b/tests/e2e/fixtures/corrupt_truncated.stlnew file mode 100644index 0000000..fe79a57Binary files /dev/null and b/tests/e2e/fixtures/corrupt_truncated.stl differdiff --git a/tests/e2e/fixtures/cube_40mm.stl b/tests/e2e/fixtures/cube_40mm.stlnew file mode 100644index 0000000..ed4cc46Binary files /dev/null and b/tests/e2e/fixtures/cube_40mm.stl differdiff --git a/tests/e2e/fixtures/cube_ascii_25mm.stl b/tests/e2e/fixtures/cube_ascii_25mm.stlnew file mode 100644index 0000000..579f2d5--- /dev/null+++ b/tests/e2e/fixtures/cube_ascii_25mm.stl@@ -0,0 +1,86 @@+solid cube_25mm+ facet normal 0.000000 0.000000 -1.000000+ outer loop+ vertex -12.500000 -12.500000 0.000000+ vertex -12.500000 12.500000 0.000000+ vertex 12.500000 12.500000 0.000000+ endloop+ endfacet+ facet normal 0.000000 0.000000 -1.000000+ outer loop+ vertex -12.500000 -12.500000 0.000000+ vertex 12.500000 12.500000 0.000000+ vertex 12.500000 -12.500000 0.000000+ endloop+ endfacet+ facet normal 0.000000 0.000000 1.000000+ outer loop+ vertex -12.500000 -12.500000 25.000000+ vertex 12.500000 -12.500000 25.000000+ vertex 12.500000 12.500000 25.000000+ endloop+ endfacet+ facet normal 0.000000 0.000000 1.000000+ outer loop+ vertex -12.500000 -12.500000 25.000000+ vertex 12.500000 12.500000 25.000000+ vertex -12.500000 12.500000 25.000000+ endloop+ endfacet+ facet normal 0.000000 -1.000000 0.000000+ outer loop+ vertex -12.500000 -12.500000 0.000000+ vertex 12.500000 -12.500000 0.000000+ vertex 12.500000 -12.500000 25.000000+ endloop+ endfacet+ facet normal 0.000000 -1.000000 0.000000+ outer loop+ vertex -12.500000 -12.500000 0.000000+ vertex 12.500000 -12.500000 25.000000+ vertex -12.500000 -12.500000 25.000000+ endloop+ endfacet+ facet normal 0.000000 1.000000 0.000000+ outer loop+ vertex -12.500000 12.500000 0.000000+ vertex -12.500000 12.500000 25.000000+ vertex 12.500000 12.500000 25.000000+ endloop+ endfacet+ facet normal 0.000000 1.000000 0.000000+ outer loop+ vertex -12.500000 12.500000 0.000000+ vertex 12.500000 12.500000 25.000000+ vertex 12.500000 12.500000 0.000000+ endloop+ endfacet+ facet normal -1.000000 0.000000 0.000000+ outer loop+ vertex -12.500000 -12.500000 0.000000+ vertex -12.500000 -12.500000 25.000000+ vertex -12.500000 12.500000 25.000000+ endloop+ endfacet+ facet normal -1.000000 0.000000 0.000000+ outer loop+ vertex -12.500000 -12.500000 0.000000+ vertex -12.500000 12.500000 25.000000+ vertex -12.500000 12.500000 0.000000+ endloop+ endfacet+ facet normal 1.000000 0.000000 0.000000+ outer loop+ vertex 12.500000 -12.500000 0.000000+ vertex 12.500000 12.500000 0.000000+ vertex 12.500000 12.500000 25.000000+ endloop+ endfacet+ facet normal 1.000000 0.000000 0.000000+ outer loop+ vertex 12.500000 -12.500000 0.000000+ vertex 12.500000 12.500000 25.000000+ vertex 12.500000 -12.500000 25.000000+ endloop+ endfacet+endsolid cube_25mmdiff --git a/tests/e2e/fixtures/empty.stl b/tests/e2e/fixtures/empty.stlnew file mode 100644index 0000000..e69de29diff --git a/tests/e2e/fixtures/floating_island.forma b/tests/e2e/fixtures/floating_island.formanew file mode 100644index 0000000..2e574a2--- /dev/null+++ b/tests/e2e/fixtures/floating_island.forma@@ -0,0 +1,3 @@+part = box(0.04, 0.04, 0.01, z0=0)+ | add(box(0.01, 0.01, 0.01, at=(0, 0, 0.03)))+ | mat("pla_yellow", color=(0.9, 0.8, 0.1))diff --git a/tests/e2e/fixtures/functional_bracket.forma b/tests/e2e/fixtures/functional_bracket.formanew file mode 100644index 0000000..473492a--- /dev/null+++ b/tests/e2e/fixtures/functional_bracket.forma@@ -0,0 +1,6 @@+bracket = box(0.060, 0.040, 0.006, z0=0)+ | add(box(0.060, 0.006, 0.030, at=(0, -0.017, 0), z0=0.004))+ | add(box(0.006, 0.024, 0.020, at=(0, -0.005, 0), z0=0.004))+ | cut(cyl(0.0022, 0.020, at=[(-0.022, 0.010, 0), (0.022, 0.010, 0), (-0.022, -0.004, 0), (0.022, -0.004, 0)]))+ | cut(cyl(0.005, 0.020, axis=y, at=(0, -0.017, 0.020)))+ | mat("petg_black", color=(0.15, 0.15, 0.17))diff --git a/tests/e2e/fixtures/h2d_dual_span.forma b/tests/e2e/fixtures/h2d_dual_span.formanew file mode 100644index 0000000..c4f31e2--- /dev/null+++ b/tests/e2e/fixtures/h2d_dual_span.forma@@ -0,0 +1,2 @@+part = box(0.320, 0.040, 0.020, z0=0)+ | mat("pla_teal", color=(0.15, 0.65, 0.65))diff --git a/tests/e2e/fixtures/high_poly.forma b/tests/e2e/fixtures/high_poly.formanew file mode 100644index 0000000..8c9b8d5--- /dev/null+++ b/tests/e2e/fixtures/high_poly.forma@@ -0,0 +1,4 @@+part = torus(0.030, 0.010)+ | subsurf(levels=2, crease=false)+ | align_z0(0)+ | mat("pla_silver", color=(0.78, 0.80, 0.84), metallic=0.3, roughness=0.4)diff --git a/tests/e2e/fixtures/hollow_closed.forma b/tests/e2e/fixtures/hollow_closed.formanew file mode 100644index 0000000..0185972--- /dev/null+++ b/tests/e2e/fixtures/hollow_closed.forma@@ -0,0 +1,3 @@+part = box(0.04, 0.04, 0.04, z0=0)+ | shell(0.003, open_top=false)+ | mat("resin_grey", color=(0.6, 0.62, 0.65))diff --git a/tests/e2e/fixtures/hollow_drained.forma b/tests/e2e/fixtures/hollow_drained.formanew file mode 100644index 0000000..eb116e9--- /dev/null+++ b/tests/e2e/fixtures/hollow_drained.forma@@ -0,0 +1,4 @@+part = (box(0.04, 0.04, 0.04, z0=0) | shell(0.003, open_top=false))+ | cut(cyl(0.0025, 0.012, at=(-0.01, 0, 0.002)))+ | cut(cyl(0.0025, 0.012, at=(0.01, 0, 0.002)))+ | mat("resin_grey", color=(0.6, 0.62, 0.65))diff --git a/tests/e2e/fixtures/invalid_syntax.forma b/tests/e2e/fixtures/invalid_syntax.formanew file mode 100644index 0000000..7618794--- /dev/null+++ b/tests/e2e/fixtures/invalid_syntax.forma@@ -0,0 +1 @@+part = box(0.04, 0.03, ) | unknown_op_xyz(123diff --git a/tests/e2e/fixtures/multi_color_ams.forma b/tests/e2e/fixtures/multi_color_ams.formanew file mode 100644index 0000000..08391e9--- /dev/null+++ b/tests/e2e/fixtures/multi_color_ams.forma@@ -0,0 +1,3 @@+combo = (box(0.03, 0.03, 0.01, z0=0) | mat("red_pla", color=(0.9, 0.1, 0.1)))+ | add(box(0.02, 0.02, 0.01, z0=0.009) | mat("blue_pla", color=(0.1, 0.2, 0.9)))+ | add(box(0.01, 0.01, 0.01, z0=0.018) | mat("white_pla", color=(0.95, 0.95, 0.95)))diff --git a/tests/e2e/fixtures/multi_color_enclosure.forma b/tests/e2e/fixtures/multi_color_enclosure.formanew file mode 100644index 0000000..154c0f4--- /dev/null+++ b/tests/e2e/fixtures/multi_color_enclosure.forma@@ -0,0 +1,8 @@+base = box(0.080, 0.050, 0.024, at=(-0.045, 0, 0), z0=0)+ | bevel(vertical, 0.004, segs=2)+ | shell(0.003, open_top=true)+ | mat("enclosure_dark", color=(0.18, 0.20, 0.24))++lid = box(0.080, 0.050, 0.005, at=(0.045, 0, 0), z0=0)+ | bevel(vertical, 0.004, segs=2)+ | mat("lid_orange", color=(0.92, 0.42, 0.12))diff --git a/tests/e2e/fixtures/multi_part_clear.forma b/tests/e2e/fixtures/multi_part_clear.formanew file mode 100644index 0000000..0d91902--- /dev/null+++ b/tests/e2e/fixtures/multi_part_clear.forma@@ -0,0 +1,4 @@+a = box(0.03, 0.03, 0.02, z0=0)+ | mat("part_a", color=(0.3, 0.7, 0.4))+b = box(0.03, 0.03, 0.02, at=(0.0303, 0, 0), z0=0)+ | mat("part_b", color=(0.4, 0.5, 0.8))diff --git a/tests/e2e/fixtures/multi_part_collision.forma b/tests/e2e/fixtures/multi_part_collision.formanew file mode 100644index 0000000..8829615--- /dev/null+++ b/tests/e2e/fixtures/multi_part_collision.forma@@ -0,0 +1,4 @@+a = box(0.03, 0.03, 0.02, z0=0)+ | mat("part_a", color=(0.8, 0.3, 0.3))+b = box(0.03, 0.03, 0.02, at=(0.025, 0, 0), z0=0)+ | mat("part_b", color=(0.3, 0.3, 0.8))diff --git a/tests/e2e/fixtures/non_manifold.stl b/tests/e2e/fixtures/non_manifold.stlnew file mode 100644index 0000000..8391260Binary files /dev/null and b/tests/e2e/fixtures/non_manifold.stl differdiff --git a/tests/e2e/fixtures/overhang_cone.forma b/tests/e2e/fixtures/overhang_cone.formanew file mode 100644index 0000000..d618f6b--- /dev/null+++ b/tests/e2e/fixtures/overhang_cone.forma@@ -0,0 +1,2 @@+part = cone(0.010, 0.040, 0.020, z0=0)+ | mat("pla_red", color=(0.85, 0.2, 0.2))diff --git a/tests/e2e/fixtures/oversized_part.forma b/tests/e2e/fixtures/oversized_part.formanew file mode 100644index 0000000..74fbbd2--- /dev/null+++ b/tests/e2e/fixtures/oversized_part.forma@@ -0,0 +1,2 @@+part = box(0.40, 0.40, 0.40, z0=0)+ | mat("pla_orange", color=(0.9, 0.45, 0.1))diff --git a/tests/e2e/fixtures/p1s_cutter_zone.forma b/tests/e2e/fixtures/p1s_cutter_zone.formanew file mode 100644index 0000000..08cb227--- /dev/null+++ b/tests/e2e/fixtures/p1s_cutter_zone.forma@@ -0,0 +1,2 @@+part = box(0.254, 0.254, 0.010, z0=0)+ | mat("pla_blue", color=(0.2, 0.4, 0.85))diff --git a/tests/e2e/fixtures/sls_batch.forma b/tests/e2e/fixtures/sls_batch.formanew file mode 100644index 0000000..83d4b18--- /dev/null+++ b/tests/e2e/fixtures/sls_batch.forma@@ -0,0 +1,10 @@+spacer_a = pipe(0.015, 0.008, 0.025, at=(-0.035, 0, 0), z0=0)+ | mat("pa12_nylon", color=(0.82, 0.82, 0.80))++spacer_b = box(0.030, 0.030, 0.020, at=(0, 0, 0), z0=0)+ | cut(cyl(0.006, 0.030))+ | mat("pa12_nylon", color=(0.82, 0.82, 0.80))++spacer_c = cyl(0.014, 0.025, segs=6, at=(0.035, 0, 0), z0=0)+ | cut(cyl(0.005, 0.035, at=(0.035, 0, 0)))+ | mat("pa12_nylon", color=(0.82, 0.82, 0.80))diff --git a/tests/e2e/fixtures/tall_unstable.forma b/tests/e2e/fixtures/tall_unstable.formanew file mode 100644index 0000000..8b8a7b7--- /dev/null+++ b/tests/e2e/fixtures/tall_unstable.forma@@ -0,0 +1,4 @@+part = box(0.01, 0.01, 0.005, z0=0)+ | add(box(0.006, 0.006, 0.08, z0=0.004))+ | add(box(0.06, 0.06, 0.02, at=(0.025, 0, 0.08)))+ | mat("pla_amber", color=(0.9, 0.6, 0.1))diff --git a/tests/e2e/fixtures/thin_wall.forma b/tests/e2e/fixtures/thin_wall.formanew file mode 100644index 0000000..e76d9be--- /dev/null+++ b/tests/e2e/fixtures/thin_wall.forma@@ -0,0 +1,3 @@+part = box(0.03, 0.03, 0.02, z0=0)+ | shell(0.0003, open_top=true)+ | mat("pla_purple", color=(0.6, 0.2, 0.8))diff --git a/tests/e2e/fixtures/unsupported_ceiling.forma b/tests/e2e/fixtures/unsupported_ceiling.formanew file mode 100644index 0000000..43912f6--- /dev/null+++ b/tests/e2e/fixtures/unsupported_ceiling.forma@@ -0,0 +1,3 @@+part = box(0.010, 0.030, 0.022, at=(-0.030, 0, 0), z0=0)+ | add(box(0.070, 0.030, 0.005, at=(0.0, 0, 0), z0=0.020))+ | mat("pla_coral", color=(0.9, 0.4, 0.35))diff --git a/tests/e2e/fixtures/upside_down_t.forma b/tests/e2e/fixtures/upside_down_t.formanew file mode 100644index 0000000..47344a1--- /dev/null+++ b/tests/e2e/fixtures/upside_down_t.forma@@ -0,0 +1,3 @@+part = box(0.012, 0.030, 0.030, z0=0)+ | add(box(0.060, 0.060, 0.008, z0=0.028))+ | mat("petg_blue", color=(0.2, 0.5, 0.8))diff --git a/tests/e2e/helpers.py b/tests/e2e/helpers.pynew file mode 100644index 0000000..5d32b25--- /dev/null+++ b/tests/e2e/helpers.py@@ -0,0 +1,1513 @@+"""Opaque-box E2E test helpers for forma-print (Python 3 stdlib + optional tiktoken)."""++from __future__ import annotations++import dataclasses+import json+import math+import os+import pathlib+import re+import select+import shutil+import struct+import subprocess+import tempfile+import time+import urllib.parse+import xml.etree.ElementTree as ET+import zipfile+import zlib+from typing import Any, Callable++REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]+E2E_DIR = REPO_ROOT / "tests" / "e2e"+FIXTURES_DIR = E2E_DIR / "fixtures"+RESEARCH_DIR = REPO_ROOT / "research"+CRATES_DIR = REPO_ROOT / "crates"++BASELINE_SIZES = {+ "forma": 1818160,+ "forma-mcp": 1775040,+ "wasm": 786102,+}++EXPECTED_PRINTER_VOLUMES_MM: dict[str, tuple[float, float, float]] = {+ "bambu_a1_mini": (180.0, 180.0, 180.0),+ "bambu_a1": (256.0, 256.0, 256.0),+ "bambu_p1s": (256.0, 256.0, 256.0),+ "bambu_x1c": (256.0, 256.0, 256.0),+ "bambu_h2d_single": (325.0, 320.0, 325.0),+ "bambu_h2d_dual": (300.0, 320.0, 320.0),+ "prusa_mk4s": (250.0, 210.0, 220.0),+ "prusa_core_one": (250.0, 220.0, 270.0),+ "prusa_xl": (360.0, 360.0, 360.0),+ "voron_24_250": (250.0, 250.0, 250.0),+ "voron_24_300": (300.0, 300.0, 300.0),+ "voron_24_350": (350.0, 350.0, 350.0),+ "creality_k1c": (220.0, 220.0, 250.0),+ "creality_k2_plus": (350.0, 350.0, 350.0),+ "elegoo_mars_5_ultra": (153.36, 77.76, 165.0),+ "elegoo_saturn_4_ultra": (218.88, 122.88, 220.0),+ "formlabs_form_4": (200.0, 125.0, 210.0),+ "formlabs_fuse_1p": (165.0, 165.0, 300.0),+}++EXPECTED_PRINTER_TECH: dict[str, str] = {+ "bambu_a1_mini": "fdm",+ "bambu_a1": "fdm",+ "bambu_p1s": "fdm",+ "bambu_x1c": "fdm",+ "bambu_h2d_single": "fdm",+ "bambu_h2d_dual": "fdm",+ "prusa_mk4s": "fdm",+ "prusa_core_one": "fdm",+ "prusa_xl": "fdm",+ "voron_24_250": "fdm",+ "voron_24_300": "fdm",+ "voron_24_350": "fdm",+ "creality_k1c": "fdm",+ "creality_k2_plus": "fdm",+ "elegoo_mars_5_ultra": "sla",+ "elegoo_saturn_4_ultra": "sla",+ "formlabs_form_4": "sla",+ "formlabs_fuse_1p": "sls",+}++EXPECTED_MATERIALS: tuple[str, ...] = (+ "PLA",+ "PETG",+ "ABS",+ "ASA",+ "TPU",+ "PA_CF",+ "RESIN_STD",+ "RESIN_TOUGH",+ "SLS_PA12",+)++EXPECTED_HEAT_INSERTS: tuple[str, ...] = (+ "M2",+ "M2.5",+ "M3_voron",+ "M3_std",+ "M4",+ "M5",+)++_FORMA_PRINT_BUILT: pathlib.Path | None = None+++class SkipNotBuilt(Exception):+ """Raised when an optional artifact (forma-print or research/) is not built yet."""++[email protected](frozen=True)+class TestCase:+ id: str+ tier: int+ feature_id: str+ title: str+ requires: tuple[str, ...]+ fn: Callable[[], None]+++def test_case(+ *,+ id: str,+ tier: int,+ feature_id: str,+ title: str,+ requires: tuple[str, ...],+) -> Callable[[Callable[[], None]], Callable[[], None]]:+ """Decorator attaching structured requirement metadata to a test function."""++ def decorator(fn: Callable[[], None]) -> Callable[[], None]:+ fn._e2e_meta = TestCase( # type: ignore[attr-defined]+ id=id,+ tier=tier,+ feature_id=feature_id,+ title=title,+ requires=requires,+ fn=fn,+ )+ return fn++ return decorator+++def collect_tests_from_module(mod: Any) -> list[TestCase]:+ cases: list[TestCase] = []+ for attr in dir(mod):+ obj = getattr(mod, attr)+ meta = getattr(obj, "_e2e_meta", None)+ if isinstance(meta, TestCase):+ cases.append(meta)+ cases.sort(key=lambda c: (c.tier, c.id))+ return cases+++def cargo_env(extra: dict[str, str] | None = None) -> dict[str, str]:+ env = os.environ.copy()+ if os.uname().sysname == "Darwin" and "DEVELOPER_DIR" not in env:+ clt = "/Library/Developer/CommandLineTools"+ if pathlib.Path(clt).exists():+ env["DEVELOPER_DIR"] = clt+ if extra:+ env.update(extra)+ return env+++def run_cmd(+ args: list[str],+ *,+ cwd: pathlib.Path = REPO_ROOT,+ stdin_text: str | None = None,+ timeout: float = 60.0,+ env: dict[str, str] | None = None,+) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ [str(a) for a in args],+ cwd=str(cwd),+ input=stdin_text,+ text=True,+ capture_output=True,+ timeout=timeout,+ env=cargo_env(env),+ )+++def find_forma_bin() -> pathlib.Path:+ for candidate in (+ os.environ.get("FORMA_BIN"),+ str(REPO_ROOT / "target" / "release" / "forma"),+ str(REPO_ROOT / "target" / "debug" / "forma"),+ ):+ if candidate and pathlib.Path(candidate).is_file():+ return pathlib.Path(candidate)+ raise FileNotFoundError("Core binary target/release/forma not found")+++def find_forma_mcp_bin() -> pathlib.Path:+ for candidate in (+ os.environ.get("FORMA_MCP_BIN"),+ str(REPO_ROOT / "target" / "release" / "forma-mcp"),+ str(REPO_ROOT / "target" / "debug" / "forma-mcp"),+ ):+ if candidate and pathlib.Path(candidate).is_file():+ return pathlib.Path(candidate)+ raise FileNotFoundError("Core binary target/release/forma-mcp not found")+++def find_forma_print_bin() -> pathlib.Path:+ global _FORMA_PRINT_BUILT+ override = os.environ.get("FORMA_PRINT_BIN")+ if override:+ p = pathlib.Path(override)+ if p.is_file():+ return p+ raise SkipNotBuilt(f"FORMA_PRINT_BIN points to missing file: {p}")++ if _FORMA_PRINT_BUILT is not None and _FORMA_PRINT_BUILT.is_file():+ return _FORMA_PRINT_BUILT++ release_bin = REPO_ROOT / "target" / "release" / "forma-print"+ if release_bin.is_file():+ _FORMA_PRINT_BUILT = release_bin+ return release_bin++ crate_toml = CRATES_DIR / "forma-print" / "Cargo.toml"+ if crate_toml.is_file():+ proc = run_cmd(+ [+ "cargo",+ "build",+ "--manifest-path",+ str(REPO_ROOT / "Cargo.toml"),+ "--release",+ "-p",+ "forma-print",+ ],+ timeout=300.0,+ )+ if proc.returncode != 0:+ raise AssertionError(+ f"Failed to build crates/forma-print:\n{proc.stdout}\n{proc.stderr}"+ )+ if release_bin.is_file():+ _FORMA_PRINT_BUILT = release_bin+ return release_bin++ debug_bin = REPO_ROOT / "target" / "debug" / "forma-print"+ if debug_bin.is_file():+ _FORMA_PRINT_BUILT = debug_bin+ return debug_bin++ raise SkipNotBuilt("forma-print crate/binary not yet created or built")+++def require_forma_print() -> pathlib.Path:+ return find_forma_print_bin()+++def require_research_file(rel_path: str) -> pathlib.Path:+ p = RESEARCH_DIR / rel_path+ if not p.exists():+ raise SkipNotBuilt(f"research artifact not yet created: research/{rel_path}")+ return p+++def check_requirements_available(requires: tuple[str, ...]) -> tuple[bool, str]:+ for req in requires:+ if req == "core_baseline":+ continue+ if req == "forma_print":+ try:+ find_forma_print_bin()+ except SkipNotBuilt as exc:+ return False, str(exc)+ elif req == "research":+ if not RESEARCH_DIR.is_dir():+ return False, "research/ directory does not exist yet"+ marker_files = (+ "corpus/software.jsonl",+ "corpus/manufacturers.jsonl",+ "corpus/papers.jsonl",+ )+ missing = [m for m in marker_files if not (RESEARCH_DIR / m).is_file()]+ if len(missing) == len(marker_files):+ return False, "research/ corpus artifacts not yet created"+ else:+ return False, f"unknown requirement: {req}"+ return True, ""+++def run_forma(+ args: list[str],+ *,+ stdin_text: str | None = None,+ timeout: float = 30.0,+) -> subprocess.CompletedProcess[str]:+ return run_cmd([str(find_forma_bin()), *args], stdin_text=stdin_text, timeout=timeout)+++def run_forma_print(+ args: list[str],+ *,+ stdin_text: str | None = None,+ timeout: float = 60.0,+) -> subprocess.CompletedProcess[str]:+ bin_path = require_forma_print()+ return run_cmd([str(bin_path), *args], stdin_text=stdin_text, timeout=timeout)+++def run_forma_print_json(+ args: list[str],+ *,+ stdin_text: str | None = None,+ timeout: float = 60.0,+ allow_nonzero: bool = False,+) -> tuple[subprocess.CompletedProcess[str], Any]:+ full_args = list(args)+ if "--json" not in full_args:+ full_args.append("--json")+ proc = run_forma_print(full_args, stdin_text=stdin_text, timeout=timeout)+ if not allow_nonzero and proc.returncode != 0:+ raise AssertionError(+ f"forma-print {' '.join(full_args)} exited {proc.returncode}:\n"+ f"STDOUT: {proc.stdout}\nSTDERR: {proc.stderr}"+ )+ raw = proc.stdout.strip()+ if not raw:+ raise AssertionError(+ f"Expected JSON stdout from forma-print {' '.join(full_args)}, got empty.\n"+ f"rc={proc.returncode} stderr={proc.stderr}"+ )+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise AssertionError(+ f"Invalid JSON from forma-print {' '.join(full_args)}: {exc}\nRAW:\n{raw}"+ ) from exc+ return proc, parsed+++def verify_forma_fixture(path: pathlib.Path, *, expect_ok: bool = True) -> dict[str, Any]:+ proc = run_forma(["eval", "--strict", "--json"], stdin_text=path.read_text(encoding="utf-8"))+ if expect_ok:+ if proc.returncode != 0:+ raise AssertionError(+ f"Valid fixture {path.name} failed forma eval --strict (rc={proc.returncode}): "+ f"{proc.stdout} {proc.stderr}"+ )+ data = json.loads(proc.stdout)+ if not data.get("ok"):+ raise AssertionError(f"Fixture {path.name} returned ok=false: {data}")+ parts = data.get("parts", {})+ if not isinstance(parts, dict) or not parts:+ raise AssertionError(f"Fixture {path.name} produced no parts: {data}")+ for pname, pinfo in parts.items():+ if not pinfo.get("watertight"):+ raise AssertionError(f"Fixture {path.name} part {pname} not watertight: {pinfo}")+ if pinfo.get("non_manifold_edges", -1) != 0:+ raise AssertionError(+ f"Fixture {path.name} part {pname} has non-manifold edges: {pinfo}"+ )+ return data+ else:+ if proc.returncode == 0:+ raise AssertionError(f"Invalid fixture {path.name} unexpectedly passed forma eval!")+ return {"ok": False, "returncode": proc.returncode, "output": proc.stdout or proc.stderr}+++def count_o200k_tokens(obj_or_text: Any) -> int:+ try:+ import tiktoken # type: ignore[import-not-found]+ except ImportError as exc:+ raise RuntimeError(+ "tiktoken is required for exact o200k_base token assertions"+ ) from exc+ enc = tiktoken.get_encoding("o200k_base")+ text = (+ obj_or_text+ if isinstance(obj_or_text, str)+ else json.dumps(obj_or_text, separators=(",", ":"))+ )+ return len(enc.encode(text))+++class McpClient:+ """Line-delimited JSON-RPC 2.0 stdio client for forma-mcp and forma-print --mcp."""++ def __init__(self, cmd: list[str], *, cwd: pathlib.Path = REPO_ROOT, timeout: float = 15.0):+ self.cmd = [str(c) for c in cmd]+ self.cwd = cwd+ self.timeout = timeout+ self.proc: subprocess.Popen[str] | None = None+ self._next_id = 1++ def __enter__(self) -> "McpClient":+ self.proc = subprocess.Popen(+ self.cmd,+ cwd=str(self.cwd),+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ bufsize=1,+ env=cargo_env(),+ )+ return self++ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:+ if self.proc is not None:+ try:+ if self.proc.stdin:+ self.proc.stdin.close()+ except OSError:+ pass+ try:+ self.proc.wait(timeout=3.0)+ except subprocess.TimeoutExpired:+ self.proc.kill()+ self.proc.wait(timeout=3.0)++ def _read_line(self, timeout: float | None = None) -> str | None:+ assert self.proc and self.proc.stdout+ wait = self.timeout if timeout is None else timeout+ fd = self.proc.stdout.fileno()+ ready, _, _ = select.select([fd], [], [], wait)+ if not ready:+ return None+ line = self.proc.stdout.readline()+ if line == "":+ return None+ return line.rstrip("\r\n")++ def send_raw(self, raw_line: str, *, expect_response: bool = True, wait: float | None = None) -> Any:+ assert self.proc and self.proc.stdin+ self.proc.stdin.write(raw_line + "\n")+ self.proc.stdin.flush()+ if not expect_response:+ line = self._read_line(timeout=wait if wait is not None else 0.25)+ return line+ line = self._read_line(timeout=wait)+ if line is None:+ stderr_rem = ""+ if self.proc.poll() is not None and self.proc.stderr:+ stderr_rem = self.proc.stderr.read()+ raise TimeoutError(+ f"Timed out waiting for JSON-RPC response from {self.cmd}. stderr={stderr_rem}"+ )+ return json.loads(line)++ def request(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:+ req_id = self._next_id+ self._next_id += 1+ payload: dict[str, Any] = {"jsonrpc": "2.0", "id": req_id, "method": method}+ if params is not None:+ payload["params"] = params+ resp = self.send_raw(json.dumps(payload, separators=(",", ":")), expect_response=True)+ if resp.get("id") != req_id:+ raise AssertionError(f"Mismatched JSON-RPC id: expected {req_id}, got {resp}")+ return resp++ def notify(self, method: str, params: dict[str, Any] | None = None) -> str | None:+ payload: dict[str, Any] = {"jsonrpc": "2.0", "method": method}+ if params is not None:+ payload["params"] = params+ return self.send_raw(+ json.dumps(payload, separators=(",", ":")), expect_response=False, wait=0.25+ )++ def initialize(self) -> dict[str, Any]:+ resp = self.request(+ "initialize",+ {+ "protocolVersion": "2024-11-05",+ "capabilities": {},+ "clientInfo": {"name": "forma-print-e2e", "version": "1.0.0"},+ },+ )+ if "error" in resp:+ raise AssertionError(f"MCP initialize failed: {resp}")+ self.notify("notifications/initialized")+ return resp["result"]++ def ping(self) -> dict[str, Any]:+ resp = self.request("ping")+ if "error" in resp:+ raise AssertionError(f"MCP ping failed: {resp}")+ return resp["result"]++ def tools_list(self) -> list[dict[str, Any]]:+ resp = self.request("tools/list")+ if "error" in resp:+ raise AssertionError(f"MCP tools/list failed: {resp}")+ tools = resp.get("result", {}).get("tools")+ if not isinstance(tools, list):+ raise AssertionError(f"tools/list missing tools array: {resp}")+ return tools++ def tools_call(self, name: str, arguments: dict[str, Any] | None = None) -> dict[str, Any]:+ resp = self.request("tools/call", {"name": name, "arguments": arguments or {}})+ if "error" in resp:+ raise AssertionError(f"MCP tools/call {name} returned protocol error: {resp}")+ return resp["result"]+++def build_mcp_tool_args(+ tools: list[dict[str, Any]],+ tool_name: str,+ *,+ input_path: str | None = None,+ out_path: str | None = None,+ printer: str | None = None,+ material: str | None = None,+ orient: bool | None = None,+ tech: str | None = None,+ unit: str | None = None,+) -> dict[str, Any]:+ """Build tools/call arguments matching the tool's declared inputSchema.properties."""+ tool_def = next((t for t in tools if isinstance(t, dict) and t.get("name") == tool_name), None)+ props: dict[str, Any] = {}+ if isinstance(tool_def, dict):+ schema = tool_def.get("inputSchema") or {}+ if isinstance(schema, dict) and isinstance(schema.get("properties"), dict):+ props = schema["properties"]++ args: dict[str, Any] = {}++ def _pick(candidates: tuple[str, ...], value: Any, default_key: str, *, required_if_missing: bool = False) -> None:+ if value is None:+ return+ if props:+ for cand in candidates:+ if cand in props:+ args[cand] = value+ return+ if required_if_missing:+ args[default_key] = value+ else:+ args[default_key] = value++ _pick(+ ("input", "path", "file", "file_path", "input_path", "model", "source", "script"),+ input_path,+ "input",+ required_if_missing=True,+ )+ _pick(+ ("out", "output", "output_path", "out_path", "dest", "destination", "target"),+ out_path,+ "out",+ required_if_missing=True,+ )+ _pick(("printer", "printer_id", "profile"), printer, "printer")+ _pick(("material", "material_id", "filament"), material, "material")+ _pick(("orient", "auto_orient"), orient, "orient")+ _pick(("tech", "technology"), tech, "tech")+ _pick(("unit", "units"), unit, "unit")+ return args+++def _paeth_predictor(a: int, b: int, c: int) -> int:+ p = a + b - c+ pa = abs(p - a)+ pb = abs(p - b)+ pc = abs(p - c)+ if pa <= pb and pa <= pc:+ return a+ if pb <= pc:+ return b+ return c+++def inspect_png_bytes(data: bytes) -> dict[str, Any]:+ sig = b"\x89PNG\r\n\x1a\n"+ if not data.startswith(sig):+ raise AssertionError(f"Invalid PNG signature: {data[:16]!r}")+ pos = 8+ chunks: list[tuple[str, bytes]] = []+ ihdr: dict[str, int] | None = None+ idat_parts: list[bytes] = []+ saw_iend = False++ while pos < len(data):+ if pos + 8 > len(data):+ raise AssertionError("Truncated PNG chunk header")+ length, ctype_b = struct.unpack(">I4s", data[pos : pos + 8])+ pos += 8+ if pos + length + 4 > len(data):+ raise AssertionError(f"Truncated PNG chunk {ctype_b!r}")+ payload = data[pos : pos + length]+ crc_actual = struct.unpack(">I", data[pos + length : pos + length + 4])[0]+ crc_expected = zlib.crc32(ctype_b + payload) & 0xFFFFFFFF+ if crc_actual != crc_expected:+ raise AssertionError(+ f"PNG CRC mismatch in chunk {ctype_b!r}: {crc_actual:#x} != {crc_expected:#x}"+ )+ pos += length + 4+ ctype = ctype_b.decode("ascii", errors="replace")+ chunks.append((ctype, payload))+ if ctype == "IHDR":+ if length != 13:+ raise AssertionError(f"Invalid IHDR length: {length}")+ w, h, bd, ct, comp, filt, interlace = struct.unpack(">IIBBBBB", payload)+ ihdr = {+ "width": w,+ "height": h,+ "bit_depth": bd,+ "color_type": ct,+ "compression": comp,+ "filter": filt,+ "interlace": interlace,+ }+ elif ctype == "IDAT":+ idat_parts.append(payload)+ elif ctype == "IEND":+ saw_iend = True+ break++ if ihdr is None:+ raise AssertionError("PNG missing IHDR")+ if not idat_parts:+ raise AssertionError("PNG missing IDAT")+ if not saw_iend:+ raise AssertionError("PNG missing IEND")++ raw = zlib.decompress(b"".join(idat_parts))+ distinct_colors: set[tuple[int, ...]] = set()+ w = ihdr["width"]+ h = ihdr["height"]+ bd = ihdr["bit_depth"]+ ct = ihdr["color_type"]+ bpp_map = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}+ if w <= 0 or h <= 0:+ raise AssertionError(f"Invalid PNG dimensions: {w}x{h}")+ if ihdr["compression"] != 0 or ihdr["filter"] != 0:+ raise AssertionError(+ f"Unsupported PNG compression/filter header: {ihdr['compression']}/{ihdr['filter']}"+ )+ if bd != 8 or ct not in bpp_map or ihdr["interlace"] != 0:+ raise AssertionError(+ f"PNG pixel decoding requires 8-bit non-interlaced image, got "+ f"bit_depth={bd}, color_type={ct}, interlace={ihdr['interlace']}"+ )++ bpp = bpp_map[ct]+ stride = w * bpp+ expected_len = h * (1 + stride)+ if len(raw) != expected_len:+ raise AssertionError(+ f"PNG decompressed pixel length {len(raw)} != expected {expected_len} "+ f"for {w}x{h} ct={ct}"+ )++ prev = bytearray(stride)+ idx = 0+ step_y = max(1, h // 64)+ step_x = max(1, w // 64)+ for y in range(h):+ ftype = raw[idx]+ if ftype not in (0, 1, 2, 3, 4):+ raise AssertionError(f"Invalid PNG scanline filter type {ftype} at row {y}")+ idx += 1+ scan = bytearray(raw[idx : idx + stride])+ idx += stride+ if ftype == 1:+ for i in range(bpp, stride):+ scan[i] = (scan[i] + scan[i - bpp]) & 0xFF+ elif ftype == 2:+ for i in range(stride):+ scan[i] = (scan[i] + prev[i]) & 0xFF+ elif ftype == 3:+ for i in range(stride):+ left = scan[i - bpp] if i >= bpp else 0+ scan[i] = (scan[i] + ((left + prev[i]) >> 1)) & 0xFF+ elif ftype == 4:+ for i in range(stride):+ left = scan[i - bpp] if i >= bpp else 0+ up = prev[i]+ ul = prev[i - bpp] if i >= bpp else 0+ scan[i] = (scan[i] + _paeth_predictor(left, up, ul)) & 0xFF+ if y % step_y == 0 and len(distinct_colors) < 256:+ for x in range(0, w, step_x):+ px = tuple(scan[x * bpp : x * bpp + min(3, bpp)])+ distinct_colors.add(px)+ if len(distinct_colors) >= 256:+ break+ prev = scan++ return {+ "width": w,+ "height": h,+ "bit_depth": bd,+ "color_type": ct,+ "chunk_types": [c[0] for c in chunks],+ "idat_bytes": sum(len(p) for p in idat_parts),+ "distinct_colors_sampled": len(distinct_colors),+ }+++def inspect_png(path: pathlib.Path) -> dict[str, Any]:+ if not path.is_file():+ raise AssertionError(f"Missing PNG file: {path}")+ return inspect_png_bytes(path.read_bytes())+++_IDENTITY_3MF_MAT: tuple[float, ...] = (+ 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_3mf_transform(attr: str | None) -> tuple[float, ...]:+ if not attr or not attr.strip():+ return _IDENTITY_3MF_MAT+ parts = attr.strip().split()+ if len(parts) != 12:+ raise AssertionError(f"Invalid 3MF transform matrix (expected 12 floats): {attr!r}")+ return tuple(float(x) for x in parts)+++def _compose_3mf_mat(local_m: tuple[float, ...], parent_m: tuple[float, ...]) -> tuple[float, ...]:+ """Compose two 4x3 row-vector 3MF affine matrices: p' = (p * local_m) * parent_m."""+ a = (+ (local_m[0], local_m[1], local_m[2], 0.0),+ (local_m[3], local_m[4], local_m[5], 0.0),+ (local_m[6], local_m[7], local_m[8], 0.0),+ (local_m[9], local_m[10], local_m[11], 1.0),+ )+ b = (+ (parent_m[0], parent_m[1], parent_m[2], 0.0),+ (parent_m[3], parent_m[4], parent_m[5], 0.0),+ (parent_m[6], parent_m[7], parent_m[8], 0.0),+ (parent_m[9], parent_m[10], parent_m[11], 1.0),+ )+ out: list[float] = []+ for r in range(4):+ for c in range(3):+ out.append(sum(a[r][k] * b[k][c] for k in range(4)))+ return tuple(out)+++def _apply_3mf_mat(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],+ )+++def inspect_3mf(path: pathlib.Path) -> dict[str, Any]:+ if not path.is_file() or path.stat().st_size == 0:+ raise AssertionError(f"Missing or empty .3mf archive: {path}")++ with zipfile.ZipFile(path, "r") as zf:+ bad = zf.testzip()+ if bad is not None:+ raise AssertionError(f"Corrupt ZIP entry in {path}: {bad}")+ infos = {info.filename: info for info in zf.infolist()}+ required = [+ "[Content_Types].xml",+ "_rels/.rels",+ "3D/3dmodel.model",+ "Metadata/model_settings.config",+ "Metadata/project_settings.config",+ "Metadata/plate_1.json",+ "Metadata/Slic3r_PE_model.config",+ "Metadata/plate_1.png",+ ]+ missing = [r for r in required if r not in infos]+ if missing:+ raise AssertionError(f".3mf {path} missing required entries: {missing}")++ non_deflate = [+ name+ for name, info in infos.items()+ if not info.is_dir() and info.compress_type != zipfile.ZIP_DEFLATED+ ]+ if non_deflate:+ raise AssertionError(+ f".3mf entries not RFC-1951 Deflate compressed (type=8): {non_deflate}"+ )++ content_types_xml = zf.read("[Content_Types].xml").decode("utf-8")+ ET.fromstring(content_types_xml)++ rels_xml = zf.read("_rels/.rels").decode("utf-8")+ rels_root = ET.fromstring(rels_xml)+ rel_targets = [+ el.attrib.get("Target", "")+ for el in rels_root.iter()+ if el.tag.endswith("Relationship")+ ]+ if not any("3dmodel.model" in t for t in rel_targets):+ raise AssertionError(f"_rels/.rels missing 3dmodel.model target: {rel_targets}")+ if not any("plate_1.png" in t for t in rel_targets):+ raise AssertionError(f"_rels/.rels missing plate_1.png target: {rel_targets}")++ model_xml_text = zf.read("3D/3dmodel.model").decode("utf-8")+ model_root = ET.fromstring(model_xml_text)+ unit = model_root.attrib.get("unit")+ if unit != "millimeter":+ raise AssertionError(f"Expected 3D/3dmodel.model unit='millimeter', got {unit!r}")++ xs: list[float] = []+ ys: list[float] = []+ zs: list[float] = []+ objects_count = 0+ triangles_count = 0+ basematerials_count = 0+ colorgroups_count = 0+ build_items_count = 0+ objects_by_id: dict[str, dict[str, Any]] = {}+ build_items: list[tuple[str | None, tuple[float, ...]]] = []++ for el in model_root.iter():+ tag_local = el.tag.split("}")[-1]+ if tag_local == "vertex":+ xs.append(float(el.attrib["x"]))+ ys.append(float(el.attrib["y"]))+ zs.append(float(el.attrib["z"]))+ elif tag_local == "triangle":+ triangles_count += 1+ elif tag_local == "object":+ objects_count += 1+ oid = el.attrib.get("id")+ obj_verts: list[tuple[float, float, float]] = []+ obj_comps: list[tuple[str, tuple[float, ...]]] = []+ for sub in el.iter():+ sub_tag = sub.tag.split("}")[-1]+ if sub_tag == "vertex":+ obj_verts.append((float(sub.attrib["x"]), float(sub.attrib["y"]), float(sub.attrib["z"])))+ elif sub_tag == "component":+ c_oid = sub.attrib.get("objectid")+ if c_oid:+ obj_comps.append((c_oid, _parse_3mf_transform(sub.attrib.get("transform"))))+ if oid:+ objects_by_id[oid] = {"vertices": obj_verts, "components": obj_comps}+ elif tag_local == "basematerials":+ basematerials_count += 1+ elif tag_local == "colorgroup":+ colorgroups_count += 1+ elif tag_local == "item":+ build_items_count += 1+ build_items.append((el.attrib.get("objectid"), _parse_3mf_transform(el.attrib.get("transform"))))++ if not xs or triangles_count == 0 or objects_count == 0 or build_items_count == 0:+ raise AssertionError(+ f"3D/3dmodel.model incomplete geometry: verts={len(xs)}, tris={triangles_count}, "+ f"objs={objects_count}, items={build_items_count}"+ )++ def _collect_transformed_pts(+ oid: str,+ mat: tuple[float, ...],+ seen: set[str],+ out_pts: list[tuple[float, float, float]],+ ) -> None:+ if oid in seen or oid not in objects_by_id:+ return+ seen.add(oid)+ obj_data = objects_by_id[oid]+ for pt in obj_data["vertices"]:+ out_pts.append(_apply_3mf_mat(mat, pt))+ for child_oid, comp_mat in obj_data["components"]:+ _collect_transformed_pts(+ child_oid,+ _compose_3mf_mat(comp_mat, mat),+ seen,+ out_pts,+ )+ seen.remove(oid)++ world_pts: list[tuple[float, float, float]] = []+ for item_oid, item_mat in build_items:+ if item_oid and item_oid in objects_by_id:+ _collect_transformed_pts(item_oid, item_mat, set(), world_pts)++ if world_pts:+ wxs = [p[0] for p in world_pts]+ wys = [p[1] for p in world_pts]+ wzs = [p[2] for p in world_pts]+ else:+ wxs, wys, wzs = xs, ys, zs++ bbox_min = [min(wxs), min(wys), min(wzs)]+ bbox_max = [max(wxs), max(wys), max(wzs)]+ size = [bbox_max[i] - bbox_min[i] for i in range(3)]++ model_settings_raw = zf.read("Metadata/model_settings.config").decode("utf-8")+ ET.fromstring(model_settings_raw)++ project_settings = json.loads(zf.read("Metadata/project_settings.config").decode("utf-8"))+ plate_1 = json.loads(zf.read("Metadata/plate_1.json").decode("utf-8"))++ slic3r_pe_raw = zf.read("Metadata/Slic3r_PE_model.config").decode("utf-8")+ ET.fromstring(slic3r_pe_raw)++ thumb = inspect_png_bytes(zf.read("Metadata/plate_1.png"))+ if thumb["width"] != 256 or thumb["height"] != 256:+ raise AssertionError(+ f"Expected Metadata/plate_1.png 256x256, got {thumb['width']}x{thumb['height']}"+ )+ if thumb["distinct_colors_sampled"] <= 1:+ raise AssertionError(+ f"Expected non-blank Metadata/plate_1.png (>1 distinct color), got {thumb['distinct_colors_sampled']}"+ )++ total_compressed = sum(i.compress_size for i in infos.values())+ total_uncompressed = sum(i.file_size for i in infos.values())++ return {+ "entries": sorted(infos.keys()),+ "unit": unit,+ "vertices": len(xs),+ "triangles": triangles_count,+ "objects": objects_count,+ "basematerials": basematerials_count,+ "colorgroups": colorgroups_count,+ "build_items": build_items_count,+ "bbox_min": bbox_min,+ "bbox_max": bbox_max,+ "size": size,+ "model_settings_xml": model_settings_raw,+ "project_settings": project_settings,+ "plate_1": plate_1,+ "slic3r_pe_xml": slic3r_pe_raw,+ "thumbnail": thumb,+ "total_compressed": total_compressed,+ "total_uncompressed": total_uncompressed,+ }+++def inspect_step(path: pathlib.Path) -> dict[str, Any]:+ if not path.is_file() or path.stat().st_size == 0:+ raise AssertionError(f"Missing or empty .step file: {path}")+ text = path.read_text(encoding="utf-8", errors="replace").strip()+ if not text.startswith("ISO-10303-21;"):+ raise AssertionError("STEP file missing ISO-10303-21; header")+ if not text.endswith("END-ISO-10303-21;"):+ raise AssertionError("STEP file missing END-ISO-10303-21; footer")+ if "SI_UNIT(.MILLI.,.METRE.)" not in text:+ raise AssertionError("STEP file missing SI_UNIT(.MILLI.,.METRE.) millimeter declaration")+ if "SI_UNIT($,.METRE.)" in text:+ raise AssertionError("STEP file contains meter SI_UNIT($,.METRE.) instead of millimeter")+ if "CLOSED_SHELL" not in text or "MANIFOLD_SOLID_BREP" not in text:+ raise AssertionError("STEP file missing CLOSED_SHELL or MANIFOLD_SOLID_BREP")++ pts = re.findall(+ r"CARTESIAN_POINT\s*\([^,]*,\s*\(\s*([-+0-9.eE]+)\s*,\s*([-+0-9.eE]+)\s*,\s*([-+0-9.eE]+)\s*\)\s*\)",+ text,+ )+ if not pts:+ raise AssertionError("STEP file contains no parseable CARTESIAN_POINT entries")+ coords = [(float(x), float(y), float(z)) for x, y, z in pts]+ xs = [c[0] for c in coords]+ ys = [c[1] for c in coords]+ zs = [c[2] for c in coords]+ bbox_min = [min(xs), min(ys), min(zs)]+ bbox_max = [max(xs), max(ys), max(zs)]+ size = [bbox_max[i] - bbox_min[i] for i in range(3)]+ return {+ "cartesian_points": len(coords),+ "bbox_min": bbox_min,+ "bbox_max": bbox_max,+ "size": size,+ "has_automotive_design": "AUTOMOTIVE_DESIGN" in text,+ }+++def write_binary_box_stl(+ path: pathlib.Path,+ size_xyz: tuple[float, float, float],+ *,+ center_xy: tuple[float, float] = (0.0, 0.0),+ z0: float = 0.0,+) -> pathlib.Path:+ sx, sy, sz = size_xyz+ cx, cy = center_xy+ xmin, xmax = cx - sx / 2.0, cx + sx / 2.0+ ymin, ymax = cy - sy / 2.0, cy + sy / 2.0+ zmin, zmax = z0, z0 + sz+ p000 = (xmin, ymin, zmin)+ p100 = (xmax, ymin, zmin)+ p110 = (xmax, ymax, zmin)+ p010 = (xmin, ymax, zmin)+ p001 = (xmin, ymin, zmax)+ p101 = (xmax, ymin, zmax)+ p111 = (xmax, ymax, zmax)+ p011 = (xmin, ymax, zmax)+ tris = [+ (p000, p010, p110),+ (p000, p110, p100),+ (p001, p101, p111),+ (p001, p111, p011),+ (p000, p100, p101),+ (p000, p101, p001),+ (p010, p011, p111),+ (p010, p111, p110),+ (p000, p001, p011),+ (p000, p011, p010),+ (p100, p110, p111),+ (p100, p111, p101),+ ]+ buf = bytearray(b"forma-print e2e generated binary STL".ljust(80, b"\x00"))+ buf.extend(struct.pack("<I", len(tris)))+ for a, b, c in tris:+ ux, uy, uz = b[0] - a[0], b[1] - a[1], b[2] - a[2]+ vx, vy, vz = c[0] - a[0], c[1] - a[1], c[2] - a[2]+ nx = uy * vz - uz * vy+ ny = uz * vx - ux * vz+ nz = ux * vy - uy * vx+ ln = math.sqrt(nx * nx + ny * ny + nz * nz) or 1.0+ buf.extend(struct.pack("<12fH", nx / ln, ny / ln, nz / ln, *a, *b, *c, 0))+ path.write_bytes(bytes(buf))+ return path+++def inspect_stl(path: pathlib.Path) -> dict[str, Any]:+ if not path.is_file():+ raise AssertionError(f"Missing STL file: {path}")+ raw = path.read_bytes()+ if len(raw) == 0:+ raise ValueError("Empty STL file (0 bytes)")++ # Check ASCII STL first if starts with 'solid' and parses cleanly+ if raw[:5].lower() == b"solid":+ try:+ text = raw.decode("utf-8")+ verts: list[tuple[float, float, float]] = []+ for m in re.finditer(+ r"vertex\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)", text+ ):+ coords = (float(m.group(1)), float(m.group(2)), float(m.group(3)))+ if not all(math.isfinite(v) for v in coords):+ raise ValueError("Non-finite vertex in ASCII STL")+ verts.append(coords)+ if verts and len(verts) % 3 == 0 and "endsolid" in text.lower():+ xs = [v[0] for v in verts]+ ys = [v[1] for v in verts]+ zs = [v[2] for v in verts]+ return {+ "format": "ascii",+ "triangles": len(verts) // 3,+ "bbox_min": [min(xs), min(ys), min(zs)],+ "bbox_max": [max(xs), max(ys), max(zs)],+ "size": [max(xs) - min(xs), max(ys) - min(ys), max(zs) - min(zs)],+ }+ except UnicodeDecodeError:+ pass++ if len(raw) < 84:+ raise ValueError(f"Truncated binary STL (<84 bytes): {len(raw)}")+ tri_count = struct.unpack("<I", raw[80:84])[0]+ expected_len = 84 + 50 * tri_count+ if len(raw) != expected_len or tri_count == 0:+ raise ValueError(+ f"Invalid/truncated binary STL: len={len(raw)}, expected={expected_len}, tris={tri_count}"+ )+ xs, ys, zs = [], [], []+ for i in range(tri_count):+ off = 84 + i * 50+ vals = struct.unpack("<12fH", raw[off : off + 50])+ if not all(math.isfinite(v) for v in vals[:12]):+ raise ValueError("Non-finite float in binary STL")+ for j in (3, 6, 9):+ xs.append(vals[j])+ ys.append(vals[j + 1])+ zs.append(vals[j + 2])+ return {+ "format": "binary",+ "triangles": tri_count,+ "bbox_min": [min(xs), min(ys), min(zs)],+ "bbox_max": [max(xs), max(ys), max(zs)],+ "size": [max(xs) - min(xs), max(ys) - min(ys), max(zs) - min(zs)],+ }+++def load_jsonl(path: pathlib.Path) -> list[dict[str, Any]]:+ records: list[dict[str, Any]] = []+ for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):+ stripped = line.strip()+ if not stripped:+ continue+ try:+ obj = json.loads(stripped)+ except json.JSONDecodeError as exc:+ raise AssertionError(f"Invalid JSONL at {path}:{lineno}: {exc}") from exc+ if not isinstance(obj, dict):+ raise AssertionError(f"Expected JSON object at {path}:{lineno}, got {type(obj)}")+ records.append(obj)+ return records+++def is_valid_http_url(url: str) -> bool:+ if not isinstance(url, str) or not url.strip():+ return False+ parsed = urllib.parse.urlparse(url.strip())+ return parsed.scheme in ("http", "https") and bool(parsed.netloc) and "." in parsed.netloc+++def validate_json_schema_subset(value: Any, schema: dict[str, Any], path: str = "$") -> list[str]:+ """Pure-Python JSON Schema validator supporting common Draft-07/2020-12 keywords."""+ errors: list[str] = []+ expected_type = schema.get("type")+ if expected_type is not None:+ types = expected_type if isinstance(expected_type, list) else [expected_type]+ type_ok = False+ for t in types:+ if t == "object" and isinstance(value, dict):+ type_ok = True+ elif t == "array" and isinstance(value, list):+ type_ok = True+ elif t == "string" and isinstance(value, str):+ type_ok = True+ elif t == "boolean" and isinstance(value, bool):+ type_ok = True+ elif t == "integer" and isinstance(value, int) and not isinstance(value, bool):+ type_ok = True+ elif t == "number" and isinstance(value, (int, float)) and not isinstance(value, bool):+ type_ok = True+ elif t == "null" and value is None:+ type_ok = True+ if not type_ok:+ errors.append(f"{path}: expected type {expected_type}, got {type(value).__name__}")+ return errors++ if "enum" in schema and value not in schema["enum"]:+ errors.append(f"{path}: value {value!r} not in enum {schema['enum']}")++ if isinstance(value, str):+ if "minLength" in schema and len(value) < schema["minLength"]:+ errors.append(f"{path}: string length {len(value)} < minLength {schema['minLength']}")+ if "pattern" in schema and not re.search(schema["pattern"], value):+ errors.append(f"{path}: string {value!r} does not match pattern {schema['pattern']!r}")+ if schema.get("format") == "uri" and not is_valid_http_url(value):+ errors.append(f"{path}: invalid URI {value!r}")++ if isinstance(value, (int, float)) and not isinstance(value, bool):+ if "minimum" in schema and value < schema["minimum"]:+ errors.append(f"{path}: {value} < minimum {schema['minimum']}")+ if "maximum" in schema and value > schema["maximum"]:+ errors.append(f"{path}: {value} > maximum {schema['maximum']}")++ if isinstance(value, list):+ if "minItems" in schema and len(value) < schema["minItems"]:+ errors.append(f"{path}: array len {len(value)} < minItems {schema['minItems']}")+ if "items" in schema and isinstance(schema["items"], dict):+ for idx, item in enumerate(value):+ errors.extend(validate_json_schema_subset(item, schema["items"], f"{path}[{idx}]"))++ if isinstance(value, dict):+ for req in schema.get("required", []):+ if req not in value:+ errors.append(f"{path}: missing required key {req!r}")+ props = schema.get("properties", {})+ for k, subschema in props.items():+ if k in value and isinstance(subschema, dict):+ errors.extend(validate_json_schema_subset(value[k], subschema, f"{path}.{k}"))+ if schema.get("additionalProperties") is False:+ extra = set(value.keys()) - set(props.keys())+ if extra:+ errors.append(f"{path}: unexpected additionalProperties {sorted(extra)}")++ return errors+++def extract_urls_from_record(rec: Any) -> list[str]:+ urls: list[str] = []+ if isinstance(rec, str):+ if rec.startswith(("http://", "https://")):+ urls.append(rec)+ elif isinstance(rec, list):+ for item in rec:+ urls.extend(extract_urls_from_record(item))+ elif isinstance(rec, dict):+ for v in rec.values():+ urls.extend(extract_urls_from_record(v))+ return urls+++def extract_printers(profiles_json: Any) -> list[dict[str, Any]]:+ if isinstance(profiles_json, list):+ return [p for p in profiles_json if isinstance(p, dict)]+ if isinstance(profiles_json, dict):+ for key in ("printers", "printer_profiles"):+ val = profiles_json.get(key)+ if isinstance(val, list):+ return [p for p in val if isinstance(p, dict)]+ if isinstance(val, dict):+ out = []+ for k, v in val.items():+ if isinstance(v, dict):+ item = dict(v)+ item.setdefault("id", k)+ out.append(item)+ return out+ raise AssertionError(f"Could not find printers list in profiles JSON: {profiles_json}")+++def extract_materials(profiles_json: Any) -> list[Any]:+ if isinstance(profiles_json, dict):+ for key in ("materials", "filaments", "material_profiles"):+ val = profiles_json.get(key)+ if isinstance(val, list):+ return val+ if isinstance(val, dict):+ return [{"id": k, **v} if isinstance(v, dict) else {"id": k} for k, v in val.items()]+ raise AssertionError(f"Could not find materials list in profiles JSON: {profiles_json}")+++def printer_id_of(p: dict[str, Any]) -> str:+ for key in ("id", "profile_id", "name"):+ if key in p and isinstance(p[key], str):+ return p[key]+ raise AssertionError(f"Printer object missing id: {p}")+++def printer_tech_of(p: dict[str, Any]) -> str:+ for key in ("tech", "technology", "process"):+ if key in p and isinstance(p[key], str):+ return p[key].lower()+ raise AssertionError(f"Printer object missing tech: {p}")+++def printer_volume_of(p: dict[str, Any]) -> tuple[float, float, float]:+ for key in ("build_volume_mm", "build_volume", "volume_mm", "bed_mm"):+ val = p.get(key)+ if isinstance(val, (list, tuple)) and len(val) == 3:+ return (float(val[0]), float(val[1]), float(val[2]))+ if isinstance(val, dict):+ for xk, yk, zk in (("x", "y", "z"), ("x_mm", "y_mm", "z_mm"), ("width", "depth", "height")):+ if xk in val and yk in val and zk in val:+ return (float(val[xk]), float(val[yk]), float(val[zk]))+ if all(k in p for k in ("x_mm", "y_mm", "z_mm")):+ return (float(p["x_mm"]), float(p["y_mm"]), float(p["z_mm"]))+ raise AssertionError(f"Printer object missing build volume: {p}")+++def find_all_strings(obj: Any) -> list[str]:+ out: list[str] = []+ if isinstance(obj, str):+ out.append(obj)+ elif isinstance(obj, list):+ for item in obj:+ out.extend(find_all_strings(item))+ elif isinstance(obj, dict):+ for k, v in obj.items():+ out.append(str(k))+ out.extend(find_all_strings(v))+ return out+++_FAILING_STATUSES = {"fail", "failed", "warn", "warning", "error"}+_PASSING_STATUSES = {"pass", "passed", "ok", "clean"}+_FAILING_SEVERITIES = {"warn", "warning", "error", "fail", "critical", "fatal"}+_DEFECT_BOOL_RE = re.compile(+ r"(exceed|violation|overlap|collid|collision|suction|cavity|trap|unstable|tip|exclusion|cutter|non_manifold|failed|out_of_bounds)"+)+_POSITIVE_BOOL_KEYS = {+ "watertight",+ "manifold",+ "is_watertight",+ "is_manifold",+ "fits_volume",+ "fits_build_volume",+ "in_bounds",+ "bed_stable",+ "stable",+ "clearance_ok",+ "wall_thickness_ok",+ "overhang_ok",+ "islands_ok",+}+_DEFECT_COUNT_RE = re.compile(+ r"(floating_island|island_count|^islands$|collision|overlap|intersection|suction|cavity|trapped|thin_wall|thin_face|overhang_face|overhang_count|bridge_fail|non_manifold|violation|issue_count|error_count|warning_count|failure_count)"+)+++def _is_dict_failing(d: dict[str, Any]) -> bool:+ if (+ d.get("passed") is False+ or d.get("ok") is False+ or d.get("pass") is False+ or d.get("clean") is False+ or d.get("failed") is True+ or d.get("flagged") is True+ ):+ return True+ if str(d.get("status", "")).lower() in _FAILING_STATUSES:+ return True+ if str(d.get("severity", "")).lower() in _FAILING_SEVERITIES:+ return True+ return False+++def _is_dict_explicitly_passing(d: dict[str, Any]) -> bool:+ if d.get("passed") is True or d.get("ok") is True or d.get("pass") is True:+ return True+ return str(d.get("status", "")).lower() in _PASSING_STATUSES+++def extract_issue_texts(report: Any) -> list[str]:+ """Extract diagnostic/warning/error issue descriptions from opaque check JSON."""+ texts: list[str] = []+ if not isinstance(report, dict):+ return texts++ for key in ("issues", "warnings", "errors", "failures", "violations"):+ val = report.get(key)+ if isinstance(val, list):+ for item in val:+ if isinstance(item, dict) and _is_dict_explicitly_passing(item) and not _is_dict_failing(item):+ continue+ texts.append(json.dumps(item).lower())++ for key in ("findings", "diagnostics"):+ val = report.get(key)+ if isinstance(val, list):+ for item in val:+ if isinstance(item, dict):+ if _is_dict_failing(item) or (+ not _is_dict_explicitly_passing(item)+ and str(item.get("severity", "")).lower() != "info"+ ):+ texts.append(json.dumps(item).lower())+ elif isinstance(item, str) and item.strip():+ texts.append(item.lower())++ parent_passing = _is_dict_explicitly_passing(report) and not _is_dict_failing(report)++ for key, val in report.items():+ k_low = str(key).lower()+ if isinstance(val, dict):+ if _is_dict_failing(val):+ texts.append((k_low + " " + json.dumps(val)).lower())+ texts.extend(extract_issue_texts(val))+ elif isinstance(val, list) and key not in (+ "parts",+ "vertices",+ "triangles",+ "faces",+ "issues",+ "warnings",+ "errors",+ "failures",+ "violations",+ "findings",+ "diagnostics",+ ):+ for item in val:+ if isinstance(item, dict):+ if _is_dict_failing(item):+ texts.append(json.dumps(item).lower())+ texts.extend(extract_issue_texts(item))+ elif not parent_passing:+ if (+ val is True+ and _DEFECT_BOOL_RE.search(k_low)+ and not k_low.startswith(("no_", "not_", "allow_", "ignore_", "supports_"))+ ):+ texts.append(f"{k_low}: true")+ elif val is False and k_low in _POSITIVE_BOOL_KEYS:+ texts.append(f"{k_low}: false")+ elif (+ isinstance(val, (int, float))+ and not isinstance(val, bool)+ and val > 0+ and _DEFECT_COUNT_RE.search(k_low)+ ):+ texts.append(f"{k_low}: {val}")+ return texts+++def report_has_failure_or_warning(report: Any) -> bool:+ if not isinstance(report, dict) or len(report) == 0:+ return False+ if report.get("passed") is False or report.get("ok") is False or report.get("printable") is False:+ return True+ if str(report.get("status", "")).lower() in _FAILING_STATUSES:+ return True+ return len(extract_issue_texts(report)) > 0+++def assert_check_flags(report: Any, keywords: tuple[str, ...], context: str) -> None:+ if not report_has_failure_or_warning(report):+ flat = json.dumps(report).lower()+ raise AssertionError(+ f"Expected DFM check to flag issue ({context}, keywords={keywords}), "+ f"but report showed no warning/failure:\n{flat[:1200]}"+ )+ issue_texts = extract_issue_texts(report)+ issue_blob = "\n".join(issue_texts)+ if not issue_blob or not any(kw.lower() in issue_blob for kw in keywords):+ raise AssertionError(+ f"DFM check flagged an issue for {context}, but none of {keywords} matched "+ f"extracted issue texts:\n{issue_blob[:1200]}\n(full={json.dumps(report)[:600]})"+ )+++def assert_check_clean(report: Any, context: str) -> None:+ if not isinstance(report, dict) or len(report) == 0:+ raise AssertionError(f"Expected non-empty dict report for {context}, got: {report!r}")+ if report.get("passed") is False or report.get("ok") is False or report.get("printable") is False:+ raise AssertionError(f"Expected clean pass for {context}, got: {report}")+ if str(report.get("status", "")).lower() in _FAILING_STATUSES:+ raise AssertionError(f"Expected clean status for {context}, got status={report.get('status')!r}: {report}")+ for key in ("errors", "failures", "violations"):+ val = report.get(key)+ if isinstance(val, list) and len(val) > 0:+ raise AssertionError(f"Expected no {key} for {context}, got: {val}")+ issue_texts = extract_issue_texts(report)+ if issue_texts:+ raise AssertionError(f"Expected no failed sub-checks/warnings/errors for {context}, got: {issue_texts[:10]}")+++_TIMING_KEY_RE = re.compile(r"(time|latency|elapsed|duration|_ms$|_s$|_sec$|timestamp|date)")+++def parse_structured_bench_output(stdout: str) -> dict[str, Any]:+ """Parse JSON or structured key-value/tabular metrics from bench_efficiency.py."""+ raw = stdout.strip()+ if not raw:+ raise AssertionError("bench_efficiency.py produced empty stdout")++ all_items: dict[str, Any] = {}+ fmt = "text"++ parsed_json: Any = None+ if raw.startswith("{") or raw.startswith("["):+ try:+ parsed_json = json.loads(raw)+ except json.JSONDecodeError:+ parsed_json = None++ if isinstance(parsed_json, (dict, list)):+ fmt = "json"++ def _flatten(obj: Any, prefix: str) -> None:+ if isinstance(obj, dict):+ for k, v in obj.items():+ nxt = f"{prefix}.{k}" if prefix else str(k)+ _flatten(v, nxt)+ elif isinstance(obj, list):+ for idx, v in enumerate(obj):+ _flatten(v, f"{prefix}[{idx}]")+ else:+ all_items[prefix] = obj++ _flatten(parsed_json, "")+ else:+ for line in raw.splitlines():+ s = line.strip()+ if not s or set(s) <= set("-|=+: "):+ continue+ if s.startswith("|") and "|" in s[1:]:+ cells = [c.strip() for c in s.strip("|").split("|")]+ if len(cells) >= 2 and cells[0] and not set(cells[0]) <= set("-: "):+ key = re.sub(r"\s+", "_", cells[0].lower())+ all_items[key] = " | ".join(cells[1:])+ continue+ m = re.match(r"^([A-Za-z0-9_ ./()-]{2,60}?)\s*[:=]\s*(.+)$", s)+ if m:+ key = re.sub(r"\s+", "_", m.group(1).strip().lower())+ all_items[key] = m.group(2).strip()++ if len(all_items) < 2:+ raise AssertionError(+ f"Expected structured JSON or >=2 metric lines from bench_efficiency.py, got:\n{raw[:800]}"+ )++ deterministic: dict[str, Any] = {+ k: v for k, v in all_items.items() if not _TIMING_KEY_RE.search(k.lower())+ }+ return {+ "format": fmt,+ "keys": sorted(all_items.keys()),+ "deterministic": deterministic,+ "all_items": all_items,+ }+++def extract_numeric_field(obj: Any, candidate_keys: tuple[str, ...]) -> float | None:+ if isinstance(obj, dict):+ for k in candidate_keys:+ v = obj.get(k)+ if isinstance(v, (int, float)) and not isinstance(v, bool):+ return float(v)+ for v in obj.values():+ if isinstance(v, dict):+ found = extract_numeric_field(v, candidate_keys)+ if found is not None:+ return found+ return None+++def extract_bbox_size_mm(obj: Any) -> tuple[float, float, float] | None:+ if isinstance(obj, dict):+ for key in ("size_mm", "size", "extents_mm", "dimensions_mm"):+ v = obj.get(key)+ if isinstance(v, (list, tuple)) and len(v) == 3:+ return (float(v[0]), float(v[1]), float(v[2]))+ if isinstance(v, dict) and all(k in v for k in ("x", "y", "z")):+ return (float(v["x"]), float(v["y"]), float(v["z"]))+ bmin = obj.get("bbox_min") or obj.get("min_mm")+ bmax = obj.get("bbox_max") or obj.get("max_mm")+ if isinstance(bmin, (list, tuple)) and isinstance(bmax, (list, tuple)) and len(bmin) == 3 and len(bmax) == 3:+ return (float(bmax[0]) - float(bmin[0]), float(bmax[1]) - float(bmin[1]), float(bmax[2]) - float(bmin[2]))+ for v in obj.values():+ if isinstance(v, dict):+ found = extract_bbox_size_mm(v)+ if found is not None:+ return found+ return None+++def temp_dir(prefix: str = "forma_print_e2e_") -> tempfile.TemporaryDirectory[str]:+ return tempfile.TemporaryDirectory(prefix=prefix)diff --git a/tests/e2e/run_e2e.py b/tests/e2e/run_e2e.pynew file mode 100644index 0000000..18b0ba7--- /dev/null+++ b/tests/e2e/run_e2e.py@@ -0,0 +1,307 @@+#!/usr/bin/env python3+"""Opaque-box 4-tier E2E test runner for forma-print."""++from __future__ import annotations++import argparse+import json+import pathlib+import re+import sys+import time+import traceback+from collections import Counter+from typing import Any++E2E_DIR = pathlib.Path(__file__).resolve().parent+if str(E2E_DIR) not in sys.path:+ sys.path.insert(0, str(E2E_DIR))++import helpers as h # noqa: E402+import test_tier1_features # noqa: E402+import test_tier2_boundaries # noqa: E402+import test_tier3_cross_feature # noqa: E402+import test_tier4_scenarios # noqa: E402++FEATURE_IDS = [f"#{i}" for i in range(2, 21)]+++def discover_all_tests() -> list[h.TestCase]:+ tests: list[h.TestCase] = []+ for mod in (+ test_tier1_features,+ test_tier2_boundaries,+ test_tier3_cross_feature,+ test_tier4_scenarios,+ ):+ tests.extend(h.collect_tests_from_module(mod))+ return tests+++def run_dry_run_checks(all_tests: list[h.TestCase]) -> dict[str, Any]:+ errors: list[str] = []++ # 1. Duplicate ID & coverage threshold checks+ ids = [t.id for t in all_tests]+ dups = [k for k, v in Counter(ids).items() if v > 1]+ if dups:+ errors.append(f"Duplicate test IDs: {dups}")++ by_tier = Counter(t.tier for t in all_tests)+ if by_tier[1] < 95:+ errors.append(f"Tier 1 count {by_tier[1]} < 95")+ if by_tier[2] < 95:+ errors.append(f"Tier 2 count {by_tier[2]} < 95")+ if by_tier[3] < 19:+ errors.append(f"Tier 3 count {by_tier[3]} < 19")+ if by_tier[4] < 10:+ errors.append(f"Tier 4 count {by_tier[4]} < 10")++ for fid in FEATURE_IDS:+ t1_cnt = sum(1 for t in all_tests if t.tier == 1 and t.feature_id == fid)+ t2_cnt = sum(1 for t in all_tests if t.tier == 2 and t.feature_id == fid)+ if t1_cnt < 5:+ errors.append(f"Feature {fid} has {t1_cnt} < 5 Tier 1 tests")+ if t2_cnt < 5:+ errors.append(f"Feature {fid} has {t2_cnt} < 5 Tier 2 tests")++ # 2. Validate .forma fixtures via core forma eval --strict --json+ forma_results: dict[str, str] = {}+ forma_files = sorted(h.FIXTURES_DIR.glob("*.forma"))+ if not forma_files:+ errors.append("No .forma fixtures found in tests/e2e/fixtures/")+ for fpath in forma_files:+ expect_ok = fpath.name != "invalid_syntax.forma"+ try:+ h.verify_forma_fixture(fpath, expect_ok=expect_ok)+ forma_results[fpath.name] = "ok" if expect_ok else "expected_error_ok"+ except Exception as exc:+ errors.append(f"Forma fixture {fpath.name}: {exc}")+ forma_results[fpath.name] = f"ERROR: {exc}"++ # 3. Validate .stl fixtures+ stl_results: dict[str, str] = {}+ expected_stl_valid = {"cube_40mm.stl", "cube_ascii_25mm.stl", "non_manifold.stl"}+ expected_stl_corrupt = {"corrupt_truncated.stl", "empty.stl"}+ for stl_name in sorted(expected_stl_valid | expected_stl_corrupt):+ spath = h.FIXTURES_DIR / stl_name+ if not spath.is_file():+ errors.append(f"Missing STL fixture: {stl_name}")+ stl_results[stl_name] = "MISSING"+ continue+ if stl_name in expected_stl_valid:+ try:+ info = h.inspect_stl(spath)+ proc = h.run_forma(["eval", "--strict", "--json"], stdin_text=f'p = load("{spath}")\n')+ if stl_name == "non_manifold.stl":+ if proc.returncode == 0:+ errors.append("non_manifold.stl unexpectedly passed forma eval --strict")+ stl_results[stl_name] = f"expected_non_manifold_ok (tris={info['triangles']})"+ else:+ if proc.returncode != 0:+ errors.append(f"{stl_name} failed forma eval --strict: {proc.stdout} {proc.stderr}")+ stl_results[stl_name] = f"ok (tris={info['triangles']}, fmt={info['format']})"+ except Exception as exc:+ errors.append(f"STL fixture {stl_name}: {exc}")+ stl_results[stl_name] = f"ERROR: {exc}"+ else:+ try:+ h.inspect_stl(spath)+ errors.append(f"Corrupt/empty STL fixture {stl_name} unexpectedly parsed cleanly")+ stl_results[stl_name] = "ERROR: parsed"+ except ValueError:+ stl_results[stl_name] = "expected_invalid_ok"++ # 4. Zero-bloat Cargo.toml / package.json isolation check+ isolation: dict[str, Any] = {}+ try:+ toml_text = (h.REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")+ m = re.search(r"default-members\s*=\s*\[(.*?)\]", toml_text, flags=re.S)+ assert m and "forma-print" not in m.group(1), "forma-print in Cargo.toml default-members"+ pkg = json.loads((h.REPO_ROOT / "package.json").read_text(encoding="utf-8"))+ files = pkg.get("files", [])+ assert not any("research" in f or "forma-print" in f for f in files), f"package.json leak: {files}"+ isolation["ok"] = True+ except Exception as exc:+ isolation["ok"] = False+ isolation["error"] = str(exc)+ errors.append(f"Zero-bloat isolation check: {exc}")++ return {+ "mode": "dry-run",+ "ok": len(errors) == 0,+ "counts": {+ "total": len(all_tests),+ "tier_1": by_tier[1],+ "tier_2": by_tier[2],+ "tier_3": by_tier[3],+ "tier_4": by_tier[4],+ },+ "forma_fixtures": forma_results,+ "stl_fixtures": stl_results,+ "isolation": isolation,+ "errors": errors,+ }+++def run_live_tests(+ selected: list[h.TestCase],+ *,+ allow_unbuilt: bool,+ verbose: bool,+ json_mode: bool,+) -> dict[str, Any]:+ results: list[dict[str, Any]] = []+ passed = 0+ failed = 0+ skipped = 0++ req_cache: dict[tuple[str, ...], tuple[bool, str]] = {}++ for tc in selected:+ t0 = time.monotonic()+ if tc.requires not in req_cache:+ req_cache[tc.requires] = h.check_requirements_available(tc.requires)+ avail, reason = req_cache[tc.requires]+ if not avail:+ skipped += 1+ entry = {+ "id": tc.id,+ "tier": tc.tier,+ "feature_id": tc.feature_id,+ "title": tc.title,+ "requires": list(tc.requires),+ "status": "SKIP_NOT_BUILT",+ "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),+ "detail": reason,+ }+ results.append(entry)+ if not json_mode and verbose:+ print(f"[SKIP_NOT_BUILT] {tc.id} ({tc.feature_id}) {tc.title}: {reason}")+ continue++ try:+ tc.fn()+ passed += 1+ entry = {+ "id": tc.id,+ "tier": tc.tier,+ "feature_id": tc.feature_id,+ "title": tc.title,+ "requires": list(tc.requires),+ "status": "PASS",+ "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),+ "detail": "",+ }+ results.append(entry)+ if not json_mode and verbose:+ print(f"[PASS] {tc.id} ({tc.feature_id}) {tc.title} ({entry['duration_ms']}ms)")+ except h.SkipNotBuilt as exc:+ skipped += 1+ entry = {+ "id": tc.id,+ "tier": tc.tier,+ "feature_id": tc.feature_id,+ "title": tc.title,+ "requires": list(tc.requires),+ "status": "SKIP_NOT_BUILT",+ "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),+ "detail": str(exc),+ }+ results.append(entry)+ if not json_mode and verbose:+ print(f"[SKIP_NOT_BUILT] {tc.id} ({tc.feature_id}) {tc.title}: {exc}")+ except Exception as exc:+ failed += 1+ tb = traceback.format_exc()+ entry = {+ "id": tc.id,+ "tier": tc.tier,+ "feature_id": tc.feature_id,+ "title": tc.title,+ "requires": list(tc.requires),+ "status": "FAIL",+ "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),+ "detail": f"{type(exc).__name__}: {exc}",+ "traceback": tb,+ }+ results.append(entry)+ if not json_mode:+ print(f"[FAIL] {tc.id} ({tc.feature_id}) {tc.title}: {exc}")+ if verbose:+ print(tb)++ ok = (failed == 0) and (allow_unbuilt or skipped == 0)+ return {+ "mode": "live",+ "ok": ok,+ "allow_unbuilt": allow_unbuilt,+ "summary": {+ "total": len(selected),+ "passed": passed,+ "failed": failed,+ "skipped_not_built": skipped,+ },+ "results": results,+ }+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Run forma-print 4-tier opaque-box E2E test suite.")+ parser.add_argument("--tier", choices=("1", "2", "3", "4", "all"), default="all", help="Select tier to run")+ parser.add_argument("--dry-run", action="store_true", help="Validate suite counts, fixtures, and zero-bloat isolation without running live tests")+ parser.add_argument("--allow-unbuilt", action="store_true", help="Exit 0 even if unbuilt artifacts cause SKIP_NOT_BUILT")+ parser.add_argument("--json", action="store_true", help="Emit JSON output")+ parser.add_argument("--filter", default="", help="Substring filter on test id, feature_id, or title")+ parser.add_argument("--verbose", action="store_true", help="Verbose per-test output")+ args = parser.parse_args(argv)++ all_tests = discover_all_tests()++ if args.dry_run:+ report = run_dry_run_checks(all_tests)+ if args.json:+ print(json.dumps(report, indent=2))+ else:+ c = report["counts"]+ print(+ f"DRY-RUN {'OK' if report['ok'] else 'FAILED'}: "+ f"total={c['total']} (T1={c['tier_1']}, T2={c['tier_2']}, T3={c['tier_3']}, T4={c['tier_4']}), "+ f"forma_fixtures={len(report['forma_fixtures'])}, stl_fixtures={len(report['stl_fixtures'])}"+ )+ if report["errors"]:+ for err in report["errors"]:+ print(f" ERROR: {err}")+ return 0 if report["ok"] else 1++ selected = all_tests+ if args.tier != "all":+ tnum = int(args.tier)+ selected = [t for t in selected if t.tier == tnum]+ if args.filter:+ needle = args.filter.lower()+ selected = [+ t+ for t in selected+ if needle in t.id.lower() or needle in t.feature_id.lower() or needle in t.title.lower()+ ]++ report = run_live_tests(+ selected,+ allow_unbuilt=args.allow_unbuilt,+ verbose=args.verbose,+ json_mode=args.json,+ )+ if args.json:+ print(json.dumps(report, indent=2))+ else:+ s = report["summary"]+ print(+ f"E2E {'PASS' if report['ok'] else 'INCOMPLETE/FAIL'}: "+ f"total={s['total']} passed={s['passed']} failed={s['failed']} skipped_not_built={s['skipped_not_built']}"+ )+ return 0 if report["ok"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/e2e/test_tier1_features.py b/tests/e2e/test_tier1_features.pynew file mode 100644index 0000000..7bca2f7--- /dev/null+++ b/tests/e2e/test_tier1_features.py@@ -0,0 +1,1137 @@+"""Tier 1 E2E Tests: Core Smoke / Happy Path (95 tests = 5 per feature #2-#20)."""++from __future__ import annotations++import importlib.util+import json+import pathlib+import re+import sqlite3+import subprocess++import helpers as h+++# ---------------------------------------------------------------------------+# Internal helpers for opaque-box research/ & forma-print assertions+# ---------------------------------------------------------------------------++def _load_software() -> list[dict]:+ p = h.require_research_file("corpus/software.jsonl")+ recs = h.load_jsonl(p)+ assert recs, "software.jsonl must not be empty"+ return recs+++def _load_manufacturers() -> list[dict]:+ p = h.require_research_file("corpus/manufacturers.jsonl")+ recs = h.load_jsonl(p)+ assert recs, "manufacturers.jsonl must not be empty"+ return recs+++def _load_papers() -> list[dict]:+ p = h.require_research_file("corpus/papers.jsonl")+ recs = h.load_jsonl(p)+ assert recs, "papers.jsonl must not be empty"+ return recs+++def _find_matching_records(records: list[dict], needles: tuple[str, ...]) -> list[dict]:+ matched = []+ for rec in records:+ blob = json.dumps(rec).lower()+ if any(n.lower() in blob for n in needles):+ matched.append(rec)+ return matched+++def _assert_records_present(records: list[dict], groups: list[tuple[str, ...]], domain: str) -> None:+ for needles in groups:+ hits = _find_matching_records(records, needles)+ assert hits, f"Expected {domain} record matching one of {needles}"+++def _run_query_rag(query: str, *, domain: str | None = None, top_k: int = 5, db_path: pathlib.Path | None = None) -> str:+ 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")++ proc = h.run_cmd(cmd)+ assert proc.returncode == 0, f"query_rag.py failed (rc={proc.returncode}): {proc.stdout}\n{proc.stderr}"+ out = proc.stdout.strip()+ assert out, f"query_rag.py returned empty output for query={query!r}"+ return out+++def _run_query_rag_json(+ query: str,+ *,+ domain: str | None = None,+ top_k: int = 5,+ db_path: pathlib.Path | None = None,+) -> dict:+ out = _run_query_rag(query, domain=domain, top_k=top_k, db_path=db_path)+ try:+ payload = json.loads(out)+ except json.JSONDecodeError as exc:+ raise AssertionError(+ f"query_rag.py did not emit valid JSON for query={query!r}: {out[:200]!r}"+ ) from exc+ assert isinstance(payload, dict), (+ f"Expected JSON object from query_rag.py, got {type(payload).__name__}"+ )+ return payload+++def _assert_query_rag_domain_hits(+ query: str,+ *,+ expected_domain: str,+ expected_keywords: tuple[str, ...],+ top_k: int = 5,+ db_path: pathlib.Path | None = None,+) -> list[dict]:+ payload = _run_query_rag_json(query, domain=expected_domain, top_k=top_k, db_path=db_path)+ results = payload.get("results")+ assert isinstance(results, list), (+ f"Expected 'results' list, got {type(results).__name__}: {payload!r}"+ )+ assert 1 <= len(results) <= top_k, (+ f"Expected 1..{top_k} results for {expected_domain!r}, got {len(results)}"+ )+ assert all(+ isinstance(r, dict) and r.get("domain") == expected_domain+ for r in results+ ), (+ f"Domain mismatch in results for {expected_domain!r}: "+ f"{[r.get('domain') if isinstance(r, dict) else type(r).__name__ for r in results]}"+ )+ assert all(+ isinstance(r.get("chunk_id"), str) and r["chunk_id"].strip()+ and isinstance(r.get("entity_id"), str) and r["entity_id"].strip()+ and isinstance(r.get("snippet"), str) and r["snippet"].strip()+ for r in results+ ), f"Result item missing required fields (chunk_id/entity_id/snippet): {results!r}"+ needles = tuple(k.lower() for k in expected_keywords)+ assert any(+ any(n in json.dumps(r, ensure_ascii=False).lower() for n in needles)+ for r in results+ ), f"No result item matched {expected_keywords} for domain={expected_domain!r}: {results!r}"+ return results+++def _run_validate_kb_json() -> dict:+ 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:\n{proc.stdout}\n{proc.stderr}"+ try:+ report = json.loads(proc.stdout)+ except json.JSONDecodeError as exc:+ raise AssertionError(+ f"validate_kb.py --json did not emit valid JSON: {proc.stdout[:200]!r}"+ ) from exc+ assert isinstance(report, dict), (+ f"Expected JSON object from validate_kb.py, got {type(report).__name__}"+ )+ assert report.get("status") == "pass", f"Unexpected validate_kb.py status: {report.get('status')!r}"+ return report+++def _load_validate_kb_module():+ p = h.require_research_file("scripts/validate_kb.py")+ spec = importlib.util.spec_from_file_location("forma_print_validate_kb", str(p))+ assert spec is not None and spec.loader is not None, f"Could not load spec for {p}"+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++# ===========================================================================+# #2: R1.1 OSS Slicers catalog (5 tests)+# ===========================================================================+[email protected]_case(id="T1-02-1", tier=1, feature_id="#2", title="OrcaSlicer record present & valid", requires=("research",))+def t1_02_1() -> None:+ _assert_records_present(_load_software(), [("orcaslicer", "orca-slicer")], "software")++[email protected]_case(id="T1-02-2", tier=1, feature_id="#2", title="PrusaSlicer record present & valid", requires=("research",))+def t1_02_2() -> None:+ _assert_records_present(_load_software(), [("prusaslicer", "prusa-slicer")], "software")++[email protected]_case(id="T1-02-3", tier=1, feature_id="#2", title="Bambu Studio record present & valid", requires=("research",))+def t1_02_3() -> None:+ _assert_records_present(_load_software(), [("bambu studio", "bambustudio", "bambu_studio")], "software")++[email protected]_case(id="T1-02-4", tier=1, feature_id="#2", title="Cura / CuraEngine record present & valid", requires=("research",))+def t1_02_4() -> None:+ _assert_records_present(_load_software(), [("curaengine", "ultimaker cura", "cura")], "software")++[email protected]_case(id="T1-02-5", tier=1, feature_id="#2", title="SuperSlicer / Slic3r records present", requires=("research",))+def t1_02_5() -> None:+ _assert_records_present(_load_software(), [("superslicer",), ("slic3r",)], "software")+++# ===========================================================================+# #3: R1.2 Mesh repair & analysis libs (5 tests)+# ===========================================================================+[email protected]_case(id="T1-03-1", tier=1, feature_id="#3", title="lib3mf record present", requires=("research",))+def t1_03_1() -> None:+ _assert_records_present(_load_software(), [("lib3mf",)], "software")++[email protected]_case(id="T1-03-2", tier=1, feature_id="#3", title="Manifold library record present", requires=("research",))+def t1_03_2() -> None:+ _assert_records_present(_load_software(), [("manifold",)], "software")++[email protected]_case(id="T1-03-3", tier=1, feature_id="#3", title="MeshLab / VCGLib record present", requires=("research",))+def t1_03_3() -> None:+ _assert_records_present(_load_software(), [("meshlab", "vcglib")], "software")++[email protected]_case(id="T1-03-4", tier=1, feature_id="#3", title="trimesh & meshoptimizer records present", requires=("research",))+def t1_03_4() -> None:+ _assert_records_present(_load_software(), [("trimesh",), ("meshoptimizer",)], "software")++[email protected]_case(id="T1-03-5", tier=1, feature_id="#3", title="UVtools & Open3D/CGAL/libigl records present", requires=("research",))+def t1_03_5() -> None:+ _assert_records_present(_load_software(), [("uvtools",), ("open3d", "cgal", "libigl")], "software")+++# ===========================================================================+# #4: R1.3 Host, fleet & spool controllers (5 tests)+# ===========================================================================+[email protected]_case(id="T1-04-1", tier=1, feature_id="#4", title="OctoPrint record present", requires=("research",))+def t1_04_1() -> None:+ _assert_records_present(_load_software(), [("octoprint",)], "software")++[email protected]_case(id="T1-04-2", tier=1, feature_id="#4", title="Moonraker record present", requires=("research",))+def t1_04_2() -> None:+ _assert_records_present(_load_software(), [("moonraker",)], "software")++[email protected]_case(id="T1-04-3", tier=1, feature_id="#4", title="Mainsail & Fluidd records present", requires=("research",))+def t1_04_3() -> None:+ _assert_records_present(_load_software(), [("mainsail",), ("fluidd",)], "software")++[email protected]_case(id="T1-04-4", tier=1, feature_id="#4", title="Prusa-Link / Prusa Connect record present", requires=("research",))+def t1_04_4() -> None:+ _assert_records_present(_load_software(), [("prusalink", "prusa-link", "prusa link", "prusa connect")], "software")++[email protected]_case(id="T1-04-5", tier=1, feature_id="#4", title="Spoolman / Obico / ChitUI records present", requires=("research",))+def t1_04_5() -> None:+ _assert_records_present(_load_software(), [("spoolman",), ("obico", "chitui")], "software")+++# ===========================================================================+# #5: R1.4 Printer firmware catalog (5 tests)+# ===========================================================================+[email protected]_case(id="T1-05-1", tier=1, feature_id="#5", title="Klipper firmware record present", requires=("research",))+def t1_05_1() -> None:+ _assert_records_present(_load_software(), [("klipper",)], "software")++[email protected]_case(id="T1-05-2", tier=1, feature_id="#5", title="Marlin firmware record present", requires=("research",))+def t1_05_2() -> None:+ _assert_records_present(_load_software(), [("marlin",)], "software")++[email protected]_case(id="T1-05-3", tier=1, feature_id="#5", title="RepRapFirmware record present", requires=("research",))+def t1_05_3() -> None:+ _assert_records_present(_load_software(), [("reprapfirmware", "reprap firmware")], "software")++[email protected]_case(id="T1-05-4", tier=1, feature_id="#5", title="Prusa-Firmware-Buddy record present", requires=("research",))+def t1_05_4() -> None:+ _assert_records_present(_load_software(), [("prusa-firmware-buddy", "prusa firmware buddy", "buddy")], "software")++[email protected]_case(id="T1-05-5", tier=1, feature_id="#5", title="Smoothieware / GRBL / FluidNC records present", requires=("research",))+def t1_05_5() -> None:+ _assert_records_present(_load_software(), [("smoothieware", "grbl", "fluidnc")], "software")+++# ===========================================================================+# #6: R1.5 Programmatic CAD & CLI utilities (5 tests)+# ===========================================================================+[email protected]_case(id="T1-06-1", tier=1, feature_id="#6", title="OpenSCAD record present", requires=("research",))+def t1_06_1() -> None:+ _assert_records_present(_load_software(), [("openscad",)], "software")++[email protected]_case(id="T1-06-2", tier=1, feature_id="#6", title="CadQuery record present", requires=("research",))+def t1_06_2() -> None:+ _assert_records_present(_load_software(), [("cadquery",)], "software")++[email protected]_case(id="T1-06-3", tier=1, feature_id="#6", title="build123d record present", requires=("research",))+def t1_06_3() -> None:+ _assert_records_present(_load_software(), [("build123d",)], "software")++[email protected]_case(id="T1-06-4", tier=1, feature_id="#6", title="BOSL2 record present", requires=("research",))+def t1_06_4() -> None:+ _assert_records_present(_load_software(), [("bosl2",)], "software")++[email protected]_case(id="T1-06-5", tier=1, feature_id="#6", title="Fornjot / zoo / kcl / pronsole records present", requires=("research",))+def t1_06_5() -> None:+ _assert_records_present(_load_software(), [("fornjot", "zoo", "kcl", "pronsole", "printrun")], "software")+++# ===========================================================================+# #7: R1.6 Modern app inspection (Shpigford/nurb) (5 tests)+# ===========================================================================+[email protected]_case(id="T1-07-1", tier=1, feature_id="#7", title="nurb_inspection.md exists & non-empty", requires=("research",))+def t1_07_1() -> None:+ p = h.require_research_file("reports/nurb_inspection.md")+ text = p.read_text(encoding="utf-8")+ assert len(text.strip()) >= 500, "nurb_inspection.md unexpectedly short"++[email protected]_case(id="T1-07-2", tier=1, feature_id="#7", title="nurb entry present in software.jsonl", requires=("research",))+def t1_07_2() -> None:+ _assert_records_present(_load_software(), [("shpigford/nurb", "nurb")], "software")++[email protected]_case(id="T1-07-3", tier=1, feature_id="#7", title="nurb inspection documents checks.py / probe.py", requires=("research",))+def t1_07_3() -> None:+ text = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8").lower()+ assert "checks.py" in text or "probe.py" in text, "nurb_inspection.md missing checks.py/probe.py"++[email protected]_case(id="T1-07-4", tier=1, feature_id="#7", title="nurb inspection documents printers.toml, nurb slice, & .3mf", requires=("research",))+def t1_07_4() -> None:+ text = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8").lower()+ assert "printers.toml" in text or "printer.toml" in text, "nurb_inspection.md missing printers.toml"+ assert "3mf" in text, "nurb_inspection.md missing .3mf analysis"++[email protected]_case(id="T1-07-5", tier=1, feature_id="#7", title="nurb inspection documents nurb-benchmarks & architectural lessons", requires=("research",))+def t1_07_5() -> None:+ text = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8").lower()+ assert "lesson" in text or "forma-print" in text, "nurb_inspection.md missing architectural lessons"+ assert "benchmark" in text, "nurb_inspection.md missing benchmark discussion"+++# ===========================================================================+# #8: R2.1-R2.4 Manufacturer sweep (5 tests)+# ===========================================================================+[email protected]_case(id="T1-08-1", tier=1, feature_id="#8", title=">=19 distinct manufacturers in manufacturers.jsonl", requires=("research",))+def t1_08_1() -> None:+ recs = _load_manufacturers()+ assert len(recs) >= 19, f"Expected >=19 manufacturers, found {len(recs)}"++[email protected]_case(id="T1-08-2", tier=1, feature_id="#8", title="Bambu Lab, Prusa, Voron, Creality, Elegoo, Formlabs present", requires=("research",))+def t1_08_2() -> None:+ _assert_records_present(+ _load_manufacturers(),+ [("bambu",), ("prusa",), ("voron",), ("creality",), ("elegoo",), ("formlabs",)],+ "manufacturers",+ )++[email protected]_case(id="T1-08-3", tier=1, feature_id="#8", title="Anycubic, QIDI, Sovol, Raise3D, UltiMaker, Markforged, Stratasys present", requires=("research",))+def t1_08_3() -> None:+ _assert_records_present(+ _load_manufacturers(),+ [("anycubic",), ("qidi",), ("sovol",), ("raise3d",), ("ultimaker",), ("markforged",), ("stratasys",)],+ "manufacturers",+ )++[email protected]_case(id="T1-08-4", tier=1, feature_id="#8", title="FlashForge, Snapmaker, Phrozen, AnkerMake, RatRig, LulzBot/Duet3D present", requires=("research",))+def t1_08_4() -> None:+ _assert_records_present(+ _load_manufacturers(),+ [("flashforge",), ("snapmaker",), ("phrozen",), ("ankermake", "eufymake"), ("ratrig", "rat rig"), ("lulzbot", "duet3d", "bigtreetech", "btt")],+ "manufacturers",+ )++[email protected]_case(id="T1-08-5", tier=1, feature_id="#8", title="Manufacturer records conform to manufacturers.schema.json", requires=("research",))+def t1_08_5() -> None:+ schema = json.loads(h.require_research_file("schemas/manufacturers.schema.json").read_text(encoding="utf-8"))+ for idx, rec in enumerate(_load_manufacturers()):+ errs = h.validate_json_schema_subset(rec, schema)+ assert not errs, f"Manufacturer record #{idx} schema errors: {errs}"+++# ===========================================================================+# #9: R3.1-R3.7 Academic papers corpus (5 tests)+# ===========================================================================+[email protected]_case(id="T1-09-1", tier=1, feature_id="#9", title="Printability optimization papers present", requires=("research",))+def t1_09_1() -> None:+ _assert_records_present(_load_papers(), [("printab",)], "papers")++[email protected]_case(id="T1-09-2", tier=1, feature_id="#9", title="Overhang & support minimization papers present", requires=("research",))+def t1_09_2() -> None:+ _assert_records_present(_load_papers(), [("overhang", "support")], "papers")++[email protected]_case(id="T1-09-3", tier=1, feature_id="#9", title="Structural & wall thickness analysis papers present", requires=("research",))+def t1_09_3() -> None:+ _assert_records_present(_load_papers(), [("thickness", "structural", "strength", "thin")], "papers")++[email protected]_case(id="T1-09-4", tier=1, feature_id="#9", title="Hollowing/drainage & decomposition/packing papers present", requires=("research",))+def t1_09_4() -> None:+ _assert_records_present(_load_papers(), [("hollow", "drain", "void"), ("decompos", "pack", "nest", "split")], "papers")++[email protected]_case(id="T1-09-5", tier=1, feature_id="#9", title="Clearance/tolerance/orientation papers present", requires=("research",))+def t1_09_5() -> None:+ _assert_records_present(_load_papers(), [("clearance", "tolerance", "orient")], "papers")+++# ===========================================================================+# #10: R4.1-R4.2 RAG DB & chunking layout (5 tests)+# ===========================================================================+[email protected]_case(id="T1-10-1", tier=1, feature_id="#10", title="All 4 JSON schemas in research/schemas/ are valid JSON", requires=("research",))+def t1_10_1() -> None:+ for name in ("software.schema.json", "manufacturers.schema.json", "papers.schema.json", "rag_chunks.schema.json"):+ p = h.require_research_file(f"schemas/{name}")+ obj = json.loads(p.read_text(encoding="utf-8"))+ assert isinstance(obj, dict) and ("properties" in obj or "$schema" in obj), f"Invalid schema {name}"++[email protected]_case(id="T1-10-2", tier=1, feature_id="#10", title="forma_print_kb.sqlite exists with FTS5 tables & non-zero rows", requires=("research",))+def t1_10_2() -> None:+ db = h.require_research_file("rag/forma_print_kb.sqlite")+ assert db.stat().st_size > 0+ conn = sqlite3.connect(str(db))+ try:+ rows = conn.execute("SELECT name, sql FROM sqlite_master WHERE type='table'").fetchall()+ tables = [r[0] for r in rows]+ assert tables, "SQLite DB has no tables"+ fts_tables = [r[0] for r in rows if "fts5" in (r[1] or "").lower()]+ assert fts_tables, f"SQLite DB has no FTS5 virtual table: {tables}"+ assert "chunks_fts" in fts_tables, f"Expected 'chunks_fts' FTS5 table, got {fts_tables}"+ total_rows = 0+ for tbl in tables:+ if tbl.endswith(("_data", "_idx", "_docsize", "_config", "_content")):+ continue+ cnt = conn.execute(f'SELECT COUNT(*) FROM "{tbl}"').fetchone()[0]+ total_rows += cnt+ assert total_rows > 0, "SQLite DB has 0 rows"+ finally:+ conn.close()++[email protected]_case(id="T1-10-3", tier=1, feature_id="#10", title="query_rag.py returns results for software query", requires=("research",))+def t1_10_3() -> None:+ _assert_query_rag_domain_hits(+ "OrcaSlicer 3mf metadata",+ expected_domain="software",+ expected_keywords=("orca", "3mf"),+ top_k=5,+ )++[email protected]_case(id="T1-10-4", tier=1, feature_id="#10", title="query_rag.py returns results for manufacturer query", requires=("research",))+def t1_10_4() -> None:+ _assert_query_rag_domain_hits(+ "Bambu Lab LAN developer mode MQTT telemetry",+ expected_domain="manufacturer",+ expected_keywords=("bambu",),+ top_k=5,+ )++[email protected]_case(id="T1-10-5", tier=1, feature_id="#10", title="query_rag.py returns results for academic paper query", requires=("research",))+def t1_10_5() -> None:+ _assert_query_rag_domain_hits(+ "overhang support minimization orientation",+ expected_domain="paper",+ expected_keywords=("overhang", "support"),+ top_k=5,+ )+++# ===========================================================================+# #11: R4.3 Automated KB & RAG validation (5 tests)+# ===========================================================================+[email protected]_case(id="T1-11-1", tier=1, feature_id="#11", title="validate_kb.py exists & is readable", requires=("research",))+def t1_11_1() -> None:+ p = h.require_research_file("scripts/validate_kb.py")+ assert p.stat().st_size > 100++[email protected]_case(id="T1-11-2", tier=1, feature_id="#11", title="validate_kb.py exits 0 on repo KB", requires=("research",))+def t1_11_2() -> None:+ p = h.require_research_file("scripts/validate_kb.py")+ proc = h.run_cmd(["python3", str(p)])+ assert proc.returncode == 0, f"validate_kb.py failed:\n{proc.stdout}\n{proc.stderr}"++[email protected]_case(id="T1-11-3", tier=1, feature_id="#11", title="validate_kb.py verifies schema conformance", requires=("research",))+def t1_11_3() -> None:+ report = _run_validate_kb_json()+ checks = {c.get("name"): c for c in report.get("checks", []) if isinstance(c, dict)}++ stage1 = checks.get("stage1_schemas")+ assert stage1 is not None and stage1.get("passed") is True, f"stage1_schemas failed: {stage1!r}"+ s1_details = stage1.get("details", {})+ loaded = set(s1_details.get("loaded", []))+ expected_schemas = {+ "software.schema.json",+ "manufacturers.schema.json",+ "papers.schema.json",+ "rag_chunks.schema.json",+ }+ assert expected_schemas.issubset(loaded), f"Missing loaded schemas: {expected_schemas - loaded}"+ assert s1_details.get("errors") == [], f"Unexpected stage1 schema errors: {s1_details.get('errors')}"++ stage2 = checks.get("stage2_corpus")+ assert stage2 is not None and stage2.get("passed") is True, f"stage2_corpus failed: {stage2!r}"+ counts = stage2.get("details", {}).get("counts", {})+ for dom in ("software", "manufacturers", "papers"):+ assert counts.get(dom, 0) > 0, f"Expected positive count for {dom!r}, got {counts}"++ stage4 = checks.get("stage4_rag_db_and_isolation")+ assert stage4 is not None and stage4.get("passed") is True, (+ f"stage4_rag_db_and_isolation failed: {stage4!r}"+ )+ assert report.get("total_chunks", 0) > 0, f"Expected total_chunks > 0, got {report.get('total_chunks')}"++[email protected]_case(id="T1-11-4", tier=1, feature_id="#11", title="validate_kb.py verifies URL/citation & non-empty fields", requires=("research",))+def t1_11_4() -> None:+ report = _run_validate_kb_json()+ checks = {c.get("name"): c for c in report.get("checks", []) if isinstance(c, dict)}+ stage2 = checks.get("stage2_corpus")+ assert stage2 is not None and stage2.get("passed") is True, f"stage2_corpus failed: {stage2!r}"+ assert stage2.get("details", {}).get("errors") == [], (+ f"Unexpected stage2 corpus errors: {stage2.get('details', {}).get('errors')}"+ )++ vkb = _load_validate_kb_module()+ assert vkb.is_valid_http_url("https://example.com/docs") is True+ assert vkb.is_valid_http_url("not-a-url") is False+ assert vkb.is_valid_http_url("ftp://example.com/file") is False+ assert vkb.is_valid_http_url("https://example.com/bad space") is False++ assert vkb.find_empty_trimmed_strings({"ok": "value", "nested": ["a"]}) == []+ assert vkb.find_empty_trimmed_strings({"x": " "}) == ["$.x"]++ assert vkb.DOI_RE.match("10.1145/2601097.2601165") is not None+ assert vkb.DOI_RE.match("not-a-doi") is None+ assert vkb.ARXIV_RE.match("2301.12345") is not None+ assert vkb.ARXIV_RE.match("not-an-arxiv-id") is None++[email protected]_case(id="T1-11-5", tier=1, feature_id="#11", title="validate_kb.py exercises sample queries across all 3 domains", requires=("research",))+def t1_11_5() -> None:+ p = h.require_research_file("scripts/validate_kb.py")+ help_proc = h.run_cmd(["python3", str(p), "--help"])+ help_text = (help_proc.stdout + "\n" + help_proc.stderr).lower()+ if "--json" in help_text:+ proc = h.run_cmd(["python3", str(p), "--json"])+ assert proc.returncode == 0, f"validate_kb.py --json failed:\n{proc.stdout}\n{proc.stderr}"+ report = json.loads(proc.stdout)+ assert report.get("status") == "pass", f"Unexpected validate_kb.py status: {report.get('status')!r}"+ checks = report.get("checks", [])+ stage5 = next((c for c in checks if c.get("name") == "stage5_rag_retrieval"), None)+ assert stage5 is not None and stage5.get("passed") is True, f"stage5_rag_retrieval failed: {stage5!r}"+ rag_queries = report.get("rag_queries", [])+ for dom in ("software", "manufacturer", "paper"):+ assert any(+ q.get("name", "").startswith(dom) and q.get("hit_count", 0) >= 1+ for q in rag_queries+ ), f"validate_kb.py --json missing passing query for domain {dom!r}"+ else:+ proc = h.run_cmd(["python3", str(p)])+ assert proc.returncode == 0+ combined = (proc.stdout + proc.stderr).lower()+ assert "software" in combined and "manufacturer" in combined and "paper" in combined+++# ===========================================================================+# #12: R5.1-R5.2 Efficiency & justification analysis (5 tests)+# ===========================================================================+[email protected]_case(id="T1-12-1", tier=1, feature_id="#12", title="efficiency_justification.md exists & non-empty", requires=("research",))+def t1_12_1() -> None:+ p = h.require_research_file("analysis/efficiency_justification.md")+ assert len(p.read_text(encoding="utf-8").strip()) >= 800++[email protected]_case(id="T1-12-2", tier=1, feature_id="#12", title="Efficiency analysis covers accuracy, latency, token/compute cost & deterministic checks", requires=("research",))+def t1_12_2() -> None:+ text = h.require_research_file("analysis/efficiency_justification.md").read_text(encoding="utf-8").lower()+ for term in ("accuracy", "latency", "token", "deterministic"):+ assert term in text, f"efficiency_justification.md missing {term!r}"++[email protected]_case(id="T1-12-3", tier=1, feature_id="#12", title="Efficiency analysis compares against large LLM guesswork (Fable 5.2)", requires=("research",))+def t1_12_3() -> None:+ text = h.require_research_file("analysis/efficiency_justification.md").read_text(encoding="utf-8").lower()+ assert "fable" in text or "5.2" in text, "efficiency_justification.md missing Fable 5.2 comparison"++[email protected]_case(id="T1-12-4", tier=1, feature_id="#12", title="Efficiency analysis states explicit non-replacement bounds", requires=("research",))+def t1_12_4() -> None:+ text = h.require_research_file("analysis/efficiency_justification.md").read_text(encoding="utf-8").lower()+ assert "slicer" in text and ("replace" in text or "scope" in text or "bound" in text)++[email protected]_case(id="T1-12-5", tier=1, feature_id="#12", title="bench_efficiency.py exists & runs exiting 0", requires=("research",))+def t1_12_5() -> None:+ p = h.require_research_file("scripts/bench_efficiency.py")+ proc = h.run_cmd(["python3", str(p)], timeout=120.0)+ assert proc.returncode == 0, f"bench_efficiency.py failed:\n{proc.stdout}\n{proc.stderr}"+ assert proc.stdout.strip(), "bench_efficiency.py produced empty stdout"+++# ===========================================================================+# #13: R6.1 Workspace & zero-bloat isolation (5 tests)+# ===========================================================================+[email protected]_case(id="T1-13-1", tier=1, feature_id="#13", title="crates/forma-print listed in Cargo.toml workspace.members", requires=("forma_print",))+def t1_13_1() -> None:+ toml_text = (h.REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")+ m = re.search(r"(?m)^members\s*=\s*\[(.*?)\]", toml_text, flags=re.S)+ assert m, "members missing in Cargo.toml"+ assert '"crates/forma-print"' in m.group(1), "crates/forma-print missing from workspace.members"++[email protected]_case(id="T1-13-2", tier=1, feature_id="#13", title="crates/forma-print NOT in Cargo.toml default-members", requires=("core_baseline",))+def t1_13_2() -> None:+ toml_text = (h.REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")+ m = re.search(r"default-members\s*=\s*\[(.*?)\]", toml_text, flags=re.S)+ assert m, "default-members missing in Cargo.toml"+ assert "forma-print" not in m.group(1), "forma-print must NEVER be in default-members"++[email protected]_case(id="T1-13-3", tier=1, feature_id="#13", title="cargo build --release builds core binaries without forma-print", requires=("core_baseline",))+def t1_13_3() -> None:+ proc = h.run_cmd(["cargo", "build", "--manifest-path", str(h.REPO_ROOT / "Cargo.toml"), "--release"], timeout=180.0)+ assert proc.returncode == 0, f"Core release build failed:\n{proc.stdout}\n{proc.stderr}"+ assert h.find_forma_bin().is_file()+ assert h.find_forma_mcp_bin().is_file()++[email protected]_case(id="T1-13-4", tier=1, feature_id="#13", title="Core forma-mcp tools/list stays < 800 o200k tokens", requires=("core_baseline",))+def t1_13_4() -> None:+ with h.McpClient([str(h.find_forma_mcp_bin())]) as mcp:+ mcp.initialize()+ tools = mcp.tools_list()+ toks = h.count_o200k_tokens(tools)+ assert toks < 800, f"Core forma-mcp tools/list exceeded 800 o200k tokens: {toks}"++[email protected]_case(id="T1-13-5", tier=1, feature_id="#13", title="research/ and crates/forma-print excluded from package.json files", requires=("core_baseline",))+def t1_13_5() -> None:+ pkg = json.loads((h.REPO_ROOT / "package.json").read_text(encoding="utf-8"))+ files = pkg.get("files", [])+ assert not any("research" in f or "forma-print" in f for f in files), f"Unexpected package.json files: {files}"+++# ===========================================================================+# #14: R6.2 Printer & filament profiles (5 tests)+# ===========================================================================+[email protected]_case(id="T1-14-1", tier=1, feature_id="#14", title="profiles --json returns all 18 printers", requires=("forma_print",))+def t1_14_1() -> None:+ _, data = h.run_forma_print_json(["profiles"])+ printers = h.extract_printers(data)+ ids = {h.printer_id_of(p) for p in printers}+ missing = set(h.EXPECTED_PRINTER_VOLUMES_MM) - ids+ assert not missing, f"Missing printer profiles: {sorted(missing)}"+ assert len(printers) >= 18++[email protected]_case(id="T1-14-2", tier=1, feature_id="#14", title="profiles --json returns all 9 materials", requires=("forma_print",))+def t1_14_2() -> None:+ _, data = h.run_forma_print_json(["profiles"])+ mats = h.extract_materials(data)+ mat_ids = {m["id"] if isinstance(m, dict) else str(m) for m in mats}+ for req in h.EXPECTED_MATERIALS:+ assert any(req.lower() == mid.lower() for mid in mat_ids), f"Missing material {req!r} in {mat_ids}"++[email protected]_case(id="T1-14-3", tier=1, feature_id="#14", title="profiles --tech fdm returns 14 FDM printers", requires=("forma_print",))+def t1_14_3() -> None:+ _, data = h.run_forma_print_json(["profiles", "--tech", "fdm"])+ printers = h.extract_printers(data)+ assert len(printers) == 14, f"Expected 14 FDM printers, got {len(printers)}"+ assert all(h.printer_tech_of(p) == "fdm" for p in printers)++[email protected]_case(id="T1-14-4", tier=1, feature_id="#14", title="profiles --tech sla returns 3 MSLA printers", requires=("forma_print",))+def t1_14_4() -> None:+ _, data = h.run_forma_print_json(["profiles", "--tech", "sla"])+ printers = h.extract_printers(data)+ assert len(printers) == 3, f"Expected 3 SLA printers, got {len(printers)}"+ assert all(h.printer_tech_of(p) in ("sla", "msla") for p in printers)++[email protected]_case(id="T1-14-5", tier=1, feature_id="#14", title="profiles --tech sls returns 1 SLS printer", requires=("forma_print",))+def t1_14_5() -> None:+ _, data = h.run_forma_print_json(["profiles", "--tech", "sls"])+ printers = h.extract_printers(data)+ assert len(printers) == 1, f"Expected 1 SLS printer, got {len(printers)}"+ assert h.printer_id_of(printers[0]) == "formlabs_fuse_1p"+++# ===========================================================================+# #15: R6.3 Unit bridge (m|mm|auto + --scale) (5 tests)+# ===========================================================================+[email protected]_case(id="T1-15-1", tier=1, feature_id="#15", title="--unit m scales 0.04x0.03x0.02 m box to 40x30x20 mm", requires=("forma_print",))+def t1_15_1() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--printer", "bambu_x1c"])+ sz = h.extract_bbox_size_mm(data)+ assert sz is not None, f"Could not extract bbox size from check JSON: {data}"+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(sz), [20.0, 30.0, 40.0])), f"Expected 40x30x20 mm, got {sz}"++[email protected]_case(id="T1-15-2", tier=1, feature_id="#15", title="--unit mm keeps 40x30x20 box as 40x30x20 mm", requires=("forma_print",))+def t1_15_2() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "box_mm.forma"), "--unit", "mm", "--printer", "bambu_x1c"])+ sz = h.extract_bbox_size_mm(data)+ assert sz is not None+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(sz), [20.0, 30.0, 40.0])), f"Expected 40x30x20 mm, got {sz}"++[email protected]_case(id="T1-15-3", tier=1, feature_id="#15", title="--unit auto on box_meters.forma resolves to 40x30x20 mm", requires=("forma_print",))+def t1_15_3() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "auto", "--printer", "bambu_x1c"])+ sz = h.extract_bbox_size_mm(data)+ assert sz is not None+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(sz), [20.0, 30.0, 40.0])), f"Expected 40x30x20 mm, got {sz}"++[email protected]_case(id="T1-15-4", tier=1, feature_id="#15", title="--unit auto on cube_40mm.stl keeps 40x40x40 mm", requires=("forma_print",))+def t1_15_4() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "cube_40mm.stl"), "--unit", "auto", "--printer", "bambu_x1c"])+ sz = h.extract_bbox_size_mm(data)+ assert sz is not None+ assert all(abs(a - 40.0) < 0.5 for a in sz), f"Expected 40x40x40 mm, got {sz}"++[email protected]_case(id="T1-15-5", tier=1, feature_id="#15", title="--scale 2.0 doubles output dimensions", requires=("forma_print",))+def t1_15_5() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--scale", "2.0", "--printer", "bambu_x1c"])+ sz = h.extract_bbox_size_mm(data)+ assert sz is not None+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(sz), [40.0, 60.0, 80.0])), f"Expected 80x60x40 mm, got {sz}"+++# ===========================================================================+# #16: R6.4 BVH & pure-Rust DFM audit (5 tests)+# ===========================================================================+[email protected]_case(id="T1-16-1", tier=1, feature_id="#16", title="Clean printable box passes on bambu_x1c + PLA", requires=("forma_print",))+def t1_16_1() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", "bambu_x1c", "--material", "PLA"])+ h.assert_check_clean(data, "clean box_meters on bambu_x1c")++[email protected]_case(id="T1-16-2", tier=1, feature_id="#16", title="Oversized part fails build-volume check", requires=("forma_print",))+def t1_16_2() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "oversized_part.forma"), "--printer", "bambu_x1c", "--material", "PLA"], allow_nonzero=True)+ h.assert_check_flags(data, ("volume", "bound", "fit", "size", "exceed", "dimension", "build"), "oversized_part on bambu_x1c")++[email protected]_case(id="T1-16-3", tier=1, feature_id="#16", title="Overhang cone (>45° FDM) flagged", requires=("forma_print",))+def t1_16_3() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--printer", "bambu_a1_mini", "--material", "PLA"], allow_nonzero=True)+ h.assert_check_flags(data, ("overhang", "angle", "support"), "overhang_cone on bambu_a1_mini")++[email protected]_case(id="T1-16-4", tier=1, feature_id="#16", title="Floating island flagged", requires=("forma_print",))+def t1_16_4() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "floating_island.forma"), "--printer", "bambu_x1c", "--material", "PLA"], allow_nonzero=True)+ h.assert_check_flags(data, ("island", "float", "unsupported", "disconnected"), "floating_island on bambu_x1c")++[email protected]_case(id="T1-16-5", tier=1, feature_id="#16", title="Thin wall (<0.4 mm) flagged", requires=("forma_print",))+def t1_16_5() -> None:+ _, data = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "thin_wall.forma"), "--printer", "bambu_x1c", "--material", "PLA"], allow_nonzero=True)+ h.assert_check_flags(data, ("thin", "wall", "thickness"), "thin_wall on bambu_x1c")+++# ===========================================================================+# #17: R6.5 4-view diagnostic heatmap PNG (5 tests)+# ===========================================================================+[email protected]_case(id="T1-17-1", tier=1, feature_id="#17", title="check --heatmap creates valid PNG file", requires=("forma_print",))+def t1_17_1() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "heatmap.png"+ proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--heatmap", str(out), "--json"])+ assert proc.returncode == 0 or out.is_file()+ info = h.inspect_png(out)+ assert info["idat_bytes"] > 0+ assert info["width"] >= 128 and info["distinct_colors_sampled"] >= 2++[email protected]_case(id="T1-17-2", tier=1, feature_id="#17", title="Heatmap PNG has valid signature, IHDR, IDAT, IEND", requires=("forma_print",))+def t1_17_2() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "heatmap.png"+ proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--heatmap", str(out)])+ assert proc.returncode == 0, f"check --heatmap failed on clean box_meters: {proc.stdout}\n{proc.stderr}"+ info = h.inspect_png(out)+ assert info["chunk_types"][0] == "IHDR"+ assert info["chunk_types"][-1] == "IEND"+ assert "IDAT" in info["chunk_types"]+ assert info["width"] >= 128 and info["distinct_colors_sampled"] >= 2++[email protected]_case(id="T1-17-3", tier=1, feature_id="#17", title="Heatmap PNG dimensions are square >= 128x128", requires=("forma_print",))+def t1_17_3() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "heatmap.png"+ proc = h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--heatmap", str(out)])+ assert proc.returncode == 0, f"check --heatmap failed on clean box_meters: {proc.stdout}\n{proc.stderr}"+ info = h.inspect_png(out)+ assert info["width"] == info["height"] and info["width"] >= 128++[email protected]_case(id="T1-17-4", tier=1, feature_id="#17", title="Heatmap works on .forma, .stl, and .glb inputs", requires=("forma_print",))+def t1_17_4() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ glb_path = td_p / "box.glb"+ r = h.run_forma(["eval", "--strict", "--out", str(glb_path)], stdin_text=(h.FIXTURES_DIR / "box_meters.forma").read_text())+ assert r.returncode == 0 and glb_path.is_file()+ for label, inp in [+ ("forma", h.FIXTURES_DIR / "box_meters.forma"),+ ("stl", h.FIXTURES_DIR / "cube_40mm.stl"),+ ("glb", glb_path),+ ]:+ out = td_p / f"hm_{label}.png"+ proc = h.run_forma_print(["check", str(inp), "--heatmap", str(out)])+ assert proc.returncode == 0, f"check --heatmap failed on {label}: {proc.stdout}\n{proc.stderr}"+ info = h.inspect_png(out)+ assert info["width"] >= 128++[email protected]_case(id="T1-17-5", tier=1, feature_id="#17", title="Heatmap PNG on failing part differs visually from clean part", requires=("forma_print",))+def t1_17_5() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ clean_png = td_p / "clean.png"+ fail_png = td_p / "fail.png"+ h.run_forma_print(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--heatmap", str(clean_png)])+ h.run_forma_print(["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--heatmap", str(fail_png)])+ assert clean_png.read_bytes() != fail_png.read_bytes()+++# ===========================================================================+# #18: R6.6 Auto-orientation solver (5 tests)+# ===========================================================================+[email protected]_case(id="T1-18-1", tier=1, feature_id="#18", title="Upside-down T-bracket flips to minimize overhangs/islands", requires=("forma_print",))+def t1_18_1() -> None:+ with h.temp_dir() as td:+ out_mesh = pathlib.Path(td) / "oriented.stl"+ _, data = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--out", str(out_mesh)])+ assert out_mesh.is_file()+ stl_info = h.inspect_stl(out_mesh)+ assert abs(stl_info["bbox_min"][2]) < 0.5, f"Expected z0=0 after orient, got {stl_info['bbox_min']}"+ assert isinstance(data, dict), f"Expected orient JSON dict, got {type(data).__name__}"+ assert data.get("rotated_from_input") is True, f"Expected upside_down_t to rotate, got {data.get('rotated_from_input')!r}"+ assert data.get("report", {}).get("printable") is True, f"Expected oriented upside_down_t printable=True, got {data.get('report')!r}"++[email protected]_case(id="T1-18-2", tier=1, feature_id="#18", title="Tall unstable bar lays flat to reduce Z-height/tipping", requires=("forma_print",))+def t1_18_2() -> None:+ with h.temp_dir() as td:+ out_mesh = pathlib.Path(td) / "oriented_tall.stl"+ h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "tall_unstable.forma"), "--out", str(out_mesh)])+ stl_info = h.inspect_stl(out_mesh)+ assert stl_info["size"][2] < 85.0, f"Expected tall part to lay flatter (Z < 85 mm), got {stl_info['size']}"++[email protected]_case(id="T1-18-3", tier=1, feature_id="#18", title="Oriented part rests cleanly at z0 = 0", requires=("forma_print",))+def t1_18_3() -> None:+ with h.temp_dir() as td:+ out_mesh = pathlib.Path(td) / "oriented_z0.stl"+ _, data = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--out", str(out_mesh)])+ stl_info = h.inspect_stl(out_mesh)+ assert abs(stl_info["bbox_min"][2]) < 1e-2, f"Expected z_min ~ 0, got {stl_info['bbox_min'][2]}"+ assert isinstance(data, dict), f"Expected orient JSON dict, got {type(data).__name__}"+ assert data.get("rotated_from_input") is True, f"Expected overhang_cone to rotate, got {data.get('rotated_from_input')!r}"+ assert data.get("report", {}).get("checks", {}).get("overhangs") == "pass", (+ f"Expected overhangs check to pass after orient, got {data.get('report', {}).get('checks')!r}"+ )++[email protected]_case(id="T1-18-4", tier=1, feature_id="#18", title="orient --out writes valid mesh (.stl and .glb)", requires=("forma_print",))+def t1_18_4() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ out_stl = td_p / "out.stl"+ out_glb = td_p / "out.glb"+ h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--out", str(out_stl)])+ h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--out", str(out_glb)])+ assert h.inspect_stl(out_stl)["triangles"] > 0+ assert out_glb.read_bytes()[:4] == b"glTF"++[email protected]_case(id="T1-18-5", tier=1, feature_id="#18", title="orient --json reports structured orientation metrics", requires=("forma_print",))+def t1_18_5() -> None:+ _, data = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma")])+ blob = json.dumps(data).lower()+ assert any(k in blob for k in ("score", "overhang", "rotation", "matrix", "euler", "bed"))+++# ===========================================================================+# #19: R6.7 mm-scaled Deflate .3mf & .step export (5 tests)+# ===========================================================================+[email protected]_case(id="T1-19-1", tier=1, feature_id="#19", title="Exported .3mf is valid PKZIP Deflate (compress_type==8)", requires=("forma_print",))+def t1_19_1() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "part.3mf"+ h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--out", str(out)])+ info = h.inspect_3mf(out)+ assert info["total_compressed"] < info["total_uncompressed"]++[email protected]_case(id="T1-19-2", tier=1, feature_id="#19", title=".3mf contains [Content_Types].xml, _rels/.rels, 3D/3dmodel.model", requires=("forma_print",))+def t1_19_2() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "part.3mf"+ h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--out", str(out)])+ info = h.inspect_3mf(out)+ for req in ("[Content_Types].xml", "_rels/.rels", "3D/3dmodel.model"):+ assert req in info["entries"]++[email protected]_case(id="T1-19-3", tier=1, feature_id="#19", title="3D/3dmodel.model has unit='millimeter' and mm vertex coords", requires=("forma_print",))+def t1_19_3() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "part.3mf"+ h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--out", str(out)])+ info = h.inspect_3mf(out)+ 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]))++[email protected]_case(id="T1-19-4", tier=1, feature_id="#19", title=".3mf contains slicer Metadata configs & 256x256 plate_1.png", requires=("forma_print",))+def t1_19_4() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "part.3mf"+ h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--out", str(out)])+ info = h.inspect_3mf(out)+ assert info["thumbnail"]["width"] == 256 and info["thumbnail"]["height"] == 256+ assert "filament_colour" in info["project_settings"]+ assert "filament_type" in info["project_settings"]++[email protected]_case(id="T1-19-5", tier=1, feature_id="#19", title="Exported .step has ISO-10303-21, SI_UNIT(.MILLI.,.METRE.), and mm coords", requires=("forma_print",))+def t1_19_5() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "part.step"+ h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--out", str(out)])+ info = h.inspect_step(out)+ assert info["has_automotive_design"]+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(info["size"]), [20.0, 30.0, 40.0]))+++# ===========================================================================+# #20: R6.8 Library, CLI & opt-in --mcp surface (5 tests)+# ===========================================================================+[email protected]_case(id="T1-20-1", tier=1, feature_id="#20", title="forma-print --mcp initialize + ping succeed", requires=("forma_print",))+def t1_20_1() -> None:+ bin_path = h.require_forma_print()+ with h.McpClient([str(bin_path), "--mcp"]) as mcp:+ init = mcp.initialize()+ assert "protocolVersion" in init+ pong = mcp.ping()+ assert isinstance(pong, dict)++[email protected]_case(id="T1-20-2", tier=1, feature_id="#20", title="forma-print --mcp tools/list exposes 4 expected tools", requires=("forma_print",))+def t1_20_2() -> None:+ bin_path = h.require_forma_print()+ with h.McpClient([str(bin_path), "--mcp"]) as mcp:+ mcp.initialize()+ tools = mcp.tools_list()+ names = {t["name"] for t in tools}+ assert {"print_check", "print_prep", "print_export", "print_profiles"}.issubset(names), f"Got tools: {names}"++[email protected]_case(id="T1-20-3", tier=1, feature_id="#20", title="MCP print_profiles returns printers and materials", requires=("forma_print",))+def t1_20_3() -> None:+ bin_path = h.require_forma_print()+ with h.McpClient([str(bin_path), "--mcp"]) as mcp:+ mcp.initialize()+ res = mcp.tools_call("print_profiles", {})+ assert not res.get("isError"), f"print_profiles errored: {res}"+ text = "\n".join(c.get("text", "") for c in res.get("content", []))+ assert "bambu_x1c" in text and "PLA" in text++[email protected]_case(id="T1-20-4", tier=1, feature_id="#20", title="MCP print_check audits geometry", requires=("forma_print",))+def t1_20_4() -> None:+ bin_path = h.require_forma_print()+ with h.McpClient([str(bin_path), "--mcp"]) as mcp:+ mcp.initialize()+ tools = mcp.tools_list()+ clean_args = h.build_mcp_tool_args(+ tools,+ "print_check",+ input_path=str(h.FIXTURES_DIR / "box_meters.forma"),+ printer="bambu_x1c",+ material="PLA",+ )+ res = mcp.tools_call("print_check", clean_args)+ assert not res.get("isError"), f"print_check errored on clean box: {res}"+ text = "\n".join(c.get("text", "") for c in res.get("content", [])).strip()+ assert text, "print_check returned empty text"++ parsed_clean = None+ try:+ parsed_clean = json.loads(text)+ except json.JSONDecodeError:+ parsed_clean = None++ if isinstance(parsed_clean, dict):+ h.assert_check_clean(parsed_clean, "MCP print_check box_meters")+ sz = h.extract_bbox_size_mm(parsed_clean)+ if sz is not None:+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(sz), [20.0, 30.0, 40.0])), (+ f"Unexpected MCP print_check bbox size: {sz}"+ )+ else:+ blob = json.dumps(parsed_clean).lower()+ dfm_markers = (+ "watertight",+ "manifold",+ "overhang",+ "wall",+ "island",+ "bbox",+ "size",+ "volume",+ "triangle",+ "passed",+ "printable",+ "checks",+ "issues",+ "warnings",+ )+ assert sum(1 for m in dfm_markers if m in blob) >= 2, (+ f"MCP print_check JSON lacks geometry/DFM semantic content: {text[:500]}"+ )+ else:+ low = text.lower()+ geom_hits = sum(+ 1+ for m in ("40", "30", "20", "watertight", "overhang", "wall", "bbox", "size", "volume", "pass")+ if m in low+ )+ assert geom_hits >= 2, f"MCP print_check text lacks geometry/DFM semantic content: {text[:500]}"++ bad_args = h.build_mcp_tool_args(+ tools,+ "print_check",+ input_path=str(h.FIXTURES_DIR / "oversized_part.forma"),+ printer="bambu_x1c",+ material="PLA",+ )+ bad_res = mcp.tools_call("print_check", bad_args)+ bad_text = "\n".join(c.get("text", "") for c in bad_res.get("content", [])).strip()+ assert not bad_res.get("isError"), (+ f"MCP print_check returned unexpected tool error on oversized_part: {bad_text}"+ )+ assert bad_text, "print_check returned empty text on oversized_part"+ try:+ parsed_bad = json.loads(bad_text)+ except json.JSONDecodeError as exc:+ raise AssertionError(+ f"MCP print_check did not return valid JSON on oversized_part: {bad_text[:500]}"+ ) from exc+ assert isinstance(parsed_bad, dict), (+ f"Expected JSON object from MCP print_check on oversized_part, got {type(parsed_bad).__name__}"+ )+ h.assert_check_flags(+ parsed_bad,+ ("volume", "bound", "fit", "size", "exceed", "dimension", "build", "400"),+ "MCP print_check oversized_part",+ )++[email protected]_case(id="T1-20-5", tier=1, feature_id="#20", title="MCP print_prep + print_export produce valid .3mf", requires=("forma_print",))+def t1_20_5() -> None:+ bin_path = h.require_forma_print()+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "mcp_out.3mf"+ with h.McpClient([str(bin_path), "--mcp"]) as mcp:+ mcp.initialize()+ tools = mcp.tools_list()+ prep_args = h.build_mcp_tool_args(+ tools,+ "print_prep",+ input_path=str(h.FIXTURES_DIR / "upside_down_t.forma"),+ printer="bambu_x1c",+ )+ prep = mcp.tools_call("print_prep", prep_args)+ assert not prep.get("isError"), f"print_prep errored: {prep}"+ exp_args = h.build_mcp_tool_args(+ tools,+ "print_export",+ input_path=str(h.FIXTURES_DIR / "upside_down_t.forma"),+ out_path=str(out),+ printer="bambu_x1c",+ orient=True,+ )+ exp = mcp.tools_call("print_export", exp_args)+ assert not exp.get("isError"), f"print_export errored: {exp}"+ info = h.inspect_3mf(out)+ assert info["unit"] == "millimeter"diff --git a/tests/e2e/test_tier2_boundaries.py b/tests/e2e/test_tier2_boundaries.pynew file mode 100644index 0000000..8b62801--- /dev/null+++ b/tests/e2e/test_tier2_boundaries.py@@ -0,0 +1,1512 @@+"""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)+# ===========================================================================+[email protected]_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}"++[email protected]_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}"++[email protected]_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}"++[email protected]_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')}"++[email protected]_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)+# ===========================================================================+[email protected]_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}"++[email protected]_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}"++[email protected]_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++[email protected]_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')}"+ )++[email protected]_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)+# ===========================================================================+[email protected]_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')}"+ )++[email protected]_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')}"+ )++[email protected]_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)++[email protected]_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++[email protected]_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)+# ===========================================================================+[email protected]_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"))++[email protected]_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"))++[email protected]_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)++[email protected]_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++[email protected]_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)+# ===========================================================================+[email protected]_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"))++[email protected]_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)++[email protected]_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"))++[email protected]_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)++[email protected]_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)+# ===========================================================================+[email protected]_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++[email protected]_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"))++[email protected]_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++[email protected]_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"++[email protected]_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)+# ===========================================================================+[email protected]_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}"++[email protected]_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}"++[email protected]_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)++[email protected]_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}]")++[email protected]_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)+# ===========================================================================+[email protected]_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}"++[email protected]_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}"++[email protected]_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"++[email protected]_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}"++[email protected]_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)+# ===========================================================================+[email protected]_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++[email protected]_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"++[email protected]_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}"++[email protected]_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)++[email protected]_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)+# ===========================================================================+[email protected]_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)++[email protected]_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)++[email protected]_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)++[email protected]_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)++[email protected]_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)+# ===========================================================================+[email protected]_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"+ )++[email protected]_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++[email protected]_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"++[email protected]_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}"++[email protected]_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)+# ===========================================================================+[email protected]_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}"++[email protected]_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]}"++[email protected]_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']}"++[email protected]_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}"++[email protected]_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)+# ===========================================================================+[email protected]_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}"++[email protected]_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++[email protected]_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++[email protected]_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++[email protected]_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)+# ===========================================================================+[email protected]_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++[email protected]_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++[email protected]_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++[email protected]_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++[email protected]_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)+# ===========================================================================+[email protected]_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")++[email protected]_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")++[email protected]_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")++[email protected]_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")++[email protected]_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)+# ===========================================================================+[email protected]_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++[email protected]_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}"++[email protected]_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++[email protected]_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()++[email protected]_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)+# ===========================================================================+[email protected]_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++[email protected]_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")++[email protected]_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++[email protected]_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++[email protected]_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)+# ===========================================================================+[email protected]_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++[email protected]_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++[email protected]_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++[email protected]_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++[email protected]_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)+# ===========================================================================+[email protected]_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() == {}++[email protected]_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() == {}++[email protected]_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() == {}++[email protected]_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}"++[email protected]_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()diff --git a/tests/e2e/test_tier3_cross_feature.py b/tests/e2e/test_tier3_cross_feature.pynew file mode 100644index 0000000..8f6a6ce--- /dev/null+++ b/tests/e2e/test_tier3_cross_feature.py@@ -0,0 +1,921 @@+"""Tier 3 E2E Tests: Cross-Feature End-to-End Workflows (20 tests)."""++from __future__ import annotations++import json+import pathlib+import re+import shutil+import sqlite3+import struct+import xml.etree.ElementTree as ET+import zipfile+import zlib+from typing import Any++import helpers as h+++def _query_rag_json(+ query: str,+ *,+ domain: str | None = None,+ top_k: int = 5,+ db_path: pathlib.Path | None = None,+) -> dict[str, Any]:+ script = h.require_research_file("rag/query_rag.py")+ help_text = h.run_cmd(["python3", str(script), "--help"]).stdout.lower()+ assert "--json" in help_text, "query_rag.py must support --json"+ 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:+ assert "--domain" in help_text, "query_rag.py must support --domain"+ cmd.extend(["--domain", domain])+ if "--top-k" in help_text:+ cmd.extend(["--top-k", str(top_k)])+ if db_path is not None:+ assert "--db" in help_text, "query_rag.py must support --db"+ cmd.extend(["--db", str(db_path)])+ cmd.append("--json")+ proc = h.run_cmd(cmd)+ assert proc.returncode == 0, f"query_rag.py failed: {proc.stdout}\n{proc.stderr}"+ raw = proc.stdout.strip()+ assert raw, f"query_rag.py returned empty output for query={query!r}"+ try:+ payload = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise AssertionError(f"query_rag.py did not emit valid JSON: {raw[:300]!r}") from exc+ assert isinstance(payload, dict), f"Expected JSON object from query_rag.py, got {type(payload).__name__}"+ return payload+++def _assert_rag_results(+ query: str,+ *,+ domain: str | None = None,+ top_k: int = 5,+ db_path: pathlib.Path | None = None,+ all_in_domain: str | None = None,+ expected_domains: set[str] | None = None,+ required_entities: set[str] | None = None,+ any_entities: set[str] | None = None,+ all_keywords: tuple[str, ...] = (),+) -> list[dict[str, Any]]:+ payload = _query_rag_json(query, domain=domain, top_k=top_k, db_path=db_path)+ results = payload.get("results")+ assert isinstance(results, list), f"Expected 'results' list, got {type(results).__name__}: {payload!r}"+ assert 1 <= len(results) <= top_k, f"Expected 1..{top_k} results for {query!r}, got {len(results)}"++ for idx, r in enumerate(results):+ assert isinstance(r, dict), f"Result[{idx}] is not a dict: {r!r}"+ for field in ("chunk_id", "domain", "entity_id", "section", "snippet"):+ val = r.get(field)+ assert isinstance(val, str) and val.strip(), f"Result[{idx}] missing non-empty {field!r}: {r!r}"+ src_url = r.get("source_url", "")+ assert h.is_valid_http_url(src_url), f"Result[{idx}] invalid source_url {src_url!r}: {r!r}"++ domains = {r["domain"] for r in results}+ entities = {r["entity_id"] for r in results}++ if all_in_domain is not None:+ assert domains == {all_in_domain}, f"Expected all results in domain={all_in_domain!r}, got {domains}"+ if expected_domains is not None:+ assert expected_domains.issubset(domains), (+ f"Expected domains {sorted(expected_domains)} in results, got {sorted(domains)}"+ )+ if required_entities is not None:+ assert required_entities.issubset(entities), (+ f"Expected entities {sorted(required_entities)} in results, got {sorted(entities)}"+ )+ if any_entities is not None:+ assert any_entities & entities, (+ f"Expected at least one of {sorted(any_entities)} in results, got {sorted(entities)}"+ )++ if all_keywords:+ # Check ONLY payload["results"], never outer payload["query"] / payload["filters"].+ results_blob = json.dumps(results, ensure_ascii=False).lower()+ missing_kw = [kw for kw in all_keywords if kw.lower() not in results_blob]+ assert not missing_kw, f"Keywords {missing_kw} missing from RAG results for {query!r}: {results_blob[:600]}"++ return results+++def _paeth_predictor(a: int, b: int, c: int) -> int:+ p = a + b - c+ pa = abs(p - a)+ pb = abs(p - b)+ pc = abs(p - c)+ if pa <= pb and pa <= pc:+ return a+ if pb <= pc:+ return b+ return c+++def _count_png_red_pixels(path: pathlib.Path) -> int:+ h.inspect_png(path)+ data = path.read_bytes()+ pos = 8+ w = 0+ ht = 0+ ct = 0+ idat_parts: list[bytes] = []+ while pos < len(data):+ length, ctype_b = struct.unpack(">I4s", data[pos : pos + 8])+ payload = data[pos + 8 : pos + 8 + length]+ pos += 12 + length+ if ctype_b == b"IHDR":+ w, ht, bd, ct, comp, filt, interlace = struct.unpack(">IIBBBBB", payload)+ assert bd == 8 and comp == 0 and filt == 0 and interlace == 0+ elif ctype_b == b"IDAT":+ idat_parts.append(payload)+ elif ctype_b == b"IEND":+ break+ assert ct in (2, 6), f"Expected RGB/RGBA PNG (color_type 2 or 6), got {ct}"+ bpp = 3 if ct == 2 else 4+ stride = w * bpp+ raw = zlib.decompress(b"".join(idat_parts))+ assert len(raw) == ht * (1 + stride)++ prev = bytearray(stride)+ idx = 0+ red_count = 0+ for _ in range(ht):+ ftype = raw[idx]+ idx += 1+ scan = bytearray(raw[idx : idx + stride])+ idx += stride+ if ftype == 1:+ for i in range(bpp, stride):+ scan[i] = (scan[i] + scan[i - bpp]) & 0xFF+ elif ftype == 2:+ for i in range(stride):+ scan[i] = (scan[i] + prev[i]) & 0xFF+ elif ftype == 3:+ for i in range(stride):+ left = scan[i - bpp] if i >= bpp else 0+ scan[i] = (scan[i] + ((left + prev[i]) >> 1)) & 0xFF+ elif ftype == 4:+ for i in range(stride):+ left = scan[i - bpp] if i >= bpp else 0+ up = prev[i]+ ul = prev[i - bpp] if i >= bpp else 0+ scan[i] = (scan[i] + _paeth_predictor(left, up, ul)) & 0xFF+ for x in range(0, stride, bpp):+ r, g, b = scan[x], scan[x + 1], scan[x + 2]+ if r > g + 40 and r > b + 40:+ red_count += 1+ prev = scan+ return red_count+++_IDENTITY_MAT: tuple[float, ...] = (+ 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_3mf_mat(attr: str | None) -> tuple[float, ...]:+ if not attr or not attr.strip():+ return _IDENTITY_MAT+ parts = [float(x) for x in attr.strip().split()]+ assert len(parts) == 12, f"Expected 12-float 3MF matrix, got {attr!r}"+ return tuple(parts)+++def _compose_3mf_mat(local_m: tuple[float, ...], parent_m: tuple[float, ...]) -> tuple[float, ...]:+ a = (+ (local_m[0], local_m[1], local_m[2], 0.0),+ (local_m[3], local_m[4], local_m[5], 0.0),+ (local_m[6], local_m[7], local_m[8], 0.0),+ (local_m[9], local_m[10], local_m[11], 1.0),+ )+ b = (+ (parent_m[0], parent_m[1], parent_m[2], 0.0),+ (parent_m[3], parent_m[4], parent_m[5], 0.0),+ (parent_m[6], parent_m[7], parent_m[8], 0.0),+ (parent_m[9], parent_m[10], parent_m[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_3mf_mat(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],+ )+++def _extract_3mf_world_vertices(path: pathlib.Path) -> list[tuple[float, float, float]]:+ with zipfile.ZipFile(path, "r") as zf:+ root = ET.fromstring(zf.read("3D/3dmodel.model").decode("utf-8"))+ objects_by_id: dict[str, dict[str, Any]] = {}+ build_items: list[tuple[str, tuple[float, ...]]] = []+ for el in root.iter():+ tag = el.tag.split("}")[-1]+ if tag == "object":+ oid = el.attrib.get("id")+ if oid:+ verts = [+ (float(sub.attrib["x"]), float(sub.attrib["y"]), float(sub.attrib["z"]))+ for sub in el.iter()+ if sub.tag.split("}")[-1] == "vertex"+ ]+ comps = [+ (sub.attrib["objectid"], _parse_3mf_mat(sub.attrib.get("transform")))+ for sub in el.iter()+ if sub.tag.split("}")[-1] == "component" and sub.attrib.get("objectid")+ ]+ objects_by_id[oid] = {"vertices": verts, "components": comps}+ elif tag == "item":+ oid = el.attrib.get("objectid")+ if oid:+ build_items.append((oid, _parse_3mf_mat(el.attrib.get("transform"))))++ world_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 objects_by_id:+ return+ seen.add(oid)+ obj = objects_by_id[oid]+ for pt in obj["vertices"]:+ world_pts.append(_apply_3mf_mat(mat, pt))+ for child_oid, comp_mat in obj["components"]:+ _walk(child_oid, _compose_3mf_mat(comp_mat, mat), seen)+ seen.remove(oid)++ for oid, item_mat in build_items:+ _walk(oid, item_mat, set())+ assert world_pts, f"No world vertices extracted from {path}"+ return world_pts+++def _parse_mcp_json_result(resp: dict[str, Any], label: str) -> Any:+ assert not resp.get("isError"), f"{label} returned isError=true: {resp}"+ content = resp.get("content")+ assert isinstance(content, list) and content, f"{label} missing content list: {resp}"+ item = content[0]+ assert isinstance(item, dict) and item.get("type") == "text", f"{label} content[0] not text: {item}"+ text = item.get("text")+ assert isinstance(text, str) and text.strip(), f"{label} content[0].text empty: {item}"+ try:+ return json.loads(text)+ except json.JSONDecodeError as exc:+ raise AssertionError(f"{label} content[0].text is not valid JSON: {text[:300]!r}") from exc++[email protected]_case(id="T3-01", tier=3, feature_id="#2", title="RAG query for slicer 3MF metadata cross-checked against exported .3mf", requires=("research", "forma_print"))+def t3_01() -> None:+ _assert_rag_results(+ "OrcaSlicer PrusaSlicer 3mf model_settings.config Slic3r_PE_model.config",+ domain="software",+ top_k=5,+ all_in_domain="software",+ any_entities={"orcaslicer", "prusaslicer"},+ all_keywords=("model_settings.config", "slic3r_pe_model.config", "3mf"),+ )+ with h.temp_dir() as td:+ out_3mf = pathlib.Path(td) / "cross.3mf"+ _, exp_json = h.run_forma_print_json(+ ["export", str(h.FIXTURES_DIR / "multi_color_ams.forma"), "--out", str(out_3mf)]+ )+ assert exp_json.get("ok") is True+ info = h.inspect_3mf(out_3mf)+ assert info["basematerials"] >= 1 or info["colorgroups"] >= 1+ assert "Metadata/model_settings.config" in info["entries"]+ assert "Metadata/Slic3r_PE_model.config" in info["entries"]++[email protected]_case(id="T3-02", tier=3, feature_id="#3", title="RAG query for mesh analysis libraries cross-checked against forma-print check", requires=("research", "forma_print"))+def t3_02() -> None:+ _assert_rag_results(+ "Manifold lib3mf trimesh watertight mesh repair",+ domain="software",+ top_k=5,+ all_in_domain="software",+ any_entities={"manifold", "lib3mf", "trimesh"},+ all_keywords=("watertight",),+ )+ _, rep = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", "bambu_x1c"])+ h.assert_check_clean(rep, "box_meters check")+ assert rep.get("printer_id") == "bambu_x1c"+ sz = h.extract_bbox_size_mm(rep)+ assert sz is not None+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(sz), [20.0, 30.0, 40.0]))++[email protected]_case(id="T3-03", tier=3, feature_id="#4", title="RAG query for Moonraker/OctoPrint upload API & LAN auth workflow", requires=("research",))+def t3_03() -> None:+ _assert_rag_results(+ "Moonraker OctoPrint file upload HTTP API key LAN",+ domain="software",+ top_k=5,+ all_in_domain="software",+ required_entities={"moonraker", "octoprint"},+ all_keywords=("http", "rest", "api", "x-api-key", "push"),+ )++[email protected]_case(id="T3-04", tier=3, feature_id="#5", title="RAG query linking Klipper firmware to Voron profile & check", requires=("research", "forma_print"))+def t3_04() -> None:+ _assert_rag_results(+ "Klipper CoreXY kinematics Voron",+ top_k=5,+ required_entities={"klipper", "voron_design"},+ )+ _, prof = h.run_forma_print_json(["profiles", "--tech", "fdm"])+ ids = {h.printer_id_of(p) for p in h.extract_printers(prof)}+ assert "voron_24_300" in ids+ _, rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", "voron_24_300", "--material", "ABS"]+ )+ h.assert_check_clean(rep, "voron_24_300 + ABS")+ assert rep.get("printer_id") == "voron_24_300"+ assert rep.get("material_id") == "ABS"++[email protected]_case(id="T3-05", tier=3, feature_id="#6", title="RAG query comparing programmatic CAD (BOSL2/CadQuery) to Forma-Pipe + forma-print", requires=("research", "forma_print"))+def t3_05() -> None:+ _assert_rag_results(+ "CadQuery BOSL2 OpenSCAD programmatic CAD 3D printing",+ domain="software",+ top_k=5,+ all_in_domain="software",+ any_entities={"cadquery", "bosl2", "openscad"},+ )+ with h.temp_dir() as td:+ step = pathlib.Path(td) / "cad.step"+ _, exp_json = h.run_forma_print_json(+ ["export", str(h.FIXTURES_DIR / "functional_bracket.forma"), "--out", str(step)]+ )+ assert exp_json.get("ok") is True+ step_info = h.inspect_step(step)+ assert step_info["cartesian_points"] > 0+ assert step_info["has_automotive_design"] is True+ assert all(dim > 10.0 for dim in step_info["size"])++[email protected]_case(id="T3-06", tier=3, feature_id="#7", title="RAG query for nurb checks.py / printers.toml retrieves software & report context", requires=("research",))+def t3_06() -> None:+ report = h.require_research_file("reports/nurb_inspection.md").read_text(encoding="utf-8").lower()+ assert "checks.py" in report and ("printers.toml" in report or "printer.toml" in report)+ _assert_rag_results(+ "nurb checks.py printers.toml",+ top_k=5,+ expected_domains={"report", "software"},+ required_entities={"nurb_inspection", "nurb"},+ all_keywords=("checks.py", "printers.toml"),+ )++[email protected]_case(id="T3-07", tier=3, feature_id="#8", title="Cross-check manufacturer protocols/sensors (Bambu LAN, PrusaLink, Klipper/Moonraker) in RAG", requires=("research",))+def t3_07() -> None:+ _assert_rag_results(+ "Bambu Lab LAN developer mode MQTT FTPS",+ domain="manufacturer",+ top_k=5,+ all_in_domain="manufacturer",+ required_entities={"bambu_lab"},+ all_keywords=("mqtt", "ftps"),+ )+ _assert_rag_results(+ "PrusaLink Prusa Connect telemetry sensor",+ domain="manufacturer",+ top_k=5,+ all_in_domain="manufacturer",+ required_entities={"prusa_research"},+ all_keywords=("prusalink", "prusa connect"),+ )+ _assert_rag_results(+ "Voron Klipper Moonraker telemetry sensor",+ domain="manufacturer",+ top_k=5,+ all_in_domain="manufacturer",+ required_entities={"voron_design"},+ all_keywords=("klipper", "moonraker"),+ )++[email protected]_case(id="T3-08", tier=3, feature_id="#9", title="RAG academic papers for overhang + floating island + wall thickness align with DFM audit", requires=("research", "forma_print"))+def t3_08() -> None:+ results = _assert_rag_results(+ "overhang angle support minimization thin wall thickness",+ domain="paper",+ top_k=5,+ all_in_domain="paper",+ any_entities={+ "vanek-2014-clever-support",+ "gaynor-2016-overhang-topology",+ "wu-2016-rhombic-infill",+ "wang-2013-skin-frame",+ "dumas-2014-bridging-the-gap",+ "telea-2011-voxel-printability",+ },+ all_keywords=("overhang", "wall", "support"),+ )+ assert any(+ isinstance(r.get("metadata"), dict)+ and isinstance(r["metadata"].get("doi_or_arxiv_id"), str)+ and (+ r["metadata"]["doi_or_arxiv_id"].strip().startswith("10.")+ or "arxiv" in r["metadata"]["doi_or_arxiv_id"].lower()+ )+ for r in results+ ), f"Expected valid DOI/arXiv metadata in paper RAG results: {results!r}"+ proc, rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "thin_wall.forma"), "--printer", "bambu_x1c"],+ allow_nonzero=True,+ )+ assert proc.returncode == 3+ assert rep.get("printable") is False+ assert rep.get("checks", {}).get("wall_thickness") == "fail"+ h.assert_check_flags(rep, ("thin", "wall", "thickness"), "thin_wall")++[email protected]_case(id="T3-09", tier=3, feature_id="#10", title="Full build_rag.py -> query_rag.py pipeline into isolated temp SQLite across 3 domains", requires=("research",))+def t3_09() -> 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:+ td_p = pathlib.Path(td)+ tmp_db = td_p / "isolated.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:+ copy_r = td_p / "research"+ shutil.copytree(build_script.parents[1], 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+ assert tmp_db.is_file() and tmp_db.stat().st_size > 0++ conn = sqlite3.connect(str(tmp_db))+ try:+ chunks_count = conn.execute("SELECT COUNT(*) FROM chunks").fetchone()[0]+ fts_count = conn.execute("SELECT COUNT(*) FROM chunks_fts").fetchone()[0]+ finally:+ conn.close()+ assert chunks_count >= 400 and chunks_count == fts_count, (+ f"Expected chunks == chunks_fts >= 400, got chunks={chunks_count}, fts={fts_count}"+ )++ _assert_rag_results(+ "OrcaSlicer",+ domain="software",+ top_k=3,+ db_path=tmp_db,+ all_in_domain="software",+ required_entities={"orcaslicer"},+ )+ _assert_rag_results(+ "Bambu Lab",+ domain="manufacturer",+ top_k=3,+ db_path=tmp_db,+ all_in_domain="manufacturer",+ required_entities={"bambu_lab"},+ )+ _assert_rag_results(+ "overhang",+ domain="paper",+ top_k=3,+ db_path=tmp_db,+ all_in_domain="paper",+ )++ # Prove query_rag.py genuinely honors --db rather than falling back to the repo DB+ empty_db = td_p / "empty_zero_row.sqlite"+ econn = sqlite3.connect(str(empty_db))+ try:+ econn.executescript(+ """+ CREATE TABLE chunks (+ chunk_id TEXT PRIMARY KEY,+ domain TEXT NOT NULL,+ entity_id TEXT NOT NULL,+ title TEXT NOT NULL,+ section TEXT NOT NULL,+ tags_text TEXT NOT NULL,+ text TEXT NOT NULL,+ source_url TEXT NOT NULL,+ category TEXT NOT NULL,+ manufacturer TEXT,+ tech_json TEXT NOT NULL,+ protocol_json TEXT NOT NULL,+ fault_prefix_json TEXT NOT NULL,+ tags_json TEXT NOT NULL,+ metadata_json TEXT NOT NULL,+ token_count INTEGER NOT NULL,+ tfidf_json TEXT NOT NULL,+ tfidf_norm REAL NOT NULL,+ content_hash TEXT NOT NULL+ );+ CREATE VIRTUAL TABLE chunks_fts USING fts5(+ title, section, entity_id, tags_text, text,+ content='chunks', content_rowid='rowid', tokenize='porter unicode61'+ );+ CREATE TABLE vocab_idf (+ term_id INTEGER PRIMARY KEY,+ term TEXT UNIQUE NOT NULL,+ df INTEGER NOT NULL,+ idf REAL NOT NULL+ );+ CREATE TABLE kb_manifest (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+ );+ """+ )+ finally:+ econn.close()+ empty_payload = _query_rag_json("OrcaSlicer", top_k=5, db_path=empty_db)+ assert empty_payload["results"] == []+ assert empty_payload["total_candidates"] == 0++[email protected]_case(id="T3-10", tier=3, feature_id="#11", title="validate_kb.py passes end-to-end after fresh temp DB build", requires=("research",))+def t3_10() -> None:+ val_script = h.require_research_file("scripts/validate_kb.py")+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ copy_r = td_p / "research"+ shutil.copytree(val_script.parents[1], copy_r)+ for root_file in ("Cargo.toml", "package.json", ".gitignore"):+ shutil.copy2(h.REPO_ROOT / root_file, td_p / root_file)+ db_file = copy_r / "rag" / "forma_print_kb.sqlite"+ if db_file.exists():+ db_file.unlink()+ assert not db_file.exists()++ build_proc = h.run_cmd(["python3", str(copy_r / "rag" / "build_rag.py")])+ assert build_proc.returncode == 0, f"build_rag.py failed: {build_proc.stdout}\n{build_proc.stderr}"+ assert db_file.is_file() and db_file.stat().st_size > 0++ val_proc = h.run_cmd(["python3", str(copy_r / "scripts" / "validate_kb.py"), "--json"])+ assert val_proc.returncode == 0, f"validate_kb failed after rebuild: {val_proc.stdout}\n{val_proc.stderr}"+ report = json.loads(val_proc.stdout)+ assert report["status"] == "pass"+ assert report["errors"] == []+ checks = {c["name"]: c for c in report["checks"]}+ expected_stages = (+ "stage1_schemas",+ "stage2_corpus",+ "stage3_secrets",+ "stage4_rag_db_and_isolation",+ "stage5_rag_retrieval",+ )+ for stage in expected_stages:+ assert stage in checks, f"Missing stage {stage!r} in validate_kb.py output: {list(checks)}"+ assert checks[stage]["passed"] is True, f"Stage {stage!r} failed: {checks[stage]}"++[email protected]_case(id="T3-11", tier=3, feature_id="#12", title="bench_efficiency.py metrics align with efficiency_justification.md", requires=("research",))+def t3_11() -> None:+ doc = h.require_research_file("analysis/efficiency_justification.md").read_text(encoding="utf-8")+ bench = h.require_research_file("scripts/bench_efficiency.py")+ proc = h.run_cmd(["python3", str(bench), "--runs", "3", "--rag-runs", "3", "--json"], timeout=120.0)+ assert proc.returncode == 0, f"bench_efficiency.py failed: {proc.stdout}\n{proc.stderr}"+ assert "Fable" in doc and "token" in doc.lower()++ data = json.loads(proc.stdout)+ bytes_map = data["artifacts"]["bytes"]+ assert bytes_map["forma"] == 1818160 and "1,818,160" in doc+ assert bytes_map["forma_mcp"] == 1775040 and "1,775,040" in doc+ assert bytes_map["forma_wasm"] == 786102 and "786,102" in doc+ assert bytes_map["rag_sqlite"] == 1802240 and "1,802,240" in doc++ iso = data["artifacts"]["workspace_isolation"]+ assert isinstance(iso, dict) and iso and all(v is True for v in iso.values()), f"Workspace isolation failed: {iso}"++ mcp_data = data["mcp"]+ assert mcp_data["core_forma_mcp"]["tools_compact_o200k_tokens"] == 788 and "788" in doc+ assert mcp_data["opt_in_forma_print_mcp"]["tools_compact_o200k_tokens"] == 391 and "391" in doc+ assert mcp_data["combined_tools_compact_o200k_tokens"] == 1179 and "1,179" in doc++ totals = data["rag_benchmarks"]["corpus_totals"]+ assert totals["total_chunks"] == 448 and "448" in doc+ assert totals["citations"]["total_records"] == 130 and "130" in doc+ assert totals["citations"]["unique_primary_source_urls_union"] == 354 and "354" in doc++ top5 = data["rag_benchmarks"]["by_top_k"]["5"]+ assert top5["rank1_hits"] == 18 and top5["queries_total"] == 18 and "18/18" in doc++ cli_b = {item["id"]: item for item in data["cli_benchmarks"]["benchmarks"]}+ assert cli_b["upside_down_t_check_heatmap"]["deterministic"]["volume_cm3"] == 38.88 and "38.88" in doc+ assert cli_b["multi_color_ams_check_heatmap"]["deterministic"]["ams_swaps"] == 2 and "ams_swaps=2" in doc+ assert cli_b["upside_down_t_export_orient_3mf"]["deterministic"]["archive_3mf"]["file_bytes"] == 7509 and "7,509" in doc+ assert cli_b["box_meters_check_heatmap"]["deterministic"]["heatmap_png_bytes"] == 13137 and "13,137" in doc++[email protected]_case(id="T3-12", tier=3, feature_id="#13", title="Full core zero-bloat workflow (cargo test + release build + token count + binary sizes)", requires=("core_baseline",))+def t3_12() -> None:+ cargo_toml = (h.REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")+ dm_match = re.search(r"default-members\s*=\s*\[([^\]]*)\]", cargo_toml, re.DOTALL)+ assert dm_match is not None, "Cargo.toml missing default-members"+ assert "forma-print" not in dm_match.group(1), f"forma-print must not be in default-members: {dm_match.group(1)!r}"++ t_proc = h.run_cmd(["cargo", "test", "--manifest-path", str(h.REPO_ROOT / "Cargo.toml"), "--release"], timeout=180.0)+ assert t_proc.returncode == 0+ b_proc = h.run_cmd(["cargo", "build", "--manifest-path", str(h.REPO_ROOT / "Cargo.toml"), "--release"], timeout=180.0)+ assert b_proc.returncode == 0+ assert h.find_forma_bin().stat().st_size == h.BASELINE_SIZES["forma"]+ assert h.find_forma_mcp_bin().stat().st_size == h.BASELINE_SIZES["forma-mcp"]+ assert (h.REPO_ROOT / "wasm" / "forma.wasm").stat().st_size == h.BASELINE_SIZES["wasm"]+ with h.McpClient([str(h.find_forma_mcp_bin())]) as mcp:+ mcp.initialize()+ tools = mcp.tools_list()+ assert [t.get("name") for t in tools] == ["eval", "inspect", "tx", "export"]+ assert h.count_o200k_tokens(tools) < 800++[email protected]_case(id="T3-13", tier=3, feature_id="#14", title="profiles -> check -> export across FDM, SLA, and SLS technologies", requires=("forma_print",))+def t3_13() -> None:+ masses: list[float] = []+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ for tech, expect_tech, mat, expect_pid in [+ ("fdm", "fdm", "PLA", "bambu_x1c"),+ ("sla", "msla", "RESIN_STD", "elegoo_saturn_4_ultra"),+ ("sls", "sls", "SLS_PA12", "formlabs_fuse_1p"),+ ]:+ _, prof = h.run_forma_print_json(["profiles", "--tech", tech])+ printers = h.extract_printers(prof)+ assert printers and all(h.printer_tech_of(p) == expect_tech for p in printers)+ pids = {h.printer_id_of(p) for p in printers}+ assert expect_pid in pids+ mat_ids = {m["id"] if isinstance(m, dict) else m for m in h.extract_materials(prof)}+ assert mat in mat_ids++ _, chk = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", expect_pid, "--material", mat]+ )+ h.assert_check_clean(chk, f"{expect_pid} + {mat}")+ assert chk.get("printer_id") == expect_pid+ assert chk.get("material_id") == mat+ mass_g = chk.get("stats", {}).get("total_mass_g")+ assert isinstance(mass_g, (int, float)) and mass_g > 0+ masses.append(round(float(mass_g), 3))++ out = td_p / f"{tech}.3mf"+ h.run_forma_print_json(+ ["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", expect_pid, "--material", mat, "--out", str(out)]+ )+ info = h.inspect_3mf(out)+ 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]))+ assert len(set(masses)) == 3, f"Expected distinct masses across PLA/RESIN_STD/SLS_PA12, got {masses}"++[email protected]_case(id="T3-14", tier=3, feature_id="#15", title="box_meters.forma -> check --unit m -> export --unit m -> verify mm coords in .3mf and .step", requires=("forma_print",))+def t3_14() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ _, chk = h.run_forma_print_json(["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--printer", "bambu_x1c"])+ h.assert_check_clean(chk, "box_meters unit m")+ assert chk.get("unit", {}).get("scale_to_mm") == 1000.0+ chk_sz = h.extract_bbox_size_mm(chk)+ assert chk_sz is not None and all(abs(a - b) < 0.5 for a, b in zip(sorted(chk_sz), [20.0, 30.0, 40.0]))+ out_3mf = td_p / "u.3mf"+ out_step = td_p / "u.step"+ h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--out", str(out_3mf)])+ h.run_forma_print_json(["export", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--out", str(out_step)])+ m3 = h.inspect_3mf(out_3mf)+ st = h.inspect_step(out_step)+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(m3["size"]), [20.0, 30.0, 40.0]))+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(st["size"]), [20.0, 30.0, 40.0]))++[email protected]_case(id="T3-15", tier=3, feature_id="#16", title="Combined multi-defect bracket triggers multiple DFM flags cleanly", requires=("forma_print",))+def t3_15() -> None:+ with h.temp_dir() as td:+ bad_script = (+ 'a = box(0.03, 0.03, 0.02, z0=0) | shell(0.0003, open_top=true)\n'+ 'b = cone(0.010, 0.040, 0.020, at=(0.025, 0, 0), z0=0)\n'+ )+ p = pathlib.Path(td) / "multi_defect.forma"+ p.write_text(bad_script, encoding="utf-8")+ proc, rep = h.run_forma_print_json(["check", str(p), "--printer", "bambu_a1_mini"], allow_nonzero=True)+ assert proc.returncode == 3+ assert rep.get("printable") is False+ checks = rep.get("checks", {})+ assert checks.get("wall_thickness") == "fail"+ assert checks.get("clearance") == "fail"+ assert checks.get("overhangs") in ("warn", "fail")+ h.assert_check_flags(rep, ("wall", "thin"), "T3-15 thin wall")+ h.assert_check_flags(rep, ("overhang", "angle"), "T3-15 overhang")+ h.assert_check_flags(rep, ("clear", "collid", "intersect", "overlap"), "T3-15 clearance/collision")++[email protected]_case(id="T3-16", tier=3, feature_id="#17", title="check with both --heatmap and --json on failing overhang bracket", requires=("forma_print",))+def t3_16() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ hm = td_p / "bridge_hm.png"+ proc, rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "unsupported_ceiling.forma"), "--printer", "bambu_a1_mini", "--heatmap", str(hm)],+ allow_nonzero=True,+ )+ assert proc.returncode == 3 and rep.get("printable") is False+ assert "Critical" in rep.get("face_severities", {})+ h.assert_check_flags(rep, ("overhang", "bridge", "ceiling", "support"), "unsupported_ceiling")+ info = h.inspect_png(hm)+ assert info["width"] == info["height"] >= 128 and info["distinct_colors_sampled"] >= 3++ bvc_proc, bvc_rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "bridge_vs_cantilever.forma"), "--printer", "bambu_a1_mini", "--material", "PLA"],+ allow_nonzero=True,+ )+ assert bvc_proc.returncode == 3 and bvc_rep.get("printable") is False+ assert "Bridge" in bvc_rep.get("face_severities", {})+ assert "Critical" in bvc_rep.get("face_severities", {})+ h.assert_check_flags(+ bvc_rep,+ ("overhang", "bridge", "cantilever", "ceiling", "support", "unsupported"),+ "bridge_vs_cantilever",+ )++ # Clean part renders 0 red pixels; failing part with visible Critical faces renders >0 red pixels+ clean_hm = td_p / "clean_hm.png"+ clean_proc, clean_rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", "bambu_x1c", "--heatmap", str(clean_hm)]+ )+ assert clean_proc.returncode == 0 and clean_rep.get("printable") is True+ clean_info = h.inspect_png(clean_hm)+ assert clean_info["width"] == clean_info["height"] >= 128 and clean_info["distinct_colors_sampled"] >= 3+ assert _count_png_red_pixels(clean_hm) == 0++ fail_hm = td_p / "fail_visible_hm.png"+ fail_proc, fail_rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "functional_bracket.forma"), "--printer", "bambu_x1c", "--heatmap", str(fail_hm)],+ allow_nonzero=True,+ )+ assert fail_proc.returncode == 3 and fail_rep.get("printable") is False+ assert "Critical" in fail_rep.get("face_severities", {})+ fail_info = h.inspect_png(fail_hm)+ assert fail_info["width"] == fail_info["height"] >= 128 and fail_info["distinct_colors_sampled"] >= 3+ assert _count_png_red_pixels(fail_hm) > 0++[email protected]_case(id="T3-17", tier=3, feature_id="#18", title="orient upside_down_t -> check oriented mesh -> verify overhang/support issue cleared", requires=("forma_print",))+def t3_17() -> None:+ with h.temp_dir() as td:+ before_proc, before = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--printer", "bambu_x1c"],+ allow_nonzero=True,+ )+ assert before_proc.returncode == 3 and before.get("printable") is False+ h.assert_check_flags(before, ("overhang", "bridge", "ceiling", "support"), "raw upside_down_t")+ oriented = pathlib.Path(td) / "t_fixed.stl"+ _, ori_json = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--out", str(oriented)])+ assert ori_json.get("rotated_from_input") is True+ assert ori_json.get("report", {}).get("printable") is True+ assert abs(h.inspect_stl(oriented)["bbox_min"][2]) < 1e-2++ _, after = h.run_forma_print_json(["check", str(oriented), "--unit", "mm", "--printer", "bambu_x1c"])+ h.assert_check_clean(after, "oriented upside_down_t")+ assert abs(before["stats"]["volume_cm3"] - after["stats"]["volume_cm3"]) < 0.1++[email protected]_case(id="T3-18", tier=3, feature_id="#19", title="Multi-color .forma -> export --orient --out multi.3mf -> full XML/config/thumbnail verification", requires=("forma_print",))+def t3_18() -> None:+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "multi_oriented.3mf"+ _, exp_json = h.run_forma_print_json(+ ["export", str(h.FIXTURES_DIR / "multi_color_ams.forma"), "--printer", "bambu_x1c", "--material", "PLA", "--orient", "--out", str(out)]+ )+ assert exp_json.get("ok") is True and exp_json.get("oriented") is True+ info = h.inspect_3mf(out)+ assert info["unit"] == "millimeter"+ assert abs(info["bbox_min"][2]) < 0.5+ assert info["thumbnail"]["width"] == 256+ assert len(info["project_settings"].get("filament_colour", [])) >= 3+ assert info["basematerials"] >= 1 or info["colorgroups"] >= 1+ assert "extruder" in info["model_settings_xml"].lower()+ assert "extruder" in info["slic3r_pe_xml"].lower()+ assert "printer_id" in info["plate_1"] and "filament_colors" in info["plate_1"]+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(info["size"]), [28.0, 30.0, 30.0]))++[email protected]_case(id="T3-19", tier=3, feature_id="#20", title="Full MCP stateful session: initialize -> print_profiles -> print_check -> print_prep -> print_export", requires=("forma_print",))+def t3_19() -> None:+ bin_path = h.require_forma_print()+ with h.temp_dir() as td:+ out = pathlib.Path(td) / "session.3mf"+ with h.McpClient([str(bin_path), "--mcp"]) as mcp:+ mcp.initialize()+ tools = mcp.tools_list()+ assert len(tools) == 4+ r_prof = mcp.tools_call(+ "print_profiles",+ h.build_mcp_tool_args(tools, "print_profiles", tech="fdm"),+ )+ prof_json = _parse_mcp_json_result(r_prof, "print_profiles")+ printers = h.extract_printers(prof_json)+ assert printers and all(h.printer_tech_of(p) == "fdm" for p in printers)+ assert "bambu_x1c" in {h.printer_id_of(p) for p in printers}++ r_chk = mcp.tools_call(+ "print_check",+ h.build_mcp_tool_args(+ tools,+ "print_check",+ input_path=str(h.FIXTURES_DIR / "upside_down_t.forma"),+ printer="bambu_x1c",+ ),+ )+ chk_json = _parse_mcp_json_result(r_chk, "print_check")+ assert chk_json.get("printable") is False and chk_json.get("printer_id") == "bambu_x1c"+ h.assert_check_flags(chk_json, ("overhang", "bridge", "ceiling", "support"), "mcp print_check")++ r_prep = mcp.tools_call(+ "print_prep",+ h.build_mcp_tool_args(+ tools,+ "print_prep",+ input_path=str(h.FIXTURES_DIR / "upside_down_t.forma"),+ printer="bambu_x1c",+ ),+ )+ prep_json = _parse_mcp_json_result(r_prep, "print_prep")+ assert prep_json.get("rotated_from_input") is True+ assert prep_json.get("report", {}).get("printable") is True+ h.assert_check_clean(prep_json["report"], "mcp print_prep")++ r_exp = mcp.tools_call(+ "print_export",+ h.build_mcp_tool_args(+ tools,+ "print_export",+ input_path=str(h.FIXTURES_DIR / "upside_down_t.forma"),+ out_path=str(out),+ printer="bambu_x1c",+ orient=True,+ ),+ )+ exp_json = _parse_mcp_json_result(r_exp, "print_export")+ assert exp_json.get("ok") is True and exp_json.get("oriented") is True+ assert exp_json.get("bytes") == out.stat().st_size+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(exp_json["size_mm"]), [36.0, 60.0, 60.0]))++ assert h.inspect_3mf(out)["unit"] == "millimeter"+ world_pts = _extract_3mf_world_vertices(out)+ zmin = min(p[2] for p in world_pts)+ assert abs(zmin) < 1e-2+ z0_pts = [p for p in world_pts if abs(p[2] - zmin) < 1e-2]+ assert z0_pts+ span_x = max(p[0] for p in z0_pts) - min(p[0] for p in z0_pts)+ span_y = max(p[1] for p in z0_pts) - min(p[1] for p in z0_pts)+ assert abs(span_x - 60.0) < 0.5 and abs(span_y - 60.0) < 0.5++[email protected]_case(id="T3-20", tier=3, feature_id="#20", title="Full CLI closed-loop: check -> orient -> check -> export .3mf + .step + heatmap", requires=("forma_print",))+def t3_20() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ hm1 = td_p / "before.png"+ hm2 = td_p / "after.png"+ oriented = td_p / "oriented.stl"+ out_3mf = td_p / "final.3mf"+ out_step = td_p / "final.step"+ before_proc, before = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--heatmap", str(hm1)],+ allow_nonzero=True,+ )+ assert before_proc.returncode == 3+ h.assert_check_flags(before, ("overhang", "bridge", "ceiling", "support"), "closed-loop raw check")++ _, ori_json = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / "upside_down_t.forma"), "--out", str(oriented)])+ assert ori_json.get("rotated_from_input") is True++ after_proc, after = h.run_forma_print_json(["check", str(oriented), "--unit", "mm", "--heatmap", str(hm2)])+ assert after_proc.returncode == 0+ h.assert_check_clean(after, "closed-loop oriented check")+ h.run_forma_print_json(["export", str(oriented), "--unit", "mm", "--out", str(out_3mf)])+ h.run_forma_print_json(["export", str(oriented), "--unit", "mm", "--out", str(out_step)])+ assert h.inspect_png(hm1)["width"] >= 128 and h.inspect_png(hm2)["width"] >= 128+ assert hm1.read_bytes() != hm2.read_bytes()+ m3 = h.inspect_3mf(out_3mf)+ st = h.inspect_step(out_step)+ assert m3["unit"] == "millimeter"+ assert abs(m3["bbox_min"][2]) < 1e-2+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(m3["size"]), [36.0, 60.0, 60.0]))+ assert st["cartesian_points"] > 0+ assert abs(st["bbox_min"][2]) < 1e-2+ assert all(abs(a - b) < 0.5 for a, b in zip(sorted(st["size"]), [36.0, 60.0, 60.0]))diff --git a/tests/e2e/test_tier4_scenarios.py b/tests/e2e/test_tier4_scenarios.pynew file mode 100644index 0000000..e48115e--- /dev/null+++ b/tests/e2e/test_tier4_scenarios.py@@ -0,0 +1,633 @@+"""Tier 4 E2E Tests: Stress, Scale, Determinism, Real-World & Zero-Bloat Scenarios (12 tests)."""++from __future__ import annotations++import json+import math+import pathlib+import re+import shutil+import sqlite3+import sys+import time+from typing import Any++import helpers as h++_DOI_RE = re.compile(r"^10\.\d{4,9}/\S+$")+_ARXIV_RE = re.compile(r"^(?:arXiv:)?\d{4}\.\d{4,5}(?:v\d+)?$", re.IGNORECASE)+++def _find_empty_trimmed_strings(obj: Any, path: str = "$") -> list[str]:+ hits: list[str] = []+ if isinstance(obj, str):+ if obj.strip() == "":+ hits.append(path)+ elif isinstance(obj, list):+ for idx, item in enumerate(obj):+ hits.extend(_find_empty_trimmed_strings(item, f"{path}[{idx}]"))+ elif isinstance(obj, dict):+ for k, v in obj.items():+ hits.extend(_find_empty_trimmed_strings(v, f"{path}.{k}"))+ return hits+++def _assert_unique_items(items: Any, context: str) -> None:+ assert isinstance(items, list), f"{context}: expected list, got {type(items).__name__}"+ canonical = [json.dumps(x, sort_keys=True, ensure_ascii=False) for x in items]+ assert len(canonical) == len(set(canonical)), f"{context}: duplicate items violate uniqueItems: {items!r}"+++def _canonical_bench_json(doc: dict[str, Any]) -> dict[str, Any]:+ 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++[email protected]_case(id="T4-01", tier=4, feature_id="#2", title="Full software.jsonl & nurb inspection validation under time bound", requires=("research",))+def t4_01() -> None:+ t0 = time.monotonic()+ schema = json.loads(h.require_research_file("schemas/software.schema.json").read_text(encoding="utf-8"))+ recs = h.load_jsonl(h.require_research_file("corpus/software.jsonl"))+ nurb_report_path = h.require_research_file("reports/nurb_inspection.md")+ assert len(recs) >= 59, f"Expected >= 59 software records, got {len(recs)}"++ seen_ids: set[str] = set()+ by_id: dict[str, dict[str, Any]] = {}+ for idx, rec in enumerate(recs):+ errs = h.validate_json_schema_subset(rec, schema)+ assert not errs, f"software.jsonl #{idx} schema error: {errs}"+ rid = rec["id"]+ assert rid not in seen_ids, f"Duplicate software id {rid!r}"+ seen_ids.add(rid)+ by_id[rid] = rec+ assert rec.get("source_verified") is True, f"software.jsonl #{idx} ({rid}) source_verified is not True"+ empty_strs = _find_empty_trimmed_strings(rec)+ assert not empty_strs, f"software.jsonl #{idx} ({rid}) empty trimmed strings at {empty_strs}"+ _assert_unique_items(rec["source_urls"], f"software[{idx}].source_urls")+ primary_url = rec["repo_or_primary_url"]+ assert not any(ch.isspace() for ch in primary_url) and h.is_valid_http_url(primary_url), (+ f"software.jsonl #{idx} ({rid}) invalid repo_or_primary_url: {primary_url!r}"+ )+ assert all(+ not any(ch.isspace() for ch in u) and h.is_valid_http_url(u)+ for u in rec["source_urls"]+ ), (+ f"software.jsonl #{idx} ({rid}) invalid source_urls: {rec['source_urls']!r}"+ )++ assert "nurb" in by_id, "Missing 'nurb' entry in software.jsonl"+ assert by_id["nurb"]["category"] == "modern_agentic_cad"+ assert by_id["nurb"]["repo_or_primary_url"] == "https://github.com/Shpigford/nurb"++ nurb_text = nurb_report_path.read_text(encoding="utf-8")+ assert len(nurb_text.strip()) >= 5000, f"nurb_inspection.md unexpectedly short: {len(nurb_text)} chars"+ for marker in ("https://github.com/Shpigford/nurb", "checks.py", "printers.toml", "build123d"):+ assert marker in nurb_text, f"nurb_inspection.md missing required marker {marker!r}"++ elapsed = time.monotonic() - t0+ assert elapsed < 2.0, f"Software corpus validation took too long: {elapsed:.2f}s"++[email protected]_case(id="T4-02", tier=4, feature_id="#8", title="100% schema, uniqueItems, DOI/arXiv & URL integrity check across manufacturers & papers", requires=("research",))+def t4_02() -> None:+ m_schema = json.loads(h.require_research_file("schemas/manufacturers.schema.json").read_text(encoding="utf-8"))+ p_schema = json.loads(h.require_research_file("schemas/papers.schema.json").read_text(encoding="utf-8"))+ mans = h.load_jsonl(h.require_research_file("corpus/manufacturers.jsonl"))+ papers = h.load_jsonl(h.require_research_file("corpus/papers.jsonl"))+ assert len(mans) >= 22, f"Expected >= 22 manufacturers, got {len(mans)}"+ assert len(papers) >= 49, f"Expected >= 49 papers, got {len(papers)}"++ seen_ids: set[str] = set()+ for idx, rec in enumerate(mans):+ errs = h.validate_json_schema_subset(rec, m_schema)+ assert not errs, f"Manufacturer #{idx} failed schema: {errs}"+ rid = rec["id"]+ assert rid not in seen_ids, f"Duplicate manufacturer id {rid!r}"+ seen_ids.add(rid)+ assert rec.get("source_verified") is True, f"Manufacturer #{idx} ({rid}) source_verified is not True"+ empty_strs = _find_empty_trimmed_strings(rec)+ assert not empty_strs, f"Manufacturer #{idx} ({rid}) empty trimmed strings at {empty_strs}"+ _assert_unique_items(rec["technologies"], f"manufacturer[{idx}].technologies")+ _assert_unique_items(rec["representative_models"], f"manufacturer[{idx}].representative_models")+ _assert_unique_items(rec["source_urls"], f"manufacturer[{idx}].source_urls")+ _assert_unique_items(+ rec["troubleshooting_and_faults"]["official_kb_urls"],+ f"manufacturer[{idx}].troubleshooting_and_faults.official_kb_urls",+ )+ urls = h.extract_urls_from_record(rec)+ assert urls and all(h.is_valid_http_url(u) for u in urls), (+ f"Manufacturer #{idx} ({rid}) invalid URLs: {urls!r}"+ )+ mfr_urls = (+ list(rec["source_urls"])+ + list(rec["troubleshooting_and_faults"]["official_kb_urls"])+ + [fc["kb_url"] for fc in rec["troubleshooting_and_faults"]["example_fault_codes"]]+ )+ assert mfr_urls and all(+ not any(ch.isspace() for ch in u) and h.is_valid_http_url(u) for u in mfr_urls+ ), f"Manufacturer #{idx} ({rid}) invalid URL fields: {mfr_urls!r}"++ for idx, rec in enumerate(papers):+ errs = h.validate_json_schema_subset(rec, p_schema)+ assert not errs, f"Paper #{idx} failed schema: {errs}"+ rid = rec["id"]+ assert rid not in seen_ids, f"Duplicate/colliding paper id {rid!r}"+ seen_ids.add(rid)+ assert rec.get("source_verified") is True, f"Paper #{idx} ({rid}) source_verified is not True"+ empty_strs = _find_empty_trimmed_strings(rec)+ assert not empty_strs, f"Paper #{idx} ({rid}) empty trimmed strings at {empty_strs}"+ paper_url = str(rec.get("url", ""))+ assert not any(ch.isspace() for ch in paper_url) and h.is_valid_http_url(paper_url), (+ f"Paper #{idx} ({rid}) invalid url: {paper_url!r}"+ )+ cite = str(rec.get("doi_or_arxiv_id", ""))+ assert _DOI_RE.match(cite) or _ARXIV_RE.match(cite), f"Paper #{idx} ({rid}) invalid DOI/arXiv id: {cite!r}"+ clean_cite = cite.replace("arXiv:", "").replace("arxiv:", "").lower()+ assert clean_cite in paper_url.lower(), f"Paper #{idx} ({rid}) url {paper_url!r} missing citation {cite!r}"++[email protected]_case(id="T4-03", tier=4, feature_id="#10", title="RAG CLI --json validation, 20-query p95 < 100 ms & SQLite DB bloat/isolation check", requires=("research",))+def t4_03() -> None:+ db = h.require_research_file("rag/forma_print_kb.sqlite")+ assert db.stat().st_size < 2 * 1024 * 1024, f"RAG DB exceeds 2 MiB cap: {db.stat().st_size} bytes"+ script = h.require_research_file("rag/query_rag.py")++ cli_cases = (+ ("OrcaSlicer 3MF model_settings.config", "software", "orcaslicer"),+ ("Bambu Lab MQTTS FTPS LAN mode", "manufacturer", "bambu_lab"),+ ("bridging steady scaffoldings overhang", "paper", "dumas-2014-bridging-the-gap"),+ ("Shpigford nurb build123d checks.py probe.py", "report", "nurb_inspection"),+ )+ for q_text, exp_domain, exp_eid in cli_cases:+ proc = h.run_cmd(+ ["python3", str(script), "--query", q_text, "--domain", exp_domain, "--top-k", "5", "--json"]+ )+ assert proc.returncode == 0, f"query_rag.py CLI failed on {q_text!r}: {proc.stderr}"+ payload = json.loads(proc.stdout)+ results = payload.get("results")+ assert isinstance(results, list) and 1 <= len(results) <= 5, f"Unexpected CLI results for {q_text!r}: {payload}"+ for hit in results:+ assert isinstance(hit.get("chunk_id"), str) and hit["chunk_id"].strip()+ assert hit.get("domain") == exp_domain+ assert float(hit.get("score", 0.0)) > 0.0+ assert h.is_valid_http_url(str(hit.get("source_url", "")))+ assert isinstance(hit.get("snippet"), str) and hit["snippet"].strip()+ assert exp_eid in {r["entity_id"] for r in results}, (+ f"CLI query {q_text!r} missed {exp_eid!r}: {[r['entity_id'] for r in results]}"+ )++ if str(h.REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(h.REPO_ROOT))+ from research.rag import query_rag++ queries_20 = (+ ("OrcaSlicer 3MF model_settings.config", "software", "orcaslicer"),+ ("PrusaSlicer Slic3r_PE_model.config", "software", "prusaslicer"),+ ("Manifold watertight boolean mesh", "software", "manifold"),+ ("UVtools floating islands suction cups", "software", "uvtools"),+ ("Moonraker upload klippy_uds 7125", "software", "moonraker"),+ ("Bambu Lab MQTTS FTPS LAN mode", "manufacturer", "bambu_lab"),+ ("PrusaLink HTTP REST API #31208", "manufacturer", "prusa_research"),+ ("Voron Tap ADXL345 Moonraker", "manufacturer", "voron_design"),+ ("Creality K2 Plus Moonraker CFS", "manufacturer", "creality"),+ ("Elegoo SDCP v3.0 Saturn 4 Ultra", "manufacturer", "elegoo"),+ ("Formlabs Form 4 Fuse 1+ SLS", "manufacturer", "formlabs"),+ ("Sovol eddy current probe LDC1612", "manufacturer", "sovol"),+ ("Make It Stand static equilibrium CoM", "paper", "prevost-2013-make-it-stand"),+ ("bridging steady scaffoldings overhang", "paper", "dumas-2014-bridging-the-gap"),+ ("Clever Support tree support overhang", "paper", "vanek-2014-clever-support"),+ ("Chopper partitioning interlocking parts", "paper", "luo-2012-chopper"),+ ("support-free hollowing contour offsetting", "paper", "wang-2017-support-free-hollowing"),+ ("powder removal passageway SLS voids", "paper", "liu-2022-powder-removal-passageway"),+ ("Shpigford nurb build123d checks.py probe.py", "report", "nurb_inspection"),+ ("nurb printers.toml OCCT cold start", "report", "nurb_inspection"),+ )++ latencies_ms: list[float] = []+ conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)+ try:+ chunks_cnt = conn.execute("SELECT COUNT(*) FROM chunks").fetchone()[0]+ fts_cnt = conn.execute("SELECT COUNT(*) FROM chunks_fts").fetchone()[0]+ assert chunks_cnt == fts_cnt >= 400, f"Unexpected chunk counts: chunks={chunks_cnt}, fts={fts_cnt}"+ query_rag.query_kb("warmup query", db_path=db, conn=conn, top_k=1)++ for q_text, exp_domain, exp_eid in queries_20:+ res = query_rag.query_kb(q_text, db_path=db, conn=conn, domain=exp_domain, top_k=5)+ hits = res.get("results", [])+ assert isinstance(hits, list) and 1 <= len(hits) <= 5, f"Unexpected hits for {q_text!r}: {res}"+ for hit in hits:+ assert hit.get("domain") == exp_domain+ assert float(hit.get("score", 0.0)) > 0.0+ assert h.is_valid_http_url(str(hit.get("source_url", "")))+ hit_eids = [hit["entity_id"] for hit in hits]+ assert exp_eid in hit_eids and hit_eids[0] == exp_eid, (+ f"Expected rank-1 {exp_eid!r} for {q_text!r}, got {hit_eids}"+ )+ latencies_ms.append(float(res["latency_ms"]))+ finally:+ conn.close()++ sorted_lats = sorted(latencies_ms)+ p95_ms = sorted_lats[max(0, math.ceil(0.95 * len(sorted_lats)) - 1)]+ assert p95_ms < 100.0, f"In-process 20-query p95 latency {p95_ms:.2f} ms >= 100.0 ms (samples={sorted_lats})"++ with h.temp_dir() as td:+ zero_db = pathlib.Path(td) / "zero_rows.sqlite"+ shutil.copy2(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()+ zero_res = query_rag.query_kb("OrcaSlicer 3MF", db_path=zero_db, domain="software", top_k=5)+ assert zero_res["total_candidates"] == 0 and zero_res["results"] == [], (+ f"Expected empty results on zero-row DB, got {zero_res}"+ )++[email protected]_case(id="T4-04", tier=4, feature_id="#12", title="Efficiency benchmark JSON reproducibility & invariant verification", requires=("research", "forma_print"))+def t4_04() -> None:+ bench = h.require_research_file("scripts/bench_efficiency.py")+ t0 = time.monotonic()+ p1 = h.run_cmd(["python3", str(bench), "--runs", "3", "--rag-runs", "3", "--json"], timeout=120.0)+ p2 = h.run_cmd(["python3", str(bench), "--runs", "3", "--rag-runs", "3", "--json"], timeout=120.0)+ assert p1.returncode == 0, f"bench_efficiency.py run 1 failed: {p1.stderr}"+ assert p2.returncode == 0, f"bench_efficiency.py run 2 failed: {p2.stderr}"+ assert (time.monotonic() - t0) < 120.0, "Dual bench_efficiency.py runs exceeded 120s"++ d1 = json.loads(p1.stdout)+ d2 = json.loads(p2.stdout)+ c1 = _canonical_bench_json(d1)+ c2 = _canonical_bench_json(d2)+ assert c1 == c2, "Canonicalized bench_efficiency.py JSON drifted across repeated runs"++ assert d1["artifacts"]["workspace_isolation"] == {+ "forma_print_excluded_from_default_members": True,+ "research_excluded_from_npm_files": True,+ "forma_print_excluded_from_npm_files": True,+ }+ core_mcp = d1["mcp"]["core_forma_mcp"]+ print_mcp = d1["mcp"]["opt_in_forma_print_mcp"]+ assert core_mcp["tools"] == ["eval", "inspect", "tx", "export"]+ assert 0 < core_mcp["tools_compact_o200k_tokens"] < 800+ assert print_mcp["tools"] == ["print_check", "print_prep", "print_export", "print_profiles"]+ assert 0 < print_mcp["tools_compact_o200k_tokens"] < 450+ assert len(d1["cli_benchmarks"]["benchmarks"]) >= 15++ for k in ("3", "5", "10"):+ by_k_1 = d1["rag_benchmarks"]["by_top_k"][k]+ by_k_2 = d2["rag_benchmarks"]["by_top_k"][k]+ assert by_k_1["queries_total"] == 18+ assert by_k_1["rank1_hits"] == 18+ assert by_k_1["relevant_any_hits"] == 18+ assert by_k_1["compression_ratio_vs_raw_corpus"] > 1.0+ assert by_k_1["timing"]["p95_ms"] < 100.0+ assert by_k_2["timing"]["p95_ms"] < 100.0++[email protected]_case(id="T4-05", tier=4, feature_id="#13", title="Dual MCP token-budget, tool list, release/WASM baseline parity & workspace isolation", requires=("core_baseline", "forma_print"))+def t4_05() -> None:+ with h.McpClient([str(h.find_forma_mcp_bin())]) as core_mcp:+ core_mcp.initialize()+ core_tools = core_mcp.tools_list()+ assert [t["name"] for t in core_tools] == ["eval", "inspect", "tx", "export"]+ core_tokens = h.count_o200k_tokens(core_tools)+ assert 0 < core_tokens < 800, f"Core forma-mcp tokens {core_tokens} out of (0, 800)"++ with h.McpClient([str(h.require_forma_print()), "--mcp"]) as print_mcp:+ print_mcp.initialize()+ print_tools = print_mcp.tools_list()+ assert [t["name"] for t in print_tools] == ["print_check", "print_prep", "print_export", "print_profiles"]+ print_tokens = h.count_o200k_tokens(print_tools)+ assert 0 < print_tokens < 450, f"forma-print --mcp tokens {print_tokens} out of (0, 450)"++ forma_sz = h.find_forma_bin().stat().st_size+ mcp_sz = h.find_forma_mcp_bin().stat().st_size+ wasm_sz = (h.REPO_ROOT / "wasm" / "forma.wasm").stat().st_size+ assert forma_sz == h.BASELINE_SIZES["forma"], f"forma size {forma_sz} != {h.BASELINE_SIZES['forma']}"+ assert mcp_sz == h.BASELINE_SIZES["forma-mcp"], f"forma-mcp size {mcp_sz} != {h.BASELINE_SIZES['forma-mcp']}"+ assert wasm_sz == h.BASELINE_SIZES["wasm"], f"wasm/forma.wasm size {wasm_sz} != {h.BASELINE_SIZES['wasm']}"++ cargo_toml = (h.REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")+ m_def = re.search(r"default-members\s*=\s*\[([^\]]*)\]", cargo_toml, re.DOTALL)+ assert m_def is not None, "Cargo.toml missing default-members"+ assert "forma-print" not in m_def.group(1) and "research" not in m_def.group(1), (+ f"Cargo.toml default-members must exclude forma-print and research: {m_def.group(1)}"+ )++ pkg = json.loads((h.REPO_ROOT / "package.json").read_text(encoding="utf-8"))+ assert not any("research" in str(x) or "forma-print" in str(x) for x in pkg.get("files", [])), (+ f"package.json files must exclude research and forma-print: {pkg.get('files')}"+ )++[email protected]_case(id="T4-06", tier=4, feature_id="#14", title="Exhaustive matrix sweep across all 18 printers & 9 materials with matching tech", requires=("forma_print",))+def t4_06() -> None:+ _, prof = h.run_forma_print_json(["profiles"])+ printers = h.extract_printers(prof)+ materials = h.extract_materials(prof)+ assert len(printers) == 18 and {p["id"] for p in printers} == set(h.EXPECTED_PRINTER_TECH.keys())+ assert len(materials) == 9 and {m["id"] for m in materials} == set(h.EXPECTED_MATERIALS)+ assert len(prof.get("heat_inserts", [])) == 6+ assert {ins["id"] for ins in prof["heat_inserts"]} == set(h.EXPECTED_HEAT_INSERTS)++ geom_checks = (+ "watertight",+ "build_volume",+ "overhangs",+ "floating_islands",+ "bridges",+ "wall_thickness",+ "bed_adhesion",+ "clearance",+ )+ masses_by_mat: dict[str, float] = {}+ for p in printers:+ pid, ptech = p["id"], p["tech"]+ expected_tech = "msla" if h.EXPECTED_PRINTER_TECH[pid] == "sla" else h.EXPECTED_PRINTER_TECH[pid]+ assert ptech == expected_tech, f"{pid}: tech={ptech!r}, expected={expected_tech!r}"+ for m in materials:+ if m["tech"] != ptech:+ continue+ mid = m["id"]+ _, rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--printer", pid, "--material", mid],+ allow_nonzero=True,+ )+ assert rep["printer_id"] == pid and rep["material_id"] == mid+ assert rep["printable"] is True, f"{pid}+{mid} unexpectedly unprintable: {rep['issues']}"+ for k in geom_checks:+ assert rep["checks"][k] == "pass", f"{pid}+{mid} check {k}={rep['checks'][k]}"+ expect_warn = (m["requires_enclosure"] and not p["enclosed"]) or (+ m["requires_hardened_nozzle"] and not p["hardened_nozzle"]+ )+ expected_mat_status = "warn" if expect_warn else "pass"+ assert rep["checks"]["material_and_swaps"] == expected_mat_status, (+ f"{pid}+{mid} material_and_swaps={rep['checks']['material_and_swaps']}, expected={expected_mat_status}"+ )+ mass = rep["stats"]["part_mass_g"]+ assert mass > 0.0+ masses_by_mat[mid] = round(mass, 4)+ assert len(masses_by_mat) == 9 and len(set(masses_by_mat.values())) == 9, (+ f"Expected 9 distinct masses: {masses_by_mat}"+ )++[email protected]_case(id="T4-07", tier=4, feature_id="#15", title="Unit-roundtrip invariance: 0.04x0.03x0.02 m .forma vs 40x30x20 mm .stl", requires=("forma_print",))+def t4_07() -> None:+ with h.temp_dir() as td:+ stl_path = h.write_binary_box_stl(pathlib.Path(td) / "box_40_30_20.stl", (40.0, 30.0, 20.0))+ _, r_forma = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "box_meters.forma"), "--unit", "m", "--printer", "bambu_x1c"]+ )+ _, r_stl = h.run_forma_print_json(+ ["check", str(stl_path), "--unit", "mm", "--printer", "bambu_x1c"]+ )+ h.assert_check_clean(r_forma, "box_meters.forma --unit m")+ h.assert_check_clean(r_stl, "box_40_30_20.stl --unit mm")+ assert abs(r_forma["unit"]["scale_to_mm"] - 1000.0) < 1e-6+ assert abs(r_stl["unit"]["scale_to_mm"] - 1.0) < 1e-6+ assert r_forma["checks"] == r_stl["checks"]+ for rep in (r_forma, r_stl):+ sz = rep["stats"]["size_mm"]+ assert all(abs(a - b) < 0.1 for a, b in zip(sz, (40.0, 30.0, 20.0))), f"Unexpected size_mm: {sz}"+ assert abs(rep["stats"]["volume_cm3"] - 24.0) < 0.1+ assert abs(rep["stats"]["bed_contact_area_mm2"] - 1200.0) < 0.5+ assert abs(r_forma["stats"]["part_mass_g"] - r_stl["stats"]["part_mass_g"]) < 1e-3++[email protected]_case(id="T4-08", tier=4, feature_id="#16", title="High-poly mesh (16k+ tris) DFM audit speed, heatmap & determinism", requires=("forma_print",))+def t4_08() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ hm1, hm2 = td_p / "hp1.png", td_p / "hp2.png"+ t0 = time.monotonic()+ _, r1 = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "high_poly.forma"), "--printer", "bambu_x1c", "--heatmap", str(hm1)],+ allow_nonzero=True,+ )+ elapsed_ms = (time.monotonic() - t0) * 1000.0+ _, r2 = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "high_poly.forma"), "--printer", "bambu_x1c", "--heatmap", str(hm2)],+ allow_nonzero=True,+ )+ assert elapsed_ms < 5000.0, f"High-poly audit too slow: {elapsed_ms:.1f} ms"+ assert len(r1["face_severities"]) >= 8000, f"Expected >=8000 faces (16k+ tris), got {len(r1['face_severities'])}"+ assert r1["printable"] is False and r1["checks"]["overhangs"] == "fail"+ assert r1 == r2, "High-poly check report was not deterministic across repeated runs"+ png_info = h.inspect_png(hm1)+ assert png_info["width"] == png_info["height"] >= 256+ assert png_info["distinct_colors_sampled"] >= 3+ assert hm1.read_bytes() == hm2.read_bytes(), "High-poly heatmap PNG bytes differed across runs"++[email protected]_case(id="T4-09", tier=4, feature_id="#18", title="Auto-orientation determinism & z0=0 on functional_bracket.forma & upside_down_t.forma", requires=("forma_print",))+def t4_09() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ for fname, expect_rotated, expect_printable in (+ ("functional_bracket.forma", False, False),+ ("upside_down_t.forma", True, True),+ ):+ s1, s2 = td_p / f"{fname}_1.stl", td_p / f"{fname}_2.stl"+ _, j1 = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / fname), "--out", str(s1)])+ _, j2 = h.run_forma_print_json(["orient", str(h.FIXTURES_DIR / fname), "--out", str(s2)])+ assert j1["rotated_from_input"] is expect_rotated+ assert j1["candidates_evaluated"] >= 10+ assert j1["report"]["printable"] is expect_printable+ assert abs(j1["report"]["stats"]["bbox_min_mm"][2]) < 1e-4+ j1_cmp = {k: v for k, v in j1.items() if k != "out_path"}+ j2_cmp = {k: v for k, v in j2.items() if k != "out_path"}+ assert j1_cmp == j2_cmp, f"orient JSON differed for {fname}"+ i1 = h.inspect_stl(s1)+ i2 = h.inspect_stl(s2)+ assert abs(i1["bbox_min"][2]) < 1e-3+ assert all(abs(a - b) < 0.1 for a, b in zip(i1["size"], j1["report"]["stats"]["size_mm"])), (+ f"orient STL size {i1['size']} != report size_mm {j1['report']['stats']['size_mm']} for {fname}"+ )+ _, recheck = h.run_forma_print_json(+ ["check", str(s1), "--unit", "mm", "--printer", j1["printer_id"], "--material", j1["material_id"]],+ allow_nonzero=True,+ )+ assert recheck["printable"] is expect_printable, (+ f"recheck printable={recheck['printable']} != {expect_printable} for {fname}"+ )+ assert recheck["checks"] == j1["report"]["checks"], (+ f"recheck checks {recheck['checks']} != orient report checks {j1['report']['checks']} for {fname}"+ )+ assert i1["triangles"] == i2["triangles"]+ assert all(abs(a - b) < 1e-3 for a, b in zip(i1["size"], i2["size"]))+ assert s1.read_bytes() == s2.read_bytes(), f"orient STL bytes differed for {fname}"++[email protected]_case(id="T4-10", tier=4, feature_id="#19", title="Multi-part/multi-color enclosure exports valid Deflate .3mf & AP214 .step", requires=("forma_print",))+def t4_10() -> None:+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ out_3mf = td_p / "enclosure.3mf"+ out_step = td_p / "enclosure.step"+ _, e3 = h.run_forma_print_json(+ ["export", str(h.FIXTURES_DIR / "multi_color_enclosure.forma"), "--printer", "bambu_p1s", "--material", "PETG", "--out", str(out_3mf)]+ )+ _, est = h.run_forma_print_json(+ ["export", str(h.FIXTURES_DIR / "multi_color_enclosure.forma"), "--out", str(out_step)]+ )+ assert e3["ok"] is True and e3["parts"] == 2 and e3["printer_id"] == "bambu_p1s" and e3["material_id"] == "PETG"+ assert est["ok"] is True and est["parts"] == 2+ m3 = h.inspect_3mf(out_3mf)+ st = h.inspect_step(out_step)+ assert m3["unit"] == "millimeter"+ assert m3["build_items"] == 2 and m3["basematerials"] >= 1 and m3["colorgroups"] >= 1+ assert m3["project_settings"].get("filament_type") == ["PETG", "PETG"]+ assert len(m3["project_settings"].get("filament_colour", [])) >= 2+ assert "extruder" in m3["model_settings_xml"] and "extruder" in m3["slic3r_pe_xml"]+ assert st["cartesian_points"] > 0 and st["has_automotive_design"] is True+ assert abs(m3["bbox_min"][2]) < 0.1 and abs(st["bbox_min"][2]) < 0.1+ for dim, exp in zip(m3["size"], (170.0, 50.0, 24.0)):+ assert abs(dim - exp) < 0.2+ for a, b in zip(m3["size"], st["size"]):+ assert abs(a - b) < 0.2, f".3mf size {m3['size']} != .step size {st['size']}"++[email protected]_case(id="T4-11", tier=4, feature_id="#20", title="Sequential multi-request MCP session stability (20 back-to-back calls)", requires=("forma_print",))+def t4_11() -> None:+ bin_path = h.require_forma_print()+ with h.temp_dir() as td:+ td_p = pathlib.Path(td)+ with h.McpClient([str(bin_path), "--mcp"], timeout=30.0) as mcp:+ mcp.initialize()+ tools = mcp.tools_list()+ assert {t["name"] for t in tools} == {"print_check", "print_prep", "print_export", "print_profiles"}+ chk_args = h.build_mcp_tool_args(tools, "print_check", input_path=str(h.FIXTURES_DIR / "box_meters.forma"))+ prep_args = h.build_mcp_tool_args(tools, "print_prep", input_path=str(h.FIXTURES_DIR / "box_meters.forma"))+ first_check = None+ for i in range(20):+ slot = i % 5+ if slot == 0:+ res = mcp.tools_call("print_profiles", {})+ assert not res.get("isError"), f"MCP call #{i} failed: {res}"+ payload = json.loads(res["content"][0]["text"])+ assert len(payload["printers"]) == 18 and len(payload["materials"]) == 9 and len(payload["heat_inserts"]) == 6+ elif slot == 1:+ res = mcp.tools_call("print_check", chk_args)+ assert not res.get("isError"), f"MCP call #{i} failed: {res}"+ payload = json.loads(res["content"][0]["text"])+ assert payload["printable"] is True and payload["part_count"] == 1+ assert abs(payload["unit_scale"]["scale_to_mm"] - 1000.0) < 1e-6+ assert set(payload["checks"].keys()) == {+ "watertight",+ "build_volume",+ "overhangs",+ "floating_islands",+ "bridges",+ "wall_thickness",+ "bed_adhesion",+ "clearance",+ "material_and_swaps",+ }+ if first_check is None:+ first_check = payload+ else:+ assert payload == first_check+ elif slot == 2:+ res = mcp.tools_call("print_prep", prep_args)+ assert not res.get("isError"), f"MCP call #{i} failed: {res}"+ payload = json.loads(res["content"][0]["text"])+ assert payload["rotated_from_input"] is False and payload["candidates_evaluated"] >= 1+ assert payload["report"]["printable"] is True+ elif slot == 3:+ out_3mf = td_p / f"mcp_export_{i}.3mf"+ exp_args = h.build_mcp_tool_args(+ tools,+ "print_export",+ input_path=str(h.FIXTURES_DIR / "box_meters.forma"),+ out_path=str(out_3mf),+ )+ res = mcp.tools_call("print_export", exp_args)+ assert not res.get("isError"), f"MCP call #{i} failed: {res}"+ payload = json.loads(res["content"][0]["text"])+ assert payload["ok"] is True and payload["format"] == "3mf" and payload["parts"] == 1+ assert h.inspect_3mf(out_3mf)["unit"] == "millimeter"+ else:+ res = mcp.ping()+ assert res == {}+ assert mcp.proc is not None and mcp.proc.poll() is None, f"MCP server exited prematurely at call #{i}"++[email protected]_case(id="T4-12", tier=4, feature_id="#20", title="Tier 1 multi-tech DFM comparison (MSLA vs FDM vs SLS) & SLS 3-part batch export", requires=("forma_print",))+def t4_12() -> None:+ # 1. Hollow shell: MSLA flags 34 mm unsupported bridge (>2.5 mm); drain holes reduce volume & bed contact; SLS self-supports+ _, closed_rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "hollow_closed.forma"), "--printer", "elegoo_saturn_4_ultra", "--material", "RESIN_STD"],+ allow_nonzero=True,+ )+ _, drained_rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "hollow_drained.forma"), "--printer", "elegoo_saturn_4_ultra", "--material", "RESIN_STD"],+ allow_nonzero=True,+ )+ assert closed_rep["printable"] is False and closed_rep["checks"]["bridges"] == "fail"+ assert drained_rep["printable"] is False and drained_rep["checks"]["bridges"] == "fail"+ assert drained_rep["stats"]["volume_cm3"] < closed_rep["stats"]["volume_cm3"]+ assert drained_rep["stats"]["bed_contact_area_mm2"] < closed_rep["stats"]["bed_contact_area_mm2"]+ _, drained_sls = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "hollow_drained.forma"), "--printer", "formlabs_fuse_1p", "--material", "SLS_PA12"],+ )+ h.assert_check_clean(drained_sls, "hollow_drained on SLS Fuse 1+")++ # 2. Overhang cone (56.2 deg): fails MSLA (30 deg), warns FDM (50 deg), passes SLS (90 deg)+ _, cone_sla = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--printer", "elegoo_saturn_4_ultra", "--material", "RESIN_STD"],+ allow_nonzero=True,+ )+ _, cone_fdm = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--printer", "bambu_x1c", "--material", "PLA"],+ )+ _, cone_sls = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "overhang_cone.forma"), "--printer", "formlabs_fuse_1p", "--material", "SLS_PA12"],+ )+ assert cone_sla["printable"] is False and cone_sla["checks"]["overhangs"] == "fail"+ assert cone_fdm["printable"] is True and cone_fdm["checks"]["overhangs"] == "warn"+ h.assert_check_clean(cone_sls, "overhang_cone on SLS Fuse 1+")++ # 3. Multi-part SLS batch: clearance >= 0.50 mm (5.0 mm actual), bridges pass, and 3-part .3mf export+ _, sls_rep = h.run_forma_print_json(+ ["check", str(h.FIXTURES_DIR / "sls_batch.forma"), "--printer", "formlabs_fuse_1p", "--material", "SLS_PA12"],+ )+ h.assert_check_clean(sls_rep, "SLS batch on Fuse 1+")+ assert sls_rep["checks"]["bridges"] == "pass" and sls_rep["stats"]["bridge_face_count"] > 0+ assert (sls_rep["stats"]["min_part_clearance_mm"] or 0.0) >= 0.50+ with h.temp_dir() as td:+ sls_3mf = pathlib.Path(td) / "sls_batch.3mf"+ _, exp = h.run_forma_print_json(+ ["export", str(h.FIXTURES_DIR / "sls_batch.forma"), "--printer", "formlabs_fuse_1p", "--material", "SLS_PA12", "--out", str(sls_3mf)],+ )+ assert exp["ok"] is True and exp["parts"] == 3+ m3 = h.inspect_3mf(sls_3mf)+ assert m3["build_items"] == 3 and abs(m3["bbox_min"][2]) < 0.1+ for dim, exp_dim in zip(m3["size"], (99.0, 30.0, 25.0)):+ assert abs(dim - exp_dim) < 0.2