From 8b8c50ec748b4aca246e771914763498daec7831 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:36:10 +0800 Subject: [PATCH 1/2] fix(control-plane): stabilize v2.4.0 quota, turn-envelope, and capabilities slice Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../todo-durability-fixture-smoke.py | 2 +- examples/explore-result-layer-smoke.py | 5 +- ...ue-fix-validated-memory-writeback-smoke.py | 81 ++++++++++++++++--- loopx/cli_commands/quota.py | 2 + loopx/cli_commands/quota_context.py | 34 ++++---- loopx/cli_commands/quota_presentation.py | 35 ++++++-- loopx/cli_commands/quota_request.py | 32 +++++--- loopx/cli_commands/quota_result_delivery.py | 41 +++++++++- loopx/cli_commands/quota_reward_memory.py | 3 +- loopx/cli_commands/quota_should_run.py | 15 +++- loopx/cli_commands/turn_decision.py | 11 +++ .../control_plane/collaboration/delegation.ts | 1 + .../quota/execution_preparation.py | 13 ++- loopx/control_plane/quota/settlement_cli.py | 2 +- loopx/control_plane/quota/turn_envelope.py | 20 +++++ loopx/control_plane/quota/turn_envelope.ts | 61 ++++++++++++-- .../test_periodic_report_native_successor.py | 22 +++-- .../test_periodic_report_pending_intent.py | 15 +++- .../test_periodic_report_turn_replan.py | 5 +- .../test_periodic_report_turn_writeback.py | 35 +++++--- ..._quota_turn_envelope_validation_failure.py | 8 +- .../test_acceptance_restoration.py | 4 +- tests/control_plane/test_agent_preferences.py | 5 +- .../test_bound_owner_web_input.py | 4 +- .../test_canonical_todo_writer_isolation.py | 1 + tests/control_plane/test_cli_output_budget.py | 47 +++++++---- .../test_context_delivery_cli.py | 22 +++-- .../test_quota_acceptance_references.py | 36 +++++---- .../test_quota_execution_preparation.py | 6 +- .../test_selected_work_requirements.py | 38 ++++----- .../test_turn_capability_lifecycle.py | 2 +- 31 files changed, 456 insertions(+), 152 deletions(-) diff --git a/examples/control_plane/todo-durability-fixture-smoke.py b/examples/control_plane/todo-durability-fixture-smoke.py index 3c6b3d0d16..56dc8bb4a0 100644 --- a/examples/control_plane/todo-durability-fixture-smoke.py +++ b/examples/control_plane/todo-durability-fixture-smoke.py @@ -167,7 +167,7 @@ def assert_parseable_agent_todos(agent_todos: dict, *, hot_path: bool = False) - if hot_path: assert "first_open_items" not in agent_todos, agent_todos assert agent_todos["payload_compaction"]["schema_version"] == ( - "quota_cli_todo_summary_compaction_v0" + "quota_todo_summary_payload_compaction_v0" ), agent_todos return diff --git a/examples/explore-result-layer-smoke.py b/examples/explore-result-layer-smoke.py index 75bd033443..795cb4aa92 100644 --- a/examples/explore-result-layer-smoke.py +++ b/examples/explore-result-layer-smoke.py @@ -152,7 +152,10 @@ def check_result_log_contract() -> dict[str, object]: mermaid = projection["mermaid"] assert mermaid.startswith("flowchart TD"), mermaid - assert "node_kcg" in mermaid and ":::blocked" in mermaid, mermaid + assert ( + result_log.explore_mermaid_node_id("node_kcg") in mermaid + and ":::blocked" in mermaid + ), mermaid assert "-->|subtopic_of|" in mermaid, mermaid focused = result_log.build_explore_graph_view( diff --git a/examples/issue-fix-validated-memory-writeback-smoke.py b/examples/issue-fix-validated-memory-writeback-smoke.py index d96265761d..33b6691a30 100644 --- a/examples/issue-fix-validated-memory-writeback-smoke.py +++ b/examples/issue-fix-validated-memory-writeback-smoke.py @@ -32,6 +32,47 @@ ) +def _resolve_recovery_ref(repo_root: Path) -> str | None: + symbolic = subprocess.run( + ["git", "symbolic-ref", "--quiet", "HEAD"], + cwd=repo_root, + text=True, + stdout=subprocess.PIPE, + check=False, + ).stdout.strip() + if symbolic: + return symbolic + candidates = subprocess.run( + [ + "git", + "for-each-ref", + "--points-at", + "HEAD", + "--format=%(refname)", + "refs/heads", + "refs/remotes", + "refs/tags", + ], + cwd=repo_root, + text=True, + stdout=subprocess.PIPE, + check=False, + ).stdout.splitlines() + valid = [ + ref.strip() + for ref in candidates + if ref.strip() and 4 <= len(ref.strip()) <= 80 + ] + for preferred in ("refs/remotes/origin/main", "refs/heads/main"): + if preferred in valid: + return preferred + for prefix in ("refs/heads/", "refs/remotes/", "refs/tags/"): + for ref in valid: + if ref.startswith(prefix): + return ref + return None + + REVISION = subprocess.run( ["git", "rev-parse", "HEAD"], cwd=ROOT, @@ -39,13 +80,7 @@ stdout=subprocess.PIPE, check=True, ).stdout.strip() -RECOVERY_REF = subprocess.run( - ["git", "symbolic-ref", "--quiet", "HEAD"], - cwd=ROOT, - text=True, - stdout=subprocess.PIPE, - check=False, -).stdout.strip() or "refs/remotes/origin/main" +RECOVERY_REF = _resolve_recovery_ref(ROOT) OBSERVED_AT = "2026-07-11T08:40:00+08:00" @@ -700,6 +735,34 @@ def main() -> int: ), encoding="utf-8", ) + repo_path = ROOT + recovery_ref = RECOVERY_REF + if recovery_ref is None: + # Detached HEAD with no matching ref: bind an isolated local ref without mutating ROOT. + repo_path = tmp / "detached-recovery-repo" + subprocess.run( + ["git", "clone", "--quiet", "--shared", "--no-checkout", str(ROOT), str(repo_path)], + check=True, + ) + remotes = subprocess.run( + ["git", "remote"], + cwd=ROOT, + text=True, + stdout=subprocess.PIPE, + check=True, + ).stdout.splitlines() + for name in [item.strip() for item in remotes if item.strip()]: + url = subprocess.run( + ["git", "remote", "get-url", name], + cwd=ROOT, + text=True, + stdout=subprocess.PIPE, + check=True, + ).stdout.strip() + action = "set-url" if name == "origin" else "add" + subprocess.run(["git", "remote", action, name, url], cwd=repo_path, check=True) + recovery_ref = "refs/heads/smoke-recovery" + subprocess.run(["git", "update-ref", recovery_ref, REVISION], cwd=repo_path, check=True) command = [ sys.executable, "-m", @@ -724,9 +787,9 @@ def main() -> int: str(config_path), "--write-repository-memory", "--repo-path", - str(ROOT), + str(repo_path), "--repository-ref", - RECOVERY_REF, + recovery_ref, "--generated-at", OBSERVED_AT, ] diff --git a/loopx/cli_commands/quota.py b/loopx/cli_commands/quota.py index 22985998b1..5f6acd8a2c 100644 --- a/loopx/cli_commands/quota.py +++ b/loopx/cli_commands/quota.py @@ -259,6 +259,7 @@ def _prepare_quota_result_context( *, registry_path: Path, heartbeat_turn_id: str | None, + attach_recall: bool = True, ) -> tuple[dict[str, object], dict[str, Any]]: from .quota_result_delivery import prepare_quota_result_context @@ -267,6 +268,7 @@ def _prepare_quota_result_context( args, registry_path=registry_path, heartbeat_turn_id=heartbeat_turn_id, + attach_recall=attach_recall, ) diff --git a/loopx/cli_commands/quota_context.py b/loopx/cli_commands/quota_context.py index 7c2fde92cd..57630dc136 100644 --- a/loopx/cli_commands/quota_context.py +++ b/loopx/cli_commands/quota_context.py @@ -68,10 +68,14 @@ class QuotaCommandContext: def _scheduler_execution_context_from_args( args: argparse.Namespace, ) -> Mapping[str, object] | SchedulerExecutionContextResolution | None: + host_surface = getattr(args, "host_surface", None) + scheduler_owner = getattr(args, "scheduler_owner", None) + execution_mode = getattr(args, "execution_mode", None) + runtime_profile = getattr(args, "runtime_profile", None) explicit_scheduler_fields = ( - args.host_surface, - args.scheduler_owner, - args.execution_mode, + host_surface, + scheduler_owner, + execution_mode, ) codex_app = bool(getattr(args, "codex_app", False)) trae_app = bool(getattr(args, "trae_app", False)) @@ -81,32 +85,34 @@ def _scheduler_execution_context_from_args( raise QuotaCommandValidationError( "--codex-app, --trae_app, and --antigravity_app are mutually exclusive" ) - if app_alias_count and (args.runtime_profile or any(explicit_scheduler_fields)): + if app_alias_count and (runtime_profile or any(explicit_scheduler_fields)): raise QuotaCommandValidationError( "app runtime aliases cannot be combined with --runtime-profile, " "--host-surface, --scheduler-owner, or --execution-mode" ) - if args.runtime_profile and any(explicit_scheduler_fields): + if runtime_profile and any(explicit_scheduler_fields): raise QuotaCommandValidationError( "--runtime-profile cannot be combined with --host-surface, " "--scheduler-owner, or --execution-mode" ) - runtime_profile = ( + effective_runtime_profile = ( SchedulerRuntimeProfile.CODEX_APP_HEARTBEAT.value if codex_app else SchedulerRuntimeProfile.TRAE_APP.value if trae_app else SchedulerRuntimeProfile.ANTIGRAVITY_APP.value if antigravity_app - else args.runtime_profile + else runtime_profile ) - if runtime_profile: - return scheduler_execution_context_for_runtime_profile(runtime_profile) + if effective_runtime_profile: + return scheduler_execution_context_for_runtime_profile( + effective_runtime_profile + ) if any(explicit_scheduler_fields): return { - "host_surface": args.host_surface, - "scheduler_owner": args.scheduler_owner, - "execution_mode": args.execution_mode, + "host_surface": host_surface, + "scheduler_owner": scheduler_owner, + "execution_mode": execution_mode, "source": "quota_cli_invocation", } return None @@ -180,7 +186,7 @@ def validate_quota_command_context_request( raise QuotaCommandValidationError( "--replan-obligation-id cannot be combined with --todo-id" ) - if heartbeat_turn_id and not args.agent_id: + if heartbeat_turn_id and not getattr(args, "agent_id", None): raise QuotaCommandValidationError( "turn-scoped quota settlement requires --agent-id" ) @@ -266,7 +272,7 @@ def validate_quota_command_context_request( if ( (heartbeat_turn_id or begin_turn) and command == "should-run" - and bool(args.dry_run) + and bool(getattr(args, "dry_run", False)) ): raise QuotaCommandValidationError( "turn-scoped `quota should-run` cannot use --dry-run" diff --git a/loopx/cli_commands/quota_presentation.py b/loopx/cli_commands/quota_presentation.py index 966a3145d6..c6537b0339 100644 --- a/loopx/cli_commands/quota_presentation.py +++ b/loopx/cli_commands/quota_presentation.py @@ -9,6 +9,32 @@ from ..control_plane.scheduler.execution_context import SchedulerExecutionContextResolution +UNDECLARED_JSON_COMPLETE_TURN_OPTIONS = ( + "complete_turn", + "turn_envelope", + "codex_context_dir", + "codex_context_root", + "prepared_capture_reference", + "defer_context_presentation", + "decision_handoff_socket", +) + + +def is_undeclared_json_quota_caller( + args: argparse.Namespace, + scheduler_context: Mapping[str, object] | SchedulerExecutionContextResolution | None, +) -> bool: + """Return True when a JSON caller uses the currently qualified public quota packet.""" + return ( + getattr(args, "format", None) == "json" + and scheduler_context is None + and not any( + getattr(args, option, None) + for option in UNDECLARED_JSON_COMPLETE_TURN_OPTIONS + ) + ) + + def compose_quota_work_contract(payload: dict[str, object], args: argparse.Namespace, *, scheduler_context: Mapping[str, object] | SchedulerExecutionContextResolution | None, capture_directory: Path | None, @@ -16,14 +42,7 @@ def compose_quota_work_contract(payload: dict[str, object], args: argparse.Names """Compose Complete Turn sources before capture and display.""" if args.quota_command != "should-run" or not isinstance(payload.get("interaction_contract"), Mapping): return payload - if ( - args.format == "json" - and scheduler_context is None - and not any(getattr(args, option, None) for option in ( - "complete_turn", "turn_envelope", "codex_context_dir", "codex_context_root", - "prepared_capture_reference", "defer_context_presentation", "decision_handoff_socket", - )) - ): + if is_undeclared_json_quota_caller(args, scheduler_context): # Undeclared JSON callers use the currently qualified public quota packet. return payload from ..control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError diff --git a/loopx/cli_commands/quota_request.py b/loopx/cli_commands/quota_request.py index bab2f66cb4..fef28d6103 100644 --- a/loopx/cli_commands/quota_request.py +++ b/loopx/cli_commands/quota_request.py @@ -126,7 +126,7 @@ def register_quota_monitor_poll_request_arguments( def validate_quota_command_request(args: argparse.Namespace) -> None: command = args.quota_command if getattr(args, "material_change_scope", None) and ( - command != "monitor-poll" or not args.material_change + command != "monitor-poll" or not bool(getattr(args, "material_change", False)) ): raise QuotaCommandValidationError( "--material-change-scope requires quota monitor-poll --material-change" @@ -139,9 +139,13 @@ def validate_quota_command_request(args: argparse.Namespace) -> None: lease_version = getattr(args, "task_lease_expected_version", None) use_current_lease = bool(getattr(args, "use_current_task_lease", False)) if use_current_lease: - if command != "monitor-poll" or not args.execute: + if command != "monitor-poll" or not bool(getattr(args, "execute", False)): raise QuotaCommandValidationError("--use-current-task-lease requires executing quota monitor-poll") - if not args.todo_id or not args.turn_instance_id or not args.agent_id: + if ( + not getattr(args, "todo_id", None) + or not getattr(args, "turn_instance_id", None) + or not getattr(args, "agent_id", None) + ): raise QuotaCommandValidationError( "--use-current-task-lease requires --todo-id, --turn-instance-id, and --agent-id" ) @@ -154,14 +158,14 @@ def validate_quota_command_request(args: argparse.Namespace) -> None: raise QuotaCommandValidationError("task lease proof is only valid with quota monitor-poll") if not lease_key or lease_version is None or lease_version < 1 or lease_version > 9007199254740991: raise QuotaCommandValidationError("Monitor lease proof requires an execution key and positive safe-integer version") - if not (args.todo_id or args.target_key): + if not (getattr(args, "todo_id", None) or getattr(args, "target_key", None)): raise QuotaCommandValidationError("Monitor lease proof requires --todo-id or --target-key") if getattr(args, "delivery_workspace_path", None) is not None and command != "spend-slot": raise QuotaCommandValidationError( "--delivery-workspace-path is only valid with `loopx quota spend-slot`" ) begin_turn = bool(getattr(args, "begin_turn", False)) - if command not in {"status", "plan"} and not args.goal_id: + if command not in {"status", "plan"} and not getattr(args, "goal_id", None): raise QuotaCommandValidationError( f"`loopx quota {command}` requires --goal-id" ) @@ -170,15 +174,19 @@ def validate_quota_command_request(args: argparse.Namespace) -> None: "scheduler-ack-current", "scheduler-fail-current", } - if command in scheduler_commands and not args.agent_id: + if command in scheduler_commands and not getattr(args, "agent_id", None): raise QuotaCommandValidationError( f"`loopx quota {command}` requires --agent-id" ) - if command == "void-slot" and not args.void_generated_at: + if command == "void-slot" and not getattr(args, "void_generated_at", None): raise QuotaCommandValidationError( "`loopx quota void-slot` requires --void-generated-at" ) - if command == "should-run" and args.todo_id and not (args.turn_instance_id or begin_turn): + if ( + command == "should-run" + and getattr(args, "todo_id", None) + and not (getattr(args, "turn_instance_id", None) or begin_turn) + ): raise QuotaCommandValidationError( "`loopx quota should-run --todo-id` requires --turn-instance-id or --begin-turn" ) @@ -186,18 +194,18 @@ def validate_quota_command_request(args: argparse.Namespace) -> None: raise QuotaCommandValidationError( "--begin-turn is only valid with `loopx quota should-run`" ) - if begin_turn and args.turn_instance_id: + if begin_turn and getattr(args, "turn_instance_id", None): raise QuotaCommandValidationError( "--begin-turn cannot be combined with --turn-instance-id" ) - if begin_turn and not args.agent_id: + if begin_turn and not getattr(args, "agent_id", None): raise QuotaCommandValidationError( "--begin-turn requires exact --agent-id identity" ) if ( command not in {"status", "plan", "should-run"} - and args.dry_run - and args.execute + and bool(getattr(args, "dry_run", False)) + and bool(getattr(args, "execute", False)) ): raise QuotaCommandValidationError( f"`loopx quota {command}` accepts only one of --dry-run or --execute" diff --git a/loopx/cli_commands/quota_result_delivery.py b/loopx/cli_commands/quota_result_delivery.py index ccad2d22f9..916901fcdb 100644 --- a/loopx/cli_commands/quota_result_delivery.py +++ b/loopx/cli_commands/quota_result_delivery.py @@ -81,8 +81,9 @@ def prepare_quota_result_context( *, registry_path: Path, heartbeat_turn_id: str | None, + attach_recall: bool = True, ) -> tuple[dict[str, object], dict[str, Any]]: - """Resolve presentation and attach recall before composing the work contract.""" + """Resolve presentation and optionally attach recall before composition.""" try: activation = native_context_activation(args) except QuotaCommandValidationError: @@ -90,7 +91,7 @@ def prepare_quota_result_context( raise # Keep the original diagnostic on a refused guard. activation = {"progressive_enabled": False, "enabled": False} - if args.quota_command == "should-run": + if attach_recall and args.quota_command == "should-run": attach_reward_memory_recall_after_should_run( payload, quota_command=args.quota_command, @@ -253,6 +254,7 @@ def _publish_quota_result( args, registry_path=registry_path, heartbeat_turn_id=heartbeat_turn_id, + attach_recall=False, ) # Compose optional capability guidance after recovery has chosen the plan, # before capture/compaction. The quota decision owner stays capability-neutral. @@ -318,6 +320,7 @@ def _publish_quota_result( "full_decision": context_capture_read_command(source, "", reference_file=source.with_suffix(".reader.json"), reader_argv=reader_argv), }} + pre_contract_decision = payload payload = compose_quota_work_contract( payload, args, @@ -325,6 +328,40 @@ def _publish_quota_result( capture_directory=capture_directory, record_capture=record_capture, ) + if args.quota_command == "should-run": + from ..control_plane.quota.turn_envelope import ( + COMPLETE_TURN_DECISION_VERSION, + attach_complete_turn_context, + ) + + if payload.get("schema_version") == COMPLETE_TURN_DECISION_VERSION: + hook_target = dict(payload) + attach_reward_memory_recall_after_should_run( + hook_target, + quota_command=args.quota_command, + heartbeat_turn_id=heartbeat_turn_id, + registry_path=registry_path, + goal_id=args.goal_id, + agent_id=args.agent_id, + decision=pre_contract_decision, + ) + additions = { + key: value + for key, value in hook_target.items() + if key not in payload + } + if additions: + payload = attach_complete_turn_context(payload, additions) + else: + attach_reward_memory_recall_after_should_run( + payload, + quota_command=args.quota_command, + heartbeat_turn_id=heartbeat_turn_id, + registry_path=registry_path, + goal_id=args.goal_id, + agent_id=args.agent_id, + decision=pre_contract_decision, + ) captured_digest = capture_decision( capture_directory, payload, diff --git a/loopx/cli_commands/quota_reward_memory.py b/loopx/cli_commands/quota_reward_memory.py index 17580d090b..68b33e910d 100644 --- a/loopx/cli_commands/quota_reward_memory.py +++ b/loopx/cli_commands/quota_reward_memory.py @@ -110,6 +110,7 @@ def attach_reward_memory_recall_after_should_run( registry_path: Path, goal_id: str, agent_id: str, + decision: Mapping[str, Any] | None = None, ) -> None: heartbeat_receipt = payload.get("heartbeat_receipt") if ( @@ -128,6 +129,6 @@ def attach_reward_memory_recall_after_should_run( registry_path=registry_path, goal_id=goal_id, agent_id=agent_id, - decision=payload, + decision=payload if decision is None else decision, turn_instance_id=heartbeat_turn_id, ) diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index e65679bdc8..9b4bb4eeb9 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -21,6 +21,7 @@ ) from ..file_lock import LockAcquireTimeoutError from ..rollout_event_log import RolloutAppendPreconditionChanged +from .quota_presentation import is_undeclared_json_quota_caller if TYPE_CHECKING: from .quota_action_selection import RequestedQuotaActionSelection @@ -53,7 +54,9 @@ def dispatch_quota_turn_start_hooks( runtime_root_arg: str | None, lark_turn_start_hook_dispatcher: Callable[..., dict[str, object]] | None = None, ) -> tuple[dict[str, object] | None, bool]: - quota_module._export("validate_quota_command_context_request")(args) + _, scheduler_context, _ = quota_module._export( + "validate_quota_command_context_request" + )(args) if args.quota_command != "should-run": return None, False preview = bool(getattr(args, "dry_run", False)) @@ -96,7 +99,10 @@ def dispatch_quota_turn_start_hooks( ) # A preview still needs the current local Inbox and preferences. These # hooks observe existing context without recording reads or delivery. - model_read = not getattr(args, "scheduler_observation", False) + model_read = ( + not getattr(args, "scheduler_observation", False) + and not is_undeclared_json_quota_caller(args, scheduler_context) + ) context_dispatch = dispatch_turn_start_hooks( ( turn_start_hook( @@ -367,7 +373,10 @@ def execute_quota_should_run( agent_id=args.agent_id, todo_id=args.todo_id, ) - complete_context = not getattr(args, "scheduler_observation", False) + complete_context = ( + not getattr(args, "scheduler_observation", False) + and not is_undeclared_json_quota_caller(args, scheduler_context) + ) payload = export("build_live_quota_should_run_decision")( status_payload, goal_id=args.goal_id, diff --git a/loopx/cli_commands/turn_decision.py b/loopx/cli_commands/turn_decision.py index a1e1de678f..bf54f53947 100644 --- a/loopx/cli_commands/turn_decision.py +++ b/loopx/cli_commands/turn_decision.py @@ -417,9 +417,20 @@ def current_turn_host_launch_decision( ) # Reuse the existing side-effect-free Host route projection, including # delivery, user-gate and protocol checks. No plan/session is persisted. + host = getattr(args, "host", "generic-cli") + session_scope = ( + getattr(args, "session_scope", None) + if host in {"codex-cli", "codex-app-server"} + and not getattr(args, "codex_operation_tools", False) + else "todo" + ) + if host in {"codex-cli", "codex-app-server"} and identity.request_subject is not None: + session_scope = "agent" plan = build_loopx_turn_plan( current_contract, host=args.host, execution_mode=args.execution_mode, scheduler_owner=args.scheduler_owner, turn_instance_id=identity.turn_instance_id, + iteration_context_policy=getattr(args, "iteration_context", "resume"), + session_scope=session_scope, goal_ref=goal_ref, include_selected_work_basis=planned_selected_work_basis is not None, ) route = plan["route"] diff --git a/loopx/control_plane/collaboration/delegation.ts b/loopx/control_plane/collaboration/delegation.ts index 58814c3867..a116c10919 100644 --- a/loopx/control_plane/collaboration/delegation.ts +++ b/loopx/control_plane/collaboration/delegation.ts @@ -236,6 +236,7 @@ export function delegationRequestDecision(params: JsonObject): JsonObject { cli.spend_policy = "spend once after independent request validation and durable writeback"; const contract = requireJsonObject(packet.interaction_contract, "interaction contract"); const agent = requireJsonObject(contract.agent_channel, "agent channel"); + for (const key of ["selection_required", "action_portfolio_ref", "suggested_action_count"]) delete agent[key]; const work = requireJsonObject(agent.work_context, "work context"); if (Array.isArray(work.sources)) work.sources = work.sources.filter(raw => requireJsonObject(raw, "work source").source !== "selected_todo"); diff --git a/loopx/control_plane/quota/execution_preparation.py b/loopx/control_plane/quota/execution_preparation.py index 43e4cea981..4fb044f3e6 100644 --- a/loopx/control_plane/quota/execution_preparation.py +++ b/loopx/control_plane/quota/execution_preparation.py @@ -268,12 +268,21 @@ def apply_selected_todo_execution_preparation( receipt_bound: bool = False, ) -> None: selected = payload.get("selected_todo") + scoped_fallback_admitted = ( + isinstance(payload.get("scoped_user_gate_fallback"), Mapping) + and obligation is not None + and obligation.get("delivery_allowed") is True + ) if ( not isinstance(selected, dict) or payload.get("should_run") is not True # Planning and recovery can retain a Todo without authorizing its - # business execution. Preserve their existing typed route. - or payload.get("normal_delivery_allowed") is not True + # business execution. Preserve their existing typed route, while still + # preparing scoped user-gate fallback work whose delivery is admitted. + or ( + payload.get("normal_delivery_allowed") is not True + and not scoped_fallback_admitted + ) or action_portfolio_requires_explicit_selection(payload) ): return diff --git a/loopx/control_plane/quota/settlement_cli.py b/loopx/control_plane/quota/settlement_cli.py index c73eb4b760..39adb33660 100644 --- a/loopx/control_plane/quota/settlement_cli.py +++ b/loopx/control_plane/quota/settlement_cli.py @@ -551,7 +551,7 @@ def quota_rollout_details( todo_id=todo_id, selected_todo_id=details["selected_todo_id"], agent_id=getattr(args, "agent_id", None), - delivery_admitted=closeout_required and payload.get("normal_delivery_allowed") is True, + delivery_admitted=closeout_required, )) return details diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index 23cf9f685f..9c3f693ac6 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -110,6 +110,10 @@ def _turn_envelope_result( tokens = source_number_tokens(params) if tokens: request["source_number_tokens"] = tokens + if operation == "attach_complete_turn_context" and isinstance(params.get("context_additions"), Mapping): + addition_tokens = source_number_tokens(params["context_additions"]) + if addition_tokens: + request["context_addition_tokens"] = addition_tokens if operation == "capability_automation_source" and set(params) == {"payload"} and isinstance(payload, Mapping): transport = pack_turn_source(payload) if transport is not None: @@ -331,6 +335,22 @@ def compose_turn_decision( return _apply_context_projection_changes(source, result) +def attach_complete_turn_context( + payload: Mapping[str, Any], + context_additions: Mapping[str, Any], +) -> dict[str, Any]: + """Seal validated turn-context fields onto an already-composed decision.""" + source = dict(payload) + additions = dict(context_additions) + result = _turn_envelope_result( + "attach_complete_turn_context", + payload=source, + context_additions=additions, + source_edits=True, + ) + return _apply_context_projection_changes(source, result) + + def is_legacy_saved_quota_decision(payload: Mapping[str, Any]) -> bool: """Recognize saved raw/v0 carriers that predate complete-source checking.""" return ( diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index a39e9e5ba9..9b2de57fb9 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -2046,6 +2046,20 @@ function selectedWorkLaunchBasis(decision: JsonObject, verifiedTextSha256?: stri required_capabilities: selected.required_capabilities ?? []}); } +function sealCompleteTurnDecision( + source: JsonObject, + schedulerExecutionArgs: string, + identity: ReturnType, +): JsonObject { + requireCompleteDecisionSource(source); + const result: JsonObject = {...source, schema_version: COMPLETE_TURN_DECISION_VERSION, + contract_binding: {scheduler_execution_args: schedulerExecutionArgs, + hash_codec: COMPLETE_TURN_HASH_CODEC, + source_decision_hash: completeSourceHash(source, identity)}}; + result.contract_binding = {...object(result.contract_binding), content_hash: completeSourceHash(result, identity)}; + return result; +} + export function composeCompleteTurnDecision(value: unknown): JsonObject { const request = requireJsonObject(value, "complete Turn decision request"); const payload = requireJsonObject(request.payload, "complete Turn decision source"); @@ -2114,13 +2128,41 @@ export function composeCompleteTurnDecision(value: unknown): JsonObject { source = referenceCurrentTaskTitle(source); source = referenceVisionContinuation(source, sourceIdentity); source = referenceQuotaSummaryLanes(source, sourceIdentity); - requireCompleteDecisionSource(source); - const result: JsonObject = {...source, schema_version: COMPLETE_TURN_DECISION_VERSION, - contract_binding: {scheduler_execution_args: request.scheduler_execution_args, - hash_codec: COMPLETE_TURN_HASH_CODEC, - source_decision_hash: completeSourceHash(source, sourceIdentity)}}; - result.contract_binding = {...object(result.contract_binding), content_hash: completeSourceHash(result, sourceIdentity)}; - return result; + return sealCompleteTurnDecision(source, request.scheduler_execution_args, sourceIdentity); +} + +const CONTEXT_ADDITION_FIELD_PATTERN = /^(?:turn_context_contributions|turn_context_hook_failures|[a-z][a-z0-9_]{2,95})$/; + +export function attachCompleteTurnContext(value: unknown): JsonObject { + const request = requireJsonObject(value, "complete Turn context request"); + const decision = requireCompleteTurnDecision(request.payload, request.source_number_tokens); + const schedulerExecutionArgs = object(decision.contract_binding).scheduler_execution_args; + if (typeof schedulerExecutionArgs !== "string") { + throw new EffectRuntimeRequestError("Turn scheduler execution binding must be a string"); + } + const additions = requireJsonObject(request.context_additions, "complete Turn context additions"); + const additionTokens = Array.isArray(request.context_addition_tokens) + ? request.context_addition_tokens : []; + const source: JsonObject = {...decision}; + delete source.schema_version; + delete source.contract_binding; + for (const [key, item] of Object.entries(additions)) { + if (key === "schema_version" || key === "contract_binding" + || !CONTEXT_ADDITION_FIELD_PATTERN.test(key) + || Object.hasOwn(source, key)) { + throw new EffectRuntimeRequestError(`complete Turn context cannot replace or add invalid field: ${key}`); + } + source[key] = item; + } + const combinedTokens = [ + ...(Array.isArray(request.source_number_tokens) ? request.source_number_tokens : []), + ...additionTokens, + ]; + const sourceIdentity = contextSourceIdentity( + source, + combinedTokens.length > 0 ? combinedTokens : undefined, + ); + return sealCompleteTurnDecision(source, schedulerExecutionArgs, sourceIdentity); } export function buildTurnEnvelope(value: unknown): JsonObject { @@ -2628,6 +2670,11 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { return request.source_edits === true ? contextProjectionChanges(requireJsonObject(request.payload, "complete Turn source"), result) : result; } + if (operation === "attach_complete_turn_context") { + const result = attachCompleteTurnContext(request); + return request.source_edits === true + ? contextProjectionChanges(requireJsonObject(request.payload, "complete Turn decision"), result) : result; + } if (operation === "complete_consumer") { requireCompleteTurnDecision(request.payload, request.source_number_tokens); return {ok: true}; diff --git a/tests/capabilities/test_periodic_report_native_successor.py b/tests/capabilities/test_periodic_report_native_successor.py index 7cf667a509..7adaa59c0b 100644 --- a/tests/capabilities/test_periodic_report_native_successor.py +++ b/tests/capabilities/test_periodic_report_native_successor.py @@ -78,13 +78,19 @@ def _native_successor( selected = first_guard["selected_todo"]["todo_id"] bound_guard = _run_cli([*guard, "--todo-id", selected]) assert bound_guard["heartbeat_receipt"]["settlement_identity"]["todo_id"] == selected - review = json.loads(subprocess.check_output( - shlex.split(bound_guard["replan_action_packet"]["review"]), text=True, - )) - writeback = json.loads(subprocess.check_output( - shlex.split(review["next"]["writeback"]), text=True, - )) - assert writeback["obligation_id"] == bound_guard["replan_action_packet"]["obligation_id"] + packet = bound_guard["replan_action_packet"] + if "review" in packet: + review = json.loads(subprocess.check_output( + shlex.split(packet["review"]), text=True, + )) + writeback = json.loads(subprocess.check_output( + shlex.split(review["next"]["writeback"]), text=True, + )) + assert writeback["obligation_id"] == packet["obligation_id"] + stride_decision = writeback["stride_control"]["minimal_example"] + else: + stride_decision = packet["stride_control"]["minimal_example"] + assert stride_decision["reference_obligation_id"] == packet["obligation_id"] successor_vision = { "schema_version": "goal_vision_replan_contract_v0", @@ -101,7 +107,7 @@ def _native_successor( "evidence_refs": ["fixture:accepted-stage-boundary"], "changed": ["Advance the successor fixture check."], }, - "stride_decision": writeback["stride_control"]["minimal_example"], + "stride_decision": stride_decision, } vision_path = project / "successor-vision.json" vision_path.write_text(json.dumps(successor_vision), encoding="utf-8") diff --git a/tests/capabilities/test_periodic_report_pending_intent.py b/tests/capabilities/test_periodic_report_pending_intent.py index ebb89132b2..7c2f0aaba4 100644 --- a/tests/capabilities/test_periodic_report_pending_intent.py +++ b/tests/capabilities/test_periodic_report_pending_intent.py @@ -236,7 +236,7 @@ def test_calendar_reporter_replacement_uses_admitted_window_state(tmp_path, prep @pytest.mark.parametrize( - "change", ["reporter", "schedule", "disabled", "stopped", "activation_stopped"] + "change", ["reporter", "schedule", "disabled", "archived", "activation_stopped"] ) def test_calendar_hook_rechecks_live_authority_after_construction(tmp_path, change): from datetime import datetime @@ -256,8 +256,8 @@ def test_calendar_hook_rechecks_live_authority_after_construction(tmp_path, chan goal["control_plane"]["periodic_report"]["schedule"]["rrule"] = "FREQ=WEEKLY;BYDAY=FR;BYHOUR=17" elif change == "disabled": goal["control_plane"]["periodic_report"]["enabled"] = False - elif change == "stopped": - goal["status"] = "stopped" + elif change == "archived": + goal["status"] = "archived" else: goal["activation"] = { "schema_version": "loopx_goal_activation_v1", @@ -303,6 +303,8 @@ def test_inactive_goal_does_not_reactivate_an_admitted_report(tmp_path, field, v periodic_report_cadence_hooks, ) from loopx.capabilities.periodic_report.cadence_journal import read_cadence_journal + from loopx.control_plane.goals.activation_service import upgrade_goal_activation_registries + from loopx.control_plane.projects.registry_codec import ProjectRegistryProtocolError registry, runtime = _calendar_fixture(tmp_path) kwargs = dict(registry_path=registry, runtime_root=runtime, goal_id=GOAL_ID, agent_id=AGENT_ID) @@ -311,6 +313,13 @@ def test_inactive_goal_does_not_reactivate_an_admitted_report(tmp_path, field, v config = json.loads(registry.read_text()) config["goals"][0][field] = value registry.write_text(json.dumps(config)) + if field == "status" and value in ("stopped", "paused"): + with pytest.raises(ProjectRegistryProtocolError): + periodic_report_cadence_hooks(**kwargs) + with pytest.raises(ProjectRegistryProtocolError): + pending_periodic_report_intents(**kwargs) + assert read_cadence_journal(runtime_root=runtime, goal_id=GOAL_ID) == original + upgrade_goal_activation_registries([registry], execute=True) assert periodic_report_cadence_hooks(**kwargs) == () assert pending_periodic_report_intents(**kwargs) == [] assert consume_pending_periodic_report_intent(**kwargs, execute=True)["status"] == "no_pending_intent" diff --git a/tests/capabilities/test_periodic_report_turn_replan.py b/tests/capabilities/test_periodic_report_turn_replan.py index 3f84402014..08e8fd477a 100644 --- a/tests/capabilities/test_periodic_report_turn_replan.py +++ b/tests/capabilities/test_periodic_report_turn_replan.py @@ -119,8 +119,11 @@ def test_turn_milestone_intent_is_replay_stable( author_candidate = ( "import json, shlex, subprocess\n" f"candidate = {candidate!r}\n" + f"expected_schema = {'loopx_turn_model_context_v0' if host_kind == 'dsh' else 'loopx_turn_host_request_v1'!r}\n" "def authored_candidate(request):\n" - " assert request['schema_version'] == 'loopx_turn_host_request_v1'\n" + " assert request['schema_version'] == expected_schema\n" + " if expected_schema == 'loopx_turn_model_context_v0':\n" + " assert request['source_schema_version'] == 'loopx_turn_host_request_v1'\n" " packet = request['detail_ref']['replan_action_packet']\n" " review = json.loads(subprocess.check_output(\n" " shlex.split(packet['review']), text=True))\n" diff --git a/tests/capabilities/test_periodic_report_turn_writeback.py b/tests/capabilities/test_periodic_report_turn_writeback.py index d7192adab9..cde8507cb6 100644 --- a/tests/capabilities/test_periodic_report_turn_writeback.py +++ b/tests/capabilities/test_periodic_report_turn_writeback.py @@ -94,13 +94,19 @@ def _accepted_closed_vision_and_successor( assert guard["decision"] == "autonomous_replan_required" todo_id = guard["selected_todo"]["todo_id"] bound_guard = _run_cli([*guard_args, "--todo-id", todo_id]) - review = json.loads(subprocess.check_output( - shlex.split(bound_guard["replan_action_packet"]["review"]), text=True, - )) - writeback = json.loads(subprocess.check_output( - shlex.split(review["next"]["writeback"]), text=True, - )) - assert writeback["obligation_id"] == bound_guard["replan_action_packet"]["obligation_id"] + packet = bound_guard["replan_action_packet"] + if "review" in packet: + review = json.loads(subprocess.check_output( + shlex.split(packet["review"]), text=True, + )) + writeback = json.loads(subprocess.check_output( + shlex.split(review["next"]["writeback"]), text=True, + )) + assert writeback["obligation_id"] == packet["obligation_id"] + stride_decision = writeback["stride_control"]["minimal_example"] + else: + stride_decision = packet["stride_control"]["minimal_example"] + assert stride_decision["reference_obligation_id"] == packet["obligation_id"] successor_vision = { "schema_version": "goal_vision_replan_contract_v0", @@ -117,7 +123,7 @@ def _accepted_closed_vision_and_successor( "evidence_refs": ["fixture:accepted-closed-vision"], "changed": ["Finish the remaining fixture Todo."], }, - "stride_decision": writeback["stride_control"]["minimal_example"], + "stride_decision": stride_decision, } vision_path = project / "successor-vision.json" vision_path.write_text(json.dumps(successor_vision), encoding="utf-8") @@ -131,6 +137,13 @@ def _accepted_closed_vision_and_successor( assert ack["recorded"] is True assert ack["semantic_delta"]["accepted"] is True assert "fresh_vision_path_outcome" in ack["semantic_delta"]["outcomes"] + spent = _run_cli([ + "--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", + "quota", "spend-slot", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--todo-id", todo_id, "--turn-instance-id", turn_id, + "--slots", "1", "--source", "heartbeat", "--execute", + ]) + assert spent["appended"] is True def _enable_weekly_report(registry: Path) -> None: @@ -225,7 +238,7 @@ def count_optional_source_read(*args: object, **kwargs: object) -> object: ).read_text(encoding="utf-8").splitlines() ] assert sum(row.get("classification") == "fixture_completion" for row in rows) == 1 - assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 1 + assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 2 if enabled: assert replay["terminal_post_writeback_hooks"]["intents"] == [] assert { @@ -302,7 +315,7 @@ def fail_one_terminal_response(**kwargs: object) -> dict[str, object]: ).read_text(encoding="utf-8").splitlines() ] assert sum(row.get("classification") == "fixture_completion" for row in rows) == 1 - assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 1 + assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 2 @pytest.mark.parametrize("provider", ["file", "sqlite"]) @@ -420,7 +433,7 @@ def malformed_optional_readback(*args: object, **kwargs: object) -> object: ).read_text(encoding="utf-8").splitlines() ] assert sum(row.get("classification") == "fixture_completion" for row in rows) == 1 - assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 1 + assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 2 def _public_closed_current_vision_args( diff --git a/tests/cli_commands/test_quota_turn_envelope_validation_failure.py b/tests/cli_commands/test_quota_turn_envelope_validation_failure.py index bd667aa8fd..4adab21f65 100644 --- a/tests/cli_commands/test_quota_turn_envelope_validation_failure.py +++ b/tests/cli_commands/test_quota_turn_envelope_validation_failure.py @@ -68,6 +68,8 @@ def _fail_context(*_args, **_kwargs): assert payload.get("decision") == "skip" assert payload.get("error_code") if turn_envelope: - # The envelope is additive; on a failure payload it degrades to the - # typed diagnostic instead of masking it with a renderer crash. - assert payload.get("turn_envelope_skipped") or payload.get("view") == "turn_envelope" + # Collection/validation failures without an interaction contract + # retain the exact typed diagnostic without crashing or reentering. + assert payload.get("error_code") == "QUOTA_VALIDATION_FAILED" + assert "interaction_contract" not in payload + assert "turn_envelope_skipped" not in payload diff --git a/tests/control_plane/test_acceptance_restoration.py b/tests/control_plane/test_acceptance_restoration.py index 092bb81a64..782cc92f1b 100644 --- a/tests/control_plane/test_acceptance_restoration.py +++ b/tests/control_plane/test_acceptance_restoration.py @@ -76,8 +76,6 @@ def inspect(): assert first["acquired"] turn_binding = ["--agent-id", "agent-a", "--todo-id", target, "--turn-instance-id", "turn-restore-acceptance"] - guard = cli("quota", "should-run", "--codex-app", *turn_binding, ) - assert guard["heartbeat_receipt"]["settlement_identity"]["todo_id"] == target cli("todo", "update", "--todo-id", target, "--agent-id", "agent-a", "--clear-resume-when", "--task-lease-idempotency-key", "execution-one", "--task-lease-expected-version", "1") assert inspect()["goal_acceptance_contract"]["tasks"][0]["state"] == "stale" @@ -112,6 +110,8 @@ def turn_holds(): next_lease = cli("task-lease", "acquire", "--todo-id", target, "--owner", "agent-a", "--idempotency-key", "execution-two", "--expected-version", "1", "--ttl-seconds", "600") assert next_lease["acquired"] and next_lease["lease"]["version"] == 2 + guard = cli("quota", "should-run", "--codex-app", *turn_binding, ) + assert guard["heartbeat_receipt"]["settlement_identity"]["todo_id"] == target # Recovery replay remains historical after a fresh execution starts; it # cannot release or acquire another generation, complete work or spend quota. after_acquire = inspect() diff --git a/tests/control_plane/test_agent_preferences.py b/tests/control_plane/test_agent_preferences.py index fb69b6de9a..30b7cef208 100644 --- a/tests/control_plane/test_agent_preferences.py +++ b/tests/control_plane/test_agent_preferences.py @@ -212,12 +212,13 @@ def call(action, *args): assert authority["interaction_contract"]["agent_channel"]["required_reads"] == [] prompt = render_prompt(authority) rendered = json.loads(prompt.split("Turn request:\n", 1)[1].split("\n\n", 1)[0]) - assert rendered["work_contract"]["interaction_contract"]["agent_channel"]["work_context"]["unavailable_context"] == unavailable + assert rendered["schema_version"] == "loopx_turn_model_context_v0" + assert rendered["task_context"]["interaction_contract"]["agent_channel"]["work_context"]["unavailable_context"] == unavailable assert "work_context" in prompt and "independent work retains existing authority" in prompt assert "Use a reviewer." not in prompt and "{broken" not in prompt rc, quota_envelope = _run_cli(registry, runtime, "quota", "should-run", *scope, "--turn-envelope") assert rc == 0, quota_envelope - assert quota_envelope["contract_capsule"]["unavailable_context"] == unavailable + assert quota_envelope["interaction_contract"]["agent_channel"]["work_context"]["unavailable_context"] == unavailable changed = deepcopy(failed_plan) del changed["work_contract"]["interaction_contract"]["agent_channel"]["work_context"]["unavailable_context"] with pytest.raises(ValueError, match="complete Turn contract rejected"): diff --git a/tests/control_plane/test_bound_owner_web_input.py b/tests/control_plane/test_bound_owner_web_input.py index 4088685c98..3dcea654b5 100644 --- a/tests/control_plane/test_bound_owner_web_input.py +++ b/tests/control_plane/test_bound_owner_web_input.py @@ -185,9 +185,9 @@ def observe(_): def test_http_binding_discovery_preserves_duplicate_observations_for_the_typed_owner(bound_chat, monkeypatch): store, _, _, _, post, open_bound, _, _ = bound_chat binding, _ = open_bound() - observed = store.list_sessions() + observed = list(store.iter_session_metadata()) # Inject an ambiguous storage read, never duplicate/corrupt a live store. - monkeypatch.setattr(store, "list_sessions", lambda **_: observed + observed) + monkeypatch.setattr(store, "iter_session_metadata", lambda **_: iter(observed + observed)) status, denied = _bound_sessions(post, "conversation_binding_id=" + binding["binding_id"]) assert status == 409 and "sessions" not in denied diff --git a/tests/control_plane/test_canonical_todo_writer_isolation.py b/tests/control_plane/test_canonical_todo_writer_isolation.py index 1c6051c268..04350273fa 100644 --- a/tests/control_plane/test_canonical_todo_writer_isolation.py +++ b/tests/control_plane/test_canonical_todo_writer_isolation.py @@ -348,6 +348,7 @@ def guard(turn): offline.rename(backend) refreshed = run("refresh-state", *identity, "--turn-instance-id", settlement.TURN_ID, + *proof, "--classification", "validated_progress", "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress", "--no-global-sync", "--suppress-external-sinks", "--vision-state", "vision_on_track", "--vision-summary", "Continue canonical delivery.", diff --git a/tests/control_plane/test_cli_output_budget.py b/tests/control_plane/test_cli_output_budget.py index 312c8dead6..37cad32ed2 100644 --- a/tests/control_plane/test_cli_output_budget.py +++ b/tests/control_plane/test_cli_output_budget.py @@ -547,6 +547,7 @@ def _mode_variant_commands( registry_path: Path, state_file: Path, output_format: str, + complete_quota: bool = True, ) -> dict[str, list[str]]: common = [ "--registry", @@ -574,6 +575,7 @@ def _mode_variant_commands( quota = _surface_commands( project=project, runtime=runtime, registry_path=registry_path, state_file=state_file, output_format=output_format, + complete_quota=complete_quota, )["quota_should_run"] return { "start_goal_guided_command_pack_detail": [ @@ -923,8 +925,8 @@ def test_turn_envelope_references_selected_todo_without_duplicate_context( assert exit_code == 0, text payload = _json_payload(text) - assert payload["action"]["selected_todo"]["text_ref"] == "action.recommended_action" - work_context = payload["work_context"] + assert payload["selected_todo"]["text"] + work_context = payload["interaction_contract"]["agent_channel"]["work_context"] assert work_context["selected_todo_ref"] == "selected_todo" source = next(row for row in work_context["sources"] if row["source"] == "selected_todo") authority = source["content"]["authority_read"] @@ -983,11 +985,7 @@ def test_compact_selected_todo_markdown_preserves_work_context_instruction( assert json_exit_code == 0, json_text assert markdown_exit_code == 0, markdown_text payload = _json_payload(json_text) - work_context = ( - payload["interaction_contract"]["agent_channel"]["work_context"] - if surface_id == "quota_should_run" - else payload["work_context"] - ) + work_context = payload["interaction_contract"]["agent_channel"]["work_context"] instruction = work_context["instruction"] assert instruction assert markdown_text.count(instruction) == 1 @@ -1042,7 +1040,7 @@ def test_quota_should_run_no_format_uses_machine_contract_json( assert no_format_exit_code == 0, no_format_text assert _json_payload(no_format_text)["goal_id"] == GOAL_ID assert markdown_exit_code == 0, markdown_text - assert markdown_text.startswith("# LoopX Quota Should Run") + assert markdown_text.startswith("# LoopX Turn Envelope") assert not markdown_text.lstrip().startswith("{") @@ -1089,6 +1087,7 @@ def test_quota_cli_keeps_full_agent_todo_diagnostics_on_explicit_cold_path( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run"] detail_command = _mode_variant_commands( project=project, @@ -1096,6 +1095,7 @@ def test_quota_cli_keeps_full_agent_todo_diagnostics_on_explicit_cold_path( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run_todo_summary_detail"] default_exit_code, default_text = _invoke_cli(default_command, read_context=True) @@ -1193,6 +1193,7 @@ def test_quota_cli_keeps_complete_vision_rules_with_reachable_duplicate_refs( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run"] detail_command = _mode_variant_commands( project=project, @@ -1200,6 +1201,7 @@ def test_quota_cli_keeps_complete_vision_rules_with_reachable_duplicate_refs( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run_vision_detail"] default_exit_code, default_text = _invoke_cli(default_command, read_context=True) @@ -1474,6 +1476,7 @@ def test_quota_cli_keeps_full_user_todo_diagnostics_on_explicit_cold_path( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run"] detail_command = _mode_variant_commands( project=project, @@ -1481,6 +1484,7 @@ def test_quota_cli_keeps_full_user_todo_diagnostics_on_explicit_cold_path( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run_user_todo_summary_detail"] default_exit_code, default_text = _invoke_cli(default_command, read_context=True) @@ -1530,6 +1534,7 @@ def test_quota_cli_keeps_goal_boundary_authority_on_explicit_cold_path( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run"] detail_command = _mode_variant_commands( project=project, @@ -1537,6 +1542,7 @@ def test_quota_cli_keeps_goal_boundary_authority_on_explicit_cold_path( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run_goal_boundary_detail"] default_exit_code, default_text = _invoke_cli(default_command, read_context=True) @@ -1596,6 +1602,7 @@ def test_quota_cli_deprecated_scheduler_detail_flag_matches_canonical_selector( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run"] canonical_exit_code, canonical_text = _invoke_cli( default_command + ["--include-detail", "scheduler"], @@ -1636,6 +1643,7 @@ def test_quota_cli_all_detail_matches_repeated_canonical_selectors( registry_path=registry_path, state_file=state_file, output_format="json", + complete_quota=False, )["quota_should_run"] repeated_command = list(default_command) for section in ("scheduler", "agent-todos", "user-todos", "goal-boundary"): @@ -2262,16 +2270,21 @@ def test_turn_envelope_cli_preserves_codex_app_scheduler_binding( assert exit_code == 0, text payload = _json_payload(text) - full_decision = shlex.split(payload["detail_ref"]["full_decision"]) - # A cold read must preserve the complete originating source and host profile. - assert full_decision == [ - "loopx", "--registry", str(registry_path), "--runtime-root", str(runtime), - "--format", "json", "quota", "should-run", "--goal-id", GOAL_ID, - "--agent-id", AGENT_IDS[0], "--codex-app", - ] - read_rc, read_text = _invoke_cli(full_decision[1:], read_context=True) + assert shlex.split(payload["contract_binding"]["scheduler_execution_args"]) == ["--codex-app"] + assert payload["scheduler_hint"]["app_automation"]["host_surface"] == "codex_app" + # A fresh codex-app read without --turn-envelope preserves the same host profile. + read_rc, read_text = _invoke_cli( + [ + "--registry", str(registry_path), "--runtime-root", str(runtime), + "--format", "json", "quota", "should-run", "--goal-id", GOAL_ID, + "--agent-id", AGENT_IDS[0], "--codex-app", + ], + read_context=True, + ) assert read_rc == 0, read_text - assert _json_payload(read_text)["goal_id"] == GOAL_ID + read_payload = _json_payload(read_text) + assert read_payload["goal_id"] == GOAL_ID + assert shlex.split(read_payload["contract_binding"]["scheduler_execution_args"]) == ["--codex-app"] def test_quota_should_run_cli_actions_keep_explicit_runtime_root( diff --git a/tests/control_plane/test_context_delivery_cli.py b/tests/control_plane/test_context_delivery_cli.py index 9ec8a50ee9..3f0b48f21e 100644 --- a/tests/control_plane/test_context_delivery_cli.py +++ b/tests/control_plane/test_context_delivery_cli.py @@ -239,14 +239,24 @@ def test_resumed_task_keeps_its_condition_without_expanding_diagnostic_siblings( "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", "mixed-diagnostics", cwd=project) assert code == 0 and guard["should_run"], guard + assert guard["schema_version"] == "loopx_turn_envelope_v1" summary = guard["agent_todo_summary"] - assert [item["todo_id"] for item in summary["backlog_items"]] == ["todo_work_1"] - condition = summary["backlog_items"][0]["resume_condition"] + # The complete writer retains the original bounded source rows. It no + # longer emits the legacy display projection as its canonical decision. + assert [item["todo_id"] for item in summary["backlog_items"]] == [TODO_ID, "todo_work_1"] + condition = summary["backlog_items"][1]["resume_condition"] assert condition["satisfied"] and condition["target_todo_id"] == "todo_dependency" assert len(summary["first_executable_items"]) == 3 candidates = guard["capability_gate"]["runnable_candidates"] assert {row["todo_id"] for row in candidates} == {row["todo_id"] for row in todos[:8]} assert all(row["title"].endswith("Final condition: stop before publication.") for row in candidates) + # The shared historical display owner still isolates the exceptional row; + # no resumed row expands known diagnostic siblings in that projection. + from loopx.control_plane.quota.cli_projection import compact_quota_should_run_cli_payload + displayed = compact_quota_should_run_cli_payload(deepcopy(guard))["agent_todo_summary"] + assert [item["todo_id"] for item in displayed["backlog_items"]] == ["todo_work_1"] + assert displayed["backlog_items"][0]["resume_condition"] == condition + assert len(displayed["first_executable_items"]) == 3 assert state.read_bytes() == before and _spend_run_count(runtime) == 0 code, detailed = _run_cli(registry, runtime, "todo", "list", "--goal-id", GOAL_ID, "--todo-id", "todo_work_7", cwd=project) @@ -648,16 +658,16 @@ def test_native_projection_never_layers_host_projection(tmp_path, monkeypatch, n from hashlib import sha256 from loopx.cli import build_parser - from loopx.cli_commands import quota, quota_context_reader + from loopx.cli_commands import quota, quota_context_reader, quota_result_delivery from loopx.control_plane.turn_driver import codex_context args = build_parser().parse_args(["--format", "json", "quota", "should-run", "--goal-id", "fixture", "--agent-id", "worker", "--context-delivery", "on", "--codex-app", "--codex-context-dir", str(tmp_path)]) original = {"ok": True, "goal_id": "fixture", "agent_identity": {"agent_id": "worker"}, "heartbeat_receipt": {"turn_instance_id": "original-turn", "status": "committed"}} - monkeypatch.setattr(quota, "handoff_decision", + monkeypatch.setattr(quota_result_delivery, "handoff_decision", lambda *args, capture_sha256: ({"scope": "host-request"}, capture_sha256)) - monkeypatch.setattr(quota, "_project_quota_cli_payload", lambda payload, *args, **kwargs: payload) + monkeypatch.setattr(quota_result_delivery, "_project_quota_cli_payload", lambda payload, *args, **kwargs: payload) def competing(*args, **kwargs): pytest.fail("explicit native observation must not compose two projection owners") @@ -676,7 +686,7 @@ def unavailable_directory(**kwargs): def unavailable_reference(*args, **kwargs): raise OSError("synthetic reader metadata unavailable") - monkeypatch.setattr(quota, "project_captured_context", competing) + monkeypatch.setattr(quota_result_delivery, "project_captured_context", competing) monkeypatch.setattr(codex_context, "prepare_codex_context", native) if native_failure == "directory": monkeypatch.setattr(codex_context, "codex_context_directory", unavailable_directory) diff --git a/tests/control_plane/test_quota_acceptance_references.py b/tests/control_plane/test_quota_acceptance_references.py index 2a7592d8e1..d19b65a5bd 100644 --- a/tests/control_plane/test_quota_acceptance_references.py +++ b/tests/control_plane/test_quota_acceptance_references.py @@ -212,7 +212,7 @@ def first_read(*args): chunks.extend(page["content"].encode()) if page["eof"]: assert len(chunks) == page["total_bytes"] - return selected_context_values(chunks) + return view, selected_context_values(chunks) page = run_reader(page["next_command"]) registry_path = tmp_path / "registry.json" @@ -230,18 +230,23 @@ def first_read(*args): "--document", str(document), "--expected-provider-revision", before["provider_revision"], "--operation-id", "source-requirements", "--execute") expected = call("goal-acceptance", "inspect", "--goal-id", GOAL)["goal_acceptance_contract"] - guard = first_read("--turn-instance-id", "turn-acceptance-sharing") + guard_view, guard = first_read("--turn-instance-id", "turn-acceptance-sharing") assert guard["/effective_action"] == "autonomous_replan_required" assert guard["/normal_delivery_allowed"] is False assert "/replan_action_packet/writeback" not in guard - review = run_reader(guard["/replan_action_packet/review"]) - assert review["obligation_id"] == guard["/heartbeat_receipt/semantic_replan_obligation_id"] - acceptance = review["acceptance_index"] - row, = acceptance["outcomes"] - assert row["id"] == "export" - command = acceptance["read_action_template"].replace("{outcome_ref}", row["outcome_ref"]) + assert "/replan_action_packet/review" not in guard + assert guard["/autonomous_replan_obligation/obligation_id"] == guard[ + "/heartbeat_receipt/semantic_replan_obligation_id" + ] + sources = "/interaction_contract/agent_channel/work_context/sources/" + guard_owner, = (path.removesuffix("/source") for path, value in guard.items() + if path.startswith(sources) and path.endswith("/source") and value == "goal_acceptance") + outcome_prefix = guard_owner + "/content/goal_acceptance_contract/outcome_requirements/outcomes/0" + assert guard[outcome_prefix + "/id"] == "export" + assert outcome_prefix + "/requirements" not in guard + command = guard_view["recovery"]["command"].split(" --offset ")[0] + f" --select {outcome_prefix}" original = expected["outcome_requirements"]["outcomes"][0] - assert run_reader(command)["outcome"] == original + assert selected_context_values(run_reader(command)["content"].encode())[outcome_prefix] == original # A later linked revision must reach the selected caller intact. index.write_text("") @@ -259,20 +264,19 @@ def first_read(*args): "--document", str(document), "--expected-provider-revision", revision, "--operation-id", "link-export", "--execute") expected = call("goal-acceptance", "inspect", "--goal-id", GOAL)["goal_acceptance_contract"] - planning = first_read("--turn-instance-id", "turn-export-planning") + _, planning = first_read("--turn-instance-id", "turn-export-planning") assert planning["/interaction_contract/agent_channel/delivery_allowed"] is False assert "/replan_action_packet/review" not in planning - selected = first_read("--todo-id", added["todo_id"], "--turn-instance-id", "turn-export-delivery") + _, selected = first_read("--todo-id", added["todo_id"], "--turn-instance-id", "turn-export-delivery") assert selected["/normal_delivery_allowed"] is True assert selected["/selected_todo/todo_id"] == added["todo_id"] assert "/replan_action_packet/review" not in selected - sources = "/interaction_contract/agent_channel/work_context/sources/" owner, = (path.removesuffix("/source") for path, value in selected.items() if path.startswith(sources) and path.endswith("/source") and value == "goal_acceptance") outcome = selected[owner + "/content/goal_acceptance_contract/outcome_requirements/outcomes/0"] assert outcome == expected["outcome_requirements"]["outcomes"][0] assert original["revision"] < outcome["revision"] - assert run_reader(command)["outcome"] == original + assert selected_context_values(run_reader(command)["content"].encode())[outcome_prefix] == original @pytest.mark.parametrize("provider", ["file", "sqlite"]) @@ -298,10 +302,12 @@ def test_inline_cli_delivers_complete_acceptance_for_selection_and_replan(tmp_pa guard = call("quota", "should-run", "--codex-app", "--context-delivery", "off", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", "turn-acceptance-sharing") assert guard["effective_action"] == "autonomous_replan_required" - ref = "$.interaction_contract.agent_channel.work_context.sources[0].content.goal_acceptance_contract" + guard_sources = guard["interaction_contract"]["agent_channel"]["work_context"]["sources"] + guard_index = next(i for i, row in enumerate(guard_sources) if row["source"] == "goal_acceptance") + ref = f"$.interaction_contract.agent_channel.work_context.sources[{guard_index}].content.goal_acceptance_contract" assert guard["autonomous_replan_obligation"]["replan_context"]["core_goal"]["acceptance_contract_ref"] == ref assert guard["agent_todo_summary"]["goal_acceptance_contract_ref"] == ref - assert guard["interaction_contract"]["agent_channel"]["work_context"]["sources"][0]["content"]["goal_acceptance_contract"] == expected + assert guard_sources[guard_index]["content"]["goal_acceptance_contract"] == expected assert build_turn_envelope(guard)["action_signature"]["matches"] is True # Normal selected delivery must use the exact inline acceptance read and diff --git a/tests/control_plane/test_quota_execution_preparation.py b/tests/control_plane/test_quota_execution_preparation.py index 58d7ccc214..d3832f56ad 100644 --- a/tests/control_plane/test_quota_execution_preparation.py +++ b/tests/control_plane/test_quota_execution_preparation.py @@ -576,9 +576,13 @@ def hook(name): claim = invoke(*first["execution_preparation"]["claim"]["cli_args"], "--thin") ready = invoke("quota", "should-run", *scope, "--runtime-profile", scenario, "--context-delivery", "off") assert ready["execution_preparation"]["state"] == "ready" + proof = ready["execution_preparation"]["lease_proof"] identity = ready["heartbeat_receipt"]["settlement_identity"] assert identity == first["heartbeat_receipt"]["settlement_identity"] - refresh = ["refresh-state", *scope, "--classification", "fixture_manual_result", + refresh = ["refresh-state", *scope, + "--task-lease-idempotency-key", proof["idempotency_key"], + "--task-lease-expected-version", str(proof["expected_version"]), + "--classification", "fixture_manual_result", "--delivery-batch-scale", "single_surface", "--delivery-outcome", "outcome_progress", "--delivery-boundary", "in_flight_continuation", "--progress-result-class", "advanced", "--progress-work-item-id", TODO, "--progress-evidence-id", "fixture:manual-result", diff --git a/tests/control_plane/test_selected_work_requirements.py b/tests/control_plane/test_selected_work_requirements.py index bdaa1551ea..3c73c83527 100644 --- a/tests/control_plane/test_selected_work_requirements.py +++ b/tests/control_plane/test_selected_work_requirements.py @@ -147,7 +147,7 @@ def old_delivery(options): assert packet["scoped_user_gate_fallback"]["selected_executable"]["todo_id"] == "todo_inspect" assert channel["work_context"]["complete"] is True envelope = guard("--turn-envelope") - assert envelope["work_context"]["user_todos"] == channel["work_context"]["user_todos"] + assert envelope["interaction_contract"]["agent_channel"]["work_context"]["user_todos"] == channel["work_context"]["user_todos"] assert state.read_text() == state_text # Canonical tasks still exist: the full Goal source must fail closed, # rather than silently substituting a Todo summary for missing intent. @@ -231,8 +231,7 @@ def guard(*extra: str) -> dict: full = json.loads(result.stdout) assert full["should_run"] is True, full.get("reason") channel = full["interaction_contract"]["agent_channel"] - assert [read["source"] for read in channel["required_reads"]] == ["goal_state"] - goal_read = channel["required_reads"][0] + assert channel["required_reads"] == [] assert "required_reads" not in full["interaction_contract"]["cli_channel"] context = channel["work_context"] assert context["complete"] and not context.get("failures", []) @@ -240,8 +239,10 @@ def guard(*extra: str) -> dict: assert "unknown, not unchanged" in context["instruction"] assert "summaries cannot replace full requirements" in context["instruction"] reads = context["sources"] - assert [read["source"] for read in reads] == ["selected_todo"] - assert not any(read["source"] == "goal_state" for read in reads) + assert [read["source"] for read in reads] == ["goal_state", "selected_todo"] + goal_read = next(read for read in reads if read["source"] == "goal_state") + assert goal_requirements in goal_read["content"]["text"] + assert "Stop before an unauthorized deployment." in goal_read["content"]["text"] goal_result = subprocess.run(shlex.split(goal_read["command"]), capture_output=True, text=True, check=True) assert goal_requirements in goal_result.stdout assert "Stop before an unauthorized deployment." in goal_result.stdout @@ -250,15 +251,11 @@ def guard(*extra: str) -> dict: assert "_context_text_sha256" not in full["selected_todo"] assert reads[-1]["content"]["todo"]["text"] == expected assert json.dumps(context).count(expected) == 1 - assert envelope["required_reads"] == channel["required_reads"] + env_channel = envelope["interaction_contract"]["agent_channel"] + assert env_channel["required_reads"] == channel["required_reads"] assert context["selected_todo_text_verified"] is True - assert envelope["work_context"] == { - key: value - for key, value in context.items() - if key != "selected_todo_text_verified" - } - assert envelope["action"]["selected_todo"]["text_source_verified"] is True - selected = envelope["action"]["selected_todo"] + assert env_channel["work_context"] == context + selected = envelope["selected_todo"] assert selected["todo_id"] == "todo_cursor_work" read = reads[-1] tokens = shlex.split(read["command"]) @@ -278,7 +275,8 @@ def read_detail() -> dict: assert not {"todos", "agent_todos", "user_todos"}.intersection(detail) assert json.dumps(detail).count(expected) == 1 assert detail["todo"]["claimed_by"] == "agent-a" - assert envelope["action_signature"]["matches"] is True + assert envelope["contract_binding"]["source_decision_hash"] + assert envelope["contract_binding"]["content_hash"] assert state.read_bytes() == before plan = build_loopx_turn_plan(envelope, host="codex-cli", execution_mode="isolated-headless", @@ -287,10 +285,11 @@ def read_detail() -> dict: assert read["command"] in _prompt(request) assert "work_context" in _prompt(request) authority = extract_turn_authority(request) + auth_channel = authority["interaction_contract"]["agent_channel"] assert authority["selected_todo"]["todo_id"] == "todo_cursor_work" - assert authority["required_reads"] == channel["required_reads"] - assert authority["work_context"] == envelope["work_context"] - assert authority["selected_todo"]["text_source_verified"] is True + assert auth_channel["required_reads"] == channel["required_reads"] + assert auth_channel["work_context"] == env_channel["work_context"] + assert auth_channel["work_context"]["selected_todo_text_verified"] is True assert read["command"] in render_prompt(authority) # A fresh CLI process must recover current requirements from the same owner, @@ -461,7 +460,8 @@ def test_short_selected_todo_deduplicates_body_but_keeps_canonical_note( context = channel["work_context"] assert context["complete"] is True assert context["selected_todo_ref"] == "selected_todo" - assert [read["source"] for read in channel["required_reads"]] == ["goal_state"] + assert channel["required_reads"] == [] + assert [read["source"] for read in context["sources"]] == ["goal_state", "selected_todo"] selected_source = next(source for source in context["sources"] if source["source"] == "selected_todo") source_todo = selected_source["content"]["todo"] assert source_todo.get("text") is None @@ -473,7 +473,7 @@ def test_short_selected_todo_deduplicates_body_but_keeps_canonical_note( "--agent-id", "agent-a", "--turn-envelope", registry_path=registry, runtime_root=runtime) assert code == 0 and turn["ok"], turn - turn_context = turn["work_context"] + turn_context = turn["interaction_contract"]["agent_channel"]["work_context"] assert turn_context["complete"] is True assert turn_context["selected_todo_ref"] == "selected_todo" turn_source = next(source for source in turn_context["sources"] if source["source"] == "selected_todo") diff --git a/tests/control_plane/test_turn_capability_lifecycle.py b/tests/control_plane/test_turn_capability_lifecycle.py index 41f599c997..94fdad3cbf 100644 --- a/tests/control_plane/test_turn_capability_lifecycle.py +++ b/tests/control_plane/test_turn_capability_lifecycle.py @@ -228,7 +228,7 @@ def test_optional_recall_size_never_disables_enabled_ingest( == 2400 ) assert any( - "Set reward_memory_reflection_json" in item + "reward_memory_reflection_json" in item for item in result["instructions"] ) delivered = result["context_fields"]["reward_memory_recall"] From 5b5449e8ca7e7628bb25299409be629d078cbfc1 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:10:00 +0800 Subject: [PATCH 2/2] fix(quota): preserve tokenless identity and exact numeric types in attach_complete_turn_context Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/control_plane/quota/turn_envelope.py | 2 +- loopx/control_plane/quota/turn_envelope.ts | 11 ++-- .../test_quota_memory_context.py | 57 +++++++++++++++++++ tests/control_plane_ts/turn_envelope.test.ts | 47 +++++++++++++++ 4 files changed, 110 insertions(+), 7 deletions(-) diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index 9c3f693ac6..ab55982167 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -348,7 +348,7 @@ def attach_complete_turn_context( context_additions=additions, source_edits=True, ) - return _apply_context_projection_changes(source, result) + return _apply_context_projection_changes({**source, **additions}, result) def is_legacy_saved_quota_decision(payload: Mapping[str, Any]) -> bool: diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 9b2de57fb9..ca8a3f3a40 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -2158,10 +2158,7 @@ export function attachCompleteTurnContext(value: unknown): JsonObject { ...(Array.isArray(request.source_number_tokens) ? request.source_number_tokens : []), ...additionTokens, ]; - const sourceIdentity = contextSourceIdentity( - source, - combinedTokens.length > 0 ? combinedTokens : undefined, - ); + const sourceIdentity = contextSourceIdentity(source, combinedTokens); return sealCompleteTurnDecision(source, schedulerExecutionArgs, sourceIdentity); } @@ -2672,8 +2669,10 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { } if (operation === "attach_complete_turn_context") { const result = attachCompleteTurnContext(request); - return request.source_edits === true - ? contextProjectionChanges(requireJsonObject(request.payload, "complete Turn decision"), result) : result; + if (request.source_edits !== true) return result; + const payload = requireJsonObject(request.payload, "complete Turn decision"); + const additions = requireJsonObject(request.context_additions, "complete Turn context additions"); + return contextProjectionChanges({...payload, ...additions}, result); } if (operation === "complete_consumer") { requireCompleteTurnDecision(request.payload, request.source_number_tokens); diff --git a/tests/control_plane/test_quota_memory_context.py b/tests/control_plane/test_quota_memory_context.py index fdb8570b41..7212cb032d 100644 --- a/tests/control_plane/test_quota_memory_context.py +++ b/tests/control_plane/test_quota_memory_context.py @@ -339,3 +339,60 @@ def test_real_guard_complete_memory_rejects_changed_source_without_provider_repl quota_capability_automation_source(damaged) assert memory.calls == 1 assert json.dumps(source, ensure_ascii=False, sort_keys=True) == before + + +def test_attach_complete_turn_context_preserves_tokenless_and_numeric_roundtrip() -> None: + from loopx.control_plane.effect_runtime import source_number_tokens + from loopx.control_plane.quota.turn_envelope import ( + assert_complete_turn_decision, + attach_complete_turn_context, + compose_turn_decision, + ) + + guard, _ = quota_context() + assert not source_number_tokens(guard) + base = compose_turn_decision(guard) + assert not source_number_tokens(base) + + tokenless_addition = {"reward_memory_recall": {"status": "empty"}} + assert not source_number_tokens(tokenless_addition) + tokenless_attached = attach_complete_turn_context(base, tokenless_addition) + assert tokenless_attached["reward_memory_recall"] == {"status": "empty"} + assert_complete_turn_decision(tokenless_attached) + + big_int = 2**80 + numeric_attached = attach_complete_turn_context( + tokenless_attached, + {"post_attach_recall": {"val": 1.0, "big": big_int}}, + ) + post_attach = numeric_attached["post_attach_recall"] + assert isinstance(post_attach["val"], float) + assert post_attach["val"] == 1.0 + assert type(post_attach["big"]) is int + assert post_attach["big"] == big_int + assert_complete_turn_decision(numeric_attached) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_real_guard_complete_memory_accepts_auto_context_delivery( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, +) -> None: + registry, route = quota_fixture(tmp_path, monkeypatch, provider) + enable_live_memory(registry, recall=True, ingest=True) + _, config = resolve_reward_memory_experiment( + registry_path=registry, goal_id=GOAL_ID, agent_id=AGENT_ID) + memory = RecallProvider(active_record(config, expires_at="2099-01-01T00:00:00+00:00")) + monkeypatch.setattr( + "loopx.capabilities.agent_turn_recall.run_configured_agent_turn_recall_fail_open", + lambda **kwargs: run_configured_agent_turn_recall_fail_open(**kwargs, provider=memory)) + guard = run_cli( + route + [ + "quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--turn-instance-id", "auto-delivery-memory-check", + "--context-delivery", "auto", "--available-capability", "filesystem_read", + ], + ) + assert guard["should_run"] is True + assert guard["reward_memory_recall"]["status"] == "applied" + assert memory.calls == 1 + assert project_turn_context(guard)["reward_memory_recall"]["context"]["guidance"] diff --git a/tests/control_plane_ts/turn_envelope.test.ts b/tests/control_plane_ts/turn_envelope.test.ts index 42e8a4e754..5da929e9c7 100644 --- a/tests/control_plane_ts/turn_envelope.test.ts +++ b/tests/control_plane_ts/turn_envelope.test.ts @@ -1930,3 +1930,50 @@ test("complete execution keeps the adaptive primary and unbound selection distin assert.equal(result.sha256, null); } }); + +test("attachCompleteTurnContext preserves tokenless identity and avoids rounding additions on source_edits", () => { + const source = payload(); + const complete = evaluateTurnEnvelope({ + operation: "compose_complete", + payload: source, + scheduler_execution_args: "", + }); + const tokenlessAttached = evaluateTurnEnvelope({ + operation: "attach_complete_turn_context", + payload: complete, + context_additions: {reward_memory_recall: {status: "empty", guidance: []}}, + }); + assert.deepEqual( + evaluateTurnEnvelope({operation: "complete_consumer", payload: tokenlessAttached}), + {ok: true}, + ); + const editResult = evaluateTurnEnvelope({ + operation: "attach_complete_turn_context", + payload: complete, + context_additions: {post_attach_recall: {val: 1, big: 2 ** 80}}, + context_addition_tokens: [ + [["post_attach_recall", "val"], "1.0"], + [["post_attach_recall", "big"], "1208925819614629174706176"], + ], + source_edits: true, + }); + const changes = editResult.changes as {path: (string | number)[]}[]; + assert.ok(changes.length > 0); + assert.ok(changes.every(change => change.path[0] === "contract_binding")); + assert.throws( + () => evaluateTurnEnvelope({ + operation: "attach_complete_turn_context", + payload: complete, + context_additions: {contract_binding: {}}, + }), + EffectRuntimeRequestError, + ); + assert.throws( + () => evaluateTurnEnvelope({ + operation: "attach_complete_turn_context", + payload: complete, + context_additions: {goal_id: "overwrite"}, + }), + EffectRuntimeRequestError, + ); +});