diff --git a/loopx/cli_commands/turn.py b/loopx/cli_commands/turn.py index 7bbf6e0205..41180c0a08 100644 --- a/loopx/cli_commands/turn.py +++ b/loopx/cli_commands/turn.py @@ -106,6 +106,7 @@ def project_preparation_effects(value: dict[str, Any]) -> None: ): from ..control_plane.turn_driver.codex_execution_preparation import ( builtin_execution_preparation_claim, + unconsumed_preparation_refusal, ) from .turn_host_request import prepare_turn_host_arguments @@ -138,7 +139,7 @@ def record_claim(receipt: Mapping[str, Any]) -> None: preparation_error = "execution preparation did not make the same Todo ready" def execution_preparer(decision: Mapping[str, Any]) -> str | None: - return builtin_execution_preparation_claim( + prepared_todo = builtin_execution_preparation_claim( decision, agent_id=args.agent_id, registry_path=registry_path.expanduser().resolve(), @@ -149,6 +150,13 @@ def execution_preparer(decision: Mapping[str, Any]) -> str | None: admit_start=admit_preparation, on_claim=record_claim, ) + if prepared_todo is None and preparation_admission is None: + refusal = unconsumed_preparation_refusal( + decision, goal_id=args.goal_id, agent_id=args.agent_id, + ) + if refusal is not None: + raise refusal + return prepared_todo resume_instance = getattr(args, "resume_turn_instance_id", None) if resume_instance is not None: diff --git a/loopx/cli_commands/turn_rendering.py b/loopx/cli_commands/turn_rendering.py index c480835c0f..d783a451ee 100644 --- a/loopx/cli_commands/turn_rendering.py +++ b/loopx/cli_commands/turn_rendering.py @@ -259,6 +259,14 @@ def render_loopx_turn_execution_markdown(payload: dict[str, object]) -> str: f"- quota_spent: {effects.get('quota_spent')}", *_turn_start_observation_lines(payload), *([f"- error: {payload['error']}"] if payload.get("error") else []), + *( + [ + f"- reason: {payload['error_code']}", + *([f"- claim_command: {payload['claim_command']}", + f"- next_step: {payload['next_step']}"] if payload.get("claim_command") else []), + ] + if payload.get("status") == "execution_preparation_required" else [] + ), *([f"- journal_readback: {journal_observation.get('status')}", f"- recorded_effects: {journal_observation.get('recorded_effects')}", f"- recovery_from: {(journal_observation.get('recovery_decision') or {}).get('resume_from')}", diff --git a/loopx/control_plane/turn_driver/codex_execution_preparation.py b/loopx/control_plane/turn_driver/codex_execution_preparation.py index 8648adaefb..8628e2fe31 100644 --- a/loopx/control_plane/turn_driver/codex_execution_preparation.py +++ b/loopx/control_plane/turn_driver/codex_execution_preparation.py @@ -181,6 +181,16 @@ class ExecutionPreparationClaimFailed(ValueError): } +class UnconsumedExecutionPreparationClaim(ValueError): + """The builtin adapter could not prepare a required managed claim.""" + + code = "turn_execution_preparation_claim_not_consumed" + + def __init__(self, recovery: Mapping[str, str]) -> None: + super().__init__("The builtin CLI did not claim the Todo required to run this Turn.") + self.payload = {"status": "execution_preparation_required", "executed": False, **recovery} + + def _exact_identity(value: object) -> str | None: """Keep a decision identity exact; display normalization cannot stand in for it.""" if isinstance(value, str) and value and value == value.strip(): @@ -188,29 +198,9 @@ def _exact_identity(value: object) -> str | None: return None -def builtin_execution_preparation_claim( - decision: Mapping[str, Any], - *, - agent_id: str, - registry_path: Path, - runtime_root: Path, - cwd: Path, - turn_instance_id: str | None = None, - goal_ref: Mapping[str, object] | None = None, - runner: CommandRunner | None = None, - timeout: float = 30, - admit_start: Callable[[SettlementIdentity], bool] | None = None, - on_claim: Callable[[Mapping[str, Any]], None] | None = None, -) -> str | None: - """Execute the exact ordinary claim a decision advertised for a Host. - - The decision stays the owner of readiness: this adapter runs only the - claim the decision already published as Host-executable, then the caller - re-reads the same decision and must observe the same Todo ready. A - preparation this adapter does not recognise is left untouched so its - original typed wait keeps its meaning. - """ - +def _builtin_claim_identity( + decision: Mapping[str, Any], agent_id: str, +) -> tuple[str, str, str, list[str]] | None: preparation = decision.get("execution_preparation") selected = decision.get("selected_todo") if not isinstance(preparation, Mapping) or not isinstance(selected, Mapping): @@ -236,10 +226,6 @@ def builtin_execution_preparation_claim( decision_agent_id = ( _exact_identity(declared_agent) if declared_agent is not None else identity_agent_id ) - expected_claim = [ - "todo", "claim", "--goal-id", goal_id, "--todo-id", todo_id, - "--agent-id", caller_agent_id, "--claimed-by", caller_agent_id, - ] if ( preparation.get("schema_version") != "execution_preparation_v0" or preparation.get("delivery_allowed") is not False @@ -255,12 +241,41 @@ def builtin_execution_preparation_claim( or preparation_agent_id != caller_agent_id or (selected_agent is not None and selected_agent_id != caller_agent_id) or (identity_agent is not None and identity_agent_id != caller_agent_id) - or claim.get("cli_args") != expected_claim - or not registry_path.is_absolute() - or not runtime_root.is_absolute() - or not cwd.is_absolute() ): return None + expected_claim = [ + "todo", "claim", "--goal-id", goal_id, "--todo-id", todo_id, + "--agent-id", caller_agent_id, "--claimed-by", caller_agent_id, + ] + if claim.get("cli_args") != expected_claim: + return None + return goal_id, caller_agent_id, todo_id, expected_claim + + +def builtin_execution_preparation_claim( + decision: Mapping[str, Any], + *, + agent_id: str, + registry_path: Path, + runtime_root: Path, + cwd: Path, + turn_instance_id: str | None = None, + goal_ref: Mapping[str, object] | None = None, + runner: CommandRunner | None = None, + timeout: float = 30, + admit_start: Callable[[SettlementIdentity], bool] | None = None, + on_claim: Callable[[Mapping[str, Any]], None] | None = None, +) -> str | None: + """Execute the exact ordinary claim a decision advertised for a Host. + + The decision stays the owner of readiness: this adapter runs only the + claim the decision already published as Host-executable, then the caller + re-reads the same decision and must observe the same Todo ready. + """ + claim_identity = _builtin_claim_identity(decision, agent_id) + if claim_identity is None or not all(path.is_absolute() for path in (registry_path, runtime_root, cwd)): + return None + goal_id, caller_agent_id, todo_id, expected_claim = claim_identity heartbeat = decision.get("heartbeat_receipt") # Resolve one Turn identity before reading a receipt or running the claim. # The transaction plan applies the same normalization, so a padded or @@ -360,6 +375,31 @@ def before_bind() -> None: return todo_id +def unconsumed_preparation_refusal( + decision: Mapping[str, Any], *, goal_id: str, agent_id: str, +) -> UnconsumedExecutionPreparationClaim | None: + """Surface only a claim the exact builtin adapter could accept.""" + preparation = decision.get("execution_preparation") + if not isinstance(preparation, Mapping) or preparation.get("state") != "claim_required": + return None + recovery: dict[str, str] = {} + identity = _builtin_claim_identity(decision, agent_id) + if identity is not None and identity[0] == goal_id: + _, _, todo_id, argv = identity + command = shlex.join(["loopx", *argv, "--thin"]) + if preparation["claim"].get("command_line") == command: + recovery = { + "todo_id": todo_id, + "claim_command": command, + "next_step": ( + "Use the same registry and runtime options for the claim. " + "Rerun quota should-run for the same Goal, agent, Todo, and Turn, " + "and continue only when execution_preparation.state is ready." + ), + } + return UnconsumedExecutionPreparationClaim(recovery) + + def _native_claim_operation_id(request: Mapping[str, Any]) -> str: """Reuse the captured managed claim identity on an authorized retry.""" digest = request.get("claim_source_sha256") diff --git a/tests/control_plane/test_turn_run_once_claim_preparation.py b/tests/control_plane/test_turn_run_once_claim_preparation.py index 47692a920e..74f3f14295 100644 --- a/tests/control_plane/test_turn_run_once_claim_preparation.py +++ b/tests/control_plane/test_turn_run_once_claim_preparation.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import shlex import subprocess from pathlib import Path @@ -44,6 +45,7 @@ def _decision(*, state: str = "claim_required", host_execution_allowed: bool = T "reason_code": "task_lease_missing", "claim": { "command": "loopx todo claim", + "command_line": shlex.join(["loopx", *advertised, "--thin"]), "cli_args": advertised if cli_args is None else cli_args, "host_execution_allowed": host_execution_allowed, "postcondition": ( @@ -316,3 +318,109 @@ def test_a_legacy_unstarted_cadence_reservation_recovers_without_a_second_start( migrated.confirm() duplicate = migrated.admit(attempt) assert duplicate["admitted"] is False and duplicate["reason"] == "duplicate_or_stale_trigger" + + +def test_unconsumed_preparation_refusal_names_the_advertised_claim() -> None: + from loopx.control_plane.turn_driver.codex_execution_preparation import ( + unconsumed_preparation_refusal, + ) + + decision = _decision() + refusal = unconsumed_preparation_refusal(decision, goal_id=GOAL, agent_id=AGENT) + assert refusal is not None + assert refusal.code == "turn_execution_preparation_claim_not_consumed" + assert refusal.payload["todo_id"] == TODO + assert refusal.payload["claim_command"] == decision["execution_preparation"]["claim"]["command_line"] + + +def test_unconsumed_preparation_refusal_leaves_other_states_alone() -> None: + from loopx.control_plane.turn_driver.codex_execution_preparation import ( + unconsumed_preparation_refusal, + ) + + assert unconsumed_preparation_refusal(_decision(state="ready"), goal_id=GOAL, agent_id=AGENT) is None + assert unconsumed_preparation_refusal({"ok": True}, goal_id=GOAL, agent_id=AGENT) is None + + +@pytest.mark.parametrize( + "decision, goal_id, agent_id, altered_command", [ + (_decision(host_execution_allowed=False), GOAL, AGENT, None), + (_decision(todo_id="todo_other"), GOAL, AGENT, None), + (_decision(), "goal-other", AGENT, None), + (_decision(), GOAL, "agent-b", None), + (_decision(), GOAL, AGENT, "loopx todo claim --goal-id goal-other --thin"), + ], +) +def test_unconsumed_preparation_refusal_never_advertises_an_unverified_claim( + decision, goal_id, agent_id, altered_command, +) -> None: + from loopx.control_plane.turn_driver.codex_execution_preparation import ( + unconsumed_preparation_refusal, + ) + if altered_command: + decision["execution_preparation"]["claim"]["command_line"] = altered_command + refusal = unconsumed_preparation_refusal(decision, goal_id=goal_id, agent_id=agent_id) + assert refusal is not None + assert "claim_command" not in refusal.payload and "next_step" not in refusal.payload + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("output_format", ["default", "json"]) +def test_run_once_refuses_typed_when_the_builtin_claim_is_not_consumed( + tmp_path: Path, monkeypatch, provider: str, output_format: str, +) -> None: + import contextlib + import io + + from loopx.cli import main + from loopx.control_plane.turn_driver import codex_execution_preparation + from test_loopx_turn_codex_cli import _fake_codex + from test_loopx_turn_driver import _write_live_fixture + + project, runtime, registry = _write_live_fixture( + tmp_path, provider=provider, handoff_mode="hard_lease", + ) + native, marker = _fake_codex(tmp_path) + monkeypatch.setenv("FAKE_CODEX_LOG", str(marker)) + declined = [] + monkeypatch.setattr( + codex_execution_preparation, + "builtin_execution_preparation_claim", + lambda decision, **kwargs: declined.append(decision["execution_preparation"]["state"]), + ) + output = io.StringIO() + with contextlib.redirect_stdout(output): + code = main([ + "--registry", str(registry), "--runtime-root", str(runtime), + *(["--format", "json"] if output_format == "json" else []), + "turn", "run-once", "--goal-id", "loopx-turn-fixture", "--agent-id", "codex-fixture", + "--host", "codex-cli", "--project", str(project), "--codex-bin", str(native), + "--codex-sandbox", "read-only", "--no-global-sync", "--iteration-context", "fresh", + "--timeout-seconds", "15", "--execute", + ]) + rendered = output.getvalue() + claim_command = ( + "loopx todo claim --goal-id loopx-turn-fixture --todo-id todo_fixture0001 " + "--agent-id codex-fixture --claimed-by codex-fixture --thin" + ) + assert code == 1, rendered + assert declined == ["claim_required"], rendered + if output_format == "json": + packet = json.loads(rendered) + assert packet["schema_version"] == "loopx_turn_execution_v0" + assert packet["ok"] is False and packet["executed"] is False + assert packet["status"] == "execution_preparation_required" + assert packet["error_code"] == "turn_execution_preparation_claim_not_consumed" + assert packet["claim_command"] == claim_command + assert "execution_preparation.state is ready" in packet["next_step"] + assert not any(packet["effects"].values()) + assert "journal_ref" not in packet + else: + assert rendered.startswith("# LoopX Turn Run Once\n") + assert "- status: execution_preparation_required" in rendered + assert "- reason: turn_execution_preparation_claim_not_consumed" in rendered + assert f"- claim_command: {claim_command}" in rendered + assert "execution_preparation.state is ready" in rendered + assert "- host_invoked: False" in rendered + assert "- quota_spent: False" in rendered + assert not marker.exists(), "the Host must not be invoked on a refused preparation" diff --git a/tests/test_native_steward_turn_host.py b/tests/test_native_steward_turn_host.py index e4f272f0f2..f46c251654 100644 --- a/tests/test_native_steward_turn_host.py +++ b/tests/test_native_steward_turn_host.py @@ -255,6 +255,36 @@ def checked_plan(source, *args, **kwargs): service.submit(sid, agent_id=actor["agent_id"], operation_id="local-native-1", todo_id="todo_other") +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_native_preparer_declining_a_claim_keeps_the_native_refusal(steward, tmp_path, monkeypatch, provider): + from loopx.control_plane.turn_driver import codex_execution_preparation + + service, session, actor, _, _, capture = managed_fixture(steward, tmp_path, monkeypatch, provider) + store, runtime, *_ = steward + original_calls = capture.read_bytes() + preparation_states = [] + monkeypatch.setattr( + codex_execution_preparation, + "compact_execution_preparation_request", + lambda decision: preparation_states.append(decision["execution_preparation"]["state"]), + ) + sid = session["session_id"] + accepted, _ = service.submit(sid, agent_id=actor["agent_id"], operation_id="native-declines-claim") + finish(runtime, accepted) + assert preparation_states == ["claim_required"] + results = [ + event["payload"] for event in store.events_after(sid, accepted["turn_id"], None) + if event["kind"] == "native_loopx.result" + ] + result, = results + assert result["ok"] is False + assert result["error"] == "LoopX Turn route is not host executable" + assert "claim_command" not in result + assert not any(result["effects"].values()) + calls = [json.loads(row) for row in capture.read_bytes()[len(original_calls):].splitlines()] + assert not any(call["method"] == "turn/start" for call in calls) + + @pytest.mark.parametrize("fault", ["busy", "queued", "attached", "foreign_goal", "stopped_goal", "private", "native_goal", "unregistered", "host_closed"]) def test_local_managed_session_denials_never_launch_or_accept(steward, tmp_path, monkeypatch, fault): service, session, actor, todo_id, _, capture = managed_fixture(steward, tmp_path, monkeypatch)