"""Find related Confluence/Jira docs for a meeting via twg; writes out//docs.json. Never fails the flow.""" import json, os, re, shutil, subprocess # report: chat() helper, TICKET regex, JIRA_BROWSE; llama: proxy address. import db, llama, report # twg CLI: from PATH, else the default per-user install location. TWG = shutil.which("twg") or os.path.expandvars(r"%LOCALAPPDATA%\Programs\twg\bin\twg.exe") # Prompt: 4 short search queries (3-6 words) from the meeting description. 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.' # Prompt: relevance score 0-3 for each numbered candidate doc. 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).' # Full Jira key match (anchored). KEY = re.compile(r"^[A-Z][A-Z0-9]{1,9}-\d{1,6}$") # Confluence checkbox line ("* [ ] text" or "* [x] text"); group 1 = text. Used to harvest people names. PEOPLE = re.compile(r"^\s*\* \[[ xX]\] (.+?)\s*$", re.M) # Run twg. Returns parsed JSON for "-o json" calls, else stdout (None on failure). # Retries once through the proxy when the failure looks like a network/proxy error. def _twg(*args, timeout=120): # Child env without Python home vars that would confuse twg. 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) # JSON mode: parse stdout; twg may instead print a YAML envelope pointing at a spooled file. 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 # Plain-text mode: stdout only on success. else: out = r.stdout if r.returncode == 0 else None # Stop unless this is the first attempt and stderr looks like a network/proxy error. if out is not None or attempt or not re.search(r"(?i)ECONN|ETIMEDOUT|network|certificate|proxy", r.stderr): return out # Second attempt goes through the proxy. env = {**env, "HTTPS_PROXY": llama.PROXY, "HTTP_PROXY": llama.PROXY} # Gather candidate docs for a meeting: queries, Confluence/Jira search, Jira key lookups, LLM relevance scoring. # Returns the docs.json payload; raises on hard failure (run() catches it). def _run(name): if not os.path.exists(TWG): raise FileNotFoundError("twg not found") # Per-meeting output directory. 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 # Titles of lead content screens: deduped, max 30. 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 "" # Meeting description for the LLM: title, screen titles, glossary, first 800 words of transcript. desc = f"Titolo: {title}\nSchermate: {'; '.join(screens)}\nGlossario: {', '.join(gl[:40])}\nTrascrizione (inizio): {' '.join(txt.split()[:800])}" # Title is always a query; add up to 4 LLM-generated ones. 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)] # Case-insensitive de-dup of queries. queries = list({q.lower(): q for q in reversed(queries)}.values())[::-1] # Candidates keyed by URL across all queries. cand = {} for q in queries: # Confluence: up to 6 hits per query; Jira: up to 4. 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 []: # Skip results without a URL or already seen. u = it.get("url") if not u or u in cand: continue # Jira key from /browse/KEY-N URLs; Confluence page id from /pages/ID URLs. 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()) # Text to scan for ticket keys: transcript plus shot OCR text. blob = [txt] + [s.get("text") or "" for s in shots] # Ticket keys found in the content (valid format), then keys already on candidates. 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] # Keys literally mentioned in the meeting content. mentioned = set(k for k in keys if k in {m for b in blob for m in report.TICKET.findall(b)}) # Jira lookup: summary + status for keys, one batch of up to 26. known = {} # Only call twg when there are keys. 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 "") # Apply Jira summary/status to candidates that have a key. for e in items: if e["key"] in known: e["title"], e["status"] = known[e["key"]] # Add mentioned Jira tickets not already in items. 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}) # Flag items mentioned in the meeting and resolved in Jira. for e in items: e["mentioned"] = e["mentioned"] or bool(e["key"] in mentioned and e["key"] in known) # Relevance: LLM scores non-mentioned items; missing score = 0. scores = {} rel = [e for e in items if not e["mentioned"]] # Only score non-mentioned items, if any. if rel: # Numbered candidate list appended to the meeting description. u = desc + "\n\nDOCUMENTI:\n" + "\n".join(f"[{i}] {e['title']} — {e['snippet'][:300]}" for i, e in enumerate(rel)) # Score indices refer to positions in 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 # Non-mentioned items keep the LLM score (0 if missing). for i, e in enumerate(rel): e["score"] = scores.get(i, 0) # Mentioned items score 3 unless already set. for e in items: e.setdefault("score", 3 if e["mentioned"] else 0) # Keep mentioned items plus those scored >= 2, best first. keep = sorted([e for e in items if e["mentioned"] or e["score"] >= 2], key=lambda e: -e["score"]) # Cap per source: 8 Confluence; Jira: up to 6 non-mentioned plus all mentioned. 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 # Fetch Confluence bodies (markdown, 6000 chars max); Jira items get a one-line body. 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 "" # twg prefixes the body with a "Content loaded." banner line; drop it. 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']})" # Stable index used to reference docs from report.py. for i, e in enumerate(keep): e["i"] = i # People names: checkbox lines in bodies, multi-word only, deduped. 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} # Entry point. Never fails the flow: errors are recorded in docs.json (error field) instead of raised. 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")