From 634002f1ce9595541b6cf8b2d8bd63b027aca4c2 Mon Sep 17 00:00:00 2001 From: BigDataDZ <76271875+BigDataDZ@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:18:14 +0800 Subject: [PATCH 1/2] fix(turn): refuse a run-once preparation claim that was not consumed When a should-run decision advertises a managed claim before work and the builtin run-once bridge declines it, the flow previously fell through to the generic not-host-executable rejection. A bounded caller then retried the identical blocked route without ever invoking the Host. Refuse with a typed boundary instead: the run-once packet now carries status=execution_preparation_required with the turn_execution_preparation _claim_not_consumed reason code, the advertised claim command and the bound Todo, and exits without host invocation or quota spend. The existing consumption path, its admission wait and the ready postcondition are unchanged. Signed-off-by: BigDataDZ <76271875+BigDataDZ@users.noreply.github.com> --- loopx/cli_commands/turn.py | 22 +++++++ .../codex_execution_preparation.py | 30 +++++++++ .../test_turn_run_once_claim_preparation.py | 66 +++++++++++++++++++ 3 files changed, 118 insertions(+) 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" From 4c0d1e0bf412817175ba90ab51b99b6585ccb6d7 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:21:54 +0800 Subject: [PATCH 2/2] Keep run-once preparation refusal scoped to Codex CLI Leave native App Server preparation on its existing path. Render a typed execution refusal with the verified claim and readiness requirement when the builtin CLI cannot prepare work. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/cli_commands/turn.py | 30 ++--- loopx/cli_commands/turn_rendering.py | 8 ++ .../codex_execution_preparation.py | 122 ++++++++++-------- .../test_turn_run_once_claim_preparation.py | 90 +++++++++---- tests/test_native_steward_turn_host.py | 30 +++++ 5 files changed, 178 insertions(+), 102 deletions(-) diff --git a/loopx/cli_commands/turn.py b/loopx/cli_commands/turn.py index c9cb0a1aa3..41180c0a08 100644 --- a/loopx/cli_commands/turn.py +++ b/loopx/cli_commands/turn.py @@ -139,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(), @@ -150,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: @@ -363,27 +370,6 @@ 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/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 328c7ccc8b..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,34 +375,29 @@ 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. - """ - +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 - 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 + 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: 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 cf75b511ec..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,7 +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": "loopx todo claim --goal-id " + GOAL + " --thin", + "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": ( @@ -324,11 +325,12 @@ def test_unconsumed_preparation_refusal_names_the_advertised_claim() -> None: unconsumed_preparation_refusal, ) - refusal = unconsumed_preparation_refusal(_decision()) + decision = _decision() + refusal = unconsumed_preparation_refusal(decision, goal_id=GOAL, agent_id=AGENT) 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") + 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: @@ -336,16 +338,36 @@ def test_unconsumed_preparation_refusal_leaves_other_states_alone() -> None: 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 + 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, + tmp_path: Path, monkeypatch, provider: str, output_format: str, ) -> None: import contextlib import io @@ -355,30 +377,50 @@ def test_run_once_refuses_typed_when_the_builtin_claim_is_not_consumed( 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") + 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: list[int] = [] + declined = [] monkeypatch.setattr( codex_execution_preparation, "builtin_execution_preparation_claim", - lambda *args, **kwargs: declined.append(1) or None, + 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", + "--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", ]) - 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") + 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)