Skip to content

richfrem/agent-plugins-skills / plugins/agent-agentic-os/.apm/skills/running-control-plane

running-control-plane

Flagged

CRITICAL INTAKE GATEWAY: use at the start of any non-trivial engineering task, feature, refactor, multi-file bugfix, work package or new idea, including requests to explore, brainstorm, build, fix or change something, before planning or code changes. Enforces read-only discovery, 1-3 structured questions with defaults, control-plane registration and the immutable four-pillar TASK_SPEC.md. Also runs the rest of the control plane: health ("run health check", "check os metrics", "system monitor", event bus, locks, memory, "is my signing identity ready" status check), transition simulation ("dry run transition", "simulate transition", "check edge X -> Y"), worktree selection, and gating on/off ("disable the control plane", "turn off the push guard", "stop gating my commits"). Not for project setup or key creation (use setting-up-agentic-os) or improving skills (use improving-skills-in-lab).

FileKindSize
SKILL.mdskill md5.4 KB
evals/evals.jsonconfig8.3 KB
references/acceptance-criteria.mdmarkdown4.0 KB
references/agentic-os-skill-map.mdmarkdown2.3 KB
references/architecture/architecture.mdmarkdown2.4 KB
references/architecture/context-folder-patterns.mdmarkdown3.3 KB
references/architecture/vision.mdmarkdown56.6 KB
references/cheap-agent-transition-simulation.mdmarkdown6.1 KB
references/control-plane-architecture.mdmarkdown9.0 KB
references/control-plane-rebuild-recovery.mdmarkdown6.2 KB
references/control-plane-simulation-protocol.mdmarkdown5.7 KB
references/diagrams/agentic-os-memory-subsystem.mmdother1.4 KB
references/diagrams/architecture-overview.mmdother3.1 KB
references/diagrams/control-plane-architecture.mermaidother6.3 KB
references/diagrams/control-plane-lifecycle-hardened-with-ciba-rar.mermaidother4.5 KB
references/diagrams/control-plane-pipeline-happy-path.mermaidother5.0 KB
references/diagrams/control-plane-pipeline.mermaidother9.3 KB
references/diagrams/event-bus-architecture.mmdother2.4 KB
references/diagrams/increment-b-human-only-transition-ssh-signing.mermaidother5.3 KB
references/edge-matrix.mdmarkdown13.3 KB
references/fallback-tree.mdmarkdown2.9 KB
references/health-detailed-reference.mdmarkdown7.1 KB
references/healthy-transcript.mdmarkdown3.8 KB
references/implementation-ledger-contract.mdmarkdown851 B
references/intake-detailed-reference.mdmarkdown3.1 KB
references/modes/health.mdmarkdown3.4 KB
references/modes/intake.mdmarkdown3.8 KB
references/modes/mode.mdmarkdown5.8 KB
references/modes/simulator.mdmarkdown6.2 KB
references/modes/worktree.mdmarkdown2.9 KB
references/multi-round-external-review-protocol.mdmarkdown2.6 KB
references/worktree-reconciliation-and-multi-worktree-practices.mdmarkdown5.8 KB
requirements-dev.inother741 B
requirements-dev.txtmarkdown603 B
requirements.inother196 B
requirements.txtmanifest202 B
scripts/agent_control.pyscript97.7 KB
scripts/audit_map_debt.pyscript6.1 KB
scripts/capability_probe.pyscript6.4 KB
scripts/check_plan_links.pyscript1.8 KB
scripts/control_plane/__init__.pyscript842 B
scripts/control_plane/adapters.pyscript144.9 KB
scripts/control_plane/approver_policy.pyscript20.0 KB
scripts/control_plane/baseline_transition_report.pyscript4.0 KB
scripts/control_plane/constants.pyscript13.5 KB
scripts/control_plane/coordinator.pyscript57.3 KB
scripts/control_plane/edge_matrix.pyscript3.1 KB
scripts/control_plane/gate1_approval.pyscript10.7 KB
scripts/control_plane/gate_evidence.pyscript9.9 KB
scripts/control_plane/identity_layout.pyscript2.9 KB
scripts/control_plane/identity_setup.pyscript11.0 KB
scripts/control_plane/implementation.pyscript3.7 KB
scripts/control_plane/implementation_loop.pyscript11.3 KB
scripts/control_plane/inspection.pyscript3.9 KB
scripts/control_plane/installation_probe.pyscript5.7 KB
scripts/control_plane/isolation_check.pyscript14.0 KB
scripts/control_plane/measurement.pyscript39.1 KB
scripts/control_plane/pipeline_simulator.pyscript30.0 KB
scripts/control_plane/policy.pyscript32.5 KB
scripts/control_plane/ports.pyscript20.3 KB
scripts/control_plane/proof_edges.pyscript4.6 KB
scripts/control_plane/proof_policy.pyscript2.2 KB
scripts/control_plane/receipt_provenance.pyscript4.7 KB
scripts/control_plane/registry.pyscript32.9 KB
scripts/control_plane/review_options.pyscript8.2 KB
scripts/control_plane/review_selection.pyscript3.2 KB
scripts/control_plane/run_transition_simulation.pyscript12.0 KB
scripts/control_plane/signing_selftest.pyscript6.8 KB
scripts/control_plane/simulation_identity.pyscript10.4 KB
scripts/control_plane/snapshot.pyscript10.8 KB
scripts/control_plane/ssh_signing.pyscript21.8 KB
scripts/control_plane/state_machine.pyscript5.8 KB
scripts/control_plane/transition_request.pyscript19.5 KB
scripts/control_plane/transition_simulation_cases.pyscript24.6 KB
scripts/control_plane/transition_templates.yamlconfig159.1 KB
scripts/control_plane/tty_signer.pyscript3.0 KB
scripts/control_plane/wrappers/__init__.pyscript24 B
scripts/control_plane/wrappers/record_interview_question.pyscript8.0 KB
scripts/control_plane/wrappers/record_retrospective.pyscript2.3 KB
scripts/control_plane/wrappers/run_exit_verification.pyscript6.4 KB
scripts/control_plane/wrappers/run_verify_exit_bundle.pyscript5.4 KB
scripts/control_plane/wrappers/write_plan_document.pyscript9.6 KB
scripts/control_plane_hooks.pyscript10.5 KB
scripts/control_plane_mode.pyscript12.0 KB
scripts/distill_playbook.pyexecutablescript9.9 KB
scripts/evolution_state.pyscript29.4 KB
scripts/export_upstream_pr.pyscript4.4 KB
scripts/interview_spec_engine.pyscript9.1 KB
scripts/kernel.pyscript14.6 KB
scripts/pre-commit-evolution-guardexecutablescript3.7 KB
scripts/pre-commit-pipeline-guardexecutablescript13.6 KB
scripts/pre-push-review-guardexecutablescript10.5 KB
scripts/record_trace.pyscript7.2 KB
scripts/smoke_test.pyexecutablescript22.6 KB
scripts/test_capability_probe.pyscript3.9 KB
scripts/test_worktree_manager.pyscript2.8 KB
scripts/verify_evolution_receipt.pyscript7.5 KB
scripts/verify_gate_evidence.pyscript1.6 KB
scripts/worktree_manager.pyscript3.0 KB
tests/conftest.pyscript7.7 KB
tests/helpers/__init__.pyscript0 B
tests/helpers/control_plane_fixtures.pyscript2.6 KB
tests/helpers/control_plane_repo.pyscript4.0 KB
tests/helpers/gate1_fixtures.pyscript5.8 KB
tests/helpers/human_signer.pyscript7.3 KB
tests/helpers/implementation_ledger.pyscript1.1 KB
tests/interview_helpers.pyscript5.2 KB
tests/test_actionable_rollback.pyscript2.2 KB
tests/test_agent_control.pyscript190.6 KB
tests/test_agent_control_gate_characterization.pyscript14.7 KB
tests/test_approve_transition.pyscript10.5 KB
tests/test_approver_identity_guidance.pyscript3.4 KB
tests/test_approver_isolation.pyscript12.3 KB
tests/test_audit_map_debt.pyscript4.7 KB
tests/test_authorized_actor_enforcement.pyscript22.9 KB
tests/test_background_document_priority.pyscript924 B
tests/test_check_plan_links.pyscript1.1 KB
tests/test_content_snapshot.pyscript11.8 KB
tests/test_control_plane_architecture_diagram_contract.pyscript9.0 KB
tests/test_control_plane_architecture_overview_contract.pyscript2.1 KB
tests/test_control_plane_critic_review.pyscript3.1 KB
tests/test_control_plane_crypto_adapter.pyscript5.0 KB
tests/test_control_plane_delegation_contract.pyscript5.7 KB
tests/test_control_plane_facade_composition.pyscript15.9 KB
tests/test_control_plane_filesystem_adapter.pyscript4.9 KB
tests/test_control_plane_hooks.pyscript7.3 KB
tests/test_control_plane_interview_guidance.pyscript3.8 KB
tests/test_control_plane_measurement_contract.pyscript28.0 KB
tests/test_control_plane_mode.pyscript7.5 KB
tests/test_control_plane_mode_guards.pyscript3.5 KB
tests/test_control_plane_model_catalog_adapter.pyscript9.2 KB
tests/test_control_plane_pipeline_diagram_contract.pyscript2.3 KB
tests/test_control_plane_pipeline_simulator.pyscript7.5 KB
tests/test_control_plane_policy.pyscript13.0 KB
tests/test_control_plane_ports.pyscript3.2 KB
tests/test_control_plane_reset_transition.pyscript13.6 KB
tests/test_control_plane_schema_rebuild_atomicity.pyscript20.0 KB
tests/test_control_plane_simulation_protocol_contract.pyscript959 B
tests/test_control_plane_sqlite_persistence_adapter.pyscript5.5 KB
tests/test_control_plane_state_machine.pyscript15.2 KB
tests/test_control_plane_trigger_enforcement.pyscript14.6 KB
tests/test_control_plane_worktree_sharing.pyscript4.5 KB
tests/test_domain_namespaces.pyscript6.7 KB
tests/test_done_closure_proof.pyscript6.9 KB
tests/test_draft_plan_interactive_outline_gap.pyscript2.2 KB
tests/test_dual_identity_onboarding.pyscript7.3 KB
tests/test_edge_matrix.pyscript3.2 KB
tests/test_ensure_schema_fastpath.pyscript4.4 KB
tests/test_evolution_guards.pyscript14.9 KB
tests/test_evolution_scripts.pyscript55.3 KB
tests/test_gate1_guidance.pyscript1.8 KB
tests/test_gate3_code_acceptance.pyscript13.5 KB
tests/test_graph_state_machine.pyscript16.0 KB
tests/test_guidance_readiness.pyscript2.2 KB
tests/test_health_check_signing_status.pyscript3.5 KB
tests/test_human_decision_trigger_enforcement.pyscript37.3 KB
tests/test_human_only_wiring.pyscript22.3 KB
tests/test_human_signer_isolation.pyscript4.0 KB
tests/test_identity_verification_readiness.pyscript5.8 KB
tests/test_implementation_ledger.pyscript3.4 KB
tests/test_implementation_loop.pyscript6.9 KB
tests/test_implementation_runtime_bridge.pyscript2.6 KB
tests/test_init_agentic_os_scaffolding.pyscript10.0 KB
tests/test_init_respects_control_plane_mode.pyscript4.3 KB
tests/test_inspect_verbs.pyscript3.6 KB
tests/test_installation_probe.pyscript3.1 KB
tests/test_intake_scenarios.pyscript7.2 KB
tests/test_interview_plan_outline.pyscript2.8 KB
tests/test_isolation_check.pyscript12.5 KB
tests/test_isolation_setup_docs.pyscript2.7 KB
tests/test_kernel_security.pyscript4.0 KB
tests/test_legacy_input_fallback.pyscript6.0 KB
tests/test_list_review_options.pyscript3.1 KB
tests/test_multi_agent_bundle_gate.pyscript5.5 KB
tests/test_one_approver_per_pipeline.pyscript15.8 KB
tests/test_os_init_dual_identity.pyscript3.9 KB
tests/test_os_init_identity_bootstrap.pyscript8.8 KB
tests/test_os_init_identity_status.pyscript3.9 KB
tests/test_os_init_single_instruction_file.pyscript7.3 KB
tests/test_p00_live_baseline.pyscript10.2 KB
tests/test_p01_intake_persistence.pyscript6.7 KB
tests/test_post_run_metrics_protocol.pyscript3.3 KB
tests/test_pre_commit_pipeline_guard.pyscript29.1 KB
tests/test_pre_push_review_guard.pyscript5.7 KB
tests/test_receipt_provenance.pyscript6.6 KB
tests/test_retrospective_pipeline.pyscript5.3 KB
tests/test_review_option_menus.pyscript6.6 KB
tests/test_review_selection.pyscript8.2 KB
tests/test_round3_fixes.pyscript8.3 KB
tests/test_rules_compliance.pyscript1.3 KB
tests/test_run_transition_simulation_formatting.pyscript1.7 KB
tests/test_run_verify_exit_bundle.pyscript10.2 KB
tests/test_setup_ciba_identity.pyscript11.2 KB
tests/test_signed_approval_human_receipt.pyscript3.9 KB
tests/test_signing_mechanics_selftest.pyscript6.9 KB
tests/test_signing_skill_selfcontained.pyscript3.4 KB
tests/test_skip_receipt_guidance.pyscript2.7 KB
tests/test_ssh_signing.pyscript23.9 KB
tests/test_strategy_artifacts.pyscript21.8 KB
tests/test_transition_answer_normalization.pyscript1.1 KB

scripts/control_plane/policy.py

View on GitHub
"""
control_plane/policy.py — Unified Declarative Gate-Policy Engine (issue-524, Step 4)
========================================================================================

Purpose:
    Replaces agent_control.py's 4 scattered gate mechanisms — the GATE_REQUIREMENTS registry,
    the 3 hardcoded _check_prior_art_guard/_check_done_guard/_check_rolled_back_guard methods,
    and update_worktree()'s own independent pushed_to_origin barrier — with ONE declarative
    policy-evaluation mechanism that can evaluate both:
      (a) lifecycle transitions, keyed by (from_state, to_state); and
      (b) controlled operations (e.g. the worktree-push write), keyed by an operation name.
    Per docs/plans/issue-524-spec.md Section 5 Step 4 (generalized per external plan review
    round 1): one policy path, two rule kinds it can evaluate — not two independent engines.

    This module does not itself talk to SQLite, subprocess, hashlib, or the filesystem — every
    rule receives a `ctx` dict of plain data/callables (counts, a bound verify-sovereignty
    callback), so this file has zero infrastructure imports (dependency-direction invariant,
    DoD item 5). Since the persistence extraction revision, `ctx`'s callables are backed by
    control_plane.adapters.SqlitePersistenceAdapter (via ControlPlane) rather than a raw
    connection — this module never sees or imports sqlite3 either way.

Layer:
    OS Kernel / Execution Control Plane Substrate — Policy (domain layer)

Key Input Dependencies:
    None directly — all data arrives via the `ctx` dict passed to `evaluate()`.

    Key Functions:
    - PolicyViolation — exception raised when a rule's check fails (caller-facing validation
      failure, e.g. missing receipt)
    - PolicyConfigurationError — exception raised when a rule itself is malformed (an unknown
      `check` type) — a bug in the policy registry, never silently treated as a pass
    - CHECK_REGISTRY — closed registry of deterministic check callables keyed by check_id
    - OPERATION_RULES — declarative registry keyed by operation name
    - evaluate_check() — evaluates a deterministic check by check_id
    - evaluate_operation() — evaluates all rules registered for a given operation name
"""

from fnmatch import fnmatch
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from control_plane.constants import (
    AGENT_CONTROL_CMD,
    STATE_INTAKE, STATE_INTERVIEW, STATE_DRAFT_PLAN, STATE_MULTI_AGENT_REVIEW, STATE_PLAN_REVIEW, STATE_AWAITING_APPROVAL, STATE_IN_WORKTREE, STATE_WORKTREE_REVIEW, STATE_MULTI_AGENT_CODE_REVIEW, STATE_VERIFY_EXIT, STATE_DONE, STATE_ROLLED_BACK,
)


class DelegationContractError(ValueError):
    """Raised when a delegation contract or receipt violates its approved boundary."""


DELEGATION_REQUIRED_FIELDS = (
    "objective", "scope", "authority", "tool_limits", "budget", "artifacts",
    "verifier", "escalation", "fallback_candidates", "backend", "model_id",
    "cost_tier", "capability_class",
)


def validate_delegation_contract(contract: Dict[str, Any]) -> None:
    """Validate the governance boundary without constraining model reasoning or strategy."""
    missing = [field for field in DELEGATION_REQUIRED_FIELDS if field not in contract]
    if missing:
        raise DelegationContractError("Delegation contract missing: " + ", ".join(missing))
    if not str(contract["objective"]).strip():
        raise DelegationContractError("Delegation objective is required")
    if not isinstance(contract["scope"], list) or not contract["scope"] or not all(isinstance(item, str) and item for item in contract["scope"]):
        raise DelegationContractError("Delegation scope must contain at least one boundary")
    if not isinstance(contract["tool_limits"], list):
        raise DelegationContractError("Delegation tool_limits must be a list")
    budget = contract["budget"]
    if not isinstance(budget, dict) or int(budget.get("max_requests", 0)) < 1:
        raise DelegationContractError("Delegation budget must define max_requests >= 1")
    if contract["cost_tier"] not in {"low", "medium", "high"}:
        raise DelegationContractError("Delegation cost_tier must be low, medium, or high")
    authority = contract["authority"]
    if not isinstance(authority, dict) or not isinstance(authority.get("read"), bool):
        raise DelegationContractError("Delegation authority must declare boolean read access")
    if not isinstance(contract["artifacts"], list):
        raise DelegationContractError("Delegation artifacts must be a list")
    if not isinstance(contract["verifier"], dict) or not contract["verifier"].get("command"):
        raise DelegationContractError("Delegation verifier command is required")
    if not isinstance(contract["escalation"], dict):
        raise DelegationContractError("Delegation escalation policy is required")
    if not isinstance(contract["fallback_candidates"], list):
        raise DelegationContractError("Delegation fallback_candidates must be a list")


def delegation_requires_approval(contract: Dict[str, Any]) -> bool:
    """High-cost or write-capable delegation requires a human approval receipt."""
    authority = contract.get("authority", {})
    return contract.get("cost_tier") == "high" or bool(authority.get("write"))


def validate_delegation_receipt(
    contract: Dict[str, Any],
    receipt: Dict[str, Any],
    request_count: int,
) -> bool:
    """Validate one execution attempt against the approved contract."""
    if not receipt.get("backend_available", True):
        raise DelegationContractError("Delegation backend is unavailable")
    max_requests = int(contract["budget"].get("max_requests", 0))
    if request_count >= max_requests:
        raise DelegationContractError("Delegation budget exhausted")
    if receipt.get("cost_tier") not in {"low", "medium", "high"}:
        raise DelegationContractError("Delegation receipt has invalid cost tier")
    if receipt.get("written_paths"):
        patterns = contract["scope"]
        out_of_scope = [path for path in receipt["written_paths"] if not any(fnmatch(path, pattern) for pattern in patterns)]
        if out_of_scope:
            raise DelegationContractError(f"Delegation write is outside approved scope: {out_of_scope}")
    changed_identity = receipt.get("backend") != contract.get("backend") or receipt.get("model_id") != contract.get("model_id")
    if changed_identity:
        declared = any(
            candidate.get("backend") == receipt.get("backend") and candidate.get("model_id") == receipt.get("model_id")
            for candidate in contract.get("fallback_candidates", [])
            if isinstance(candidate, dict)
        )
        if not declared:
            raise DelegationContractError("Delegation substitution is not a declared fallback candidate")
    changed_boundary = any(
        receipt.get(field) != contract.get(field)
        for field in ("cost_tier", "capability_class")
    ) or bool(receipt.get("write_capable")) != bool(contract["authority"].get("write"))
    if changed_boundary:
        raise DelegationContractError("Delegation substitution requires renewed approval")
    return True


class PolicyViolation(Exception):
    """Raised when a policy rule's check fails. agent_control.py's ControlPlane catches this
    and re-raises as PersistenceInvariantViolation to preserve the existing CLI exit-code
    contract (DoD item 6 of docs/plans/issue-524-spec.md) — external behavior is unchanged."""
    pass


class PolicyConfigurationError(Exception):
    """Raised when a rule declares an unrecognized `check` type — a bug in the policy registry
    itself, not a normal validation failure. Deliberately NOT a subclass of PolicyViolation:
    ControlPlane's `except PolicyViolation` clauses must not silently convert this into a
    PersistenceInvariantViolation (which would look like an ordinary, retryable gate failure)
    — it should propagate as an unhandled error (CLI exit code 1, a genuine crash), since it
    means a rule was misconfigured, not that a real precondition was unmet. Added after
    external post-implementation review flagged the prior `else: satisfied = True` fallback
    as an unsafe fail-open default for the single authoritative policy engine."""
    pass


def _gate_receipt_exists(ctx: Dict[str, Any], gate_name: str) -> bool:
    """Rule primitive: checks ctx['has_receipt'](gate_name)."""
    return ctx["has_receipt"](gate_name)


def _gate_critic_review_pass(ctx: Dict[str, Any]) -> bool:
    """Rule primitive: checks ctx['has_passing_critic_review']()."""
    return ctx["has_passing_critic_review"]()


def _gate_any_of(ctx: Dict[str, Any], options: List[Dict[str, Any]]) -> bool:
    """Rule primitive: passes if any nested option passes."""
    for opt in options:
        if opt["type"] == "receipt" and _gate_receipt_exists(ctx, opt["gate_name"]):
            return True
        if opt["type"] == "critic_review_pass" and _gate_critic_review_pass(ctx):
            return True
    return False


def _prior_art_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Predicate rule folding in the original _check_prior_art_guard: blocks EVOLUTION tasks
    from leaving INTAKE without a logged prior-art scan. Returns an error message string if
    the rule fails (with the exact original wording), or None if it passes/is not applicable."""
    task = ctx["task"]
    if task.get("task_type", "GENERAL") != "EVOLUTION":
        return None
    if ctx["count_asymmetric_persistence"](details_like="%prior_art_scan%") > 0:
        return None
    task_id = ctx["task_id"]
    return (
        f"Cannot advance EVOLUTION task '{task_id}' past INTAKE: "
        "Prior art scan required. Read references/map-debt.md (check Repeat: YES entries) "
        "and wiki/decisions/ before drafting hypotheses. "
        "Log result via log_asymmetric_persistence() with details containing 'prior_art_scan'."
    )


def _interview_route_check(ctx: Dict[str, Any], expected_classification: str, adaptive_question_id: str) -> Optional[str]:
    """Require the short-form interview baseline and its classification-driven follow-up."""
    answers = ctx.get("stage_answers", {})
    if answers.get("interview_classification", "").strip() != expected_classification:
        return (
            f"Interview classification must be {expected_classification} before this route; "
            f"received '{answers.get('interview_classification', '')}'."
        )
    required_ids = (
        "interview_classification",
        "interview_summary",
        "interview_scope",
        "interview_verification",
        adaptive_question_id,
    )
    missing = [qid for qid in required_ids if not str(answers.get(qid, "")).strip()]
    if missing:
        return "Interview answers missing: " + ", ".join(missing)
    return None


def _interview_trivial_check(ctx: Dict[str, Any]) -> Optional[str]:
    return _interview_route_check(ctx, "TRIVIAL", "interview_trivial_evidence")


def _interview_standard_check(ctx: Dict[str, Any]) -> Optional[str]:
    return _interview_route_check(ctx, "STANDARD", "interview_acceptance_criteria")


def _interview_plan_route_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Allow either interview route to produce a bounded plan artifact.

    TRIVIAL work uses the same lifecycle states as STANDARD work, but omits the
    standard-only acceptance-detail and planning-model questions.  It still
    requires the short interview and explicit smallest-change evidence.
    """
    classification = str(ctx.get("stage_answers", {}).get("interview_classification", "")).strip()
    if classification == "TRIVIAL":
        return _interview_trivial_check(ctx)
    if classification == "STANDARD":
        return _interview_standard_check(ctx)
    return "Interview classification must be TRIVIAL or STANDARD before plan drafting."


def _worktree_isolation_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Require isolated worktree metadata unless a human records an exception.

    Also rejects registering the main checkout path itself as the "worktree" —
    found live (2026-09-13): an agent passed --path "$(pwd)" (the main checkout)
    to update-worktree, which this check previously accepted because it only
    verified worktree_path/worktree_branch were non-empty and the branch wasn't
    main/master. That is not an isolated worktree. The only sanctioned way to
    work in the existing checkout is the pre-existing existing_worktree_exception
    receipt (recorded when the user explicitly authorizes it), not a default."""
    task = ctx.get("task") or {}
    if ctx["count_receipts"]("existing_worktree_exception", 0) > 0:
        return None

    worktree_path = str(task.get("worktree_path") or "").strip()
    worktree_branch = str(task.get("worktree_branch") or "").strip()
    if not worktree_path or not worktree_branch:
        return (
            "Cannot enter IN_WORKTREE: record an isolated worktree path and feature branch "
            "before implementation, or record an explicit existing_worktree_exception."
        )
    if worktree_branch in {"main", "master"}:
        return (
            f"Cannot enter IN_WORKTREE on default branch '{worktree_branch}': use an isolated "
            "feature branch or record an explicit existing_worktree_exception."
        )

    repo_root = str(ctx.get("repo_root") or "").strip()
    if repo_root:
        resolved_worktree = str(Path(worktree_path).resolve())
        resolved_repo_root = str(Path(repo_root).resolve())
        if resolved_worktree == resolved_repo_root:
            return (
                "Cannot enter IN_WORKTREE: registered worktree_path is the main checkout itself "
                f"('{resolved_worktree}'), not an isolated worktree. Create an isolated worktree "
                "(e.g. .worktrees/task-<task-id>/) and register that path with update-worktree, "
                "or record an explicit human existing_worktree_exception receipt if the user has "
                "authorized working directly in the existing checkout."
            )
    return None


def _main_clean_before_approval_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Enforce the documented-but-previously-unenforced practice from
    references/worktree-reconciliation-and-multi-worktree-practices.md Section 1:
    commit interim INTAKE/INTERVIEW/DRAFT_PLAN work to a small branch and get it
    merged BEFORE APPROVED, so main is clean before a worktree is ever created.
    main_worktree_reconciliation (a later check, at APPROVED -> IN_WORKTREE) is a
    safety net for what slips through, not a substitute for keeping main clean in
    the first place -- this check closes that gap at the earlier edge.

    Found live (2026-09-13): an agent accumulated substantial uncommitted/committed
    work directly on the task's own branch through INTERVIEW/DRAFT_PLAN, entered
    APPROVED/IN_WORKTREE without a clean-foundation commit+PR cycle, then could not
    push the branch at all once IN_WORKTREE (pre-push-review-guard correctly denies
    task-branch pushes before DONE) -- a real conflict between two individually
    correct rules, caused by skipping this earlier gate."""
    if ctx["count_receipts"]("main_dirty_before_approval_exception", 0) > 0:
        return None
    get_advisory = ctx.get("get_main_dirty_advisory")
    if get_advisory is None:
        return None
    advisory = get_advisory()
    dirty_count = advisory.get("dirty_count", 0) if isinstance(advisory, dict) else 0
    if dirty_count > 0:
        dirty_paths = advisory.get("dirty_paths", []) if isinstance(advisory, dict) else []
        joined = ", ".join(dirty_paths[:10])
        more = f" (+{len(dirty_paths) - 10} more)" if len(dirty_paths) > 10 else ""
        return (
            f"Cannot enter APPROVED: {dirty_count} dirty path(s) on the source checkout "
            f"({joined}{more}). Commit this interim work to a small branch and get it "
            "reviewed/merged before a worktree is created, per "
            "references/worktree-reconciliation-and-multi-worktree-practices.md Section 1, "
            "or record an explicit human main_dirty_before_approval_exception receipt with "
            "the reason if the human has authorized proceeding with dirty state."
        )
    return None


def _main_worktree_reconciliation_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Force pre-worktree dirty source-checkout changes into the newly registered worktree
    at transition time via code (ctx['reconcile_main_into_worktree']), never by trusting an
    agent's claim that reconciliation happened (github issue #609). A genuine conflict —
    the worktree independently diverged on the same path — blocks the transition instead
    of silently overwriting either side; record an explicit human exception to proceed."""
    if ctx["count_receipts"]("main_worktree_reconciliation_exception", 0) > 0:
        return None
    reconcile = ctx.get("reconcile_main_into_worktree")
    if reconcile is None:
        return "Cannot enter IN_WORKTREE: reconciliation callable unavailable in policy context."
    result = reconcile()
    conflicts = result.get("conflicts") or []
    if conflicts:
        joined = ", ".join(conflicts)
        return (
            "Cannot enter IN_WORKTREE: the following source-checkout changes conflict with "
            f"independent worktree content and were not auto-reconciled: {joined}. Resolve the "
            "conflict manually inside the worktree, or record an explicit human "
            "main_worktree_reconciliation_exception receipt with the reason."
        )
    return None


def _done_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Predicate rule folding in the original _check_done_guard: requires a passing test_suite
    receipt, an asymmetric persistence log entry, a clean leak check, and (if any verifiers
    were locked) intact verifier sovereignty. Returns an error message on failure, else None.
    Raises whatever ctx['verify_sovereignty']() raises (VerifierSovereigntyViolation) — that
    exception type and message are preserved exactly, unrelated to PolicyViolation."""
    task_id = ctx["task_id"]
    planning_only = ctx["count_receipts"](gate_name="planning_only_completion", exit_code=0) > 0
    # A TRIVIAL implementation still needs focused verification, but does not
    # require a repository-wide suite unless the user requests/authorizes it.
    trivial_route = ctx["count_receipts"]("trivial_route_selected", 0) > 0
    required_test_gate = "plan_validation" if planning_only else ("focused_test_suite" if trivial_route else "test_suite")
    if ctx["count_receipts"](gate_name=required_test_gate, exit_code=0) == 0:
        return (
            f"Cannot complete task '{task_id}': No passing {required_test_gate} verification receipt "
            f"(gate_name='{required_test_gate}', exit_code == 0) found."
        )

    if ctx["count_locked_verifiers"]() > 0:
        ctx["verify_sovereignty"]()  # raises VerifierSovereigntyViolation directly if tampered

    if ctx["count_asymmetric_persistence"](
        destination_like_any=["%wiki/decisions/%", "%references/map-debt.md%", "%map-debt%"]
    ) == 0:
        return (
            f"Cannot complete task '{task_id}': Asymmetric persistence required before DONE. "
            "Log an entry to wiki/decisions/ or references/map-debt.md."
        )

    if ctx["count_receipts"](gate_name="leak_check", exit_code=0) == 0:
        return f"Cannot complete task '{task_id}': Missing clean leak check receipt (gate_name='leak_check', exit_code=0)."

    return None


def _full_test_suite_or_trivial_focused(ctx: Dict[str, Any]) -> Optional[str]:
    """Keep STANDARD full-suite enforcement while allowing explicit TRIVIAL focus."""
    if ctx["count_receipts"]("full_test_suite", 0) > 0:
        return None
    if (
        ctx["count_receipts"]("trivial_route_selected", 0) > 0
        and ctx["count_receipts"]("focused_test_suite", 0) > 0
    ):
        return None
    return (
        "Cannot advance: record a passing full_test_suite receipt, or for a selected "
        "TRIVIAL route record a passing focused_test_suite receipt."
    )


def _retrospective_done_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Requires the optional survey to be completed or explicitly skipped before DONE."""
    if not ctx["has_complete_retrospective"]():
        return (
            f"Cannot complete task '{ctx['task_id']}': retrospective is incomplete. "
            "Complete the survey or explicitly skip it with a reason; confirmed issue follow-ups "
            "must be created or rejected first."
        )
    return None


def _implementation_completeness_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Require the approved implementation ledger to prove every task is complete."""
    return ctx["check_implementation_completeness"]()


def _rolled_back_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Predicate rule folding in the original _check_rolled_back_guard: requires at least one
    asymmetric_persistence_log entry documenting the failure before rollback."""
    task_id = ctx["task_id"]
    if ctx["count_asymmetric_persistence"]() > 0:
        return None
    return (
        f"Cannot roll back task '{task_id}': Asymmetric persistence required. "
        "Document failure mode/learning in asymmetric_persistence_log before rolling back code."
    )


def _worktree_push_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Predicate rule enforcing push gate: pushing to origin is strictly forbidden unless
    the task has cleared all verification gates and is in final state DONE."""
    task_state = ctx["task_state"]
    task_id = ctx["task_id"]
    if task_state == STATE_DONE:
        return None
    return (
        f"Cannot mark worktree 'pushed_to_origin' for task '{task_id}': Task state is '{task_state}'. "
        "Pushing to origin requires full pipeline completion. Task must be in final state 'DONE' before pushing."
    )


def _task_commit_check(ctx: Dict[str, Any]) -> Optional[str]:
    """Predicate rule enforcing pipeline execution and stage validity on git commits.
    
    Permits commit if:
    1. The task is in an authorized implementation state (IN_WORKTREE, WORKTREE_REVIEW,
       MULTI_AGENT_CODE_REVIEW, VERIFY_EXIT, DONE); OR
    2. The task is in a planning/proposal state (INTAKE, INTERVIEW, DRAFT_PLAN, PLAN_REVIEW,
       MULTI_AGENT_REVIEW, AWAITING_APPROVAL) AND all staged files are documentation under
       docs/plans/ or docs/superpowers/.
       
    Furthermore, if a session was initiated in the control plane:
    - Verifies all transitions recorded in task_transitions match valid_transitions.
    - Verifies no transition violations are recorded for the task.
    - Verifies transition chain continuity from INTAKE to current state.
    """
    task_state = ctx.get("task_state")
    task_id = ctx.get("task_id", "unknown")
    staged_files: List[str] = ctx.get("staged_files", [])

    implementation_states = (STATE_IN_WORKTREE, STATE_WORKTREE_REVIEW, STATE_MULTI_AGENT_CODE_REVIEW, STATE_VERIFY_EXIT, STATE_DONE)
    planning_states = (STATE_INTAKE, STATE_INTERVIEW, STATE_DRAFT_PLAN, STATE_PLAN_REVIEW, STATE_MULTI_AGENT_REVIEW, STATE_AWAITING_APPROVAL)

    # If in planning states, permit only if ALL staged files are docs/plans/ or docs/superpowers/
    if task_state in planning_states:
        if staged_files:
            non_doc_files = [
                f for f in staged_files
                if not (f.startswith("docs/plans/") or f.startswith("docs/superpowers/"))
            ]
            if non_doc_files:
                return (
                    f"Cannot commit code for task '{task_id}': Task state is '{task_state}' (Proposal Mode). "
                    f"Production code modifications are prohibited during planning. Non-planning staged files: {non_doc_files}. "
                    f"Complete Socratic interview, spec generation, and human approval before implementing in worktree."
                )
        # If all staged files are planning docs (or no staged files provided), allow commit
        return None

    if task_state not in implementation_states:
        return (
            f"Cannot commit for task '{task_id}': Task state is '{task_state}'. "
            f"Commits are only permitted in implementation states {implementation_states} "
            f"or during planning with documentation files only."
        )

    # If the caller provided transition history and validation functions, verify execution integrity
    validate_history_fn = ctx.get("validate_transition_history")
    if validate_history_fn is not None:
        history_error = validate_history_fn()
        if history_error:
            return f"Cannot commit for task '{task_id}': Pipeline integrity check failed: {history_error}"

    return None


# --- Controlled-operation rules, keyed by operation name (not a lifecycle transition) ---
OPERATION_RULES: Dict[str, List[Dict[str, Any]]] = {
    "worktree_push": [{"check": "predicate", "fn": _worktree_push_check}],
    "commit": [{"check": "predicate", "fn": _task_commit_check}],
}


# --- Closed Check Registry: check_id -> callable predicate ---
CHECK_REGISTRY: Dict[str, Any] = {
    "prior_art_scan": _prior_art_check,
    "interview_trivial_complete": _interview_trivial_check,
    "interview_standard_complete": _interview_standard_check,
    "interview_plan_route_complete": _interview_plan_route_check,
    "plan_mode_or_socratic": lambda ctx: (
        None if _gate_any_of(ctx, [
            {"type": "receipt", "gate_name": "plan_mode_entry"},
            {"type": "receipt", "gate_name": "socratic_intake_complete"},
        ]) else (
            "Cannot advance: no proof Plan Mode was entered or Socratic intake completed. "
            "Call record_plan_mode_entry() or record_socratic_intake_complete() first."
        )
    ),
    "critic_review_or_skip": lambda ctx: (
        None if _gate_any_of(ctx, [
            {"type": "critic_review_pass"},
            {"type": "receipt", "gate_name": "multi_agent_review_skipped"},
        ]) else (
            "Cannot advance: no passing review or recorded skip found. "
            "To record a review pass: YOU (the agent) run " + AGENT_CONTROL_CMD + " record-critic-review --task-id <task-id> --verdict PASS. "
            "To skip review: the HUMAN runs " + AGENT_CONTROL_CMD + " record-review-skip --task-id <task-id> --phase multi_agent_review --interactive."
        )
    ),
    "critic_review_pass": lambda ctx: (
        None if _gate_critic_review_pass(ctx) else (
            "Cannot advance: no passing critic review found. "
            "YOU (the agent) run: " + AGENT_CONTROL_CMD + " record-critic-review --task-id <task-id> --verdict PASS."
        )
    ),
    "human_approval": lambda ctx: (
        None if _gate_receipt_exists(ctx, "human_approval") else (
            "Cannot advance: no recorded human_approval receipt found. "
            "Call record_human_approval() — this gate can never be skipped."
        )
    ),
    "planning_only_completion": lambda ctx: (
        None if _gate_receipt_exists(ctx, "planning_only_completion") else (
            "Cannot advance: no planning_only_completion receipt found. "
            "Record explicit approval that implementation is intentionally skipped."
        )
    ),
    "worktree_isolation_or_exception": _worktree_isolation_check,
    "main_worktree_reconciliation": _main_worktree_reconciliation_check,
    "main_clean_before_approval": _main_clean_before_approval_check,
    "test_suite": lambda ctx: (
        None if _gate_receipt_exists(ctx, "test_suite") else (
            "Cannot advance: no recorded test_suite verification receipt found. "
            "Call record_verification_receipt(gate_name='test_suite', ...)."
        )
    ),
    # Edge-scoped softening for IN_WORKTREE -> WORKTREE_REVIEW ONLY (added
    # 2026-09-13, explicit human request): accepts either a real test_suite
    # receipt, or an explicit human-recorded skip decision deferring testing
    # to the later MULTI_AGENT_CODE_REVIEW/VERIFY_EXIT gate, which re-checks
    # test_suite/full_test_suite independently and is NOT weakened by this.
    # This does not touch the generic "test_suite" check above, used by
    # other edges -- only this specific edge's deterministic_checks entry
    # points at this function instead.
    "test_suite_or_deferred_to_review": lambda ctx: (
        None if (
            _gate_receipt_exists(ctx, "test_suite")
            or ctx["count_receipts"]("test_suite_deferred_to_review", 0) > 0
        ) else (
            "Cannot advance: no test_suite receipt found, and testing was not explicitly "
            "deferred. Either record a test_suite verification receipt, or record an "
            "explicit human test_suite_deferred_to_review decision if the human wants to "
            "defer testing to the later review/control step."
        )
    ),
    "full_test_suite": lambda ctx: (
        None if ctx["count_receipts"]("full_test_suite", 0) > 0 else (
            "Cannot advance: no recorded passing full_test_suite verification receipt "
            "found. Run the repository-wide pytest -q suite through the approved "
            "verifier and ensure it exits 0."
        )
    ),
    "full_test_suite_or_trivial_focused": _full_test_suite_or_trivial_focused,
    "code_review_or_skip": lambda ctx: (
        None if _gate_any_of(ctx, [
            {"type": "critic_review_pass"},
            {"type": "receipt", "gate_name": "multi_agent_code_review_skipped"},
        ]) else (
            "Cannot advance: no passing code review or recorded skip found. "
            "To record a review pass: YOU (the agent) run " + AGENT_CONTROL_CMD + " record-critic-review --task-id <task-id> --verdict PASS. "
            "To skip review: the HUMAN runs " + AGENT_CONTROL_CMD + " record-review-skip --task-id <task-id> --phase multi_agent_code_review --interactive."
        )
    ),
    "done_guard": _done_check,
    "retrospective_done_guard": _retrospective_done_check,
    "implementation_completeness": _implementation_completeness_check,
    "rolled_back_guard": _rolled_back_check,
}


def get_registered_check_ids() -> List[str]:
    """Returns a list of all registered deterministic check IDs."""
    return list(CHECK_REGISTRY.keys())


def evaluate_check(check_id: str, ctx: Dict[str, Any]) -> None:
    """Evaluates a single check by its check_id. Raises PolicyViolation if check fails,
    or PolicyConfigurationError if check_id is unrecognized."""
    if check_id not in CHECK_REGISTRY:
        raise PolicyConfigurationError(f"Unknown check_id: '{check_id}'")
    fn = CHECK_REGISTRY[check_id]
    error = fn(ctx)
    if error is not None:
        raise PolicyViolation(error)


def evaluate_operation(ctx: Dict[str, Any], operation_name: str) -> None:
    """Evaluates every rule registered for the given controlled operation (e.g.
    'worktree_push'). Raises PolicyViolation on the first failing rule."""
    if operation_name not in OPERATION_RULES:
        raise PolicyConfigurationError(f"Unknown operation: '{operation_name}'")
    for rule in OPERATION_RULES.get(operation_name, []):
        error = rule["fn"](ctx)
        if error is not None:
            raise PolicyViolation(error)


def _run_rule(ctx: Dict[str, Any], rule: Dict[str, Any]) -> None:
    """Dispatches a single rule spec by its `check` type. Raises PolicyViolation if the
    rule's predicate fails, or PolicyConfigurationError if `check` is unrecognized — fails
    closed on a misconfigured rule rather than silently passing (see PolicyConfigurationError
    docstring)."""
    check_type = rule.get("check")
    if check_type == "predicate":
        error = rule["fn"](ctx)
        if error is not None:
            raise PolicyViolation(error)
        return
    raise PolicyConfigurationError(f"Unknown policy check type: '{check_type}'")


def evaluate_transition(ctx: Dict[str, Any], from_state: str, to_state: str) -> None:
    """Evaluates the small set of legacy lifecycle-edge rules that predate the
    template-driven deterministic_checks/CHECK_REGISTRY path in coordinator.py (prior art,
    done, rolled back guards). A no-op for any other edge — everything else is governed
    entirely by CHECK_REGISTRY via evaluate_check(), driven from transition_templates.yaml.

    Deliberately no module-level TRANSITION_RULES/TO_STATE_RULES table here (Architecture
    Review Finding 6, see test_policy_py_contains_no_transition_rules_or_to_state_rules) —
    this local mapping exists only inside this function, routing through the same
    CHECK_REGISTRY functions _prior_art_check/_done_check/_rolled_back_check already use."""
    edge_to_check_fn = {
        (STATE_INTAKE, STATE_INTERVIEW): _prior_art_check,
        (STATE_VERIFY_EXIT, STATE_DONE): _done_check,
        (STATE_IN_WORKTREE, STATE_ROLLED_BACK): _rolled_back_check,
    }
    fn = edge_to_check_fn.get((from_state, to_state))
    if fn is not None:
        _run_rule(ctx, {"check": "predicate", "fn": fn})
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexUnverifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall