""" 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 [--dry-run]") print(" List pending rules:") print(" python agent2_learner.py pending") print(" Approve a rule:") print(" python agent2_learner.py approve [note]") print(" Reject a rule:") print(" python agent2_learner.py reject ") 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)