#!/usr/bin/env python3 """Cloud-model synthesis on the full Buryans Hub inventory.""" import json, re, subprocess, urllib.request from pathlib import Path ROOT = Path("/root/buryan-infra/ops/audit") FULL = json.loads((ROOT / "AUDIT-360-FULL.json").read_text(encoding="utf-8")) DEEPSEEK = Path("/root/.deepseek-key").read_text().strip() GEMINI = Path("/root/.gemini-key").read_text().strip() VPS = "root@193.233.210.184" compact = { "summary": FULL["summary"], "cts": [f'{c.get("vmid")}:{c.get("name")}:{c.get("status")}' for c in FULL.get("cts", [])], "containers": [f'{c.get("ct")}:{c.get("name")}:{c.get("state")}' for c in FULL.get("containers", [])], "systemd": [s.get("unit") for s in FULL.get("systemd", [])], "domains": FULL.get("nginx_domains", []), "routes": FULL.get("routes", []), "owners": FULL.get("owners", []), "kuma": [f'{k.get("name")}:{"up" if k.get("up") else "down"}' for k in FULL.get("kuma", [])], "databases": [f'{d.get("name")}:{d.get("size")}' for d in FULL.get("databases", [])], "backups": [b.get("path") for b in FULL.get("backups", [])[:15]], "findings": (FULL.get("audit") or {}).get("findings", []), "capabilities": (FULL.get("audit") or {}).get("capabilities", []), "decisions": (FULL.get("audit") or {}).get("decisions", []), "experiments": (FULL.get("audit") or {}).get("experiments", []), "arena_items": FULL.get("arena_items", []), } PACKET = json.dumps(compact, ensure_ascii=False) PROMPT = """Ты независимый архитектор и аудитор Buryans Hub. Не выдумывай сервисы, цифры, владельцев. Ниже ПОЛНЫЙ инвентарь: контейнеры, systemd, домены, Kuma, все БД, бэкапы, findings, capabilities, decisions. Задача — не конкурс моделей, а полезные решения для развития проекта. Предложи 12 инициатив, максимум пользы при текущих ограничениях (RAM мало, HA отложена). Для каждой: id, title, why, evidence (конкретные сервисы/факты), impact 1-5, effort 1-5, risk 1-5, depends_on, first_step, owner_role, what_not_to_do. Отдельно: top3 сейчас, top3 после RAM, риски и что не делать. Верни ТОЛЬКО валидный JSON: {"initiatives":[...],"top3_now":[...],"top3_after_ram":[...],"risks":[...],"do_not_do":[...]} ПОЛНЫЙ ИНВЕНТАРЬ: %s """ % PACKET def j(text): t = str(text or "").strip() t = re.sub(r"^```(?:json)?", "", t, flags=re.I).strip() t = re.sub(r"```$", "", t).strip() try: return json.loads(t) except Exception: i, j2 = t.find("{"), t.rfind("}") if i >= 0 and j2 > i: return json.loads(t[i:j2 + 1]) raise def deepseek(): req = urllib.request.Request("https://api.deepseek.com/v1/chat/completions", data=json.dumps({ "model": "deepseek-chat", "messages": [{"role": "system", "content": "Отвечай только валидным JSON."}, {"role": "user", "content": PROMPT}], "temperature": 0.2, "max_tokens": 4000, }).encode(), headers={"Authorization": "Bearer " + DEEPSEEK, "Content-Type": "application/json"}, method="POST") with urllib.request.urlopen(req, timeout=240) as r: d = json.load(r) return d.get("choices", [{}])[0].get("message", {}).get("content") or "{}" def gemini(): body = json.dumps({"contents": [{"parts": [{"text": PROMPT}]}], "generationConfig": {"temperature": 0.2, "maxOutputTokens": 4000}}) subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", VPS, "umask 077; cat > /tmp/.audit-gemini-key"], input=GEMINI, text=True, timeout=20, check=True) remote = ("KEY=$(cat /tmp/.audit-gemini-key); " "curl -sS --max-time 220 -X POST -H 'Content-Type: application/json' -d @- " "'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$KEY'; " "rm -f /tmp/.audit-gemini-key") p = subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", VPS, remote], input=body, text=True, capture_output=True, timeout=260) if p.returncode != 0: raise RuntimeError((p.stderr or "gemini ssh error")[:300]) d = json.loads(p.stdout) return d.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text") or "{}" for name, fn in [("deepseek", deepseek), ("gemini", gemini)]: try: raw = fn() (ROOT / ("AUDIT-360-%s-RAW.json" % name)).write_text(raw, encoding="utf-8") data = j(raw) (ROOT / ("AUDIT-360-%s.json" % name)).write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") print(name, "initiatives", len(data.get("initiatives", [])), "bytes", len(raw)) except Exception as e: print(name, "ERROR", str(e)[:300])