#!/usr/bin/env python3 import json import re 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() cur.execute("select id,audit_run_id from audit.arena_runs order by id desc limit 1") run_id, audit_run_id = cur.fetchone() cur.execute("select key,leverage,criticality from audit.capabilities where run_id=%s", (audit_run_id,)) cap_meta = {r[0]: (r[1] or 3, r[2] or 3) for r in cur.fetchall()} cur.execute("select voice,answer from audit.arena_answers where arena_run_id=%s", (run_id,)) all_items = [] for voice, answer in cur.fetchall(): for it in (answer or []): if isinstance(it, dict) and it.get("title"): it["_voice"] = voice all_items.append(it) def norm(s): return re.sub(r"[^a-zа-я0-9]+", " ", str(s or "").lower()).strip() groups = {} for it in all_items: key = (norm(it.get("capability")), norm(it.get("title"))) g = groups.setdefault(key, {"item": it, "voices": set()}) g["voices"].add(it.get("_voice")) ranked = [] for g in groups.values(): it = dict(g["item"]); voices = sorted(g["voices"]) impact = int(it.get("impact") or 3); effort = int(it.get("effort") or 3); risk = int(it.get("risk") or 3) lev, crit = cap_meta.get(str(it.get("capability") or ""), (3, 3)) score = impact * 2 - effort + (5 - risk) + max(0, len(voices) - 1) + lev + crit it["_score"] = score; it["_voices"] = voices ranked.append(it) ranked.sort(key=lambda x: x["_score"], reverse=True) # One selected opportunity per capability; keep the best. selected = [] seen_caps = set() for it in ranked: cap = str(it.get("capability") or "") if cap and cap in seen_caps: continue selected.append(it) if cap: seen_caps.add(cap) if len(selected) >= 8: break cur.execute("delete from audit.arena_items where arena_run_id=%s", (run_id,)) for it in ranked: cur.execute("""insert into audit.arena_items(arena_run_id,title,capability,voices,impact,effort,risk,score,evidence,hypothesis,first_step,selected) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""", (run_id, str(it.get("title"))[:300], str(it.get("capability") or ""), ",".join(it["_voices"]), int(it.get("impact") or 3), int(it.get("effort") or 3), int(it.get("risk") or 3), it["_score"], str(it.get("evidence") or "")[:1000], str(it.get("hypothesis") or "")[:1000], str(it.get("first_step") or "")[:1000], it in selected)) cur.execute("update audit.arena_runs set status='done', finished_at=now(), summary=%s where id=%s", (json.dumps({"voices": len(set(i["_voice"] for i in all_items)), "items": len(ranked), "selected": len(selected)}, ensure_ascii=False), run_id)) conn.commit() print("arena", run_id, "answers", len(all_items), "items", len(ranked), "selected", len(selected)) cur.close(); conn.close()