diff --git a/loopx/cli_commands/turn.py b/loopx/cli_commands/turn.py index 7bbf6e0205..c9cb0a1aa3 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 @@ -362,6 +363,27 @@ def read_decision_owner(): or (decision.get("selected_todo") or {}).get("todo_id") != prepared_todo or decision.get("normal_delivery_allowed") is not True): raise ValueError(preparation_error) + else: + refusal = unconsumed_preparation_refusal(decision) + if refusal is not None: + # The advertised claim was not consumed, so this route + # stays blocked. Refuse with the typed action boundary + # instead of the generic not-host-executable rejection + # a bounded caller would otherwise retry identically. + blocked_plan = build_loopx_turn_plan( + decision, host=args.host, execution_mode=args.execution_mode, + scheduler_owner=args.scheduler_owner, session_binding=session_binding, + turn_instance_id=args.turn_instance_id, iteration_context_policy=args.iteration_context, + session_scope=args.session_scope, goal_ref=goal_ref, + ) + transaction = blocked_plan.get("transaction") + if isinstance(transaction, dict): + transaction.pop("settlement_plan", None) + blocked_plan.update(mode="run_once", status="execution_preparation_required", + execute=True, executed=False, **refusal) + project_preparation_effects(blocked_plan) + print_payload(blocked_plan, output_format(args), _render_loopx_turn_plan_markdown) + return 1 # Operation-equipped app-server sessions retain their Todo-bound # approval/handoff contract; this option controls exec conversation reuse. session_scope = (args.session_scope if args.host in {"codex-cli", "codex-app-server"} diff --git a/loopx/control_plane/turn_driver/codex_execution_preparation.py b/loopx/control_plane/turn_driver/codex_execution_preparation.py index 8648adaefb..328c7ccc8b 100644 --- a/loopx/control_plane/turn_driver/codex_execution_preparation.py +++ b/loopx/control_plane/turn_driver/codex_execution_preparation.py @@ -360,6 +360,36 @@ def before_bind() -> None: return todo_id +def unconsumed_preparation_refusal(decision: Mapping[str, Any]) -> dict[str, Any] | None: + """Typed refusal when an advertised preparation claim was not consumed. + + The builtin run-once bridge only executes the exact ordinary claim a + decision published as Host-executable. When it declines, the caller must + not be sent back into the generic not-host-executable rejection: that + route stays blocked and identical retries never invoke the Host. Surface + the advertised claim and a typed reason so a bounded caller can act. + """ + + preparation = decision.get("execution_preparation") + if not isinstance(preparation, Mapping) or preparation.get("state") != "claim_required": + return None + claim = preparation.get("claim") + command = claim.get("command_line") if isinstance(claim, Mapping) else None + refusal: dict[str, Any] = { + "reason_code": "turn_execution_preparation_claim_not_consumed", + "todo_id": preparation.get("todo_id"), + "message": ( + "This should-run decision advertised a managed claim before work, but the " + "builtin run-once preparation did not consume it, so the Turn route stays " + "blocked. Execute the advertised claim or repair why it was not consumed; " + "retrying this route repeats the same refusal without invoking the Host." + ), + } + if isinstance(command, str) and command.strip(): + refusal["claim_command"] = command + return refusal + + 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..cf75b511ec 100644 --- a/tests/control_plane/test_turn_run_once_claim_preparation.py +++ b/tests/control_plane/test_turn_run_once_claim_preparation.py @@ -44,6 +44,7 @@ def _decision(*, state: str = "claim_required", host_execution_allowed: bool = T "reason_code": "task_lease_missing", "claim": { "command": "loopx todo claim", + "command_line": "loopx todo claim --goal-id " + GOAL + " --thin", "cli_args": advertised if cli_args is None else cli_args, "host_execution_allowed": host_execution_allowed, "postcondition": ( @@ -316,3 +317,68 @@ 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, + ) + + refusal = unconsumed_preparation_refusal(_decision()) + assert refusal is not None + assert refusal["reason_code"] == "turn_execution_preparation_claim_not_consumed" + assert refusal["todo_id"] == TODO + assert refusal["claim_command"].startswith("loopx todo claim") + + +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")) is None + assert unconsumed_preparation_refusal({"ok": True}) is None + without_command = _decision() + without_command["execution_preparation"]["claim"] = {"host_execution_allowed": False} + refusal = unconsumed_preparation_refusal(without_command) + assert refusal is not None and "claim_command" not in refusal + + +def test_run_once_refuses_typed_when_the_builtin_claim_is_not_consumed( + tmp_path: Path, monkeypatch, +) -> 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, handoff_mode="hard_lease") + native, marker = _fake_codex(tmp_path) + monkeypatch.setenv("FAKE_CODEX_LOG", str(marker)) + declined: list[int] = [] + monkeypatch.setattr( + codex_execution_preparation, + "builtin_execution_preparation_claim", + lambda *args, **kwargs: declined.append(1) or None, + ) + output = io.StringIO() + with contextlib.redirect_stdout(output): + code = main([ + "--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", + "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", + ]) + packet = json.loads(output.getvalue()) + assert code == 1, packet + assert declined == [1], packet + assert packet.get("status") == "execution_preparation_required", packet + assert packet["reason_code"] == "turn_execution_preparation_claim_not_consumed" + assert "todo claim" in packet["claim_command"] + effects = packet.get("effects") or {} + assert not effects.get("quota_spent") and not effects.get("state_written") + assert not marker.exists(), "the Host must not be invoked on a refused preparation"