From 386c5f136a0fa14c300ddb6d9559a3dc0c6ab67c Mon Sep 17 00:00:00 2001 From: Roman Buryan Date: Wed, 18 Nov 2026 11:55:17 +0300 Subject: [PATCH] =?UTF-8?q?[P0]=20Privacy-gate,=20approvals=20journal+limi?= =?UTF-8?q?ts,=20heavy-job=20guard/=D1=80=D0=B0=D1=81=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5,=20weekly=20review,=20incident=20templ?= =?UTF-8?q?ate,=20ADR-008=20=D1=80=D0=BE=D0=BB=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...R-008-ROLES-HUBCORE-HERMES-OPENCLAW-N8N.md | 40 +++++++++++++ ops/policies/APPROVALS.md | 36 +++++++++++ ops/policies/PRIVACY-GATE.md | 41 +++++++++++++ ops/reliability/HEAVY-JOBS.md | 35 +++++++++++ ops/scripts/heavy_guard.sh | 12 ++++ ops/scripts/weekly_review.py | 59 +++++++++++++++++++ ops/templates/INCIDENT-POSTMORTEM.md | 30 ++++++++++ ops/tools/gateway.py | 55 ++++++++++++++++- 8 files changed, 306 insertions(+), 2 deletions(-) create mode 100644 ops/adr/ADR-008-ROLES-HUBCORE-HERMES-OPENCLAW-N8N.md create mode 100644 ops/policies/APPROVALS.md create mode 100644 ops/policies/PRIVACY-GATE.md create mode 100644 ops/reliability/HEAVY-JOBS.md create mode 100755 ops/scripts/heavy_guard.sh create mode 100755 ops/scripts/weekly_review.py create mode 100644 ops/templates/INCIDENT-POSTMORTEM.md diff --git a/ops/adr/ADR-008-ROLES-HUBCORE-HERMES-OPENCLAW-N8N.md b/ops/adr/ADR-008-ROLES-HUBCORE-HERMES-OPENCLAW-N8N.md new file mode 100644 index 0000000..416eea2 --- /dev/null +++ b/ops/adr/ADR-008-ROLES-HUBCORE-HERMES-OPENCLAW-N8N.md @@ -0,0 +1,40 @@ +# ADR-008: роли hub-core, Hermes, OpenClaw, n8n + +Статус: accepted · 18.11.2026 + +## Контекст + +Аудит показал пересечение ролей: hub-core, Hermes и OpenClaw дублируют self-heal +и агентную логику; n8n не подтверждён в досье. Нужны границы, чтобы не получить +«второй мозг» и рассинхрон. + +## Решение + +| Компонент | Роль | Можно | Нельзя | +|---|---|---|---| +| **hub-core** (:9120) | политика, статус, self-heal API, граф сущностей | решать «сервис лежит → действие», отдавать `/status.json`, аудит | быть LLM, вести диалог, хранить память | +| **Hermes** | планировщик | запускать job по времени, ретраи, уведомления | думать, выбирать инструменты, менять политику | +| **OpenClaw** | диалог/агент | понимать запрос, вызывать Tool Gateway, объяснять | иметь shell/root, решать «можно ли», писать в обход gateway | +| **n8n** | внешние интеграции | почта, CRM, вебхуки, уведомления | быть в критическом пути BOM/расчёта, менять каталог | + +## Контракты + +- Все действия — через **Tool Gateway** (typed tools, scope, confirm, audit). +- `ha.call`, `hub.notify`, `media.request`, `calendar.create` — только с `confirm=true`, + запись в `tool_approvals` + `tool_audit`. +- Секреты и биометрия — **не через облачную модель**; `photos.*` закрыты privacy-gate. +- Hermes не вызывает OpenClaw для «подумать»; только job. +- n8n читает готовый результат, не влияет на расчёт. + +## Router (решение) + +- DeepSeek — для нечувствительных задач и сложного reasoning. +- Локальная модель (Ollama 229) — для чувствительных данных и простых задач. +- Автоматического fallback «облако при ошибке локальной» **нет** — только явное решение. +- Лог стоимости/модели — в аудит (следующий шаг). + +## Последствия + +- Меньше дублирования, понятная ответственность. +- OpenClaw не может «починить» сервис сам — только предложить, hub-core решает. +- n8n вне критического пути. diff --git a/ops/policies/APPROVALS.md b/ops/policies/APPROVALS.md new file mode 100644 index 0000000..7a6f84d --- /dev/null +++ b/ops/policies/APPROVALS.md @@ -0,0 +1,36 @@ +# Approvals и лимиты write-инструментов + +Дата: 18.11.2026 · P0 + +## Что требует подтверждения + +| Инструмент | confirm | лимит | +|---|---|---| +| `ha.call` | да | 5 / 60 сек | +| `hub.notify` | да | 10 / 60 сек | +| `media.request` | да | 5 / 60 сек | +| `calendar.create` | да | 10 / 60 сек | + +Без `confirm=true` — `409 confirmation_required`, действие не выполняется. + +## Журнал + +Подтверждённые вызовы пишутся в Postgres `hermes.tool_approvals`: +`ts, actor, tool, args, decision=confirmed`. + +Просмотр: `approvals.recent` (Tool Gateway). +Общий аудит: `tool_audit` + `audit.recent`. + +## Проверка + +``` +ha.call без confirm → 409 +hub.notify без confirm → 409 +approvals.recent → список +``` + +## Осталось + +- UI/Matrix-подтверждение для человека (сейчас confirm выставляет клиент); +- политика «кто подтверждает» для family/agent; +- лимиты на чтение по акторам. diff --git a/ops/policies/PRIVACY-GATE.md b/ops/policies/PRIVACY-GATE.md new file mode 100644 index 0000000..0b06aef --- /dev/null +++ b/ops/policies/PRIVACY-GATE.md @@ -0,0 +1,41 @@ +# Privacy-gate Tool Gateway + +Дата: 18.11.2026 · P0 + +## Правило + +Биометрические и персональные данные **не отдаются облачной модели**. +На уровне Tool Gateway инструменты `photos.people` и `photos.albums` +помечены `local_only` и возвращают: + +``` +403 {"error":"privacy_gate","reason":"local-only: персональные/биометрические данные нельзя отдавать облачной модели"} +``` + +## Что ещё нельзя в облако + +- лица/фото Immich, биометрия; +- личная переписка Matrix, здоровье, финансы, документы; +- точные адреса/геолокация, Frigate; +- секреты, токены, `.env`; +- research-факты о семье. + +## Можно + +- агрегированный статус сервисов; +- названия медиа, свободные слоты календаря без деталей; +- публичная документация. + +## Проверка + +``` +photos.people → 403 privacy_gate +photos.albums → 403 privacy_gate +``` + +Политика также в `AGENTS.md` OpenClaw. + +## Ограничение + +Gate блокирует инструмент целиком; локального клиента для photos.* пока нет. +Если понадобится — отдельный local-token и local-модель, без облака. diff --git a/ops/reliability/HEAVY-JOBS.md b/ops/reliability/HEAVY-JOBS.md new file mode 100644 index 0000000..f9302f6 --- /dev/null +++ b/ops/reliability/HEAVY-JOBS.md @@ -0,0 +1,35 @@ +# Надёжность: тяжёлые jobs и память + +Дата: 18.11.2026 + +## Факт + +Хост: 15 ГиБ, занято ~11 ГиБ, swap занят ~10 ГиБ. Окно 08:00–08:45 было +перегружено: `trust-report`, `weekly-report`, `evolution-report`, +`research-alternatives`, `ai-digest`, `rag-reindex`, `update-plan`. + +## Что сделано + +1. **heavy_guard.sh** — только один тяжёлый job одновременно (`flock`), + при `MemAvailable < 800 МБ` job пропускается. +2. **nice -n 10** внутри guard — меньше влияния на интерактив. +3. **Разведены окна**: + - `rag-reindex`: 08:30 → **02:00**; + - `night-analysis`: 03:00 → **00:30**; + - `ai-digest`: 08:30 → **09:30**; + - остальные короткие — в 08:00–08:20, сериализуются guard'ом. +4. Hermes перезапущен, YAML валиден. + +## Проверка + +``` +free -h +/root/buryan-infra/ops/scripts/heavy_guard.sh echo ok +grep -A3 '^rag-reindex:' /opt/hermes/jobs.yaml +``` + +## Осталось + +- разобраться, кто занимает 10 ГиБ swap (кандидаты: OpenClaw, Ollama 229 — не на хосте, ZRAM); +- проверить OOM в следующий тяжёлый прогон; +- при необходимости — `zram`/swap tuning и лимит памяти для OpenClaw. diff --git a/ops/scripts/heavy_guard.sh b/ops/scripts/heavy_guard.sh new file mode 100755 index 0000000..ae19879 --- /dev/null +++ b/ops/scripts/heavy_guard.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# Heavy job guard: только один тяжёлый job одновременно; пропуск при нехватке RAM. +set -u +LOCK=/var/lock/combine-heavy.lock +exec 9>"$LOCK" +flock -n 9 || { echo "heavy job already running, skip"; exit 0; } +AVAIL_KB=$(awk '/MemAvailable:/ {print $2}' /proc/meminfo) +if [ "${AVAIL_KB:-0}" -lt 800000 ]; then + echo "skip: MemAvailable ${AVAIL_KB}kB < 800MB" + exit 0 +fi +exec nice -n 10 "$@" diff --git a/ops/scripts/weekly_review.py b/ops/scripts/weekly_review.py new file mode 100755 index 0000000..d85616a --- /dev/null +++ b/ops/scripts/weekly_review.py @@ -0,0 +1,59 @@ +#!/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) + print("sent" if send("\n".join(lines), dry) else "failed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ops/templates/INCIDENT-POSTMORTEM.md b/ops/templates/INCIDENT-POSTMORTEM.md new file mode 100644 index 0000000..51cbd43 --- /dev/null +++ b/ops/templates/INCIDENT-POSTMORTEM.md @@ -0,0 +1,30 @@ +# Шаблон incident postmortem + +## Инцидент +- ID/дата: +- Сервис/CT: +- Длительность: +- Влияние на пользователя: + +## Таймлайн (MSK) +| Время | Событие | +|---|---| +| | | + +## Что сработало +- + +## Корневая причина +- + +## Что чинили +- + +## Что предотвратит повтор +- [ ] мониторинг +- [ ] автопроверка +- [ ] изменение конфига +- [ ] документация + +## Уроки +- diff --git a/ops/tools/gateway.py b/ops/tools/gateway.py index 0a3ddd6..fbeccca 100755 --- a/ops/tools/gateway.py +++ b/ops/tools/gateway.py @@ -426,6 +426,38 @@ def t_docs_search(args): return {"query": q, "count": len(rows), "results": rows} +LOCAL_ONLY = {"photos.people", "photos.albums"} +TOOL_LIMIT = {"ha.call": (5, 60), "hub.notify": (10, 60), "media.request": (5, 60), + "calendar.create": (10, 60)} +TOOL_RATE = {} +TOOL_RATE_LOCK = threading.Lock() + + +def pg_approval(actor, tool, args): + try: + _pg("""CREATE TABLE IF NOT EXISTS tool_approvals( + id bigserial PRIMARY KEY, ts timestamptz DEFAULT now(), + actor text, tool text, args jsonb, decision text);""") + a = json.dumps(args, ensure_ascii=False).replace("'", "''")[:2000] + _pg("INSERT INTO tool_approvals(actor,tool,args,decision) VALUES " + "('%s','%s','%s'::jsonb,'confirmed');" + % (actor.replace("'", "''"), tool.replace("'", "''"), a)) + except Exception: + pass + + +def t_approvals_recent(args): + n = int(args.get("limit", 20)) + r = _pg("SELECT to_char(ts,'MM-DD HH24:MI:SS'), actor, tool, decision " + "FROM tool_approvals ORDER BY id DESC LIMIT %d;" % n) + rows = [] + for ln in (r.stdout or "").strip().splitlines(): + p = ln.split("|") + if len(p) >= 4: + rows.append({"ts": p[0], "actor": p[1], "tool": p[2], "decision": p[3]}) + 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, @@ -438,8 +470,10 @@ TOOLS = { "calendar.list": {"fn": t_calendar_list, "scope": "read", "confirm": False}, "calendar.create": {"fn": t_calendar_create, "scope": "write", "confirm": True, "actors": ["owner", "family"]}, - "photos.people": {"fn": t_photos_people, "scope": "read", "confirm": False}, - "photos.albums": {"fn": t_photos_albums, "scope": "read", "confirm": False}, + "photos.people": {"fn": t_photos_people, "scope": "read", "confirm": False, + "local_only": True}, + "photos.albums": {"fn": t_photos_albums, "scope": "read", "confirm": False, + "local_only": True}, "ha.search": {"fn": t_ha_search, "scope": "read", "confirm": False}, "media.search": {"fn": t_media_search, "scope": "read", "confirm": False}, "media.request": {"fn": t_media_request, "scope": "write", "confirm": True, @@ -452,6 +486,7 @@ TOOLS = { "books.status": {"fn": t_books_status, "scope": "read", "confirm": False}, "audit.recent": {"fn": t_audit_recent, "scope": "read", "confirm": False}, "docs.search": {"fn": t_docs_search, "scope": "read", "confirm": False}, + "approvals.recent": {"fn": t_approvals_recent, "scope": "read", "confirm": False}, } @@ -550,6 +585,20 @@ class Handler(BaseHTTPRequestHandler): if actor not in allowed: return self._send(403, {"error": "forbidden for actor", "actor": actor, "allowed": allowed}) + if spec.get("local_only") or tool in LOCAL_ONLY: + return self._send(403, {"error": "privacy_gate", "tool": tool, + "reason": "local-only: персональные/биометрические данные нельзя отдавать облачной модели"}) + lim = TOOL_LIMIT.get(tool) + if lim: + n, window = lim + now = time.time() + with TOOL_RATE_LOCK: + q = TOOL_RATE.setdefault(tool, []) + TOOL_RATE[tool] = [t for t in q if now - t < window] + if len(TOOL_RATE[tool]) >= n: + return self._send(429, {"error": "tool_rate_limit", "tool": tool, + "limit": "%d/%dsec" % (n, window)}) + TOOL_RATE[tool].append(now) required = { "ha.call": ["domain", "service"], "calendar.create": ["title", "start"], @@ -569,6 +618,8 @@ class Handler(BaseHTTPRequestHandler): if spec["confirm"] and not req.get("confirm"): return self._send(409, {"error": "confirmation_required", "tool": tool, "hint": "повторите с confirm=true"}) + if spec.get("confirm"): + pg_approval(actor, tool, args) started = time.time() try: result = spec["fn"](args)