""" agent1a_boundary.py ------------------- Agent 1a: The Boundary Detector. Given a confirmed topical section, proposes episode boundaries — the turn positions where one behavioral episode ends and another begins. This is a purely structural task; dimension coding is delegated entirely to Agent 1b. Why separate boundary detection from coding? -------------------------------------------- Krippendorff (2004, ch. 7) establishes that unitising (defining segment boundaries) should precede categorisation. Mixing the two tasks in one prompt conflates structurally distinct cognitive operations and reduces reliability in both. Annotation research consistently shows that human coders perform better when these tasks are separated: Krippendorff, K. (2004). Content analysis: An introduction to its methodology (2nd ed., ch. 7 "Unitizing"). Sage. MacWhinney, B. (2000). The CHILDES Project: Tools for analyzing talk (3rd ed.). Lawrence Erlbaum. — CLAN/ELAN annotation workflows define utterance units before assigning any tier labels. Pustejovsky, J., & Stubbs, A. (2012). Natural Language Annotation for Machine Learning (ch. 4). O'Reilly. — "Unit definition is logically and procedurally prior to labelling." Episode boundary signals ------------------------ Based on conversation analysis (Schegloff 2007) and pragmatics (Levinson 1983): Schegloff, E. A. (2007). Sequence organization in interaction (vol. 1). Cambridge University Press. — Adjacency pairs, sequence completion, transition relevance points. Levinson, S. C. (1983). Pragmatics (ch. 6). Cambridge University Press. — Turn-taking machinery and episode closure. Jefferson, G. (1984). On the organization of laughter in talk about troubles. In J. M. Atkinson & J. Heritage (Eds.), Structures of social action. Cambridge University Press. — Completion signals in interaction. Stivers, T., & Robinson, J. D. (2006). A preference for progressivity in interaction. Language in Society, 35(3), 367–392. — Topic shift as an interactional resource. Agent 1a reads NO library tiers (no Tier 1/2/3). Agent 1a NEVER assigns dimension codes. """ from __future__ import annotations import json from pathlib import Path from llm_client import call_llm MAX_TOKENS = 1500 # --------------------------------------------------------------------------- # Formatters # --------------------------------------------------------------------------- def _format_turns(turns: list[dict]) -> str: lines = [] for t in turns: lines.append( f"[{t['turn_id']:>4}] {t['start_time']} {t['speaker']}: {t['text']}" ) return "\n".join(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 what activity type to expect in this section, reducing cold-start errors at 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 boundaries within a section of a collaborative work transcript. An episode boundary marks where one coherent behavioral unit ends and another begins. You are NOT assigning dimension codes — only marking transition points. Boundary signals (Schegloff 2007; Levinson 1983): explicit_transition — turn-initial markers: "OK", "right", "so", "now let's", "moving on", "anyway", or speaker explicitly closes topic sequence_completion — an adjacency pair completes (Q answered, request fulfilled) and neither speaker continues on that thread activity_change — the dyad shifts from one type of action to another (e.g. reading aloud → discussing → coding → reviewing) topic_exhaustion — topic reaches a natural close before a new one opens, marked by silence, acknowledgement tokens, or reformulation Confidence levels: high — clear boundary signal present in the transcript text medium — likely boundary but signal is ambiguous or implicit low — 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 list and set n_episodes to 1. """ def build_user_prompt(section: dict, turns: list[dict]) -> str: return f"""Section: {section['section_id']} — {section['label']} Summary: {section.get('summary', '')} Turns: {turns[0]['turn_id']} – {turns[-1]['turn_id']} ({len(turns)} total) === TRANSCRIPT === {_format_turns(turns)} Identify episode boundaries within this section. """ # --------------------------------------------------------------------------- # Response parser # --------------------------------------------------------------------------- def _parse_response(raw: str, section_id: str) -> dict: cleaned = raw.strip() if cleaned.startswith("```"): cleaned = "\n".join(cleaned.split("\n")[1:]) if cleaned.endswith("```"): cleaned = "\n".join(cleaned.split("\n")[:-1]) cleaned = cleaned.strip() try: result = json.loads(cleaned) except json.JSONDecodeError as e: raise ValueError( f"Agent 1a returned invalid JSON for {section_id}.\n" f"Error: {e}\nRaw:\n{raw}" ) from e if "boundaries" not in result: raise ValueError( f"Agent 1a response missing 'boundaries' key for {section_id}." ) return result # --------------------------------------------------------------------------- # Boundary → segment converter # --------------------------------------------------------------------------- def boundaries_to_segments( section: dict, turns: list[dict], boundaries: list[dict], session_id: str, ) -> list[dict]: """ Convert a boundary list into uncoded segment dicts (turn ranges only). Each segment spans from one boundary to the next. The first segment starts at the section's first turn; the last ends at the section's last turn. Dimension fields are left as None for Agent 1b to fill. """ if not turns: return [] turn_ids = sorted(t["turn_id"] for t in turns) turn_map = {t["turn_id"]: t for t in turns} # Cut points: start of section + one cut per boundary cut_starts = [turn_ids[0]] for b in sorted(boundaries, key=lambda x: x["after_turn_id"]): after = b["after_turn_id"] if after in turn_ids: idx = turn_ids.index(after) if idx < len(turn_ids) - 1: cut_starts.append(turn_ids[idx + 1]) segments = [] for i, start in enumerate(cut_starts): if i + 1 < len(cut_starts): end_idx = turn_ids.index(cut_starts[i + 1]) - 1 end = turn_ids[end_idx] else: end = turn_ids[-1] seg_turns = [t for t in turns if start <= t["turn_id"] <= end] if not seg_turns: continue ep_num = i + 1 seg_id = f"{session_id}_{section['section_id']}_ep{ep_num:02d}" segments.append({ "segment_id": seg_id, "section_id": section["section_id"], "start_turn_id": start, "end_turn_id": end, "start_time": turn_map[start]["start_time"], "end_time": turn_map[end]["start_time"], "turns": seg_turns, # Filled by Agent 1b "dimension_id": None, "dimension_label": None, "rationale": None, "confident": None, "uncertain": None, "uncertainty_note": None, }) return segments # --------------------------------------------------------------------------- # Public API # --------------------------------------------------------------------------- def propose_boundaries( section: dict, turns: list[dict], session_id: str, ) -> dict: """ Propose episode boundaries for one confirmed topical section. Args: section: Confirmed section dict (section_id, label, summary, turn range). turns: The turns belonging to this section. session_id: Session identifier (used in segment ID namespacing). Returns: Dict with: section_id, boundaries, n_episodes, segments (uncoded). """ print( f"[Agent 1a] Proposing boundaries for {section['section_id']} " f"— {section['label']} ({len(turns)} turns)..." ) system_prompt = build_system_prompt() user_prompt = build_user_prompt(section, turns) raw = call_llm(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) # Attach boundary metadata to each segment for UI display boundary_map: dict[int, dict] = {} for b in boundaries: boundary_map[b["after_turn_id"]] = b for seg in segments: prev_end = seg["start_turn_id"] - 1 seg["_boundary_before"] = boundary_map.get(prev_end) print( f"[Agent 1a] {section['section_id']}: " f"{len(boundaries)} boundaries → {len(segments)} episodes" ) return { "section_id": section["section_id"], "boundaries": boundaries, "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 at section 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_timed print( 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