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

tests/test_pre_commit_pipeline_guard.py

View on GitHub
"""
test_pre_commit_pipeline_guard.py — Deterministic Pipeline Execution & Stage Gate Tests
========================================================================================

Purpose:
    Tests the git pre-commit pipeline execution guard (`pre-commit-pipeline-guard`) and the
    policy engine operation rule (`OPERATION_RULES["commit"]`).
    Validates:
    - Bypasses non-task branches (main, master, untracked) with exit 0.
    - Permits planning documentation commits (docs/plans/*, docs/superpowers/*) during proposal mode.
    - Blocks code commits during proposal mode (INTAKE, INTERVIEW, DRAFT_PLAN, etc.) with exit 1.
    - Permits commits during implementation (IN_WORKTREE, WORKTREE_REVIEW, etc.) when pipeline
      execution history is valid and contiguous.
    - Blocks commits if transition_violations are recorded for the task.
    - Blocks commits if transitions in task_transitions do not exist in valid_transitions.
    - Blocks commits if the transition chain is broken (skipped stages).
"""

import os
import sqlite3
import subprocess
import sys
from pathlib import Path

import pytest

SCRIPTS_DIR = Path(__file__).resolve().parent.parent / "scripts"
if str(SCRIPTS_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPTS_DIR))

from control_plane.adapters import SqlitePersistenceAdapter, FilesystemAdapter
from control_plane.policy import evaluate_operation, PolicyViolation
from agent_control import ControlPlane, PersistenceInvariantViolation
from interview_helpers import stage_interview_answers
from helpers.implementation_ledger import stage_implementation_ledger
from control_plane.constants import (
    STATE_INTERVIEW, STATE_DRAFT_PLAN, STATE_PLAN_REVIEW, STATE_AWAITING_APPROVAL, STATE_APPROVED, STATE_IN_WORKTREE, STATE_WORKTREE_REVIEW, STATE_VERIFY_EXIT, STATE_RETROSPECTIVE, STATE_DONE,
)

HOOK_PATH = SCRIPTS_DIR / "pre-commit-pipeline-guard"


def _setup_git_repo_with_db(tmp_path):
    """Creates a temporary git repository with initialized control_plane.db."""
    repo = tmp_path / "repo"
    repo.mkdir()
    subprocess.run(["git", "init", "-b", "main"], cwd=str(repo), check=True, capture_output=True)
    subprocess.run(["git", "config", "user.name", "Test User"], cwd=str(repo), check=True)
    subprocess.run(["git", "config", "user.email", "test@example.com"], cwd=str(repo), check=True)

    # Initial commit so HEAD exists
    readme = repo / "README.md"
    readme.write_text("# Test Repo\n", encoding="utf-8")
    # The control-plane database lives in this repo and changes on every write, so it must be ignored: Gate 3 signs
    # the untracked-files hash, and a churning untracked DB would invalidate every request before it is signed.
    (repo / ".gitignore").write_text("context/\n", encoding="utf-8")
    subprocess.run(["git", "add", "README.md", ".gitignore"], cwd=str(repo), check=True)
    subprocess.run(["git", "commit", "-m", "Initial commit"], cwd=str(repo), check=True)

    db_path = repo / "context" / "control_plane.db"
    adapter = SqlitePersistenceAdapter(db_path, FilesystemAdapter())
    adapter.ensure_schema()
    return repo, db_path


def _advance_task_to_in_worktree(cp, task_id, repo, branch):
    """Advances task through all required pipeline stages to IN_WORKTREE."""
    cp.create_task(task_id, f"Task {task_id}", "claude")
    cp.transition(task_id, STATE_INTERVIEW, "tester", "interview")
    cp.record_plan_mode_entry(task_id, "tester")
    stage_interview_answers(cp, task_id)
    cp.transition(task_id, STATE_DRAFT_PLAN, "tester", "draft")
    plans = repo / "docs" / "plans"
    plans.mkdir(parents=True, exist_ok=True)
    (plans / f"{task_id}-spec.md").write_text("# Spec\n", encoding="utf-8")
    (plans / f"{task_id}-implementation-plan.md").write_text("# Plan\n", encoding="utf-8")
    cp.repo_root = repo
    stage_implementation_ledger(cp, task_id, repo)
    from control_plane.coordinator import TransitionCoordinator
    # Each real edge question is followed by the mandatory guidance-compliance
    # confirmation ("1" alone is no longer enough -- it would get reused for that
    # question too and be read as "not YES", blocking the task).
    answers = iter(["1", "YES", "1", "YES"])
    coordinator = TransitionCoordinator(control_plane=cp, input_fn=lambda _prompt: next(answers))
    coordinator.coordinate_transition(
        task_id=task_id,
        to_state=STATE_PLAN_REVIEW,
        actor="human",
        reason="Submit plan for disposition",
        interactive=True,
    )
    cp.record_review_skip(task_id, "multi_agent_review", "tester", "skip")
    coordinator.coordinate_transition(
        task_id=task_id,
        to_state=STATE_AWAITING_APPROVAL,
        actor="human",
        reason="Accept plan after review skip",
        interactive=True,
    )
    cp.record_human_approval(task_id, "tester")
    conn = sqlite3.connect(cp.db_path)
    last_trans = conn.execute("SELECT transition_id FROM task_transitions WHERE task_id = ? ORDER BY transition_id DESC LIMIT 1", (task_id,)).fetchone()[0]
    conn.execute(
        """
        INSERT INTO transition_decisions (
            task_id, source_occupancy_transition_id, from_state, to_state,
            question_id, answer, decision_type, actor, recorded_at
        ) VALUES (?, ?, 'AWAITING_APPROVAL', 'APPROVED', 'human_implementation_approval', 'Yes, approve implementation [Recommended]', 'ANSWER', 'human', 12345.0),
                 (?, ?, 'AWAITING_APPROVAL', 'APPROVED', 'approval_awaiting_approval_to_approved', 'APPROVAL', 'APPROVAL', 'human', 12345.0)
        """,
        (task_id, last_trans, task_id, last_trans)
    )
    conn.commit()
    conn.close()
    cp.record_verification_receipt(
        task_id=task_id, gate_name="main_dirty_before_approval_exception",
        command_executed="test-fixture-uses-real-dirty-planning-files", exit_code=0,
    )  # DEBT-20260913-MAIN-DIRTY-BEFORE-APPROVAL-UNENFORCED: this fixture's planning
    # files are intentionally uncommitted for the test's own purpose (testing the
    # commit-pipeline-guard hook), not real interim work needing the clean-checkout gate.
    cp.transition(task_id, STATE_APPROVED, "tester", "approved")
    cp.update_worktree(task_id, str(repo), branch, "written_in_worktree")
    cp.record_verification_receipt(
        task_id=task_id, gate_name="existing_worktree_exception",
        command_executed="test-fixture-reuses-repo-as-worktree", exit_code=0,
    )  # this fixture intentionally reuses the same repo dir as the "worktree" to
    # keep the git-hook test simple -- not a real isolated worktree.
    cp.transition(task_id, STATE_IN_WORKTREE, "tester", "in worktree")


def test_hook_bypasses_main_branch(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 0


def test_hook_bypasses_untracked_branch_with_warning(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    subprocess.run(["git", "checkout", "-b", "feat/untracked-work"], cwd=str(repo), check=True, capture_output=True)
    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 0
    assert "WARNING" in res.stderr
    assert "no task registered for branch 'feat/untracked-work'" in res.stderr


def test_hook_blocks_code_commit_during_planning_states(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-planning-001"
    branch = "feat/planning-task"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    cp.create_task(task_id, "Planning Task", "claude")
    cp.update_worktree(task_id, str(repo), branch, "written_in_worktree")

    # Stage production code
    code_file = repo / "src.py"
    code_file.write_text("print('code')\n", encoding="utf-8")
    subprocess.run(["git", "add", "src.py"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 1
    assert "GIT COMMIT BLOCKED: Proposal Mode Violation!" in res.stdout
    assert "src.py" in res.stdout


def test_hook_allows_plan_doc_commit_during_planning_states(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-plan-docs-002"
    branch = "feat/plan-docs-task"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    cp.create_task(task_id, "Plan Docs Task", "claude")
    cp.transition(task_id, STATE_INTERVIEW, "tester", "interview")
    cp.record_plan_mode_entry(task_id, "tester")
    stage_interview_answers(cp, task_id)
    cp.transition(task_id, STATE_DRAFT_PLAN, "tester", "draft")
    cp.update_worktree(task_id, str(repo), branch, "written_in_worktree")

    # Stage plan documentation only
    plan_file = repo / "docs" / "plans" / f"{task_id}-spec.md"
    plan_file.parent.mkdir(parents=True, exist_ok=True)
    plan_file.write_text("# Spec\n", encoding="utf-8")
    subprocess.run(["git", "add", "docs/plans/"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 0


def test_hook_allows_code_commit_with_valid_contiguous_history(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-valid-exec-003"
    branch = "feat/valid-execution"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    # Stage production code
    code_file = repo / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 0


def test_hook_blocks_if_transition_violations_exist(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-viol-004"
    branch = "feat/viol-task"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    # Log an illegal transition violation directly in DB
    conn = sqlite3.connect(str(db_path))
    conn.execute(
        "INSERT INTO transition_violations (task_id, attempted_from_state, attempted_to_state) VALUES (?, 'INTAKE', 'IN_WORKTREE')",
        (task_id,)
    )
    conn.commit()
    conn.close()

    code_file = repo / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 1
    assert "GIT COMMIT BLOCKED: Control Plane Transition Violations Detected!" in res.stdout


def test_hook_blocks_if_transition_not_in_valid_transitions(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-invalid-edge-005"
    branch = "feat/invalid-edge"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    # Inject invalid transition into task_transitions
    conn = sqlite3.connect(str(db_path))
    conn.execute(
        "INSERT INTO task_transitions (task_id, from_state, to_state, actor, reason) VALUES (?, 'ESCALATED', 'IN_WORKTREE', 'attacker', 'bypass')",
        (task_id,)
    )
    conn.commit()
    conn.close()

    code_file = repo / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 1
    assert "GIT COMMIT BLOCKED: Invalid State Transition Detected!" in res.stdout


def test_hook_blocks_if_transition_chain_is_broken(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-broken-chain-006"
    branch = "feat/broken-chain"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    # Inject a gap in task_transitions: e.g. delete DRAFT_PLAN -> AWAITING_APPROVAL so chain is broken
    conn = sqlite3.connect(str(db_path))
    conn.execute(
        "DELETE FROM task_transitions WHERE task_id = ? AND from_state = 'DRAFT_PLAN'",
        (task_id,)
    )
    conn.commit()
    conn.close()

    code_file = repo / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 1
    assert "GIT COMMIT BLOCKED: Broken Pipeline State Chain!" in res.stdout


def test_control_plane_verify_commit_api(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    cp = ControlPlane(db_path=db_path)
    task_id = "task-api-007"
    branch = "feat/api-test"

    cp.create_task(task_id, "API Task", "claude")
    cp.update_worktree(task_id, str(repo), branch, "written_in_worktree")

    # In proposal mode with code staged -> raises PersistenceInvariantViolation
    with pytest.raises(PersistenceInvariantViolation, match="Proposal Mode"):
        cp.verify_commit(branch=branch, staged_files=["src/code.py"])

    # In proposal mode with docs staged -> allowed
    res = cp.verify_commit(branch=branch, staged_files=["docs/plans/spec.md"])
    assert res["status"] == "ALLOWED"

    # Once advanced to IN_WORKTREE -> allowed for code
    cp.transition(task_id, STATE_INTERVIEW, "tester", "interview")
    cp.record_plan_mode_entry(task_id, "tester")
    stage_interview_answers(cp, task_id)
    cp.transition(task_id, STATE_DRAFT_PLAN, "tester", "draft")
    plans = repo / "docs" / "plans"
    plans.mkdir(parents=True, exist_ok=True)
    (plans / f"{task_id}-spec.md").write_text("# Spec\n", encoding="utf-8")
    (plans / f"{task_id}-implementation-plan.md").write_text("# Plan\n", encoding="utf-8")
    cp.repo_root = repo
    from control_plane.coordinator import TransitionCoordinator
    answers = iter(["1", "YES", "1", "YES"])
    coordinator = TransitionCoordinator(control_plane=cp, input_fn=lambda _prompt: next(answers))
    coordinator.coordinate_transition(task_id=task_id, to_state=STATE_PLAN_REVIEW, actor="human", reason="Submit plan", interactive=True)
    cp.record_review_skip(task_id, "multi_agent_review", "tester", "skip")
    coordinator.coordinate_transition(task_id=task_id, to_state=STATE_AWAITING_APPROVAL, actor="human", reason="Accept skipped plan", interactive=True)
    cp.record_human_approval(task_id, "tester")
    conn = sqlite3.connect(cp.db_path)
    last_trans = conn.execute("SELECT transition_id FROM task_transitions WHERE task_id = ? ORDER BY transition_id DESC LIMIT 1", (task_id,)).fetchone()[0]
    conn.execute(
        """
        INSERT INTO transition_decisions (
            task_id, source_occupancy_transition_id, from_state, to_state,
            question_id, answer, decision_type, actor, recorded_at
        ) VALUES (?, ?, 'AWAITING_APPROVAL', 'APPROVED', 'human_implementation_approval', 'Yes, approve implementation [Recommended]', 'ANSWER', 'human', 12345.0),
                 (?, ?, 'AWAITING_APPROVAL', 'APPROVED', 'approval_awaiting_approval_to_approved', 'APPROVAL', 'APPROVAL', 'human', 12345.0)
        """,
        (task_id, last_trans, task_id, last_trans)
    )
    conn.commit()
    conn.close()
    cp.record_verification_receipt(
        task_id=task_id, gate_name="main_dirty_before_approval_exception",
        command_executed="test-fixture-uses-real-dirty-planning-files", exit_code=0,
    )  # DEBT-20260913-MAIN-DIRTY-BEFORE-APPROVAL-UNENFORCED: this fixture's planning
    # files are intentionally uncommitted for the test's own purpose (testing the
    # commit-pipeline-guard hook), not real interim work needing the clean-checkout gate.
    cp.transition(task_id, STATE_APPROVED, "tester", "approved")
    cp.update_worktree(task_id, str(repo), branch, "written_in_worktree")
    cp.record_verification_receipt(
        task_id=task_id, gate_name="existing_worktree_exception",
        command_executed="test-fixture-reuses-repo-as-worktree", exit_code=0,
    )  # this fixture intentionally reuses the same repo dir as the "worktree" to
    # keep the git-hook test simple -- not a real isolated worktree.
    cp.transition(task_id, STATE_IN_WORKTREE, "tester", "in worktree")

    res2 = cp.verify_commit(branch=branch, staged_files=["src/code.py"])
    assert res2["status"] == "ALLOWED"


PUSH_HOOK_PATH = SCRIPTS_DIR / "pre-push-review-guard"


def test_push_hook_blocks_when_not_done(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-push-not-done-008"
    branch = "feat/push-not-done"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    # In IN_WORKTREE, push is blocked
    res = subprocess.run([str(PUSH_HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 1
    assert "GIT PUSH BLOCKED: Pipeline Not Complete (Final State 'DONE' Required)!" in res.stdout


def test_push_hook_allows_when_done_with_valid_history(tmp_path):
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-push-done-009"
    branch = "feat/push-done"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)
    
    # Advance task to DONE (record test_suite before entering WORKTREE_REVIEW)
    cp.record_verification_receipt(task_id, "test_suite", "pytest", 0)
    cp.record_verification_receipt(task_id, "full_test_suite", "pytest -q", 0)
    conn = sqlite3.connect(cp.db_path)
    last_trans = conn.execute("SELECT transition_id FROM task_transitions WHERE task_id = ? ORDER BY transition_id DESC LIMIT 1", (task_id,)).fetchone()[0]
    conn.execute(
        """
        INSERT INTO transition_decisions (
            task_id, source_occupancy_transition_id, from_state, to_state,
            question_id, answer, decision_type, actor, recorded_at
        ) VALUES (?, ?, 'IN_WORKTREE', 'WORKTREE_REVIEW', 'confirm_review_in_worktree_to_worktree_review', 'Proceed with review [Recommended]', 'ANSWER', 'human', 12345.0),
                 (?, ?, 'IN_WORKTREE', 'WORKTREE_REVIEW', 'confirm_test_suite_or_defer', 'Run tests now instead', 'ANSWER', 'human', 12345.0)
        """,
        (task_id, last_trans, task_id, last_trans)
    )
    conn.commit()
    conn.close()
    cp.transition(task_id, STATE_WORKTREE_REVIEW, "tester", "review")
    cp.record_review_skip(task_id, "multi_agent_code_review", "tester", "skip")

    # WORKTREE_REVIEW -> VERIFY_EXIT is Gate 3 (auth-ciba-increment-b): no staged decision rows. The transition
    # below is completed through the signed-request flow (the test human signs for real; see conftest.py).
    cp.transition(task_id, STATE_VERIFY_EXIT, "tester", "verify")
    cp.record_verification_receipt(task_id, "leak_check", "git status", 0)
    cp.log_asymmetric_persistence(task_id, "references/map-debt.md", "RESOLVED", "test")
    cp.transition(task_id, STATE_RETROSPECTIVE, "tester", "enter retrospective")
    cp.save_retrospective(
        task_id,
        {"decision": "skip", "completion_mode": "skipped", "actor": "human", "skip_reason": "hook fixture"},
        [],
    )
    from control_plane.coordinator import TransitionCoordinator
    TransitionCoordinator(control_plane=cp).coordinate_transition(  # closure is signed (the test human signs for real)
        task_id, STATE_DONE, "tester", "done", interactive=True,
    )

    res = subprocess.run([str(PUSH_HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 0


@pytest.mark.xfail(strict=True, reason=(
    "OPEN map-debt (2026-09-20): apply_recovery_transition() leaves the consumed recovery approval with "
    "bound_transition_id NULL, so the commit/push guards see a NON-DAG recovery edge as unapproved. The previous "
    "version of this test used IN_WORKTREE -> DONE, which is a DAG edge, so the recovery-approval branch of the "
    "hooks was never actually exercised. strict=True: fixing the binding turns this into a hard pass."
))
def test_git_guards_allow_exact_human_approved_recovery_edge(tmp_path):
    """Allow a non-DAG edge only when its exact recovery approval is persisted and consumed."""
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-approved-recovery-010"
    branch = "feat/approved-recovery"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)
    # Recovery into DONE is refused by design (it would bypass the signed closure gate), so the exact-approved
    # non-DAG edge exercised here is IN_WORKTREE -> MULTI_AGENT_CODE_REVIEW.
    from control_plane.constants import STATE_MULTI_AGENT_CODE_REVIEW as _RECOVERY_TARGET
    token = cp.record_recovery_approval(
        task_id, _RECOVERY_TARGET, "human-reviewer", actor="human",
        reason="Reopen only through the explicitly approved recovery edge.",
    )
    cp.apply_recovery_transition(
        task_id, _RECOVERY_TARGET, token, "human", "Apply the approved recovery edge for code review."
    )

    code_file = repo / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(repo), check=True)

    commit_check = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    push_check = subprocess.run([str(PUSH_HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert commit_check.returncode == 0, commit_check.stdout + commit_check.stderr
    assert push_check.returncode == 0, push_check.stdout + push_check.stderr


def test_recovery_into_done_is_refused_because_closure_needs_a_signature(tmp_path):
    """A recovery approval can never be used to reach DONE: every inbound edge to DONE is a cryptographic gate, and
    the recovery path has no signature, so it fails closed instead of bypassing the gate."""
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-recovery-into-done-011"
    branch = "feat/recovery-into-done"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)
    with pytest.raises(ValueError, match="Recovery into 'DONE' is not permitted"):
        cp.record_recovery_approval(
            task_id, STATE_DONE, "human-reviewer", actor="human", reason="Attempt to close through recovery.",
        )
    assert cp.get_task(task_id)["state"] == STATE_IN_WORKTREE


# --- Registered-worktree location-check regression tests -------------------
# Regression coverage for a confirmed defect (see references/map-debt.md,
# tracked separately from GitHub issue #621's human-authorization finding):
# the hook's RESOLVED_TASK_WORKTREE resolution (~line 97) previously resolved
# a repository-relative registered worktree_path against the *current shell
# CWD* instead of REPO_ROOT, so a legitimate commit made from inside the
# correctly registered worktree was misclassified as "Commit Outside
# Registered Worktree" whenever worktree_path was stored relative (as it
# normally is in real usage, e.g. ".worktrees/task-<id>"). Only an
# absolute worktree_path happened to work by accident. Fixed by resolving
# relative paths against REPO_ROOT explicitly (restoring the case-statement
# semantics originally reviewed in commit 45b3fe51).

def test_hook_allows_commit_from_relative_registered_worktree(tmp_path):
    """A: relative registered worktree path + commit from that worktree -> PASS."""
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-relwt-pass-011"
    branch = "feat/relwt-pass"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    # Free `branch` from the main checkout so it can be checked out in the
    # new worktree (git disallows the same branch in two checkouts at once).
    subprocess.run(["git", "checkout", "main"], cwd=str(repo), check=True, capture_output=True)
    worktree_dir = repo / ".worktrees" / "relwt-pass"
    subprocess.run(
        ["git", "worktree", "add", str(worktree_dir), branch],
        cwd=str(repo), check=True, capture_output=True,
    )
    # Register the DB path exactly as real usage does: repository-relative.
    cp.update_worktree(task_id, ".worktrees/relwt-pass", branch, "written_in_worktree")

    code_file = worktree_dir / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(worktree_dir), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(worktree_dir), capture_output=True, text=True)
    assert res.returncode == 0, res.stdout + res.stderr


def test_hook_blocks_commit_from_main_checkout_when_relative_worktree_registered(tmp_path):
    """B: relative registered worktree path + commit from main checkout -> BLOCK."""
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-relwt-block-012"
    branch = "feat/relwt-block"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    # Register an isolated worktree path that is never actually populated with
    # this commit -- the commit below happens from the main checkout instead,
    # which still has `branch` checked out (git's own worktree exclusivity
    # means the same branch cannot be checked out twice, so the main checkout
    # is the realistic stand-in for "wrong location" here).
    cp.update_worktree(task_id, ".worktrees/relwt-block", branch, "written_in_worktree")

    code_file = repo / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 1
    assert "Commit Outside Registered Worktree" in res.stdout


def test_hook_allows_commit_from_absolute_registered_worktree(tmp_path):
    """C: absolute registered worktree path + commit from that worktree -> PASS."""
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-abswt-pass-013"
    branch = "feat/abswt-pass"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    subprocess.run(["git", "checkout", "main"], cwd=str(repo), check=True, capture_output=True)
    worktree_dir = repo / ".worktrees" / "abswt-pass"
    subprocess.run(
        ["git", "worktree", "add", str(worktree_dir), branch],
        cwd=str(repo), check=True, capture_output=True,
    )
    cp.update_worktree(task_id, str(worktree_dir), branch, "written_in_worktree")

    code_file = worktree_dir / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(worktree_dir), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(worktree_dir), capture_output=True, text=True)
    assert res.returncode == 0, res.stdout + res.stderr


def test_hook_blocks_commit_from_main_checkout_when_absolute_worktree_registered(tmp_path):
    """D: absolute registered worktree path + commit from the wrong checkout -> BLOCK."""
    repo, db_path = _setup_git_repo_with_db(tmp_path)
    task_id = "task-abswt-block-014"
    branch = "feat/abswt-block"
    subprocess.run(["git", "checkout", "-b", branch], cwd=str(repo), check=True, capture_output=True)

    cp = ControlPlane(db_path=db_path)
    _advance_task_to_in_worktree(cp, task_id, repo, branch)

    worktree_dir = repo / ".worktrees" / "abswt-block"
    cp.update_worktree(task_id, str(worktree_dir), branch, "written_in_worktree")
    # Note: worktree_dir is deliberately never created via `git worktree add`
    # here -- the registered absolute path exists only in the DB, and the
    # commit below is attempted from the main checkout (which still holds
    # `branch`), exercising the same "wrong location" path as test B but for
    # an absolute registered path instead of a relative one.

    code_file = repo / "feature.py"
    code_file.write_text("def run(): pass\n", encoding="utf-8")
    subprocess.run(["git", "add", "feature.py"], cwd=str(repo), check=True)

    res = subprocess.run([str(HOOK_PATH)], cwd=str(repo), capture_output=True, text=True)
    assert res.returncode == 1
    assert "Commit Outside Registered Worktree" in res.stdout
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