"""Find related Confluence/Jira docs for a meeting via twg; writes out//docs.json. Never fails the flow.""" import json, os, re, shutil, subprocess import db, llama, report TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe") SYS_Q = 'Genera query di ricerca per trovare documentazione aziendale (Confluence/Jira) collegata a questa riunione. Rispondi SOLO JSON: {"queries":[str]} con 4 query brevi (3-6 parole) usando i termini come appaiono nel testo.' SYS_R = 'Valuta la pertinenza di ogni documento rispetto alla riunione descritta. Rispondi SOLO JSON: {"scores":[{"i":int,"score":int}]} con score 0 (non pertinente) … 3 (stesso argomento/progetto).' KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$") PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M) def _twg(*args, timeout=120): env = {k: v for k, v in os.environ.items() if k not in ("PYTHONHOME", "UV_INTERNAL__PYTHONHOME")} for attempt in range(2): r = subprocess.run([TWG, *args], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, env=env) if "-o" in args and "json" in args: try: return json.loads(r.stdout) # rovo exits 3 on partial results but still prints JSON except ValueError: out = None # twg >= 1.3 spools large results to a file and prints a YAML envelope: output_files: stdout: "" if (m := re.search(r'^\s*stdout:\s*"(.+?\.json)"', r.stdout, re.M)): try: return json.loads(open(m[1].replace("\\\\", "\\"), encoding="utf-8").read()) except (OSError, ValueError): pass else: out = r.stdout if r.returncode == 0 else None if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY} def _run(name): if not os.path.exists(TWG): raise FileNotFoundError("twg not found") d = db.out_dir(name) meta = [json.loads(e["text"]) for e in db.events(name, "meta") if e["who_key"] != "video"] # Teams topic only, never a shot guess title = (meta[-1].get("title") or "") if meta else "" shots = json.loads((d / "shots.json").read_text(encoding="utf-8")) if (d / "shots.json").exists() else [] gl = json.loads((d / "glossary.json").read_text(encoding="utf-8")) if (d / "glossary.json").exists() else [] from shots import CONTENT_KINDS screens = list(dict.fromkeys(s["title"] for s in shots if s.get("lead") and s["kind"] in CONTENT_KINDS and s.get("title")))[:30] tx = db.out_dir(name) / "transcript.txt" txt = tx.read_text(encoding="utf-8") if tx.exists() else "" desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}" queries = [title] if title else [] queries += [q for q in ((report.chat(SYS_Q, desc, 400) or {}).get("queries") or [])[:4] if isinstance(q, str)] queries = list({q.lower(): q for q in reversed(queries)}.values())[::-1] cand = {} for q in queries: for app, lim in (("confluence", 6), ("jira", 4)): for it in (_twg("rovo", "search", q, "--app", app, "--limit", str(lim), "-o", "json") or {}).get("items") or []: u = it.get("url") if not u or u in cand: continue jk = re.search(r"/browse/([A-Z][A-Z0-9]+-\d+)", u); cid = re.search(r"/pages/(\d+)", u) cand[u] = {"source": "jira" if "/browse/" in u else "confluence", "key": jk[1] if jk else None, "id": cid[1] if cid else None, "title": it.get("title") or "", "url": u, "status": None, "snippet": (it.get("snippet") or "")[:400], "mentioned": False} items = list(cand.values()) blob = [txt] + [s.get("text") or "" for s in shots] keys = [k for k in dict.fromkeys(m for b in blob for m in report.TICKET.findall(b)) if KEY.match(k)] keys += [k for k in (e["key"] for e in items) if k and k not in keys] mentioned = set(k for k in keys if k in {m for b in blob for m in report.TICKET.findall(b)}) known = {} if keys[:20 + 6]: r = _twg("jira", "workitem", "get", *keys[:26], "-o", "json") or {} for it in (r.get("data") or {}).get("items") or []: if it.get("ok") and it.get("data"): x = it["data"]; known[x["key"]] = (x.get("summary") or "", (x.get("status") or {}).get("name") or "") for e in items: if e["key"] in known: e["title"], e["status"] = known[e["key"]] have = {e["key"] for e in items if e["key"]} for k in keys: if k in known and k in mentioned and k not in have: items.append({"source": "jira", "key": k, "id": None, "title": known[k][0], "url": f"{report.JIRA_BROWSE}/{k}", "status": known[k][1], "snippet": "", "mentioned": True}) for e in items: e["mentioned"] = e["mentioned"] or bool(e["key"] in mentioned and e["key"] in known) scores = {} rel = [e for e in items if not e["mentioned"]] if rel: u = desc + "\n\nDOCUMENTI:\n" + "\n".join(f"[{i}] {e['title']} — {e['snippet'][:300]}" for i, e in enumerate(rel)) for s in (report.chat(SYS_R, u, 800) or {}).get("scores") or []: try: scores[int(s["i"])] = int(s["score"]) except (KeyError, TypeError, ValueError): pass for i, e in enumerate(rel): e["score"] = scores.get(i, 0) for e in items: e.setdefault("score", 3 if e["mentioned"] else 0) keep = sorted([e for e in items if e["mentioned"] or e["score"] >= 2], key=lambda e: -e["score"]) conf = [e for e in keep if e["source"] == "confluence"][:8] jira = [e for e in keep if e["source"] == "jira" and not e["mentioned"]][:6] + [e for e in keep if e["mentioned"]] keep = conf + jira for e in keep: if e["source"] == "confluence" and e["id"]: b = _twg("confluence", "content", "get", e["id"], "--detail", "full", "--format", "md", "--body-only") or "" lines = b.splitlines() if lines and lines[0].strip() == "+ Content loaded.": lines = lines[1:] e["body"] = "\n".join(lines)[:6000] else: e["body"] = f"{e['key']} {e['title']} ({e['status']})" for i, e in enumerate(keep): e["i"] = i people = [] for e in keep: for m in PEOPLE.finditer(e["body"]): n = db.norm_name(m[1]) if " " in n and n not in people: people.append(n) return {"queries": queries, "items": keep, "people": people, "error": None} def run(name): try: out = _run(name) except Exception as e: print("docs failed:", repr(e), flush=True) out = {"queries": [], "items": [], "people": [], "error": repr(e)[:300]} (db.out_dir(name) / "docs.json").write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")