Skip to content

armgit / forma

Public Imported from GitHub
0

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

8.8 KB
Raw Blame

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

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)

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)

# 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

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)

# 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 — 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():
    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.