138 lines
7.4 KiB
Python
138 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
||
"""Render Audit 360 run into Markdown from audit schema."""
|
||
import json
|
||
from collections import Counter
|
||
from pathlib import Path
|
||
|
||
import psycopg2
|
||
|
||
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
|
||
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
|
||
cur = conn.cursor()
|
||
run_id = int(__import__("sys").argv[1]) if len(__import__("sys").argv) > 1 else 1
|
||
cur.execute("select started_at,finished_at,summary from audit.runs where id=%s", (run_id,))
|
||
r = cur.fetchone()
|
||
if not r:
|
||
raise SystemExit("run not found")
|
||
started, finished, summary = r
|
||
facts = (summary or {}).get("facts", {})
|
||
cur.execute("select kind,count(*) from audit.entities where run_id=%s group by kind order by 2 desc", (run_id,))
|
||
kinds = cur.fetchall()
|
||
cur.execute("select severity,area,title,evidence,recommendation from audit.findings where run_id=%s order by case severity when 'high' then 1 when 'medium' then 2 else 3 end,id", (run_id,))
|
||
findings = cur.fetchall()
|
||
cur.execute("select count(*) from audit.links where run_id=%s", (run_id,))
|
||
links = cur.fetchone()[0]
|
||
cur.execute("select src,dst,kind,evidence from audit.links where run_id=%s order by id limit 60", (run_id,))
|
||
link_rows = cur.fetchall()
|
||
cur.execute("select key,title,services,maturity,automation,leverage,criticality,gaps from audit.capabilities where run_id=%s order by criticality desc,key", (run_id,))
|
||
cap_rows = cur.fetchall()
|
||
cur.execute("select title,capability,impact,effort,risk,hypothesis,first_step,evidence,source from audit.opportunities where run_id=%s order by impact desc,effort asc", (run_id,))
|
||
opp_rows = cur.fetchall()
|
||
cur.execute("""select title,capability,voices,impact,effort,risk,score,hypothesis,first_step,evidence
|
||
from audit.arena_items where selected and arena_run_id=(select max(id) from audit.arena_runs where status='done')
|
||
order by score desc""")
|
||
arena_rows = cur.fetchall()
|
||
|
||
lines = []
|
||
lines.append("# Audit 360 — Buryans Hub + Prism")
|
||
lines.append("")
|
||
lines.append("**Run:** %s " % run_id)
|
||
lines.append("**Started:** %s " % started)
|
||
lines.append("**Finished:** %s" % finished)
|
||
lines.append("")
|
||
lines.append("## Executive summary")
|
||
lines.append("")
|
||
lines.append("Детерминированный срез инфраструктуры без LLM-домыслов. ")
|
||
lines.append("")
|
||
for k, v in [
|
||
("Hub", "%s/%s" % (facts.get("hub", {}).get("up"), facts.get("hub", {}).get("total"))),
|
||
("CT running", facts.get("containers")),
|
||
("Сервисов running", facts.get("services_running")),
|
||
("Слушающих портов", facts.get("ports")),
|
||
("Баз данных", facts.get("databases")),
|
||
("Nginx proxy", facts.get("nginx_proxies")),
|
||
("Моделей Prism", facts.get("prism", {}).get("models")),
|
||
("Kuma down", "%s/%s" % (facts.get("kuma", {}).get("down"), facts.get("kuma", {}).get("total"))),
|
||
("Последний бэкап", "%s дней" % facts.get("backups", {}).get("age_days")),
|
||
("Диск /", "%s%%" % facts.get("disk", {}).get("used_pct")),
|
||
]:
|
||
lines.append("- **%s:** %s" % (k, v))
|
||
lines.append("")
|
||
lines.append("## Findings")
|
||
lines.append("")
|
||
for sev, area, title, evidence, rec in findings:
|
||
lines.append("### [%s] %s — %s" % (sev.upper(), area, title))
|
||
lines.append("")
|
||
lines.append("- Evidence: `%s`" % (evidence or ""))
|
||
lines.append("- Recommendation: %s" % (rec or "—"))
|
||
lines.append("")
|
||
lines.append("## Inventory")
|
||
lines.append("")
|
||
lines.append("| Kind | Count |")
|
||
lines.append("|---|---:|")
|
||
for k, n in kinds:
|
||
lines.append("| %s | %s |" % (k, n))
|
||
lines.append("")
|
||
lines.append("## Integration links")
|
||
lines.append("")
|
||
lines.append("Рёбра графа: **%s**. Первые 60:" % links)
|
||
lines.append("")
|
||
lines.append("| Source | Destination | Kind | Evidence |")
|
||
lines.append("|---|---|---|---|")
|
||
for src, dst, kind, ev in link_rows:
|
||
lines.append("| %s | %s | %s | %s |" % (src, dst, kind, (ev or "").replace("|", "\\|")[:120]))
|
||
lines.append("")
|
||
lines.append("## Capability matrix")
|
||
lines.append("")
|
||
lines.append("| Возможность | Maturity | Automation | Leverage | Criticality | Пробел |")
|
||
lines.append("|---|---:|---:|---:|---:|---|")
|
||
for key, title, services, mat, auto, lev, crit, gaps in cap_rows:
|
||
lines.append("| **%s** | %s | %s | %s | %s | %s |" % (title, mat, auto, lev, crit, (gaps or "").replace("|", "\\|")[:180]))
|
||
lines.append("")
|
||
lines.append("## Opportunity portfolio")
|
||
lines.append("")
|
||
lines.append("| Возможность | Impact | Effort | Risk | Гипотеза |")
|
||
lines.append("|---|---:|---:|---:|---|")
|
||
for title, cap, imp, eff, risk, hyp, step, ev, source in opp_rows:
|
||
lines.append("| **%s** | %s | %s | %s | %s |" % (title, imp, eff, risk, (hyp or "").replace("|", "\\|")[:180]))
|
||
lines.append("")
|
||
lines.append("## Arena 360")
|
||
lines.append("")
|
||
lines.append("Один evidence-пакет, два голоса: локальная Qwen 3B и DeepSeek. Выбор — детерминированный: impact/effort/risk + leverage/criticality + одна возможность на capability.")
|
||
lines.append("")
|
||
lines.append("| Возможность | Capability | Голоса | I | E | R | Score |")
|
||
lines.append("|---|---|---|---:|---:|---:|---:|")
|
||
for title, cap, voices, imp, eff, risk, score, hyp, step, ev in arena_rows:
|
||
lines.append("| **%s** | %s | %s | %s | %s | %s | %s |" % (title, cap, voices, imp, eff, risk, score))
|
||
lines.append("")
|
||
lines.append("## Roadmap (draft)")
|
||
lines.append("")
|
||
lines.append("### 0–2 недели")
|
||
lines.append("- Проверить и восстановить backup/restore; разобрать 5 down-мониторов Kuma.")
|
||
lines.append("- Решить судьбу `combine-*` и `llm-dispatcher`: Prism — основной контур или legacy fallback.")
|
||
lines.append("- Включить/задокументировать неактивные таймеры агентов, если они нужны.")
|
||
lines.append("")
|
||
lines.append("### 2–6 недель")
|
||
lines.append("- Убрать единую точку отказа PostgreSQL: реплика + проверенный failover.")
|
||
lines.append("- Ввести владельцев и SLA для 15 возможностей; закрыть разрыв между docs и фактом.")
|
||
lines.append("- Добавить Audit 360 в Prism как страницу с run/diff.")
|
||
lines.append("")
|
||
lines.append("### 6–12 недель")
|
||
lines.append("- Единый поиск по знаниям и документам; довести Paperless/Nextcloud/Docmost.")
|
||
lines.append("- Агентский слой: approvals, SLA, наблюдаемость; включить таймеры.")
|
||
lines.append("- Продуктовые сценарии: Prism как AV knowledge platform, Секретарь как orchestrator.")
|
||
lines.append("")
|
||
lines.append("## Следующие слои Audit 360")
|
||
lines.append("")
|
||
lines.append("- capability matrix: сервис → возможность → зрелость;")
|
||
lines.append("- value/leverage: переиспользование, автоматизация, продукт;")
|
||
lines.append("- risk: SPOF, секреты, бэкапы, единственный GPU;")
|
||
lines.append("- opportunity portfolio и roadmap;")
|
||
lines.append("- LLM-синтез строго по evidence.")
|
||
lines.append("")
|
||
|
||
out = Path("/root/buryan-infra/ops/audit/reports/AUDIT-360-%s.md" % run_id)
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
out.write_text("\n".join(lines), encoding="utf-8")
|
||
print(out)
|