"""Command-line entry point for the MVP runtime."""

from __future__ import annotations

import argparse
import json
import sys
import tempfile
from pathlib import Path
from uuid import uuid4

from .agent import CognitiveAgent
from .controller import HeuristicController
from .advisory_arbiter import AdvisoryArbiterController
from .doc_research import run_local_document_research_task
from .evaluation import run_final_v1_eval, run_gate3_forge_eval, run_gate3b_audit, run_gate4_dream_eval, run_gate5a_dataset_eval, run_gate5a_repair_eval, run_gate5b_calibration_eval, run_gate5b_shadow_controller_eval, run_gate5c_advisory_arbiter_eval, run_gate5d_readonly_proposal_eval, run_gate5d_readonly_scale_audit, run_gate5e_skill_recommendation_eval, run_gate5e_skill_recommendation_scale_audit, run_gate5f_sandbox_skill_exec_eval, run_gate5f_skill_exec_scale_audit, run_gate5g_human_approved_apply_eval, run_gate5g_worktree_skill_dryrun_eval, run_gate6a_patch_recommendation_eval, run_gate6b_sandbox_patch_exec_eval, run_gate6c_worktree_patch_proposal_eval, run_gate7a_memory_recommendation_eval, run_gate7b_memory_write_approval_eval, run_gate7c_skill_update_recommendation_eval, run_gate7d_skill_update_approval_eval, run_gate7d_skill_update_scale_audit, run_gate8a_controller_v2_data_eval, run_gate8a_controller_v2_lock_audit, run_gate8b_neural_controller_shadow_eval, run_gate8c_neural_calibration_eval, run_gate8d_controller_arbitration_eval, run_gate9a_real_repo_benchmark_eval, run_gate9b_repo_supervised_eval, run_gate9c_repo_autopilot_worktree_eval, run_gate10a_doc_research_eval, run_gate10b_planning_automation_eval, run_gate11a_dream_v2_eval, run_gate11b_self_improvement_dryrun_eval, run_gate11c_self_improvement_worktree_eval, run_gate12a_security_boundary_audit, run_gate12b_resource_budget_audit, run_gate13a_cli_ux_eval, run_gate13b_packaging_eval, run_repeated_task_eval
from .cli_ux import (
    USER_COMMANDS,
    build_doctor_payload,
    build_dream_payload,
    build_eval_payload,
    build_memory_payload,
    build_release_check_payload,
    build_skills_payload,
)
from .learned_proposal import LearnedReadOnlyProposalController
from .memory import EpisodeMemory
from .shadow_controller import SHADOW_CALIBRATION_FILE, SHADOW_MODEL_FILE, ShadowCalibration, ShadowControllerModel, ShadowLoggingController
from .skill_recommendation import LearnedSkillRecommendationController
from .skills import SkillGraph
from .patch_proposals import PATCH_PROPOSAL_CONFIRMATION_TOKEN
from .repo_task import run_repo_task_session
from .worktree_runner import APPROVED_DIFF_CONFIRMATION_TOKEN


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Run the Ra Cognitive CPU MVP runtime.")
    parser.add_argument("task", nargs="?", help="Task text to process")
    parser.add_argument("--max-steps", type=int, default=None, help="Maximum bytecode steps")
    parser.add_argument("--state-dir", type=Path, default=None, help="Directory for memory and skill files")
    parser.add_argument("--gate2-eval", action="store_true", help="Run the deterministic Gate 2 repeated-task benchmark")
    parser.add_argument("--gate3-forge-eval", action="store_true", help="Run the Gate 3 grounded skill forge benchmark")
    parser.add_argument("--gate3b-audit", action="store_true", help="Run the Gate 3B adversarial skill forge audit")
    parser.add_argument("--gate4-dream-eval", action="store_true", help="Run the Gate 4 verifiable dream consolidation benchmark")
    parser.add_argument(
        "--gate5a-dataset-eval",
        "--gate5a-controller-data-eval",
        dest="gate5a_dataset_eval",
        action="store_true",
        help="Run the Gate 5A controller dataset and offline policy contract benchmark",
    )
    parser.add_argument("--gate5a-repair-eval", action="store_true", help="Run the Gate 5A-R anti-shortcut repair benchmark")
    parser.add_argument("--gate5b-shadow-controller-eval", action="store_true", help="Run the Gate 5B-S tiny local shadow controller benchmark")
    parser.add_argument("--gate5b-calibration-eval", action="store_true", help="Run the Gate 5B-C shadow controller calibration and abstention benchmark")
    parser.add_argument("--gate5c-advisory-arbiter-eval", action="store_true", help="Run the Gate 5C guarded advisory arbiter benchmark")
    parser.add_argument("--gate5d-readonly-proposal-eval", action="store_true", help="Run the Gate 5D constrained learned read-only proposal benchmark")
    parser.add_argument("--gate5d-readonly-scale-audit", action="store_true", help="Run the Gate 5D-R read-only and verifier proposal scaling audit")
    parser.add_argument("--gate5e-skill-recommendation-eval", action="store_true", help="Run the Gate 5E-S dry-run learned skill recommendation benchmark")
    parser.add_argument("--gate5e-skill-recommendation-scale-audit", action="store_true", help="Run the Gate 5E-R dry-run skill recommendation scale and adversarial audit")
    parser.add_argument("--gate5f-sandbox-skill-exec-eval", action="store_true", help="Run the Gate 5F-S sandboxed learned-recommended skill execution benchmark")
    parser.add_argument("--gate5f-skill-exec-scale-audit", action="store_true", help="Run the Gate 5F-R sandboxed skill execution scale and rollback audit")
    parser.add_argument("--gate5g-worktree-skill-dryrun-eval", action="store_true", help="Run the Gate 5G-S isolated worktree skill execution dry-run benchmark")
    parser.add_argument("--gate5g-human-approved-apply-eval", action="store_true", help="Run the Gate 5G-R human-approved worktree diff apply benchmark")
    parser.add_argument("--gate6a-patch-recommendation-eval", action="store_true", help="Run the Gate 6A dry-run patch candidate recommendation benchmark")
    parser.add_argument("--gate6b-sandbox-patch-exec-eval", action="store_true", help="Run the Gate 6B sandboxed patch candidate execution benchmark")
    parser.add_argument("--gate6c-worktree-patch-proposal-eval", action="store_true", help="Run the Gate 6C worktree patch proposal and human approval benchmark")
    parser.add_argument("--gate7a-memory-recommendation-eval", action="store_true", help="Run the Gate 7A dry-run memory write recommendation benchmark")
    parser.add_argument("--gate7b-memory-write-approval-eval", action="store_true", help="Run the Gate 7B deterministic memory write approval benchmark")
    parser.add_argument("--gate7c-skill-update-recommendation-eval", action="store_true", help="Run the Gate 7C dry-run skill graph update recommendation benchmark")
    parser.add_argument("--gate7d-skill-update-approval-eval", action="store_true", help="Run the Gate 7D deterministic skill graph update approval benchmark")
    parser.add_argument("--gate7d-skill-update-scale-audit", action="store_true", help="Run the Gate 7D-R skill graph update scale and poisoning audit")
    parser.add_argument("--gate8a-controller-v2-data-eval", action="store_true", help="Run the Gate 8A unified controller v2 dataset benchmark")
    parser.add_argument("--gate8a-controller-v2-lock-audit", action="store_true", help="Run the Gate 8A-R controller v2 dataset lock and forensics audit")
    parser.add_argument("--gate9a-real-repo-benchmark-eval", action="store_true", help="Run the Gate 9A real repository benchmark harness")
    parser.add_argument("--gate8b-neural-controller-shadow-eval", action="store_true", help="Run the Gate 8B local learned controller shadow-mode benchmark")
    parser.add_argument("--gate8c-neural-calibration-eval", action="store_true", help="Run the Gate 8C neural controller calibration and abstention benchmark")
    parser.add_argument("--gate8d-controller-arbitration-eval", action="store_true", help="Run the Gate 8D deterministic controller arbitration benchmark")
    parser.add_argument("--gate9b-repo-agent-supervised-eval", action="store_true", help="Run the Gate 9B repo-task supervised local workflow benchmark")
    parser.add_argument("--gate9c-repo-autopilot-worktree-eval", action="store_true", help="Run the Gate 9C worktree-only repo autopilot benchmark")
    parser.add_argument("--gate10a-doc-research-eval", action="store_true", help="Run the Gate 10A local document research benchmark")
    parser.add_argument("--gate10b-planning-automation-eval", action="store_true", help="Run the Gate 10B planning and automation benchmark")
    parser.add_argument("--gate11a-dream-v2-eval", action="store_true", help="Run the Gate 11A dream consolidation v2 benchmark")
    parser.add_argument("--gate11b-self-improvement-dryrun-eval", action="store_true", help="Run the Gate 11B self-improvement proposal dry-run benchmark")
    parser.add_argument("--gate11c-self-improvement-worktree-eval", action="store_true", help="Run the Gate 11C sandboxed self-improvement worktree proposal benchmark")
    parser.add_argument("--gate12a-security-boundary-audit", action="store_true", help="Run the Gate 12A security and capability boundary audit")
    parser.add_argument("--gate12b-resource-budget-audit", action="store_true", help="Run the Gate 12B performance and resource budget audit")
    parser.add_argument("--gate13a-cli-ux-eval", action="store_true", help="Run the Gate 13A user-facing CLI and runbook benchmark")
    parser.add_argument("--gate13b-packaging-eval", action="store_true", help="Run the Gate 13B packaging and installation benchmark")
    parser.add_argument("--final-v1-eval", action="store_true", help="Run the Gate 14A final Ra v1 benchmark")
    parser.add_argument("--doc-research", action="store_true", help="Run local document research against only the provided local documents")
    parser.add_argument("--doc-dir", type=Path, default=None, help="Directory of local markdown/text documents for --doc-research")
    parser.add_argument("--doc-path", action="append", type=Path, default=None, help="Specific local markdown/text document path for --doc-research; may be repeated")
    parser.add_argument("--repo", type=Path, default=None, help="Reviewed local repository path for repo-task supervised mode")
    parser.add_argument("--task", dest="repo_task_text", default="", help="Task text for repo-task supervised mode")
    parser.add_argument("--apply-approved-diff", action="store_true", help="Explicitly permit Gate 5G-R fixture diff apply during the human-approved apply benchmark")
    parser.add_argument("--apply-confirmation-token", default="", help="Confirmation token required with --apply-approved-diff")
    parser.add_argument("--shadow-controller", action="store_true", help="Log shadow-controller predictions during a normal deterministic run")
    parser.add_argument("--advisory-arbiter", action="store_true", help="Enable guarded advisory arbiter logging during a normal deterministic run")
    parser.add_argument("--learned-readonly-proposals", action="store_true", help="Enable Gate 5D learned read-only proposal mode during a normal deterministic run")
    parser.add_argument("--learned-skill-recommendations", action="store_true", help="Enable Gate 5E-S learned skill recommendation dry-run logging during a normal deterministic run")
    parser.add_argument("--json", action="store_true", help="Print machine-readable JSON")
    return parser


def _run_user_command(argv: list[str]) -> int:
    command = argv[0]
    parser = argparse.ArgumentParser(prog=f"ra_cpu {command}", description=f"Run the {command} operator command.")
    parser.add_argument("--state-dir", type=Path, default=Path(tempfile.gettempdir()) / f"ra_cpu_{command.replace('-', '_')}")
    parser.add_argument("--json", action="store_true")
    parser.add_argument("--require-clean", action="store_true", help="Require a clean tree for release-check")
    parser.add_argument("--help-main", action="store_true", help=argparse.SUPPRESS)
    args = parser.parse_args(argv[1:])
    if command == "doctor":
        payload = build_doctor_payload(args.state_dir)
    elif command == "eval":
        payload = build_eval_payload(args.state_dir)
    elif command == "memory":
        payload = build_memory_payload(args.state_dir)
    elif command == "skills":
        payload = build_skills_payload(args.state_dir)
    elif command == "dream":
        payload = build_dream_payload(args.state_dir)
    elif command == "release-check":
        payload = build_release_check_payload(args.state_dir, require_clean=args.require_clean)
    elif command == "repo-task":
        payload = {
            "command": "repo-task",
            "usage": "python -m ra_cpu.cli repo-task --repo <path> --task <task> --state-dir <state> --json",
            "supervised": True,
            "human_approval_required_for_apply": True,
            "implemented_by": "existing repo-task --repo/--task supervised workflow",
        }
    else:
        raise AssertionError(command)
    if args.json:
        print(json.dumps(payload, indent=2, sort_keys=True))
    else:
        for key, value in payload.items():
            print(f"{key}: {value}")
    return 0


def main(argv: list[str] | None = None) -> int:
    raw_argv = list(sys.argv[1:] if argv is None else argv)
    if raw_argv and raw_argv[0] in USER_COMMANDS and raw_argv[0] != "repo-task":
        return _run_user_command(raw_argv)
    args = build_parser().parse_args(argv)
    if args.gate2_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate2_eval")
        summary = run_repeated_task_eval(state_dir=state_dir, max_steps=args.max_steps or 8)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 2 improved: {payload['improved']}")
            print(f"Cases: {payload['total_cases']}")
            print(f"Baseline average steps: {summary.baseline.average_steps}")
            print(f"Post-reuse average steps: {summary.post_reuse.average_steps}")
            print(f"Average step reduction: {summary.average_step_reduction}")
            print(f"Skill promoted: {summary.promotion.promoted}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate3_forge_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate3_forge")
        summary = run_gate3_forge_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 3 improved: {payload['improved']}")
            print(f"Families: {payload['total_families']}")
            print(f"Promoted skills: {payload['promoted_count']}")
            print(f"Average baseline steps: {summary.average_baseline_steps}")
            print(f"Average reuse steps: {summary.average_reuse_steps}")
            print(f"Average saved steps: {summary.average_saved_steps}")
            print(f"False triggers: {summary.false_trigger_count}")
            print(f"Fallbacks: {summary.fallback_count}")
            print(f"Quarantines: {summary.quarantine_count}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate3b_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate3b_audit")
        summary = run_gate3b_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 3B passed: {payload['gate3b_passed']}")
            print(f"Improved: {payload['improved']}")
            print(f"Bad candidates rejected: {payload['rejected_candidate_count']}/{payload['bad_candidate_count']}")
            print(f"False trigger rate: {payload['false_trigger_rate']}")
            print(f"Fallbacks: {payload['fallback_count']}")
            print(f"Quarantines: {payload['quarantine_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate4_dream_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate4_dream")
        summary = run_gate4_dream_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 4 passed: {payload['gate4_passed']}")
            print(f"Improved: {payload['improved']}")
            print(f"Trace count: {payload['trace_ledger']['trace_count']}")
            print(f"Memory items: {payload['memory']['memory_item_count']}")
            print(f"Dream tasks: {payload['dream_tasks']['generated_task_count']}")
            print(f"Retrieval precision: {payload['retrieval']['retrieval_precision']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5a_dataset_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5a_dataset")
        summary = run_gate5a_dataset_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5A passed: {payload['gate5a_passed']}")
            print(f"Transitions: {payload['dataset']['transition_count']}")
            print(f"Distinct actions: {payload['dataset']['distinct_target_actions']}")
            print(f"Oracle leaks: {payload['leak_audit']['oracle_leak_count']}")
            print(f"Canary leaks: {payload['canary_audit']['canary_leak_count']}")
            print(f"Replay valid: {payload['replay_validation']['replay_validation_passed']}")
            print(f"Best baseline: {payload['offline_baselines']['best_baseline']['name']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5a_repair_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5a_repair")
        summary = run_gate5a_repair_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5A-R passed: {payload['gate5a_repair_passed']}")
            print(f"Gate 5A still passed: {payload['gate5a_still_passed']}")
            print(f"Shortcut risk before: {payload['shortcut_risk_before']}")
            print(f"Shortcut risk after: {payload['shortcut_risk_after']}")
            print(f"Contrast pairs: {payload['contrast_set']['contrast_pair_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5b_shadow_controller_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5b_shadow")
        summary = run_gate5b_shadow_controller_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5B-S passed: {payload['gate5b_shadow_passed']}")
            print(f"Gate 5A-R still passed: {payload['gate5a_repair_still_passed']}")
            print(f"Shadow actions executed: {payload['learned_controller_actions_executed']}")
            print(f"Validation top1: {payload['metrics']['validation_top1']}")
            print(f"Contrast top1: {payload['metrics']['contrast_top1']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5b_calibration_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5b_calibration")
        summary = run_gate5b_calibration_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5B-C passed: {payload['gate5b_calibration_passed']}")
            print(f"Gate 5B-S still passed: {payload['gate5b_shadow_still_passed']}")
            print(f"Shadow actions executed: {payload['learned_controller_actions_executed']}")
            print(f"Counterfactual accuracy: {payload['counterfactual_accuracy']}")
            print(f"OOD abstention rate: {payload['ood_abstention_rate']}")
            print(f"Selective accuracy: {payload['selective_accuracy_at_threshold']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5c_advisory_arbiter_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5c_advisory")
        summary = run_gate5c_advisory_arbiter_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5C passed: {payload['gate5c_advisory_passed']}")
            print(f"Gate 5B-C still passed: {payload['gate5b_calibration_still_passed']}")
            print(f"Learned direct actions: {payload['learned_direct_domain_actions_executed']}")
            print(f"Unsafe block rate: {payload['fault_injection']['unsafe_candidate_block_rate']}")
            print(f"Correct intervention rate: {payload['fault_injection']['correct_intervention_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5d_readonly_proposal_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5d_readonly")
        summary = run_gate5d_readonly_proposal_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5D passed: {payload['gate5d_readonly_proposal_passed']}")
            print(f"Gate 5C still passed: {payload['gate5c_still_passed']}")
            print(f"Learned proposals made: {payload['proposal_accounting']['learned_proposals_made']}")
            print(f"Learned mutating actions: {payload['learned_mutating_actions_executed']}")
            print(f"Bad proposal reject rate: {payload['fault_injection']['bad_proposal_reject_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5d_readonly_scale_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5d_scale")
        summary = run_gate5d_readonly_scale_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5D-R passed: {payload['gate5d_scale_audit_passed']}")
            print(f"Gate 5D still passed: {payload['gate5d_still_passed']}")
            print(f"Proposal opportunities: {payload['proposal_accounting']['proposal_opportunity_count']}")
            print(f"Learned proposals executed: {payload['proposal_accounting']['learned_proposals_executed']}")
            print(f"Verifier proposals executed: {payload['verifier_proposals']['verifier_proposals_executed']}")
            print(f"Bad proposal reject rate: {payload['fault_injection']['bad_proposal_reject_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5e_skill_recommendation_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5e_skill_rec")
        summary = run_gate5e_skill_recommendation_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5E-S passed: {payload['gate5e_skill_recommendation_passed']}")
            print(f"Gate 5D-R still passed: {payload['gate5d_scale_audit_still_passed']}")
            print(f"Recommendation opportunities: {payload['recommendation_accounting']['skill_recommendation_opportunity_count']}")
            print(f"Recommendations approved: {payload['recommendation_accounting']['learned_skill_recommendations_approved']}")
            print(f"Learned skill calls executed: {payload['learned_skill_calls_executed']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5e_skill_recommendation_scale_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5e_scale")
        summary = run_gate5e_skill_recommendation_scale_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5E-R passed: {payload['gate5e_scale_audit_passed']}")
            print(f"Gate 5E-S still passed: {payload['gate5e_still_passed']}")
            print(f"Recommendation opportunities: {payload['opportunity_count']}")
            print(f"Recommendations approved: {payload['recommendation_accounting']['learned_skill_recommendations_approved']}")
            print(f"Learned skill calls executed: {payload['learned_skill_calls_executed']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5f_sandbox_skill_exec_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5f_skill_exec")
        summary = run_gate5f_sandbox_skill_exec_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5F-S passed: {payload['gate5f_sandbox_skill_exec_passed']}")
            print(f"Gate 5E-R still passed: {payload['gate5e_scale_audit_still_passed']}")
            print(f"Sandbox executions: {payload['deterministic_skill_executions_from_learned_recommendation']}")
            print(f"Skill execution success rate: {payload['skill_execution_success_rate']}")
            print(f"Rollback success rate: {payload['rollback_success_rate']}")
            print(f"Bad recommendation reject rate: {payload['bad_recommendation_reject_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5f_skill_exec_scale_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5f_scale")
        summary = run_gate5f_skill_exec_scale_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5F-R passed: {payload['gate5f_scale_audit_passed']}")
            print(f"Gate 5F-S still passed: {payload['gate5f_sandbox_skill_exec_still_passed']}")
            print(f"Execution opportunities: {payload['execution_opportunity_count']}")
            print(f"Approved executions: {payload['approved_execution_count']}")
            print(f"Forced verifier failures: {payload['forced_failure_count']}")
            print(f"Rollback success rate: {payload['rollback_success_rate']}")
            print(f"Bad recommendation reject rate: {payload['metrics']['bad_recommendation_reject_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5g_worktree_skill_dryrun_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5g_worktree")
        summary = run_gate5g_worktree_skill_dryrun_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5G-S passed: {payload['gate5g_worktree_dryrun_passed']}")
            print(f"Gate 5F-R still passed: {payload['gate5f_scale_audit_still_passed']}")
            print(f"Worktree executions: {payload['worktree_execution_count']}")
            print(f"Main checkout mutations: {payload['main_checkout_mutation_count']}")
            print(f"Worktree cleanup success rate: {payload['worktree_cleanup_success_rate']}")
            print(f"Diff captures: {payload['diff_capture_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate5g_human_approved_apply_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate5g_apply")
        summary = run_gate5g_human_approved_apply_eval(
            state_dir=state_dir,
            apply_approved_diff=args.apply_approved_diff,
            confirmation_token=args.apply_confirmation_token,
        )
        payload = {**summary.to_dict(), "state_dir": str(state_dir), "required_confirmation_token": APPROVED_DIFF_CONFIRMATION_TOKEN}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 5G-R passed: {payload['gate5g_apply_passed']}")
            print(f"Gate 5G-S still passed: {payload['gate5g_worktree_dryrun_still_passed']}")
            print(f"Approved apply successes: {payload['approved_apply_success_count']}")
            print(f"Dirty worktree refusals: {payload['dirty_worktree_refusal_count']}")
            print(f"Auto-apply without approval: {payload['auto_apply_without_approval_count']}")
            print(f"Post-apply verifier passes: {payload['post_apply_verifier_pass_count']}")
            print(f"Rollback artifacts: {payload['rollback_artifact_created_count']}")
            print(f"Required confirmation token: {APPROVED_DIFF_CONFIRMATION_TOKEN}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate6a_patch_recommendation_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate6a_patch_rec")
        summary = run_gate6a_patch_recommendation_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 6A passed: {payload['gate6a_patch_recommendation_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Patch candidate opportunities: {payload['patch_candidate_opportunity_count']}")
            print(f"Recommendation precision: {payload['recommendation_precision']}")
            print(f"Recommendation recall: {payload['recommendation_recall']}")
            print(f"False recommendation rate: {payload['false_recommendation_rate']}")
            print(f"Learned patch text generated: {payload['learned_patch_text_generated_count']}")
            print(f"Learned patches applied: {payload['learned_patch_applied_count']}")
            print(f"File writes: {payload['file_write_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate6b_sandbox_patch_exec_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate6b_patch_exec")
        summary = run_gate6b_sandbox_patch_exec_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 6B passed: {payload['gate6b_sandbox_patch_exec_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Sandbox patch executions: {payload['sandbox_patch_execution_count']}")
            print(f"Verifier-after-patch count: {payload['verifier_after_patch_count']}")
            print(f"Rollback success rate: {payload['rollback_success_rate']}")
            print(f"Patch escapes: {payload['patch_escape_count']}")
            print(f"Real repo mutations: {payload['real_repo_mutation_count']}")
            print(f"Learned raw patch generation: {payload['learned_raw_patch_generation_count']}")
            print(f"Regression rate: {payload['regression_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate6c_worktree_patch_proposal_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate6c_patch_proposal")
        summary = run_gate6c_worktree_patch_proposal_eval(
            state_dir=state_dir,
            apply_approved_diff=args.apply_approved_diff,
            confirmation_token=args.apply_confirmation_token,
        )
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 6C passed: {payload['gate6c_worktree_patch_proposal_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Proposal reports: {payload['proposal_report_count']}")
            print(f"Auto apply count: {payload['auto_apply_count']}")
            print(f"Human-approved apply path tested: {payload['human_approved_apply_path_tested']}")
            print(f"Dirty worktree refusals: {payload['dirty_worktree_refusal_count']}")
            print(f"Post-apply verifier passes: {payload['post_apply_verifier_pass_count']}")
            print(f"Rollback artifacts: {payload['rollback_artifact_count']}")
            print(f"Required confirmation token: {PATCH_PROPOSAL_CONFIRMATION_TOKEN}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate7a_memory_recommendation_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate7a_memory_rec")
        summary = run_gate7a_memory_recommendation_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 7A passed: {payload['gate7a_memory_recommendation_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Memory recommendation opportunities: {payload['memory_recommendation_opportunity_count']}")
            print(f"Unsupported memory reject rate: {payload['unsupported_memory_reject_rate']}")
            print(f"Recommendation precision: {payload['recommendation_precision']}")
            print(f"Learned memory writes executed: {payload['learned_memory_writes_executed']}")
            print(f"Oracle leaks: {payload['oracle_leak_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate7b_memory_write_approval_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate7b_memory_write")
        summary = run_gate7b_memory_write_approval_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 7B passed: {payload['gate7b_memory_write_approval_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Approved memory writes: {payload['approved_memory_write_count']}")
            print(f"Unsupported memory writes: {payload['unsupported_memory_write_count']}")
            print(f"Evidence coverage: {payload['evidence_coverage']}")
            print(f"Invalidated bad memories: {payload['invalidated_bad_memory_count']}")
            print(f"Retrieval precision: {payload['retrieval_precision']}")
            print(f"Regression rate: {payload['regression_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate7c_skill_update_recommendation_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate7c_skill_update_rec")
        summary = run_gate7c_skill_update_recommendation_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 7C passed: {payload['gate7c_skill_update_recommendation_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Skill update opportunities: {payload['skill_update_opportunity_count']}")
            print(f"Bad update reject rate: {payload['bad_update_reject_rate']}")
            print(f"Recommendation precision: {payload['recommendation_precision']}")
            print(f"Learned skill graph writes executed: {payload['learned_skill_graph_writes_executed']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate7d_skill_update_approval_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate7d_skill_update_approval")
        summary = run_gate7d_skill_update_approval_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 7D passed: {payload['gate7d_skill_update_approval_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Approved skill updates: {payload['approved_skill_update_count']}")
            print(f"Bad update reject rate: {payload['bad_update_reject_rate']}")
            print(f"Rollback success rate: {payload['rollback_success_rate']}")
            print(f"Post-update regression rate: {payload['post_update_regression_rate']}")
            print(f"Post-update regression suite runs: {payload['post_update_regression_suite_run_count']}")
            print(f"Write path containment passed: {payload['write_path_containment_passed']}")
            print(f"Skill reuse improvement detected: {payload['skill_reuse_improvement_detected']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate7d_skill_update_scale_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate7d_scale")
        summary = run_gate7d_skill_update_scale_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 7D-R passed: {payload['gate7d_scale_audit_passed']}")
            print(f"Gate 7D still passed: {payload['gate7d_still_passed']}")
            print(f"Update opportunities: {payload['update_opportunity_count']}")
            print(f"Approved updates: {payload['approved_update_count']}")
            print(f"Bad update reject rate: {payload['bad_update_reject_rate']}")
            print(f"Rollback success rate: {payload['rollback_success_rate']}")
            print(f"Poisoning reject rate: {payload['poisoning']['poisoning_reject_rate']}")
            print(f"Post-update regression rate: {payload['regression']['post_update_regression_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate8a_controller_v2_data_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate8a_controller_v2")
        summary = run_gate8a_controller_v2_data_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 8A passed: {payload['gate8a_controller_v2_data_passed']}")
            print(f"Gate 7D-R still passed: {payload['gate7d_r_still_passed']}")
            print(f"Transitions: {payload['transition_count']}")
            print(f"Candidate classes: {payload['candidate_class_count']}")
            print(f"Authority levels: {payload['authority_level_count']}")
            print(f"Contrast pairs: {payload['contrast_pair_count']}")
            print(f"Shortcut risk: {payload['shortcut_risk']}")
            print(f"Manifest rebuild match: {payload['manifest_rebuild_match']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate8a_controller_v2_lock_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate8a_lock")
        summary = run_gate8a_controller_v2_lock_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 8A-R passed: {payload['gate8a_lock_passed']}")
            print(f"Gate 8A still passed: {payload['gate8a_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Candidate ID shortcut risk: {payload['candidate_id_shortcut_risk']}")
            print(f"Candidate position shortcut risk: {payload['candidate_position_shortcut_risk']}")
            print(f"Contrast bigram accuracy: {payload['contrast_bigram_accuracy']}")
            print(f"Manifest rebuild match: {payload['manifest_rebuild_match']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate9a_real_repo_benchmark_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate9a_real_repo")
        summary = run_gate9a_real_repo_benchmark_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 9A passed: {payload['gate9a_real_repo_benchmark_passed']}")
            print(f"Gate 8A-R still passed: {payload['gate8a_r_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Fixture repos: {payload['fixture_repo_count']}")
            print(f"Benchmark tasks: {payload['benchmark_task_count']}")
            print(f"Success rate: {payload['success_rate']}")
            print(f"Worktree isolation rate: {payload['worktree_isolation_rate']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate8b_neural_controller_shadow_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate8b_neural_shadow")
        summary = run_gate8b_neural_controller_shadow_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 8B passed: {payload['gate8b_neural_shadow_passed']}")
            print(f"Gate 9A still passed: {payload['gate9a_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Validation top-1: {payload['validation_top1']}")
            print(f"Random baseline top-1: {payload['random_baseline_top1']}")
            print(f"Majority baseline top-1: {payload['majority_baseline_top1']}")
            print(f"Contrast accuracy: {payload['contrast_accuracy']}")
            print(f"OOD abstention rate: {payload['ood_abstention_rate']}")
            print(f"Unsafe predictions: {payload['unsafe_prediction_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate8c_neural_calibration_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate8c_neural_calibration")
        summary = run_gate8c_neural_calibration_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 8C passed: {payload['gate8c_neural_calibration_passed']}")
            print(f"Gate 8B still passed: {payload['gate8b_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Selective accuracy: {payload['selective_accuracy_at_threshold']}")
            print(f"Selective coverage: {payload['selective_coverage_at_threshold']}")
            print(f"False accept rate: {payload['false_accept_rate']}")
            print(f"OOD abstention rate: {payload['ood_abstention_rate']}")
            print(f"Counterfactual accuracy: {payload['counterfactual_accuracy']}")
            print(f"Unsafe predictions: {payload['unsafe_prediction_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate8d_controller_arbitration_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate8d_arbitration")
        summary = run_gate8d_controller_arbitration_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 8D passed: {payload['gate8d_controller_arbitration_passed']}")
            print(f"Gate 8C still passed: {payload['gate8c_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Ensemble success rate: {payload['ensemble_success_rate']}")
            print(f"Best single policy success rate: {payload['best_single_policy_success_rate']}")
            print(f"Unsafe actions: {payload['unsafe_action_count']}")
            print(f"Masked candidate accepts: {payload['masked_candidate_accept_count']}")
            print(f"Fallbacks to deterministic: {payload['fallback_to_deterministic_count']}")
            print(f"Advisory signal count: {payload['advisory_signal_count']}")
            print(f"Advisory influence count: {payload['advisory_influence_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate9b_repo_agent_supervised_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate9b_repo_supervised")
        summary = run_gate9b_repo_supervised_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 9B passed: {payload['gate9b_repo_supervised_passed']}")
            print(f"Gate 8D still passed: {payload['gate8d_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Repo-task success rate: {payload['repo_task_success_rate']}")
            print(f"Trace coverage: {payload['trace_coverage']}")
            print(f"Verifier-after-patch rate: {payload['verifier_after_patch_rate']}")
            print(f"Mutation without approval: {payload['main_checkout_mutation_without_approval_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate9c_repo_autopilot_worktree_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate9c_autopilot")
        summary = run_gate9c_repo_autopilot_worktree_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 9C passed: {payload['gate9c_autopilot_worktree_passed']}")
            print(f"Gate 9B still passed: {payload['gate9b_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Autopilot tasks: {payload['autopilot_task_count']}")
            print(f"Success rate: {payload['success_rate']}")
            print(f"Worktree cleanup success rate: {payload['worktree_cleanup_success_rate']}")
            print(f"Main checkout mutations: {payload['main_checkout_mutation_count']}")
            print(f"Unsafe shell count: {payload['unsafe_shell_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate10a_doc_research_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate10a_docs")
        summary = run_gate10a_doc_research_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 10A passed: {payload['gate10a_doc_research_passed']}")
            print(f"Gate 9C still passed: {payload['gate9c_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Document task count: {payload['document_task_count']}")
            print(f"Citation coverage: {payload['citation_coverage']}")
            print(f"Unsupported claim rate: {payload['unsupported_claim_rate']}")
            print(f"Source trace coverage: {payload['source_trace_coverage']}")
            print(f"Answer without source count: {payload['answer_without_source_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate10b_planning_automation_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate10b_planning")
        summary = run_gate10b_planning_automation_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 10B passed: {payload['gate10b_planning_passed']}")
            print(f"Gate 10A still passed: {payload['gate10a_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Planning tasks: {payload['planning_task_count']}")
            print(f"Plan schema valid rate: {payload['plan_schema_valid_rate']}")
            print(f"Dry-run side effects: {payload['dry_run_side_effect_count']}")
            print(f"Blocked side effects: {payload['blocked_side_effect_count']}")
            print(f"Approval required for side effects: {payload['approval_required_for_side_effects']}")
            print(f"Required approval token: {payload['approval_token']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate11a_dream_v2_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate11a_dream_v2")
        summary = run_gate11a_dream_v2_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 11A passed: {payload['gate11a_dream_v2_passed']}")
            print(f"Gate 10B still passed: {payload['gate10b_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Trace count: {payload['trace_count']}")
            print(f"Replay tasks: {payload['generated_replay_task_count']}")
            print(f"Adversarial tasks: {payload['adversarial_task_count']}")
            print(f"Retrieval precision: {payload['retrieval_precision']}")
            print(f"Controller refresh passed: {payload['controller_dataset_refresh_passed']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate11b_self_improvement_dryrun_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate11b_self_improve")
        summary = run_gate11b_self_improvement_dryrun_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 11B passed: {payload['gate11b_self_improvement_dryrun_passed']}")
            print(f"Gate 11A still passed: {payload['gate11a_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Proposals: {payload['proposal_count']}")
            print(f"Valid test plan rate: {payload['valid_test_plan_rate']}")
            print(f"Self patches applied: {payload['self_patch_applied_count']}")
            print(f"Repo mutations: {payload['repo_mutation_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate11c_self_improvement_worktree_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate11c_self_worktree")
        summary = run_gate11c_self_improvement_worktree_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 11C passed: {payload['gate11c_self_improvement_worktree_passed']}")
            print(f"Gate 11B still passed: {payload['gate11b_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Worktree proposals: {payload['self_improvement_worktree_count']}")
            print(f"Main checkout auto mutations: {payload['main_checkout_auto_mutation_count']}")
            print(f"Validation required for each diff: {payload['validation_required_for_each_diff']}")
            print(f"Human approval required for apply: {payload['human_approval_required_for_apply']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate12a_security_boundary_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate12a_security")
        summary = run_gate12a_security_boundary_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 12A passed: {payload['gate12a_security_audit_passed']}")
            print(f"Gate 11C still passed: {payload['gate11c_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Path traversal bypasses: {payload['path_traversal_bypass_count']}")
            print(f"Illegal shell bypasses: {payload['illegal_shell_bypass_count']}")
            print(f"Unsafe learned authority: {payload['unsafe_learned_authority_count']}")
            print(f"Unapproved repo mutations: {payload['unapproved_repo_mutation_count']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate12b_resource_budget_audit:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate12b_resource")
        summary = run_gate12b_resource_budget_audit(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 12B passed: {payload['gate12b_resource_audit_passed']}")
            print(f"Gate 12A still passed: {payload['gate12a_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Runtime reported: {payload['default_eval_runtime_reported']}")
            print(f"Memory usage bytes: {payload['memory_usage_bytes']}")
            print(f"State artifact size bytes: {payload['state_artifact_size_bytes']}")
            print(f"Cleanup command exists: {payload['cleanup_command_exists']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate13a_cli_ux_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate13a_cli")
        summary = run_gate13a_cli_ux_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 13A passed: {payload['gate13a_cli_ux_passed']}")
            print(f"Gate 12B still passed: {payload['gate12b_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Doctor passes: {payload['doctor_command_passes']}")
            print(f"Help text exists: {payload['help_text_exists_for_main_commands']}")
            print(f"Examples run: {payload['example_commands_run']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.gate13b_packaging_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_gate13b_packaging")
        summary = run_gate13b_packaging_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Gate 13B passed: {payload['gate13b_packaging_passed']}")
            print(f"Gate 13A still passed: {payload['gate13a_still_passed']}")
            print(f"Prior gates still passed: {payload['all_prior_gates_still_passed']}")
            print(f"Release archive created: {payload['release_archive_created']}")
            print(f"Clean clone install passes: {payload['clean_clone_install_passes']}")
            print(f"Doctor after install passes: {payload['doctor_passes_after_install']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.final_v1_eval:
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_final_v1")
        summary = run_final_v1_eval(state_dir=state_dir)
        payload = {**summary.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Ra v1 passed: {payload['ra_v1_passed']}")
            print(f"Release name: {payload['release_name']}")
            print(f"All gates passed: {payload['all_gates_passed']}")
            print(f"Acceptance failures: {payload['acceptance_failures']}")
            print(f"State directory: {state_dir}")
        return 0

    if args.doc_research:
        if args.task is None:
            build_parser().error("doc research requires task text")
        if args.doc_dir is None and not args.doc_path:
            build_parser().error("doc research requires --doc-dir or --doc-path")
        try:
            answer, documents, network_guard = run_local_document_research_task(
                task_id=f"doc_research_{uuid4().hex[:12]}",
                question=args.task,
                doc_dir=args.doc_dir,
                doc_paths=args.doc_path or (),
            )
        except ValueError as exc:
            build_parser().error(str(exc))
        payload = {
            "mode": "doc_research",
            "local_only": True,
            "question": args.task,
            "document_count": len(documents),
            "documents": [
                {
                    "doc_id": document.doc_id,
                    "path": document.path,
                    "source_trace_id": document.source_trace_id,
                    "source_hash": document.source_hash,
                }
                for document in documents
            ],
            "network_guard": network_guard.to_dict(),
            "answer": answer.to_dict(),
        }
        print(json.dumps(payload, indent=2, sort_keys=True))
        return 0

    repo_task_requested = args.task == "repo-task" and (
        args.repo is not None
        or bool(args.repo_task_text)
        or args.apply_approved_diff
        or bool(args.apply_confirmation_token)
    )
    if repo_task_requested:
        if args.repo is None:
            build_parser().error("repo-task requires --repo")
        if not args.repo_task_text:
            build_parser().error("repo-task requires --task")
        state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_repo_task")
        report = run_repo_task_session(
            repo_root=args.repo,
            task_text=args.repo_task_text,
            state_dir=state_dir,
            apply_approved_diff=args.apply_approved_diff,
            confirmation_token=args.apply_confirmation_token,
        )
        payload = {**report.to_dict(), "state_dir": str(state_dir)}
        if args.json:
            print(json.dumps(payload, indent=2, sort_keys=True))
        else:
            print(f"Repo-task success: {payload['success']}")
            print(f"Patch proposed: {payload['patch_proposed']}")
            print(f"Verifier passed: {payload['verifier_passed']}")
            print(f"Approval required: {payload['human_approval_required_for_apply']}")
            print(f"Session report: {payload['paths']['session_report_path']}")
        return 0

    if args.task is None:
        build_parser().error("task is required unless an evaluation flag is used")

    state_dir = args.state_dir or (Path(tempfile.gettempdir()) / "ra_cpu_cli")
    state_dir.mkdir(parents=True, exist_ok=True)

    memory = EpisodeMemory(state_dir / "episodes.sqlite3")
    skills = SkillGraph(state_dir / "skills.json")
    shadow_logger: ShadowLoggingController | None = None
    advisory_logger: AdvisoryArbiterController | None = None
    proposal_logger: LearnedReadOnlyProposalController | None = None
    skill_recommendation_logger: LearnedSkillRecommendationController | None = None
    controller = None
    enabled_wrappers = [args.shadow_controller, args.advisory_arbiter, args.learned_readonly_proposals, args.learned_skill_recommendations]
    if sum(1 for enabled in enabled_wrappers if enabled) > 1:
        build_parser().error("--shadow-controller, --advisory-arbiter, --learned-readonly-proposals, and --learned-skill-recommendations are mutually exclusive")
    if args.shadow_controller:
        model_path = state_dir / "shadow_controller" / SHADOW_MODEL_FILE
        if not model_path.exists():
            run_gate5b_shadow_controller_eval(state_dir=state_dir)
        model = ShadowControllerModel.load(model_path)
        shadow_logger = ShadowLoggingController(HeuristicController(), model)
        controller = shadow_logger
    if args.advisory_arbiter:
        calibration_summary = run_gate5b_calibration_eval(state_dir=state_dir / f"gate5b_calibration_seed_{uuid4().hex}")
        model = ShadowControllerModel.load(Path(str(calibration_summary.model["artifact_path"])))
        calibration = ShadowCalibration.load(Path(str(calibration_summary.model["calibration_artifact_path"])))
        advisory_logger = AdvisoryArbiterController(HeuristicController(), model, calibration)
        controller = advisory_logger
    if args.learned_readonly_proposals:
        seed_dir = state_dir / f"gate5c_seed_{uuid4().hex}"
        run_gate5c_advisory_arbiter_eval(state_dir=seed_dir)
        model_path = seed_dir / "gate5b_calibration_seed" / "shadow_controller" / SHADOW_MODEL_FILE
        calibration_path = seed_dir / "gate5b_calibration_seed" / "shadow_controller" / SHADOW_CALIBRATION_FILE
        model = ShadowControllerModel.load(model_path)
        calibration = ShadowCalibration.load(calibration_path)
        proposal_logger = LearnedReadOnlyProposalController(HeuristicController(), model, calibration)
        controller = proposal_logger
    if args.learned_skill_recommendations:
        seed_dir = state_dir / f"gate5b_calibration_seed_{uuid4().hex}"
        calibration_summary = run_gate5b_calibration_eval(state_dir=seed_dir)
        model = ShadowControllerModel.load(Path(str(calibration_summary.model["artifact_path"])))
        calibration = ShadowCalibration.load(Path(str(calibration_summary.model["calibration_artifact_path"])))
        calibration.config.confidence_threshold = 0.40
        skill_recommendation_logger = LearnedSkillRecommendationController(HeuristicController(), model, calibration, skills)
        controller = skill_recommendation_logger

    agent = CognitiveAgent(memory=memory, skills=skills, controller=controller)
    result = agent.run(args.task, max_steps=args.max_steps or 12)

    payload = {
        "answer": result.answer,
        "trace_length": result.trace_length,
        "episode_id": result.episode.episode_id,
        "workspace_summary": result.workspace.summary(),
        "memory_path": str(result.memory_path),
        "skills_path": str(result.skills_path),
        "memory_stats": memory.statistics(),
    }
    if shadow_logger is not None:
        payload["shadow_logging"] = shadow_logger.summary()
    if advisory_logger is not None:
        advisory_summary = advisory_logger.summary()
        payload["advisory"] = advisory_summary
        for key in [
            "advisory_enabled",
            "advisory_decision_count",
            "advisory_intervention_count",
            "learned_direct_domain_actions_executed",
            "deterministic_actions_executed",
            "verifier_requests_inserted",
            "blocks_applied",
            "fallbacks_requested",
            "quarantine_reviews_requested",
        ]:
            payload[key] = advisory_summary[key]
    if proposal_logger is not None:
        proposal_summary = proposal_logger.summary()
        payload["learned_readonly_proposals"] = proposal_summary
        payload["proposal_accounting"] = proposal_summary["proposal_accounting"]
        payload["readonly_proof"] = proposal_summary["readonly_proof"]
        payload["no_authoritative_mutating_learned_control"] = proposal_summary["no_authoritative_mutating_learned_control"]
        payload["learned_mutating_actions_executed"] = proposal_summary["proposal_accounting"]["learned_mutating_actions_executed"]
        payload["learned_answer_actions_executed"] = proposal_summary["proposal_accounting"]["learned_answer_actions_executed"]
    if skill_recommendation_logger is not None:
        recommendation_summary = skill_recommendation_logger.summary()
        payload["learned_skill_recommendations"] = recommendation_summary
        payload["recommendation_accounting"] = recommendation_summary["recommendation_accounting"]
        payload["dry_run_proof"] = recommendation_summary["dry_run_proof"]
        payload["dry_run_only"] = recommendation_summary["dry_run_only"]
        payload["learned_skill_calls_executed"] = recommendation_summary["learned_skill_calls_executed"]
        payload["learned_mutating_actions_executed"] = recommendation_summary["learned_mutating_actions_executed"]
        payload["learned_answer_actions_executed"] = recommendation_summary["learned_answer_actions_executed"]

    if args.json:
        print(json.dumps(payload, indent=2, sort_keys=True))
    else:
        print(f"Answer: {payload['answer']}")
        print(f"Trace length: {payload['trace_length']}")
        print(f"Episode ID: {payload['episode_id']}")
        print(f"Workspace: {payload['workspace_summary']}")
        print(f"Memory: {payload['memory_path']}")
        print(f"Skills: {payload['skills_path']}")
        print(f"Memory stats: {payload['memory_stats']}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
