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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SQLite interface for paper cache, extraction results, and match outcomes.
|
| 3 |
+
|
| 4 |
+
Schema:
|
| 5 |
+
papers: arXiv metadata + pipeline status + citation metadata
|
| 6 |
+
concepts: extracted concepts per paper (from LLM deconstruction)
|
| 7 |
+
reductions: match results per concept (from compositional matching engine)
|
| 8 |
+
formalism_kb: cached KB entries for fast lookup (mirrors YAML)
|
| 9 |
+
pipeline_runs: audit log of pipeline executions
|
| 10 |
+
|
| 11 |
+
Thread-safe: uses WAL mode. Single-writer by design (pipeline is sequential).
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import sqlite3
|
| 18 |
+
import time
|
| 19 |
+
from dataclasses import dataclass, field
|
| 20 |
+
from datetime import datetime, timezone
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any, Optional
|
| 23 |
+
|
| 24 |
+
# ---------------------------------------------------------------------------
|
| 25 |
+
# Schema
|
| 26 |
+
# ---------------------------------------------------------------------------
|
| 27 |
+
|
| 28 |
+
SCHEMA_SQL = """
|
| 29 |
+
PRAGMA journal_mode=WAL;
|
| 30 |
+
PRAGMA foreign_keys=ON;
|
| 31 |
+
|
| 32 |
+
CREATE TABLE IF NOT EXISTS papers (
|
| 33 |
+
arxiv_id TEXT PRIMARY KEY,
|
| 34 |
+
title TEXT NOT NULL,
|
| 35 |
+
abstract TEXT NOT NULL,
|
| 36 |
+
authors TEXT NOT NULL, -- JSON array of strings
|
| 37 |
+
categories TEXT NOT NULL, -- JSON array of strings
|
| 38 |
+
published TEXT NOT NULL, -- ISO 8601
|
| 39 |
+
updated TEXT NOT NULL, -- ISO 8601
|
| 40 |
+
pdf_url TEXT,
|
| 41 |
+
-- Pipeline status
|
| 42 |
+
status TEXT NOT NULL DEFAULT 'ingested', -- ingested|triaged|extracted|matched|displayed|skipped|error
|
| 43 |
+
triage_passed INTEGER, -- 1 = novelty claim detected, 0 = skipped, NULL = not triaged
|
| 44 |
+
triage_reason TEXT, -- why it passed or was skipped
|
| 45 |
+
ingestion_ts TEXT NOT NULL DEFAULT (datetime('now')),
|
| 46 |
+
extraction_ts TEXT,
|
| 47 |
+
matching_ts TEXT,
|
| 48 |
+
error_message TEXT,
|
| 49 |
+
citation_count INTEGER DEFAULT 0,
|
| 50 |
+
citation_fetched_ts TEXT
|
| 51 |
+
);
|
| 52 |
+
|
| 53 |
+
CREATE TABLE IF NOT EXISTS concepts (
|
| 54 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 55 |
+
paper_arxiv_id TEXT NOT NULL REFERENCES papers(arxiv_id) ON DELETE CASCADE,
|
| 56 |
+
name TEXT NOT NULL, -- the term the paper uses
|
| 57 |
+
is_claimed_novel INTEGER NOT NULL DEFAULT 0,
|
| 58 |
+
claimed_novelty_text TEXT,
|
| 59 |
+
mathematical_operation TEXT NOT NULL,
|
| 60 |
+
domain TEXT,
|
| 61 |
+
codomain TEXT,
|
| 62 |
+
objective TEXT,
|
| 63 |
+
constraints TEXT, -- JSON array
|
| 64 |
+
canonical_analog TEXT,
|
| 65 |
+
deconstructive_move TEXT,
|
| 66 |
+
confidence TEXT NOT NULL DEFAULT 'low', -- high|medium|low
|
| 67 |
+
confidence_rationale TEXT,
|
| 68 |
+
flags TEXT, -- JSON array
|
| 69 |
+
-- Extraction metadata
|
| 70 |
+
extraction_json TEXT NOT NULL, -- full concept JSON from LLM
|
| 71 |
+
extracted_at TEXT NOT NULL DEFAULT (datetime('now'))
|
| 72 |
+
);
|
| 73 |
+
|
| 74 |
+
CREATE TABLE IF NOT EXISTS reductions (
|
| 75 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 76 |
+
concept_id INTEGER NOT NULL REFERENCES concepts(id) ON DELETE CASCADE,
|
| 77 |
+
paper_arxiv_id TEXT NOT NULL REFERENCES papers(arxiv_id) ON DELETE CASCADE,
|
| 78 |
+
concept_name TEXT NOT NULL,
|
| 79 |
+
result_type TEXT NOT NULL, -- identity|compositional|analogy|unknown|confused
|
| 80 |
+
reduction TEXT NOT NULL, -- e.g., "Kernel CCA ∘ neuralize ∘ predict_in_codomain"
|
| 81 |
+
canonical_analog TEXT,
|
| 82 |
+
genuine_delta TEXT,
|
| 83 |
+
micro TEXT,
|
| 84 |
+
meso TEXT,
|
| 85 |
+
macro TEXT,
|
| 86 |
+
confidence REAL NOT NULL DEFAULT 0.0,
|
| 87 |
+
display TEXT NOT NULL, -- sous rature formatted string
|
| 88 |
+
notes TEXT, -- JSON array
|
| 89 |
+
match_json TEXT NOT NULL, -- full MatchResult as JSON
|
| 90 |
+
matched_at TEXT NOT NULL DEFAULT (datetime('now'))
|
| 91 |
+
);
|
| 92 |
+
|
| 93 |
+
CREATE TABLE IF NOT EXISTS formalism_kb (
|
| 94 |
+
id TEXT PRIMARY KEY, -- matches formalism.id in YAML
|
| 95 |
+
name TEXT NOT NULL,
|
| 96 |
+
signature_json TEXT NOT NULL, -- JSON: {operation, domain, codomain, objective_family}
|
| 97 |
+
meso_type TEXT,
|
| 98 |
+
macro_type TEXT,
|
| 99 |
+
canonical_reference TEXT,
|
| 100 |
+
researchor_artifact_id TEXT,
|
| 101 |
+
researchor_mental_model_id TEXT,
|
| 102 |
+
status TEXT NOT NULL DEFAULT 'seed',
|
| 103 |
+
cached_at TEXT NOT NULL DEFAULT (datetime('now'))
|
| 104 |
+
);
|
| 105 |
+
|
| 106 |
+
CREATE TABLE IF NOT EXISTS pipeline_runs (
|
| 107 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 108 |
+
run_type TEXT NOT NULL, -- daily|single|retroactive|manual
|
| 109 |
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
| 110 |
+
finished_at TEXT,
|
| 111 |
+
papers_ingested INTEGER DEFAULT 0,
|
| 112 |
+
papers_triaged INTEGER DEFAULT 0,
|
| 113 |
+
papers_extracted INTEGER DEFAULT 0,
|
| 114 |
+
papers_matched INTEGER DEFAULT 0,
|
| 115 |
+
papers_error INTEGER DEFAULT 0,
|
| 116 |
+
status TEXT NOT NULL DEFAULT 'running', -- running|completed|failed
|
| 117 |
+
error_message TEXT,
|
| 118 |
+
config_json TEXT -- snapshot of pipeline config at run time
|
| 119 |
+
);
|
| 120 |
+
|
| 121 |
+
CREATE INDEX IF NOT EXISTS idx_papers_status ON papers(status);
|
| 122 |
+
CREATE INDEX IF NOT EXISTS idx_papers_updated ON papers(updated);
|
| 123 |
+
CREATE INDEX IF NOT EXISTS idx_concepts_paper ON concepts(paper_arxiv_id);
|
| 124 |
+
CREATE INDEX IF NOT EXISTS idx_reductions_paper ON reductions(paper_arxiv_id);
|
| 125 |
+
CREATE INDEX IF NOT EXISTS idx_reductions_concept ON reductions(concept_id);
|
| 126 |
+
CREATE INDEX IF NOT EXISTS idx_reductions_type ON reductions(result_type);
|
| 127 |
+
CREATE INDEX IF NOT EXISTS idx_pipeline_runs_started ON pipeline_runs(started_at);
|
| 128 |
+
|
| 129 |
+
-- Migration: add citation columns (safe to run on existing DBs)
|
| 130 |
+
ALTER TABLE papers ADD COLUMN citation_count INTEGER DEFAULT 0;
|
| 131 |
+
ALTER TABLE papers ADD COLUMN citation_fetched_ts TEXT;
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# ---------------------------------------------------------------------------
|
| 136 |
+
# Database wrapper
|
| 137 |
+
# ---------------------------------------------------------------------------
|
| 138 |
+
|
| 139 |
+
@dataclass
|
| 140 |
+
class Database:
|
| 141 |
+
"""SQLite database interface for the Différance Engine pipeline."""
|
| 142 |
+
|
| 143 |
+
path: Path
|
| 144 |
+
_conn: sqlite3.Connection | None = field(default=None, repr=False, init=False)
|
| 145 |
+
|
| 146 |
+
def __post_init__(self):
|
| 147 |
+
self.path = Path(self.path)
|
| 148 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 149 |
+
|
| 150 |
+
def connect(self):
|
| 151 |
+
"""Open connection and ensure schema exists."""
|
| 152 |
+
if self._conn is not None:
|
| 153 |
+
return
|
| 154 |
+
self._conn = sqlite3.connect(str(self.path))
|
| 155 |
+
self._conn.row_factory = sqlite3.Row
|
| 156 |
+
self._conn.executescript(SCHEMA_SQL)
|
| 157 |
+
self._conn.commit()
|
| 158 |
+
|
| 159 |
+
def close(self):
|
| 160 |
+
if self._conn is not None:
|
| 161 |
+
self._conn.close()
|
| 162 |
+
self._conn = None
|
| 163 |
+
|
| 164 |
+
def __enter__(self):
|
| 165 |
+
self.connect()
|
| 166 |
+
return self
|
| 167 |
+
|
| 168 |
+
def __exit__(self, *args):
|
| 169 |
+
self.close()
|
| 170 |
+
|
| 171 |
+
# ---- Papers ----
|
| 172 |
+
|
| 173 |
+
def paper_exists(self, arxiv_id: str) -> bool:
|
| 174 |
+
self.connect()
|
| 175 |
+
row = self._conn.execute("SELECT 1 FROM papers WHERE arxiv_id = ?", (arxiv_id,)).fetchone()
|
| 176 |
+
return row is not None
|
| 177 |
+
|
| 178 |
+
def insert_paper(self, paper: dict) -> bool:
|
| 179 |
+
"""Insert a paper from arXiv API parsed data. Returns True if new."""
|
| 180 |
+
self.connect()
|
| 181 |
+
if self.paper_exists(paper["arxiv_id"]):
|
| 182 |
+
return False
|
| 183 |
+
self._conn.execute(
|
| 184 |
+
"""INSERT INTO papers (arxiv_id, title, abstract, authors, categories,
|
| 185 |
+
published, updated, pdf_url, status)
|
| 186 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ingested')""",
|
| 187 |
+
(
|
| 188 |
+
paper["arxiv_id"],
|
| 189 |
+
paper["title"],
|
| 190 |
+
paper["abstract"],
|
| 191 |
+
json.dumps(paper.get("authors", [])),
|
| 192 |
+
json.dumps(paper.get("categories", [])),
|
| 193 |
+
paper.get("published", ""),
|
| 194 |
+
paper.get("updated", ""),
|
| 195 |
+
paper.get("pdf_url", ""),
|
| 196 |
+
),
|
| 197 |
+
)
|
| 198 |
+
self._conn.commit()
|
| 199 |
+
return True
|
| 200 |
+
|
| 201 |
+
def update_triage(self, arxiv_id: str, passed: bool, reason: str = ""):
|
| 202 |
+
self.connect()
|
| 203 |
+
self._conn.execute(
|
| 204 |
+
"""UPDATE papers SET triage_passed = ?, triage_reason = ?,
|
| 205 |
+
status = CASE WHEN ? THEN 'triaged' ELSE 'skipped' END
|
| 206 |
+
WHERE arxiv_id = ?""",
|
| 207 |
+
(1 if passed else 0, reason, passed, arxiv_id),
|
| 208 |
+
)
|
| 209 |
+
self._conn.commit()
|
| 210 |
+
|
| 211 |
+
def update_status(self, arxiv_id: str, status: str, error: str = ""):
|
| 212 |
+
self.connect()
|
| 213 |
+
ts = datetime.now(timezone.utc).isoformat()
|
| 214 |
+
field = {"extracted": "extraction_ts", "matched": "matching_ts",
|
| 215 |
+
"displayed": "matching_ts"}.get(status, "")
|
| 216 |
+
if field:
|
| 217 |
+
self._conn.execute(
|
| 218 |
+
f"UPDATE papers SET status = ?, {field} = ?, error_message = ? WHERE arxiv_id = ?",
|
| 219 |
+
(status, ts, error, arxiv_id),
|
| 220 |
+
)
|
| 221 |
+
else:
|
| 222 |
+
self._conn.execute(
|
| 223 |
+
"UPDATE papers SET status = ?, error_message = ? WHERE arxiv_id = ?",
|
| 224 |
+
(status, error, arxiv_id),
|
| 225 |
+
)
|
| 226 |
+
self._conn.commit()
|
| 227 |
+
|
| 228 |
+
def update_citation(self, arxiv_id: str, count: int):
|
| 229 |
+
self.connect()
|
| 230 |
+
try:
|
| 231 |
+
self._conn.execute(
|
| 232 |
+
"UPDATE papers SET citation_count = ?, citation_fetched_ts = ? WHERE arxiv_id = ?",
|
| 233 |
+
(count, "now", arxiv_id),
|
| 234 |
+
)
|
| 235 |
+
self._conn.commit()
|
| 236 |
+
except sqlite3.OperationalError:
|
| 237 |
+
# Column might not exist yet
|
| 238 |
+
try:
|
| 239 |
+
self._conn.execute("ALTER TABLE papers ADD COLUMN citation_count INTEGER DEFAULT 0")
|
| 240 |
+
self._conn.execute("ALTER TABLE papers ADD COLUMN citation_fetched_ts TEXT")
|
| 241 |
+
self._conn.execute(
|
| 242 |
+
"UPDATE papers SET citation_count = ?, citation_fetched_ts = ? WHERE arxiv_id = ?",
|
| 243 |
+
(count, "now", arxiv_id),
|
| 244 |
+
)
|
| 245 |
+
self._conn.commit()
|
| 246 |
+
except Exception:
|
| 247 |
+
pass
|
| 248 |
+
|
| 249 |
+
def get_papers_by_status(self, status: str, limit: int = 100) -> list[dict]:
|
| 250 |
+
self.connect()
|
| 251 |
+
rows = self._conn.execute(
|
| 252 |
+
"SELECT * FROM papers WHERE status = ? ORDER BY updated DESC LIMIT ?",
|
| 253 |
+
(status, limit),
|
| 254 |
+
).fetchall()
|
| 255 |
+
return [_row_to_dict(r) for r in rows]
|
| 256 |
+
|
| 257 |
+
def get_papers_needing_extraction(self, limit: int = 10) -> list[dict]:
|
| 258 |
+
self.connect()
|
| 259 |
+
rows = self._conn.execute(
|
| 260 |
+
"SELECT * FROM papers WHERE status = 'triaged' AND triage_passed = 1 ORDER BY updated DESC LIMIT ?",
|
| 261 |
+
(limit,),
|
| 262 |
+
).fetchall()
|
| 263 |
+
return [_row_to_dict(r) for r in rows]
|
| 264 |
+
|
| 265 |
+
def get_paper(self, arxiv_id: str) -> dict | None:
|
| 266 |
+
self.connect()
|
| 267 |
+
row = self._conn.execute("SELECT * FROM papers WHERE arxiv_id = ?", (arxiv_id,)).fetchone()
|
| 268 |
+
return _row_to_dict(row) if row else None
|
| 269 |
+
|
| 270 |
+
def find_paper(self, arxiv_id: str) -> dict | None:
|
| 271 |
+
"""Look up a paper by arXiv ID, trying version-suffix variations.
|
| 272 |
+
|
| 273 |
+
arXiv IDs can be stored with version suffixes (e.g. 2301.07093v1)
|
| 274 |
+
but users may query without them (2301.07093). This tries exact
|
| 275 |
+
match first, then strips/adds version suffixes.
|
| 276 |
+
"""
|
| 277 |
+
# 1. Exact match
|
| 278 |
+
paper = self.get_paper(arxiv_id)
|
| 279 |
+
if paper:
|
| 280 |
+
return paper
|
| 281 |
+
|
| 282 |
+
# 2. User provided no version — try v1, v2, v3
|
| 283 |
+
import re
|
| 284 |
+
if not re.search(r'v\d+$', arxiv_id):
|
| 285 |
+
for v in range(1, 4):
|
| 286 |
+
paper = self.get_paper(f"{arxiv_id}v{v}")
|
| 287 |
+
if paper:
|
| 288 |
+
return paper
|
| 289 |
+
else:
|
| 290 |
+
# 3. User provided version — try stripping it
|
| 291 |
+
base = re.sub(r'v\d+$', '', arxiv_id)
|
| 292 |
+
paper = self.get_paper(base)
|
| 293 |
+
if paper:
|
| 294 |
+
return paper
|
| 295 |
+
|
| 296 |
+
# 4. LIKE prefix match (finds any version of this paper)
|
| 297 |
+
self.connect()
|
| 298 |
+
row = self._conn.execute(
|
| 299 |
+
"SELECT * FROM papers WHERE arxiv_id LIKE ? || '%' LIMIT 1",
|
| 300 |
+
(arxiv_id,),
|
| 301 |
+
).fetchone()
|
| 302 |
+
return _row_to_dict(row) if row else None
|
| 303 |
+
|
| 304 |
+
def count_by_status(self) -> dict[str, int]:
|
| 305 |
+
self.connect()
|
| 306 |
+
rows = self._conn.execute(
|
| 307 |
+
"SELECT status, COUNT(*) as cnt FROM papers GROUP BY status"
|
| 308 |
+
).fetchall()
|
| 309 |
+
return {r["status"]: r["cnt"] for r in rows}
|
| 310 |
+
|
| 311 |
+
# ---- Concepts ----
|
| 312 |
+
|
| 313 |
+
def insert_concept(self, paper_arxiv_id: str, concept: dict):
|
| 314 |
+
self.connect()
|
| 315 |
+
self._conn.execute(
|
| 316 |
+
"""INSERT INTO concepts (paper_arxiv_id, name, is_claimed_novel,
|
| 317 |
+
claimed_novelty_text, mathematical_operation, domain, codomain,
|
| 318 |
+
objective, constraints, canonical_analog, deconstructive_move,
|
| 319 |
+
confidence, confidence_rationale, flags, extraction_json)
|
| 320 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
| 321 |
+
(
|
| 322 |
+
paper_arxiv_id,
|
| 323 |
+
concept.get("name", ""),
|
| 324 |
+
1 if concept.get("is_claimed_novel") else 0,
|
| 325 |
+
concept.get("claimed_novelty_text"),
|
| 326 |
+
concept.get("mathematical_operation", ""),
|
| 327 |
+
concept.get("domain"),
|
| 328 |
+
concept.get("codomain"),
|
| 329 |
+
concept.get("objective"),
|
| 330 |
+
json.dumps(concept.get("constraints", [])),
|
| 331 |
+
concept.get("canonical_analog"),
|
| 332 |
+
concept.get("deconstructive_move"),
|
| 333 |
+
concept.get("confidence", "low"),
|
| 334 |
+
concept.get("confidence_rationale"),
|
| 335 |
+
json.dumps(concept.get("flags", [])),
|
| 336 |
+
json.dumps(concept),
|
| 337 |
+
),
|
| 338 |
+
)
|
| 339 |
+
self._conn.commit()
|
| 340 |
+
return self._conn.execute("SELECT last_insert_rowid()").fetchone()[0]
|
| 341 |
+
|
| 342 |
+
def delete_concepts_for_paper(self, arxiv_id: str):
|
| 343 |
+
self.connect()
|
| 344 |
+
self._conn.execute("DELETE FROM concepts WHERE paper_arxiv_id = ?", (arxiv_id,))
|
| 345 |
+
self._conn.commit()
|
| 346 |
+
|
| 347 |
+
# ---- Reductions ----
|
| 348 |
+
|
| 349 |
+
def insert_reduction(self, concept_id: int, paper_arxiv_id: str, match: dict):
|
| 350 |
+
self.connect()
|
| 351 |
+
self._conn.execute(
|
| 352 |
+
"""INSERT INTO reductions (concept_id, paper_arxiv_id, concept_name,
|
| 353 |
+
result_type, reduction, canonical_analog, genuine_delta, micro,
|
| 354 |
+
meso, macro, confidence, display, notes, match_json)
|
| 355 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
| 356 |
+
(
|
| 357 |
+
concept_id, paper_arxiv_id,
|
| 358 |
+
match.get("concept_name", ""),
|
| 359 |
+
match.get("result_type", ""),
|
| 360 |
+
match.get("reduction", ""),
|
| 361 |
+
match.get("canonical_analog", ""),
|
| 362 |
+
match.get("genuine_delta", ""),
|
| 363 |
+
match.get("micro", ""),
|
| 364 |
+
match.get("meso", ""),
|
| 365 |
+
match.get("macro", ""),
|
| 366 |
+
match.get("confidence", 0.0),
|
| 367 |
+
match.get("display", ""),
|
| 368 |
+
json.dumps(match.get("notes", [])),
|
| 369 |
+
json.dumps(match),
|
| 370 |
+
),
|
| 371 |
+
)
|
| 372 |
+
self._conn.commit()
|
| 373 |
+
|
| 374 |
+
def delete_reductions_for_paper(self, arxiv_id: str):
|
| 375 |
+
self.connect()
|
| 376 |
+
self._conn.execute("DELETE FROM reductions WHERE paper_arxiv_id = ?", (arxiv_id,))
|
| 377 |
+
self._conn.commit()
|
| 378 |
+
|
| 379 |
+
def get_reductions_for_paper(self, arxiv_id: str) -> list[dict]:
|
| 380 |
+
self.connect()
|
| 381 |
+
rows = self._conn.execute(
|
| 382 |
+
"SELECT * FROM reductions WHERE paper_arxiv_id = ? ORDER BY id",
|
| 383 |
+
(arxiv_id,),
|
| 384 |
+
).fetchall()
|
| 385 |
+
return [_row_to_dict(r) for r in rows]
|
| 386 |
+
|
| 387 |
+
def get_displayable_papers(self, limit: int = 50) -> list[dict]:
|
| 388 |
+
"""Papers ready for display: matched results exist."""
|
| 389 |
+
self.connect()
|
| 390 |
+
rows = self._conn.execute(
|
| 391 |
+
"""SELECT p.* FROM papers p
|
| 392 |
+
WHERE p.status = 'matched'
|
| 393 |
+
ORDER BY p.updated DESC LIMIT ?""",
|
| 394 |
+
(limit,),
|
| 395 |
+
).fetchall()
|
| 396 |
+
return [_row_to_dict(r) for r in rows]
|
| 397 |
+
|
| 398 |
+
# ---- Cross-reference indexing ----
|
| 399 |
+
|
| 400 |
+
def get_canonical_analogs(self) -> list[dict]:
|
| 401 |
+
"""All distinct canonical analogs cited, with paper counts."""
|
| 402 |
+
self.connect()
|
| 403 |
+
rows = self._conn.execute(
|
| 404 |
+
"""SELECT canonical_analog, COUNT(*) as paper_count,
|
| 405 |
+
GROUP_CONCAT(DISTINCT paper_arxiv_id) as paper_ids
|
| 406 |
+
FROM reductions
|
| 407 |
+
WHERE canonical_analog IS NOT NULL AND canonical_analog != ''
|
| 408 |
+
GROUP BY canonical_analog
|
| 409 |
+
ORDER BY paper_count DESC"""
|
| 410 |
+
).fetchall()
|
| 411 |
+
return [_row_to_dict(r) for r in rows]
|
| 412 |
+
|
| 413 |
+
def get_papers_by_analog(self, analog: str, limit: int = 20) -> list[dict]:
|
| 414 |
+
"""Papers that share a canonical analog (fuzzy match)."""
|
| 415 |
+
self.connect()
|
| 416 |
+
rows = self._conn.execute(
|
| 417 |
+
"""SELECT DISTINCT p.* FROM papers p
|
| 418 |
+
JOIN reductions r ON r.paper_arxiv_id = p.arxiv_id
|
| 419 |
+
WHERE r.canonical_analog LIKE ?
|
| 420 |
+
ORDER BY p.updated DESC LIMIT ?""",
|
| 421 |
+
(f"%{analog}%", limit),
|
| 422 |
+
).fetchall()
|
| 423 |
+
return [_row_to_dict(r) for r in rows]
|
| 424 |
+
|
| 425 |
+
def get_papers_by_move(self, move: str, limit: int = 20) -> list[dict]:
|
| 426 |
+
"""Papers whose concepts use a specific deconstructive move."""
|
| 427 |
+
self.connect()
|
| 428 |
+
rows = self._conn.execute(
|
| 429 |
+
"""SELECT DISTINCT p.*, c.deconstructive_move, c.name as concept_name
|
| 430 |
+
FROM papers p
|
| 431 |
+
JOIN concepts c ON c.paper_arxiv_id = p.arxiv_id
|
| 432 |
+
WHERE c.deconstructive_move = ?
|
| 433 |
+
ORDER BY p.updated DESC LIMIT ?""",
|
| 434 |
+
(move, limit),
|
| 435 |
+
).fetchall()
|
| 436 |
+
return [_row_to_dict(r) for r in rows]
|
| 437 |
+
|
| 438 |
+
def get_move_counts(self) -> list[dict]:
|
| 439 |
+
"""Count of each deconstructive move across all concepts."""
|
| 440 |
+
self.connect()
|
| 441 |
+
rows = self._conn.execute(
|
| 442 |
+
"""SELECT deconstructive_move, COUNT(*) as cnt
|
| 443 |
+
FROM concepts
|
| 444 |
+
WHERE deconstructive_move IS NOT NULL
|
| 445 |
+
GROUP BY deconstructive_move
|
| 446 |
+
ORDER BY cnt DESC"""
|
| 447 |
+
).fetchall()
|
| 448 |
+
return [_row_to_dict(r) for r in rows]
|
| 449 |
+
|
| 450 |
+
def get_papers_with_unknown(self, limit: int = 100) -> list[dict]:
|
| 451 |
+
"""Papers with at least one UNKNOWN reduction (retroactive queue)."""
|
| 452 |
+
self.connect()
|
| 453 |
+
rows = self._conn.execute(
|
| 454 |
+
"""SELECT DISTINCT p.* FROM papers p
|
| 455 |
+
JOIN reductions r ON r.paper_arxiv_id = p.arxiv_id
|
| 456 |
+
WHERE r.result_type = 'unknown'
|
| 457 |
+
ORDER BY p.updated DESC LIMIT ?""",
|
| 458 |
+
(limit,),
|
| 459 |
+
).fetchall()
|
| 460 |
+
return [_row_to_dict(r) for r in rows]
|
| 461 |
+
|
| 462 |
+
# ---- KB cache ----
|
| 463 |
+
|
| 464 |
+
def sync_kb_cache(self, formalisms: list[dict]):
|
| 465 |
+
"""Sync the cached KB table from the current formalisms list."""
|
| 466 |
+
self.connect()
|
| 467 |
+
self._conn.execute("DELETE FROM formalism_kb")
|
| 468 |
+
for fm in formalisms:
|
| 469 |
+
self._conn.execute(
|
| 470 |
+
"""INSERT OR REPLACE INTO formalism_kb
|
| 471 |
+
(id, name, signature_json, meso_type, macro_type,
|
| 472 |
+
canonical_reference, researchor_artifact_id,
|
| 473 |
+
researchor_mental_model_id, status)
|
| 474 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
| 475 |
+
(
|
| 476 |
+
fm["id"],
|
| 477 |
+
fm["name"],
|
| 478 |
+
json.dumps(fm.get("signature", {})),
|
| 479 |
+
fm.get("meso_type"),
|
| 480 |
+
fm.get("macro_type"),
|
| 481 |
+
fm.get("canonical_reference"),
|
| 482 |
+
fm.get("researchor_artifact_id"),
|
| 483 |
+
fm.get("researchor_mental_model_id"),
|
| 484 |
+
fm.get("status", "seed"),
|
| 485 |
+
),
|
| 486 |
+
)
|
| 487 |
+
self._conn.commit()
|
| 488 |
+
|
| 489 |
+
# ---- Pipeline runs ----
|
| 490 |
+
|
| 491 |
+
def start_run(self, run_type: str, config: dict | None = None) -> int:
|
| 492 |
+
self.connect()
|
| 493 |
+
cur = self._conn.execute(
|
| 494 |
+
"INSERT INTO pipeline_runs (run_type, config_json) VALUES (?, ?)",
|
| 495 |
+
(run_type, json.dumps(config) if config else "{}"),
|
| 496 |
+
)
|
| 497 |
+
self._conn.commit()
|
| 498 |
+
return cur.lastrowid
|
| 499 |
+
|
| 500 |
+
def finish_run(self, run_id: int, counts: dict, error: str = ""):
|
| 501 |
+
self.connect()
|
| 502 |
+
status = "failed" if error else "completed"
|
| 503 |
+
self._conn.execute(
|
| 504 |
+
"""UPDATE pipeline_runs SET finished_at = ?, papers_ingested = ?,
|
| 505 |
+
papers_triaged = ?, papers_extracted = ?, papers_matched = ?,
|
| 506 |
+
papers_error = ?, status = ?, error_message = ?
|
| 507 |
+
WHERE id = ?""",
|
| 508 |
+
(
|
| 509 |
+
datetime.now(timezone.utc).isoformat(),
|
| 510 |
+
counts.get("ingested", 0),
|
| 511 |
+
counts.get("triaged", 0),
|
| 512 |
+
counts.get("extracted", 0),
|
| 513 |
+
counts.get("matched", 0),
|
| 514 |
+
counts.get("errors", 0),
|
| 515 |
+
status,
|
| 516 |
+
error,
|
| 517 |
+
run_id,
|
| 518 |
+
),
|
| 519 |
+
)
|
| 520 |
+
self._conn.commit()
|
| 521 |
+
|
| 522 |
+
def recent_runs(self, limit: int = 10) -> list[dict]:
|
| 523 |
+
self.connect()
|
| 524 |
+
rows = self._conn.execute(
|
| 525 |
+
"SELECT * FROM pipeline_runs ORDER BY started_at DESC LIMIT ?",
|
| 526 |
+
(limit,),
|
| 527 |
+
).fetchall()
|
| 528 |
+
return [_row_to_dict(r) for r in rows]
|
| 529 |
+
|
| 530 |
+
# ---- Stats ----
|
| 531 |
+
|
| 532 |
+
def stats(self) -> dict:
|
| 533 |
+
self.connect()
|
| 534 |
+
counts = self.count_by_status()
|
| 535 |
+
total = sum(counts.values())
|
| 536 |
+
|
| 537 |
+
# Reduction type breakdown
|
| 538 |
+
red_rows = self._conn.execute(
|
| 539 |
+
"SELECT result_type, COUNT(*) as cnt FROM reductions GROUP BY result_type"
|
| 540 |
+
).fetchall()
|
| 541 |
+
reduction_counts = {r["result_type"]: r["cnt"] for r in red_rows}
|
| 542 |
+
|
| 543 |
+
# Top deconstructive moves
|
| 544 |
+
move_rows = self._conn.execute(
|
| 545 |
+
"SELECT deconstructive_move, COUNT(*) as cnt FROM concepts WHERE deconstructive_move IS NOT NULL GROUP BY deconstructive_move ORDER BY cnt DESC LIMIT 5"
|
| 546 |
+
).fetchall()
|
| 547 |
+
|
| 548 |
+
return {
|
| 549 |
+
"total_papers": total,
|
| 550 |
+
"by_status": counts,
|
| 551 |
+
"total_concepts": sum(
|
| 552 |
+
r["cnt"] for r in self._conn.execute("SELECT COUNT(*) as cnt FROM concepts").fetchall()
|
| 553 |
+
),
|
| 554 |
+
"total_reductions": sum(reduction_counts.values()),
|
| 555 |
+
"reductions_by_type": reduction_counts,
|
| 556 |
+
"reduction_rate": (
|
| 557 |
+
(reduction_counts.get("identity", 0) + reduction_counts.get("compositional", 0))
|
| 558 |
+
/ max(sum(reduction_counts.values()), 1)
|
| 559 |
+
),
|
| 560 |
+
"top_moves": [{"move": r["deconstructive_move"], "count": r["cnt"]} for r in move_rows],
|
| 561 |
+
"recent_runs": self.recent_runs(3),
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
# ---------------------------------------------------------------------------
|
| 566 |
+
# Helpers
|
| 567 |
+
# ---------------------------------------------------------------------------
|
| 568 |
+
|
| 569 |
+
def _row_to_dict(row: sqlite3.Row | None) -> dict | None:
|
| 570 |
+
if row is None:
|
| 571 |
+
return None
|
| 572 |
+
d = dict(row)
|
| 573 |
+
# Deserialize JSON fields
|
| 574 |
+
for field in ("authors", "categories", "constraints", "flags", "notes"):
|
| 575 |
+
if field in d and isinstance(d[field], str):
|
| 576 |
+
try:
|
| 577 |
+
d[field] = json.loads(d[field])
|
| 578 |
+
except (json.JSONDecodeError, TypeError):
|
| 579 |
+
pass
|
| 580 |
+
return d
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
# ---------------------------------------------------------------------------
|
| 584 |
+
# Convenience
|
| 585 |
+
# ---------------------------------------------------------------------------
|
| 586 |
+
|
| 587 |
+
def get_db(path: Path | str | None = None) -> Database:
|
| 588 |
+
"""Get a Database instance for the default data directory."""
|
| 589 |
+
if path is None:
|
| 590 |
+
path = Path(__file__).resolve().parent.parent / "data" / "papers.db"
|
| 591 |
+
return Database(Path(path))
|