"""Decision ledger: a small SQLite file remembering every keep / reap / protect decision.""" from __future__ import annotations import json import sqlite3 from datetime import datetime, timedelta from pathlib import Path ACTIONS = ("keep", "reap", "downgrade", "protect") _SCHEMA = """ CREATE TABLE IF NOT EXISTS decisions ( guid TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, action TEXT NOT NULL, score INTEGER, size_bytes INTEGER, breakdown TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS executions ( id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, guid TEXT NOT NULL, kind TEXT NOT NULL, title TEXT NOT NULL, action TEXT NOT NULL, arr TEXT, arr_id INTEGER, files TEXT, size_bytes INTEGER, dry_run INTEGER NOT NULL, ok INTEGER NOT NULL, detail TEXT ); CREATE TABLE IF NOT EXISTS cache ( key TEXT PRIMARY KEY, value TEXT NOT NULL, at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS log ( id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, guid TEXT NOT NULL, title TEXT NOT NULL, action TEXT NOT NULL, detail TEXT ); """ class Ledger: def __init__(self, path: str | Path) -> None: self.path = Path(path).expanduser() self.path.parent.mkdir(parents=True, exist_ok=True) self.conn = sqlite3.connect(self.path) self.conn.row_factory = sqlite3.Row self.conn.executescript(_SCHEMA) def close(self) -> None: self.conn.close() def decisions(self) -> dict[str, str]: return {r["guid"]: r["action"] for r in self.conn.execute("SELECT guid, action FROM decisions")} def rows(self, action: str | None = None) -> list[sqlite3.Row]: if action: return list(self.conn.execute("SELECT * FROM decisions WHERE action = ? ORDER BY updated_at DESC", (action,))) return list(self.conn.execute("SELECT * FROM decisions ORDER BY updated_at DESC")) def set( self, guid: str, action: str, *, kind: str, title: str, score: int | None = None, size_bytes: int | None = None, breakdown: dict | None = None, ) -> None: if action not in ACTIONS: raise ValueError(f"unknown action {action!r}") now = datetime.now().isoformat(timespec="seconds") with self.conn: self.conn.execute( """ INSERT INTO decisions (guid, kind, title, action, score, size_bytes, breakdown, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(guid) DO UPDATE SET action=excluded.action, score=excluded.score, size_bytes=excluded.size_bytes, breakdown=excluded.breakdown, updated_at=excluded.updated_at """, (guid, kind, title, action, score, size_bytes, json.dumps(breakdown) if breakdown else None, now, now), ) self.conn.execute( "INSERT INTO log (at, guid, title, action, detail) VALUES (?, ?, ?, ?, ?)", (now, guid, title, action, None), ) def clear(self, guid: str, *, reason: str = "clear") -> None: now = datetime.now().isoformat(timespec="seconds") with self.conn: row = self.conn.execute("SELECT title FROM decisions WHERE guid = ?", (guid,)).fetchone() if row is None: return self.conn.execute("DELETE FROM decisions WHERE guid = ?", (guid,)) self.conn.execute( "INSERT INTO log (at, guid, title, action, detail) VALUES (?, ?, ?, ?, ?)", (now, guid, row["title"], reason, None), ) # ---- executions ------------------------------------------------------------- def record_execution( self, *, guid: str, kind: str, title: str, action: str, arr: str | None, arr_id: int | None, files: list[dict], size_bytes: int, dry_run: bool, ok: bool, detail: str | None, ) -> None: now = datetime.now().isoformat(timespec="seconds") with self.conn: self.conn.execute( """ INSERT INTO executions (at, guid, kind, title, action, arr, arr_id, files, size_bytes, dry_run, ok, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (now, guid, kind, title, action, arr, arr_id, json.dumps(files), size_bytes, int(dry_run), int(ok), detail), ) def executions(self, *, include_dry_runs: bool = False) -> list[sqlite3.Row]: sql = "SELECT * FROM executions" + ("" if include_dry_runs else " WHERE dry_run = 0") + " ORDER BY id DESC" return list(self.conn.execute(sql)) # ---- enrichment cache --------------------------------------------------------- def cache_get(self, key: str, ttl_hours: float) -> dict | None: row = self.conn.execute("SELECT value, at FROM cache WHERE key = ?", (key,)).fetchone() if row is None: return None if datetime.now() - datetime.fromisoformat(row["at"]) > timedelta(hours=ttl_hours): return None return json.loads(row["value"]) def cache_set(self, key: str, value: dict) -> None: with self.conn: self.conn.execute( "INSERT OR REPLACE INTO cache (key, value, at) VALUES (?, ?, ?)", (key, json.dumps(value), datetime.now().isoformat(timespec="seconds")), )