[P0] Privacy-gate, approvals journal+limits, heavy-job guard/расписание, weekly review, incident template, ADR-008 ролей
lint / hygiene (push) Failing after 22s
standard / check (push) Successful in 7s

This commit is contained in:
root committed 2026-11-18 11:55:17 +03:00
1 parent ad1728d161
commit 386c5f136a
8 files changed
+306 -2

No files matched your search

@@ -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 вне критического пути.
+36
View File
@@ -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;
- лимиты на чтение по акторам.
+41
View File
@@ -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-модель, без облака.
+35
View File
@@ -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.
+12
View File
@@ -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 "$@"
+59
View File
@@ -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())
+30
View File
@@ -0,0 +1,30 @@
# Шаблон incident postmortem
## Инцидент
- ID/дата:
- Сервис/CT:
- Длительность:
- Влияние на пользователя:
## Таймлайн (MSK)
| Время | Событие |
|---|---|
| | |
## Что сработало
-
## Корневая причина
-
## Что чинили
-
## Что предотвратит повтор
- [ ] мониторинг
- [ ] автопроверка
- [ ] изменение конфига
- [ ] документация
## Уроки
-
+53 -2
View File
@@ -426,6 +426,38 @@ def t_docs_search(args):
return {"query": q, "count": len(rows), "results": rows} 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 = { TOOLS = {
"hub.status": {"fn": t_hub_status, "scope": "read", "confirm": False}, "hub.status": {"fn": t_hub_status, "scope": "read", "confirm": False},
"hub.notify": {"fn": t_hub_notify, "scope": "write", "confirm": True, "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.list": {"fn": t_calendar_list, "scope": "read", "confirm": False},
"calendar.create": {"fn": t_calendar_create, "scope": "write", "confirm": True, "calendar.create": {"fn": t_calendar_create, "scope": "write", "confirm": True,
"actors": ["owner", "family"]}, "actors": ["owner", "family"]},
"photos.people": {"fn": t_photos_people, "scope": "read", "confirm": False}, "photos.people": {"fn": t_photos_people, "scope": "read", "confirm": False,
"photos.albums": {"fn": t_photos_albums, "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}, "ha.search": {"fn": t_ha_search, "scope": "read", "confirm": False},
"media.search": {"fn": t_media_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, "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}, "books.status": {"fn": t_books_status, "scope": "read", "confirm": False},
"audit.recent": {"fn": t_audit_recent, "scope": "read", "confirm": False}, "audit.recent": {"fn": t_audit_recent, "scope": "read", "confirm": False},
"docs.search": {"fn": t_docs_search, "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: if actor not in allowed:
return self._send(403, {"error": "forbidden for actor", "actor": actor, return self._send(403, {"error": "forbidden for actor", "actor": actor,
"allowed": allowed}) "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 = { required = {
"ha.call": ["domain", "service"], "ha.call": ["domain", "service"],
"calendar.create": ["title", "start"], "calendar.create": ["title", "start"],
@@ -569,6 +618,8 @@ class Handler(BaseHTTPRequestHandler):
if spec["confirm"] and not req.get("confirm"): if spec["confirm"] and not req.get("confirm"):
return self._send(409, {"error": "confirmation_required", "tool": tool, return self._send(409, {"error": "confirmation_required", "tool": tool,
"hint": "повторите с confirm=true"}) "hint": "повторите с confirm=true"})
if spec.get("confirm"):
pg_approval(actor, tool, args)
started = time.time() started = time.time()
try: try:
result = spec["fn"](args) result = spec["fn"](args)