A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
research: add 3D printing KB corpus, RAG index, validation, and efficiency analysis
wrong-nebula51468ea8af3b
diff --git a/research/README.md b/research/README.mdnew file mode 100644index 0000000..4c8cb07--- /dev/null+++ b/research/README.md@@ -0,0 +1,151 @@+# Forma-Print Research Knowledge Base & RAG Index++Pure-text structured research corpus, deterministic stdlib-only SQLite FTS5 + TF-IDF hybrid RAG index, and automated validation suite supporting `crates/forma-print` (Milestone M1–M3).++---++## 1. Zero-Bloat & Workspace Isolation Architecture++- **Zero Core Binary / WASM / npm Footprint:** `research/` is completely outside `Cargo.toml` (`workspace.members` and `default-members`) and `package.json` (`files`). It adds **0 bytes** to `forma`, `forma-mcp`, `wasm/forma.wasm`, and npm tarballs, and **0 tokens** to core `forma-mcp`.+- **Controlled Storage (`< 2 MB` Index):** Instead of committing multi-megabyte binary PDFs, scraped HTML dumps, or external vector-DB weights, all primary research is distilled into normalized UTF-8 JSONL records (`~283.5 KB` raw across corpora + `nurb_inspection.md`) and indexed into a single deterministic, `VACUUM`-compacted SQLite database (`research/rag/forma_print_kb.sqlite`, `~1.72 MiB`, strictly `< 2 MiB`).+- **Zero External Runtime Dependencies:** Both `build_rag.py` and `query_rag.py` use **Python 3 stdlib only** (`sqlite3` with FTS5 `porter unicode61`, `json`, `re`, `hashlib`, `math`, `pathlib`). `validate_kb.py` uses `jsonschema` when installed and ships a strict pure-stdlib Draft 2020-12 fallback (`--stdlib-only`).++---++## 2. Directory Layout++```text+research/+├── README.md # This document+├── schemas/+│ ├── software.schema.json # Draft 2020-12 schema for R1 software records+│ ├── manufacturers.schema.json # Draft 2020-12 schema for R2 manufacturer records+│ ├── papers.schema.json # Draft 2020-12 schema for R3 academic papers+│ └── rag_chunks.schema.json # Draft 2020-12 schema for normalized RAG chunks+├── corpus/+│ ├── software.jsonl # 59 open-source 3D printing & agentic CAD tools+│ ├── manufacturers.jsonl # 22 3D printer manufacturers / hardware ecosystems+│ └── papers.jsonl # 49 mesh-optimization & 3D-printing academic papers+├── reports/+│ └── nurb_inspection.md # Primary-source architectural inspection of Shpigford/nurb+├── rag/+│ ├── build_rag.py # Deterministic bit-identical SQLite FTS5 + TF-IDF builder+│ ├── query_rag.py # Hybrid BM25 + TF-IDF cosine CLI & Python API+│ └── forma_print_kb.sqlite # Prebuilt compact RAG index (< 2 MiB, 448 chunks)+├── scripts/+│ ├── validate_kb.py # 5-stage offline KB, RAG & isolation validation suite+│ └── bench_efficiency.py # Reproducible CLI/MCP/RAG efficiency & token benchmark+└── analysis/+ └── efficiency_justification.md # 4-axis R5 efficiency & non-replacement justification report+```++---++## 3. Corpus & Schema Summary++| Source | Records | Chunks | Primary Focus & Policy |+|---|---:|---:|---|+| `corpus/software.jsonl` | 59 | 177 | Slicers, mesh repair/analysis, host/fleet/spool tools, firmware, programmatic CAD/CLI, modern agentic CAD (`nurb`, `nurb_benchmarks`). |+| `corpus/manufacturers.jsonl` | 22 | 160 | Direct local/cloud protocols, auth/LAN modes, monitoring/sensors, and troubleshooting/fault codes (chunked by aspect + 72 per-fault chunks). Undocumented interfaces are explicitly marked `not_publicly_documented` or `unavailable`. |+| `corpus/papers.jsonl` | 49 | 98 | Balanced across 7 mesh-optimization & printability categories with verified DOIs/arXiv IDs (`10.*` / `arXiv:*`) and algorithmic mappings to `forma-print`. |+| `reports/nurb_inspection.md` | 1 (13 subsections) | 13 | Deep architectural analysis of `Shpigford/nurb` (`v1.6.0`/`v1.17.0`) and `Shpigford/nurb-benchmarks`. |+| **Total** | **130 + 1 report** | **448** | **Bit-identical deterministic SQLite index (`forma_print_kb.sqlite`)** |++---++## 4. Building & Querying the RAG Database++### Build / Rebuild (`build_rag.py`)++```bash+python3 research/rag/build_rag.py+```++Key options:+- `--db <path>`: Override output SQLite path (default: `research/rag/forma_print_kb.sqlite`).+- `--emit-chunks-jsonl`: Opt-in flag to also dump `research/rag/chunks.jsonl` (omitted by default to prevent repo bloat).+- `--chunks-jsonl <path>`: Override output path when `--emit-chunks-jsonl` is enabled (default: `research/rag/chunks.jsonl`).+- `--check-size-mb <float>`: Fail if the built SQLite file exceeds `<float>` MiB (default: `2.0`).+- `--quiet`: Suppress JSON build summary.++Builds execute atomically (`<db>.tmp` -> `VACUUM;` -> `PRAGMA integrity_check;` -> size gate -> `os.replace`) with zero volatile timestamps in `kb_manifest`, guaranteeing **bit-identical SHA-256** across repeated builds.++### CLI Retrieval (`query_rag.py`)++```bash+# Exact fault code lookup (punctuation-safe FTS5 sanitization)+python3 research/rag/query_rag.py --query "HMS_0700-0100-0002-0002" --domain manufacturer --top-k 3++# Protocol + technology faceted search+python3 research/rag/query_rag.py --query "WebSocket file upload" --tech msla --protocol sdcp --json++# Metadata-only fault prefix lookup+python3 research/rag/query_rag.py --fault-prefix HMS_ --top-k 5 --json++# Academic paper & architectural report retrieval+python3 research/rag/query_rag.py --query "overhang support bridging" --domain paper --top-k 3+python3 research/rag/query_rag.py --query "checks.py probe.py" --domain report --top-k 3+```++Supported flags: `--query`, `--domain` (`software|manufacturer|paper|report`), `--tech` (`fdm|msla|sla|sls`), `--manufacturer`, `--protocol`, `--category`, `--fault-prefix`, `--top-k` (default `5`), `--db`, `--json`.++### Python API++```python+from research.rag.query_rag import query_kb, search # `search` is an alias for `query_kb`++resp = search(+ "Bambu Lab MQTTS FTPS LiDAR",+ domain="manufacturer",+ tech="fdm",+ top_k=3,+)+for hit in resp["results"]:+ print(hit["entity_id"], hit["score"], hit["source_url"])+```++**Hybrid Scoring & Safety:**+1. Query tokens are sanitized and phrase-quoted for FTS5 `MATCH` (`"tok1" OR "tok2"`) so fault codes (`HMS_0700-0100-0002-0002`, `#31208`, `ER18`), operators (`c++`, `AND`, `OR`, `NOT`), and empty/missing queries never raise `sqlite3.OperationalError`.+2. Candidates are ranked with `0.55 * norm(BM25) + 0.45 * tfidf_cosine + exact_match_bonus` using `chunks_fts` (`porter unicode61`) and `vocab_idf`, achieving `p95 < 100 ms` (typically `10–65 ms`).++---++## 5. Automated Validation (`validate_kb.py`)++```bash+# Default validation (uses jsonschema if installed, else stdlib fallback)+python3 research/scripts/validate_kb.py++# Structured JSON output+python3 research/scripts/validate_kb.py --json++# Pure-stdlib Draft 2020-12 validator check (zero external Python dependencies)+python3 research/scripts/validate_kb.py --stdlib-only --json++# Rebuild DB, verify bit-identical determinism, and run all 5 stages+python3 research/scripts/validate_kb.py --rebuild-rag+```++Validation stages (exits `0` only if all pass):+1. **Schemas:** Parses and validates all 4 Draft 2020-12 schemas.+2. **Corpus Invariants:** Validates all `59 + 22 + 49` records, unique IDs, `source_verified == true`, non-empty trimmed strings, uniform `^https?://[^\s]+$` + `urlparse` URLs, and DOI/arXiv citations.+3. **Secret Scan:** Scans all text files in `research/` for API keys/tokens/UUIDv4 secrets without ever printing matched secret text.+4. **RAG DB & Repo Isolation:** Verifies `PRAGMA integrity_check`, `kb_manifest` parity, validates **all 448 chunk rows** against `rag_chunks.schema.json` + `content_hash`, checks `< 2 MiB` DB size and zero `.pdf`/`.html` dumps, and verifies Cargo `default-members`, `package.json`, and `.gitignore` isolation.+5. **RAG Retrieval Suite:** Runs sample queries across all 4 domains, metadata filters, fault codes, diacritics, whitespace/punctuation/empty/missing edge cases, and enforces `p95 < 100 ms`.++---++## 6. Efficiency Benchmark & Justification Analysis (M3 / R5)++- **Analysis Report:** [`analysis/efficiency_justification.md`](analysis/efficiency_justification.md) — 4-axis comparison (`Accuracy & Hallucination Mitigation`, `Latency`, `Token & Compute Cost`, `Deterministic Geometry & Printer-API Verification`) vs. frontier LLM guesswork, plus explicit non-replacement architectural boundaries.+- **Reproducible Benchmark (`bench_efficiency.py`):** Measures binary/KB footprints, `o200k_base` MCP schema & tool-call tokens, CLI DFM/orient/`.3mf`/`.step` `p50`/`p95` latencies, and 18-query RAG compression offline in `tempfile.TemporaryDirectory()`:+ ```bash+ python3 research/scripts/bench_efficiency.py --json+ ```++---++## 7. Secret & Environment Hygiene++- `.env` and `.env.*` are gitignored in `.gitignore` and must never be read, printed, or committed.+- All RAG builds, queries, and validation checks run **100% offline** with zero API keys or network calls.diff --git a/research/analysis/efficiency_justification.md b/research/analysis/efficiency_justification.mdnew file mode 100644index 0000000..3bdcc77--- /dev/null+++ b/research/analysis/efficiency_justification.md@@ -0,0 +1,183 @@+# Efficiency & Justification Analysis: Forma + RAG KB + Deterministic `forma-print` vs. Large Model Guesswork (R5)++**Scope:** Evaluates **Forma (`forma-core`, `forma-lang`, `forma-mcp`) + `forma-print` Tier 1 + SQLite FTS5/BM25+TF-IDF RAG Knowledge Base** against **ungrounded frontier LLM guesswork (e.g., Fable 5.2 / `claude-fable-5`-class reasoning loops without deterministic DFM or grounded hardware/paper retrieval)** across four operational axes — **Accuracy & Hallucination Mitigation**, **Latency**, **Token & Compute Cost**, and **Deterministic Geometry & Printer-API Verification** — while defining explicit architectural boundaries showing why this stack **does not replace** full slicers, interactive GUI CAD applications, printer firmware, or host/fleet daemons.++---++## 1. Executive Summary & Attribution Boundary++Pure frontier-LLM guesswork fails predictably on 3D printing workflows for two structural reasons:+1. **Text tokens cannot compute continuous 3D geometry or print physics.** Without a deterministic geometry kernel, an LLM estimating overhang angles, inward thin walls (`< 0.84 mm`), Z-slice floating islands, center-of-mass tipping stability, multi-part clearances, or valid Deflate `.3mf` ZIP binaries is performing mental simulation over coordinates—a task where even top reasoning models exhibit Turn-1 geometric errors, silent non-manifold corruptions, and `3×–5×` multi-turn repair token blowups.+2. **Parametric LLM memory cannot reliably recall 22+ printer ecosystems' exact ports, auth gates, sensor feeds, fault hex codes, and undocumented boundaries.** Guessing whether a printer exposes an open local REST API (PrusaLink `80/tcp`), requires LAN-Only + Developer Mode MQTTS/FTPS (`8883/tcp` / `990/tcp`), uses SDCP WebSockets (`3030/tcp`), or is strictly enterprise-gated (`closed_or_usb_only` / `unavailable`) induces subtle, hard-to-debug integration failures.++Combining **`Forma-Pipe` (`788` `o200k_base` MCP tokens)** + **opt-in `forma-print` (`391` `o200k_base` MCP tokens, `2.294 MB` static binary)** + **a `1.7188 MiB` offline SQLite FTS5/TF-IDF RAG index (`448` chunks, `354` unique primary-source URLs)** resolves both failure modes locally in milliseconds:+- **Deterministic pre-print DFM + orientation + `.3mf`/`.step` export** runs in **`7.01–32.16 ms` (`p50`)** on standard CAD parts (`56.82–101.62 ms` for DFM/export on an `8,192`-face subdivided torus), with **`0` extra bytes** on core `forma` / `forma-mcp` / `wasm/forma.wasm`.+- **Hybrid BM25+TF-IDF RAG retrieval** across 130 primary-source-verified records and the `Shpigford/nurb` inspection report achieves **`18/18` (`100%`) rank-1 hits** at **`p50 = 1.925 ms` / `p95 = 3.071 ms`** (`top_k=5`), compressing **`75,723` `o200k_base` corpus+report tokens** down to **`1,052.94` retrieved chunk-text tokens (`71.92×` reduction at `k=5`; `109.58×` at `k=3`)**.++### Three-Tier Evidence & Attribution Policy++Every claim in this document is explicitly attributed to one of three evidence tiers. **No external Fable 5.2 API runs were fabricated or executed locally.**++| Evidence Tier | Source & Scope | Verification Method |+|---|---|---|+| **Tier A — Live Local Measurements** | Executed offline on this host via `python3 research/scripts/bench_efficiency.py --json` (`tiktoken` `o200k_base`, `target/release/{forma,forma-mcp,forma-print}`, `research/rag/forma_print_kb.sqlite`, `tests/e2e/fixtures/*.forma`, `runs=15` fast / `5` high-poly, `rag-runs=3`). | Reproducible zero-side-effect run (`tempfile.TemporaryDirectory()`, exit `0`). |+| **Tier B — Published Empirical Baselines** | Verified telemetry already recorded in repository reports: `research/reports/nurb_inspection.md` (`Shpigford/nurb` & `Shpigford/nurb-benchmarks` `claude-fable-5` / `claude-opus-5` / `gpt-5.6-sol` telemetry), `docs/PHASE1_BASELINE_REPORT.md`, `docs/PHASE2_LANGUAGE_ABLATION.md`, `docs/EXTENDED_BENCHMARK_REPORT.md`, `docs/VERIFICATION_REPORT.md`, and `docs/AUTORESEARCH_HILLCLIMB.md`. | Direct file/line citations in §6 and `"published_baselines"` in `bench_efficiency.py`. |+| **Tier C — Transparent Analytical Estimates** | Clearly labeled mathematical bounds (e.g., raw `.3mf`/`.step` token equivalent if fed directly to an LLM, or multi-turn retry cost multipliers when ungrounded guesswork fails). | Explicit formula and stated assumptions inline wherever used. |++---++## 2. Artifact & Isolation Footprint (Tier A — Live Measured)++`crates/forma-print` is included in `Cargo.toml` `workspace.members` **only** (excluded from `default-members`), and `research/` is excluded from both `Cargo.toml` and `package.json` `files`.++| Artifact | Path | Exact Size | Notes / Isolation Status |+|---|---|---:|---|+| Core CLI binary | `target/release/forma` | `1,818,160 B` (`1.734 MB`) | **0 extra bytes** from `forma-print` or `research/` |+| Core MCP binary | `target/release/forma-mcp` | `1,775,040 B` (`1.693 MB`) | **4 tools**, `788` `o200k_base` tokens (`< 800` cap) |+| Core WASM bundle | `wasm/forma.wasm` | `786,102 B` (`767.68 KB`) | **0 extra bytes** from `forma-print` or `research/` |+| Opt-in Print binary | `target/release/forma-print` | `2,405,824 B` (`2.294 MB`) | Standalone CLI + opt-in `--mcp` (`391` `o200k_base` tokens) |+| RAG SQLite Index | `research/rag/forma_print_kb.sqlite` | `1,802,240 B` (`1.7188 MiB`) | `448` chunks, FTS5 + IDF vocab, read-only queryable |+| Raw Corpora + Report | `research/corpus/*.jsonl` + `nurb_inspection.md` | `290,300 B` (`269,323 B` JSONL) | `130` verified records + `1` report (`75,723` `o200k_base` tok) |++---++## 3. Four-Axis Comparison vs. Large Model Guesswork++### Axis 1 — Accuracy & Hallucination Mitigation++#### 1A. Why Pure LLM Guesswork Fails in Practice (Tier B + Tier A)+1. **Even `Shpigford/nurb` engineers guardrails because frontier LLMs cannot be trusted to guess (`Tier B`):** As documented in `research/reports/nurb_inspection.md:48-70`, `nurb` had to introduce `measurements.py` (`measured()` raising `MeasurementError` against `measurements.toml` to prevent LLMs from fabricating physical mating dimensions) alongside a 15-rule B-rep printability gate (`checks.py`) and `probe.py` face pinning.+2. **Silent geometric corruption in standard scripting (`Tier B`):** In `docs/PHASE1_BASELINE_REPORT.md:32,45` (48 Blender `bpy` trials across 4 models), **`5` exports had silent non-manifold corruption (`WT=False`, `NM=4..6`, `IoU=0.0`) while Blender exited with code `0`**, and multi-turn repair loops exploded token usage `3×–5×` (`2,932–11,678` tokens).+3. **Cross-lab reliability gap (`Tier B`):** Across `254` paired matrix trials in `docs/EXTENDED_BENCHMARK_REPORT.md:26,44-47,72-74` (12 late-2026 models, 10 labs), `Forma-Pipe` achieved **`48/48` (`100%`) Pass@3** at `low`/`medium` reasoning (`0.975–0.976` Mean Volumetric IoU) vs. **`20/24` (`83.3%`)** flat Pass@3 for Blender `bpy` across `low`, `medium`, and `high` reasoning. In `docs/PHASE2_LANGUAGE_ABLATION.md:26-28`, `Forma-Pipe` outperformed `bpy` by `+12.5 pp` Pass@1 (`68.8% → 81.2%`) and `+12.5 pp` Pass@3 (`85.4% → 97.9%`).+4. **Live deterministic defect detection vs. visual guesswork (`Tier A`):** On `tests/e2e/fixtures/upside_down_t.forma`, an unassisted LLM might overlook cantilever bridging until slicing fails; `forma-print check` deterministically flags `bridges=fail` (`rc=3`, `printable=false`), and `forma-print orient` evaluates `10` candidates and rotates the part into a `9/9` passing orientation (`printable=true`). On `functional_bracket.forma` (`734` faces), BVH raycasting + normal checks pinpoint **both** `overhangs=fail` (`73.1°` horizontal bore) and `wall_thickness=fail` (`0.007 mm` thin tangent edge `< 0.84 mm`) in `27.77 ms` (`p50`).++#### 1B. Anti-Hallucination Grounding in Printer Protocols, Sensors, Fault Codes & Printability Theory (`Tier A`)+Instead of relying on frontier-model parametric weights (which conflate firmware revisions, port numbers, and proprietary lockouts), `research/rag/query_rag.py` achieves **`18/18` (`100%`) rank-1 accuracy** across `top_k ∈ {3, 5, 10}` over `130/130` `source_verified == true` records (`354` unique primary-source URLs):++| Domain | Example Grounded Query (`bench_efficiency.py`) | Rank-1 Entity (`k=5`) | Verified Anti-Hallucination Facts Retrieved |+|---|---|---|---|+| **Fault Codes** | `"HMS_0700-0100-0002-0002"` | `bambu_lab` | Exact 16-digit HMS code (`AMS assist motor overloaded`), official `wiki.bambulab.com` URL (`manufacturers.jsonl:1`). |+| **Local Auth & Ports** | `"Bambu Lab MQTTS 8883 FTPS 990 LAN access code"` | `bambu_lab` | `8883/tcp` MQTTS, `990/tcp` Implicit FTPS, `322/tcp` RTSPS, **LAN Only + Developer Mode (ACS)** requirement, `bblp` + 8-digit access code (`manufacturers.jsonl:1`). |+| **REST + Error Code** | `"PrusaLink HTTP REST API #31208"` | `prusa_research` | `80/tcp` OpenAPI 3.0.1 (`/api/v1/files/{storage}/{path}`, Digest/`X-Api-Key`), `#31208` hotend mintemp (`manufacturers.jsonl:2`). |+| **Klipper Telemetry** | `"Voron Moonraker 7125 Klipper ADXL345"` | `voron_design` | `7125/tcp` Moonraker HTTP + JSON-RPC WebSocket, `trusted_clients` CIDR auth, `ADXL345` input shaper (`manufacturers.jsonl:3`, `software.jsonl:24`). |+| **MSLA WebSocket** | `"WebSocket file upload SDCP"` (`tech=msla, protocol=sdcp`) | `elegoo` | `3000/udp` `'M99999'` discovery, `3030/tcp` SDCP v3.0 WebSocket + `1 MB` chunked `/uploadFile/upload` with `S-File-MD5` (`manufacturers.jsonl:6`). |+| **Closed Boundaries** | `"Stratasys F123 MTConnect GrabCAD SDK closed"` | `stratasys` | Read-only MTConnect XML (`5000/tcp` F123 / `53750/tcp` Fortus) vs. `closed_or_usb_only` GrabCAD SDK (`manufacturers.jsonl:15`; paired with Markforged `unavailable` local endpoints at `manufacturers.jsonl:14`). |+| **Peer-Reviewed Math** | `"Make It Stand center of mass stability"`, `"bridging steady scaffoldings..."`, `"voxel printability..."`, `"build orientation..."` | `prevost-2013`, `dumas-2014`, `telea-2011`, `delfs-2016` | Exact DOIs (`10.1145/2461912.2461957`, `10.1145/2601097.2601153`, `10.1007/978-3-642-21569-8_34`, `10.1016/j.addma.2016.06.003`) grounding CoM convex-hull stability, bridge span bounds, minimum wall thickness (`1.6 mm`/`1.0 mm` Štava 2012), $C^0$ non-smooth orientation curves (Ezair 2015), and `+0.13 mm` hole expansion (Grgić 2023). |++---++### Axis 2 — Latency (`Tier A` Live vs. `Tier B` Published Baselines)++#### 2A. Live Deterministic CLI & MCP Latency (`Tier A` — `bench_efficiency.py --json`)++| Workload (`tests/e2e/fixtures/`) | Operation | Printer | Runs | `p50` (ms) | `p95` (ms) | Deterministic Output |+|---|---|---|---:|---:|---:|---|+| `box_meters.forma` (`6` faces) | `check --heatmap` | `bambu_x1c` | 15 | `7.519` | `8.954` | `rc=0`, `9/9` pass, `24.0 cm³`, HM `13,137 B` |+| `upside_down_t.forma` (`28` faces) | `check --heatmap` | `bambu_x1c` | 15 | `7.732` | `8.173` | `rc=3`, `bridges` fail, `38.88 cm³`, HM `14,241 B` |+| `upside_down_t.forma` | `orient` | `bambu_x1c` | 15 | `7.010` | `7.963` | `rc=0`, `10` cands, `rotated=true`, `9/9` pass |+| `upside_down_t.forma` | `export --orient .3mf` | `bambu_x1c` | 15 | `8.925` | `10.734` | `7,509 B` (`1.574×` file Deflate, `8` entries) |+| `upside_down_t.forma` | `export --orient .step` | `bambu_x1c` | 15 | `7.482` | `8.866` | `19,958 B` (`SI_UNIT(.MILLI.,.METRE.)`) |+| `functional_bracket.forma` (`734` faces) | `check --heatmap` | `bambu_x1c` | 15 | `27.770` | `35.217` | `rc=3`, `overhangs`+`wall_thickness` fail, HM `18,323 B` |+| `multi_color_ams.forma` (`60` faces) | `check --heatmap` | `bambu_x1c` | 15 | `9.279` | `10.115` | `rc=0`, `ams_swaps=2`, `purge=1.116 g`, HM `18,580 B` |+| `multi_color_enclosure.forma` (`106` faces) | `check --heatmap` | `bambu_p1s` | 15 | `10.649` | `15.103` | `rc=0`, `ams_swaps=26`, `purge=14.508 g`, HM `16,991 B` |+| `multi_color_enclosure.forma` | `orient` | `bambu_p1s` | 15 | `28.401` | `31.662` | `rc=0`, `19` cands, `rotated=false`, `printable=true` |+| `multi_color_enclosure.forma` | `export --orient .3mf` | `bambu_p1s` | 15 | `32.163` | `39.767` | `2` parts, `8,808 B` (`2.234×` file Deflate, `8` entries) |+| `multi_color_enclosure.forma` | `export --orient .step` | `bambu_p1s` | 15 | `28.648` | `82.668` | `2` parts, `78,659 B` |+| `high_poly.forma` (`8,192` faces) | `check --heatmap` | `bambu_x1c` | 5 | `101.622` | `158.350` | `rc=3`, `overhangs` fail, `55.64 cm³`, HM `78,948 B` |+| `high_poly.forma` (`8,192` faces) | `orient` | `bambu_x1c` | 5 | `868.282` | `940.500` | `rc=0`, `24` cands, `rotated=false` |+| `high_poly.forma` (`8,192` faces) | `export .3mf` | `bambu_x1c` | 5 | `56.823` | `57.585` | `185,453 B` (`5.998×` file / `6.031×` payload Deflate) |+| `high_poly.forma` (`8,192` faces) | `export .step` | `bambu_x1c` | 5 | `41.521` | `43.046` | `7,693,075 B` |++- **MCP Handshake & Tool-Call Latency (`Tier A`):** `forma-mcp` handshake (`initialize` + `notifications/initialized` + `tools/list`) took **`6.521 ms`**; `forma-print --mcp` handshake took **`5.564 ms`**; live `upside_down_t.forma` tool calls executed in **`7.764 ms`** (`print_check`), **`3.094 ms`** (`print_prep`), **`4.914 ms`** (`print_export`), and **`0.261 ms`** (`print_profiles`).+- **RAG Query Latency (`Tier A`, 54 timed runs per `top_k`):** **`p50 = 1.670 ms` / `p95 = 3.041 ms`** (`k=3`), **`p50 = 1.925 ms` / `p95 = 3.071 ms`** (`k=5`), **`p50 = 2.210 ms` / `p95 = 4.061 ms`** (`k=10`); cold-open (`conn=None`) samples measured **`1.657–2.607 ms`**.++#### 2B. Comparison vs. Heavy Kernels & Frontier Agent Loops (`Tier B`)+- **vs. `Shpigford/nurb` (`nurb_inspection.md:30`):** `nurb` incurs a **`~45 s` OCCT/Python cold import** (requiring a long-lived `serve.py` daemon) and **`30–400 ms`** warm rebuilds. Stateless cold `forma-print check` on typical parts (`7.52–27.77 ms` `p50`) is **`~1,620×–5,980×` faster** than `nurb`'s cold boot and faster than or on par with its warm daemon loop.+- **vs. Stock Blender 5.3 (`docs/VERIFICATION_REPORT.md:27,39`, `docs/PHASE2_LANGUAGE_ABLATION.md:26-27`):** `forma` cold+eval+export (`18.83 ms` median) is **`50×` faster** than Blender 5.3 (`947.5 ms`), and `Forma-Pipe` median engine latency (`25.9 ms`) is **`50.4×` faster** than `bpy` (`1,306.8 ms`).+- **vs. `claude-fable-5` on `Shpigford/nurb-benchmarks` (`nurb_inspection.md:104-115`):** Even *with* `nurb` MCP feedback, `claude-fable-5` took **`139 s` (`medium`) / `219 s` (`high`)** on `bit_block` and **`253 s` (`medium`) / `652 s` (`high`)** on `bundle_holder` (`claude-opus-5` high: `1,140 s`; `gpt-5.6-sol` high: `331 s`). Deterministic local DFM + RAG lookups execute in **`~2–35 ms`**, shifting iteration from multi-minute LLM conjecture loops to sub-50 ms verified checks.++---++### Axis 3 — Token & Compute Cost (`Tier A` Live + `Tier B` Published + `Tier C` Analytical)++#### 3A. Exact `o200k_base` MCP Schema & Tool-Call Token Budgets (`Tier A`)+- **Tool Schema Discovery (`tools/list` compact JSON):**+ - Core `forma-mcp` (`eval`, `inspect`, `tx`, `export`): **`788` `o200k_base` tokens** (`2,179 B`; `790` compact result; `968` pretty-printed).+ - Opt-in `forma-print --mcp` (`print_check`, `print_prep`, `print_export`, `print_profiles`): **`391` `o200k_base` tokens** (`1,468 B`; `393` compact result; `687` pretty-printed).+ - Combined (`forma-mcp` + `forma-print --mcp`): **`1,179` `o200k_base` tokens** (`0` added to core `forma-mcp` when print is not loaded)—compared with `nurb`'s multi-tool suite + `MCP_MAX_CHARS = 149,000` envelope and injected `doctrine.md` (`nurb_inspection.md:39-41`).+- **Live `forma-print --mcp` Response Payloads (`upside_down_t.forma`):**+ - `print_check`: `785` `o200k_base` tokens (`2,165 B`) — flags `bridges` fail in one call.+ - `print_prep`: `2,524` `o200k_base` tokens (`7,388 B`) — includes top-5 candidates + post-orient audit.+ - `print_export`: `236` `o200k_base` tokens (`546 B`) — confirms `7,509 B` Deflate `.3mf` written.+ - `print_profiles`: `10,203` `o200k_base` tokens (`30,357 B`, unfiltered all 18 printers / 9 materials / 6 inserts — only called once or filtered by `--tech`).+- **4-View Composite Heatmap Savings (`Tier B` + `Tier A`):** Rendering all 4 orthographic/isometric severity views into one `512×512` 2×2 composite PNG (`13,137–78,948 B`, `3.92 ms` pure-Rust renderer per `docs/AUTORESEARCH_HILLCLIMB.md:29`) cuts VLM image-token cost **`4×`** vs. 4 separate view images (`nurb_inspection.md:80`).++#### 3B. Exact RAG Token Compression Across `k ∈ {3, 5, 10}` (`Tier A`)+Full raw corpus + report size: **`75,723` `o200k_base` tokens** (`290,300 B`: `software.jsonl` `22,652` + `manufacturers.jsonl` `30,928` + `papers.jsonl` `15,795` + `nurb_inspection.md` `6,348`). Total DB `chunks.text` across `448` chunks: **`76,571` `o200k_base` tokens** (`36,147` lexical words; `87,062` `embedding_ready_text` tokens).++| `top_k` | Rank-1 Accuracy (18 Queries) | `p50` / `p95` (ms) | Mean Retrieved `chunks.text` (`o200k_base`) | Compression vs. Raw (`75,723` tok) | Compression vs. DB `text` (`76,571` tok) | Mean `embedding_ready` (`o200k_base`) | Mean `query_kb` JSON (`o200k_base`) | Unique Primary URLs |+|---:|---:|---:|---:|---:|---:|---:|---:|---:|+| **3** | `18/18` (`100%`) | `1.670` / `3.041` | `691.00` | **`109.58×`** | **`110.81×`** | `767.50` | `961.89` | `35` |+| **5** | `18/18` (`100%`) | `1.925` / `3.071` | `1,052.94` | **`71.92×`** | **`72.72×`** | `1,180.06` | `1,577.78` | `52` |+| **10** | `18/18` (`100%`) | `2.210` / `4.061` | `1,996.06` | **`37.94×`** | **`38.36×`** | `2,247.39` | `3,063.56` | `89` |++#### 3C. Frontier LLM Compute Spend vs. Zero-GPU Local Rust (`Tier B` + `Tier C`)+- **Published CAD & Printability Token/USD Spend (`Tier B`):**+ - `docs/PHASE2_LANGUAGE_ABLATION.md:53-55`: `Forma-Pipe` reduced total API tokens **`2.48×`** (`165,523 → 66,724`), completion tokens **`4.85×`** (`94,085 → 19,393`), and median code tokens **`5.60×`** (`644 → 115`) vs. `bpy`.+ - `docs/EXTENDED_BENCHMARK_REPORT.md:45-47,74`: `Forma-Pipe` (`low`/`medium` reasoning) cost **`$0.132–$0.202`** (`100%` Pass@3) vs. `$1.285` (`bpy` `high` reasoning, `83.3%` Pass@3 — **`6.4×–9.7×` cheaper**).+ - `research/reports/nurb_inspection.md:104-115`: `claude-fable-5` burned **`3,204` (`$0.95`)–`9,028` (`$1.92`) tokens** on `bit_block` and **`8,667` (`$1.47`)–`36,715` (`$4.84`) tokens** on `bundle_holder` (`gpt-5.6-sol` reached `593,633` cumulative context tokens on `bundle_holder`).+- **Why Local Deterministic Offload Eliminates Guesswork Token Burn (`Tier C` — Analytical Estimate):**+ - *Raw Mesh / B-Rep Context Prohibition:* Feeding `high_poly.forma`'s `1,112,436 B` uncompressed `.3mf` XML or `7,693,075 B` `.step` text directly into an LLM (`~4 bytes/token` conservative text density → **`~278k`–`1.92M` tokens**) exceeds or saturates frontier context windows just to inspect one `8,192`-face mesh. `forma-print` audits that mesh locally in `101.62 ms` and returns a **`~785`-token** structured JSON verdict + optional `78.9 KB` 4-view PNG (`~350×–2,400×` smaller than raw geometry serialization).+ - *Hardware/Protocol Context Compression:* Injecting the full `75,723`-token corpus on every session vs. `1,052.94` retrieved tokens at `k=5` saves `~74,670` prompt tokens per turn (**`71.92×` reduction**). Over a 3-turn debug session where ungrounded guesswork triggers even 1 wrong port/fault retry (observed `3×–5×` repair blowup in `PHASE1_BASELINE_REPORT.md:43`), deterministic RAG + DFM avoids extra reasoning/repair turns while adding `$0.00` local CPU compute (`2.16 MB` peak RSS for `forma` vs. `223 MB` Blender 5.3 per `VERIFICATION_REPORT.md:38`).++---++### Axis 4 — Deterministic Geometry & Printer-API Verification (`Tier A` + `Tier B`)++| Verification Dimension | Ungrounded LLM Guesswork | `Forma` + `forma-print` + RAG KB |+|---|---|---|+| **Topological Gate** | Cannot verify closed 2-manifoldness from script text; Blender `bpy` silently exited `0` on `5` `NM>0` corruptions (`PHASE1_BASELINE_REPORT.md:32`). | `WT=ok NM=0 B=0` checked first; `strict: true` auto-rolls back invalid booleans; `500`-op strict fuzz = `100%` watertight (`VERIFICATION_REPORT.md:52`). |+| **DFM & Print Physics** | Heuristic/visual guessing of overhangs, wall thickness, islands, and tipping. | 9 deterministic checks (`profiles.rs` 18 printers / 9 materials / 6 inserts): BVH `±12°` cone-ray wall thickness, Z-slice + vertex-minima floating islands, bridge span vs. unsupported ceiling, 2D convex-hull CoM stability, `spatial::clearance`, AMS swap/purge estimation. |+| **Unit & Slicer Packaging** | Common `m` vs `mm` 1000× scaling errors; LLMs cannot synthesize valid binary Deflate ZIPs. | Explicit `--unit m\|mm\|auto` (`scale_to_mm=1000.0`), pure-Rust RFC-1951 Deflate `.3mf` (`unit="millimeter"`, `<basematerials>`, `<m:colorgroup>`, all 8 slicer-native entries, **`1.574×–5.998×`** file-level compression), and AP214 `.step` (`SI_UNIT(.MILLI.,.METRE.)`). |+| **Printer API & Fault Provenance** | Vulnerable to hallucinated endpoints, outdated firmware auth assumptions, or invented fault codes. | Draft 2020-12 schema-validated JSONL (`130/130` `source_verified == true`, `354` unique primary URLs), explicit `not_publicly_documented` / `closed_or_usb_only` / `unavailable` markers, enforced offline by `validate_kb.py` (5/5 stages). |++---++## 4. Explicit Non-Replacement Architectural Boundaries++Per `contribute/forma-print.md` and `research/reports/nurb_inspection.md:146-150`, **`forma-print` + RAG is intentionally scoped as a lightweight pre-print verification, packaging, and knowledge-grounding layer — NOT a replacement for downstream manufacturing applications.**++| External System Category | Representative Systems (from `software.jsonl` & `nurb_inspection.md`) | What They Own (Out of Scope for `forma-print` Tier 1) | What `Forma + forma-print + RAG` Owns | Exact Handoff Contract |+|---|---|---|---|---|+| **Full G-Code / MSLA Slicers** | `OrcaSlicer`, `PrusaSlicer`, `Bambu Studio`, `Cura` / `CuraEngine`, `CHITUBOX`, `Lychee Slicer` | Toolpath planning, Arachne variable line width, organic/tree supports, infill patterns, scarf seams, pressure advance, cooling fan curves, volumetric flow limits, `.gcode`/`.bgcode`/`.ctb`/`.goo` binary generation. | Pre-slicer DFM audit, auto-orientation, unit scaling (`m → mm`), AMS/MMU swap estimation, and slicer-ready multi-material packaging. | Deflate `.3mf` (`unit="millimeter"` + `Metadata/{model_settings.config, project_settings.config, plate_1.json, Slic3r_PE_model.config, plate_1.png}`) or `.step`; optional Tier 3 `slicer-cli` subprocess bridge (`contribute/forma-print.md:132`). |+| **Interactive GUI CAD & Heavy B-Rep Daemons** | `OpenSCAD`, `CadQuery`, `build123d`, `Zoo/KCL`, `Shpigford/nurb` Desktop (and conceptual desktop GUIs like Fusion 360 / Blender / Shapr3D) | Interactive 3D viewports, constraint sketching, NURBS/BREP filleting/drafting UI, persistent workspace SQLite projects, `~45 s` OCCT C++ runtime or `~953 MB` GUI studio suites. | `1.734–2.294 MB` stateless headless polyhedral modeling (`Forma-Pipe`), sub-40 ms DFM/orient/export, and `788 + 391` `o200k_base` MCP tools. | `.forma` scripts, `.step` (faceted AP214), `.stl`, `.obj`, `.glb`, `.3mf`, plus 4-view diagnostic `.png` heatmaps. |+| **Printer Firmware** | `Klipper`, `Marlin`, `RepRapFirmware`, `Prusa-Firmware-Buddy` | Real-time MCU step/dir timing, kinematics (CoreXY/Delta/bedslinger), PID thermal runaway loops, `ADXL345` input shaping, CAN-FD toolboard comms, sensor interrupt handling. | Static hardware envelope & thermal/nozzle constraints (`profiles.rs`), plus RAG-indexed firmware capabilities and fault-code diagnostics. | G-code emitted by the user's slicer (never generated or streamed directly by Tier 1 `forma-print`). |+| **Host, Fleet & Spool Daemons** | `OctoPrint`, `Moonraker`, `Mainsail`, `Fluidd`, `PrusaLink`, `Spoolman` | Long-running HTTP/WebSocket job queues, webcam RTSP/MJPEG streams, live temperature graphs, filament spool weight tracking, emergency cancel/pause control. | Exact primary-source protocol, port, auth mode, sensor telemetry, and fault-code lookup via `query_rag.py` (offline `1.7188 MiB` SQLite DB). | Verified local/cloud endpoint specs (`Moonraker` `7125/tcp`, `PrusaLink` `80/tcp`, `SDCP` `3030/tcp`, `Bambu` `8883/990`, or `closed_or_usb_only`); optional Tier 3 `net-lan` feature (`contribute/forma-print.md:133`). |++---++## 5. Reproducibility & Verification Commands++Run all commands from the repository root (zero tracked files are modified):++```bash+# 1. Reproduce all live Tier A measurements (footprints, MCP o200k tokens, CLI p50/p95, 18-query RAG)+python3 research/scripts/bench_efficiency.py --json+python3 research/scripts/bench_efficiency.py++# 2. Verify KB schemas, 130/130 source_verified records, secret scan, isolation, and RAG p95 < 100 ms+python3 research/scripts/validate_kb.py --json++# 3. Verify Tier 1 Rust implementation (profiles, units, BVH, DFM, heatmap, orient, 3MF/STEP, MCP)+cargo test -p forma-print+```++---++## 6. Cross-References++- **Live Benchmark Script:** [`research/scripts/bench_efficiency.py`](../scripts/bench_efficiency.py)+- **KB & RAG Validation Suite:** [`research/scripts/validate_kb.py`](../scripts/validate_kb.py) and [`research/rag/query_rag.py`](../rag/query_rag.py)+- **M1 Inspection & Telemetry Baselines:** [`research/reports/nurb_inspection.md`](../reports/nurb_inspection.md)+- **Core CAD Benchmarks:** [`docs/PHASE1_BASELINE_REPORT.md`](../../docs/PHASE1_BASELINE_REPORT.md), [`docs/PHASE2_LANGUAGE_ABLATION.md`](../../docs/PHASE2_LANGUAGE_ABLATION.md), [`docs/EXTENDED_BENCHMARK_REPORT.md`](../../docs/EXTENDED_BENCHMARK_REPORT.md), [`docs/VERIFICATION_REPORT.md`](../../docs/VERIFICATION_REPORT.md), [`docs/AUTORESEARCH_HILLCLIMB.md`](../../docs/AUTORESEARCH_HILLCLIMB.md)+- **Tier 1–3 Architecture & Roadmap:** [`contribute/forma-print.md`](../../contribute/forma-print.md)diff --git a/research/corpus/manufacturers.jsonl b/research/corpus/manufacturers.jsonlnew file mode 100644index 0000000..c41869d--- /dev/null+++ b/research/corpus/manufacturers.jsonl@@ -0,0 +1,22 @@+{"id":"bambu_lab","manufacturer":"Bambu Lab","technologies":["FDM"],"segment":"prosumer","representative_models":["Bambu Lab X1-Carbon (X1C)","Bambu Lab P1S","Bambu Lab A1","Bambu Lab A1 mini","Bambu Lab H2D"],"direct_communication":{"local_protocols":["MQTTS (MQTT over TLS)","Implicit FTPS","TLS 1.2 LAN File Tunnel (TCP 6000 on select models)","RTSPS (X1 / H2 / P2S / X2D)","JPEG frame stream over TLS (P1 / A1 on TCP 6000)"],"cloud_protocols":["Bambu Cloud MQTTS (mqtts://us.mqtt.bambulab.com:8883)","Bambu Cloud HTTPS API (e.g., GET /v1/design-user-service/my/preference)"],"ports":["8883/tcp (MQTTS telemetry & control)","990/tcp (Implicit FTPS file upload & timelapse download)","322/tcp (RTSPS live camera stream on X1/H2/P2S/X2D)","6000/tcp (Model-dependent: TLS-wrapped JPEG video stream on A1/P1, or TLS 1.2 binary-framed LAN file-transfer tunnel on select models)"],"auth_and_modes":"Requires enabling LAN Only Mode AND Developer Mode on the printer touchscreen (Authorization Control System / ACS) for third-party local control; authenticates with username 'bblp' and the 8-digit LAN Access Code shown on screen. Cloud mode uses 'u_{USER_ID}' and Bambu account Access Token.","upload_print_control_endpoints":["FTPS ftps://{DEVICE_IP}:990 (implicit TLS, user 'bblp', password LAN access code): upload .gcode.3mf to /sdcard/","TCP {PRINTER_IP}:6000 LAN File Tunnel (TLS 1.2 + 64-byte auth packet + 16-byte LE framed JSON: cmdtype 1=LIST_INFO, 2=SUB_FILE, 3=FILE_DEL, 4=FILE_DOWNLOAD)","MQTT topic device/{DEVICE_ID}/request: command 'project_file' (url 'file:///sdcard/<file>.gcode.3mf', param 'Metadata/plate_1.gcode', plate_idx, use_ams)","MQTT topic device/{DEVICE_ID}/request: command 'gcode_line' (raw G-code execution, gated by Developer Mode) & info.get_version","MQTT topic device/{DEVICE_ID}/report: JSON telemetry & command response stream","Official public local API specification: not_publicly_documented (documented via community RE such as Doridian/OpenBambuAPI & greghesp/ha-bambulab)"],"offline_capable":true,"offline_mode_notes":"Supports microSD/USB offline printing and full local LAN Only + Developer Mode operation without Bambu Cloud (Bambu Handy remote cloud features are disabled in LAN Only Mode).","status":"gated_local_or_community_re"},"monitoring_and_sensors":{"thermal_sensors":"Nozzle thermistor, heatbed thermistor, and chamber temperature sensor on X1C and H2D (H2D adds active chamber heating up to 65 C); P1S, A1, and A1 mini have NO hardware chamber temperature sensor.","cameras":"X1/P2S/H2: rtsps://bblp:<Access_Code>@<Printer_IP>:322/streaming/live/1 (requires LAN Mode or LAN Mode Liveview); P1/A1: proprietary JPEG frames over TLS on TCP port 6000; H2D adds nozzle macro camera + BirdsEye top camera.","lidar_and_ai_inspection":"X1C: dual-beam LiDAR (first-layer inspection & flow calibration) + AI spaghetti/failure camera; H2D: nozzle AI camera + BirdsEye vision (spaghetti, nozzle clumping, air-print detection); P1S/A1/A1 mini: no LiDAR.","filament_and_spool_systems":"AMS / AMS 2 Pro / AMS Lite (4-16 slots) with Bambu RFID tag auto-identification (material, color, recommended temperatures), filament runout/hub sensors, and AMS assist motor overload detection.","accelerometers_input_shaper":"Built-in toolhead vibration/resonance compensation (input shaper).","bed_probes":"X1C/P1S: bed force/piezo sensors; A1/A1 mini/H2D: non-contact Eddy Current Sensor for mesh leveling and flow calibration.","status_error_feeds":"MQTT topic device/{DEVICE_ID}/report JSON push stream (temperatures, progress, AMS state, HMS error codes)."},"troubleshooting_and_faults":{"fault_code_taxonomy":"HMS (Health Management System) 16-digit hyphenated hex codes XXXX-XXXX-XXXX-XXXX (Module-ModuleNo-Part-AlertLevel): 0300=heatbed/nozzle/temp/AI monitoring, 0500=toolhead/MC/AP/AMS/WiFi comms, 0700=AMS assist/feed; separate forced screen Error Codes also exist.","example_fault_codes":[{"code":"HMS_0700-0100-0002-0002","description":"The AMS assist motor is overloaded; filament may be tangled or stuck (also 0701/0702/0703 variants).","kb_url":"https://wiki.bambulab.com/en/x1/troubleshooting/hmscode/0700_0100_0002_0002"},{"code":"HMS_0500-0400-0001-0002","description":"Failed to report task state to cloud service; please check your network connection.","kb_url":"https://wiki.bambulab.com/en/x1/troubleshooting/hmscode/0500_0400_0001_0002"},{"code":"HMS_0500-0300-0002-000C","description":"Wireless hardware error detected by AP board.","kb_url":"https://wiki.bambulab.com/en/x1/troubleshooting/hmscode/0500_0300_0002_000C"},{"code":"HMS_0500-0300-0001-0003","description":"The AMS module is malfunctioning; check AMS cables and internal connections.","kb_url":"https://wiki.bambulab.com/en/x1/troubleshooting/hmscode/0500_0300_0001_0003"}],"diagnostic_logs":"Export via touchscreen: Settings -> General -> Export Log to MicroSD Card (or FAT32 USB), producing a .tar / .tar.gz archive of daemon, network, and system logs.","official_kb_urls":["https://wiki.bambulab.com/en/hms/home","https://wiki.bambulab.com/en/hms/error-code","https://wiki.bambulab.com/en/knowledge-sharing/enable-lan-mode","https://wiki.bambulab.com/en/knowledge-sharing/enable-developer-mode"]},"source_urls":["https://wiki.bambulab.com/en/hms/home","https://wiki.bambulab.com/en/hms/error-code","https://wiki.bambulab.com/en/knowledge-sharing/enable-lan-mode","https://wiki.bambulab.com/en/knowledge-sharing/enable-developer-mode","https://github.com/Doridian/OpenBambuAPI","https://github.com/Doridian/OpenBambuAPI/blob/main/mqtt.md","https://github.com/Doridian/OpenBambuAPI/blob/main/lan-file-tunnel.md","https://github.com/Doridian/OpenBambuAPI/blob/main/ftp.md","https://github.com/Doridian/OpenBambuAPI/blob/main/video.md","https://github.com/greghesp/ha-bambulab","https://github.com/bambulab/BambuStudio"],"source_verified":true,"availability_notes":"Official local MQTT/FTPS/TCP-6000 protocol specification is not_publicly_documented by Bambu Lab and is documented via community reverse engineering (Doridian/OpenBambuAPI, greghesp/ha-bambulab). Current firmware gates local control mutations behind LAN Only + Developer Mode (ACS).","relevance_to_forma_print":"Matches profiles bambu_a1_mini, bambu_a1, bambu_p1s, bambu_x1c, bambu_h2d_single, and bambu_h2d_dual; validates Metadata/model_settings.config + project_settings.config + plate_1.json .3mf layout for AMS/H2D dual-nozzle purge estimation; P1S/A1 missing chamber temp sensor affects ABS/ASA warping guidance."}+{"id":"prusa_research","manufacturer":"Prusa Research","technologies":["FDM","MSLA"],"segment":"prosumer","representative_models":["Original Prusa MK4S","Prusa CORE One","Original Prusa XL","Original Prusa MINI+","Original Prusa SL1S SPEED"],"direct_communication":{"local_protocols":["HTTP REST (PrusaLink /api/v1/, OpenAPI 3.0.1)","Prusa Connect Local (self-hosted local-first fleet server)"],"cloud_protocols":["HTTPS REST (Prusa Connect connect.prusa3d.com)","Prusa Camera Service API (camera-service.prusa3d.com/v1/...)"],"ports":["80/tcp (PrusaLink HTTP REST)","8080/tcp (optional PrusaLink / Raspberry Pi reverse proxy)","443/tcp (Prusa Connect HTTPS)"],"auth_and_modes":"PrusaLink OpenAPI 3.0.1 uses HTTP Digest Access Authentication (digestAuth; user 'maker' or 'jo' on Pi; screen-provided password or X-Api-Key header under Settings > Network > PrusaLink on Buddy printers). Prusa Connect Camera API uses a 20-character alphanumeric camera token.","upload_print_control_endpoints":["GET http://<ip>/api/version","GET http://<ip>/api/v1/info","GET http://<ip>/api/v1/status (returns required 'printer' + optional 'job', 'transfer', 'storage', 'camera')","GET http://<ip>/api/v1/job","PUT http://<ip>/api/v1/job/{id}/pause","PUT http://<ip>/api/v1/job/{id}/resume","DELETE http://<ip>/api/v1/job/{id}","GET http://<ip>/api/v1/storage","GET/POST/PUT http://<ip>/api/v1/files/{storage}/{path} (supports Print-After-Upload and Overwrite headers)","Cloud Camera: https://connect.prusa3d.com/c/snapshot (legacy) & https://camera-service.prusa3d.com/v1/... (current)"],"offline_capable":true,"offline_mode_notes":"Full offline USB drive printing (.bgcode/.gcode/.sl1s) and 100% local LAN operation via PrusaLink (/api/v1/) or self-hosted Prusa Connect Local without internet.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Hotend & heatbed thermistors, Nextruder Dwarf board sensors, and CORE One chamber temperature sensor.","cameras":"Periodic JPEG snapshot upload via Prusa Connect Camera API (/c/snapshot or camera-service.prusa3d.com/v1/...) plus official Buddy3D Wi-Fi camera with IR illumination; no native continuous RTSP from Buddy board.","lidar_and_ai_inspection":"unavailable (no native LiDAR or onboard AI spaghetti detection).","filament_and_spool_systems":"Nextruder Hall-effect/magnetic filament sensor, MMU3 (5-slot), XL independent multi-toolhead (1-5 toolheads).","accelerometers_input_shaper":"Input Shaper supported across Buddy firmware with optional/supported accelerometer calibration.","bed_probes":"Nextruder Loadcell sensor (MK4S, CORE One, XL — nozzle-touch probing and collision detection); SuperPINDA inductive probe (MINI+).","status_error_feeds":"GET /api/v1/status polling (job, printer, transfer, storage, camera) and upstream Prusa Connect telemetry."},"troubleshooting_and_faults":{"fault_code_taxonomy":"5-digit QR error codes XXYZZ: XX=model (12=MINI, 13=MK4, 17=XL, 21=MK3.9, 26=MK4S, 27=MK3.9S, 31=CORE One, 35=CORE One L), Y=subsystem (1=Mechanical, 2=Temperature/Heating, 3=Homing/Calibration, 5=Electronics/System/BSOD, 8=Timeouts/Crash Recovery), ZZ=specific fault.","example_fault_codes":[{"code":"#31208 / #26208 / #13208","description":"Hotend mintemp error (CORE One / MK4S / MK4 print head thermistor wiring or <15 C ambient).","kb_url":"https://help.prusa3d.com/article/hotend-mintemp-error-31208-core-one-35208-core-one-l-26208-mk4s-13208-mk4-27208-mk3-9s-21208-mk3-9_401189"},{"code":"#31203 / #26203 / #13203","description":"Bed thermal runaway (CORE One / MK4S / MK4 heatbed thermistor or heater drop).","kb_url":"https://help.prusa3d.com/article/bed-thermal-runaway-31203-core-one-35203-core-one-l-36203-core-one-indx-26203-mk4s-13203-mk4-27203-mk3-9s-21203-mk3-9-28203-mk3-5s-23203-mk3-5_401068"},{"code":"#31538 / #26538 / #17538","description":"Blue Screen of Death (BSOD) / firmware crash / critical system exception.","kb_url":"https://help.prusa3d.com/article/blue-screen-of-death-bsod-31538-core-one-35538-core-one-l-36538-core-one-indx-26538-mk4s-13538-mk4-27538-mk3-9s-17538-xl-21538-mk3-9-28538-mk3-5s-23538-mk3-5-12538-mi_689421"},{"code":"#12204","description":"Thermal runaway print head on MINI (6 C drop unrecovered after 20s).","kb_url":"https://help.prusa3d.com/article/thermal-runaway-print-head-12204-mini_154813"}],"diagnostic_logs":"Buddy firmware writes crash dumps to internal xFlash memory (persists across reboots until D22 command); retrieve via USB serial at 115200 baud (PuTTY / OctoPrint serial logging).","official_kb_urls":["https://help.prusa3d.com/en/","https://help.prusa3d.com/article/qr-error-codes_176114"]},"source_urls":["https://github.com/prusa3d/Prusa-Link-Web","https://github.com/prusa3d/Prusa-Link-Web/blob/master/spec/openapi.yaml","https://github.com/prusa3d/Prusa-Firmware-Buddy","https://help.prusa3d.com/en/","https://help.prusa3d.com/article/qr-error-codes_176114","https://connect.prusa3d.com"],"source_verified":true,"availability_notes":"Open official OpenAPI 3.0.1 spec in prusa3d/Prusa-Link-Web/blob/master/spec/openapi.yaml and open-source Buddy firmware; native LiDAR and onboard AI failure detection are unavailable.","relevance_to_forma_print":"Matches profiles prusa_mk4s, prusa_core_one, and prusa_xl; informs Metadata/Slic3r_PE_model.config extruder mapping in export_3mf.rs and PrusaLink HTTP Digest/X-Api-Key upload workflow."}+{"id":"voron_design","manufacturer":"Voron Design","technologies":["FDM"],"segment":"ecosystem","representative_models":["Voron 2.4","Voron Trident","Voron V0.2","Voron Switchwire"],"direct_communication":{"local_protocols":["HTTP REST (Moonraker)","JSON-RPC 2.0 over WebSocket (Moonraker)","Mainsail / Fluidd HTTP WebUI","Crowsnest MJPEG / WebRTC"],"cloud_protocols":["none_native (optional third-party: Obico, OctoEverywhere, SimplyPrint)"],"ports":["7125/tcp (Moonraker HTTP REST & WebSocket)","80/tcp (Mainsail/Fluidd reverse proxy)","8080/tcp (Crowsnest webcam stream)"],"auth_and_modes":"moonraker.conf [authorization] trusted_clients CIDR allowlist and cors_domains; untrusted clients use JSON Web Token (JWT), API key, or oneshot tokens.","upload_print_control_endpoints":["POST http://<ip>:7125/server/files/upload (HTTP-exclusive multipart G-code upload to 'gcodes' root)","GET http://<ip>:7125/server/info","GET http://<ip>:7125/printer/info","GET http://<ip>:7125/printer/objects/query?extruder&heater_bed","POST http://<ip>:7125/printer/gcode/script?script=<gcode>","POST http://<ip>:7125/printer/emergency_stop","POST http://<ip>:7125/printer/print/pause | resume | cancel","WS ws://<ip>:7125/websocket (JSON-RPC 2.0: printer.objects.subscribe, printer.gcode.script)","WS ws://<ip>:7125/klippysocket (raw Klippy bridge)"],"offline_capable":true,"offline_mode_notes":"100% local LAN and offline capable via Klipper + Moonraker + Mainsail/Fluidd without any cloud account or internet connectivity.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Hotend, heatbed, enclosed chamber, and MCU/SBC host thermistors configured in Klipper printer.cfg.","cameras":"Crowsnest (ustreamer / camera-streamer) exposing MJPEG (/webcam/?action=stream on port 8080/80) or WebRTC.","lidar_and_ai_inspection":"unavailable natively (optional third-party Obico AI monitoring via Moonraker plugin).","filament_and_spool_systems":"Optional filament runout switch, ERCF (Enraged Rabbit Carrot Feeder) / BoxTurtle MMU, and Moonraker [spoolman] (:7912) inventory integration.","accelerometers_input_shaper":"ADXL345 / LIS2DW accelerometers over SPI/USB toolhead board for Klipper Input Shaper resonance testing.","bed_probes":"Voron Tap (optical nozzle-actuated Z-probe), Klicky/Euclid dockable microswitch probes, inductive probes, or Beacon.","status_error_feeds":"Moonraker JSON-RPC WebSocket push notifications (notify_status_update) and HTTP polling via /printer/objects/query."},"troubleshooting_and_faults":{"fault_code_taxonomy":"Human-readable Klipper shutdown/error strings in klippy.log and Moonraker status messages (e.g., MCU shutdown, Timer too close, Heater faults, ADXL SPI errors).","example_fault_codes":[{"code":"MCU '...' shutdown: Timer too close","description":"Host failed to deliver synchronized commands to MCU in time due to CPU load, USB/CAN drops, or SD wear.","kb_url":"https://www.klipper3d.org/"},{"code":"Heater extruder not heating at expected rate","description":"Thermal protection triggered when hotend fails to track target temperature.","kb_url":"https://www.klipper3d.org/"},{"code":"Invalid adxl345 id (got 0 vs e5)","description":"SPI communication failure between host/MCU and ADXL345 accelerometer.","kb_url":"https://www.klipper3d.org/"}],"diagnostic_logs":"klippy.log (with Stats blocks: sysload, memavail, buffer_time, bytes_retransmit) and moonraker.log accessible in Mainsail/Fluidd UI or via POST /server/logs/rollover.","official_kb_urls":["https://docs.vorondesign.com/","https://www.klipper3d.org/","https://moonraker.readthedocs.io/en/stable/external_api/introduction/","https://moonraker.readthedocs.io/en/stable/external_api/file_manager/"]},"source_urls":["https://docs.vorondesign.com/","https://mods.vorondesign.com/","https://github.com/VoronDesign","https://www.klipper3d.org/","https://moonraker.readthedocs.io/en/stable/external_api/introduction/","https://moonraker.readthedocs.io/en/stable/external_api/file_manager/","https://moonraker.readthedocs.io/en/stable/external_api/printer/","https://github.com/Arksine/moonraker"],"source_verified":true,"availability_notes":"Fully open-source hardware and Klipper/Moonraker software ecosystem; file transfers (upload/download) are HTTP-exclusive in Moonraker.","relevance_to_forma_print":"Matches profiles voron_24_250, voron_24_300, and voron_24_350; validates CNC Kitchen/Voron M3_voron heat-set insert table and Moonraker POST /server/files/upload LAN target."}+{"id":"creality","manufacturer":"Creality","technologies":["FDM","MSLA"],"segment":"consumer","representative_models":["Creality K1","Creality K1C","Creality K1 Max","Creality K2 Plus","Creality Ender-3 V3","Creality Halot-Mage","Creality Halot-Play"],"direct_communication":{"local_protocols":["Fluidd WebUI (port 4408 on K1/Ender-3 V3)","Moonraker HTTP/WS (port 7125 native on K2 Plus, or via root/Helper Script on K1/Ender-3 V3)","Local WebSocket status API (port 9999)"],"cloud_protocols":["Creality Cloud App & WebRTC camera daemon"],"ports":["4408/tcp (Fluidd WebUI on K1 / Ender-3 V3)","7125/tcp (Moonraker API native on K2 Plus / rooted K1)","9999/tcp (Local WebSocket status API)"],"auth_and_modes":"K2 Plus exposes Moonraker (:7125) locally out-of-the-box; K1/K1C/Ender-3 V3 expose Fluidd (:4408) locally and unlock full Moonraker/Fluidd/Mainsail via SSH root + Guilouz Creality-Helper-Script (some newer 2025 factory firmware revisions restrict root access). Halot MSLA LAN/cloud API is proprietary.","upload_print_control_endpoints":["K2 Plus & rooted K1/Ender-3 V3: Moonraker POST http://<ip>:7125/server/files/upload & WS ws://<ip>:7125/websocket","Stock K1/Ender-3 V3: Fluidd WebUI on http://<ip>:4408; local WebSocket telemetry on port 9999 (community RE)","Halot MSLA direct local API: not_publicly_documented"],"offline_capable":true,"offline_mode_notes":"USB drive offline printing supported across FDM and Halot MSLA lines; LAN printing and monitoring work without Creality Cloud via Fluidd (:4408) / Moonraker (:7125) on K-series and Ender-3 V3.","status":"gated_local_or_community_re"},"monitoring_and_sensors":{"thermal_sensors":"Hotend and heatbed thermistors; K2 Plus adds actively heated chamber thermistor/control.","cameras":"Stock K1/K1 Max internal camera uses proprietary cam_app shared memory -> Creality Cloud WebRTC (no open RTSP/MJPEG out-of-the-box without root + go2rtc/mjpeg-streamer).","lidar_and_ai_inspection":"K1 Max and K2 Plus include LiDAR + AI camera (first-layer scan, flow calibration, spaghetti/foreign-object detection).","filament_and_spool_systems":"Filament runout sensors; K2 Plus supports CFS (Creality Filament System, up to 16 slots) with RFID filament recognition and automated cutter; closed-loop step-servo motors on K2 Plus.","accelerometers_input_shaper":"Integrated toolhead G-sensor / ADXL345 accelerometer for Klipper input shaping.","bed_probes":"Toolhead/bed strain gauge loadcell sensors for automatic Z-offset and bed mesh leveling (K1, K2 Plus, Ender-3 V3).","status_error_feeds":"Moonraker WebSocket (:7125) on K2 Plus/rooted units, Fluidd (:4408), and local WebSocket (:9999)."},"troubleshooting_and_faults":{"fault_code_taxonomy":"Creality keyXXXX / TE / CM hardware & Klipper error codes (e.g., key: 2564 heating, key: 2000 MCU error, CM2784/2786/2788/2789 K2/Hi motor resistance overcurrent).","example_fault_codes":[{"code":"key: 2564","description":"The extruder is not heating as expected (nozzle heating or thermosensitive detection malfunction).","kb_url":"https://wiki.creality.com/en/ender-series/ender-3-v3/troubleshooting/2564-error-trouble-shooting"},{"code":"Key: 2000","description":"Unknown exception / unable to update MCU configuration because MCU is closed.","kb_url":"https://wiki.creality.com/en/ender-series/ender-3-v3-plus/troubleshooting/2000-error-trouble-shooting"},{"code":"CM2784","description":"Abnormal resistance in X/Y/Z/E movement direction triggering motor overcurrent protection (K2 Series / Creality Hi).","kb_url":"https://wiki.creality.com/en/printers-general-documents/CM2784"}],"diagnostic_logs":"Local USB export via Settings -> Help / Fault Reporting -> Export Log (FAT32 USB), Creality Cloud Workbench -> Send Feedback -> Upload Logs, or klippy.log on Klipper/rooted units.","official_kb_urls":["https://wiki.creality.com/en/home","https://wiki.creality.com/en/k1-flagship-series/k1/troubleshooting","https://wiki.creality.com/en/halot-series"]},"source_urls":["https://wiki.creality.com/en/home","https://wiki.creality.com/en/k1-flagship-series/k1/troubleshooting","https://wiki.creality.com/en/printers-general-documents/CM2784","https://wiki.creality.com/en/ender-series/ender-3-v3/troubleshooting/2564-error-trouble-shooting","https://wiki.creality.com/en/halot-series","https://github.com/Guilouz/Creality-Helper-Script"],"source_verified":true,"availability_notes":"K2 Plus exposes Moonraker (:7125) natively, whereas stock K1 camera/WebSocket APIs and Halot MSLA network APIs are not_publicly_documented and require community RE or root scripts (restricted on some newer revisions).","relevance_to_forma_print":"Matches profiles creality_k1c and creality_k2_plus; informs CFS 16-slot multi-color .3mf metadata and active chamber profile constraints."}+{"id":"anycubic","manufacturer":"Anycubic","technologies":["FDM","MSLA"],"segment":"consumer","representative_models":["Anycubic Kobra 3","Anycubic Kobra S1","Anycubic Kobra 2 Pro","Anycubic Photon Mono M5s","Anycubic Photon Mono M7 Pro"],"direct_communication":{"local_protocols":["HTTP local discovery (/info, /ctrl on port 18910 — Kobra 3/S1 LAN Mode)","mTLS MQTT broker (port 9883 — Kobra 3/S1 LAN Mode)","Moonraker/Mainsail/Fluidd (via community Rinkhals firmware overlay)"],"cloud_protocols":["Anycubic Cloud / Anycubic App / Anycubic Slicer Next"],"ports":["18910/tcp (HTTP local discovery /info & /ctrl auth)","9883/tcp (mTLS local MQTT broker in LAN Mode)","7125/tcp (Moonraker via unofficial community Rinkhals overlay only)"],"auth_and_modes":"Kobra 3 and Kobra S1 support Settings -> Network -> LAN Mode on touchscreen; local HTTP GET :18910/info returns token and /ctrl endpoint for mTLS MQTT session. Community Rinkhals overlay adds SSH (root/rockchip) and Moonraker/Mainsail/Fluidd. Photon Mono M7 Pro and Kobra 2 lack documented standalone LAN APIs and default to Anycubic Cloud.","upload_print_control_endpoints":["Official local API documentation: not_publicly_documented by Anycubic","Community RE (Kobra 3/S1 LAN Mode): GET http://<ip>:18910/info -> /ctrl auth -> mTLS MQTT port 9883","Community Rinkhals overlay: standard Moonraker (:7125) endpoints","Photon Mono M5s / M7 Pro local control API: not_publicly_documented (cloud/USB-first)"],"offline_capable":true,"offline_mode_notes":"USB flash drive offline printing supported across FDM and MSLA models; Kobra 3/S1 support LAN Mode without cloud via Anycubic Slicer Next or community MQTT/Rinkhals tools; Photon Mono M7 Pro relies heavily on Anycubic Cloud for networked printing.","status":"cloud_first_limited_local"},"monitoring_and_sensors":{"thermal_sensors":"Hotend and bed thermistors on FDM; Photon Mono M7 Pro includes resin tank thermal & resin level monitoring.","cameras":"USB camera supported on Kobra 3/S1 (community proxy 'acproxycam' bridges feed to Mainsail/Fluidd/Home Assistant); no standardized open RTSP documented by Anycubic.","lidar_and_ai_inspection":"unavailable (no native LiDAR documented).","filament_and_spool_systems":"Filament break/runout sensor; ACE Pro multi-color engine (4-slot per box, filament weight/type/color, integrated drying, RFID).","accelerometers_input_shaper":"Resonance compensation supported on Kobra 3 / S1 GoKlipper firmware.","bed_probes":"LeviQ automated bed leveling (strain-gauge / inductive depending on generation).","status_error_feeds":"Local mTLS MQTT (:9883) telemetry in LAN Mode (community RE) or Anycubic Cloud API."},"troubleshooting_and_faults":{"fault_code_taxonomy":"5-digit numeric error codes (e.g., 101xx print/filament tasks, 104xx/114xx network/cloud timeouts, 115xx ACE Pro color engine faults).","example_fault_codes":[{"code":"10101","description":"Print job already active (print task already exists).","kb_url":"https://wiki.anycubic.com/"},{"code":"10107","description":"Abnormal filament / filament broken or ACE Pro filament runout.","kb_url":"https://wiki.anycubic.com/en/error-codes/10107-code/s1"},{"code":"11503","description":"Color engine connection problem; check ACE Pro power and signal cables.","kb_url":"https://wiki.anycubic.com/en/error-codes/11503-code/kobra-3"},{"code":"11402","description":"Network connection timeout.","kb_url":"https://wiki.anycubic.com/"}],"diagnostic_logs":"Stock firmware log retrieval is via Anycubic App/support workflows; Rinkhals overlay exposes SSH and standard Klipper/Moonraker logs.","official_kb_urls":["https://wiki.anycubic.com/","https://wiki.anycubic.com/en/error-codes/10107-code","https://wiki.anycubic.com/en/error-codes/11503-code","https://wiki.anycubic.com/en/resin-3d-printer/photon-mono-m7-pro"]},"source_urls":["https://wiki.anycubic.com/","https://wiki.anycubic.com/en/error-codes/10107-code/s1","https://wiki.anycubic.com/en/error-codes/11503-code/kobra-3","https://wiki.anycubic.com/en/resin-3d-printer/photon-mono-m7-pro","https://github.com/jbatonnet/Rinkhals","https://jbatonnet.github.io/Rinkhals/"],"source_verified":true,"availability_notes":"Anycubic does not publish an official public LAN API specification; Kobra 3/S1 LAN Mode HTTP (:18910) + mTLS MQTT (:9883) is community-RE documented, and Photon Mono M7 Pro / Kobra 2 remain cloud-first or USB-offline.","relevance_to_forma_print":"Highlights need for cloud-free USB/3MF export fallback on Photon Mono M7 Pro and ACE Pro multi-slot color metadata mapping."}+{"id":"elegoo","manufacturer":"Elegoo","technologies":["FDM","MSLA"],"segment":"consumer","representative_models":["Elegoo Centauri Carbon","Elegoo Centauri Carbon 2","Elegoo Neptune 4","Elegoo Saturn 4 Ultra","Elegoo Mars 5 Ultra"],"direct_communication":{"local_protocols":["SDCP v3.0 (UDP discovery + WebSocket JSON + HTTP chunked upload) on Centauri Carbon, Centauri Carbon 2, Saturn 4 Ultra, Mars 5 Ultra","Moonraker HTTP/WS + Fluidd (Klipper) on Neptune 4"],"cloud_protocols":["Elegoo Matrix / Chitu ecosystem relays (optional)"],"ports":["3000/udp (SDCP discovery broadcast 'M99999')","3030/tcp (SDCP WebSocket /websocket & HTTP /uploadFile/upload)","554/tcp (RTSP camera stream /video)","3031/tcp (HTTP MJPEG camera /video on select firmware builds)","7125/tcp (Moonraker HTTP/WS on Neptune 4)","80/tcp (Fluidd WebUI on Neptune 4)"],"auth_and_modes":"SDCP v3.0 printers (Centauri Carbon, Saturn 4 Ultra, Mars 5 Ultra) accept local LAN WebSocket and HTTP upload connections on port 3030 without an initial TLS handshake or auth token out-of-the-box. Neptune 4 runs Klipper/Moonraker (:7125) and Fluidd.","upload_print_control_endpoints":["UDP broadcast 'M99999' to port 3000 -> returns JSON with MainboardIP, MainboardID (16-bit), ProtocolVersion V3.0.0","WS ws://${MainboardIP}:3030/websocket (topics: sdcp/request/${MainboardID}, sdcp/response/${MainboardID}, sdcp/status/${MainboardID}, sdcp/attributes/${MainboardID}, sdcp/error/${MainboardID}, sdcp/notice/${MainboardID}; Cmd 0=status, Cmd 1=attributes, Cmd 128=start print)","POST http://${MainboardIP}:3030/uploadFile/upload (multipart/form-data: S-File-MD5, Check, Offset, Uuid, TotalSize, File in 1MB chunks)","Neptune 4: standard Moonraker (:7125) /server/files/upload & /printer/print/start"],"offline_capable":true,"offline_mode_notes":"USB offline printing supported on all models; full cloud-free local LAN control and file upload via SDCP v3.0 (:3030) on Centauri Carbon / Saturn 4 Ultra / Mars 5 Ultra and via Moonraker (:7125) on Neptune 4.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Hotend and bed thermistors (Centauri Carbon / Neptune 4); UV light source / system thermistors (Saturn 4 Ultra / Mars 5 Ultra).","cameras":"RTSP stream at rtsp://<ip>:554/video (strict limit of max 2 concurrent streams; abrupt client kill without RTSP TEARDOWN leaks NumberOfVideoStreamConnected and can freeze UI) or HTTP :3031/video on select builds.","lidar_and_ai_inspection":"Saturn 4 Ultra includes built-in AI camera for failure/floating-part detection and time-lapse; no LiDAR.","filament_and_spool_systems":"Centauri Carbon supports CANVAS multi-color system, filament runout detection, cutter, and load/unload sensors.","accelerometers_input_shaper":"ADXL345 / input shaper supported on Neptune 4 Klipper stack.","bed_probes":"Saturn 4 Ultra / Mars 5 Ultra: mechanical sensor for one-touch auto-leveling, foreign-object detection (prevents LCD cracking), resin-level alerts, and tilt-release vat; Neptune 4: inductive probe.","status_error_feeds":"SDCP WebSocket topics sdcp/status/${MainboardID}, sdcp/error/${MainboardID}, sdcp/notice/${MainboardID}; Moonraker WebSocket on Neptune 4."},"troubleshooting_and_faults":{"fault_code_taxonomy":"SDCP HTTP upload integer codes (-1 to -4), Centauri Carbon / Saturn structured operational integer codes (101-104 heating, 1101-1102 exhaust vent, 1211-1263 material/extruder/cutter), and Klipper klippy.log strings on Neptune 4.","example_fault_codes":[{"code":"101 - 102","description":"Heated bed temperature rise failure, thermistor damage, or disconnected sensor.","kb_url":"https://wiki.elegoo.com/"},{"code":"103 - 104","description":"Hotend ceramic heating element fault or nozzle temperature sensor disconnection.","kb_url":"https://wiki.elegoo.com/"},{"code":"1211 - 1263","description":"Material system faults (filament depletion, extruder jam, cutter failure, load/unload timeout).","kb_url":"https://wiki.elegoo.com/"},{"code":"-2 (SDCP HTTP upload)","description":"Offset mismatch during chunked /uploadFile/upload transfer.","kb_url":"https://github.com/cbd-tech/SDCP-Smart-Device-Control-Protocol-V3.0.0/blob/main/SDCP(Smart%20Device%20Control%20Protocol)_V3.0.0_EN.md"}],"diagnostic_logs":"SDCP error/notice WebSocket topics and wiki troubleshooting procedures on Centauri/Saturn; klippy.log / moonraker.log on Neptune 4.","official_kb_urls":["https://wiki.elegoo.com/","https://github.com/cbd-tech/SDCP-Smart-Device-Control-Protocol-V3.0.0/blob/main/SDCP(Smart%20Device%20Control%20Protocol)_V3.0.0_EN.md"]},"source_urls":["https://wiki.elegoo.com/","https://github.com/cbd-tech/SDCP-Smart-Device-Control-Protocol-V3.0.0","https://github.com/cbd-tech/SDCP-Smart-Device-Control-Protocol-V3.0.0/blob/main/SDCP(Smart%20Device%20Control%20Protocol)_V3.0.0_EN.md","https://github.com/alfiedennen/sdcp-saturn-4-ultra","https://github.com/danielcherubini/elegoo-homeassistant","https://github.com/bjan/pycentauri","https://github.com/J-Lindvig/Centauri-Carbon-Manager"],"source_verified":true,"availability_notes":"SDCP v3.0 specification is openly published by CBD-Tech on GitHub; Centauri Carbon 2 uses the same SDCP protocol family.","relevance_to_forma_print":"Matches profiles elegoo_mars_5_ultra and elegoo_saturn_4_ultra; tilt-release MSLA physics still require strict suction-cup, drain-hole, and floating-island DFM checks to protect LCD/FEP."}+{"id":"flashforge","manufacturer":"FlashForge","technologies":["FDM"],"segment":"prosumer","representative_models":["FlashForge Adventurer 5M","FlashForge Adventurer 5M Pro","FlashForge AD5X","FlashForge Guider 3"],"direct_communication":{"local_protocols":["HTTP REST JSON API (port 8898 on AD5M/AD5X)","Raw TCP text G/M-code protocol (port 8899)","HTTP MJPEG webcam stream (port 8080)"],"cloud_protocols":["FlashCloud / Flashmaker / Orca-Flashforge Cloud"],"ports":["8898/tcp (HTTP REST JSON API)","8899/tcp (TCP G/M-code session protocol)","8080/tcp (MJPEG webcam stream /?action=stream)"],"auth_and_modes":"Enabling LAN-only mode on the touchscreen displays device Serial Number and CheckCode; HTTP port 8898 requires 'serialNumber' and 'checkCode' in request headers or JSON body. TCP port 8899 requires locking a control session via 'M601 S1' (released with 'M602').","upload_print_control_endpoints":["HTTP POST http://<ip>:8898/detail (machine status, temps, IFS slots)","HTTP POST http://<ip>:8898/product (capability flags)","HTTP POST http://<ip>:8898/control (lights, fans, job control)","HTTP POST http://<ip>:8898/uploadGcode (multipart/form-data file upload)","HTTP POST http://<ip>:8898/printGcode (start print from local file)","HTTP POST http://<ip>:8898/gcodeThumb (retrieve file thumbnails)","TCP :8899 (community RE): M601 S1 (grab control), M602 (release), ~M115 (info), ~M119 (endstops), ~M105 (temps), ~G28 (home), ~M27 (status), M28 <size> <filename> / M29 (file upload), ~M114 (coords)","Official public OpenAPI documentation: not_publicly_documented (documented via Parallel-7/flashforge-api-docs)"],"offline_capable":true,"offline_mode_notes":"Supports USB flash drive offline printing and full LAN-only operation on ports 8898/8899 without FlashCloud.","status":"gated_local_or_community_re"},"monitoring_and_sensors":{"thermal_sensors":"Extruder and build platform thermistors.","cameras":"Built-in camera MJPEG stream at http://<printer-ip>:8080/?action=stream (AD5M Pro built-in; AD5X may require optional camera kit).","lidar_and_ai_inspection":"unavailable (no native LiDAR documented).","filament_and_spool_systems":"Filament detector assembly (runout); AD5X supports 4-slot IFS (Independent Filament System) multi-color material station; AD5M Pro adds HEPA 13 + activated carbon dual air filtration, particulate detector, and safety door sensor.","accelerometers_input_shaper":"Built-in XY vibration test / accelerometer resonance compensation (input shaping) on AD5M Klipper-based firmware.","bed_probes":"Pressure-sensing / loadcell automated bed leveling.","status_error_feeds":"HTTP POST :8898/detail JSON polling or TCP :8899 ~M105/~M27/~M114 polling."},"troubleshooting_and_faults":{"fault_code_taxonomy":"Firmware diagnostic E-codes (E0001-E0021+) documented on FlashForge Wiki.","example_fault_codes":[{"code":"E0002","description":"Lost communication with the MCU e-board.","kb_url":"https://wiki.flashforge.com/"},{"code":"E0007 - E0008","description":"Extruder not heating as expected (loose extruder cable, poor contact, or damaged nozzle).","kb_url":"https://wiki.flashforge.com/"},{"code":"E0020 - E0021","description":"Real-time video service failure / failed to enable the camera.","kb_url":"https://wiki.flashforge.com/"}],"diagnostic_logs":"FlashPrint 5 / Orca-Flashforge: File -> Help -> One-Click Log Export.","official_kb_urls":["https://wiki.flashforge.com/"]},"source_urls":["https://wiki.flashforge.com/","https://github.com/Parallel-7/flashforge-api-docs","https://github.com/Parallel-7/flashforge-api-docs/wiki/HTTP-REST-API","https://github.com/Parallel-7/flashforge-api-docs/wiki/TCP-Protocol","https://github.com/Parallel-7/flashforge-api-docs/blob/main/endpoints/endpoints_5m_3.2.7.yaml"],"source_verified":true,"availability_notes":"Official HTTP/TCP protocol docs are not_publicly_documented by FlashForge and are documented through community RE (Parallel-7/flashforge-api-docs Wiki/YAML).","relevance_to_forma_print":"Informs AD5M Pro enclosed filtration profile, AD5X 4-slot IFS multi-material .3mf export, and CheckCode + M601 S1 session semantics for future LAN bridge."}+{"id":"qidi_tech","manufacturer":"QIDI Tech","technologies":["FDM"],"segment":"prosumer","representative_models":["QIDI Q1 Pro","QIDI Plus4","QIDI X-Max 3"],"direct_communication":{"local_protocols":["Moonraker HTTP REST & WebSocket (port 7125)","Fluidd WebUI (port 10088)"],"cloud_protocols":["QIDI Link / QIDI Studio cloud / QIDI Maker app (optional)","Obico compatible"],"ports":["7125/tcp (Moonraker HTTP/WS API)","10088/tcp (Fluidd WebUI & webcam stream)"],"auth_and_modes":"Customized Klipper/Moonraker stack (open source in QIDITECH GitHub repos); local Fluidd (:10088) and Moonraker (:7125) work over LAN without mandatory cloud auth. Older 3/4-series use serial TJC HMI screens while Q2/Max 4/Plus 5 use Linux framebuffer displays.","upload_print_control_endpoints":["POST http://<ip>:7125/server/files/upload","WS ws://<ip>:7125/websocket","POST http://<ip>:7125/printer/gcode/script?script=<gcode>","POST http://<ip>:7125/printer/print/pause | resume | cancel"],"offline_capable":true,"offline_mode_notes":"Supports USB drive offline printing and 100% local LAN operation via Fluidd (:10088) and Moonraker (:7125).","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Hotend (up to 370 C on Plus4), bed, and active 65 C chamber heater (heater_generic chamber) with chamber thermistor.","cameras":"Built-in webcam exposed via Fluidd at http://<ip>:10088/webcam/?action=stream.","lidar_and_ai_inspection":"unavailable natively (optional Obico AI integration).","filament_and_spool_systems":"Filament runout and tangle detection sensors; QIDI Box multi-color/dryer unit on supported newer models.","accelerometers_input_shaper":"ADXL345 accelerometer for Klipper Input Shaper.","bed_probes":"Inductive probe paired with toolhead piezo nozzle-touch sensor for automatic Z-offset and bed mesh.","status_error_feeds":"Moonraker JSON-RPC WebSocket (:7125) and Fluidd WebUI (:10088)."},"troubleshooting_and_faults":{"fault_code_taxonomy":"Klipper shutdown strings in klippy.log combined with QIDI-specific QDC (status/box notifications) and QDE (subsystem logic) diagnostic codes.","example_fault_codes":[{"code":"Lost communication with MCU MKS_THR","description":"Toolhead MCU lost connection with mainboard (typically USB Type-C wear, static, or adapter board fault).","kb_url":"https://wiki.qidi3d.com/"},{"code":"MCU 'mcu' shutdown: Thermocouple ADC out of range","description":"Faulty hotend thermocouple reading or damaged wiring.","kb_url":"https://wiki.qidi3d.com/"},{"code":"QDE_004 (series)","description":"QIDI Box filament hub loading/unloading jam or sensor trip failure.","kb_url":"https://wiki.qidi3d.com/"}],"diagnostic_logs":"Download klippy.log directly from Fluidd Configuration/Machine tab (http://<ip>:10088); updates auto-backup configs as printer_{datetime}.cfg.","official_kb_urls":["https://wiki.qidi3d.com/","https://wiki.qidi3d.com/en/Q1-Pro","https://wiki.qidi3d.com/en/X-Plus4/Manual/Replacing-Fluidd"]},"source_urls":["https://wiki.qidi3d.com/","https://wiki.qidi3d.com/en/Q1-Pro","https://wiki.qidi3d.com/en/X-Plus4/Manual/Replacing-Fluidd","https://github.com/QIDITECH/QIDI_PLUS4","https://github.com/QIDITECH/QIDI_Q1_Pro/releases","https://github.com/prestonbrown/helixscreen/blob/main/docs/devel/printers/QIDI_SUPPORT.md"],"source_verified":true,"availability_notes":"Open Klipper/Moonraker API on port 7125 with non-default Fluidd UI port 10088; official firmware releases hosted on QIDITECH GitHub.","relevance_to_forma_print":"Highlights non-default Fluidd port 10088 alongside standard Moonraker port 7125 and active 65 C heated-chamber support for high-temp engineering polymers (ABS/ASA/PA-CF/PC)."}+{"id":"sovol","manufacturer":"Sovol","technologies":["FDM"],"segment":"consumer","representative_models":["Sovol SV08","Sovol SV06 Plus ACE","Sovol Zero"],"direct_communication":{"local_protocols":["Moonraker HTTP REST & WebSocket (port 7125)","Mainsail / Fluidd HTTP WebUI (port 80)"],"cloud_protocols":["none_native (optional OctoEverywhere / Obico)"],"ports":["7125/tcp (Moonraker HTTP/WS API)","80/tcp (Mainsail WebUI)","8080/tcp (Crowsnest webcam stream)"],"auth_and_modes":"Open-source Klipper/Moonraker stack; local LAN access controlled via Moonraker trusted_clients.","upload_print_control_endpoints":["POST http://<ip>:7125/server/files/upload","WS ws://<ip>:7125/websocket","POST http://<ip>:7125/printer/gcode/script?script=<gcode>","POST http://<ip>:7125/printer/print/pause | resume | cancel"],"offline_capable":true,"offline_mode_notes":"100% offline USB/SD and local LAN capable via Klipper + Moonraker + Mainsail without cloud dependency.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Hotend, heatbed, and MCU/host thermistors.","cameras":"USB webcam stream configured via Crowsnest and viewable in Mainsail/Fluidd or Obico.","lidar_and_ai_inspection":"unavailable natively (optional Obico AI integration).","filament_and_spool_systems":"Filament runout detection sensor.","accelerometers_input_shaper":"ADXL345 accelerometer for Klipper Input Shaper.","bed_probes":"LDC1612 Eddy current probe (Sovol Zero / SV08 Max / SV08 Eddy Kit), inductive probe (SV08), and loadcell probe (SV06 Plus ACE / Zero).","status_error_feeds":"Moonraker WebSocket (:7125) and Mainsail WebUI."},"troubleshooting_and_faults":{"fault_code_taxonomy":"Klipper shutdown and LDC1612 eddy-probe / accelerometer error strings in klippy.log and Mainsail console.","example_fault_codes":[{"code":"!! Error during homing probe: Eddy current sensor error","description":"Eddy probe drive current deviates from expected 14/15 or AB-gantry/bed misalignment (verify via LDC_CALIBRATE_DRIVE_CURRENT CHIP=eddy).","kb_url":"https://wiki.sovol3d.com/en/SV08Max/Eddy-current-sensor-error-message-types"},{"code":"!!LDC1612 12C bus busy or timeout error","description":"I2C bus busy or timeout between LDC1612 eddy sensor module and mainboard.","kb_url":"https://wiki.sovol3d.com/en/SV08Max/Eddy-current-sensor-error-message-types"},{"code":"Trigger analog error: RAW_RANGE","description":"Eddy sensor max_sensor_hz / clock divider configuration mismatch.","kb_url":"https://wiki.sovol3d.com/"},{"code":"Invalid adxl345 id (got 0 vs e5)","description":"SPI communication failure to ADXL345 accelerometer.","kb_url":"https://wiki.sovol3d.com/"}],"diagnostic_logs":"klippy.log and moonraker.log accessible via Mainsail UI or SSH.","official_kb_urls":["https://wiki.sovol3d.com/","https://wiki.sovol3d.com/en/SV08Max/Eddy-current-sensor-error-message-types","https://wiki.sovol3d.com/en/SV08/SV08-Eddy-Current-Sensor-Kit","https://wiki.sovol3d.com/en/SV06ACE"]},"source_urls":["https://wiki.sovol3d.com/","https://wiki.sovol3d.com/en/SV08Max/Eddy-current-sensor-error-message-types","https://wiki.sovol3d.com/en/SV08/SV08-Eddy-Current-Sensor-Kit","https://github.com/Sovol3d"],"source_verified":true,"availability_notes":"Open-source Klipper configs and OrcaSlicer profiles published on github.com/Sovol3d; full local Moonraker API.","relevance_to_forma_print":"Voron-inspired SV08 and high-speed Sovol Zero validate Moonraker :7125 LAN workflow and Klipper/LDC1612 eddy diagnostic KB entries."}+{"id":"ratrig","manufacturer":"RatRig","technologies":["FDM"],"segment":"ecosystem","representative_models":["RatRig V-Core 4","RatRig V-Core 4 IDEX","RatRig V-Minion"],"direct_communication":{"local_protocols":["Moonraker HTTP REST & WebSocket (port 7125)","Mainsail HTTP WebUI (port 80)","Crowsnest MJPEG / camera-streamer (port 8080)"],"cloud_protocols":["none_native (optional Obico / OctoEverywhere)"],"ports":["7125/tcp (Moonraker HTTP/WS API)","80/tcp (Mainsail WebUI)","8080/tcp (Crowsnest webcam stream)","7912/tcp (optional Spoolman server)"],"auth_and_modes":"RatOS open-source Klipper distribution using Moonraker trusted_clients CIDR allowlist and SSH ([email protected]).","upload_print_control_endpoints":["POST http://<ip>:7125/server/files/upload","WS ws://<ip>:7125/websocket","POST http://<ip>:7125/printer/gcode/script?script=<gcode>","POST http://<ip>:7125/printer/print/pause | resume | cancel"],"offline_capable":true,"offline_mode_notes":"100% local LAN and offline capable via RatOS (Klipper + Moonraker + Mainsail) with zero cloud requirement.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Hotend, heatbed, optional chamber, and multi-MCU thermistors (mainboard + dual IDEX toolhead MCUs).","cameras":"Crowsnest (mode: camera-streamer for Raspberry Pi CSI or ustreamer for USB) exposed via Mainsail.","lidar_and_ai_inspection":"unavailable natively (optional Obico).","filament_and_spool_systems":"Filament runout sensors and native Moonraker [spoolman] (:7912) inventory tracking.","accelerometers_input_shaper":"ADXL345 accelerometers for automated RatOS Input Shaper tuning.","bed_probes":"Beacon eddy-current/contact probe (including dual Beacon on IDEX) or SuperPINDA probe.","status_error_feeds":"Moonraker JSON-RPC WebSocket (:7125) and Mainsail WebUI."},"troubleshooting_and_faults":{"fault_code_taxonomy":"Klipper shutdown strings plus RatOS multi-MCU / IDEX configuration & firmware-sync diagnostics.","example_fault_codes":[{"code":"Firmware version mismatch between host and guest","description":"Host Klipper version out of sync with mainboard or IDEX toolhead MCUs (resolved via COMPILE_BINARIES macro and re-flash).","kb_url":"https://os.ratrig.com/"},{"code":"MCU '...' shutdown: Timer too close","description":"Host-to-MCU synchronization deadline missed.","kb_url":"https://www.klipper3d.org/"}],"diagnostic_logs":"/home/pi/printer_data/logs/klippy.log, moonraker.log, ratos-configurator.log, crowsnest.log, plus /var/log/ratos-{cli,server,configurator}.log and CLI 'ssh [email protected] ratos doctor'.","official_kb_urls":["https://os.ratrig.com/","https://wiki.ratrig.com/","https://github.com/Rat-OS/RatOS-configurator/blob/v2.1.x/LOGGING_SYSTEM.md"]},"source_urls":["https://os.ratrig.com/","https://wiki.ratrig.com/","https://github.com/Rat-OS/RatOS","https://github.com/Rat-OS/RatOS-configuration/blob/v2.1.x/macros.cfg","https://github.com/Rat-OS/RatOS-configurator/blob/v2.1.x/LOGGING_SYSTEM.md","https://www.klipper3d.org/","https://moonraker.readthedocs.io/"],"source_verified":true,"availability_notes":"Fully open-source RatOS / Klipper / Moonraker stack; user overrides must stay in printer.cfg outside the managed RatOS/ folder.","relevance_to_forma_print":"Informs IDEX multi-toolhead export semantics (dual-carriage zero-purge dissimilar support/material mapping), Spoolman :7912 inventory linkage, and Moonraker :7125 LAN upload."}+{"id":"raise3d","manufacturer":"Raise3D","technologies":["FDM"],"segment":"industrial","representative_models":["Raise3D Pro3","Raise3D Pro3 Plus","Raise3D E2","Raise3D RMF500","Raise3D Pro2"],"direct_communication":{"local_protocols":["HTTP REST (RaiseTouch Remote Access WebAPI)"],"cloud_protocols":["RaiseCloud (HTTPS/cloud relay via ideaMaker/RaiseTouch)"],"ports":["10800/tcp (RaiseTouch Remote Access WebAPI & embedded interactive API docs)"],"auth_and_modes":"Disabled by default. Requires enabling Secure Settings & Secure Password (Machine > More Settings > Privacy and Security > Secure Settings), then enabling Remote Access API (Machine > Developer > Enable Remote Access API) and setting an Access/SSH password. Uses signature + millisecond UNIX timestamp authentication via GET /v1/login?sign=<signature>×tamp=<ms_timestamp> to obtain a 24-hour session token.","upload_print_control_endpoints":["GET http://<printer_ip>:10800/ (embedded interactive RaiseTouch WebAPI documentation)","GET http://<printer_ip>:10800/v1/login?sign=<signature>×tamp=<ms_timestamp> (token auth)","not_publicly_documented (full /v1/ printer/job/file endpoint schemas are served locally on port 10800 per printer firmware and not published in an official public OpenAPI repo)"],"offline_capable":true,"offline_mode_notes":"Supports full offline USB flash drive printing (.gcode / .raising) and LAN-only operation via ideaMaker or the local RaiseTouch Developer WebAPI on port 10800 without RaiseCloud.","status":"gated_local_or_community_re"},"monitoring_and_sensors":{"thermal_sensors":"Polarized hotend thermocouples (red+/white- on Extruder Connection Board); Heated bed thermistor; PID auto-tuning via RaiseTouch (Hardware > PID Settings)","cameras":"Built-in live-view & timelapse camera accessible via RaiseTouch, ideaMaker (v3.1.7+), and RaiseCloud (stream endpoint not publicly documented outside local :10800 docs)","lidar_and_ai_inspection":"EVE Smart Assistant on Pro3 Series (interactive on-screen failure/jam/maintenance assistant triggered on errors; no LiDAR)","filament_and_spool_systems":"Optical/mechanical filament runout sensors on extruders; Open Filament Program (OFP) profiles","accelerometers_input_shaper":"unavailable (no stock accelerometer telemetry exposed; Pro3 HS / Hyperspeed uses factory-tuned input shaping profiles)","bed_probes":"Automated mesh bed leveling on Pro3 series (Simple 9-point / Full 63-point) and inductive/contact probing","status_error_feeds":"RaiseTouch touchscreen alerts, flashing red extruder LED on Pro3 faults, JSON status via local :10800 WebAPI (auth required)"},"troubleshooting_and_faults":{"fault_code_taxonomy":"RaiseTouch numeric error codes (e.g., 1000-series MCB/serial comms, 2000-series key/ID faults, 10000-series firmware update faults) plus Marlin motion-controller board (MCB) thermal runaway / min-max temp halts.","example_fault_codes":[{"code":"Error 1000","description":"Communication error between Motion Controller Board (MCB) and RaiseTouch touchscreen","kb_url":"https://forum.raise3d.com/viewtopic.php?start=20&t=23536"},{"code":"Error 1010","description":"Serial error: No such device or address (USB/serial link loss between RaiseTouch and MCB)","kb_url":"https://forum.raise3d.com/viewtopic.php?t=21934"},{"code":"Error 2006 / Error 10111","description":"Error 2006: cannot find valid serial by id (Hyperspeed key mismatch); Error 10111: failed firmware installation","kb_url":"https://forum.raise3d.com/viewtopic.php?start=20&t=23536"}],"diagnostic_logs":"Export Serial Port Log via Settings > More Settings > Serial Port Log > Export to FAT32 USB; Export Remote Access API log via Settings > Developer > Export remote access API log.","official_kb_urls":["https://support.raise3d.com/RaiseTouch/1-5-1-9-developer-17-1264.html","https://support.raise3d.com/RaiseTouch/6-1-7-1-enable-remote-access-api-17-895.html","https://support.raise3d.com/Pro3-Series/how-to-use-eve-smart-assistant-26-1497.html","https://support.raise3d.com/Pro3-Series/how-to-export-the-serial-port-log-26-1627.html","https://support.raise3d.com/Pro3-Series/how-to-replace-the-thermocouple-26-1618.html","https://support.raise3d.com/E2/how-to-export-serial-port-log-20-1216.html"]},"source_urls":["https://support.raise3d.com/RaiseTouch/1-5-1-9-developer-17-1264.html","https://support.raise3d.com/RaiseTouch/6-1-7-1-enable-remote-access-api-17-895.html","https://support.raise3d.com/Pro3-Series/how-to-use-eve-smart-assistant-26-1497.html","https://support.raise3d.com/Pro3-Series/how-to-export-the-serial-port-log-26-1627.html","https://github.com/daestx/raise3d","https://github.com/Raise3D/Marlin-Raise3D-N-Series"],"source_verified":true,"availability_notes":"Local WebAPI on port 10800 is officially available in RaiseTouch (>=1.1.0) once Developer mode + Secure password are enabled, but complete endpoint schemas are embedded on-device (http://<ip>:10800) rather than published in an official public OpenAPI spec. Numbered error codes (1000, 1010, 2006, 10111) are confirmed via official Raise3D staff posts on forum.raise3d.com; support.raise3d.com primarily indexes component replacement and log-export guides.","relevance_to_forma_print":"Target industrial IDEX/dual-extruder profiles (Pro3/E2); dual-nozzle extrusion clearance and thermal runaway / thermocouple diagnostic lookup in RAG troubleshooting KB."}+{"id":"ultimaker","manufacturer":"UltiMaker","technologies":["FDM"],"segment":"prosumer","representative_models":["UltiMaker S5","UltiMaker S7","UltiMaker S6 / S8","UltiMaker Factor 4","UltiMaker 3 / S3"],"direct_communication":{"local_protocols":["HTTP/1.1 REST OpenAPI (/api/v1/, /cluster-api/v1/) on UltiMaker 3/S3/S5/S7/S6/S8/Factor 4","mDNS (UDP 5353)","MJPEG Camera HTTP (:8080)"],"cloud_protocols":["UltiMaker Digital Factory / Connect API (https://api.ultimaker.com/connect/v1, https://api.ultimaker.com/cura/v1)"],"ports":["80/tcp (UltiMaker local REST API & Swagger UI)","8080/tcp (UltiMaker live camera stream)","5353/udp (mDNS printer discovery)"],"auth_and_modes":"UltiMaker 3/S-series/Factor 4: Read-only GET endpoints are unauthenticated; PUT/POST/DELETE require HTTP Digest Access Authentication (RFC 2617, realm 'Jedi-API', no Basic fallback) paired via POST /api/v1/auth/request -> touchscreen confirmation -> GET /api/v1/auth/check/{id} -> GET /api/v1/auth/verify. UltiMaker Cloud APIs require Pro/Education Digital Factory subscription tiers.","upload_print_control_endpoints":["GET http://<ip>/docs/api (on-printer OpenAPI Swagger UI for low-level system API)","GET http://<ip>/cluster-api/v1/ (on-printer OpenAPI Swagger UI for cluster & print job queue API)","POST http://<ip>/api/v1/auth/request","GET http://<ip>/api/v1/auth/check/{id}","GET http://<ip>/api/v1/auth/verify","GET http://<ip>/api/v1/printer","PUT http://<ip>/api/v1/system/display_message","GET http://<ip>/api/v1/camera/feed (and http://<ip>:8080/)","GET / POST http://<ip>/cluster-api/v1/print_job","https://api.ultimaker.com/connect/v1/clusters (Cloud Connect API, subscription-gated)"],"offline_capable":true,"offline_mode_notes":"UltiMaker S-series/Factor 4/3 support full offline USB printing and LAN-only printing/API control without Digital Factory.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Dual Print Core thermistors/RTDs; Heated build plate sensor; Heated build chamber sensor (Factor 4)","cameras":"Built-in build-chamber camera exposed locally on UltiMaker 3/S-series/Factor 4 at port 8080 (http://<ip>:8080/ & /api/v1/camera/feed)","lidar_and_ai_inspection":"unavailable (no built-in LiDAR; optional Digital Factory analytics)","filament_and_spool_systems":"UltiMaker Material Station (6-bay NFC spool readers, humidity control, automatic material bay switching exposed in cluster-api); flow/runout sensors on print heads","accelerometers_input_shaper":"unavailable (no user-exposed accelerometer telemetry documented in public local API)","bed_probes":"Active capacitive/inductive bed leveling (S-series capacitive print head sensor; Factor 4 inductive bed sensor + 5V optical gantry limit switches)","status_error_feeds":"GET /api/v1/printer & /cluster-api/v1/ status JSON; printer touchscreen ERxx/ERxxx codes; Digital Factory webhooks/Connect API"},"troubleshooting_and_faults":{"fault_code_taxonomy":"UltiMaker uses ERxx / ERxxx alphanumeric error codes (e.g., ER11, ER18, ER34, ER313, ER999).","example_fault_codes":[{"code":"ER18","description":"Print head communication error (UltiMaker 3; equivalent is ER34 on S-series)","kb_url":"https://support.ultimaker.com/s/article/1667411318111"},{"code":"ER313","description":"Power malfunction error — 5V/24V rails outside acceptable voltage range (UltiMaker S6, S8, Factor 4)","kb_url":"https://support.ultimaker.com/s/article/ER313"},{"code":"ER999","description":"Unspecified control software error (UltiMaker S3, S5, S7, Factor 4; replaces legacy ER27)","kb_url":"https://support.ultimaker.com/s/article/1667411042133"}],"diagnostic_logs":"Dump printer log files to USB from printer Maintenance/Diagnostics menu (or Digital Factory).","official_kb_urls":["https://support.ultimaker.com/s/article/1667412427787","https://support.ultimaker.com/s/article/1667412427791","https://support.ultimaker.com/s/article/ER313","https://support.ultimaker.com/s/article/1667411042133","https://support.ultimaker.com/s/article/1667411318111"]},"source_urls":["https://support.ultimaker.com/s/article/1667412427787","https://support.ultimaker.com/s/article/1667412427791","https://support.ultimaker.com/s/article/ER313","https://support.ultimaker.com/s/article/1667411042133","https://support.ultimaker.com/s/article/1667411318111","https://gist.github.com/SimonIT/ea672554e9d642b517202125b10d3b37","https://github.com/vanderbilt-design-studio/python-ultimaker-printer-api"],"source_verified":true,"availability_notes":"UltiMaker 3/S3/S5/S7/S6/S8/Factor 4 local HTTP OpenAPI is open on-device ('provided as-is without official support or warranty'). UltiMaker Cloud Connect API requires a paid Digital Factory Pro/Edu subscription. Note: MakerBot Method / Method X / Method XL / Sketch printers (merged into UltiMaker in 2022) lack UltiMaker's open local HTTP API and are cataloged in a separate record (id='makerbot').","relevance_to_forma_print":"Exemplar RFC 2617 HTTP Digest auth pattern for dual-extruder prosumer 2.85mm LAN dispatch; Material Station 6-bay NFC metadata and ERxx fault taxonomy for RAG."}+{"id":"formlabs","manufacturer":"Formlabs","technologies":["SLA","MSLA","SLS"],"segment":"industrial","representative_models":["Formlabs Form 4","Formlabs Form 4L","Formlabs Fuse 1+ 30W","Formlabs Form 3 / 3L"],"direct_communication":{"local_protocols":["HTTP/1.1 REST OpenAPI 3.1.0 via PreForm / headless PreFormServer (e.g., http://localhost:44388 when launched with required --port 44388)"],"cloud_protocols":["HTTPS REST Formlabs Web API (Dashboard Developer API: https://api.formlabs.com/developer/v1/)"],"ports":["44388/tcp (PreFormServer documented example HTTP API port; -p / --port flag is required)","443/tcp (Formlabs Web API HTTPS & Dashboard)"],"auth_and_modes":"PreFormServer (Local API): Free download/Docker image (formlabs/preform-server:release-latest --port 44388) with no per-call fees; local scene/slice ops are unauthenticated on localhost, while Fleet Control queues and Dashboard-registered printers require /v1/login/ (OpenID Connect). Formlabs Web API: OAuth 2.0 Client Credentials grant (POST https://api.formlabs.com/developer/v1/o/token/ -> 24h Bearer token). Open Material Mode requires a one-time lifetime license unlock per printer (requires temporary internet connection).","upload_print_control_endpoints":["GET http://localhost:44388/v1/scene/list/","POST http://localhost:44388/v1/scene/save/","POST http://localhost:44388/v1/scene/open/","GET http://localhost:44388/v1/device/list/?can_print=true","GET http://localhost:44388/v1/print-setting/list/","POST http://localhost:44388/v1/login/","POST http://localhost:44388/v1/device/upload-firmware/","POST http://localhost:44388/v1/scene/model/fill-build-platform/ (SLA, scene_id in JSON body)","POST http://localhost:44388/v1/scene/model/fill-build-chamber/ (SLS, scene_id in JSON body)","GET https://api.formlabs.com/developer/v1/printers/","GET https://api.formlabs.com/developer/v1/printers/{printer_serial}/","GET https://api.formlabs.com/developer/v1/prints/","GET https://api.formlabs.com/developer/v1/tanks/","GET https://api.formlabs.com/developer/v1/cartridges/","GET https://api.formlabs.com/developer/v1/events/","GET / POST https://api.formlabs.com/developer/v1/groups/"],"offline_capable":true,"offline_mode_notes":"PreForm / PreFormServer can prepare scenes and send jobs over LAN/USB to local Formlabs printers without internet (DISABLE_PREFORMSERVER_TELEMETRY=1 supported), though Dashboard-linked Fleet Control queues, Web API, and initial Open Material Mode activation require internet.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Form 4/4L IR Resin Temperature Sensor + vat/cartridge heaters; Fuse 1+ 30W IR bed temperature sensor (RP-FS1-IRK-02) + hopper trough RTD (RP-FS1-BRTD-02) + radiant heaters","cameras":"Internal camera in Form 4/4L (RP-F4-CAM-01) and Fuse 1/1+ for remote timelapses and post-print inspection in Formlabs Dashboard (no raw local RTSP stream documented)","lidar_and_ai_inspection":"unavailable (no LiDAR; optical/IR thermal monitoring on Fuse 1+ and LevelSense on Form 4)","filament_and_spool_systems":"Resin cartridge & tank RFID readers (Form 4/4L) + LevelSense resin level sensor (RP-F4-LVL-01); powder cartridge/hopper RFID & tracking on Fuse 1+ 30W; tracked via /developer/v1/tanks/ and /developer/v1/cartridges/","accelerometers_input_shaper":"unavailable (not applicable to SLA/SLS)","bed_probes":"Form 4 Low Force Display (LFD) peel force & Z-axis mechanical calibration; Fuse 1+ chamber pressure sensors (nitrogen/air)","status_error_feeds":"Formlabs Web API GET /developer/v1/events/ & /printers/ status; PreFormServer structured JSON error codes (e.g., INVALID_QUERY_PARAMETER, NOT_FOUND); on-printer touchscreen errors"},"troubleshooting_and_faults":{"fault_code_taxonomy":"Form 4/4L uses hierarchical X.YY.ZZ codes (X=machine code e.g. 1, YY=subsystem e.g. 3 for heater/resin temp, ZZ=symptom); Fuse 1/1+ and legacy Form 2/3 use integer Error codes (e.g., Error 41, Error 194, Error 195).","example_fault_codes":[{"code":"1.3.1","description":"Form 4 generation resin heater/temperature subsystem error (resin failed to reach target temperature)","kb_url":"https://support.formlabs.com/s/article/Form-4-generation-error-messages"},{"code":"Error 194","description":"Fuse 1 generation: Optical cassette not detected","kb_url":"https://support.formlabs.com/s/article/Fuse-1-generation-error-message-Error-194-Optical-cassette-not-detected"},{"code":"Error 195 / Error 41","description":"Fuse 1+ Error 195 (PRESSURE_CHECK_SENSING_FAULT); Form 2 Error 41 (galvanometer abnormal power consumption)","kb_url":"https://support.formlabs.com/s/topic/0TO1Y000000cWJRWA2/troubleshooting-the-fuse-1-generation-fuse-1-generation?language=en_US"}],"diagnostic_logs":"PreFormServer --export-support-bundle CLI flag bundles structured diagnostic and text logs; printer diagnostic logs uploadable to Dashboard or exported via UI.","official_kb_urls":["https://developer.formlabs.com/api-reference/","https://developer.formlabs.com/api-reference/devices/","https://developer.formlabs.com/resources/preform-server-cli/","https://developer.formlabs.com/core-concepts/dashboard-client/","https://support.formlabs.com/s/article/Form-4-generation-error-messages","https://support.formlabs.com/s/article/Fuse-1-generation-error-message-Error-194-Optical-cassette-not-detected","https://formlabs.com/support/Formlabs-replacement-part-guides/","https://formlabs.com/support/Replacing-the-Fuse-1-30W-IR-sensor-flow-body/"]},"source_urls":["https://developer.formlabs.com/api-reference/","https://developer.formlabs.com/api-reference/devices/","https://developer.formlabs.com/resources/preform-server-cli/","https://developer.formlabs.com/core-concepts/dashboard-client/","https://github.com/Formlabs/formlabs-api-python","https://github.com/Formlabs/formlabs-api-python/blob/main/formlabs_sdk/preform_api.py","https://github.com/Formlabs/formlabs-api-python/blob/main/examples/README.md","https://formlabs-dashboard-api-resources.s3.amazonaws.com/formlabs-web-api-latest.html","https://developer.formlabs.com/api-reference/modifying-models/fill-build-platform.md","https://developer.formlabs.com/api-reference/modifying-models/fill-build-chamber.md","https://developer.formlabs.com/api-reference/devices/upload-firmware.md","https://support.formlabs.com/s/article/Form-4-generation-error-messages","https://support.formlabs.com/s/article/Fuse-1-generation-error-message-Error-194-Optical-cassette-not-detected"],"source_verified":true,"availability_notes":"PreFormServer (Local API) and Formlabs Web API are officially documented on developer.formlabs.com with OpenAPI specs and Python SDK without per-call fees. Note that Web API is cloud-only and requires Dashboard registration; Formlabs printers do not expose a direct unmediated REST API on the printer hardware IP itself—local automation routes through PreFormServer.","relevance_to_forma_print":"Direct Tier 1 printer profiles for `formlabs_form_4` (LFD/MSLA) and `formlabs_fuse_1p` (SLS); highlights headless PreFormServer job-prep boundary (forma-print checks wall thickness, hollowing/drainage & orientation before PreFormServer scene/slice dispatch)."}+{"id":"markforged","manufacturer":"Markforged","technologies":["FDM","CFF"],"segment":"industrial","representative_models":["Markforged Mark Two","Markforged X7","Markforged FX10","Markforged FX20","Markforged Onyx Pro"],"direct_communication":{"local_protocols":["unavailable on printer firmware (On-Prem API exists only via enterprise Local LAN Connector / Offline Eiger appliance)"],"cloud_protocols":["HTTPS REST (Eiger API v3: https://www.eiger.io/api/v3/)"],"ports":["443/tcp (Eiger Cloud API HTTPS)"],"auth_and_modes":"Cloud-first Eiger API v3 (gated to Essential/Fleet/Enterprise plans). Uses HTTP Basic Authentication with organization-owner-generated Access Key (username) and Secret Key (password) via Settings > Organization Settings > API Keys. On-Prem API for Local LAN Connector / Offline Eiger requires enterprise deployment.","upload_print_control_endpoints":["GET https://www.eiger.io/api/v3/devices","GET https://www.eiger.io/api/v3/devices/{device_id}","POST https://www.eiger.io/api/v3/devices/{device_id}/queue (add build to printer queue)","GET https://www.eiger.io/api/v3/builds","GET https://www.eiger.io/api/v3/builds/{build_id}","GET https://www.eiger.io/api/v3/print_jobs","GET https://www.eiger.io/api/v3/print_jobs/{print_job_id}","GET https://www.eiger.io/api/v3/print_jobs/{print_job_id}/scan_report (Inspection scan report URLs for a print job)","GET https://www.eiger.io/api/v3/parts/{part_id}","POST https://www.eiger.io/api/v3/parts/upload_stl (multipart/form-data STL upload)","GET https://www.eiger.io/api/v3/part_versions/{part_version_id}","GET https://www.eiger.io/api/v3/part_versions/{part_version_id}/download (30s STL download URL)","GET https://www.eiger.io/api/v3/printed_parts","GET https://www.eiger.io/api/v3/printed_parts/{printed_part_id}","GET https://www.eiger.io/api/v3/printed_parts/{printed_part_id}/scan_report (Blacksmith / Inspection scan report URL)","GET https://www.eiger.io/api/v3/users","GET https://www.eiger.io/api/v3/users/{user_id}","unavailable (no direct open local HTTP/WebSocket endpoint on Mark Two / X7 / FX10 / FX20 printer firmware)"],"offline_capable":true,"offline_mode_notes":"Supports offline USB print job loading (.mfp exported from Eiger / Offline Eiger) and air-gapped Offline Eiger appliance for high-security facilities, but lacks a direct third-party LAN REST API on the printer.","status":"cloud_first_limited_local"},"monitoring_and_sensors":{"thermal_sensors":"Dual-nozzle plastic/fiber thermistors; Heated build plate & heated chamber thermal sensors (FX10 / FX20); Sinter-1/2 furnace zone thermocouples (ZONE_1..3) & RTDs","cameras":"unavailable (no open RTSP/HTTP camera feed exposed via Eiger API v3)","lidar_and_ai_inspection":"Onboard Laser Micrometer (X7, FX10, FX20) powering Inspection & Blacksmith closed-loop dimensional deviation scanning (requires Eiger Advanced plan; reports downloadable via Eiger API)","filament_and_spool_systems":"Material drawer/bay out-of-plastic & fiber jam detection (Nozzle A / Nozzle B & fiber encoder on FX10/FX20); dry-box material monitoring","accelerometers_input_shaper":"unavailable (proprietary motion control)","bed_probes":"Laser micrometer Z-axis calibration & reference bed / laser-guided offset calibration (X7, FX10, FX20)","status_error_feeds":"Eiger API v3 /devices & /print_jobs status; HTTP 400/401/403/404/429/500 responses; on-printer touchscreen prompts & Eiger Device Event logs"},"troubleshooting_and_faults":{"fault_code_taxonomy":"Composite printers (Mark Two, X7, FX10, FX20) surface descriptive touchscreen fault prompts and Eiger event logs (e.g., Plastic Extrusion Issue, Fiber Jam); Metal Sinter-1/2 furnaces expose explicit uppercase hardware fault codes (ADC_ERR_*, TC_ERR_*, ERR_SHIELD).","example_fault_codes":[{"code":"Plastic Extrusion Issue / Nozzle A|B Jam","description":"P-PLA or Onyx extrusion jam detected by extruder/pre-extruder sensor on Desktop/Industrial/FX20","kb_url":"https://support.markforged.com/portal/s/article/Plastic-Jam-Troubleshooting-FX20"},{"code":"Fiber Jam","description":"Continuous fiber feeding fault on FX10/FX20 triggering automatic pause and flossing recovery wizard","kb_url":"https://support.markforged.com/portal/s/article/Fiber-Jam-Troubleshooting-FX10-FX20"},{"code":"ADC_ERR_HIGH / TC_ERR_OPEN / ERR_SHIELD","description":"Sinter-1 furnace firmware faults: PRESSURE PROCESS clog (ADC_ERR_HIGH), thermocouple unplugged (TC_ERR_OPEN), inlet door hot (ERR_SHIELD)","kb_url":"https://support.markforged.com/portal/s/article/Common-Sinter-1-Firmware-Errors"}],"diagnostic_logs":"Machine logs & telemetry uploaded via Eiger cloud or exported via USB/Network Utilities for Partner/Markforged Support differential diagnosis.","official_kb_urls":["https://www.eiger.io/developer","https://www.eiger.io/developer/spec","https://support.markforged.com/portal/s/article/Eiger-API","https://support.markforged.com/portal/s/article/On-Prem-API","https://support.markforged.com/portal/s/article/Calibrating-Your-Blacksmith-Printer","https://support.markforged.com/portal/s/article/Z-Axis-Calibration-Industrial","https://support.markforged.com/portal/s/article/Plastic-Jam-Troubleshooting-FX20","https://support.markforged.com/portal/s/article/Fiber-Jam-Troubleshooting-FX10-FX20","https://support.markforged.com/portal/s/article/P-PLA-Extruder-Jams","https://support.markforged.com/portal/s/article/Common-Sinter-1-Firmware-Errors"]},"source_urls":["https://www.eiger.io/developer","https://www.eiger.io/developer/spec","https://support.markforged.com/portal/s/article/Eiger-API","https://support.markforged.com/portal/s/article/On-Prem-API","https://support.markforged.com/portal/s/article/Calibrating-Your-Blacksmith-Printer","https://support.markforged.com/portal/s/article/Z-Axis-Calibration-Industrial","https://support.markforged.com/portal/s/article/Plastic-Jam-Troubleshooting-FX20","https://support.markforged.com/portal/s/article/Fiber-Jam-Troubleshooting-FX10-FX20","https://support.markforged.com/portal/s/article/Common-Sinter-1-Firmware-Errors"],"source_verified":true,"availability_notes":"The Eiger API v3 (3.0.1) ReDoc reference and OpenAPI specification download are publicly accessible at https://www.eiger.io/developer (and https://www.eiger.io/developer/spec), while API key generation and endpoint execution remain subscription-gated (Essential plan; Blacksmith/Inspection scan reports require Advanced plan; Markforged explicitly states it provides no further support for custom API integration). Composite printers do not publish a raw numeric fault code table publicly—only descriptive recovery workflows, whereas Sinter-1 publishes explicit ADC_ERR/TC_ERR codes.","relevance_to_forma_print":"Informs continuous-fiber (CFF) / Onyx wall thickness & minimum feature DFM rules and documents closed-loop laser micrometer inspection constraints."}+{"id":"stratasys","manufacturer":"Stratasys","technologies":["FDM","PolyJet","SLA"],"segment":"industrial","representative_models":["Stratasys F123 Series (F170 / F270 / F370 / F370CR)","Stratasys Fortus 450mc / F900","Stratasys J55 / J850 (PolyJet)","Stratasys Origin One / Origin Two (P3 DLP)"],"direct_communication":{"local_protocols":["MTConnect XML over HTTP (read-only telemetry on F123 series & Fortus models except 250mc/360mc/400mc)","GrabCAD Print local helper daemons (PrinterServiceServerConsole.exe, FDMBuildServiceServerConsole.exe, PolyJetService.exe)"],"cloud_protocols":["GrabCAD Printer Connectivity SDK / GrabCAD Print SDK (HTTPS to api.grabcad.com, print-api.grabcad.com, usage-api.grabcad.com)"],"ports":["5000/tcp (MTConnect HTTP XML stream on F123 series e.g. http://<ip>:5000/sample?count=1000)","53750/tcp (MTConnect HTTP XML stream on select Fortus/F-series e.g. http://<ip>:53750/probe)","80/tcp, 443/tcp (GrabCAD Print & Connectivity SDK)"],"auth_and_modes":"MTConnect: free read-only package, enabled locally on touchscreen (Tools > Settings > MTConnect > ON; requires F123 firmware >=2.2.5940 / 3.27+). Two-way job scheduling, queue control, and MES/ERP/PLM integration via GrabCAD Printer Connectivity SDK / GrabCAD Print SDK are enterprise-gated (requires GrabCAD Software Partner Program membership or commercial SDK license purchase).","upload_print_control_endpoints":["GET http://<printer_ip>:5000/probe | /current | /sample | /assets (MTConnect read-only XML on F123)","GET http://<printer_ip>:53750/probe | /current | /sample | /assets (MTConnect read-only XML on select Fortus/Stratasys)","not_publicly_documented (GrabCAD Printer Connectivity SDK & GrabCAD Print SDK two-way APIs are gated to commercial SDK licensees/partners)"],"offline_capable":true,"offline_mode_notes":"Supports local LAN job submission from GrabCAD Print / Insight on isolated enterprise networks and USB/local storage workflows without public internet, though third-party two-way automation requires licensed Connectivity SDK.","status":"closed_or_usb_only"},"monitoring_and_sensors":{"thermal_sensors":"Liquefier head thermocouples/sensors; Heated build chamber & oven thermal sensors","cameras":"Internal chamber monitoring camera accessible inside GrabCAD Print (no public unauthenticated local MJPEG/RTSP endpoint documented)","lidar_and_ai_inspection":"unavailable (no public LiDAR telemetry; closed industrial calibration)","filament_and_spool_systems":"Material canister/spool EEPROM/RFID validation (model & support material verification, expiration/license checks), dual-bay auto-changeover (e.g., F370 2 model + 2 support spools), head spinout / extrusion speed monitoring","accelerometers_input_shaper":"unavailable","bed_probes":"End-of-travel (EOT) X/Y/Z axis limit sensors & automated head Z-height / tip calibration","status_error_feeds":"MTConnect XML <Condition> elements (Unavailable, Active, Interrupted, Fault, Warning, Normal); touchscreen yellow/red notification badges; GrabCAD Print status"},"troubleshooting_and_faults":{"fault_code_taxonomy":"F123 Series surfaces descriptive touchscreen Warnings and Build Abort Errors (e.g., Failed to find Z zero, Failed to process the part, Failed to load toolpaths, Failed to calibrate tip offsets, No Material Detected In Head) alongside MTConnect <Condition> states (Unavailable, Active, Interrupted, Fault, Warning, Normal). Legacy Dimension/Prodigy FDM systems (768/Elite/1200) expose numeric major/minor LCD error codes (e.g., 10: Command Failed, 11: Queue Communication, 14,01: Abort: Z Axis jammed, 14,34: Abort: Z axis table jammed).","example_fault_codes":[{"code":"Failed to find Z zero","description":"F123 Series Build Abort Error: Z stage failed to find its home position; check for obstructions on platen calibration targets.","kb_url":"https://support.stratasys.com/SupportCenter/HTML5UserGuides/F123_UG_April_2021/Responsive%20HTML5/F123_Series_User_Guide-HTML/Troubleshooting/Troubleshooting.htm"},{"code":"Failed to process the part / Failed to load toolpaths","description":"F123 Series Build Abort Errors: error translating CMB file into printer commands (corrupt/outdated CMB) or printer unexpectedly lost job toolpath data during build.","kb_url":"https://support.stratasys.com/SupportCenter/HTML5UserGuides/F123_UG_April_2021/Responsive%20HTML5/F123_Series_User_Guide-HTML/Troubleshooting/Troubleshooting.htm"},{"code":"Failed to calibrate tip offsets","description":"F123 Series Build Abort Error: automatic model/support tip offset calibration failed; ensure targets are clear and retry automatic or manual tip calibration.","kb_url":"https://support.stratasys.com/SupportCenter/HTML5UserGuides/F123_UG_April_2021/Responsive%20HTML5/F123_Series_User_Guide-HTML/Troubleshooting/Troubleshooting.htm"},{"code":"No Material Detected In Head","description":"Material spun out inside F123 print head / failed to feed into liquefier","kb_url":"https://support.alleghenyedusys.com/portal/en/kb/articles/stratasys-f123-series-no-material-detected-in-head-error"},{"code":"14,01 (Abort: Z Axis jammed)","description":"Dimension 768/Elite Controller Abort Minor Error (Code 14, XX): Z-axis jam or limit/sensor fault requiring leadscrew debris inspection and Z-stage diagnostics.","kb_url":"https://cdn.hackaday.io/files/10782461297088/768_Elite_Service_Guide.pdf"}],"diagnostic_logs":"Export System Configuration (.CFG) file via GrabCAD Print (printer firmware management -> Export Printer Configuration) or directly via printer USB port.","official_kb_urls":["https://grabcad.com/en/software-development-kit","https://www.stratasys.com/en/software/connectivity-and-iiot/","https://support.stratasys.com/en/Printers/FDM/F123-Series","https://support.stratasys.com/SupportCenter/HTML5UserGuides/F123_UG_April_2021/Responsive%20HTML5/F123_Series_User_Guide-HTML/Troubleshooting/Troubleshooting.htm","https://www.stratasys.com/siteassets/3dlc/getting-started/f123_series_user_guide.pdf?v=48f313"]},"source_urls":["https://grabcad.com/en/software-development-kit","https://www.stratasys.com/en/software/connectivity-and-iiot/","https://investors.stratasys.com/news-events/press-releases/detail/719/stratasys-brings-enterprise-software-connectivity-to-3d","https://support.stratasys.com/en/Printers/FDM/F123-Series","https://support.stratasys.com/SupportCenter/HTML5UserGuides/F123_UG_April_2021/Responsive%20HTML5/F123_Series_User_Guide-HTML/Troubleshooting/Troubleshooting.htm","https://support.alleghenyedusys.com/portal/en/kb/articles/stratasys-f123-series-no-material-detected-in-head-error","https://cdn.hackaday.io/files/10782461297088/768_Elite_Service_Guide.pdf"],"source_verified":true,"availability_notes":"Read-only MTConnect XML streaming is free on supported F123 and Fortus printers, but two-way job submission and printer control via GrabCAD Printer Connectivity SDK / GrabCAD Print SDK are enterprise-gated behind paid SDK licenses or the GrabCAD Software Partner Program, with endpoint docs not publicly published. Origin One / Origin Two P3 DLP photopolymerization is categorized under SLA.","relevance_to_forma_print":"Highlights enterprise industrial boundary: forma-print handles geometry/DFM/STEP/3MF preparation before GrabCAD Print / Insight ingestion; MTConnect read-only port 5000/53750 telemetry integration pattern."}+{"id":"snapmaker","manufacturer":"Snapmaker","technologies":["FDM"],"segment":"consumer","representative_models":["Snapmaker 2.0 (A350T)","Snapmaker Artisan","Snapmaker J1 / J1s (IDEX)","Snapmaker U1"],"direct_communication":{"local_protocols":["HTTP/1.1 REST API (/api/v1/) on port 8080","UDP broadcast discovery on port 20054","SACP (Snapmaker Application Communication Protocol) over TCP port 8888","USB Serial (Marlin-FreeRTOS)","WebSocket / Moonraker (7125/tcp via U1 native Klipper stack or community snapmaker_moonraker bridge on J1s)"],"cloud_protocols":["unavailable (primarily local LAN / Luban workflow; U1 supports Snapmaker app/cloud notifications)"],"ports":["8080/tcp (Snapmaker HTTP REST API v1)","20054/udp (UDP broadcast discovery)","8888/tcp (SACP binary TCP protocol)","7125/tcp (Klipper/Moonraker on U1 or community bridge)"],"auth_and_modes":"Token authentication on HTTP port 8080: POST /api/v1/connect prompts physical confirmation on the printer touchscreen within 60 seconds and issues an API token; automated print sessions require periodic status polling ('heartbeat') to avoid session timeout.","upload_print_control_endpoints":["POST http://<ip>:8080/api/v1/connect?token=<token>","GET http://<ip>:8080/api/v1/status?token=<token>","POST http://<ip>:8080/api/v1/prepare_print?token=<token> (multipart file upload e.g. type=3DP)","POST http://<ip>:8080/api/v1/start_print?token=<token>","POST http://<ip>:8080/api/v1/pause?token=<token>","POST http://<ip>:8080/api/v1/resume?token=<token>","POST http://<ip>:8080/api/v1/stop?token=<token>","POST http://<ip>:8080/api/v1/execute_code?token=<token>&code=<gcode>","SACP binary protocol via Snapmaker/Luban SacpClient.ts & @snapmaker/snapmaker-sacp-sdk (TCP port 8888)"],"offline_capable":true,"offline_mode_notes":"Fully offline-capable via USB flash drive, USB serial, or local LAN HTTP :8080 / SACP :8888 without any cloud account.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"Single/dual extruder hotend thermistors; Heated bed thermistor; Chamber temperature detection (U1 module 0527)","cameras":"Built-in camera / AI monitoring on newer U1/firmware via WebSocket; older A350T/Artisan/J1 lack stock camera (optional/external)","lidar_and_ai_inspection":"AI print defect detection (spaghetti/foreign object) on newer U1 firmware; unavailable on A350T/Artisan/J1","filament_and_spool_systems":"Filament runout sensors on 3D printing toolheads; U1 multi-feeder / automatic filament feeder module (0525)","accelerometers_input_shaper":"Input shaping / vibration compensation on J1/J1s and U1 (Marlin/Klipper)","bed_probes":"Inductive/proximity or nozzle-contact auto bed leveling (Artisan, A350T, J1/J1s)","status_error_feeds":"GET /api/v1/status JSON telemetry (temperatures, progress, coordinates, state); SACP real-time packets; touchscreen error popups with QR links to Snapmaker Wiki"},"troubleshooting_and_faults":{"fault_code_taxonomy":"Artisan/2.0 use numeric hyphenated codes (e.g., 515-6, 515-10) and descriptive alerts; Snapmaker U1 uses structured 16-digit 4-group codes SSSS-MMMM-SUBB-IIII (Severity 0000..0003, Module 0522=Motion, 0523=Toolhead, 0525=Filament feeder, 0526=Heated bed, 0527=Chamber temp, 0528=Homing, 0529=G-code, 0530=Detection/calibration, 0531=Slicing file).","example_fault_codes":[{"code":"515-10 / 515-6","description":"Snapmaker Artisan heated bed underheat error codes","kb_url":"https://wiki.snapmaker.com/en/snapmaker_artisan/troubleshooting/heatbed_error"},{"code":"0002-0528-0003-0013","description":"Snapmaker U1 Warning (0002) — Homing anomaly (0528)","kb_url":"https://wiki.snapmaker.com/en/snapmaker_u1/troubleshooting/u1_error_codes"},{"code":"0003-0522-0000-0000 / 0003-0522-0000-0002","description":"Snapmaker U1 System Anomaly (module 0522; accumulated server messages — 0003-0522-0000-0000 dismissible via Confirm, 0003-0522-0000-0002 resolved via U1 USB firmware update or log export).","kb_url":"https://wiki.snapmaker.com/en/snapmaker_u1/troubleshooting/0003-0522-0000-0002or0000"}],"diagnostic_logs":"Exportable machine/Luban logs via touchscreen Settings or Luban machine.json / log directory; QR codes on touchscreen error popups link to Snapmaker Wiki.","official_kb_urls":["https://wiki.snapmaker.com/en/snapmaker_u1/troubleshooting/u1_error_codes","https://wiki.snapmaker.com/en/snapmaker_u1/troubleshooting/0003-0522-0000-0002or0000","https://wiki.snapmaker.com/snapmaker_artisan/troubleshooting/Touchscreen_error_code_reference","https://wiki.snapmaker.com/en/snapmaker_artisan/troubleshooting/heatbed_error","https://wiki.snapmaker.com/en/snapmaker_j1/troubleshooting/false_trigger_filament_failure_error"]},"source_urls":["https://github.com/Snapmaker/Luban/blob/main/src/server/services/machine/sacp/SacpClient.ts","https://github.com/conallob/homeassistant-snapmaker/blob/main/CLAUDE.md","https://github.com/goeland86/snapmaker_moonraker","https://github.com/hauti123/Snapmaker","https://forum.snapmaker.com/t/sending-own-g-code-directly-from-a-selfbuilt-software/37847","https://wiki.snapmaker.com/en/snapmaker_u1/troubleshooting/u1_error_codes","https://wiki.snapmaker.com/en/snapmaker_artisan/troubleshooting/heatbed_error"],"source_verified":true,"availability_notes":"HTTP REST API on port 8080 is documented by Snapmaker community/Luban open source; SACP binary protocol is open-source in Snapmaker/Luban and Snapmaker-SACP SDK on GitHub/NPM.","relevance_to_forma_print":"Clear local LAN dispatch model (UDP 20054 discovery + HTTP 8080 / SACP 8888); IDEX dual-extruder J1s profile & structured U1 fault taxonomy for RAG diagnostics."}+{"id":"phrozen","manufacturer":"Phrozen","technologies":["MSLA"],"segment":"consumer","representative_models":["Phrozen Sonic Mighty Revo","Phrozen Sonic Mighty Revo 16K","Phrozen Sonic Mega 8K S","Phrozen Sonic Mini 8K S"],"direct_communication":{"local_protocols":["SDCP v3.0.0 (Smart Device Control Protocol — JSON over WebSocket on port 3030, UDP discovery on port 3000, HTTP file upload on port 3030)","RTSP video stream (when CameraStatus=1 / VIDEO_STREAM capability supported)","USB FAT32 offline transfer (.ctb / .prz) for USB-only models like Sonic Mega 8K S"],"cloud_protocols":["Phrozen GO / mobile remote monitoring app (proprietary cloud relay on supported models)"],"ports":["3000/udp (SDCP broadcast discovery 'M99999')","3030/tcp (SDCP WebSocket ws://<ip>:3030/websocket & HTTP chunked upload :3030/uploadFile/upload)","554/tcp (RTSP video stream where supported)","54780/tcp (community ChitUI web bridge default port)"],"auth_and_modes":"SDCP v3.0.0 LAN WebSocket on port 3030 requires no login/token on the local subnet (discovered via UDP 'M99999' returning MainboardID). Older/USB-only models (e.g., Sonic Mega 8K S without network SDCP board) have no network control and require FAT32 USB drive.","upload_print_control_endpoints":["UDP broadcast 'M99999' to <broadcast>:3000 (returns MainboardIP, MainboardID, ProtocolVersion, FirmwareVersion)","WS ws://<MainboardIP>:3030/websocket (topics: sdcp/request/${MainboardID}, sdcp/response/${MainboardID}, sdcp/status/${MainboardID}, sdcp/attributes/${MainboardID}, sdcp/error/${MainboardID}, sdcp/notice/${MainboardID})","SDCP Cmd 0 (status), Cmd 1 (attributes), Cmd 64 (disconnect), Cmd 128 (start print: Filename, StartLayer), Cmd 256 (upload file), Cmd 512 (set reporting TimePeriod)","POST http://<MainboardIP>:3030/uploadFile/upload (1 MB chunked multipart upload with Offset, TotalSize, Uuid, S-File-MD5)"],"offline_capable":true,"offline_mode_notes":"Fully offline-capable via LAN-only SDCP 3.0 (ChitUI / ChiTuBox) or FAT32 USB flash drive (.ctb / .prz) without internet.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"UV LED temperature sensor (SDCP DevicesStatus.TempSensorStatusOfUVLED, TempOfUVLEDMax); Built-in resin vat/chamber heater on Sonic Mighty Revo","cameras":"Built-in camera on Sonic Mighty Revo (SDCP CameraStatus & RTSP VIDEO_STREAM capability); unavailable on Sonic Mega 8K S","lidar_and_ai_inspection":"unavailable (no LiDAR; Revo uses strain-gauge residue/failure detection rather than optical LiDAR)","filament_and_spool_systems":"unavailable (resin MSLA; optional external resin pump/auto-feeder on Revo/Mega accessories; release film life counter ReleaseFilmMax in SDCP Attributes)","accelerometers_input_shaper":"unavailable","bed_probes":"Strain-gauge / residue & failure detection sensor on Sonic Mighty Revo (SDCP DevicesStatus.SgStatus: 0=disconnected, 1=normal, 2=calibration failed) + auto-leveling; manual 4-screw A4-paper Z-calibration on Sonic Mega 8K S","status_error_feeds":"SDCP WebSocket topics sdcp/status/${MainboardID}, sdcp/error/${MainboardID}, sdcp/notice/${MainboardID}, and DevicesStatus bit-states (UVLED, LCD, Strain Gauge, Z/Rotate/X motors, ReleaseFilm)"},"troubleshooting_and_faults":{"fault_code_taxonomy":"SDCP JSON error messages on sdcp/error/${MainboardID} + touchscreen hardware diagnostic routines (LCD test, LED array check, Z-axis/motor check, touch panel) and descriptive 'Printing Error' alerts.","example_fault_codes":[{"code":"DevicesStatus.SgStatus = 2 / Residue Detection","description":"Strain gauge / auto-leveling calibration failure or vat residue obstruction reported via SDCP DevicesStatus","kb_url":"https://github.com/cbd-tech/SDCP-Smart-Device-Control-Protocol-V3.0.0/blob/main/SDCP(Smart%20Device%20Control%20Protocol)_V3.0.0_EN.md"},{"code":"Printing Error (file/USB corruption)","description":"Mid-print halt on Sonic Mega 8K S / MSLA printers due to large/corrupt .ctb/.prz or non-FAT32 USB drive","kb_url":"https://helpcenter.phrozen3d.com/hc/en-us/articles/6369983852569-Firmware-downloads-and-release-notes"},{"code":"Bottom Layers Missing / Compressed","description":"Z-axis zero/leveling compression fault requiring multi-sheet A4 calibration and Z-offset tuning","kb_url":"https://helpcenter.phrozen3d.com/hc/en-us/articles/33887953007385-Why-Are-The-Bottom-Layers-Missing-Or-Compressed"}],"diagnostic_logs":"Touchscreen Tools/Settings > Info > Error Log exported to USB drive.","official_kb_urls":["https://helpcenter.phrozen3d.com/hc/en-us/sections/28050685075737--Sonic-Mighty-Revo-Hardware-Troubleshooting","https://helpcenter.phrozen3d.com/hc/en-us/articles/28051680346393--Sonic-Mighty-Revo-Z-axis-Calibration","https://helpcenter.phrozen3d.com/hc/en-us/articles/21706516790425--Sonic-Mega-8K-S-Checking-the-Z-axis-and-Motor","https://helpcenter.phrozen3d.com/hc/en-us/articles/21706298769305--Sonic-Mega-8K-S-Checking-the-LED","https://helpcenter.phrozen3d.com/hc/en-us/articles/33887953007385-Why-Are-The-Bottom-Layers-Missing-Or-Compressed","https://helpcenter.phrozen3d.com/hc/en-us/articles/6369983852569-Firmware-downloads-and-release-notes"]},"source_urls":["https://github.com/cbd-tech/SDCP-Smart-Device-Control-Protocol-V3.0.0/blob/main/SDCP(Smart%20Device%20Control%20Protocol)_V3.0.0_EN.md","https://github.com/jangrewe/ChitUI","https://github.com/vvuk/cassini/blob/main/saturn_printer.py","https://helpcenter.phrozen3d.com/hc/en-us/sections/28050685075737--Sonic-Mighty-Revo-Hardware-Troubleshooting","https://helpcenter.phrozen3d.com/hc/en-us/articles/33887953007385-Why-Are-The-Bottom-Layers-Missing-Or-Compressed"],"source_verified":true,"availability_notes":"SDCP v3.0.0 is officially open-sourced by Chitu/CBD-Tech on GitHub and supported on network-enabled Revo models (bridged by ChitUI); USB-only Phrozen models (e.g. Mega 8K S) lack network APIs.","relevance_to_forma_print":"Confirms SDCP v3.0.0 shared protocol across Chitu-powered MSLA printers (Elegoo + Phrozen), informing MSLA hollowing/drainage/suction DFM checks and LAN dispatch."}+{"id":"ankermake_eufymake","manufacturer":"AnkerMake / eufyMake","technologies":["FDM","UV_Inkjet"],"segment":"consumer","representative_models":["AnkerMake M5","AnkerMake M5C","eufyMake E1 (UV printer)"],"direct_communication":{"local_protocols":["PPPP P2P UDP (port 32100, PktLanSearch + file transfer + camera stream via community RE ankermake-m5-protocol / ankerctl)","unavailable on eufyMake E1 (zero official local or cloud API; community automation relies on UI scripting + physical button servo)"],"cloud_protocols":["HTTPS cloud login/config (port 443, login.json)","MQTTS telemetry & control (port 8883, topic /phone/maker/<DEVICE_SN>/notice)"],"ports":["443/tcp (HTTPS cloud auth/config)","8883/tcp (MQTTS telemetry & command notices)","32100/udp (PPPP P2P LAN discovery, file transfer & camera video)"],"auth_and_modes":"Cloud-first proprietary authentication via AnkerMake account (login.json / AnkerMake Studio). No official third-party local developer API. Community RE tool `ankerctl` / `libflagship` (`ankermgmt/ankermake-m5-protocol`) imports AnkerMake Studio login credentials to access MQTTS:8883 and local PPPP:32100 tunnels.","upload_print_control_endpoints":["MQTTS :8883 topic /phone/maker/<DEVICE_SN>/notice (telemetry & commands via libflagship, community RE)","PPPP UDP :32100 PktLanSearch / FileTransfer / P2PCmdType (LAN G-code upload & camera feed via ankerctl, community RE)","unavailable (no official public REST/WS endpoints for M5/M5C or eufyMake E1)"],"offline_capable":true,"offline_mode_notes":"M5 supports USB-C flash drive offline printing; M5C lacks a built-in screen and relies heavily on app/PC software (or ankerctl over LAN after initial cloud login import). eufyMake E1 requires eufyMake Studio desktop app.","status":"cloud_first_limited_local"},"monitoring_and_sensors":{"thermal_sensors":"Hotend thermistor; Heated bed thermistor","cameras":"M5: Built-in 1080p AI camera streamed over proprietary PPPP UDP:32100 (accessible via ankerctl). M5C: unavailable (no camera). eufyMake E1: optical/snapshot tray camera inside eufyMake Studio","lidar_and_ai_inspection":"M5: Onboard AI camera spaghetti/extrusion failure detection (unavailable on M5C); eufyMake E1: dual laser alignment/obstruction sensors","filament_and_spool_systems":"Filament runout / broken-filament sensor on M5/M5C","accelerometers_input_shaper":"unavailable (proprietary firmware input shaping on M5/M5C Marlin-based controller)","bed_probes":"Nozzle strain-gauge auto-bed leveling (7x7 / 49-point mesh on M5/M5C)","status_error_feeds":"MQTTS :8883 notice payloads (community-decoded via libflagship) and AnkerMake/eufyMake App/PC alerts"},"troubleshooting_and_faults":{"fault_code_taxonomy":"AnkerMake M5/M5C primarily emit descriptive App/PC error alerts (Data Transmission Error, Auto-Leveling Error, Heating Anomaly), while eufyMake systems expose 32-bit hexadecimal fault codes (0xFD...).","example_fault_codes":[{"code":"0xFD01120001","description":"eufyMake Laser sensor error (laser receiver blocked by foreign object or laser alignment disabled)","kb_url":"https://support.eufymake.com/s/article/Printer-Laser-Sensor-Error"},{"code":"Data Transmission Error (M5C)","description":"Poor contact on nozzle assembly USB Type-C cable or left shoulder cable","kb_url":"https://support.ankermake.com/s/article/How-to-Fix-Data-Transmission-Error-for-the-M5C-Printer"},{"code":"Auto-Leveling Error (M5C)","description":"Nozzle tip debris or USB-C strain-gauge communication fault during bed probing","kb_url":"https://support.ankermake.com/s/article/How-to-Fix-the-Auto-Leveling-Error-for-the-M5C-Printer"}],"diagnostic_logs":"Printer and App logs uploaded via AnkerMake / eufyMake App or PC Studio (Log Feedback Upload Process).","official_kb_urls":["https://support.ankermake.com/s/article/How-to-Fix-Data-Transmission-Error-for-the-M5C-Printer","https://support.ankermake.com/s/article/How-to-Fix-the-Auto-Leveling-Error-for-the-M5C-Printer","https://support.ankermake.com/s/article/Ankermake-Studio-Issues-Troubleshooting","https://support.eufymake.com/s/article/Printer-Laser-Sensor-Error","https://support.eufymake.com/s/article/Initialization-Troubleshooting-Common-Issues-Solutions"]},"source_urls":["https://github.com/Ankermgmt/ankermake-m5-protocol","https://github.com/Ankermgmt/ankermake-m5-protocol/blob/master/ankerctl.py","https://support.ankermake.com/s/article/How-to-Fix-Data-Transmission-Error-for-the-M5C-Printer","https://support.ankermake.com/s/article/How-to-Fix-the-Auto-Leveling-Error-for-the-M5C-Printer","https://support.eufymake.com/s/article/Printer-Laser-Sensor-Error","https://hackaday.io/project/204104-hacking-the-eufy-e1-make-uv-printer"],"source_verified":true,"availability_notes":"No official public API exists for AnkerMake or eufyMake. Community RE (`ankermgmt/ankermake-m5-protocol`) supports M5/M5C via MQTTS:8883 and PPPP:32100 after extracting AnkerMake Studio login credentials, though firmware updates periodically break MQTT decoders. eufyMake E1 UV printer has zero local/cloud API.","relevance_to_forma_print":"Demonstrates why forma-print prioritizes standard `.3mf`/`.step` export over fragile proprietary P2P/cloud protocols, while cataloging M5/M5C strain-gauge & USB-C troubleshooting in RAG."}+{"id":"lulzbot","manufacturer":"LulzBot (FAME 3D)","technologies":["FDM"],"segment":"prosumer","representative_models":["LulzBot TAZ Workhorse","LulzBot TAZ Pro","LulzBot SideKick (289 / 747)","LulzBot TAZ 6"],"direct_communication":{"local_protocols":["USB Serial G-code (Marlin 2.x at 250000 baud, legacy 115200 baud)","SD Card offline","OctoPrint HTTP REST API (when paired with external Raspberry Pi / OctoPrint host)"],"cloud_protocols":["unavailable (no native cloud protocol; optional OctoPrint plugins)"],"ports":["USB Virtual COM /dev/ttyACM* (250000 baud, legacy 115200 baud)","80/tcp or 5000/tcp (external OctoPrint host if attached, not native on printer)"],"auth_and_modes":"Unauthenticated direct USB serial connection from Cura LulzBot Edition (Cura LE), Pronterface, or OctoPrint. No native Ethernet/Wi-Fi on stock RAMBo/Archim/SKR controller configurations.","upload_print_control_endpoints":["USB Serial G-code commands (G28, G29, M104, M140, M105, M112, M600 at 250000 baud)","unavailable natively over IP (requires external OctoPrint / Moonraker host for HTTP REST)"],"offline_capable":true,"offline_mode_notes":"100% offline-capable via SD card + LCD controller or direct USB serial from Cura LE / Pronterface.","status":"closed_or_usb_only"},"monitoring_and_sensors":{"thermal_sensors":"Hotend thermistor (2.85mm / 1.75mm toolheads); Heated bed thermistor","cameras":"unavailable natively (added only via external OctoPrint webcam)","lidar_and_ai_inspection":"unavailable","filament_and_spool_systems":"Rotary encoder + O-ring filament runout and jam sensor on TAZ Pro / advanced toolheads (emits //action:paused Filament_runout 0)","accelerometers_input_shaper":"unavailable","bed_probes":"Electrical conductivity nozzle-to-corner-washer probing (TAZ 6 / Workhorse / TAZ Pro) or BLTouch mechanical pin probe (SideKick / upgrades)","status_error_feeds":"Marlin serial terminal echoes (M105 temperatures, //action:prompt_*, Error: halts) and graphical LCD status"},"troubleshooting_and_faults":{"fault_code_taxonomy":"Standard Marlin firmware safety halt and action prompt strings over serial and LCD (Probing failed, MINTEMP, MAXTEMP, Thermal Runaway, BLTouch Error, Filament_runout).","example_fault_codes":[{"code":"Probing failed PRINTER HALTED Please reset","description":"Electrical conductivity probe failure caused by dirty nozzle/corner washers or out-of-level X-axis","kb_url":"https://forum.lulzbot.com/t/probing-failed-printer-halted-please-reset/25567"},{"code":"Err: MINTEMP / MAXTEMP","description":"Thermistor open circuit / cold room (<min temp) or thermistor short circuit","kb_url":"https://forum.lulzbot.com/t/mintemp-error-after-failed-print-on-taz6/24421"},{"code":"//action:paused Filament_runout 0","description":"TAZ Pro rotary encoder filament runout/jam trigger (often caused by worn O-rings or slippery/1.75mm filament)","kb_url":"https://forum.lulzbot.com/t/filamentrunout-print-error/27141"}],"diagnostic_logs":"Cura LE / OctoPrint serial terminal logs (serial.log / octoprint.log).","official_kb_urls":["https://ohai.lulzbot.com","https://gitlab.com/lulzbot3d","https://lulzbot.com","https://ohai.lulzbot.com/project/leveling-x-axis/maintenance-repairs/","https://forum.lulzbot.com/t/probing-failed-printer-halted-please-reset/25567","https://forum.lulzbot.com/t/filamentrunout-print-error/27141"]},"source_urls":["https://ohai.lulzbot.com","https://gitlab.com/lulzbot3d","https://lulzbot.com","https://forum.lulzbot.com/t/probing-failed-printer-halted-please-reset/25567","https://forum.lulzbot.com/t/filamentrunout-print-error/27141","https://forum.lulzbot.com/t/mintemp-error-after-failed-print-on-taz6/24421"],"source_verified":true,"availability_notes":"Fully open-source hardware/firmware (OHAI + GitLab Marlin), but stock printers are USB-serial / SD-card only without a built-in network API unless connected to OctoPrint.","relevance_to_forma_print":"Represents classic USB-serial Marlin / 2.85mm filament ecosystem; Cura LE profile & conductivity-probing / rotary-runout diagnostics for RAG KB."}+{"id":"duet3d","manufacturer":"Duet3D (RepRapFirmware / DSF Ecosystem)","technologies":["FDM"],"segment":"ecosystem","representative_models":["Duet 2 WiFi / Ethernet","Duet 3 Mainboard 6HC / 6XD","Duet 3 Mini 5+","Duet 3 Toolboard 1LC / SZP"],"direct_communication":{"local_protocols":["RepRapFirmware (RRF) HTTP/HTTPS REST + WebSockets (standalone mode)","Duet Software Framework (DSF) HTTP REST + WebSocket JSON-patch (SBC mode via SPI or USB)","Telnet / FTP (optional via M586)","CAN-FD (Duet 3 expansion & toolboards)"],"cloud_protocols":["unavailable (100% self-hosted local-first architecture)"],"ports":["80/tcp (HTTP Duet Web Control & REST/WebSocket API)","443/tcp (HTTPS when enabled via M586)","21/tcp, 23/tcp (optional FTP / Telnet via M586)"],"auth_and_modes":"Standalone mode: GET /rr_connect?password=<pwd> (default 'reprap', optional sessionKey=yes since RRF 3.5-b4); returns 401 if no valid session. SBC mode (DuetWebServer -> DuetControlServer IPC): GET /machine/connect?password=<pwd> returns {\"sessionKey\":...} passed via X-Session-Key header or ?sessionKey= WebSocket query param (returns 403 if invalid). OpenAPI YAML specs available since RRF 3.4.1.","upload_print_control_endpoints":["GET /rr_connect?password=<pwd>&sessionKey=yes (Standalone)","GET /rr_model?key=<object_model_key> (Standalone Object Model; legacy rr_status removed in RRF 3.6+)","GET /rr_gcode?gcode=<cmd> (Standalone)","POST /rr_upload?name=<path> & GET /rr_download?name=<path> & GET /rr_filelist (Standalone)","GET /machine/connect?password=<pwd> (DSF SBC mode)","GET /machine/model & WS /machine?sessionKey=<key> (DSF full Object Model + JSON-patch stream)","POST /machine/code?async=true|false (DSF G/M/T-code execution)","PUT /machine/file/{filename} & GET /machine/file/{filename} & DELETE /machine/file/{filename} & GET /machine/fileinfo/{filename} (DSF)"],"offline_capable":true,"offline_mode_notes":"Designed from the ground up for 100% offline/LAN operation with Duet Web Control (DWC) served locally and SD/SBC file execution.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"NTC thermistors, PT100/PT1000 (MAX31865), K/J-type thermocouples (MAX31855/31856); MCU & TMC stepper driver over-temperature telemetry in Object Model","cameras":"No native camera hardware; Duet Web Control supports embedding external MJPEG/RTSP IP webcam streams","lidar_and_ai_inspection":"unavailable","filament_and_spool_systems":"Duet3D Rotating Magnet Filament Monitor (motion + direction via M591; legacy Laser Filament Monitor discontinued), simple switch sensors, triggers filament-error.g or automatic pause.g","accelerometers_input_shaper":"Duet3D Accelerometer v0.2 (LIS3DH) / v1.0 (LIS2DW12) via 3.3V SPI daughterboard header + built-in accelerometers on Duet 3 toolboards for RRF Input Shaping plugin","bed_probes":"Z-probe modes via Object Model sensors.probes: Duet3D Smart Effector, Scanning Z Probe, IR Z probe, FSR, piezo, BLTouch, NPN/PNP inductive/capacitive, microswitch","status_error_feeds":"Unified RepRapFirmware Object Model (M409 / rr_model / /machine/model / WS /machine), M122 diagnostics report, M291/DWC popups and console"},"troubleshooting_and_faults":{"fault_code_taxonomy":"M122 diagnostic report with 5-bit Error Status bitmask (0x01..0x10), ARM Cortex software reset codes (Hard Fault, Memory Protection Fault, Watchdog + stack trace), plus heater faults and emergency stop (M112).","example_fault_codes":[{"code":"M122 Error status 0x01 / 0x02","description":"0x01: Watchdog turned heater off temporarily; 0x02: One or more step errors occurred","kb_url":"https://docs.duet3d.com/User_manual/Troubleshooting/Error_codes"},{"code":"M122 Error status 0x04 / 0x08 / 0x10","description":"0x04: Output buffer starvation; 0x08: Output stack overflow; 0x10: SD card operation timed out","kb_url":"https://docs.duet3d.com/User_manual/Troubleshooting/Error_codes"},{"code":"Software reset code 0x0003 (Watchdog / Hard Fault)","description":"Last software reset cause in M122 report with HFSR/CFSR/ICSR/BFAR registers and task stack trace","kb_url":"https://docs.duet3d.com/User_manual/Troubleshooting/Error_codes"}],"diagnostic_logs":"M122 command output in DWC Console; DSF/DCS systemd & syslog logs on DuetPi SBC.","official_kb_urls":["https://docs.duet3d.com/User_manual/Reference/APIs","https://docs.duet3d.com/User_manual/Machine_configuration/DSF","https://docs.duet3d.com/User_manual/RepRapFirmware/Object_Model","https://docs.duet3d.com/User_manual/Reference/Duet_Web_Control_Manual","https://docs.duet3d.com/User_manual/Troubleshooting/Error_codes","https://docs.duet3d.com/Duet3D_hardware/Accessories/Duet3D_Accelerometer","https://docs.duet3d.com/User_manual/Connecting_hardware/Sensors_filament","https://docs.duet3d.com/en/User_manual/Connecting_hardware/Z_probe_connecting","https://duet3d.github.io/DuetSoftwareFramework/articles/rest-api.html","https://github.com/Duet3D/RepRapFirmware/wiki/HTTP-requests"]},"source_urls":["https://docs.duet3d.com/User_manual/Reference/APIs","https://duet3d.github.io/DuetSoftwareFramework/articles/rest-api.html","https://github.com/Duet3D/RepRapFirmware/wiki/HTTP-requests","https://docs.duet3d.com/User_manual/Troubleshooting/Error_codes","https://docs.duet3d.com/Duet3D_hardware/Accessories/Duet3D_Accelerometer","https://docs.duet3d.com/User_manual/Connecting_hardware/Sensors_filament"],"source_verified":true,"availability_notes":"Completely open, officially documented dual API model (RRF HTTP requests for standalone boards and DSF REST/WebSocket API for SBC mode) with OpenAPI specs and zero cloud lock-in.","relevance_to_forma_print":"Gold-standard Object Model + REST/WebSocket reference architecture for custom/industrial FDM printers; informs M122/filament-monitor/accelerometer RAG troubleshooting."}+{"id":"bigtreetech","manufacturer":"BigTreeTech (BTT / BIQU Hardware Ecosystem)","technologies":["FDM"],"segment":"ecosystem","representative_models":["BTT Octopus V1.1 / Pro","BTT Manta M8P / M5P / M4P + CB1 / CM4","BTT SKR 3 / SKR Mini E3","BTT EBB36 / EBB42 / SB2209 CANbus Toolboards","BTT Eddy / Eddy Duo / Eddy Coil & SFS V2.0"],"direct_communication":{"local_protocols":["Klipper + Moonraker HTTP REST / JSON-RPC WebSocket (port 7125, when running Klipper on CB1/CM4/Pi)","Mainsail / Fluidd web UI (port 80) & KlipperScreen local touchscreen GUI","CAN bus (can0 at 1000000 bps / 1000K for EBB36/42 & Eddy Duo CAN)","USB Serial (250000 baud for Klipper MCU or Marlin SKR/Octopus standalone)"],"cloud_protocols":["unavailable natively (optional third-party Obico / OctoEverywhere / Tailscale plugins on host)"],"ports":["7125/tcp (Moonraker HTTP & WebSocket JSON-RPC when running Klipper)","80/tcp (Mainsail / Fluidd HTTP)","8080/tcp (webcam streamer / Crowsnest)","CAN0 1Mbps / USB Serial 250000 baud (MCU & toolboard bus)"],"auth_and_modes":"Open-source ecosystem: Moonraker uses trusted_clients IP CIDR rules and optional X-Api-Key / user auth in moonraker.conf; KlipperScreen connects locally or remotely to Moonraker IP. Marlin-flashed SKR/Octopus boards use unauthenticated USB serial / SD card.","upload_print_control_endpoints":["GET http://<host>:7125/printer/objects/query?... (Moonraker Klipper state)","POST http://<host>:7125/server/files/upload (Moonraker G-code upload)","POST http://<host>:7125/printer/gcode/script?script=... (Moonraker G-code exec)","POST http://<host>:7125/printer/print/start?filename=... (Moonraker print start)","WS ws://<host>:7125/websocket (Moonraker JSON-RPC real-time telemetry)"],"offline_capable":true,"offline_mode_notes":"100% offline/LAN-capable via CB1/CM4 Linux host (Mainsail/Fluidd/KlipperScreen) or SD card + BTT TFT serial screen under Marlin.","status":"open_official"},"monitoring_and_sensors":{"thermal_sensors":"100K NTC thermistors + onboard MAX31865 PT100/PT1000 RTDs (EBB36/42 & Octopus Pro); Host CB1/CM4 SoC & MCU internal temperature sensors; TMC2209/TMC5160 UART/SPI driver over-temperature flags","cameras":"USB/CSI webcams streamed via Crowsnest / mjpg-streamer on host (port 8080 / /webcam/?action=stream)","lidar_and_ai_inspection":"unavailable natively (supports optional external Obico AI webcam plugin via Moonraker)","filament_and_spool_systems":"BTT Smart Filament Sensor SFS V1.0 & V2.0 (dual microswitch runout + 7mm optical encoder jam/tangle detection via [filament_switch_sensor] & [filament_motion_sensor])","accelerometers_input_shaper":"Onboard ADXL345 on EBB36/42 CAN toolboards, standalone ADXL345/S2DW via SPI on CB1 40-pin GPIO (/boot/BoardEnv.txt overlays=spi-spidev) for Klipper SHAPER_CALIBRATE","bed_probes":"BTT Eddy / Eddy Duo / Eddy Coil (non-contact eddy-current probe, 0.5um standard error, thermal compensation, <=60C ambient, USB/CAN/I2C; must mount 2-3mm above nozzle), plus BLTouch / inductive probes","status_error_feeds":"Moonraker WebSocket JSON-RPC notifications, KlipperScreen error modals, Klipper Stats bytes_invalid CANbus counter in klippy.log"},"troubleshooting_and_faults":{"fault_code_taxonomy":"Klipper MCU shutdown/config/probe/TMC error strings (e.g., Lost communication with MCU, I2C BUS_TIMEOUT, Timer too close, TMC reports error, BLTouch failed) plus Marlin thermal/endstop halts when configured with Marlin.","example_fault_codes":[{"code":"Lost communication with MCU 'eddy' / I2C request to addr 42 reports error BUS_TIMEOUT","description":"BTT Eddy RP2040 USB/EMI drop or LDC_CALIBRATE_DRIVE_CURRENT I2C bus timeout","kb_url":"https://github.com/bigtreetech/Eddy/issues/17"},{"code":"Error during homing z: Eddy current sensor error","description":"Eddy mounting height outside 2-3mm nozzle offset window causing coil saturation or out-of-range voltage amplitude","kb_url":"https://github.com/bigtreetech/docs/blob/master/docs/Eddy.md"},{"code":"bytes_invalid incrementing / CANbus communication error","description":"Missing 120-ohm termination resistors, untwisted CANH/CANL wiring, or bad crimps on EBB36/42 CAN bus","kb_url":"https://www.klipper3d.org/CANBUS_Troubleshooting.html"}],"diagnostic_logs":"klippy.log, moonraker.log, crowsnest.log, KlipperScreen.log (accessible via Mainsail/Fluidd Machine tab or SSH on CB1/CM4).","official_kb_urls":["https://github.com/bigtreetech","https://global.bttwiki.com/","https://neo.bttwiki.com/en/docs/accessories-docs/sensor/eddy/eddy-hardware/","https://neo.bttwiki.com/en/docs/board-docs/ebb-series/ebb-36/ebb-36-firmware","https://github.com/bigtreetech/docs/blob/master/docs/Eddy.md","https://github.com/bigtreetech/smart-filament-detection-module","https://github.com/bigtreetech/EBB","https://github.com/bigtreetech/BIGTREETECH-OCTOPUS-V1.0","https://github.com/bigtreetech/KlipperScreen","https://www.klipper3d.org/CANBUS_Troubleshooting.html"]},"source_urls":["https://github.com/bigtreetech","https://github.com/bigtreetech/docs/blob/master/docs/Eddy.md","https://github.com/bigtreetech/smart-filament-detection-module","https://github.com/bigtreetech/EBB","https://github.com/bigtreetech/KlipperScreen","https://github.com/bigtreetech/CB1/discussions/47","https://neo.bttwiki.com/en/docs/accessories-docs/sensor/eddy/eddy-hardware/","https://www.klipper3d.org/CANBUS_Troubleshooting.html"],"source_verified":true,"availability_notes":"Fully open-source hardware schematics, pinouts, and Klipper/Marlin configs on GitHub/bttwiki. Requires host SBC (CB1/CM4/RPi) running Klipper+Moonraker for IP/REST/WS control; bare Octopus/SKR boards under Marlin are USB-serial/SD only.","relevance_to_forma_print":"Core hardware substrate for Voron/RatRig/custom Klipper printers; covers Moonraker :7125 dispatch, SFS V2.0 7mm motion/switch runout, BTT Eddy 2-3mm mount constraints, and CANbus/ADXL345 diagnostics in RAG."}+{"id":"makerbot","manufacturer":"MakerBot (UltiMaker Method / Sketch Lineage)","technologies":["FDM"],"segment":"prosumer","representative_models":["MakerBot Method","MakerBot Method X","MakerBot Method XL","MakerBot Sketch / Sketch Large / Sketch Sprint"],"direct_communication":{"local_protocols":["Proprietary local discovery/relay on TCP 9999 and 12309 (no open local HTTP/REST/WebSocket API; UltiMaker Cura cannot connect to Method over LAN or direct USB)"],"cloud_protocols":["UltiMaker Digital Factory cloud workflow (api.ultimaker.com, digitalfactory.ultimaker.com, cloudauth.makerbot.com, reflector.makerbot.com)"],"ports":["12309/tcp (Digital Factory cloud & local network communication)","9999/tcp (MakerBot local network discovery/communication)","123/udp (NTP time.nist.gov sync required for cloud)"],"auth_and_modes":"Networked Method/Method X/Method XL printing in UltiMaker Cura is supported exclusively via UltiMaker Digital Factory cloud login (legacy MakerBot Print cloud auth servers retired; IPv4 recommended over IPv6). Direct USB connection and Local network / LAN mode / Direct IP printing from Cura are explicitly unsupported.","upload_print_control_endpoints":["unavailable (no open local HTTP/REST/WebSocket API; UltiMaker Cura cannot connect via local IP or direct USB)","Digital Factory cloud print queue via UltiMaker Cura ('Print via cloud') or offline USB drive (.makerbot)"],"offline_capable":true,"offline_mode_notes":"Supports offline USB flash drive printing (.makerbot exported from UltiMaker Cura or CloudPrint) without network connectivity, though networked LAN-only slicing/control from Cura is unsupported.","status":"cloud_first_limited_local"},"monitoring_and_sensors":{"thermal_sensors":"Dual extruder thermal sensors (up to 300 C on Method X); VECT actively heated chamber sensors (up to 110 C on Method X, 100 C on Method XL); heated build plate up to 105 C on Method XL","cameras":"Built-in 640x480 chamber monitoring camera accessible via Digital Factory / MakerBot software (no open local RTSP/MJPEG stream documented)","lidar_and_ai_inspection":"unavailable (no native LiDAR)","filament_and_spool_systems":"Dry-sealed material bays with MakerBot Smart Spool RFID readers (material type, color, remaining length/weight), drawer humidity/temperature sensors, extruder material detection, and encoder-based jam detection","accelerometers_input_shaper":"unavailable (no user-exposed accelerometer telemetry documented)","bed_probes":"Automated nozzle-contact bed leveling & dual-extruder Z/XY offset calibration","status_error_feeds":"Touchscreen numeric fault alerts, UltiMaker Digital Factory cloud status, and 21-sensor onboard diagnostics"},"troubleshooting_and_faults":{"fault_code_taxonomy":"Method series uses 4-digit numeric error codes (e.g., 1013 Homing Time Out, 1032 extruder offset calibration failure, 1100 Internal Timeout); Sketch Sprint uses SPxxx codes (e.g., SP001, SP007, SP009).","example_fault_codes":[{"code":"1013 (Homing Error / Homing Time Out)","description":"Calibration homing process timed out while extruder nozzle awaited build plate contact or failed to reseat/light up in carriage.","kb_url":"https://support.makerbot.com/s/article/Homing-Error-1013"},{"code":"1032 (Method Calibration Error)","description":"Toolhead calibration failed to calculate XY/Z offsets (typically debris on nozzle tips, unseated extruders, or firmware needing USB refresh).","kb_url":"https://support.makerbot.com/s/article/Method-Error-1032"},{"code":"1100 (Internal Timeout)","description":"Internal operation timeout, often triggered when print file was exported from a slicer version incompatible with printer firmware.","kb_url":"https://support.makerbot.com/s/article/Error-1100"}],"diagnostic_logs":"On Method / Method X / Method XL touchscreen: Settings -> Advanced Settings -> Copy logs to USB (exports a single .zip archive to USB stick).","official_kb_urls":["https://support.makerbot.com/s/article/Network-Configuration-Requirements","https://support.makerbot.com/s/article/000003066","https://support.makerbot.com/s/topic/0TO5b000000sXvNGAU/method-troubleshooting","https://support.makerbot.com/s/article/Homing-Error-1013","https://support.makerbot.com/s/article/Method-Error-1032","https://support.makerbot.com/s/article/Error-1100","https://support.makerbot.com/s/article/1667337561393"]},"source_urls":["https://support.makerbot.com/s/article/Network-Configuration-Requirements","https://support.makerbot.com/s/article/000003066","https://support.makerbot.com/s/topic/0TO5b000000sXvNGAU/method-troubleshooting","https://support.makerbot.com/s/article/Homing-Error-1013","https://support.makerbot.com/s/article/Method-Error-1032","https://support.makerbot.com/s/article/Error-1100","https://support.makerbot.com/s/article/1667337561393","https://ultimaker.com/3d-printers/method-series/ultimaker-method-x/","https://ultimaker.com/3d-printers/method-series/ultimaker-method-xl/"],"source_verified":true,"availability_notes":"Although MakerBot merged with UltiMaker in 2022, Method/Method X/Method XL/Sketch printers do NOT inherit UltiMaker's open local /api/v1/ HTTP REST API; Cura explicitly disables LAN/direct-USB connections to Method and routes networked jobs via Digital Factory cloud (ports 123/12309/9999) or offline USB (.makerbot).","relevance_to_forma_print":"Prevents false-positive open_official LAN filtering by separating MakerBot's cloud-first/USB workflow from UltiMaker S-series/Factor 4; documents 1.75mm actively heated 100-110C ABS/SR-30 dual-extrusion profiles and 1013/1032/1100 diagnostics in RAG."}diff --git a/research/corpus/papers.jsonl b/research/corpus/papers.jsonlnew file mode 100644index 0000000..2f74c2e--- /dev/null+++ b/research/corpus/papers.jsonl@@ -0,0 +1,49 @@+{"id": "prevost-2013-make-it-stand", "title": "Make It Stand: Balancing Shapes for 3D Fabrication", "authors": ["Romain Prévost", "Emily Whiting", "Sylvain Lefebvre", "Olga Sorkine-Hornung"], "year": 2013, "venue": "ACM Transactions on Graphics (SIGGRAPH 2013)", "category": "printability_optimization", "doi_or_arxiv_id": "10.1145/2461912.2461957", "url": "https://doi.org/10.1145/2461912.2461957", "summary": "Introduces a computational design tool that modifies arbitrary 3D meshes so fabricated prints stand stably in static equilibrium under gravity without external bases or glue. The method combines interior carving/hollowing with subtle surface deformation to move the center of mass over the support polygon while preserving artistic details.", "key_algorithm": "Formulates static balance as a constrained energy-minimization problem projecting the center of mass (CoM) into the 2D convex hull of bottom contact points. Jointly optimizes discrete interior void voxels and low-distortion cage/handle-based surface deformations using closed-form volumetric CoM derivatives.", "relevance_to_forma_print": "Directly informs `dfm.rs` bed-adhesion and tipping stability checks (divergence-theorem CoM projection into the 2D convex hull of bed-contact vertices) and motivates future Tier 2 interactive CoM-balancing deformation or selective hollowing.", "source_verified": true}+{"id": "baecher-2014-spin-it", "title": "Spin-It: Optimizing Moment of Inertia for Spinnable Objects", "authors": ["Moritz Bächer", "Emily Whiting", "Bernd Bickel", "Olga Sorkine-Hornung"], "year": 2014, "venue": "ACM Transactions on Graphics (SIGGRAPH 2014)", "category": "printability_optimization", "doi_or_arxiv_id": "10.1145/2601097.2601157", "url": "https://doi.org/10.1145/2601097.2601157", "summary": "Presents a computational fabrication method that optimizes the internal mass distribution of arbitrary asymmetric 3D meshes so they spin stably like tops or yo-yos around a user-chosen axis. By carving internal voids while keeping the exterior geometry fixed, the algorithm aligns principal inertia axes with the target rotation axis.", "key_algorithm": "Discretizes the interior into an adaptive multiresolution octree voxel grid and solves a continuous nonlinear optimization over voxel fill values. Aligns the inertia tensor eigenvectors with the target spin frame and maximizes the dominant principal moment of inertia subject to mass and shell-thickness bounds.", "relevance_to_forma_print": "Demonstrates octree-based volumetric inertia-tensor computation and internal void optimization with fixed outer shells, relevant for `forma-print` divergence-theorem physical property auditing and multi-material mass balancing (e.g., dense vs. sparse modifier regions in `.3mf`).", "source_verified": true}+{"id": "musialski-2015-offset-surfaces", "title": "Reduced-order shape optimization using offset surfaces", "authors": ["Przemyslaw Musialski", "Thomas Auzinger", "Michael Birsak", "Michael Wimmer", "Leif Kobbelt"], "year": 2015, "venue": "ACM Transactions on Graphics (SIGGRAPH 2015)", "category": "printability_optimization", "doi_or_arxiv_id": "10.1145/2766955", "url": "https://doi.org/10.1145/2766955", "summary": "Develops a reduced-order framework for optimizing the physical properties (mass, center of mass, moments of inertia) of 3D-printable shells using variable-thickness inner and outer offset surfaces. Representing offsets in a low-frequency spectral basis prevents high-frequency wrinkling and decouples solver complexity from mesh resolution.", "key_algorithm": "Parameterizes normal offset fields on a 2-manifold surface using a truncated basis of low-frequency Manifold Harmonics (eigenvectors of the mesh Laplacian). Converts 3D volume integrals of mass and inertia into surface integrals via the Divergence Theorem, yielding analytic gradients for fast nonlinear constrained optimization.", "relevance_to_forma_print": "Provides exact Divergence-Theorem surface-integral formulations for mass and CoM used in `dfm.rs` bed stability checks, and offers a mesh-resolution-independent offset-shell formulation for Tier 2 variable-thickness hollowing.", "source_verified": true}+{"id": "shugrina-2015-fab-forms", "title": "Fab Forms: Customizable Objects for Fabrication with Validity and Geometry Caching", "authors": ["Maria Shugrina", "Ariel Shamir", "Wojciech Matusik"], "year": 2015, "venue": "ACM Transactions on Graphics (SIGGRAPH 2015)", "category": "printability_optimization", "doi_or_arxiv_id": "10.1145/2766994", "url": "https://doi.org/10.1145/2766994", "summary": "Introduces Fab Forms, a parametric customization representation that guarantees user-edited 3D models remain watertight, structurally valid, and 3D-printable across interactive parameter sweeps. Precomputed validity regions and cached sub-geometries allow real-time feedback without re-running expensive full printability checks on every edit.", "key_algorithm": "Adaptively samples the parametric design space offline using physics and geometric printability evaluators to construct an approximate valid design manifold, paired with dependency-graph geometry caching for sub-millisecond runtime re-evaluation.", "relevance_to_forma_print": "Aligns directly with Forma's parametric `Forma-Pipe` + transactional `eval`/`print_check` workflow: caching per-part DFM bounds and exposing fast parametric printability feedback so AI agents and users cannot drift into unprintable parameter regimes.", "source_verified": true}+{"id": "wang-2015-saliency-slicing", "title": "Saliency-Preserving Slicing Optimization for Effective 3D Printing", "authors": ["Weiming Wang", "Haiyuan Chao", "Jing Tong", "Zhouwang Yang", "Xin Tong", "Hang Li", "Xiuping Liu", "Ligang Liu"], "year": 2015, "venue": "Computer Graphics Forum", "category": "printability_optimization", "doi_or_arxiv_id": "10.1111/cgf.12527", "url": "https://doi.org/10.1111/cgf.12527", "summary": "Presents an adaptive slicing and segmentation optimization framework that cuts 3D printing time by 30–40% while preserving visually salient surface detail. Thinner layers are assigned to high-curvature/high-saliency regions while low-saliency zones use thicker layers within a bounded visual-error budget.", "key_algorithm": "Computes a per-vertex mesh saliency field and formulates adaptive layer-thickness selection as a constrained l0 optimization minimizing total slice count subject to a saliency-weighted staircase error bound. Uses an alternating two-step solver for layer timing and visual quality, plus optional saliency-guided mesh segmentation into independently sliced subparts.", "relevance_to_forma_print": "Guides surface-error vs. print-time trade-off modeling for `forma-print` profiles (layer height parameters, adaptive layer height recommendations) and future `split.rs` segmentation boundaries that avoid high-saliency seams.", "source_verified": true}+{"id": "livesu-2017-processing-pipeline", "title": "From 3D models to 3D prints: an overview of the processing pipeline", "authors": ["Marco Livesu", "Stefano Ellero", "Jonàs Martínez", "Sylvain Lefebvre", "Marco Attene"], "year": 2017, "venue": "Computer Graphics Forum", "category": "printability_optimization", "doi_or_arxiv_id": "10.1111/cgf.13147", "url": "https://doi.org/10.1111/cgf.13147", "summary": "Comprehensive Eurographics State-of-the-Art Report (STAR) surveying the end-to-end geometry processing pipeline for additive manufacturing. Categorizes mesh repair, printability analysis, structural/mass optimization, hollowing, decomposition, support generation, slicing, and toolpath planning.", "key_algorithm": "Synthesizes formal topological/geometric printability criteria (2-manifoldness, watertightness, positive volume orientation, overhang thresholds, minimum feature thickness) and compares surface, volumetric/tetrahedral, and voxel/implicit process-planning algorithms.", "relevance_to_forma_print": "Serves as the canonical taxonomic blueprint for `forma-print` (`dfm.rs`, `orient.rs`, Tier 2 `split.rs`/`nest.rs`/hollowing), grounding the crate's separation between mesh invariants, DFM audit rules, and slicer export.", "source_verified": true}+{"id": "attene-2018-exact-stl-repair", "title": "As-exact-as-possible repair of unprintable STL files", "authors": ["Marco Attene"], "year": 2018, "venue": "Rapid Prototyping Journal", "category": "printability_optimization", "doi_or_arxiv_id": "10.1108/RPJ-11-2016-0185", "url": "https://doi.org/10.1108/RPJ-11-2016-0185", "summary": "Formalizes the combinatorial topology criteria distinguishing syntactically valid STL files from physically printable solids and introduces a fully automatic repair algorithm that modifies geometry only where strictly necessary. Avoids global voxel remeshing distortion while resolving self-intersections, non-manifold edges, holes, and zero-thickness sheets.", "key_algorithm": "Computes exact triangle-triangle intersections to form a valid 2-complex, classifies patches as bounding true solid volumes versus zero-thickness open sheets via outer-hull/winding analysis, repairs solid boundaries without distortion, and thickens/removes unprintable zero-thickness artifacts to guarantee a watertight manifold solid.", "relevance_to_forma_print": "Directly relevant to `forma-print check` watertightness/manifold validation on imported `.stl`/`.obj`/`.glb` meshes and informs future pure-Rust mesh repair before `.3mf` export without losing sharp CAD features.", "source_verified": true}+{"id": "dumas-2014-bridging-the-gap", "title": "Bridging the gap: Automated steady scaffoldings for 3D printing", "authors": ["Jérémie Dumas", "Jean Hergel", "Sylvain Lefebvre"], "year": 2014, "venue": "ACM Transactions on Graphics (SIGGRAPH 2014)", "category": "overhang_support_minimization", "doi_or_arxiv_id": "10.1145/2601097.2601153", "url": "https://doi.org/10.1145/2601097.2601153", "summary": "Presents an automated scaffolding synthesis algorithm that exploits horizontal bridging capabilities of FDM printers to minimize support material while guaranteeing mechanical stability during printing. Horizontal bridge bars connect vertical pillars to hold overhanging regions reliably with minimal surface contact.", "key_algorithm": "Identifies unprintable overhangs and local minima via slicing/geometry analysis, solves for sparse vertical pillar positions and horizontal bridge spans within maximum bridgeable length bounds, and checks intermediate print states against gravity and lateral extruder forces for mechanical steadiness.", "relevance_to_forma_print": "Directly underpins `forma-print`'s distinction in `dfm.rs` between printable horizontal bridges (<= 10–25 mm depending on material profile) and unsupported ceilings/floating islands.", "source_verified": true}+{"id": "vanek-2014-clever-support", "title": "Clever Support: Efficient Support Structure Generation for Digital Fabrication", "authors": ["Juraj Vanek", "Jorge A. Garcia Galicia", "Bedrich Benes"], "year": 2014, "venue": "Computer Graphics Forum", "category": "overhang_support_minimization", "doi_or_arxiv_id": "10.1111/cgf.12437", "url": "https://doi.org/10.1111/cgf.12437", "summary": "Introduces an automatic geometry-based method to generate sparse, tree-like support structures for FDM 3D printing instead of bulky vertical support columns. By merging nearby support struts into angled trunks under self-supporting angle limits, it significantly reduces support material and print time.", "key_algorithm": "Detects overhanging faces and local Z-minima requiring support, samples support contact points, and greedily constructs a downward-merging tree hierarchy whose strut inclinations respect the printer's maximum self-supporting overhang angle, avoiding collisions with the model mesh.", "relevance_to_forma_print": "Directly maps to `dfm.rs` overhang + floating-island detection and `orient.rs` support-volume estimation heuristic, as well as informing organic/tree support guidelines in the RAG knowledge base.", "source_verified": true}+{"id": "hu-2015-support-slimming", "title": "Support slimming for single material based additive manufacturing", "authors": ["Kailun Hu", "Shuo Jin", "Charlie C. L. Wang"], "year": 2015, "venue": "Computer-Aided Design", "category": "overhang_support_minimization", "doi_or_arxiv_id": "10.1016/j.cad.2015.03.001", "url": "https://doi.org/10.1016/j.cad.2015.03.001", "summary": "Introduces an orientation-driven shape optimizer that gently deforms a 3D mesh to eliminate or slim downward-facing overhangs in single-material additive manufacturing. Produces visually faithful self-supporting approximations that drastically reduce required sacrificial supports.", "key_algorithm": "Embeds the input surface mesh inside a volumetric tetrahedral mesh and alternates local rotational reorientation of overhang boundary tetrahedra (via closed-form solutions on the Gauss sphere) with global ARAP-like rigidity energy minimization to preserve shape fidelity.", "relevance_to_forma_print": "Complements `orient.rs` (rigid build orientation search) by defining how non-rigid local overhang deformation can rescue models where no rigid rotation eliminates all critical overhangs.", "source_verified": true}+{"id": "gaynor-2016-overhang-topology", "title": "Topology optimization considering overhang constraints: Eliminating sacrificial support material in additive manufacturing through design", "authors": ["Andrew T. Gaynor", "James K. Guest"], "year": 2016, "venue": "Structural and Multidisciplinary Optimization", "category": "overhang_support_minimization", "doi_or_arxiv_id": "10.1007/s00158-016-1551-x", "url": "https://doi.org/10.1007/s00158-016-1551-x", "summary": "Integrates self-supporting overhang-angle constraints directly into density-based structural topology optimization so optimized parts need zero sacrificial support material. Demonstrates smooth, differentiable projection filters compatible with gradient-based compliance minimization.", "key_algorithm": "Cascades a local length-scale Heaviside projection filter with a directional support-region projection operator: an element can only take solid density if sufficient solid material exists inside a downward-pointing cone defined by the minimum self-supporting angle.", "relevance_to_forma_print": "Establishes the cone-of-support physical criterion directly analogous to `dfm.rs` overhang face-normal checks (`n.z < -cos(theta_max)`) and informs Tier 2/3 generative bracket/structural design guidance.", "source_verified": true}+{"id": "wu-2016-rhombic-infill", "title": "Self-supporting rhombic infill structures for additive manufacturing", "authors": ["Jun Wu", "Charlie C. L. Wang", "Xiaoting Zhang", "Rüdiger Westermann"], "year": 2016, "venue": "Computer-Aided Design", "category": "overhang_support_minimization", "doi_or_arxiv_id": "10.1016/j.cad.2016.07.006", "url": "https://doi.org/10.1016/j.cad.2016.07.006", "summary": "Generates adaptive interior rhombic lattice infills that strictly obey printer overhang-angle and minimum-wall-thickness constraints, removing the need for internal support structures. Hierarchical cell subdivision concentrates stiffness where mechanical loads or balance require it.", "key_algorithm": "Constructs an initial coarse grid of rhombic cells tilted within the allowable self-supporting angle inside the boundary shell, then iteratively subdivides cells via numerical optimization driven by compliance and static center-of-mass stability objectives.", "relevance_to_forma_print": "Relevant to self-supporting internal reinforcement design and slicer infill guidance (`modifier_part` zones in `export_3mf.rs`) where standard rectilinear infills waste material or fail on steep roofs.", "source_verified": true}+{"id": "langelaar-2017-am-filter", "title": "An additive manufacturing filter for topology optimization of print-ready designs", "authors": ["Matthijs Langelaar"], "year": 2017, "venue": "Structural and Multidisciplinary Optimization", "category": "overhang_support_minimization", "doi_or_arxiv_id": "10.1007/s00158-016-1522-2", "url": "https://doi.org/10.1007/s00158-016-1522-2", "summary": "Proposes a fast, differentiable layerwise Additive Manufacturing (AM) filter that transforms arbitrary density fields into strictly self-supporting, print-ready 3D designs. By propagating supportability layer-by-layer from the build plate upward, it eliminates unprintable downward-facing islands and shallow overhangs.", "key_algorithm": "Defines a bottom-up directional sweep over voxel/element layers where an element's printable density is smoothly capped by a smooth-maximum (P-norm/Kreisselmeier-Steinhauser) over its supporting neighborhood in the layer immediately below, with exact adjoint sensitivities.", "relevance_to_forma_print": "Conceptually mirrors `forma-print`'s layer-by-layer slice-overlap floating-island check (`spatial::section_z` loop overlap) and provides an exact differentiable model of layerwise self-supportability for Tier 2/3 design synthesis.", "source_verified": true}+{"id": "zhu-2019-tree-internal-support", "title": "Design of lightweight tree-shaped internal support structures for 3D printed shell models", "authors": ["Lin Zhu", "Ruiliang Feng", "Xianda Li", "Juntong Xi", "Xiangzhi Wei"], "year": 2019, "venue": "Rapid Prototyping Journal", "category": "overhang_support_minimization", "doi_or_arxiv_id": "10.1108/RPJ-04-2019-0108", "url": "https://doi.org/10.1108/RPJ-04-2019-0108", "summary": "Develops a lightweight branching tree support generator specifically for hollow 3D-printed shell models, reducing internal support volume and build time relative to lattice infills. Branch geometry is constrained by empirically calibrated buckling and yield-length limits across print parameters.", "key_algorithm": "Combines an improved Particle Swarm Optimization (PSO) over trunk and primary node topology with a greedy downward branching heuristic that connects overhanging inner-shell sample points to parent branches while enforcing overhang-angle and critical branch-length constraints.", "relevance_to_forma_print": "Informs internal support evaluation and sacrificial rib/tree recommendations when `dfm.rs` detects internal ceiling overhangs inside shelled enclosures or hollowed models.", "source_verified": true}+{"id": "telea-2011-voxel-printability", "title": "Voxel-based assessment of printability of 3D shapes", "authors": ["Alexandru Telea", "Andrei C. Jalba"], "year": 2011, "venue": "International Symposium on Mathematical Morphology (ISMM 2011), Lecture Notes in Computer Science", "category": "structural_wall_thickness", "doi_or_arxiv_id": "10.1007/978-3-642-21569-8_34", "url": "https://doi.org/10.1007/978-3-642-21569-8_34", "summary": "Proposes an automated, topology-agnostic voxel pipeline to detect unprintable thin walls, narrow necks, and fragile spikes below a printer's resolution limit. Avoids mesh-repair fragility on high-genus or noisy models by operating on a binary voxelization.", "key_algorithm": "Voxelizes the mesh and applies multi-scale mathematical morphology (morphological opening and top-hat transforms with spherical structuring elements) combined with curve/surface skeletonization and distance transforms to localize features thinner than threshold tau.", "relevance_to_forma_print": "Provides a foundational baseline comparison for `forma-print`'s `bvh.rs` cone-ray wall-thickness detector: whereas Telea & Jalba use voxel morphological opening, `forma-print` uses exact BVH inward raycasts (`-n_f` + ±12° cone) to achieve zero-voxelization memory overhead in `~8–25 ms`.", "source_verified": true}+{"id": "stava-2012-stress-relief", "title": "Stress Relief: Improving Structural Strength of 3D Printable Objects", "authors": ["Ondrej Stava", "Juraj Vanek", "Bedrich Benes", "Nathan Carr", "Radomír Měch"], "year": 2012, "venue": "ACM Transactions on Graphics (SIGGRAPH 2012)", "category": "structural_wall_thickness", "doi_or_arxiv_id": "10.1145/2185520.2185544", "url": "https://doi.org/10.1145/2185520.2185544", "summary": "Introduces an automated structural analysis and geometric correction loop that reinforces weak regions of 3D-printable meshes before fabrication. Combines selective hollowing, local thickening, and internal strut insertion to relieve high-stress concentrations under gravity and handling loads.", "key_algorithm": "Solves linear elasticity FEM under gravity and grip/pinching loads to locate regions exceeding material yield stress, then iteratively applies three corrections: medial-axis-guided hollowing to shed dead weight, local surface thickening of overloaded walls, and internal truss strut insertion across cavities.", "relevance_to_forma_print": "Informs `forma-print` minimum functional wall-thickness thresholds (1.6 mm FDM, 1.0 mm MSLA unsupported) and guides future Tier 2 automated thickening / modifier-part high-infill reinforcement around stressed regions.", "source_verified": true}+{"id": "wang-2013-skin-frame", "title": "Cost-effective Printing of 3D Objects with Skin-Frame Structures", "authors": ["Weiming Wang", "Tuanfeng Y. Wang", "Zhouwang Yang", "Ligang Liu", "Xin Tong", "Weihua Tong", "Jiansong Deng", "Falai Chen", "Xiuping Liu"], "year": 2013, "venue": "ACM Transactions on Graphics (SIGGRAPH Asia 2013)", "category": "structural_wall_thickness", "doi_or_arxiv_id": "10.1145/2508363.2508382", "url": "https://doi.org/10.1145/2508363.2508382", "summary": "Replaces solid interiors with an optimized lightweight strut-frame lattice supporting a thin outer skin shell, minimizing total printed volume while preserving mechanical stiffness, static stability, and printability. Achieves substantial material savings over uniform shells and dense infills.", "key_algorithm": "Generates an interior truss frame by sparsifying a multi-scale tetrahedral/octahedral strut network via iterative l0/sparsity-inducing structural optimization subject to displacement, stress, strut-thickness, and overhang-angle constraints coupled to the outer skin.", "relevance_to_forma_print": "Provides quantitative basis for thin outer-shell thickness paired with internal structural framing, relevant to `forma-print` mass estimation and lightweighting recommendations for large FDM/SLS parts.", "source_verified": true}+{"id": "zhou-2013-worst-case", "title": "Worst-case structural analysis", "authors": ["Qingnan Zhou", "Julian Panetta", "Denis Zorin"], "year": 2013, "venue": "ACM Transactions on Graphics (SIGGRAPH 2013)", "category": "structural_wall_thickness", "doi_or_arxiv_id": "10.1145/2461912.2461967", "url": "https://doi.org/10.1145/2461912.2461967", "summary": "Eliminates the need for users to manually specify external loads by computing the worst-case force distribution that maximizes local stress across a 3D-printable model. Outputs a per-region structural weakness map highlighting fragile thin walls, necks, and overhangs prone to breaking under unknown handling.", "key_algorithm": "Volumetricizes the mesh into a tetrahedral domain, extracts low-frequency elastic vibration modes via modal eigenanalysis to isolate high-strain-energy candidate weak zones, and solves localized constrained stress-maximization subproblems over bounded surface pressure loads to produce a global weakness scalar field.", "relevance_to_forma_print": "Motivates load-agnostic DFM screening and per-face severity coloring (`heatmap.rs` 5-slot DFM palette), and serves as the structural counterpart to geometric thin-wall detection in `dfm.rs`.", "source_verified": true}+{"id": "lu-2014-build-to-last", "title": "Build-to-last: Strength to weight 3D printed objects", "authors": ["Lin Lu", "Andrei Sharf", "Haisen Zhao", "Yuan Wei", "Qingnan Fan", "Xuelin Chen", "Yann Savoye", "Changhe Tu", "Daniel Cohen-Or", "Baoquan Chen"], "year": 2014, "venue": "ACM Transactions on Graphics (SIGGRAPH 2014)", "category": "structural_wall_thickness", "doi_or_arxiv_id": "10.1145/2601097.2601168", "url": "https://doi.org/10.1145/2601097.2601168", "summary": "Optimizes internal hollowing using a stress-adaptive irregular Voronoi honeycomb to maximize strength-to-weight ratio for 3D-printed objects. Denser cellular walls reinforce high-stress regions while wider cavities reduce mass in low-stress zones.", "key_algorithm": "Performs interior stress analysis and couples Voronoi seed placement (controlling local cell size) with maximal hollowing of cell interiors/wall thickness via iterative optimization, producing graded porous honeycomb structures.", "relevance_to_forma_print": "Informs stress-graded variable infill and local wall-reinforcement strategies (e.g., `modifier_part` 100% infill zones in `.3mf` around bolt bosses and high-stress necks).", "source_verified": true}+{"id": "nelaturi-2015-manufacturability-feedback", "title": "Manufacturability Feedback and Model Correction for Additive Manufacturing", "authors": ["Saigopal Nelaturi", "Walter Kim", "Tolga Kurtoglu"], "year": 2015, "venue": "ASME Journal of Manufacturing Science and Engineering", "category": "structural_wall_thickness", "doi_or_arxiv_id": "10.1115/1.4029374", "url": "https://doi.org/10.1115/1.4029374", "summary": "Formalizes a printability map over sliced layers using mathematical morphology and the Medial Axis Transform (MAT) to detect sub-resolution thin walls, sharp tips, and narrow gaps, then automatically thickens unprintable regions while preserving part topology.", "key_algorithm": "Computes 2D/3D Medial Axis Transforms and local feature-size radius fields on sliced geometry, applies morphological opening/closing scaled by process resolution limits to build a printability map, and corrects thin features using homotopy-preserving MAT radius inflation.", "relevance_to_forma_print": "Directly parallels `forma-print`'s per-printer minimum wall-thickness and XY-clearance thresholds (`profiles.rs` + `dfm.rs`) and provides a rigorous MAT-based correction blueprint for thin-wall auto-repair.", "source_verified": true}+{"id": "martinez-2016-voronoi-foams", "title": "Procedural Voronoi Foams for Additive Manufacturing", "authors": ["Jonàs Martínez", "Jérémie Dumas", "Sylvain Lefebvre"], "year": 2016, "venue": "ACM Transactions on Graphics (SIGGRAPH 2016)", "category": "structural_wall_thickness", "doi_or_arxiv_id": "10.1145/2897824.2925922", "url": "https://doi.org/10.1145/2897824.2925922", "summary": "Introduces an implicit procedural framework for open-cell Voronoi foam microstructures with spatially varying elasticity and density, evaluated on the fly during slicing. Eliminates massive explicit lattice meshes while seamlessly blending graded internal foams into solid outer shells.", "key_algorithm": "Evaluates aperiodic 3D Voronoi cell edges implicitly per slice point from hashed jittered grid seeds with spatially varying density and beam radius functions, framing solid-to-foam boundary transitions smoothly via distance-field blending.", "relevance_to_forma_print": "Explains why `forma-print` delegates fine lattice/gyroid/Voronoi infill generation to slicers (`OrcaSlicer`/`PrusaSlicer`) via `.3mf` metadata and modifier meshes rather than blowing up triangle counts in `PolyMesh`.", "source_verified": true}+{"id": "liu-2015-virtual-temperature", "title": "An identification method for enclosed voids restriction in manufacturability design for additive manufacturing structures", "authors": ["Shutian Liu", "Quhao Li", "Wenjiong Chen", "Liyong Tong", "Gengdong Cheng"], "year": 2015, "venue": "Frontiers of Mechanical Engineering", "category": "hollowing_drainage_suction", "doi_or_arxiv_id": "10.1007/s11465-015-0340-3", "url": "https://doi.org/10.1007/s11465-015-0340-3", "summary": "Introduces the Virtual Temperature Method (VTM) to automatically detect trapped, enclosed voids in additive manufacturing structures so unmelted powder or liquid resin does not remain sealed inside hollow parts. Translates topological cavity detection into a continuous heat-conduction boundary value problem.", "key_algorithm": "Assigns high thermal conductivity and uniform internal heat generation to void regions, assigns near-insulating conductivity to solid material, and fixes exterior boundary temperature at zero; enclosed voids trap heat and produce sharp temperature spikes exceeding a threshold T_max.", "relevance_to_forma_print": "Complements `forma-print`'s topological/slice-based trapped-cavity detection (`contribute/forma-print.md` Tier 2 SLA/SLS trapped-cavity check) with an alternative continuous PDE formulation for voxelized or implicit geometries.", "source_verified": true}+{"id": "li-2016-connectivity-constraint", "title": "Structural topology optimization considering connectivity constraint", "authors": ["Quhao Li", "Wenjiong Chen", "Shutian Liu", "Liyong Tong"], "year": 2016, "venue": "Structural and Multidisciplinary Optimization", "category": "hollowing_drainage_suction", "doi_or_arxiv_id": "10.1007/s00158-016-1459-5", "url": "https://doi.org/10.1007/s00158-016-1459-5", "summary": "Integrates the Virtual Temperature Method directly as an explicit differentiable connectivity constraint in SIMP topology optimization to guarantee void regions connect to the exterior boundary. Prevents enclosed cavities that trap un-sintered powder in SLS/SLM or uncured resin in SLA.", "key_algorithm": "Solves a steady-state virtual heat-conduction FEM system alongside structural elasticity at each iteration and constrains the P-norm/maximum virtual temperature T_max <= T_is using exact adjoint sensitivities within an MMA optimizer, forcing drainage tunnels to open whenever cavities form.", "relevance_to_forma_print": "Reinforces why SLS (`formlabs_fuse_1p`) and MSLA (`elegoo_mars_5_ultra`, `formlabs_form_4`) profiles require strict connectivity/escape-hole checks whenever internal hollow cavities exist.", "source_verified": true}+{"id": "pan-2017-sla-separation-force", "title": "Study of separation force in constrained surface projection stereolithography", "authors": ["Yayue Pan", "Haiyang He", "Jie Xu", "Alan Feinerman"], "year": 2017, "venue": "Rapid Prototyping Journal", "category": "hollowing_drainage_suction", "doi_or_arxiv_id": "10.1108/RPJ-12-2015-0188", "url": "https://doi.org/10.1108/RPJ-12-2015-0188", "summary": "Models and experimentally measures the suction-induced separation force generated when peeling newly cured layers off the vat window in bottom-up projection stereolithography. Shows how closed cross-sections, large solid areas, and restricted resin inflow amplify vacuum suction forces that tear layers or films.", "key_algorithm": "Formulates viscous resin inflow during vertical Z-stage separation using Navier-Stokes / lubrication-theory Stefan adhesion models parameterized by separation velocity, oxygen-inhibition gap, cross-sectional area, perimeter, and porous/vented drainage channels.", "relevance_to_forma_print": "Provides the physical fluid-mechanics justification for `forma-print`'s MSLA suction-cup detector (`contribute/forma-print.md` §1.2 & Tier 2): CW closed inner loops facing the vat create Stefan vacuum suction unless vented by >=2 drainage holes (Ø >= 3.5 mm).", "source_verified": true}+{"id": "wang-2017-support-free-hollowing", "title": "Support-Free Hollowing", "authors": ["Weiming Wang", "Yong-Jin Liu", "Jun Wu", "Shengjing Tian", "Charlie C. L. Wang", "Ligang Liu", "Xiuping Liu"], "year": 2017, "venue": "IEEE Transactions on Visualization and Computer Graphics (Early Access 2017; Vol. 24, No. 10, 2018)", "category": "hollowing_drainage_suction", "doi_or_arxiv_id": "10.1109/TVCG.2017.2764462", "url": "https://doi.org/10.1109/TVCG.2017.2764462", "summary": "Presents a geometric hollowing optimization framework that carves internal voids whose roof and wall facets are strictly self-supporting along the build direction, avoiding unremovable internal supports. Can be applied iteratively to create nested, lightweight multi-cavity interiors.", "key_algorithm": "Maps 3D interior surface hollowing onto a sequence of planar 2D non-uniform contour offsetting steps across slicing layers, imposing overhang-angle slope constraints between consecutive slice loops and resolving contour topology splits/merges during shape optimization.", "relevance_to_forma_print": "Directly informs Tier 2 auto-hollowing in `forma-print`: naive uniform inward shell offsetting creates internal ceiling overhangs and trapped cavities, whereas slice-constrained offsetting preserves self-supportability.", "source_verified": true}+{"id": "lee-2018-voronoi-hollowing", "title": "Support-Free Hollowing for 3D Printing via Voronoi Diagram of Ellipses", "authors": ["Mokwon Lee", "Qing Fang", "Youngsong Cho", "Joonghyun Ryu", "Ligang Liu", "Deok-Soo Kim"], "year": 2018, "venue": "Computer-Aided Design", "category": "hollowing_drainage_suction", "doi_or_arxiv_id": "10.1016/j.cad.2018.03.007", "url": "https://doi.org/10.1016/j.cad.2018.03.007", "summary": "Carves support-free internal voids by packing and protruding non-overlapping ellipses across parallel slicing planes using exact computational geometry. Maximizes hollowed volume while preserving minimum wall thickness and self-supporting roof angles.", "key_algorithm": "Slices the input mesh into parallel planes, constructs the exact Voronoi diagram of ellipses within each 2D cross-section polygon to locate maximal free space, and optimizes ellipse radii, eccentricities, and centers across adjacent layers subject to inter-layer overhang-angle and wall-clearance bounds.", "relevance_to_forma_print": "Offers a clean 2D slice-loop geometric formulation compatible with `forma_core::spatial::section_z` for computing support-free hollow cavities and tracking void connectivity across Z-layers.", "source_verified": true}+{"id": "xiong-2020-eliminating-voids", "title": "A new approach to eliminating enclosed voids in topology optimization for additive manufacturing", "authors": ["Yulin Xiong", "Song Yao", "Zi-Long Zhao", "Yi Min Xie"], "year": 2020, "venue": "Additive Manufacturing", "category": "hollowing_drainage_suction", "doi_or_arxiv_id": "10.1016/j.addma.2019.101006", "url": "https://doi.org/10.1016/j.addma.2019.101006", "summary": "Eliminates trapped internal voids in powder-bed additive manufacturing by automatically carving drainage tunnels that connect enclosed cavities to the exterior surface during structural optimization. Avoids expensive PDE solves by using direct geometric graph connectivity.", "key_algorithm": "Integrates a connectivity-control step into Bi-directional Evolutionary Structural Optimization (BESO): detects disconnected void components via flood-fill/connected-component labeling and excavates minimum-strain-energy shortest-path drainage channels linking trapped voids to the outer boundary.", "relevance_to_forma_print": "Provides a direct geometric blueprint for `forma-print` Tier 2 trapped-cavity resolution: connected-component cavity detection followed by shortest-path / lowest-Z drain and top-vent hole placement.", "source_verified": true}+{"id": "liu-2022-powder-removal-passageway", "title": "Topology optimization incorporating a passageway for powder removal in designs for additive manufacturing", "authors": ["Dedao Liu", "Louis N. S. Chiu", "Chris Davies", "Wenyi Yan"], "year": 2022, "venue": "Structural and Multidisciplinary Optimization", "category": "hollowing_drainage_suction", "doi_or_arxiv_id": "10.1007/s00158-022-03280-3", "url": "https://doi.org/10.1007/s00158-022-03280-3", "summary": "Couples structural optimization with graph-based path planning to create a single continuous entrance-voids-exit passageway for powder evacuation in SLS/SLM parts. Enforcing a two-port flow-through path ensures effective post-print powder clearing and rinsing while minimizing stiffness loss.", "key_algorithm": "Identifies isolated void clusters during topology optimization, builds a spatial connectivity graph between a designated entrance, all internal voids, and an exit, and uses Depth-First Search (DFS) plus shortest-path optimization weighted by element compliance sensitivity to carve a stiffness-preserving flow-through channel.", "relevance_to_forma_print": "Directly validates `forma-print`'s two-hole drainage rule (`>= 2` holes `Ø >= 5.0 mm` for SLS `formlabs_fuse_1p` and `Ø >= 3.5 mm` for MSLA) and provides a graph-routing method for placing low-stress inlet/outlet drain holes across multiple internal cavities.", "source_verified": true}+{"id": "luo-2012-chopper", "title": "Chopper: Partitioning Models into 3D-Printable Parts", "authors": ["Linjie Luo", "Ilya Baran", "Szymon Rusinkiewicz", "Wojciech Matusik"], "year": 2012, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2012)", "category": "decomposition_packing_interlocking", "doi_or_arxiv_id": "10.1145/2366145.2366148", "url": "https://doi.org/10.1145/2366145.2366148", "summary": "Chopper addresses the problem of fabricating 3D models larger than a printer's build volume by partitioning watertight meshes into printable sub-parts. It optimizes planar cuts so that every part fits inside the target build box while minimizing total part count, seam obtrusiveness, and structural weakness, and automatically embeds alignment connectors along cut faces.", "key_algorithm": "Recursive Binary Space Partitioning (BSP) tree with bounded beam search over candidate cutting planes on the largest sub-volumes. Minimizes a composite objective over part count, seam length/visibility, build-volume utilization, symmetry preservation, and connector feasibility, then generates prismatic male/female alignment connectors across planar interfaces.", "relevance_to_forma_print": "Directly informs Tier 2 auto-split (split.rs) when dfm.rs build-volume fit fails: motivates BSP planar bisection minimizing cross-section area/seam visibility and automatic connector/pin generation alongside Forma's boolean subtract/union ops.", "source_verified": true}+{"id": "hu-2014-pyramidal", "title": "Approximate Pyramidal Shape Decomposition", "authors": ["Ruizhen Hu", "Honghua Li", "Hao Zhang", "Daniel Cohen-Or"], "year": 2014, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2014)", "category": "decomposition_packing_interlocking", "doi_or_arxiv_id": "10.1145/2661229.2661244", "url": "https://doi.org/10.1145/2661229.2661244", "summary": "Introduces approximate pyramidal shape decomposition for support-free 3D printing and molding, where each decomposed sub-part is a pyramidal region admitting a single-valued height field over a flat base without undercuts. Because exact minimal pyramidal decomposition is NP-hard, the method uses surface clustering and exact cover selection to partition complex meshes into few near-pyramidal components.", "key_algorithm": "Generates candidate pyramidal base directions and surface patches via normal/height-field clustering and voting, then formulates partition selection as an Exact Cover Problem (ECP) solved using Knuth's Algorithm X to minimize the number of support-free pyramidal blocks within an approximation bound.", "relevance_to_forma_print": "Provides an algorithmic basis for Tier 2 multi-part support-free splitting in split.rs and multi-orientation sub-part scoring in orient.rs, enabling large overhanging Forma assemblies to be bisected into flat-based, zero-support blocks.", "source_verified": true}+{"id": "vanek-2014-packmerger", "title": "PackMerger: A 3D Print Volume Optimizer", "authors": ["Juraj Vanek", "Jorge A. Garcia Galicia", "Bedrich Benes", "Radomír Měch", "Nathan A. Carr", "Ondrej Stava", "Gavin S. P. Miller"], "year": 2014, "venue": "Computer Graphics Forum", "category": "decomposition_packing_interlocking", "doi_or_arxiv_id": "10.1111/cgf.12353", "url": "https://doi.org/10.1111/cgf.12353", "summary": "PackMerger reduces FDM print time, support material waste, and bounding volume by converting a solid model into a hollow shell, segmenting the shell into assemble-able sub-parts, and tightly nesting those pieces inside a minimal print volume. Experiments demonstrated 15–65% support material savings and 5–30% print time reduction, as well as fabrication of oversized models in a single job.", "key_algorithm": "Shell hollowing followed by mesh segmentation optimizing segment size, glue-interface area, and part count, coupled with a Simulated Annealing (SA) 3D packing optimizer over piece translations and rotations to minimize bounding volume, maximize nested cavity reuse, and minimize support volume.", "relevance_to_forma_print": "Motivates combining Tier 2 hollowing, shell splitting (split.rs), and multi-part build-plate nesting (nest.rs + plate_1.json/plate_2.json in export_3mf.rs) while accounting for cut-interface gluing area and total Z-height/print time.", "source_verified": true}+{"id": "chen-2015-dapper", "title": "Dapper: Decompose-and-Pack for 3D Printing", "authors": ["Xuelin Chen", "Hao Zhang", "Jinjie Lin", "Ruizhen Hu", "Lin Lu", "Qixing Huang", "Bedrich Benes", "Daniel Cohen-Or", "Baoquan Chen"], "year": 2015, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2015)", "category": "decomposition_packing_interlocking", "doi_or_arxiv_id": "10.1145/2816795.2818087", "url": "https://doi.org/10.1145/2816795.2818087", "summary": "Dapper couples model decomposition and build-volume packing into a unified Decompose-and-Pack (DAP) optimization for both SLS powder-bed and FDM printers. Rather than packing arbitrary chunks after splitting, Dapper decomposes models into pyramidal primitives specifically shaped to nest tightly together while minimizing support material, print time, and cut seams.", "key_algorithm": "Top-down iterative decomposition using pyramidal primitives inside a prioritized, bounded beam search. Evaluates both local part docking stability/fit and global DAP objectives (packing density, support volume, build height, and part count) with breadth and depth pruning.", "relevance_to_forma_print": "Informs joint split-and-pack workflows for SLS (formlabs_fuse_1p) and FDM profiles in forma-print: rather than running orient.rs, split.rs, and nest.rs in strict isolation, cut planes can be scored by post-cut footprint/nesting efficiency.", "source_verified": true}+{"id": "song-2015-interlocking", "title": "Printing 3D Objects with Interlocking Parts", "authors": ["Peng Song", "Zhongqi Fu", "Ligang Liu", "Chi-Wing Fu"], "year": 2015, "venue": "Computer Aided Geometric Design (Proc. GMP 2015)", "category": "decomposition_packing_interlocking", "doi_or_arxiv_id": "10.1016/j.cagd.2015.03.020", "url": "https://doi.org/10.1016/j.cagd.2015.03.020", "summary": "Presents an automated method to partition a 3D model into a collection of self-locking parts that can be printed separately and assembled without glue or external fasteners. The resulting assemblies remain mechanically immobilized except along a controlled disassembly sequence triggered by a single key piece.", "key_algorithm": "Voxelizes the input watertight mesh via ray-casting, constructs a directional blocking graph over voxel clusters along principal axes (+/-X, +/-Y, +/-Z), and recursively extracts interlocking puzzle parts anchored by a key piece with exactly one valid translation direction; finally intersects voxel blocks with the smooth input surface via CSG.", "relevance_to_forma_print": "Provides design rules for Tier 2 snap-fit/interlocking joints (split.rs and ops_print.rs): models directional blocking constraints and assembly sequence validation alongside forma_core::spatial::clearance tolerance offsets.", "source_verified": true}+{"id": "yao-2015-levelset-packing", "title": "Level-Set-Based Partitioning and Packing Optimization of a Printable Model", "authors": ["Miaojun Yao", "Zhili Chen", "Linjie Luo", "Rui Wang", "Huamin Wang"], "year": 2015, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2015)", "category": "decomposition_packing_interlocking", "doi_or_arxiv_id": "10.1145/2816795.2818064", "url": "https://doi.org/10.1145/2816795.2818064", "summary": "Proposes a continuous multi-phase level-set optimization framework that simultaneously partitions a 3D model into printable pieces and optimizes their packed arrangement. The formulation jointly accounts for packed bounding volume, per-part printability, print time, structural load resistance, seam aesthetics, and reassembly.", "key_algorithm": "Represents part partitions implicitly via a multi-phase level-set field evolved under PDE/variational updates over a 6-term objective combining packed bounding volume, printer build-volume fit, estimated production time, structural stress load, cut-interface area/detail preservation, and reassembly feasibility.", "relevance_to_forma_print": "Demonstrates how continuous cut-boundary optimization can co-minimize cut-interface area and print time; guides future Tier 2/3 enhancements to split.rs beyond axis-aligned planar cuts when structural stress or seam area matters.", "source_verified": true}+{"id": "cui-2023-spectral-packing", "title": "Dense, Interlocking-Free and Scalable Spectral Packing of Generic 3D Objects", "authors": ["Qiaodong Cui", "Victor Rong", "Desai Chen", "Wojciech Matusik"], "year": 2023, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH 2023)", "category": "decomposition_packing_interlocking", "doi_or_arxiv_id": "10.1145/3592126", "url": "https://doi.org/10.1145/3592126", "summary": "Introduces a scalable 3D packing algorithm for large batches of arbitrary non-convex meshes targeting additive manufacturing build volumes. By operating in the spectral domain over voxelized geometries, it achieves high packing density while guaranteeing that packed parts are interlocking-free and removable.", "key_algorithm": "Discretizes objects and container into voxel grids and Signed Distance Fields (SDFs), expressing 3D collision detection and placement cost functions across all translations simultaneously as cross-correlations evaluated via Fast Fourier Transform (FFT), paired with directional accessibility checks to forbid mechanical interlocking.", "relevance_to_forma_print": "Establishes the gold-standard 3D volumetric nesting algorithm for SLS/MJF build chambers (formlabs_fuse_1p) as an upgrade path beyond Tier 2 2D rotating-calipers/MaxRects plate nesting (nest.rs) when multi-part Z-stacking is needed.", "source_verified": true}+{"id": "baecher-2012-articulated", "title": "Fabricating Articulated Characters from Skinned Meshes", "authors": ["Moritz Bächer", "Bernd Bickel", "Doug L. James", "Hanspeter Pfister"], "year": 2012, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH 2012)", "category": "clearance_tolerance_orientation", "doi_or_arxiv_id": "10.1145/2185520.2185543", "url": "https://doi.org/10.1145/2185520.2185543", "summary": "Converts virtually rigged and skinned character meshes into 3D-printable articulated physical models with embedded non-assembly joints. The method optimizes joint placement and geometry so limbs articulate smoothly after printing while retaining sufficient friction to hold arbitrary poses against gravity.", "key_algorithm": "Extracts an approximate medial-axis joint placement maximizing cross-sectional strength, embeds parameterized ball-and-socket and hinge primitives with explicit clearance gaps to avoid sintering/extrusion fusion, and tunes socket geometry and clamping friction so joint friction torque exceeds gravitational limb torque.", "relevance_to_forma_print": "Directly validates forma-print's technology-specific sliding/PIP clearance checks in dfm.rs (0.30-0.40 mm FDM, 0.20-0.30 mm SLA, >=0.50 mm SLS) and motivates Tier 2 snap/articulated joint primitives with clearance envelopes.", "source_verified": true}+{"id": "cali-2012-non-assembly", "title": "3D-Printing of Non-Assembly, Articulated Models", "authors": ["Jacques Calì", "Dan A. Calian", "Cristina Amati", "Rebecca Kleinberger", "Anthony Steed", "Jan Kautz", "Tim Weyrich"], "year": 2012, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2012)", "category": "clearance_tolerance_orientation", "doi_or_arxiv_id": "10.1145/2366145.2366149", "url": "https://doi.org/10.1145/2366145.2366149", "summary": "Presents a computational pipeline for fabricating posable, print-in-place articulated models in a single print without post-assembly. Using printer-calibrated joint templates, it prevents mating surfaces from fusing while controlling socket elasticity to provide calibrated Coulomb friction.", "key_algorithm": "Fits parameterized spherical and revolute joint templates onto skeletal rigs using four primary geometric parameters: radial clearance tolerance t (calibrated via 0.1-0.4 mm test suites), outer socket band thickness (controlling normal clamping force and Coulomb friction), joint radius R, and rotational limit pins/colliders, followed by air-gap validation.", "relevance_to_forma_print": "Provides empirical grounding for print-in-place clearance thresholds in profiles.rs and spatial::clearance checks in dfm.rs, plus highlights the need to verify air gaps between nested sub-meshes before .3mf export.", "source_verified": true}+{"id": "ezair-2015-orientation", "title": "Orientation analysis of 3D objects toward minimal support volume in 3D-printing", "authors": ["Ben Ezair", "Fady Massarwi", "Gershon Elber"], "year": 2015, "venue": "Computers & Graphics (Vol. 51, pp. 117-124)", "category": "clearance_tolerance_orientation", "doi_or_arxiv_id": "10.1016/j.cag.2015.05.009", "url": "https://doi.org/10.1016/j.cag.2015.05.009", "summary": "Investigates optimal build orientation for minimizing exact 3D support structure volume. Proves that support volume as a function of orientation angles is C0-continuous with sharp non-smooth transitions, and introduces a fast GPU rasterization method to compute exact support volumes across candidate orientations.", "key_algorithm": "Uses orthographic top-down GPU Z-buffer depth projections per candidate orientation to compute vertical material-column bounds and exact support volume by subtracting part volume, enabling global search over spherical/Euler orientation space without O(N^3) voxelization.", "relevance_to_forma_print": "Explains why orient.rs cannot rely solely on smooth gradient descent over orientations (non-smooth support transitions) and motivates discrete candidate generation (planar normal clusters + convex hull facets + canonical axes) plus exact column-based support volume estimation.", "source_verified": true}+{"id": "zhang-2015-perceptual-direction", "title": "Perceptual Models of Preference in 3D Printing Direction", "authors": ["Xiaoting Zhang", "Xinyi Le", "Athina Panotopoulou", "Emily Whiting", "Charlie C. L. Wang"], "year": 2015, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2015)", "category": "clearance_tolerance_orientation", "doi_or_arxiv_id": "10.1145/2816795.2818121", "url": "https://doi.org/10.1145/2816795.2818121", "summary": "Develops a data-driven perceptual model for selecting 3D printing build orientations that minimize visible scarring from support removal and stair-stepping on aesthetically important regions. Validates via large-scale user studies that geometric support-minimization alone often places ugly scars on salient front-facing features.", "key_algorithm": "Extracts orientation-dependent feature vectors combining support contact area, mesh visual saliency, preferred viewing angles, and stair-stepping smoothness, then trains a closed-form linear preference ranking model from human pairwise comparison studies to score candidate printing directions.", "relevance_to_forma_print": "Guides multi-objective weighting in orient.rs: beyond raw overhang area and Z-height, user-marked or front-facing aesthetic faces (e.g. via Forma face tags) can receive higher overhang/seam penalties to avoid support scarring on visible surfaces.", "source_verified": true}+{"id": "delfs-2016-build-orientation", "title": "Optimized build orientation of additive manufactured parts for improved surface quality and build time", "authors": ["Patrick Delfs", "Marcel Töws", "Hans-Joachim Schmid"], "year": 2016, "venue": "Additive Manufacturing (Vol. 12, Part B, pp. 314-320)", "category": "clearance_tolerance_orientation", "doi_or_arxiv_id": "10.1016/j.addma.2016.06.003", "url": "https://doi.org/10.1016/j.addma.2016.06.003", "summary": "Presents a multi-objective build orientation optimizer balancing surface quality (topography/roughness across triangular facets) against total build time (Z-height). Incorporates empirical surface roughness models alongside theoretical cusp height and supports prioritizing critical functional faces.", "key_algorithm": "Evaluates candidate orientations across discretized rotation increments using a weighted objective over part Z-height (build time proxy) and area/priority-weighted surface roughness mapped from facet normal inclination angles and empirical roughness curves (extending geometric cusp height h_c = t * cos(theta)).", "relevance_to_forma_print": "Directly mirrors orient.rs's multi-objective scoring tuple (overhangs, islands, support_vol, bed_area, z_height, ams_swaps) and provides the mathematical basis for adding cusp-height / layer-height surface roughness terms per printer profile.", "source_verified": true}+{"id": "wang-2021-thermal-compensation", "title": "Quantification and compensation of thermal distortion in additive manufacturing: A computational statistics approach", "authors": ["Chao Wang", "Shaofan Li", "Danielle Zeng", "Xinhai Zhu"], "year": 2021, "venue": "Computer Methods in Applied Mechanics and Engineering (Vol. 375, 113611)", "category": "clearance_tolerance_orientation", "doi_or_arxiv_id": "10.1016/j.cma.2020.113611", "url": "https://doi.org/10.1016/j.cma.2020.113611", "summary": "Combines computational statistics and non-rigid mesh morphing to predict and pre-compensate permanent thermal distortion and shrinkage in additive manufacturing. Rather than needing full transient thermo-mechanical simulation histories, it learns distortion fields from scanned part deviations and warps the input mesh inversely.", "key_algorithm": "Uses probabilistic registration and Gaussian Process / statistical surrogate modeling to map nominal mesh coordinates to permanent thermal displacement fields, then computes an inverse shape-morphing deformation applied pre-print so the thermally shrunk physical part converges to target tolerances.", "relevance_to_forma_print": "Informs material-dependent XY/Z shrinkage compensation factors in profiles.rs (e.g., ABS/ASA vs PLA warp/shrinkage) and outlines a Tier 3 closed-loop metrology/compensation workflow for morphing meshes prior to .3mf export.", "source_verified": true}+{"id": "grgic-2023-tolerance-fields", "title": "Accuracy of FDM PLA Polymer 3D Printing Technology Based on Tolerance Fields", "authors": ["Ivan Grgić", "Mirko Karakašić", "Hrvoje Glavaš", "Pejo Konjatić"], "year": 2023, "venue": "Processes (Vol. 11, No. 10, Article 2810)", "category": "clearance_tolerance_orientation", "doi_or_arxiv_id": "10.3390/pr11102810", "url": "https://doi.org/10.3390/pr11102810", "summary": "Evaluates dimensional accuracy and ISO 286 tolerance-fit capabilities of desktop FDM PLA printing for multi-part mechanical assemblies. Quantifies how slicer compensation settings—specifically Horizontal Expansion, Hole Horizontal Expansion, and Linear Advance—govern hole-shaft clearances and roundness.", "key_algorithm": "Experimental factorial calibration mapping ISO 286 hole-basis tolerance fields against slicer horizontal expansion offsets, empirically demonstrating that setting Hole Horizontal Expansion (+0.13 mm) with Linear Advance calibration brings desktop FDM hole-shaft fits within functional assembly tolerance classes.", "relevance_to_forma_print": "Directly informs internal-hole vs external-perimeter clearance tolerances in profiles.rs, CNC Kitchen heat-set insert pilot hole checks, and Tier 2 elephant_chamfer()/snap_fit() compensation offsets exported to slicer metadata.", "source_verified": true}+{"id": "chakraborty-2008-clfdm", "title": "Extruder path generation for Curved Layer Fused Deposition Modeling", "authors": ["Debapriya Chakraborty", "B. Aneesh Reddy", "A. Roy Choudhury"], "year": 2008, "venue": "Computer-Aided Design (Vol. 40, Issue 2, pp. 235-243)", "category": "multi_axis_curved_slicing", "doi_or_arxiv_id": "10.1016/j.cad.2007.10.014", "url": "https://doi.org/10.1016/j.cad.2007.10.014", "summary": "Foundational paper defining Curved Layer Fused Deposition Modeling (CLFDM) to eliminate stair-stepping and improve filament continuity on thin curved shells. Generates non-planar deposition paths directly on parametric offset surfaces rather than horizontal Z-planes.", "key_algorithm": "Represents the part reference surface parametrically as P(u,v), generates stacked curved layers via normal surface offsetting by layer thickness t (checking for curvature-induced self-intersections), and discretizes isoparametric curves into linear toolpath segments bounded by a maximum chord-deviation tolerance.", "relevance_to_forma_print": "Establishes the geometric limitations of planar slicing assumed in Tier 1 (dfm.rs stair-stepping/overhang metrics) and defines parametric offset and chord-deviation constraints needed if forma-print adds non-planar surface-capping export in future tiers.", "source_verified": true}+{"id": "wu-2017-robofdm", "title": "RoboFDM: A Robotic System for Support-Free Fabrication Using FDM", "authors": ["Chenming Wu", "Chengkai Dai", "Guoxin Fang", "Yong-Jin Liu", "Charlie C. L. Wang"], "year": 2017, "venue": "2017 IEEE International Conference on Robotics and Automation (ICRA)", "category": "multi_axis_curved_slicing", "doi_or_arxiv_id": "10.1109/ICRA.2017.7989140", "url": "https://doi.org/10.1109/ICRA.2017.7989140", "summary": "Introduces a multi-axis robotic FDM system that eliminates support structures by decomposing a 3D mesh into support-free sub-parts printed sequentially along distinct build directions. Combines skeleton-guided segmentation with collision-free print-order planning.", "key_algorithm": "Extracts a 1D curve skeleton via mean-curvature flow and Shape Diameter Function to perform coarse branching decomposition, refines planar clipping cuts using beam search to enforce self-support overhang bounds per part, and plans an inverse base-to-tip collision-free robotic printing sequence.", "relevance_to_forma_print": "Bridges decomposition (split.rs) and orientation (orient.rs): shows how branching Forma parts fail single-direction 3-axis overhang checks in dfm.rs and how skeleton-guided planar clipping finds locally support-free orientations.", "source_verified": true}+{"id": "dai-2018-multiaxis", "title": "Support-Free Volume Printing by Multi-Axis Motion", "authors": ["Chengkai Dai", "Charlie C. L. Wang", "Chenming Wu", "Sylvain Lefebvre", "Guoxin Fang", "Yong-Jin Liu"], "year": 2018, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH 2018)", "category": "multi_axis_curved_slicing", "doi_or_arxiv_id": "10.1145/3197517.3201342", "url": "https://doi.org/10.1145/3197517.3201342", "summary": "Replaces planar slicing with continuous curved volumetric layers fabricated by a multi-axis robotic printer to achieve completely support-free 3D printing of complex geometries. Decomposes volumes into curved surfaces ordered so every deposited voxel is supported and collision-free.", "key_algorithm": "Computes an accumulation scalar field via geodesic propagation/inverse peeling over a voxelized volume, grows layers incrementally via a field-governed convex-front strategy bounded by the dynamic convex hull of printed voxels + build plate to guarantee collision-free nozzle accessibility, and extracts curved iso-surface toolpaths.", "relevance_to_forma_print": "Demonstrates how overhang constraints in dfm.rs are fundamentally tied to 3-axis planar slicing assumptions; informs future multi-axis capability flags in profiles.rs and curved-layer feasibility analysis.", "source_verified": true}+{"id": "ahlers-2019-nonplanar", "title": "3D Printing of Nonplanar Layers for Smooth Surface Generation", "authors": ["Daniel Ahlers", "Florens Wasserfall", "Norman Hendrich", "Jianwei Zhang"], "year": 2019, "venue": "2019 IEEE 15th International Conference on Automation Science and Engineering (CASE)", "category": "multi_axis_curved_slicing", "doi_or_arxiv_id": "10.1109/COASE.2019.8843116", "url": "https://doi.org/10.1109/COASE.2019.8843116", "summary": "Presents a practical hybrid planar/non-planar slicing algorithm integrated into Slic3r for standard 3-axis FDM printers. Prints interior volume with fast flat layers and switches to surface-conforming non-planar layers on top skins while checking full printhead collision geometry.", "key_algorithm": "Identifies shallow-angle top surfaces via heightmap/slope analysis, generates curved offset skin layers merged with planar base slices, and performs geometric collision detection against a parameterized 3D bounding volume of the nozzle, heater block, and fan shroud before emitting non-planar G-code.", "relevance_to_forma_print": "Informs printer profile metadata in profiles.rs (printhead/nozzle clearance angle and shroud geometry) and Tier 3 slicer-cli bridge extensions for non-planar top-skin detection on aerodynamic or contoured Forma models.", "source_verified": true}+{"id": "etienne-2019-curvislicer", "title": "CurviSlicer: Slightly curved slicing for 3-axis printers", "authors": ["Jimmy Etienne", "Nicolas Ray", "Daniele Panozzo", "Samuel Hornus", "Charlie C. L. Wang", "Jonàs Martínez", "Sara McMains", "Marc Alexa", "Brian Wyvill", "Sylvain Lefebvre"], "year": 2019, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH 2019)", "category": "multi_axis_curved_slicing", "doi_or_arxiv_id": "10.1145/3306346.3323022", "url": "https://doi.org/10.1145/3306346.3323022", "summary": "Enables curved-layer printing on ordinary 3-axis FDM printers to eliminate stair-stepping on shallow slopes without hardware modification. Solves a constrained deformation of the model and surrounding space so standard planar slicing yields collision-free curved toolpaths when mapped back.", "key_algorithm": "Embeds the mesh and surrounding air into a tetrahedral mesh, solves a Quadratic Programming (QP) deformation flattening near-horizontal slopes while constraining Jacobian stretching (extrusion thickness limits) and an inverted nozzle collision cone (~45 deg clearance), slices planarly in deformed space, and pulls G-code back via the inverse map.", "relevance_to_forma_print": "Highly actionable for standard 3-axis FDM printers in profiles.rs (Prusa MK4S, Bambu X1C/A1): nozzle clearance-cone checks and shallow-slope stair-stepping detection in dfm.rs can identify parts ideal for CurviSlicer/non-planar post-processing.", "source_verified": true}+{"id": "fang-2020-reinforced-fdm", "title": "Reinforced FDM: Multi-axis filament alignment with controlled anisotropic strength", "authors": ["Guoxin Fang", "Tianyu Zhang", "Sikai Zhong", "Xiangjia Chen", "Zichun Zhong", "Charlie C. L. Wang"], "year": 2020, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2020)", "category": "multi_axis_curved_slicing", "doi_or_arxiv_id": "10.1145/3414685.3417834", "url": "https://doi.org/10.1145/3414685.3417834", "summary": "Optimizes multi-axis curved slicing to overcome FDM's weak inter-layer Z-strength by aligning continuous extruded filaments with principal stress trajectories. Demonstrates substantial load-bearing gains over planar printing on structural brackets and mechanical parts.", "key_algorithm": "Performs Finite Element Analysis (FEA) to obtain 3x3 element stress tensors, extracts principal stress eigenvectors to synthesize an optimized vector field V(x), computes a smooth governing scalar field G(x) via least-squares gradient fitting (grad G approx V) with collision/accessibility constraints, and extracts curved iso-surface layers.", "relevance_to_forma_print": "Connects structural anisotropy awareness to dfm.rs and orient.rs: even in 3-axis Tier 1, orient.rs can warn when high-aspect-ratio cantilevers align layer planes perpendicular to bending loads, and informs Tier 2 modifier_part local reinforcement.", "source_verified": true}+{"id": "zhang-2022-s3-slicer", "title": "S3-Slicer: A General Slicing Framework for Multi-Axis 3D Printing", "authors": ["Tianyu Zhang", "Guoxin Fang", "Yuming Huang", "Neelotpal Dutta", "Sylvain Lefebvre", "Zekai Murat Kilic", "Charlie C. L. Wang"], "year": 2022, "venue": "ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2022)", "category": "multi_axis_curved_slicing", "doi_or_arxiv_id": "10.1145/3550454.3555516", "url": "https://doi.org/10.1145/3550454.3555516", "summary": "Introduces a unified deformation-based multi-axis slicing framework (Simple, Smooth, Smart) capable of jointly optimizing support-free printability, surface quality, and stress-aligned mechanical strength. Improves robustness and generality over prior single-objective curved slicers.", "key_algorithm": "Represents the input volume as a tetrahedral mesh M and optimizes a field of per-tetrahedron unit quaternions Q={q_e} via a two-level solver: an inner loop rotating elements to satisfy local objectives (principal stress alignment, overhang elimination, surface normal alignment) and an outer loop blending rotations into a smooth deformed mesh M_d whose planar height-field slices pull back to curved layers.", "relevance_to_forma_print": "Provides the unified theoretical blueprint for multi-objective slicing optimization, demonstrating how overhang, surface smoothness, and mechanical strength objectives interact when upgrading from Tier 1 planar orientation (orient.rs) to multi-axis curved slicing.", "source_verified": true}diff --git a/research/corpus/software.jsonl b/research/corpus/software.jsonlnew file mode 100644index 0000000..74d393e--- /dev/null+++ b/research/corpus/software.jsonl@@ -0,0 +1,59 @@+{"id":"orcaslicer","name":"OrcaSlicer","category":"slicer","repo_or_primary_url":"https://github.com/OrcaSlicer/OrcaSlicer","source_urls":["https://github.com/OrcaSlicer/OrcaSlicer","https://www.orcaslicer.com","https://github.com/OrcaSlicer/OrcaSlicer/wiki/cli_mode","https://github.com/OrcaSlicer/OrcaSlicer/wiki/cli_actions"],"license":"AGPL-3.0","languages":["C++","C","CMake","Python","TypeScript","JavaScript","GLSL"],"capabilities":["Fork of Bambu Studio and PrusaSlicer supporting FFF slicing and Arachne wall generator","Built-in calibration suites (pressure advance, flow rate, VFA, temperature towers)","Multi-plate management, tree/organic supports, and multi-color painting","Device profiles for Bambu Lab, Klipper, Marlin, Prusa, and Voron printers"],"workflows":["Desktop GUI","Headless CLI automation (orca-slicer [files...] [options...]) for CI/farm slicing","Direct LAN/cloud printer push (Moonraker, OctoPrint, Bambu)"],"input_formats":["3mf","stl","obj","step","amf","svg","json"],"output_formats":["gcode","gcode.3mf","3mf","stl","json"],"cli_or_api_flags":["--slice <0|i>","--export-3mf <file.3mf>","--min-save","--export-stl","--export-stls <dir>","--export-settings <settings.json>","--export-slicedata <dir>","--load-slicedata <dir>","--load-settings \"machine.json;process.json\"","--load-filaments \"f1.json;...\"","--load-defaultfila","--arrange <0|1>","--orient <0|1>","--scale <factor>","--outputdir <dir>","--pipe <pipename>","--info","--uptodate","--mtcpp <n>","--mstpp <sec>","--no-check","--normative-check","--debug <0..5>","--help / -h","--<hyphenated-setting-key>=<val>"],"three_mf_metadata_schema":"OPC ZIP container ([Content_Types].xml, _rels/.rels, 3D/3dmodel.model) plus Metadata/: project_settings.config (JSON with filament_colour[], filament_type[], machine/process settings), model_settings.config (XML <config><plate><object id><part id subtype=\"normal_part|modifier_part|negative_part|support_enforcer|support_blocker\"><metadata key=\"extruder\" value=\"1..N\"/>), plate_N.json, plate_N.gcode, plate_N.gcode.md5, slice_info.config, and plate thumbnails.","architectural_lessons_for_forma_print":"Exact target schema for export_3mf.rs (Metadata/model_settings.config 1-indexed extruder + subtype=\"modifier_part\", Metadata/project_settings.config JSON filament_colour[]/filament_type[], Metadata/plate_1.json); --pipe and --export-slicedata show how Tier 3 slicer.rs should parse headless slice output.","source_verified":true,"availability_notes":"Fully open-source and documented (AGPL-3.0); SoftFever/OrcaSlicer GitHub URLs redirect to OrcaSlicer/OrcaSlicer.","relevance_to_forma_print":"Primary FFF slicer consumer of forma-print .3mf exports and Tier 3 slicer-cli integration target."}+{"id":"prusaslicer","name":"PrusaSlicer","category":"slicer","repo_or_primary_url":"https://github.com/prusa3d/PrusaSlicer","source_urls":["https://github.com/prusa3d/PrusaSlicer","https://www.prusa3d.com/prusaslicer/","https://github.com/prusa3d/PrusaSlicer/wiki/Command-Line-Interface","https://deepwiki.com/prusa3d/PrusaSlicer/1.2-command-line-interface"],"license":"AGPL-3.0","languages":["C++","C","CMake"],"capabilities":["Slic3r-derived FFF and MSLA/SLA slicer supporting organic supports","Multi-toolhead Prusa XL and MMU3 multi-material painting","Variable layer height, native STEP tessellation, and mesh repair","Binary G-code (.bgcode) and MSLA (.sl1/.sl1s) export"],"workflows":["Desktop GUI","Headless CLI (prusa-slicer / prusa-slicer-console.exe on Windows)","Direct upload to PrusaLink, Prusa Connect, OctoPrint, or Moonraker"],"input_formats":["3mf","stl","obj","step","amf","ini"],"output_formats":["gcode","bgcode","3mf","amf","sl1","sl1s","stl","obj"],"cli_or_api_flags":["--export-gcode / -g","--export-3mf","--export-sla","--load <config.ini>","--output <path>","--info","--datadir <path>","--dont-arrange","--center <x,y>","--merge / -m","--help / -h","--help-fff","--help-sla"],"three_mf_metadata_schema":"OPC ZIP container ([Content_Types].xml, _rels/.rels, 3D/3dmodel.model) plus Metadata/Slic3r_PE.config (INI key-value print/filament/printer snapshot), Metadata/Slic3r_PE_model.config (XML <config><object id><volume id><metadata key=\"extruder|name|volume_type\" value=\"...\"/></object></config>), and Metadata/thumbnail.png.","architectural_lessons_for_forma_print":"Slic3r_PE_model.config XML volume-level extruder mapping must be emitted alongside Bambu/Orca model_settings.config so Prusa XL/MMU3 users get automatic multi-extruder slot pre-assignment; treat Slic3r_PE.config post_process keys as untrusted when ingesting external 3MFs.","source_verified":true,"availability_notes":"Fully open-source (AGPL-3.0); note prusa-slicer-console.exe is required on Windows for stdout/stderr capture.","relevance_to_forma_print":"Second primary FFF/MSLA target for export_3mf.rs (Slic3r_PE_model.config) and Tier 3 slicer.rs; backs profiles prusa_mk4s, prusa_core_one, prusa_xl."}+{"id":"bambu_studio","name":"Bambu Studio","category":"slicer","repo_or_primary_url":"https://github.com/bambulab/BambuStudio","source_urls":["https://github.com/bambulab/BambuStudio","https://github.com/bambulab/BambuStudio/wiki/Command-Line-Usage"],"license":"AGPL-3.0","languages":["C++","C","CMake","Python"],"capabilities":["PrusaSlicer fork tailored for Bambu Lab printers (A1 mini, A1, P1S, X1C, H2D)","AMS 1..16 slot painting and multi-plate nesting","Native STEP import and mesh slicing","Bambu cloud and LAN MQTT+FTPS print dispatch"],"workflows":["Desktop GUI","Headless CLI (bambu-studio [OPTIONS] [file.3mf/file.stl ...])","Bambu Cloud or LAN-Only + Developer Mode push"],"input_formats":["3mf","stl","obj","step","amf","svg","json"],"output_formats":["gcode.3mf","3mf","gcode","json"],"cli_or_api_flags":["--debug <0..5>","--load-filaments \"f1.json;f2.json\"","--load-settings \"machine.json;process.json\"","--outputdir <dir>","--arrange <0|1|auto>","--orient","--scale <factor>","--export-3mf <filename.3mf>","--export-settings <settings.json>","--export-slicedata <dir>","--load-slicedata <dir>","--help / -h","--info","--pipe <pipename>","--slice <0|i>","--uptodate","--<key>=<value>"],"three_mf_metadata_schema":"Same Bambu-dialect OPC ZIP layout as OrcaSlicer: 3D/3dmodel.model, Metadata/model_settings.config (XML <object>/<part subtype=\"...\"> + 1-indexed extruder), Metadata/project_settings.config (JSON filament_colour[], filament_type[]), Metadata/plate_N.json, Metadata/plate_N.png, Metadata/slice_info.config, Metadata/plate_N.gcode.","architectural_lessons_for_forma_print":"Strict 3-tier settings precedence (CLI --key=val > --load-settings/--load-filaments full JSONs > embedded 3MF configs); --load-settings requires full merged profile JSONs rather than partial resource snippets.","source_verified":true,"availability_notes":"Slicer source is open-source (AGPL-3.0), while Bambu Network Plugin (bambu_networking) used for cloud/encrypted LAN comms is a proprietary binary.","relevance_to_forma_print":"Primary consumer of forma-print's AMS-preassigned .3mf for bambu_* profiles and Tier 3 slicer.rs."}+{"id":"cura","name":"UltiMaker Cura","category":"slicer","repo_or_primary_url":"https://github.com/Ultimaker/Cura","source_urls":["https://github.com/Ultimaker/Cura","https://ultimaker.com/en/products/cura-software"],"license":"LGPL-3.0","languages":["Python","QML","CMake"],"capabilities":["Modular Python + Qt/QML desktop frontend built on the Uranium framework (Ultimaker/Uranium)","Marketplace plugins and multi-extruder support","Digital Factory integration","Protobuf IPC (libArcus) to CuraEngine"],"workflows":["Interactive desktop GUI","Plugin-extensible pipeline (including 3MF writer/reader plugins)","Dispatches slicing jobs to CuraEngine"],"input_formats":["3mf","stl","obj","amf","x3d","dae"],"output_formats":["gcode","3mf","ufp"],"cli_or_api_flags":["GUI-focused frontend; accepts model file paths on launch, while headless slicing is invoked via the separate CuraEngine binary."],"three_mf_metadata_schema":"OPC ZIP container with 3D/3dmodel.model, Metadata/thumbnail.png, and Cura-specific Cura/*.global.cfg + Cura/*.extruder.cfg INI-style configuration files storing machine definition IDs, material GUIDs, and per-extruder train settings.","architectural_lessons_for_forma_print":"Clean separation between Python/QML UI (LGPL-3.0) and C++ slicing engine (AGPL-3.0); demonstrates why forma-print should isolate headless DFM/export from any heavy GUI framework.","source_verified":true,"availability_notes":"Open-source (LGPL-3.0).","relevance_to_forma_print":"Secondary .3mf consumer and ecosystem reference for material/extruder separation."}+{"id":"cura_engine","name":"CuraEngine","category":"slicer","repo_or_primary_url":"https://github.com/Ultimaker/CuraEngine","source_urls":["https://github.com/Ultimaker/CuraEngine","https://github.com/Ultimaker/CuraEngine/wiki/Internals","https://github.com/Ultimaker/CuraEngine/wiki/Slicing"],"license":"AGPL-3.0","languages":["C++","CMake","Python"],"capabilities":["High-speed headless C++ G-code generator featuring Arachne variable line width","Tree supports and infill/skin area generation","Multi-extruder trains","libArcus/gRPC socket communication"],"workflows":["Headless CLI (CuraEngine slice ...)","Socket/gRPC daemon driven by Cura or farm backends"],"input_formats":["stl","obj","def.json"],"output_formats":["gcode"],"cli_or_api_flags":["slice","-j <definition.json>","-s <setting>=<value>","-l <model_file>","-o <output.gcode>","-e <extruder_nr>","-g","--next","-v","-p"],"three_mf_metadata_schema":"none (CuraEngine CLI accepts raw STL/OBJ meshes + JSON definitions; 3MF packaging/extraction is handled by Cura frontend or external wrappers).","architectural_lessons_for_forma_print":"Positional CLI state scoping (-e0, -g, -l, -s) allows single-command multi-extruder slicing without XML/ZIP overhead; illustrates pure headless C++ engine design.","source_verified":true,"availability_notes":"Open-source (AGPL-3.0); note CuraEngine alone lacks native .3mf input in its standalone slice CLI.","relevance_to_forma_print":"Tier 3 slicer.rs candidate alongside orca-slicer and prusa-slicer."}+{"id":"superslicer","name":"SuperSlicer","category":"slicer","repo_or_primary_url":"https://github.com/supermerill/SuperSlicer","source_urls":["https://github.com/supermerill/SuperSlicer","https://superslicer.org"],"license":"AGPL-3.0","languages":["C++","C","CMake","AngelScript","Python"],"capabilities":["PrusaSlicer fork adding fine-grained Klipper/Voron tuning","Built-in calibration prints and AngelScript custom supports/patterns","Thin-wall and gap-fill controls","mSLA PNG layer export"],"workflows":["Desktop GUI","PrusaSlicer-compatible CLI (--export-gcode, --export-3mf, --export-sla)"],"input_formats":["stl","obj","amf","3mf","ini"],"output_formats":["gcode","3mf","amf","png"],"cli_or_api_flags":["--help","--help-fff","--help-sla","--loglevel <severity>","--datadir <path>","--export-gcode","--export-3mf <file.3mf>","--export-sla","--load <config.ini>","Note: explicitly omits upstream Slic3r --cut-grid, --cut-x, --cut-y, and --autosave"],"three_mf_metadata_schema":"Shares PrusaSlicer OPC ZIP layout (3D/3dmodel.model, Metadata/Slic3r_PE.config, Metadata/Slic3r_PE_model.config, Metadata/thumbnail.png).","architectural_lessons_for_forma_print":"Exposing granular wall/overhang/calibration knobs and Klipper-centric profiles validates voron_24_* profile assumptions and Slic3r_PE_model.config compatibility.","source_verified":true,"availability_notes":"Open-source (AGPL-3.0); maintenance cadence lags upstream PrusaSlicer/OrcaSlicer.","relevance_to_forma_print":"Compatible consumer of Prusa-dialect .3mf and useful reference for Voron/Klipper printability parameters."}+{"id":"slic3r","name":"Slic3r","category":"slicer","repo_or_primary_url":"https://github.com/slic3r/Slic3r","source_urls":["https://github.com/slic3r/Slic3r","https://slic3r.org/"],"license":"AGPL-3.0","languages":["C++","Perl","C","CMake"],"capabilities":["Foundational RepRap toolpath generator (libslic3r C++ core + Perl orchestration/wxPerl GUI)","Multi-extruder slicing, adaptive layers, and modifier meshes","Mesh repair (--repair), Z-cutting (--cut), and shell splitting (--split)","SVG slice export"],"workflows":["Desktop GUI","slic3r.pl CLI automation","libslic3r embeddable C++ core"],"input_formats":["stl","obj","amf","3mf","ini"],"output_formats":["gcode","svg","stl","obj","amf","3mf"],"cli_or_api_flags":["--help","--version","-o / --output <file>","--load <ini>","--save <ini>","--datadir <path>","-j / --threads <num>","--repair","--cut <z>","--split","--info"],"three_mf_metadata_schema":"Basic 3MF mesh/object reading and writing; predates PrusaSlicer's Slic3r_PE_model.config extensions.","architectural_lessons_for_forma_print":"Origin of --repair, --cut, --split, --info CLI verbs and libslic3r geometry kernel inherited by PrusaSlicer/Bambu/Orca; demonstrates decoupling geometry core from frontend.","source_verified":true,"availability_notes":"Open-source (AGPL-3.0); legacy Perl/wxPerl stack, largely superseded in active development by PrusaSlicer/OrcaSlicer.","relevance_to_forma_print":"Historical baseline for slicer CLI ergonomics and mesh-prep operations (split.rs, dfm.rs)."}+{"id":"ideamaker","name":"Raise3D ideaMaker","category":"slicer","repo_or_primary_url":"https://www.raise3d.com/ideamaker","source_urls":["https://www.raise3d.com/ideamaker"],"license":"Proprietary (Freeware)","languages":["unavailable (closed-source binary)"],"capabilities":["Closed-source FFF/DLP slicer by Raise3D featuring modifier regions","Surface texture mapping onto meshes","Automated support generation","RaiseCloud integration"],"workflows":["Desktop GUI","Exports template bundles and dispatches to Raise3D printers via RaiseCloud or local LAN"],"input_formats":["stl","obj","3mf","oltp"],"output_formats":["gcode","data","idea","bin","printer","filament"],"cli_or_api_flags":["GUI-only; no public headless slicing CLI or open developer API documented"],"three_mf_metadata_schema":"Imports standard .3mf meshes; internal .idea/.bin project and template formats are proprietary.","architectural_lessons_for_forma_print":"Illustrates vendor lock-in friction when CLI/API and internal project schemas are closed, directly justifying forma-print's open CLI/MCP and documented .3mf layout.","source_verified":true,"availability_notes":"Closed-source freeware; source code and headless CLI/API specifications are unavailable.","relevance_to_forma_print":"Explicit proprietary contrast entry showing why forma-print targets open slicers (OrcaSlicer, PrusaSlicer, CuraEngine)."}+{"id":"chitubox","name":"CHITUBOX Basic & Pro","category":"slicer","repo_or_primary_url":"https://www.chitubox.com","source_urls":["https://www.chitubox.com"],"license":"Proprietary (Free Basic / Paid Subscription Pro)","languages":["unavailable (closed-source binary)"],"capabilities":["Dominant MSLA/DLP resin slicer supporting hollowing and drain holes","Island detection (Pro) and tree/heavy-to-light supports","Encrypted .ctb/.goo export for Elegoo, Anycubic, Phrozen, and partner resin printers"],"workflows":["Desktop GUI bound to online account license keys (2 PCs personal / 5 PCs team)","Limited basic CLI mesh invocation in Basic"],"input_formats":["stl","obj","3mf","chitubox","ctp"],"output_formats":["ctb","cbddlp","goo","chitubox","ctp"],"cli_or_api_flags":["Basic command-line mesh invocation documented in CHITUBOX developer reference; full headless slicing APIs are closed/partner-restricted."],"three_mf_metadata_schema":"Imports .3mf mesh geometry; native project metadata uses proprietary .chitubox/.ctp containers rather than open 3MF slicer extensions.","architectural_lessons_for_forma_print":"Highlights why MSLA printers need pre-slicer pure-Rust DFM (dfm.rs: 30 deg resin overhangs, floating islands, wall thickness, and Tier 2 suction/hollow checks) before entering closed GUI resin slicers.","source_verified":true,"availability_notes":"Closed-source proprietary software; online seat binding and restricted API availability.","relevance_to_forma_print":"Contrast entry motivating elegoo_mars_5_ultra / elegoo_saturn_4_ultra DFM checks and UVtools open-source resin bridge."}+{"id":"lychee_slicer","name":"Lychee Slicer","category":"slicer","repo_or_primary_url":"https://lychee.co","source_urls":["https://lychee.co","https://mango3d.io"],"license":"Proprietary (Freemium: Free / Paid Pro Subscription)","languages":["unavailable (closed-source binary)"],"capabilities":["Mango 3D desktop slicer for MSLA resin and FDM printers","Interactive island detection and suction cup warnings (Pro)","Magic auto-orientation, supports, and hollowing"],"workflows":["Desktop GUI requiring Mango 3D account login (up to 2 installs, 1 concurrent active machine)"],"input_formats":["stl","obj","3mf","lys","lyt"],"output_formats":["ctb","goo","pwmx","sl1","gcode","lys"],"cli_or_api_flags":["GUI-only; no public headless CLI or public API documented."],"three_mf_metadata_schema":"Imports standard .3mf geometry; project state is stored in proprietary .lys/.lyt files.","architectural_lessons_for_forma_print":"Validates that commercial resin slicers gate island and suction-cup checks behind interactive GUI subscriptions, making fast deterministic headless DFM + auto-orientation in forma-print high-value for AI agents.","source_verified":true,"availability_notes":"Closed-source freemium desktop app; no headless CLI/API available.","relevance_to_forma_print":"Explicit contrast entry for resin workflow automation limits."}+{"id":"lib3mf","name":"3MF Consortium lib3mf","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/3MFConsortium/lib3mf","source_urls":["https://github.com/3MFConsortium/lib3mf","http://3mf.io/specification/","https://lib3mf.readthedocs.io"],"license":"BSD-2-Clause","languages":["C++","C","Python","C#","Go","JavaScript","Java","Pascal"],"capabilities":["Official reference implementation of the 3MF specification (Core, Materials & Properties, Production, Beam Lattice, Slice, Secure Content, Boolean Operations, Displacement, Toolpath/Volumetric extensions)","OPC ZIP parsing and validation","WASM builds (@3mfconsortium/lib3mf)"],"workflows":["Linked C/C++ shared library","PyPI (lib3mf) or npm WASM bindings inside slicers, CAD exporters, and validators"],"input_formats":["3mf"],"output_formats":["3mf"],"cli_or_api_flags":["Programmatic C-ABI / OOP wrappers (Wrapper::CreateModel, ReadFromFile, WriteToFile, AddMeshObject, AddBaseMaterialGroup, AddColorGroup); no standalone end-user CLI."],"three_mf_metadata_schema":"Canonical implementer of <model unit=\"millimeter\">, <resources><basematerials>, <m:colorgroup>, <components>, <build><item>, <metadata>, [Content_Types].xml, and _rels/.rels.","architectural_lessons_for_forma_print":"Authoritative reference for XML namespaces, unit=\"millimeter\", <basematerials>, <m:colorgroup>, and OPC relationships emitted by export_3mf.rs without pulling C++ lib3mf into Rust (0 new crates).","source_verified":true,"availability_notes":"Permissively licensed (BSD-2-Clause); note no official pure-Rust binding in upstream repo.","relevance_to_forma_print":"Spec oracle for validating forma-print .3mf output conformance."}+{"id":"manifold","name":"Manifold","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/elalish/manifold","source_urls":["https://github.com/elalish/manifold"],"license":"Apache-2.0","languages":["C++","C","Python","TypeScript","JavaScript"],"capabilities":["Parallelized CSG and triangle mesh boolean library guaranteeing manifold/watertight output across coplanar/degenerate cases","Arbitrary vertex property interpolation and 2D CrossSection offsets/extrusions","WASM (manifold-3d), PyPI (manifold3d), and OpenSCAD integration"],"workflows":["Embedded C++/WASM/Python geometry kernel for solid modeling and boolean operations"],"input_formats":["manifold_mesh","cross_section","gltf_ext_mesh_manifold"],"output_formats":["manifold_mesh"],"cli_or_api_flags":["Library API (Manifold::Boolean, Extrude, Revolve, Hull, Smooth, Decompose, Status); no standalone CLI."],"three_mf_metadata_schema":"not_applicable (advocates 3MF and glTF EXT_mesh_manifold over STL for preserving topology; does not serialize 3MF files directly).","architectural_lessons_for_forma_print":"Reinforces Forma's core invariant (WT=ok NM=0 B=0 by construction) and shows how EXT_mesh_manifold / topological indices beat polygon-soup heuristic repair.","source_verified":true,"availability_notes":"Fully open-source (Apache-2.0).","relevance_to_forma_print":"Benchmark/reference for boolean robustness and manifold-by-construction workflows."}+{"id":"meshlab","name":"MeshLab","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/cnr-isti-vclab/meshlab","source_urls":["https://github.com/cnr-isti-vclab/meshlab","http://www.meshlab.net"],"license":"GPL-3.0","languages":["C++","C","CMake"],"capabilities":["Plugin-based desktop mesh processing application powered by VCGLib","Non-manifold edge/vertex removal, duplicate/degenerate cleanup, and hole filling","Poisson/Ball-Pivoting surface reconstruction, ICP alignment, quadric decimation, Hausdorff distance, and format conversion"],"workflows":["Interactive Qt desktop GUI","Automated Python scripting via PyMeshLab (cnr-isti-vclab/PyMeshLab), which superseded legacy meshlabserver"],"input_formats":["ply","stl","obj","off","3mf","gltf","dae","xyz"],"output_formats":["ply","stl","obj","off","3mf","gltf","dae"],"cli_or_api_flags":["Legacy meshlabserver (-i, -o, -s <mlx_script>) replaced by PyMeshLab Python API (MeshSet.load_new_mesh, apply_filter, save_current_mesh)."],"three_mf_metadata_schema":"Reads/writes basic 3MF mesh geometry for conversion; does not author Bambu/Prusa slicer .config metadata.","architectural_lessons_for_forma_print":"Demonstrates modular filter-pipeline architecture and why headless scriptable APIs (PyMeshLab) replaced brittle XML macro CLI (meshlabserver).","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Reference for mesh repair filters (non-manifold cleanup, hole filling) and Hausdorff comparison benchmarks."}+{"id":"vcglib","name":"VCGLib","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/cnr-isti-vclab/vcglib","source_urls":["https://github.com/cnr-isti-vclab/vcglib","http://vcglib.net/"],"license":"GPL-3.0","languages":["C++","C"],"capabilities":["Header-only template C++ library for triangle and tetrahedral meshes","Half-edge/winged topology and spatial hashing/BVH","Simplification, smoothing, hole filling, and thickness/SDF computation"],"workflows":["Embedded C++ header-only dependency for standalone high-throughput mesh pipelines and MeshLab plugins"],"input_formats":["ply","stl","obj","off"],"output_formats":["ply","stl","obj","off"],"cli_or_api_flags":["C++ template API (vcg::tri::Clean, vcg::tri::Hole, vcg::tri::UpdateTopology); no CLI."],"three_mf_metadata_schema":"none (geometry library only).","architectural_lessons_for_forma_print":"Validates BVH/raycast wall-thickness and manifold adjacency checks in bvh.rs + dfm.rs.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Algorithmic reference for pure-Rust mesh diagnostics without GPL/C++ dependency contamination."}+{"id":"trimesh","name":"trimesh","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/mikedh/trimesh","source_urls":["https://github.com/mikedh/trimesh","https://trimesh.org"],"license":"MIT","languages":["Python"],"capabilities":["Pure-Python NumPy-backed triangular mesh analysis/repair library","Watertightness (is_watertight), winding/normal repair, and hole filling","BVH ray-casting (ray), 2D cross-sections (section), convex hull, clearance/proximity, and scene-graph transforms"],"workflows":["Interactive Jupyter/Python scripts","Headless CI checks and web CAD backends (used directly by Shpigford/nurb)"],"input_formats":["stl","obj","ply","glb","gltf","3mf","off","dxf","dae"],"output_formats":["stl","obj","ply","glb","gltf","3mf","off","dxf"],"cli_or_api_flags":["Python API (trimesh.load, mesh.is_watertight, mesh.section, trimesh.repair.fix_normals, trimesh.exchange.threemf); no primary CLI."],"three_mf_metadata_schema":"Built-in trimesh.exchange.threemf parses/exports core 3MF 3D/3dmodel.model XML meshes and scene transforms (requires soft dep lxml), without Bambu/Prusa slicer .config files.","architectural_lessons_for_forma_print":"nurb uses trimesh for checks.py/probe.py (sections, raycasts, watertightness) — forma-print implements the same deterministic checks in pure Rust (bvh.rs, dfm.rs) 10-100x faster with 0 Python/C deps.","source_verified":true,"availability_notes":"Permissively licensed (MIT); booleans and 3MF require optional dependencies (manifold3d/blender, lxml).","relevance_to_forma_print":"Direct Python counterpart to forma-print Tier 1 DFM geometry checks."}+{"id":"meshoptimizer","name":"meshoptimizer (+ gltfpack)","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/zeux/meshoptimizer","source_urls":["https://github.com/zeux/meshoptimizer","https://meshoptimizer.org/"],"license":"MIT","languages":["C++","C","JavaScript","Python"],"capabilities":["Vertex cache, overdraw, and fetch optimization","Attribute-preserving mesh simplification (LODs) and meshlet building","Vertex/index buffer compression (EXT_meshopt_compression) and gltfpack CLI tool"],"workflows":["C/C++ library (plus meshopt Rust crate / meshoptimizer.js)","gltfpack CLI asset pipeline"],"input_formats":["gltf","glb","obj"],"output_formats":["gltf","glb"],"cli_or_api_flags":["gltfpack CLI: -i <file>","-o <file>","-c","-cc","-cz","-si <ratio>","-tc","-tp","-tw","-mi"],"three_mf_metadata_schema":"none (glTF/OBJ pipeline only).","architectural_lessons_for_forma_print":"Shows clean C/CLI separation and deterministic attribute-preserving decimation; highlights why forma-print uses RFC-1951 Deflate on 3MF rather than lossy quantization that could break print manifoldness.","source_verified":true,"availability_notes":"Open-source (MIT).","relevance_to_forma_print":"Complementary glTF web-preview optimization reference; not for lossless CAD/print export."}+{"id":"corto","name":"Corto","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/cnr-isti-vclab/corto","source_urls":["https://github.com/cnr-isti-vclab/corto"],"license":"Dual: GPL-3.0 (C++ library/CLI) / MIT (JavaScript decoder)","languages":["C++","C","JavaScript","C#"],"capabilities":["Ultra-fast-decoding mesh and point-cloud compression using Tunstall entropy coding for vertex attributes (positions, normals, colors, UVs)","Three.js CORTOLoader support"],"workflows":["Compress .ply/.obj via corto CLI or libcorto C++ API","Fast browser decompression via corto.js/corto.em.js"],"input_formats":["ply","obj"],"output_formats":["crt"],"cli_or_api_flags":["corto CLI compressor and C++/JS encoder-decoder APIs (crt::Encoder, crt::Decoder)."],"three_mf_metadata_schema":"none","architectural_lessons_for_forma_print":"Fast client-side mesh streaming inspiration, though 3MF/STEP manufacturing pipelines require lossless ZIP/Deflate or ASCII STEP rather than quantized .crt.","source_verified":true,"availability_notes":"C++ side is GPL-3.0; JS decoder is MIT.","relevance_to_forma_print":"Contrast mesh-streaming codec vs. lossless manufacturing formats."}+{"id":"draco","name":"Google Draco","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/google/draco","source_urls":["https://github.com/google/draco","https://google.github.io/draco/"],"license":"Apache-2.0","languages":["C++","C","JavaScript","C#"],"capabilities":["Edgebreaker-based 3D mesh and point-cloud compression/decompression (KHR_draco_mesh_compression in glTF 2.0)","Configurable quantization bits and compression levels 0..10","WASM decoders"],"workflows":["draco_encoder / draco_decoder CLI tools","C++/WASM SDK embedded in glTF pipelines"],"input_formats":["obj","ply","stl"],"output_formats":["drc","obj","ply","stl"],"cli_or_api_flags":["draco_encoder / draco_decoder CLI: -i <input>","-o <output>","-cl <0..10>","-qp <bits>","-qn <bits>","-qt <bits>"],"three_mf_metadata_schema":"none","architectural_lessons_for_forma_print":"Beware lossy vertex-position quantization (-qp) on tight-tolerance 3D-printed parts because it can collapse thin walls or create non-manifold edges.","source_verified":true,"availability_notes":"Open-source (Apache-2.0).","relevance_to_forma_print":"Explains why forma-print keeps exact unquantized f64/f32 coordinates inside Deflate .3mf and .step."}+{"id":"uvtools","name":"UVtools (+ UVtoolsCmd CLI)","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/sn4k3/UVtools","source_urls":["https://github.com/sn4k3/UVtools","https://github.com/sn4k3/UVtools/blob/master/UVtools.Cmd/Program.cs","https://github.com/sn4k3/UVtools/wiki/CLI-(Command-Line-Interface)"],"license":"AGPL-3.0","languages":["C#","Python"],"capabilities":["Cross-platform MSLA/DLP sliced file analyzer, calibrator, converter, and repair tool supporting 35+ resin formats","Detects and repairs floating islands, suction cups, resin traps, overhangs, and empty layers","Injects PrusaSlicer SL1S proxy profiles for .ctb/.goo printers"],"workflows":["Avalonia desktop GUI","UVtoolsCmd headless CLI (System.CommandLine) for batch inspection (print-issues), repair (run), format conversion (convert), and thumbnail injection (set-thumbnail)"],"input_formats":["ctb","cbddlp","goo","sl1","sl1s","photon","pwmx","phz","prz","cxdlp","zip"],"output_formats":["ctb","cbddlp","goo","sl1","sl1s","photon","pwmx","phz","png"],"cli_or_api_flags":["UVtoolsCmd subcommands: convert","run","extract","print-issues","print-properties","print-gcode","print-machines","print-formats","set-properties","set-thumbnail","copy-parameters","compare","benchmark-layer-codecs","Global flags: --quiet","--no-progress","--dummy","--core-version","-? / --help"],"three_mf_metadata_schema":"none directly (operates on post-slice raster resin archives like .sl1s/.ctb/.goo; pairs with PrusaSlicer .3mf -> .sl1s upstream).","architectural_lessons_for_forma_print":"Gold-standard taxonomy of MSLA print failure modes (floating islands, suction cups, resin traps) and headless print-issues / set-thumbnail CLI ergonomics.","source_verified":true,"availability_notes":"Open-source (AGPL-3.0 verified in UVtools.Cmd/Program.cs; note older summaries mistakenly list GPL-3.0).","relevance_to_forma_print":"Directly informs dfm.rs island detection, elegoo_mars_5_ultra/elegoo_saturn_4_ultra profiles, Tier 2 suction-cup detector, and thumbnail embedding."}+{"id":"open3d","name":"Open3D","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/isl-org/Open3D","source_urls":["https://github.com/isl-org/Open3D","https://github.com/isl-org/Open3D/blob/main/LICENSE","http://www.open3d.org"],"license":"MIT","languages":["C++","Python","C","CUDA"],"capabilities":["Point cloud, triangle mesh, voxel grid, and octree/KD-tree processing","Poisson/Ball-Pivoting surface reconstruction, ICP registration, and PBR visualization","Basic mesh repair (remove_non_manifold_edges, remove_degenerate_triangles, fill_holes)"],"workflows":["Python (open3d) or C++ library for 3D perception, scan-to-mesh, and ML pipelines (Open3D-ML)"],"input_formats":["ply","stl","obj","off","gltf","glb","pcd","xyz"],"output_formats":["ply","stl","obj","off","gltf","glb","pcd","xyz"],"cli_or_api_flags":["C++/Python API (open3d.io.read_triangle_mesh, remove_non_manifold_edges, remove_duplicated_vertices, fill_holes); no dedicated CLI."],"three_mf_metadata_schema":"none (lacks native .3mf reader/writer).","architectural_lessons_for_forma_print":"Shows clear separation between scan/point-cloud perception tools and CAD/manufacturing .3mf pipelines.","source_verified":true,"availability_notes":"Open-source (MIT).","relevance_to_forma_print":"Reference for scan cleanup before CAD/print checks."}+{"id":"cgal","name":"CGAL","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/CGAL/cgal","source_urls":["https://github.com/CGAL/cgal","https://github.com/CGAL/cgal/blob/master/LICENSE.md"],"license":"Dual: GPL-3.0 / LGPL-3.0 (package-dependent) + Commercial (GeometryFactory)","languages":["C++","C"],"capabilities":["Header-only (since v5.0) exact-arithmetic computational geometry library","Polygon Mesh Processing (PMP) handles polygon-soup repair, self-intersection removal, hole fairing/filling, corefinement booleans, isotropic remeshing, and 2D/3D convex hulls"],"workflows":["Embedded C++ template library (also backs OpenSCAD's traditional CSG backend and PrusaSlicer geometry ops)"],"input_formats":["off","obj","stl","ply"],"output_formats":["off","obj","stl","ply"],"cli_or_api_flags":["C++ template API (CGAL::Polygon_mesh_processing::repair_polygon_soup, orient, corefine_and_compute_union, does_self_intersect); no standalone CLI."],"three_mf_metadata_schema":"none (requires external loader such as lib3mf).","architectural_lessons_for_forma_print":"Gold standard for exact-predicate polygon mesh repair, though heavy template compile times and GPL/LGPL terms explain why forma-print stays pure Rust + lightweight BVH/spatial math.","source_verified":true,"availability_notes":"Dual-licensed (GPL-3.0/LGPL-3.0 or commercial); docs/tests in git are CC0-1.0.","relevance_to_forma_print":"Algorithmic benchmark for DFM watertightness, self-intersection, and convex-hull stability math."}+{"id":"libigl","name":"libigl","category":"mesh_repair_analysis","repo_or_primary_url":"https://github.com/libigl/libigl","source_urls":["https://github.com/libigl/libigl","http://libigl.github.io/libigl/"],"license":"MPL-2.0 (core); optional copyleft submodules (igl::copyleft::cgal) GPL-3.0","languages":["C++","C","Python (nanobind)"],"capabilities":["Header-only C++ geometry processing library using Eigen matrices (V, F) for discrete differential geometry","Cotangent Laplacians, UV parameterization (LSCM/ARAP), SDF/winding numbers, and deformations"],"workflows":["Embedded C++ headers","pip install libigl Python NumPy/SciPy workflows"],"input_formats":["obj","stl","ply","off","wrl"],"output_formats":["obj","stl","ply","off"],"cli_or_api_flags":["C++/Python matrix API (igl::readOBJ, igl::signed_distance, igl::fast_winding_number, igl::lscm); no standalone CLI."],"three_mf_metadata_schema":"none","architectural_lessons_for_forma_print":"Matrix/half-edge simplicity and fast winding-number / SDF concepts; forma_core already uses LSCM UVs, and forma-print reuses forma_core rather than adding C++ FFI.","source_verified":true,"availability_notes":"Core is MPL-2.0; GitHub auto-detects GPL-3.0 because of optional copyleft submodules.","relevance_to_forma_print":"Reference for fast winding-number and signed-distance thickness verification."}+{"id":"octoprint","name":"OctoPrint","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/OctoPrint/OctoPrint","source_urls":["https://github.com/OctoPrint/OctoPrint","https://octoprint.org"],"license":"AGPL-3.0","languages":["Python","JavaScript","CSS"],"capabilities":["Mature Python web host for USB/serial 3D printers (Marlin, RepRap, Klipper-via-virtual-tty)","Plugin ecosystem, webcam streaming, and G-code viewer","Full REST + SockJS push API"],"workflows":["Self-hosted Raspberry Pi/Linux daemon","Slicers push G-code via REST POST /api/files/local with X-Api-Key"],"input_formats":["gcode","gco","g"],"output_formats":["serial_gcode_stream","json_rest_api"],"cli_or_api_flags":["CLI: octoprint serve","--host","--port","--config","--basedir","REST API: POST /api/files/local","GET /api/printer","POST /api/job","GET /api/version (Header: X-Api-Key)"],"three_mf_metadata_schema":"not_applicable (accepts sliced G-code files; thumbnail/metadata plugins parse embedded G-code comments or slicer previews).","architectural_lessons_for_forma_print":"Standardized POST /api/files/local multipart upload contract targeted by Tier 3 printer_api.rs (net-lan).","source_verified":true,"availability_notes":"Open-source (AGPL-3.0).","relevance_to_forma_print":"Primary LAN host target for Marlin/legacy FDM printers in Tier 3."}+{"id":"moonraker","name":"Moonraker","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/Arksine/moonraker","source_urls":["https://github.com/Arksine/moonraker","https://moonraker.readthedocs.io"],"license":"GPL-3.0","languages":["Python"],"capabilities":["Async Python 3 Tornado web server exposing REST + WebSocket JSON-RPC APIs over Klipper's Unix domain socket (/tmp/klippy_uds)","File uploads, print queue, Spoolman integration, SimplyPrint/Obico bridges, and power/sensor plugins (default port 7125)"],"workflows":["Background systemd daemon paired with Klipper and frontends (Mainsail/Fluidd)","Direct slicer/agent upload via HTTP multipart"],"input_formats":["gcode","cfg"],"output_formats":["json_rpc","http_rest","klipper_uds"],"cli_or_api_flags":["REST/JSON-RPC: POST /server/files/upload","GET /printer/info","GET /printer/objects/query","POST /printer/print/start","POST /printer/print/pause","POST /printer/print/cancel","POST /printer/gcode/script","GET /server/history/list"],"three_mf_metadata_schema":"not_applicable (parses G-code header/footer metadata + embedded PNG thumbnails for Mainsail/Fluidd; does not slice .3mf).","architectural_lessons_for_forma_print":"Pure-Rust HTTP/1.1 multipart POST /server/files/upload and JSON-RPC status polling are trivial (0 external crates via std::net::TcpStream for plain LAN HTTP) for Tier 3 printer_api.rs.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Primary LAN API target for Klipper printers (voron_24_*, creality_k1c)."}+{"id":"mainsail","name":"Mainsail","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/mainsail-crew/mainsail","source_urls":["https://github.com/mainsail-crew/mainsail","https://docs.mainsail.xyz"],"license":"GPL-3.0","languages":["TypeScript","Vue","JavaScript","CSS"],"capabilities":["Web UI for Klipper via Moonraker JSON-RPC WebSockets","Live temperature charts, 3D/2D G-code viewer, and bed-mesh heightmap visualization","Webcam feeds (Crowsnest), macro buttons, and Spoolman integration"],"workflows":["Browser SPA served by nginx/Caddy talking to Moonraker port 7125"],"input_formats":["gcode","cfg","moonraker_json_rpc"],"output_formats":["moonraker_json_rpc_commands"],"cli_or_api_flags":["Stateless browser UI consuming Moonraker WebSocket JSON-RPC API (no standalone backend API)."],"three_mf_metadata_schema":"not_applicable (renders PNG thumbnails extracted from G-code metadata).","architectural_lessons_for_forma_print":"Demonstrates clean separation of thin UI from Moonraker API, and how bed-mesh, thermal, and Spoolman telemetry is surfaced to operators.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Ecosystem context for Klipper fleet telemetry and Spoolman spool tracking."}+{"id":"fluidd","name":"Fluidd","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/fluidd-core/fluidd","source_urls":["https://github.com/fluidd-core/fluidd","https://docs.fluidd.xyz"],"license":"GPL-3.0","languages":["TypeScript","Vue","JavaScript"],"capabilities":["Lightweight customizable-layout Vue/Vuetify web frontend for Klipper + Moonraker","Multi-printer switching, G-code preview, and bed mesh visualization","Macro management and Spoolman integration"],"workflows":["Browser SPA communicating concurrently with Moonraker JSON-RPC WebSockets"],"input_formats":["gcode","cfg","moonraker_json_rpc"],"output_formats":["moonraker_json_rpc_commands"],"cli_or_api_flags":["Stateless browser UI consuming Moonraker WebSocket JSON-RPC API (no standalone backend API)."],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Confirms Moonraker's single-source-of-truth WebSocket model enables any external agent (forma-print Tier 3) to coexist safely alongside Mainsail/Fluidd UIs.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Ecosystem context for Klipper UI interoperability."}+{"id":"prusa_link","name":"Prusa-Link (+ Prusa-Link-Web)","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/prusa3d/Prusa-Link","source_urls":["https://github.com/prusa3d/Prusa-Link","https://github.com/prusa3d/Prusa-Connect-Local"],"license":"GPL-3.0","languages":["Python","JavaScript","HTML"],"capabilities":["Local host daemon (for 8-bit MK2.5/MK3/MK3S+ via RPi UART/USB; embedded natively in 32-bit Prusa-Firmware-Buddy)","Exposes OpenAPI-specified /api/v1/ REST endpoints and Prusa-Link-Web UI (prusa3d/Prusa-Link-Web)"],"workflows":["Local LAN upload and print control from PrusaSlicer/OrcaSlicer or custom REST clients using HTTP Digest or X-Api-Key auth"],"input_formats":["gcode","bgcode"],"output_formats":["json_rest_api","serial_gcode"],"cli_or_api_flags":["REST /api/v1/: GET /api/v1/status","GET /api/v1/storages","GET /api/v1/storages/{storage}/content","PUT /api/v1/storages/{storage}/content?path=","POST /api/v1/job/{id}/pause","POST /api/v1/job/{id}/cancel"],"three_mf_metadata_schema":"not_applicable (consumes .gcode/.bgcode with embedded thumbnails).","architectural_lessons_for_forma_print":"OpenAPI-specified /api/v1/ REST contract (PUT /api/v1/storages/{storage}/content) provides a clean LAN target for prusa_mk4s, prusa_core_one, and prusa_xl.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Direct LAN protocol reference for Prusa hardware profiles."}+{"id":"prusa_connect","name":"Prusa Connect (Local Server & Cloud)","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/prusa3d/prusa-connect","source_urls":["https://github.com/prusa3d/prusa-connect","https://github.com/prusa3d/prusa-connect/blob/main/LICENSE","https://github.com/prusa3d/Prusa-Connect-SDK-Printer"],"license":"Source-available: OCL v1.1 + Micro v1 + NoSaaS v1 + SWAtt v1 (Prusa Connect Cloud connect.prusa3d.com is proprietary hosted SaaS)","languages":["Go","Svelte","TypeScript","JavaScript"],"capabilities":["Self-hosted single-binary Go + Svelte fleet server (prusa3d/prusa-connect) supporting Prusa firmware >=6.4.0 and third-party drivers","REST API, MQTT, and Server-Sent Events (SSE) completely offline without a Prusa cloud account","Contrasted with hosted EU cloud dashboard connect.prusa3d.com"],"workflows":["Self-hosted local binary/Docker server","Hosted EU cloud dashboard for multi-printer queueing, camera snapshots, and telemetry"],"input_formats":["gcode","bgcode","http_rest","mqtt"],"output_formats":["json_rest_api","mqtt","sse"],"cli_or_api_flags":["REST /api/v1/ fleet endpoints + MQTT + SSE","Prusa-Connect-SDK-Printer Python SDK"],"three_mf_metadata_schema":"not_applicable (manages sliced jobs & telemetry).","architectural_lessons_for_forma_print":"Single-binary Go + embedded web UI model shows local-first fleet design; OCL+NoSaaS license highlights importance of distinguishing OSI-compatible vs source-available licensing.","source_verified":true,"availability_notes":"prusa3d/prusa-connect is source-available (OCL v1.1 + Micro v1 + NoSaaS v1 + SWAtt v1, non-OSI); hosted connect.prusa3d.com is closed SaaS.","relevance_to_forma_print":"Reference for Prusa fleet management and local-first vs cloud trade-offs."}+{"id":"spoolman","name":"Spoolman","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/Donkie/Spoolman","source_urls":["https://github.com/Donkie/Spoolman"],"license":"MIT","languages":["Python","TypeScript","JavaScript","CSS"],"capabilities":["Self-hosted filament spool inventory service (FastAPI backend + web UI)","Tracks vendor, material, color hex, and remaining weight","Extrusion usage sync with Moonraker/OctoPrint and NFC/RFID tag scanning"],"workflows":["Docker/Python daemon queried by Moonraker/OctoPrint during prints to deduct filament grams automatically"],"input_formats":["json_rest_api","nfc_rfid_tag"],"output_formats":["json_rest_api"],"cli_or_api_flags":["REST API endpoints: /filament/...","/spool/...","/vendor/...","/tag/scan"],"three_mf_metadata_schema":"not_applicable (complements project_settings.config filament_colour[]/filament_type[] by mapping virtual AMS/MMU slots to physical spool weights).","architectural_lessons_for_forma_print":"Shows how forma-print's estimated part + purge grams (dfm.rs) can feed inventory/spool checks before dispatching a job.","source_verified":true,"availability_notes":"Open-source (MIT).","relevance_to_forma_print":"Filament mass/color-slot accounting companion to profiles.rs and dfm.rs."}+{"id":"obico_server","name":"obico-server","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/TheSpaghettiDetective/obico-server","source_urls":["https://github.com/TheSpaghettiDetective/obico-server","https://www.obico.io/docs/server-guides/"],"license":"AGPL-3.0","languages":["Python","JavaScript","Go Template"],"capabilities":["Self-hostable AI print-failure (spaghetti) detection server with ML webcam frame inference","Remote printer monitoring and tunnelled web UI access","Automatic pause triggers and webhook alerts"],"workflows":["Docker Compose self-hosted server","Obico Cloud receiving snapshots/events from OctoPrint plugin or moonraker-obico"],"input_formats":["jpeg_webcam_frames","gcode","json_events"],"output_formats":["json_rest_api","pause_cancel_alerts"],"cli_or_api_flags":["REST /api/v1/: /api/v1/printers/","/api/v1/prints/","/api/v1/gcodefiles/","/api/v1/octo/pic/","/api/v1/octo/printer_events/"],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Illustrates closed-loop runtime failure detection (post-dispatch) as distinct from pre-print geometric DFM (forma-print).","source_verified":true,"availability_notes":"Open-source (AGPL-3.0).","relevance_to_forma_print":"Runtime monitoring counterpart in the broader print stack (R5 non-replacement boundary)."}+{"id":"moonraker_obico","name":"moonraker-obico","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/TheSpaghettiDetective/moonraker-obico","source_urls":["https://github.com/TheSpaghettiDetective/moonraker-obico"],"license":"AGPL-3.0","languages":["Python"],"capabilities":["Moonraker client agent streaming Klipper status (127.0.0.1:7125) and local camera snapshots to obico-server","Executes pause/resume/cancel actions with reconnect backoff"],"workflows":["Background systemd service installed alongside Moonraker"],"input_formats":["moonraker_json_rpc","webcam_mjpeg"],"output_formats":["obico_rest_api","moonraker_pause_commands"],"cli_or_api_flags":["Daemon configured via moonraker-obico.cfg; consumes Moonraker port 7125 JSON-RPC."],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Reference pattern for a lightweight sidecar daemon bridging local Moonraker JSON-RPC to external intelligence.","source_verified":true,"availability_notes":"Open-source (AGPL-3.0).","relevance_to_forma_print":"Pattern reference for Tier 3 printer_api.rs Moonraker polling."}+{"id":"chitui","name":"ChitUI","category":"host_fleet_spool","repo_or_primary_url":"https://github.com/jangrewe/ChitUI","source_urls":["https://github.com/jangrewe/ChitUI"],"license":"Unspecified (no LICENSE file present in repository)","languages":["Python","JavaScript","HTML","CSS"],"capabilities":["Web UI for resin printers implementing Chitubox SDCP 3.0 (Simple Device Control Protocol)","Discovers printers via LAN UDP broadcast","Exposes browser monitoring and control on port 54780"],"workflows":["python main.py","Docker with --network=host (required for UDP discovery)"],"input_formats":["sdcp_3_0_udp_websocket"],"output_formats":["web_ui_http_54780","sdcp_3_0_commands"],"cli_or_api_flags":["python main.py (serves HTTP on port 54780); communicates via Chitubox SDCP 3.0 UDP/WebSocket protocol."],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Shows SDCP 3.0 LAN protocol exists for Elegoo/Chitubox-based resin printers (elegoo_mars_5_ultra, elegoo_saturn_4_ultra), though lack of a declared license prevents direct code reuse.","source_verified":true,"availability_notes":"Public source repo on GitHub, but no LICENSE file is present (all rights reserved by default until licensed).","relevance_to_forma_print":"Documents LAN protocol options for Elegoo MSLA printers."}+{"id":"simplyprint","name":"SimplyPrint","category":"host_fleet_spool","repo_or_primary_url":"https://simplyprint.io","source_urls":["https://simplyprint.io","https://apidocs.simplyprint.io"],"license":"Proprietary SaaS (Free tier up to 2 printers; paid per-printer subscriptions)","languages":["unavailable (closed-source cloud SaaS)"],"capabilities":["Cloud fleet management over OctoPrint plugin, native Moonraker [simplyprint] module, PrusaLink, and Bambu LAN mode","Browser slicer, print queue, and webhooks","OAuth2/API keys, llms.txt, and api/index.json for AI agents"],"workflows":["Cloud dashboard","HTTPS REST/webhook automation (apidocs.simplyprint.io)"],"input_formats":["stl","3mf","gcode","https_rest"],"output_formats":["https_rest_json","webhooks"],"cli_or_api_flags":["HTTPS REST API + webhooks (apidocs.simplyprint.io)","OAuth2 & API keys","llms.txt + api/index.json (backend implementation closed)"],"three_mf_metadata_schema":"Proprietary cloud ingestion (details not open-sourced).","architectural_lessons_for_forma_print":"Validates native Moonraker integration + llms.txt/MCP-friendly API design, while showing recurring SaaS cost and cloud dependency vs. forma-print's local pure-Rust design.","source_verified":true,"availability_notes":"Closed-source commercial SaaS; public API docs exist at apidocs.simplyprint.io.","relevance_to_forma_print":"Explicit closed SaaS contrast entry."}+{"id":"printago","name":"Printago","category":"host_fleet_spool","repo_or_primary_url":"https://printago.io","source_urls":["https://printago.io","https://docs.printago.io"],"license":"Proprietary SaaS (Free monitoring tier; ~$4-$8/concurrent production slot/mo; self-hosted enterprise option)","languages":["unavailable (closed-source SaaS; embeds OrcaSlicer headless)"],"capabilities":["Print-farm SaaS with 300+ REST endpoints and live OpenAPI spec","MQTT/WebSocket telemetry, CIDR-scoped API keys, and store sync","Automated headless OrcaSlicer .3mf slicing and queueing"],"workflows":["Cloud/enterprise farm queue driven via web UI, REST API, MQTT, or AI agent skills"],"input_formats":["3mf","stl","scad","https_rest"],"output_formats":["https_rest_json","mqtt","websocket"],"cli_or_api_flags":["300+ REST endpoints (live OpenAPI spec in user portal)","MQTT & WebSocket streams (source code closed)"],"three_mf_metadata_schema":"Consumes OrcaSlicer/Bambu .3mf (Metadata/project_settings.config, plate_N.gcode, slice_info.config) as documented in Printago engineering posts.","architectural_lessons_for_forma_print":"Demonstrates real-world commercial headless OrcaSlicer .3mf orchestration and production-slot queuing, reinforcing forma-print's focus on pre-slice DFM + valid .3mf generation without building a SaaS farm manager.","source_verified":true,"availability_notes":"Closed-source commercial SaaS; public docs at docs.printago.io.","relevance_to_forma_print":"Explicit closed SaaS contrast entry."}+{"id":"klipper","name":"Klipper","category":"firmware","repo_or_primary_url":"https://github.com/Klipper3d/klipper","source_urls":["https://github.com/Klipper3d/klipper","https://www.klipper3d.org"],"license":"GPL-3.0","languages":["Python","C","C++"],"capabilities":["Host-MCU split firmware (Linux Python host klippy + C helpers + real-time C MCU)","Multi-MCU boards, Input Shaping (ADXL345 accelerometer resonance compensation), and Pressure Advance","Smooth look-ahead kinematics, Jinja2 macros, and runtime printer.cfg edits without reflashing"],"workflows":["Runs on Raspberry Pi/SBC paired with Moonraker (/tmp/klippy_uds API server) + Mainsail/Fluidd"],"input_formats":["gcode","printer.cfg","klippy_uds_json"],"output_formats":["mcu_step_protocol","serial_gcode_responses","klippy_uds_json"],"cli_or_api_flags":["klippy.py CLI + Unix domain socket JSON API (/tmp/klippy_uds)","G-code extended commands: SET_PRESSURE_ADVANCE, SHAPER_CALIBRATE, BED_MESH_CALIBRATE"],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Input Shaping + Pressure Advance + high-acceleration CoreXY kinematics inform voron_24_* and creality_k1c profile tolerances and Klipper G-code compatibility.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Primary firmware for Voron/Creality K-series profiles and Moonraker Tier 3 dispatch."}+{"id":"marlin","name":"Marlin","category":"firmware","repo_or_primary_url":"https://github.com/MarlinFirmware/Marlin","source_urls":["https://github.com/MarlinFirmware/Marlin","https://marlinfw.org"],"license":"GPL-3.0","languages":["C++","C"],"capabilities":["Monolithic embedded C++ firmware running directly on 8-bit/32-bit printer mainboards","Linear Advance, Input Shaping, UBL/ABL bed leveling, IDEX/multi-extruder, and thermal runaway protection","Configured at compile time via Configuration.h and Configuration_adv.h"],"workflows":["Compiled via PlatformIO/Arduino and flashed to MCU","Driven via SD card or USB serial hosts (OctoPrint, Pronsole, gcode-cli)"],"input_formats":["gcode","configuration_h"],"output_formats":["serial_ok_temp_responses","lcd_ui"],"cli_or_api_flags":["Serial G-code protocol (G0-G3, G28, G29, M104/M109, M140/M190, M112, M900 Linear Advance); no built-in HTTP API."],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Explains why non-networked Marlin printers rely on OctoPrint/Pronsole/SD-card bridges rather than direct HTTP endpoints.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Baseline firmware for budget/legacy FDM printers and OctoPrint Tier 3 integration."}+{"id":"reprapfirmware","name":"RepRapFirmware","category":"firmware","repo_or_primary_url":"https://github.com/Duet3D/RepRapFirmware","source_urls":["https://github.com/Duet3D/RepRapFirmware","https://docs.duet3d.com"],"license":"GPL-3.0","languages":["C++","C","Go"],"capabilities":["Object-oriented C++ 32-bit firmware for Duet boards featuring a live JSON Object Model","Standalone web server + OpenAPI HTTP endpoints (rr_model, rr_connect)","CAN-FD expansion toolboards (Duet 3), SBC/Duet Software Framework (DSF) REST mode, and runtime SD config.g macros"],"workflows":["Standalone Wi-Fi/Ethernet web UI (Duet Web Control)","SBC REST API configured at runtime via G-code macro files"],"input_formats":["gcode","config_g_macros"],"output_formats":["json_object_model","http_rest_api","can_fd"],"cli_or_api_flags":["HTTP endpoints: rr_connect","rr_model","rr_gcode","rr_upload","rr_filelist (plus DSF REST API in SBC mode)"],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Structured live Object Model (rr_model) is an exemplary telemetry contract for machine state, sensors, and fault reporting.","source_verified":true,"availability_notes":"Open-source (GPL-3.0, with minor vendor HAL clauses).","relevance_to_forma_print":"Reference architecture for deterministic printer-API state queries."}+{"id":"prusa_firmware_buddy","name":"Prusa-Firmware-Buddy","category":"firmware","repo_or_primary_url":"https://github.com/prusa3d/Prusa-Firmware-Buddy","source_urls":["https://github.com/prusa3d/Prusa-Firmware-Buddy","https://github.com/prusa3d/Prusa-Firmware-Buddy/blob/master/LICENSE.md"],"license":"Firmware code: GPL-3.0; Graphics/design: CC-BY-NC-SA-4.0; Fonts: Free/CC-BY-SA-4.0","languages":["C++","C","Python","Rust (tooling/components)"],"capabilities":["FreeRTOS + LwIP embedded firmware for 32-bit STM32 Prusa printers (MINI/+, MK3.5, MK3.9, MK4/S, XL, CORE One)","Load-cell first-layer probing, Input Shaping, and modular toolchanging (XL)",".bgcode streaming and built-in PrusaLink HTTP /api/v1/ server"],"workflows":["Built via python utils/build.py","Natively serves PrusaLink LAN REST API and Prusa Connect uplink without an external Raspberry Pi"],"input_formats":["gcode","bgcode"],"output_formats":["prusalink_rest_api","prusa_connect_telemetry","lcd_ui"],"cli_or_api_flags":["Embedded PrusaLink HTTP REST /api/v1/ (status, storages, job)","Build CLI: python utils/build.py"],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Shows how modern OEM firmware embeds PrusaLink /api/v1/ directly on MCU + LwIP and uses .bgcode to compress/embed thumbnails and metadata.","source_verified":true,"availability_notes":"Dual-licensed repo (GPL-3.0 code, CC-BY-NC-SA-4.0 graphics/design).","relevance_to_forma_print":"Firmware backing prusa_mk4s, prusa_core_one, and prusa_xl profiles."}+{"id":"smoothieware","name":"Smoothieware","category":"firmware","repo_or_primary_url":"https://github.com/Smoothieware/Smoothieware","source_urls":["https://github.com/Smoothieware/Smoothieware","http://smoothieware.org/"],"license":"GPL-3.0","languages":["C++","C","Python"],"capabilities":["Modular event-driven C++ firmware for 32-bit ARM boards (Smoothieboard LPC17xx, V2 STM32H7)","Supports RepRap 3D printing and Grbl CNC/laser dialects (grbl_mode)","Configured at runtime via SD config text file"],"workflows":["USB/UART serial host streaming","SD card printing"],"input_formats":["gcode","sd_config_txt"],"output_formats":["serial_responses"],"cli_or_api_flags":["Serial G-code (RepRap & Grbl dialects; M999 clear halt); optional Ethernet web/telnet module."],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Early pioneer of runtime text config on 32-bit ARM without recompilation.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Historical 32-bit firmware reference in the RepRap lineage."}+{"id":"grbl","name":"Grbl","category":"firmware","repo_or_primary_url":"https://github.com/gnea/grbl","source_urls":["https://github.com/gnea/grbl","https://github.com/gnea/grbl/blob/master/COPYING","https://github.com/gnea/grbl/wiki"],"license":"GPL-3.0","languages":["C","C++"],"capabilities":["Cycle-accurate AVR ATmega328P CNC/laser motion controller written in C","Jitter-free 30 kHz step pulses with 16-motion look-ahead planning and arcs","Real-time status and feed-hold overrides"],"workflows":["Driven over USB serial (115200 baud) by G-code senders (gcode-cli, UGS, CNCjs)"],"input_formats":["gcode"],"output_formats":["serial_ok_error_alarm"],"cli_or_api_flags":["Serial protocol: ok/error:N/ALARM:N responses + single-byte real-time commands (?, !, ~, Ctrl-X); $$ EEPROM settings."],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Demonstrates strict LF-only line framing (CRLF confuses Grbl) and why gcode-cli exists.","source_verified":true,"availability_notes":"Open-source (GPL-3.0 verified in COPYING).","relevance_to_forma_print":"Contrast subtractive/laser CNC firmware (no thermal/extrusion stack) and serial flow-control protocol reference."}+{"id":"fluidnc","name":"FluidNC","category":"firmware","repo_or_primary_url":"https://github.com/bdring/FluidNC","source_urls":["https://github.com/bdring/FluidNC","https://github.com/bdring/FluidNC/blob/main/LICENSE"],"license":"GPL-3.0","languages":["C++","C","JavaScript","HTML","Python"],"capabilities":["ESP32 object-oriented successor to Grbl_ESP32 with HAL for spindles/lasers/toolchangers","Runtime config.yaml stored on flash ($Config/Filename=)","Grbl-compatible USB serial and built-in Wi-Fi WebUI (HTTP /files, /upload + WebSocket port 81)"],"workflows":["Browser WebUI over ESP32 Wi-Fi","Grbl-compatible USB serial senders"],"input_formats":["gcode","yaml"],"output_formats":["serial_grbl_protocol","http_websocket_webui"],"cli_or_api_flags":["Serial Grbl commands ($Config/Filename=...) + HTTP (/files, /upload) + WebSocket port 81."],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Clean YAML runtime machine configuration + lightweight embedded HTTP/WS API on resource-constrained hardware.","source_verified":true,"availability_notes":"Open-source (GPL-3.0 verified in LICENSE).","relevance_to_forma_print":"Modern CNC/laser firmware counterpart to Klipper/RepRapFirmware."}+{"id":"openscad","name":"OpenSCAD","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/openscad/openscad","source_urls":["https://github.com/openscad/openscad","https://github.com/openscad/openscad/blob/master/COPYING","https://www.openscad.org"],"license":"GPL-2.0-or-later (with special CGAL linking exception)","languages":["C++","C","OpenSCAD"],"capabilities":["Script-only CSG CAD compiler supporting CGAL and fast parallel Manifold backends","Customizer JSON parameter sets and lazy-union multi-part 3MF export","Headless PNG/STL/3MF/SVG/DXF CLI rendering"],"workflows":["Desktop preview/editor","Headless openscad -o out.3mf model.scad in CI/agent loops"],"input_formats":["scad","csg","json","stl","off","dxf","svg"],"output_formats":["stl","3mf","amf","off","dxf","svg","pdf","png","csg"],"cli_or_api_flags":["-o <file>","-D <var=val>","-p <customizer.json>","-P <setName>","--export-format <asciistl|binstl|...>","--backend <CGAL|Manifold>","--enable <lazy-union|manifold|all>","--camera <...>","--imgsize <w,h>","--autocenter","--viewall","-v / --version","-h / --help"],"three_mf_metadata_schema":"Exports core 3D/3dmodel.model XML meshes (multi-object components when --enable lazy-union is enabled); does not emit Bambu/Prusa slicer .config files.","architectural_lessons_for_forma_print":"Proves script-first CLI (-o, --backend, --imgsize) works well for programmatic CAD, while Forma's pure-Rust engine avoids OpenSCAD's CGAL slowness and lack of .step export.","source_verified":true,"availability_notes":"Open-source (GPL-2.0-or-later + CGAL exception verified in COPYING); no native STEP export.","relevance_to_forma_print":"Primary baseline for programmatic 3D-printable CAD; forma-print adds DFM + slicer-native multi-color .3mf + .step."}+{"id":"cadquery","name":"CadQuery","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/CadQuery/cadquery","source_urls":["https://github.com/CadQuery/cadquery","https://github.com/CadQuery/cadquery/blob/master/LICENSE","https://cadquery.org"],"license":"Apache-2.0","languages":["Python"],"capabilities":["Python parametric B-Rep CAD framework built on Open CASCADE (OCP) using fluent workplane chaining","Topological selectors (.faces(\">Z\").edges()) and assemblies","Exact fillets, lofts, sweeps, and lossless STEP + tessellated STL/3MF export"],"workflows":["Headless Python scripts in CI/servers","Jupyter notebooks or CQ-Editor GUI"],"input_formats":["py","step","brep","dxf"],"output_formats":["step","stl","3mf","amf","svg","dxf","vrml"],"cli_or_api_flags":["Python library API (cadquery.Workplane, Assembly, exporters.export, selectors); no standalone built-in CLI."],"three_mf_metadata_schema":"Exports core .3mf triangle meshes via OCCT/lib3mf-style tessellation; no Bambu/Prusa slicer .config metadata.","architectural_lessons_for_forma_print":"Topological selector pattern (.faces(\">Z\")) parallels Forma's semantic selectors (top, top_rim), while Forma avoids OCCT's ~100+ MB native C++ dependency footprint.","source_verified":true,"availability_notes":"Open-source (Apache-2.0 verified in LICENSE).","relevance_to_forma_print":"Major Python B-Rep reference for parametric mechanical parts and STEP/3MF tessellation."}+{"id":"build123d","name":"build123d","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/gumyr/build123d","source_urls":["https://github.com/gumyr/build123d"],"license":"Apache-2.0","languages":["Python"],"capabilities":["Modern Python B-Rep CAD library on OCCT (OCP) separating 1D/2D/3D classes","Stateful Builder Mode (context managers) and stateless Algebra Mode (+/-/& operators)","ocp_vscode live preview and STEP/STL/3MF/glTF export"],"workflows":["Python scripts","VS Code ocp_vscode extension","AI-agent code generation pipelines"],"input_formats":["py","step","brep","svg","dxf"],"output_formats":["step","stl","3mf","svg","dxf","gltf"],"cli_or_api_flags":["Python API (BuildPart, BuildSketch, BuildLine, Algebra operators, export_step, export_stl, export_gltf); no standalone CLI."],"three_mf_metadata_schema":"Exports core 3MF meshes without Bambu/Prusa slicer .config metadata.","architectural_lessons_for_forma_print":"Stateless Algebra mode (+/-) mirrors Forma-Pipe composability; Shpigford/nurb itself uses build123d + trimesh for agentic CAD + print checks.","source_verified":true,"availability_notes":"Open-source (Apache-2.0).","relevance_to_forma_print":"Direct architectural inspiration and primary modern Python CAD comparator."}+{"id":"bosl2","name":"BOSL2 (The Belfry OpenSCAD Library v2)","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/BelfrySCAD/BOSL2","source_urls":["https://github.com/BelfrySCAD/BOSL2","https://github.com/BelfrySCAD/BOSL2/wiki"],"license":"BSD-2-Clause","languages":["OpenSCAD"],"capabilities":["Comprehensive OpenSCAD library providing relative attach()/position() anchors and edge rounding/chamfer masks","Bezier/NURBS/skinning, involute gears, and printable threads/screws","3D-printing clearance/slop utilities ($slop)"],"workflows":["Included inside .scad scripts (include <BOSL2/std.scad>) compiled by OpenSCAD GUI or CLI"],"input_formats":["scad"],"output_formats":["scad_geometry"],"cli_or_api_flags":["OpenSCAD module/function API (attachable, cuboid(..., rounding=...), threaded_rod, $slop); invoked via openscad CLI."],"three_mf_metadata_schema":"not_applicable (library inside OpenSCAD).","architectural_lessons_for_forma_print":"$slop global clearance variable, relative attachment frames, and printable-thread/teardrop/snap-fit primitives directly inspire forma-print Tier 1 clearance checks (dfm.rs) and Tier 2 ops_print.rs.","source_verified":true,"availability_notes":"Open-source (BSD-2-Clause).","relevance_to_forma_print":"Blueprint reference for print-native CAD ops and tolerance modeling."}+{"id":"fornjot","name":"Fornjot","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/hannobraun/fornjot","source_urls":["https://github.com/hannobraun/fornjot","https://github.com/hannobraun/fornjot/blob/main/LICENSE.md","https://hannobraun.com"],"license":"0BSD (Zero-Clause BSD)","languages":["Rust","WGSL"],"capabilities":["Experimental pure-Rust B-Rep CAD kernel (now archived/shut down)","2D sketches, straight extrusions/sweeps, early CSG, and STL/3MF export"],"workflows":["Code-first Rust model crates compiled against Fornjot kernel (no longer actively maintained)"],"input_formats":["rust_model_crates"],"output_formats":["stl","3mf"],"cli_or_api_flags":["Rust crate/app API; project archived before stable CLI/kernel completion."],"three_mf_metadata_schema":"Basic 3MF mesh export only; no slicer .config metadata.","architectural_lessons_for_forma_print":"Cautionary lesson on from-scratch pure-Rust B-Rep complexity — explains why forma succeeded with a fast watertight polyhedral/CSG kernel (~1.7 MB) + faceted STEP + pure-Rust forma-print DFM rather than chasing full NURBS B-Rep.","source_verified":true,"availability_notes":"Archived / shut down (\"This project has been shut down. Its goals were never reached.\"); 0BSD license verified in LICENSE.md.","relevance_to_forma_print":"Pure-Rust CAD ecosystem precedent and scope validation."}+{"id":"zoo_kcl","name":"Zoo Design Studio / KCL / KittyCAD CLI","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/KittyCAD/modeling-app","source_urls":["https://github.com/KittyCAD/modeling-app","https://github.com/KittyCAD/cli","https://zoo.dev/docs/cli/manual"],"license":"MIT (modeling-app, cli, kcl-lib); Proprietary Cloud Geometry Engine (Zoo API)","languages":["Rust (kcl-lib, zoo CLI)","TypeScript / React (modeling-app)","KCL"],"capabilities":["Hybrid code-first & GUI CAD around KCL (KittyCAD Language) with bidirectional code-to-GUI sync","kcl-lib Rust parser/AST and zoo CLI (zoo kcl snapshot)","Text-to-CAD and cloud Vulkan GPU-accelerated B-Rep streaming"],"workflows":["Electron/web Zoo Design Studio","zoo CLI calling Zoo's hosted cloud geometry API"],"input_formats":["kcl","step","stl","obj","gltf"],"output_formats":["step","stl","obj","gltf","png","jpeg"],"cli_or_api_flags":["zoo CLI (e.g. zoo kcl snapshot): -t / --output-format <png|jpeg>","--angle <front|top|right-side|four-ways|iso>","--camera-style <ortho|perspective>","--camera-padding <val>","--session <id>","--allow-errors","--host <url>","-d / --debug","-h / --help"],"three_mf_metadata_schema":"none (centers on .kcl, .step, .stl, .gltf).","architectural_lessons_for_forma_print":"Bidirectional code-first DSL + --angle four-ways snapshot CLI is closely aligned with forma (render_quad_png_bytes); however, Zoo's core geometry engine requires proprietary cloud GPUs, whereas forma + forma-print runs 100% locally in milliseconds offline.","source_verified":true,"availability_notes":"Client/CLI/kcl-lib are MIT, while the backend GPU CAD geometry engine is proprietary cloud SaaS.","relevance_to_forma_print":"Key modern code-first CAD comparator highlighting forma-print's offline pure-Rust advantage."}+{"id":"printrun_pronsole","name":"Printrun / pronsole","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/kliment/Printrun","source_urls":["https://github.com/kliment/Printrun","https://pronterface.com"],"license":"GPL-3.0-or-later","languages":["Python","Cython","C"],"capabilities":["Pure-Python RepRap host suite (printcore.py library, pronsole.py interactive/scriptable CLI host, pronterface.py GUI)","Serial G-code streaming, SD card upload/print, and RPC server"],"workflows":["Scripted or interactive USB serial control (python pronsole.py -e \"connect /dev/ttyUSB0 115200\" -e ...)"],"input_formats":["gcode","stl"],"output_formats":["serial_gcode_stream"],"cli_or_api_flags":["pronsole.py flags: -h / --help","-e / --execute <cmd>","-v / --verbose","-c / --conf <file>","Interactive commands: connect <port> <baud>, block_until_online, load <file.gcode>, upload <local> <remote>, print"],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"-e chained startup command execution is a clean pattern for scriptable printer-host control over legacy serial printers.","source_verified":true,"availability_notes":"Open-source (GPL-3.0-or-later).","relevance_to_forma_print":"CLI serial-host reference alongside gcode-cli."}+{"id":"gcode_cli","name":"gcode-cli","category":"programmatic_cad_cli","repo_or_primary_url":"https://github.com/hzeller/gcode-cli","source_urls":["https://github.com/hzeller/gcode-cli"],"license":"Unspecified (no LICENSE file present in repository)","languages":["C++"],"capabilities":["Ultra-minimal C++ command-line sender that strips ; comments and CRLF->LF","Streams G-code line-by-line over serial, TCP, or stdin/stdout using ok/error flow control for Marlin, Grbl, and BeagleG"],"workflows":["Unix pipe/CLI invocation (gcode-cli /dev/ttyUSB0,b115200 part.gcode)"],"input_formats":["gcode"],"output_formats":["serial_stream","tcp_stream","stdout"],"cli_or_api_flags":["-h","-b <num_outstanding_blocks>","-F (disable flow control)","<conn_string> (/dev/ttyUSB0,b115200 | host:port | - | -crtscts)"],"three_mf_metadata_schema":"not_applicable","architectural_lessons_for_forma_print":"Minimal Unix-pipe philosophy (stdin/stdout, tiny C++ binary) mirrors forma-print's zero-bloat CLI design, though absence of a LICENSE file prevents code copying.","source_verified":true,"availability_notes":"Public GitHub repo (hzeller/gcode-cli), but no LICENSE file exists in master.","relevance_to_forma_print":"Minimalist serial/TCP G-code sender reference."}+{"id":"nurb","name":"nurb","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/Shpigford/nurb","source_urls":["https://github.com/Shpigford/nurb","https://nurb.app"],"license":"FSL-1.1-MIT (converts to MIT 2 years after each GitHub release)","languages":["Python","TypeScript","React","Rust (Tauri v2)"],"capabilities":["Agent-first parametric 3D-printable CAD powered by build123d/OCCT, trimesh, and Tauri v2 desktop workbench","Long-lived local HTTP/WebSocket/MCP server (serve.py port 7373) with SQLite persistence and 240s warm engine_run.py worker","15 B-rep printability rules (checks.py) with dual message/plain text and face-pinned probe.py coordinates","@part parameter sliders, measured() / measurements.toml provenance guard, stand() diagonal orientation with break-away fins, 27 printers.toml profiles, zero-GPU numpy 2x2 raster.py, and OrcaSlicer/BambuStudio/PrusaSlicer CLI bridge (slicing.py)"],"workflows":["Tauri v2 desktop app bundling uv, CPython >=3.13, and @nurb/workbench Three.js Z-up viewer","External AI agents connecting via bearer-token /mcp JSON-RPC over serve.py (standalone PyPI/cli.py removed in v1.0+)"],"input_formats":["py","toml","3mf","stl","step"],"output_formats":["3mf","stl","step","glb","png"],"cli_or_api_flags":["python -m nurb.serve (port 7373, bearer-token /mcp + SameOrigin /ws)","MCP tools (tools.json): list_projects, get_project, create_project, read_guide, pin_spec, amend_spec, read_measurements, record_measurement, write_part_source, edit_part_source, run_build, set_label, read_plate, set_plate (standalone cli.py removed in v1.0+)"],"three_mf_metadata_schema":"Stdlib-only (zipfile + xml.etree.ElementTree) reader threemf.py supporting Bambu/Orca 3D/Objects/*.model production paths and Metadata/model_settings.config; engine_run.py writes multi-color .3mf via builder.write_3mf and passes --load-settings/--load-filaments/--slice to OrcaSlicer/BambuStudio.","architectural_lessons_for_forma_print":"Validates single-body gating before downstream checks, 15-rule DFM taxonomy (hole_ceiling, warp_risk, pin, stability, concave_cosmetic), 2x2 composite PNG to cut VLM tokens 4x, central printer profiles, and stdlib .3mf handling — while its ~45s OCCT cold boot and heavy Python/Tauri/SQLite daemon motivate forma-print's stateless pure-Rust <25ms zero-bloat design.","source_verified":true,"availability_notes":"Source-available under FSL-1.1-MIT (non-competing use; converts to MIT after 2 years); embeds LGPL-2.1 OCCT via Apache-2.0 OCP/build123d and mcp 2.2.0 (~27 MB across 27 packages); standalone CLI removed in v1.0+.","relevance_to_forma_print":"Primary modern agentic-CAD reference architecture and direct efficiency/stack comparison baseline (R1.6, R5)."}+{"id":"nurb_benchmarks","name":"nurb-benchmarks","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/Shpigford/nurb-benchmarks","source_urls":["https://github.com/Shpigford/nurb-benchmarks","https://nurb.dev/benchmarks"],"license":"FSL-1.1-MIT","languages":["Python"],"capabilities":["Headless B-rep benchmark suite evaluating LLM coding agents on 3D-printable part design","6 tasks across Spec (cable_clip, bit_block), Function (bundle_holder, pole_rest, valve_knob), and Judgment (leg_cup) classes","Gate-then-grade scoring (timeout + single valid solid gate, then 0.3 printability + 0.5 B-rep assertions + 0.2 flex probes)","Published multi-model leaderboard (REPORT.md) tracking pass@1, pass@3, tokens, cost, and wall time"],"workflows":["Headless Python benchmark runner executing candidate build123d scripts in isolated workers and grading exported B-rep geometry"],"input_formats":["py","toml"],"output_formats":["brep","json","markdown"],"cli_or_api_flags":["Python benchmark harness over nurb>=0.23, shapely>=2, networkx>=3, rtree>=1 (grading entrypoint isolated from candidate script)."],"three_mf_metadata_schema":"not_applicable (grades candidate scripts on B-rep solids and nurb printability rules).","architectural_lessons_for_forma_print":"Gate-then-grade scoring (valid single manifold solid before DFM grading) and int-parameterized flex probes prevent LLM overfitting to fixed dimensions; REPORT.md data (3.2k-593k tokens, 98s-1140s wall time) provides empirical cost/latency evidence for R5.","source_verified":true,"availability_notes":"Open/source-available under FSL-1.1-MIT; separated from Shpigford/nurb in Aug 2026 to keep benchmark logs out of the engine repo.","relevance_to_forma_print":"Benchmark methodology reference for crates/forma-print tests and R5 efficiency comparison."}+{"id":"zoo_mcp","name":"Zoo MCP (KittyCAD/mcp)","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/KittyCAD/mcp","source_urls":["https://github.com/KittyCAD/mcp","https://github.com/KittyCAD/modeling-app"],"license":"MIT (zoo-mcp client/server); Proprietary Cloud Geometry Engine (Zoo API)","languages":["Python","KCL"],"capabilities":["Official MCP server wrapping Zoo/KittyCAD Text-to-CAD and KCL execution","Mock preflight validation + real cloud KCL execution (execute_kcl)","Multi-angle rendering snapshots (snapshot) via Zoo cloud GPU engine"],"workflows":["Run via uvx zoo-mcp or standalone PyInstaller binaries from AI coding agents over stdio MCP"],"input_formats":["kcl","step","stl","obj","gltf"],"output_formats":["step","stl","gltf","glb","obj","3dm","png"],"cli_or_api_flags":["uvx zoo-mcp / PyInstaller binaries","MCP tools: execute_kcl (mock preflight + real execution), snapshot"],"three_mf_metadata_schema":"none (focuses on KCL scripts and STEP/STL/glTF/OBJ/3DM cloud exports).","architectural_lessons_for_forma_print":"Mock-preflight + snapshot tool ergonomics show clean agent loop feedback, while cloud API latency, API key requirement, and lack of local DFM/.3mf metadata highlight forma-print's offline pure-Rust advantage.","source_verified":true,"availability_notes":"MCP server code is MIT, but geometry execution depends on Zoo's proprietary cloud GPU API.","relevance_to_forma_print":"Direct modern agentic-CAD MCP comparator for R1.6 and R5."}+{"id":"cadam","name":"CADAM","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/Adam-CAD/CADAM","source_urls":["https://github.com/Adam-CAD/CADAM","https://adam.new/cadam"],"license":"GPL-3.0","languages":["TypeScript","JavaScript","OpenSCAD"],"capabilities":["Browser-based Text-to-CAD and Image-to-CAD studio (React 19, TanStack Start, Three.js/R3F)","Compiles generated code in-browser via OpenSCAD WASM with BOSL, BOSL2, and MCAD libraries","Automatic parameter extraction into live UI sliders"],"workflows":["Hosted web app (adam.new/cadam) or self-hosted TanStack Start + Supabase app"],"input_formats":["text_prompt","image","scad"],"output_formats":["stl","scad","dxf"],"cli_or_api_flags":["Web application UI and server routes; no standalone headless CLI or MCP server documented."],"three_mf_metadata_schema":"none (exports .stl, .scad, and .dxf without slicer-native .3mf metadata).","architectural_lessons_for_forma_print":"Demonstrates browser WASM compilation + automatic parameter sliders, while showing gap in deterministic DFM checks, .step export, and multi-color .3mf packaging.","source_verified":true,"availability_notes":"Open-source (GPL-3.0).","relevance_to_forma_print":"Web agentic-CAD reference for WASM UX and parameter sliders."}+{"id":"cadmium","name":"CADmium","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/CADmium-Co/CADmium","source_urls":["https://github.com/CADmium-Co/CADmium"],"license":"Elastic-2.0","languages":["Rust","TypeScript","Svelte","WGSL"],"capabilities":["Local-first browser and desktop (Tauri) parametric CAD built on the Rust Truck B-rep/NURBS kernel","SvelteKit + Three.js (Threlte) viewport with WASM kernel","Exports STEP, OBJ, SVG, DXF, and native .cadmium JSON"],"workflows":["Local web app or Tauri desktop prototype"],"input_formats":["cadmium_json","sketch_features"],"output_formats":["step","obj","cadmium","svg","dxf"],"cli_or_api_flags":["Browser/Tauri GUI prototype; no headless printability CLI or MCP server."],"three_mf_metadata_schema":"none (no .3mf export or printability analysis implemented).","architectural_lessons_for_forma_print":"Illustrates Rust WASM + Tauri local-first CAD architecture using Truck B-rep, and reinforces that headless DFM + slicer-native .3mf remain missing in Rust CAD prototypes.","source_verified":true,"availability_notes":"Source-available under Elastic-2.0; repository is an archived/inactive prototype.","relevance_to_forma_print":"Rust local-first CAD precedent contrasting polyhedral forma-print with Truck B-rep."}+{"id":"agentcad","name":"agentcad","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/jdilla1277/agentcad","source_urls":["https://github.com/jdilla1277/agentcad","https://agentcad.dev"],"license":"Apache-2.0","languages":["Python","JavaScript"],"capabilities":["CLI + MCP workflow enforcing Inspect -> Specify -> Build -> Validate -> Deliver for LLM CAD","Uses build123d by default (optional CadQuery) with structured JSON stdout","Generates 4-view PNGs, B-rep diffing, and local .agentcad/reviews spatial comments"],"workflows":["Headless CLI with structured JSON output","MCP server integrated into coding agents"],"input_formats":["py","step"],"output_formats":["step","stl","glb","obj","png","json"],"cli_or_api_flags":["CLI + MCP server workflow (Inspect -> Specify -> Build -> Validate -> Deliver) with structured JSON stdout, 4-view PNGs, and B-rep diffing."],"three_mf_metadata_schema":"none (exports .step, .stl, .glb, .obj without multi-color slicer .3mf metadata).","architectural_lessons_for_forma_print":"Structured JSON stdout, explicit Inspect->Validate->Deliver phases, and 4-view PNG feedback align tightly with forma-print's CLI --json + 4-view heatmap PNG + MCP workflow.","source_verified":true,"availability_notes":"Open-source (Apache-2.0).","relevance_to_forma_print":"Modern agentic-CAD CLI/MCP workflow comparator."}+{"id":"build123d_mcp","name":"build123d-mcp","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/pzfreo/build123d-mcp","source_urls":["https://github.com/pzfreo/build123d-mcp"],"license":"Apache-2.0","languages":["Python"],"capabilities":["Sandboxed persistent Python MCP session for build123d","Incremental execution (execute()), feature recognition (inspect_features), and STEP diffing (diff_step)","FDM printability & clearance checks plus SVG/DXF/PNG multi-view renders"],"workflows":["Persistent stdio MCP server driven by LLM agents over build123d/OCCT"],"input_formats":["py","step"],"output_formats":["step","stl","dxf","svg","png"],"cli_or_api_flags":["MCP tools: execute()","inspect_features","diff_step","FDM printability & clearance checks, SVG/DXF/PNG views"],"three_mf_metadata_schema":"none (exports .step, .stl, .dxf, .svg without Bambu/Prusa .3mf metadata).","architectural_lessons_for_forma_print":"Validates incremental session execution, clearance checks, and STEP diffing in agentic CAD, while relying on heavy Python/OCCT rather than sub-25ms pure Rust.","source_verified":true,"availability_notes":"Open-source (Apache-2.0).","relevance_to_forma_print":"Direct MCP + printability comparator built on build123d."}+{"id":"text_to_cadquery","name":"Text-to-CadQuery","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/Text-to-CadQuery/Text-to-CadQuery","source_urls":["https://github.com/Text-to-CadQuery/Text-to-CadQuery"],"license":"Unspecified (no explicit LICENSE file in repository)","languages":["Python"],"capabilities":["Academic fine-tuning and evaluation pipeline (~170k CadQuery annotations)","Fine-tunes CodeGPT, Gemma, GPT-2, Mistral, and Qwen to emit CadQuery Python scripts","Executes scripts to STL, renders via Blender, and scores via Chamfer Distance"],"workflows":["Offline ML training and batch evaluation scripts (Prompt -> CadQuery -> STL -> Blender render)"],"input_formats":["text_prompt","py"],"output_formats":["py","stl","png"],"cli_or_api_flags":["Python training and evaluation scripts (no interactive MCP server or printer DFM CLI)."],"three_mf_metadata_schema":"none (outputs CadQuery scripts and raw .stl for Chamfer Distance evaluation).","architectural_lessons_for_forma_print":"Demonstrates why fine-tuned or large-model code generation evaluated only on Chamfer Distance misses manufacturability constraints (overhangs, islands, clearances, wall thickness) that deterministic DFM catches.","source_verified":true,"availability_notes":"Public GitHub research repository, but no explicit LICENSE file is declared.","relevance_to_forma_print":"Academic baseline contrasting LLM geometry synthesis without DFM vs. deterministic printability verification (R5)."}+{"id":"openscad_wasm_mcp","name":"openscad-wasm-mcp","category":"modern_agentic_cad","repo_or_primary_url":"https://github.com/suapapa/openscad-wasm-mcp","source_urls":["https://github.com/suapapa/openscad-wasm-mcp"],"license":"MIT","languages":["TypeScript","JavaScript"],"capabilities":["Node.js MCP bridge over openscad-wasm","Validates OpenSCAD scripts and analyzes bounding box and triangle counts","Renders WebP previews and exports STL/OFF/CSG/DXF/SVG"],"workflows":["Stdio MCP server invoked by coding agents for OpenSCAD compilation without native OpenSCAD install"],"input_formats":["scad"],"output_formats":["stl","off","csg","dxf","svg","webp"],"cli_or_api_flags":["Node.js MCP server wrapping openscad-wasm (SCAD validation, bbox/triangle analysis, WebP render, mesh export)."],"three_mf_metadata_schema":"none (explicitly notes .3mf is currently unsupported in its openscad-wasm build).","architectural_lessons_for_forma_print":"Shows how lightweight WASM CAD MCP servers provide fast bbox/tri feedback, while lacking .3mf export, .step export, and DFM rules that forma-print provides natively in Rust.","source_verified":true,"availability_notes":"Open-source (MIT).","relevance_to_forma_print":"WASM MCP CAD comparator illustrating .3mf/DFM gaps in OpenSCAD WASM wrappers."}+{"id":"makergrid_ai","name":"MakerGrid.ai","category":"modern_agentic_cad","repo_or_primary_url":"https://makergrid.ai","source_urls":["https://makergrid.ai"],"license":"Proprietary / Closed SaaS","languages":["unavailable (closed-source cloud web app)"],"capabilities":["Commercial web app for text/sketch/image-to-3D generation (Replicate/Hugging Face backed)","Companion Blender extension for mesh refinement"],"workflows":["Hosted browser SaaS workflow + Blender add-on"],"input_formats":["text_prompt","sketch","image"],"output_formats":["unavailable (proprietary cloud export pipeline)"],"cli_or_api_flags":["GUI-only cloud web app + Blender extension; no public OSS source repository, CLI, or open MCP API verified."],"three_mf_metadata_schema":"unavailable (closed-source SaaS; no open slicer-native 3MF metadata schema documented).","architectural_lessons_for_forma_print":"Commercial contrast illustrating closed generative-3D web tools that lack deterministic parametric precision, local offline execution, and DFM verification.","source_verified":true,"availability_notes":"Proprietary / Closed SaaS; no public open-source repository verified.","relevance_to_forma_print":"Commercial contrast entry for modern AI 3D modeling tools."}diff --git a/research/rag/build_rag.py b/research/rag/build_rag.pynew file mode 100644index 0000000..cf6a296--- /dev/null+++ b/research/rag/build_rag.py@@ -0,0 +1,1056 @@+#!/usr/bin/env python3+"""Deterministic stdlib-only RAG knowledge base builder for forma-print.++Reads:+ - research/corpus/software.jsonl+ - research/corpus/manufacturers.jsonl+ - research/corpus/papers.jsonl+ - research/reports/nurb_inspection.md+ - research/schemas/rag_chunks.schema.json++Builds:+ - research/rag/forma_print_kb.sqlite (atomic <db>.tmp -> VACUUM -> integrity_check -> os.replace)+ - Optional research/rag/chunks.jsonl via --emit-chunks-jsonl+"""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import os+import re+import sqlite3+import sys+import unicodedata+from pathlib import Path+from typing import Any++REPO_ROOT = Path(__file__).resolve().parents[2]+RESEARCH_DIR = REPO_ROOT / "research"+DEFAULT_DB_PATH = RESEARCH_DIR / "rag" / "forma_print_kb.sqlite"+DEFAULT_CHUNKS_JSONL_PATH = RESEARCH_DIR / "rag" / "chunks.jsonl"+SCHEMA_PATH = RESEARCH_DIR / "schemas" / "rag_chunks.schema.json"++SOFTWARE_PATH = RESEARCH_DIR / "corpus" / "software.jsonl"+MANUFACTURERS_PATH = RESEARCH_DIR / "corpus" / "manufacturers.jsonl"+PAPERS_PATH = RESEARCH_DIR / "corpus" / "papers.jsonl"+REPORT_PATH = RESEARCH_DIR / "reports" / "nurb_inspection.md"++SCHEMA_VERSION = "1.0.0"++PROTOCOL_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (+ ("mqtts", re.compile(r"\bmqtts\b|mqtt\s+over\s+tls", re.IGNORECASE)),+ ("mqtt", re.compile(r"\bmqtt\b", re.IGNORECASE)),+ ("ftps", re.compile(r"\bftps\b|implicit\s+tls.*ftp", re.IGNORECASE)),+ ("ftp", re.compile(r"\bftp\b", re.IGNORECASE)),+ ("https", re.compile(r"\bhttps\b", re.IGNORECASE)),+ ("http", re.compile(r"\bhttp\b|http/1\.1", re.IGNORECASE)),+ ("rest", re.compile(r"\brest\b|webapi", re.IGNORECASE)),+ ("openapi", re.compile(r"\bopenapi\b", re.IGNORECASE)),+ ("websocket", re.compile(r"\bwebsockets?\b|\bws://|\bwss://", re.IGNORECASE)),+ ("json-rpc", re.compile(r"\bjson-rpc\b", re.IGNORECASE)),+ ("moonraker", re.compile(r"\bmoonraker\b", re.IGNORECASE)),+ ("sdcp", re.compile(r"\bsdcp\b", re.IGNORECASE)),+ ("sacp", re.compile(r"\bsacp\b", re.IGNORECASE)),+ ("mtconnect", re.compile(r"\bmtconnect\b", re.IGNORECASE)),+ ("can-fd", re.compile(r"\bcan-fd\b", re.IGNORECASE)),+ ("can", re.compile(r"\bcan\s+bus\b|\bcanbus\b|\bcan0\b|\bcan-fd\b", re.IGNORECASE)),+ ("serial", re.compile(r"\bserial\b|\bbaud\b", re.IGNORECASE)),+ ("usb", re.compile(r"\busb\b", re.IGNORECASE)),+ ("rtsps", re.compile(r"\brtsps\b", re.IGNORECASE)),+ ("rtsp", re.compile(r"\brtsp\b", re.IGNORECASE)),+ ("mjpeg", re.compile(r"\bmjpeg\b", re.IGNORECASE)),+ ("webrtc", re.compile(r"\bwebrtc\b", re.IGNORECASE)),+ ("mdns", re.compile(r"\bmdns\b", re.IGNORECASE)),+ ("udp", re.compile(r"\budp\b", re.IGNORECASE)),+ ("tcp", re.compile(r"\btcp\b", re.IGNORECASE)),+ ("mtls", re.compile(r"\bmtls\b", re.IGNORECASE)),+ ("tls", re.compile(r"\btls\b", re.IGNORECASE)),+ ("pppp", re.compile(r"\bpppp\b", re.IGNORECASE)),+ ("octoprint", re.compile(r"\boctoprint\b", re.IGNORECASE)),+ ("prusalink", re.compile(r"\bprusalink\b|prusa-link", re.IGNORECASE)),+ ("prusaconnect", re.compile(r"prusa\s*connect|prusa_connect", re.IGNORECASE)),+ ("grabcad", re.compile(r"\bgrabcad\b", re.IGNORECASE)),+ ("eiger", re.compile(r"\beiger\b", re.IGNORECASE)),+ ("klipper", re.compile(r"\bklipper\b", re.IGNORECASE)),+ ("marlin", re.compile(r"\bmarlin\b", re.IGNORECASE)),+ ("reprapfirmware", re.compile(r"\breprapfirmware\b|\brrf\b", re.IGNORECASE)),+ ("telnet", re.compile(r"\btelnet\b", re.IGNORECASE)),+ ("mcp", re.compile(r"\bmcp\b", re.IGNORECASE)),+ ("gcode", re.compile(r"\bg-?code\b", re.IGNORECASE)),+)+++STOPWORDS = frozenset(+ {+ "the", "and", "for", "with", "that", "this", "from", "are", "was", "were",+ "been", "being", "have", "has", "had", "into", "onto", "over", "under",+ "also", "such", "when", "where", "which", "while", "each", "all", "not",+ "but", "can", "use", "used", "using", "via", "per", "etc", "its", "their",+ "than", "then", "them", "they", "only", "both", "more", "most", "other",+ "some", "any", "may", "will", "should", "must", "non", "off", "out",+ }+)+++def fold_diacritics(text: str) -> str:+ """Fold Unicode diacritics via NFKD decomposition so lexical tokens match SQLite unicode61."""+ if text.isascii():+ return text+ return "".join(+ ch for ch in unicodedata.normalize("NFKD", text) if unicodedata.category(ch) != "Mn"+ )+++def tokenize(text: str) -> list[str]:+ """Deterministic lexical tokenizer matching both composite and split sub-tokens."""+ cleaned = re.sub(r"https?://\S+", " ", fold_diacritics(text).lower())+ tokens: list[str] = []+ for tok in re.findall(r"[a-z0-9][a-z0-9_./-]*[a-z0-9]|[a-z0-9]{2,}", cleaned):+ if tok in STOPWORDS:+ continue+ tokens.append(tok)+ if any(sep in tok for sep in ("_", "-", ".", "/")):+ for part in re.split(r"[_./-]+", tok):+ if len(part) >= 2 and part != tok and part not in STOPWORDS:+ tokens.append(part)+ return tokens+++def count_words(text: str) -> int:+ return max(1, len(re.findall(r"\S+", text)))+++def extract_protocols(*parts: Any) -> list[str]:+ joined = " ".join(_flatten_strings(parts))+ found = [name for name, pat in PROTOCOL_PATTERNS if pat.search(joined)]+ return sorted(set(found))+++def _flatten_strings(obj: Any) -> list[str]:+ if obj is None or isinstance(obj, bool):+ return []+ if isinstance(obj, str):+ return [obj]+ if isinstance(obj, (int, float)):+ return [str(obj)]+ if isinstance(obj, (list, tuple)):+ out: list[str] = []+ for item in obj:+ out.extend(_flatten_strings(item))+ return out+ if isinstance(obj, dict):+ out = []+ for val in obj.values():+ out.extend(_flatten_strings(val))+ return out+ return []+++def infer_software_tech(rec: dict[str, Any]) -> list[str]:+ text = " ".join(+ _flatten_strings(+ [+ rec.get("name"),+ rec.get("category"),+ rec.get("capabilities"),+ rec.get("workflows"),+ rec.get("input_formats"),+ rec.get("output_formats"),+ rec.get("cli_or_api_flags"),+ rec.get("three_mf_metadata_schema"),+ rec.get("relevance_to_forma_print"),+ ]+ )+ ).lower()+ tech: set[str] = set()+ if re.search(r"\b(fdm|fff|gcode|g-code|marlin|klipper|reprapfirmware|smoothieware|bgcode)\b", text):+ tech.add("fdm")+ if re.search(r"\b(msla|ctb|cbddlp|goo|prz|uvtools|chitubox|lychee|sl1|sl1s|photon|chitui)\b", text):+ tech.add("msla")+ if re.search(r"\b(sla|stereolithography|sl1|sl1s)\b", text):+ tech.add("sla")+ if re.search(r"\bdlp\b", text):+ tech.add("dlp")+ if re.search(r"\bsls\b", text):+ tech.add("sls")+ return sorted(tech)+++def infer_paper_tech(rec: dict[str, Any]) -> list[str]:+ text = " ".join(+ _flatten_strings(+ [+ rec.get("title"),+ rec.get("summary"),+ rec.get("key_algorithm"),+ rec.get("relevance_to_forma_print"),+ ]+ )+ ).lower()+ tech: set[str] = set()+ if re.search(r"\b(fdm|fff|fused\s+filament|extrusion)\b", text):+ tech.add("fdm")+ if re.search(r"\b(msla)\b", text):+ tech.add("msla")+ if re.search(r"\b(sla|stereolithography)\b", text):+ tech.add("sla")+ if re.search(r"\b(sls|selective\s+laser\s+sintering)\b", text):+ tech.add("sls")+ if re.search(r"\b(mjf|multi\s+jet\s+fusion)\b", text):+ tech.add("mjf")+ return sorted(tech)+++def extract_fault_prefixes(codes: list[str], taxonomy: str = "") -> list[str]:+ prefixes: set[str] = set()+ for raw in codes:+ code = raw.strip()+ if not code:+ continue+ # Split slash-delimited compound fault examples like "#31208 / #26208 / #13208"+ parts = [p.strip() for p in re.split(r"\s+/\s+", code) if p.strip()]+ if not parts:+ parts = [code]+ for part in parts:+ # Strip trailing parenthetical annotations for clean code token+ base = re.sub(r"\s*\([^)]*\)\s*$", "", part).strip()+ if base and " " not in base and (any(ch.isdigit() for ch in base) or "_" in base or "-" in base):+ prefixes.add(base)+ # HMS_0700-0100-0002-0002 -> HMS_, HMS_0700+ m_hms = re.match(r"^(HMS_)([0-9A-Fa-f]{4})", base)+ if m_hms:+ prefixes.add(m_hms.group(1))+ prefixes.add(m_hms.group(1) + m_hms.group(2))+ # #31208 -> #31, 31, #31208, 31208+ m_hash = re.match(r"^#(\d{2,})", base)+ if m_hash:+ digits = m_hash.group(1)+ prefixes.add(f"#{digits[:2]}")+ prefixes.add(digits[:2])+ prefixes.add(digits)+ # Hex codes like 0xFD01120001+ m_hex = re.match(r"^(0x)([0-9A-Fa-f]{2,})", base)+ if m_hex:+ prefixes.add("0x")+ prefixes.add("0x" + m_hex.group(2)[:2])+ # Embedded 0x tokens like M122 Error status 0x01 / 0x02+ for hx in re.findall(r"0x[0-9A-Fa-f]+", part):+ prefixes.add("0x")+ prefixes.add(hx)+ # Alphanumeric prefixed codes like ER18, E0002, CM2784, QDE_004, M122+ m_alpha = re.match(r"^([A-Za-z]+_?)(\d+)", base)+ if m_alpha:+ p_alpha = m_alpha.group(1)+ prefixes.add(p_alpha)+ if p_alpha.endswith("_"):+ prefixes.add(p_alpha.rstrip("_"))+ # Uppercase error constants like ADC_ERR_HIGH+ m_const = re.match(r"^([A-Z]+_[A-Z]+)_[A-Z0-9_]+$", base)+ if m_const:+ prefixes.add(m_const.group(1))+ # Hyphenated numeric codes like 515-10, 0002-0528-0003-0013+ m_numdash = re.match(r"^(\d+)-(\d+)", base)+ if m_numdash:+ prefixes.add(f"{m_numdash.group(1)}-")+ prefixes.add(f"{m_numdash.group(1)}-{m_numdash.group(2)}")+ # "Error 1000", "key: 2564" (only when followed by an actual numeric/hex code)+ m_label = re.match(r"^(Error|key:|Err:)\s*(\d+[A-Za-z0-9._-]*)", base, re.IGNORECASE)+ if m_label:+ prefixes.add(f"{m_label.group(1)} {m_label.group(2)[0]}".strip())+ prefixes.add(m_label.group(2))+ # Plain 4-5 digit numeric code like 10101 -> 101+ if re.fullmatch(r"\d{4,6}", base):+ prefixes.add(base[:3])+ # Dotted numeric like 1.3.1+ m_dot = re.match(r"^(\d+\.\d+)\.", base)+ if m_dot:+ prefixes.add(m_dot.group(1))++ if taxonomy:+ for tok in re.findall(r"\b(?:HMS_|QDE|QDC|ER\b|E00|CM\b|M122|ADC_ERR|TC_ERR|ERR_)\w*", taxonomy):+ prefixes.add(tok)++ return sorted(p for p in prefixes if p.strip())+++def canonical_chunk_hash(chunk: dict[str, Any]) -> str:+ payload = {+ "chunk_id": chunk["chunk_id"],+ "domain": chunk["domain"],+ "entity_id": chunk["entity_id"],+ "title": chunk["title"],+ "section": chunk["section"],+ "text": chunk["text"],+ "metadata": chunk["metadata"],+ "source_url": chunk["source_url"],+ }+ encoded = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")+ return hashlib.sha256(encoded).hexdigest()+++def format_embedding_ready_text(domain: str, entity_id: str, section: str, title: str, text: str) -> str:+ return f"[{domain} | {entity_id} | {section}] {title}\n{text}"+++def make_chunk(+ *,+ chunk_id: str,+ domain: str,+ entity_id: str,+ title: str,+ section: str,+ text: str,+ source_url: str,+ metadata: dict[str, Any],+) -> dict[str, Any]:+ clean_text = text.strip()+ clean_title = title.strip()+ clean_section = section.strip()+ embedding_ready = format_embedding_ready_text(domain, entity_id, clean_section, clean_title, clean_text)+ chunk = {+ "chunk_id": chunk_id,+ "domain": domain,+ "entity_id": entity_id,+ "title": clean_title,+ "section": clean_section,+ "text": clean_text,+ "metadata": metadata,+ "source_url": source_url.strip(),+ "token_count": count_words(clean_text),+ "embedding_ready_text": embedding_ready,+ "embedding_dim": None,+ "embedding_model": None,+ }+ chunk["content_hash"] = canonical_chunk_hash(chunk)+ return chunk+++def load_jsonl(path: Path) -> list[dict[str, Any]]:+ records: list[dict[str, Any]] = []+ with path.open("r", encoding="utf-8") as fh:+ for line in fh:+ stripped = line.strip()+ if stripped:+ records.append(json.loads(stripped))+ return records+++def chunk_software(records: list[dict[str, Any]]) -> list[dict[str, Any]]:+ chunks: list[dict[str, Any]] = []+ for rec in records:+ eid = rec["id"]+ name = rec["name"]+ cat = rec["category"]+ primary_url = rec["repo_or_primary_url"]+ source_urls = list(rec["source_urls"])+ tech = infer_software_tech(rec)+ protocols = extract_protocols(+ rec.get("workflows"),+ rec.get("input_formats"),+ rec.get("output_formats"),+ rec.get("cli_or_api_flags"),+ rec.get("capabilities"),+ )+ base_tags = sorted(+ {+ "software",+ cat.lower(),+ *(lang.lower() for lang in rec.get("languages", []) if lang.strip()),+ *(fmt.lower() for fmt in rec.get("input_formats", []) if fmt.strip()),+ *(fmt.lower() for fmt in rec.get("output_formats", []) if fmt.strip()),+ *tech,+ *protocols,+ }+ )+ meta_overview = {+ "tech": tech,+ "manufacturer": None,+ "protocol": protocols,+ "category": cat,+ "fault_code_prefix": [],+ "tags": base_tags,+ "source_urls": source_urls,+ "source_file": "research/corpus/software.jsonl",+ "license": rec.get("license"),+ }+ meta_sub = {+ "tech": tech,+ "manufacturer": None,+ "protocol": protocols,+ "category": cat,+ "fault_code_prefix": [],+ "tags": base_tags,+ "source_file": "research/corpus/software.jsonl",+ "license": rec.get("license"),+ }++ text_overview = (+ f"Software: {name} (id={eid}, category={cat}, license={rec['license']}).\n"+ f"Languages: {', '.join(rec['languages'])}.\n"+ f"Capabilities: {'; '.join(rec['capabilities'])}.\n"+ f"Availability: {rec['availability_notes']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"sw:{eid}:overview_capabilities",+ domain="software",+ entity_id=eid,+ title=name,+ section="Overview & Capabilities",+ text=text_overview,+ source_url=primary_url,+ metadata=meta_overview,+ )+ )++ text_wf = (+ f"Software: {name} ({cat}).\n"+ f"Workflows: {'; '.join(rec['workflows'])}.\n"+ f"Input formats: {', '.join(rec['input_formats'])}.\n"+ f"Output formats: {', '.join(rec['output_formats'])}.\n"+ f"CLI / API flags & endpoints: {'; '.join(rec['cli_or_api_flags'])}."+ )+ chunks.append(+ make_chunk(+ chunk_id=f"sw:{eid}:workflows_formats_cli",+ domain="software",+ entity_id=eid,+ title=name,+ section="Workflows, Formats & CLI/API",+ text=text_wf,+ source_url=primary_url,+ metadata=dict(meta_sub),+ )+ )++ text_arch = (+ f"Software: {name} ({cat}).\n"+ f"3MF & Metadata Schema: {rec['three_mf_metadata_schema']}\n"+ f"Architectural Lessons for forma-print: {rec['architectural_lessons_for_forma_print']}\n"+ f"Relevance to forma-print: {rec['relevance_to_forma_print']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"sw:{eid}:three_mf_and_architecture",+ domain="software",+ entity_id=eid,+ title=name,+ section="3MF Metadata & Architectural Lessons",+ text=text_arch,+ source_url=primary_url,+ metadata=dict(meta_sub),+ )+ )+ return chunks+++def chunk_manufacturers(records: list[dict[str, Any]]) -> list[dict[str, Any]]:+ chunks: list[dict[str, Any]] = []+ for rec in records:+ eid = rec["id"]+ name = rec["manufacturer"]+ segment = rec["segment"]+ tech = sorted({t.lower() for t in rec["technologies"]})+ dc = rec["direct_communication"]+ ms = rec["monitoring_and_sensors"]+ tf = rec["troubleshooting_and_faults"]+ primary_url = rec["source_urls"][0]+ protocols = extract_protocols(+ dc.get("local_protocols"),+ dc.get("cloud_protocols"),+ dc.get("upload_print_control_endpoints"),+ dc.get("ports"),+ )+ all_fault_codes = [f["code"] for f in tf["example_fault_codes"]]+ all_fault_prefixes = extract_fault_prefixes(all_fault_codes, tf["fault_code_taxonomy"])+ base_tags = sorted(+ {+ "manufacturer",+ eid,+ segment.lower(),+ dc["status"].lower(),+ "offline_capable" if dc["offline_capable"] else "online_required",+ *tech,+ *protocols,+ }+ )++ meta_aspect_overview = {+ "tech": tech,+ "manufacturer": eid,+ "protocol": protocols,+ "category": segment,+ "fault_code_prefix": [],+ "tags": base_tags,+ "source_urls": list(rec["source_urls"]),+ "source_file": "research/corpus/manufacturers.jsonl",+ "segment": segment,+ "status": dc["status"],+ "offline_capable": dc["offline_capable"],+ }+ meta_aspect = {+ "tech": tech,+ "manufacturer": eid,+ "protocol": protocols,+ "category": segment,+ "fault_code_prefix": [],+ "tags": base_tags,+ "source_file": "research/corpus/manufacturers.jsonl",+ "segment": segment,+ "status": dc["status"],+ "offline_capable": dc["offline_capable"],+ }++ text_overview = (+ f"Manufacturer: {name} (id={eid}, segment={segment}, technologies={', '.join(rec['technologies'])}).\n"+ f"Representative models: {', '.join(rec['representative_models'])}.\n"+ f"Availability notes: {rec['availability_notes']}\n"+ f"Relevance to forma-print: {rec['relevance_to_forma_print']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"mf:{eid}:overview",+ domain="manufacturer",+ entity_id=eid,+ title=name,+ section="Overview & Relevance",+ text=text_overview,+ source_url=primary_url,+ metadata=meta_aspect_overview,+ )+ )++ text_dc = (+ f"Manufacturer: {name} ({eid}) Direct Communication (status={dc['status']}, offline_capable={dc['offline_capable']}).\n"+ f"Local protocols: {'; '.join(dc['local_protocols'])}.\n"+ f"Cloud protocols: {'; '.join(dc['cloud_protocols'])}.\n"+ f"Ports & bus identifiers: {'; '.join(dc['ports'])}.\n"+ f"Auth & modes: {dc['auth_and_modes']}\n"+ f"Upload, print & control endpoints: {'; '.join(dc['upload_print_control_endpoints'])}.\n"+ f"Offline mode notes: {dc['offline_mode_notes']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"mf:{eid}:direct_communication",+ domain="manufacturer",+ entity_id=eid,+ title=name,+ section="Direct Communication & Protocols",+ text=text_dc,+ source_url=primary_url,+ metadata=dict(meta_aspect),+ )+ )++ text_ms = (+ f"Manufacturer: {name} ({eid}) Monitoring & Sensors.\n"+ f"Thermal sensors: {ms['thermal_sensors']}\n"+ f"Cameras: {ms['cameras']}\n"+ f"LiDAR & AI inspection: {ms['lidar_and_ai_inspection']}\n"+ f"Filament & spool systems: {ms['filament_and_spool_systems']}\n"+ f"Accelerometers & input shaper: {ms['accelerometers_input_shaper']}\n"+ f"Bed probes: {ms['bed_probes']}\n"+ f"Status & error feeds: {ms['status_error_feeds']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"mf:{eid}:monitoring_and_sensors",+ domain="manufacturer",+ entity_id=eid,+ title=name,+ section="Monitoring & Sensors",+ text=text_ms,+ source_url=primary_url,+ metadata=dict(meta_aspect),+ )+ )++ fault_summary = "; ".join(f"{f['code']}: {f['description']}" for f in tf["example_fault_codes"])+ meta_tf = dict(meta_aspect)+ meta_tf["fault_code_prefix"] = all_fault_prefixes+ meta_tf["fault_codes"] = all_fault_codes+ meta_tf["tags"] = sorted({*base_tags, "troubleshooting", "faults"})+ meta_tf["source_urls"] = list(tf["official_kb_urls"])++ text_tf = (+ f"Manufacturer: {name} ({eid}) Troubleshooting & Fault Taxonomy.\n"+ f"Fault code taxonomy: {tf['fault_code_taxonomy']}\n"+ f"Example fault codes: {fault_summary}\n"+ f"Diagnostic logs: {tf['diagnostic_logs']}\n"+ f"Official KB URLs: {', '.join(tf['official_kb_urls'])}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"mf:{eid}:troubleshooting_and_faults",+ domain="manufacturer",+ entity_id=eid,+ title=name,+ section="Troubleshooting, Fault Taxonomy & Logs",+ text=text_tf,+ source_url=tf["official_kb_urls"][0],+ metadata=meta_tf,+ )+ )++ for idx, fault in enumerate(tf["example_fault_codes"]):+ f_code = fault["code"].strip()+ f_prefixes = extract_fault_prefixes([f_code])+ meta_fault = dict(meta_aspect)+ meta_fault["fault_code_prefix"] = f_prefixes+ meta_fault["fault_codes"] = [f_code]+ meta_fault["tags"] = sorted({*base_tags, "fault_code", "troubleshooting"})+ meta_fault["source_urls"] = [fault["kb_url"]]++ text_fault = (+ f"Manufacturer: {name} ({eid}) Fault Code {f_code}.\n"+ f"Fault description: {fault['description']}\n"+ f"Taxonomy context: {tf['fault_code_taxonomy']}\n"+ f"Diagnostic logs: {tf['diagnostic_logs']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"mf:{eid}:fault:{idx}",+ domain="manufacturer",+ entity_id=eid,+ title=name,+ section=f"Fault Code: {f_code}",+ text=text_fault,+ source_url=fault["kb_url"],+ metadata=meta_fault,+ )+ )++ return chunks+++def chunk_papers(records: list[dict[str, Any]]) -> list[dict[str, Any]]:+ chunks: list[dict[str, Any]] = []+ for rec in records:+ eid = rec["id"]+ title = rec["title"]+ cat = rec["category"]+ tech = infer_paper_tech(rec)+ tags = sorted(+ {+ "paper",+ cat.lower(),+ str(rec["year"]),+ *tech,+ }+ )+ meta = {+ "tech": tech,+ "manufacturer": None,+ "protocol": [],+ "category": cat,+ "fault_code_prefix": [],+ "tags": tags,+ "source_urls": [rec["url"]],+ "source_file": "research/corpus/papers.jsonl",+ "year": rec["year"],+ "doi_or_arxiv_id": rec["doi_or_arxiv_id"],+ }++ text_sum = (+ f"Paper: {title} ({rec['year']}, {rec['venue']}).\n"+ f"Authors: {', '.join(rec['authors'])}.\n"+ f"Category: {cat} | Identifier: {rec['doi_or_arxiv_id']}.\n"+ f"Summary: {rec['summary']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"pp:{eid}:summary_and_citation",+ domain="paper",+ entity_id=eid,+ title=title,+ section="Summary & Citation",+ text=text_sum,+ source_url=rec["url"],+ metadata=dict(meta),+ )+ )++ text_alg = (+ f"Paper: {title} ({rec['year']}, category={cat}, id={rec['doi_or_arxiv_id']}).\n"+ f"Key Algorithm: {rec['key_algorithm']}\n"+ f"Relevance to forma-print: {rec['relevance_to_forma_print']}"+ )+ chunks.append(+ make_chunk(+ chunk_id=f"pp:{eid}:algorithm_and_relevance",+ domain="paper",+ entity_id=eid,+ title=title,+ section="Key Algorithm & Forma-Print Relevance",+ text=text_alg,+ source_url=rec["url"],+ metadata=dict(meta),+ )+ )+ return chunks+++def chunk_report(report_path: Path) -> list[dict[str, Any]]:+ lines = report_path.read_text(encoding="utf-8").splitlines()+ sections: list[tuple[str, str, list[str]]] = []+ cur_h2 = ""+ cur_h3 = ""+ cur_lines: list[str] = []++ def flush() -> None:+ nonlocal cur_lines+ body = "\n".join(line for line in cur_lines if line.strip() != "---").strip()+ if cur_h2 and body and not cur_h3:+ sections.append((cur_h2, cur_h2, [body]))+ elif cur_h2 and cur_h3 and body:+ sections.append((cur_h2, cur_h3, [body]))+ cur_lines = []++ for line in lines:+ if line.startswith("## "):+ flush()+ cur_h2 = line[3:].strip()+ cur_h3 = ""+ elif line.startswith("### "):+ flush()+ cur_h3 = line[4:].strip()+ elif cur_h2:+ cur_lines.append(line)+ flush()++ chunks: list[dict[str, Any]] = []+ for h2, heading, body_parts in sections:+ m_num = re.match(r"^(\d+(?:\.\d+)?)\b", heading)+ sec_slug = f"sec_{m_num.group(1).replace('.', '_')}" if m_num else f"sec_{len(chunks)+1}"+ is_bench = "nurb-benchmarks" in h2.lower() or "nurb-benchmarks" in heading.lower()+ primary_url = "https://github.com/Shpigford/nurb-benchmarks" if is_bench else "https://github.com/Shpigford/nurb"+ body = "\n".join(body_parts).strip()+ if heading != h2:+ full_text = f"{h2} — {heading}\n{body}"+ else:+ full_text = f"{h2}\n{body}"+ protocols = extract_protocols(full_text)+ tags = sorted({"report", "nurb", "nurb_benchmarks", "fdm", *protocols})+ meta = {+ "tech": ["fdm"],+ "manufacturer": None,+ "protocol": protocols,+ "category": "architectural_inspection",+ "fault_code_prefix": [],+ "tags": tags,+ "source_urls": [+ "https://github.com/Shpigford/nurb",+ "https://github.com/Shpigford/nurb-benchmarks",+ ],+ "source_file": "research/reports/nurb_inspection.md",+ "license": "FSL-1.1-MIT",+ }+ chunks.append(+ make_chunk(+ chunk_id=f"rp:nurb_inspection:{sec_slug}",+ domain="report",+ entity_id="nurb_inspection",+ title="Architectural Inspection: Shpigford/nurb & nurb-benchmarks",+ section=heading,+ text=full_text,+ source_url=primary_url,+ metadata=meta,+ )+ )+ return chunks+++def compute_build_hash(paths: list[Path]) -> str:+ h = hashlib.sha256()+ for p in sorted(paths, key=lambda x: str(x.relative_to(REPO_ROOT))):+ rel = str(p.relative_to(REPO_ROOT))+ file_hash = hashlib.sha256(p.read_bytes()).hexdigest()+ h.update(f"{rel}:{file_hash}\n".encode("utf-8"))+ return h.hexdigest()+++def build_tags_text(chunk: dict[str, Any]) -> str:+ meta = chunk["metadata"]+ parts = [+ chunk["domain"],+ meta["category"],+ meta["manufacturer"] or "",+ *meta["tech"],+ *meta["protocol"],+ *meta["fault_code_prefix"],+ *meta.get("fault_codes", []),+ *meta["tags"],+ ]+ return " ".join(p for p in parts if p)+++def build_database(+ db_path: Path = DEFAULT_DB_PATH,+ *,+ emit_chunks_jsonl: bool = False,+ chunks_jsonl_path: Path = DEFAULT_CHUNKS_JSONL_PATH,+ max_db_mb: float = 2.0,+ quiet: bool = False,+) -> dict[str, Any]:+ software_records = load_jsonl(SOFTWARE_PATH)+ manufacturer_records = load_jsonl(MANUFACTURERS_PATH)+ paper_records = load_jsonl(PAPERS_PATH)+ schema_obj = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))++ chunks: list[dict[str, Any]] = []+ chunks.extend(chunk_software(software_records))+ chunks.extend(chunk_manufacturers(manufacturer_records))+ chunks.extend(chunk_papers(paper_records))+ chunks.extend(chunk_report(REPORT_PATH))+ chunks.sort(key=lambda c: c["chunk_id"])++ # Compute document frequency (DF) and IDF across all chunks deterministically+ total_docs = len(chunks)+ doc_tokens: list[list[str]] = []+ df_counts: dict[str, int] = {}+ for chunk in chunks:+ tags_text = build_tags_text(chunk)+ toks = tokenize(f"{chunk['title']} {chunk['section']} {chunk['entity_id']} {chunk['text']} {tags_text}")+ doc_tokens.append(toks)+ for term in set(toks):+ df_counts[term] = df_counts.get(term, 0) + 1++ vocab_idf: dict[str, float] = {+ term: round(math.log((total_docs + 1.0) / (df + 1.0)) + 1.0, 3)+ for term, df in sorted(df_counts.items())+ }+ term_to_id: dict[str, int] = {term: idx for idx, term in enumerate(sorted(vocab_idf), start=1)}++ # Precompute compact sparse TF-IDF vector (keyed by vocab_idf.term_id, capped at top 48 terms)+ chunk_tfidf: list[tuple[str, float]] = []+ for toks in doc_tokens:+ tf_counts: dict[str, int] = {}+ for t in toks:+ tf_counts[t] = tf_counts.get(t, 0) + 1+ scored = [+ (term, round((1.0 + math.log(tf)) * vocab_idf[term], 2))+ for term, tf in tf_counts.items()+ ]+ scored.sort(key=lambda item: (-item[1], item[0]))+ scored = scored[:48]+ vec = {str(term_to_id[term]): w for term, w in sorted(scored, key=lambda x: term_to_id[x[0]])}+ norm = round(math.sqrt(sum(w * w for _, w in scored)), 4)+ chunk_tfidf.append((json.dumps(vec, separators=(",", ":")), norm))++ domain_counts: dict[str, int] = {}+ for c in chunks:+ d = c["domain"]+ domain_counts[d] = domain_counts.get(d, 0) + 1++ source_records_info = {+ "software": len(software_records),+ "manufacturers": len(manufacturer_records),+ "papers": len(paper_records),+ "report_sections": domain_counts.get("report", 0),+ }++ build_hash = compute_build_hash(+ [SOFTWARE_PATH, MANUFACTURERS_PATH, PAPERS_PATH, REPORT_PATH, SCHEMA_PATH]+ )++ if emit_chunks_jsonl:+ chunks_jsonl_path.parent.mkdir(parents=True, exist_ok=True)+ with chunks_jsonl_path.open("w", encoding="utf-8") as out_fh:+ for c in chunks:+ out_fh.write(json.dumps(c, ensure_ascii=False, separators=(",", ":")) + "\n")++ db_path.parent.mkdir(parents=True, exist_ok=True)+ tmp_path = db_path.with_name(db_path.name + ".tmp")+ for sidecar in (tmp_path, Path(str(tmp_path) + "-wal"), Path(str(tmp_path) + "-shm")):+ if sidecar.exists():+ sidecar.unlink()++ conn = sqlite3.connect(str(tmp_path))+ try:+ conn.execute("PRAGMA journal_mode=DELETE;")+ conn.execute("PRAGMA synchronous=OFF;")+ conn.execute("PRAGMA page_size=8192;")++ conn.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 INDEX idx_chunks_domain ON chunks(domain);+ CREATE INDEX idx_chunks_entity ON chunks(entity_id);+ CREATE INDEX idx_chunks_category ON chunks(category);+ CREATE INDEX idx_chunks_manufacturer ON chunks(manufacturer);++ 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+ );+ """+ )++ chunk_rows = []+ for idx, (chunk, (tfidf_json, tfidf_norm)) in enumerate(zip(chunks, chunk_tfidf), start=1):+ meta = chunk["metadata"]+ extra_meta = {+ k: v+ for k, v in meta.items()+ if k not in ("tech", "manufacturer", "protocol", "category", "fault_code_prefix", "tags")+ }+ chunk_rows.append(+ (+ idx,+ chunk["chunk_id"],+ chunk["domain"],+ chunk["entity_id"],+ chunk["title"],+ chunk["section"],+ build_tags_text(chunk),+ chunk["text"],+ chunk["source_url"],+ meta["category"],+ meta["manufacturer"],+ json.dumps(meta["tech"], separators=(",", ":")),+ json.dumps(meta["protocol"], separators=(",", ":")),+ json.dumps(meta["fault_code_prefix"], separators=(",", ":")),+ json.dumps(meta["tags"], separators=(",", ":")),+ json.dumps(extra_meta, sort_keys=True, ensure_ascii=False, separators=(",", ":")),+ chunk["token_count"],+ tfidf_json,+ tfidf_norm,+ chunk["content_hash"],+ )+ )++ conn.executemany(+ """+ INSERT INTO chunks (+ rowid, chunk_id, domain, entity_id, title, section, tags_text, text,+ source_url, category, manufacturer,+ tech_json, protocol_json, fault_prefix_json, tags_json,+ metadata_json, token_count, tfidf_json, tfidf_norm, content_hash+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ chunk_rows,+ )+ conn.execute("INSERT INTO chunks_fts(chunks_fts) VALUES ('rebuild');")+ conn.executemany(+ "INSERT INTO vocab_idf (term_id, term, df, idf) VALUES (?, ?, ?, ?)",+ [(term_to_id[term], term, df_counts[term], vocab_idf[term]) for term in sorted(vocab_idf)],+ )++ manifest_items = sorted(+ {+ "schema_version": SCHEMA_VERSION,+ "rag_chunks_schema_id": schema_obj["$id"],+ "build_hash": build_hash,+ "total_chunks": str(total_docs),+ "vocab_size": str(len(vocab_idf)),+ "domain_counts_json": json.dumps(domain_counts, sort_keys=True, separators=(",", ":")),+ "source_records_json": json.dumps(source_records_info, sort_keys=True, separators=(",", ":")),+ }.items()+ )+ conn.executemany("INSERT INTO kb_manifest (key, value) VALUES (?, ?)", manifest_items)+ conn.commit()+ conn.execute("VACUUM;")+ integrity = conn.execute("PRAGMA integrity_check;").fetchone()+ if not integrity or integrity[0] != "ok":+ raise RuntimeError(f"SQLite integrity_check failed: {integrity}")+ finally:+ conn.close()++ size_bytes = tmp_path.stat().st_size+ max_bytes = int(max_db_mb * 1024 * 1024)+ if size_bytes > max_bytes:+ tmp_path.unlink(missing_ok=True)+ raise RuntimeError(f"SQLite DB size {size_bytes} bytes exceeds limit {max_bytes} bytes ({max_db_mb} MB)")++ os.replace(tmp_path, db_path)+ for sidecar in (Path(str(db_path) + "-wal"), Path(str(db_path) + "-shm")):+ if sidecar.exists():+ sidecar.unlink()++ db_sha256 = hashlib.sha256(db_path.read_bytes()).hexdigest()+ summary = {+ "db_path": str(db_path),+ "db_size_bytes": size_bytes,+ "db_sha256": db_sha256,+ "build_hash": build_hash,+ "total_chunks": total_docs,+ "vocab_size": len(vocab_idf),+ "domain_counts": dict(sorted(domain_counts.items())),+ "source_records": source_records_info,+ }+ if not quiet:+ print(json.dumps(summary, indent=2, sort_keys=True))+ return summary+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Build forma-print deterministic SQLite FTS5 + TF-IDF RAG DB.")+ parser.add_argument("--db", type=Path, default=DEFAULT_DB_PATH, help="Output SQLite DB path.")+ parser.add_argument(+ "--emit-chunks-jsonl",+ action="store_true",+ help="Optionally write normalized chunks to research/rag/chunks.jsonl.",+ )+ parser.add_argument(+ "--chunks-jsonl",+ type=Path,+ default=DEFAULT_CHUNKS_JSONL_PATH,+ help="Output path when --emit-chunks-jsonl is enabled.",+ )+ parser.add_argument("--check-size-mb", type=float, default=2.0, help="Maximum allowed SQLite DB size in MiB.")+ parser.add_argument("--quiet", action="store_true", help="Suppress build summary output.")+ args = parser.parse_args(argv)++ build_database(+ db_path=args.db,+ emit_chunks_jsonl=args.emit_chunks_jsonl,+ chunks_jsonl_path=args.chunks_jsonl,+ max_db_mb=args.check_size_mb,+ quiet=args.quiet,+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/research/rag/forma_print_kb.sqlite b/research/rag/forma_print_kb.sqlitenew file mode 100644index 0000000..1717ed3Binary files /dev/null and b/research/rag/forma_print_kb.sqlite differdiff --git a/research/rag/query_rag.py b/research/rag/query_rag.pynew file mode 100644index 0000000..8e8dc10--- /dev/null+++ b/research/rag/query_rag.py@@ -0,0 +1,625 @@+#!/usr/bin/env python3+"""Stdlib-only hybrid FTS5 BM25 + TF-IDF cosine RAG query engine for forma-print."""++from __future__ import annotations++import argparse+import json+import math+import re+import sqlite3+import sys+import time+import unicodedata+from pathlib import Path+from typing import Any++REPO_ROOT = Path(__file__).resolve().parents[2]+DEFAULT_DB_PATH = REPO_ROOT / "research" / "rag" / "forma_print_kb.sqlite"++STOPWORDS = frozenset(+ {+ "the", "and", "for", "with", "that", "this", "from", "are", "was", "were",+ "been", "being", "have", "has", "had", "into", "onto", "over", "under",+ "also", "such", "when", "where", "which", "while", "each", "all", "not",+ "but", "can", "use", "used", "using", "via", "per", "etc", "its", "their",+ "than", "then", "them", "they", "only", "both", "more", "most", "other",+ "some", "any", "may", "will", "should", "must", "non", "off", "out",+ }+)+++_MN_RE = re.compile(r"[\u0300-\u036f\ufe20-\ufe2f]+")+_MAYBE_EXOTIC_MN_RE = re.compile(r"[^\x00-\u02ff\u1e00-\u20cf\u2100-\u27bf]")+++def fold_diacritics(text: str) -> str:+ """Fold Unicode diacritics via NFKD decomposition to match SQLite unicode61."""+ if text.isascii():+ return text+ stripped = _MN_RE.sub("", unicodedata.normalize("NFKD", text))+ if _MAYBE_EXOTIC_MN_RE.search(stripped):+ return "".join(ch for ch in stripped if unicodedata.category(ch) != "Mn")+ return stripped+++def tokenize(text: str) -> list[str]:+ """Match build_rag.py lexical tokenization deterministically."""+ cleaned = re.sub(r"https?://\S+", " ", fold_diacritics(text).lower())+ tokens: list[str] = []+ for tok in re.findall(r"[a-z0-9][a-z0-9_./-]*[a-z0-9]|[a-z0-9]{2,}", cleaned):+ if tok in STOPWORDS:+ continue+ tokens.append(tok)+ if any(sep in tok for sep in ("_", "-", ".", "/")):+ for part in re.split(r"[_./-]+", tok):+ if len(part) >= 2 and part != tok and part not in STOPWORDS:+ tokens.append(part)+ return tokens+++def sanitize_fts_tokens(query: str) -> list[str]:+ """Extract FTS5-safe alphanumeric/underscore tokens so punctuation never causes syntax errors."""+ raw = re.findall(r"[a-z0-9][a-z0-9_]*", fold_diacritics(query).lower())+ seen: set[str] = set()+ out: list[str] = []+ for tok in raw:+ if len(tok) >= 1 and tok not in seen:+ seen.add(tok)+ out.append(tok)+ return out+++def _norm_ident(val: str) -> str:+ return re.sub(r"[^a-z0-9]+", "", fold_diacritics(val).lower())+++def _make_snippet(text: str, query_tokens: list[str], max_len: int = 240) -> str:+ compact = re.sub(r"\s+", " ", text).strip()+ if len(compact) <= max_len:+ return compact++ if compact.isascii():+ lower = compact.lower()+ hit_pos = -1+ for tok in query_tokens:+ if len(tok) < 2:+ continue+ pos = lower.find(fold_diacritics(tok).lower())+ if pos != -1 and (hit_pos == -1 or pos < hit_pos):+ hit_pos = pos+ else:+ folded_chars: list[str] = []+ folded_to_orig: list[int] = []+ for orig_idx, ch in enumerate(compact):+ for dec in unicodedata.normalize("NFKD", ch):+ if unicodedata.category(dec) != "Mn":+ folded_chars.append(dec.lower())+ folded_to_orig.append(orig_idx)+ lower = "".join(folded_chars)++ hit_pos = -1+ for tok in query_tokens:+ if len(tok) < 2:+ continue+ folded_tok = fold_diacritics(tok).lower()+ pos = lower.find(folded_tok)+ if pos != -1:+ orig_pos = folded_to_orig[pos]+ if hit_pos == -1 or orig_pos < hit_pos:+ hit_pos = orig_pos++ if hit_pos <= max_len // 3:+ cut = compact[:max_len].rsplit(" ", 1)[0]+ return f"{cut}..."++ start = max(0, hit_pos - max_len // 3)+ if start > 0:+ space_after = compact.find(" ", start)+ if space_after != -1 and space_after < hit_pos:+ start = space_after + 1+ end = min(len(compact), start + max_len)+ window = compact[start:end]+ if end < len(compact):+ window = window.rsplit(" ", 1)[0] + "..."+ if start > 0:+ window = "..." + window+ return window+++def _reconstruct_metadata(row: sqlite3.Row) -> dict[str, Any]:+ meta = json.loads(row["metadata_json"])+ meta.setdefault("tech", json.loads(row["tech_json"]))+ meta.setdefault("manufacturer", row["manufacturer"])+ meta.setdefault("protocol", json.loads(row["protocol_json"]))+ meta.setdefault("category", row["category"])+ meta.setdefault("fault_code_prefix", json.loads(row["fault_prefix_json"]))+ meta.setdefault("tags", json.loads(row["tags_json"]))+ return meta+++def _reconstruct_metadata_tuple(row: tuple[Any, ...]) -> dict[str, Any]:+ meta = json.loads(row[14])+ meta.setdefault("tech", json.loads(row[10]))+ meta.setdefault("manufacturer", row[9])+ meta.setdefault("protocol", json.loads(row[11]))+ meta.setdefault("category", row[8])+ meta.setdefault("fault_code_prefix", json.loads(row[12]))+ meta.setdefault("tags", json.loads(row[13]))+ return meta+++def _matches_filters(+ row: sqlite3.Row,+ *,+ domain: str | None,+ tech: str | None,+ manufacturer: str | None,+ protocol: str | None,+ category: str | None,+ fault_prefix: str | None,+) -> tuple[bool, dict[str, Any]]:+ if domain and row["domain"].lower() != domain.strip().lower():+ return False, {}+ if category and row["category"].lower() != category.strip().lower():+ return False, {}++ if manufacturer:+ m_q = manufacturer.strip().lower()+ m_norm = _norm_ident(manufacturer)+ row_m = (row["manufacturer"] or "").lower()+ row_eid = row["entity_id"].lower()+ row_title_norm = _norm_ident(row["title"])+ if not (+ row_m == m_q+ or row_eid == m_q+ or (m_norm and (_norm_ident(row_m) == m_norm or _norm_ident(row_eid) == m_norm or m_norm in row_title_norm))+ ):+ return False, {}++ if tech:+ t_q = tech.strip().lower()+ if t_q == "fff":+ t_q = "fdm"+ tech_list = [x.lower() for x in json.loads(row["tech_json"])]+ if t_q not in tech_list:+ return False, {}++ if protocol:+ p_q = protocol.strip().lower()+ proto_list = [x.lower() for x in json.loads(row["protocol_json"])]+ if p_q not in proto_list and not any(p_q in p for p in proto_list):+ return False, {}++ meta = _reconstruct_metadata(row)+ if fault_prefix:+ fp_q = fault_prefix.strip().lower()+ fp_nohash = fp_q.lstrip("#")+ fp_list = [x.lower() for x in meta["fault_code_prefix"]]+ fc_list = [x.lower() for x in meta.get("fault_codes", [])]++ def _matches_fp(cand: str) -> bool:+ if len(fp_q) <= 3 and "error".startswith(fp_q) and (cand.startswith("error ") or cand.startswith("err:")):+ return False+ return cand.startswith(fp_q) or (bool(fp_nohash) and cand.lstrip("#").startswith(fp_nohash))++ matched_fp = any(_matches_fp(x) for x in (*fp_list, *fc_list))+ if not matched_fp:+ return False, {}++ return True, meta+++def query_kb(+ query: str = "",+ *,+ db_path: Path | str = DEFAULT_DB_PATH,+ conn: sqlite3.Connection | None = None,+ domain: str | None = None,+ tech: str | None = None,+ manufacturer: str | None = None,+ protocol: str | None = None,+ category: str | None = None,+ fault_prefix: str | None = None,+ top_k: int = 5,+) -> dict[str, Any]:+ """Query the forma-print SQLite RAG knowledge base with hybrid BM25 + TF-IDF scoring."""+ t0 = time.perf_counter()+ resolved_db = Path(db_path)+ if conn is None and not resolved_db.exists():+ raise FileNotFoundError(f"RAG SQLite database not found: {resolved_db}")++ domain = (domain or "").strip() or None+ tech = (tech or "").strip() or None+ manufacturer = (manufacturer or "").strip() or None+ protocol = (protocol or "").strip() or None+ category = (category or "").strip() or None+ fault_prefix = (fault_prefix or "").strip() or None++ top_k = int(top_k)+ filters_active = any(+ v is not None for v in (domain, tech, manufacturer, protocol, category, fault_prefix)+ )+ filters_dict = {+ "domain": domain,+ "tech": tech,+ "manufacturer": manufacturer,+ "protocol": protocol,+ "category": category,+ "fault_prefix": fault_prefix,+ }++ if top_k <= 0:+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3)+ return {+ "query": query,+ "filters": filters_dict,+ "total_candidates": 0,+ "latency_ms": elapsed_ms,+ "results": [],+ }++ fts_tokens = sanitize_fts_tokens(query)+ tfidf_tokens = tokenize(query)++ if not fts_tokens and not tfidf_tokens and not filters_active:+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3)+ return {+ "query": query,+ "filters": filters_dict,+ "total_candidates": 0,+ "latency_ms": elapsed_ms,+ "results": [],+ }++ owns_conn = conn is None+ if owns_conn:+ conn = sqlite3.connect(f"file:{resolved_db}?mode=ro", uri=True)+ try:+ sql_clauses: list[str] = []+ sql_params: list[Any] = []+ if domain:+ sql_clauses.append("LOWER(domain) = ?")+ sql_params.append(domain.lower())+ if category:+ sql_clauses.append("LOWER(category) = ?")+ sql_params.append(category.lower())+ where_sql = f"WHERE {' AND '.join(sql_clauses)}" if sql_clauses else ""++ rows = conn.execute(+ f"""+ SELECT rowid, chunk_id, domain, entity_id, title, section, text,+ source_url, category, manufacturer, tech_json, protocol_json,+ fault_prefix_json, tags_json, metadata_json, tfidf_json, tfidf_norm+ FROM chunks+ {where_sql}+ ORDER BY chunk_id+ """,+ sql_params,+ ).fetchall()++ filtered: dict[int, tuple[Any, ...]] = {}+ if not (manufacturer or tech or protocol or fault_prefix):+ for row in rows:+ filtered[row[0]] = row+ else:+ m_q = manufacturer.lower() if manufacturer else ""+ m_norm = _norm_ident(manufacturer) if manufacturer else ""+ t_q = ("fdm" if tech.lower() == "fff" else tech.lower()) if tech else ""+ p_q = protocol.lower() if protocol else ""+ fp_q = fault_prefix.lower() if fault_prefix else ""+ fp_nohash = fp_q.lstrip("#") if fp_q else ""+ fp_err_guard = bool(fp_q) and len(fp_q) <= 3 and "error".startswith(fp_q)++ for row in rows:+ if manufacturer:+ row_m = (row[9] or "").lower()+ row_eid = row[3].lower()+ if not (+ row_m == m_q+ or row_eid == m_q+ or (+ m_norm+ and (+ _norm_ident(row_m) == m_norm+ or _norm_ident(row_eid) == m_norm+ or m_norm in _norm_ident(row[4])+ )+ )+ ):+ continue++ if tech:+ tech_raw = row[10]+ if tech_raw == "[]":+ continue+ if t_q not in (x.lower() for x in json.loads(tech_raw)):+ continue++ if protocol:+ proto_raw = row[11]+ if proto_raw == "[]":+ continue+ proto_list = [x.lower() for x in json.loads(proto_raw)]+ if p_q not in proto_list and not any(p_q in p for p in proto_list):+ continue++ if fault_prefix:+ fp_raw = row[12]+ meta_raw = row[14]+ if fp_raw == "[]" and '"fault_codes"' not in meta_raw and '"fault_code_prefix"' not in meta_raw and "\\" not in meta_raw:+ continue+ if '"fault_code_prefix"' in meta_raw or '"fault_codes"' in meta_raw or "\\" in meta_raw:+ meta_obj = json.loads(meta_raw)+ fp_vals = meta_obj.get("fault_code_prefix")+ if fp_vals is None:+ fp_vals = json.loads(fp_raw)+ fc_vals = meta_obj.get("fault_codes") or ()+ else:+ fp_vals = json.loads(fp_raw)+ fc_vals = ()++ matched_fp = False+ for cand in (*fp_vals, *fc_vals):+ cand_l = cand.lower()+ if fp_err_guard and (cand_l.startswith("error ") or cand_l.startswith("err:")):+ continue+ if cand_l.startswith(fp_q) or (bool(fp_nohash) and cand_l.lstrip("#").startswith(fp_nohash)):+ matched_fp = True+ break+ if not matched_fp:+ continue++ filtered[row[0]] = row++ if not filtered:+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3)+ return {+ "query": query,+ "filters": filters_dict,+ "total_candidates": 0,+ "latency_ms": elapsed_ms,+ "results": [],+ }++ # Metadata-only query (no query tokens, active metadata filters)+ if not fts_tokens and not tfidf_tokens:+ ordered = sorted(filtered.values(), key=lambda row: (row[2], row[3], row[1]))+ results = []+ for row in ordered[:top_k]:+ results.append(+ {+ "chunk_id": row[1],+ "domain": row[2],+ "entity_id": row[3],+ "title": row[4],+ "section": row[5],+ "score": 1.0,+ "bm25_score": 0.0,+ "tfidf_score": 0.0,+ "snippet": _make_snippet(row[6], []),+ "source_url": row[7],+ "metadata": _reconstruct_metadata_tuple(row),+ }+ )+ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3)+ return {+ "query": query,+ "filters": filters_dict,+ "total_candidates": len(filtered),+ "latency_ms": elapsed_ms,+ "results": results,+ }++ # Stage 1: FTS5 BM25 retrieval+ bm25_raw_by_rowid: dict[int, float] = {}+ if fts_tokens:+ fts_expr = " OR ".join(f'"{tok}"' for tok in fts_tokens)+ fts_rows = conn.execute(+ """+ SELECT rowid, bm25(chunks_fts, 3.0, 1.5, 2.5, 2.0, 1.0) AS raw_bm25+ FROM chunks_fts+ WHERE chunks_fts MATCH ?+ """,+ (fts_expr,),+ ).fetchall()+ for r in fts_rows:+ rid = r[0]+ if rid in filtered:+ bm25_raw_by_rowid[rid] = max(0.0, -float(r[1]))++ max_bm25 = max(bm25_raw_by_rowid.values(), default=0.0)++ # Stage 2: Query TF-IDF vector using vocab_idf (fetch only matched terms)+ q_tfidf_vec: dict[int, float] = {}+ q_tfidf_norm = 0.0+ if tfidf_tokens:+ q_tf: dict[str, int] = {}+ for t in tfidf_tokens:+ q_tf[t] = q_tf.get(t, 0) + 1+ placeholders = ",".join("?" for _ in q_tf)+ term_rows = conn.execute(+ f"SELECT term_id, term, idf FROM vocab_idf WHERE term IN ({placeholders})",+ list(q_tf.keys()),+ ).fetchall()+ sq_sum = 0.0+ for tr in term_rows:+ w = (1.0 + math.log(q_tf[tr[1]])) * float(tr[2])+ q_tfidf_vec[int(tr[0])] = w+ sq_sum += w * w+ q_tfidf_norm = math.sqrt(sq_sum)++ # Evaluate candidates (FTS5 hits, or all filtered candidates if FTS5 hits are sparse)+ if len(bm25_raw_by_rowid) >= max(top_k * 5, 25):+ candidate_rids = list(bm25_raw_by_rowid.keys())+ else:+ candidate_rids = list(filtered.keys())++ q_lower = re.sub(r"\s+", " ", fold_diacritics(query.strip()).lower())+ q_code_tokens = [t for t in re.findall(r"[a-z0-9#_.-]{3,}", q_lower)]+ q_tfidf_keys = tuple((f'"{tid}"', str(tid), qw) for tid, qw in q_tfidf_vec.items())++ scored_candidates: list[tuple[float, float, float, str, tuple[Any, ...]]] = []+ for rid in candidate_rids:+ row = filtered[rid]+ bm25_raw = bm25_raw_by_rowid.get(rid, 0.0)+ bm25_norm = (bm25_raw / max_bm25) if max_bm25 > 0.0 else 0.0++ tfidf_cos = 0.0+ doc_norm = float(row[16])+ if q_tfidf_norm > 0.0 and doc_norm > 0.0:+ tfidf_raw = row[15]+ if any(k_pat in tfidf_raw for k_pat, _, _ in q_tfidf_keys) or "\\" in tfidf_raw:+ doc_vec = json.loads(tfidf_raw)+ dot = 0.0+ for _, tid_str, qw in q_tfidf_keys:+ dw = doc_vec.get(tid_str)+ if dw is not None:+ dot += qw * float(dw)+ if dot > 0.0:+ tfidf_cos = min(1.0, dot / (q_tfidf_norm * doc_norm))++ exact_bonus = 0.0+ if q_lower:+ fault_codes_lower: list[str] = []+ meta_raw = row[14]+ if '"fault_codes"' in meta_raw or "\\" in meta_raw:+ if "\\" in meta_raw:+ fault_codes_lower = [+ fold_diacritics(fc).lower() for fc in (json.loads(meta_raw).get("fault_codes") or ())+ ]+ else:+ meta_lower = meta_raw.lower() if meta_raw.isascii() else fold_diacritics(meta_raw).lower()+ if q_lower in meta_lower or any(tok in meta_lower for tok in q_code_tokens):+ fault_codes_lower = [+ fold_diacritics(fc).lower() for fc in (json.loads(meta_raw).get("fault_codes") or ())+ ]++ if fault_codes_lower and any(q_lower == fc or q_lower in fc for fc in fault_codes_lower):+ exact_bonus = 0.25+ else:+ title_raw = row[4]+ eid_raw = row[3]+ title_lower = title_raw.lower() if title_raw.isascii() else fold_diacritics(title_raw).lower()+ eid_lower = eid_raw.lower() if eid_raw.isascii() else fold_diacritics(eid_raw).lower()+ if q_lower in title_lower or q_lower in eid_lower:+ exact_bonus = 0.18+ else:+ sec_raw = row[5]+ sec_lower = sec_raw.lower() if sec_raw.isascii() else fold_diacritics(sec_raw).lower()+ in_sec_or_text = q_lower in sec_lower+ if not in_sec_or_text:+ text_raw = row[6]+ if text_raw.isascii():+ in_sec_or_text = q_lower in text_raw.lower()+ elif q_lower in text_raw.lower():+ in_sec_or_text = True+ else:+ in_sec_or_text = q_lower in fold_diacritics(text_raw).lower()+ if in_sec_or_text:+ exact_bonus = 0.12+ elif fault_codes_lower and any(tok in fault_codes_lower for tok in q_code_tokens):+ exact_bonus = 0.15++ if bm25_norm == 0.0 and tfidf_cos == 0.0 and exact_bonus == 0.0:+ continue++ hybrid = round(0.55 * bm25_norm + 0.45 * tfidf_cos + exact_bonus, 6)+ scored_candidates.append(+ (hybrid, round(bm25_norm, 6), round(tfidf_cos, 6), row[1], row)+ )++ scored_candidates.sort(key=lambda item: (-item[0], -item[1], -item[2], item[3]))+ snippet_tokens = fts_tokens or tfidf_tokens+ results = []+ for hybrid, bm25_norm, tfidf_cos, _, row in scored_candidates[:top_k]:+ results.append(+ {+ "chunk_id": row[1],+ "domain": row[2],+ "entity_id": row[3],+ "title": row[4],+ "section": row[5],+ "score": hybrid,+ "bm25_score": bm25_norm,+ "tfidf_score": tfidf_cos,+ "snippet": _make_snippet(row[6], snippet_tokens),+ "source_url": row[7],+ "metadata": _reconstruct_metadata_tuple(row),+ }+ )++ elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3)+ return {+ "query": query,+ "filters": filters_dict,+ "total_candidates": len(scored_candidates),+ "latency_ms": elapsed_ms,+ "results": results,+ }+ finally:+ if owns_conn:+ conn.close()+++search = query_kb+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Query the forma-print SQLite FTS5 + TF-IDF RAG knowledge base.")+ parser.add_argument("--query", default="", help="Search query text.")+ parser.add_argument("--domain", choices=["software", "manufacturer", "paper", "report"], default=None)+ parser.add_argument("--tech", default=None, help="Technology filter (e.g. fdm, msla, sla, sls).")+ parser.add_argument("--manufacturer", default=None, help="Manufacturer ID or name filter.")+ parser.add_argument("--protocol", default=None, help="Protocol filter (e.g. mqtt, mqtts, rest, sdcp).")+ parser.add_argument("--category", default=None, help="Category or segment filter.")+ parser.add_argument("--fault-prefix", dest="fault_prefix", default=None, help="Fault code prefix filter.")+ parser.add_argument("--top-k", dest="top_k", type=int, default=5, help="Maximum number of results.")+ parser.add_argument("--db", type=Path, default=DEFAULT_DB_PATH, help="Path to forma_print_kb.sqlite.")+ parser.add_argument("--json", action="store_true", help="Emit JSON response.")+ args = parser.parse_args(argv)++ def _emit_error(msg: str, code: int = 1) -> int:+ if args.json:+ print(json.dumps({"error": msg}, indent=2, ensure_ascii=False))+ else:+ print(f"error: {msg}", file=sys.stderr)+ return code++ if args.top_k <= 0:+ return _emit_error(f"--top-k must be > 0, got {args.top_k}", code=2)++ try:+ response = query_kb(+ query=args.query,+ db_path=args.db,+ domain=args.domain,+ tech=args.tech,+ manufacturer=args.manufacturer,+ protocol=args.protocol,+ category=args.category,+ fault_prefix=args.fault_prefix,+ top_k=args.top_k,+ )+ except (FileNotFoundError, sqlite3.Error, ValueError) as exc:+ return _emit_error(str(exc), code=1)++ if args.json:+ print(json.dumps(response, indent=2, ensure_ascii=False))+ else:+ print(+ f"Query: {response['query']!r} | hits={len(response['results'])} "+ f"(candidates={response['total_candidates']}, latency={response['latency_ms']} ms)"+ )+ for idx, res in enumerate(response["results"], start=1):+ print(+ f"{idx}. [{res['domain']}] {res['entity_id']} — {res['section']} "+ f"(score={res['score']:.4f}, bm25={res['bm25_score']:.3f}, tfidf={res['tfidf_score']:.3f})"+ )+ print(f" {res['snippet']}")+ print(f" source: {res['source_url']}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/research/reports/nurb_inspection.md b/research/reports/nurb_inspection.mdnew file mode 100644index 0000000..d37d290--- /dev/null+++ b/research/reports/nurb_inspection.md@@ -0,0 +1,150 @@+# Architectural Inspection Report: `Shpigford/nurb` & `Shpigford/nurb-benchmarks`++**Inspection Target:** `https://github.com/Shpigford/nurb` (`https://nurb.app`) and `https://github.com/Shpigford/nurb-benchmarks` (`https://nurb.dev/benchmarks`)+**Purpose:** Primary-source architectural analysis of a leading modern agentic-CAD + printability desktop application (`M1a` / `R1.6`) to extract concrete design lessons, benchmark baselines, and explicit non-goals for `crates/forma-print`.++---++## 1. Executive Summary & Identity++| Field | Verified Fact (Primary Source) |+|---|---|+| **Repositories** | `https://github.com/Shpigford/nurb` (`https://nurb.app`); `https://github.com/Shpigford/nurb-benchmarks` (`https://nurb.dev/benchmarks`) |+| **Author / Maintainer** | Josh Pigford (`@Shpigford`, Copyright 2026 Ordinary Systems LLC); observed repo metadata: 659 stars, 66 forks, created `2026-07-25T19:12:10Z` |+| **Observed Versions** | Engine `1.17.0` (`engine/pyproject.toml`), Desktop `1.17.0` (`desktop/src-tauri/tauri.conf.json`) |+| **License** | **`FSL-1.1-MIT`** (Functional Source License, Version 1.1, MIT Future License) — source-available for any non-competing use, converting to plain **`MIT`** 2 years after each GitHub release date |+| **Core Runtime Dependencies** | Python `>=3.13` (`uv_build`), `build123d>=0.11.1` (Apache-2.0) + `OCP` (Apache-2.0) dynamically linking **OCCT** (LGPL-2.1-with-exception), `mcp>=2.2.0` (`27` packages including `starlette`, `uvicorn`, `httpx2`, `pydantic`, `jsonschema`; `~27 MB` in a bare venv per `README.md`), `trimesh>=4.12.2` (MIT), `pillow>=11.0`, `websockets>=16.1.1` |+| **Frontend / Shell Dependencies** | Tauri v2 (`dev.nurb.desktop`), `@nurb/ui` (React), `@nurb/workbench` (React + bundled `three.js` [MIT] Z-up viewer), redistributed SIL OFL 1.1 fonts (`JetBrains Mono`, `Instrument Sans`, `Liberation Sans Bold`, `Archivo Black`, `Stardos Stencil Bold`) |+| **Binary / Installer Footprint Note** | Upstream `README.md` explicitly notes `mcp 2.2.0` adds `~27 MB` across 27 packages, while neither `README.md` nor `tauri.conf.json` publishes a total macOS `.dmg` installer byte size (left explicitly unstated rather than estimated). |++`nurb` is a local-first agentic parametric CAD studio built around Python `build123d`/OCCT, a persistent local HTTP/WebSocket/MCP server backed by SQLite, a 15-rule B-rep printability engine, and a Tauri v2 desktop workbench. Its design validates deterministic geometry-first printability checks and 4-view visual inspection for LLM agents, while its heavy Python/OCCT cold-start (`~45 s`) and multi-process daemon architecture highlight why Forma and `crates/forma-print` should stay pure Rust, stateless, and zero-dependency.++---++## 2. System Architecture & Stack++### 2.1 Python `build123d` / OCCT Backend & Daemon (`serve.py`, `db.py`, `engine_run.py`, `builder.py`)+- **Packaging (`engine/pyproject.toml`)**: Builds `nurb==1.17.0` on Python `>=3.13` via `uv_build`, strictly bounding `build123d>=0.11.1`, `mcp>=2.2.0`, `pillow>=11.0`, `trimesh>=4.12.2`, and `websockets>=16.1.1`.+- **Single Long-Lived Server (`serve.py`)**: Runs `python -m nurb.serve` bound to loopback port `7373` by default. Uses `fcntl.flock` on `serve.lock` to enforce a single instance per workspace/user, bearer-token authentication on `/mcp`, and a `SameOrigin` guard on HTTP and WebSocket (`/ws`) endpoints rejecting non-loopback `Origin` headers.+- **SQLite Persistence (`db.py`)**: Stores full workspace state across relational tables: `projects`, `parts`, `part_revisions`, `build_runs`, `measurements`, `project_files`, `messages`, `pinned_specs`, `attachments`, `labels`, `shares`, plus `deleted` and `changes` sync tables.+- **Cold-Start Mitigation (`CONTRIBUTING.md`, `engine_run.py`)**: Importing OCCT/Python costs **`~45 seconds` cold**. To avoid paying that penalty per edit, `serve.py` keeps a warm worker subprocess (`engine_run.py`, enforcing a `240 s` build timeout), reducing subsequent warm rebuilds to **`30–400 ms`**.+- **Deterministic OCCT Triangulation Optimization (`builder.py`)**: `builder._triangulate` bypassed `build123d`'s `poly.Triangles()` Python iterator — measured at **`536 ms`** on a 7,790-triangle gridfinity shelf — by reading indexed `OCP.BRep_Tool.Triangulation_s` buffers directly (**`6.8 ms`** read time, `~10 ms` meshing, `~30 ms` total rebuild). It also canonicalizes triangle vertex ordering and rounds normals so `arm64` and `x86` hosts emit bit-identical GLB hashes.++### 2.2 Desktop Shell, Frontend Workbench & CLI Removal (`desktop/`, `packages/`)+- **Frontend Packages**: `packages/@nurb/ui` supplies React design tokens and inspector panels; `packages/@nurb/workbench` bundles React + `three.js` into a Z-up interactive viewport compiled into `engine/src/nurb/workbench/`.+- **Tauri v2 Desktop App (`desktop/src-tauri/tauri.conf.json`)**: Targets `version: "1.17.0"` (`identifier: "dev.nurb.desktop"`), ships macOS `.app`/`.dmg` + updater artifacts, and bundles `uv` (`externalBin: ["binaries/uv"]`). On first launch, Tauri provisions a managed CPython runtime, virtual environment, bundled `nurb` wheel, Node, and ACP adapters under `~/Library/Application Support/dev.nurb.desktop`.+- **Removal of Standalone CLI (`v1.0+`)**: As of `v1.0+`, `cli.py` and the standalone PyPI `nurb` CLI (as well as `export.py`) were removed from `main` (returning 404 upstream). The desktop app embeds the engine directly, and external coding agents connect via MCP over `serve.py`.++### 2.3 MCP Contract & Engineering Doctrine (`tools.json`, `mcp_server.py`, `guide.py`, `doctrine.md`)+- **Flat, Explicit Tool Surface (`tools.json`, `mcp_server.py`)**: Exposes Draft 2020-12 validated tools including `list_projects`, `get_project`, `create_project`, `read_guide`, `pin_spec`, `amend_spec`, `read_measurements`, `record_measurement`, `write_part_source`, `edit_part_source`, `run_build`, `set_label`, `read_plate`, and `set_plate`.+- **Envelope Budgeting**: Enforces `MCP_MAX_CHARS = 149000`, progressively degrading oversized responses from inline text -> resource links -> images.+- **Injected Printability Doctrine (`read_guide` + `doctrine.md`)**: Injects empirical FDM design rules directly into agent context: ISO metric fastener clearance/tap tables, 45° corbel overhang design rules, `counterbore` sacrificial 2-layer bridges, and fit clearance bands (`press 0.1 mm`, `snug 0.2 mm`, `moving 0.3 mm`, `free 0.5 mm`).++---++## 3. Printability Checks, Probes, Parametrics, Profiles, Rasterizer & 3MF/Slicer Handoff++### 3.1 15 Printability Rules & B-Rep Face Pinning (`checks.py`, `probe.py`)+`checks.py` implements a **gate-then-check** model:+1. **`solids` gate**: Verifies the built shape is a single valid solid (`solids == 1`). If empty or multi-body, downstream printability checks are silenced so the agent receives one actionable structural failure rather than noisy cascaded warnings.+2. **All 15 Rules**:+ - `solids` — single valid solid check+ - `text` — raised/debossed text stroke width vs. `min_wall`, plus raised letters on bed detection+ - `mesh` — triangle mesh closure/watertightness+ - `overhang` — downward faces `> 45°`, distinguishing bridges from cantilevers+ - `floating` — first-layer geometry starting in mid-air+ - `hole_ceiling` — blind counterbore flat ceilings needing sacrificial bridges or chamfers+ - `min_wall` — inward ray cast corrected by inscribed sphere thickness+ - `sliver` — sub-`1 mm²` degenerate or sliver faces+ - `concave_cosmetic` — fillets/chamfers/polish applied to concave interior edges (tested via `n1 · _into_face(f2)`)+ - `bed_bevel` — bed-contact chamfer/bevel risk reducing adhesion or causing first-layer overhang curl+ - `warp_risk` — first-layer footprint `> 20,000 mm²` with sharp corners (`< 8 mm` radius), scaled **5× tighter** for ABS/ASA+ - `pin` — free-standing pins `< 5 mm` diameter with height `> 2 × diameter`+ - `stability` — Center of Mass projection falling outside the bed-contact footprint+ - `projection_ratio` — unsupported reach/height ratio `> 2.5`+ - `build_volume` — fit check against active `printers.toml` envelope+3. **Dual Reporting & Face Pinning (`probe.py`)**: Every `Finding` stores both an agent-dense `message` and a user-friendly `plain` explanation plus `(x, y, z)` coordinates (`where`), which `probe.py` (`finding_faces`, `report`) resolves back onto exact B-rep faces.++### 3.2 Parametric Sliders & Measurement Provenance (`registry.py`, `measurements.py`)+- **`@part` Introspection (`registry.py`)**: Inspects Python keyword defaults and type annotations to generate live UI controls automatically (`float` -> continuous slider, `int` -> integer-step slider, `bool` -> checkbox, `Literal[...]` -> dropdown, `FilamentColor` -> color picker, `draft=False` -> runtime-injected flag to skip slow cosmetic fillets during iteration), paired with Google-style docstrings.+- **Anti-Guessing Measurement Guard (`measurements.py`)**: `measured(name)` reads `measurements.toml` requiring `value`, `unit="mm"`, `how` provenance (and optional `provisional=true`), raising `MeasurementError` when an unmeasured real-world dimension is referenced. This prevents LLMs from silently fabricating physical mating dimensions.++### 3.3 Auto-Orientation, Printer Profiles & Zero-GPU Rasterizer (`orient.py`, `printers.toml`, `raster.py`)+- **Orientation (`orient.py`)**: `stand(shape, tilt=45.0, axis=Axis.Y, facet=2.0, fins=True)` tilts thin/tall parts diagonally onto a shaved `>= 2 mm` bed flat and automatically adds break-away support fins, pads, and `0.3 mm` single-layer tines when height exceeds `LEVERAGE * facet`.+- **27 Printer Profiles (`printers.toml`)**: Built-in hardware profiles spanning:+ - **Bambu Lab (10)**: `x1c`, `x2d`, `p1s`, `p2s`, `p1p`, `a1`, `a1_mini`, `h2c`, `h2d`, `h2s`+ - **Prusa (6)**: `mk4s`, `core_one`, `core_one_l`, `mk3`, `mini`, `xl`+ - **Creality (2)**: `ender_3_v3`, `k2_plus`+ - **Anycubic (1)**: `kobra_2`+ - **Voron (8)**: `0`, `trident_250`, `trident_300`, `trident_350`, `2_4_250`, `2_4_300`, `2_4_350`, `switchwire`+- **Zero-GPU 4-View Rasterizer (`raster.py`, `render.py`)**: Pure `numpy` + `zlib`/`struct` tile z-buffer rasterizer rendering `iso`, `back`, `top`, and `under` cameras into a **single 2×2 composite PNG** — explicitly engineered to cut VLM image-token cost **4×** relative to sending 4 separate PNGs — while avoiding any import of `nurb`/OCCT (saving a `~4 s` import penalty).++### 3.4 Stdlib `.3mf` & Local Slicer CLI Bridge (`threemf.py`, `slicing.py`, `engine_run.py`)+- **`threemf.py`**: Python stdlib-only (`zipfile`, `xml.etree.ElementTree`) multi-file `.3mf` reader supporting Bambu/Orca `3D/Objects/*.model` production extension paths and `Metadata/model_settings.config`.+- **Multi-Format Export (`engine_run.py`)**: Exports multi-color `.3mf` (`builder.write_3mf`), `.stl`, and `.step`.+- **Local Slicer Handoff (`slicing.py`)**: Discovers locally installed **OrcaSlicer**, **BambuStudio** (invoked headlessly via `--load-settings`, `--load-filaments`, `--slice`, `--outputdir`), and **PrusaSlicer** (for Prusa INI presets and "Open in"), injects `TUNED` settings (`gyroid`, `10%` infill, `wall_loops=3`, plus `5 mm` `outer_only` brim triggered automatically by `warp_risk` or `stability` findings), and parses G-code footer comments for sliced print time and filament grams.++---++## 4. `Shpigford/nurb-benchmarks` Analysis++### 4.1 Architecture & Task Taxonomy+- **Separation from Engine Repo**: Split into `https://github.com/Shpigford/nurb-benchmarks` in Aug 2026 so benchmark transcripts and logs do not bloat the `nurb` repo (`FSL-1.1-MIT`; depends on `nurb>=0.23`, `shapely>=2`, `networkx>=3`, `rtree>=1`).+- **6 Tasks Across 3 Design Classes**:+ 1. **Spec**: `tasks/cable_clip`, `tasks/bit_block` (grid of chamfered pocket mouths with `2.0 mm` webs near OCCT's adjacent-chamfer failure limit, plus integer-parameterized flex probes).+ 2. **Function**: `tasks/bundle_holder`, `tasks/pole_rest` (demands a continuous `120°` backed arc around a measured pole), `tasks/valve_knob` (virtual D-stem inserted into bore, graded on clearance/slop bands plus a `20°` rotation collision test).+ 3. **Judgment**: `tasks/leg_cup` (tests `measured()` discipline and provisional provenance handling against a rewritten `measurements.toml`).+- **Gate-then-Grade Isolation**: Candidate code runs inside an isolated worker and crosses the grading boundary strictly as B-rep geometry. A submission must build within the timeout and produce **exactly 1 valid solid** (else score `0`), then receives a weighted score: **`0.3` printability rules + `0.5` B-rep dimensional assertions + `0.2` flex probes**.++### 4.2 Verified Leaderboard Telemetry (`REPORT.md`)+Representative rows from `REPORT.md` demonstrate the high token, cost, and wall-clock budgets required even when frontier models have full `nurb` MCP feedback:++| Task (Seed) | Model & Effort | Score | `pass@1` | Tokens | Cost (USD) | Wall Time |+|---|---|---:|---:|---:|---:|---:|+| `bit_block` (seed 13) | `claude-fable-5` medium | `1.000` | `1.00` | `3,204` | `$0.95` | `139 s` |+| `bit_block` (seed 13) | `claude-fable-5` high | `1.000` | — | `9,028` | `$1.92` | `219 s` |+| `bit_block` (seed 13) | `claude-opus-5` medium | `1.000` | — | `8,536` | `$1.13` | `254 s` |+| `bit_block` (seed 13) | `claude-sonnet-5` low | `1.000` | — | `6,546` | `$0.38` | `243 s` |+| `bit_block` (seed 13) | `claude-haiku-4-5` high | `0.806` | `0.33` | `30,793` | `$0.49` | `488 s` |+| `bit_block` (seed 13) | `gpt-5.6-sol` medium | `1.000` | — | `424,634`* | `$1.80` | `208 s` |+| `bit_block` (seed 13) | `gpt-5.6-luna` high | `0.843` | `0.00` | `480,207`* | `$0.11` | `222 s` |+| `bit_block` (seed 13) | `grok-4.6` low | `1.000` | — | `78,719` | `$0.05` | `98 s` |+| `bundle_holder` (seed 13) | `claude-fable-5` medium | `1.000` | — | `8,667` | `$1.47` | `253 s` |+| `bundle_holder` (seed 13) | `claude-fable-5` high | `1.000` | — | `36,715` | `$4.84` | `652 s` |+| `bundle_holder` (seed 13) | `claude-opus-5` high | `1.000` | — | `66,870` | `$4.02` | `1140 s` |+| `bundle_holder` (seed 13) | `gpt-5.6-sol` high | `1.000` | — | `593,633`* | `$2.53` | `331 s` |++*\*Note: `REPORT.md` notes `gpt-5.6-*` token counters include full per-turn context accumulation.*++---++## 5. Latency, Size & Dependency Profile vs. Forma / `crates/forma-print`++| Dimension | `Shpigford/nurb` (`v1.17.0`) | Forma Core + `crates/forma-print` Tier 1 |+|---|---|---|+| **Language & Geometry Kernel** | Python `>=3.13` + `build123d` / `OCP` (OCCT C++ B-rep) + `trimesh` + `numpy` + `pillow` | Pure Rust polyhedral/CSG kernel (`forma-core`, `forma-lang`) + `forma-print` (`0` new external crates) |+| **Binary / Footprint** | Tauri v2 desktop + `uv` + CPython + OCCT + `mcp 2.2.0` (`~27 MB` across 27 Python packages; total `.dmg` size not published in repo docs) | `forma` CLI `~1.7–1.8 MB` (`1,818,160 B` baseline), `forma-mcp` `1,775,040 B`, `wasm/forma.wasm` `~0.8 MB` (`786,102 B`); `forma-print` excluded from `default-members` (`0 B` core delta; target `~160–220 KB` opt-in delta) |+| **Cold Boot & Execution Latency** | **`~45 s`** OCCT cold import (`~4 s` even without full `nurb` in `raster.py`), requiring a persistent daemon; **`30–400 ms`** warm rebuilds (`engine_run.py` 240 s timeout) | Stateless cold CLI/MCP execution: `< 25 ms` pure-Rust DFM audit (`~8–25 ms` on 10k tris per `contribute/forma-print.md`), `< 4 ms` 4-view heatmap PNG, `~15–40 ms` auto-orientation |+| **Runtime Architecture** | Stateful single-instance daemon (`serve.py` port `7373`, `serve.lock`, SQLite DB, WebSocket `/ws`, Tauri desktop) | Stateless, transactional CLI (`forma-print`) and opt-in stdio MCP (`forma-print --mcp`), zero background daemons or DBs |+| **MCP Token Budget** | Full `tools.json` suite + `MCP_MAX_CHARS = 149000` + `read_guide` (`doctrine.md`) | Core `forma-mcp`: **`788` `o200k` tokens** (`0` extra tokens added); opt-in `forma-print --mcp` (4 tools): target **`~380` `o200k` tokens** |+| **3MF & STEP Readiness** | `nurb` exports multi-color `.3mf`, `.stl`, `.step` via OCCT/`builder.write_3mf` and invokes local slicers via `slicing.py` | **Current core gap (`crates/forma-core/src/export.rs:483-746`)**: core `write_3mf_bytes` uses Stored (`method=0`) ZIP, `unit="meter"`, 1 `<object>` without `<basematerials>`/`<m:colorgroup>`, and 3 files missing all `Metadata/*`; core `write_step_bytes` emits `SI_UNIT($,.METRE.)`. `crates/forma-print/src/export_3mf.rs` fills this cleanly with pure-Rust RFC-1951 Deflate, `unit="millimeter"` / `SI_UNIT(.MILLI.,.METRE.)`, material/color groups, Bambu/Orca/Prusa `Metadata/*`, and `256×256` thumbnail. |+| **Print Technologies Covered** | 27 FDM profiles (`printers.toml`: Bambu, Prusa, Creality, Anycubic, Voron) | 18 verified profiles across **FDM, MSLA resin, and SLS PA12** (`profiles.rs`), plus 9 material profiles and CNC Kitchen M2–M5 heat-set inserts |+| **License** | `FSL-1.1-MIT` (converts to MIT after 2 years) + LGPL-2.1 OCCT | `GPL-3.0-or-later` (`Cargo.toml:22`) |++---++## 6. Concrete Architectural Lessons & Explicit Non-Goals for `crates/forma-print`++### 6.1 Concrete Lessons to Adopt in `crates/forma-print`+1. **`dfm.rs` (Single-Body Gate + Non-Overlapping Rule Taxonomy)**: Adopt `nurb`'s `solids == 1` gating pattern (`WT=ok && NM=0 && B=0` checked first so broken non-manifold meshes don't spam downstream thickness/overhang/stability false positives), and include distinct rules for `hole_ceiling` (unsupported flat blind ceilings vs. open bridges), `warp_risk` (large sharp-cornered bed footprints scaled by material warp sensitivity such as ABS/ASA), `pin` slenderness, and `stability` (CoM projection inside 2D bed convex hull).+2. **`heatmap.rs` (Single 2×2 Composite PNG)**: `nurb/raster.py` explicitly packs 4 orthographic/isometric views into one 2×2 PNG to reduce VLM token cost 4×. Keep `heatmap.rs` producing a single 4-view diagnostic PNG via `forma_core::render::render_quad_png_bytes` with 5-slot `face.mat_id` severity coloring.+3. **`profiles.rs` (Centralized Typed Machine + Material Matrix)**: Follow `printers.toml`'s centralized profile discipline across `bambu_*`, `prusa_*`, `voron_24_*`, `creality_*`, plus MSLA (`elegoo_mars_5_ultra`, `elegoo_saturn_4_ultra`, `formlabs_form_4`) and SLS (`formlabs_fuse_1p`), using exact `mm` and degrees consistently everywhere (`probe.py` lesson).+4. **`orient.rs` (Practical Bed Flat & Stability Scoring)**: `nurb`'s `stand()` shows that thin/tall parts often need diagonal rotation + a flat bed landing + stability verification. `orient.rs` should evaluate planar face clusters and convex-hull facets against weighted `(overhangs, islands, support_vol, bed_area, z_height, ams_swaps)` and emit deterministic transforms aligned to `z0=0`.+5. **`export_3mf.rs` (Self-Contained Deflate Multi-Color `.3mf` + mm `.step`)**: Because `crates/forma-core/src/export.rs:483-746` is read-only and emits Stored (`method=0`) meter-scaled 3-file `.3mf` and meter-scaled `.step`, `export_3mf.rs` must implement pure-Rust RFC-1951 Deflate, `unit="millimeter"`, `<basematerials>`, `<m:colorgroup>`, per-`mat_id` sub-meshes, `Metadata/{model_settings.config,project_settings.config,plate_1.json,Slic3r_PE_model.config,plate_1.png}`, and `SI_UNIT(.MILLI.,.METRE.)` `.step` with zero external crates (`threemf.py` zero-extra-library lesson).+6. **`mcp.rs` & Tests (Boring Opt-In MCP + Gate-Then-Grade Flex Tests)**: Keep `forma-print --mcp` strictly opt-in (`print_check`, `print_prep`, `print_export`, `print_profiles`) so core `forma-mcp` stays `< 800` `o200k` tokens (`788`), and structure `crates/forma-print/tests/` around `nurb-benchmarks`-style gate-then-grade assertions (`WT=ok NM=0 B=0` before DFM grading) plus parameterized dimensional sweep tests.++### 6.2 Explicit Non-Goals for `crates/forma-print` Tier 1+1. **No Python, OCCT, `build123d`, or `trimesh` Dependencies**: Importing OCCT/Python breaks Forma's `~1.7–1.8 MB` native / `~0.8 MB` WASM footprint, `0` new external crates rule, and `< 25 ms` cold execution budget with a `~45 s` cold boot.+2. **No Persistent Daemon, SQLite DB, Tauri Shell, or WebSocket Three.js Workbench**: `forma-print` is a stateless CLI/library + opt-in stdio MCP binary, not an interactive desktop CAD IDE.+3. **No Tier 1 External Slicer Execution or Full Slicer Replacement**: Equivalent functionality to `nurb/slicing.py` (invoking `orca-slicer`/`BambuStudio`/`prusa-slicer` subprocesses) remains strictly deferred to opt-in Tier 3 (`slicer-cli`), and `forma-print` never attempts to replace G-code toolpath generation.+4. **No `FSL-1.1-MIT` Code Copying**: Because `forma` is `GPL-3.0-or-later` (`Cargo.toml:22`) and `nurb` is `FSL-1.1-MIT` (non-competing use restriction until 2-year MIT conversion), only clean-room architectural patterns and publicly documented format contracts are adopted.diff --git a/research/schemas/manufacturers.schema.json b/research/schemas/manufacturers.schema.jsonnew file mode 100644index 0000000..41efbf1--- /dev/null+++ b/research/schemas/manufacturers.schema.json@@ -0,0 +1,290 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://forma-print.local/schemas/manufacturers.schema.json",+ "title": "Forma-Print 3D Printer Manufacturer & Hardware Ecosystem Record",+ "description": "Schema for manufacturer manuals, direct local/cloud communication protocols, monitoring/sensors, and troubleshooting/fault records in research/corpus/manufacturers.jsonl.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "manufacturer",+ "technologies",+ "segment",+ "representative_models",+ "direct_communication",+ "monitoring_and_sensors",+ "troubleshooting_and_faults",+ "source_urls",+ "source_verified",+ "availability_notes",+ "relevance_to_forma_print"+ ],+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z0-9][a-z0-9_-]*$",+ "minLength": 3,+ "description": "Unique kebab-case or snake_case identifier for the manufacturer or ecosystem."+ },+ "manufacturer": {+ "type": "string",+ "minLength": 2,+ "description": "Display name of the manufacturer or hardware/firmware ecosystem."+ },+ "technologies": {+ "type": "array",+ "minItems": 1,+ "uniqueItems": true,+ "items": {+ "type": "string",+ "enum": [+ "FDM",+ "MSLA",+ "SLA",+ "SLS",+ "CFF",+ "MJF",+ "PolyJet",+ "FGF",+ "UV_Inkjet"+ ]+ },+ "description": "Additive manufacturing technologies supported by this manufacturer or ecosystem."+ },+ "segment": {+ "type": "string",+ "enum": [+ "consumer",+ "prosumer",+ "industrial",+ "ecosystem"+ ],+ "description": "Market/deployment segment classification."+ },+ "representative_models": {+ "type": "array",+ "minItems": 1,+ "uniqueItems": true,+ "items": {+ "type": "string",+ "minLength": 2+ },+ "description": "Representative printer models, controller boards, or platform families."+ },+ "direct_communication": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "local_protocols",+ "cloud_protocols",+ "ports",+ "auth_and_modes",+ "upload_print_control_endpoints",+ "offline_capable",+ "offline_mode_notes",+ "status"+ ],+ "properties": {+ "local_protocols": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 2+ },+ "description": "Verified local LAN/USB/bus protocols or explicit unavailable markers."+ },+ "cloud_protocols": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 2+ },+ "description": "Verified cloud protocols/services or explicit none_native / unavailable markers."+ },+ "ports": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 2+ },+ "description": "Annotated network ports, serial baud rates, or bus identifiers."+ },+ "auth_and_modes": {+ "type": "string",+ "minLength": 5,+ "description": "Authentication mechanisms, LAN/Developer modes, and firmware gating details."+ },+ "upload_print_control_endpoints": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 2+ },+ "description": "Verified API endpoints, MQTT topics, G/M-code commands, or explicit not_publicly_documented / unavailable markers."+ },+ "offline_capable": {+ "type": "boolean",+ "description": "Whether the hardware supports printing without public internet connectivity."+ },+ "offline_mode_notes": {+ "type": "string",+ "minLength": 5,+ "description": "Details on USB/SD offline printing and air-gapped LAN mode behavior."+ },+ "status": {+ "type": "string",+ "enum": [+ "open_official",+ "gated_local_or_community_re",+ "cloud_first_limited_local",+ "closed_or_usb_only"+ ],+ "description": "Openness classification for third-party software integration."+ }+ }+ },+ "monitoring_and_sensors": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "thermal_sensors",+ "cameras",+ "lidar_and_ai_inspection",+ "filament_and_spool_systems",+ "accelerometers_input_shaper",+ "bed_probes",+ "status_error_feeds"+ ],+ "properties": {+ "thermal_sensors": {+ "type": "string",+ "minLength": 3,+ "description": "Hotend, bed, chamber, UV LED, or MCU thermal sensing capabilities."+ },+ "cameras": {+ "type": "string",+ "minLength": 3,+ "description": "Built-in or supported camera hardware, stream protocols, and constraints."+ },+ "lidar_and_ai_inspection": {+ "type": "string",+ "minLength": 3,+ "description": "LiDAR, laser micrometer, or AI vision inspection capabilities, or explicit unavailable marker."+ },+ "filament_and_spool_systems": {+ "type": "string",+ "minLength": 3,+ "description": "Filament runout/jam sensors, RFID/NFC spool systems, AMS/CFS/MMU, or resin/powder tracking."+ },+ "accelerometers_input_shaper": {+ "type": "string",+ "minLength": 3,+ "description": "Accelerometer hardware and input shaper resonance compensation support, or explicit unavailable marker."+ },+ "bed_probes": {+ "type": "string",+ "minLength": 3,+ "description": "Bed leveling, loadcell, eddy current, inductive, optical, or mechanical probe mechanisms."+ },+ "status_error_feeds": {+ "type": "string",+ "minLength": 3,+ "description": "Real-time status/error telemetry channels and protocols."+ }+ }+ },+ "troubleshooting_and_faults": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "fault_code_taxonomy",+ "example_fault_codes",+ "diagnostic_logs",+ "official_kb_urls"+ ],+ "properties": {+ "fault_code_taxonomy": {+ "type": "string",+ "minLength": 5,+ "description": "Structure and prefixes of vendor/firmware fault codes and error messages."+ },+ "example_fault_codes": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "code",+ "description",+ "kb_url"+ ],+ "properties": {+ "code": {+ "type": "string",+ "minLength": 1,+ "description": "Verified fault code or canonical firmware error string."+ },+ "description": {+ "type": "string",+ "minLength": 5,+ "description": "Verified fault cause/symptom description."+ },+ "kb_url": {+ "type": "string",+ "format": "uri",+ "pattern": "^https?://[^\\s]+$",+ "description": "Primary KB or firmware documentation URL for the fault."+ }+ }+ }+ },+ "diagnostic_logs": {+ "type": "string",+ "minLength": 5,+ "description": "Log file formats, paths, serial dump mechanisms, and export procedures."+ },+ "official_kb_urls": {+ "type": "array",+ "minItems": 1,+ "uniqueItems": true,+ "items": {+ "type": "string",+ "format": "uri",+ "pattern": "^https?://[^\\s]+$"+ },+ "description": "Non-empty list of verified official knowledge base / specification URLs."+ }+ }+ },+ "source_urls": {+ "type": "array",+ "minItems": 1,+ "uniqueItems": true,+ "items": {+ "type": "string",+ "format": "uri",+ "pattern": "^https?://[^\\s]+$"+ },+ "description": "Primary source documentation and repository URLs supporting all claims."+ },+ "source_verified": {+ "type": "boolean",+ "description": "Whether claims and primary URLs were verified against primary documentation."+ },+ "availability_notes": {+ "type": "string",+ "minLength": 10,+ "description": "Explicit notes on open specs, community reverse engineering, gated SDKs, and unavailable/undocumented items."+ },+ "relevance_to_forma_print": {+ "type": "string",+ "minLength": 10,+ "description": "Engineering mapping to forma-print profiles, DFM checks, 3MF/STEP export, LAN dispatch, or RAG troubleshooting."+ }+ }+}diff --git a/research/schemas/papers.schema.json b/research/schemas/papers.schema.jsonnew file mode 100644index 0000000..989c2b4--- /dev/null+++ b/research/schemas/papers.schema.json@@ -0,0 +1,105 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://forma-print.local/schemas/papers.schema.json",+ "title": "Forma-Print Academic Paper Record",+ "description": "Schema for mesh optimization and 3D-modeling-for-3D-printing academic papers in research/corpus/papers.jsonl.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "title",+ "authors",+ "year",+ "venue",+ "category",+ "doi_or_arxiv_id",+ "url",+ "summary",+ "key_algorithm",+ "relevance_to_forma_print",+ "source_verified"+ ],+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z0-9][a-z0-9_-]*$",+ "minLength": 3,+ "description": "Unique kebab-case or snake_case identifier (e.g., luo-2012-chopper)."+ },+ "title": {+ "type": "string",+ "minLength": 5,+ "pattern": "\\S",+ "description": "Exact verified paper title."+ },+ "authors": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1,+ "pattern": "\\S"+ },+ "description": "Non-empty list of verified author names."+ },+ "year": {+ "type": "integer",+ "minimum": 1990,+ "maximum": 2030,+ "description": "Integer publication year."+ },+ "venue": {+ "type": "string",+ "minLength": 2,+ "pattern": "\\S",+ "description": "Verified journal, conference, or repository venue."+ },+ "category": {+ "type": "string",+ "enum": [+ "printability_optimization",+ "overhang_support_minimization",+ "structural_wall_thickness",+ "hollowing_drainage_suction",+ "decomposition_packing_interlocking",+ "clearance_tolerance_orientation",+ "multi_axis_curved_slicing"+ ],+ "description": "Primary research taxonomy category."+ },+ "doi_or_arxiv_id": {+ "type": "string",+ "minLength": 3,+ "pattern": "\\S",+ "description": "Verified DOI, arXiv ID, or explicit unavailable marker on a primary page."+ },+ "url": {+ "type": "string",+ "format": "uri",+ "pattern": "^https?://[A-Za-z0-9.-]+\\.[A-Za-z]{2,}(?:/[^\\s]*)?$",+ "description": "Verified primary source URL (DOI resolver, publisher page, or arXiv)."+ },+ "summary": {+ "type": "string",+ "minLength": 30,+ "pattern": "\\S",+ "description": "Technical summary of problem, method, and findings."+ },+ "key_algorithm": {+ "type": "string",+ "minLength": 30,+ "pattern": "\\S",+ "description": "Concrete algorithmic formulation (data structures, objective, geometric criteria)."+ },+ "relevance_to_forma_print": {+ "type": "string",+ "minLength": 20,+ "pattern": "\\S",+ "description": "Engineering mapping to forma-print DFM checks, orientation, export, or Tier 2/3 ops."+ },+ "source_verified": {+ "type": "boolean",+ "description": "Whether bibliographic fields and primary URL were independently verified."+ }+ }+}diff --git a/research/schemas/rag_chunks.schema.json b/research/schemas/rag_chunks.schema.jsonnew file mode 100644index 0000000..ad511c4--- /dev/null+++ b/research/schemas/rag_chunks.schema.json@@ -0,0 +1,237 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://forma-print.local/schemas/rag_chunks.schema.json",+ "title": "Forma-Print RAG Knowledge Base Chunk",+ "description": "Schema for normalized, deterministic RAG chunks generated from research/corpus/*.jsonl and research/reports/nurb_inspection.md.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "chunk_id",+ "domain",+ "entity_id",+ "title",+ "section",+ "text",+ "metadata",+ "source_url",+ "token_count",+ "embedding_ready_text"+ ],+ "properties": {+ "chunk_id": {+ "type": "string",+ "pattern": "^[a-z0-9][a-z0-9_:-]*$",+ "minLength": 3,+ "description": "Deterministic unique chunk identifier (e.g., mf:bambu_lab:fault:0)."+ },+ "domain": {+ "type": "string",+ "enum": [+ "software",+ "manufacturer",+ "paper",+ "report"+ ],+ "description": "Source corpus or report domain."+ },+ "entity_id": {+ "type": "string",+ "pattern": "^[a-z0-9][a-z0-9_-]*$",+ "minLength": 2,+ "description": "Canonical parent record identifier or report identifier."+ },+ "title": {+ "type": "string",+ "minLength": 2,+ "pattern": "\\S",+ "description": "Human-readable entity or document title."+ },+ "section": {+ "type": "string",+ "minLength": 2,+ "pattern": "\\S",+ "description": "Aspect, fault code, or markdown subsection heading."+ },+ "text": {+ "type": "string",+ "minLength": 20,+ "pattern": "\\S",+ "description": "Normalized chunk body text."+ },+ "metadata": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "tech",+ "manufacturer",+ "protocol",+ "category",+ "fault_code_prefix",+ "tags"+ ],+ "properties": {+ "tech": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 2,+ "pattern": "\\S"+ },+ "description": "Normalized lowercase printing technologies (e.g., fdm, msla, sla, sls), or [] if tech-agnostic."+ },+ "manufacturer": {+ "type": [+ "string",+ "null"+ ],+ "minLength": 2,+ "pattern": "\\S",+ "description": "Lowercase manufacturer id for manufacturer chunks, otherwise null."+ },+ "protocol": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 2,+ "pattern": "\\S"+ },+ "description": "Normalized lowercase communication/control protocols, or [] if none."+ },+ "category": {+ "type": "string",+ "minLength": 2,+ "pattern": "\\S",+ "description": "Domain-specific category or segment."+ },+ "fault_code_prefix": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "pattern": "\\S"+ },+ "description": "Extracted fault code prefixes and exact fault codes, or [] for non-fault chunks."+ },+ "tags": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "pattern": "\\S"+ },+ "description": "Deduplicated sorted lowercase metadata tags."+ },+ "source_urls": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uri",+ "pattern": "^https?://[^\\s]+$"+ },+ "description": "Supporting primary-source URLs."+ },+ "source_file": {+ "type": "string",+ "minLength": 1,+ "pattern": "\\S",+ "description": "Relative repository path of the source file."+ },+ "segment": {+ "type": [+ "string",+ "null"+ ],+ "minLength": 2,+ "description": "Manufacturer market segment when applicable."+ },+ "status": {+ "type": [+ "string",+ "null"+ ],+ "minLength": 2,+ "description": "Manufacturer direct-communication openness status when applicable."+ },+ "offline_capable": {+ "type": [+ "boolean",+ "null"+ ],+ "description": "Whether offline/LAN printing is supported when applicable."+ },+ "license": {+ "type": [+ "string",+ "null"+ ],+ "minLength": 1,+ "description": "Software/report license string when applicable."+ },+ "year": {+ "type": [+ "integer",+ "null"+ ],+ "minimum": 1990,+ "maximum": 2030,+ "description": "Publication year for academic papers."+ },+ "doi_or_arxiv_id": {+ "type": [+ "string",+ "null"+ ],+ "minLength": 3,+ "description": "DOI or arXiv identifier for academic papers."+ },+ "fault_codes": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "pattern": "\\S"+ },+ "description": "Exact fault code strings associated with this chunk."+ }+ }+ },+ "source_url": {+ "type": "string",+ "format": "uri",+ "pattern": "^https?://[^\\s]+$",+ "description": "Primary verifiable HTTP/HTTPS source URL for this chunk."+ },+ "token_count": {+ "type": "integer",+ "minimum": 1,+ "description": "Deterministic lexical token count of text."+ },+ "embedding_ready_text": {+ "type": "string",+ "minLength": 20,+ "pattern": "\\S",+ "description": "Context-prefixed text suitable for lexical or dense vector embedding."+ },+ "embedding_dim": {+ "type": [+ "integer",+ "null"+ ],+ "minimum": 1,+ "description": "Optional dense vector dimension (null in stdlib lexical+TF-IDF build)."+ },+ "embedding_model": {+ "type": [+ "string",+ "null"+ ],+ "minLength": 1,+ "description": "Optional dense embedding model identifier (null in stdlib lexical+TF-IDF build)."+ },+ "content_hash": {+ "type": "string",+ "pattern": "^[0-9a-f]{64}$",+ "description": "SHA-256 hex digest of canonical chunk payload."+ }+ }+}diff --git a/research/schemas/software.schema.json b/research/schemas/software.schema.jsonnew file mode 100644index 0000000..5ea6b02--- /dev/null+++ b/research/schemas/software.schema.json@@ -0,0 +1,149 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://forma.local/schemas/software.schema.json",+ "title": "Forma-Print Open-Source 3D Printing & Agentic CAD Software Record",+ "description": "Schema for verified open-source 3D printing software, mesh libraries, host/fleet controllers, firmware, programmatic CAD tools, and modern agentic CAD apps (with explicit contrast entries for proprietary/closed tools).",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "name",+ "category",+ "repo_or_primary_url",+ "source_urls",+ "license",+ "languages",+ "capabilities",+ "workflows",+ "input_formats",+ "output_formats",+ "cli_or_api_flags",+ "three_mf_metadata_schema",+ "architectural_lessons_for_forma_print",+ "source_verified",+ "availability_notes",+ "relevance_to_forma_print"+ ],+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z0-9]+(?:_[a-z0-9]+)*$",+ "description": "Unique snake_case identifier."+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "description": "Human-readable software or library name."+ },+ "category": {+ "type": "string",+ "enum": [+ "slicer",+ "mesh_repair_analysis",+ "host_fleet_spool",+ "firmware",+ "programmatic_cad_cli",+ "modern_agentic_cad"+ ],+ "description": "Primary R1 software taxonomy category."+ },+ "repo_or_primary_url": {+ "type": "string",+ "pattern": "^https?://",+ "description": "Canonical source repository URL or primary product documentation URL."+ },+ "source_urls": {+ "type": "array",+ "minItems": 1,+ "uniqueItems": true,+ "items": {+ "type": "string",+ "pattern": "^https?://"+ },+ "description": "Verified primary-source URLs supporting this record."+ },+ "license": {+ "type": "string",+ "minLength": 1,+ "description": "Verified SPDX license, source-available terms, proprietary terms, or explicit undeclared license note."+ },+ "languages": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1+ },+ "description": "Primary implementation languages or explicit unavailable marker for closed-source binaries."+ },+ "capabilities": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1+ },+ "description": "Verified functional capabilities and domain features."+ },+ "workflows": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1+ },+ "description": "Supported operational workflows (GUI, headless CLI, daemon/API, embedded library, etc.)."+ },+ "input_formats": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1+ },+ "description": "Supported input file formats, protocols, or data representations."+ },+ "output_formats": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1+ },+ "description": "Supported output file formats, streams, or API responses."+ },+ "cli_or_api_flags": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "string",+ "minLength": 1+ },+ "description": "Documented CLI flags, REST/JSON-RPC/MCP endpoints, programmatic APIs, or explicit statement when GUI-only/no public CLI exists."+ },+ "three_mf_metadata_schema": {+ "type": "string",+ "minLength": 1,+ "description": "How the tool reads/writes 3MF and slicer-specific Metadata/* files, or explicit none/not_applicable note."+ },+ "architectural_lessons_for_forma_print": {+ "type": "string",+ "minLength": 1,+ "description": "Concrete architectural patterns, pitfalls, or interface contracts extracted for crates/forma-print."+ },+ "source_verified": {+ "type": "boolean",+ "description": "Whether primary sources were verified for this record."+ },+ "availability_notes": {+ "type": "string",+ "minLength": 1,+ "description": "Availability, licensing nuances, archival status, or closed/proprietary constraints."+ },+ "relevance_to_forma_print": {+ "type": "string",+ "minLength": 1,+ "description": "Concrete engineering relevance to forma-print Tier 1-3 or RAG retrieval."+ }+ }+}diff --git a/research/scripts/bench_efficiency.py b/research/scripts/bench_efficiency.pynew file mode 100644index 0000000..707d848--- /dev/null+++ b/research/scripts/bench_efficiency.py@@ -0,0 +1,1547 @@+#!/usr/bin/env python3+"""Reproducible offline efficiency & justification benchmark for Forma + RAG KB + forma-print.++Measures dynamically against compiled release binaries, the read-only SQLite RAG DB,+and checked-in test fixtures (using tempfile.TemporaryDirectory for zero side effects):+ 1. Artifact & binary footprints (forma, forma-mcp, forma-print, forma.wasm, RAG DB, corpus)+ 2. MCP stdio JSON-RPC 2.0 schema & tool-call o200k_base token probes+ 3. Deterministic CLI geometry/DFM/orient/export benchmarks (p50/p95/min/max ms + outputs)+ 4. RAG KB latency, token compression, and primary-source citation benchmarks (18 queries)+ 5. Published repo reference baselines (clearly tagged source_type="published_repo_baseline")++Dependencies: Python 3 stdlib + tiktoken.+Usage:+ python3 research/scripts/bench_efficiency.py+ python3 research/scripts/bench_efficiency.py --json+ python3 research/scripts/bench_efficiency.py --runs 15 --rag-runs 3 --json+"""++from __future__ import annotations++import argparse+import json+import math+import os+import sqlite3+import subprocess+import sys+import tempfile+import time+import zipfile+from pathlib import Path+from typing import Any+from urllib.parse import urlparse++import tiktoken++REPO_ROOT = Path(__file__).resolve().parents[2]+if str(REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(REPO_ROOT))++from research.rag import build_rag, query_rag # noqa: E402++TARGET_RELEASE = REPO_ROOT / "target" / "release"+FORMA_BIN = TARGET_RELEASE / "forma"+FORMA_MCP_BIN = TARGET_RELEASE / "forma-mcp"+FORMA_PRINT_BIN = TARGET_RELEASE / "forma-print"+WASM_BIN = REPO_ROOT / "wasm" / "forma.wasm"+RAG_DB_PATH = REPO_ROOT / "research" / "rag" / "forma_print_kb.sqlite"+CORPUS_DIR = REPO_ROOT / "research" / "corpus"+NURB_REPORT_PATH = REPO_ROOT / "research" / "reports" / "nurb_inspection.md"+FIXTURES_DIR = REPO_ROOT / "tests" / "e2e" / "fixtures"++# Representative 18-query suite spanning software (3), report (1), manufacturers (8), papers (6).+RAG_QUERY_SUITE: list[dict[str, Any]] = [+ {+ "id": "sw_orcaslicer_3mf",+ "kwargs": {"query": "OrcaSlicer 3MF model_settings.config Metadata", "domain": "software"},+ "expect_rank1": "orcaslicer",+ "expect_any": {"orcaslicer"},+ },+ {+ "id": "sw_moonraker_api",+ "kwargs": {"query": "Moonraker HTTP REST JSON-RPC WebSocket API Klipper", "domain": "software"},+ "expect_rank1": "moonraker",+ "expect_any": {"moonraker"},+ },+ {+ "id": "sw_manifold_boolean",+ "kwargs": {"query": "Manifold watertight boolean mesh repair", "domain": "software"},+ "expect_rank1": "manifold",+ "expect_any": {"manifold"},+ },+ {+ "id": "rp_nurb_checks",+ "kwargs": {"query": "Shpigford nurb build123d checks.py probe.py", "domain": "report"},+ "expect_rank1": "nurb_inspection",+ "expect_any": {"nurb_inspection"},+ },+ {+ "id": "mf_bambu_mqtt_ftps",+ "kwargs": {"query": "Bambu Lab MQTTS 8883 FTPS 990 LAN access code", "domain": "manufacturer"},+ "expect_rank1": "bambu_lab",+ "expect_any": {"bambu_lab"},+ },+ {+ "id": "mf_bambu_hms_fault",+ "kwargs": {"query": "HMS_0700-0100-0002-0002", "domain": "manufacturer"},+ "expect_rank1": "bambu_lab",+ "expect_any": {"bambu_lab"},+ },+ {+ "id": "mf_prusa_link_fault",+ "kwargs": {"query": "PrusaLink HTTP REST API #31208", "domain": "manufacturer"},+ "expect_rank1": "prusa_research",+ "expect_any": {"prusa_research"},+ },+ {+ "id": "mf_voron_klipper_moonraker",+ "kwargs": {"query": "Voron Moonraker 7125 Klipper ADXL345", "domain": "manufacturer"},+ "expect_rank1": "voron_design",+ "expect_any": {"voron_design"},+ },+ {+ "id": "mf_creality_moonraker_fault",+ "kwargs": {"query": "Creality K1 K2 Plus Moonraker 7125 4408 key 2564", "domain": "manufacturer"},+ "expect_rank1": "creality",+ "expect_any": {"creality"},+ },+ {+ "id": "mf_elegoo_sdcp_msla",+ "kwargs": {"query": "WebSocket file upload SDCP", "tech": "msla", "protocol": "sdcp"},+ "expect_rank1": "elegoo",+ "expect_any": {"elegoo"},+ },+ {+ "id": "mf_formlabs_preform",+ "kwargs": {"query": "Formlabs PreFormServer 44388 Form 4 error 1.3.1", "domain": "manufacturer"},+ "expect_rank1": "formlabs",+ "expect_any": {"formlabs"},+ },+ {+ "id": "mf_stratasys_closed",+ "kwargs": {"query": "Stratasys F123 MTConnect GrabCAD SDK closed", "domain": "manufacturer"},+ "expect_rank1": "stratasys",+ "expect_any": {"stratasys"},+ },+ {+ "id": "pp_printability_stand",+ "kwargs": {"query": "Make It Stand center of mass stability", "domain": "paper"},+ "expect_rank1": "prevost-2013-make-it-stand",+ "expect_any": {"prevost-2013-make-it-stand"},+ },+ {+ "id": "pp_overhang_support",+ "kwargs": {"query": "bridging steady scaffoldings overhang support minimization", "domain": "paper"},+ "expect_rank1": "dumas-2014-bridging-the-gap",+ "expect_any": {"dumas-2014-bridging-the-gap"},+ },+ {+ "id": "pp_wall_thickness",+ "kwargs": {"query": "voxel printability wall thickness thin features", "domain": "paper"},+ "expect_rank1": "telea-2011-voxel-printability",+ "expect_any": {"telea-2011-voxel-printability"},+ },+ {+ "id": "pp_hollowing_drainage",+ "kwargs": {"query": "enclosed voids hollowing drainage resin", "domain": "paper"},+ "expect_rank1": "liu-2015-virtual-temperature",+ "expect_any": {"liu-2015-virtual-temperature"},+ },+ {+ "id": "pp_decomposition_chopper",+ "kwargs": {"query": "Chopper partitioning interlocking parts", "domain": "paper"},+ "expect_rank1": "luo-2012-chopper",+ "expect_any": {"luo-2012-chopper"},+ },+ {+ "id": "pp_clearance_orientation",+ "kwargs": {"query": "build orientation surface roughness support volume", "domain": "paper"},+ "expect_rank1": "delfs-2016-build-orientation",+ "expect_any": {"delfs-2016-build-orientation"},+ },+]+++def nearest_rank_percentile(sorted_vals: list[float], q: float) -> float:+ """Nearest-rank percentile matching research/scripts/validate_kb.py."""+ if not sorted_vals:+ return 0.0+ idx = max(0, math.ceil(q * len(sorted_vals)) - 1)+ return sorted_vals[min(idx, len(sorted_vals) - 1)]+++def summarize_latencies(samples_ms: list[float]) -> dict[str, Any]:+ s = sorted(samples_ms)+ return {+ "runs": len(s),+ "min_ms": round(s[0], 3) if s else 0.0,+ "p50_ms": round(nearest_rank_percentile(s, 0.50), 3),+ "p95_ms": round(nearest_rank_percentile(s, 0.95), 3),+ "max_ms": round(s[-1], 3) if s else 0.0,+ "mean_ms": round(sum(s) / len(s), 3) if s else 0.0,+ }+++def is_valid_http_url(url: str) -> bool:+ if not isinstance(url, str) or not url or any(ch.isspace() for ch in url):+ return False+ parsed = urlparse(url)+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc)+++def check_required_files() -> list[str]:+ required = [+ FORMA_BIN,+ FORMA_MCP_BIN,+ FORMA_PRINT_BIN,+ WASM_BIN,+ RAG_DB_PATH,+ CORPUS_DIR / "software.jsonl",+ CORPUS_DIR / "manufacturers.jsonl",+ CORPUS_DIR / "papers.jsonl",+ NURB_REPORT_PATH,+ FIXTURES_DIR / "box_meters.forma",+ FIXTURES_DIR / "upside_down_t.forma",+ FIXTURES_DIR / "functional_bracket.forma",+ FIXTURES_DIR / "multi_color_ams.forma",+ FIXTURES_DIR / "multi_color_enclosure.forma",+ FIXTURES_DIR / "high_poly.forma",+ ]+ missing = [str(p.relative_to(REPO_ROOT)) for p in required if not p.exists()]+ return missing+++def measure_artifacts(enc: tiktoken.Encoding) -> dict[str, Any]:+ files = {+ "forma": FORMA_BIN,+ "forma_mcp": FORMA_MCP_BIN,+ "forma_print": FORMA_PRINT_BIN,+ "forma_wasm": WASM_BIN,+ "rag_sqlite": RAG_DB_PATH,+ "software_jsonl": CORPUS_DIR / "software.jsonl",+ "manufacturers_jsonl": CORPUS_DIR / "manufacturers.jsonl",+ "papers_jsonl": CORPUS_DIR / "papers.jsonl",+ "nurb_inspection_md": NURB_REPORT_PATH,+ }+ sizes_bytes = {k: p.stat().st_size for k, p in files.items()}+ corpus_jsonl_bytes = (+ sizes_bytes["software_jsonl"]+ + sizes_bytes["manufacturers_jsonl"]+ + sizes_bytes["papers_jsonl"]+ )+ corpus_plus_report_bytes = corpus_jsonl_bytes + sizes_bytes["nurb_inspection_md"]++ # Check Cargo.toml default-members and package.json files isolation statically.+ cargo_toml = (REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")+ pkg_json = json.loads((REPO_ROOT / "package.json").read_text(encoding="utf-8"))+ default_members_section = cargo_toml.split("default-members", 1)[-1].split("]", 1)[0]+ forma_print_excluded_from_default = "forma-print" not in default_members_section+ pkg_files = pkg_json.get("files", [])+ research_excluded_from_npm = not any("research" in str(entry) for entry in pkg_files)+ crate_excluded_from_npm = not any("forma-print" in str(entry) for entry in pkg_files)++ assert forma_print_excluded_from_default, "crates/forma-print must stay excluded from default-members"+ assert research_excluded_from_npm and crate_excluded_from_npm, "package.json files must exclude research/ and forma-print"++ return {+ "bytes": sizes_bytes,+ "derived": {+ "corpus_jsonl_bytes": corpus_jsonl_bytes,+ "corpus_plus_report_bytes": corpus_plus_report_bytes,+ "rag_sqlite_mib": round(sizes_bytes["rag_sqlite"] / (1024 * 1024), 4),+ "forma_mb": round(sizes_bytes["forma"] / (1024 * 1024), 3),+ "forma_mcp_mb": round(sizes_bytes["forma_mcp"] / (1024 * 1024), 3),+ "forma_print_mb": round(sizes_bytes["forma_print"] / (1024 * 1024), 3),+ "forma_wasm_kb": round(sizes_bytes["forma_wasm"] / 1024, 2),+ },+ "workspace_isolation": {+ "forma_print_excluded_from_default_members": forma_print_excluded_from_default,+ "research_excluded_from_npm_files": research_excluded_from_npm,+ "forma_print_excluded_from_npm_files": crate_excluded_from_npm,+ },+ }+++def _mcp_exchange(proc: subprocess.Popen[str], payload: dict[str, Any]) -> tuple[dict[str, Any], float]:+ t0 = time.perf_counter()+ assert proc.stdin is not None and proc.stdout is not None+ proc.stdin.write(json.dumps(payload, separators=(",", ":")) + "\n")+ proc.stdin.flush()+ line = proc.stdout.readline()+ dt_ms = (time.perf_counter() - t0) * 1000.0+ if not line:+ stderr = proc.stderr.read() if proc.stderr else ""+ raise RuntimeError(f"MCP EOF on method={payload.get('method')}; stderr={stderr}")+ return json.loads(line), dt_ms+++def _mcp_notify(proc: subprocess.Popen[str], method: str) -> None:+ assert proc.stdin is not None+ proc.stdin.write(json.dumps({"jsonrpc": "2.0", "method": method}, separators=(",", ":")) + "\n")+ proc.stdin.flush()+++def probe_mcp_server(+ cmd: list[str],+ enc: tiktoken.Encoding,+ expected_tools: list[str],+) -> dict[str, Any]:+ proc = subprocess.Popen(+ cmd,+ cwd=str(REPO_ROOT),+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ try:+ t_start = time.perf_counter()+ init_resp, init_ms = _mcp_exchange(+ proc,+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2024-11-05",+ "capabilities": {},+ "clientInfo": {"name": "bench_efficiency", "version": "1.0"},+ },+ },+ )+ _mcp_notify(proc, "notifications/initialized")+ list_resp, list_ms = _mcp_exchange(+ proc,+ {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}},+ )+ total_ms = (time.perf_counter() - t_start) * 1000.0+ finally:+ if proc.stdin:+ proc.stdin.close()+ proc.wait(timeout=10)++ assert proc.returncode == 0, f"MCP server {cmd} exited {proc.returncode}"+ result = list_resp["result"]+ tools = result["tools"]+ tool_names = [t["name"] for t in tools]+ assert len(tools) == 4, f"Expected 4 tools for {cmd}, got {len(tools)}: {tool_names}"+ assert tool_names == expected_tools, f"Unexpected tools {tool_names} != {expected_tools}"++ compact_tools_json = json.dumps(tools, separators=(",", ":"))+ pretty_tools_json = json.dumps(tools, indent=2)+ compact_result_json = json.dumps(result, separators=(",", ":"))++ return {+ "command": cmd,+ "server_info": init_resp["result"]["serverInfo"],+ "tool_count": len(tools),+ "tools": tool_names,+ "initialize_ms": round(init_ms, 3),+ "tools_list_ms": round(list_ms, 3),+ "handshake_total_ms": round(total_ms, 3),+ "tools_compact_bytes": len(compact_tools_json.encode("utf-8")),+ "tools_compact_o200k_tokens": len(enc.encode(compact_tools_json)),+ "tools_pretty_o200k_tokens": len(enc.encode(pretty_tools_json)),+ "result_compact_o200k_tokens": len(enc.encode(compact_result_json)),+ }+++def probe_mcp_tool_session(enc: tiktoken.Encoding, tmpdir: Path) -> dict[str, Any]:+ fixture = str(FIXTURES_DIR / "upside_down_t.forma")+ out_3mf = str(tmpdir / "mcp_upside_down_t.3mf")+ out_hm = str(tmpdir / "mcp_upside_down_t_hm.png")++ proc = subprocess.Popen(+ [str(FORMA_PRINT_BIN), "--mcp"],+ cwd=str(REPO_ROOT),+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ calls: dict[str, Any] = {}+ try:+ _mcp_exchange(+ proc,+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2024-11-05",+ "capabilities": {},+ "clientInfo": {"name": "bench_efficiency", "version": "1.0"},+ },+ },+ )+ _mcp_notify(proc, "notifications/initialized")++ tool_requests = [+ (+ "print_check",+ 2,+ {+ "name": "print_check",+ "arguments": {"input": fixture, "printer": "bambu_x1c", "heatmap_out": out_hm},+ },+ ),+ (+ "print_prep",+ 3,+ {+ "name": "print_prep",+ "arguments": {"input": fixture, "printer": "bambu_x1c"},+ },+ ),+ (+ "print_export",+ 4,+ {+ "name": "print_export",+ "arguments": {+ "input": fixture,+ "printer": "bambu_x1c",+ "orient": True,+ "out": out_3mf,+ },+ },+ ),+ (+ "print_profiles",+ 5,+ {+ "name": "print_profiles",+ "arguments": {},+ },+ ),+ ]++ for label, req_id, params in tool_requests:+ resp, dt_ms = _mcp_exchange(+ proc,+ {"jsonrpc": "2.0", "id": req_id, "method": "tools/call", "params": params},+ )+ res = resp["result"]+ assert res.get("isError") is False, f"MCP {label} returned error: {res}"+ text = res["content"][0]["text"]+ parsed = json.loads(text)+ calls[label] = {+ "latency_ms": round(dt_ms, 3),+ "is_error": res.get("isError", False),+ "response_bytes": len(text.encode("utf-8")),+ "response_o200k_tokens": len(enc.encode(text)),+ "summary": (+ {+ "printable": parsed.get("printable"),+ "checks_failed": [+ k for k, v in parsed.get("checks", {}).items() if v == "fail"+ ],+ }+ if label == "print_check"+ else (+ {+ "rotated_from_input": parsed.get("rotated_from_input"),+ "candidates_evaluated": parsed.get("candidates_evaluated"),+ "post_orient_printable": parsed.get("report", {}).get("printable"),+ }+ if label == "print_prep"+ else (+ {+ "ok": parsed.get("ok"),+ "bytes": parsed.get("bytes"),+ "oriented": parsed.get("oriented"),+ }+ if label == "print_export"+ else {+ "printers": len(parsed.get("printers", [])),+ "materials": len(parsed.get("materials", [])),+ "heat_inserts": len(parsed.get("heat_inserts", [])),+ }+ )+ )+ ),+ }+ finally:+ if proc.stdin:+ proc.stdin.close()+ proc.wait(timeout=10)++ assert proc.returncode == 0+ assert Path(out_3mf).is_file() and Path(out_3mf).stat().st_size > 0+ assert Path(out_hm).is_file() and Path(out_hm).stat().st_size > 0+ assert calls["print_check"]["summary"]["printable"] is False+ assert calls["print_prep"]["summary"]["rotated_from_input"] is True+ assert calls["print_prep"]["summary"]["post_orient_printable"] is True+ assert calls["print_export"]["summary"]["ok"] is True+ assert calls["print_profiles"]["summary"]["printers"] == 18+ assert calls["print_profiles"]["summary"]["materials"] == 9+ assert calls["print_profiles"]["summary"]["heat_inserts"] == 6+ return calls+++def inspect_3mf_archive(path: Path) -> dict[str, Any]:+ compressed_file_bytes = path.stat().st_size+ with zipfile.ZipFile(path, "r") as zf:+ infos = zf.infolist()+ uncompressed_payload_bytes = sum(i.file_size for i in infos)+ compressed_payload_bytes = sum(i.compress_size for i in infos)+ names = [i.filename for i in infos]+ model_xml = zf.read("3D/3dmodel.model").decode("utf-8")+ assert 'unit="millimeter"' in model_xml, f"3MF {path} missing unit='millimeter'"+ expected_entries = {+ "[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",+ }+ assert expected_entries.issubset(set(names)), f"Missing 3MF entries in {names}"+ compress_types = sorted({i.compress_type for i in infos})+ assert zipfile.ZIP_DEFLATED in compress_types, f"Expected Deflate entries, got {compress_types}"++ deflate_ratio_vs_file = (+ round(uncompressed_payload_bytes / compressed_file_bytes, 3)+ if compressed_file_bytes > 0+ else 0.0+ )+ deflate_ratio_vs_payload = (+ round(uncompressed_payload_bytes / compressed_payload_bytes, 3)+ if compressed_payload_bytes > 0+ else 0.0+ )+ return {+ "entry_count": len(names),+ "entries": names,+ "file_bytes": compressed_file_bytes,+ "compressed_payload_bytes": compressed_payload_bytes,+ "uncompressed_payload_bytes": uncompressed_payload_bytes,+ "deflate_ratio_vs_file": deflate_ratio_vs_file,+ "deflate_ratio_vs_payload": deflate_ratio_vs_payload,+ }+++def run_timed_cli(+ args: list[str],+ expected_rc: int,+ runs: int,+ warmup: int = 1,+) -> tuple[dict[str, Any], dict[str, Any]]:+ cmd = [str(FORMA_PRINT_BIN), *args]+ for _ in range(warmup):+ res = subprocess.run(cmd, cwd=str(REPO_ROOT), capture_output=True, text=True)+ if res.returncode != expected_rc:+ raise AssertionError(+ f"Warmup CLI {cmd} exited {res.returncode} (expected {expected_rc}); stderr={res.stderr}"+ )++ latencies: list[float] = []+ last_stdout = ""+ for _ in range(runs):+ t0 = time.perf_counter()+ res = subprocess.run(cmd, cwd=str(REPO_ROOT), capture_output=True, text=True)+ dt_ms = (time.perf_counter() - t0) * 1000.0+ if res.returncode != expected_rc:+ raise AssertionError(+ f"Timed CLI {cmd} exited {res.returncode} (expected {expected_rc}); stderr={res.stderr}"+ )+ latencies.append(dt_ms)+ last_stdout = res.stdout++ parsed = json.loads(last_stdout)+ return summarize_latencies(latencies), parsed+++def summarize_checks(checks: dict[str, str]) -> dict[str, Any]:+ passed = [k for k, v in checks.items() if v == "pass"]+ warned = [k for k, v in checks.items() if v == "warn"]+ failed = [k for k, v in checks.items() if v == "fail"]+ skipped = [k for k, v in checks.items() if v == "skip"]+ return {+ "total": len(checks),+ "pass": len(passed),+ "warn": len(warned),+ "fail": len(failed),+ "skip": len(skipped),+ "failed_checks": failed,+ "warned_checks": warned,+ }+++def benchmark_cli(runs: int, tmpdir: Path) -> dict[str, Any]:+ high_poly_orient_runs = max(1, min(runs, 5))+ benchmarks: list[dict[str, Any]] = []++ # 1. box_meters.forma check --heatmap+ box_hm = tmpdir / "box_meters_hm.png"+ timing, parsed = run_timed_cli(+ [+ "check",+ str(FIXTURES_DIR / "box_meters.forma"),+ "--printer",+ "bambu_x1c",+ "--heatmap",+ str(box_hm),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["printable"] is True+ chk = summarize_checks(parsed["checks"])+ assert chk["pass"] == 9 and chk["fail"] == 0+ assert box_hm.is_file() and box_hm.stat().st_size > 0+ benchmarks.append(+ {+ "id": "box_meters_check_heatmap",+ "fixture": "tests/e2e/fixtures/box_meters.forma",+ "operation": "check --heatmap",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "printable": parsed["printable"],+ "checks": chk,+ "volume_cm3": round(parsed["stats"]["volume_cm3"], 4),+ "faces": len(parsed.get("face_severities", [])),+ "heatmap_png_bytes": box_hm.stat().st_size,+ },+ }+ )++ # 2. upside_down_t.forma check (with & without heatmap), orient, export --orient (.3mf, .step)+ t_hm = tmpdir / "upside_down_t_hm.png"+ timing, parsed = run_timed_cli(+ [+ "check",+ str(FIXTURES_DIR / "upside_down_t.forma"),+ "--printer",+ "bambu_x1c",+ "--heatmap",+ str(t_hm),+ "--json",+ ],+ expected_rc=3,+ runs=runs,+ )+ assert parsed["printable"] is False+ chk = summarize_checks(parsed["checks"])+ assert chk["fail"] >= 1+ benchmarks.append(+ {+ "id": "upside_down_t_check_heatmap",+ "fixture": "tests/e2e/fixtures/upside_down_t.forma",+ "operation": "check --heatmap",+ "printer": "bambu_x1c",+ "expected_rc": 3,+ "timing": timing,+ "deterministic": {+ "printable": parsed["printable"],+ "checks": chk,+ "volume_cm3": round(parsed["stats"]["volume_cm3"], 4),+ "faces": len(parsed.get("face_severities", [])),+ "heatmap_png_bytes": t_hm.stat().st_size,+ },+ }+ )++ t_orient_out = tmpdir / "upside_down_t_oriented.stl"+ timing, parsed = run_timed_cli(+ [+ "orient",+ str(FIXTURES_DIR / "upside_down_t.forma"),+ "--printer",+ "bambu_x1c",+ "--out",+ str(t_orient_out),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["rotated_from_input"] is True+ assert parsed["report"]["printable"] is True+ benchmarks.append(+ {+ "id": "upside_down_t_orient",+ "fixture": "tests/e2e/fixtures/upside_down_t.forma",+ "operation": "orient",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "rotated_from_input": parsed["rotated_from_input"],+ "candidates_evaluated": parsed["candidates_evaluated"],+ "post_orient_printable": parsed["report"]["printable"],+ "post_orient_checks": summarize_checks(parsed["report"]["checks"]),+ },+ }+ )++ t_3mf = tmpdir / "upside_down_t.3mf"+ timing, parsed = run_timed_cli(+ [+ "export",+ str(FIXTURES_DIR / "upside_down_t.forma"),+ "--printer",+ "bambu_x1c",+ "--orient",+ "--out",+ str(t_3mf),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["ok"] is True and parsed["oriented"] is True+ arch = inspect_3mf_archive(t_3mf)+ benchmarks.append(+ {+ "id": "upside_down_t_export_orient_3mf",+ "fixture": "tests/e2e/fixtures/upside_down_t.forma",+ "operation": "export --orient .3mf",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "parts": parsed["parts"],+ "size_mm": [round(x, 3) for x in parsed["size_mm"]],+ "archive_3mf": arch,+ },+ }+ )++ t_step = tmpdir / "upside_down_t.step"+ timing, parsed = run_timed_cli(+ [+ "export",+ str(FIXTURES_DIR / "upside_down_t.forma"),+ "--printer",+ "bambu_x1c",+ "--orient",+ "--out",+ str(t_step),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["ok"] is True+ assert "SI_UNIT(.MILLI.,.METRE.)" in t_step.read_text(encoding="utf-8")+ benchmarks.append(+ {+ "id": "upside_down_t_export_orient_step",+ "fixture": "tests/e2e/fixtures/upside_down_t.forma",+ "operation": "export --orient .step",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "parts": parsed["parts"],+ "step_bytes": t_step.stat().st_size,+ },+ }+ )++ # 3. functional_bracket.forma check --heatmap+ fb_hm = tmpdir / "functional_bracket_hm.png"+ timing, parsed = run_timed_cli(+ [+ "check",+ str(FIXTURES_DIR / "functional_bracket.forma"),+ "--printer",+ "bambu_x1c",+ "--heatmap",+ str(fb_hm),+ "--json",+ ],+ expected_rc=3,+ runs=runs,+ )+ assert parsed["printable"] is False+ assert parsed["checks"]["overhangs"] == "fail"+ assert parsed["checks"]["wall_thickness"] == "fail"+ benchmarks.append(+ {+ "id": "functional_bracket_check_heatmap",+ "fixture": "tests/e2e/fixtures/functional_bracket.forma",+ "operation": "check --heatmap",+ "printer": "bambu_x1c",+ "expected_rc": 3,+ "timing": timing,+ "deterministic": {+ "printable": parsed["printable"],+ "checks": summarize_checks(parsed["checks"]),+ "volume_cm3": round(parsed["stats"]["volume_cm3"], 4),+ "faces": len(parsed.get("face_severities", [])),+ "heatmap_png_bytes": fb_hm.stat().st_size,+ },+ }+ )++ # 4. multi_color_ams.forma check --heatmap+ mc_hm = tmpdir / "multi_color_ams_hm.png"+ timing, parsed = run_timed_cli(+ [+ "check",+ str(FIXTURES_DIR / "multi_color_ams.forma"),+ "--printer",+ "bambu_x1c",+ "--heatmap",+ str(mc_hm),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["printable"] is True+ assert parsed["ams_swaps"] == 2+ assert parsed["purge_grams"] > 0+ benchmarks.append(+ {+ "id": "multi_color_ams_check_heatmap",+ "fixture": "tests/e2e/fixtures/multi_color_ams.forma",+ "operation": "check --heatmap",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "printable": parsed["printable"],+ "checks": summarize_checks(parsed["checks"]),+ "ams_swaps": parsed["ams_swaps"],+ "purge_grams": round(parsed["purge_grams"], 3),+ "volume_cm3": round(parsed["stats"]["volume_cm3"], 4),+ "faces": len(parsed.get("face_severities", [])),+ "heatmap_png_bytes": mc_hm.stat().st_size,+ },+ }+ )++ # 5. multi_color_enclosure.forma check, orient, export --orient .3mf & .step+ enc_hm = tmpdir / "multi_color_enclosure_hm.png"+ timing, parsed = run_timed_cli(+ [+ "check",+ str(FIXTURES_DIR / "multi_color_enclosure.forma"),+ "--printer",+ "bambu_p1s",+ "--heatmap",+ str(enc_hm),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["printable"] is True+ benchmarks.append(+ {+ "id": "multi_color_enclosure_check_heatmap",+ "fixture": "tests/e2e/fixtures/multi_color_enclosure.forma",+ "operation": "check --heatmap",+ "printer": "bambu_p1s",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "printable": parsed["printable"],+ "checks": summarize_checks(parsed["checks"]),+ "ams_swaps": parsed["ams_swaps"],+ "purge_grams": round(parsed["purge_grams"], 3),+ "volume_cm3": round(parsed["stats"]["volume_cm3"], 4),+ "faces": len(parsed.get("face_severities", [])),+ "heatmap_png_bytes": enc_hm.stat().st_size,+ },+ }+ )++ timing, parsed = run_timed_cli(+ [+ "orient",+ str(FIXTURES_DIR / "multi_color_enclosure.forma"),+ "--printer",+ "bambu_p1s",+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["report"]["printable"] is True+ benchmarks.append(+ {+ "id": "multi_color_enclosure_orient",+ "fixture": "tests/e2e/fixtures/multi_color_enclosure.forma",+ "operation": "orient",+ "printer": "bambu_p1s",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "rotated_from_input": parsed["rotated_from_input"],+ "candidates_evaluated": parsed["candidates_evaluated"],+ "post_orient_printable": parsed["report"]["printable"],+ },+ }+ )++ enc_3mf = tmpdir / "multi_color_enclosure.3mf"+ timing, parsed = run_timed_cli(+ [+ "export",+ str(FIXTURES_DIR / "multi_color_enclosure.forma"),+ "--printer",+ "bambu_p1s",+ "--orient",+ "--out",+ str(enc_3mf),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["ok"] is True and parsed["parts"] == 2+ arch = inspect_3mf_archive(enc_3mf)+ benchmarks.append(+ {+ "id": "multi_color_enclosure_export_orient_3mf",+ "fixture": "tests/e2e/fixtures/multi_color_enclosure.forma",+ "operation": "export --orient .3mf",+ "printer": "bambu_p1s",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "parts": parsed["parts"],+ "size_mm": [round(x, 3) for x in parsed["size_mm"]],+ "archive_3mf": arch,+ },+ }+ )++ enc_step = tmpdir / "multi_color_enclosure.step"+ timing, parsed = run_timed_cli(+ [+ "export",+ str(FIXTURES_DIR / "multi_color_enclosure.forma"),+ "--printer",+ "bambu_p1s",+ "--orient",+ "--out",+ str(enc_step),+ "--json",+ ],+ expected_rc=0,+ runs=runs,+ )+ assert parsed["ok"] is True and parsed["parts"] == 2+ benchmarks.append(+ {+ "id": "multi_color_enclosure_export_orient_step",+ "fixture": "tests/e2e/fixtures/multi_color_enclosure.forma",+ "operation": "export --orient .step",+ "printer": "bambu_p1s",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "parts": parsed["parts"],+ "step_bytes": enc_step.stat().st_size,+ },+ }+ )++ # 6. high_poly.forma check, orient, export .3mf & .step+ hp_hm = tmpdir / "high_poly_hm.png"+ timing, parsed = run_timed_cli(+ [+ "check",+ str(FIXTURES_DIR / "high_poly.forma"),+ "--printer",+ "bambu_x1c",+ "--heatmap",+ str(hp_hm),+ "--json",+ ],+ expected_rc=3,+ runs=high_poly_orient_runs,+ )+ assert parsed["printable"] is False+ benchmarks.append(+ {+ "id": "high_poly_check_heatmap",+ "fixture": "tests/e2e/fixtures/high_poly.forma",+ "operation": "check --heatmap",+ "printer": "bambu_x1c",+ "expected_rc": 3,+ "timing": timing,+ "deterministic": {+ "printable": parsed["printable"],+ "checks": summarize_checks(parsed["checks"]),+ "volume_cm3": round(parsed["stats"]["volume_cm3"], 4),+ "faces": len(parsed.get("face_severities", [])),+ "heatmap_png_bytes": hp_hm.stat().st_size,+ },+ }+ )++ hp_3mf = tmpdir / "high_poly.3mf"+ timing, parsed = run_timed_cli(+ [+ "orient",+ str(FIXTURES_DIR / "high_poly.forma"),+ "--printer",+ "bambu_x1c",+ "--json",+ ],+ expected_rc=0,+ runs=high_poly_orient_runs,+ )+ benchmarks.append(+ {+ "id": "high_poly_orient",+ "fixture": "tests/e2e/fixtures/high_poly.forma",+ "operation": "orient",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "rotated_from_input": parsed["rotated_from_input"],+ "candidates_evaluated": parsed["candidates_evaluated"],+ "post_orient_printable": parsed["report"]["printable"],+ },+ }+ )++ timing, parsed = run_timed_cli(+ [+ "export",+ str(FIXTURES_DIR / "high_poly.forma"),+ "--printer",+ "bambu_x1c",+ "--out",+ str(hp_3mf),+ "--json",+ ],+ expected_rc=0,+ runs=high_poly_orient_runs,+ )+ assert parsed["ok"] is True+ arch = inspect_3mf_archive(hp_3mf)+ benchmarks.append(+ {+ "id": "high_poly_export_3mf",+ "fixture": "tests/e2e/fixtures/high_poly.forma",+ "operation": "export .3mf",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "parts": parsed["parts"],+ "size_mm": [round(x, 3) for x in parsed["size_mm"]],+ "archive_3mf": arch,+ },+ }+ )++ hp_step = tmpdir / "high_poly.step"+ timing, parsed = run_timed_cli(+ [+ "export",+ str(FIXTURES_DIR / "high_poly.forma"),+ "--printer",+ "bambu_x1c",+ "--out",+ str(hp_step),+ "--json",+ ],+ expected_rc=0,+ runs=high_poly_orient_runs,+ )+ assert parsed["ok"] is True+ benchmarks.append(+ {+ "id": "high_poly_export_step",+ "fixture": "tests/e2e/fixtures/high_poly.forma",+ "operation": "export .step",+ "printer": "bambu_x1c",+ "expected_rc": 0,+ "timing": timing,+ "deterministic": {+ "parts": parsed["parts"],+ "step_bytes": hp_step.stat().st_size,+ },+ }+ )++ return {+ "fast_runs": runs,+ "high_poly_runs": high_poly_orient_runs,+ "warmup_runs": 1,+ "benchmarks": benchmarks,+ }+++def extract_corpus_primary_urls() -> dict[str, Any]:+ software_urls: set[str] = set()+ mfr_urls: set[str] = set()+ paper_urls: set[str] = set()+ source_verified_true = 0+ total_records = 0++ for line in (CORPUS_DIR / "software.jsonl").read_text(encoding="utf-8").splitlines():+ if not line.strip():+ continue+ rec = json.loads(line)+ total_records += 1+ if rec.get("source_verified") is True:+ source_verified_true += 1+ for u in [rec.get("repo_or_primary_url"), *rec.get("source_urls", [])]:+ if is_valid_http_url(u):+ software_urls.add(u)++ for line in (CORPUS_DIR / "manufacturers.jsonl").read_text(encoding="utf-8").splitlines():+ if not line.strip():+ continue+ rec = json.loads(line)+ total_records += 1+ if rec.get("source_verified") is True:+ source_verified_true += 1+ tf = rec.get("troubleshooting_and_faults", {})+ candidates = [+ *rec.get("source_urls", []),+ *tf.get("official_kb_urls", []),+ *(fc.get("kb_url") for fc in tf.get("example_fault_codes", [])),+ ]+ for u in candidates:+ if is_valid_http_url(u):+ mfr_urls.add(u)++ for line in (CORPUS_DIR / "papers.jsonl").read_text(encoding="utf-8").splitlines():+ if not line.strip():+ continue+ rec = json.loads(line)+ total_records += 1+ if rec.get("source_verified") is True:+ source_verified_true += 1+ u = rec.get("url")+ if is_valid_http_url(u):+ paper_urls.add(u)++ union_urls = software_urls | mfr_urls | paper_urls+ assert source_verified_true == total_records, "All corpus records must have source_verified == true"+ return {+ "total_records": total_records,+ "source_verified_records": source_verified_true,+ "unique_urls_by_corpus": {+ "software": len(software_urls),+ "manufacturers": len(mfr_urls),+ "papers": len(paper_urls),+ },+ "unique_primary_source_urls_union": len(union_urls),+ }+++def benchmark_rag(enc: tiktoken.Encoding, rag_runs: int) -> dict[str, Any]:+ raw_files = {+ "software_jsonl": CORPUS_DIR / "software.jsonl",+ "manufacturers_jsonl": CORPUS_DIR / "manufacturers.jsonl",+ "papers_jsonl": CORPUS_DIR / "papers.jsonl",+ "nurb_inspection_md": NURB_REPORT_PATH,+ }+ raw_stats: dict[str, Any] = {}+ total_raw_bytes = 0+ total_raw_o200k = 0+ for key, path in raw_files.items():+ text = path.read_text(encoding="utf-8")+ b = len(text.encode("utf-8"))+ tok = len(enc.encode(text))+ total_raw_bytes += b+ total_raw_o200k += tok+ raw_stats[key] = {"bytes": b, "o200k_tokens": tok}++ citations = extract_corpus_primary_urls()++ conn = sqlite3.connect(f"file:{RAG_DB_PATH}?mode=ro", uri=True)+ try:+ rows = conn.execute(+ "SELECT chunk_id, domain, entity_id, title, section, text, token_count, source_url "+ "FROM chunks ORDER BY rowid"+ ).fetchall()++ chunk_lookup: dict[str, dict[str, Any]] = {}+ domain_totals: dict[str, dict[str, int]] = {}+ db_text_o200k_total = 0+ db_emb_o200k_total = 0+ db_words_total = 0+ db_text_bytes_total = 0++ for chunk_id, domain, entity_id, title, section, text, word_count, source_url in rows:+ emb_text = build_rag.format_embedding_ready_text(domain, entity_id, section, title, text)+ text_tok = len(enc.encode(text))+ emb_tok = len(enc.encode(emb_text))+ text_bytes = len(text.encode("utf-8"))++ chunk_lookup[chunk_id] = {+ "text_o200k": text_tok,+ "emb_o200k": emb_tok,+ "words": int(word_count),+ "source_url": source_url,+ }+ db_text_o200k_total += text_tok+ db_emb_o200k_total += emb_tok+ db_words_total += int(word_count)+ db_text_bytes_total += text_bytes++ d = domain_totals.setdefault(+ domain,+ {"chunks": 0, "text_bytes": 0, "lexical_words": 0, "text_o200k": 0, "emb_o200k": 0},+ )+ d["chunks"] += 1+ d["text_bytes"] += text_bytes+ d["lexical_words"] += int(word_count)+ d["text_o200k"] += text_tok+ d["emb_o200k"] += emb_tok++ # Warmup pass across the 18 queries so page cache is warm before timed passes.+ for q in RAG_QUERY_SUITE:+ query_rag.query_kb(db_path=RAG_DB_PATH, conn=conn, top_k=5, **q["kwargs"])++ by_top_k: dict[str, Any] = {}+ trace_k5: list[dict[str, Any]] = []++ for k in (3, 5, 10):+ latencies_ms: list[float] = []+ relevant_any_hits = 0+ rank1_hits = 0+ text_tokens_per_query: list[int] = []+ emb_tokens_per_query: list[int] = []+ resp_tokens_per_query: list[int] = []+ unique_urls: set[str] = set()++ for run_idx in range(rag_runs):+ for q in RAG_QUERY_SUITE:+ res = query_rag.query_kb(db_path=RAG_DB_PATH, conn=conn, top_k=k, **q["kwargs"])+ latencies_ms.append(float(res["latency_ms"]))+ if run_idx == 0:+ hits = res["results"]+ entities = [h["entity_id"] for h in hits]+ assert hits, f"Query {q['id']} (k={k}) returned 0 hits"+ for h in hits:+ assert is_valid_http_url(h.get("source_url", "")), (+ f"Invalid source_url in {q['id']}: {h.get('source_url')!r}"+ )+ unique_urls.add(h["source_url"])++ if set(entities) & q["expect_any"]:+ relevant_any_hits += 1+ if entities[0] == q["expect_rank1"]:+ rank1_hits += 1++ q_text_tok = sum(chunk_lookup[h["chunk_id"]]["text_o200k"] for h in hits)+ q_emb_tok = sum(chunk_lookup[h["chunk_id"]]["emb_o200k"] for h in hits)+ resp_json = json.dumps(res, ensure_ascii=False, separators=(",", ":"))+ q_resp_tok = len(enc.encode(resp_json))++ text_tokens_per_query.append(q_text_tok)+ emb_tokens_per_query.append(q_emb_tok)+ resp_tokens_per_query.append(q_resp_tok)++ if k == 5:+ trace_k5.append(+ {+ "id": q["id"],+ "domain": q["kwargs"].get("domain") or "filtered",+ "rank1_entity": entities[0],+ "expected_rank1": q["expect_rank1"],+ "hit_count": len(hits),+ "latency_ms": round(float(res["latency_ms"]), 3),+ "retrieved_text_o200k": q_text_tok,+ "retrieved_emb_o200k": q_emb_tok,+ "response_json_o200k": q_resp_tok,+ }+ )++ assert relevant_any_hits == len(RAG_QUERY_SUITE), (+ f"k={k}: relevant_any_hits={relevant_any_hits}/{len(RAG_QUERY_SUITE)}"+ )+ assert rank1_hits == len(RAG_QUERY_SUITE), (+ f"k={k}: rank1_hits={rank1_hits}/{len(RAG_QUERY_SUITE)}"+ )++ timing = summarize_latencies(latencies_ms)+ assert timing["p95_ms"] < 100.0, f"k={k}: p95_ms={timing['p95_ms']} >= 100.0"++ mean_text = round(sum(text_tokens_per_query) / len(text_tokens_per_query), 2)+ mean_emb = round(sum(emb_tokens_per_query) / len(emb_tokens_per_query), 2)+ mean_resp = round(sum(resp_tokens_per_query) / len(resp_tokens_per_query), 2)++ by_top_k[str(k)] = {+ "queries_total": len(RAG_QUERY_SUITE),+ "timed_query_execs": len(latencies_ms),+ "relevant_any_hits": relevant_any_hits,+ "rank1_hits": rank1_hits,+ "timing": timing,+ "mean_retrieved_text_o200k_tokens": mean_text,+ "mean_retrieved_embedding_ready_o200k_tokens": mean_emb,+ "mean_query_kb_json_o200k_tokens": mean_resp,+ "compression_ratio_vs_raw_corpus": round(total_raw_o200k / mean_text, 2),+ "compression_ratio_vs_db_text": round(db_text_o200k_total / mean_text, 2),+ "compression_ratio_vs_db_embedding_ready": round(db_emb_o200k_total / mean_emb, 2),+ "unique_primary_source_urls": len(unique_urls),+ }+ finally:+ conn.close()++ # Cold-open SQLite connection probe (conn=None) on 4 representative domains.+ cold_samples_ms: list[float] = []+ for idx in (0, 3, 5, 13):+ q = RAG_QUERY_SUITE[idx]+ res = query_rag.query_kb(db_path=RAG_DB_PATH, conn=None, top_k=5, **q["kwargs"])+ cold_samples_ms.append(round(float(res["latency_ms"]), 3))++ return {+ "corpus_totals": {+ "raw_files": raw_stats,+ "total_raw_bytes": total_raw_bytes,+ "total_raw_o200k_tokens": total_raw_o200k,+ "db_size_bytes": RAG_DB_PATH.stat().st_size,+ "total_chunks": len(rows),+ "db_text_bytes": db_text_bytes_total,+ "db_lexical_words": db_words_total,+ "db_text_o200k_tokens": db_text_o200k_total,+ "db_embedding_ready_o200k_tokens": db_emb_o200k_total,+ "by_domain": domain_totals,+ "citations": citations,+ },+ "rag_runs_per_k": rag_runs,+ "by_top_k": by_top_k,+ "cold_open_samples_ms": cold_samples_ms,+ "trace_top_k_5": trace_k5,+ }+++def get_published_baselines() -> dict[str, Any]:+ """Published empirical baselines from repository docs/ and research/reports/ (never live Fable runs)."""+ return {+ "source_type": "published_repo_baseline",+ "note": "Reference telemetry cited verbatim from repository documents; no live external LLM API runs executed here.",+ "nurb_and_nurb_benchmarks": {+ "source": "research/reports/nurb_inspection.md:16-31,102-115,126-130",+ "occt_cold_import_s": 45.0,+ "warm_rebuild_ms_range": [30.0, 400.0],+ "mcp_2_2_0_python_deps": 27,+ "mcp_2_2_0_venv_mb": 27.0,+ "mcp_max_chars_cap": 149000,+ "claude_fable_5_telemetry": [+ {"task": "bit_block", "effort": "medium", "score": 1.000, "pass_at_1": 1.00, "tokens": 3204, "cost_usd": 0.95, "wall_time_s": 139},+ {"task": "bit_block", "effort": "high", "score": 1.000, "tokens": 9028, "cost_usd": 1.92, "wall_time_s": 219},+ {"task": "bundle_holder", "effort": "medium", "score": 1.000, "tokens": 8667, "cost_usd": 1.47, "wall_time_s": 253},+ {"task": "bundle_holder", "effort": "high", "score": 1.000, "tokens": 36715, "cost_usd": 4.84, "wall_time_s": 652},+ ],+ "other_frontier_models_bundle_holder_high": [+ {"model": "claude-opus-5", "tokens": 66870, "cost_usd": 4.02, "wall_time_s": 1140},+ {"model": "gpt-5.6-sol", "tokens": 593633, "cost_usd": 2.53, "wall_time_s": 331},+ ],+ },+ "forma_vs_blender_cad_benchmarks": {+ "phase1_baseline_report": {+ "source": "docs/PHASE1_BASELINE_REPORT.md:17-45",+ "bpy_silent_non_manifold_exit_0_count": 5,+ "repair_loop_token_range": [2932, 11678],+ "hy4_flash_bpy_pass_at_3": "5/12",+ },+ "phase2_language_ablation": {+ "source": "docs/PHASE2_LANGUAGE_ABLATION.md:24-28,53-57",+ "trials_per_condition": 48,+ "bpy_pass_at_1_pct": 68.8,+ "forma_pipe_pass_at_1_pct": 81.2,+ "bpy_pass_at_3_pct": 85.4,+ "forma_pipe_pass_at_3_pct": 97.9,+ "api_token_reduction_x": 2.48,+ "completion_token_reduction_x": 4.85,+ "median_code_token_reduction_x": 5.60,+ "bpy_median_latency_ms": 1306.8,+ "forma_pipe_median_latency_ms": 25.9,+ "latency_speedup_x": 50.4,+ },+ "extended_benchmark_report": {+ "source": "docs/EXTENDED_BENCHMARK_REPORT.md:26,44-47,72-74",+ "total_paired_matrix_trials": 254,+ "models_count": 12,+ "labs_count": 10,+ "forma_pipe_low_medium_pass_at_3": "48/48 (100%)",+ "forma_pipe_low_medium_usd": [0.132, 0.202],+ "bpy_low_medium_high_pass_at_3": "20/24 (83.3%)",+ "bpy_high_usd": 1.285,+ },+ "verification_report": {+ "source": "docs/VERIFICATION_REPORT.md:26-42",+ "canonical_gate": "12/12 PASS",+ "forma_median_cold_eval_export_ms": 18.83,+ "blender_cold_eval_export_ms": 947.5,+ "forma_peak_rss_mb": 2.16,+ "blender_peak_rss_mb": 223.0,+ },+ "autoresearch_hillclimb": {+ "source": "docs/AUTORESEARCH_HILLCLIMB.md:29,98,120",+ "render_4view_png_ms": 3.92,+ "png_deflate_compression_vs_stored_x": 37.5,+ "full_8_pipeline_suite_ms": 27.20,+ "fuzzer_11000_ops_s": 2.46,+ },+ },+ }+++def run_benchmark(runs: int, rag_runs: int) -> dict[str, Any]:+ missing = check_required_files()+ if missing:+ raise FileNotFoundError(f"Missing required benchmark artifacts: {missing}")++ enc = tiktoken.get_encoding("o200k_base")+ t0 = time.perf_counter()++ artifacts = measure_artifacts(enc)+ core_mcp = probe_mcp_server(+ [str(FORMA_MCP_BIN)],+ enc,+ ["eval", "inspect", "tx", "export"],+ )+ print_mcp = probe_mcp_server(+ [str(FORMA_PRINT_BIN), "--mcp"],+ enc,+ ["print_check", "print_prep", "print_export", "print_profiles"],+ )++ with tempfile.TemporaryDirectory(prefix="forma_print_bench_") as tmp_str:+ tmpdir = Path(tmp_str)+ mcp_session = probe_mcp_tool_session(enc, tmpdir)+ cli_bench = benchmark_cli(runs=runs, tmpdir=tmpdir)++ rag_bench = benchmark_rag(enc=enc, rag_runs=rag_runs)+ total_duration_s = round(time.perf_counter() - t0, 3)++ return {+ "schema_version": "1.0.0",+ "repo_root": str(REPO_ROOT),+ "tokenizer": "o200k_base",+ "total_benchmark_duration_s": total_duration_s,+ "artifacts": artifacts,+ "mcp": {+ "core_forma_mcp": core_mcp,+ "opt_in_forma_print_mcp": print_mcp,+ "combined_tools_compact_o200k_tokens": (+ core_mcp["tools_compact_o200k_tokens"] + print_mcp["tools_compact_o200k_tokens"]+ ),+ "live_session_upside_down_t": mcp_session,+ },+ "cli_benchmarks": cli_bench,+ "rag_benchmarks": rag_bench,+ "published_baselines": get_published_baselines(),+ }+++def print_human_summary(report: dict[str, Any]) -> None:+ b = report["artifacts"]["bytes"]+ d = report["artifacts"]["derived"]+ mcp = report["mcp"]+ core_m = mcp["core_forma_mcp"]+ print_m = mcp["opt_in_forma_print_mcp"]+ rag_t = report["rag_benchmarks"]["corpus_totals"]++ print("=== Forma + forma-print + RAG Efficiency Benchmark ===")+ print(f"Duration: {report['total_benchmark_duration_s']} s | Tokenizer: {report['tokenizer']}")+ print("\n[1] Binary & KB Footprints")+ print(f" forma: {b['forma']:,} B ({d['forma_mb']} MB)")+ print(f" forma-mcp: {b['forma_mcp']:,} B ({d['forma_mcp_mb']} MB)")+ print(f" forma-print: {b['forma_print']:,} B ({d['forma_print_mb']} MB, excluded from default-members)")+ print(f" forma.wasm: {b['forma_wasm']:,} B ({d['forma_wasm_kb']} KB)")+ print(+ f" RAG SQLite: {b['rag_sqlite']:,} B ({d['rag_sqlite_mib']} MiB, "+ f"{rag_t['total_chunks']} chunks, {rag_t['citations']['unique_primary_source_urls_union']} unique URLs)"+ )++ print("\n[2] MCP Schema & Tool-Call Tokens (o200k_base)")+ print(+ f" core forma-mcp: {core_m['tool_count']} tools | "+ f"{core_m['tools_compact_o200k_tokens']} tok (<800) | handshake {core_m['handshake_total_ms']} ms"+ )+ print(+ f" opt-in forma-print: {print_m['tool_count']} tools | "+ f"{print_m['tools_compact_o200k_tokens']} tok | handshake {print_m['handshake_total_ms']} ms"+ )+ print(f" combined schema total: {mcp['combined_tools_compact_o200k_tokens']} o200k tokens")+ sess = mcp["live_session_upside_down_t"]+ for name in ("print_check", "print_prep", "print_export", "print_profiles"):+ c = sess[name]+ print(f" MCP {name:14s}: {c['latency_ms']:6.2f} ms | {c['response_o200k_tokens']:5d} tok | {c['response_bytes']:,} B")++ print("\n[3] Deterministic CLI Benchmarks (p50 / p95 ms)")+ for item in report["cli_benchmarks"]["benchmarks"]:+ t = item["timing"]+ det = item["deterministic"]+ extra = ""+ if "archive_3mf" in det:+ a = det["archive_3mf"]+ extra = (+ f" | 3MF={a['file_bytes']:,}B (raw={a['uncompressed_payload_bytes']:,}B, "+ f"{a['deflate_ratio_vs_file']}x Deflate, {a['entry_count']} entries)"+ )+ elif "step_bytes" in det:+ extra = f" | STEP={det['step_bytes']:,}B"+ elif "heatmap_png_bytes" in det:+ extra = f" | HM={det['heatmap_png_bytes']:,}B | rc={item['expected_rc']}"+ elif "candidates_evaluated" in det:+ extra = f" | cands={det['candidates_evaluated']} | rotated={det['rotated_from_input']}"+ print(+ f" {item['id']:40s} p50={t['p50_ms']:7.2f} ms p95={t['p95_ms']:7.2f} ms{extra}"+ )++ print("\n[4] RAG KB Benchmarks (18 queries, o200k_base)")+ print(+ f" Raw corpus+report: {rag_t['total_raw_o200k_tokens']:,} o200k tok | "+ f"DB chunks.text: {rag_t['db_text_o200k_tokens']:,} tok | "+ f"DB embedding_ready: {rag_t['db_embedding_ready_o200k_tokens']:,} tok"+ )+ for k_str, stats in report["rag_benchmarks"]["by_top_k"].items():+ t = stats["timing"]+ print(+ f" top_k={k_str:2s}: rank1={stats['rank1_hits']}/{stats['queries_total']} "+ f"| p50={t['p50_ms']:5.2f} ms p95={t['p95_ms']:5.2f} ms "+ f"| mean_text={stats['mean_retrieved_text_o200k_tokens']:7.1f} tok "+ f"({stats['compression_ratio_vs_raw_corpus']}x vs raw) "+ f"| urls={stats['unique_primary_source_urls']}"+ )+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ description="Reproducible efficiency benchmark for Forma + RAG KB + forma-print."+ )+ parser.add_argument("--json", action="store_true", help="Emit JSON only to stdout.")+ parser.add_argument("--runs", type=int, default=15, help="Timed CLI runs per fast fixture (default: 15).")+ parser.add_argument("--rag-runs", type=int, default=3, help="Timed passes across 18 RAG queries (default: 3).")+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv)+ if args.runs < 1 or args.rag_runs < 1:+ print("ERR: --runs and --rag-runs must be >= 1", file=sys.stderr)+ return 2+ try:+ report = run_benchmark(runs=args.runs, rag_runs=args.rag_runs)+ except Exception as exc: # noqa: BLE001+ if args.json:+ print(json.dumps({"error": str(exc)}, indent=2))+ else:+ print(f"BENCHMARK FAILED: {exc}", file=sys.stderr)+ return 1++ if args.json:+ print(json.dumps(report, indent=2, ensure_ascii=False))+ else:+ print_human_summary(report)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/research/scripts/validate_kb.py b/research/scripts/validate_kb.pynew file mode 100644index 0000000..0858d15--- /dev/null+++ b/research/scripts/validate_kb.py@@ -0,0 +1,991 @@+#!/usr/bin/env python3+"""Automated 5-stage validation suite for the forma-print research KB & RAG DB.++Stages:+ 1. JSON Schema Draft 2020-12 self-check across all 4 schemas+ 2. Corpus schema conformance, ID uniqueness, source_verified, trimmed strings, URLs & citations+ 3. Secret / API-key regex scan across research/ (never prints matched secret text)+ 4. SQLite integrity_check, kb_manifest parity, per-row rag_chunks schema validation, bloat & isolation checks+ 5. Sample RAG retrieval suite across all 4 domains, metadata filters, fault codes, edge cases & p95 < 100 ms+"""++from __future__ import annotations++import argparse+import json+import math+import re+import sqlite3+import sys+import time+from pathlib import Path+from typing import Any+from urllib.parse import urlparse++REPO_ROOT = Path(__file__).resolve().parents[2]+RESEARCH_DIR = REPO_ROOT / "research"+SCHEMAS_DIR = RESEARCH_DIR / "schemas"+CORPUS_DIR = RESEARCH_DIR / "corpus"+DB_PATH = RESEARCH_DIR / "rag" / "forma_print_kb.sqlite"++if str(REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(REPO_ROOT))++from research.rag import build_rag, query_rag # noqa: E402++STRICT_URL_RE = re.compile(r"^https?://[^\s]+$")+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)++SECRET_RULES: tuple[tuple[str, re.Pattern[str]], ...] = (+ ("exa_api_key_literal", re.compile(r"EXA_API_KEY\s*=\s*[A-Za-z0-9_-]{8,}")),+ ("openai_sk_token", re.compile(r"\bsk-[A-Za-z0-9_-]{16,}")),+ ("github_pat", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}")),+ ("aws_access_key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),+ ("bearer_token", re.compile(r"Bearer\s+[A-Za-z0-9._-]{20,}")),+ (+ "uuidv4_secret",+ re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b", re.IGNORECASE),+ ),+)+++def is_valid_http_url(url: str) -> bool:+ if not isinstance(url, str) or not STRICT_URL_RE.match(url):+ return False+ parsed = urlparse(url)+ return parsed.scheme in {"http", "https"} and bool(parsed.netloc) and not any(c.isspace() for c in url)+++class StdlibDraft202012Validator:+ """Strict pure-stdlib subset validator covering all Draft 2020-12 keywords used by forma-print."""++ def __init__(self, schema: dict[str, Any]) -> None:+ self.schema = schema++ def iter_errors(self, instance: Any) -> list[str]:+ errors: list[str] = []+ self._validate(instance, self.schema, "$", errors)+ return errors++ @classmethod+ def _canonical_value(cls, item: Any) -> Any:+ if isinstance(item, bool):+ return ("bool", item)+ if isinstance(item, (int, float)):+ if math.isfinite(item) and float(item).is_integer():+ return ("num", int(item))+ return ("num", float(item))+ if isinstance(item, str):+ return ("str", item)+ if item is None:+ return ("null", None)+ if isinstance(item, list):+ return ("list", tuple(cls._canonical_value(x) for x in item))+ if isinstance(item, dict):+ return ("dict", tuple(sorted((k, cls._canonical_value(v)) for k, v in item.items())))+ return ("other", repr(item))++ @staticmethod+ def _matches_type(val: Any, expected: str) -> bool:+ if expected == "object":+ return isinstance(val, dict)+ if expected == "array":+ return isinstance(val, list)+ if expected == "string":+ return isinstance(val, str)+ if expected == "integer":+ return isinstance(val, int) and not isinstance(val, bool)+ if expected == "number":+ return isinstance(val, (int, float)) and not isinstance(val, bool)+ if expected == "boolean":+ return isinstance(val, bool)+ if expected == "null":+ return val is None+ return True++ def _validate(self, val: Any, schema: dict[str, Any], path: str, errors: list[str]) -> None:+ if "const" in schema and val != schema["const"]:+ errors.append(f"{path}: value does not equal const {schema['const']!r}")++ if "enum" in schema and val not in schema["enum"]:+ errors.append(f"{path}: value {val!r} not in enum {schema['enum']!r}")++ if "type" in schema:+ t = schema["type"]+ allowed = [t] if isinstance(t, str) else list(t)+ if not any(self._matches_type(val, item) for item in allowed):+ errors.append(f"{path}: expected type {t!r}, got {type(val).__name__}")+ return++ if "allOf" in schema:+ for idx, sub in enumerate(schema["allOf"]):+ self._validate(val, sub, f"{path}.allOf[{idx}]", errors)++ if "anyOf" in schema:+ matched_any = False+ for sub in schema["anyOf"]:+ sub_errs: list[str] = []+ self._validate(val, sub, path, sub_errs)+ if not sub_errs:+ matched_any = True+ break+ if not matched_any:+ errors.append(f"{path}: value failed anyOf constraint")++ if "oneOf" in schema:+ matches = 0+ for sub in schema["oneOf"]:+ sub_errs = []+ self._validate(val, sub, path, sub_errs)+ if not sub_errs:+ matches += 1+ if matches != 1:+ errors.append(f"{path}: expected exactly 1 match for oneOf, got {matches}")++ if isinstance(val, str):+ if "minLength" in schema and len(val) < schema["minLength"]:+ errors.append(f"{path}: string length {len(val)} < minLength {schema['minLength']}")+ if "maxLength" in schema and len(val) > schema["maxLength"]:+ errors.append(f"{path}: string length {len(val)} > maxLength {schema['maxLength']}")+ if "pattern" in schema and not re.search(schema["pattern"], val):+ errors.append(f"{path}: string {val!r} does not match pattern {schema['pattern']!r}")+ if schema.get("format") == "uri" and not is_valid_http_url(val):+ errors.append(f"{path}: string {val!r} failed uri format check")++ elif isinstance(val, (int, float)) and not isinstance(val, bool):+ if "minimum" in schema and val < schema["minimum"]:+ errors.append(f"{path}: {val} < minimum {schema['minimum']}")+ if "maximum" in schema and val > schema["maximum"]:+ errors.append(f"{path}: {val} > maximum {schema['maximum']}")+ if "exclusiveMinimum" in schema and val <= schema["exclusiveMinimum"]:+ errors.append(f"{path}: {val} <= exclusiveMinimum {schema['exclusiveMinimum']}")+ if "exclusiveMaximum" in schema and val >= schema["exclusiveMaximum"]:+ errors.append(f"{path}: {val} >= exclusiveMaximum {schema['exclusiveMaximum']}")++ elif isinstance(val, list):+ if "minItems" in schema and len(val) < schema["minItems"]:+ errors.append(f"{path}: array len {len(val)} < minItems {schema['minItems']}")+ if "maxItems" in schema and len(val) > schema["maxItems"]:+ errors.append(f"{path}: array len {len(val)} > maxItems {schema['maxItems']}")+ if schema.get("uniqueItems"):+ seen: set[Any] = set()+ for idx, item in enumerate(val):+ key = self._canonical_value(item)+ if key in seen:+ errors.append(f"{path}[{idx}]: duplicate item violates uniqueItems")+ break+ seen.add(key)+ item_schema = schema.get("items")+ if isinstance(item_schema, dict):+ for idx, item in enumerate(val):+ self._validate(item, item_schema, f"{path}[{idx}]", errors)++ elif isinstance(val, dict):+ props = schema.get("properties", {})+ for req in schema.get("required", []):+ if req not in val:+ errors.append(f"{path}: missing required property {req!r}")+ add_props = schema.get("additionalProperties", True)+ for k, v in val.items():+ if k in props:+ self._validate(v, props[k], f"{path}.{k}", errors)+ elif add_props is False:+ errors.append(f"{path}: unexpected additional property {k!r}")+ elif isinstance(add_props, dict):+ self._validate(v, add_props, f"{path}.{k}", errors)+++def make_validator(schema: dict[str, Any], *, stdlib_only: bool) -> tuple[Any, str]:+ if not stdlib_only:+ try:+ import jsonschema # type: ignore++ return (+ jsonschema.Draft202012Validator(schema, format_checker=jsonschema.FormatChecker()),+ "jsonschema",+ )+ except ImportError:+ pass+ return StdlibDraft202012Validator(schema), "stdlib"+++def validate_record(validator: Any, engine: str, record: dict[str, Any]) -> list[str]:+ if engine == "jsonschema":+ return [f"{list(err.path)}: {err.message}" for err in validator.iter_errors(record)]+ return validator.iter_errors(record)+++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 run_validation(+ *,+ stdlib_only: bool = False,+ rebuild_rag: bool = False,+ max_db_mb: float = 2.0,+) -> dict[str, Any]:+ t_start = time.perf_counter()+ checks: list[dict[str, Any]] = []+ errors: list[str] = []+ engine_used = "stdlib"++ def record_check(name: str, passed: bool, details: Any) -> None:+ checks.append({"name": name, "passed": passed, "details": details})+ if not passed:+ errors.append(f"{name}: {details}")++ # ------------------------------------------------------------------+ # Stage 1: Schema Files Self-Check+ # ------------------------------------------------------------------+ schema_names = [+ "software.schema.json",+ "manufacturers.schema.json",+ "papers.schema.json",+ "rag_chunks.schema.json",+ ]+ schemas: dict[str, dict[str, Any]] = {}+ stage1_errs: list[str] = []+ for fname in schema_names:+ spath = SCHEMAS_DIR / fname+ if not spath.exists():+ stage1_errs.append(f"Missing schema: {spath}")+ continue+ try:+ sobj = json.loads(spath.read_text(encoding="utf-8"))+ if "2020-12" not in str(sobj.get("$schema", "")):+ stage1_errs.append(f"{fname}: $schema must reference Draft 2020-12")+ if not stdlib_only:+ try:+ import jsonschema # type: ignore++ jsonschema.Draft202012Validator.check_schema(sobj)+ except ImportError:+ pass+ schemas[fname] = sobj+ except Exception as exc: # noqa: BLE001+ stage1_errs.append(f"{fname}: {exc}")++ record_check("stage1_schemas", len(stage1_errs) == 0, {"loaded": list(schemas.keys()), "errors": stage1_errs})++ # ------------------------------------------------------------------+ # Stage 2: Corpus Schema, Uniqueness, URLs, Citations+ # ------------------------------------------------------------------+ corpus_specs = [+ ("software", CORPUS_DIR / "software.jsonl", "software.schema.json", 59),+ ("manufacturers", CORPUS_DIR / "manufacturers.jsonl", "manufacturers.schema.json", 22),+ ("papers", CORPUS_DIR / "papers.jsonl", "papers.schema.json", 49),+ ]+ global_ids: dict[str, str] = {}+ corpus_counts: dict[str, int] = {}+ stage2_errs: list[str] = []++ for domain_key, cpath, sname, expected_min in corpus_specs:+ if not cpath.exists():+ stage2_errs.append(f"Missing corpus file: {cpath}")+ continue+ if sname not in schemas:+ stage2_errs.append(f"Missing schema {sname} for {cpath.name}")+ continue++ validator, eng = make_validator(schemas[sname], stdlib_only=stdlib_only)+ engine_used = eng+ lines = [ln for ln in cpath.read_text(encoding="utf-8").splitlines() if ln.strip()]+ corpus_counts[domain_key] = len(lines)+ if len(lines) < expected_min:+ stage2_errs.append(f"{cpath.name}: expected >= {expected_min} records, got {len(lines)}")++ local_ids: set[str] = set()+ for lineno, line in enumerate(lines, start=1):+ try:+ rec = json.loads(line)+ except json.JSONDecodeError as exc:+ stage2_errs.append(f"{cpath.name}:{lineno}: invalid JSON ({exc})")+ continue++ verrs = validate_record(validator, eng, rec)+ for verr in verrs[:5]:+ stage2_errs.append(f"{cpath.name}:{lineno} ({rec.get('id', '?')}): {verr}")++ rid = rec.get("id")+ if not isinstance(rid, str) or not rid.strip():+ stage2_errs.append(f"{cpath.name}:{lineno}: missing id")+ else:+ if rid in local_ids:+ stage2_errs.append(f"{cpath.name}:{lineno}: duplicate local id {rid!r}")+ local_ids.add(rid)+ if rid in global_ids:+ stage2_errs.append(f"{cpath.name}:{lineno}: cross-corpus duplicate id {rid!r} (seen in {global_ids[rid]})")+ global_ids[rid] = cpath.name++ if rec.get("source_verified") is not True:+ stage2_errs.append(f"{cpath.name}:{lineno} ({rid}): source_verified is not True")++ empty_paths = find_empty_trimmed_strings(rec)+ if empty_paths:+ stage2_errs.append(f"{cpath.name}:{lineno} ({rid}): whitespace-only strings at {empty_paths[:3]}")++ urls_to_check: list[tuple[str, Any]] = []+ if domain_key == "software":+ urls_to_check.append(("repo_or_primary_url", rec.get("repo_or_primary_url")))+ for i, u in enumerate(rec.get("source_urls", [])):+ urls_to_check.append((f"source_urls[{i}]", u))+ elif domain_key == "manufacturers":+ for i, u in enumerate(rec.get("source_urls", [])):+ urls_to_check.append((f"source_urls[{i}]", u))+ tf = rec.get("troubleshooting_and_faults", {})+ for i, u in enumerate(tf.get("official_kb_urls", [])):+ urls_to_check.append((f"official_kb_urls[{i}]", u))+ for i, fc in enumerate(tf.get("example_fault_codes", [])):+ urls_to_check.append((f"example_fault_codes[{i}].kb_url", fc.get("kb_url")))+ elif domain_key == "papers":+ urls_to_check.append(("url", rec.get("url")))+ cite = rec.get("doi_or_arxiv_id", "")+ if not (DOI_RE.match(cite) or ARXIV_RE.match(cite)):+ stage2_errs.append(f"{cpath.name}:{lineno} ({rid}): invalid DOI/arXiv citation {cite!r}")+ else:+ clean_cite = cite.replace("arXiv:", "").replace("arxiv:", "")+ if clean_cite.lower() not in str(rec.get("url", "")).lower():+ stage2_errs.append(f"{cpath.name}:{lineno} ({rid}): url does not reflect citation {cite!r}")++ for upath, uval in urls_to_check:+ if not is_valid_http_url(uval):+ stage2_errs.append(f"{cpath.name}:{lineno} ({rid}): invalid URL at {upath}: {uval!r}")++ record_check("stage2_corpus", len(stage2_errs) == 0, {"counts": corpus_counts, "errors": stage2_errs[:20]})++ # ------------------------------------------------------------------+ # Stage 3: Secret & API-Key Scan Across research/+ # ------------------------------------------------------------------+ secret_hits: list[str] = []+ scanned_files = 0+ for fpath in sorted(RESEARCH_DIR.rglob("*")):+ if not fpath.is_file():+ continue+ if fpath.suffix in {".sqlite", ".pyc", ".png"} or "__pycache__" in fpath.parts:+ continue+ if fpath.name.endswith(".sqlite-wal") or fpath.name.endswith(".sqlite-shm"):+ continue+ scanned_files += 1+ try:+ text = fpath.read_text(encoding="utf-8", errors="ignore")+ except Exception as exc: # noqa: BLE001+ secret_hits.append(f"{fpath.relative_to(REPO_ROOT)}: unreadable ({exc})")+ continue+ for lineno, line in enumerate(text.splitlines(), start=1):+ for rule_name, pat in SECRET_RULES:+ if pat.search(line):+ # Report ONLY path, line number, and rule name — never matched text!+ secret_hits.append(f"{fpath.relative_to(REPO_ROOT)}:{lineno} matched {rule_name}")++ record_check("stage3_secrets", len(secret_hits) == 0, {"scanned_files": scanned_files, "hits": secret_hits})++ # ------------------------------------------------------------------+ # Stage 4: RAG SQLite DB, Manifest, Chunk Schema, Bloat & Isolation+ # ------------------------------------------------------------------+ stage4_errs: list[str] = []+ db_size_bytes = 0+ total_chunks = 0++ if rebuild_rag:+ build_rag.build_database(db_path=DB_PATH, max_db_mb=max_db_mb, quiet=True)+ det_tmp = DB_PATH.with_name("forma_print_kb.det_check.sqlite")+ try:+ s1 = build_rag.build_database(db_path=det_tmp, max_db_mb=max_db_mb, quiet=True)+ import hashlib++ h_main = hashlib.sha256(DB_PATH.read_bytes()).hexdigest()+ if h_main != s1["db_sha256"]:+ stage4_errs.append(f"Non-deterministic SQLite rebuild: {h_main} != {s1['db_sha256']}")+ finally:+ det_tmp.unlink(missing_ok=True)++ if not DB_PATH.exists():+ stage4_errs.append(f"Missing SQLite DB: {DB_PATH}")+ else:+ db_size_bytes = DB_PATH.stat().st_size+ max_bytes = int(max_db_mb * 1024 * 1024)+ if db_size_bytes > max_bytes:+ stage4_errs.append(f"DB size {db_size_bytes} bytes > max {max_bytes} bytes ({max_db_mb} MiB)")++ for sidecar in (Path(str(DB_PATH) + "-wal"), Path(str(DB_PATH) + "-shm")):+ if sidecar.exists():+ stage4_errs.append(f"Unexpected SQLite sidecar present: {sidecar.name}")++ conn = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)+ conn.row_factory = sqlite3.Row+ try:+ integ = conn.execute("PRAGMA integrity_check;").fetchone()+ if not integ or integ[0] != "ok":+ stage4_errs.append(f"PRAGMA integrity_check failed: {integ}")++ manifest = {r["key"]: r["value"] for r in conn.execute("SELECT key, value FROM kb_manifest").fetchall()}+ chunk_rows = conn.execute("SELECT * FROM chunks ORDER BY chunk_id").fetchall()+ total_chunks = len(chunk_rows)+ fts_count = conn.execute("SELECT COUNT(*) FROM chunks_fts").fetchone()[0]+ vocab_count = conn.execute("SELECT COUNT(*) FROM vocab_idf").fetchone()[0]++ if int(manifest.get("total_chunks", -1)) != total_chunks:+ stage4_errs.append(f"Manifest total_chunks={manifest.get('total_chunks')} != chunks={total_chunks}")+ if fts_count != total_chunks:+ stage4_errs.append(f"chunks_fts count {fts_count} != chunks count {total_chunks}")+ if vocab_count == 0:+ stage4_errs.append("vocab_idf table is empty")++ src_counts = json.loads(manifest.get("source_records_json", "{}"))+ for k, expected in (("software", 59), ("manufacturers", 22), ("papers", 49)):+ if src_counts.get(k) != expected:+ stage4_errs.append(f"Manifest source_records[{k!r}]={src_counts.get(k)} != {expected}")+ if int(src_counts.get("report_sections", 0)) < 1:+ stage4_errs.append("Manifest report_sections < 1")++ if "rag_chunks.schema.json" in schemas:+ chunk_validator, c_eng = make_validator(schemas["rag_chunks.schema.json"], stdlib_only=stdlib_only)+ for row in chunk_rows:+ meta = json.loads(row["metadata_json"])+ meta.setdefault("tech", json.loads(row["tech_json"]))+ meta.setdefault("manufacturer", row["manufacturer"])+ meta.setdefault("protocol", json.loads(row["protocol_json"]))+ meta.setdefault("category", row["category"])+ meta.setdefault("fault_code_prefix", json.loads(row["fault_prefix_json"]))+ meta.setdefault("tags", json.loads(row["tags_json"]))+ chunk_obj = {+ "chunk_id": row["chunk_id"],+ "domain": row["domain"],+ "entity_id": row["entity_id"],+ "title": row["title"],+ "section": row["section"],+ "text": row["text"],+ "metadata": meta,+ "source_url": row["source_url"],+ "token_count": row["token_count"],+ "embedding_ready_text": build_rag.format_embedding_ready_text(+ row["domain"], row["entity_id"], row["section"], row["title"], row["text"]+ ),+ "embedding_dim": None,+ "embedding_model": None,+ "content_hash": row["content_hash"],+ }+ verrs = validate_record(chunk_validator, c_eng, chunk_obj)+ if verrs:+ stage4_errs.append(f"chunk {row['chunk_id']}: {verrs[0]}")+ if len(stage4_errs) >= 15:+ break+ if build_rag.canonical_chunk_hash(chunk_obj) != row["content_hash"]:+ stage4_errs.append(f"chunk {row['chunk_id']}: content_hash mismatch")+ break+ finally:+ conn.close()++ # Bloat & prohibited blob check+ total_research_bytes = 0+ for fpath in RESEARCH_DIR.rglob("*"):+ if fpath.is_file() and "__pycache__" not in fpath.parts:+ total_research_bytes += fpath.stat().st_size+ if fpath.suffix.lower() in {".pdf", ".html", ".htm", ".zip", ".tar", ".gz"}:+ stage4_errs.append(f"Prohibited binary/HTML dump in research/: {fpath.relative_to(REPO_ROOT)}")+ if total_research_bytes > 5 * 1024 * 1024:+ stage4_errs.append(f"Total research/ size {total_research_bytes} bytes > 5 MiB cap")++ # Cargo / npm / .gitignore isolation checks+ cargo_toml = (REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")+ m_def = re.search(r"default-members\s*=\s*\[([^\]]*)\]", cargo_toml, re.DOTALL)+ if not m_def:+ stage4_errs.append("Cargo.toml missing default-members")+ elif "forma-print" in m_def.group(1) or "research" in m_def.group(1):+ stage4_errs.append("Cargo.toml default-members must exclude forma-print and research")++ pkg_json = json.loads((REPO_ROOT / "package.json").read_text(encoding="utf-8"))+ if any("research" in str(entry) for entry in pkg_json.get("files", [])):+ stage4_errs.append("package.json files must exclude research/")++ gitignore_lines = {ln.strip() for ln in (REPO_ROOT / ".gitignore").read_text(encoding="utf-8").splitlines()}+ if ".env" not in gitignore_lines:+ stage4_errs.append(".gitignore must contain .env")++ record_check(+ "stage4_rag_db_and_isolation",+ len(stage4_errs) == 0,+ {+ "db_size_bytes": db_size_bytes,+ "total_research_bytes": total_research_bytes,+ "total_chunks": total_chunks,+ "errors": stage4_errs,+ },+ )++ # ------------------------------------------------------------------+ # Stage 5: Sample RAG Retrieval Suite & p95 < 100 ms Latency Check+ # ------------------------------------------------------------------+ stage5_errs: list[str] = []+ rag_queries_log: list[dict[str, Any]] = []+ latencies_ms: list[float] = []++ if DB_PATH.exists():+ test_cases = [+ {+ "name": "software_orcaslicer_3mf",+ "kwargs": {"query": "OrcaSlicer 3MF model_settings.config Metadata", "domain": "software", "top_k": 3},+ "expect_any_entity": {"orcaslicer"},+ },+ {+ "name": "software_manifold_repair",+ "kwargs": {"query": "Manifold watertight boolean mesh", "domain": "software", "top_k": 3},+ "expect_any_entity": {"manifold"},+ },+ {+ "name": "report_nurb_checks",+ "kwargs": {"query": "Shpigford nurb build123d checks.py probe.py", "domain": "report", "top_k": 3},+ "expect_any_entity": {"nurb_inspection"},+ },+ {+ "name": "manufacturer_bambu_mqtts_lidar",+ "kwargs": {"query": "Bambu Lab MQTTS FTPS LiDAR LAN mode", "domain": "manufacturer", "top_k": 3},+ "expect_any_entity": {"bambu_lab"},+ "expect_rank1": "bambu_lab",+ },+ {+ "name": "manufacturer_prusa_rest_fault",+ "kwargs": {"query": "PrusaLink HTTP REST API #31208", "domain": "manufacturer", "top_k": 3},+ "expect_any_entity": {"prusa_research"},+ },+ {+ "name": "manufacturer_exact_fault_hms",+ "kwargs": {"query": "HMS_0700-0100-0002-0002", "domain": "manufacturer", "top_k": 3},+ "expect_any_entity": {"bambu_lab"},+ "expect_rank1": "bambu_lab",+ },+ {+ "name": "manufacturer_eddy_sensor",+ "kwargs": {"query": "eddy current probe LDC1612 homing error", "domain": "manufacturer", "top_k": 3},+ "expect_any_entity": {"sovol", "bigtreetech"},+ },+ {+ "name": "paper_overhang_support",+ "kwargs": {"query": "bridging steady scaffoldings overhang support minimization", "domain": "paper", "top_k": 3},+ "expect_any_entity": {"dumas-2014-bridging-the-gap"},+ },+ {+ "name": "paper_hollowing_drainage",+ "kwargs": {"query": "enclosed voids hollowing drainage resin", "domain": "paper", "top_k": 3},+ "expect_any_category": {"hollowing_drainage_suction"},+ },+ {+ "name": "paper_decomposition_chopper",+ "kwargs": {"query": "Chopper partitioning interlocking parts", "domain": "paper", "top_k": 3},+ "expect_any_entity": {"luo-2012-chopper"},+ },+ {+ "name": "paper_diacritic_tows",+ "kwargs": {"query": "Töws", "top_k": 3},+ "expect_any_entity": {"delfs-2016-build-orientation"},+ "expect_rank1": "delfs-2016-build-orientation",+ },+ {+ "name": "paper_diacritic_substr_bache",+ "kwargs": {"query": "bache", "top_k": 5},+ "expect_all_entities": {"baecher-2012-articulated", "baecher-2014-spin-it"},+ "expect_only_entities": {"baecher-2012-articulated", "baecher-2014-spin-it"},+ },+ {+ "name": "paper_diacritic_substr_udig",+ "kwargs": {"query": "udig", "top_k": 3},+ "expect_any_entity": {"wu-2016-rhombic-infill"},+ "expect_only_entities": {"wu-2016-rhombic-infill"},+ "expect_rank1": "wu-2016-rhombic-infill",+ },+ {+ "name": "paper_diacritic_substr_erem",+ "kwargs": {"query": "erem", "top_k": 5},+ "expect_all_entities": {"dumas-2014-bridging-the-gap", "martinez-2016-voronoi-foams"},+ },+ {+ "name": "paper_diacritic_substr_onas",+ "kwargs": {"query": "onas", "top_k": 5},+ "expect_all_entities": {+ "etienne-2019-curvislicer",+ "livesu-2017-processing-pipeline",+ "martinez-2016-voronoi-foams",+ },+ },+ {+ "name": "filter_msla_protocol_sdcp",+ "kwargs": {"query": "WebSocket file upload", "tech": "msla", "protocol": "sdcp", "top_k": 5},+ "expect_any_entity": {"elegoo", "phrozen"},+ },+ {+ "name": "filter_fault_prefix_er",+ "kwargs": {"query": "", "fault_prefix": "ER", "top_k": 5},+ "expect_any_entity": {"ultimaker"},+ "forbid_entities": {"lulzbot"},+ },+ {+ "name": "filter_fault_prefix_hash",+ "kwargs": {"query": "", "fault_prefix": "#", "top_k": 25},+ "expect_any_entity": {"prusa_research"},+ "expect_only_entities": {"prusa_research"},+ "forbid_entities": {+ "ankermake_eufymake",+ "anycubic",+ "bambu_lab",+ "bigtreetech",+ "creality",+ "duet3d",+ "elegoo",+ "flashforge",+ "formlabs",+ "lulzbot",+ "makerbot",+ "markforged",+ "phrozen",+ "qidi_tech",+ "raise3d",+ "ratrig",+ "snapmaker",+ "sovol",+ "stratasys",+ "ultimaker",+ "voron_design",+ },+ },+ {+ "name": "edge_punctuation_operators",+ "kwargs": {"query": "c++ AND OR -test #31208", "top_k": 3},+ "expect_any_entity": {"prusa_research"},+ },+ {+ "name": "edge_empty_query",+ "kwargs": {"query": "", "top_k": 5},+ "expect_empty": True,+ },+ {+ "name": "edge_top_k_zero",+ "kwargs": {"query": "Bambu Lab", "top_k": 0},+ "expect_empty": True,+ },+ {+ "name": "edge_nonexistent_token",+ "kwargs": {"query": "qxqz_nonexistent_xylophobe_zz77", "top_k": 5},+ "expect_empty": True,+ },+ ]++ rag_conn = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)+ try:+ for tc in test_cases:+ res = query_rag.query_kb(db_path=DB_PATH, conn=rag_conn, **tc["kwargs"])+ latencies_ms.append(float(res["latency_ms"]))+ hits = res["results"]+ hit_entities = [h["entity_id"] for h in hits]+ rag_queries_log.append(+ {+ "name": tc["name"],+ "latency_ms": res["latency_ms"],+ "hit_count": len(hits),+ "top_entities": hit_entities,+ }+ )++ if tc.get("expect_empty"):+ if hits:+ stage5_errs.append(f"{tc['name']}: expected 0 hits, got {len(hits)}")+ continue++ if not hits:+ stage5_errs.append(f"{tc['name']}: expected hits, got 0")+ continue++ for h in hits:+ if not is_valid_http_url(h.get("source_url", "")):+ stage5_errs.append(f"{tc['name']}: invalid hit source_url {h.get('source_url')!r}")++ if "expect_any_entity" in tc and not (set(hit_entities) & tc["expect_any_entity"]):+ stage5_errs.append(+ f"{tc['name']}: expected one of {sorted(tc['expect_any_entity'])}, got {hit_entities}"+ )+ if "expect_all_entities" in tc and not tc["expect_all_entities"].issubset(set(hit_entities)):+ stage5_errs.append(+ f"{tc['name']}: missing required entities {sorted(tc['expect_all_entities'] - set(hit_entities))} from {hit_entities}"+ )+ if "expect_only_entities" in tc and not set(hit_entities).issubset(tc["expect_only_entities"]):+ stage5_errs.append(+ f"{tc['name']}: expected only {sorted(tc['expect_only_entities'])}, got {hit_entities}"+ )+ if "forbid_entities" in tc and (set(hit_entities) & tc["forbid_entities"]):+ stage5_errs.append(+ f"{tc['name']}: forbidden entities {sorted(set(hit_entities) & tc['forbid_entities'])} present in {hit_entities}"+ )+ if "expect_rank1" in tc and hit_entities[0] != tc["expect_rank1"]:+ stage5_errs.append(f"{tc['name']}: expected rank-1 {tc['expect_rank1']}, got {hit_entities[0]}")+ if "expect_any_category" in tc:+ cats = {h["metadata"].get("category") for h in hits}+ if not (cats & tc["expect_any_category"]):+ stage5_errs.append(f"{tc['name']}: expected category in {tc['expect_any_category']}, got {cats}")++ # Regression check: whitespace-only filters must behave identically to unfiltered queries+ baseline_bambu = query_rag.query_kb("Bambu Lab", db_path=DB_PATH, conn=rag_conn, top_k=5)+ latencies_ms.append(float(baseline_bambu["latency_ms"]))+ baseline_ids = [h["chunk_id"] for h in baseline_bambu["results"]]+ for ws_label, ws_kwargs in (+ ("whitespace_filter_tech", {"tech": " "}),+ ("whitespace_filter_manufacturer", {"manufacturer": " "}),+ ("whitespace_filter_domain", {"domain": " "}),+ ):+ ws_res = query_rag.query_kb("Bambu Lab", db_path=DB_PATH, conn=rag_conn, top_k=5, **ws_kwargs)+ latencies_ms.append(float(ws_res["latency_ms"]))+ ws_ids = [h["chunk_id"] for h in ws_res["results"]]+ rag_queries_log.append(+ {+ "name": ws_label,+ "latency_ms": ws_res["latency_ms"],+ "hit_count": len(ws_res["results"]),+ "top_entities": [h["entity_id"] for h in ws_res["results"]],+ }+ )+ if ws_ids != baseline_ids:+ stage5_errs.append(f"{ws_label}: expected {baseline_ids}, got {ws_ids}")++ # Repeat queries to verify p95 latency < 100 ms over >= 20 runs+ for q in ("HMS_0700-0100-0002-0002", "OrcaSlicer 3MF", "Make It Stand CoM", "PrusaLink #31208", "nurb checks.py"):+ latencies_ms.append(float(query_rag.query_kb(q, db_path=DB_PATH, conn=rag_conn, top_k=5)["latency_ms"]))+ finally:+ rag_conn.close()++ # Lightweight :memory: synthetic edge-case guard (outside real-KB latencies_ms)+ mem_conn = sqlite3.connect(":memory:")+ try:+ mem_conn.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+ );+ """+ )+ mem_conn.executemany(+ "INSERT INTO vocab_idf (term_id, term, df, idf) VALUES (?, ?, ?, ?)",+ [(1, "calibration", 1, 1.5), (2, "nozzle", 1, 2.0)],+ )+ mem_rows = [+ (+ 1, "pp:syn:tows", "paper", "syn_tows", "Compound Diacritic", "Body", "",+ "We evaluated microTöws_unit in lab.", "https://example.org/tows", "orientation",+ None, "[]", "[]", "[]", "[]", "{}", 6, "{}", 0.0, "h1",+ ),+ (+ 2, "pp:syn:filter", "paper", "syn_filter", "Ligature Token", "Body", "",+ "Using a microfilter improves resin clarity.", "https://example.org/filter", "materials",+ None, "[]", "[]", "[]", "[]", "{}", 6, "{}", 0.0, "h2",+ ),+ (+ 3, "mf:syn:calib", "manufacturer", "syn_calib", "Alpha Printer", "Config", "",+ "Printer parameter reference.", "https://example.org/calib", "desktop",+ "syn_calib", "[]", "[]", "[]", "[]", "{}", 3, '{"1" : 1.5}', 1.5, "h3",+ ),+ (+ 4, "mf:syn:ab", "manufacturer", "syn_ab", "Beta Printer", "Faults", "",+ "Slash fault entry.", "https://example.org/ab", "desktop",+ "syn_ab", "[]", "[]", "[]", "[]", '{"fault_codes":["A\\/B"]}', 3, "{}", 0.0, "h4",+ ),+ (+ 5, "mf:syn:ukey_tfidf", "manufacturer", "syn_ukey_tfidf", "Gamma Printer", "Parts", "",+ "Component geometry check.", "https://example.org/ukey1", "desktop",+ "syn_ukey_tfidf", "[]", "[]", "[]", "[]", "{}", 3, '{"\\u0032": 2.0}', 2.0, "h5",+ ),+ (+ 6, "mf:syn:ukey_fc", "manufacturer", "syn_ukey_fc", "Delta Printer", "Faults", "",+ "Escaped key fault entry.", "https://example.org/ukey2", "desktop",+ "syn_ukey_fc", "[]", "[]", "[]", "[]", '{"fault\\u005fcodes":["X99"]}', 4, "{}", 0.0, "h6",+ ),+ ]+ mem_conn.executemany(+ """+ INSERT INTO chunks (+ rowid, chunk_id, domain, entity_id, title, section, tags_text, text,+ source_url, category, manufacturer, tech_json, protocol_json,+ fault_prefix_json, tags_json, metadata_json, token_count,+ tfidf_json, tfidf_norm, content_hash+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ mem_rows,+ )+ mem_conn.execute("INSERT INTO chunks_fts(chunks_fts) VALUES ('rebuild');")++ syn_cases = [+ ("syn_compound_tows", {"query": "tows"}, "pp:syn:tows", None),+ ("syn_ligature_filter", {"query": "filter"}, "pp:syn:filter", None),+ ("syn_tfidf_space_colon", {"query": "calibration"}, "mf:syn:calib", 1.0),+ ("syn_fault_slash_escape", {"query": "a/b"}, "mf:syn:ab", None),+ ("syn_tfidf_escaped_key", {"query": "nozzle"}, "mf:syn:ukey_tfidf", 1.0),+ ("syn_fault_escaped_key_query", {"query": "x99"}, "mf:syn:ukey_fc", None),+ ("syn_fault_escaped_key_prefix", {"query": "", "fault_prefix": "X"}, "mf:syn:ukey_fc", None),+ ]+ for syn_name, syn_kwargs, expected_chunk_id, expected_tfidf in syn_cases:+ syn_res = query_rag.query_kb(conn=mem_conn, top_k=5, **syn_kwargs)+ syn_hits = syn_res["results"]+ hit_ids = [h["chunk_id"] for h in syn_hits]+ if expected_chunk_id not in hit_ids:+ stage5_errs.append(f"{syn_name}: expected {expected_chunk_id} in {hit_ids}")+ elif expected_tfidf is not None:+ matched = next(h for h in syn_hits if h["chunk_id"] == expected_chunk_id)+ if matched["tfidf_score"] != expected_tfidf:+ stage5_errs.append(+ f"{syn_name}: expected tfidf_score={expected_tfidf}, got {matched['tfidf_score']}"+ )+ finally:+ mem_conn.close()++ sorted_lat = sorted(latencies_ms)+ p95_idx = max(0, math.ceil(0.95 * len(sorted_lat)) - 1)+ p95_ms = round(sorted_lat[p95_idx], 3)+ if p95_ms >= 100.0:+ stage5_errs.append(f"p95 query latency {p95_ms} ms >= 100.0 ms")++ # CLI error-handling regressions for query_rag.py (missing --db & --top-k <= 0)+ import subprocess # noqa: PLC0415++ qscript = str(REPO_ROOT / "research" / "rag" / "query_rag.py")+ missing_db_json = subprocess.run(+ [sys.executable, qscript, "--query", "Bambu", "--db", str(DB_PATH.with_name("nonexistent_kb.sqlite")), "--json"],+ capture_output=True,+ text=True,+ check=False,+ )+ if missing_db_json.returncode != 1 or "Traceback" in missing_db_json.stderr:+ stage5_errs.append(+ f"query_rag missing --db --json unexpected rc={missing_db_json.returncode} stderr={missing_db_json.stderr!r}"+ )+ else:+ try:+ err_obj = json.loads(missing_db_json.stdout)+ if not isinstance(err_obj.get("error"), str) or not err_obj["error"]:+ stage5_errs.append(f"query_rag missing --db --json missing error field: {err_obj!r}")+ except json.JSONDecodeError as exc:+ stage5_errs.append(f"query_rag missing --db --json invalid JSON: {exc}")++ missing_db_plain = subprocess.run(+ [sys.executable, qscript, "--query", "Bambu", "--db", str(DB_PATH.with_name("nonexistent_kb.sqlite"))],+ capture_output=True,+ text=True,+ check=False,+ )+ if missing_db_plain.returncode != 1 or "Traceback" in missing_db_plain.stderr or not missing_db_plain.stderr.strip():+ stage5_errs.append(+ f"query_rag missing --db plain unexpected rc={missing_db_plain.returncode} stderr={missing_db_plain.stderr!r}"+ )++ for bad_k in ("0", "-3"):+ bad_topk = subprocess.run(+ [sys.executable, qscript, "--query", "Bambu", "--db", str(DB_PATH), "--top-k", bad_k, "--json"],+ capture_output=True,+ text=True,+ check=False,+ )+ if bad_topk.returncode == 0 or "Traceback" in bad_topk.stderr:+ stage5_errs.append(f"query_rag --top-k {bad_k} unexpected rc={bad_topk.returncode}")+ else:+ try:+ err_obj = json.loads(bad_topk.stdout)+ if not isinstance(err_obj.get("error"), str) or not err_obj["error"]:+ stage5_errs.append(f"query_rag --top-k {bad_k} missing error field: {err_obj!r}")+ except json.JSONDecodeError as exc:+ stage5_errs.append(f"query_rag --top-k {bad_k} invalid JSON: {exc}")+ else:+ p95_ms = 0.0+ stage5_errs.append("Skipped RAG queries because DB is missing")++ record_check(+ "stage5_rag_retrieval",+ len(stage5_errs) == 0,+ {"queries_run": len(rag_queries_log), "p95_latency_ms": p95_ms, "errors": stage5_errs},+ )++ duration_ms = round((time.perf_counter() - t_start) * 1000.0, 2)+ return {+ "status": "pass" if not errors else "fail",+ "duration_ms": duration_ms,+ "validator_engine": engine_used,+ "counts": corpus_counts,+ "total_chunks": total_chunks,+ "db_size_bytes": db_size_bytes,+ "p95_latency_ms": p95_ms,+ "checks": checks,+ "rag_queries": rag_queries_log,+ "errors": errors,+ }+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Validate forma-print research KB schemas, corpus, RAG DB & retrieval.")+ parser.add_argument("--json", action="store_true", help="Emit structured JSON report.")+ parser.add_argument("--stdlib-only", action="store_true", help="Force built-in pure-stdlib Draft 2020-12 validator.")+ parser.add_argument("--rebuild-rag", action="store_true", help="Rebuild and verify bit-identical determinism before checks.")+ parser.add_argument("--max-db-mb", type=float, default=2.0, help="Maximum allowed SQLite DB size in MiB.")+ args = parser.parse_args(argv)++ report = run_validation(+ stdlib_only=args.stdlib_only,+ rebuild_rag=args.rebuild_rag,+ max_db_mb=args.max_db_mb,+ )++ if args.json:+ print(json.dumps(report, indent=2, ensure_ascii=False))+ else:+ print(+ f"validate_kb: status={report['status'].upper()} | engine={report['validator_engine']} | "+ f"chunks={report['total_chunks']} | db={report['db_size_bytes']} B | "+ f"p95={report['p95_latency_ms']} ms | duration={report['duration_ms']} ms"+ )+ for chk in report["checks"]:+ mark = "PASS" if chk["passed"] else "FAIL"+ print(f" [{mark}] {chk['name']}")+ if report["errors"]:+ print("Errors:")+ for err in report["errors"]:+ print(f" - {err}")++ return 0 if report["status"] == "pass" else 1+++if __name__ == "__main__":+ sys.exit(main())