Files
buryan-infra/ops/audit/audit360_svc.py
T
architect 768ba209f6
lint / hygiene (push) Failing after 19s
lint / hygiene (pull_request) Failing after 23s
standard / check (push) Successful in 10s
standard / check (pull_request) Successful in 10s
[ARCH] Audit 360 service, collectors, snapshots and sprint tool
2026-11-26 21:45:23 +03:00

547 lines
39 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
import base64
import json
import os
import re
import urllib.error
import urllib.request
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlparse, parse_qs
import psycopg2
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
GITEA = os.environ.get("AUDIT360_GITEA_URL", "http://192.168.1.140:3000")
GITEA_REPO = os.environ.get("AUDIT360_GITEA_REPO", "infrastructure/buryan-audit")
GITEA_TOKEN = Path("/root/.gitea-admin-token").read_text().strip()
ALLOWED_EMAILS = {x.strip().lower() for x in os.environ.get("AUDIT360_ALLOWED_EMAILS", "maloyakapg@gmail.com,akadmin").split(",") if x.strip()}
HOST = os.environ.get("AUDIT360_HOST", "127.0.0.1")
PORT = int(os.environ.get("AUDIT360_PORT", "9160"))
def db():
return psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
def gitea(method, path, body=None):
data = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
req = urllib.request.Request(GITEA + "/api/v1" + path, data=data,
headers={"Authorization": "token " + GITEA_TOKEN, "Content-Type": "application/json"}, method=method)
try:
with urllib.request.urlopen(req, timeout=20) as r:
raw = r.read().decode()
except urllib.error.HTTPError as e:
raw = e.read().decode(errors="replace")
raise RuntimeError("gitea HTTP %s: %s" % (e.code, raw[:300]))
try:
return json.loads(raw or "{}")
except Exception:
raise RuntimeError("gitea invalid JSON: %s" % raw[:300])
def gitea_user_map():
out = {}
try:
for u in gitea("GET", "/admin/users?limit=100") or []:
login = str(u.get("login") or "")
for key in (u.get("email"), u.get("full_name"), login):
if key:
out[str(key).strip().lower()] = login
except Exception:
pass
return out
def match_owner(owner, users):
s = str(owner or "").strip()
candidates = [s, s.split("<")[0].strip()]
m = re.search(r"<([^>]+)>", s)
if m:
candidates.append(m.group(1).strip())
for c in candidates:
if c and c.lower() in users:
return users[c.lower()]
return None
def gitea_issue_for_decision(did):
c = db(); cur = c.cursor()
cur.execute("select id,title,rationale,alternatives,owner,gitea_issue_url,gitea_issue_number from audit.decisions where id=%s", (did,))
r = cur.fetchone()
if not r:
c.close(); raise RuntimeError("decision not found")
ident, title, rationale, alternatives, owner, url, num = r
if url:
c.close(); return {"ok": True, "url": url, "number": num, "existing": True}
login = match_owner(owner, gitea_user_map())
body = "**Decision:** %s\n\n**Rationale:**\n%s\n\n**Alternatives:**\n%s\n\n**Owner:** %s\n\n**Audit 360:** http://192.168.1.10:9161/\n" % (title, rationale or "", alternatives or "", owner or "")
payload = {"title": "[DECISION] %s" % title, "body": body}
if login:
payload["assignees"] = [login]
issue = gitea("POST", "/repos/%s/issues" % GITEA_REPO, payload)
cur.execute("update audit.decisions set gitea_issue_url=%s,gitea_issue_number=%s,updated_at=now() where id=%s",
(issue.get("html_url"), issue.get("number"), did))
c.commit(); c.close()
return {"ok": True, "url": issue.get("html_url"), "number": issue.get("number")}
def gitea_assign_for_finding(fid):
c = db(); cur = c.cursor()
cur.execute("select owner,gitea_issue_number from audit.findings where id=%s", (fid,))
r = cur.fetchone()
if not r or not r[1]:
c.close(); return {"ok": False, "error": "finding or issue missing"}
login = match_owner(r[0], gitea_user_map())
if not login:
c.close(); return {"ok": False, "error": "owner not mapped to Gitea user"}
gitea("PATCH", "/repos/%s/issues/%s" % (GITEA_REPO, r[1]), {"assignees": [login]})
cur.execute("update audit.findings set gitea_assignee=%s,updated_at=now() where id=%s", (login, fid))
c.commit(); c.close()
return {"ok": True, "assignee": login}
def gitea_issue_for_finding(fid):
c = db(); cur = c.cursor()
cur.execute("select id,severity,area,title,evidence,recommendation,owner,gitea_issue_url,gitea_issue_number,gitea_assignee from audit.findings where id=%s", (fid,))
r = cur.fetchone()
if not r:
c.close(); raise RuntimeError("finding not found")
ident, sev, area, title, evidence, rec, owner, url, num, assignee = r
if url:
c.close(); return {"ok": True, "url": url, "number": num, "assignee": assignee, "existing": True}
body = "**Severity:** %s\n\n**Area:** %s\n\n**Evidence:**\n%s\n\n**Recommendation:**\n%s\n\n**Owner:** %s\n\n**Audit 360:** http://192.168.1.10:9161/\n" % (sev, area, evidence or "", rec or "", owner or "")
login = match_owner(owner, gitea_user_map())
payload = {"title": "[AUDIT][%s] %s" % (str(sev).upper(), title), "body": body}
if login:
payload["assignees"] = [login]
issue = gitea("POST", "/repos/%s/issues" % GITEA_REPO, payload)
cur.execute("update audit.findings set gitea_issue_url=%s,gitea_issue_number=%s,gitea_assignee=%s,updated_at=now() where id=%s",
(issue.get("html_url"), issue.get("number"), login, fid))
c.commit(); c.close()
return {"ok": True, "url": issue.get("html_url"), "number": issue.get("number"), "assignee": login}
def gitea_sync():
c = db(); cur = c.cursor()
cur.execute("select id,gitea_issue_number from audit.findings where gitea_issue_number is not null")
rows = cur.fetchall(); synced = 0
for fid, num in rows:
issue = gitea("GET", "/repos/%s/issues/%s" % (GITEA_REPO, num))
state = issue.get("state")
if state == "closed":
status = "fixed"
else:
cur.execute("select status from audit.findings where id=%s", (fid,))
old = (cur.fetchone() or ["open"])[0]
status = old if old in ("accepted", "in_progress", "wontfix") else "in_progress"
cur.execute("update audit.findings set status=%s,updated_at=now() where id=%s", (status, fid))
synced += 1
c.commit(); c.close()
return {"ok": True, "synced": synced}
def identity_owners():
try:
with urllib.request.urlopen("http://127.0.0.1:9150/v1/accounts", timeout=5) as r:
accounts = json.loads(r.read().decode()).get("accounts") or []
with urllib.request.urlopen("http://127.0.0.1:9150/v1/persons", timeout=5) as r:
persons = {x.get("id"): x.get("display_name") for x in (json.loads(r.read().decode()).get("persons") or [])}
out = []
for a in accounts:
name = persons.get(a.get("person_id")) or a.get("email") or a.get("subject")
out.append({"id": a.get("person_id") or a.get("subject"), "name": name,
"email": a.get("email"), "role": a.get("role")})
return out
except Exception:
return [{"id": "admin", "name": "admin", "email": None, "role": "admin"}]
def graph_data(node=""):
c = db(); cur = c.cursor()
cur.execute("select max(r.id) from audit.runs r where exists(select 1 from audit.capabilities c where c.run_id=r.id)")
rid = cur.fetchone()[0]
cur.execute("select count(*) from audit.entities where run_id=%s", (rid,)); nodes = cur.fetchone()[0]
cur.execute("select count(*) from audit.links where run_id=%s", (rid,)); edges = cur.fetchone()[0]
node = str(node or "").strip()
if node:
cur.execute("""select src,dst,kind,evidence from audit.links where run_id=%s and (src=%s or dst=%s)
order by id limit 120""", (rid, node, node))
else:
cur.execute("""select src,dst,kind,evidence from audit.links where run_id=%s
order by id limit 120""", (rid,))
links = [{"src": r[0], "dst": r[1], "kind": r[2], "evidence": r[3]} for r in cur.fetchall()]
cur.execute("""select kind,name,status from audit.entities where run_id=%s and
(%s='' or name=%s or kind=%s) order by kind,name limit 120""", (rid, node, node, node))
ents = [{"kind": r[0], "name": r[1], "status": r[2]} for r in cur.fetchall()]
c.close()
return {"ok": True, "node": node, "nodes_total": nodes, "edges_total": edges,
"nodes": ents, "links": links}
def diff_data(frm=None, to=None):
c = db(); cur = c.cursor()
cur.execute("select id from audit.runs order by id desc limit 2")
ids = [x[0] for x in cur.fetchall()]
a = int(frm) if frm else (ids[1] if len(ids) > 1 else None)
b = int(to) if to else (ids[0] if ids else None)
if not a or not b:
c.close(); return {"ok": False, "error": "need two runs"}
def rows(run):
cur.execute("select title,severity,status,owner,evidence from audit.findings where run_id=%s", (run,))
return {r[0]: {"severity": r[1], "status": r[2], "owner": r[3], "evidence": r[4]} for r in cur.fetchall()}
A, B = rows(a), rows(b)
new = [{"title": k, **B[k]} for k in sorted(set(B) - set(A))]
resolved = [{"title": k, **A[k]} for k in sorted(set(A) - set(B))]
changed = []
for k in sorted(set(A) & set(B)):
delta = {f: [A[k].get(f), B[k].get(f)] for f in ("severity", "status", "owner") if A[k].get(f) != B[k].get(f)}
if delta:
changed.append({"title": k, "changes": delta})
c.close()
return {"ok": True, "from": a, "to": b, "new": new, "resolved": resolved, "changed": changed,
"counts": {"from": len(A), "to": len(B), "new": len(new), "resolved": len(resolved), "changed": len(changed)}}
def api_data():
c = db(); cur = c.cursor()
cur.execute("select id,started_at,finished_at,status,summary from audit.runs r where exists(select 1 from audit.capabilities c where c.run_id=r.id) order by id desc limit 1")
r = cur.fetchone()
if not r:
c.close(); return {"ok": False, "error": "audit run not found"}
rid, started, finished, status, summary = r
out = {"ok": True, "id": rid, "started_at": str(started), "finished_at": str(finished), "status": status, "summary": summary or {}}
def q(sql):
cur.execute(sql)
return [dict(zip([d[0] for d in cur.description], row)) for row in cur.fetchall()]
out["findings"] = q("select id,severity,area,title,evidence,recommendation,owner,status,gitea_issue_url,gitea_issue_number from audit.findings where run_id=%d order by case severity when 'high' then 1 when 'medium' then 2 else 3 end,id" % rid)
out["capabilities"] = q("select key,title,maturity,automation,leverage,criticality,gaps from audit.capabilities where run_id=%d order by criticality desc,key" % rid)
out["opportunities"] = q("select title,capability,impact,effort,risk,hypothesis,first_step,evidence,source from audit.opportunities where run_id=%d order by impact desc,effort asc" % rid)
out["arena"] = q("select title,capability,voices,impact,effort,risk,score,evidence,hypothesis,first_step from audit.arena_items where selected and arena_run_id=(select max(id) from audit.arena_runs where status='done') order by score desc")
out["decisions"] = q("select id,finding_id,title,rationale,alternatives,owner,status,review_at,created_at,gitea_issue_url,gitea_issue_number from audit.decisions order by id desc")
out["experiments"] = q("select id,decision_id,title,hypothesis,metric,baseline,target,status,result,verification,verify_run_id,started_at,finished_at from audit.experiments order by id desc")
out["sprint"] = q("select code,phase,seq,title,detail,owner,status,requires_user,user_action,evidence,source,gitea_issue,gate,updated_at,closed_at from audit.sprint_items order by phase,seq")
out["sprint_comments"] = q("select code,count(*) as n from audit.sprint_comments group by code")
f = out["findings"]; d = out["decisions"]; e = out["experiments"]
out["semantic"] = q("""select distinct on (name) name,status,ok,latency_ms,error,checked_at
from audit.semantic_checks order by name,checked_at desc""")
out["owners"] = identity_owners()
out["metrics"] = {
"findings": len(f),
"owned": sum(1 for x in f if x.get("owner")),
"open": sum(1 for x in f if x.get("status") not in ("fixed", "wontfix")),
"fixed": sum(1 for x in f if x.get("status") == "fixed"),
"decisions": len(d),
"experiments": len(e),
"experiments_done": sum(1 for x in e if x.get("status") == "done"),
"gitea_issues": sum(1 for x in f if x.get("gitea_issue_url")),
"sprint": len(out["sprint"]),
"sprint_done": sum(1 for x in out["sprint"] if x.get("status") == "done"),
"sprint_user": sum(1 for x in out["sprint"] if x.get("requires_user") and x.get("status") != "done"),
}
try:
out["diff"] = diff_data()
except Exception as e:
out["diff"] = {"ok": False, "error": str(e)[:200]}
c.close()
return out
def bundle():
d = api_data()
d["schema"] = "audit360/v1"
d["generated_at"] = datetime.now(timezone.utc).isoformat()
d["agent_packet"] = {
"purpose": "Manual multi-model audit: feed this packet to any agent/model. Facts are evidence-based.",
"instructions": "Do not invent services. Return opportunities/risks with evidence. Preserve IDs.",
"facts": (d.get("summary") or {}).get("facts", {}),
"capabilities": d.get("capabilities", []),
"findings": d.get("findings", []),
"opportunities": d.get("opportunities", []),
"arena": d.get("arena", []),
}
return d
def publish_file(path, content, message):
data = base64.b64encode(content).decode()
body = {"message": message, "content": data, "branch": "main"}
try:
old = gitea("GET", "/repos/%s/contents/%s" % (GITEA_REPO, path))
if old.get("sha"):
body["sha"] = old["sha"]
except Exception:
pass
res = gitea("PUT", "/repos/%s/contents/%s" % (GITEA_REPO, path), body)
return {"path": path, "url": (res.get("content") or {}).get("html_url"), "sha": (res.get("content") or {}).get("sha")}
def publish_gitea():
d = bundle()
raw = json.dumps(d, ensure_ascii=False, indent=2, default=str).encode()
out = [publish_file("audit-360.json", raw, "Audit 360: JSON snapshot")]
md = Path("/root/buryan-infra/ops/audit/reports/AUDIT-360-%s.md" % d.get("id"))
if md.exists():
out.append(publish_file("AUDIT-360.md", md.read_bytes(), "Audit 360: report"))
return {"ok": True, "files": out}
def export_markdown():
d = bundle()
lines = ["# Audit 360 export", "", "Generated: %s" % d.get("generated_at"), ""]
lines += ["## Findings", ""]
for x in d.get("findings") or []:
lines.append("- [%s] %s — `%s`" % (x.get("severity"), x.get("title"), x.get("evidence") or ""))
lines += ["", "## Capabilities", ""]
for x in d.get("capabilities") or []:
lines.append("- %s: maturity %s, leverage %s, criticality %s. %s" % (x.get("title"), x.get("maturity"), x.get("leverage"), x.get("criticality"), x.get("gaps") or ""))
lines += ["", "## Opportunities", ""]
for x in d.get("opportunities") or []:
lines.append("- %s (I%s/E%s/R%s): %s" % (x.get("title"), x.get("impact"), x.get("effort"), x.get("risk"), x.get("hypothesis") or ""))
lines += ["", "## Arena", ""]
for x in d.get("arena") or []:
lines.append("- %s [%s] score %s" % (x.get("title"), x.get("voices"), x.get("score")))
return "\n".join(lines).encode()
HTML = """<!doctype html><html lang=ru><head><meta charset=utf-8><title>Audit 360 — Buryans Hub</title>
<style>body{background:#0d1117;color:#e6edf3;font:14px/1.5 -apple-system,Segoe UI,Arial;margin:0;padding:28px}h1{font-size:24px;margin:0 0 6px}h2{font-size:16px;margin:22px 0 8px}.mut{color:#8b949e}.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:16px;margin:12px 0}table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:7px;border-bottom:1px solid #21262d;vertical-align:top}th{color:#8b949e;font-weight:500}.tag{display:inline-block;padding:1px 7px;border-radius:20px;background:#21262d;font-size:12px}.bad{background:#3d1518;color:#ffb4ab}.ok{background:#12351f;color:#7ee787}.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.stat{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:12px}.n{font-size:24px;font-weight:700}.l{color:#8b949e;font-size:12px}a{color:#58a6ff}</style></head><body>
<h1>Audit 360 <span class=mut>Buryans Hub</span></h1>
<div style="margin:8px 0"><a href="/api/export" download>Скачать JSON</a> · <a href="/api/export.md" download>Скачать Markdown</a> · <button onclick="publishGitea()">Publish Gitea</button></div>
<div class=mut id=meta>загрузка…</div>
<div id=out></div>
<script>
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
let OWNERS=[];
async function post(path,body){const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});const d=await r.json();if(!d.ok)alert(d.error||'error');else location.reload();}
function setFinding(id,title){const owner=prompt('Владелец: '+title+' | '+OWNERS.join(' | '));if(owner===null)return;const status=prompt('Статус: open / accepted / in_progress / fixed / wontfix','open');if(status===null)return;post('/api/finding',{id:id,owner:owner,status:status});}
function newDecision(fid,title){const rationale=prompt('Почему решаем: '+title);if(rationale===null)return;const alternatives=prompt('Альтернативы / что отвергли','')||'';const owner=prompt('Владелец решения | '+OWNERS.join(' | '),'')||'';post('/api/decision',{finding_id:fid,title:title,rationale:rationale,alternatives:alternatives,owner:owner,status:'proposed'});}
function newExperiment(did){const title=prompt('Название эксперимента');if(!title)return;const hypothesis=prompt('Гипотеза','')||'';const metric=prompt('Метрика','')||'';const baseline=prompt('Baseline','')||'';const target=prompt('Target','')||'';post('/api/experiment',{decision_id:did,title:title,hypothesis:hypothesis,metric:metric,baseline:baseline,target:target,status:'planned'});}
function runExperiment(id){const status=prompt('Статус: planned / running / done / failed','running');if(!status)return;const result=prompt('Результат','')||'';post('/api/experiment/status',{id:id,status:status,result:result});}
function setDecision(id){const status=prompt('Статус: proposed / accepted / in_progress / done / dropped / backlog','in_progress');if(!status)return;const review=prompt('Дата пересмотра YYYY-MM-DD (можно пусто)','')||'';post('/api/decision/status',{id:id,status:status,review_at:review||null});}
function decisionGitea(id){post('/api/gitea/decision',{id:id});}
function sprintStatus(code){const status=prompt('Статус: open / in_progress / waiting_user / blocked / done / dropped','in_progress');if(!status)return;const comment=prompt('Комментарий к статусу'+(status==='done'?' (обязателен)':''),'')||'';post('/api/sprint/status',{code:code,status:status,comment:comment});}
function sprintComment(code){const body=prompt('Комментарий к '+code);if(!body)return;post('/api/sprint/comment',{code:code,body:body});}
function giteaIssue(id){post('/api/gitea/finding',{id:id});}
function giteaAssign(id){post('/api/gitea/assign',{id:id});}
function giteaSync(){post('/api/gitea/sync',{});}
async function publishGitea(){const r=await fetch('/api/gitea/publish',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});const d=await r.json();if(!d.ok)alert(d.error||'error');else alert('Опубликовано: '+(d.files||[]).map(x=>x.url).join(' | '));}
async function loadGraph(node){
const r=await fetch('/api/graph?node='+encodeURIComponent(node||'')); const d=await r.json(); const out=document.getElementById('gout');
if(!d.ok){out.textContent=d.error||'error';return}
out.innerHTML='<div class=mut>узлов '+d.nodes_total+' · связей '+d.edges_total+' · показано '+d.links.length+'</div>'+
(d.links.length?'<table><thead><tr><th>Откуда</th><th>Куда</th><th>Тип</th></tr></thead><tbody>'+d.links.map(x=>`<tr><td><button class=gbtn data-n="${e(x.src)}">${e(x.src)}</button></td><td><button class=gbtn data-n="${e(x.dst)}">${e(x.dst)}</button></td><td class=mut>${e(x.kind)}</td></tr>`).join('')+'</tbody></table>':'<div class=mut>связей нет</div>');
document.querySelectorAll('#gout .gbtn').forEach(b=>b.onclick=()=>loadGraph(b.dataset.n));
}
fetch('/api/audit').then(r=>r.json()).then(d=>{
OWNERS=(d.owners||[]).map(x=>x.name+' <'+(x.email||x.role||'')+'>');
if(!d.ok){document.getElementById('out').innerHTML='<div class=card>'+e(d.error||'нет данных')+'</div>';return}
document.getElementById('meta').textContent='run '+d.id+' · '+d.status;
const high=(d.findings||[]).filter(x=>x.severity==='high').length;
const f=(d.findings||[]).map(x=>`<tr><td><span class="tag ${x.severity==='high'?'bad':''}">${e(x.severity)}</span></td><td>${e(x.area)}</td><td><b>${e(x.title)}</b><div class=mut>${e(x.evidence||'')}</div></td><td>${e(x.owner||'—')}<br><span class=tag>${e(x.status||'open')}</span></td><td><button onclick="setFinding(${x.id},${JSON.stringify(x.title).replace(/"/g,'&quot;')})">Владелец</button> <button onclick="newDecision(${x.id},${JSON.stringify(x.title).replace(/"/g,'&quot;')})">Решение</button> ${x.gitea_issue_url?'<a href="'+e(x.gitea_issue_url)+'" target=_blank>Gitea #'+x.gitea_issue_number+'</a> <button onclick="giteaAssign('+x.id+')">Assign</button>':'<button onclick="giteaIssue('+x.id+')">Gitea</button>'}</td></tr>`).join('');
const c=(d.capabilities||[]).map(x=>`<tr><td><b>${e(x.title)}</b></td><td>${x.maturity}</td><td>${x.automation}</td><td>${x.leverage}</td><td>${x.criticality}</td><td class=mut>${e(x.gaps||'')}</td></tr>`).join('');
const o=(d.opportunities||[]).map(x=>`<tr><td><b>${e(x.title)}</b></td><td>${e(x.capability||'')}</td><td>${x.impact}</td><td>${x.effort}</td><td>${x.risk}</td><td class=mut>${e(x.hypothesis||'')}</td></tr>`).join('');
const a=(d.arena||[]).map(x=>`<tr><td><b>${e(x.title)}</b></td><td>${e(x.capability||'')}</td><td>${e(x.voices||'')}</td><td>${x.impact}/${x.effort}/${x.risk}</td><td>${e(x.score)}</td></tr>`).join('');
const cm=Object.fromEntries((d.sprint_comments||[]).map(x=>[x.code,x.n]));
const spr=(d.sprint||[]).map(x=>`<tr><td><b>${e(x.code)}</b><div class=mut>${e(x.phase)}</div></td><td>${e(x.title)}<div class=mut>${e(x.detail||'')}</div></td><td><span class="tag ${x.status==='done'?'ok':x.requires_user?'bad':''}">${e(x.status)}</span>${x.requires_user?' <span class="tag bad">USER</span>':''}</td><td>${e(x.owner||'—')}</td><td>${e(x.evidence||'')}<div class=mut>${e(x.user_action||'')}</div></td><td>${cm[x.code]||0}</td><td><button onclick="sprintStatus('${x.code}')">Статус</button> <button onclick="sprintComment('${x.code}')">Коммент</button></td></tr>`).join('');
const dec=(d.decisions||[]).map(x=>`<tr><td>${x.id}</td><td><b>${e(x.title)}</b><div class=mut>${e(x.rationale||'')}</div></td><td>${e(x.owner||'—')}</td><td><span class=tag>${e(x.status)}</span></td><td>${e(x.review_at||'')}</td><td><button onclick="newExperiment(${x.id})">Эксперимент</button> <button onclick="setDecision(${x.id})">Статус</button> ${x.gitea_issue_url?'<a href="'+e(x.gitea_issue_url)+'" target=_blank>Gitea #'+x.gitea_issue_number+'</a>':'<button onclick="decisionGitea('+x.id+')">Gitea</button>'}</td></tr>`).join('');
const exp=(d.experiments||[]).map(x=>`<tr><td>${x.id}</td><td><b>${e(x.title)}</b><div class=mut>${e(x.hypothesis||'')}</div></td><td>${e(x.metric||'')}</td><td>${e(x.status)}</td><td>${e(x.verification||'pending')}${x.verify_run_id?' · run '+x.verify_run_id:''}</td><td>${e(x.result||'')}</td><td><button onclick="runExperiment(${x.id})">Статус</button></td></tr>`).join('');
const sem=(d.semantic||[]).map(x=>`<tr><td>${e(x.name)}</td><td><span class="tag ${x.ok?'ok':'bad'}">${x.ok?'OK':'FAIL'}</span></td><td>${x.status??'—'}</td><td>${x.latency_ms??'—'} ms</td><td class=mut>${e(x.error||'')}</td></tr>`).join('');
const df=d.diff||{};
const difRows=[...(df.new||[]).map(x=>'<span class="tag bad">NEW</span> '+e(x.title)),...(df.resolved||[]).map(x=>'<span class="tag ok">RESOLVED</span> '+e(x.title)),...(df.changed||[]).map(x=>'<span class="tag">CHANGED</span> '+e(x.title))];
const dif=difRows.length?difRows.join('<br>'):'<span class=mut>изменений нет</span>';
const m=d.metrics||{};
document.getElementById('out').innerHTML=`<div class=stats><div class=stat><div class=n>${m.findings||0}</div><div class=l>findings · ${high} high</div></div><div class=stat><div class=n>${m.owned||0}</div><div class=l>с владельцем</div></div><div class=stat><div class=n>${m.decisions||0}</div><div class=l>решений</div></div><div class=stat><div class=n>${m.experiments||0}</div><div class=l>экспериментов · ${m.experiments_done||0} done</div></div></div>
<div class=card><h2>Sprint tracker · ${m.sprint_done||0}/${m.sprint||0} done · ${m.sprint_user||0} требуют Романа</h2><div class=mut>Каждый пункт нумерован. Закрытие — только с комментарием.</div><table><thead><tr><th>Код</th><th>Задача</th><th>Статус</th><th>Owner</th><th>Evidence / действие</th><th>Комм.</th><th></th></tr></thead><tbody>${spr}</tbody></table></div>
<div class=card><h2>Findings <button onclick=giteaSync()>Sync Gitea</button></h2><table><thead><tr><th>Severity</th><th>Area</th><th>Факт</th><th>Owner / status</th><th></th></tr></thead><tbody>${f}</tbody></table></div>
<div class=card><h2>Diff ${df.from||''} → ${df.to||''}</h2><div class=mut>new ${df.counts?.new||0} · resolved ${df.counts?.resolved||0} · changed ${df.counts?.changed||0}</div><div style="margin-top:8px">${dif}</div></div>
<div class=card><h2>Граф</h2><div class=mut>Клик по узлу — показать его связи.</div><div style="margin:6px 0"><input id=gq placeholder="узел: service:..., container:..., docker:..., endpoint:..." style="width:55%"> <button onclick="loadGraph(document.getElementById('gq').value)">Показать</button> <button onclick="loadGraph('')">Сброс</button></div><div id=gout class=mut>загрузка…</div></div>
<div class=card><h2>Semantic checks</h2><table><thead><tr><th>Service</th><th>Status</th><th>HTTP</th><th>Latency</th><th>Error</th></tr></thead><tbody>${sem||'<tr><td colspan=5 class=mut>проверок пока нет</td></tr>'}</tbody></table></div>
<div class=card><h2>Capability matrix</h2><table><thead><tr><th>Возможность</th><th>Maturity</th><th>Automation</th><th>Leverage</th><th>Criticality</th><th>Пробел</th></tr></thead><tbody>${c}</tbody></table></div>
<div class=card><h2>Opportunity portfolio</h2><table><thead><tr><th>Идея</th><th>Capability</th><th>I</th><th>E</th><th>R</th><th>Гипотеза</th></tr></thead><tbody>${o}</tbody></table></div>
<div class=card><h2>Arena 360</h2><table><thead><tr><th>Идея</th><th>Capability</th><th>Голоса</th><th>I/E/R</th><th>Score</th></tr></thead><tbody>${a}</tbody></table></div>
<div class=card><h2>Решения</h2><table><thead><tr><th>ID</th><th>Решение</th><th>Владелец</th><th>Статус</th><th>Пересмотр</th><th></th></tr></thead><tbody>${dec||'<tr><td colspan=6 class=mut>решений пока нет</td></tr>'}</tbody></table></div>
<div class=card><h2>Эксперименты</h2><table><thead><tr><th>ID</th><th>Эксперимент</th><th>Метрика</th><th>Статус</th><th>Верификация</th><th>Результат</th><th></th></tr></thead><tbody>${exp||'<tr><td colspan=7 class=mut>экспериментов пока нет</td></tr>'}</tbody></table></div>`;
loadGraph('');
});
</script></body></html>"""
class H(BaseHTTPRequestHandler):
def _allowed(self):
user = (self.headers.get("X-Audit-User") or self.headers.get("X-Audit-User-Name")
or self.headers.get("X-Auth-Request-Email") or "").strip().lower()
gateway = self.headers.get("X-Audit-Gateway") == "1"
if not user and not gateway and self.client_address[0] in ("127.0.0.1", "::1"):
return True
return user in ALLOWED_EMAILS
def _deny(self):
print("AUDIT_DENY path=%s user=%r name=%r client=%s" % (
self.path, self.headers.get("X-Audit-User"), self.headers.get("X-Audit-User-Name"),
self.client_address[0]), flush=True)
data = b"forbidden: Audit 360 access is restricted"
self.send_response(403)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers(); self.wfile.write(data)
def do_GET(self):
if not self._allowed():
return self._deny()
if self.path.startswith("/api/graph"):
q = parse_qs(urlparse(self.path).query)
data = json.dumps(graph_data(q.get("node", [""])[0]), ensure_ascii=False, default=str).encode()
self.send_response(200); self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return
if self.path.startswith("/api/diff"):
q = parse_qs(urlparse(self.path).query)
data = json.dumps(diff_data(q.get("from", [None])[0], q.get("to", [None])[0]), ensure_ascii=False, default=str).encode()
self.send_response(200); self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return
if self.path.startswith("/api/export.md"):
data = export_markdown()
self.send_response(200); self.send_header("Content-Type", "text/markdown; charset=utf-8")
self.send_header("Content-Disposition", "attachment; filename=AUDIT-360.md")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return
if self.path.startswith("/api/export"):
data = json.dumps(bundle(), ensure_ascii=False, indent=2, default=str).encode()
self.send_response(200); self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Disposition", "attachment; filename=audit-360.json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data); return
if self.path.startswith("/api/audit"):
try:
data = json.dumps(api_data(), ensure_ascii=False, default=str).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers(); self.wfile.write(data)
except Exception as e:
data = json.dumps({"ok": False, "error": str(e)[:300]}, ensure_ascii=False).encode()
self.send_response(500); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(data)
return
if self.path.startswith("/health"):
self.send_response(200); self.end_headers(); self.wfile.write(b"ok"); return
data = HTML.encode()
self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
def do_POST(self):
if not self._allowed():
return self._deny()
try:
n = int(self.headers.get("Content-Length") or 0)
p = json.loads(self.rfile.read(n).decode() or "{}")
c = db(); cur = c.cursor()
if self.path == "/api/gitea/finding":
res = gitea_issue_for_finding(int(p.get("id")))
c.close()
data = json.dumps(res, ensure_ascii=False).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
return
if self.path == "/api/gitea/decision":
res = gitea_issue_for_decision(int(p.get("id")))
c.close()
data = json.dumps(res, ensure_ascii=False).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
return
if self.path == "/api/decision/status":
cur.execute("update audit.decisions set status=%s,review_at=coalesce(%s,review_at),updated_at=now() where id=%s",
(p.get("status") or "proposed", p.get("review_at") or None, int(p.get("id"))))
elif self.path == "/api/gitea/assign":
res = gitea_assign_for_finding(int(p.get("id")))
c.close()
data = json.dumps(res, ensure_ascii=False).encode()
self.send_response(200 if res.get("ok") else 400); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
return
if self.path == "/api/gitea/publish":
res = publish_gitea()
c.close()
data = json.dumps(res, ensure_ascii=False).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
return
if self.path == "/api/gitea/sync":
res = gitea_sync()
c.close()
data = json.dumps(res, ensure_ascii=False).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
return
if self.path == "/api/sprint/status":
code = str(p.get("code") or "").strip()
status = str(p.get("status") or "open")
comment = str(p.get("comment") or "").strip()
if not code:
raise RuntimeError("sprint code required")
if status == "done" and not comment:
raise RuntimeError("comment required to close sprint item")
cur.execute("""update audit.sprint_items set status=%s,evidence=coalesce(%s,evidence),
user_action=coalesce(%s,user_action),requires_user=coalesce(%s,requires_user),
updated_at=now(),closed_at=case when %s='done' then now() else null end where code=%s""",
(status, p.get("evidence") or None, p.get("user_action") or None,
p.get("requires_user"), status, code))
if cur.rowcount == 0:
raise RuntimeError("sprint item not found")
if comment:
cur.execute("insert into audit.sprint_comments(code,author,body) values(%s,%s,%s)",
(code, p.get("author") or "agent", comment))
c.commit(); c.close()
data = json.dumps({"ok": True, "code": code, "status": status}, ensure_ascii=False).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
return
if self.path == "/api/sprint/comment":
code = str(p.get("code") or "").strip()
body = str(p.get("body") or "").strip()
if not code or not body:
raise RuntimeError("code and body required")
cur.execute("insert into audit.sprint_comments(code,author,body) values(%s,%s,%s)",
(code, p.get("author") or "agent", body))
cur.execute("update audit.sprint_items set updated_at=now() where code=%s", (code,))
c.commit(); c.close()
data = json.dumps({"ok": True}, ensure_ascii=False).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
return
if self.path == "/api/finding":
cur.execute("update audit.findings set owner=%s,status=%s,updated_at=now() where id=%s",
(p.get("owner") or None, p.get("status") or "open", int(p.get("id"))))
elif self.path == "/api/decision":
cur.execute("""insert into audit.decisions(run_id,finding_id,title,rationale,alternatives,owner,status,review_at)
values(1,%s,%s,%s,%s,%s,%s,%s) returning id""",
(p.get("finding_id"), p.get("title") or "Решение", p.get("rationale") or "",
p.get("alternatives") or "", p.get("owner") or "", p.get("status") or "proposed", p.get("review_at") or None))
did = cur.fetchone()[0]
elif self.path == "/api/experiment":
cur.execute("""insert into audit.experiments(decision_id,title,hypothesis,metric,baseline,target,status)
values(%s,%s,%s,%s,%s,%s,%s) returning id""",
(p.get("decision_id"), p.get("title") or "Эксперимент", p.get("hypothesis") or "",
p.get("metric") or "", p.get("baseline") or "", p.get("target") or "", p.get("status") or "planned"))
did = cur.fetchone()[0]
elif self.path == "/api/experiment/status":
cur.execute("""update audit.experiments set status=%s,result=%s,
started_at=coalesce(started_at,case when %s='running' then now() end),
finished_at=case when %s in ('done','failed') then now() else finished_at end where id=%s""",
(p.get("status") or "planned", p.get("result") or "", p.get("status"), p.get("status"), int(p.get("id"))))
else:
raise RuntimeError("unknown endpoint")
c.commit(); c.close()
data = json.dumps({"ok": True}, ensure_ascii=False).encode()
self.send_response(200); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
except Exception as e:
data = json.dumps({"ok": False, "error": str(e)[:300]}, ensure_ascii=False).encode()
self.send_response(500); self.send_header("Content-Type", "application/json")
self.end_headers(); self.wfile.write(data)
def log_message(self, fmt, *args):
pass
if __name__ == "__main__":
ThreadingHTTPServer((HOST, PORT), H).serve_forever()