Политика: перезапуск — класс C с подтверждением; заявки в Matrix
Перезапуск контейнера отнесён к классу C (влияет на сервис) — агент только предлагает, владелец подтверждает. Добавлена очередь заявок /opt/hub-agents/approvals.json и команды бота: !заявки, !одобрить N, !отклонить N. Исполняются только разрешённые действия (restart_container). Дорожная карта переставлена: сначала скелет и структура сервисов, работа (ВКС/Presale) — после стабилизации. Wiki обновлена.
This commit is contained in:
1 parent
3af3fa304f
commit
43502690c9
3 files changed
+199
-21
No files matched your search
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Очередь заявок класса C: агент предлагает — владелец одобряет.
|
||||
|
||||
Использование:
|
||||
approvals.py list — показать ожидающие
|
||||
approvals.py approve <id> — выполнить (только из actions_allowed)
|
||||
approvals.py reject <id> — отклонить
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
QUEUE = "/var/lib/hub-agents/approvals.json"
|
||||
JOURNAL = "/var/lib/hub-agents/journal"
|
||||
ALLOWED = {"restart_container"}
|
||||
|
||||
|
||||
def load():
|
||||
try:
|
||||
return json.load(open(QUEUE, encoding="utf-8"))
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def save(items):
|
||||
os.makedirs(os.path.dirname(QUEUE), exist_ok=True)
|
||||
json.dump(items, open(QUEUE, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
||||
|
||||
|
||||
def next_id(items):
|
||||
return (max([i.get("id", 0) for i in items] or [0]) + 1)
|
||||
|
||||
|
||||
def add(proposals, agent):
|
||||
"""Добавляет предложения агента в очередь (без дублей)."""
|
||||
items = load()
|
||||
added = []
|
||||
for p in proposals:
|
||||
if (p.get("class") or "").upper() != "C":
|
||||
continue
|
||||
action = p.get("action")
|
||||
target = p.get("target")
|
||||
if not action or not target:
|
||||
continue
|
||||
dup = [i for i in items if i.get("action") == action
|
||||
and i.get("target") == target and i.get("status") == "pending"]
|
||||
if dup:
|
||||
continue
|
||||
item = {
|
||||
"id": next_id(items),
|
||||
"agent": agent,
|
||||
"action": action,
|
||||
"target": target,
|
||||
"why": p.get("why", ""),
|
||||
"status": "pending",
|
||||
"created": datetime.now().isoformat(timespec="seconds"),
|
||||
}
|
||||
items.append(item)
|
||||
added.append(item)
|
||||
save(items)
|
||||
return added
|
||||
|
||||
|
||||
def find(items, ident):
|
||||
for i in items:
|
||||
if str(i.get("id")) == str(ident):
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
def log(entry):
|
||||
os.makedirs(JOURNAL, exist_ok=True)
|
||||
path = os.path.join(JOURNAL, datetime.now().strftime("%Y-%m-%d") + "-approvals.jsonl")
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
def execute(item):
|
||||
action, target = item.get("action"), item.get("target")
|
||||
if action not in ALLOWED:
|
||||
return False, f"действие {action} не разрешено к исполнению"
|
||||
# ищем контейнер: сначала на хосте, потом по CT
|
||||
try:
|
||||
r = subprocess.run(["docker", "restart", target], capture_output=True,
|
||||
text=True, timeout=90)
|
||||
if r.returncode == 0:
|
||||
return True, "перезапущен на хосте"
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
cts = subprocess.run(["pct", "list"], capture_output=True, text=True, timeout=20).stdout
|
||||
for line in cts.splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) < 3:
|
||||
continue
|
||||
ct = parts[0]
|
||||
names = subprocess.run(["pct", "exec", ct, "--", "docker", "ps",
|
||||
"--format", "{{.Names}}"],
|
||||
capture_output=True, text=True, timeout=15).stdout
|
||||
if target in names.split():
|
||||
r = subprocess.run(["pct", "exec", ct, "--", "docker", "restart", target],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
return (r.returncode == 0), f"перезапущен в CT{ct}"
|
||||
except Exception as e:
|
||||
return False, str(e)[:120]
|
||||
return False, "контейнер не найден"
|
||||
|
||||
|
||||
def cmd_list():
|
||||
items = [i for i in load() if i.get("status") == "pending"]
|
||||
if not items:
|
||||
print("заявок нет")
|
||||
return
|
||||
for i in items:
|
||||
print(f"#{i['id']} [{i['agent']}] {i['action']} {i['target']} — {i.get('why', '')[:90]}")
|
||||
|
||||
|
||||
def cmd_approve(ident):
|
||||
items = load()
|
||||
item = find(items, ident)
|
||||
if not item or item.get("status") != "pending":
|
||||
print("заявка не найдена или уже обработана")
|
||||
return
|
||||
ok, detail = execute(item)
|
||||
item["status"] = "done" if ok else "failed"
|
||||
item["result"] = detail
|
||||
item["decided"] = datetime.now().isoformat(timespec="seconds")
|
||||
save(items)
|
||||
log(item)
|
||||
print(("✅ " if ok else "❌ ") + f"#{item['id']} {item['action']} {item['target']}: {detail}")
|
||||
|
||||
|
||||
def cmd_reject(ident):
|
||||
items = load()
|
||||
item = find(items, ident)
|
||||
if not item or item.get("status") != "pending":
|
||||
print("заявка не найдена")
|
||||
return
|
||||
item["status"] = "rejected"
|
||||
item["decided"] = datetime.now().isoformat(timespec="seconds")
|
||||
save(items)
|
||||
log(item)
|
||||
print(f"отклонено #{item['id']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) < 2:
|
||||
cmd_list()
|
||||
elif sys.argv[1] == "list":
|
||||
cmd_list()
|
||||
elif sys.argv[1] == "approve" and len(sys.argv) > 2:
|
||||
cmd_approve(sys.argv[2])
|
||||
elif sys.argv[1] == "reject" and len(sys.argv) > 2:
|
||||
cmd_reject(sys.argv[2])
|
||||
else:
|
||||
print(__doc__)
|
||||
+27
-12
@@ -1,32 +1,46 @@
|
||||
version: 1
|
||||
version: 2
|
||||
# Политика действий агентов.
|
||||
# A — только чтение и метрики (сам)
|
||||
# B — гигиена без влияния на доступность (сам, с записью)
|
||||
# C — влияет на сервис → ТОЛЬКО с подтверждением владельца
|
||||
# D — запрещено
|
||||
|
||||
classes:
|
||||
A:
|
||||
title: Безопасное
|
||||
title: Наблюдение
|
||||
auto: true
|
||||
examples: [restart_container, cleanup_logs, health_check, vacuum_journal]
|
||||
examples: [health_check, collect_metrics, journal_write, status_probe]
|
||||
limits:
|
||||
actions_per_hour: 10
|
||||
actions_per_day: 50
|
||||
actions_per_hour: 60
|
||||
affects_service: false
|
||||
B:
|
||||
title: Заметное
|
||||
title: Гигиена
|
||||
auto: true
|
||||
notify: journal
|
||||
examples: [update_container, rotate_logs, reindex_library, refresh_cache]
|
||||
examples: [rotate_logs, vacuum_journal, clear_cache, trim_tmp]
|
||||
limits:
|
||||
actions_per_hour: 3
|
||||
actions_per_day: 10
|
||||
actions_per_hour: 4
|
||||
actions_per_day: 12
|
||||
affects_service: false
|
||||
C:
|
||||
title: Рискованное
|
||||
title: Влияет на сервис
|
||||
auto: false
|
||||
approval: matrix_owner
|
||||
examples: [change_config, migrate_data, delete_service, change_dns]
|
||||
examples: [restart_container, update_container, change_config, migrate_data,
|
||||
delete_service, change_dns, reindex_library]
|
||||
note: "Любое действие, после которого сервис может стать недоступен"
|
||||
D:
|
||||
title: Запрещено
|
||||
auto: false
|
||||
approval: never
|
||||
examples: [delete_backup, read_secrets, change_router_config, disable_2fa]
|
||||
examples: [delete_backup, read_secrets, disable_2fa, change_router_config,
|
||||
drop_database]
|
||||
|
||||
approvals:
|
||||
channel: matrix
|
||||
ttl_hours: 24
|
||||
queue: /var/lib/hub-agents/approvals.json
|
||||
actions_allowed: [restart_container]
|
||||
|
||||
notifications:
|
||||
owner:
|
||||
@@ -40,6 +54,7 @@ notifications:
|
||||
journal: /var/lib/hub-agents/journal
|
||||
|
||||
safety:
|
||||
observe_mode: true
|
||||
dry_run_first_days: 14
|
||||
snapshot_before_change: true
|
||||
auto_rollback_if_unhealthy: true
|
||||
|
||||
+14
-9
@@ -180,15 +180,20 @@ def page_roadmap():
|
||||
|
||||
| Фаза | Статус | Результат |
|
||||
|---|---|---|
|
||||
| 0. Скелет | ✅ сделано | реестр, Wiki, статус-страница, сверка с аудитом |
|
||||
| 1. Агенты-наблюдатели | 🔄 в работе | 6 агентов «читать и предлагать», журнал |
|
||||
| 2. Автономия A | ⏳ | перезапуск, чистка, health |
|
||||
| 3. Автономия B | ⏳ | обновления, ротация |
|
||||
| 4. Класс C + Голова | ⏳ | подтверждения, сводки |
|
||||
| 5. Быт | ⏳ | Grocy, Vikunja, Actual, Mealie |
|
||||
| 6. Работа | ⏳ | Presale Cockpit |
|
||||
| 7. Интеллект | ⏳ | RAG, CLIP, MCP |
|
||||
| 8. Устойчивость | ⏳ | учения, резервный канал, UPS |
|
||||
| 0. Скелет | ✅ | реестр, Wiki, статус-страница, сверка с аудитом |
|
||||
| 1. Структура сервисов | 🔄 сейчас | карточки на все сервисы, группы, связи |
|
||||
| 2. Агенты + заявки C | 🔄 сейчас | 6 секретарей, DeepSeek, подтверждения в Matrix |
|
||||
| 3. Гигиена B | ⏳ | логи, кэш, ротация — без влияния на доступность |
|
||||
| 4. Дом и быт | ⏳ | сценарии HA, Grocy, Vikunja, бюджет |
|
||||
| 5. Контент и интеллект | ⏳ | RAG, CLIP, рекомендации, аудиокниги |
|
||||
| 6. Работа (Presale) | ⏳ позже | после полной структуры сервисов |
|
||||
| 7. Устойчивость | ⏳ | учения, резервный канал, UPS |
|
||||
|
||||
## Правило порядка
|
||||
|
||||
Сначала **скелет и структура**: реестр, карточки, связи, агенты.
|
||||
Работа (ВКС/Presale) — после того, как сервисы и процессы стабильны.
|
||||
Никаких новых сервисов, пока нет карточки, бэкапа и мониторинга.
|
||||
|
||||
Подробно — `ops/audit/AUDIT-2026-10-21-VISION.md`.
|
||||
"""
|
||||
|
||||
Reference in new issue
Block a user