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
7 changes: 7 additions & 0 deletions loopx/cli_commands/quota.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions loopx/cli_commands/quota_should_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
(
Expand Down
81 changes: 69 additions & 12 deletions loopx/control_plane/quota/settlement_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand All @@ -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."""

Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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."""

Expand All @@ -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

Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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"
Expand Down
7 changes: 4 additions & 3 deletions loopx/control_plane/quota/spend_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 '<unique-work-iteration-id-reuse-on-retry>'"


Expand Down
121 changes: 117 additions & 4 deletions tests/control_plane/test_quota_settlement_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -5083,11 +5089,118 @@ 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


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,
Expand Down
Loading