# Plan: Lightweight Standalone SQLite + FTS5 Metadata & Telemetry Database (`metadata.db`) Engine (`v2.0.18`) - **Document ID:** `PLAN-SQLITE-REST-API-METADATA-DB` (`v2.0.18`) - **Roadmap Status:** **ACTIVE / READY** (Core `hyperstitionstud_io.db.sqlite_meta` + `hs-db-build` CLI + automatic population of the SQLite metadata/telemetry database on every `/api/v1/*` REST and `/mcp` JSON-RPC call) - **Target Modules:** - `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/db/__init__.py` & `sqlite_meta.py` (`hs-db-build` CLI & SQLite/FTS5 catalog + telemetry engine) - `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/rest.py` (`dispatch_rest_v1` telemetry hook populating SQLite on every `/api/v1/*` call) - `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/server.py` (`dispatch_jsonrpc` telemetry hook populating SQLite on every `/mcp` JSON-RPC call) - `/workspace/hyperstitionstudio-core/deploy/logrotate.d/hyperstition-sqlite-meta` (Quiescent `logrotate.d` truncation at configurable default `100M` / `100 MB` limit) - `/workspace/hyperstitionstudio-core/pyproject.toml` (`hs-db-build` entry point) - `/workspace/hyperstitionstudio-core/tests/test_core_suite.py` (Unit verification that `/api/v1/*` and `/mcp` calls populate the SQLite metadata/telemetry DB and `logrotate.d` quiescently truncates it) - **Explicitly Deferred Scope (Moved to Long-Term Inactive Plan `PLAN-SQLITE-META-REST-ENDPOINTS-ETAG-AND-VPS-SYNC`):** Exposing HTTP `/api/v1/meta/{manifests,search,coordinate/{aq_int},timeseries/query,telemetry}`, HTTP `ETag` / `If-None-Match` (`304 Not Modified`) middleware, MCP tool `hs_query_sqlite_catalog`, and wiring `hs-db-build` into `deploy/sync-vps-repos.sh` remain **inactive** in `/workspace/encyclopedia-knowledge-graph/docs/PLAN-SQLITE-META-REST-ENDPOINTS-ETAG-AND-VPS-SYNC.{md,pdf}` alongside all other inactive plans. - **Zero External Dependencies:** Built **100% on Python's standard-library `sqlite3` module** (`0` third-party ORMs, `0` external DB daemons). - **Core Architectural Separation (Immutable Catalog Index vs. Ephemeral Runtime Telemetry):** To preserve the strict `ReadOnlyIsolationGuard` guarantees while enabling both sub-millisecond indexed search and local telemetry rollups in Python, the SQLite architecture splits cleanly into **two lightweight SQLite database files** (connected simultaneously via `ATTACH DATABASE` or dedicated connections): 1. **Catalog Metadata & FTS5 Index DB (`hyperstition-catalog.db`, Read-Only at Runtime, `mode=ro`):** Compiled deterministically via `hs-db-build` (`python3 -m hyperstitionstud_io.db.sqlite_meta --build`). Indexes all `282` glossary entries, `190` bilingual lexical specimens, `388` Knowledge Graph nodes, `1,282` edges, `71` archive dossiers, `1,850+` verified `333/666/777` equations, `24 × 30` periodic time-series bars, and all `CIDv1` registry digests with **SQLite FTS5 (`BM25`) full-text search** and B-tree integer indices on `ing_aq`, `eng_aq`, `target_sum`, `symbol`, and `date_utc`. 2. **Runtime Telemetry & Audit DB (`api-telemetry.db`, WAL Mode):** Lightweight, append-only SQLite database (`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;`) that records privacy-preserving per-operation call counts, status tallies, execution latency ($\text{p50 / p95 / p99}$ microseconds), and `ReadOnlyIsolationGuard` audit receipts—without storing any client IP addresses, cookies, or PII. --- ## 1. Why a Standalone SQLite + FTS5 Metadata DB Transforms Local Corpus Querying & Observability Currently, querying across `glossary-registry.json`, `encyclopedia-graph.json`, `quant-timeseries.json`, and the `71` Markdown dossiers requires reading and parsing multiple `.json` and `.md` files (`~12–45 ms` of file I/O and regex parsing per call). By introducing the dual SQLite metadata layer (`hyperstitionstud_io.db.sqlite_meta`): | Capability | Current File-Scan / Regex Behavior | With Standalone SQLite + FTS5 (`hyperstitionstud_io.db.sqlite_meta`) | Improvement | | :--- | :--- | :--- | :--- | | **1. Sub-Millisecond Indexed Lookups (`B-Tree`)** | Parses `encyclopedia-graph.json` (`1.4 MB`), `glossary-registry.json`, or `quant-timeseries.json` on each call (`12–28 ms`). | Point & range queries against B-tree indices (`idx_specimens_ing_aq`, `idx_bars_sym_date`, `idx_nodes_id`) execute in **`80–250 microseconds` (`< 0.25 ms`)**. | **`50x–120x` faster** | | **2. Full-Text Search Across All 71 Dossiers & 282 Glossary Terms (`FTS5 BM25`)** | Linear `glob("*.md")` + Python substring/regex scan across 71 files (`25–45 ms`), no relevance ranking. | Single `SELECT ... FROM fts_catalog WHERE fts_catalog MATCH ? ORDER BY bm25(fts_catalog)` query with snippet highlighting and prefix matching in **`< 0.6 ms`**. | **Ranked `BM25` + `60x` faster** | | **3. Multi-Table Relational Joins in One Query (`SQL`)** | Requires multiple separate Python passes to join a ticker (`NVDA`), its `AQ` coordinate (`137`), its Knowledge Graph neighbors, and its dated `333/666/777` archive equations. | Single indexed SQL join across `quant_timeseries_bars`, `kg_nodes`, `kg_edges`, and `archive_equations` via `query_coordinate_join(137)`. | **1 query instead of 4 passes** | | **4. Cryptographic Provenance & `CIDv1` Registry Manifest Table** | Re-computes SHA-256 and `dag-json` `CIDv1` digests over raw files on demand. | `registry_manifests` table stores pre-computed `dag_json_cidv1` (`baguqeera...`), `raw_sha256`, and `record_count` per compiled registry. | **Instant `< 0.1 ms` digest lookup** | | **5. Zero-PII Telemetry & Latency Rollups (`api-telemetry.db`)** | Stateless stdout only; zero structured persistence of query latency or `ReadOnlyIsolationGuard` verification counts. | Append-only WAL table `api_endpoint_rollups` and 200-event ring buffer `api_audit_ringbuffer` track call counts, status tallies, mean/max latency ($\mu\text{s}$), and `ReadOnlyIsolationGuard` pass counts in `<= 64 KB`. | **Deterministic local audit rollups** | --- ## 2. Relational & FTS5 Schema Design (`hyperstition-catalog.db` & `api-telemetry.db`) ### 2.1 Read-Only Catalog & Search Database (`hyperstition-catalog.db`) ```sql -- 1. Cryptographic Registry & Schema Provenance Manifests CREATE TABLE registry_manifests ( registry_slug TEXT PRIMARY KEY, -- e.g. 'glossary-registry', 'encyclopedia-graph', 'quant-timeseries' source_path TEXT NOT NULL, schema_urn TEXT NOT NULL, version TEXT NOT NULL, record_count INTEGER NOT NULL, raw_sha256 TEXT NOT NULL, dag_json_cidv1 TEXT NOT NULL, -- 'baguqeera...' byte_size INTEGER NOT NULL, compiled_at_utc TEXT NOT NULL ) WITHOUT ROWID; -- 2. Canonical Glossary & Bilingual Vocabulary Specimens (282 Glossary + 190 Bilingual Specimens) CREATE TABLE glossary_entries ( entry_id INTEGER PRIMARY KEY, term TEXT NOT NULL UNIQUE, category TEXT NOT NULL, section_id TEXT NOT NULL, eng_aq INTEGER NOT NULL, ing_term TEXT NOT NULL, ing_aq INTEGER NOT NULL, delta INTEGER NOT NULL, is_isometric INTEGER NOT NULL, -- 0 or 1 is_twin_prime INTEGER NOT NULL, -- 0 or 1 division_id TEXT, volume_pdf TEXT, definition TEXT NOT NULL ); CREATE INDEX idx_glossary_ing_aq ON glossary_entries(ing_aq); CREATE INDEX idx_glossary_eng_aq ON glossary_entries(eng_aq); CREATE INDEX idx_glossary_cat ON glossary_entries(category); -- 3. Knowledge Graph Nodes (388 Nodes) & Deduplicated Edges (1,282 Edges) CREATE TABLE kg_nodes ( node_id TEXT PRIMARY KEY, -- e.g. 'aq:137', 'build:S1', 'spec:envideea' node_urn TEXT NOT NULL UNIQUE, node_type TEXT NOT NULL, label TEXT NOT NULL, aq_value INTEGER, degree INTEGER NOT NULL, is_flex_pivot INTEGER NOT NULL DEFAULT 0, guild_id TEXT, metadata_json TEXT NOT NULL ) WITHOUT ROWID; CREATE INDEX idx_kg_nodes_aq ON kg_nodes(aq_value); CREATE INDEX idx_kg_nodes_type ON kg_nodes(node_type); CREATE TABLE kg_edges ( source_id TEXT NOT NULL, target_id TEXT NOT NULL, relation TEXT NOT NULL, weight REAL NOT NULL DEFAULT 1.0, PRIMARY KEY (source_id, target_id, relation) ) WITHOUT ROWID; CREATE INDEX idx_kg_edges_target ON kg_edges(target_id); CREATE INDEX idx_kg_edges_rel ON kg_edges(relation); -- 4. Archive & Zoology Dossiers (01..71) & Verified Multi-Scale Equations (333 / 666 / 777) CREATE TABLE dossiers ( dossier_number INTEGER PRIMARY KEY, -- 1..71 file_name TEXT NOT NULL UNIQUE, title TEXT NOT NULL, is_periodic_news INTEGER NOT NULL, -- 1 for *-dossier-news-YYYY-MM-DD.md, 0 for static dossiers date_utc TEXT, -- 'YYYY-MM-DD' if periodic news/quant dossier, else NULL equation_count INTEGER NOT NULL, sha256 TEXT NOT NULL ); CREATE INDEX idx_dossiers_date ON dossiers(date_utc) WHERE date_utc IS NOT NULL; CREATE TABLE archive_equations ( eq_id TEXT PRIMARY KEY, -- Content-addressed key: e.g. 'eq_333_envideea_0042' dossier_number INTEGER NOT NULL, date_utc TEXT, -- Populated if from dated periodic dossier target_sum INTEGER NOT NULL, -- 333, 666, 777, etc. ing_phrase TEXT NOT NULL, eng_gloss TEXT NOT NULL, breakdown TEXT NOT NULL, word_count INTEGER NOT NULL, FOREIGN KEY (dossier_number) REFERENCES dossiers(dossier_number) ) WITHOUT ROWID; CREATE INDEX idx_eq_target ON archive_equations(target_sum); CREATE INDEX idx_eq_date ON archive_equations(date_utc) WHERE date_utc IS NOT NULL; -- 5. Periodic Quantitative Financial Time-Series Bars (24 Tickers x T UTC Days — Strictly Periodic Only) CREATE TABLE quant_timeseries_bars ( symbol TEXT NOT NULL, date_utc TEXT NOT NULL, entity_eng TEXT NOT NULL, entity_ing TEXT NOT NULL, entity_ing_aq INTEGER NOT NULL, guilds_csv TEXT NOT NULL, tradingview_symbol TEXT NOT NULL, tradingview_url TEXT NOT NULL, close_usd REAL NOT NULL, change_pct REAL NOT NULL, change_bps INTEGER NOT NULL, volume_ratio_20d REAL NOT NULL, market_cap_str TEXT NOT NULL, close_digit_aq INTEGER NOT NULL, close_spoken_ing TEXT NOT NULL, close_spoken_ing_aq INTEGER NOT NULL, scaled_cap_spoken_ing_aq INTEGER NOT NULL, bps_spoken_ing_aq INTEGER NOT NULL, co_present_in_news_wire INTEGER NOT NULL, contingent_points REAL NOT NULL, locks_json TEXT NOT NULL, PRIMARY KEY (symbol, date_utc) ) WITHOUT ROWID; CREATE INDEX idx_qbars_date ON quant_timeseries_bars(date_utc); CREATE INDEX idx_qbars_close_aq ON quant_timeseries_bars(close_spoken_ing_aq); CREATE INDEX idx_qbars_ent_aq ON quant_timeseries_bars(entity_ing_aq); -- 6. Unified FTS5 Full-Text Search Virtual Table (BM25 Ranked Search Across Glossary, Graph & Equations) CREATE VIRTUAL TABLE fts_catalog USING fts5( doc_type, -- 'glossary' | 'equation' | 'node' | 'dossier' | 'instrument' doc_id, -- Primary key / URI title_or_ing, -- Headword or Ingglish phrase gloss_or_body, -- English gloss, definition, or breakdown aq_coord, -- Integer AQ coordinate(s) as text tokens guild_tags, -- S1..S6, M1..M7+ tokenize = 'unicode61 remove_diacritics 2' ); ``` ### 2.2 Runtime Telemetry & Audit Database (`api-telemetry.db` — WAL Mode, Zero PII) ```sql PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; -- 1. Per-Operation Aggregated Request & Latency Rollups (Bounded to <= 100 rows total!) CREATE TABLE IF NOT EXISTS api_endpoint_rollups ( protocol TEXT NOT NULL, -- 'python_api' | 'cli' | 'rest_v1' | 'mcp_jsonrpc' method TEXT NOT NULL, -- 'CALL' | 'GET' | 'POST' endpoint_pattern TEXT NOT NULL, -- e.g. 'sqlite_meta:query_coordinate_join' total_requests INTEGER NOT NULL DEFAULT 0, status_2xx INTEGER NOT NULL DEFAULT 0, status_304 INTEGER NOT NULL DEFAULT 0, status_4xx INTEGER NOT NULL DEFAULT 0, status_5xx INTEGER NOT NULL DEFAULT 0, total_latency_us INTEGER NOT NULL DEFAULT 0, max_latency_us INTEGER NOT NULL DEFAULT 0, last_called_utc TEXT NOT NULL, PRIMARY KEY (protocol, method, endpoint_pattern) ) WITHOUT ROWID; -- 2. Ring-Buffer of Last 200 Isolation & Harvest Audit Events (Auto-Pruned via Trigger) CREATE TABLE IF NOT EXISTS api_audit_ringbuffer ( event_id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp_utc TEXT NOT NULL, endpoint TEXT NOT NULL, status_code INTEGER NOT NULL, latency_us INTEGER NOT NULL, isolation_ok INTEGER NOT NULL -- 1 = ReadOnlyIsolationGuard verified ); ``` *(By aggregating telemetry by `(protocol, method, endpoint_pattern)` and capping `api_audit_ringbuffer` at the most recent `200` rows, `api-telemetry.db` never grows past `~64 KB` on disk).* --- ## 3. Python Query & CLI Surface (`hyperstitionstud_io.db.sqlite_meta` & `hs-db-build`) `hyperstitionstud_io.db.sqlite_meta` exposes a clean, self-contained Python API and CLI (`hs-db-build`) operating strictly over `hyperstition-catalog.db` (`mode=ro` on query) and `api-telemetry.db`: | Python Function / CLI Flag | Arguments | What It Queries or Builds in SQLite (`< 1 ms`) | | :--- | :--- | :--- | | `build_catalog_sqlite_db(db_path=None)` / `hs-db-build --build` | `db_path: Path \| None` | Compiles `registry_manifests`, `glossary_entries`, `kg_nodes`, `kg_edges`, `dossiers`, `archive_equations`, `quant_timeseries_bars`, and `fts_catalog` while verifying source registries remain untouched under `ReadOnlyIsolationGuard`, then runs `PRAGMA optimize; VACUUM;`. | | `query_registry_manifests(db_path=None, registry=None)` / `hs-db-build --manifests` | `registry: str \| None` | Queries `registry_manifests` for all compiled schemas/registries, their record counts, `raw_sha256`, and `dag_json_cidv1`. | | `query_fts_catalog(query, doc_type="all", limit=25, db_path=None)` / `hs-db-build --search ` | `query: str`, `doc_type: str`, `limit: int` | Executes a ranked **FTS5 `BM25` full-text search** across `fts_catalog` (searching glossary terms, 1,850+ equations, 388 graph nodes, and 24 tickers in `< 0.6 ms`). | | `query_coordinate_join(aq_int, db_path=None)` / `hs-db-build --coordinate ` | `aq_int: int` (`1..999`, e.g. `137` or `125`) | **Unified Cross-Corpus Coordinate Join:** In a single indexed SQL query, returns every glossary term, bilingual specimen, Knowledge Graph node/edge, `333/666/777` archive equation, and `/quant/` closing-bell bar that locks onto integer coordinate `aq_int`. | | `query_timeseries_bars(symbol=None, start_date=None, end_date=None, min_points=0.0, db_path=None)` / `hs-db-build --timeseries` | `symbol`, `start_date`, `end_date`, `min_points` | Executes indexed range queries over `quant_timeseries_bars` (`WHERE symbol = ? AND date_utc BETWEEN ? AND ? AND contingent_points >= ?`). | | `record_api_telemetry(...)` & `get_api_telemetry_summary(telemetry_db_path=None)` / `hs-db-build --telemetry` | `protocol`, `method`, `endpoint_pattern`, `status_code`, `latency_us`, `isolation_ok` | Writes/reads `api_endpoint_rollups` and the latest 25 rows of `api_audit_ringbuffer` in `api-telemetry.db` (`<= 200` ring-buffer cap). | --- ## 4. Three-Phase Implementation Roadmap (`Phases 1–3`) ### Phase 1: Implement `hyperstitionstud_io.db.sqlite_meta` & `hs-db-build` CLI 1. Create `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/db/__init__.py` and `sqlite_meta.py` implementing: - `build_catalog_sqlite_db(db_path)` & `ensure_catalog_sqlite_db(db_path)` (compiles `registry_manifests`, `glossary_entries`, `kg_nodes`, `kg_edges`, `dossiers`, `archive_equations`, `quant_timeseries_bars`, and the `fts_catalog` FTS5 index while verifying source repositories are never mutated, then runs `PRAGMA optimize; VACUUM;`), - `query_registry_manifests(db_path, registry=None)` (opens `file:...?mode=ro` with `PRAGMA query_only = ON;`), - `query_fts_catalog(query, doc_type="all", limit=25, db_path=None)`, - `query_coordinate_join(aq_int, db_path=None)`, - `query_timeseries_bars(symbol=None, start_date=None, end_date=None, min_points=0.0, db_path=None)`, and - `record_api_telemetry(protocol, method, endpoint_pattern, status_code, latency_us, isolation_ok, telemetry_db_path=None)` + `get_api_telemetry_summary(telemetry_db_path=None)`. 2. Register `hs-db-build = "hyperstitionstud_io.db.sqlite_meta:main"` in `/workspace/hyperstitionstudio-core/pyproject.toml`. ### Phase 2: Wire Automatic SQLite Population into `dispatch_rest_v1` (`mcp/rest.py`) & `dispatch_jsonrpc` (`mcp/server.py`) 1. In `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/rest.py`, wrap `dispatch_rest_v1(method, raw_path, body_bytes)` with high-resolution `time.perf_counter_ns()` timing and a `finally` hook calling `record_api_telemetry(protocol="rest_v1", method=method, endpoint_pattern=normalized_route, status_code=status, latency_us=elapsed_us, isolation_ok=isolation_verified)` so every `/api/v1/*` REST API call automatically populates `api_endpoint_rollups` and `api_audit_ringbuffer` in the SQLite metadata/telemetry database (`api-telemetry.db`). 2. In `/workspace/hyperstitionstudio-core/src/hyperstitionstud_io/mcp/server.py`, wrap `dispatch_jsonrpc(req)` with `time.perf_counter_ns()` timing and a `finally` hook calling `record_api_telemetry(protocol="mcp_jsonrpc", method="POST", endpoint_pattern=rpc_pattern, status_code=status, latency_us=elapsed_us, isolation_ok=isolation_verified)` (e.g. `tools/call:hs_evaluate_aq_and_ingglish`, `resources/read`, `prompts/get`) so every MCP call also populates the SQLite database. 3. Ensure `record_api_telemetry()` writes strictly to a safe writable path (`HYPERSTITION_TELEMETRY_DB_PATH` or `/tmp/hyperstition-api-telemetry.db` fallback when under systemd `ProtectSystem=strict`) and never raises if the filesystem is read-only. 4. Create `/workspace/hyperstitionstudio-core/deploy/logrotate.d/hyperstition-sqlite-meta` (`size 100M` default, `rotate 12`, `compress`, `delaycompress`, configurable via `HYPERSTITION_SQLITE_MAX_MB` / `HYPERSTITION_SQLITE_MAX_BYTES`) with a `prerotate` block calling `python3 -m hyperstitionstud_io.db.sqlite_meta --truncate-quiescent --compress-archive` (`BEGIN EXCLUSIVE` + consistent SQLite snapshot compressed to `.1.gz` + table purge + `PRAGMA wal_checkpoint(TRUNCATE)` + `VACUUM` + `PRAGMA integrity_check == 'ok'`). ### Phase 3: Verification in `tests/test_core_suite.py` 1. Add unit tests in `tests/test_core_suite.py` verifying: - `build_catalog_sqlite_db()` table row counts (`282+` glossary rows, `388` nodes, `1,282` edges, `71+` dossiers, `720` periodic time-series bars), - Sub-millisecond FTS5 `BM25` search via `query_fts_catalog("envideea")`, - Unified coordinate join via `query_coordinate_join(137)`, - Indexed periodic bar range queries via `query_timeseries_bars(symbol="NVDA", min_points=1.0)`, - Executing `/api/v1/*` REST API calls (`dispatch_rest_v1`) and `/mcp` JSON-RPC calls (`dispatch_jsonrpc`) automatically populates `api_endpoint_rollups` and `api_audit_ringbuffer` (`<= 200` ring-buffer cap, `status_2xx`, `isolation_ok == 1`) in the SQLite database while leaving all inactive plan routes (`/api/v1/meta/*`, `hs_query_sqlite_catalog`, `/gallery/`) unexposed, and - Executing `run_logrotate_directive()` / `truncate_telemetry_db_quiescent()` against `/workspace/hyperstitionstudio-core/deploy/logrotate.d/hyperstition-sqlite-meta` verifies the default `100M` (`100 MB`) threshold and quiescently truncates the SQLite database when the threshold is reached (`PRAGMA integrity_check == 'ok'`).