Lara Monteagudo Tubau commited on
Commit ·
d176097
1
Parent(s): 893ae76
Update Script pipeline and coding flow
Browse filesFiles changed (6)
- agent1a_boundary.py+79-7
- agent1b_coder.py+156-14
- app.py+400-152
- kappa_calculator.py+599-296
- llm_client.py+253-28
- pipeline.pyAdded+409
73 unmodified lines747576777879808113 unmodified lines9596979899100101102103104105106107108109110111112113114115157 unmodified lines27327427573 unmodified lines# Prompt builder# ---------------------------------------------------------------------------def build_system_prompt() -> str:return """You are a discourse analyst. Your task is to identify episode boundarieswithin a section of a collaborative work transcript.An episode boundary marks where one coherent behavioral unit ends and another begins.13 unmodified lineshigh — clear boundary signal present in the transcript textmedium — likely boundary but signal is ambiguous or implicitlow — possible boundary; human reviewer should check carefullyOutput ONLY valid JSON — no preamble, no explanation outside the JSON:{"section_id": "s01","boundaries": [{"boundary_id": "b_s01_01","after_turn_id": 12,"confidence": "high | medium | low","boundary_signal": "explicit_transition | sequence_completion | activity_change | topic_exhaustion","rationale": "1 sentence citing the specific observable signal at this turn"}],"n_episodes": 4}If the entire section is one coherent episode, return an empty boundaries listand set n_episodes to 1.157 unmodified lines"n_episodes": result.get("n_episodes", len(segments)),"segments": segments,}73 unmodified lines747576777879808182838485868788899091929394959697989910010110213 unmodified lines116117118119120121122123124125126127128129130131132133134135136157 unmodified lines29429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634773 unmodified lines# Prompt builder# ---------------------------------------------------------------------------def build_system_prompt(agent0_handoff: dict | None = None) -> str:"""Build the Agent 1a system prompt, optionally enriched with Agent 0 context.The context block improves boundary detection by telling Agent 1a whatactivity type to expect in this section, reducing cold-start errorsat the edges of sections (Park et al. 2023 — agent memory passing)."""context_block = ""if agent0_handoff:context_block = f"""=== SESSION CONTEXT FROM AGENT 0 ===Session overview: {agent0_handoff.get('session_overview', '').strip()}This section ({agent0_handoff.get('section_id', '')}): {agent0_handoff.get('section_summary', '').strip()}Activity label: {agent0_handoff.get('section_label', '')}Time window: {agent0_handoff.get('start_time', '')} – {agent0_handoff.get('end_time', '')}Use this context to calibrate boundary sensitivity. A section labelled"debugging" is likely to have finer-grained boundaries than one labelled"task orientation". Do not let this context override what you observe in the text."""return f"""You are a discourse analyst. Your task is to identify episode boundarieswithin a section of a collaborative work transcript.An episode boundary marks where one coherent behavioral unit ends and another begins.13 unmodified lineshigh — clear boundary signal present in the transcript textmedium — likely boundary but signal is ambiguous or implicitlow — possible boundary; human reviewer should check carefully{context_block}Output ONLY valid JSON — no preamble, no explanation outside the JSON:{{"section_id": "s01","boundaries": [{{"boundary_id": "b_s01_01","after_turn_id": 12,"confidence": "high | medium | low","boundary_signal": "explicit_transition | sequence_completion | activity_change | topic_exhaustion","rationale": "1 sentence citing the specific observable signal at this turn"}}],"n_episodes": 4}}If the entire section is one coherent episode, return an empty boundaries listand set n_episodes to 1.157 unmodified lines"n_episodes": result.get("n_episodes", len(segments)),"segments": segments,}def propose_boundaries_with_context(section: dict,turns: list[dict],session_id: str,agent0_handoff: dict | None = None,) -> tuple[dict, object]:"""Context-aware boundary detection — for use by pipeline.py.Same as propose_boundaries() but:1. Accepts an Agent 0 handoff document to enrich the system prompt.2. Returns (result_dict, llm_stats) instead of just result_dict,so pipeline.py can track timing and token usage.The context chain (Agent 0 → Agent 1a) reduces cold-start errors atsection edges by informing Agent 1a what kind of activity it is examining.Literature: Park et al. (2023) Generative Agents; Hong et al. (2023) MetaGPT."""from llm_client import call_llm_timedprint(f"[Agent 1a] {section['section_id']} — {section.get('label','')} "f"({len(turns)} turns, context={'yes' if agent0_handoff else 'no'})...")system_prompt = build_system_prompt(agent0_handoff=agent0_handoff)user_prompt = build_user_prompt(section, turns)raw, stats = call_llm_timed(system_prompt, user_prompt, max_tokens=MAX_TOKENS)result = _parse_response(raw, section["section_id"])boundaries = result.get("boundaries", [])segments = boundaries_to_segments(section, turns, boundaries, session_id)boundary_map = {b["after_turn_id"]: b for b in boundaries}for seg in segments:seg["_boundary_before"] = boundary_map.get(seg["start_turn_id"] - 1)print(f"[Agent 1a] {section['section_id']}: "f"{len(boundaries)} boundaries → {len(segments)} episodes "f"({stats.wall_time_s:.1f}s, ~{stats.estimated_total_tok:,} tok)")return {"section_id": section["section_id"],"boundaries": boundaries,"n_episodes": result.get("n_episodes", len(segments)),"segments": segments,}, stats
163 unmodified lines1641651661671681691701711721731741751767 unmodified lines18418518618718818919019119219319419519619719819920020199 unmodified lines3013023033043053063073083093103113122 unmodified lines315316317163 unmodified lines# Prompt builders# ---------------------------------------------------------------------------def build_system_prompt(tier1: dict, tier2: dict, section: dict) -> str:return f"""You are a behavioral coding assistant trained in collaborative learning research.You are coding segments from one section of a Zoom transcript.Section context: {section['label']} — {section.get('summary', '')}Use this context to inform your interpretation, but base your final decisionsolely on observable turn content.=== DIMENSION DEFINITIONS ==={_format_dimensions(tier1['dimensions'])}7 unmodified lines=== VALIDATED LEARNINGS FROM PRIOR SESSIONS ==={_format_learned(tier2)}=== OUTPUT FORMAT ===Respond ONLY with valid JSON. Code ALL segments provided.{{"coded_segments": [{{"segment_id": "must match input segment_id exactly","dimension_id": "D1 to D9","dimension_label": "string","confident": true or false,"uncertain": true or false,"uncertainty_note": "competing dimension and why, or null","rationale": "1–2 sentences citing specific observable behaviors"}}]}}99 unmodified linescode = all_coded.get(seg["segment_id"], {})result.append({**seg,"dimension_id": code.get("dimension_id", ""),"dimension_label": code.get("dimension_label", ""),"confident": code.get("confident", False),"uncertain": code.get("uncertain", False),"uncertainty_note": code.get("uncertainty_note"),"rationale": code.get("rationale", ""),})n_uncertain = sum(1 for s in result if s.get("uncertain"))2 unmodified linesf"{n_uncertain} flagged uncertain — route to researcher review.")return result163 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102117 unmodified lines21922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725899 unmodified lines3583593603613623633643653663673683693703713722 unmodified lines375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459163 unmodified lines# Prompt builders# ---------------------------------------------------------------------------def build_system_prompt(tier1: dict,tier2: dict,section: dict,boundary_handoff: dict | None = None,) -> str:"""Build the Agent 1b system prompt, optionally enriched with Agent 1a'sboundary analysis handoff.Receiving the boundary rationale means Agent 1b knows why each episodewas carved out — it can use this to calibrate dimension assignment, e.g.if a boundary fell on a 'sequence_completion', Agent 1b knows the episodeit is coding represents a self-contained conversational act.(Hong et al. 2023 MetaGPT — structured inter-agent document passing)"""boundary_context = ""if boundary_handoff:previews = boundary_handoff.get("episode_previews", [])preview_text = "\n".join(f" {p['segment_id']}: \"{p['first_turn'][:60]}…\""for p in previews) or " (no previews)"boundary_context = f"""=== EPISODE STRUCTURE FROM AGENT 1a ===This section contains {boundary_handoff.get('n_episodes', '?')} episodescarved by {boundary_handoff.get('n_boundaries', 0)} boundaries.Boundary signals found: {boundary_handoff.get('boundary_signals', 'none')}Episode entry points:{preview_text}Use this to understand the local conversational rhythm, but base yourdimension assignment solely on observable turn content."""return f"""You are a behavioral coding assistant trained in collaborative learning research.You are coding segments from one section of a Zoom transcript.Section context: {section['label']} — {section.get('summary', '')}Use this context to inform your interpretation, but base your final decisionsolely on observable turn content.{boundary_context}=== DIMENSION DEFINITIONS ==={_format_dimensions(tier1['dimensions'])}7 unmodified lines=== VALIDATED LEARNINGS FROM PRIOR SESSIONS ==={_format_learned(tier2)}=== SECONDARY DIMENSION (optional — use sparingly) ===Collaborative discourse moves are sometimes genuinely multifunctional.If an episode PROMINENTLY exhibits a second dimension alongside the primary —not merely as a surface feature but as a sustained behavioral pattern —set secondary_dimension_id to that dimension's ID.Rules:- Use secondary ONLY when a second dimension is clearly observable and significant- Secondary must be different from primary- Do NOT use secondary instead of uncertain: true (they serve different purposes)- Most segments will have null secondary_dimension_id- Valid example: episode primarily about reaching consensus (D4) where speakersalso actively check understanding throughout → D4 primary, D1 secondarySet secondary_dimension_id to null if no secondary applies. Do not force it.This follows Strijbos et al. (2006) and Suthers & Rosen (2011): discourse movesare often multifunctional; forcing a single code loses analytical nuance.=== OUTPUT FORMAT ===Respond ONLY with valid JSON. Code ALL segments provided.{{"coded_segments": [{{"segment_id": "must match input segment_id exactly","dimension_id": "D1 to D9","dimension_label": "string","secondary_dimension_id": "D1 to D9 or null — use sparingly","secondary_dimension_label":"string or null","secondary_rationale": "1 sentence explaining why secondary applies, or null","confident": true or false,"uncertain": true or false,"uncertainty_note": "competing dimension and why, or null","rationale": "1–2 sentences citing specific observable behaviors"}}]}}99 unmodified linescode = all_coded.get(seg["segment_id"], {})result.append({**seg,"dimension_id": code.get("dimension_id", ""),"dimension_label": code.get("dimension_label", ""),"secondary_dimension_id": code.get("secondary_dimension_id"),"secondary_dimension_label":code.get("secondary_dimension_label"),"secondary_rationale": code.get("secondary_rationale"),"confident": code.get("confident", False),"uncertain": code.get("uncertain", False),"uncertainty_note": code.get("uncertainty_note"),"rationale": code.get("rationale", ""),})n_uncertain = sum(1 for s in result if s.get("uncertain"))2 unmodified linesf"{n_uncertain} flagged uncertain — route to researcher review.")return resultdef code_section_with_context(section: dict,segments: list[dict],boundary_handoff: dict | None = None,library_root=None,) -> tuple[list[dict], object]:"""Context-aware dimension coding — for use by pipeline.py.Same as code_section() but:1. Accepts an Agent 1a boundary handoff to enrich the system prompt.2. Returns (coded_segments, llm_stats) for pipeline-level tracking.The boundary handoff tells Agent 1b how the episodes were carved, so itcan better calibrate dimension assignment to the local conversationalstructure (Hong et al. 2023 MetaGPT — inter-agent document passing)."""from llm_client import call_llm_timedglobal LIBRARY_ROOT, TIER1_PATH, TIER2_PATHif library_root:LIBRARY_ROOT = library_rootTIER1_PATH = library_root / "tier1_core"TIER2_PATH = library_root / "tier2_validated"if not segments:return [], Noneprint(f"[Agent 1b] {section['section_id']} — {section.get('label','')} "f"({len(segments)} segments, boundary_ctx={'yes' if boundary_handoff else 'no'})...")tier1 = load_tier1()tier2 = load_tier2()system_prompt = build_system_prompt(tier1, tier2, section,boundary_handoff=boundary_handoff)batches = [segments[i:i + MAX_SEGS_PER_CALL]for i in range(0, len(segments), MAX_SEGS_PER_CALL)]all_coded: dict[str, dict] = {}last_stats = Nonefor batch_idx, batch in enumerate(batches):user_prompt = build_user_prompt(batch)raw, stats = call_llm_timed(system_prompt, user_prompt, max_tokens=MAX_TOKENS)last_stats = statscoded_batch = _parse_response(raw)for c in coded_batch:all_coded[c["segment_id"]] = cif len(batches) > 1:print(f"[Agent 1b] Batch {batch_idx+1}/{len(batches)} done "f"({stats.wall_time_s:.1f}s, ~{stats.estimated_total_tok:,} tok)")result = []for seg in segments:code = all_coded.get(seg["segment_id"], {})result.append({**seg,"dimension_id": code.get("dimension_id", ""),"dimension_label": code.get("dimension_label", ""),"secondary_dimension_id": code.get("secondary_dimension_id"),"secondary_dimension_label":code.get("secondary_dimension_label"),"secondary_rationale": code.get("secondary_rationale"),"confident": code.get("confident", False),"uncertain": code.get("uncertain", False),"uncertainty_note": code.get("uncertainty_note"),"rationale": code.get("rationale", ""),})n_uncertain = sum(1 for s in result if s.get("uncertain"))print(f"[Agent 1b] {section['section_id']}: {len(result)} coded, "f"{n_uncertain} uncertain "f"({last_stats.wall_time_s if last_stats else '?':.1f}s)")return result, last_stats
32 unmodified lines33343536373855 unmodified lines949596979899460 unmodified lines560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608144 unmodified lines75375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678711 unmodified lines7998008018028038047 unmodified lines81281381481581681792 unmodified lines91091191291391491591691791847 unmodified lines9669679689699709719729739749759769779789792 unmodified lines982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810796 unmodified lines10861087108810891090109110929 unmodified lines11021103110411051106110711081109111011111112111311141115111611171118111924 unmodified lines11441145114611471148114911501 unmodified line11521153115411551156115711581159116024 unmodified lines118511861187118811891190119111921193119411951196119753 unmodified lines125112521253125412551256125712581259275 unmodified lines15351536153715381539154015411542154315441545154615471548154915501551155247 unmodified lines160016011602160316041605160616071608164 unmodified lines1773177417751776177717781779178017811782178317841785178617871 unmodified line178917901791179217931794179525 unmodified lines182118221823182418251826182718281829183018311832183318341835183618372 unmodified lines18401841184218431844184518461847184818491850185118526 unmodified lines185918601861186218631864186532 unmodified linesdiscard_disagreement,)from agent2_learner import list_pending_rules, approve_rule, reject_ruleSESSIONS_ROOT = Path("sessions")_STYLES_DIR = Path(__file__).parent / "static" / "styles"55 unmodified linesDIM_ID_FROM_CHOICE = {f"{d} — {l}": d for d, l, _ in DIMENSIONS}DIM_DESC_FROM_ID = {d: desc for d, _, desc in DIMENSIONS}# ---------------------------------------------------------------------------# Speaker palette — 6 perceptually distinct colours (deuteranopia-safe pair460 unmodified linesdef _kappa_html(report: dict) -> str:kappa = report.get("overall_kappa", 0.0)interp = report.get("kappa_interpretation", "")gate = report.get("gate_passed", False)n_segs = report.get("n_segments_total", 0)n_dis = len(report.get("segments_in_disagreement", []))col = "#065f46" if gate else "#be123c"icon = "✓" if gate else "✗"pct = int(min(max(kappa, 0) * 100, 100))dim_rows = ""for dim, k in sorted((report.get("kappa_per_dimension") or {}).items()):if k is None:continuekp = int(min(max(k, 0) * 100, 100))kc = "#065f46" if k >= 0.70 else "#b45309" if k >= 0.50 else "#be123c"dim_rows += (f'<div style="display:flex;gap:8px;align-items:center;padding:3px 0;'f'border-top:1px solid #f1f5f9">'f'<span style="font-weight:700;font-size:0.82em;width:32px">{_h(dim)}</span>'f'<div style="flex:1;height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden">'f'<div style="height:100%;width:{kp}%;background:{kc};border-radius:3px"></div></div>'f'<span style="font-weight:700;font-size:0.82em;color:{kc};width:40px;text-align:right">'f'{k:.3f}</span></div>')return (f'<div style="background:white;border:1px solid #e2e8f0;border-radius:12px;padding:20px">'f'<div style="display:flex;align-items:flex-end;gap:14px;margin-bottom:8px">'f'<span style="font-size:3em;font-weight:800;color:{col};line-height:1">{kappa:.3f}</span>'f'<div><div style="font-weight:700;color:{col};font-size:1.05em">{icon} {_h(interp)}</div>'f'<div style="font-size:0.78em;color:#94a3b8">threshold κ=0.70 — Landis & Koch (1977)</div>'f'</div></div>'f'<div style="position:relative;height:10px;background:#e2e8f0;border-radius:5px;margin:10px 0">'f'<div style="position:absolute;height:100%;width:{pct}%;background:{col};border-radius:5px"></div>'f'<div style="position:absolute;left:70%;top:-4px;height:18px;width:2px;background:#94a3b8"></div>'f'<div style="position:absolute;left:70%;top:-16px;font-size:0.68em;color:#94a3b8;'f'transform:translateX(-50%)">0.70</div>'f'</div>'f'<div style="font-size:0.83em;color:#64748b;margin-bottom:14px">'f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis!=1 else ""}</div>'f'<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;'f'letter-spacing:0.07em;color:#94a3b8;margin-bottom:8px">Per-Dimension κ</div>'f'{dim_rows}</div>')144 unmodified lines# ===========================================================================def _segment_label(seg: dict, codings: dict) -> str:sid = seg["segment_id"]ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:]did = seg.get("dimension_id") or "?"coded = "✓" if codings.get(sid, {}).get("dimension_id") else "○"flag = " ⚠" if seg.get("uncertain") else ""return f"{coded} ep{ep} [{did}]{flag}"def _proposal_md(seg: dict) -> str:did = seg.get("dimension_id", "?")rat = seg.get("rationale", "")tags = []if seg.get("confident"):tags.append("✅ Confident")if seg.get("uncertain"):tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note', '')}")return f"> **AI proposal: {did}** \n> {rat}\n\n{' '.join(tags)}".strip()CODING_EMPTY = ("", # progress htmlgr.update(choices=[], value=None), # segment_jump"", # turns_display_html"", # uncertainty_htmlgr.update(value="", visible=False), # proposal_mdgr.update(choices=DIM_CHOICES, value=None), # dim_radio"", # dim_desc_html"", # comment_boxgr.update(visible=False), # next_section_btn)11 unmodified linesexisting = codings.get(sid, {})saved = existing.get("dimension_id", "")choice = next((c for c in DIM_CHOICES if c.startswith(saved)), None)all_done = len(codings) >= len(segs) and all(codings.get(s["segment_id"], {}).get("dimension_id") for s in segs)7 unmodified linesgr.update(value=_proposal_md(seg), visible=False),gr.update(choices=DIM_CHOICES, value=choice),_dim_desc_html(choice or ""),existing.get("comment", ""),gr.update(visible=all_done),)92 unmodified linesuser_prev = f"Segment {len(state['turns'])} turns into topical sections."state = dict(state)state["sections"] = sectionsstate["section_stages"] = {s["section_id"]: "pending" for s in sections}state["stage"] = "sectioned"log = _make_log_entry("Agent 0 — Structural Segmenter", rt,sections_proposed=len(sections),47 unmodified linesfor i, s in enumerate(sections)]if len(labels) != len(sections):gr.Warning(f"Label count mismatch ({len(labels)} vs {len(sections)}) — unmatched sections keep original labels.")state = dict(state)state.update({"sections": confirmed,"section_idx": 0,"section_stages": {s["section_id"]: "pending" for s in confirmed},"stage": "coding",})d = _session_dir(state)2 unmodified lines)_persist(state)sec = confirmed[0]n = sec["end_turn_id"] - sec["start_turn_id"] + 1hdr = (f"### Section 1 of {len(confirmed)}: {sec['label']}\n"f"*{sec.get('summary', '')}* · "f"turns {sec['start_turn_id']}–{sec['end_turn_id']} ({n} turns)")gr.Info(f"{len(confirmed)} sections confirmed. Detect boundaries for Section 1.")return (state,_pipeline_html("coding"),_section_cards_html(confirmed, state["section_stages"], 0),hdr,gr.update(visible=True), # col_section_workgr.update(visible=True), # col_boundary_btngr.update(visible=False), # col_boundary_reviewgr.update(visible=False), # col_coding)# ── Stage 3a: Agent 1a ────────────────────────────────────────────────────────def fn_propose_boundaries(state: dict):sec = _current_section(state)if not sec:raise gr.Error("No section loaded.")turns = _turns_for_section(state["turns"], sec)if not turns:raise gr.Error(f"No turns found for section {sec['section_id']}.")yield state, "⏳ Detecting episode boundaries…", gr.update(visible=False), "", "", ""t0 = time.perf_counter()try:result = propose_boundaries(section=sec, turns=turns,session_id=state["session_id"])except Exception as e:raise gr.Error(f"Agent 1a failed: {e}") from ert = round(time.perf_counter() - t0, 1)from agent1a_boundary import build_system_prompt as a1a_sysfrom agent1a_boundary import build_user_prompt as a1a_usersys_prev = a1a_sys()[:120]user_prev = f"Section: {sec['section_id']} — {sec['label']} ({len(turns)} turns)"boundaries = result["boundaries"]n_low = sum(1 for b in boundaries if b.get("confidence") == "low")if n_low:gr.Warning(f"{n_low} low-confidence boundary{'ies' if n_low>1 else ''} — review carefully.")state = dict(state)state["section_boundaries"][sec["section_id"]] = boundariesstate["section_segments"][sec["section_id"]] = result["segments"]state["section_stages"][sec["section_id"]] = "boundaries"log = _make_log_entry("Agent 1a — Boundary Detector", rt,boundaries_proposed=len(boundaries),episodes=len(result["segments"]),low_confidence=n_low,system_prompt_preview=sys_prev,user_prompt_preview=user_prev,)state = _push_log(state, log)ids_text = ", ".join(str(b["after_turn_id"]) for b in boundaries)status = (f"**{len(boundaries)} boundary{'ies' if len(boundaries)!=1 else ''} proposed "f"→ {len(result['segments'])} episodes.** \n"f"Review the episode table, edit turn IDs if needed, then confirm.")gr.Info(f"{len(boundaries)} boundaries detected in {rt}s.")yield (state,status,gr.update(visible=True),_episode_table_html(turns, boundaries),ids_text,_agent_log_html(state["agent_logs"]),)# ── Stage 3b: Confirm + Agent 1b ─────────────────────────────────────────────def fn_confirm_and_code(boundary_ids_text: str, state: dict):sec = _current_section(state)if not sec:raise gr.Error("No section loaded.")turns = _turns_for_section(state["turns"], sec)valid_ids = {t["turn_id"] for t in turns}boundaries: list[dict] = []6 unmodified linesexcept ValueError:raise gr.Error(f"'{tok}' is not a valid turn ID.")if tid not in valid_ids:raise gr.Error(f"Turn {tid} is outside this section (range {min(valid_ids)}–{max(valid_ids)}).")boundaries.append({"boundary_id": f"r_{tid}", "after_turn_id": tid,"confidence": "high", "boundary_signal": "researcher_defined","rationale": "Set by researcher."})9 unmodified linesyield state, f"⏳ Agent 1b coding {len(segments)} episode(s)…", gr.update(visible=False), *CODING_EMPTY, ""t0 = time.perf_counter()try:coded = code_section(section=sec, segments=segments)except Exception as e:raise gr.Error(f"Agent 1b failed: {e}") from ert = round(time.perf_counter() - t0, 1)from agent1b_coder import build_system_prompt as a1b_sys, load_tier1, load_tier2tier1 = load_tier1()tier2 = load_tier2()sys_prev = a1b_sys(tier1, tier2, sec)[:120]user_prev = f"Code {len(segments)} segments in section: {sec['label']}"n_uncertain = sum(1 for s in coded if s.get("uncertain"))24 unmodified lines# ── Navigate segments ─────────────────────────────────────────────────────────def fn_navigate(direction: int, dim_choice: str, comment: str, state: dict):segs = _current_section_segments(state)if not segs:return state, *_render_coding(state)1 unmodified linecodings = dict(state.get("codings", {}))sid = segs[idx]["segment_id"]if dim_choice:codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice], "comment": comment.strip()}state = dict(state)state["codings"] = codingsstate["coding_idx"] = max(0, min(idx + direction, len(segs) - 1))return state, *_render_coding(state)24 unmodified lines# ── Next section ──────────────────────────────────────────────────────────────def fn_next_section(dim_choice: str, comment: str, state: dict):segs = _current_section_segments(state)codings = dict(state.get("codings", {}))idx = state.get("coding_idx", 0)if segs and dim_choice:sid = segs[min(idx, len(segs) - 1)]["segment_id"]codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice], "comment": comment.strip()}state = dict(state)state["codings"] = codings53 unmodified lines"session_id": state["session_id"],"researcher_id": state["researcher_id"],"codings": [{"segment_id": s["segment_id"], "section_id": s.get("section_id", ""),"dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""),"comment": codings.get(s["segment_id"], {}).get("comment", "")}for s in all_segs],}275 unmodified lines# Step 3: Per-section codingwith gr.Column(visible=False) as col_section_work:gr.HTML('<hr style="margin:16px 0;border-color:#e2e8f0">')gr.Markdown("### Step 3 — Section-by-Section Coding")sections_overview_html = gr.HTML()section_header_md = gr.Markdown()# 3a: Boundary detectionwith gr.Column() as col_boundary_btn:propose_btn = gr.Button("Detect Episode Boundaries (Agent 1a) →", variant="primary")boundary_status = gr.Markdown()# 3b: Boundary reviewwith gr.Column(visible=False) as col_boundary_review:gr.HTML('<div style="background:#f8fafc;border:1px solid #e2e8f0;'47 unmodified lineswith gr.Column(scale=2):gr.Markdown("#### Your Coding")dim_radio = gr.Radio(choices=DIM_CHOICES, label="Dimension", value=None)dim_desc_comp = gr.HTML()comment_box = gr.Textbox(label="Comment (optional)", lines=2,placeholder="Note any ambiguity for the disagreement review…"164 unmodified lines# =====================================================================CODING_OUTPUTS = [coding_progress_comp,segment_jump,turns_html_comp,uncertainty_comp,proposal_comp,dim_radio,dim_desc_comp,comment_box,next_section_btn,]NEXT_SECTION_OUTS = [1 unmodified linepipeline_html,sections_overview_html,section_header_md,col_boundary_btn,col_boundary_review,col_coding,col_complete,25 unmodified linesconfirm_sections_btn.click(fn=fn_confirm_sections,inputs=[sections_labels_box, state],outputs=[state, pipeline_html, sections_overview_html,section_header_md, col_section_work,col_boundary_btn, col_boundary_review, col_coding],).then(fn=lambda: RESEARCH_INFO["boundaries"], outputs=[pipeline_info])propose_btn.click(fn=fn_propose_boundaries,inputs=[state],outputs=[state, boundary_status, col_boundary_review,boundary_display_html, boundary_ids_box, sidebar_log],)confirm_boundaries_btn.click(fn=fn_confirm_and_code,2 unmodified lines).then(fn=lambda: RESEARCH_INFO["coding"], outputs=[pipeline_info])next_btn.click(fn=lambda d, c, s: fn_navigate(+1, d, c, s),inputs=[dim_radio, comment_box, state],outputs=[state] + CODING_OUTPUTS,)prev_btn.click(fn=lambda d, c, s: fn_navigate(-1, d, c, s),inputs=[dim_radio, comment_box, state],outputs=[state] + CODING_OUTPUTS,)segment_jump.change(6 unmodified linesnext_section_btn.click(fn=fn_next_section,inputs=[dim_radio, comment_box, state],outputs=NEXT_SECTION_OUTS,)32 unmodified lines3334353637383940414243444555 unmodified lines101102103104105106107108109110111460 unmodified lines572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709144 unmodified lines85485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490511 unmodified lines9179189199209219229239249259269279289297 unmodified lines93793893994094194294392 unmodified lines103610371038103910401041104210431044104547 unmodified lines1093109410951096109710981099110011011102110311041105110611072 unmodified lines111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812796 unmodified lines12861287128812891290129112921293129412959 unmodified lines1305130613071308130913101311131213131314131513161317131813191320132113221323132424 unmodified lines13491350135113521353135413551 unmodified line135713581359136013611362136313641365136613671368136924 unmodified lines1394139513961397139813991400140114021403140414051406140714081409141053 unmodified lines1464146514661467146814691470147114721473147414751476275 unmodified lines175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178247 unmodified lines1830183118321833183418351836183718381839184018411842184318441845164 unmodified lines20102011201220132014201520162017201820192020202120222023202420251 unmodified line202720282029203020312032203325 unmodified lines2059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852 unmodified lines20882089209020912092209320942095209620972098209921006 unmodified lines210721082109211021112112211332 unmodified linesdiscard_disagreement,)from agent2_learner import list_pending_rules, approve_rule, reject_rulefrom pipeline import (run_boundaries_parallel,run_coding_with_context,render_pipeline_stats_html,PipelineStats,)from llm_client import circuit_stateSESSIONS_ROOT = Path("sessions")_STYLES_DIR = Path(__file__).parent / "static" / "styles"55 unmodified linesDIM_ID_FROM_CHOICE = {f"{d} — {l}": d for d, l, _ in DIMENSIONS}DIM_DESC_FROM_ID = {d: desc for d, _, desc in DIMENSIONS}# Secondary dimension choices — "None" is explicit and defaultSEC_NONE = "None — single dimension only"SEC_DIM_CHOICES = [SEC_NONE] + DIM_CHOICESSEC_ID_FROM_CHOICE = {SEC_NONE: None, **DIM_ID_FROM_CHOICE}# ---------------------------------------------------------------------------# Speaker palette — 6 perceptually distinct colours (deuteranopia-safe pair460 unmodified linesdef _kappa_html(report: dict) -> str:"""Render the full reliability report card.Shows Gwet's AC1 as primary (gate metric) and Cohen's κ as secondaryreference. Flags the divergence when prevalence bias is making κmisleadingly low (Byrt, Bishop & Carlin 1993)."""# Primary: AC1ac1 = report.get("overall_ac1", report.get("overall_kappa", 0.0))ac1_interp = report.get("ac1_interpretation", report.get("kappa_interpretation", ""))ac1_ci = report.get("ac1_ci_95", [None, None])gate = report.get("gate_passed", False)col = "#065f46" if gate else "#be123c"icon = "✓" if gate else "✗"pct = int(min(max(ac1, 0) * 100, 100))# Secondary: κkappa = report.get("overall_kappa", 0.0)kappa_ci = report.get("kappa_ci_95", [None, None])divergence = report.get("kappa_ac1_divergence", 0.0)div_flag = report.get("kappa_ac1_divergence_flag", False)prev_warn = report.get("prevalence_warning", False)n_segs = report.get("n_segments_total", 0)n_dis = len(report.get("segments_in_disagreement", []))# Confidence interval textci_text = ""if ac1_ci[0] is not None:ci_text = f'<span style="font-size:0.75em;color:#64748b"> 95% CI [{ac1_ci[0]:.3f}, {ac1_ci[1]:.3f}]</span>'# Prevalence warning bannerprev_banner = ""if prev_warn:dominant = max(((d, v["prevalence"]) for d, v in (report.get("category_distribution") or {}).items()),key=lambda x: x[1], default=("?", 0))prev_banner = (f'<div style="background:#fffbeb;border:1px solid #fbbf24;border-radius:6px;'f'padding:8px 12px;margin-bottom:10px;font-size:0.82em;color:#78350f">'f'⚠ <strong>Prevalence bias detected:</strong> {_h(dominant[0])} accounts for 'f'{dominant[1]:.0%} of codings. Cohen\'s κ is artificially depressed — 'f'AC1 is the appropriate metric here. 'f'<em>(Byrt, Bishop & Carlin 1993)</em>'f'</div>')# κ vs AC1 divergence notediv_note = ""if div_flag:kc = "#065f46" if kappa >= 0.70 else "#be123c"div_note = (f'<div style="font-size:0.78em;color:#64748b;margin-top:4px">'f'Cohen\'s κ = <span style="font-weight:700;color:{kc}">{kappa:.3f}</span>'+ (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') +f' · |AC1 − κ| = <strong style="color:#d97706">{divergence:.3f}</strong>'f' (prevalence bias in κ)'f'</div>')else:kc = "#065f46" if kappa >= 0.70 else "#be123c"div_note = (f'<div style="font-size:0.78em;color:#94a3b8;margin-top:4px">'f'Cohen\'s κ = <span style="color:{kc}">{kappa:.3f}</span>'+ (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') +f' (reference only — Gwet 2008 primary)</div>')# Per-dimension AC1 rows (primary) — fall back to κ if new report not availabledim_src = report.get("ac1_per_dimension") or report.get("kappa_per_dimension") or {}dim_label = "AC1" if "ac1_per_dimension" in report else "κ"dim_rows = ""for dim in ["D1","D2","D3","D4","D5","D6","D7","D8","D9","NS","NA"]:v = dim_src.get(dim)if v is None:dim_rows += (f'<div style="display:flex;gap:8px;align-items:center;padding:3px 0;'f'border-top:1px solid #f1f5f9;opacity:0.4">'f'<span style="font-weight:700;font-size:0.82em;width:32px">{dim}</span>'f'<span style="font-size:0.75em;color:#94a3b8;flex:1">insufficient data</span>'f'</div>')continuevp = int(min(max(v, 0) * 100, 100))vc = "#065f46" if v >= 0.70 else "#b45309" if v >= 0.50 else "#be123c"gate_pip = (f'<span style="font-size:0.7em;color:{vc};margin-left:4px">'f'{"✓" if v >= 0.70 else "·"}</span>')dim_rows += (f'<div style="display:flex;gap:8px;align-items:center;padding:4px 0;'f'border-top:1px solid #f1f5f9">'f'<span style="font-weight:700;font-size:0.82em;width:32px">{dim}</span>'f'<div style="flex:1;height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden">'f'<div style="height:100%;width:{vp}%;background:{vc};border-radius:3px"></div></div>'f'<span style="font-weight:700;font-size:0.82em;color:{vc};width:40px;text-align:right">'f'{v:.3f}</span>'f'{gate_pip}'f'</div>')return (f'<div style="background:white;border:1px solid #e2e8f0;border-radius:12px;padding:20px">'f'{prev_banner}'# Primary scoref'<div style="display:flex;align-items:flex-end;gap:14px;margin-bottom:4px">'f'<span style="font-size:3em;font-weight:800;color:{col};line-height:1">{ac1:.3f}</span>'f'<div>'f'<div style="font-weight:700;color:{col};font-size:1em">{icon} {_h(ac1_interp)}</div>'f'<div style="font-size:0.76em;color:#94a3b8">'f'Gwet\'s AC1 · gate ≥ 0.70 · <em>Gwet (2008); Landis & Koch (1977)</em>'f'</div>'f'</div></div>'f'{ci_text}'# Progress bar with 0.70 threshold markerf'<div style="position:relative;height:10px;background:#e2e8f0;border-radius:5px;margin:10px 0">'f'<div style="position:absolute;height:100%;width:{pct}%;background:{col};border-radius:5px"></div>'f'<div style="position:absolute;left:70%;top:-4px;height:18px;width:2px;background:#94a3b8"></div>'f'<div style="position:absolute;left:70%;top:-16px;font-size:0.68em;color:#94a3b8;'f'transform:translateX(-50%)">0.70</div>'f'</div>'# Counts + secondary metricf'<div style="font-size:0.83em;color:#64748b">'f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis!=1 else ""}'f'</div>'f'{div_note}'# Per-dimensionf'<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;'f'letter-spacing:0.07em;color:#94a3b8;margin:14px 0 6px">Per-Dimension {dim_label} (one-vs-rest)</div>'f'{dim_rows}'f'</div>')144 unmodified lines# ===========================================================================def _segment_label(seg: dict, codings: dict) -> str:sid = seg["segment_id"]ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:]c = codings.get(sid, {})did = c.get("dimension_id") or seg.get("dimension_id") or "?"sec = c.get("secondary_dimension_id")coded = "✓" if c.get("dimension_id") else "○"flag = " ⚠" if seg.get("uncertain") else ""multi = f"+{sec}" if sec else ""return f"{coded} ep{ep} [{did}{multi}]{flag}"def _proposal_md(seg: dict) -> str:did = seg.get("dimension_id", "?")rat = seg.get("rationale", "")sec_did = seg.get("secondary_dimension_id")sec_rat = seg.get("secondary_rationale", "")lines = [f"> **AI primary: {did}** \n> {rat}"]if sec_did:lines.append(f"> **AI secondary: {sec_did}** \n"f"> _{sec_rat or 'co-occurring dimension'}_")tags = []if seg.get("confident"):tags.append("✅ Confident")if seg.get("uncertain"):tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note', '')}")if sec_did:tags.append(f"🔗 Multi-dimensional: {did} + {sec_did}")return ("\n\n".join(lines) + ("\n\n" + " ".join(tags) if tags else "")).strip()CODING_EMPTY = ("", # 0 progress htmlgr.update(choices=[], value=None), # 1 segment_jump"", # 2 turns_display_html"", # 3 uncertainty_htmlgr.update(value="", visible=False), # 4 proposal_mdgr.update(choices=DIM_CHOICES, value=None), # 5 dim_radio"", # 6 dim_desc_htmlgr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), # 7 secondary_dim_drop"", # 8 comment_boxgr.update(visible=False), # 9 next_section_btn)11 unmodified linesexisting = codings.get(sid, {})saved = existing.get("dimension_id", "")choice = next((c for c in DIM_CHOICES if c.startswith(saved)), None)saved_sec = existing.get("secondary_dimension_id")sec_choice = (next((c for c in DIM_CHOICES if c.startswith(saved_sec)), SEC_NONE)if saved_sec else SEC_NONE)all_done = len(codings) >= len(segs) and all(codings.get(s["segment_id"], {}).get("dimension_id") for s in segs)7 unmodified linesgr.update(value=_proposal_md(seg), visible=False),gr.update(choices=DIM_CHOICES, value=choice),_dim_desc_html(choice or ""),gr.update(choices=SEC_DIM_CHOICES, value=sec_choice),existing.get("comment", ""),gr.update(visible=all_done),)92 unmodified linesuser_prev = f"Segment {len(state['turns'])} turns into topical sections."state = dict(state)state["sections"] = sectionsstate["section_stages"] = {s["section_id"]: "pending" for s in sections}state["stage"] = "sectioned"state["_agent0_overview"] = result.get("session_overview", "") # passed to Agent 1a context chainlog = _make_log_entry("Agent 0 — Structural Segmenter", rt,sections_proposed=len(sections),47 unmodified linesfor i, s in enumerate(sections)]if len(labels) != len(sections):gr.Warning(f"Label count mismatch ({len(labels)} vs {len(sections)}).")state = dict(state)state.update({"sections": confirmed,"section_idx": 0,"section_stages": {s["section_id"]: "pending" for s in confirmed},"section_a1a_results":{}, # section_id → Agent 1a result dict (pre-fetched)"stage": "coding",})d = _session_dir(state)2 unmodified lines)_persist(state)n = confirmed[0]["end_turn_id"] - confirmed[0]["start_turn_id"] + 1gr.Info(f"{len(confirmed)} sections confirmed. "f"Click 'Analyse All Boundaries' to run Agent 1a in parallel on all sections.")return (state,_pipeline_html("coding"),_section_cards_html(confirmed, state["section_stages"], 0),gr.update(visible=True), # col_section_workgr.update(visible=True), # col_run_all_boundariesgr.update(visible=False), # col_boundary_reviewgr.update(visible=False), # col_coding"", # parallel_status_html)# ── Stage 3a: Agent 1a — PARALLEL for all sections ───────────────────────────def fn_run_all_boundaries(state: dict):"""Generator: run Agent 1a on ALL confirmed sections in parallel.Yields one progress update per section as it completes (Dean & Ghemawat 2004map-reduce pattern; Nielsen 1994 — feedback within 10s).Final yield shows the complete stats table and transitions to per-section review."""sections = state.get("sections", [])if not sections:raise gr.Error("Confirm sections first.")session_overview = state.get("_agent0_overview", "")n = len(sections)# Initial yield — tell the UI we've startedyield (state,f"⏳ Running Agent 1a on {n} section{'s' if n>1 else ''} in parallel "f"(max {min(n, 3)} concurrent workers)…","",gr.update(visible=False),gr.update(visible=False),"","",)collected_results: dict[str, dict] = {}pipeline_stats_html = ""try:for sr, pstats in run_boundaries_parallel(sections=sections,all_turns=state["turns"],session_id=state["session_id"],session_overview=session_overview,):if sr.success:collected_results[sr.section_id] = sr.resultelse:gr.Warning(f"Section {sr.section_id} failed: {sr.error}")# Build live progress tabledone = len(collected_results)pending = [s for s in sections if s["section_id"] not in collected_results andnot any(not x.success and x.section_id == s["section_id"]for x in pstats.results)]prog_lines = []for s in sections:res = collected_results.get(s["section_id"])failed = any(not x.success and x.section_id == s["section_id"]for x in pstats.results)if res:b = len(res.get("boundaries", []))e = len(res.get("segments", []))prog_lines.append(f"✓ **{s['section_id']}** {s['label']} — {b} boundaries → {e} episodes")elif failed:prog_lines.append(f"✗ **{s['section_id']}** {s['label']} — ERROR")else:prog_lines.append(f"⏳ **{s['section_id']}** {s['label']}…")status_md = f"**{done}/{n} sections complete**\n\n" + "\n\n".join(prog_lines)pipeline_stats_html = render_pipeline_stats_html(pstats)yield (state,status_md,pipeline_stats_html,gr.update(visible=False),gr.update(visible=False),"","",)except Exception as e:raise gr.Error(f"Parallel boundary detection failed: {e}") from e# All done — update statestate = dict(state)n_success = len(collected_results)n_error = n - n_successfor sec in sections:sid = sec["section_id"]result = collected_results.get(sid)if result:state["section_boundaries"][sid] = result["boundaries"]state["section_segments"][sid] = result["segments"]state["section_stages"][sid] = "boundaries"state.setdefault("section_a1a_results", {})[sid] = resultelse:state["section_stages"][sid] = "error"# Log to agent activitytotal_rt = sum((r.wall_time_s for r in pstats.results if r.success), 0.0)log = _make_log_entry("Agent 1a — Boundary Detector (parallel)", round(pstats.parallel_wall_s, 1),sections_ok=n_success, sections_error=n_error,speedup=f"{pstats.speedup:.1f}x",total_est_tokens=pstats.total_estimated_tokens,)state = _push_log(state, log)_persist(state)# Transition: show section-by-section boundary review for section 0sec = sections[0]turns = _turns_for_section(state["turns"], sec)result = collected_results.get(sec["section_id"], {})bounds = result.get("boundaries", [])ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)status_final = (f"✓ All {n_success} sections analysed "f"({pstats.parallel_wall_s:.0f}s parallel vs ~{pstats.sequential_est_s:.0f}s serial — "f"{pstats.speedup:.1f}× speedup).\n\n"f"Now review section boundaries one by one and confirm before coding begins.")if n_error:status_final += f"\n\n⚠ {n_error} section(s) failed — their boundaries need manual entry."gr.Info(f"Parallel analysis complete: {n_success}/{n} sections OK.")yield (state,status_final,pipeline_stats_html,gr.update(visible=True,value=_episode_table_html(turns, bounds)), # boundary_display_htmlgr.update(visible=True, value=ids_txt), # boundary_ids_boxf"### Reviewing: {sec['label']} ({sec['section_id']})",_agent_log_html(state["agent_logs"]),)# ── Stage 3b: Confirm boundaries + run Agent 1b ───────────────────────────────def fn_confirm_and_code(boundary_ids_text: str, state: dict):sec = _current_section(state)if not sec:raise gr.Error("No section loaded.")turns = _turns_for_section(state["turns"], sec)valid_ids = {t["turn_id"] for t in turns}boundaries: list[dict] = []6 unmodified linesexcept ValueError:raise gr.Error(f"'{tok}' is not a valid turn ID.")if tid not in valid_ids:raise gr.Error(f"Turn {tid} is outside this section "f"(valid: {min(valid_ids)}–{max(valid_ids)}).")boundaries.append({"boundary_id": f"r_{tid}", "after_turn_id": tid,"confidence": "high", "boundary_signal": "researcher_defined","rationale": "Set by researcher."})9 unmodified linesyield state, f"⏳ Agent 1b coding {len(segments)} episode(s)…", gr.update(visible=False), *CODING_EMPTY, ""# Pass Agent 1a's result as context for Agent 1b (context chain)agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"])t0 = time.perf_counter()try:coded, llm_stats = run_coding_with_context(section=sec,segments=segments,agent1a_result=agent1a_result,)except Exception as e:raise gr.Error(f"Agent 1b failed: {e}") from ert = round(time.perf_counter() - t0, 1)sys_prev = f"Context chain: section={sec['label']}, boundary_ctx={'yes' if agent1a_result else 'no'}"user_prev = f"Code {len(segments)} segments in section: {sec['label']}"n_uncertain = sum(1 for s in coded if s.get("uncertain"))24 unmodified lines# ── Navigate segments ─────────────────────────────────────────────────────────def fn_navigate(direction: int, dim_choice: str, sec_choice: str, comment: str, state: dict):segs = _current_section_segments(state)if not segs:return state, *_render_coding(state)1 unmodified linecodings = dict(state.get("codings", {}))sid = segs[idx]["segment_id"]if dim_choice:codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice],"secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),"comment": comment.strip(),}state = dict(state)state["codings"] = codingsstate["coding_idx"] = max(0, min(idx + direction, len(segs) - 1))return state, *_render_coding(state)24 unmodified lines# ── Next section ──────────────────────────────────────────────────────────────def fn_next_section(dim_choice: str, sec_choice: str, comment: str, state: dict):segs = _current_section_segments(state)codings = dict(state.get("codings", {}))idx = state.get("coding_idx", 0)if segs and dim_choice:sid = segs[min(idx, len(segs) - 1)]["segment_id"]codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice],"secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),"comment": comment.strip(),}state = dict(state)state["codings"] = codings53 unmodified lines"session_id": state["session_id"],"researcher_id": state["researcher_id"],"codings": [{"segment_id": s["segment_id"],"section_id": s.get("section_id", ""),"dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""),"secondary_dimension_id":codings.get(s["segment_id"], {}).get("secondary_dimension_id"),"comment": codings.get(s["segment_id"], {}).get("comment", ""),}for s in all_segs],}275 unmodified lines# Step 3: Per-section codingwith gr.Column(visible=False) as col_section_work:gr.HTML('<hr style="margin:16px 0;border-color:#e2e8f0">')gr.Markdown("### Step 3 — Boundary Analysis + Coding")sections_overview_html = gr.HTML()# 3a: Parallel Agent 1a for ALL sectionswith gr.Column() as col_run_all_boundaries:gr.HTML('<div style="background:#eff6ff;border:1px solid #93c5fd;''border-radius:8px;padding:12px 16px;margin-bottom:10px;''font-size:0.88em;color:#1e3a8a">''<strong>Agent 1a runs in parallel on all sections simultaneously.</strong>'' Processing time scales with the longest section, not the total ''transcript length. *(Dean & Ghemawat 2004 — parallel map pattern)*''</div>')run_all_btn = gr.Button("⚡ Analyse All Boundaries in Parallel (Agent 1a)",variant="primary",)parallel_status_md = gr.Markdown()parallel_stats_html = gr.HTML()# Current section review headersection_header_md = gr.Markdown()# 3b: Per-section boundary review (after parallel run)with gr.Column(visible=False) as col_boundary_review:gr.HTML('<div style="background:#f8fafc;border:1px solid #e2e8f0;'47 unmodified lineswith gr.Column(scale=2):gr.Markdown("#### Your Coding")dim_radio = gr.Radio(choices=DIM_CHOICES, label="Primary dimension", value=None)dim_desc_comp = gr.HTML()secondary_dim_drop = gr.Dropdown(choices=SEC_DIM_CHOICES,value=SEC_NONE,label="Secondary dimension (optional)",info="Use only when a second dimension is clearly sustained throughout the episode. Strijbos et al. (2006); Suthers & Rosen (2011).",interactive=True,)comment_box = gr.Textbox(label="Comment (optional)", lines=2,placeholder="Note any ambiguity for the disagreement review…"164 unmodified lines# =====================================================================CODING_OUTPUTS = [coding_progress_comp, # 0segment_jump, # 1turns_html_comp, # 2uncertainty_comp, # 3proposal_comp, # 4dim_radio, # 5dim_desc_comp, # 6secondary_dim_drop, # 7 ← NEWcomment_box, # 8next_section_btn, # 9]NEXT_SECTION_OUTS = [1 unmodified linepipeline_html,sections_overview_html,section_header_md,col_run_all_boundaries,col_boundary_review,col_coding,col_complete,25 unmodified linesconfirm_sections_btn.click(fn=fn_confirm_sections,inputs=[sections_labels_box, state],outputs=[state, pipeline_html, sections_overview_html,col_section_work,col_run_all_boundaries, col_boundary_review, col_coding,parallel_stats_html,],).then(fn=lambda: RESEARCH_INFO["boundaries"], outputs=[pipeline_info])run_all_btn.click(fn=fn_run_all_boundaries,inputs=[state],outputs=[state,parallel_status_md,parallel_stats_html,boundary_display_html,boundary_ids_box,section_header_md,sidebar_log,],).then(fn=lambda: RESEARCH_INFO["boundaries"], outputs=[pipeline_info])confirm_boundaries_btn.click(fn=fn_confirm_and_code,2 unmodified lines).then(fn=lambda: RESEARCH_INFO["coding"], outputs=[pipeline_info])next_btn.click(fn=lambda d, sec, c, s: fn_navigate(+1, d, sec, c, s),inputs=[dim_radio, secondary_dim_drop, comment_box, state],outputs=[state] + CODING_OUTPUTS,)prev_btn.click(fn=lambda d, sec, c, s: fn_navigate(-1, d, sec, c, s),inputs=[dim_radio, secondary_dim_drop, comment_box, state],outputs=[state] + CODING_OUTPUTS,)segment_jump.change(6 unmodified linesnext_section_btn.click(fn=fn_next_section,inputs=[dim_radio, secondary_dim_drop, comment_box, state],outputs=NEXT_SECTION_OUTS,)
123456789101112131415161718192021221 unmodified line242526272829303132333435363738394041424344454647484950515253543 unmodified lines585960616263641 unmodified line666768697071721 unmodified line74757677787980818283848586878889909192934 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761772 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102114 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752766 unmodified lines2832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733742 unmodified lines3773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214222 unmodified lines4254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554562 unmodified lines4594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894902 unmodified lines4934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325 unmodified lines538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569"""kappa_calculator.py-------------------Calculates Cohen's Kappa between two researcher codings of the sameproposed segments from Agent 1.Assumptions (prototype):- Both researchers accept Agent 1's segment boundaries- Only the dimension label (D1-D9) is the unit of agreement- Boundary concerns are captured as free-text comments, not in the metric- Kappa gate threshold: 0.70Outputs a structured kappa_report.json to the session folder."""import jsonfrom pathlib import Pathfrom datetime import datetime, timezonefrom collections import defaultdictfrom typing import Optional1 unmodified line# Constants# ---------------------------------------------------------------------------KAPPA_THRESHOLD = 0.70DIMENSIONS = ["D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "NS", "NA"]# ---------------------------------------------------------------------------# Data loaders# ---------------------------------------------------------------------------def load_coding(filepath: Path) -> dict:"""Load a researcher coding file.Expected structure:{"researcher_id": "R1","session_id": "dyad_12","codings": [{"segment_id": "...","dimension_id": "D1","comment": "optional free text"},...]}"""data = json.loads(filepath.read_text(encoding="utf-8"))if "codings" not in data:raise ValueError(f"Coding file missing 'codings' key: {filepath}")3 unmodified linesdef load_proposed_segments(filepath: Path) -> dict:"""Load the proposed segments from Agent 1 output."""data = json.loads(filepath.read_text(encoding="utf-8"))if "segments" not in data:raise ValueError(f"Segments file missing 'segments' key: {filepath}")1 unmodified line# ---------------------------------------------------------------------------# Validation# ---------------------------------------------------------------------------def validate_codings(1 unmodified linecoding_r2: dict,proposed_segments: dict,) -> list[str]:"""Check that both codings cover exactly the same segments.Returns a list of error strings (empty = all good)."""errors = []ids_r1 = {c["segment_id"] for c in coding_r1["codings"]}ids_r2 = {c["segment_id"] for c in coding_r2["codings"]}ids_proposed = set(proposed_segments.keys())missing_r1 = ids_proposed - ids_r1missing_r2 = ids_proposed - ids_r2extra_r1 = ids_r1 - ids_proposedextra_r2 = ids_r2 - ids_proposedif missing_r1:errors.append(f"{coding_r1['researcher_id']} has not coded: {sorted(missing_r1)}")4 unmodified linesif extra_r2:errors.append(f"{coding_r2['researcher_id']} coded unknown segments: {sorted(extra_r2)}")# Check all dimension IDs are validfor coding in [coding_r1, coding_r2]:for c in coding["codings"]:if c["dimension_id"] not in DIMENSIONS:errors.append(f"{coding['researcher_id']} used unknown dimension "f"'{c['dimension_id']}' for segment {c['segment_id']}")return errors# ---------------------------------------------------------------------------# Cohen's Kappa# ---------------------------------------------------------------------------def _build_aligned_labels(coding_r1: dict,coding_r2: dict,) -> tuple[list[str], list[str], list[str]]:"""Align the two codings by segment_id.Returns (segment_ids, labels_r1, labels_r2) in the same order."""map_r1 = {c["segment_id"]: c["dimension_id"] for c in coding_r1["codings"]}map_r2 = {c["segment_id"]: c["dimension_id"] for c in coding_r2["codings"]}# Use only segments present in both (validation already flagged gaps)shared = sorted(set(map_r1.keys()) & set(map_r2.keys()))labels_r1 = [map_r1[sid] for sid in shared]labels_r2 = [map_r2[sid] for sid in shared]return shared, labels_r1, labels_r2def _cohen_kappa(labels_a: list[str], labels_b: list[str]) -> float:"""Calculate Cohen's Kappa for two aligned label lists.Returns float in [-1, 1]. Returns 0.0 if calculation is undefined."""n = len(labels_a)if n == 0:return 0.0# Observed agreementp_o = sum(a == b for a, b in zip(labels_a, labels_b)) / n# Expected agreementcategories = set(labels_a) | set(labels_b)p_e = 0.0for cat in categories:prop_a = labels_a.count(cat) / nprop_b = labels_b.count(cat) / np_e += prop_a * prop_bif p_e == 1.0:# Perfect expected agreement — kappa undefined, treat as 1.0 if also perfect observedreturn 1.0 if p_o == 1.0 else 0.0return (p_o - p_e) / (1.0 - p_e)def calculate_overall_kappa(coding_r1: dict,coding_r2: dict,) -> tuple[float, list[str], list[str], list[str]]:"""Calculate overall Cohen's Kappa across all segments.Returns (kappa, segment_ids, labels_r1, labels_r2)."""segment_ids, labels_r1, labels_r2 = _build_aligned_labels(coding_r1, coding_r2)kappa = _cohen_kappa(labels_r1, labels_r2)return kappa, segment_ids, labels_r1, labels_r2def calculate_per_dimension_kappa(2 unmodified lineslabels_r2: list[str],) -> dict[str, Optional[float]]:"""Calculate Kappa restricted to segments where at least one raterassigned a given dimension. This reveals where agreement breaks down.Returns dict: {"D1": 0.82, "D2": 0.61, ...}Dimensions with fewer than 2 observations return None (insufficient data)."""per_dim = {}for dim in DIMENSIONS:# Include segments where R1 or R2 assigned this dimensionindices = [i for i, (a, b) in enumerate(zip(labels_r1, labels_r2))if a == dim or b == dim]if len(indices) < 2:per_dim[dim] = Nonecontinuesub_r1 = [labels_r1[i] for i in indices]sub_r2 = [labels_r2[i] for i in indices]per_dim[dim] = round(_cohen_kappa(sub_r1, sub_r2), 4)return per_dim# ---------------------------------------------------------------------------# Disagreement analysis# ---------------------------------------------------------------------------def identify_disagreements(4 unmodified linescoding_r2: dict,proposed_segments: dict,) -> list[dict]:"""Build a structured list of all disagreeing segments with context."""map_comments_r1 = {c["segment_id"]: c.get("comment", "") for c in coding_r1["codings"]}map_comments_r2 = {c["segment_id"]: c.get("comment", "") for c in coding_r2["codings"]}disagreements = []for sid, d1, d2 in zip(segment_ids, labels_r1, labels_r2):if d1 != d2:seg = proposed_segments.get(sid, {})disagreements.append({"segment_id": sid,"start_time": seg.get("start_time"),"end_time": seg.get("end_time"),"agent1_dimension": seg.get("dimension_id"),"agent1_rationale": seg.get("rationale"),f"{coding_r1['researcher_id']}_dimension": d1,f"{coding_r1['researcher_id']}_comment": map_comments_r1.get(sid, ""),f"{coding_r2['researcher_id']}_dimension": d2,f"{coding_r2['researcher_id']}_comment": map_comments_r2.get(sid, ""),"resolution_status": "pending","resolved_dimension": None,"resolution_note": "",})return disagreements# ---------------------------------------------------------------------------# Kappa interpretation# ---------------------------------------------------------------------------def interpret_kappa(kappa: float) -> str:if kappa < 0:return "poor — worse than chance"elif kappa < 0.20:return "slight"elif kappa < 0.40:return "fair"elif kappa < 0.60:return "moderate"elif kappa < 0.70:return "substantial — below gate threshold"elif kappa < 0.80:return "substantial — gate passed"elif kappa < 0.90:return "strong"else:return "near-perfect"# ---------------------------------------------------------------------------# Main report builder# ---------------------------------------------------------------------------6 unmodified linesoutput_path: Optional[Path] = None,) -> dict:"""Full kappa report for a session.Args:session_id: Identifier for this dyad/transcript sessioncoding_r1_path: Path to Researcher 1 coding JSONcoding_r2_path: Path to Researcher 2 coding JSONproposed_segments_path: Path to Agent 1 segments_proposed.jsonoutput_path: Where to save the report (optional)Returns:Full kappa report dict."""# Loadcoding_r1 = load_coding(coding_r1_path)coding_r2 = load_coding(coding_r2_path)proposed_segments = load_proposed_segments(proposed_segments_path)# Validate completenesserrors = validate_codings(coding_r1, coding_r2, proposed_segments)if errors:raise ValueError("Coding validation failed — cannot calculate kappa:\n" +"\n".join(f" - {e}" for e in errors))# Overall kappaoverall_kappa, segment_ids, labels_r1, labels_r2 = calculate_overall_kappa(coding_r1, coding_r2)# Per-dimension kappaper_dim_kappa = calculate_per_dimension_kappa(segment_ids, labels_r1, labels_r2)# Disagreementsdisagreements = identify_disagreements(segment_ids, labels_r1, labels_r2,coding_r1, coding_r2, proposed_segments,)# Gategate_passed = overall_kappa >= KAPPA_THRESHOLD# Agreement breakdownn_total = len(segment_ids)n_agree = sum(a == b for a, b in zip(labels_r1, labels_r2))n_disagree = n_total - n_agreereport = {"session_id": session_id,"timestamp": datetime.now(timezone.utc).isoformat(),"researcher_1": coding_r1["researcher_id"],"researcher_2": coding_r2["researcher_id"],"n_segments_total": n_total,"n_segments_agreed": n_agree,"n_segments_disagreed": n_disagree,"overall_kappa": round(overall_kappa, 4),"kappa_interpretation": interpret_kappa(overall_kappa),"gate_threshold": KAPPA_THRESHOLD,"gate_passed": gate_passed,"kappa_per_dimension": per_dim_kappa,"segments_in_disagreement": [d["segment_id"] for d in disagreements],"disagreements": disagreements,"status": ("ready_for_agent2" if gate_passed and not disagreementselse "pending_disagreement_review" if gate_passedelse "below_threshold_review_required"),}# Saveif output_path:output_path.parent.mkdir(parents=True, exist_ok=True)output_path.write_text(json.dumps(report, indent=2, ensure_ascii=False),encoding="utf-8",)print(f"[Kappa] Report saved to {output_path}")# Print summary_print_summary(report)return report# ---------------------------------------------------------------------------# Disagreement resolution (called after human review)# ---------------------------------------------------------------------------def resolve_disagreement(2 unmodified linesresolved_dimension: str,resolution_note: str,) -> dict:"""Record a human resolution for a specific disagreement.Updates the report file in place.Args:report_path: Path to the kappa_report.jsonsegment_id: Which segment was resolvedresolved_dimension: The agreed-upon dimension coderesolution_note: Why this dimension was chosenReturns:Updated report dict."""report = json.loads(report_path.read_text(encoding="utf-8"))resolved_count = 0for d in report["disagreements"]:if d["segment_id"] == segment_id:d["resolution_status"] = "resolved"d["resolved_dimension"] = resolved_dimensiond["resolution_note"] = resolution_noteresolved_count += 1if resolved_count == 0:raise ValueError(f"Segment {segment_id} not found in disagreements.")# Check if all disagreements are now handled (resolved or discarded)all_handled = all(d["resolution_status"] in ("resolved", "discarded")for d in report["disagreements"])if all_handled and report["gate_passed"]:report["status"] = "ready_for_agent2"report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False),encoding="utf-8",)print(f"[Kappa] Resolved disagreement for {segment_id} → {resolved_dimension}")return report2 unmodified linessegment_id: str,discard_note: str,) -> dict:"""Mark a disagreement as discarded (unresolvable).Discarded segments are excluded from Agent 2 learning."""report = json.loads(report_path.read_text(encoding="utf-8"))for d in report["disagreements"]:if d["segment_id"] == segment_id:d["resolution_status"] = "discarded"d["resolved_dimension"] = Noned["resolution_note"] = discard_note# Check if remaining disagreements are all handledall_handled = all(d["resolution_status"] in ("resolved", "discarded")for d in report["disagreements"])if all_handled and report["gate_passed"]:report["status"] = "ready_for_agent2"report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False),encoding="utf-8",)print(f"[Kappa] Discarded disagreement for {segment_id}")return report2 unmodified lines# ---------------------------------------------------------------------------def _print_summary(report: dict) -> None:print("\n" + "═" * 52)print(f" KAPPA REPORT — {report['session_id']}")print("═" * 52)print(f" Researchers : {report['researcher_1']} vs {report['researcher_2']}")print(f" Segments : {report['n_segments_total']} total")print(f" Agreed : {report['n_segments_agreed']}")print(f" Disagreed : {report['n_segments_disagreed']}")print(f" Kappa : {report['overall_kappa']:.4f} ({report['kappa_interpretation']})")print(f" Gate (≥0.70) : {'✓ PASSED' if report['gate_passed'] else '✗ FAILED'}")print(f" Status : {report['status']}")print("\n Per-dimension kappa:")for dim, k in report["kappa_per_dimension"].items():if k is not None:bar = "▓" * int(k * 20)print(f" {dim} {k:.2f} {bar}")else:print(f" {dim} — (insufficient data)")if report["segments_in_disagreement"]:print(f"\n Disagreeing segments:")for sid in report["segments_in_disagreement"]:print(f" · {sid}")print("═" * 52 + "\n")# ---------------------------------------------------------------------------# Coding file template generator# ---------------------------------------------------------------------------def generate_coding_template(2 unmodified linessession_id: str,output_path: Path,) -> None:"""Generate a blank coding template for a researcher to fill in.Each segment has an empty dimension_id and comment field."""proposed = json.loads(proposed_segments_path.read_text(encoding="utf-8"))template = {"researcher_id": researcher_id,"session_id": session_id,"instructions": ("Fill in dimension_id for each segment (D1–D9, NS=Not Sure, NA=Not Applicable). ""Use the comment field for boundary concerns or ambiguity notes. ""Do not change segment_id values."),"codings": [{"segment_id": seg["segment_id"],"start_time": seg.get("start_time"),"end_time": seg.get("end_time"),"agent1_label": seg.get("dimension_id"),"agent1_rationale": seg.get("rationale"),"dimension_id": "","comment": "",}for seg in proposed["segments"]]}output_path.parent.mkdir(parents=True, exist_ok=True)output_path.write_text(json.dumps(template, indent=2, ensure_ascii=False),encoding="utf-8",)print(f"[Kappa] Coding template for {researcher_id} saved to {output_path}")# ---------------------------------------------------------------------------5 unmodified linesif len(sys.argv) < 2:print("Usage:")print(" Calculate kappa:")print(" python kappa_calculator.py calc <session_id> <r1.json> <r2.json> <segments.json> [report.json]")print(" Generate coding template:")print(" python kappa_calculator.py template <segments.json> <researcher_id> <session_id> <output.json>")sys.exit(1)command = sys.argv[1]if command == "calc":session_id = sys.argv[2]r1_path = Path(sys.argv[3])r2_path = Path(sys.argv[4])segments_path = Path(sys.argv[5])output = Path(sys.argv[6]) if len(sys.argv) > 6 else \Path(f"sessions/{session_id}/kappa_report.json")calculate_kappa_report(session_id, r1_path, r2_path, segments_path, output)elif command == "template":segments_path = Path(sys.argv[2])researcher_id = sys.argv[3]session_id = sys.argv[4]output = Path(sys.argv[5])generate_coding_template(segments_path, researcher_id, session_id, output)else:print(f"Unknown command: {command}")sys.exit(1)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182831 unmodified line8586878889909192939495969798991001011021031041051061071083 unmodified lines1121131141151161171 unmodified line1191201211221231241251 unmodified line1271281291301311321331341351361371381391401414 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173182 unmodified lines3213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185194 unmodified lines5245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585596 unmodified lines5665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876882 unmodified lines6916926936946956966976986997007017027037047057067077087097107117127137147152 unmodified lines7187197207217227237247257267277287297307317327337347357367377382 unmodified lines7417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118122 unmodified lines8158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458465 unmodified lines852853854855856857858859860861862863864865866867868869870871872"""kappa_calculator.py-------------------Inter-rater reliability for CollabCode.PRIMARY METRIC : Gwet's AC1 (Gwet 2008)SECONDARY METRIC: Cohen's Kappa (Cohen 1960) — retained for journal compatibilityGATE THRESHOLD : AC1 ≥ 0.70Why AC1 over Cohen's κ?-----------------------Cohen's κ has a well-documented prevalence-bias problem: when one or more categoriesdominate the distribution (common in CSCL coding — D3 and D9 typically appear farmore often than D6 or D7), κ is systematically depressed below the actual level ofagreement. Two coders can genuinely agree 80% of the time but produce κ < 0.50purely because of category imbalance. This makes sessions appear to fail thereliability gate when coders are actually working well.Gwet's AC1 corrects for this by computing chance agreement as a function of the*average* marginal proportions (not their product), which is bounded away from 1even when one category dominates — preventing artificial depression of the metric.Byrt, Bishop & Carlin (1993) demonstrated the mathematical basis for this artifactin κ. Gwet (2008) proposed AC1 as the correction. Wongpakaran et al. (2013)validated AC1 clinically across imbalanced coding schemes.Key references--------------Gwet, K. L. (2008). Computing inter-rater reliability and its variance in thepresence of high agreement. British Journal of Mathematical and StatisticalPsychology, 61(1), 29–48.Byrt, T., Bishop, J., & Carlin, J. B. (1993). Bias, prevalence and kappa.Journal of Clinical Epidemiology, 46(5), 423–429.Cohen, J. (1960). A coefficient of agreement for nominal scales.Educational and Psychological Measurement, 20(1), 37–46.Wongpakaran, N., Wongpakaran, T., Wedding, D., & Gwet, K. L. (2013).A comparison of Cohen's kappa and Gwet's AC1 when calculating inter-raterreliability coefficients. BMC Medical Research Methodology, 13(1), 61.Landis, J. R., & Koch, G. G. (1977). The measurement of observer agreementfor categorical data. Biometrics, 33(1), 159–174.— Verbal interpretation benchmarks (same numeric thresholds used for both κ and AC1).Bujang, M. A., & Baharum, N. (2017). Guidelines of the minimum sample sizerequirements for Cohen's Kappa. Epidemiology, Biostatistics and Public Health, 14(2).— Sample size guidance applies equally to AC1 given equivalent statistical power.Confidence intervals--------------------95% percentile bootstrap CIs (B=1000 resamples, seed=42 for reproducibility).The bootstrap is preferred over analytical SEs for small samples (N<100) andnon-normal coefficient distributions, as is common with AC1 near 0 or 1.Efron, B., & Tibshirani, R. J. (1994). An Introduction to the Bootstrap.Chapman & Hall. — Bootstrap CI methodology.Per-dimension reliability-------------------------Computed as a binary one-vs-rest AC1: for each dimension D, labels are recoded as{D, not-D} and AC1 is computed on these binary labels. This correctly answers"how reliably can coders identify episodes of dimension D?" without the distributionaldistortion introduced by the subsetting approach used for Cohen's κ.Gate note---------AC1 ≥ 0.70 is retained as the same numeric threshold as the prior κ gate. Inbalanced distributions AC1 ≈ κ; in imbalanced distributions AC1 > κ, so the gateis slightly more lenient than κ ≥ 0.70 would have been. This is intentional:the gate should reflect actual agreement, not measurement artefact."""from __future__ import annotationsimport jsonimport randomfrom pathlib import Pathfrom datetime import datetime, timezonefrom typing import Optional1 unmodified line# Constants# ---------------------------------------------------------------------------AC1_GATE_THRESHOLD = 0.70 # primary gate (Gwet's AC1)KAPPA_THRESHOLD = 0.70 # secondary reference (Cohen's κ)DIMENSIONS = ["D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "NS", "NA"]N_BOOTSTRAP = 1000 # resamples for confidence intervalsCI_LEVEL = 0.95 # 95% CIBOOTSTRAP_SEED = 42 # fixed seed → reproducible CIs across runs# Prevalence warning: flag if any single category accounts for more than this# proportion of all codings, as κ–AC1 divergence becomes large above ~40%.PREVALENCE_WARNING_THRESHOLD = 0.40# ---------------------------------------------------------------------------# Data loaders (unchanged API)# ---------------------------------------------------------------------------def load_coding(filepath: Path) -> dict:data = json.loads(filepath.read_text(encoding="utf-8"))if "codings" not in data:raise ValueError(f"Coding file missing 'codings' key: {filepath}")3 unmodified linesdef load_proposed_segments(filepath: Path) -> dict:data = json.loads(filepath.read_text(encoding="utf-8"))if "segments" not in data:raise ValueError(f"Segments file missing 'segments' key: {filepath}")1 unmodified line# ---------------------------------------------------------------------------# Validation (unchanged)# ---------------------------------------------------------------------------def validate_codings(1 unmodified linecoding_r2: dict,proposed_segments: dict,) -> list[str]:errors = []ids_r1 = {c["segment_id"] for c in coding_r1["codings"]}ids_r2 = {c["segment_id"] for c in coding_r2["codings"]}ids_all = set(proposed_segments.keys())missing_r1 = ids_all - ids_r1missing_r2 = ids_all - ids_r2extra_r1 = ids_r1 - ids_allextra_r2 = ids_r2 - ids_allif missing_r1:errors.append(f"{coding_r1['researcher_id']} has not coded: {sorted(missing_r1)}")4 unmodified linesif extra_r2:errors.append(f"{coding_r2['researcher_id']} coded unknown segments: {sorted(extra_r2)}")for coding in [coding_r1, coding_r2]:for c in coding["codings"]:if c["dimension_id"] not in DIMENSIONS:errors.append(f"{coding['researcher_id']} used unknown dimension "f"'{c['dimension_id']}' for {c['segment_id']}")# secondary_dimension_id is optional; only validate if present and non-nullsec = c.get("secondary_dimension_id")if sec is not None and sec not in DIMENSIONS:errors.append(f"{coding['researcher_id']} used unknown secondary dimension "f"'{sec}' for {c['segment_id']}")if sec is not None and sec == c.get("dimension_id"):errors.append(f"{coding['researcher_id']} set secondary == primary "f"('{sec}') for {c['segment_id']} — secondary must differ")return errors# ---------------------------------------------------------------------------# Alignment helper# ---------------------------------------------------------------------------def _build_aligned_labels(coding_r1: dict,coding_r2: dict,) -> tuple[list[str], list[str], list[str]]:map_r1 = {c["segment_id"]: c["dimension_id"] for c in coding_r1["codings"]}map_r2 = {c["segment_id"]: c["dimension_id"] for c in coding_r2["codings"]}shared = sorted(set(map_r1) & set(map_r2))return shared, [map_r1[s] for s in shared], [map_r2[s] for s in shared]# ---------------------------------------------------------------------------# Core agreement functions# ---------------------------------------------------------------------------def _observed_agreement(labels_a: list[str], labels_b: list[str]) -> float:n = len(labels_a)return sum(a == b for a, b in zip(labels_a, labels_b)) / n if n else 0.0def _cohen_kappa(labels_a: list[str], labels_b: list[str]) -> float:"""Cohen's κ (Cohen 1960).Preserved for journal compatibility; AC1 is the primary metric.Known limitation: depressed by prevalence imbalance — do not use alone asthe gate metric (Byrt, Bishop & Carlin 1993)."""n = len(labels_a)if n == 0:return 0.0p_o = _observed_agreement(labels_a, labels_b)cats = set(labels_a) | set(labels_b)p_e = sum((labels_a.count(c) / n) * (labels_b.count(c) / n) for c in cats)if p_e >= 1.0:return 1.0 if p_o >= 1.0 else 0.0return (p_o - p_e) / (1.0 - p_e)def _gwet_ac1(labels_a: list[str], labels_b: list[str]) -> float:"""Gwet's AC1 (Gwet 2008).Chance agreement formula:P_e = [1 / (K-1)] * Σ_k π_k * (1 - π_k)where π_k = average marginal proportion for category k,K = number of distinct categories used by either rater.This P_e is bounded away from 1 even when one category dominates,preventing the prevalence-induced depression of κ."""n = len(labels_a)if n == 0:return 0.0p_o = _observed_agreement(labels_a, labels_b)cats = set(labels_a) | set(labels_b)K = len(cats)if K <= 1:return 1.0 if p_o >= 1.0 else 0.0p_e = sum(((labels_a.count(c) / n + labels_b.count(c) / n) / 2)* (1 - (labels_a.count(c) / n + labels_b.count(c) / n) / 2)for c in cats) / (K - 1)if p_e >= 1.0:return 1.0 if p_o >= 1.0 else 0.0return (p_o - p_e) / (1.0 - p_e)def _bootstrap_ci(labels_a: list[str],labels_b: list[str],fn,n_boot: int = N_BOOTSTRAP,ci: float = CI_LEVEL,seed: int = BOOTSTRAP_SEED,) -> tuple[float, float]:"""Percentile bootstrap CI for any reliability function fn(a, b) → float.(Efron & Tibshirani 1994)Critical implementation detail: indices are shared across both raters sothat (label_a_i, label_b_i) pairs are resampled together. Independentresampling would break the pairing and produce nonsensical reliabilityestimates on shuffled data.Preferred over analytical SEs for small N and non-normal coefficientdistributions, as is common with AC1 near 0 or 1."""rng = random.Random(seed)n = len(labels_a)boots: list[float] = []for _ in range(n_boot):# One set of indices used for BOTH raters — paired resamplingidxs = [rng.randrange(n) for _ in range(n)]ba = [labels_a[i] for i in idxs]bb = [labels_b[i] for i in idxs]boots.append(fn(ba, bb))boots.sort()lo_idx = int(n_boot * (1 - ci) / 2)hi_idx = min(int(n_boot * (1 + ci) / 2), n_boot - 1)return round(boots[lo_idx], 4), round(boots[hi_idx], 4)# ---------------------------------------------------------------------------# Interpretation (Landis & Koch 1977 benchmarks — apply to both κ and AC1)# ---------------------------------------------------------------------------def _interpret(value: float) -> str:if value < 0:return "poor — worse than chance"elif value < 0.20:return "slight"elif value < 0.40:return "fair"elif value < 0.60:return "moderate"elif value < 0.70:return "substantial — below gate"elif value < 0.80:return "substantial — gate passed"elif value < 0.90:return "strong"else:return "near-perfect"# Keep old name for any external callersdef interpret_kappa(kappa: float) -> str:return _interpret(kappa)# ---------------------------------------------------------------------------# Per-dimension reliability# ---------------------------------------------------------------------------def _binary_labels(labels: list[str], target_dim: str) -> list[str]:"""Recode to binary: target_dim vs. 'other'. One-vs-rest for per-dim AC1."""return [target_dim if l == target_dim else "_other_" for l in labels]def calculate_per_dimension_kappa(2 unmodified lineslabels_r2: list[str],) -> dict[str, Optional[float]]:"""Cohen's κ per dimension — subsetting approach (retained for backwards compatibility).Subset = segments where at least one rater used that dimension."""per_dim = {}for dim in DIMENSIONS:idxs = [i for i, (a, b) in enumerate(zip(labels_r1, labels_r2))if a == dim or b == dim]if len(idxs) < 2:per_dim[dim] = Nonecontinuesub_r1 = [labels_r1[i] for i in idxs]sub_r2 = [labels_r2[i] for i in idxs]per_dim[dim] = round(_cohen_kappa(sub_r1, sub_r2), 4)return per_dimdef calculate_per_dimension_ac1(segment_ids: list[str],labels_r1: list[str],labels_r2: list[str],) -> dict[str, Optional[float]]:"""Gwet's AC1 per dimension — binary one-vs-rest approach.For each dimension D:Recode all labels as {D, "_other_"} and compute AC1.Answers: "how reliably can raters identify episodes of dimension D?"This avoids the distributional distortion of the subsetting approach andgives a reliability estimate that is directly interpretable for each dimension.Requires ≥ 2 instances of the target dimension (summed across both raters)."""per_dim: dict[str, Optional[float]] = {}for dim in DIMENSIONS:n_instances = sum(1 for l in labels_r1 + labels_r2 if l == dim)if n_instances < 2:per_dim[dim] = Nonecontinuebin_r1 = _binary_labels(labels_r1, dim)bin_r2 = _binary_labels(labels_r2, dim)per_dim[dim] = round(_gwet_ac1(bin_r1, bin_r2), 4)return per_dim# ---------------------------------------------------------------------------# Category distribution / prevalence diagnostics# ---------------------------------------------------------------------------def _compute_category_distribution(labels_r1: list[str],labels_r2: list[str],) -> dict[str, dict]:"""Compute per-category counts and prevalence for both raters.Prevalence = average proportion across both raters.High prevalence (> PREVALENCE_WARNING_THRESHOLD) indicates potentialκ–AC1 divergence: AC1 will be notably higher than κ in these cases."""n = len(labels_r1)if n == 0:return {}dist: dict[str, dict] = {}for dim in DIMENSIONS:c1 = labels_r1.count(dim)c2 = labels_r2.count(dim)prev = ((c1 / n) + (c2 / n)) / 2if c1 > 0 or c2 > 0:dist[dim] = {"r1_count": c1,"r2_count": c2,"prevalence": round(prev, 4),}return distdef _prevalence_warning(dist: dict[str, dict]) -> bool:"""True if any category's prevalence exceeds the warning threshold."""return any(v["prevalence"] > PREVALENCE_WARNING_THRESHOLDfor v in dist.values())# ---------------------------------------------------------------------------# Secondary dimension analysis# ---------------------------------------------------------------------------_NO_SECONDARY = "NONE" # sentinel label used when secondary_dimension_id is nulldef _extract_secondary_labels(coding_r1: dict,coding_r2: dict,segment_ids: list[str],) -> tuple[list[str], list[str]]:"""Build paired secondary-label lists aligned by segment_id.Segments with no secondary are labelled _NO_SECONDARY.This treats "no secondary dimension" as a valid, explicit category —which is correct, since most segments are single-dimensional and bothraters marking no secondary is a genuine agreement."""map_r1 = {c["segment_id"]: c.get("secondary_dimension_id") or _NO_SECONDARYfor c in coding_r1["codings"]}map_r2 = {c["segment_id"]: c.get("secondary_dimension_id") or _NO_SECONDARYfor c in coding_r2["codings"]}sec_r1 = [map_r1.get(sid, _NO_SECONDARY) for sid in segment_ids]sec_r2 = [map_r2.get(sid, _NO_SECONDARY) for sid in segment_ids]return sec_r1, sec_r2def _compute_secondary_agreement(coding_r1: dict,coding_r2: dict,segment_ids: list[str],) -> dict:"""Compute Gwet's AC1 for secondary dimension labels.High prevalence of _NO_SECONDARY is expected and correct — AC1 handlesthis naturally without the prevalence bias that would afflict Cohen's κin the same situation (Byrt, Bishop & Carlin 1993).Returns a dict with:n_with_secondary_r1 : segments where R1 marked a secondaryn_with_secondary_r2 : segments where R2 marked a secondaryn_with_secondary_both : segments where BOTH marked a secondarysecondary_agreement_ac1 : AC1 on secondary labels (NONE treated as valid category)secondary_ci_95 : bootstrap CI for secondary AC1secondary_interpretation : verbal label"""sec_r1, sec_r2 = _extract_secondary_labels(coding_r1, coding_r2, segment_ids)n_r1 = sum(1 for l in sec_r1 if l != _NO_SECONDARY)n_r2 = sum(1 for l in sec_r2 if l != _NO_SECONDARY)n_both = sum(1 for a, b in zip(sec_r1, sec_r2)if a != _NO_SECONDARY and b != _NO_SECONDARY)if n_r1 == 0 and n_r2 == 0:return {"n_with_secondary_r1": 0,"n_with_secondary_r2": 0,"n_with_secondary_both": 0,"secondary_agreement_ac1":None,"secondary_ci_95": None,"secondary_interpretation":"no secondary dimensions used",}ac1 = round(_gwet_ac1(sec_r1, sec_r2), 4)ci = _bootstrap_ci(sec_r1, sec_r2, _gwet_ac1)return {"n_with_secondary_r1": n_r1,"n_with_secondary_r2": n_r2,"n_with_secondary_both": n_both,"secondary_agreement_ac1":ac1,"secondary_ci_95": list(ci),"secondary_interpretation":_interpret(ac1),}def _compute_codimension_frequency(coding_r1: dict,coding_r2: dict,segment_ids: list[str],) -> dict[str, int]:"""Count how often each (primary + secondary) dimension pair occursacross both raters' codings.Segments without a secondary are recorded as "{primary}" only.Segments with a secondary are recorded as "{primary}+{secondary}".This reveals which dimension combinations co-occur in the corpus —useful for theory refinement and for identifying where the single-codeassumption is most strained (Strijbos et al. 2006; Suthers & Rosen 2011)."""counts: dict[str, int] = {}for coding in [coding_r1, coding_r2]:for c in coding["codings"]:if c["segment_id"] not in segment_ids:continueprim = c.get("dimension_id", "?")sec = c.get("secondary_dimension_id")key = f"{prim}+{sec}" if sec else primcounts[key] = counts.get(key, 0) + 1# Sort by frequency descendingreturn dict(sorted(counts.items(), key=lambda x: -x[1]))# ---------------------------------------------------------------------------# Disagreement analysis (unchanged)# ---------------------------------------------------------------------------def identify_disagreements(4 unmodified linescoding_r2: dict,proposed_segments: dict,) -> list[dict]:map_comments_r1 = {c["segment_id"]: c.get("comment", "") for c in coding_r1["codings"]}map_comments_r2 = {c["segment_id"]: c.get("comment", "") for c in coding_r2["codings"]}disagreements = []for sid, d1, d2 in zip(segment_ids, labels_r1, labels_r2):if d1 != d2:seg = proposed_segments.get(sid, {})# Backwards-compatible field names use researcher_id prefixr1id = coding_r1["researcher_id"]r2id = coding_r2["researcher_id"]disagreements.append({"segment_id": sid,"start_time": seg.get("start_time"),"end_time": seg.get("end_time"),"agent_dimension": seg.get("dimension_id"),"agent1_dimension": seg.get("dimension_id"), # legacy key"agent1_rationale": seg.get("rationale"),"r1_dimension": d1,"r2_dimension": d2,f"{r1id}_dimension": d1,f"{r1id}_comment": map_comments_r1.get(sid, ""),f"{r2id}_dimension": d2,f"{r2id}_comment": map_comments_r2.get(sid, ""),"resolution_status": "pending","resolved_dimension": None,"resolution_note": "",})return disagreements# ---------------------------------------------------------------------------# Main report builder# ---------------------------------------------------------------------------6 unmodified linesoutput_path: Optional[Path] = None,) -> dict:"""Full inter-rater reliability report for a session.Returns a dict with both AC1 (primary) and κ (secondary), per-dimensionbreakdowns for both metrics, bootstrap CIs, prevalence diagnostics,and the full disagreement list with resolution tracking.The report is backwards-compatible: all fields present in the priorkappa-only report are retained. New fields are additive."""coding_r1 = load_coding(coding_r1_path)coding_r2 = load_coding(coding_r2_path)proposed_segments = load_proposed_segments(proposed_segments_path)errors = validate_codings(coding_r1, coding_r2, proposed_segments)if errors:raise ValueError("Coding validation failed:\n" + "\n".join(f" - {e}" for e in errors))segment_ids, labels_r1, labels_r2 = _build_aligned_labels(coding_r1, coding_r2)n = len(segment_ids)n_agree = sum(a == b for a, b in zip(labels_r1, labels_r2))n_dis = n - n_agree# ── Primary metric: Gwet's AC1 ──────────────────────────────────────────ac1 = round(_gwet_ac1(labels_r1, labels_r2), 4)ac1_ci = _bootstrap_ci(labels_r1, labels_r2, _gwet_ac1)ac1_dim = calculate_per_dimension_ac1(segment_ids, labels_r1, labels_r2)# ── Secondary metric: Cohen's κ ─────────────────────────────────────────kappa = round(_cohen_kappa(labels_r1, labels_r2), 4)kappa_ci = _bootstrap_ci(labels_r1, labels_r2, _cohen_kappa)kappa_dim = calculate_per_dimension_kappa(segment_ids, labels_r1, labels_r2)# ── Prevalence diagnostics ───────────────────────────────────────────────cat_dist = _compute_category_distribution(labels_r1, labels_r2)prev_warning = _prevalence_warning(cat_dist)divergence = round(abs(ac1 - kappa), 4)divergence_flag = divergence > 0.05 # notable divergence: κ is biased# ── Gate ────────────────────────────────────────────────────────────────gate_passed = ac1 >= AC1_GATE_THRESHOLD# ── Secondary dimension analysis ─────────────────────────────────────────secondary_analysis = _compute_secondary_agreement(coding_r1, coding_r2, segment_ids)codimension_freq = _compute_codimension_frequency(coding_r1, coding_r2, segment_ids)# ── Disagreements ────────────────────────────────────────────────────────disagreements = identify_disagreements(segment_ids, labels_r1, labels_r2,coding_r1, coding_r2, proposed_segments,)report = {# ── Session metadata ────────────────────────────────────────────────"session_id": session_id,"timestamp": datetime.now(timezone.utc).isoformat(),"researcher_1": coding_r1["researcher_id"],"researcher_2": coding_r2["researcher_id"],"n_segments_total": n,"n_segments_agreed": n_agree,"n_segments_disagreed": n_dis,# ── PRIMARY: Gwet's AC1 ─────────────────────────────────────────────"overall_ac1": ac1,"ac1_ci_95": list(ac1_ci),"ac1_interpretation": _interpret(ac1),"ac1_per_dimension": ac1_dim,# ── SECONDARY: Cohen's κ (kept for journal compatibility) ───────────"overall_kappa": kappa, # legacy key preserved"kappa_ci_95": list(kappa_ci),"kappa_interpretation": _interpret(kappa),"kappa_per_dimension": kappa_dim,# ── Gate ────────────────────────────────────────────────────────────"gate_metric": "gwet_ac1","gate_threshold": AC1_GATE_THRESHOLD,"gate_passed": gate_passed,# ── Prevalence diagnostics ──────────────────────────────────────────"category_distribution": cat_dist,"prevalence_warning": prev_warning,"kappa_ac1_divergence": divergence,"kappa_ac1_divergence_flag": divergence_flag,# ── Secondary dimension analysis ──────────────────────────────────────"secondary_dimension_analysis": secondary_analysis,"codimension_frequency": codimension_freq,# ── Disagreements ────────────────────────────────────────────────────"segments_in_disagreement": [d["segment_id"] for d in disagreements],"disagreements": disagreements,# ── Status ───────────────────────────────────────────────────────────"status": ("ready_for_agent2"if gate_passed and not disagreementselse "pending_disagreement_review"if gate_passedelse "below_threshold_review_required"),}if output_path:output_path.parent.mkdir(parents=True, exist_ok=True)output_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")print(f"[Reliability] Report saved to {output_path}")_print_summary(report)return report# ---------------------------------------------------------------------------# Disagreement resolution (unchanged API)# ---------------------------------------------------------------------------def resolve_disagreement(2 unmodified linesresolved_dimension: str,resolution_note: str,) -> dict:report = json.loads(report_path.read_text(encoding="utf-8"))found = Falsefor d in report["disagreements"]:if d["segment_id"] == segment_id:d["resolution_status"] = "resolved"d["resolved_dimension"] = resolved_dimensiond["resolution_note"] = resolution_notefound = Trueif not found:raise ValueError(f"Segment '{segment_id}' not found in disagreements.")if all(d["resolution_status"] in ("resolved", "discarded")for d in report["disagreements"]) and report["gate_passed"]:report["status"] = "ready_for_agent2"report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")print(f"[Reliability] Resolved {segment_id} → {resolved_dimension}")return report2 unmodified linessegment_id: str,discard_note: str,) -> dict:report = json.loads(report_path.read_text(encoding="utf-8"))for d in report["disagreements"]:if d["segment_id"] == segment_id:d["resolution_status"] = "discarded"d["resolved_dimension"] = Noned["resolution_note"] = discard_noteif all(d["resolution_status"] in ("resolved", "discarded")for d in report["disagreements"]) and report["gate_passed"]:report["status"] = "ready_for_agent2"report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")print(f"[Reliability] Discarded {segment_id}")return report2 unmodified lines# ---------------------------------------------------------------------------def _print_summary(report: dict) -> None:print("\n" + "═" * 60)print(f" RELIABILITY REPORT — {report['session_id']}")print("═" * 60)print(f" Raters : {report['researcher_1']} vs {report['researcher_2']}")print(f" Segments : {report['n_segments_total']} total, "f"{report['n_segments_agreed']} agreed, "f"{report['n_segments_disagreed']} disagreed")print()print(f" PRIMARY — Gwet's AC1 (Gwet 2008):")ac1_lo, ac1_hi = report['ac1_ci_95']print(f" AC1 = {report['overall_ac1']:.4f} "f"95% CI [{ac1_lo:.4f}, {ac1_hi:.4f}]")print(f" Interpretation: {report['ac1_interpretation']}")print(f" Gate (AC1 ≥ {report['gate_threshold']:.2f}): "f"{'✓ PASSED' if report['gate_passed'] else '✗ FAILED'}")print()print(f" SECONDARY — Cohen's κ (Cohen 1960) [for reference only]:")k_lo, k_hi = report['kappa_ci_95']print(f" κ = {report['overall_kappa']:.4f} "f"95% CI [{k_lo:.4f}, {k_hi:.4f}]")print(f" |AC1 - κ| = {report['kappa_ac1_divergence']:.4f}"+ (" ← notable divergence (prevalence bias in κ)"if report['kappa_ac1_divergence_flag'] else ""))if report.get("prevalence_warning"):dom = max(report["category_distribution"].items(),key=lambda x: x[1]["prevalence"])print(f"\n ⚠ Prevalence warning: '{dom[0]}' accounts for "f"{dom[1]['prevalence']:.0%} of all codings. "f"AC1 is the appropriate metric here.")print("\n Per-dimension AC1 (one-vs-rest):")for dim in DIMENSIONS:v = report["ac1_per_dimension"].get(dim)if v is not None:bar = "▓" * int(v * 20)gate_flag = " ✓" if v >= AC1_GATE_THRESHOLD else " ·"print(f" {dim} {v:.3f} {bar}{gate_flag}")else:print(f" {dim} — (insufficient data)")# Secondary dimension summarysec = report.get("secondary_dimension_analysis", {})if sec.get("n_with_secondary_r1", 0) > 0 or sec.get("n_with_secondary_r2", 0) > 0:print(f"\n Secondary dimensions:")print(f" R1 used secondary in {sec.get('n_with_secondary_r1',0)} segments")print(f" R2 used secondary in {sec.get('n_with_secondary_r2',0)} segments")print(f" Both used secondary in {sec.get('n_with_secondary_both',0)} segments")ac1s = sec.get("secondary_agreement_ac1")if ac1s is not None:print(f" Secondary AC1: {ac1s:.4f} ({sec.get('secondary_interpretation','')})")cdf = report.get("codimension_frequency", {})multi_pairs = {k: v for k, v in cdf.items() if "+" in k}if multi_pairs:print(f" Co-occurring pairs:")for pair, count in list(multi_pairs.items())[:5]:print(f" {pair}: {count}x")else:print("\n Secondary dimensions: none used in this session")print(f"\n Status: {report['status']}")print("═" * 60 + "\n")# ---------------------------------------------------------------------------# Coding template generator (unchanged)# ---------------------------------------------------------------------------def generate_coding_template(2 unmodified linessession_id: str,output_path: Path,) -> None:proposed = json.loads(proposed_segments_path.read_text(encoding="utf-8"))template = {"researcher_id": researcher_id,"session_id": session_id,"instructions": ("Fill in dimension_id (D1–D9, NS=Not Sure, NA=Not Applicable). ""Use comment for boundary concerns or ambiguity notes."),"codings": [{"segment_id": seg["segment_id"],"start_time": seg.get("start_time"),"end_time": seg.get("end_time"),"agent1_label": seg.get("dimension_id"),"agent1_rationale": seg.get("rationale"),"dimension_id": "","comment": "",}for seg in proposed["segments"]],}output_path.parent.mkdir(parents=True, exist_ok=True)output_path.write_text(json.dumps(template, indent=2, ensure_ascii=False), encoding="utf-8")print(f"[Reliability] Template for {researcher_id} saved to {output_path}")# ---------------------------------------------------------------------------5 unmodified linesif len(sys.argv) < 2:print("Usage:")print(" python kappa_calculator.py calc <session_id> <r1.json> <r2.json> <segments.json> [report.json]")print(" python kappa_calculator.py template <segments.json> <researcher_id> <session_id> <output.json>")sys.exit(1)command = sys.argv[1]if command == "calc":calculate_kappa_report(sys.argv[2], Path(sys.argv[3]), Path(sys.argv[4]), Path(sys.argv[5]),Path(sys.argv[6]) if len(sys.argv) > 6 else None,)elif command == "template":generate_coding_template(Path(sys.argv[2]), sys.argv[3], sys.argv[4], Path(sys.argv[5]))else:print(f"Unknown command: {command}")sys.exit(1)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""llm_client.py-------------Shared LLM client for Agent 1 and Agent 2.Uses Qwen 2.5 72B via the Hugging Face Inference API.Chosen for strong Japanese language understanding and reliable JSON output.Requires HF_TOKEN environment variable (huggingface.co/settings/tokens)."""import osimport timefrom huggingface_hub import InferenceClientMODEL = "Qwen/Qwen2.5-72B-Instruct"_client: InferenceClient | None = NoneTIMEOUT_SECS = 180 # generous for large chunks on a 72B modeldef _get_client() -> InferenceClient:global _clientif _client is None:token = os.environ.get("HF_TOKEN")if not token:raise RuntimeError("HF_TOKEN environment variable is not set.")_client = InferenceClient(model=MODEL, token=token, timeout=TIMEOUT_SECS)return _clientdef call_llm(system_prompt: str, user_prompt: str, max_tokens: int = 4000) -> str:"""Send a system + user prompt to Qwen 2.5 72B and return the response text.Retries up to 3 times with backoff on transient errors (504, 503, etc)."""client = _get_client()messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": user_prompt},]for attempt in range(3):try:response = client.chat.completions.create(messages=messages,max_tokens=max_tokens,temperature=0.1,)return response.choices[0].message.contentexcept Exception as e:is_transient = any(code in str(e) for code in ("504", "503", "502", "429"))if attempt < 2 and is_transient:wait = 5 * (attempt + 1)print(f"[LLM] Transient error (attempt {attempt+1}), retrying in {wait}s…")time.sleep(wait)continueraise RuntimeError(f"LLM API error: {e}") from e123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283"""llm_client.py-------------Shared LLM client with instrumentation, adaptive timeout, and circuit breaker.Model: Qwen/Qwen2.5-72B-Instruct via Hugging Face Inference API.Requires HF_TOKEN environment variable.Design references-----------------Adaptive timeout:The Fallacies of Distributed Computing (Deutsch, 1994) — network callswill fail; callers must not assume a fixed latency. Timeout is afunction of expected payload, not a constant.Circuit breaker pattern:Nygard, M. (2007). Release It! Design and Deploy Production-ReadySoftware. Pragmatic Bookshelf.— After N consecutive failures, open the circuit so callers fail fastrather than accumulating threads waiting on a dead service.Exponential backoff with jitter:Marc Brooker (2015). "Exponential Backoff And Jitter." AWS Architecture Blog.— Prevents thundering-herd retry storms under load.Stats / observability:Sigelman et al. (2010). Dapper: A Large-Scale Distributed SystemsTracing Infrastructure. Google Technical Report.— Every meaningful call should carry timing and size metadata."""from __future__ import annotationsimport osimport timeimport randomimport threadingfrom dataclasses import dataclass, fieldfrom typing import Optionalfrom huggingface_hub import InferenceClientMODEL = "Qwen/Qwen2.5-72B-Instruct"TEMPERATURE = 0.1# Timeout bounds (seconds)_TIMEOUT_MIN = 45_TIMEOUT_MAX = 300_CHARS_PER_SEC = 800 # empirical chars-per-second at Qwen 72B on HF inference# Circuit breaker_CB_FAILURE_THRESHOLD = 4 # consecutive failures before opening_CB_RESET_SECS = 120 # seconds before trying again# Retry policy_MAX_RETRIES = 3_RETRY_BASE_SECS = 4 # first backoff; doubles each attempt + jitter_TRANSIENT_CODES = ("504", "503", "502", "429", "timeout", "Timeout")# ---------------------------------------------------------------------------# Return type# ---------------------------------------------------------------------------@dataclassclass LLMCallStats:"""Instrumentation record for a single LLM call."""model: strtemperature: floatsystem_chars: intuser_chars: intresponse_chars: intestimated_in_tok: int # rough: chars / 4estimated_out_tok: inttimeout_used_s: intwall_time_s: floatretries: intsuccess: boolerror: Optional[str] = None@propertydef estimated_total_tok(self) -> int:return self.estimated_in_tok + self.estimated_out_tok# ---------------------------------------------------------------------------# Circuit breaker (per-process singleton)# ---------------------------------------------------------------------------class _CircuitBreaker:"""Three-state finite state machine:CLOSED — normal operationOPEN — refusing calls (too many consecutive failures)HALF_OPEN— one probe call allowed to test recovery"""def __init__(self):self._lock = threading.Lock()self._failures = 0self._state = "CLOSED" # CLOSED | OPEN | HALF_OPENself._opened_at: Optional[float] = Nonedef allow_call(self) -> bool:with self._lock:if self._state == "CLOSED":return Trueif self._state == "OPEN":if time.monotonic() - self._opened_at >= _CB_RESET_SECS:self._state = "HALF_OPEN"print(f"[LLM] Circuit half-open — probe call allowed.")return Truereturn False# HALF_OPENreturn Truedef record_success(self):with self._lock:self._failures = 0if self._state != "CLOSED":print(f"[LLM] Circuit closed — service recovered.")self._state = "CLOSED"def record_failure(self):with self._lock:self._failures += 1if self._failures >= _CB_FAILURE_THRESHOLD and self._state != "OPEN":self._state = "OPEN"self._opened_at = time.monotonic()print(f"[LLM] Circuit OPENED after {self._failures} consecutive failures. "f"Will retry in {_CB_RESET_SECS}s.")@propertydef state(self) -> str:return self._state_circuit_breaker = _CircuitBreaker()_client: Optional[InferenceClient] = None# ---------------------------------------------------------------------------# Client factory# ---------------------------------------------------------------------------def _get_client(timeout_s: int) -> InferenceClient:"""Create a new client per call so timeout is respected per-request."""token = os.environ.get("HF_TOKEN")if not token:raise RuntimeError("HF_TOKEN environment variable is not set. ""Get a token at huggingface.co/settings/tokens.")return InferenceClient(model=MODEL, token=token, timeout=timeout_s)# ---------------------------------------------------------------------------# Adaptive timeout# ---------------------------------------------------------------------------def compute_timeout(system_prompt: str, user_prompt: str, max_tokens: int) -> int:"""Scale timeout to expected payload size.Formula:timeout = input_chars / chars_per_sec + max_tokens / tok_per_sec + bufferwhere chars_per_sec and tok_per_sec are empirical constants for Qwen 72B on HF.Clipped to [_TIMEOUT_MIN, _TIMEOUT_MAX]."""input_chars = len(system_prompt) + len(user_prompt)# Estimate generation time: ~40 tokens/sec for 72B on HF shared inferencegen_secs = max_tokens / 40# Estimate prefill time: ~800 chars/secprefill_secs = input_chars / _CHARS_PER_SECraw = prefill_secs + gen_secs + 15 # 15s network + queuing bufferreturn int(min(max(raw, _TIMEOUT_MIN), _TIMEOUT_MAX))# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------def call_llm(system_prompt: str, user_prompt: str, max_tokens: int = 4000) -> str:"""Backwards-compatible wrapper: returns response text only."""text, _ = call_llm_timed(system_prompt, user_prompt, max_tokens)return textdef call_llm_timed(system_prompt: str,user_prompt: str,max_tokens: int = 4000,) -> tuple[str, LLMCallStats]:"""Call the LLM and return (response_text, stats).Implements:- Adaptive timeout based on payload size- Exponential backoff with jitter on transient errors- Circuit breaker to fail fast when service is down"""if not _circuit_breaker.allow_call():raise RuntimeError(f"LLM circuit breaker is OPEN (too many consecutive failures). "f"Will auto-reset in {_CB_RESET_SECS}s. Check HF service status.")timeout_s = compute_timeout(system_prompt, user_prompt, max_tokens)messages = [{"role": "system", "content": system_prompt},{"role": "user", "content": user_prompt},]sys_chars = len(system_prompt)user_chars = len(user_prompt)est_in = (sys_chars + user_chars) // 4t0 = time.perf_counter()last_error: Optional[str] = Nonefor attempt in range(_MAX_RETRIES):try:client = _get_client(timeout_s)response = client.chat.completions.create(messages=messages,max_tokens=max_tokens,temperature=TEMPERATURE,)text = response.choices[0].message.contentwall = round(time.perf_counter() - t0, 2)_circuit_breaker.record_success()stats = LLMCallStats(model=MODEL, temperature=TEMPERATURE,system_chars=sys_chars, user_chars=user_chars,response_chars=len(text),estimated_in_tok=est_in,estimated_out_tok=len(text) // 4,timeout_used_s=timeout_s,wall_time_s=wall,retries=attempt,success=True,)return text, statsexcept Exception as exc:last_error = str(exc)is_transient = any(code in last_error for code in _TRANSIENT_CODES)if attempt < _MAX_RETRIES - 1 and is_transient:# Exponential backoff with ±25% jitter (Brooker 2015)base_wait = _RETRY_BASE_SECS * (2 ** attempt)wait = base_wait * (0.75 + random.random() * 0.5)print(f"[LLM] Transient error (attempt {attempt + 1}/{_MAX_RETRIES}), "f"retrying in {wait:.1f}s… ({last_error[:80]})")time.sleep(wait)continue_circuit_breaker.record_failure()wall = round(time.perf_counter() - t0, 2)stats = LLMCallStats(model=MODEL, temperature=TEMPERATURE,system_chars=sys_chars, user_chars=user_chars,response_chars=0,estimated_in_tok=est_in, estimated_out_tok=0,timeout_used_s=timeout_s,wall_time_s=wall,retries=attempt + 1,success=False,error=last_error,)raise RuntimeError(f"LLM call failed after {attempt + 1} attempt(s): {last_error}") from exc# Should not reach hereraise RuntimeError(f"LLM call exhausted retries: {last_error}")def circuit_state() -> str:"""Expose circuit breaker state for the UI transparency panel."""return _circuit_breaker.state
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409"""pipeline.py-----------Multi-agent pipeline orchestrator for CollabCode.
Architecture: Parallel Map with Context Chain=============================================
┌─────────────────────────────────────────────────────┐ Transcript │ Agent 0 (1 LLM call, whole transcript) │ ─────────────►│ Produces: section map + handoff documents │ └──────────────────┬──────────────────────────────────┘ │ handoff doc per section ┌──────────────────▼──────────────────────────────────┐ │ Parallel Agent 1a (N concurrent LLM calls) │ Human confirms│ Each section: boundary detection with section ctx │ sections ───►│ Produces: boundary results + episode handoffs │ └──────────────────┬──────────────────────────────────┘ │ boundary handoff per section ┌──────────────────▼──────────────────────────────────┐ │ Agent 1b (sequential per section after human review)│ Human adjusts │ Coding with boundary context from Agent 1a │ boundaries ──►│ Produces: coded segments │ └─────────────────────────────────────────────────────┘
Key design patterns-------------------
1. Parallel Map (Agent 1a) Sections are causally independent — Agent 0 fixes their boundaries before 1a runs, so 1a sections can execute concurrently. ThreadPoolExecutor with max_workers=3 limits API rate pressure. Literature: Dean & Ghemawat (2004). MapReduce: Simplified data processing on large clusters. OSDI 2004. — parallel map over independent partitions. Wu et al. (2023). AutoGen: Enabling next-gen LLM applications via multi-agent conversation. arXiv:2308.08155. — concurrent agent execution model.
2. Context Chain (handoff documents) Each agent writes a structured memo that the next agent reads. This reduces cold-start errors at agent handoffs and gives Agent 1b the boundary rationale rather than starting from zero. Literature: Park et al. (2023). Generative agents: Interactive simulacra of human behavior. UIST 2023. — agents maintain and pass memory summaries to downstream consumers. Hong et al. (2023). MetaGPT: Meta programming for multi-agent collaborative framework. ICLR 2024. — structured output documents flowing between agents. Shinn et al. (2023). Reflexion: Language agents with verbal reinforcement learning. NeurIPS 2023. — agents build context from prior observations.
3. Progress streaming A threading.Queue bridges the parallel worker threads to the Gradio generator, emitting one yield per completed section. The researcher sees a live table update rather than a frozen UI. Literature: Nielsen, J. (1994). Usability Engineering, ch.8. Academic Press. — response feedback within 10s required to maintain user flow.
4. Stats tracking (PipelineStats) Every call records wall time, estimated tokens, retries, and timeout. Speedup vs. sequential is computed and shown in the UI. Literature: Sigelman et al. (2010). Dapper: A Large-Scale Distributed Systems Tracing Infrastructure. Google Technical Report. — distributed tracing for latency analysis.
5. Circuit-breaker awareness Workers check llm_client._circuit_breaker before dispatching. Failed sections are marked ERROR and returned to the researcher rather than silently dropped or retried indefinitely."""
from __future__ import annotations
import queueimport threadingimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclass, fieldfrom typing import Callable, Iterator, Optional
from llm_client import call_llm_timed, LLMCallStats, circuit_state
# Maximum parallel workers for Agent 1a.# 3 balances latency vs. HF Inference API rate limits (typically ~5 req/min# for free tier; 3 leaves headroom for retries).MAX_PARALLEL_WORKERS = 3
# ---------------------------------------------------------------------------# Data structures# ---------------------------------------------------------------------------
@dataclassclass SectionResult: """Outcome of one Agent 1a or Agent 1b call for a single section.""" section_id: str section_label: str success: bool result: Optional[dict] # the agent's output dict stats: Optional[LLMCallStats] wall_time_s: float error: Optional[str] = None
@property def status_icon(self) -> str: if self.success: return "✓" return "✗"
@dataclassclass PipelineStats: """Aggregate statistics for the full pipeline run.""" agent_name: str n_sections: int results: list[SectionResult] = field(default_factory=list) parallel_wall_s: float = 0.0 sequential_est_s: float = 0.0 # what it would have taken serially
@property def n_success(self) -> int: return sum(1 for r in self.results if r.success)
@property def n_error(self) -> int: return sum(1 for r in self.results if not r.success)
@property def speedup(self) -> float: if self.parallel_wall_s <= 0: return 1.0 return round(self.sequential_est_s / self.parallel_wall_s, 1)
@property def total_estimated_tokens(self) -> int: return sum( r.stats.estimated_total_tok for r in self.results if r.stats and r.success )
def summary_line(self) -> str: spd = f"{self.speedup:.1f}×" if self.speedup > 1.1 else "—" return ( f"{self.n_success}/{self.n_sections} OK · " f"{self.parallel_wall_s:.0f}s wall · " f"~{self.speedup:.1f}× faster than serial · " f"~{self.total_estimated_tokens:,} tokens" )
# ---------------------------------------------------------------------------# Handoff document builders# ---------------------------------------------------------------------------
def build_agent0_section_handoff(section: dict, session_overview: str) -> dict: """ Package the context that Agent 0 produces for one section into the format Agent 1a will consume. """ return { "session_overview": session_overview, "section_id": section.get("section_id", ""), "section_label": section.get("label", ""), "section_summary": section.get("summary", ""), "start_time": section.get("start_time", ""), "end_time": section.get("end_time", ""), }
def build_agent1a_boundary_handoff(section: dict, agent1a_result: dict) -> dict: """ Package Agent 1a's boundary analysis for Agent 1b to consume.
Agent 1b receives the boundary rationale and episode distribution so it can calibrate its coding to the local conversational structure rather than starting cold (Park et al. 2023 — agent memory passing). """ boundaries = agent1a_result.get("boundaries", []) segments = agent1a_result.get("segments", []) n_boundaries = len(boundaries)
# Summarise the boundary signals found signal_counts: dict[str, int] = {} for b in boundaries: sig = b.get("boundary_signal", "unknown") signal_counts[sig] = signal_counts.get(sig, 0) + 1
signal_summary = "; ".join( f"{n} {sig.replace('_', ' ')}" for sig, n in signal_counts.items() ) or "no boundaries — single episode"
# Build short episode previews for Agent 1b context episode_previews = [] for seg in segments[:6]: # cap at 6 to avoid prompt bloat turns = seg.get("turns", []) if turns: episode_previews.append({ "segment_id": seg["segment_id"], "first_turn": turns[0].get("text", "")[:80], })
return { "section_id": section.get("section_id", ""), "section_label": section.get("label", ""), "section_summary": section.get("summary", ""), "n_boundaries": n_boundaries, "n_episodes": len(segments), "boundary_signals": signal_summary, "episode_previews": episode_previews, }
# ---------------------------------------------------------------------------# Parallel Agent 1a runner# ---------------------------------------------------------------------------
def run_boundaries_parallel( sections: list[dict], all_turns: list[dict], session_id: str, session_overview: str = "", max_workers: int = MAX_PARALLEL_WORKERS,) -> Iterator[tuple[SectionResult, PipelineStats]]: """ Run Agent 1a on all sections concurrently.
Yields (SectionResult, PipelineStats_so_far) after each section completes so callers can stream progress. The final yield contains the complete stats.
Design ------ Uses a threading.Queue to bridge worker threads and the caller's generator loop (Nielsen 1994 — live feedback prevents perceived freeze). Workers share a ThreadPoolExecutor; results arrive in completion order, not submission order (as_completed pattern).
Args ---- sections : confirmed section list from Agent 0 + human review. all_turns : full parsed turn list for the session. session_id : used for segment ID namespacing. session_overview : Agent 0's session-level summary (context chain). max_workers : parallel worker cap (default 3 to respect API limits). """ from agent1a_boundary import propose_boundaries_with_context
result_q: queue.Queue[SectionResult | None] = queue.Queue() t_wall_start = time.perf_counter() stats = PipelineStats( agent_name="Agent 1a — Boundary Detector", n_sections=len(sections), )
def _worker(sec: dict) -> None: turns = [t for t in all_turns if sec["start_turn_id"] <= t["turn_id"] <= sec["end_turn_id"]] t0 = time.perf_counter() handoff_in = build_agent0_section_handoff(sec, session_overview)
try: result, llm_stats = propose_boundaries_with_context( section=sec, turns=turns, session_id=session_id, agent0_handoff=handoff_in, ) sr = SectionResult( section_id=sec["section_id"], section_label=sec.get("label", ""), success=True, result=result, stats=llm_stats, wall_time_s=round(time.perf_counter() - t0, 1), ) except Exception as exc: sr = SectionResult( section_id=sec["section_id"], section_label=sec.get("label", ""), success=False, result=None, stats=None, wall_time_s=round(time.perf_counter() - t0, 1), error=str(exc), ) result_q.put(sr)
# Dispatch all workers executor = ThreadPoolExecutor(max_workers=max_workers) for sec in sections: executor.submit(_worker, sec) executor.shutdown(wait=False)
# Collect and yield as results arrive n_received = 0 while n_received < len(sections): sr = result_q.get(timeout=_TIMEOUT_MAX_WAIT) stats.results.append(sr) n_received += 1
if n_received == len(sections): # All done — compute final stats stats.parallel_wall_s = round(time.perf_counter() - t_wall_start, 1) stats.sequential_est_s = sum( r.wall_time_s for r in stats.results )
yield sr, stats
_TIMEOUT_MAX_WAIT = 360 # max seconds to wait for any single section result
# ---------------------------------------------------------------------------# Sequential Agent 1b runner (per-section, after human boundary review)# ---------------------------------------------------------------------------
def run_coding_with_context( section: dict, segments: list[dict], agent1a_result: Optional[dict] = None, library_root=None,) -> tuple[list[dict], LLMCallStats]: """ Run Agent 1b on one section, enriched with Agent 1a's boundary handoff.
Returns (coded_segments, stats). """ from agent1b_coder import code_section_with_context
boundary_handoff = ( build_agent1a_boundary_handoff(section, agent1a_result) if agent1a_result else None ) return code_section_with_context( section=section, segments=segments, boundary_handoff=boundary_handoff, library_root=library_root, )
# ---------------------------------------------------------------------------# Stats rendering (for UI transparency panel)# ---------------------------------------------------------------------------
def render_pipeline_stats_html(stats: PipelineStats) -> str: """Render PipelineStats as an HTML block for the UI agent log.""" rows = "" for r in stats.results: tok_str = f"~{r.stats.estimated_total_tok:,}" if r.stats else "—" time_str = f"{r.wall_time_s:.1f}s" icon = r.status_icon icon_col = "#065f46" if r.success else "#be123c" rows += ( f'<tr>' f'<td style="padding:4px 8px;font-weight:600">{r.section_id}</td>' f'<td style="padding:4px 8px;color:#475569">{r.section_label[:22]}</td>' f'<td style="padding:4px 8px;font-family:monospace">{time_str}</td>' f'<td style="padding:4px 8px;font-family:monospace;color:#64748b">{tok_str}</td>' f'<td style="padding:4px 8px;font-weight:700;color:{icon_col}">{icon}</td>' f'</tr>' )
if not rows: return ""
speedup_line = "" if stats.speedup > 1.1: speedup_line = ( f'<div style="background:#ecfdf5;border:1px solid #86efac;border-radius:6px;' f'padding:8px 12px;margin-bottom:8px;font-size:0.82em;color:#065f46">' f'<strong>⚡ {stats.speedup:.1f}× faster</strong> than sequential processing — ' f'{stats.parallel_wall_s:.0f}s wall vs ~{stats.sequential_est_s:.0f}s serial · ' f'~{stats.total_estimated_tokens:,} tokens total' f'</div>' )
cb_state = circuit_state() cb_line = "" if cb_state != "CLOSED": cb_line = ( f'<div style="background:#fef2f2;border:1px solid #fca5a5;border-radius:6px;' f'padding:6px 12px;margin-bottom:6px;font-size:0.8em;color:#991b1b">' f'⚠ Circuit breaker: <strong>{cb_state}</strong>' f'</div>' )
return ( f'{cb_line}{speedup_line}' f'<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;' f'letter-spacing:0.08em;color:#94a3b8;margin-bottom:6px">' f'{stats.agent_name}</div>' f'<table style="border-collapse:collapse;width:100%;font-size:0.8em">' f'<tr style="background:#f1f5f9;font-size:0.75em;font-weight:600;color:#64748b">' f'<th style="padding:4px 8px;text-align:left">Section</th>' f'<th style="padding:4px 8px;text-align:left">Label</th>' f'<th style="padding:4px 8px;text-align:left">Time</th>' f'<th style="padding:4px 8px;text-align:left">~Tokens</th>' f'<th style="padding:4px 8px;text-align:left">OK</th>' f'</tr>' f'{rows}</table>' )agent1a_boundary.py+79-7
agent1b_coder.py+156-14
app.py+400-152
kappa_calculator.py+599-296
llm_client.py+253-28
pipeline.pyAdded+409