Skip to content
Merged
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
3 changes: 0 additions & 3 deletions loopx/cli_commands/quota.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from ..usage_goal import observe_quota_result as observe_quota_result # noqa: PLC0414
from .quota_capture import handle_native_context_command, prepare_quota_capture
from .quota_presentation import (
_project_native_cli_settlement as _project_native_cli_settlement,
_project_quota_cli_payload as _project_quota_cli_payload,
_quota_renderer as _quota_renderer,
project_scheduler_observation as project_scheduler_observation,
Expand Down Expand Up @@ -260,7 +259,6 @@ def _prepare_quota_result_context(
*,
registry_path: Path,
heartbeat_turn_id: str | None,
capture_directory: Path | None,
) -> tuple[dict[str, object], dict[str, Any]]:
from .quota_result_delivery import prepare_quota_result_context

Expand All @@ -269,7 +267,6 @@ def _prepare_quota_result_context(
args,
registry_path=registry_path,
heartbeat_turn_id=heartbeat_turn_id,
capture_directory=capture_directory,
)


Expand Down
24 changes: 0 additions & 24 deletions loopx/cli_commands/quota_presentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,6 @@ def compose_quota_work_contract(payload: dict[str, object], args: argparse.Names
) from exc


def _project_native_cli_settlement(payload: dict[str, object]) -> dict[str, object]:
"""Publish one projected plan before capability binding and capture."""
from ..control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError, effect_runtime_result
from ..control_plane.quota.turn_envelope import _apply_context_projection_changes

interaction = payload.get("interaction_contract")
cli = interaction.get("cli_channel") if isinstance(interaction, Mapping) else None
todo = payload.get("selected_todo")
if not isinstance(cli, Mapping) or not isinstance(todo, Mapping):
return payload
try:
projection = effect_runtime_result("settlement.native_cli_projection", {
"cli": cli, "receipt": payload.get("heartbeat_receipt"), "todo_id": todo.get("todo_id"),
})
except (EffectRuntimeRemoteError, EffectRuntimeStartupError):
# The already admitted Turn still has its canonical manual plan.
return payload
if not projection:
return payload
return {**payload, "interaction_contract": {
**interaction, "cli_channel": _apply_context_projection_changes(dict(cli), projection),
}}


def project_scheduler_observation(payload: Mapping[str, object]) -> dict[str, object]:
"""Select existing scheduling and recovery facts; do not decide a wake here."""
def select(source: object, *keys: str) -> dict[str, object]:
Expand Down
25 changes: 1 addition & 24 deletions loopx/cli_commands/quota_result_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@

import argparse
from collections.abc import Callable, Mapping
from os import getenv
from pathlib import Path
from typing import TYPE_CHECKING, Any

from ..control_plane.quota.effective_action import EffectiveAction
from ..control_plane.quota.error_codes import (
QuotaCommandValidationError,
QuotaDecisionTransportError,
Expand All @@ -30,7 +28,6 @@
)
from .quota_presentation import (
compose_quota_work_contract,
_project_native_cli_settlement,
_project_quota_cli_payload,
_quota_renderer,
project_scheduler_observation,
Expand Down Expand Up @@ -84,9 +81,8 @@ def prepare_quota_result_context(
*,
registry_path: Path,
heartbeat_turn_id: str | None,
capture_directory: Path | None,
) -> tuple[dict[str, object], dict[str, Any]]:
"""Prepare current settlement and capability binding before publishing it."""
"""Resolve presentation and attach recall before composing the work contract."""
try:
activation = native_context_activation(args)
except QuotaCommandValidationError:
Expand All @@ -95,24 +91,6 @@ def prepare_quota_result_context(
# Keep the original diagnostic on a refused guard.
activation = {"progressive_enabled": False, "enabled": False}
if args.quota_command == "should-run":
if (
args.format == "json"
and capture_directory is not None
and activation["progressive_enabled"]
and activation.get("scenario") == "codex_app_heartbeat"
and (
getenv("CODEX_THREAD_ID")
or getattr(args, "prepared_capture_reference", False)
)
and (
getattr(args, "codex_context_dir", None)
or getattr(args, "codex_context_root", None)
)
and payload.get("ok") is True
and payload.get("effective_action") == EffectiveAction.NORMAL_RUN.value
and payload.get("normal_delivery_allowed") is True
):
payload = _project_native_cli_settlement(payload)
attach_reward_memory_recall_after_should_run(
payload,
quota_command=args.quota_command,
Expand Down Expand Up @@ -275,7 +253,6 @@ def _publish_quota_result(
args,
registry_path=registry_path,
heartbeat_turn_id=heartbeat_turn_id,
capture_directory=capture_directory,
)
# Compose optional capability guidance after recovery has chosen the plan,
# before capture/compaction. The quota decision owner stays capability-neutral.
Expand Down
2 changes: 0 additions & 2 deletions loopx/control_plane/effect_runtime_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -816,8 +816,6 @@ export function createEffectRuntimeHandlers(
],
["settlement.turn_scoped_cli_plan", lazyHandler(() => import("./quota/settlement_plan.ts"),
({turnScopedCliSettlementPlanPayload}) => turnScopedCliSettlementPlanPayload)],
["settlement.native_cli_projection", lazyHandler(() => import("./quota/settlement_plan.ts"),
({nativeCliSettlementProjection}) => nativeCliSettlementProjection)],
[
"settlement.result_payload",
(params) => settlementResultPayload(
Expand Down
55 changes: 21 additions & 34 deletions loopx/control_plane/quota/settlement_plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {DELIVERY_BOUNDARIES} from "../turn_driver/delivery_continuity.ts";
import {PROGRESS_RESULT_CLASSES} from "../work_items/replan_history.ts";
import {HANDOFF_MODES} from "../coordination/handoff_mode_vocabulary.ts";
import {EXECUTION_PREPARATION_SCHEMA_VERSION} from "../work_items/execution_preparation.ts";
import {contextProjectionChanges} from "./diagnostic_projection.ts";
import {EffectiveAction} from "./effective_action.generated.ts";

export const COMPOSED_CLI_SETTLEMENT_PLAN_SCHEMA_VERSION = "quota_settlement_plan_v2";
Expand Down Expand Up @@ -51,45 +50,33 @@ export function composedCliSettlementChannel(cli: JsonObject): JsonObject {
.map(command => command === writebackCommand ? newWriteback.command_template : command)};
}

/** The heartbeat publisher uses only its current admitted Todo and exact receipt. */
function receiptBoundCliSettlement(params: JsonObject, requirePreparation: boolean): JsonObject | null {
const cli = jsonObject(params.cli), receipt = jsonObject(params.receipt);
const preparation = jsonObject(cli?.execution_preparation);
const identity = jsonObject(jsonObject(cli?.settlement_plan)?.identity);
if (!cli || (Object.hasOwn(cli, "execution_preparation") && !preparation)
|| cli.selection_required === true || cli.spend_after_validation !== true
|| ((preparation || requirePreparation) && (preparation?.schema_version !== EXECUTION_PREPARATION_SCHEMA_VERSION
|| preparation.state !== "ready" || preparation.delivery_allowed !== true))
|| receipt?.closeout_required !== true
|| receipt.settlement_binding_owed === true
// Claiming within the original Turn can requalify its receipt.
|| (receipt.status !== "committed" && receipt.status !== "upgraded" && receipt.status !== "replayed")
|| !identity || typeof params.todo_id !== "string" || !params.todo_id || params.todo_id !== identity.todo_id
|| typeof identity.turn_instance_id !== "string" || receipt.turn_instance_id !== identity.turn_instance_id
|| (preparation && (preparation.todo_id !== identity.todo_id || preparation.agent_id !== identity.agent_id))
|| !isDeepStrictEqual(identity, receipt.settlement_identity)) return null;
return composedCliSettlementChannel(cli);
}

export function nativeCliSettlementProjection(params: JsonObject): JsonObject {
const cli = jsonObject(params.cli), composed = receiptBoundCliSettlement(params, true);
return !cli || !composed || composed === cli ? {} : contextProjectionChanges(cli, composed);
}

/** Explicit complete-contract consumers use the same decided plan and receipt.
* A soft claim has no preparation record; an existing non-ready record never
* disappears. The later writeback and spend still perform their own checks. */
/** Compose the existing CLI plan for the exact admitted Turn. A soft claim
* has no preparation record. A present preparation must prove readiness. */
export function completeCliSettlementChannel(payload: JsonObject): JsonObject {
const cli = jsonObject(jsonObject(payload.interaction_contract)?.cli_channel) ?? {};
const interaction = jsonObject(payload.interaction_contract);
const cli = jsonObject(interaction?.cli_channel) ?? {};
const identity = jsonObject(jsonObject(cli.settlement_plan)?.identity);
if (payload.should_run !== true || payload.effective_action !== EffectiveAction.NORMAL_RUN
|| payload.normal_delivery_allowed !== true
|| jsonObject(jsonObject(payload.interaction_contract)?.agent_channel)?.delivery_allowed !== true
|| jsonObject(interaction?.agent_channel)?.delivery_allowed !== true
|| !identity || identity.goal_id !== payload.goal_id
|| identity.agent_id !== jsonObject(payload.agent_identity)?.agent_id) return cli;
const composed = receiptBoundCliSettlement({cli, receipt: payload.heartbeat_receipt,
todo_id: jsonObject(payload.selected_todo)?.todo_id}, false);
return composed ?? cli;

const receipt = jsonObject(payload.heartbeat_receipt);
const preparation = jsonObject(cli.execution_preparation);
const todoId = jsonObject(payload.selected_todo)?.todo_id;
if ((Object.hasOwn(cli, "execution_preparation") && !preparation)
|| cli.selection_required === true || cli.spend_after_validation !== true
|| (preparation && (preparation.schema_version !== EXECUTION_PREPARATION_SCHEMA_VERSION
|| preparation.state !== "ready" || preparation.delivery_allowed !== true
|| preparation.todo_id !== identity.todo_id || preparation.agent_id !== identity.agent_id))
|| receipt?.closeout_required !== true || receipt.settlement_binding_owed === true
// Claiming within the original Turn can requalify its receipt.
|| (receipt.status !== "committed" && receipt.status !== "upgraded" && receipt.status !== "replayed")
|| typeof todoId !== "string" || !todoId || todoId !== identity.todo_id
|| typeof identity.turn_instance_id !== "string" || receipt.turn_instance_id !== identity.turn_instance_id
|| !isDeepStrictEqual(identity, receipt.settlement_identity)) return cli;
return composedCliSettlementChannel(cli);
}

/** Current continuation commands share the complete source's composition.
Expand Down
55 changes: 22 additions & 33 deletions tests/control_plane/test_cli_program_route.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,43 +153,32 @@ def run(argv, *, expected_code=0):
"--no-global-sync", "--suppress-external-sinks",
]
spend_step = steps["quota_spend"]
if handoff_mode == "hard_lease":
assert plan["schema_version"] == "quota_settlement_plan_v2"
assert spend_step["owner"] == "runtime"
assert "command_template" not in spend_step
assert all("spend-slot" not in shlex.split(action) for action in channel["next_cli_actions"])
assert {"--settle-turn", "--settlement-receipt"} <= set(refresh_argv)
else:
assert spend_step["owner"] == "agent"
assert plan["schema_version"] == "quota_settlement_plan_v2"
assert plan["identity"] == identity
assert spend_step["owner"] == "runtime"
assert "command_template" not in spend_step
assert all("spend-slot" not in shlex.split(action) for action in channel["next_cli_actions"])
assert {"--settle-turn", "--settlement-receipt"} <= set(refresh_argv)

refreshed = run(refresh_argv)
assert refreshed["vision_checkpoint"]["satisfied"]
if handoff_mode == "hard_lease":
assert refreshed["settlement_result"]["ok"]
receipts = refreshed["settlement_result"]["receipts"]
assert [receipt["step_kind"] for receipt in receipts] == [
"validation", "durable_writeback", "quota_spend",
]
assert all(
receipt["effect_id"] == identity["effect_id"] and receipt["status"] == "committed"
for receipt in receipts
)
assert refreshed["quota_spend"]["appended"]
first = refreshed
settle_argv = refresh_argv
else:
assert cli._spend_run_count(runtime) == 0
settle_argv = shlex.split(refreshed["settlement_owed"]["command"])
assert settle_argv[0] == program
first = run(settle_argv)
first = run(refresh_argv)
assert first["vision_checkpoint"]["satisfied"]
assert first["settlement_result"]["ok"]
receipts = first["settlement_result"]["receipts"]
assert [receipt["step_kind"] for receipt in receipts] == [
"validation", "durable_writeback", "quota_spend",
]
assert all(
receipt["effect_id"] == identity["effect_id"] and receipt["status"] == "committed"
for receipt in receipts
)
assert first["quota_spend"]["appended"]
assert first["settlement_identity"] == identity
assert first["settlement_progress"]["state"] == "settled" and first["appended"]
assert cli._spend_run_count(runtime) == 1
replay = run(settle_argv)
replay = run(refresh_argv)
assert replay["idempotent_replay"] and not replay["appended"]
assert first["settlement_identity"] == identity
if handoff_mode == "hard_lease":
assert replay["settlement_identity"] == identity
assert replay["settlement_result"] == first["settlement_result"]
assert replay["settlement_identity"] == identity
assert replay["settlement_result"] == first["settlement_result"]
assert cli._spend_run_count(runtime) == 1
assert cli._classification_count(runtime, "validated_progress") == 1
if lease:
Expand Down
34 changes: 24 additions & 10 deletions tests/control_plane/test_quota_execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,14 +436,14 @@ def test_native_hook_returns_readable_ready_source_and_original_claim(
assert selected["/heartbeat_receipt"]["turn_instance_id"] == "preparation-turn"
plan = selected["/interaction_contract/cli_channel"]["settlement_plan"]
assert plan["identity"]["todo_id"] == TODO and plan["identity"]["turn_instance_id"] == "preparation-turn"
assert plan["schema_version"] == (
"quota_settlement_plan_v2" if scenario == "codex_app_heartbeat" else "quota_settlement_plan_v1"
)
if scenario == "codex_app_heartbeat":
writeback, spend = [step for step in plan["ordered_steps"]
if step["kind"] in {"durable_writeback", "quota_spend"}]
assert "--settle-turn --settlement-receipt" in writeback["command_template"]
assert spend["owner"] == "runtime" and "command_template" not in spend
assert plan["identity"] == selected["/heartbeat_receipt"]["settlement_identity"]
assert plan["schema_version"] == "quota_settlement_plan_v2"
channel = selected["/interaction_contract/cli_channel"]
assert channel["quota_spend_source"] == ("heartbeat" if scenario == "codex_app_heartbeat" else "visible-goal")
writeback, spend = [step for step in plan["ordered_steps"]
if step["kind"] in {"durable_writeback", "quota_spend"}]
assert "--settle-turn --settlement-receipt" in writeback["command_template"]
assert spend["owner"] == "runtime" and "command_template" not in spend
sources = selected["/interaction_contract/agent_channel/work_context"]["sources"]
task = next(item["content"]["todo"] for item in sources if item["source"] == "selected_todo")
# The v0 owner may deduplicate short text already in selected_todo.
Expand Down Expand Up @@ -494,10 +494,17 @@ def test_native_hook_returns_readable_ready_source_and_original_claim(
readback_command = shlex.split(readback["context"]["recovery_command"])
observed = subprocess.run(readback_command, cwd=tmp_path, capture_output=True, text=True, timeout=30)
assert observed.returncode == 0, observed.stderr
projection = json.loads(observed.stdout)
assert projection["ok"] and projection["sha256"] == readback["capture_sha256"]
# C1 verifies the saved contract before offering its original reader.
# Successful projection alone does not show any source bytes were read.
reader = shlex.split(projection["recovery"]["command"])
observed = subprocess.run(reader, cwd=tmp_path, capture_output=True, text=True, timeout=30)
assert observed.returncode == 0, observed.stderr
ready_page = json.loads(observed.stdout)
assert ready_page["ok"] and ready_page["sha256"] == readback["capture_sha256"]
forged = {**ready_page, "content": "x" + ready_page["content"][1:]}
for observation, should_repeat in ((forged, True), (ready_page, False)):
for observation, should_repeat in ((projection, True), (forged, True), (ready_page, False)):
shown = subprocess.run(hook, input=json.dumps({**hook_event, "tool_response": observation}),
env=hook_env, cwd=tmp_path, capture_output=True, text=True, timeout=30)
assert shown.returncode == 0, shown.stderr
Expand Down Expand Up @@ -746,7 +753,14 @@ def read(*args):
presented_capture.mkdir(mode=0o700)
copy = presented_capture / "decision.json"
if legacy:
copy.write_text(json.dumps({**json.loads(original_bytes), "native_claim_replay_bound": True}))
# This fixture tests the former unsigned carrier. Editing the
# current signed source would stop at its integrity check,
# before the legacy marker's lack of a live guard is tested.
historical = json.loads(original_bytes)
assert historical.pop("schema_version") == "loopx_turn_envelope_v1"
historical.pop("contract_binding")
historical["native_claim_replay_bound"] = True
copy.write_text(json.dumps(historical))
else:
copy.write_bytes(original_bytes + b" ")
copy.chmod(0o600)
Expand Down
Loading
Loading