Files
ThothII/harness/nsp/evidence/model.py
T
marcopan 796a39d893 feat(harness): port vectorstore dual-key + reader RPC (D11, §5.4)
Ports vectorstore/{rest_client,rest_writer,store,reader,embeddings,records},
evidence/model (leaf dep of records), and cli/_guards (require_vector_write_allowed
workstation write-guard). Renamed psdwp3->nsp, verbatim.

VectorRestClient gains an api_key property so reader/writer clients carry their
distinct keys visibly (spec D11: vector_reader / vector_writer on the same endpoint).

scripts/create_vector_reader_rpc.sql is NEW: the reader RPCs (search_similar,
list_tables) lived server-side in Supabase and were never versioned. Authored now
mirroring the writer allowlist pattern (table allowlist, security definer, revoke
from anon/authenticated, grant to vector_reader only). Writer RPC ported verbatim.

L1: test_vector_dual_key (7 tests) pins the dual-key construction + the workstation
write-guard (exit 4 without writer key).
2026-06-26 22:55:40 +02:00

63 lines
2.2 KiB
Python

from pathlib import Path
from typing import Literal
import yaml
from pydantic import BaseModel, ValidationError
class EvidenceError(Exception):
pass
class EvidenceDoc(BaseModel):
id: str
title: str
# tier e status sono opzionali: la sola presenza di un documento basta a
# vettorizzarlo, quindi l'autore ETL non e' obbligato a compilarli.
tier: Literal["structural", "concept"] = "structural"
status: Literal["auto", "draft", "reviewed"] = "reviewed"
sources: list[str] = []
tables: list[str] = []
concepts: list[str] = []
body: str = ""
path: Path | None = None # valorizzato al load, escluso dal dump
@classmethod
def parse(cls, text: str, path: Path | None = None) -> "EvidenceDoc":
if not text.startswith("---\n"):
raise EvidenceError(f"frontmatter mancante in {path or '<testo>'}")
try:
_, fm, body = text.split("---\n", 2)
except ValueError as e:
raise EvidenceError(f"frontmatter malformato in {path or '<testo>'}") from e
meta = yaml.safe_load(fm)
if not isinstance(meta, dict):
raise EvidenceError(f"frontmatter non valido in {path or '<testo>'}")
try:
return cls.model_validate({**meta, "body": body.strip("\n"), "path": path})
except ValidationError as e:
raise EvidenceError(f"evidence non valida in {path or '<testo>'}:\n{e}") from e
def dump(self) -> str:
meta = self.model_dump(exclude={"body", "path"}, mode="json")
fm = yaml.safe_dump(meta, sort_keys=False, allow_unicode=True)
return f"---\n{fm}---\n{self.body}\n"
def save(self, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(self.dump())
self.path = path
def load_evidence_dir(root: Path) -> list[EvidenceDoc]:
"""Carica ricorsivamente tutte le evidence sotto `root`, preservando la
gerarchia per dominio. I file README (di sola navigazione) sono ignorati."""
docs: list[EvidenceDoc] = []
if not root.is_dir():
return docs
for f in sorted(root.rglob("*.md")):
if f.name.upper().startswith("README"):
continue
docs.append(EvidenceDoc.parse(f.read_text(), path=f))
return docs