#!/usr/bin/env python3 """Weekly review: аудит за 7 дней, eval, бэкапы → Matrix.""" import json import os import subprocess import sys import time import urllib.request ROOM = "!puEdcZCc87kKoCm3mX5bbjrTS-Skv2XCZg7JJBKOMw0" HS = "http://192.168.1.155:8008" def pg(sql): env = dict(os.environ, PGPASSWORD=open("/root/.pg-superuser-pass").read().strip()) r = subprocess.run(["psql", "-w", "-h", "192.168.1.151", "-U", "postgres", "-d", "hermes", "-t", "-A", "-F", "|", "-c", sql], capture_output=True, text=True, timeout=20, env=env) return [ln.split("|") for ln in (r.stdout or "").strip().splitlines() if ln] def send(text, dry=False): if dry: print(text) return 0 tok = open("/root/.matrix-admin-token").read().strip() txn = "weekly-%d" % int(time.time() * 1000) body = json.dumps({"msgtype": "m.text", "body": text}).encode() url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s?access_token=%s" % (HS, ROOM, txn, tok) r = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"}, method="PUT") with urllib.request.urlopen(r, timeout=20) as resp: return resp.status def main(): dry = "--print" in sys.argv rows = pg("select count(*), count(*) filter (where not ok), coalesce(round(avg(ms)),0) " "from tool_audit where ts > now() - interval '7 days';") total, errs, avg = (rows[0] + ["0", "0", "0"])[:3] if rows else ("0", "0", "0") top = pg("select tool,count(*),count(*) filter (where not ok) from tool_audit " "where ts > now() - interval '7 days' group by tool order by count(*) desc limit 5;") eval_summary = "" for p in ("/var/lib/secretary-eval/summary.md",): if os.path.exists(p): eval_summary = open(p, encoding="utf-8").read().strip().splitlines()[-1] lines = ["📅 **Weekly review** — " + time.strftime("%d.%m.%Y"), "• Tool calls: **%s**, ошибок: **%s**, avg: **%s мс**" % (total, errs, avg)] if top: lines.append("• Топ:") for t in top: lines.append(" – %s: %s (ошибок %s)" % (t[0], t[1], t[2])) if eval_summary: lines.append("• Eval: " + eval_summary) r = send("\n".join(lines), dry) if dry: print("dry-run") else: print("sent" if r else "failed") return 0 if __name__ == "__main__": raise SystemExit(main())