# Author: Sandeep Belgavi """Offline evidence retrieval with namespace, revision and expiry filters.""" import json import re import sqlite3 import tempfile from pathlib import Path class EvidenceStore: def __init__(self, path): self.db = sqlite3.connect(path) self.db.row_factory = sqlite3.Row self.db.execute('CREATE TABLE IF NOT EXISTS evidence(tenant TEXT,id TEXT,revision TEXT,kind TEXT,body TEXT,source TEXT,expires INTEGER,PRIMARY KEY(tenant,id))') def put(self, tenant, item_id, revision, kind, body, source, expires): if kind not in {'working', 'incident', 'runbook'} or not all(isinstance(x, str) and x for x in (tenant, item_id, revision, body, source)): raise ValueError('evidence contract') if type(expires) is not int or expires < 0: raise ValueError('expiry') with self.db: self.db.execute('INSERT OR REPLACE INTO evidence VALUES (?,?,?,?,?,?,?)', (tenant, item_id, revision, kind, body, source, expires)) def retrieve(self, tenant, revision, query, now, scorer, limit=3): if not tenant or not revision or type(limit) is not int or not 1 <= limit <= 10: raise ValueError('retrieval boundary') rows = self.db.execute('SELECT * FROM evidence WHERE tenant=? AND revision=? AND expires>?', (tenant, revision, now)).fetchall() ranked = [] for row in rows: score = scorer.score(query, row['body']) if score > 0: ranked.append((score, row['id'], dict(row))) ranked.sort(key=lambda item: (-item[0], item[1])) return [{'id': r['id'], 'kind': r['kind'], 'text': r['body'], 'citation': r['source'], 'revision': r['revision']} for _, _, r in ranked[:limit]] def forget(self, tenant, item_id): with self.db: self.db.execute('DELETE FROM evidence WHERE tenant=? AND id=?', (tenant, item_id)) def close(self): self.db.close() class TokenScorer: """Deterministic lexical seam, not embeddings or an LLM.""" def score(self, query, body): tokens = lambda text: set(re.findall(r'[a-z0-9]+', text.lower())) return len(tokens(query) & tokens(body)) def demo(): with tempfile.TemporaryDirectory() as folder: store = EvidenceStore(Path(folder) / 'memory.db') store.put('team-a', 'r1', 'v1', 'runbook', 'Queue backlog requires checking worker health', 'runbook://queue/v1', 200) store.put('team-a', 'old', 'v1', 'incident', 'Queue backlog old finding', 'incident://old', 99) store.put('team-b', 'private', 'v1', 'working', 'Queue backlog confidential', 'private://b', 200) hits = store.retrieve('team-a', 'v1', 'queue backlog', 100, TokenScorer()) result = {'citations': [hit['citation'] for hit in hits], 'hits': len(hits)} store.close() return result if __name__ == '__main__': print(json.dumps(demo(), sort_keys=True))