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

39.3 KB
Raw Blame
#!/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())