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/agent_control.py
View on GitHub#!/usr/bin/env python3
"""
agent_control.py — Lightweight SQLite Control Plane for Agent Lifecycle
========================================================================
Purpose:
ACID state machine and audit log for task execution, verifier sovereignty,
pre-execution review gating, worktree 6-state tracking, and cryptographic
receipt generation across multi-tool agent environments.
Architecture (issue-524, hexagonal decomposition):
ControlPlane is a facade composing 5 ports/adapters — it never calls sqlite3, hashlib, or
time directly. Existing calls made with the original constructor arguments and all public
method names/CLI behavior remain fully compatible; the constructor gained new *optional*
adapter-injection parameters (for testing) that did not exist before, so "compatible" is
the accurate claim here, not "unchanged" — a distinction an external review (round 2)
correctly required be stated precisely. ControlPlane's remaining code is APPLICATION
ORCHESTRATION ONLY: it coordinates state-machine validation, policy evaluation,
persistence, cryptographic integrity, filesystem operations, model recommendation, and
clock access through the composed components below — it does not itself implement
state-machine adjacency logic or model tier-selection strategy (both were still embedded
here as of an earlier revision; external review round 3 correctly required both be fully
relocated, and this docstring corrected to stop describing that stale state):
- self._state_machine -> control_plane.state_machine.StateMachine (pure domain class —
no port/adapter pair; it has no infrastructure to abstract)
- Gate/policy logic -> control_plane/policy.py (a pure domain module — see the Gate
Policy section below)
- self._fs -> control_plane.adapters.FilesystemAdapter (FilesystemPort)
- self._crypto -> control_plane.adapters.CryptoAdapter (CryptoPort)
- self._clock -> control_plane.adapters.ClockAdapter (ClockPort)
- self._model_catalog -> control_plane.adapters.ModelCatalogAdapter (ModelCatalogPort —
full resolve_recommended_model() resolution: tool-alias, tier
strategy, and fallback, not just JSON file reads)
- self._persistence -> control_plane.adapters.SqlitePersistenceAdapter (PersistencePort —
connection management, schema migration, AND every task/
transition/receipt/review/verifier/log/worktree CRUD operation;
ControlPlane composes this port, it does not issue SQL itself)
Every port is constructor-injectable for testing (e.g. `ControlPlane(persistence_adapter=...)`)
while defaulting to the real infrastructure implementation for all existing callers.
Layer:
OS Kernel / Execution Control Plane Substrate
Key Input Dependencies:
- SQLite database: context/control_plane.db (auto-initialized with WAL mode)
- Optional model catalog references: plugins/agent-orchestration/skills/cli-agent/references/*.json
Key Functions:
- ControlPlane.init_db() — Initializes tables and WAL mode
- ControlPlane.resolve_recommended_model() — Resolves model tier recommendations
- ControlPlane.create_task() — Creates task in INTAKE
- ControlPlane.get_task() — Retrieves task record
- ControlPlane.transition() — Validates and transitions canonical DAG state
- ControlPlane.lock_verifiers() — Locks SHA256 baseline hashes of verifier files
- ControlPlane.verify_sovereignty() — Ensures verifier hashes have not been mutated
- ControlPlane.record_critic_review() — Logs pre-execution review outcomes
- ControlPlane.record_verification_receipt() — Stamps deterministic exit receipts
- ControlPlane.get_verification_receipts() — Retrieves verification receipts
- ControlPlane.update_worktree() — Updates worktree path, branch, and 6-state status
- ControlPlane.log_asymmetric_persistence() — Logs Layer 2 wiki/map-debt persistence
- ControlPlane.record_plan_mode_entry() — Records proof Plan Mode was entered (DRAFT_PLAN gate)
- ControlPlane.record_socratic_intake_complete() — Records proof Socratic intake completed (DRAFT_PLAN gate)
- ControlPlane.record_human_approval() — Records the human approval receipt (APPROVED->IN_WORKTREE gate, never skippable)
- ControlPlane.record_review_skip() — Records an explicit, auditable decision to skip a discretionary review phase
- main() — CLI dispatcher entry point
Usage Examples:
python3 agent_control.py init --task-id <id> --title <title> --runtime <tool> [--task-type EVOLUTION]
python3 agent_control.py transition --task-id <id> --to <state> --reason <text>
python3 agent_control.py lock-verifiers --task-id <id> --paths <file1,file2>
python3 agent_control.py verify-sovereignty --task-id <id>
python3 agent_control.py record-receipt --task-id <id> --gate <g> --cmd "<c>" --exit-code <ec>
python3 agent_control.py update-worktree --task-id <id> --path <p> --branch <b> --state <s>
python3 agent_control.py status --task-id <id>
python3 agent_control.py log-prior-art --task-id <id> --summary <text> [--repeat-yes-entries <csv>]
python3 agent_control.py record-plan-mode-entry --task-id <id> --actor <a>
python3 agent_control.py record-socratic-intake --task-id <id> --summary <text>
python3 agent_control.py record-human-approval --task-id <id> --approver <a>
python3 agent_control.py record-review-skip --task-id <id> --phase <p> --actor <a> --reason <text>
Gate Policy (unified, issue-524 Step 4):
All gate/policy enforcement — per-edge transition requirements (formerly GATE_REQUIREMENTS),
the prior-art/done/rolled-back guards (formerly 3 hardcoded _check_*_guard methods), and the
worktree-push operation guard (formerly update_worktree()'s own independent barrier) — now
resolves through ONE declarative policy-evaluation mechanism in control_plane/policy.py.
See that module's TRANSITION_RULES/TO_STATE_RULES (lifecycle transitions) and
OPERATION_RULES (controlled operations like the worktree push) for the full registry.
Discretionary review phases (multi_agent_review, multi_agent_code_review) still accept an
explicit recorded skip (record_review_skip) as an alternative to a real critic review —
skips are never silent.
"""
import argparse
import json
import os
import sys
# Ensure UTF-8 output on Windows consoles
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
if hasattr(sys.stderr, "reconfigure"):
try:
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
from pathlib import Path
from typing import Callable, Dict, List, Optional, Any, Tuple
from control_plane.ports import (
FilesystemPort,
CryptoPort,
ModelCatalogPort,
ClockPort,
PersistencePort,
PhaseCapability,
TransitionRecord,
TransitionDecision,
InterviewAnswerRecord,
TransitionCommitRequest,
)
from control_plane.adapters import (
FilesystemAdapter, SqlitePersistenceAdapter, CryptoAdapter, ModelCatalogAdapter, ClockAdapter,
CURRENT_SCHEMA_VERSION,
)
from control_plane import policy as _policy
from control_plane.state_machine import StateMachine, CANONICAL_STATES, ALLOWED_TRANSITIONS, InvalidStateTransition
from control_plane.constants import (
AGENT_CONTROL_CMD,
STATE_INTERVIEW, STATE_DRAFT_PLAN, STATE_APPROVED, STATE_IN_WORKTREE, STATE_RETROSPECTIVE, STATE_DONE,
)
from control_plane.registry import TransitionRegistry
from control_plane.coordinator import TransitionCoordinator, TransitionCoordinatorError
WORKTREE_STATES = [
"written_in_worktree",
"committed_in_worktree",
"pushed_to_origin",
"merged_into_origin_main",
"local_branch_ref_updated",
"checked_out_on_disk"
]
# CANONICAL_STATES, ALLOWED_TRANSITIONS, InvalidStateTransition, and state-machine validation
# logic moved to control_plane/state_machine.py's StateMachine (issue-524, post-round-2-review
# correction) — the domain/state-machine-validation responsibility, previously still embedded
# directly in ControlPlane.transition(). Re-imported above for backward-compatible
# `from agent_control import CANONICAL_STATES` (existing test/consumer import surface).
# SCHEMA_SQL, CURRENT_SCHEMA_VERSION, CHILD_TABLES, ALL_REBUILD_TABLES, and SCHEMA_MIGRATIONS
# moved to control_plane/adapters.py's SqlitePersistenceAdapter (issue-524 Step 5). This module
# re-imports CURRENT_SCHEMA_VERSION above for backward-compatible `from agent_control import
# CURRENT_SCHEMA_VERSION` (existing test/consumer import surface, unchanged).
class PhaseCapabilityDenied(Exception):
"""Raised when an action capability is denied for the current phase/occupancy."""
pass
class VerifierSovereigntyViolation(Exception):
"""Raised when a protected verifier file has been tampered with."""
pass
from control_plane.ports import PersistenceInvariantViolation
class ConcurrentModificationError(Exception):
"""Raised when a transition's expected prior state no longer matches the stored row,
indicating a concurrent writer changed it — never silently overwritten (no last-writer-wins)."""
pass
# Gate/policy enforcement (per-edge transition requirements, prior-art/done/rolled-back
# guards, and the worktree-push operation guard) is unified in control_plane/policy.py's
# TRANSITION_RULES / TO_STATE_RULES / OPERATION_RULES (issue-524 Step 4). This module no
# longer declares its own gate registry.
class ControlPlane:
"""Controller and state machine manager for task lifecycles."""
def __init__(self, db_path: Optional[Path] = None, fs_adapter: Optional["FilesystemPort"] = None,
crypto_adapter: Optional["CryptoPort"] = None,
model_catalog_adapter: Optional["ModelCatalogPort"] = None,
clock_adapter: Optional["ClockPort"] = None,
persistence_adapter: Optional["PersistencePort"] = None,
implementation_controller: Optional[Callable[[str, TransitionRecord], None]] = None):
"""Initializes the ControlPlane instance. All infrastructure is delegated: connection
management, schema migration, and every task/transition/receipt/review/verifier/log/
worktree CRUD operation go through a PersistencePort (SqlitePersistenceAdapter by
default); SHA256/receipt-token hashing through a CryptoAdapter; model-catalog
resolution through a ModelCatalogAdapter; wall-clock time through a ClockAdapter;
state-machine legality through a StateMachine. `self.db_path` mirrors the persistence
adapter's resolved `db_path` attribute where one exists (a fake/test PersistencePort
may not have one, hence `getattr(..., None)`), for any code that introspects it
directly. All optional parameters default to real infrastructure adapters; tests/
callers can substitute any Port implementation — including `persistence_adapter`
directly at construction, added after external review correctly required this be a
true constructor-injection point rather than requiring private-attribute monkeypatching
after construction. Existing calls made with the original `db_path`-only constructor
argument remain fully compatible — the newly-added optional parameters extend the
signature, they do not replace it (see docs/plans/issue-524-spec.md Section 3)."""
self._fs = fs_adapter if fs_adapter is not None else FilesystemAdapter()
self._crypto = crypto_adapter if crypto_adapter is not None else CryptoAdapter()
self._clock = clock_adapter if clock_adapter is not None else ClockAdapter()
self._model_catalog = model_catalog_adapter if model_catalog_adapter is not None else ModelCatalogAdapter()
# Optional runtime bridge. Lifecycle transitions remain authoritative; the
# callback is only invoked after a committed APPROVED -> IN_WORKTREE edge.
self._implementation_controller = implementation_controller
self._state_machine = StateMachine()
if persistence_adapter is not None:
self._persistence = persistence_adapter
else:
self._persistence = SqlitePersistenceAdapter(
db_path if db_path is None else Path(db_path), self._fs, self._clock, self._crypto
)
self.db_path = getattr(self._persistence, "db_path", None)
def init_db(self):
"""Initializes SQLite tables and WAL mode. Delegates to the SqlitePersistenceAdapter,
which self-heals FK-corrupted or legacy schemas."""
self._persistence.ensure_schema()
def create_implementation_controller(
self,
dispatch,
review,
fix=None,
**kwargs,
):
"""Return the canonical persistent implementation runtime for this control plane.
The queue lives beside the control-plane database, so callers no longer need to
import the loop primitive or invent a queue location. Execution callbacks remain
supplied by the active native/portable runtime.
"""
from control_plane.implementation_loop import create_default_controller
db_path = self.db_path or (Path.cwd() / "context" / "control_plane.db")
queue_path = Path(db_path).parent / "implementation-queue.json"
return create_default_controller(queue_path, dispatch, review, fix, **kwargs)
def resolve_recommended_model(self, runtime_tool: str, tier: str = "low") -> Dict[str, str]:
"""Resolves model recommendation and model_id from plugins/agent-orchestration/skills/cli-agent/references/.
Full resolution (tool-alias, tier strategy, fallback) is delegated to
self._model_catalog — this method is a pure delegate (issue-524, post-round-2-review
correction: tier-selection/strategy logic previously still lived in ControlPlane)."""
return self._model_catalog.resolve_recommended_model(runtime_tool, tier)
def create_task(
self,
task_id: str,
title: str,
runtime_tool: str,
spec_path: Optional[str] = None,
model_tier: Optional[str] = None,
model_id: Optional[str] = None,
task_type: str = "GENERAL"
):
"""Creates a new task in INTAKE state and records creation transition."""
if task_type not in ("GENERAL", "EVOLUTION"):
raise ValueError(f"Invalid task_type '{task_type}'. Must be 'GENERAL' or 'EVOLUTION'.")
if model_tier and not model_id:
rec = self.resolve_recommended_model(runtime_tool=runtime_tool, tier=model_tier)
model_id = rec["model_id"]
self._persistence.insert_task(task_id, title, task_type, runtime_tool, spec_path, model_tier, model_id)
return {"task_id": task_id, "main_dirty_advisory": self._get_main_dirty_advisory()}
def _get_main_dirty_advisory(self) -> Dict[str, Any]:
"""Non-blocking report of dirty source-checkout paths at task-creation time, so
interim work isn't left uncommitted through the whole planning phase (github
issue #609 follow-up). Read-only: never copies or modifies files."""
import subprocess
repo_root = getattr(self, "repo_root", None)
if repo_root is None and self.db_path is not None and self.db_path.parent.name == "context":
repo_root = self.db_path.parent.parent
if repo_root is None:
repo_root = Path.cwd()
result = subprocess.run(
["git", "-C", str(repo_root), "status", "--porcelain=v1", "--untracked-files=all"],
capture_output=True, text=True, check=False,
)
paths = [line[3:].strip() for line in result.stdout.splitlines() if line.strip()]
return {"dirty_count": len(paths), "dirty_paths": paths}
def record_premium_consent(
self, task_id: str, stage: str, round_id: str, model_id: str, actor: str
) -> int:
"""Record explicit human consent for a premium model in one exact interview scope."""
if actor != "human":
raise PersistenceInvariantViolation("Premium consent requires actor='human'")
return self._persistence.insert_premium_consent(task_id, stage, round_id, model_id, actor)
def require_premium_consent(self, task_id: str, stage: str, round_id: str, model_id: str) -> None:
"""Deny premium use unless human consent matches the exact stage and round."""
if not self._persistence.has_premium_consent(task_id, stage, round_id, model_id):
raise PersistenceInvariantViolation(
"Premium consent missing for "
f"task_id='{task_id}', stage='{stage}', round_id='{round_id}', model_id='{model_id}'"
)
def record_source_assisted_answer_candidate(
self,
task_id: str,
stage: str,
round_id: str,
question_id: str,
answer: str,
source_path: str,
source_authorized: bool = True,
) -> int:
"""Persist an authorized source answer only as a candidate pending human confirmation."""
if not source_authorized:
raise PersistenceInvariantViolation("Source-assisted answer candidates require an authorized source")
return self._persistence.insert_source_assisted_answer_candidate(
task_id, stage, round_id, question_id, answer, source_path, source_authorized
)
def confirm_source_assisted_answer_candidate(self, candidate_id: int, actor: str) -> None:
"""Confirm one pending source candidate through the human decision boundary."""
if actor != "human":
raise PersistenceInvariantViolation("Source-assisted answer confirmation requires actor='human'")
if not self._persistence.confirm_source_assisted_answer_candidate(candidate_id, actor):
raise ValueError(f"Pending source-assisted answer candidate not found: {candidate_id}")
def assert_interview_exit_ready(
self, task_id: str, stage: str, round_id: Optional[str]
) -> None:
"""Block interview exit while the requested scope has a pending source candidate."""
if self._persistence.has_unconfirmed_source_assisted_answer_candidates(task_id, stage, round_id):
raise PersistenceInvariantViolation(
"Cannot exit interview with unconfirmed source-assisted answer candidate "
f"for task_id='{task_id}', stage='{stage}', round_id='{round_id}'"
)
def assert_interview_plan_outline_ready(self, task_id: str) -> None:
"""Require a persisted, non-empty interview outline before drafting a plan."""
outline = self._persistence.get_interview_plan_outline(task_id)
if not outline or not outline.get("bullets"):
raise PersistenceInvariantViolation(
f"Cannot enter DRAFT_PLAN for task_id='{task_id}': interview plan outline is missing."
)
artifact_path = self._resolve_plan_outline_path(outline["artifact_path"])
if not artifact_path.is_file() or not artifact_path.read_text(encoding="utf-8").strip():
raise PersistenceInvariantViolation(
f"Cannot enter DRAFT_PLAN for task_id='{task_id}': interview plan outline artifact is missing or empty."
)
def update_interview_plan_outline(
self, task_id: str, question_id: str, answer: str, actor: str = "interviewer"
) -> Dict[str, Any]:
"""Update the canonical outline and project its Markdown review artifact."""
task = self.get_task(task_id)
if not task:
raise ValueError(f"Task not found: {task_id}")
if self._read_current_state_for_update(task_id) != STATE_INTERVIEW:
raise PersistenceInvariantViolation(
f"Interview outline updates require current state INTERVIEW for task_id='{task_id}'."
)
if not answer or not answer.strip():
raise ValueError("Interview outline answers must be non-empty.")
outline = self._persistence.get_interview_plan_outline(task_id)
bullets = list(outline.get("bullets", [])) if outline else []
bullet_types = {
"interview_classification": "decision",
"interview_summary": "desired_user_outcome",
"interview_scope": "scope_boundary",
"interview_verification": "success_evidence",
"interview_acceptance_criteria": "constraint_or_authority",
"interview_planning_model_effort": "constraint_or_authority",
"interview_trivial_evidence": "success_evidence",
}
bullet = {
"question_id": question_id,
"bullet_type": bullet_types.get(question_id, "open_question"),
"text": answer.strip(),
"actor": actor,
}
for index, existing in enumerate(bullets):
if existing.get("question_id") == question_id:
bullets[index] = bullet
break
else:
bullets.append(bullet)
artifact_rel = f"docs/plans/work-tasks/{task_id}/{task_id}-plan-outline.md"
revision = self._persistence.upsert_interview_plan_outline(task_id, bullets, artifact_rel)
artifact_path = self._resolve_plan_outline_path(artifact_rel)
artifact_path.parent.mkdir(parents=True, exist_ok=True)
lines = [
f"# Plan Outline — {task.get('title', task_id)}", "", f"Task: `{task_id}`",
f"Revision: {revision}", "",
"These bullets are the interview input to the initial draft plan. They are not implementation approval.", "",
]
lines.extend(
f"- **{item['bullet_type']}** (`{item['question_id']}`): {item['text']}"
for item in bullets
)
temporary = artifact_path.with_name(f".{artifact_path.name}.{os.getpid()}.tmp")
try:
temporary.write_text("\n".join(lines) + "\n", encoding="utf-8")
os.replace(temporary, artifact_path)
finally:
if temporary.exists():
temporary.unlink()
return {"revision": revision, "artifact_path": artifact_rel, "bullets": bullets}
def record_interview_answer(
self,
task_id: str,
source_occupancy_transition_id: int,
from_state: str,
to_state: str,
question_id: str,
answer: str,
actor: str = "interviewer",
) -> Dict[str, Any]:
"""Persist one interview answer and outline revision in one SQLite transaction."""
task = self.get_task(task_id)
if not task:
raise ValueError(f"Task not found: {task_id}")
if from_state != STATE_INTERVIEW or self._read_current_state_for_update(task_id) != from_state:
raise PersistenceInvariantViolation(
f"Interview answer updates require current state INTERVIEW for task_id='{task_id}'."
)
if not answer or not answer.strip():
raise ValueError("Interview answers must be non-empty.")
outline = self._persistence.get_interview_plan_outline(task_id)
bullets = list(outline.get("bullets", [])) if outline else []
bullet_types = {
"interview_classification": "decision",
"interview_summary": "desired_user_outcome",
"interview_scope": "scope_boundary",
"interview_verification": "success_evidence",
"interview_acceptance_criteria": "constraint_or_authority",
"interview_planning_model_effort": "constraint_or_authority",
}
bullets.append({
"question_id": question_id,
"bullet_type": bullet_types.get(question_id, "open_question"),
"text": answer.strip(),
"actor": actor,
})
artifact_rel = f"docs/plans/work-tasks/{task_id}/{task_id}-plan-outline.md"
decision = TransitionDecision(
task_id=task_id,
source_occupancy_transition_id=source_occupancy_transition_id,
from_state=from_state,
to_state=to_state,
question_id=question_id,
answer=answer.strip(),
decision_type="ANSWER",
actor=actor,
recorded_at=self._clock.current_time(),
)
persisted = self._persistence.record_interview_answer(decision, bullets, artifact_rel)
artifact_path = self._resolve_plan_outline_path(artifact_rel)
artifact_path.parent.mkdir(parents=True, exist_ok=True)
lines = [
f"# Plan Outline — {task.get('title', task_id)}", "", f"Task: `{task_id}`",
f"Revision: {persisted.outline_revision}", "",
"These bullets are the interview input to the initial draft plan. They are not implementation approval.", "",
]
lines.extend(
f"- **{item['bullet_type']}** (`{item['question_id']}`): {item['text']}"
for item in bullets
)
temporary = artifact_path.with_name(f".{artifact_path.name}.{os.getpid()}.tmp")
try:
temporary.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
os.replace(temporary, artifact_path)
finally:
if temporary.exists():
temporary.unlink()
return {
"decision_id": persisted.decision_id,
"outline_revision": persisted.outline_revision,
"artifact_path": artifact_rel,
"bullets": bullets,
}
def get_last_transition(self, task_id: str):
"""Public facade for reading a task's most recent transition record -- delegates
to the persistence port rather than requiring callers to reach into
cp._persistence directly (test_wrappers_prohibit_raw_sql_and_private_persistence_attributes
forbids exactly that pattern outside this class)."""
return self._persistence.get_last_transition(task_id)
def get_unconsumed_transition_answers(self, task_id: str, from_state: str, to_state: str) -> Dict[str, str]:
"""Public facade for reading recorded-but-not-yet-consumed interview answers for
one transition edge -- delegates to the persistence port rather than requiring
callers (e.g. record_interview_question.py) to reach into cp._persistence directly
(test_wrappers_prohibit_raw_sql_and_private_persistence_attributes forbids exactly
that pattern outside this class)."""
return self._persistence.get_unconsumed_transition_answers(task_id, from_state, to_state)
def _resolve_plan_outline_path(self, artifact_rel: str) -> Path:
"""Resolve a plan-outline path inside the active repository root."""
repo_root = getattr(self, "repo_root", None)
if repo_root is None and self.db_path is not None and self.db_path.parent.name == "context":
repo_root = self.db_path.parent.parent
root = Path(repo_root or Path.cwd()).resolve()
path = (root / artifact_rel).resolve()
path.relative_to(root)
return path
def create_delegation_plan(self, task_id: str, contract: Dict[str, Any]) -> int:
"""Create a persisted delegation boundary; native execution strategy remains model-owned."""
if not self.get_task(task_id):
raise _policy.DelegationContractError(f"Task not found: {task_id}")
_policy.validate_delegation_contract(contract)
contract = dict(contract)
contract["status"] = "PENDING_APPROVAL" if _policy.delegation_requires_approval(contract) else STATE_APPROVED
return self._persistence.create_delegation_plan(task_id, contract)
def get_delegation_plan(self, contract_id: int) -> Optional[Dict[str, Any]]:
"""Retrieve one persisted delegation contract."""
return self._persistence.get_delegation_plan(contract_id)
def approve_delegation_plan(self, contract_id: int, actor: str) -> None:
"""Approve a high-cost or write-capable delegation through the human gate."""
if actor != "human":
raise _policy.DelegationContractError("Delegation approval requires actor='human'")
self._persistence.approve_delegation_plan(contract_id, actor)
def record_delegation_receipt(
self,
contract_id: int,
backend: str,
model_id: str,
cost_tier: str,
capability_class: str,
backend_available: bool = True,
write_capable: bool = False,
written_paths: Optional[List[str]] = None,
) -> int:
"""Record one bounded execution attempt after contract and approval checks."""
contract = self.get_delegation_plan(contract_id)
if not contract:
raise _policy.DelegationContractError(f"Delegation contract not found: {contract_id}")
if contract["status"] not in {STATE_APPROVED, "EXECUTING"}:
raise _policy.DelegationContractError("Delegation requires human approval before execution")
receipt = {
"task_id": contract["task_id"], "backend": backend, "model_id": model_id,
"cost_tier": cost_tier, "capability_class": capability_class,
"backend_available": backend_available, "write_capable": write_capable,
"written_paths": written_paths or [],
}
try:
_policy.validate_delegation_receipt(
contract, receipt, self._persistence.count_delegation_receipts(contract_id)
)
except _policy.DelegationContractError as exc:
if "renewed approval" in str(exc):
self._persistence.insert_delegation_receipt(contract_id, receipt)
self._persistence.mark_delegation_status(contract_id, "PENDING_APPROVAL")
raise
self._persistence.mark_delegation_status(contract_id, "EXECUTING")
return self._persistence.insert_delegation_receipt(contract_id, receipt)
def record_delegation_verifier_receipt(self, contract_id: int, command: str, exit_code: int) -> None:
"""Record the declared verifier result for a delegation."""
contract = self.get_delegation_plan(contract_id)
if not contract:
raise _policy.DelegationContractError(f"Delegation contract not found: {contract_id}")
if command != contract["verifier"].get("command"):
raise _policy.DelegationContractError("Verifier command does not match the approved contract")
self._persistence.insert_delegation_verifier_receipt(contract_id, command, exit_code)
def accept_delegation_result(self, contract_id: int) -> Dict[str, Any]:
"""Accept a result only after an execution receipt and passing verifier receipt exist."""
contract = self.get_delegation_plan(contract_id)
if not contract:
raise _policy.DelegationContractError(f"Delegation contract not found: {contract_id}")
if self._persistence.count_delegation_receipts(contract_id) == 0:
raise _policy.DelegationContractError("Delegation result requires an execution receipt")
if not self._persistence.has_delegation_verifier_receipt(contract_id):
raise _policy.DelegationContractError("Delegation result requires a passing verifier receipt")
self._persistence.mark_delegation_status(contract_id, "ACCEPTED")
contract["status"] = "ACCEPTED"
return contract
def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
"""Retrieves a task dictionary by task_id."""
return self._persistence.get_task(task_id)
def get_transition_guidance(
self, task_id: str, requested_to_state: Optional[str] = None
) -> Dict[str, Any]:
"""Return advisory guidance derived from the task's persisted state.
This is intentionally read-only. The returned command is never an
authorization token and cannot bypass policy, human decisions, or SQLite
transition triggers.
"""
task = self.get_task(task_id)
if not task:
raise ValueError(f"Task not found: {task_id}")
current_state = self._read_current_state_for_update(task_id)
if current_state is None:
raise ValueError(f"Task not found: {task_id}")
if not hasattr(self, "_transition_registry"):
self._transition_registry = TransitionRegistry.load_default()
guidance = self._transition_registry.get_transition_guidance(current_state, requested_to_state)
if requested_to_state and guidance.get("legal"):
guidance["readiness"] = self._edge_readiness(task_id, current_state, requested_to_state, guidance)
return guidance
def _edge_readiness(self, task_id: str, from_state: str, to_state: str, guidance: Dict[str, Any]) -> Dict[str, Any]:
"""U1: separate DATA readiness (artifacts/checks the edge names; verified by the coordinator at
transition time) from EXECUTION readiness (no human-actor question is still without an
unconsumed human decision). Read-only; it never authorizes a transition."""
template = self._transition_registry.get_template(from_state, to_state)
pending: List[str] = []
if hasattr(self._persistence, "pending_human_questions"):
pending = self._persistence.pending_human_questions(task_id, from_state, to_state)
return {
"data_readiness": {
"required_artifacts": list(template.required_artifacts),
"deterministic_checks": list(template.deterministic_checks),
"note": "Artifacts and checks are verified by the coordinator when the transition is attempted; this only lists them.",
},
"execution_readiness": {
"ready": not pending,
"pending_human_question_ids": pending,
"note": "Human-actor questions are answered by the human through --interactive. This readiness view does not authorize any transition.",
},
}
def _reconcile_main_into_worktree(self, repo_root: Path, worktree_path: Path) -> Dict[str, List[str]]:
"""Force-copies dirty (modified/untracked) files from the source checkout into the
registered worktree so pre-worktree edits are never silently left behind (github
issue #609: an agent's self-report that this happened is not evidence it happened).
Never overwrites a worktree file that has independently diverged from the same
committed base in a different way — those are reported as conflicts and left
untouched on both sides for a human to resolve."""
import subprocess
repo_root = Path(repo_root).resolve()
worktree_path = Path(worktree_path).resolve()
result = subprocess.run(
["git", "-C", str(repo_root), "status", "--porcelain=v1", "--untracked-files=all"],
capture_output=True, text=True, check=False,
)
reconciled: List[str] = []
conflicts: List[str] = []
deleted_on_main: List[str] = []
if result.returncode != 0:
# repo_root is not a real git repository (e.g. a bare tmp_path test
# fixture) -- nothing to reconcile, not a conflict. Matches the
# existing check=False handling in _get_main_dirty_advisory.
return {"reconciled": reconciled, "conflicts": conflicts, "deleted_on_main": deleted_on_main}
for line in result.stdout.splitlines():
if not line.strip():
continue
status, rel_path = line[:2], line[3:].strip()
if " -> " in rel_path:
rel_path = rel_path.split(" -> ", 1)[1]
src = repo_root / rel_path
dst = worktree_path / rel_path
if status.strip().startswith("D") or not src.exists():
deleted_on_main.append(rel_path)
continue
src_bytes = src.read_bytes()
if dst.exists():
dst_bytes = dst.read_bytes()
if dst_bytes == src_bytes:
continue
base_bytes: Optional[bytes] = None
base_result = subprocess.run(
["git", "-C", str(repo_root), "show", f"HEAD:{rel_path}"],
capture_output=True, check=False,
)
if base_result.returncode == 0:
base_bytes = base_result.stdout
if base_bytes is not None and dst_bytes != base_bytes:
conflicts.append(rel_path)
continue
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_bytes(src_bytes)
reconciled.append(rel_path)
return {"reconciled": reconciled, "conflicts": conflicts, "deleted_on_main": deleted_on_main}
def _build_transition_policy_ctx(
self,
task_id: str,
task: Dict[str, Any],
from_state: Optional[str] = None,
to_state: Optional[str] = None,
) -> Dict[str, Any]:
"""Builds the ctx dict consumed by control_plane.policy's transition/to-state rules.
Every fact the policy engine needs comes from self._persistence (PersistencePort) —
this method translates policy needs into port calls, never SQL directly."""
stage_answers = {}
get_answers = getattr(self._persistence, "get_unconsumed_transition_answers", None)
if get_answers and from_state and to_state:
stage_answers = get_answers(task_id, from_state, to_state)
def check_implementation_completeness() -> Optional[str]:
from control_plane.implementation import validate_implementation_ledger
repo_root = getattr(self, "repo_root", None)
if repo_root is None and self.db_path is not None and self.db_path.parent.name == "context":
repo_root = self.db_path.parent.parent
if repo_root is None:
repo_root = Path.cwd()
roots = []
task_worktree = task.get("worktree_path")
if task_worktree:
worktree_root = Path(task_worktree)
if not worktree_root.is_absolute():
worktree_root = Path(repo_root) / worktree_root
roots.append(worktree_root.resolve())
roots.append(Path(repo_root).resolve())
# Plans may exist in both layouts (the coordinator's plan submission stages a copy under work-tasks/ while
# later ledger updates land in the file a caller edits), and docs/plans is untracked, so it usually lives in
# the main checkout while the implementation's artifacts exist only in the task's registered worktree.
# Fail closed: the check passes only if SOME candidate plan carries a valid, fully COMPLETE ledger whose
# artifacts exist in the registered worktree or in the checkout that holds that plan; otherwise the first
# denial reason is returned. Order: documented docs/plans/work-tasks/<task-id>/ (commit a42df236), then flat.
first_denial: Optional[str] = None
for root in roots:
for plan_path in (
root / "docs" / "plans" / "work-tasks" / task_id / f"{task_id}-implementation-plan.md",
root / "docs" / "plans" / f"{task_id}-implementation-plan.md",
):
if not plan_path.exists():
continue
artifact_roots = [root] if roots[0] == root or not task_worktree or not roots[0].is_dir() else [roots[0], root]
for artifact_root in artifact_roots:
denial = validate_implementation_ledger(plan_path, artifact_root)
if denial is None:
return None
first_denial = first_denial or denial
if first_denial is not None:
return first_denial
return (
f"Implementation plan ledger missing for task '{task_id}': "
f"expected docs/plans/work-tasks/{task_id}/{task_id}-implementation-plan.md (or the legacy "
f"docs/plans/{task_id}-implementation-plan.md) with a fenced JSON "
"Implementation Task Ledger; add COMPLETE entries with evidence and existing "
"artifact paths before retrying VERIFY_EXIT -> RETROSPECTIVE."
)
def reconcile_main_into_worktree() -> Dict[str, List[str]]:
repo_root = getattr(self, "repo_root", None)
if repo_root is None and self.db_path is not None and self.db_path.parent.name == "context":
repo_root = self.db_path.parent.parent
if repo_root is None:
repo_root = Path.cwd()
worktree = task.get("worktree_path")
if not worktree:
return {"reconciled": [], "conflicts": [], "deleted_on_main": []}
worktree_root = Path(worktree)
if not worktree_root.is_absolute():
worktree_root = Path(repo_root) / worktree_root
return self._reconcile_main_into_worktree(Path(repo_root), worktree_root)
ctx_repo_root = getattr(self, "repo_root", None)
if ctx_repo_root is None and self.db_path is not None and self.db_path.parent.name == "context":
ctx_repo_root = self.db_path.parent.parent
if ctx_repo_root is None:
ctx_repo_root = Path.cwd()
return {
"task_id": task_id,
"task": task,
"repo_root": str(Path(ctx_repo_root).resolve()),
"reconcile_main_into_worktree": reconcile_main_into_worktree,
"has_receipt": lambda gate_name: self._persistence.has_receipt(task_id, gate_name),
"has_passing_critic_review": lambda: self._persistence.has_passing_critic_review(task_id),
"count_receipts": lambda gate_name, exit_code=None: self._persistence.count_receipts(task_id, gate_name, exit_code),
"count_locked_verifiers": lambda: self._persistence.count_locked_verifiers(task_id),
"count_asymmetric_persistence": lambda details_like=None, destination_like_any=None:
self._persistence.count_asymmetric_persistence(task_id, details_like, destination_like_any),
"has_complete_retrospective": lambda: self._persistence.has_complete_retrospective(task_id),
"verify_sovereignty": lambda: self.verify_sovereignty(task_id),
"stage_answers": stage_answers,
"check_implementation_completeness": check_implementation_completeness,
"get_main_dirty_advisory": self._get_main_dirty_advisory,
}
def transition(self, task_id: str, to_state: str, actor: str, reason: str,
bypass_adjacency: bool = False):
"""INTERNAL USE ONLY: Validates and applies a deterministic state transition according to the canonical DAG.
DEPRECATION NOTICE: This method is strictly internal and functional ONLY for deterministic transitions
that do not require human input or approval. For any transition requiring human questions or approval
(e.g., AWAITING_APPROVAL -> APPROVED, DRAFT_PLAN -> MULTI_AGENT_REVIEW), callers MUST use
TransitionCoordinator.coordinate_transition() to interactively capture and persist signed human decisions.
Any attempt to transition a human-gated edge via this method will be rejected with PersistenceInvariantViolation.
Known-state and adjacency legality are delegated to self._state_machine (a pure domain component,
issue-524 post-round-2-review correction); state retrieval, the guarded write, and
transition-history persistence all go through self._persistence.apply_transition() —
this method itself owns only coordination (calling the state machine, then the policy
engine, then persistence), never validation logic or SQL."""
self._state_machine.validate_known_state(to_state)
task = self.get_task(task_id)
if not task:
raise ValueError(f"Task not found: {task_id}")
block_reason = self.get_guidance_block_reason(task_id)
if block_reason:
raise PersistenceInvariantViolation(
f"BLOCKED: task '{task_id}' is guidance-blocked ({block_reason}). "
"No further transitions are permitted until clear-guidance-block is run "
"with explicit human authorization."
)
# Authoritative state read, immediately before the guarded write — closes the race
# window between the adjacency/policy checks and the write (a concurrent writer
# changing the row after this point is caught by apply_transition()'s guard rather
# than silently overwritten).
current_state = self._read_current_state_for_update(task_id)
if current_state is None:
raise ValueError(f"Task not found: {task_id}")
if to_state == STATE_DONE:
# Check edge legality first so callers receive the domain
# InvalidStateTransition for illegal edges.
self._state_machine.validate_adjacency(task_id, current_state, to_state)
if to_state == STATE_DONE:
raise PersistenceInvariantViolation(
"Closing a task (any transition to DONE) requires the human's OpenSSH signature over a transition_request: "
"run coordinate-transition --to DONE, then show-challenge, ssh-keygen -Y sign and approve-transition."
)
if not bypass_adjacency:
self._state_machine.validate_adjacency(task_id, current_state, to_state)
if current_state == STATE_INTERVIEW and to_state != STATE_INTERVIEW:
self.assert_interview_exit_ready(task_id, stage="interview", round_id=None)
if current_state == STATE_INTERVIEW and to_state == STATE_DRAFT_PLAN:
self.assert_interview_plan_outline_ready(task_id)
# --- Unified gate policy: deterministic checks from authoritative YAML registry ---
if not hasattr(self, "_transition_registry"):
self._transition_registry = TransitionRegistry.load_default()
template = self._transition_registry.get_template(current_state, to_state)
if template:
ctx = self._build_transition_policy_ctx(task_id, task, current_state, to_state)
for check_id in template.deterministic_checks:
try:
_policy.evaluate_check(check_id, ctx)
except _policy.PolicyViolation as e:
raise PersistenceInvariantViolation(str(e)) from e
applied = self._persistence.apply_transition(task_id, current_state, to_state, actor, reason)
if not applied:
self._raise_actionable_rejection(task_id, current_state, to_state)
raise ConcurrentModificationError(
f"Task '{task_id}' state changed concurrently (expected '{current_state}'). Retry."
)
def _raise_actionable_rejection(self, task_id: str, from_state: str, to_state: str) -> None:
"""U2: when the guarded write did not apply and the task is STILL in from_state, the database
trigger rejected it (missing human decisions), not a concurrent writer: name the missing
question ids instead of the misleading 'changed concurrently ... Retry.'"""
if self._persistence.read_current_state(task_id) != from_state or not hasattr(self._persistence, "pending_human_questions"):
return
missing = self._persistence.pending_human_questions(task_id, from_state, to_state)
if missing:
raise PersistenceInvariantViolation(
f"Transition {from_state} -> {to_state} for task '{task_id}' was rejected: no unconsumed human decision exists for "
f"{', '.join(missing)}. The human answers these through: {AGENT_CONTROL_CMD} "
f"coordinate-transition --task-id {task_id} --to {to_state} --interactive (an agent must not record them)."
)
def coordinate_transition(
self,
task_id: str,
to_state: str,
actor: str,
reason: str,
interactive: bool = False,
provided_answers: Optional[Dict[str, str]] = None,
approval_decision: Optional[str] = None,
skip_decision: Optional[Tuple[str, str]] = None,
skip_review: bool = False,
skip_reason: Optional[str] = None,
human_signer: Optional[Callable[..., Any]] = None,
human_confirmed: Optional[str] = None,
) -> TransitionRecord:
"""Public orchestration entry point: coordinates transition via TransitionCoordinator."""
if not hasattr(self, "_transition_registry"):
self._transition_registry = TransitionRegistry.load_default()
coord = TransitionCoordinator(control_plane=self, registry=self._transition_registry, human_signer=human_signer)
return coord.coordinate_transition(
task_id=task_id,
to_state=to_state,
actor=actor,
reason=reason,
interactive=interactive,
provided_answers=provided_answers,
approval_decision=approval_decision,
skip_decision=skip_decision,
skip_review=skip_review,
skip_reason=skip_reason,
human_confirmed=human_confirmed,
)
def commit_authorized_transition(self, commit_request: TransitionCommitRequest) -> TransitionRecord:
"""Internal atomic commit gate: passes normalized TransitionCommitRequest to PersistencePort.
PersistencePort re-validates persistable invariants in SQLite transaction and atomically commits."""
if commit_request.to_state == STATE_DONE:
self._state_machine.validate_adjacency(
commit_request.task_id,
commit_request.expected_from_state,
commit_request.to_state,
)
signed = commit_request.proof is not None and commit_request.proof.kind == "sshsig" # verified inside the commit transaction
if commit_request.to_state == STATE_DONE and not signed:
raise PersistenceInvariantViolation(
"Closing a task requires the human's OpenSSH signature over a transition_request (no typed word, flag or prompt)."
)
force_retrospective = any(
d.question_id == "force_retrospective_authorization"
and d.answer == "FORCE_RETROSPECTIVE"
and d.actor == "human"
for d in commit_request.staged_decisions
)
if (
commit_request.expected_from_state == STATE_INTERVIEW
and commit_request.to_state != STATE_INTERVIEW
and not force_retrospective
):
# This is deliberately immediately before the atomic persistence call so both
# deterministic and coordinated transition front-doors share the same gate.
# Skipped only for an explicit human-authorized FORCE_RETROSPECTIVE emergency
# close, which intentionally bypasses the normal interview-completeness gate.
self.assert_interview_exit_ready(
commit_request.task_id, stage="interview", round_id=None
)
if (
commit_request.expected_from_state == STATE_INTERVIEW
and commit_request.to_state == STATE_DRAFT_PLAN
):
self.assert_interview_plan_outline_ready(commit_request.task_id)
record = self._persistence.apply_transition_with_receipts(commit_request)
if record.from_state == STATE_APPROVED and record.to_state == STATE_IN_WORKTREE:
self._kickoff_implementation(record)
return record
def _kickoff_implementation(self, record: TransitionRecord) -> None:
"""Persist and dispatch the implementation kickoff exactly once.
The receipt is written before invoking the external controller, making
retries/replays idempotent. A controller failure is intentionally
propagated so callers can observe and recover it; the durable receipt
prevents an accidental duplicate dispatch.
"""
gate_name = "implementation_kickoff"
if self._persistence.has_receipt(record.task_id, gate_name):
return
self.record_verification_receipt(
record.task_id,
gate_name=gate_name,
command_executed=f"implementation-kickoff:owner={record.actor}",
exit_code=0,
)
if self._implementation_controller is not None:
self._implementation_controller(record.task_id, record)
def lock_verifiers(self, task_id: str, file_paths: List[Path]):
"""Calculates and locks baseline SHA256 hashes of verifier files. File-existence
checks are against arbitrary caller-supplied paths (not repo-owned files), so they
use pathlib directly rather than FilesystemPort — that port's contract covers
repo-relative side-effect writes (e.g. map-debt.md), a different concern."""
for fp in file_paths:
p = Path(fp).resolve()
if not p.exists():
raise FileNotFoundError(f"Verifier file to lock does not exist: {p}")
file_sha = self._crypto.sha256_file(p)
self._persistence.insert_locked_verifier(task_id, str(p), file_sha)
def verify_sovereignty(self, task_id: str) -> bool:
"""Verifies that locked baseline verifiers have not been modified."""
rows = self._persistence.get_locked_verifiers(task_id)
for r in rows:
p = Path(r["file_path"])
if not p.exists():
raise VerifierSovereigntyViolation(f"Verifier file missing: {p}")
curr_sha = self._crypto.sha256_file(p)
if curr_sha != r["expected_sha256"]:
raise VerifierSovereigntyViolation(
f"Verifier sovereignty violated! {p} has been mutated. Expected {r['expected_sha256']}, got {curr_sha}"
)
return True
def record_critic_review(self, task_id: str, iteration: int, model: str, verdict: str, findings: str):
"""Records a clean-context peer critic review iteration and verdict."""
if verdict == "REQUEST_CHANGES":
verdict = "REVISE"
if verdict not in ("PASS", "REVISE", "REJECT"):
raise ValueError(f"Invalid verdict: {verdict}")
self._assert_review_selection_recorded(task_id)
self._persistence.insert_critic_review(task_id, iteration, model, verdict, findings)
def _assert_review_selection_recorded(self, task_id: str) -> None:
"""review-selection-v1 (T17): an internal review's runtime/model/effort must be recorded as the
human's decisions before any reviewer outcome. No effect when the method was not internal."""
from control_plane.registry import TransitionRegistry
from control_plane.review_selection import review_edge_into
state = self._persistence.read_current_state(task_id)
edge = review_edge_into(state) if state else None
if edge is None or not hasattr(self._persistence, "review_selection_gaps"):
return
gaps = self._persistence.review_selection_gaps(TransitionRegistry.load_default(), task_id, edge[0], edge[1])
if gaps:
raise ValueError(
"Reviewer outcome refused: the internal review selection is not recorded as the human's decision "
f"(missing: {', '.join(gaps)}). Re-run the review edge interactively so the human chooses runtime, model and effort."
)
def record_verification_receipt(self, task_id: str, gate_name: str, command_executed: str, exit_code: int,
actor: Optional[str] = None, provenance: str = "api") -> str:
"""Records a deterministic exit receipt and returns an immutable receipt token. The actor and
provenance are stored on the receipt and in the append-only receipt_audit trail (T15)."""
raw = f"{task_id}:{gate_name}:{command_executed}:{exit_code}:{self._clock.current_time()}"
h = self._crypto.sha256_hex(raw)[:12]
token = f"EVO-INTEGRITY-{task_id}-{h}"
if actor is None and provenance == "api":
self._persistence.insert_verification_receipt(task_id, gate_name, command_executed, exit_code, token)
else:
self._persistence.insert_verification_receipt(
task_id, gate_name, command_executed, exit_code, token, actor=actor, provenance=provenance
)
return token
def save_retrospective(self, task_id: str, entry: Dict[str, Any], follow_ups: List[Dict[str, Any]]) -> None:
"""Creates or replaces the task's single retrospective record."""
if entry.get("decision") not in ("opt_in", "skip"):
raise ValueError("Retrospective decision must be 'opt_in' or 'skip'.")
if entry.get("completion_mode") not in ("draft", "completed", "skipped"):
raise ValueError("Retrospective completion_mode must be draft, completed, or skipped.")
if entry.get("actor") not in ("agent", "human"):
raise ValueError("Retrospective actor must be agent or human.")
self._persistence.save_retrospective(task_id, entry, follow_ups)
def record_plan_mode_entry(self, task_id: str, actor: str) -> str:
"""Records proof that native Plan Mode was entered, satisfying the DRAFT_PLAN gate."""
return self.record_verification_receipt(
task_id, gate_name="plan_mode_entry", command_executed=f"plan-mode-entered:{actor}", exit_code=0
)
def record_socratic_intake_complete(self, task_id: str, summary: str) -> str:
"""Records proof that Socratic Defaulting intake completed, satisfying the DRAFT_PLAN gate."""
return self.record_verification_receipt(
task_id, gate_name="socratic_intake_complete", command_executed=f"socratic-intake:{summary}", exit_code=0
)
def record_human_approval(self, task_id: str, approver: str) -> str:
"""Records the human approval receipt required for APPROVED -> IN_WORKTREE (never skippable)."""
return self.record_verification_receipt(
task_id, gate_name="human_approval", command_executed=f"approved-by:{approver}", exit_code=0
)
def record_recovery_approval(
self,
task_id: str,
destination_state: str,
approver: str,
actor: str,
reason: str = "",
decision: str = "APPROVAL",
expected_source_state: Optional[str] = None,
source_occupancy_transition_id: Optional[int] = None,
) -> str:
"""Public facade for an explicit human-approved recovery re-entry across a
non-DAG edge -- delegates to the persistence port rather than requiring
callers to reach into cp._persistence directly (test_wrappers_prohibit_raw_sql_and_private_persistence_attributes
forbids exactly that pattern in production code). expected_source_state and
source_occupancy_transition_id auto-derive from the task's current record when
not explicitly supplied -- the common case (a caller who just wants "approve
recovery from wherever this task currently is") shouldn't have to look those up
itself; explicit overrides remain available for callers (e.g. the CLI) that
already have them on hand and want the stricter occupancy-staleness check.
actor has no default (2026-09-18 review finding): this facade's callers must state
who they actually are, not inherit a convenient 'human' default that a non-human
caller could silently ride on. It is recorded verbatim into the decision row, and
the persistence layer independently refuses destination_state values in
RECOVERY_FORBIDDEN_DESTINATIONS (VERIFY_EXIT, APPROVED) regardless of what actor
claims, since those states require real human authorization on their normal inbound
edges that this recovery path must never bypass -- see adapters.py's
RECOVERY_FORBIDDEN_DESTINATIONS."""
if expected_source_state is None or source_occupancy_transition_id is None:
task = self.get_task(task_id)
if not task:
raise ValueError(f"Task not found: {task_id}")
if expected_source_state is None:
expected_source_state = task["state"]
if source_occupancy_transition_id is None:
last_transition = self._persistence.get_last_transition(task_id)
source_occupancy_transition_id = last_transition.transition_id if last_transition else 0
return self._persistence.record_recovery_approval(
task_id=task_id,
expected_source_state=expected_source_state,
destination_state=destination_state,
source_occupancy_transition_id=source_occupancy_transition_id,
approver=approver,
decision=decision,
reason=reason,
actor=actor,
)
def apply_recovery_transition(
self, task_id: str, destination_state: str, token: str, actor: str, reason: str
) -> TransitionRecord:
"""Applies a transition to destination_state after a matching record_recovery_approval
token has been issued. The token itself carries no separate lookup state (the
underlying APPROVAL decision rows are bound to task_id + occupancy + states, not
the token) -- token is required non-empty here as a defense against a caller
skipping record_recovery_approval and calling this directly, which would still
fail at the SQLite trigger since no matching APPROVAL decision would exist.
DONE is not a recovery target: every edge into DONE is a cryptographic gate (a human-signed
transition_request), and the recovery path carries no signature, so record_recovery_approval refuses DONE
destinations outright instead of routing around the closure gate.
Recovery edges are, by definition, outside the normal ALLOWED_TRANSITIONS DAG
(e.g. DONE -> IN_WORKTREE to reopen a closed task for bounded rework) -- that is
exactly the scenario record_recovery_approval/apply_recovery_transition exist to
support. self.transition()'s Python-level validate_adjacency() has no concept of
this override (unlike the SQLite enforce_valid_transition trigger, which already
accepts a matching unconsumed APPROVAL decision), so it must be bypassed here; the
already-required non-empty recovery token plus the trigger's own recovery_td check
remain the actual authorization gate."""
if not token or not token.strip():
raise ValueError("apply_recovery_transition requires a non-empty token from record_recovery_approval.")
if destination_state == STATE_DONE:
raise PersistenceInvariantViolation(
"A recovery approval cannot close a task: closure takes the human's OpenSSH signature (coordinate-transition --to DONE)."
)
self.transition(task_id, destination_state, actor, reason, bypass_adjacency=True)
return self._persistence.get_last_transition(task_id)
def record_review_skip(self, task_id: str, phase: str, actor: str, reason: str, provenance: str = "api") -> str:
"""Records an explicit, auditable decision to skip a user-discretionary review phase
(e.g. multi_agent_review, multi_agent_code_review) — makes the skip visible, never silent.
The CLI path is human-only (receipt_provenance.record_human_skip); this API records provenance 'api'."""
return self.record_verification_receipt(
task_id, gate_name=f"{phase}_skipped", command_executed=f"user-skip:{actor}:{reason}", exit_code=0,
actor=actor, provenance=provenance,
)
def _read_current_state_for_update(self, task_id: str) -> Optional[str]:
"""Reads the task's current state immediately before the guarded write — the value
used as the WHERE predicate closing the race window. Delegates to self._persistence;
kept as a named method (rather than inlined) because transition() and its regression
test (test_transition_race_condition_guarded_by_state_predicate) rely on being able to
substitute a stale read here to simulate a concurrent writer."""
return self._persistence.read_current_state(task_id)
def get_verification_receipts(self, task_id: str) -> List[Dict[str, Any]]:
"""Retrieves all verification receipts stamped for a given task."""
return self._persistence.get_verification_receipts(task_id)
def update_worktree(self, task_id: str, worktree_path: str, worktree_branch: str, worktree_state: str):
"""Updates worktree path, branch, and status using the strict 6-state vocabulary."""
if worktree_state not in WORKTREE_STATES:
raise ValueError(f"Invalid worktree state '{worktree_state}'. Must be one of {WORKTREE_STATES}")
# Unified gate policy: worktree_push is a controlled operation, not a lifecycle
# transition — evaluated via the same policy engine as transition() (issue-524 Step 4).
if worktree_state == "pushed_to_origin":
task_state = self._persistence.read_current_state(task_id)
if task_state is None:
raise ValueError(f"Task not found: {task_id}")
op_ctx = {"task_id": task_id, "task_state": task_state}
try:
_policy.evaluate_operation(op_ctx, "worktree_push")
except _policy.PolicyViolation as e:
raise PersistenceInvariantViolation(str(e)) from e
self._persistence.update_worktree_fields(task_id, worktree_path, worktree_branch, worktree_state)
def verify_commit(self, branch: str, staged_files: Optional[List[str]] = None) -> Dict[str, Any]:
"""Verifies whether git commit is authorized on `branch` given `staged_files`.
Returns:
Dict containing {"status": "ALLOWED"|"BLOCKED", "task_id": ..., "state": ..., "message": ...}
Raises:
PersistenceInvariantViolation if blocked and callers don't catch.
"""
# If main/master or untracked branch, allow
if branch in ("main", "master", ""):
return {"status": "ALLOWED", "branch": branch, "message": "Non-task branch bypass"}
task = self._persistence.get_task_by_worktree_branch(branch)
if task is None:
return {"status": "ALLOWED", "branch": branch, "task_id": None, "message": "Untracked branch (ungated)"}
task_id = task["task_id"]
task_state = task["state"]
# F-05 fix (external review, 2026-09-14): this Python-level check previously had no
# parity with the shell pre-commit-pipeline-guard's guidance_block_reason check --
# callers going through this API instead of the shell hook would incorrectly see
# ALLOWED for a guidance-blocked task.
block_reason = self.get_guidance_block_reason(task_id)
if block_reason:
raise PersistenceInvariantViolation(
f"BLOCKED: task '{task_id}' is guidance-blocked ({block_reason}). "
"No commit is permitted until clear-guidance-block is run with explicit human authorization."
)
op_ctx = {
"task_id": task_id,
"task_state": task_state,
"staged_files": staged_files or [],
"validate_transition_history": lambda: self._persistence.validate_task_pipeline_history(task_id, task_state),
}
try:
_policy.evaluate_operation(op_ctx, "commit")
except _policy.PolicyViolation as e:
raise PersistenceInvariantViolation(str(e)) from e
return {
"status": "ALLOWED",
"task_id": task_id,
"state": task_state,
"branch": branch,
"message": "Commit authorized"
}
def log_asymmetric_persistence(self, task_id: str, destination: str, status: str, details: str):
"""Logs asymmetric Layer 2 persistence entries into the SQLite audit table."""
self._persistence.insert_asymmetric_persistence(task_id, destination, status, details)
def get_latest_asymmetric_persistence(
self, task_id: str, destination: Optional[str] = None
) -> Optional[Dict[str, Any]]:
"""Retrieves the latest asymmetric persistence record for task_id and optional destination."""
return self._persistence.get_latest_asymmetric_persistence(task_id, destination)
def get_guidance_block_reason(self, task_id: str) -> Optional[str]:
"""Returns the task's guidance_block_reason (None if not blocked)."""
return self._persistence.get_guidance_block_reason(task_id)
def set_guidance_block(self, task_id: str, reason: str) -> None:
"""Blocks all further transitions for task_id until clear_guidance_block() is
explicitly called. Triggered when a human answers 'no' (or gives no answer) to
the mandatory per-transition guidance-compliance confirmation."""
self._persistence.set_guidance_block(task_id, reason)
def clear_guidance_block(self, task_id: str, reason: str = "") -> None:
"""Clears a guidance block -- always requires the caller to have gone through the
blanket --human-confirmed gate (enforced at the CLI dispatch layer, not here).
Bug fix (found by external review, 2026-09-14): `reason` was previously accepted
by the CLI, printed back as if recorded, then silently discarded -- never actually
persisted anywhere. Now logged to asymmetric_persistence_log, the same durable
audit trail already used for other Layer-2 persistence facts."""
self._persistence.clear_guidance_block(task_id)
if reason:
self.log_asymmetric_persistence(
task_id=task_id,
destination="guidance_block_reason",
status="RESOLVED",
details=f"Guidance block cleared. Reason: {reason}",
)
def verify_phase_capability(self, task_id: str, action_identity: str) -> PhaseCapability:
"""Verifies that an action capability is authorized for the task's current phase occupancy.
Algorithm:
1. read task current state;
2. read the latest transition whose to_state equals that current state;
3. verify that transition is the current source-occupancy row (most recent transition for task);
4. resolve its exact (from_state, to_state) template;
5. authorize only capabilities_released by that exact template;
6. fail closed if task state, transition history, or registry entry disagree.
"""
if not hasattr(self, "_transition_registry"):
self._transition_registry = TransitionRegistry.load_default()
# Fail-closed check: action identity must be known/registered in registry
releasing_edges = self._transition_registry.get_edges_releasing_capability(action_identity)
if not releasing_edges:
raise PhaseCapabilityDenied(f"Unregistered action identity: '{action_identity}'")
# Step 1: read task current state
current_state = self._persistence.read_current_state(task_id)
if current_state is None:
raise PhaseCapabilityDenied(f"Task '{task_id}' not found in control plane.")
# Step 2: read the latest transition whose to_state equals that current state
occupancy_trans = self._persistence.get_last_transition(task_id, to_state=current_state)
if not occupancy_trans:
raise PhaseCapabilityDenied(
f"No transition found leading into current state '{current_state}' for task '{task_id}'."
)
# Step 3: verify that transition is the current source-occupancy row (latest overall transition)
latest_trans = self._persistence.get_last_transition(task_id)
if not latest_trans or latest_trans.transition_id != occupancy_trans.transition_id:
raise PhaseCapabilityDenied(
f"State tamper detected: latest transition id '{getattr(latest_trans, 'transition_id', None)}' "
f"does not match current occupancy transition id '{occupancy_trans.transition_id}'."
)
# Step 4: resolve its exact (from_state, to_state) template
template = self._transition_registry.get_template(occupancy_trans.from_state, occupancy_trans.to_state)
if not template:
if occupancy_trans.from_state == "NONE":
raise PhaseCapabilityDenied(
"Task has not entered any registered phase yet — no capabilities available."
)
raise PhaseCapabilityDenied(
f"No registry template found for inbound edge "
f"({occupancy_trans.from_state} -> {occupancy_trans.to_state})."
)
# Step 5: authorize only capabilities_released by that exact template
if action_identity not in template.capabilities_released:
raise PhaseCapabilityDenied(
f"Action '{action_identity}' not authorized in state '{current_state}' "
f"(entered via {occupancy_trans.from_state} -> {occupancy_trans.to_state}). "
f"Released capabilities: {template.capabilities_released}."
)
return PhaseCapability(
task_id=task_id,
action_identity=action_identity,
current_state=current_state,
releasing_edge=(occupancy_trans.from_state, occupancy_trans.to_state),
transition_id=occupancy_trans.transition_id,
authorized_actor=template.authorized_actor,
)
def record_decision(
self,
task_id: str,
source_occupancy_transition_id: int,
from_state: str,
to_state: str,
question_id: str,
answer: str,
decision_type: str = "ANSWER",
actor: str = "interviewer",
) -> int:
"""Records an occupancy-bound decision via PersistencePort."""
decision = TransitionDecision(
task_id=task_id,
source_occupancy_transition_id=source_occupancy_transition_id,
from_state=from_state,
to_state=to_state,
question_id=question_id,
answer=answer,
decision_type=decision_type,
actor=actor,
recorded_at=self._clock.current_time(),
)
return self._persistence.record_decision(decision)
def _build_parser() -> argparse.ArgumentParser:
"""Constructs and returns CLI argument parser."""
parser = argparse.ArgumentParser(description="SQLite Control Plane CLI for Agent Lifecycle")
parser.add_argument("--db-path", default=None, help="Explicit path to control_plane.db (default: context/control_plane.db)")
sub = parser.add_subparsers(dest="subcommand")
p_init = sub.add_parser("init")
p_init.add_argument("--task-id", required=True)
p_init.add_argument("--title", required=True)
p_init.add_argument("--runtime", default="cli")
p_init.add_argument("--spec-path", default=None)
p_init.add_argument("--model-tier", choices=["low", "medium", "high"], default=None)
p_init.add_argument("--model-id", default=None)
p_init.add_argument("--task-type", choices=["GENERAL", "EVOLUTION"], default="GENERAL")
p_rec = sub.add_parser("recommend-model")
p_rec.add_argument("--runtime", required=True)
p_rec.add_argument("--tier", choices=["low", "medium", "high"], default="low")
# Primary transition command: coordinate-transition
p_ct = sub.add_parser("coordinate-transition")
p_ct.add_argument("--task-id", required=True)
p_ct.add_argument("--to", required=True)
p_ct.add_argument("--actor", default="controller")
p_ct.add_argument("--reason", default="State transition")
p_ct.add_argument("--interactive", action="store_true", default=False)
p_ct.add_argument("--answers", default=None, help="JSON dict of question answers")
p_ct.add_argument("--approval", choices=["APPROVAL", "REJECTION"], default=None)
p_ct.add_argument(
"--human-confirmed", required=False, default=None,
help=(
"Required for every transition EXCEPT those into APPROVED, VERIFY_EXIT and DONE, which are authorized "
"only by the human's OpenSSH signature and ignore (and do not require) this flag. Otherwise it must be the "
"literal phrase 'HUMAN-CONFIRMED: <quote of what the human actually typed authorizing this transition>'."
),
)
p_ct.add_argument("--key", default="~/.ssh/agentic-os_signing", help="Your private signing key (proof edges, interactive terminal)")
# Compatibility alias: transition routes directly through TransitionCoordinator
p_tr = sub.add_parser("transition")
p_tr.add_argument("--task-id", required=True)
p_tr.add_argument("--to", required=True)
p_tr.add_argument("--actor", default="controller")
p_tr.add_argument("--reason", default="State transition")
p_tr.add_argument("--interactive", action="store_true", default=False)
p_tr.add_argument("--answers", default=None, help="JSON dict of question answers")
p_tr.add_argument("--approval", choices=["APPROVAL", "REJECTION"], default=None)
p_tr.add_argument(
"--human-confirmed", required=False, default=None,
help=(
"Required for every transition EXCEPT those into APPROVED, VERIFY_EXIT and DONE, which are authorized "
"only by the human's OpenSSH signature and ignore (and do not require) this flag. Otherwise it must be the "
"literal phrase 'HUMAN-CONFIRMED: <quote of what the human actually typed authorizing this transition>'."
),
)
p_tr.add_argument("--key", default="~/.ssh/agentic-os_signing", help="Your private signing key (proof edges, interactive terminal)")
p_lock = sub.add_parser("lock-verifiers")
p_lock.add_argument("--task-id", required=True)
p_lock.add_argument("--paths", required=True, help="Comma-separated file paths")
p_vsov = sub.add_parser("verify-sovereignty")
p_vsov.add_argument("--task-id", required=True)
p_rc = sub.add_parser("record-receipt")
p_rc.add_argument("--task-id", required=True)
p_rc.add_argument("--gate", required=True)
p_rc.add_argument("--cmd", required=True)
p_rc.add_argument("--exit-code", type=int, required=True)
p_wt = sub.add_parser("update-worktree")
p_wt.add_argument("--task-id", required=True)
p_wt.add_argument("--path", required=True)
p_wt.add_argument("--branch", required=True)
p_wt.add_argument("--state", required=True)
p_st = sub.add_parser("status")
p_st.add_argument("--task-id", required=True)
p_tg = sub.add_parser("transition-guidance")
p_tg.add_argument("--task-id", required=True)
p_tg.add_argument("--to", default=None, help="Optional requested destination state")
p_lap = sub.add_parser("log-prior-art")
p_lap.add_argument("--task-id", required=True)
p_lap.add_argument("--summary", required=True, help="Summary of prior art scan findings")
p_lap.add_argument("--repeat-yes-entries", default="", help="Comma-separated Repeat:YES map-debt entries found")
p_pme = sub.add_parser("record-plan-mode-entry")
p_pme.add_argument("--task-id", required=True)
p_pme.add_argument("--actor", required=True)
p_sic = sub.add_parser("record-socratic-intake")
p_sic.add_argument("--task-id", required=True)
p_sic.add_argument("--summary", required=True)
p_ha = sub.add_parser("record-human-approval")
p_ha.add_argument("--task-id", required=True)
p_ha.add_argument("--approver", required=True)
p_rs = sub.add_parser("record-review-skip")
p_rs.add_argument("--task-id", required=True)
p_rs.add_argument("--phase", required=True, help="e.g. multi_agent_review, multi_agent_code_review")
p_rs.add_argument("--actor", default="human", help="Ignored: a review skip is always recorded as the human's, interactively")
p_rs.add_argument("--reason", required=True)
p_rs.add_argument("--interactive", action="store_true", help="Required: the HUMAN types the confirmation at a terminal")
p_ir = sub.add_parser("invalidate-receipt", help="Human-only: invalidate a receipt (it stops satisfying gates); audited")
p_ir.add_argument("--receipt-id", type=int, required=True)
p_ir.add_argument("--reason", required=True)
p_cr = sub.add_parser("record-critic-review")
p_cr.add_argument("--task-id", required=True)
p_cr.add_argument("--iteration", type=int, required=True)
p_cr.add_argument("--model", required=True)
p_cr.add_argument("--verdict", choices=["PASS", "REVISE", "REJECT", "REQUEST_CHANGES"], required=True)
p_cr.add_argument("--findings", required=True)
# Slice 4: Action wrapper verification & recovery subcommands
p_viq = sub.add_parser("verify-interview-question")
p_viq.add_argument("--task-id", required=True)
p_vpw = sub.add_parser("verify-plan-write")
p_vpw.add_argument("--task-id", required=True)
p_vex = sub.add_parser("verify-exit-verification")
p_vex.add_argument("--task-id", required=True)
p_rra = sub.add_parser("record-recovery-approval")
p_rra.add_argument("--task-id", required=True)
p_rra.add_argument("--from-state", required=True)
p_rra.add_argument("--to-state", required=True)
p_rra.add_argument("--source-occupancy-id", type=int, required=True)
p_rra.add_argument("--approver", required=True)
p_rra.add_argument("--decision", default="APPROVAL")
p_rra.add_argument("--reason", required=True)
p_rra.add_argument("--actor", default="human", help="Who is actually invoking this CLI command (default: human, since this is a human-operated administrative recovery tool).")
p_cgb = sub.add_parser("clear-guidance-block")
p_cgb.add_argument("--task-id", required=True)
p_cgb.add_argument("--reason", required=True, help="Why this block is being cleared")
# Gate 1 human-side verbs (auth-ciba-increment-b T6): no --human-confirmed (the signature is the
# proof) and deliberately no --signature argument (the path is derived from the request row).
p_sc = sub.add_parser("show-challenge", help="Render and display the Gate 1 challenge to sign")
p_sc.add_argument("--request-id", type=int, required=True)
p_sc.add_argument("--key", default="~/.ssh/agentic-os_signing", help="Path of your private signing key (shown in the sign command)")
p_at = sub.add_parser("approve-transition", help="Verify your signature and approve Gate 1")
p_at.add_argument("--request-id", type=int, required=True)
p_at.add_argument("--principal", default=None, help="Enrolled principal (default: discovered from allowed_signers)")
# Interactive signing self-test (auth-ciba-increment-b T12): a human tool; handled in main()
# BEFORE a ControlPlane/DB is constructed, and it never creates a transition_request.
p_ts = sub.add_parser("test-signing-mechanics", help="Interactive self-test of your approval-signing key")
p_ts.add_argument("--key", default="~/.ssh/agentic-os_signing", help="Path of your private signing key")
p_ts.add_argument("--repo-root", default=None, help="Repository root (default: the canonical repo root, shared by worktrees)")
# Read-only helper (auth-ciba-increment-b H1): exact runtime/model ids for the review-selection questions.
sub.add_parser("list-review-options", help="Read-only: list the runtime/model/effort identifiers to type at the review questions")
# Canonical read-only inspection (auth-ciba-increment-b U3): use these, not ad-hoc SQL.
p_id = sub.add_parser("inspect-decisions", help="Read-only: recorded decisions for a task (actor, answer, edge)")
p_id.add_argument("--task-id", required=True)
p_id.add_argument("--from-state", default=None)
p_id.add_argument("--to-state", default=None)
p_id.add_argument("--json", action="store_true", help="Machine-readable JSON output")
p_ic = sub.add_parser("inspect-candidates", help="Read-only: source-assisted answer candidates for a task")
p_ic.add_argument("--task-id", required=True)
p_ic.add_argument("--json", action="store_true", help="Machine-readable JSON output")
p_vc = sub.add_parser("verify-commit")
p_vc.add_argument("--branch", required=True, help="Git branch to verify commit authorization for")
p_vc.add_argument("--staged-files", nargs="*", default=[], help="List of staged files")
# Blanket human-confirmation gate (added 2026-09-13): every state-mutating
# subcommand requires an explicit --human-confirmed flag with no default,
# regardless of whether the underlying YAML edge is coded as
# approval.required=false. Read-only/verification subcommands (status,
# transition-guidance, recommend-model, verify-*) are exempt.
for _mutating_parser in (
p_init, p_lock, p_rc, p_wt, p_lap, p_pme, p_sic, p_ha, p_cr, p_rra, p_cgb,
):
_mutating_parser.add_argument(
"--human-confirmed", required=True,
help=(
"REQUIRED, no default. Must start with the literal marker "
"'HUMAN-CONFIRMED:' followed by a quote of what the human actually typed "
"authorizing THIS SPECIFIC action. Fabricating this string is a policy "
"violation, not a technicality to route around."
),
)
return parser
# record-review-skip is deliberately NOT here: a --human-confirmed string proves nothing about who typed
# it (2026-09-19 incident), so that verb requires --interactive and a real terminal instead (T15).
_HUMAN_CONFIRMED_GATED_COMMANDS = frozenset({
"init", "coordinate-transition", "transition", "lock-verifiers", "record-receipt",
"update-worktree", "log-prior-art", "record-plan-mode-entry", "record-socratic-intake",
"record-human-approval", "record-critic-review",
"record-recovery-approval", "clear-guidance-block",
})
def _require_human_interactive_skip(args: argparse.Namespace) -> None:
"""`record-review-skip` is a human decision (T15): it needs --interactive and a real terminal;
--actor human / --human-confirmed on the command line prove nothing about who typed them."""
if not getattr(args, "interactive", False):
raise SystemExit(
"REFUSED: record-review-skip is a human decision. The human runs it in their own terminal "
"with --interactive and types the confirmation; an agent must not record it on their behalf."
)
# Destinations whose every inbound edge requires an OpenSSH signature (requires_cryptographic_proof in the YAML).
_PROOF_TARGET_STATES = frozenset({"APPROVED", "VERIFY_EXIT", "DONE"})
def _enforce_human_confirmed(args: argparse.Namespace) -> None:
"""Blanket gate (added 2026-09-13): every state-mutating subcommand requires an
explicit --human-confirmed flag, regardless of what the per-edge YAML says about
approval.required. Added live after an agent transitioned INTAKE->INTERVIEW with
zero human authorization -- that edge's approval.required=false made it legal per
the YAML, which is exactly the gap this closes: the YAML's per-edge setting is no
longer sufficient on its own, this check applies uniformly on top of it."""
if args.subcommand in ("coordinate-transition", "transition"):
if getattr(args, "to", None) in _PROOF_TARGET_STATES:
return # cryptographic-proof edges: the signature is the only authority; this flag is ignored
human_confirmed = getattr(args, "human_confirmed", None)
if not human_confirmed or not human_confirmed.strip().startswith("HUMAN-CONFIRMED:"):
raise SystemExit(
f"BLOCKED: --human-confirmed is required for '{args.subcommand}' to {args.to} (it must start with the literal "
"marker 'HUMAN-CONFIRMED:'). Transitions into APPROVED, VERIFY_EXIT and DONE do not take it: they need "
"the human's OpenSSH signature instead."
)
return
if args.subcommand not in _HUMAN_CONFIRMED_GATED_COMMANDS:
return
human_confirmed = getattr(args, "human_confirmed", None)
if not human_confirmed or not human_confirmed.strip().startswith("HUMAN-CONFIRMED:"):
raise SystemExit(
f"BLOCKED: --human-confirmed is required for '{args.subcommand}' (added "
"2026-09-13 after an agent transitioned INTAKE->INTERVIEW without any human "
"authorization at all -- that edge's approval.required=false in the YAML made "
"it legal, which is exactly the gap this closes). It must start with the "
"literal marker 'HUMAN-CONFIRMED:' followed by a quote of what the human "
"actually typed authorizing THIS SPECIFIC action. Fabricating this string is "
"a policy violation, not a technicality to route around."
)
def _dispatch_command(cp: ControlPlane, args: argparse.Namespace):
"""Executes the dispatched CLI command."""
_enforce_human_confirmed(args)
if args.subcommand == "init":
cp.create_task(args.task_id, args.title, args.runtime, args.spec_path, args.model_tier, args.model_id, args.task_type)
print(f"Task {args.task_id} initialized in INTAKE (type={args.task_type}).")
elif args.subcommand == "recommend-model":
print(json.dumps(cp.resolve_recommended_model(args.runtime, args.tier), indent=2))
elif args.subcommand in ("coordinate-transition", "transition"):
answers_dict = json.loads(args.answers) if getattr(args, "answers", None) else None
from control_plane.tty_signer import make_tty_signer, terminal_is_interactive
# In a real terminal with --interactive the human's signing step runs inline (ssh-keygen prompts for the
# passphrase); otherwise a proof edge stops with HUMAN_PROOF_REQUIRED for the human to complete.
signer = make_tty_signer(key=getattr(args, "key", "~/.ssh/agentic-os_signing")) if (getattr(args, "interactive", False) and terminal_is_interactive()) else None
rec = cp.coordinate_transition(
task_id=args.task_id,
to_state=args.to,
actor=args.actor,
reason=args.reason,
interactive=getattr(args, "interactive", False),
provided_answers=answers_dict,
approval_decision=getattr(args, "approval", None),
human_signer=signer,
human_confirmed=getattr(args, "human_confirmed", None),
)
print(f"Transitioned task {args.task_id} to {args.to} (transition_id={rec.transition_id}).")
elif args.subcommand == "record-critic-review":
cp.record_critic_review(args.task_id, args.iteration, args.model, args.verdict, args.findings)
canonical_verdict = "REVISE" if args.verdict == "REQUEST_CHANGES" else args.verdict
print(f"Critic review recorded for task {args.task_id} (verdict={canonical_verdict}).")
elif args.subcommand == "lock-verifiers":
paths = [Path(p.strip()) for p in args.paths.split(",")]
cp.lock_verifiers(args.task_id, paths)
print(f"Locked {len(paths)} verifiers for {args.task_id}.")
elif args.subcommand == "verify-sovereignty":
cp.verify_sovereignty(args.task_id)
print(f"Verifier sovereignty verified for {args.task_id}.")
elif args.subcommand == "record-receipt":
token = cp.record_verification_receipt(args.task_id, args.gate, args.cmd, args.exit_code)
print(f"Receipt stamped: {token}")
elif args.subcommand == "update-worktree":
cp.update_worktree(args.task_id, args.path, args.branch, args.state)
print(f"Task {args.task_id} worktree state set to {args.state}.")
elif args.subcommand in ("inspect-decisions", "inspect-candidates"):
from control_plane.inspection import format_rows, inspect_candidates, inspect_decisions, open_readonly
conn = open_readonly(cp.db_path)
try:
if args.subcommand == "inspect-decisions":
rows = inspect_decisions(conn, args.task_id, from_state=args.from_state, to_state=args.to_state)
columns = ("decision_id", "edge", "question_id", "actor", "answer", "decision_type", "consumed")
else:
rows = inspect_candidates(conn, args.task_id)
columns = ("candidate_id", "stage", "question_id", "confirmation_status", "confirmed_by", "source_path", "answer")
finally:
conn.close()
print(json.dumps(rows, indent=2) if args.json else format_rows(rows, columns))
elif args.subcommand in ("show-challenge", "approve-transition"):
from control_plane.gate1_approval import GateApprovalError, approve_transition, show_challenge
try:
if args.subcommand == "show-challenge":
show_challenge(cp, args.request_id, key_hint=args.key)
else:
approve_transition(cp, args.request_id, principal=args.principal)
except GateApprovalError as exc:
raise SystemExit(f"REFUSED: {exc}")
elif args.subcommand == "status":
print(json.dumps(cp.get_task(args.task_id), indent=2, default=str))
elif args.subcommand == "transition-guidance":
print(json.dumps(cp.get_transition_guidance(args.task_id, args.to), indent=2))
elif args.subcommand == "log-prior-art":
repeat_entries = args.repeat_yes_entries or "none"
details = f"prior_art_scan: summary={args.summary}; repeat_yes_entries={repeat_entries}"
cp.log_asymmetric_persistence(
task_id=args.task_id,
destination="references/map-debt.md",
status="OBSERVED",
details=details
)
print(f"Prior art scan logged for task {args.task_id}.")
elif args.subcommand in (
"record-plan-mode-entry", "record-socratic-intake", "record-human-approval", "record-review-skip",
"invalidate-receipt",
):
_dispatch_gate_record_command(cp, args)
elif args.subcommand == "verify-interview-question":
cap = cp.verify_phase_capability(args.task_id, "interview_question")
print(f"Verified interview_question capability for {args.task_id} in {cap.current_state} (transition {cap.transition_id}).")
elif args.subcommand == "verify-plan-write":
cap = cp.verify_phase_capability(args.task_id, "plan_write")
print(f"Verified plan_write capability for {args.task_id} in {cap.current_state} (transition {cap.transition_id}).")
elif args.subcommand == "verify-exit-verification":
cap = cp.verify_phase_capability(args.task_id, "exit_verification")
print(f"Verified exit_verification capability for {args.task_id} in {cap.current_state} (transition {cap.transition_id}).")
elif args.subcommand == "record-recovery-approval":
token = cp.record_recovery_approval(
task_id=args.task_id,
expected_source_state=args.from_state,
destination_state=args.to_state,
source_occupancy_transition_id=args.source_occupancy_id,
approver=args.approver,
decision=args.decision,
reason=args.reason,
actor=args.actor,
)
print(f"Recovery approval recorded: {token}")
elif args.subcommand == "clear-guidance-block":
cp.clear_guidance_block(args.task_id, reason=args.reason)
print(f"Guidance block cleared for task '{args.task_id}'. Reason recorded: {args.reason}")
elif args.subcommand == "verify-commit":
res = cp.verify_commit(args.branch, args.staged_files)
print(f"Commit check: {res['status']} ({res['message']})")
def _dispatch_gate_record_command(cp: ControlPlane, args: argparse.Namespace):
"""Executes the gate-registry receipt-recording CLI subcommands."""
if args.subcommand == "record-plan-mode-entry":
token = cp.record_plan_mode_entry(args.task_id, args.actor)
print(f"Plan Mode entry recorded: {token}")
elif args.subcommand == "record-socratic-intake":
token = cp.record_socratic_intake_complete(args.task_id, args.summary)
print(f"Socratic intake completion recorded: {token}")
elif args.subcommand == "record-human-approval":
token = cp.record_human_approval(args.task_id, args.approver)
print(f"Human approval recorded: {token}")
elif args.subcommand == "record-review-skip":
from control_plane.receipt_provenance import ReceiptError, record_human_skip
_require_human_interactive_skip(args)
try:
token = record_human_skip(cp, args.task_id, args.phase, args.reason)
except ReceiptError as exc:
raise SystemExit(f"REFUSED: {exc}")
print(f"Review skip recorded (human, interactive): {token}")
elif args.subcommand == "invalidate-receipt":
from control_plane.receipt_provenance import ReceiptError, invalidate_receipt
try:
invalidate_receipt(cp, args.receipt_id, args.reason)
except ReceiptError as exc:
raise SystemExit(f"REFUSED: {exc}")
print(f"Receipt {args.receipt_id} invalidated (audited).")
def main():
"""Main CLI entry point for SQLite Control Plane."""
parser = _build_parser()
args = parser.parse_args()
if not args.subcommand:
parser.print_help()
sys.exit(1)
if args.subcommand == "list-review-options":
from control_plane.review_options import collect_review_options, format_review_options
print(format_review_options(collect_review_options()))
sys.exit(0)
if args.subcommand == "test-signing-mechanics":
from control_plane.identity_layout import default_layout
from control_plane.signing_selftest import run_selftest
from control_plane.identity_layout import canonical_repo_root
root = Path(args.repo_root).resolve() if args.repo_root else canonical_repo_root(".")
sys.exit(run_selftest(default_layout(root), Path(args.key).expanduser()))
cp = ControlPlane(db_path=getattr(args, "db_path", None))
try:
_dispatch_command(cp, args)
except Exception as e:
print(f"{'CONTROL PLANE ERROR' if isinstance(e, (InvalidStateTransition, VerifierSovereigntyViolation, PersistenceInvariantViolation, ConcurrentModificationError)) else 'ERROR'}: {e}", file=sys.stderr)
sys.exit(_map_exception_to_exit_code(e))
def _map_exception_to_exit_code(e: Exception) -> int:
"""Maps a caught exception to its CLI exit code. ConcurrentModificationError gets its own
code (3) since it's the one error that's explicitly retryable — indistinguishable from a
generic crash (exit 1) would prevent callers from retrying only on contention."""
if isinstance(e, ConcurrentModificationError):
return 3
if isinstance(e, (InvalidStateTransition, VerifierSovereigntyViolation, PersistenceInvariantViolation, PhaseCapabilityDenied, TransitionCoordinatorError)):
return 2
return 1
if __name__ == "__main__":
main()
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 |