richfrem/agent-plugins-skills / plugins/agent-agentic-os/.apm/skills/running-control-plane
running-control-plane
FlaggedCRITICAL 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).
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})
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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: 471k | Updated | Claude CodeCodex | Unverified | Install |
| 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: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| 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 available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |