Spaces:
Sleeping

File size: 12,959 Bytes
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a95ee9
 
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d176097
5b5a20d
d176097
5b5a20d
 
d176097
5b5a20d
 
 
 
 
d176097
5b5a20d
 
d176097
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d176097
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
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
"""
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