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82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
"""
agent1_segmenter.py
-------------------
Agent 1: The Segmenter.

Responsibilities:
- Load Tier 1 library (dimensions, examples, coding rules)
- Load Tier 2 validated learnings (if any exist)
- Receive a window of transcript turns
- Call the Claude API to segment and code each window
- Return structured segments with dimension codes, rationale, confidence,
  uncertainty flags, and open/closed boundary status
- Hand back the open segment start position for the next window

Agent 1 must NEVER read Tier 3 (candidate/quarantined learnings).
"""

import json
from pathlib import Path
from typing import Optional

from llm_client import call_llm


# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------

LIBRARY_ROOT = Path(__file__).parent / "library"
TIER1_PATH   = LIBRARY_ROOT / "tier1_core"
TIER2_PATH   = LIBRARY_ROOT / "tier2_validated"

MAX_TOKENS       = 4000
# Single-pass limit: transcripts up to ~200 turns fit comfortably.
# Beyond this the model takes too long to generate the full JSON response.
SINGLE_PASS_CHAR_LIMIT = 20_000
# Chunk size in turns for longer transcripts
CHUNK_TURNS      = 150


# ---------------------------------------------------------------------------
# Library loader
# ---------------------------------------------------------------------------

def load_tier1() -> dict:
    """Load all Tier 1 files. Raises if any file is missing or malformed."""
    dimensions   = json.loads((TIER1_PATH / "dimensions.json").read_text())
    examples     = json.loads((TIER1_PATH / "examples.json").read_text())
    coding_rules = json.loads((TIER1_PATH / "coding_rules.json").read_text())
    return {
        "dimensions":   dimensions["dimensions"],
        "examples":     examples["examples"],
        "coding_rules": coding_rules["rules"],
    }


def load_tier2() -> dict:
    """Load Tier 2 validated learnings. Returns empty structures if not yet populated."""
    learned_rules = json.loads((TIER2_PATH / "learned_rules.json").read_text())
    edge_cases    = json.loads((TIER2_PATH / "edge_cases.json").read_text())
    return {
        "learned_rules": learned_rules.get("learned_rules", []),
        "edge_cases":    edge_cases.get("edge_cases", []),
    }


# ---------------------------------------------------------------------------
# Prompt builder
# ---------------------------------------------------------------------------

def _format_dimensions(dimensions: list[dict]) -> str:
    lines = []
    for d in dimensions:
        lines.append(f"[{d['id']}] {d['label']}")
        lines.append(f"  Summary: {d['summary']}")
        lines.append(f"  Key behavioral markers:")
        for marker in d["key_behavioral_markers"]:
            lines.append(f"    - {marker}")
        lines.append("")
    return "\n".join(lines)


def _format_examples(examples: list[dict]) -> str:
    lines = []
    for ex in examples:
        lines.append(f"Dimension: {ex['dimension_id']} ({ex['type'].upper()})")
        lines.append(f"Label: {ex['label']}")
        for turn in ex["exchange"]:
            lines.append(f"  {turn['speaker']}: {turn['text']}")
        lines.append(f"Note: {ex['annotation_note']}")
        lines.append("")
    return "\n".join(lines)


def _format_rules(rules: list[dict]) -> str:
    return "\n".join(
        f"[{r['rule_id']}] {r['label']}: {r['description']}"
        for r in rules
    )


def _format_learned(tier2: dict) -> str:
    rules = tier2.get("learned_rules", [])
    cases = tier2.get("edge_cases", [])
    if not rules and not cases:
        return "None yet."
    lines = []
    for r in rules:
        lines.append(f"- LEARNED RULE: {r.get('description', '')}")
    for c in cases:
        lines.append(f"- EDGE CASE: {c.get('description', '')}")
    return "\n".join(lines)


def _format_turns(turns: list[dict]) -> str:
    lines = []
    for t in turns:
        lines.append(
            f"[turn_{t['turn_id']}] [{t['start_time']}] {t['speaker']}: {t['text']}"
        )
    return "\n".join(lines)


def build_system_prompt(tier1: dict, tier2: dict) -> str:
    return f"""You are a behavioral coding assistant trained in collaborative learning research.
Your task is to segment a transcript excerpt into episodes and assign each episode
a dimension code from a theory-driven coding framework.

You must follow all coding rules exactly. You may not infer beyond what is
observable in the transcript text.

=== DIMENSION DEFINITIONS ===
{_format_dimensions(tier1['dimensions'])}

=== ANCHOR EXAMPLES ===
{_format_examples(tier1['examples'])}

=== CODING RULES (MANDATORY) ===
{_format_rules(tier1['coding_rules'])}

=== VALIDATED LEARNINGS FROM PRIOR CODING SESSIONS ===
{_format_learned(tier2)}

=== OUTPUT FORMAT ===
You must respond ONLY with a valid JSON object. No preamble, no explanation outside the JSON.

The JSON must follow this exact structure:
{{
  "segments": [
    {{
      "segment_id": "string β€” use format seg_001, seg_002 etc.",
      "start_turn_id": integer,
      "end_turn_id": integer,
      "start_time": "HH:MM:SS",
      "end_time": "HH:MM:SS",
      "dimension_id": "D1 to D9",
      "dimension_label": "string",
      "boundary_status": "closed or open",
      "confident": true or false,
      "uncertain": true or false,
      "uncertainty_note": "string or null β€” name competing dimension and why if uncertain",
      "rationale": "1-2 sentences citing specific observable behaviors from the turns"
    }}
  ],
  "window_summary": {{
    "total_turns_processed": integer,
    "total_segments_found": integer,
    "last_segment_status": "closed or open",
    "next_window_start_turn_id": integer or null
  }}
}}

If the last segment is OPEN, set next_window_start_turn_id to the start_turn_id
of that open segment. The next window will begin from there.
If the last segment is CLOSED, set next_window_start_turn_id to null.
"""


def build_user_prompt(turns: list[dict]) -> str:
    return f"""Please segment and code the following transcript excerpt.

=== TRANSCRIPT TURNS ===
{_format_turns(turns)}

Remember:
- Assign exactly one dimension per segment
- Flag uncertainty if two dimensions are competing
- Mark the last segment as OPEN if the episode is not behaviorally complete
- Base your rationale only on observable turn content
"""


# ---------------------------------------------------------------------------
# API call
# ---------------------------------------------------------------------------

def _call_claude(system_prompt: str, user_prompt: str) -> str:
    return call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)


# ---------------------------------------------------------------------------
# Response parser
# ---------------------------------------------------------------------------

def _parse_response(raw: str) -> dict:
    """
    Parse Claude's JSON response. Strips markdown fences if present.
    Raises ValueError with details if the response is malformed.
    """
    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:
        parsed = json.loads(cleaned)
    except json.JSONDecodeError as e:
        raise ValueError(
            f"Agent 1 returned invalid JSON.\nError: {e}\nRaw response:\n{raw}"
        ) from e

    # Basic validation
    if "segments" not in parsed:
        raise ValueError(f"Response missing 'segments' key.\nRaw:\n{raw}")
    if "window_summary" not in parsed:
        raise ValueError(f"Response missing 'window_summary' key.\nRaw:\n{raw}")

    return parsed


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def segment_window(
    turns: list[dict],
    session_id: str,
    window_index: int,
    library_root: Optional[Path] = None,
) -> dict:
    """
    Segment a window of transcript turns.

    Args:
        turns:        List of turn dicts from transcript_parser.parse_transcript()
        session_id:   Identifier for this transcript/dyad session
        window_index: Which window this is (0-indexed), used for segment ID namespacing
        library_root: Override for library path (useful for testing)

    Returns:
        Dict with keys: segments, window_summary, session_id, window_index
    """
    global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH
    if library_root:
        LIBRARY_ROOT = library_root
        TIER1_PATH   = library_root / "tier1_core"
        TIER2_PATH   = library_root / "tier2_validated"

    if not turns:
        raise ValueError("No turns provided to segment_window.")

    # Load library β€” Tier 1 always, Tier 2 always, Tier 3 NEVER
    tier1 = load_tier1()
    tier2 = load_tier2()

    # Build prompts
    system_prompt = build_system_prompt(tier1, tier2)
    user_prompt   = build_user_prompt(turns)

    # Call API
    raw_response = _call_claude(system_prompt, user_prompt)

    # Parse and validate
    result = _parse_response(raw_response)

    # Namespace segment IDs to avoid collisions across windows
    prefix = f"w{window_index:02d}"
    for seg in result["segments"]:
        seg["segment_id"] = f"{session_id}_{prefix}_{seg['segment_id']}"

    result["session_id"]   = session_id
    result["window_index"] = window_index

    return result


def _call_single_pass(
    turns: list[dict],
    session_id: str,
    chunk_index: int,
    system_prompt: str,
) -> list[dict]:
    """Send one batch of turns to the LLM and return namespaced segments."""
    user_prompt = build_user_prompt(turns)
    raw         = _call_claude(system_prompt, user_prompt)
    result      = _parse_response(raw)

    prefix = f"c{chunk_index:02d}"
    for seg in result["segments"]:
        seg["segment_id"] = f"{session_id}_{prefix}_{seg['segment_id']}"

    print(f"[Agent 1] Chunk {chunk_index}: {len(result['segments'])} segments "
          f"(turns {turns[0]['turn_id']}–{turns[-1]['turn_id']})")
    return result["segments"]


def run_full_transcript(
    turns: list[dict],
    session_id: str,
    library_root: Optional[Path] = None,
) -> list[dict]:
    """
    Segment an entire transcript.

    Strategy:
      - Load library once.
      - If the formatted transcript fits within SINGLE_PASS_CHAR_LIMIT, send it
        in a single LLM call (best context, fewest calls).
      - If it exceeds the limit, split into CHUNK_TURNS-turn chunks with a
        small overlap so episodes that straddle a boundary are not lost.

    Returns:
        List of all segments across all chunks, in order.
    """
    global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH
    if library_root:
        LIBRARY_ROOT = library_root
        TIER1_PATH   = library_root / "tier1_core"
        TIER2_PATH   = library_root / "tier2_validated"

    if not turns:
        raise ValueError("No turns provided.")

    # Load library once
    tier1         = load_tier1()
    tier2         = load_tier2()
    system_prompt = build_system_prompt(tier1, tier2)

    formatted = _format_turns(turns)

    # ── Single pass ──────────────────────────────────────────────────────────
    if len(formatted) <= SINGLE_PASS_CHAR_LIMIT:
        print(f"[Agent 1] Single-pass mode ({len(turns)} turns, "
              f"{len(formatted):,} chars)")
        return _call_single_pass(turns, session_id, 0, system_prompt)

    # ── Chunked fallback ─────────────────────────────────────────────────────
    overlap  = CHUNK_TURNS // 10          # 10 % overlap between chunks
    step     = CHUNK_TURNS - overlap
    chunks   = [turns[i:i + CHUNK_TURNS] for i in range(0, len(turns), step)]

    print(f"[Agent 1] Chunked mode ({len(turns)} turns β†’ {len(chunks)} chunks "
          f"of ~{CHUNK_TURNS} with {overlap}-turn overlap)")

    all_segments: list[dict] = []
    # Track covered turn ranges by (start_turn_id, end_turn_id) to deduplicate
    # segments from overlapping chunks. Segment IDs cannot be used here because
    # each chunk gets a different prefix (c00_, c01_, …), so two segments covering
    # identical turns would have different IDs and both be included β€” a real bug
    # that creates duplicate coverage of the overlap zone.
    seen_turn_ranges: set[tuple[int, int]] = set()

    for idx, chunk in enumerate(chunks):
        segs = _call_single_pass(chunk, session_id, idx, system_prompt)
        for seg in segs:
            turn_range = (seg["start_turn_id"], seg["end_turn_id"])
            if turn_range not in seen_turn_ranges:
                seen_turn_ranges.add(turn_range)
                all_segments.append(seg)

    print(f"[Agent 1] Complete. Total segments: {len(all_segments)}")
    return all_segments


# ---------------------------------------------------------------------------
# Save output
# ---------------------------------------------------------------------------

def save_segments(segments: list[dict], output_path: Path) -> None:
    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(
        json.dumps({"segments": segments}, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )
    print(f"[Agent 1] Segments saved to {output_path}")


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 3:
        print("Usage: python agent1_segmenter.py <parsed_turns.json> <session_id> [output.json]")
        sys.exit(1)

    turns_file = Path(sys.argv[1])
    session_id = sys.argv[2]
    output_file = Path(sys.argv[3]) if len(sys.argv) > 3 else Path(f"sessions/{session_id}/segments_proposed.json")

    turns = json.loads(turns_file.read_text())
    segments = run_full_transcript(turns, session_id)
    save_segments(segments, output_file)