Skip to content

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

running-control-plane

Flagged

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

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

scripts/control_plane/transition_request.py

View on GitHub
#!/usr/bin/env python3
"""
control_plane/transition_request.py
====================================

Purpose:
    Local, vendor-independent proof-of-concept mechanics for auth-ciba-poc-
    transition-mechanics (issues #621, #626, #634): a transition_request
    record plus a self-signed stub token standing in for a real IdP's signed
    proof (e.g. a real CIBA+RAR token), so the Policy-side verification logic
    can be built and adversarially tested before any real IdP integration
    (Increment B, out of scope here). No external IdP call happens anywhere
    in this module.

Key Input Dependencies:
    - agent_control.ControlPlane (task_id existence, db_path)
    - Python stdlib only (hmac, hashlib, secrets, json, base64) -- no new
      third-party dependency for this stub signer, per this repo's
      dependency-management rules.

Key Functions:
    - create_transition_request() -- Policy-side creation; the agent proposes,
      Policy generates the nonce/revision_hash and persists PENDING (spec
      guardrail: no agent DB writes for transition_request creation).
    - issue_stub_token() -- stand-in for a real IdP's signed-proof issuance.
    - consume_with_signature() -- T4: verify a human's SSHSIG and consume the request
      inside the CALLER's open transaction (the adapter's BEGIN IMMEDIATE).
    - verify_and_consume() -- independent Policy-side verification: signature,
      expiration, payload-match against the stored request (not the token's
      own claims), content binding (T2: a request created with a content snapshot
      can only be consumed against the same live content), single-use (jti +
      nonce), atomic consume-and-commit.

Exceptions:
    - TransitionRequestError (base)
    - TokenExpired, TokenReplayed, PayloadMismatch, RequestNotFound
    - ContentChanged, ContentBindingRequired (T2, auth-ciba-increment-b)
    - StaleOccupancy (T4)
"""

import hashlib
import hmac
import json
import secrets
import sqlite3
import time
from base64 import urlsafe_b64decode, urlsafe_b64encode
from dataclasses import dataclass
from typing import Any, Dict, Optional, Sequence

from control_plane.ssh_signing import VerifiedSignature, derive_challenge_from_row, verify_signature
from control_plane.snapshot import (
    CHALLENGE_VERSION,
    SnapshotEntry,
    compute_revision_hash,
    diff_snapshot,
    snapshot_matches,
    snapshot_to_json,
)


# Default lifetime of a Gate 1 request: a human must read the challenge, sign it (passphrase or
# hardware touch) and run approve-transition, which needs more than the Increment A 300 s.
DEFAULT_GATE1_TTL_SECONDS = 900.0


class TransitionRequestError(Exception):
    """Base exception for this module's verification failures."""


class TokenExpired(TransitionRequestError):
    pass


class TokenReplayed(TransitionRequestError):
    pass


class PayloadMismatch(TransitionRequestError):
    pass


class RequestNotFound(TransitionRequestError):
    pass


class StaleOccupancy(TransitionRequestError):
    """The request was created for an earlier occupancy of the task."""


class ContentChanged(TransitionRequestError):
    """The reviewed content differs from the snapshot bound to the request."""


class ContentBindingRequired(TransitionRequestError):
    """A content-bound request cannot be consumed without a live snapshot to compare."""


@dataclass(frozen=True)
class TransitionRequestRecord:
    request_id: int
    task_id: str
    from_state: str
    to_state: str
    occupancy_id: int
    nonce: str
    expiration: float
    revision_hash: str
    status: str
    challenge_version: Optional[str] = None
    content_snapshot: Optional[str] = None


def _b64url(data: bytes) -> str:
    return urlsafe_b64encode(data).rstrip(b"=").decode("ascii")


def _b64url_decode(data: str) -> bytes:
    padding = "=" * (-len(data) % 4)
    return urlsafe_b64decode(data + padding)


def create_transition_request(
    conn: sqlite3.Connection,
    *,
    task_id: str,
    from_state: str,
    to_state: str,
    occupancy_id: int,
    ttl_seconds: float = 300.0,
    now: Optional[float] = None,
    content_snapshot: Optional[Sequence[SnapshotEntry]] = None,
) -> TransitionRequestRecord:
    """Policy-side creation. The caller (Policy, never the agent directly --
    see spec guardrail 'No agent DB writes for transition_request creation')
    generates the nonce and revision_hash and persists PENDING here."""
    nonce = secrets.token_hex(16)
    now = now if now is not None else time.time()
    expiration = now + ttl_seconds
    # T2: with a content snapshot the hash binds the reviewed files; without one it is
    # exactly the Increment A metadata-only hash.
    revision_hash = compute_revision_hash(
        task_id, from_state, to_state, occupancy_id, nonce, content_snapshot
    )
    challenge_version = CHALLENGE_VERSION if content_snapshot else None
    snapshot_json = snapshot_to_json(content_snapshot) if content_snapshot else None

    conn.execute("BEGIN IMMEDIATE;")
    try:
        cursor = conn.execute(
            """
            INSERT INTO transition_request
                (task_id, from_state, to_state, occupancy_id, nonce, expiration,
                 revision_hash, status, created_at, challenge_version, content_snapshot)
            VALUES (?, ?, ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?)
            """,
            (task_id, from_state, to_state, occupancy_id, nonce, expiration, revision_hash, now,
             challenge_version, snapshot_json),
        )
        conn.commit()
        request_id = cursor.lastrowid
    except Exception:
        conn.rollback()
        raise

    return TransitionRequestRecord(
        request_id=request_id, task_id=task_id, from_state=from_state, to_state=to_state,
        occupancy_id=occupancy_id, nonce=nonce, expiration=expiration,
        revision_hash=revision_hash, status="PENDING",
        challenge_version=challenge_version, content_snapshot=snapshot_json,
    )


def issue_stub_token(
    record: TransitionRequestRecord,
    secret: bytes,
    *,
    jti: Optional[str] = None,
    now: Optional[float] = None,
) -> str:
    """Stub stand-in for a real IdP's signed proof (e.g. CIBA+RAR). Generated
    fresh per caller and never reused as a trusted key outside a test fixture
    or this local PoC -- a real deployment replaces this entirely with actual
    IdP-issued, IdP-signed tokens (Increment B, out of scope for this module).

    Compact format: base64url(payload_json).base64url(hmac_sha256_signature) --
    deliberately not claiming JWT/JWS standard compliance, just a stand-in
    with an equivalent signed-and-verifiable shape."""
    payload = {
        "task_id": record.task_id,
        "from_state": record.from_state,
        "to_state": record.to_state,
        "occupancy_id": record.occupancy_id,
        "nonce": record.nonce,
        "revision_hash": record.revision_hash,
        "exp": record.expiration,
        "jti": jti or secrets.token_hex(16),
        "iat": now if now is not None else time.time(),
    }
    payload_bytes = json.dumps(payload, sort_keys=True).encode("utf-8")
    signature = hmac.new(secret, payload_bytes, hashlib.sha256).digest()
    return f"{_b64url(payload_bytes)}.{_b64url(signature)}"


def _decode_stub_token(token: str, secret: bytes) -> Dict[str, Any]:
    try:
        payload_part, signature_part = token.split(".", 1)
    except ValueError:
        raise TransitionRequestError("Malformed token: expected 'payload.signature'.")
    payload_bytes = _b64url_decode(payload_part)
    signature = _b64url_decode(signature_part)
    expected_signature = hmac.new(secret, payload_bytes, hashlib.sha256).digest()
    if not hmac.compare_digest(signature, expected_signature):
        raise TransitionRequestError("Token signature verification failed.")
    return json.loads(payload_bytes)


def verify_and_consume(
    conn: sqlite3.Connection,
    *,
    task_id: str,
    token: str,
    secret: bytes,
    now: Optional[float] = None,
    live_snapshot: Optional[Sequence[SnapshotEntry]] = None,
) -> TransitionRequestRecord:
    """Independent Policy-side verification -- the actual mechanics this task
    exists to prove: signature (via _decode_stub_token), expiration, payload-
    match against the STORED request (not the token's own self-reported
    claims), single-use via nonce+jti, atomic consume-and-commit in one
    transaction (TOCTOU-safe). Adversarial matrix cases 1-4 map directly onto
    this function's checks."""
    now = now if now is not None else time.time()
    payload = _decode_stub_token(token, secret)  # raises on bad signature

    conn.execute("BEGIN IMMEDIATE;")
    try:
        row = conn.execute(
            """
            SELECT request_id, task_id, from_state, to_state, occupancy_id,
                   nonce, expiration, revision_hash, status, jti,
                   challenge_version, content_snapshot
            FROM transition_request WHERE nonce = ?
            """,
            (payload.get("nonce"),),
        ).fetchone()

        if row is None:
            raise RequestNotFound(f"No transition_request found for nonce {payload.get('nonce')!r}.")

        (request_id, stored_task_id, stored_from, stored_to, stored_occ,
         stored_nonce, stored_exp, stored_rev_hash, status, stored_jti,
         stored_version, stored_snapshot) = row

        # Case 2: replay -- already consumed (or otherwise not PENDING).
        if status != "PENDING":
            raise TokenReplayed(
                f"transition_request {request_id} is '{status}', not PENDING -- "
                "token already consumed or request already resolved."
            )

        # Case 3: payload mismatch -- token's claims must match the STORED
        # request exactly, not just be internally self-consistent. A token
        # correctly signed for a *different* task/nonce must not validate here.
        if (
            payload.get("task_id") != stored_task_id
            or payload.get("from_state") != stored_from
            or payload.get("to_state") != stored_to
            or payload.get("occupancy_id") != stored_occ
            or payload.get("revision_hash") != stored_rev_hash
        ):
            raise PayloadMismatch(
                "Token payload does not match the stored transition_request -- "
                "possible cross-request token reuse."
            )
        if task_id != stored_task_id:
            raise PayloadMismatch(f"Token is for task '{stored_task_id}', not '{task_id}'.")

        # Case 4: expired.
        if now >= stored_exp:
            conn.execute(
                "UPDATE transition_request SET status = 'EXPIRED' WHERE request_id = ?",
                (request_id,),
            )
            conn.commit()
            raise TokenExpired(f"transition_request {request_id} expired at {stored_exp}, now {now}.")

        # T2 content binding: a request created with a content snapshot may only be
        # consumed against the same live content. Fail closed when the caller supplies
        # no live snapshot; leave the request PENDING (nothing is mutated on refusal).
        if stored_snapshot is not None:
            if live_snapshot is None:
                raise ContentBindingRequired(
                    f"transition_request {request_id} is bound to reviewed content; "
                    "pass live_snapshot so it can be re-checked before consumption."
                )
            if not snapshot_matches(stored_snapshot, live_snapshot):
                changed = ", ".join(diff_snapshot(stored_snapshot, live_snapshot))
                raise ContentChanged(
                    f"transition_request {request_id}: reviewed content changed since the "
                    f"request was created ({changed}); the approval no longer applies."
                )

        # All checks passed -- atomic consume-and-commit (case 1 success path).
        # WHERE ... AND status = 'PENDING' makes this the actual TOCTOU guard:
        # cursor.rowcount (not conn.total_changes, which is connection-wide and
        # not scoped to this statement) is 0 only if another writer consumed
        # this exact row between the SELECT above and this UPDATE.
        update_cursor = conn.execute(
            """
            UPDATE transition_request
            SET status = 'CONSUMED', consumed_at = ?, jti = ?
            WHERE request_id = ? AND status = 'PENDING'
            """,
            (now, payload.get("jti"), request_id),
        )
        if update_cursor.rowcount == 0:
            conn.rollback()
            raise TokenReplayed(f"transition_request {request_id} was consumed concurrently.")
        conn.commit()
    except Exception:
        conn.rollback()
        raise

    return TransitionRequestRecord(
        request_id=request_id, task_id=stored_task_id, from_state=stored_from,
        to_state=stored_to, occupancy_id=stored_occ, nonce=stored_nonce,
        expiration=stored_exp, revision_hash=stored_rev_hash, status="CONSUMED",
        challenge_version=stored_version, content_snapshot=stored_snapshot,
    )


@dataclass(frozen=True)
class PreVerified:
    """Result of preverify_signature(): the live snapshot read, the challenge rebuilt from it, and the
    signature verified over that challenge -- all computed with NO write lock held. The commit transaction
    trusts none of it blindly: consume_with_signature() rebuilds the challenge from the row inside the
    transaction and refuses unless it is byte-identical to the one that was verified here."""

    request_id: int
    live: Sequence[Any]
    challenge: Any
    verified: VerifiedSignature


def _check_request_row(conn: sqlite3.Connection, *, task_id: str, from_state: str, to_state: str,
                       occupancy_id: int, proof: Any, now: float) -> str:
    """Row-level checks shared by both phases (no external work): request exists, matches task and edge,
    is PENDING, belongs to the live occupancy, is unexpired, and is content-bound. Returns the stored snapshot."""
    row = conn.execute(
        """
        SELECT task_id, from_state, to_state, occupancy_id, expiration, status, content_snapshot
        FROM transition_request WHERE request_id = ?
        """,
        (proof.request_id,),
    ).fetchone()
    if row is None:
        raise RequestNotFound(f"No transition_request {proof.request_id}.")
    stored_task, stored_from, stored_to, stored_occ, stored_exp, status, stored_snapshot = tuple(row)
    if (stored_task, stored_from, stored_to) != (task_id, from_state, to_state):
        raise PayloadMismatch(
            f"transition_request {proof.request_id} is for {stored_task} {stored_from}->{stored_to}, "
            f"not {task_id} {from_state}->{to_state}."
        )
    if status != "PENDING":
        raise TokenReplayed(f"transition_request {proof.request_id} is '{status}', not PENDING.")
    if stored_occ != occupancy_id:
        raise StaleOccupancy(
            f"transition_request {proof.request_id} was created for occupancy {stored_occ}; live occupancy is {occupancy_id}."
        )
    if now >= stored_exp:
        raise TokenExpired(f"transition_request {proof.request_id} expired at {stored_exp}, now {now}.")
    if stored_snapshot is None:
        raise ContentBindingRequired(f"transition_request {proof.request_id} is not bound to reviewed content.")
    return stored_snapshot


def _check_live_content(stored_snapshot: str, live: Any, proof: Any) -> None:
    if live is None:
        raise ContentBindingRequired("a live content snapshot is required to consume a content-bound request.")
    if not snapshot_matches(stored_snapshot, live):
        raise ContentChanged(
            f"transition_request {proof.request_id}: reviewed content changed since the request "
            f"({', '.join(diff_snapshot(stored_snapshot, live))}); the approval no longer applies."
        )


def preverify_signature(
    conn: sqlite3.Connection,
    *,
    task_id: str,
    from_state: str,
    to_state: str,
    occupancy_id: int,
    proof: Any,
    now: float,
) -> PreVerified:
    """The slow, external half of consumption, run BEFORE the commit's `BEGIN IMMEDIATE`: read the live
    snapshot (git/file hashing), rebuild the challenge and run `ssh-keygen -Y verify`. `conn` must be a
    read-only, non-transactional connection -- holding the write lock across a subprocess makes every
    concurrent writer fail with `database is locked` for the subprocess's duration. Nothing here mutates."""
    stored_snapshot = _check_request_row(
        conn, task_id=task_id, from_state=from_state, to_state=to_state,
        occupancy_id=occupancy_id, proof=proof, now=now,
    )
    live = proof.live_snapshot_fn() if proof.live_snapshot_fn is not None else None
    _check_live_content(stored_snapshot, live, proof)
    challenge = derive_challenge_from_row(conn, proof.request_id, live)
    if proof.allowed_signers is None:
        from control_plane.ssh_signing import SignatureInvalid

        raise SignatureInvalid("no allowed_signers file supplied with the proof")
    verified = verify_signature(
        challenge, proof.signature, allowed_signers=proof.allowed_signers, principal=proof.principal,
        require_uv=proof.require_uv, binary=proof.binary, timeout=proof.timeout,
    )
    return PreVerified(request_id=proof.request_id, live=live, challenge=challenge, verified=verified)


def consume_with_signature(
    conn: sqlite3.Connection,
    *,
    task_id: str,
    from_state: str,
    to_state: str,
    occupancy_id: int,
    proof: Any,
    now: float,
    preverified: Optional[PreVerified] = None,
) -> VerifiedSignature:
    """Consume a human's SSHSIG-verified request INSIDE the caller's transaction.

    Does not begin or commit: the persistence adapter calls this within its `BEGIN IMMEDIATE` so
    consumption, decision rows and the state advance are one atomic unit (a failure anywhere rolls all of
    it back and leaves the request PENDING). `proof` is a control_plane.ports.AuthorizationProof.

    With `preverified` (the adapter path), the subprocess and git work already happened outside the write
    lock; this re-runs every row check against the transaction's own view, requires the stored snapshot to
    still match the snapshot that was verified, and requires the challenge rebuilt from the row here to be
    identical to the verified one -- so a request mutated between the two phases cannot ride the earlier
    verification -- then flips PENDING -> CONSUMED. Without it (direct callers), it performs the whole
    verification inline, exactly as before."""
    stored_snapshot = _check_request_row(
        conn, task_id=task_id, from_state=from_state, to_state=to_state,
        occupancy_id=occupancy_id, proof=proof, now=now,
    )
    if preverified is None:
        preverified = preverify_signature(
            conn, task_id=task_id, from_state=from_state, to_state=to_state,
            occupancy_id=occupancy_id, proof=proof, now=now,
        )
    else:
        if preverified.request_id != proof.request_id:
            raise PayloadMismatch("pre-verified signature belongs to a different transition_request.")
        _check_live_content(stored_snapshot, preverified.live, proof)
        if derive_challenge_from_row(conn, proof.request_id, preverified.live) != preverified.challenge:
            raise ContentChanged(
                f"transition_request {proof.request_id} changed between signature verification and commit; "
                "the verified challenge no longer matches the stored request."
            )
    verified = preverified.verified
    cursor = conn.execute(
        "UPDATE transition_request SET status = 'CONSUMED', consumed_at = ?, jti = ? WHERE request_id = ? AND status = 'PENDING'",
        (now, f"sshsig:{verified.fingerprint}", proof.request_id),
    )
    if cursor.rowcount == 0:
        raise TokenReplayed(f"transition_request {proof.request_id} was consumed concurrently.")
    return verified
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexUnverifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall