Spaces:
Sleeping

File size: 31,928 Bytes
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a95ee9
 
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a95ee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
 
 
 
 
 
 
 
 
 
2a95ee9
 
 
 
5b5a20d
2a95ee9
 
 
5b5a20d
 
2a95ee9
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a95ee9
 
 
 
 
5b5a20d
 
 
 
2a95ee9
 
 
 
5b5a20d
 
 
 
 
 
2a95ee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab719c7
5b5a20d
 
 
 
ab719c7
 
 
 
 
 
5b5a20d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
"""
agent2_learner.py
-----------------
Agent 2: The Learner.

Responsibilities:
- Only activates after kappa gate is passed AND all disagreements are resolved/discarded
- Reads Tier 3 candidate corrections (NEVER Tier 1 or Tier 2 directly)
- Reads validated kappa reports to understand agreement patterns
- Extracts three types of rules: boundary clarifications, disambiguation rules,
  behavioral marker refinements
- Writes candidate rules to Tier 2 with status: pending_review
- Rules only become active for Agent 1 after a human researcher approves them
- Never rewrites or contradicts Tier 1
- Never operates below the minimum segment threshold

Sample size rationale (encoded as constants):
  With 9 dimensions and a target kappa >= 0.70, power analysis indicates:
  - Statistical floor: ~85 segments for 80% power (PMC12935580)
  - Safe zone: 90-120 segments, accounting for unbalanced category distributions
    across 9 dimensions (some like D6, D7 are naturally sparse in collaboration
    corpora, inflating variance and requiring larger N for stable per-dim kappa)
  - Reference: Bujang & Baharum (2017), Guidelines for minimum sample size
    requirements for Cohen's Kappa. Epidemiology, Biostatistics and Public Health.

Rule types Agent 2 is allowed to write:
  Type 1 β€” Boundary clarification
  Type 2 β€” Disambiguation rule (between two specific dimensions)
  Type 3 β€” Behavioral marker refinement (context-specific sharpening)

What Agent 2 can NEVER write:
  - A redefinition of a dimension's core meaning
  - A rule that contradicts Tier 1
  - A rule from sessions where discarded segments exceed 20%
  - A rule without human approval before it goes live for Agent 1
"""

from __future__ import annotations

import json
import uuid
from pathlib import Path
from datetime import datetime, timezone
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"
TIER3_PATH      = LIBRARY_ROOT / "tier3_candidate"

MAX_TOKENS      = 2000

# Sample size thresholds β€” see module docstring for statistical rationale
MIN_SEGMENTS_FOR_LEARNING   = 90   # statistical floor (80% power, ΞΊ=0.70, 9 dims)
RECOMMENDED_SEGMENTS        = 120  # safe zone for unbalanced 9-dim distributions
MAX_DISCARD_RATE            = 0.20 # max proportion of discarded segments allowed
MIN_SESSIONS_BEFORE_WRITING = 3    # minimum validated sessions before first rule

RULE_TYPES = [
    "boundary_clarification",
    "disambiguation_rule",
    "behavioral_marker_refinement",
]


# ---------------------------------------------------------------------------
# Session accumulator β€” tracks how many validated segments exist so far
# ---------------------------------------------------------------------------

def count_validated_segments(sessions_root: Path) -> tuple[int, int]:
    """
    Count total validated segments across all sessions that:
    - Passed the kappa gate
    - Have status ready_for_agent2
    - Have a discard rate <= MAX_DISCARD_RATE

    Returns (n_valid_sessions, n_valid_segments).
    """
    n_sessions  = 0
    n_segments  = 0

    if not sessions_root.exists():
        return 0, 0

    for session_dir in sessions_root.iterdir():
        if not session_dir.is_dir():
            continue
        report_path = session_dir / "kappa_report.json"
        if not report_path.exists():
            continue

        try:
            report = json.loads(report_path.read_text(encoding="utf-8"))
        except Exception:
            continue

        if report.get("status") != "ready_for_agent2":
            continue
        if not report.get("gate_passed"):
            continue

        # Check discard rate
        total = report.get("n_segments_total", 0)
        discarded = sum(
            1 for d in report.get("disagreements", [])
            if d.get("resolution_status") == "discarded"
        )
        if total > 0 and discarded / total > MAX_DISCARD_RATE:
            continue

        n_sessions += 1
        n_segments += total

    return n_sessions, n_segments


# ---------------------------------------------------------------------------
# Tier 3 loader β€” the ONLY library tier Agent 2 reads
# ---------------------------------------------------------------------------

def load_tier3_candidates() -> list[dict]:
    """Load all pending candidate corrections from Tier 3."""
    pending_path = TIER3_PATH / "pending_review.json"
    if not pending_path.exists():
        return []
    data = json.loads(pending_path.read_text(encoding="utf-8"))
    return data.get("pending_review", [])


def load_tier1_dimension_ids() -> list[str]:
    """
    Load ONLY the dimension IDs and labels from Tier 1 β€” just enough for
    Agent 2 to validate that its rules reference real dimensions.
    Agent 2 does NOT read full Tier 1 definitions.
    """
    dims = json.loads((TIER1_PATH / "dimensions.json").read_text())
    return [{"id": d["id"], "label": d["label"]} for d in dims["dimensions"]]


def load_existing_tier2_rules() -> list[dict]:
    """Load existing validated rules so Agent 2 doesn't duplicate them."""
    rules_path = TIER2_PATH / "learned_rules.json"
    if not rules_path.exists():
        return []
    data = json.loads(rules_path.read_text(encoding="utf-8"))
    return data.get("learned_rules", [])


# ---------------------------------------------------------------------------
# Kappa report loader for context
# ---------------------------------------------------------------------------

def load_ready_reports(sessions_root: Path) -> list[dict]:
    """Load all kappa reports that are ready for Agent 2."""
    reports = []
    if not sessions_root.exists():
        return reports

    for session_dir in sessions_root.iterdir():
        if not session_dir.is_dir():
            continue
        report_path = session_dir / "kappa_report.json"
        if not report_path.exists():
            continue
        try:
            report = json.loads(report_path.read_text(encoding="utf-8"))
            if report.get("status") == "ready_for_agent2":
                reports.append(report)
        except Exception:
            continue

    return reports


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

def _format_candidates(candidates: list[dict]) -> str:
    if not candidates:
        return "No candidate corrections in Tier 3 yet."
    lines = []
    for c in candidates:
        lines.append(f"Candidate ID: {c.get('candidate_id', 'unknown')}")
        lines.append(f"  Session: {c.get('session_id')}")
        lines.append(f"  Segment: {c.get('segment_id')}")
        # Primary dimension
        a1_sec = c.get("agent1_secondary_dimension")
        lines.append(f"  Agent 1 primary: {c.get('agent1_dimension')}"
                     + (f" | secondary: {a1_sec}" if a1_sec else ""))
        r1_sec = c.get("r1_secondary_dimension")
        lines.append(f"  R1 primary: {c.get('r1_dimension')}"
                     + (f" | secondary: {r1_sec}" if r1_sec else "")
                     + f" | Comment: {c.get('r1_comment', '')}")
        r2_sec = c.get("r2_secondary_dimension")
        lines.append(f"  R2 primary: {c.get('r2_dimension')}"
                     + (f" | secondary: {r2_sec}" if r2_sec else "")
                     + f" | Comment: {c.get('r2_comment', '')}")
        res_sec = c.get("resolved_secondary_dimension")
        lines.append(f"  Resolved primary: {c.get('resolved_dimension', 'unresolved')}"
                     + (f" | secondary: {res_sec}" if res_sec else ""))
        lines.append(f"  Resolution note: {c.get('resolution_note', '')}")
        lines.append(f"  Agent 1 rationale: {c.get('agent1_rationale', '')}")
        lines.append("")
    return "\n".join(lines)


def _format_kappa_summary(reports: list[dict]) -> str:
    if not reports:
        return "No session reports available."
    lines = []
    for r in reports:
        # Use AC1 as primary reliability metric; fall back to kappa for legacy reports
        ac1   = r.get("overall_ac1", r.get("overall_kappa", "?"))
        kappa = r.get("overall_kappa", "?")
        lines.append(f"Session: {r['session_id']} | AC1: {ac1} | ΞΊ: {kappa} | "
                     f"Segments: {r['n_segments_total']} | Disagreed: {r['n_segments_disagreed']}")
        # Per-dimension reliability: prefer AC1, fall back to kappa
        dim_rel = r.get("ac1_per_dimension") or r.get("kappa_per_dimension", {})
        low_dims = [f"{d}={k:.2f}" for d, k in dim_rel.items()
                    if k is not None and k < 0.70]
        if low_dims:
            lines.append(f"  Low-reliability dimensions: {', '.join(low_dims)}")
    return "\n".join(lines)


def _format_existing_rules(rules: list[dict]) -> str:
    if not rules:
        return "No rules written yet."
    lines = []
    for r in rules:
        lines.append(f"- [{r.get('rule_type')}] {r.get('description')} "
                     f"(approved: {r.get('approved', False)})")
    return "\n".join(lines)


def _format_dimension_ids(dims: list[dict]) -> str:
    return ", ".join(f"{d['id']} ({d['label']})" for d in dims)


def build_system_prompt(
    dimension_ids: list[dict],
    existing_rules: list[dict],
) -> str:
    return f"""You are a methodology assistant for a qualitative research coding project.
Your task is to extract generalizable rules from researcher corrections to improve
a behavioral coding agent (Agent 1).

You operate under STRICT constraints. Read them carefully.

=== DIMENSIONS (for reference only β€” do NOT redefine these) ===
{_format_dimension_ids(dimension_ids)}

=== EXISTING TIER 2 RULES (do not duplicate these) ===
{_format_existing_rules(existing_rules)}

=== RULE TYPES YOU ARE ALLOWED TO WRITE ===
1. boundary_clarification
   When: You see a pattern in WHERE boundaries are placed incorrectly
   Format: "When [behavioral pattern X] transitions to [behavioral pattern Y],
            the boundary falls after [specific observable signal Z]"

2. disambiguation_rule
   Between two specific dimensions that researchers consistently confuse.
   Format: "When [D_X] and [D_Y] appear to co-occur, assign [D_X] if [condition A],
            assign [D_Y] if [condition B]"

3. behavioral_marker_refinement
   A context-specific sharpening of an existing behavioral marker.
   Format: "In this corpus, [observable behavior] is a marker of [D_X], not [D_Y],
            because [observable reason]"

=== CONSTRAINTS YOU MUST NEVER VIOLATE ===
- Never redefine a dimension's core meaning
- Never contradict the dimension definitions
- Only write rules that are clearly supported by MULTIPLE corrections (not a single case)
- Every rule must cite the candidate IDs it was derived from
- Never invent examples β€” only use what the corrections show
- If the corrections are too sparse or inconsistent to support a rule, return an empty list
- Rules about boundary placement must reference observable turn-level behaviors, not inferences

=== OUTPUT FORMAT ===
Respond ONLY with valid JSON. No preamble, no explanation outside the JSON.

{{
  "proposed_rules": [
    {{
      "rule_type": "boundary_clarification | disambiguation_rule | behavioral_marker_refinement",
      "dimensions_involved": ["D1", "D2"],
      "description": "Full rule text as specified above",
      "rationale": "Why this rule is supported by the corrections β€” cite candidate_ids",
      "derived_from_candidates": ["candidate_id_1", "candidate_id_2"],
      "confidence": "high | medium | low",
      "agent2_note": "Any caveats or conditions the reviewing researcher should consider"
    }}
  ],
  "learning_summary": {{
    "candidates_reviewed": integer,
    "rules_proposed": integer,
    "patterns_too_sparse": ["description of pattern seen but not actionable yet"],
    "recommendation": "brief note to researchers on what to watch for in future sessions"
  }}
}}

If no rules can be reliably derived, return proposed_rules as an empty list
and explain in learning_summary why.
"""


def build_user_prompt(
    candidates: list[dict],
    reports: list[dict],
) -> str:
    return f"""Please review the following researcher corrections and kappa reports.
Extract generalizable rules where the pattern is clear and consistent.

=== TIER 3 CANDIDATE CORRECTIONS ===
{_format_candidates(candidates)}

=== KAPPA REPORT SUMMARIES ===
{_format_kappa_summary(reports)}

Remember:
- Only propose rules supported by multiple consistent corrections
- Cite candidate IDs in your rationale
- If in doubt, return an empty list β€” a sparse rule is worse than no rule
"""


# ---------------------------------------------------------------------------
# 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:
    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:
        return json.loads(cleaned)
    except json.JSONDecodeError as e:
        raise ValueError(
            f"Agent 2 returned invalid JSON.\nError: {e}\nRaw:\n{raw}"
        ) from e


# ---------------------------------------------------------------------------
# Tier 2 writer β€” writes rules with pending_review status
# ---------------------------------------------------------------------------

def write_rules_to_tier2(
    proposed_rules: list[dict],
    sessions_contributing: list[str],
    n_segments_contributing: int,
) -> list[dict]:
    """
    Write proposed rules to Tier 2 with status pending_review.
    Rules are NOT active for Agent 1 until approved = True.

    Returns the list of written rule records.
    """
    rules_path = TIER2_PATH / "learned_rules.json"
    data       = json.loads(rules_path.read_text(encoding="utf-8"))

    written = []
    for rule in proposed_rules:
        record = {
            "rule_id":                  str(uuid.uuid4())[:8],
            "rule_type":                rule.get("rule_type"),
            "dimensions_involved":      rule.get("dimensions_involved", []),
            "description":              rule.get("description"),
            "rationale":                rule.get("rationale"),
            "derived_from_candidates":  rule.get("derived_from_candidates", []),
            "sessions_contributing":    sessions_contributing,
            "n_segments_contributing":  n_segments_contributing,
            "confidence":               rule.get("confidence"),
            "agent2_note":              rule.get("agent2_note", ""),
            "approved":                 False,           # MUST be reviewed by human
            "approved_by":              None,
            "approved_at":              None,
            "approval_note":            "",
            "created_at":               datetime.now(timezone.utc).isoformat(),
            "active":                   False,           # only True after approval
        }
        data["learned_rules"].append(record)
        written.append(record)

    data["_meta"]["last_updated"]  = datetime.now(timezone.utc).isoformat()
    data["_meta"]["total_entries"] = len(data["learned_rules"])

    rules_path.write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )

    return written


# ---------------------------------------------------------------------------
# Rule approval β€” called by researcher
# ---------------------------------------------------------------------------

def approve_rule(
    rule_id: str,
    approved_by: str,
    approval_note: str = "",
) -> dict:
    """
    Approve a pending rule. Sets approved=True and active=True.
    Only after this does Agent 1 see the rule.

    Args:
        rule_id:      The rule_id to approve
        approved_by:  Researcher ID approving the rule
        approval_note: Optional note on why this rule was approved

    Returns updated rule record.
    """
    rules_path = TIER2_PATH / "learned_rules.json"
    data       = json.loads(rules_path.read_text(encoding="utf-8"))

    updated = None
    for rule in data["learned_rules"]:
        if rule["rule_id"] == rule_id:
            rule["approved"]     = True
            rule["active"]       = True
            rule["approved_by"]  = approved_by
            rule["approved_at"]  = datetime.now(timezone.utc).isoformat()
            rule["approval_note"] = approval_note
            updated = rule
            break

    if updated is None:
        raise ValueError(f"Rule {rule_id} not found in Tier 2.")

    rules_path.write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )
    print(f"[Agent 2] Rule {rule_id} approved by {approved_by} β†’ now active for Agent 1")
    return updated


def reject_rule(
    rule_id: str,
    rejected_by: str,
    rejection_note: str,
) -> dict:
    """
    Reject a pending rule. Marks it as rejected so it is never shown to Agent 1.
    The record is kept for audit purposes.
    """
    rules_path = TIER2_PATH / "learned_rules.json"
    data       = json.loads(rules_path.read_text(encoding="utf-8"))

    updated = None
    for rule in data["learned_rules"]:
        if rule["rule_id"] == rule_id:
            rule["approved"]     = False
            rule["active"]       = False
            rule["approved_by"]  = rejected_by
            rule["approved_at"]  = datetime.now(timezone.utc).isoformat()
            rule["approval_note"] = f"REJECTED: {rejection_note}"
            updated = rule
            break

    if updated is None:
        raise ValueError(f"Rule {rule_id} not found in Tier 2.")

    rules_path.write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )
    print(f"[Agent 2] Rule {rule_id} rejected by {rejected_by}")
    return updated


# ---------------------------------------------------------------------------
# Tier 3 writer β€” called by kappa_calculator when disagreements are resolved
# ---------------------------------------------------------------------------

def add_to_tier3(
    session_id: str,
    segment_id: str,
    agent1_dimension: str,
    agent1_rationale: str,
    r1_dimension: str,
    r1_comment: str,
    r2_dimension: str,
    r2_comment: str,
    resolved_dimension: str,
    resolution_note: str,
    # Secondary dimension fields β€” optional, preserved for Agent 2 learning
    r1_secondary_dimension: Optional[str] = None,
    r2_secondary_dimension: Optional[str] = None,
    agent1_secondary_dimension: Optional[str] = None,
    resolved_secondary_dimension: Optional[str] = None,
) -> str:
    """
    Add a resolved disagreement to Tier 3 for Agent 2 to review later.
    Returns the candidate_id of the new entry.

    Secondary dimension fields are optional. When present they give Agent 2
    richer context: if researchers consistently mark D1 as secondary alongside
    D3, Agent 2 can propose a disambiguation or co-occurrence rule.
    """
    pending_path = TIER3_PATH / "pending_review.json"
    data         = json.loads(pending_path.read_text(encoding="utf-8"))

    candidate_id = str(uuid.uuid4())[:8]
    entry = {
        "candidate_id":                 candidate_id,
        "session_id":                   session_id,
        "segment_id":                   segment_id,
        "added_at":                     datetime.now(timezone.utc).isoformat(),
        "agent1_dimension":             agent1_dimension,
        "agent1_secondary_dimension":   agent1_secondary_dimension,
        "agent1_rationale":             agent1_rationale,
        "r1_dimension":                 r1_dimension,
        "r1_secondary_dimension":       r1_secondary_dimension,
        "r1_comment":                   r1_comment,
        "r2_dimension":                 r2_dimension,
        "r2_secondary_dimension":       r2_secondary_dimension,
        "r2_comment":                   r2_comment,
        "resolved_dimension":           resolved_dimension,
        "resolved_secondary_dimension": resolved_secondary_dimension,
        "resolution_note":              resolution_note,
        "consumed":                     False,
    }

    data["pending_review"].append(entry)
    data["_meta"]["last_updated"]  = datetime.now(timezone.utc).isoformat()
    data["_meta"]["total_entries"] = len(data["pending_review"])

    pending_path.write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )

    print(f"[Tier 3] Added candidate {candidate_id} from session {session_id}")
    return candidate_id


# ---------------------------------------------------------------------------
# Main learning run
# ---------------------------------------------------------------------------

def run_learning_cycle(
    sessions_root: Path,
    library_root: Optional[Path] = None,
    dry_run: bool = False,
) -> dict:
    """
    Run a full Agent 2 learning cycle.

    Args:
        sessions_root: Path to the sessions directory
        library_root:  Override library path (for testing)
        dry_run:       If True, extract rules but do not write to Tier 2

    Returns:
        Dict with proposed rules, learning summary, and gate status.
    """
    global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH, TIER3_PATH
    if library_root:
        LIBRARY_ROOT = library_root
        TIER1_PATH   = library_root / "tier1_core"
        TIER2_PATH   = library_root / "tier2_validated"
        TIER3_PATH   = library_root / "tier3_candidate"

    print("\n[Agent 2] Starting learning cycle...")

    # ── Gate 1: minimum sessions ──────────────────────────────────────────
    n_sessions, n_segments = count_validated_segments(sessions_root)
    print(f"[Agent 2] Validated sessions: {n_sessions} | Segments: {n_segments}")

    if n_sessions < MIN_SESSIONS_BEFORE_WRITING:
        print(f"[Agent 2] BLOCKED β€” minimum {MIN_SESSIONS_BEFORE_WRITING} sessions required "
              f"({n_sessions} available). Learning cycle skipped.")
        return {
            "status": "blocked_insufficient_sessions",
            "n_sessions": n_sessions,
            "n_segments": n_segments,
            "required_sessions": MIN_SESSIONS_BEFORE_WRITING,
            "proposed_rules": [],
        }

    # ── Gate 2: minimum segments ──────────────────────────────────────────
    if n_segments < MIN_SEGMENTS_FOR_LEARNING:
        print(f"[Agent 2] WARNING β€” below statistical floor of {MIN_SEGMENTS_FOR_LEARNING} "
              f"segments ({n_segments} available). Rules will be low-confidence.")

    if n_segments >= RECOMMENDED_SEGMENTS:
        print(f"[Agent 2] Segment count ({n_segments}) in safe zone (β‰₯{RECOMMENDED_SEGMENTS}).")
    elif n_segments >= MIN_SEGMENTS_FOR_LEARNING:
        print(f"[Agent 2] Segment count ({n_segments}) above floor but below safe zone "
              f"({RECOMMENDED_SEGMENTS}). Proceeding with caution flag.")

    # ── Load inputs ───────────────────────────────────────────────────────
    candidates      = [c for c in load_tier3_candidates() if not c.get("consumed")]
    dimension_ids   = load_tier1_dimension_ids()
    existing_rules  = load_existing_tier2_rules()
    reports         = load_ready_reports(sessions_root)

    if not candidates:
        print("[Agent 2] No unconsumed candidates in Tier 3. Nothing to learn from.")
        return {
            "status": "no_candidates",
            "proposed_rules": [],
            "learning_summary": {
                "candidates_reviewed": 0,
                "rules_proposed": 0,
            }
        }

    print(f"[Agent 2] Reviewing {len(candidates)} unconsumed candidates from Tier 3...")

    # ── Build prompts and call API ────────────────────────────────────────
    system_prompt = build_system_prompt(dimension_ids, existing_rules)
    user_prompt   = build_user_prompt(candidates, reports)
    raw           = _call_claude(system_prompt, user_prompt)
    result        = _parse_response(raw)

    proposed_rules   = result.get("proposed_rules", [])
    learning_summary = result.get("learning_summary", {})

    print(f"[Agent 2] Proposed {len(proposed_rules)} rule(s).")

    # ── Validate rules don't exceed allowed types ─────────────────────────
    valid_rules = []
    for rule in proposed_rules:
        if rule.get("rule_type") not in RULE_TYPES:
            print(f"[Agent 2] REJECTED rule with invalid type: {rule.get('rule_type')}")
            continue
        dims = rule.get("dimensions_involved", [])
        valid_dims = [d["id"] for d in dimension_ids]
        if not all(d in valid_dims for d in dims):
            print(f"[Agent 2] REJECTED rule referencing unknown dimensions: {dims}")
            continue
        valid_rules.append(rule)

    print(f"[Agent 2] {len(valid_rules)} rule(s) passed validation.")

    # ── Write to Tier 2 (pending_review, not yet active) ─────────────────
    written_rules = []
    if valid_rules and not dry_run:
        session_ids = [r["session_id"] for r in reports]
        written_rules = write_rules_to_tier2(valid_rules, session_ids, n_segments)

        # Mark candidates as consumed
        _mark_candidates_consumed([c["candidate_id"] for c in candidates])

        print(f"[Agent 2] {len(written_rules)} rule(s) written to Tier 2 with "
              f"status=pending_review. Awaiting human approval before Agent 1 sees them.")
    elif dry_run:
        print("[Agent 2] DRY RUN β€” rules not written to disk.")

    # ── Print summary ─────────────────────────────────────────────────────
    _print_learning_summary(learning_summary, valid_rules, n_segments)

    return {
        "status": "complete",
        "n_sessions": n_sessions,
        "n_segments": n_segments,
        "candidates_reviewed": len(candidates),
        "proposed_rules": valid_rules,
        "written_rules": written_rules,
        "learning_summary": learning_summary,
        "below_safe_zone": n_segments < RECOMMENDED_SEGMENTS,
    }


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _mark_candidates_consumed(candidate_ids: list[str]) -> None:
    """Mark Tier 3 candidates as consumed so they are not reprocessed."""
    pending_path = TIER3_PATH / "pending_review.json"
    data         = json.loads(pending_path.read_text(encoding="utf-8"))

    for entry in data["pending_review"]:
        if entry["candidate_id"] in candidate_ids:
            entry["consumed"] = True

    pending_path.write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )


def _print_learning_summary(
    summary: dict,
    rules: list[dict],
    n_segments: int,
) -> None:
    print("\n" + "═" * 52)
    print("  AGENT 2 LEARNING SUMMARY")
    print("═" * 52)
    print(f"  Candidates reviewed : {summary.get('candidates_reviewed', 0)}")
    print(f"  Rules proposed      : {len(rules)}")
    print(f"  Total segments      : {n_segments}")
    print(f"  Safe zone (β‰₯{RECOMMENDED_SEGMENTS})    : {'Yes' if n_segments >= RECOMMENDED_SEGMENTS else 'No β€” treat rules as provisional'}")
    if rules:
        print("\n  Proposed rules:")
        for r in rules:
            print(f"    [{r['rule_type']}] {r['description'][:80]}...")
            print(f"      Confidence: {r.get('confidence')} | "
                  f"Dims: {r.get('dimensions_involved')}")
    sparse = summary.get("patterns_too_sparse", [])
    if sparse:
        print("\n  Patterns seen but not yet actionable:")
        for p in sparse:
            print(f"    Β· {p}")
    rec = summary.get("recommendation", "")
    if rec:
        print(f"\n  Recommendation: {rec}")
    print("═" * 52 + "\n")


# ---------------------------------------------------------------------------
# List pending rules for researcher review
# ---------------------------------------------------------------------------

def list_pending_rules() -> list[dict]:
    """Return rules that are genuinely pending review (not yet approved or rejected)."""
    rules_path = TIER2_PATH / "learned_rules.json"
    if not rules_path.exists():
        return []
    data = json.loads(rules_path.read_text(encoding="utf-8"))
    return [
        r for r in data.get("learned_rules", [])
        if not r.get("approved")
        and not r.get("active")
        and not str(r.get("approval_note", "")).startswith("REJECTED:")
    ]


def print_pending_rules() -> None:
    pending = list_pending_rules()
    if not pending:
        print("[Agent 2] No rules pending review.")
        return
    print(f"\n[Agent 2] {len(pending)} rule(s) pending human review:\n")
    for r in pending:
        print(f"  Rule ID   : {r['rule_id']}")
        print(f"  Type      : {r['rule_type']}")
        print(f"  Dimensions: {r['dimensions_involved']}")
        print(f"  Rule      : {r['description']}")
        print(f"  Rationale : {r['rationale']}")
        print(f"  Confidence: {r['confidence']}")
        print(f"  Note      : {r.get('agent2_note', '')}")
        print(f"  Created   : {r['created_at']}")
        print()


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

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("Usage:")
        print("  Run learning cycle:")
        print("    python agent2_learner.py learn <sessions_dir> [--dry-run]")
        print("  List pending rules:")
        print("    python agent2_learner.py pending")
        print("  Approve a rule:")
        print("    python agent2_learner.py approve <rule_id> <researcher_id> [note]")
        print("  Reject a rule:")
        print("    python agent2_learner.py reject <rule_id> <researcher_id> <note>")
        sys.exit(1)

    command = sys.argv[1]

    if command == "learn":
        sessions_dir = Path(sys.argv[2])
        dry          = "--dry-run" in sys.argv
        run_learning_cycle(sessions_dir, dry_run=dry)

    elif command == "pending":
        print_pending_rules()

    elif command == "approve":
        rule_id     = sys.argv[2]
        researcher  = sys.argv[3]
        note        = sys.argv[4] if len(sys.argv) > 4 else ""
        approve_rule(rule_id, researcher, note)

    elif command == "reject":
        rule_id     = sys.argv[2]
        researcher  = sys.argv[3]
        note        = sys.argv[4] if len(sys.argv) > 4 else "No reason given"
        reject_rule(rule_id, researcher, note)

    else:
        print(f"Unknown command: {command}")
        sys.exit(1)