StatAgent / statagent /audit.py
mnoorchenar's picture
StatAgent code mirror
07c2907 verified
Raw History Blame Contribute Delete
2.01 kB
"""Append-only SQLite audit log (who/what/when + data hash) and the human-approval queue."""
import hashlib, json, os, sqlite3, time
from pathlib import Path
DB = Path(os.environ.get("STATAGENT_DB", Path(__file__).resolve().parent.parent / "audit.db"))
def _c():
c = sqlite3.connect(DB)
c.row_factory = sqlite3.Row
c.execute("CREATE TABLE IF NOT EXISTS audit(id INTEGER PRIMARY KEY, ts REAL, session TEXT, event TEXT, detail TEXT, data_hash TEXT)")
c.execute("CREATE TABLE IF NOT EXISTS proposals(id INTEGER PRIMARY KEY, ts REAL, session TEXT, title TEXT, body TEXT, status TEXT DEFAULT 'pending', decided_ts REAL)")
return c
def log(session, event, detail, data_hash=None):
with _c() as c:
c.execute("INSERT INTO audit(ts,session,event,detail,data_hash) VALUES(?,?,?,?,?)",
(time.time(), session, event, json.dumps(detail, default=str)[:4000], data_hash))
def sha(obj):
return hashlib.sha256(json.dumps(obj, sort_keys=True, default=str).encode()).hexdigest()[:16]
def propose(session, title, body):
with _c() as c:
cur = c.execute("INSERT INTO proposals(ts,session,title,body) VALUES(?,?,?,?)", (time.time(), session, title, body))
pid = cur.lastrowid
log(session, "proposal_created", {"id": pid, "title": title})
return pid
def decide(pid, approve, session="reviewer"):
with _c() as c:
c.execute("UPDATE proposals SET status=?, decided_ts=? WHERE id=? AND status='pending'",
("approved" if approve else "rejected", time.time(), pid))
log(session, "proposal_approved" if approve else "proposal_rejected", {"id": pid})
def proposals(status=None):
with _c() as c:
q = "SELECT * FROM proposals" + (" WHERE status=?" if status else "") + " ORDER BY id DESC"
return [dict(r) for r in c.execute(q, (status,) if status else ())]
def entries(n=100):
with _c() as c:
return [dict(r) for r in c.execute("SELECT * FROM audit ORDER BY id DESC LIMIT ?", (n,))]