diff --git a/loopx/cli_commands/quota.py b/loopx/cli_commands/quota.py index b98b9b1ef5..22985998b1 100644 --- a/loopx/cli_commands/quota.py +++ b/loopx/cli_commands/quota.py @@ -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, @@ -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 @@ -269,7 +267,6 @@ def _prepare_quota_result_context( args, registry_path=registry_path, heartbeat_turn_id=heartbeat_turn_id, - capture_directory=capture_directory, ) diff --git a/loopx/cli_commands/quota_presentation.py b/loopx/cli_commands/quota_presentation.py index 8069f612b0..278ce35319 100644 --- a/loopx/cli_commands/quota_presentation.py +++ b/loopx/cli_commands/quota_presentation.py @@ -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]: diff --git a/loopx/cli_commands/quota_result_delivery.py b/loopx/cli_commands/quota_result_delivery.py index 8a967607d1..0054760a7b 100644 --- a/loopx/cli_commands/quota_result_delivery.py +++ b/loopx/cli_commands/quota_result_delivery.py @@ -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, @@ -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, @@ -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: @@ -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, @@ -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. diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 91cf79b146..1b2a3eb1ea 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -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( diff --git a/loopx/control_plane/quota/settlement_plan.ts b/loopx/control_plane/quota/settlement_plan.ts index b2f36e91c0..c338df35f5 100644 --- a/loopx/control_plane/quota/settlement_plan.ts +++ b/loopx/control_plane/quota/settlement_plan.ts @@ -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"; @@ -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. diff --git a/tests/control_plane/test_cli_program_route.py b/tests/control_plane/test_cli_program_route.py index e2d0f51f6e..1b0f401644 100644 --- a/tests/control_plane/test_cli_program_route.py +++ b/tests/control_plane/test_cli_program_route.py @@ -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: diff --git a/tests/control_plane/test_quota_execution_preparation.py b/tests/control_plane/test_quota_execution_preparation.py index d52d284c7d..1d1f0f3a6f 100644 --- a/tests/control_plane/test_quota_execution_preparation.py +++ b/tests/control_plane/test_quota_execution_preparation.py @@ -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. @@ -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 @@ -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) diff --git a/tests/control_plane/test_selection_replan_reentry.py b/tests/control_plane/test_selection_replan_reentry.py index 9657289ad8..ec6142289b 100644 --- a/tests/control_plane/test_selection_replan_reentry.py +++ b/tests/control_plane/test_selection_replan_reentry.py @@ -439,7 +439,9 @@ def reconcile_then_change_gate(*args, **kwargs): @pytest.mark.parametrize("discovery", [False, True]) -def test_first_inline_result_has_matching_turn_envelope(tmp_path, discovery): +def test_first_inline_result_binds_the_complete_replan_contract(tmp_path, discovery): + from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision + project, runtime, registry = _write_fixture(tmp_path) _configure_selected_todo_replan_fixture(project, registry) _initialize_fixture_authority(project, runtime, provider="sqlite") @@ -450,17 +452,22 @@ def test_first_inline_result_has_matching_turn_envelope(tmp_path, discovery): if discovery: rc, first = _run_cli(registry, runtime, *guard) assert rc == 0 and first["interaction_contract"]["cli_channel"]["selection_required"] - rc, envelope = _run_cli(registry, runtime, *guard, + rc, decision = _run_cli(registry, runtime, *guard, "--todo-id", SELECTED_REPLAN_TODO_ID, "--turn-envelope") - assert rc == 0, envelope - assert envelope["action_signature"]["matches"] is True - contract = envelope["contract_capsule"]["interaction_contract"] + assert rc == 0, decision + assert_complete_turn_decision(decision) + contract = decision["interaction_contract"] assert contract["mode"] == "autonomous_replan" - assert envelope["action"]["must_attempt"] is True - assert envelope["contract_capsule"]["execution_obligation"]["kind"] == "autonomous_replan_required" - binding = envelope["writeback"]["replan_settlement_contract"]["settlement_binding"] + assert contract["agent_channel"]["must_attempt"] is True + assert contract["agent_channel"]["delivery_allowed"] is False + assert decision["execution_obligation"]["kind"] == "autonomous_replan_required" + channel = contract["cli_channel"] + binding = channel["replan_settlement_contract"]["settlement_binding"] assert binding == {"kind": "todo", "id": SELECTED_REPLAN_TODO_ID, "cli_argument": "--todo-id"} - assert envelope["writeback"]["spend_allowed_now"] is False + identity = channel["settlement_plan"]["identity"] + assert identity == decision["heartbeat_receipt"]["settlement_identity"] + assert identity["todo_id"] == SELECTED_REPLAN_TODO_ID and identity["turn_instance_id"] == turn + assert channel["spend_allowed_now"] is False assert _heartbeat_receipt_count(runtime, turn) == (3 if discovery else 1) assert _spend_run_count(runtime) == 0 diff --git a/tests/control_plane_ts/quota_settlement_plan.test.ts b/tests/control_plane_ts/quota_settlement_plan.test.ts index 4ef030a059..e1b076f97c 100644 --- a/tests/control_plane_ts/quota_settlement_plan.test.ts +++ b/tests/control_plane_ts/quota_settlement_plan.test.ts @@ -3,7 +3,7 @@ import test from "node:test"; import {settlementPlanPayload} from "../../loopx/control_plane/effect_program.ts"; import {visionAuthoringContract} from "../../loopx/control_plane/goals/vision_checkpoint.ts"; import {projectMcpInteraction} from "../../loopx/control_plane/turn_driver/host_interaction.ts"; -import {completeCliSettlementChannel, composedCliSettlementChannel, nativeCliSettlementProjection, turnScopedCliSettlementPlan, turnScopedCliSettlementPlanPayload} +import {completeCliSettlementChannel, turnScopedCliSettlementPlan, turnScopedCliSettlementPlanPayload} from "../../loopx/control_plane/quota/settlement_plan.ts"; import {EXECUTION_PREPARATION_SCHEMA_VERSION} from "../../loopx/control_plane/work_items/execution_preparation.ts"; import {DELIVERY_OUTCOMES, decodeOptionalDeliveryOutcome, isTurnScopedSettlementOutcome} @@ -42,66 +42,51 @@ test("current Todo continuation composes the same plan and preserves historical assert.throws(() => turnScopedCliSettlementPlanPayload({...input, composed_settlement}), /must be a boolean/); }); -test("native settlement only replaces matching executable steps on the original ready Turn", () => { +test("complete consumers compose only the exact executable settlement plan", () => { const plan = settlementPlanPayload(turnScopedCliSettlementPlan(input)); - const preparation = {schema_version: EXECUTION_PREPARATION_SCHEMA_VERSION, state: "ready", - todo_id: "todo", agent_id: "agent", delivery_allowed: true}; - const cli = {settlement_plan: plan, execution_preparation: preparation, spend_after_validation: true, + const cli = {settlement_plan: plan, spend_after_validation: true, next_cli_actions: ["supporting action", "writeback", "spend"]}; - const receipt = {status: "upgraded", closeout_required: true, turn_instance_id: "turn", + const receipt = {status: "committed", closeout_required: true, turn_instance_id: "turn", settlement_identity: plan.identity}; - const request = {cli, receipt, todo_id: "todo"}; - for (const status of ["committed", "upgraded", "replayed"]) - assert.ok(Array.isArray(nativeCliSettlementProjection({...request, receipt: {...receipt, status}}).changes)); - const projected = composedCliSettlementChannel(cli); - assert.deepEqual(projected.next_cli_actions, ["supporting action", "writeback --settle-turn --settlement-receipt"]); - assert.equal((projected.settlement_plan as typeof plan).identity, plan.identity); - for (const changed of [ - {todo_id: "other"}, - {receipt: {...receipt, turn_instance_id: "other"}}, - {receipt: {...receipt, settlement_identity: {...plan.identity as object, effect_id: "changed"}}}, - {receipt: {...receipt, settlement_binding_owed: true}}, - {receipt: {...receipt, closeout_required: false}}, - {receipt: {...receipt, status: "pending"}}, - {cli: {...cli, execution_preparation: {...preparation, state: "claim_required"}}}, - {cli: {...cli, spend_after_validation: false}}, - {cli: {...cli, next_cli_actions: ["spend", "writeback"]}}, - {cli: {...cli, next_cli_actions: ["writeback", "spend", "spend"]}}, - ]) assert.deepEqual(nativeCliSettlementProjection({...request, ...changed}), {}); - assert.deepEqual(cli.next_cli_actions, ["supporting action", "writeback", "spend"]); -}); - -test("complete consumers compose the original admitted CLI plan without inventing readiness", () => { - const plan = settlementPlanPayload(turnScopedCliSettlementPlan(input)); - const cli = {settlement_plan: plan, spend_after_validation: true, - next_cli_actions: ["writeback", "spend"]}; + const interaction = {agent_channel: {delivery_allowed: true}, cli_channel: cli}; const source = {goal_id: "goal", agent_identity: {agent_id: "agent"}, selected_todo: {todo_id: "todo"}, should_run: true, effective_action: "normal_run", normal_delivery_allowed: true, - interaction_contract: {agent_channel: {delivery_allowed: true}, cli_channel: cli}, - heartbeat_receipt: {status: "committed", closeout_required: true, turn_instance_id: "turn", - settlement_identity: plan.identity}}; + interaction_contract: interaction, heartbeat_receipt: receipt}; const before = structuredClone(source); - assert.deepEqual(completeCliSettlementChannel(source).next_cli_actions, - ["writeback --settle-turn --settlement-receipt"]); const prepared = {schema_version: EXECUTION_PREPARATION_SCHEMA_VERSION, state: "ready", todo_id: "todo", agent_id: "agent", delivery_allowed: true}; - for (const execution_preparation of [prepared, undefined]) { - const channel = {...cli, ...(execution_preparation ? {execution_preparation} : {})}; - assert.equal((completeCliSettlementChannel({...source, interaction_contract: { - ...source.interaction_contract, cli_channel: channel}}).settlement_plan as typeof plan).schema_version, - "quota_settlement_plan_v2"); - } - for (const changed of [{goal_id: "other"}, {agent_identity: {agent_id: "other"}}, - {selected_todo: {todo_id: "other"}}, {normal_delivery_allowed: false}, {should_run: false}, - {effective_action: "replan_required"}, {heartbeat_receipt: {...source.heartbeat_receipt, settlement_binding_owed: true}}, - {heartbeat_receipt: {...source.heartbeat_receipt, settlement_identity: {...plan.identity as object, turn_instance_id: "other"}}}]) { - assert.equal(completeCliSettlementChannel({...source, ...changed}), cli); + + for (const status of ["committed", "upgraded", "replayed"]) { + for (const channel of [cli, {...cli, execution_preparation: prepared}]) { + const projected = completeCliSettlementChannel({...source, + interaction_contract: {...interaction, cli_channel: channel}, heartbeat_receipt: {...receipt, status}}); + const projectedPlan = projected.settlement_plan as typeof plan; + assert.equal(projectedPlan.schema_version, "quota_settlement_plan_v2"); + assert.deepEqual(projectedPlan.identity, plan.identity); + assert.deepEqual(projected.next_cli_actions, ["supporting action", "writeback --settle-turn --settlement-receipt"]); + } } - for (const execution_preparation of [null, "ready", {}, {...prepared, state: "claim_required"}, - {...prepared, todo_id: "other"}, {...prepared, delivery_allowed: false}]) { - const channel = {...cli, execution_preparation}; - assert.equal(completeCliSettlementChannel({...source, interaction_contract: { - ...source.interaction_contract, cli_channel: channel}}), channel); + + for (const changed of [ + {goal_id: "other"}, {agent_identity: {agent_id: "other"}}, {selected_todo: {todo_id: "other"}}, + {normal_delivery_allowed: false}, {should_run: false}, {effective_action: "replan_required"}, + {interaction_contract: {...interaction, agent_channel: {delivery_allowed: false}}}, + {heartbeat_receipt: {...receipt, turn_instance_id: "other"}}, + {heartbeat_receipt: {...receipt, settlement_identity: {...plan.identity as object, effect_id: "changed"}}}, + {heartbeat_receipt: {...receipt, settlement_binding_owed: true}}, + {heartbeat_receipt: {...receipt, closeout_required: false}}, {heartbeat_receipt: {...receipt, status: "pending"}}, + ]) assert.equal(completeCliSettlementChannel({...source, ...changed}), cli); + + for (const changes of [ + {selection_required: true}, {spend_after_validation: false}, + {next_cli_actions: ["spend", "writeback"]}, {next_cli_actions: ["writeback", "spend", "spend"]}, + ...[null, "ready", {}, {...prepared, state: "claim_required"}, {...prepared, todo_id: "other"}, + {...prepared, agent_id: "other"}, {...prepared, delivery_allowed: false}] + .map(execution_preparation => ({execution_preparation})), + ]) { + const channel = {...cli, ...changes}; + assert.equal(completeCliSettlementChannel({...source, + interaction_contract: {...interaction, cli_channel: channel}}), channel); } assert.deepEqual(source, before); });