Download agent2_learner.py from pylxi/script: direct link, hf CLI and curl.
- Browser
- Download file 30 kB
-
https://huggingface.co/spaces/pylxi/script/resolve/5b5a20db2bac813ff45ecbca31fe006f0b6e2ecf/agent2_learner.py
- Command line
-
hf download hf://spaces/pylxi/script@5b5a20db2bac813ff45ecbca31fe006f0b6e2ecf/agent2_learner.py
-
curl -L -o agent2_learner.py https://huggingface.co/spaces/pylxi/script/resolve/5b5a20db2bac813ff45ecbca31fe006f0b6e2ecf/agent2_learner.py
30 kB
| """ | |
| 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 | |
| """ | |
| 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')}") | |
| lines.append(f" Agent 1 assigned: {c.get('agent1_dimension')}") | |
| lines.append(f" R1 coded: {c.get('r1_dimension')} | Comment: {c.get('r1_comment', '')}") | |
| lines.append(f" R2 coded: {c.get('r2_dimension')} | Comment: {c.get('r2_comment', '')}") | |
| lines.append(f" Resolved to: {c.get('resolved_dimension', 'unresolved')}") | |
| 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: | |
| lines.append(f"Session: {r['session_id']} | Kappa: {r['overall_kappa']} | " | |
| f"Segments: {r['n_segments_total']} | Disagreed: {r['n_segments_disagreed']}") | |
| dim_kappas = r.get("kappa_per_dimension", {}) | |
| low_dims = [f"{d}={k:.2f}" for d, k in dim_kappas.items() | |
| if k is not None and k < 0.70] | |
| if low_dims: | |
| lines.append(f" Low-agreement 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, | |
| ) -> str: | |
| """ | |
| Add a resolved disagreement to Tier 3 for Agent 2 to review later. | |
| Returns the candidate_id of the new entry. | |
| """ | |
| 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_rationale": agent1_rationale, | |
| "r1_dimension": r1_dimension, | |
| "r1_comment": r1_comment, | |
| "r2_dimension": r2_dimension, | |
| "r2_comment": r2_comment, | |
| "resolved_dimension": resolved_dimension, | |
| "resolution_note": resolution_note, | |
| "consumed": False, # flipped to True after Agent 2 processes it | |
| } | |
| 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 all rules awaiting human approval.""" | |
| 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")] | |
| 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) | |