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
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""
agent1b_coder.py
----------------
Agent 1b: The Dimension Coder.

Given segments with confirmed boundaries (from Agent 1a + human review),
assigns each segment a dimension code from the D1–D9 framework. Operates
on one topical section at a time, using section context to inform coding.

Rationale for separating coding from segmentation
--------------------------------------------------
See agent1a_boundary.py for the full argument. In brief:

  Krippendorff, K. (2004). Content analysis (ch. 7). Sage.
  β€” Unitising and categorising are distinct cognitive operations.
    Interleaving them in one prompt inflates apparent agreement by
    constraining where boundaries can fall to match preferred codes.

  Pustejovsky, J., & Stubbs, A. (2012). Natural Language Annotation for
    Machine Learning (ch. 4). O'Reilly.

Section context window
----------------------
Providing Agent 1b with the section label and summary (from Agent 0) acts
as a form of "discourse context" shown to improve coding reliability in:

  Reidsma, D., & Carletta, J. (2008). Reliability measurement without
    limits. Computational Linguistics, 34(3), 319–326.
    β€” Annotators with shared discourse context show higher kappa.

Uncertainty-first routing (active learning)
-------------------------------------------
Agent 1b flags segments as uncertain, enabling researchers to prioritise
review of those cases β€” the core insight from uncertainty sampling:

  Settles, B. (2012). Active learning. Synthesis Lectures on Artificial
    Intelligence and Machine Learning, 6(1), 1–114. Morgan & Claypool.

  Monarch, R. (2021). Human-in-the-loop machine learning (ch. 3).
    Manning. β€” Confidence-based routing to human review.

Collaborative learning dimension framework
------------------------------------------
The D1–D9 coding scheme implemented here follows the multi-dimensional
quality rating approach established in:

  Meier, A., Spada, H., & Rummel, N. (2007). A rating scheme for assessing
    the quality of computer-supported collaboration processes.
    International Journal of Computer-Supported Collaborative Learning,
    2(1), 63–86.

  Rummel, N., & Spada, H. (2005). Learning to collaborate: An instructional
    approach to promoting collaborative problem solving in computer-mediated
    settings. Journal of the Learning Sciences, 14(2), 201–241.

Agent 1b reads Tier 1 (core definitions) and Tier 2 (validated learnings).
Agent 1b NEVER reads Tier 3 (candidate corrections β€” reserved for Agent 2).
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Optional

from llm_client import call_llm

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

MAX_TOKENS      = 3000
MAX_SEGS_PER_CALL = 8  # batch ceiling β€” prevents context overflow on large sections


# ---------------------------------------------------------------------------
# Library loaders
# ---------------------------------------------------------------------------

def load_tier1() -> dict:
    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:
    learned_rules = json.loads((TIER2_PATH / "learned_rules.json").read_text())
    edge_cases    = json.loads((TIER2_PATH / "edge_cases.json").read_text())
    return {
        # Only active (approved) rules reach Agent 1b
        "learned_rules": [
            r for r in learned_rules.get("learned_rules", [])
            if r.get("active")
        ],
        "edge_cases": edge_cases.get("edge_cases", []),
    }


# ---------------------------------------------------------------------------
# Formatters
# ---------------------------------------------------------------------------

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('rule_type')}]: {r.get('description', '')}"
        )
    for c in cases:
        lines.append(f"- EDGE CASE: {c.get('description', '')}")
    return "\n".join(lines)


def _format_segment(seg: dict) -> str:
    turns = seg.get("turns", [])
    lines = [
        f"Segment ID: {seg['segment_id']}  "
        f"({seg.get('start_time', '?')} – {seg.get('end_time', '?')})"
    ]
    for t in turns:
        lines.append(f"  [{t['turn_id']}] {t['speaker']}: {t['text']}")
    return "\n".join(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's
    boundary analysis handoff.

    Receiving the boundary rationale means Agent 1b knows why each episode
    was carved out β€” it can use this to calibrate dimension assignment, e.g.
    if a boundary fell on a 'sequence_completion', Agent 1b knows the episode
    it 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', '?')} episodes
carved 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 your
dimension 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 decision
solely on observable turn content.
{boundary_context}

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

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

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

=== 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 speakers
    also actively check understanding throughout β†’ D4 primary, D1 secondary

Set secondary_dimension_id to null if no secondary applies. Do not force it.

This follows Strijbos et al. (2006) and Suthers & Rosen (2011): discourse moves
are 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"
    }}
  ]
}}
"""


def build_user_prompt(segments: list[dict]) -> str:
    seg_text = "\n\n".join(_format_segment(s) for s in segments)
    return (
        f"Please assign a dimension code to each of the following "
        f"{len(segments)} segment(s).\n\n{seg_text}\n\n"
        "Base rationale only on observable turn content."
    )


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

def _parse_response(raw: str) -> list[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 1b returned invalid JSON.\nError: {e}\nRaw:\n{raw}"
        ) from e
    if "coded_segments" not in result:
        raise ValueError("Agent 1b response missing 'coded_segments' key.")
    return result["coded_segments"]


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

def code_section(
    section: dict,
    segments: list[dict],
    library_root: Optional[Path] = None,
) -> list[dict]:
    """
    Assign dimension codes to all segments in one confirmed section.

    Batches the LLM call if the section has more than MAX_SEGS_PER_CALL
    segments, to avoid context overflow with many long turns.

    Args:
        section:      Confirmed section dict (for context window).
        segments:     Uncoded segment dicts from Agent 1a (boundaries confirmed
                      by the researcher).
        library_root: Override library path (for testing).

    Returns:
        List of segment dicts with dimension_id, rationale, confident, and
        uncertain fields filled. The 'turns' key is preserved for the UI.
    """
    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 segments:
        return []

    print(
        f"[Agent 1b] Coding {len(segments)} segments in "
        f"{section['section_id']} β€” {section['label']}..."
    )

    tier1         = load_tier1()
    tier2         = load_tier2()
    system_prompt = build_system_prompt(tier1, tier2, section)

    # Batch into groups to respect context limits
    batches = [
        segments[i:i + MAX_SEGS_PER_CALL]
        for i in range(0, len(segments), MAX_SEGS_PER_CALL)
    ]

    all_coded: dict[str, dict] = {}
    for batch_idx, batch in enumerate(batches):
        user_prompt = build_user_prompt(batch)
        raw         = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
        coded_batch = _parse_response(raw)
        for c in coded_batch:
            all_coded[c["segment_id"]] = c
        if len(batches) > 1:
            print(
                f"[Agent 1b] Batch {batch_idx + 1}/{len(batches)} complete "
                f"({len(coded_batch)} segments)"
            )

    # Merge coded fields back into original segment dicts (preserving 'turns')
    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)} segments coded, "
        f"{n_uncertain} flagged uncertain β€” route to researcher review."
    )
    return result


def 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 it
    can better calibrate dimension assignment to the local conversational
    structure (Hong et al. 2023 MetaGPT β€” inter-agent document passing).
    """
    from llm_client import call_llm_timed

    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 segments:
        return [], None

    print(
        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 = None

    for 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       = stats
        coded_batch      = _parse_response(raw)
        for c in coded_batch:
            all_coded[c["segment_id"]] = c
        if 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"))
    wall_str = f"{last_stats.wall_time_s:.1f}s" if last_stats else "?s"
    print(
        f"[Agent 1b] {section['section_id']}: {len(result)} coded, "
        f"{n_uncertain} uncertain ({wall_str})"
    )
    return result, last_stats