Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions loopx/cli_commands/turn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] 已持租约的 App Server 任务在执行前被拒绝。 拒绝分支进入两种 Host 共用的代码块;helper 只在 builtin CLI 的分支导入。File 和 SQLite 的原生 Steward 测试中,基线均完成并结算,候选两条 ready 路径均报未绑定局部变量,Host 未启动、额度未扣。需要领租约的原生路径仍通过;另一个独立反例也证实原生回调拒绝从原受控阻断变成异常。 将新拒绝限定在 builtin Codex CLI 实际安装的准备回调,原生回调沿用既有拒绝路径;若确有共用需求,让 adapter 提供明确的处置结果并先验证两条路径。

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 默认终端没有给出申领恢复动作,JSON 则用成功计划表示拒绝。 两库中退出码都为 1。显式 JSON 有原因和命令,却仍是 ok=true 的 loopx_turn_plan_v1;默认 Markdown 只显示 Turn Plan / blocked,省掉状态、原因和命令。成功计划读法与拒绝的机器退出语义冲突,终端用户也仍得再查 guard。 沿用现有 run-once 执行结果及渲染边界输出明确未执行、非成功的准备拒绝。只在原 guard 授权并绑定准确身份时展示原命令及就地复核要求,保留零 Host/零扣额。

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"}
Expand Down
30 changes: 30 additions & 0 deletions loopx/control_plane/turn_driver/codex_execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
66 changes: 66 additions & 0 deletions tests/control_plane/test_turn_run_once_claim_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": (
Expand Down Expand Up @@ -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"
Loading