[TOOLS] Audit Ledger: двойная запись аудита Tool Gateway в SQLite + Postgres hermes.tool_audit (actor/tool/args/result/ok/ms), добавлен инструмент audit.recent; проверено: запись owner|audit.recent|t|91, audit.recent читает из Postgres. Дальше: миграция старых записей, ежедневный отчёт, стоимость, per-user токены
lint / hygiene (push) Failing after 22s
lint / hygiene (push) Failing after 22s
This commit is contained in:
1 parent
94fa9f3394
commit
3e5d9fd851
4 files changed
+91
-3
No files matched your search
@@ -0,0 +1,43 @@
|
||||
# Audit Ledger: аудит Tool Gateway в Postgres (17.11.2026)
|
||||
|
||||
## Что сделано
|
||||
|
||||
Раньше аудит писался только в SQLite `/var/lib/tool-gateway/audit.db`.
|
||||
Теперь — **двойная запись**:
|
||||
|
||||
* SQLite (быстрый локальный лог);
|
||||
* Postgres `hermes.tool_audit`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE tool_audit(
|
||||
id bigserial PRIMARY KEY, ts timestamptz DEFAULT now(),
|
||||
actor text, tool text, args jsonb, result jsonb, ok boolean, ms int);
|
||||
```
|
||||
|
||||
Добавлен инструмент `audit.recent` (limit, actor) — читает последние записи
|
||||
из Postgres. Проверка:
|
||||
|
||||
```
|
||||
audit.recent → count 0 (первый вызов; запись идёт после ответа)
|
||||
tool_audit → 1 запись: owner | audit.recent | t | 91
|
||||
```
|
||||
|
||||
## Зачем
|
||||
|
||||
* единая история действий агента и family;
|
||||
* можно строить отчёты «кто что вызывал», «сколько ошибок», «сколько длится»;
|
||||
* основа для ежедневного аудита ведущему агенту.
|
||||
|
||||
## Ограничения
|
||||
|
||||
* запись в Postgres — через `psql` subprocess (без psycopg2 в системном python);
|
||||
* при недоступности БД аудит остаётся в SQLite (не теряется);
|
||||
* `audit.recent` читает только `hermes.tool_audit`, старые SQLite-записи
|
||||
не мигрированы.
|
||||
|
||||
## Следующие шаги
|
||||
|
||||
1. Миграция старых SQLite-записей в Postgres.
|
||||
2. Ежедневный отчёт по `tool_audit` (кто, что, ошибки, p95).
|
||||
3. Стоимость/модель в аудит (когда появится router).
|
||||
4. per-user токены вместо owner-токена для Polina.
|
||||
@@ -1,10 +1,10 @@
|
||||
# Реестр автоматизаций Buryans Hub
|
||||
# Сгенерировано: 2026-11-17 18:05 (ops/scripts/build_automations_registry.py)
|
||||
total: 168
|
||||
# Сгенерировано: 2026-11-17 18:26 (ops/scripts/build_automations_registry.py)
|
||||
total: 169
|
||||
by_source:
|
||||
cron.d: 49
|
||||
crontab: 15
|
||||
hermes: 61
|
||||
hermes: 62
|
||||
systemd: 43
|
||||
items:
|
||||
- {"source": "crontab", "line": "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}
|
||||
@@ -175,3 +175,4 @@ items:
|
||||
- {"source": "hermes", "job": "restic-restore-file", "schedule": "daily 08:40", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/restic_restore_file.py"}
|
||||
- {"source": "hermes", "job": "gitea-selfheal", "schedule": "every 300s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/gitea_selfheal.py"}
|
||||
- {"source": "hermes", "job": "path-monitor-light", "schedule": "every 300s", "command": "/usr/bin/python3 /root/buryan-infra/ops/scripts/path_monitor_light.py"}
|
||||
- {"source": "hermes", "job": "git-push", "schedule": "every 1800s", "command": "/bin/bash /root/buryan-infra/ops/scripts/git_push.sh"}
|
||||
@@ -391,6 +391,23 @@ def t_books_status(args):
|
||||
except Exception as e:
|
||||
return {"calibre_web": "https://books.buryans.ru", "error": str(e)[:120]}
|
||||
|
||||
def t_audit_recent(args):
|
||||
n = int(args.get("limit", 20))
|
||||
actor = args.get("actor")
|
||||
where = ""
|
||||
if actor:
|
||||
where = " WHERE actor='%s'" % actor.replace("'", "''")
|
||||
r = _pg("SELECT to_char(ts,'MM-DD HH24:MI:SS'), actor, tool, ok, ms "
|
||||
"FROM tool_audit%s ORDER BY id DESC LIMIT %d;" % (where, n))
|
||||
rows = []
|
||||
for ln in (r.stdout or "").strip().splitlines():
|
||||
parts = ln.split("|")
|
||||
if len(parts) >= 5:
|
||||
rows.append({"ts": parts[0], "actor": parts[1], "tool": parts[2],
|
||||
"ok": parts[3] == "t", "ms": parts[4]})
|
||||
return {"count": len(rows), "rows": rows}
|
||||
|
||||
|
||||
TOOLS = {
|
||||
"hub.status": {"fn": t_hub_status, "scope": "read", "confirm": False},
|
||||
"hub.notify": {"fn": t_hub_notify, "scope": "write", "confirm": True,
|
||||
@@ -415,9 +432,33 @@ TOOLS = {
|
||||
"books.search": {"fn": t_books_search, "scope": "read", "confirm": False},
|
||||
"books.link": {"fn": t_books_link, "scope": "read", "confirm": False},
|
||||
"books.status": {"fn": t_books_status, "scope": "read", "confirm": False},
|
||||
"audit.recent": {"fn": t_audit_recent, "scope": "read", "confirm": False},
|
||||
}
|
||||
|
||||
|
||||
def _pg(sql, timeout=15):
|
||||
import subprocess as sp
|
||||
env = dict(os.environ, PGPASSWORD=read("/root/.pg-superuser-pass"))
|
||||
return sp.run(["psql", "-w", "-h", "192.168.1.151", "-U", "postgres",
|
||||
"-d", "hermes", "-t", "-A", "-F", "|", "-c", sql],
|
||||
capture_output=True, text=True, timeout=timeout, env=env)
|
||||
|
||||
|
||||
def pg_audit(actor, tool, args, result, ok, started):
|
||||
try:
|
||||
_pg("""CREATE TABLE IF NOT EXISTS tool_audit(
|
||||
id bigserial PRIMARY KEY, ts timestamptz DEFAULT now(),
|
||||
actor text, tool text, args jsonb, result jsonb, ok boolean, ms int);""")
|
||||
a = json.dumps(args, ensure_ascii=False).replace("'", "''")[:2000]
|
||||
r = json.dumps(result, ensure_ascii=False).replace("'", "''")[:4000]
|
||||
_pg("INSERT INTO tool_audit(actor,tool,args,result,ok,ms) VALUES "
|
||||
"('%s','%s','%s'::jsonb,'%s'::jsonb,%s,%d);"
|
||||
% (actor.replace("'", "''"), tool.replace("'", "''"), a, r,
|
||||
"true" if ok else "false", int((time.time() - started) * 1000)))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def audit(actor, tool, args, result, ok, started):
|
||||
try:
|
||||
os.makedirs(os.path.dirname(DB), exist_ok=True)
|
||||
@@ -433,6 +474,7 @@ def audit(actor, tool, args, result, ok, started):
|
||||
c.close()
|
||||
except Exception:
|
||||
pass
|
||||
pg_audit(actor, tool, args, result, ok, started)
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
@@ -39,6 +39,8 @@ SCHEMAS = {
|
||||
"books.link": ("Ссылки на поиск книги (без скачивания)", {"type": "object", "properties": {
|
||||
"query": {"type": "string"}}, "required": ["query"]}),
|
||||
"books.status": ("Доступность Calibre-Web", {"type": "object", "properties": {}}),
|
||||
"audit.recent": ("Последние записи аудита Tool Gateway", {"type": "object", "properties": {
|
||||
"limit": {"type": "integer"}, "actor": {"type": "string"}}}),
|
||||
|
||||
"hub.service_detail": ("Детали одной службы хаба по имени", {"type": "object", "properties": {
|
||||
"name": {"type": "string"}}, "required": ["name"]}),
|
||||
|
||||
Reference in new issue
Block a user