File size: 2,012 Bytes
07c2907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""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,))]