From 281a8c273440290286db0f109b38644365d395fd Mon Sep 17 00:00:00 2001 From: huangruiteng Date: Wed, 18 Nov 2026 07:09:16 +0800 Subject: [PATCH 1/2] fix(quota): bind turn identity in selection commands Signed-off-by: huangruiteng --- loopx/control_plane/quota/spend_sources.py | 7 ++++--- .../control_plane/test_quota_settlement_cli.py | 17 +++++++++++++---- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/loopx/control_plane/quota/spend_sources.py b/loopx/control_plane/quota/spend_sources.py index 678202f0ac..a48b81b4e8 100644 --- a/loopx/control_plane/quota/spend_sources.py +++ b/loopx/control_plane/quota/spend_sources.py @@ -95,9 +95,10 @@ def host_goal_turn_start_args( profile = scheduler_runtime_profile_for_execution_context(scheduler_execution_context) if profile is SchedulerRuntimeProfile.CODEX_APP_SSH_VISIBLE: return " --begin-turn" - if profile not in VISIBLE_GOAL_SETTLEMENT_RUNTIME_PROFILES: - return "" - # CLI/managed Goal hosts own their iteration identity. + # Every other host owns its iteration identity. This also covers an + # unprofiled/manual guard: an explicit Todo selection must not project a + # follow-up command that the quota validator will reject for lacking a + # Turn identity. return " --turn-instance-id ''" diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index ff10826603..2fff8d9b5f 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -5057,13 +5057,19 @@ def test_begin_turn_rejects_a_non_receipt_runtime_profile(tmp_path: Path) -> Non ) -@pytest.mark.parametrize("profile", ["codex_app_ssh_goal", "codex_cli", "ark_managed_agent_goal"]) -def test_unbound_visible_goal_selection_binds_the_chosen_todo(tmp_path: Path, profile: str) -> None: +@pytest.mark.parametrize( + "profile", + [None, "generic_cli", "codex_app_ssh_goal", "codex_cli", "ark_managed_agent_goal"], +) +def test_unbound_visible_goal_selection_binds_the_chosen_todo( + tmp_path: Path, profile: str | None, +) -> None: project, runtime, registry_path = _write_fixture(tmp_path) _configure_selectable_alternative(project) _initialize_fixture_authority(project, runtime) + profile_args = ("--runtime-profile", profile) if profile else () rc, preview = _run_cli( - registry_path, runtime, "quota", "should-run", "--runtime-profile", profile, + registry_path, runtime, "quota", "should-run", *profile_args, "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, ) assert rc == 0, preview @@ -5083,7 +5089,10 @@ def test_unbound_visible_goal_selection_binds_the_chosen_todo(tmp_path: Path, pr assert bound["interaction_contract"]["agent_channel"]["delivery_allowed"] is True identity = bound["heartbeat_receipt"]["settlement_identity"] assert identity["todo_id"] == ALTERNATIVE_TODO_ID - assert bound["interaction_contract"]["cli_channel"]["settlement_plan"]["identity"] == identity + if profile is None: + assert "settlement_plan" not in bound["interaction_contract"]["cli_channel"] + else: + assert bound["interaction_contract"]["cli_channel"]["settlement_plan"]["identity"] == identity assert _heartbeat_receipt_count(runtime, identity["turn_instance_id"]) == 1 assert _spend_run_count(runtime) == 0 From be6c9572e04c45eed2d46ed98b8ef8167a212940 Mon Sep 17 00:00:00 2001 From: huangruiteng Date: Wed, 18 Nov 2026 14:07:55 +0800 Subject: [PATCH 2/2] fix(quota): preserve selected turn spend source Signed-off-by: huangruiteng --- loopx/cli_commands/quota.py | 7 ++ loopx/cli_commands/quota_should_run.py | 1 + loopx/control_plane/quota/settlement_cli.py | 81 ++++++++++++-- .../test_quota_settlement_cli.py | 104 ++++++++++++++++++ 4 files changed, 181 insertions(+), 12 deletions(-) diff --git a/loopx/cli_commands/quota.py b/loopx/cli_commands/quota.py index b98b9b1ef5..81fca96ca8 100644 --- a/loopx/cli_commands/quota.py +++ b/loopx/cli_commands/quota.py @@ -28,6 +28,9 @@ from .quota_reward_memory import attach_reward_memory_ingest_after_spend if TYPE_CHECKING: + from ..control_plane.scheduler.execution_context import ( + SchedulerExecutionContextResolution, + ) from .quota_action_selection import RequestedQuotaActionSelection from .quota_context import QuotaCommandContext from .quota_should_run import ShouldRunExecutionState @@ -445,6 +448,9 @@ def _execute_quota_command( heartbeat_stall_observation = "not_evaluated" detail_sections: frozenset[str] = frozenset() context: QuotaCommandContext | None = None + scheduler_context: ( + Mapping[str, object] | SchedulerExecutionContextResolution | None + ) = None goal_ref: dict[str, str] | None = None reentry: tuple[argparse.Namespace, str | None] | None = None should_run_state: ShouldRunExecutionState | None = None @@ -639,6 +645,7 @@ def _execute_quota_command( args, todo_id=rollout_todo_id, replan_obligation_id=rollout_replan_obligation_id, + scheduler_execution_context=scheduler_context, ) if heartbeat_turn_id and args.quota_command == "should-run": from .quota_should_run import record_should_run_heartbeat_receipt diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index dd79c10c7a..a1f5c6335a 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -459,6 +459,7 @@ def execute_quota_should_run( turn_instance_id=heartbeat_turn_id, existing=execution.heartbeat_receipt_existing, goal_ref=goal_ref, + scheduler_execution_context=context.scheduler_context, ) else: ( diff --git a/loopx/control_plane/quota/settlement_cli.py b/loopx/control_plane/quota/settlement_cli.py index 7972cf955e..108db13045 100644 --- a/loopx/control_plane/quota/settlement_cli.py +++ b/loopx/control_plane/quota/settlement_cli.py @@ -7,6 +7,7 @@ from collections.abc import Mapping from pathlib import Path +from ..scheduler.execution_context import SchedulerExecutionContextResolution from ..todos.contract import ( normalize_todo_id, normalize_todo_replan_obligation_id, @@ -35,6 +36,7 @@ build_delivery_workspace_causality, delivery_workspace_causality_event_fields, ) +from .spend_sources import quota_spend_source_for_execution_context def reconcile_existing_heartbeat_receipt( @@ -45,6 +47,9 @@ def reconcile_existing_heartbeat_receipt( turn_instance_id: str, existing: dict[str, object], goal_ref: Mapping[str, object] | None = None, + scheduler_execution_context: ( + Mapping[str, object] | SchedulerExecutionContextResolution | None + ) = None, ) -> tuple[dict[str, object], str, bool, str]: """Bind or qualify same-Turn work without replacing its settlement identity.""" @@ -140,8 +145,13 @@ def reconcile_existing_heartbeat_receipt( "heartbeat receipt effect identity does not match its " "persisted settlement binding" ) - rollout_details = quota_rollout_details(payload, args, - todo_id=rollout_todo_id, replan_obligation_id=rollout_replan_obligation_id) + rollout_details = quota_rollout_details( + payload, + args, + todo_id=rollout_todo_id, + replan_obligation_id=rollout_replan_obligation_id, + scheduler_execution_context=scheduler_execution_context, + ) rollout_details["settlement_effect_id"] = expected_effect_id replan_packet = ( payload.get("replan_action_packet") @@ -182,6 +192,7 @@ def reconcile_existing_heartbeat_receipt( args, todo_id=rollout_todo_id, replan_obligation_id=rollout_replan_obligation_id, + scheduler_execution_context=scheduler_execution_context, ) receipt, upgraded = upgrade_identityless_heartbeat_receipt( runtime_root, @@ -219,6 +230,9 @@ def reconcile_existing_heartbeat_receipt_for_turn( turn_instance_id: str, existing: dict[str, object], goal_ref: Mapping[str, object] | None = None, + scheduler_execution_context: ( + Mapping[str, object] | SchedulerExecutionContextResolution | None + ) = None, ) -> tuple[dict[str, object], str, bool, str, bool]: """Reconcile an existing receipt and report whether the turn is receipt-ready.""" @@ -229,6 +243,7 @@ def reconcile_existing_heartbeat_receipt_for_turn( turn_instance_id=turn_instance_id, existing=existing, goal_ref=goal_ref, + scheduler_execution_context=scheduler_execution_context, ) return receipt, status, appended, stall_observation, True @@ -372,12 +387,54 @@ def quota_rollout_replan_obligation_id( return replan_obligation_id +def _cli_rollout_details( + payload: Mapping[str, object], + args: argparse.Namespace, + *, + cli_channel: object, + todo_id: str | None, + replan_obligation_id: str | None, + scheduler_execution_context: ( + Mapping[str, object] | SchedulerExecutionContextResolution | None + ), +) -> dict[str, object]: + details: dict[str, object] = {} + if ( + isinstance(cli_channel, Mapping) + and cli_channel.get("selection_required") is True + and payload.get("ok") is True + and payload.get("should_run") is True + and not todo_id + and not replan_obligation_id + ): + details["selection_required"] = True + spend_source = ( + cli_channel.get("quota_spend_source") + if isinstance(cli_channel, Mapping) + else None + ) + if not spend_source and args.quota_command == "should-run" and ( + todo_id or replan_obligation_id + ): + # An explicit selection can bind a Turn before its hard lease creates a + # settlement plan. Preserve the host source for post-claim readback. + spend_source = quota_spend_source_for_execution_context( + scheduler_execution_context + ) + if spend_source: + details["quota_spend_source"] = spend_source + return details + + def quota_rollout_details( payload: Mapping[str, object], args: argparse.Namespace, *, todo_id: str | None, replan_obligation_id: str | None = None, + scheduler_execution_context: ( + Mapping[str, object] | SchedulerExecutionContextResolution | None + ) = None, ) -> dict[str, object]: successor_todo_ids = ( payload.get("successor_todo_ids") @@ -516,16 +573,16 @@ def quota_rollout_details( details["semantic_replan_gap_id"] = capability_guard["gap_id"] details["semantic_replan_frontier_revision"] = capability_guard["frontier_revision"] cli_channel = interaction.get("cli_channel") - if ( - isinstance(cli_channel, Mapping) - and cli_channel.get("selection_required") is True - and payload.get("ok") is True - and payload.get("should_run") is True - and not todo_id and not replan_obligation_id - ): - details["selection_required"] = True - if isinstance(cli_channel, Mapping) and cli_channel.get("quota_spend_source"): - details["quota_spend_source"] = cli_channel["quota_spend_source"] + details.update( + _cli_rollout_details( + payload, + args, + cli_channel=cli_channel, + todo_id=todo_id, + replan_obligation_id=replan_obligation_id, + scheduler_execution_context=scheduler_execution_context, + ) + ) retained_todo_id = normalize_todo_id(retained_selection.get("retained_todo_id")) if retained_todo_id: retained_bound = retained_disposition == "preserve_retained_todo" diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index 2fff8d9b5f..78865ae1a2 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -5097,6 +5097,110 @@ def test_unbound_visible_goal_selection_binds_the_chosen_todo( assert _spend_run_count(runtime) == 0 +def test_visible_goal_selection_before_hard_lease_preserves_spend_source( + tmp_path: Path, +) -> None: + project, runtime, registry_path = _write_fixture(tmp_path) + _configure_selectable_alternative(project) + _initialize_fixture_authority(project, runtime, handoff_mode="hard_lease") + + preview_rc, preview = _run_cli( + registry_path, + runtime, + "quota", + "should-run", + "--runtime-profile", + "codex_app_ssh_goal", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + ) + assert preview_rc == 0, preview + selection = preview["interaction_contract"]["cli_channel"]["selection_command"] + command = ( + selection["route_prefix"] + " " + selection["command_args_template"] + ).replace("{todo_id}", ALTERNATIVE_TODO_ID) + + selected_rc, selected = _run_generated_cli(command, registry_path=registry_path) + assert selected_rc == 0, selected + assert selected["execution_preparation"]["state"] == "claim_required" + identity = selected["heartbeat_receipt"]["settlement_identity"] + turn_instance_id = identity["turn_instance_id"] + receipt_events = _heartbeat_receipt_events(runtime, turn_instance_id) + assert receipt_events[-1]["details"]["quota_spend_source"] == "visible-goal" + + claim_rc, claim = _run_cli( + registry_path, + runtime, + "todo", + "claim", + "--goal-id", + GOAL_ID, + "--todo-id", + ALTERNATIVE_TODO_ID, + "--agent-id", + AGENT_ID, + "--claimed-by", + AGENT_ID, + ) + assert claim_rc == 0 and claim["execution_managed"] is True, claim + ready_rc, ready = _run_cli( + registry_path, + runtime, + "quota", + "should-run", + "--runtime-profile", + "codex_app_ssh_goal", + "--goal-id", + GOAL_ID, + "--todo-id", + ALTERNATIVE_TODO_ID, + "--agent-id", + AGENT_ID, + "--turn-instance-id", + turn_instance_id, + ) + assert ready_rc == 0, ready + assert ready["execution_preparation"]["state"] == "ready" + + refresh_rc, refresh = _run_cli( + registry_path, + runtime, + "refresh-state", + "--goal-id", + GOAL_ID, + "--todo-id", + ALTERNATIVE_TODO_ID, + "--agent-id", + AGENT_ID, + "--turn-instance-id", + turn_instance_id, + "--classification", + "visible_goal_hard_lease_progress", + "--delivery-batch-scale", + "single_surface", + "--delivery-outcome", + "outcome_progress", + "--delivery-boundary", + "in_flight_continuation", + "--delivery-workspace-path", + str(project), + "--progress-result-class", + "advanced", + "--progress-work-item-id", + ALTERNATIVE_TODO_ID, + "--progress-evidence-id", + "evidence:visible-goal-hard-lease", + "--no-global-sync", + "--suppress-external-sinks", + cwd=project, + ) + assert refresh_rc == 0, refresh + assert refresh["settlement_progress"]["quota_spend_source"] == "visible-goal" + assert "--source visible-goal" in refresh["settlement_owed"]["command"] + + @pytest.mark.parametrize("profile", ["generic_cli", "outer_controller", "codex_cli"]) def test_host_owned_turn_executes_projected_selection_and_replays_identity( tmp_path: Path, profile: str,