From 560ac7eb0b8dc33f730e7f520d46361c72e27516 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:40:06 +0800 Subject: [PATCH 1/5] Make the complete work contract the ordinary quota CLI default Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../contract-and-context.md | 7 + .../contract-and-context.zh-CN.md | 4 + .../control_plane/cli-output-probe-runner.py | 32 ++++ loopx/cli_commands/quota_presentation.py | 29 --- loopx/cli_commands/quota_registration.py | 4 +- loopx/cli_commands/quota_should_run.py | 15 +- .../testing/cli_output_budget.py | 10 +- tests/control_plane/test_cli_output_budget.py | 168 ++++++++---------- .../test_cli_output_probe_runner.py | 21 +++ .../test_selected_work_requirements.py | 14 +- tests/test_runtime_snapshot_publication.py | 8 +- 11 files changed, 161 insertions(+), 151 deletions(-) diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md index 335ae7f4f4..d2da929760 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md @@ -29,6 +29,13 @@ Full Goal material is collected independently of that presentation choice. The active CLI selection between its compactor and `buildTurnEnvelope` is removed. Status, plan and scheduler-observation retain their separate purposes; historical readers and other remaining callers are not retired by this slice. +The ordinary CLI cutover removes the JSON-only format exception from guard +context collection and from composition before capture. Scheduler observation +continues to use its separate read-only projection. The public runtime artifact +still checks its qualified default independently. An archive that exposes C1 as +its default must pass the existing supported-profile and matched single-session +outcome and full-cost qualification before adoption. + The current model-behavior portfolio also composes its should-run inputs through this complete-source owner; it no longer exercises the retired CLI compactor as the product default. Candidate context, planning relations, task continuation and diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md index efc1e6ee5d..3ec0b755c1 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md @@ -21,6 +21,10 @@ TypeScript `composeCompleteTurnDecision` owner。默认调用及兼容别名 此展示选择分开。CLI 中选择 compactor 或 `buildTurnEnvelope` 的活跃分支删除。 Status、plan 与 scheduler-observation 保留各自用途;本切片不退役历史 reader 或 其他剩余调用方。 +普通 CLI 切换同时删除准入上下文收集和捕获前组合里仅为 JSON 调用保留的格式例外。 +调度观察继续使用独立的只读展示。公开运行时包独立核对已通过资格验收的默认契约。 +以 C1 为默认的发行包仍须通过受支持配置及匹配单会话的成果与全成本验收,才能采用。 + 当前 model-behavior portfolio 的 should-run 输入也复用该完整来源 owner,不再把 已退役 CLI compactor 当作产品默认路径。候选上下文、规划关系、任务续接与诊断事实 保留。Crowded 回归的 pretty JSON 从压缩后的 86,172 字节变为完整的 121,318 字节 diff --git a/examples/control_plane/cli-output-probe-runner.py b/examples/control_plane/cli-output-probe-runner.py index ec1315339f..18a16fd3bf 100644 --- a/examples/control_plane/cli-output-probe-runner.py +++ b/examples/control_plane/cli-output-probe-runner.py @@ -4,6 +4,7 @@ from __future__ import annotations import argparse +from dataclasses import replace import importlib.util import hashlib import shlex @@ -390,6 +391,29 @@ def _assert_output_contract( raise AssertionError(f"JSON output lost semantic key(s): {', '.join(missing)}") +def _historical_ordinary_quota_carrier(spec, measurement: dict, output_format: str, text: str): + """Describe a frozen old caller; the 19-control oracle still validates it. + + Only measurement-only base probes call this. Candidate C1 shape and + budgets remain mandatory, including when the old carrier looks valid. + """ + payload = measurement.get("resolved_payload", measurement.get("payload")) + historical_json = (output_format == "json" and isinstance(payload, dict) + and payload.get("mode") == "should-run" and "schema_version" not in payload) + historical_markdown = (output_format == "markdown" + and text.startswith("# LoopX Quota Should Run\n")) + if (output_format == "json" and isinstance(payload, dict) + and payload.get("schema_version") == "loopx_turn_envelope_v0"): + return replace(spec, semantic_json_keys=("goal_id", "agent_id", "action", "writeback", + "boundary", "contract_capsule", "required_reads"), output_contract_version=None) + if historical_json or historical_markdown: + return replace(spec, + semantic_json_keys=("goal_id", "decision", "should_run", "interaction_contract", + "scheduler_hint", "selected_todo"), + markdown_anchor="# LoopX Quota Should Run", output_contract_version=None) + return spec + + def _default_rows( probe: ModuleType, semantics: ModuleType, @@ -427,6 +451,8 @@ def _default_rows( surface_id, {} )[output_format] = measurement surface = probe.CLI_OUTPUT_BUDGET_BY_ID[surface_id] + if not enforce_budget and surface_id == "quota_should_run": + surface = _historical_ordinary_quota_carrier(surface, measurement, output_format, text) if enforce_budget: if (surface_id, scenario.name, output_format) == ( "loopx_turn_plan", "crowded", "json" @@ -506,6 +532,8 @@ def _variant_rows( if exit_code != 0: raise AssertionError(f"{variant_id}/{output_format} failed") measurement = probe._measure_context_output(text, output_format=output_format) + if not enforce_budget and variant.parent_surface_id == "quota_should_run": + variant = _historical_ordinary_quota_carrier(variant, measurement, output_format, text) if enforce_budget: probe.assert_cli_output_mode_variant( variant, @@ -575,6 +603,8 @@ def _blocking_gate_rows( variant = probe.CLI_OUTPUT_MODE_VARIANT_BY_ID[ "quota_should_run_turn_envelope" ] + if not enforce_budget: + variant = _historical_ordinary_quota_carrier(variant, measurement, "json", output) if enforce_budget: probe.assert_cli_output_mode_variant( variant, @@ -633,6 +663,8 @@ def _multi_subagent_rows(probe, semantics, fixture_root, *, enforce_budget=True) raise AssertionError("enabled multi_subagent turn envelope failed") measurement = probe._measure_context_output(output, output_format="json") variant = probe.CLI_OUTPUT_MODE_VARIANT_BY_ID[variant_id] + if not enforce_budget: + variant = _historical_ordinary_quota_carrier(variant, measurement, "json", output) if enforce_budget: probe.assert_cli_output_mode_variant( variant, output_format="json", text=output, measurement=measurement, diff --git a/loopx/cli_commands/quota_presentation.py b/loopx/cli_commands/quota_presentation.py index c6537b0339..50d52d4623 100644 --- a/loopx/cli_commands/quota_presentation.py +++ b/loopx/cli_commands/quota_presentation.py @@ -9,32 +9,6 @@ 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, @@ -42,9 +16,6 @@ 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 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 from ..control_plane.quota.error_codes import QuotaDecisionTransportError from ..control_plane.quota.turn_envelope import compose_turn_decision diff --git a/loopx/cli_commands/quota_registration.py b/loopx/cli_commands/quota_registration.py index 40c23ef81c..d1fec55ce8 100644 --- a/loopx/cli_commands/quota_registration.py +++ b/loopx/cli_commands/quota_registration.py @@ -221,12 +221,12 @@ def register_quota_command( "--turn-envelope", action="store_true", help=( - "Select the complete v1 work contract for quota should-run. " + "Compatibility alias: quota should-run already returns the complete v1 work contract. " "Context and Delta delivery remain independent." ), ) turn_view.add_argument("--complete-turn", action="store_true", - help="Select the complete v1 work contract for JSON quota should-run " + help="Compatibility alias: quota should-run already returns the complete v1 work contract " "and its shared exact-Turn settlement. Context and Delta delivery remain independent.") capture_group = quota_parser.add_mutually_exclusive_group() capture_group.add_argument( diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 9b4bb4eeb9..e65679bdc8 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -21,7 +21,6 @@ ) 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 @@ -54,9 +53,7 @@ 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]: - _, scheduler_context, _ = quota_module._export( - "validate_quota_command_context_request" - )(args) + 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)) @@ -99,10 +96,7 @@ 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) - and not is_undeclared_json_quota_caller(args, scheduler_context) - ) + model_read = not getattr(args, "scheduler_observation", False) context_dispatch = dispatch_turn_start_hooks( ( turn_start_hook( @@ -373,10 +367,7 @@ def execute_quota_should_run( agent_id=args.agent_id, todo_id=args.todo_id, ) - complete_context = ( - not getattr(args, "scheduler_observation", False) - and not is_undeclared_json_quota_caller(args, scheduler_context) - ) + complete_context = not getattr(args, "scheduler_observation", False) payload = export("build_live_quota_should_run_decision")( status_payload, goal_id=args.goal_id, diff --git a/loopx/control_plane/testing/cli_output_budget.py b/loopx/control_plane/testing/cli_output_budget.py index 8f2d6f6bc6..fa858efa5e 100644 --- a/loopx/control_plane/testing/cli_output_budget.py +++ b/loopx/control_plane/testing/cli_output_budget.py @@ -132,7 +132,7 @@ class CliOutputCommandClassification: ), CliOutputBudgetSpec( surface_id="quota_should_run", - command="quota should-run --turn-envelope --context-delivery off", + command="quota should-run --context-delivery off", owner="quota guard", consumer_action="inspect the complete inline quota policy", qualification_policy="absolute_hot_path", @@ -466,9 +466,11 @@ class CliOutputCommandClassification: output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", - # The complete captured Vision projection measures 58,393 JSON chars. - # Preserve the original 55,000 failure; keep a 607-character allowance. - max_chars={'json': 59000, 'markdown': 26000}, + # The crowded fixture measures 60,826 JSON characters on both the + # previous explicit C1 path and the new default. The old default + # measured 50,549. Preserve the 55,000/59,000 misses and allow 274 + # characters of headroom without changing the wire or model budget. + max_chars={'json': 61100, 'markdown': 26000}, max_lines={"json": 1_350, "markdown": 190}, output_contract_version="loopx_turn_envelope_v1", ), diff --git a/tests/control_plane/test_cli_output_budget.py b/tests/control_plane/test_cli_output_budget.py index 37cad32ed2..78f6b74160 100644 --- a/tests/control_plane/test_cli_output_budget.py +++ b/tests/control_plane/test_cli_output_budget.py @@ -7,7 +7,7 @@ import shlex import shutil import tempfile -from dataclasses import dataclass, replace +from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path @@ -353,6 +353,14 @@ def _measure_context_output(text, *, output_format): def _quota_payload_without_rollout_receipt(text: str) -> dict[str, object]: payload = _json_payload(text) + if payload.get("schema_version") == "loopx_turn_envelope_v1": + from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision + + # Verify each original signature before comparing independent observations. + # The rollout receipt changes both derived hashes, not the task or authority. + assert_complete_turn_decision(payload) + payload["contract_binding"].pop("content_hash") + payload["contract_binding"].pop("source_decision_hash") payload.pop("rollout_event", None) return payload @@ -365,10 +373,7 @@ def _surface_commands( state_file: Path, output_format: str, context_delivery: str | None = "off", - complete_quota: bool = True, ) -> dict[str, list[str]]: - # Keep the Complete Turn budget workload on its declared carrier. - quota_view = ["--turn-envelope"] if complete_quota else [] delivery = ["--context-delivery", context_delivery] if context_delivery else [] common = [ "--registry", @@ -418,7 +423,7 @@ def _surface_commands( GOAL_ID, "--agent-id", AGENT_IDS[0], - ] + quota_view + delivery, + ] + delivery, "loopx_turn_plan": common + [ "turn", @@ -547,7 +552,6 @@ def _mode_variant_commands( registry_path: Path, state_file: Path, output_format: str, - complete_quota: bool = True, ) -> dict[str, list[str]]: common = [ "--registry", @@ -575,7 +579,6 @@ 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": [ @@ -615,7 +618,7 @@ def _mode_variant_commands( "quota_should_run_goal_boundary_detail": quota + ["--include-detail", "goal-boundary"], "quota_should_run_vision_detail": quota + ["--include-detail", "vision"], "quota_should_run_all_detail": quota + ["--include-detail", "all"], - "quota_should_run_turn_envelope": quota, + "quota_should_run_turn_envelope": quota + ["--turn-envelope"], "loopx_turn_plan_transaction_detail": common + [ "turn", @@ -925,8 +928,13 @@ def test_turn_envelope_references_selected_todo_without_duplicate_context( assert exit_code == 0, text payload = _json_payload(text) - assert payload["selected_todo"]["text"] + assert payload["schema_version"] == "loopx_turn_envelope_v1" + assert payload["selected_todo"]["todo_id"] == "todo_fixture_000" + assert payload["selected_todo"]["text"] == ( + "[P0] Validate public fixture lane 00 without reading archival detail." + ) work_context = payload["interaction_contract"]["agent_channel"]["work_context"] + assert work_context["selected_todo_text_verified"] is True 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"] @@ -1045,7 +1053,7 @@ def test_quota_should_run_no_format_uses_machine_contract_json( @pytest.mark.parametrize("scenario", SCENARIOS, ids=lambda scenario: scenario.name) -def test_public_quota_packet_keeps_original_control_keys_and_output_budget( +def test_ordinary_quota_uses_complete_contract_with_delivery_off( tmp_path: Path, scenario: Scenario, ) -> None: with _stable_budget_fixture_root(tmp_path / scenario.name) as stable_root: @@ -1053,22 +1061,21 @@ def test_public_quota_packet_keeps_original_control_keys_and_output_budget( import_fixture_authority(registry_path, GOAL_ID) command = _surface_commands( project=project, runtime=runtime, registry_path=registry_path, state_file=state_file, - output_format="json", complete_quota=False, + output_format="json", )["quota_should_run"] exit_code, output = _invoke_cli(command) assert exit_code == 0, output measurement = _measure_context_output(output, output_format="json") packet = _measured_payload(measurement) - assert packet.get("schema_version") is None + assert packet["schema_version"] == "loopx_turn_envelope_v1" + assert packet["contract_binding"] + assert "reference_file" not in packet assert packet["goal_id"] == GOAL_ID assert packet["interaction_contract"]["schema_version"] == "loopx_interaction_contract_v0" - spec = replace( - CLI_OUTPUT_BUDGET_BY_ID["quota_should_run"], output_contract_version=None, - semantic_json_keys=("interaction_contract", "scheduler_hint", "selected_todo"), - ) assert_cli_output_baseline( - spec, scenario=scenario.name, output_format="json", text=output, measurement=measurement, + CLI_OUTPUT_BUDGET_BY_ID["quota_should_run"], scenario=scenario.name, + output_format="json", text=output, measurement=measurement, ) @@ -1087,7 +1094,6 @@ 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, @@ -1095,7 +1101,6 @@ 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) @@ -1103,8 +1108,6 @@ def test_quota_cli_keeps_full_agent_todo_diagnostics_on_explicit_cold_path( assert default_exit_code == 0, default_text assert detail_exit_code == 0, detail_text - assert '"content_revision"' not in default_text - assert '"content_revision"' not in detail_text default_payload = _json_payload(default_text) detail_payload = _json_payload(detail_text) default_summary = default_payload["agent_todo_summary"] @@ -1116,18 +1119,15 @@ def test_quota_cli_keeps_full_agent_todo_diagnostics_on_explicit_cold_path( ) assert detail_inventory["item_detail_ref"] == "$.agent_todo_summary" assert detail_inventory["items"] - assert default_summary["payload_compaction"]["schema_version"] == ( - "quota_cli_todo_summary_compaction_v0" - ) - assert default_payload["todo_summary_projection"]["detail_ref"] == ( - "quota should-run --include-detail agent-todos" - ) - assert "backlog_items" not in default_summary - assert detail_summary["backlog_items"] - assert detail_payload["todo_summary_projection"]["compacted_roles"] == ["user"] - assert detail_payload["todo_summary_projection"]["detail_ref"] == ( - "quota should-run --include-detail user-todos" - ) + # Detail selectors add planning diagnostics, not a second task contract. + assert default_summary == detail_summary + assert default_summary["total_count"] == SCENARIOS[1].todo_count + assert default_summary["backlog_items"] + assert default_summary["first_executable_items"][0]["todo_id"] == "todo_fixture_000" + assert len(detail_inventory["items"]) == SCENARIOS[1].todo_count + assert {row["todo_id"] for row in detail_inventory["items"]} == { + f"todo_fixture_{index:03d}" for index in range(SCENARIOS[1].todo_count) + } for key in ("interaction_contract", "scheduler_hint", "selected_todo"): assert default_payload.get(key) == detail_payload.get(key) @@ -1193,7 +1193,6 @@ 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, @@ -1201,7 +1200,6 @@ 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) @@ -1209,43 +1207,27 @@ def test_quota_cli_keeps_complete_vision_rules_with_reachable_duplicate_refs( assert default_exit_code == 0, default_text assert detail_exit_code == 0, detail_text - # Same 36-Todo / 12-run workload: 45,313 lossy -> 48,418 complete chars. - # Retain the required clauses; the qualified complete-body ceiling is owned - # by the budget spec and leaves bounded headroom above the measured payload. - # The separate 40k compactor fixture and collection-growth guards stay fixed. - assert len(default_text) <= CLI_OUTPUT_MODE_VARIANT_BY_ID[ - "quota_should_run_vision_detail" - ].max_chars["json"] default_payload = _json_payload(default_text) detail_payload = _json_payload(detail_text) compact_audit = default_payload["vision_continuation_audit"] detailed_audit = detail_payload["vision_continuation_audit"] assert compact_audit["required"] is True assert compact_audit["vision_gap_judge"]["decision"] == "continue" - assert compact_audit["payload_compaction"]["full_detail_cold_path"] == ( - "quota should-run --include-detail vision" - ) + assert compact_audit == detailed_audit assert compact_audit["vision_gap_judge"]["registry_read_instruction"] - assert {k: v for k, v in compact_audit.items() if k != "payload_compaction"} == ( - detailed_audit - ) + assert compact_audit["vision_gap_judge"]["external_research_instruction"] + assert compact_audit["required_before_closeout"] for compact_container, detailed_container in ( (default_payload["goal_frontier_projection"], detail_payload["goal_frontier_projection"]), (default_payload["interaction_contract"]["agent_channel"], detail_payload["interaction_contract"]["agent_channel"]), (default_payload["interaction_contract"]["cli_channel"], detail_payload["interaction_contract"]["cli_channel"]), ): - if "vision_continuation_audit" not in detailed_container: - continue - audit = dict(compact_container["vision_continuation_audit"]) + assert compact_container.get("vision_continuation_audit") == detailed_container.get("vision_continuation_audit") + audit = compact_container.get("vision_continuation_audit", {}) if "projection_ref" in audit: assert audit["projection_ref"] == "$.vision_continuation_audit" - audit = {k: v for k, v in compact_audit.items() if k != "payload_compaction"} elif "projection_ref" in audit.get("vision_gap_judge", {}): - assert audit["vision_gap_judge"]["projection_ref"] == ( - "$.vision_continuation_audit.vision_gap_judge" - ) - audit["vision_gap_judge"] = compact_audit["vision_gap_judge"] - assert audit == detailed_container["vision_continuation_audit"] + assert audit["vision_gap_judge"]["projection_ref"] == "$.vision_continuation_audit.vision_gap_judge" compact_replan = default_payload["replan_action_packet"] detailed_replan = detail_payload["replan_action_packet"] assert compact_replan["writeback_contract"] == detailed_replan["writeback_contract"] @@ -1287,6 +1269,18 @@ def test_quota_cli_keeps_complete_vision_rules_with_reachable_duplicate_refs( detail_interaction["cli_channel"]["next_cli_actions"] ) + # The measured baseline allowance is not evidence of output reduction. + spec = CLI_OUTPUT_MODE_VARIANT_BY_ID["quota_should_run_vision_detail"] + assert len(default_text) <= spec.max_chars["json"] + # A bounded calibration must still reject a body beyond its allowance. + # JSON whitespace preserves all semantics while adding presentation cost. + oversized = default_text + " " * (spec.max_chars["json"] + 1 - len(default_text)) + with pytest.raises(AssertionError, match="variant ceiling"): + assert_cli_output_mode_variant( + spec, output_format="json", text=oversized, + measurement=measure_cli_output(oversized, output_format="json"), + ) + @pytest.mark.parametrize("include_agent_vision", [False, True]) def test_crowded_turn_plan_budget_preserves_executable_vision_authoring( @@ -1476,7 +1470,6 @@ 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, @@ -1484,7 +1477,6 @@ 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) @@ -1496,22 +1488,19 @@ def test_quota_cli_keeps_full_user_todo_diagnostics_on_explicit_cold_path( detail_payload = _json_payload(detail_text) default_summary = default_payload["user_todo_summary"] detail_summary = detail_payload["user_todo_summary"] - assert default_summary["payload_compaction"]["schema_version"] == ( - "quota_cli_user_todo_summary_compaction_v0" - ) - assert default_summary["payload_compaction"]["full_detail_cold_path"] == ( - "quota should-run --include-detail user-todos" - ) - assert default_summary["gate_open_items"][0]["todo_id"] == "todo_user_gate_001" - assert default_summary["gate_open_items"][0]["blocks_agent"] == "codex-alpha" - assert "other_agent_bound_user_action_items" not in default_summary - assert detail_summary["other_agent_bound_user_action_items"][0]["todo_id"] == ( - "todo_user_action_001" - ) - assert detail_summary["payload_compaction"]["schema_version"] == ( - "quota_todo_summary_payload_compaction_v0" - ) - assert detail_payload["todo_summary_projection"]["compacted_roles"] == ["agent"] + assert default_summary == detail_summary + assert default_summary["total_count"] == 2 + assert default_summary["open_count"] == 1 + # The shared owner aliases equal lanes; resolve its reference rather than + # requiring duplicate bodies or the retired CLI-only compaction format. + assert default_summary["gate_open_items_ref"] == "$.user_todo_summary.first_open_items" + gate = default_summary["first_open_items"][0] + assert gate["todo_id"] == "todo_user_gate_001" + assert gate["blocks_agent"] == AGENT_IDS[0] + other = default_summary["other_agent_bound_user_action_items"][0] + assert other["todo_id"] == "todo_user_action_001" + assert other["bound_agent"] == AGENT_IDS[1] + assert default_summary["user_action_agent_scope_filter"]["other_agent_bound_user_action_open_count"] == 1 for key in ("interaction_contract", "scheduler_hint", "selected_todo"): assert default_payload[key] == detail_payload[key] @@ -1534,7 +1523,6 @@ 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, @@ -1542,7 +1530,6 @@ 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) @@ -1556,23 +1543,14 @@ def test_quota_cli_keeps_goal_boundary_authority_on_explicit_cold_path( detail_boundary = detail_payload["goal_boundary"] default_authority = default_boundary["checkpointed_boundary_authority"] detail_authority = detail_boundary["checkpointed_boundary_authority"] - assert default_authority["payload_compaction"] == { - "schema_version": "quota_cli_goal_boundary_compaction_v0", - "omitted_entry_count": 1, - "full_detail_cold_path": "quota should-run --include-detail goal-boundary", - } - assert "entries" not in default_authority - assert detail_authority["entries"] - for key in ("active_count", "inactive_count", "active_write_scope"): - assert default_authority[key] == detail_authority[key] - expected_boundary = dict(detail_boundary) - expected_authority = dict(detail_authority) - expected_authority.pop("entries") - expected_authority["payload_compaction"] = default_authority[ - "payload_compaction" - ] - expected_boundary["checkpointed_boundary_authority"] = expected_authority - assert default_boundary == expected_boundary + assert default_authority == detail_authority + assert default_authority["active_count"] == 1 + assert default_authority["inactive_count"] == 0 + assert default_authority["active_write_scope"] == ["docs/**"] + assert default_authority["entries"][0]["decision_id"] == "todo_fixture_boundary_001" + assert default_authority["entries"][0]["decision"] == "approve" + assert default_authority["entries"][0]["write_scope"] == ["docs/**"] + assert default_boundary == detail_boundary for key in ("interaction_contract", "scheduler_hint", "selected_todo"): assert default_payload[key] == detail_payload[key] @@ -1602,7 +1580,6 @@ 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"], @@ -1643,7 +1620,6 @@ 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"): diff --git a/tests/control_plane/test_cli_output_probe_runner.py b/tests/control_plane/test_cli_output_probe_runner.py index 1ae0b1d026..6bb470cfdb 100644 --- a/tests/control_plane/test_cli_output_probe_runner.py +++ b/tests/control_plane/test_cli_output_probe_runner.py @@ -306,3 +306,24 @@ def test_complete_plan_receipt_checks_original_goal_bytes(tmp_path): goal["content"]["text"] += "\nChanged acceptance or stop condition\n" with pytest.raises(AssertionError): receipt_row(**kwargs, measurement=measure) + + +def test_historical_quota_measurement_does_not_accept_unknown_or_incomplete_carriers(): + runner = runpy.run_path(str(RUNNER)) + spec = probe.CLI_OUTPUT_BUDGET_BY_ID['quota_should_run'] + historical = {'mode': 'should-run', 'goal_id': 'fixture', 'decision': 'run', + 'should_run': True, 'interaction_contract': {}, 'scheduler_hint': {}, 'selected_todo': None} + measured = runner['_historical_ordinary_quota_carrier'](spec, + {'payload': historical}, 'json', json.dumps(historical)) + assert measured.output_contract_version is None + assert spec.output_contract_version == 'loopx_turn_envelope_v1' + # Even measurement-only does not waive a missing historical identity. + del historical['goal_id'] + with pytest.raises(AssertionError, match='goal_id'): + runner['_assert_output_contract'](output_format='json', text=json.dumps(historical), + measurement={'payload': historical}, semantic_json_keys=measured.semantic_json_keys, + markdown_anchor=measured.markdown_anchor) + for version in ('loopx_turn_envelope_v1', 'unknown'): + value = {**historical, 'schema_version': version} + assert runner['_historical_ordinary_quota_carrier'](spec, + {'payload': value}, 'json', json.dumps(value)) is spec diff --git a/tests/control_plane/test_selected_work_requirements.py b/tests/control_plane/test_selected_work_requirements.py index 3c73c83527..19c34af9dd 100644 --- a/tests/control_plane/test_selected_work_requirements.py +++ b/tests/control_plane/test_selected_work_requirements.py @@ -152,12 +152,14 @@ def old_delivery(options): # Canonical tasks still exist: the full Goal source must fail closed, # rather than silently substituting a Todo summary for missing intent. state.unlink() - failed = guard(expected_exit=1) - assert failed["ok"] is False and failed["status_health_ok"] is False - failed_channel = failed["interaction_contract"]["agent_channel"] - assert failed_channel["delivery_allowed"] is False - assert failed_channel["work_context"]["complete"] is False - assert any(read["source"] == "goal_state" for read in failed_channel["required_reads"]) + for flags in ((), ("--turn-envelope",), ("--complete-turn",)): + failed = guard(*flags, expected_exit=1) + assert failed["ok"] is False + assert failed["decision"] == "skip" and failed["should_run"] is False + assert failed["diagnostic_code"] == "invalid_request" + assert failed["reason"] == "Complete Goal source is required before host dispatch" + assert "interaction_contract" not in failed + assert "reference_file" not in failed state.write_text(state_text) assert guard()["interaction_contract"]["agent_channel"]["work_context"]["complete"] is True diff --git a/tests/test_runtime_snapshot_publication.py b/tests/test_runtime_snapshot_publication.py index b4279a5063..df4d5478fd 100644 --- a/tests/test_runtime_snapshot_publication.py +++ b/tests/test_runtime_snapshot_publication.py @@ -365,6 +365,10 @@ def observe(source: Path) -> dict: def test_release_probe_observes_real_default_without_model_or_active_goal(): from scripts.qualify_runtime_artifact import observe_default_contract - # Check the actual CLI output against the supported release contract. + # Observe the new ordinary writer without disguising it as the qualified + # historical default. Engineering cutover does not grant release adoption. observed = observe_default_contract(ROOT) - assert validate_default_contract(observed) == PUBLIC_DEFAULT_CONTRACT + assert observed["surface"] == "complete_turn" + assert observed["schema_version"] == "loopx_turn_envelope_v1" + with pytest.raises(ValueError, match="unqualified for public adoption"): + validate_default_contract(observed) From 24bc5086a498ecbe51bffd228b870d3d610b9ae8 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:07:41 +0800 Subject: [PATCH 2/5] Qualify new runtime artifacts with the Complete Turn default Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../src-tauri/src/macos_update.rs | 22 +++++++++------ .../cli_commands/public_default_contract.json | 13 ++++++--- loopx/cli_commands/update_artifact.py | 26 ++++++++---------- scripts/qualify_runtime_artifact.py | 2 +- tests/test_runtime_snapshot_publication.py | 27 +++++++++---------- tests/test_update_artifact.py | 6 ++++- 6 files changed, 54 insertions(+), 42 deletions(-) diff --git a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs index 16c07501b0..d4401c3de7 100644 --- a/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs +++ b/apps/desktop/loopx-control-plane/src-tauri/src/macos_update.rs @@ -11,7 +11,7 @@ use flate2::read::GzDecoder; use serde_json::Value; use tauri_plugin_updater::Update; -const PUBLIC_DEFAULT_CONTRACT: &str = +const ARTIFACT_DEFAULT_CONTRACTS: &str = include_str!("../../../../../loopx/cli_commands/public_default_contract.json"); /// Read the publisher's observed contract inside the signature-verified bytes @@ -31,7 +31,9 @@ pub(crate) fn qualify_candidate( } let invalid = "runtime_bundle_invalid"; let unavailable = "update_platform_unavailable"; - let supported: Value = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).map_err(|_| invalid)?; + let supported: Value = serde_json::from_str(ARTIFACT_DEFAULT_CONTRACTS).map_err(|_| invalid)?; + let current = supported.get("current").ok_or(invalid)?; + let historical = supported.get("historical").ok_or(invalid)?; let identity_path = Path::new("LoopX.app/Contents/Resources/runtime/identity.json"); let mut archive = tar::Archive::new(GzDecoder::new(Cursor::new(verified_bytes))); let mut qualified = false; @@ -46,7 +48,8 @@ pub(crate) fn qualify_candidate( let mut raw = Vec::new(); entry.read_to_end(&mut raw).map_err(|_| invalid)?; let identity = crate::bundled_runtime::parse_identity(&raw)?; - if identity["default_contract"] != supported { + let observed = &identity["default_contract"]; + if observed != current && observed != historical { return Err(unavailable.into()); } qualified = true; @@ -194,7 +197,7 @@ mod tests { Some(serde_json::json!({"surface": "unknown"})), Some(serde_json::json!({ "surface": "complete_turn", - "schema_version": "loopx_turn_envelope_v1", + "schema_version": "loopx_turn_envelope_v0", "interaction_schema_version": "loopx_interaction_contract_v0" })), ]; @@ -216,10 +219,13 @@ mod tests { assert!(qualify_candidate("stable", "2.3.0", &bytes).is_ok()); } - identity["default_contract"] = serde_json::from_str(PUBLIC_DEFAULT_CONTRACT).unwrap(); - fs::write(identity_path, identity.to_string()).unwrap(); - let bytes = archive(&candidate); - crate::prepared_update::save(&cache, "main", version, "unused", &bytes).unwrap(); + let qualified: Value = serde_json::from_str(ARTIFACT_DEFAULT_CONTRACTS).unwrap(); + for contract in ["historical", "current"] { + identity["default_contract"] = qualified[contract].clone(); + fs::write(&identity_path, identity.to_string()).unwrap(); + let bytes = archive(&candidate); + crate::prepared_update::save(&cache, "main", version, "unused", &bytes).unwrap(); + } let pointer = fs::read(cache.join("prepared.json")).unwrap(); assert!(crate::prepared_update::save(&cache, "main", version, "unused", b"bad").is_err()); assert_eq!(fs::read(cache.join("prepared.json")).unwrap(), pointer); diff --git a/loopx/cli_commands/public_default_contract.json b/loopx/cli_commands/public_default_contract.json index e62060503f..65048651fc 100644 --- a/loopx/cli_commands/public_default_contract.json +++ b/loopx/cli_commands/public_default_contract.json @@ -1,5 +1,12 @@ { - "surface": "quota_packet", - "schema_version": null, - "interaction_schema_version": "loopx_interaction_contract_v0" + "current": { + "surface": "complete_turn", + "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0" + }, + "historical": { + "surface": "quota_packet", + "schema_version": null, + "interaction_schema_version": "loopx_interaction_contract_v0" + } } diff --git a/loopx/cli_commands/update_artifact.py b/loopx/cli_commands/update_artifact.py index afc6555e61..a77a71c550 100644 --- a/loopx/cli_commands/update_artifact.py +++ b/loopx/cli_commands/update_artifact.py @@ -31,9 +31,11 @@ from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN as REPOSITORY_PATTERN RUNTIME_ARTIFACT_SCHEMA_VERSION = "loopx_runtime_artifact_v1" -PUBLIC_DEFAULT_CONTRACT = json.loads( +_ARTIFACT_DEFAULT_CONTRACTS = json.loads( Path(__file__).with_name("public_default_contract.json").read_text(encoding="utf-8") ) +PUBLIC_DEFAULT_CONTRACT = _ARTIFACT_DEFAULT_CONTRACTS["current"] +HISTORICAL_DEFAULT_CONTRACT = _ARTIFACT_DEFAULT_CONTRACTS["historical"] SHA = re.compile(r"[0-9a-f]{40}") MAX_MANIFEST = 256 * 1024 MAX_ARCHIVE = 256 * 1024 * 1024 @@ -64,11 +66,11 @@ def standalone_source() -> str: source = source.replace(old, "\n" + binding + "\n", 1) # The public installer is one file, so embed the policy that the Python # publishers and the native updater read from the distribution contract. - binding_start = source.index("\nPUBLIC_DEFAULT_CONTRACT = ") - binding_end = source.index("\nSHA = ", binding_start) + binding_start = source.index("\n_ARTIFACT_DEFAULT_CONTRACTS = ") + binding_end = source.index("\nPUBLIC_DEFAULT_CONTRACT = ", binding_start) return ( source[:binding_start] - + f"\nPUBLIC_DEFAULT_CONTRACT = {PUBLIC_DEFAULT_CONTRACT!r}" + + f"\n_ARTIFACT_DEFAULT_CONTRACTS = {_ARTIFACT_DEFAULT_CONTRACTS!r}" + source[binding_end:] ) @@ -108,17 +110,11 @@ def read_json(url: str) -> dict[str, Any]: def validate_default_contract(value: object) -> dict[str, Any]: - """Keep public artifacts within the currently supported single-session default. - - This is a distribution compatibility boundary, not a model-benefit verdict. - A new complete-contract default needs its original matched outcome/full-cost - qualification before this supported scope can be extended. Engineering - installation checks cannot authorize that extension. - """ + """Require the current engineering default on newly published artifacts.""" if not isinstance(value, dict) or value != PUBLIC_DEFAULT_CONTRACT: raise ValueError( "Runtime default contract is unqualified for public adoption; " - "the C1 single-session outcome/full-cost and supported-profile qualification is required" + "the observed default must match the complete Turn distribution contract" ) return dict(value) @@ -141,9 +137,9 @@ def validate_manifest(value: dict[str, Any], *, revision: str | None = None) -> raise ValueError("Runtime artifact has no bounded download sources") for url in urls: safe_url(url) - # Historical v1 snapshots remain readable. Newly produced artifacts and - # the publisher require the observed contract; absence is not qualification. - if "default_contract" in value: + # Published v1 snapshots can omit the attestation or carry the old default. + # New archives must pass validate_default_contract on their observed writer. + if "default_contract" in value and value["default_contract"] != HISTORICAL_DEFAULT_CONTRACT: validate_default_contract(value["default_contract"]) return dict(value) diff --git a/scripts/qualify_runtime_artifact.py b/scripts/qualify_runtime_artifact.py index a8dc69b564..e9307fb5f5 100644 --- a/scripts/qualify_runtime_artifact.py +++ b/scripts/qualify_runtime_artifact.py @@ -20,7 +20,7 @@ def observe_default_contract(source: Path) -> dict: """Observe the candidate's real default writer in an isolated release fixture. No model runs, active Goal or saved operator configuration participates. - Explicit complete-contract opt-in is intentionally not the default probe. + Probe the ordinary invocation, with inline transport for direct schema inspection. """ source = source.resolve() with tempfile.TemporaryDirectory(prefix="loopx-default-contract-") as raw: diff --git a/tests/test_runtime_snapshot_publication.py b/tests/test_runtime_snapshot_publication.py index df4d5478fd..210582293a 100644 --- a/tests/test_runtime_snapshot_publication.py +++ b/tests/test_runtime_snapshot_publication.py @@ -13,7 +13,11 @@ import pytest import yaml -from loopx.cli_commands.update_artifact import PUBLIC_DEFAULT_CONTRACT, validate_default_contract +from loopx.cli_commands.update_artifact import ( + HISTORICAL_DEFAULT_CONTRACT, + PUBLIC_DEFAULT_CONTRACT, + validate_default_contract, +) ROOT = Path(__file__).resolve().parents[1] REVISION = "a" * 40 @@ -136,7 +140,7 @@ def publish(root): @pytest.mark.parametrize("failure", [ "missing", "invalid_json", "failed", "incomplete", "wrong_revision", "wrong_channel", "wrong_size", "wrong_digest", "archive_changed", "manifest_changed", "frozen_manifest_changed", "truthy_status", - "missing_contract", "unknown_contract", "c1_default", "mismatched_contract", "missing_observed_contract", + "missing_contract", "unknown_contract", "historical_default", "mismatched_contract", "missing_observed_contract", ]) def test_unqualified_runtime_never_changes_remote_state(publication, failure): qualification = publication / "runtime" / f"qualification-{REVISION}.json" @@ -147,14 +151,14 @@ def test_unqualified_runtime_never_changes_remote_state(publication, failure): qualification.write_text("{", encoding="utf-8") elif failure == "frozen_manifest_changed": (publication / "runtime" / f"loopx-runtime-{REVISION}.json").write_text("{}", encoding="utf-8") - elif failure in {"missing_contract", "unknown_contract", "c1_default"}: + elif failure in {"missing_contract", "unknown_contract", "historical_default"}: path = publication / "runtime/loopx-runtime.json" data = json.loads(path.read_text(encoding="utf-8")) if failure == "missing_contract": data.pop("default_contract") else: - profile = {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", - "interaction_schema_version": "loopx_interaction_contract_v0"} if failure == "c1_default" else {"surface": "future"} + profile = (HISTORICAL_DEFAULT_CONTRACT + if failure == "historical_default" else {"surface": "future"}) data["default_contract"] = record["default_contract"] = profile # All engineering checks, identities and frozen bytes still agree. for name in ["loopx-runtime.json", f"loopx-runtime-{REVISION}.json"]: @@ -334,8 +338,7 @@ def observe(source: Path) -> dict: assert (source / "loopx/fixture.txt").read_text(encoding="utf-8") == "public fixture" if supported: return dict(PUBLIC_DEFAULT_CONTRACT) - return {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", - "interaction_schema_version": "loopx_interaction_contract_v0"} + return dict(HISTORICAL_DEFAULT_CONTRACT) monkeypatch.setattr(builder, "observe_default_contract", observe) output = tmp_path / "runtime" @@ -365,10 +368,6 @@ def observe(source: Path) -> dict: def test_release_probe_observes_real_default_without_model_or_active_goal(): from scripts.qualify_runtime_artifact import observe_default_contract - # Observe the new ordinary writer without disguising it as the qualified - # historical default. Engineering cutover does not grant release adoption. - observed = observe_default_contract(ROOT) - assert observed["surface"] == "complete_turn" - assert observed["schema_version"] == "loopx_turn_envelope_v1" - with pytest.raises(ValueError, match="unqualified for public adoption"): - validate_default_contract(observed) + observed = validate_default_contract(observe_default_contract(ROOT)) + assert observed == {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0"} diff --git a/tests/test_update_artifact.py b/tests/test_update_artifact.py index 936072fdd6..177c70499c 100644 --- a/tests/test_update_artifact.py +++ b/tests/test_update_artifact.py @@ -28,6 +28,8 @@ def test_exported_bootstrap_validates_metadata_without_an_installed_package(tmp_ assert module['validate_manifest'](value)==value profile = module['PUBLIC_DEFAULT_CONTRACT'] assert module['validate_manifest']({**value, 'default_contract':profile})['default_contract']==profile +history = module['HISTORICAL_DEFAULT_CONTRACT'] +assert module['validate_manifest']({**value, 'default_contract':history})['default_contract']==history for invalid in [None, {}, {'surface':'complete_turn','schema_version':'loopx_turn_envelope_v1'}, {'surface':'unknown'}]: try:module['validate_manifest']({**value,'default_contract':invalid}) except ValueError:pass @@ -98,7 +100,7 @@ def manifest(body: bytes, url: str): @pytest.mark.parametrize("profile", [None, {}, {"surface": "future"}, - {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", + {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v0", "interaction_schema_version": "loopx_interaction_contract_v0"}]) def test_unqualified_default_stops_before_download_or_activation(monkeypatch, profile): descriptor = {**manifest(b"runtime", "https://publisher.invalid/runtime"), "default_contract": profile} @@ -113,6 +115,8 @@ def test_unqualified_default_stops_before_download_or_activation(monkeypatch, pr def test_qualified_scope_and_historical_metadata_remain_readable(): historical = manifest(b"runtime", "https://publisher.invalid/runtime") assert update.validate_manifest(historical) == historical + published = {**historical, "default_contract": dict(update.HISTORICAL_DEFAULT_CONTRACT)} + assert update.validate_manifest(published) == published current = {**historical, "default_contract": dict(update.PUBLIC_DEFAULT_CONTRACT)} assert update.validate_manifest(current) == current From 93d225cbe6bc0c4cac1c74c1d3b42648f4629bd4 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:19:56 +0800 Subject: [PATCH 3/5] Retire legacy Turn format selectors from current hosts Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- benchmark/edgebench/README.md | 34 +++--- benchmark/edgebench/run.py | 13 +-- benchmark/runtime/RUNTIME.md | 36 +++---- benchmark/runtime/SETTINGS.md | 2 +- benchmark/runtime/checkpoint.py | 8 +- benchmark/runtime/checkpoint_wake.py | 5 +- benchmark/runtime/codex.py | 27 ++--- benchmark/runtime/harbor.py | 13 +-- benchmark/runtime/sforge.py | 5 +- benchmark/runtime/worker.py | 71 +----------- .../tests/test_edgebench_registration.py | 12 +-- benchmark/tests/test_native_checkpoint.py | 7 +- benchmark/tests/test_sforge_runtime.py | 38 +++---- benchmark/tests/test_sforge_turn.py | 4 +- benchmark/tests/test_shared_codex_runtime.py | 102 ++---------------- benchmark/tests/test_task_entry.py | 9 +- benchmark/tests/test_worker_phase_budget.py | 39 ------- .../contract-and-context.md | 28 +++-- .../contract-and-context.zh-CN.md | 19 ++-- docs/heartbeat-automation-prompt.md | 4 +- .../agent-facing-trajectory-quality.md | 6 +- docs/product/releases/v2.4.0.md | 20 ++-- .../codex-cli/codex-cli-automation-driver.md | 2 +- docs/reference/protocols/loopx-turn-v0.md | 2 +- docs/reference/protocols/turn-envelope-v0.md | 34 +++--- docs/reference/required-work-context.md | 9 +- loopx/cli_commands/quota_context.py | 4 - loopx/cli_commands/quota_context_reader.py | 4 +- loopx/cli_commands/quota_native_context.py | 5 +- loopx/cli_commands/quota_registration.py | 12 --- loopx/cli_commands/quota_request.py | 2 +- .../cli_commands/support_control_heartbeat.py | 2 - .../support_control_heartbeat_registration.py | 11 -- loopx/control_plane/heartbeat/builder.py | 4 - loopx/control_plane/heartbeat/host.py | 6 -- .../testing/cli_output_budget.py | 14 +-- loopx/hosts/codex_checkpoint.py | 13 +++ .../test_quota_closeout_query_failure.py | 5 +- tests/control_plane/test_agent_preferences.py | 2 +- .../test_benchmark_planning_batch.py | 2 +- tests/control_plane/test_cli_output_budget.py | 4 +- .../test_codex_context_capture.py | 6 +- .../test_context_delivery_cli.py | 3 +- .../control_plane/test_context_first_read.py | 28 +++-- .../test_dated_vision_wait_cli.py | 3 +- .../test_effect_runtime_host_permission.py | 4 +- .../test_effective_turn_replan.py | 2 +- .../test_explore_settlement_attachment.py | 2 +- tests/control_plane/test_heartbeat_cli.py | 3 +- .../test_heartbeat_command_authority.py | 3 +- .../test_heartbeat_envelope_transport.py | 65 ++++------- .../control_plane/test_open_outcome_replan.py | 2 +- .../test_progressive_native_context.py | 5 +- .../test_quota_decision_capture.py | 29 +++-- .../test_quota_execution_preparation.py | 2 - tests/control_plane/test_quota_selection.py | 9 +- .../control_plane/test_refresh_settle_turn.py | 21 ++-- .../test_replan_progress_native_cli.py | 5 +- .../control_plane/test_replan_staged_read.py | 15 +-- .../test_replan_successor_guard_reentry.py | 4 +- .../test_saved_context_project.py | 2 +- .../test_selected_work_requirements.py | 23 ++-- .../test_selection_replan_reentry.py | 4 +- .../test_settlement_input_discovery_cli.py | 2 +- .../test_turn_envelope_capability_facts.py | 4 +- .../test_turn_envelope_settlement.py | 7 +- .../test_turn_host_context_delivery.py | 4 +- .../test_work_acceptance_context.py | 2 +- .../test_work_context_host_delivery.py | 4 +- .../control_plane/test_work_yardstick_cli.py | 2 +- .../test_worker_observation_recovery_cli.py | 8 +- tests/test_delegation_turn_context.py | 2 +- 72 files changed, 284 insertions(+), 630 deletions(-) diff --git a/benchmark/edgebench/README.md b/benchmark/edgebench/README.md index 7a790c98e5..c1ac08a1f3 100644 --- a/benchmark/edgebench/README.md +++ b/benchmark/edgebench/README.md @@ -955,8 +955,8 @@ effective work Turns** by default. Use `--replan-after-turns N` to set a differe count (1–6); `--replan-after-turns 3` retains the previous benchmark default. Use `--replan-after-todos 3` for the previous completed-Todo cadence as an explicit ablation. The two options are mutually exclusive and require a -heartbeat profile. This default is independent of `--task-entry`, feedback mode, -and `--turn-envelope`. Official, single and native-goal profiles are unchanged. +heartbeat profile. This default is independent of `--task-entry` and feedback mode. +Official, single and native-goal profiles are unchanged. The shared control plane counts settled work Turns, not tool calls or idle wakes; other replan reasons may trigger sooner. Both runtime and worker-profile receipts @@ -1005,26 +1005,16 @@ review, proposal adoption and task gains require trajectory evidence. ## Quota input and historical Short -Current C1 sources give both heartbeat profiles the complete v1 input by -default. `--complete-turn` explicitly requests the complete contract, including -on supported historical product revisions. Context delivery remains a separate -setting. The [Host protocol](../../docs/reference/protocols/turn-envelope-v0.md#explicit-complete-v1-host-entry--显式完整-v1-host-入口) -documents original captures, readback and settlement. - -For a historical Short benchmark arm, use its recorded product and runner -revisions. With `--turn-envelope`, the current worker verifies the selected CLI's -actual v0 response using a read-only preview before starting a model. C1 or an -unavailable preview rejects the request. A `fresh_replan` checkpoint preloads a -different view and is incompatible with Short. Inspect the wake's -`quota_input_contract` eligibility and the actual saved decision before using -a result in a comparison. Include startup and wake costs under the same study -protocol. - -中文:当前 C1 的两种 heartbeat profile 默认交付完整 v1,`--complete-turn` -也可在支持的历史产品版本中显式选择完整输入。旧 Short 组应按记录的产品和 runner -版本复现。当前 worker 在启动模型前用只读预演核实 v0,回执 -`quota_input_contract` 记录预期、实测版本与资格。C1 或无法核实的来源会拒绝请求。 -`fresh_replan` 会预载另一种输入,因此不能与 Short 合用。 +Both heartbeat profiles use complete v1. Context delivery remains a separate +setting. See the [Host protocol](../../docs/reference/protocols/turn-envelope-v0.md#complete-v1-host-entry--完整-v1-host-入口) +for original captures, readback and settlement. + +Reproduce historical Short and explicit Complete treatments on their recorded +product and runner revisions. Review the original decision, wake receipt and +complete startup and wake costs before using the result in a comparison. + +中文:两种 heartbeat profile 默认使用完整 v1,交付传输单独配置。复现历史 Short +或显式 Complete 组时按原产品和 runner 版本执行,并核对原决策、回执和完整成本。 ## Close a managed native attempt diff --git a/benchmark/edgebench/run.py b/benchmark/edgebench/run.py index e679d04b05..d8d7fd9b68 100644 --- a/benchmark/edgebench/run.py +++ b/benchmark/edgebench/run.py @@ -30,7 +30,7 @@ from sforge.harness.run_agent import run_agent from sforge.harness.task_spec import make_task_spec -from benchmark.runtime.codex import TASK_ENTRIES, turn_envelope_receipt +from benchmark.runtime.codex import TASK_ENTRIES from loopx.reasoning_effort import REASONING_EFFORTS from loopx.control_plane.work_items.stride_policy_codec import stride_strategy_options from benchmark.runtime.sforge import ( @@ -124,11 +124,6 @@ def main(argv=None): help="New-run default: native public feedback; blind/best-only are explicit controls") parser.add_argument("--managed-run-json", type=Path, help="Opt-in private binding for native terminal proof, consumed by the controller") - turn_view = parser.add_mutually_exclusive_group() - turn_view.add_argument("--turn-envelope", action="store_true", - help="Historical Short envelope treatment; the worker requires a verified v0 quota response") - turn_view.add_argument("--complete-turn", action="store_true", - help="Explicit complete v1 Turn contract with shared exact-Turn settlement; heartbeat workers only") parser.add_argument("--context-delivery", choices=("off", "on"), help="Native Codex context delivery: on by default for heartbeat workers; pass off to disable") parser.add_argument("--execution-observation", choices=("local_probe",), @@ -213,8 +208,7 @@ def main(argv=None): try: execution = profile_execution( args.worker, task_entry=args.task_entry, - context_delivery=args.context_delivery, turn_envelope=args.turn_envelope, - complete_turn=args.complete_turn, validation_command=args.validation_command_json, + context_delivery=args.context_delivery, validation_command=args.validation_command_json, native_child_limit=args.native_child_limit, ) except ValueError as error: @@ -462,8 +456,6 @@ def main(argv=None): task_objective=task_objective, task_entry=args.task_entry, validation_command=execution.validation_command, - turn_envelope=args.turn_envelope, - **({"complete_turn": True} if args.complete_turn else {}), context_delivery=args.context_delivery, **({"execution_observation": args.execution_observation} if args.execution_observation is not None else {}), @@ -548,7 +540,6 @@ def main(argv=None): "loopx_commit": pins[0], "runner_commit": pins[1], "sforge_source": sforge_source if native_result_scope is not None else active_source_receipt(), "local_docker_images": local_docker_images, - **turn_envelope_receipt(explicit=args.turn_envelope, complete=args.complete_turn), **({"context_delivery": "on"} if args.context_delivery != "off" else {}), **({"execution_observation": args.execution_observation} if args.execution_observation is not None else {}), diff --git a/benchmark/runtime/RUNTIME.md b/benchmark/runtime/RUNTIME.md index e5385db2dd..df46fea0b8 100644 --- a/benchmark/runtime/RUNTIME.md +++ b/benchmark/runtime/RUNTIME.md @@ -81,30 +81,20 @@ agents: replan_after_turns: 6 ``` -Historical Short trials request `turn_envelope: true` in heartbeat `kwargs`. -Before planning or execution starts a model, the worker previews the selected -product's quota response through the same CLI. Its wake receipt records the -expected and observed versions and eligibility in `quota_input_contract`. C1 -sources return v1 and the Short request fails before Host preparation. A -`fresh_replan` checkpoint preloads a distinct view and also prevents a Short -launch. The preview has no Turn identity and creates no admission or capture. -Ordinary and explicit Complete wakes proceed without this Short preview. - -Use the recorded product and runner revisions to reproduce a historical -treatment. On a qualified v0 source, an execution wake records -`turn_envelope_source=explicit` once it renders the Short bootstrap. Its -same-invocation full decision remains available through `detail_ref.full_decision`. -The planning prompt has its own input. Include the preview in startup -and wake cost when measuring a new attempt with this runner. Keep captures -private and preserve the settings and receipts of existing attempts. +Historical Short trials used `turn_envelope: true` and verified a v0 guard +response before launching a model. Reproduce them with their recorded product +and runner revisions. Include the original preview in startup and wake cost. +The current runner rejects explicit historical display requests before Host +preparation. Current heartbeat runs use the complete v1 default. Preserve the +original decision, preview eligibility and complete settings of frozen runs. New native heartbeat trials default to context delivery `on`. Add `context_delivery: "off"` to the same heartbeat agent `kwargs` to disable it. An explicit off is pinned into both native tools and worker preflight; it cannot inherit a machine-wide on. Plain, native-Goal and Turn execution remain off. Only the existing Codex heartbeat worker accepts `"on"`; booleans, other modes and -scenario names are rejected. This is an experimental transport setting, separate -from `turn_envelope`. +scenario names are rejected. This transport setting preserves the default +complete v1 source. The existing EdgeBench/SForge entry exposes the same selection through `--context-delivery off` to disable a heartbeat worker's on default. Existing running or frozen trials retain their recorded source and treatment; do not @@ -224,12 +214,10 @@ Do not modify an active/frozen trial. Set `context_delivery: "off"` for a new tr to roll back; default runs install no hooks, trust or trace settings. No scorer, budget, task semantics or launch authority changes with this option. -Checkpoint capture is independent of this display experiment. A `fresh_replan` -declaration may establish a private capture/handoff socket while -`turn_envelope` remains false: the worker keeps the ordinary dispatcher and quota -input, and only an explicit true setting selects the short view. This replaces -the earlier implicit activation by checkpoint handoff. Do not relabel older -receipts or trajectories as feature-off; qualify their actual input separately. +A `fresh_replan` declaration can establish a private capture and handoff socket +with either inline or progressive delivery. Both consume the same complete v1 +decision. Interpret old receipts and trajectories according to their recorded +treatment and product revision. | Mode | Execution/continuation | LoopX skills and state | | --- | --- | --- | diff --git a/benchmark/runtime/SETTINGS.md b/benchmark/runtime/SETTINGS.md index c6004e9b2f..a136b70794 100644 --- a/benchmark/runtime/SETTINGS.md +++ b/benchmark/runtime/SETTINGS.md @@ -48,7 +48,7 @@ These are recommendations, not automatically launched experiments. | Reference | `--worker heartbeat-resume --task-entry loopx-planned --replan-after-turns 6` | Planned entry with effective-turn replanning | | Seeded | Replace only `--task-entry` with `seeded-todo` | Does initial task decomposition help? | | Explore | Replace only `--worker` with `heartbeat-explore` | Are recorded evidence and subsequent route choices useful? | -| Historical Short envelope | Use the recorded product and runner revisions with `--turn-envelope`; the current worker verifies v0 before launch | Does short input with reachable original detail reduce overhead while preserving decisions? | +| Historical Short envelope | Use the recorded product and runner revisions and check the original v0 receipt | Does short input with reachable original detail reduce overhead while preserving decisions? | | Todo cadence | Replace `--replan-after-turns 6` with `--replan-after-todos 3` | How do units and thresholds change interruptions? This is a combined ablation. | | No LoopX | `--worker official`; omit LoopX-specific flags | What is the net effect of the whole LoopX treatment? | diff --git a/benchmark/runtime/checkpoint.py b/benchmark/runtime/checkpoint.py index 1a14d1d6d1..38719914f4 100644 --- a/benchmark/runtime/checkpoint.py +++ b/benchmark/runtime/checkpoint.py @@ -24,7 +24,7 @@ research_participants, verify_research_participants, ) from .checkpoint_handoff import CHECKPOINT_CAPTURE_SECONDS -from .codex import explicit_turn_display +from .codex import reject_retired_turn_display def normalize_checkpoint_request_path(value: str) -> str: @@ -222,7 +222,7 @@ def capture_before_replan(env: dict[str, str], receipt: dict[str, Any], body: st raise ValueError("fresh_replan checkpoint trigger requires a heartbeat execute wake") started = time.monotonic() guard_path = Path(env["LOOPX_WAKE_LOG_DIR"]) / receipt["turn_id"] / "checkpoint-start-guard.json" - # Use the CLI's original-decision capture, including with TurnEnvelope off. + # Use the CLI's original-decision capture even with inline delivery. # The checkpoint selector needs the full source; the model consumes the # ordinary CLI projection of those same bytes, never a second guard. capture_root = Path(tempfile.mkdtemp(prefix="checkpoint-start-", dir=guard_path.parent)) @@ -231,9 +231,7 @@ def capture_before_replan(env: dict[str, str], receipt: dict[str, Any], body: st "--goal-id", env["LOOPX_GOAL_ID"], "--agent-id", env["LOOPX_AGENT_ID"], "--runtime-profile", "generic_cli", "--turn-instance-id", receipt["turn_id"], "--available-capability", "shell", "--available-capability", "filesystem_write"] - display = explicit_turn_display(env) - if display.complete_turn: - command.append("--complete-turn") + reject_retired_turn_display(env) native_context = env.get("LOOPX_CONTEXT_DELIVERY") == "on" and bool(env.get("LOOPX_CODEX_CONTEXT_DIR")) if native_context: # The native reader selects full/delta after SessionStart. Ask the diff --git a/benchmark/runtime/checkpoint_wake.py b/benchmark/runtime/checkpoint_wake.py index b28cdb3bba..661c8a8010 100644 --- a/benchmark/runtime/checkpoint_wake.py +++ b/benchmark/runtime/checkpoint_wake.py @@ -135,9 +135,8 @@ def _capture(self, held, deadline): "registry": self.env["LOOPX_REGISTRY"], "runtime_root": self.env["LOOPX_RUNTIME_ROOT"], "goal_id": self.env["LOOPX_GOAL_ID"], "agent_id": self.env["LOOPX_AGENT_ID"], "turn_instance_id": held["quota"]["heartbeat_receipt"]["turn_instance_id"], - # Generated guards use the default complete v1 contract without emitting - # --complete-turn; bind the CLI flag explicitly so retired aliases are rejected. - "turn_envelope": self.receipt.get("turn_envelope", False), + # Pin the current command grammar against the recorded invocation. + "turn_envelope": False, "complete_turn": False, "capture_root": str(self.capture_root), "socket_path": self.socket_path, "decision_sha256": held["sha256"]} diff --git a/benchmark/runtime/codex.py b/benchmark/runtime/codex.py index 8766af77fb..70d10d888d 100644 --- a/benchmark/runtime/codex.py +++ b/benchmark/runtime/codex.py @@ -44,10 +44,8 @@ def __post_init__(self) -> None: object.__setattr__(self, "context_delivery", "on" if self.mode == "heartbeat" else "off") if self.context_delivery not in ("off", "on") or (self.context_delivery != "off" and self.mode != "heartbeat"): raise ValueError("context_delivery supports only off or on with heartbeat execution") - if not isinstance(self.turn_envelope, bool) or (self.turn_envelope and self.mode != "heartbeat"): - raise ValueError("turn_envelope requires heartbeat execution and a boolean opt-in") - if type(self.complete_turn) is not bool or (self.complete_turn and (self.mode != "heartbeat" or self.turn_envelope)): - raise ValueError("complete_turn requires heartbeat execution without legacy turn_envelope") + if self.turn_envelope is not False or self.complete_turn is not False: + raise ValueError("Historical turn_envelope and complete_turn treatments require the recorded product and runner revisions") if self.mode not in MODES or self.context not in CONTEXTS: raise ValueError("unsupported execution mode or iteration context") if self.task_entry is None: @@ -89,22 +87,11 @@ def native_goal(self) -> bool: return self.mode in {"native-goal", "loopx-goal"} -def turn_envelope_receipt(*, explicit: bool, complete: bool = False) -> dict: - """Record only the explicit display opt-in; checkpoint capture is independent.""" - return {**({"turn_envelope": True, "turn_envelope_source": "explicit"} if explicit else {}), - **({"complete_turn": True, "complete_turn_source": "explicit"} if complete else {})} - - -def explicit_turn_display(env: dict[str, str]) -> Execution: - """Decode the shared explicit display request through its Execution owner.""" - selected = {} - for variable, field in (("LOOPX_TURN_ENVELOPE", "turn_envelope"), - ("LOOPX_COMPLETE_TURN", "complete_turn")): - value = env.get(variable, "0") - if value not in {"0", "1"}: - raise ValueError(f"{variable} must be 0 or 1") - selected[field] = value == "1" - return Execution(**selected) +def reject_retired_turn_display(env: dict[str, str]) -> None: + """Fail historical requests before a new benchmark can use the wrong treatment.""" + for variable in ("LOOPX_TURN_ENVELOPE", "LOOPX_COMPLETE_TURN"): + if env.get(variable, "0") != "0": + raise ValueError(f"{variable} requires the recorded historical product and runner revisions") def native_child_instructions(limit: int | None) -> str: diff --git a/benchmark/runtime/harbor.py b/benchmark/runtime/harbor.py index b90d81b660..93a45afe34 100644 --- a/benchmark/runtime/harbor.py +++ b/benchmark/runtime/harbor.py @@ -21,7 +21,7 @@ from loopx.control_plane.goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL from .codex_offline import MODEL_CATALOG_REMOTE, CodexOffline, stage_portable_python -from .codex import DEFAULT_REPLAN_AFTER_TURNS, Execution, turn_envelope_receipt +from .codex import DEFAULT_REPLAN_AFTER_TURNS, Execution from .layout import _ROOT, _SRC, _CONTROL, _CODEX_HOME, _REGISTRY, _LOOPX_RUNTIME from .scheduler import phase_work_reserve @@ -193,9 +193,8 @@ def __init__( if (self._get_env("CODEX_WIRE_API") or "responses") != "responses": raise ValueError("provider_request_admission requires the Responses wire API") - def _turn_envelope_receipt(self) -> dict: - return {**turn_envelope_receipt(explicit=self.execution.turn_envelope, complete=self.execution.complete_turn), - **({"native_child_limit": self.execution.native_child_limit} + def _host_context_receipt(self) -> dict: + return {**({"native_child_limit": self.execution.native_child_limit} if self.execution.native_child_limit is not None else {}), **({"context_delivery": "on"} if self.execution.context_delivery != "off" else {})} @@ -412,7 +411,7 @@ async def install(self, environment: BaseEnvironment) -> None: "task_entry": self.execution.task_entry, **({"execution_observation": self.execution_observation} if self.execution_observation is not None else {}), - **self._turn_envelope_receipt(), + **self._host_context_receipt(), **self._planning_receipt(), **({"provider_request_admission": "on"} if self.provider_request_admission else {}), "home_scope": "trial", @@ -692,8 +691,6 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]: if self.execution_observation is not None else {}), **({"LOOPX_CHECKPOINT_REQUEST": self.checkpoint_request_path} if self.checkpoint_request_path is not None else {}), - **({"LOOPX_TURN_ENVELOPE": "1"} if self.execution.turn_envelope else {}), - "LOOPX_COMPLETE_TURN": "1" if self.execution.complete_turn else "0", "LOOPX_CONTEXT_DELIVERY": self.execution.context_delivery, # A trial's explicit None must not inherit a container opt-in. "LOOPX_NATIVE_CHILD_LIMIT": ( @@ -829,7 +826,7 @@ def token_delta(key: str) -> int | None: "execution_mode": self.execution.mode, "iteration_context": self.execution.context, "task_entry": self.execution.task_entry, - **self._turn_envelope_receipt(), + **self._host_context_receipt(), **self._planning_receipt(), **({"provider_request_admission": "on"} if self.provider_request_admission else {}), "home_scope": "trial", diff --git a/benchmark/runtime/sforge.py b/benchmark/runtime/sforge.py index 6887532256..016855985c 100644 --- a/benchmark/runtime/sforge.py +++ b/benchmark/runtime/sforge.py @@ -138,7 +138,6 @@ def __init__(self, config, *, profile: str, cwd: str, complete_turn=complete_turn, validation_command=validation_command, native_child_limit=native_child_limit, ) - self.turn_envelope = self.execution.turn_envelope self.context_delivery = self.execution.context_delivery self.task_entry = self.execution.task_entry self.native_child_limit = self.execution.native_child_limit @@ -421,8 +420,6 @@ def _install_worker(self, backend, handle, log_dir, logger): turn_timeout_sec=None, scheduler_timeout_sec=self.timeout_seconds, task_entry=self.task_entry, - turn_envelope=self.turn_envelope, - **({"complete_turn": True} if self.execution.complete_turn else {}), context_delivery=self.context_delivery, **({"execution_observation": self.execution_observation} if self.execution_observation is not None else {}), @@ -530,7 +527,7 @@ def _install_worker(self, backend, handle, log_dir, logger): "stop_hook": self.profile == "official", **({"native_child_limit": self.native_child_limit} if self.native_child_limit is not None else {}), - **(self.runtime._turn_envelope_receipt() if self.runtime is not None else {}), + **(self.runtime._host_context_receipt() if self.runtime is not None else {}), **({"provider_request_admission": "on"} if self.provider_request_admission else {}), **({"native_goal_continue": True} if self.native_goal_continue else {}), **({"native_readiness_budget": dict(zip(("total_seconds", "attempt_seconds"), diff --git a/benchmark/runtime/worker.py b/benchmark/runtime/worker.py index 8b234e193b..db525ee515 100644 --- a/benchmark/runtime/worker.py +++ b/benchmark/runtime/worker.py @@ -16,10 +16,9 @@ from benchmark.runtime.codex import ( Execution, - explicit_turn_display, + reject_retired_turn_display, prepare_codex_home, process_environment, - turn_envelope_receipt, ) from benchmark.runtime.scheduler import PHASE_WORK_RESERVE_SECONDS as PHASE_WORK_RESERVE_SECONDS @@ -101,19 +100,15 @@ def heartbeat_body(env: dict[str, str], turn_id: str, *, native_goal: bool, ] if not native_goal: command += ["--turn-instance-id", turn_id] - display = explicit_turn_display(env) + reject_retired_turn_display(env) context_dir = env.get("LOOPX_CODEX_CONTEXT_DIR") if env.get("LOOPX_CONTEXT_DELIVERY") == "on" else None - if display.complete_turn or display.turn_envelope or decision_handoff_socket is not None or context_dir: + if decision_handoff_socket is not None or context_dir: if native_goal: raise ValueError("TurnEnvelope capture requires a host-owned heartbeat Turn") # Wake identity comes from this worker, never from model-authored text. root = Path(env["LOOPX_WAKE_LOG_DIR"]) / turn_id / "decisions" root.mkdir(mode=0o700, exist_ok=False) command += ["--decision-output-root", str(root)] - if display.turn_envelope: - command += ["--turn-envelope"] - if display.complete_turn: - command += ["--complete-turn"] if decision_handoff_socket is not None: command += ["--decision-handoff-socket", decision_handoff_socket] if context_dir: @@ -530,61 +525,10 @@ def _phase_timeout(timeout: float | None, deadline: float | None) -> tuple[float return timeout, False -def _qualify_short_envelope(env: dict[str, str], receipt: dict) -> bool: - """Verify the pinned Short carrier, returning False if the phase expires.""" - from loopx.control_plane.quota.turn_envelope import ( - COMPLETE_TURN_DECISION_VERSION, - TURN_ENVELOPE_SCHEMA_VERSION, - ) - - contract = { - "expected_schema_version": TURN_ENVELOPE_SCHEMA_VERSION, - "observed_schema_version": None, - "eligible": False, - } - receipt.update(quota_input_contract=contract, host_invoked=False) - # This preview runs the same product projection without a Turn, capture, - # or admission. Keep optional delivery out of the carrier observation. - command = loopx_command(env) + [ - "quota", "should-run", "--dry-run", "--runtime-profile", "generic_cli", - "--goal-id", env["LOOPX_GOAL_ID"], "--agent-id", env["LOOPX_AGENT_ID"], - "--available-capability", "shell", "--available-capability", "filesystem_write", - "--turn-envelope", "--context-delivery", "off", - ] - deadline = env.get("LOOPX_PHASE_DEADLINE_EPOCH") - timeout, phase_limited = _phase_timeout(120, float(deadline) if deadline else None) - try: - result = subprocess.run(command, cwd=env["LOOPX_PROJECT"], env=env, - capture_output=True, text=True, timeout=timeout, check=True) - payload = read_json(result.stdout) - except (OSError, ValueError, subprocess.SubprocessError) as exc: - if phase_limited and isinstance(exc, subprocess.TimeoutExpired): - receipt.update(ok=True, budget_exhausted=True) - return False - raise ValueError("Short envelope requires a successful v0 quota preview from the pinned product.") from exc - if payload.get("ok") is not True: - raise ValueError("Short envelope requires a successful v0 quota preview from the pinned product.") - observed = payload.get("schema_version") - if observed in (TURN_ENVELOPE_SCHEMA_VERSION, COMPLETE_TURN_DECISION_VERSION): - contract["observed_schema_version"] = observed - if observed != TURN_ENVELOPE_SCHEMA_VERSION: - raise ValueError("Short envelope requires a verified v0 response from the pinned product. " - "Use the recorded historical source pins for that arm.") - if checkpoint_path := env.get("LOOPX_CHECKPOINT_REQUEST"): - from .checkpoint import read_checkpoint_request - - request, _ = read_checkpoint_request(checkpoint_path) - if request.get("trigger") == "fresh_replan": - raise ValueError("Short envelope requires the direct v0 guard. " - "A fresh_replan checkpoint preloads a different view.") - contract["eligible"] = True - return True - - def run_once(env: dict[str, str]) -> dict: if env.get("LOOPX_CONTEXT_DELIVERY", "off") not in {"off", "on"}: raise ValueError("LOOPX_CONTEXT_DELIVERY supports only off or on") - display = explicit_turn_display(env) + reject_retired_turn_display(env) execution = Execution( mode=env.get("LOOPX_EXECUTION_MODE", "heartbeat"), context=env.get("LOOPX_ITERATION_CONTEXT"), @@ -593,11 +537,9 @@ def run_once(env: dict[str, str]) -> dict: if env.get("LOOPX_CODEX_TURN_TIMEOUT_SEC") else None), validation_command=json.loads(env.get("LOOPX_VALIDATION_COMMAND_JSON", "[]")), task_entry=env.get("LOOPX_TASK_ENTRY"), - turn_envelope=display.turn_envelope, context_delivery=env.get("LOOPX_CONTEXT_DELIVERY"), native_child_limit=(int(env["LOOPX_NATIVE_CHILD_LIMIT"]) if env.get("LOOPX_NATIVE_CHILD_LIMIT") else None), - complete_turn=display.complete_turn, ) request_admission = False if env.get("LOOPX_PROVIDER_REQUEST_ADMISSION", "off") != "off": @@ -643,7 +585,6 @@ def run_once(env: dict[str, str]) -> dict: "task_entry": execution.task_entry, **({"execution_observation": observation_producer} if observation_producer is not None else {}), - **turn_envelope_receipt(explicit=False, complete=execution.complete_turn), **({"context_delivery": "on"} if execution.context_delivery != "off" else {}), **({"native_child_limit": execution.native_child_limit} if execution.native_child_limit is not None else {}), @@ -684,8 +625,6 @@ def run_once(env: dict[str, str]) -> dict: execution, timeout_seconds=(remaining - reserve if execution.timeout_seconds is None else min(execution.timeout_seconds, remaining - reserve)) ) - if execution.turn_envelope and not _qualify_short_envelope(env, receipt): - return receipt prepare_codex_home( home, execution=execution, @@ -735,8 +674,6 @@ def run_once(env: dict[str, str]) -> dict: elif execution.mode in {"heartbeat", "loopx-goal"}: body = heartbeat_body(env, turn_id, native_goal=execution.native_goal, decision_handoff_socket=checkpoint_wake.socket_path) - if execution.turn_envelope: - receipt.update(turn_envelope_receipt(explicit=True)) elif execution.mode == "plain": body = Path(env["LOOPX_TASK_DOC"]).read_text(encoding="utf-8") session_wake = None diff --git a/benchmark/tests/test_edgebench_registration.py b/benchmark/tests/test_edgebench_registration.py index fa40b725b8..4471534498 100644 --- a/benchmark/tests/test_edgebench_registration.py +++ b/benchmark/tests/test_edgebench_registration.py @@ -37,14 +37,12 @@ def native_cli(tmp_path, monkeypatch): return run, args, tmp_path / "runs/run/fixture" -@pytest.mark.parametrize("profile,complete_turn", [ - ("official", False), ("single", False), ("native-goal", False), - ("heartbeat-resume", False), ("heartbeat-explore", False), ("turn-resume", False), - ("heartbeat-resume", True), +@pytest.mark.parametrize("profile", [ + "official", "single", "native-goal", "heartbeat-resume", "heartbeat-explore", "turn-resume", ]) @pytest.mark.parametrize("custom_registration", [False, True]) def test_native_cli_prepares_registration_for_every_profile(native_cli, monkeypatch, - profile, complete_turn, custom_registration): + profile, custom_registration): from benchmark.runtime.sforge_backend import RecordingDockerBackend run, args, trial = native_cli @@ -78,7 +76,6 @@ def native_provider(*, host_registration_callback=None, **kwargs): assert events == ["prepare"] events.append("register") assert kwargs["agent"].profile == profile - assert kwargs["agent"].execution.complete_turn is complete_turn assert kwargs["eval_interval"] == 0 assert kwargs["submission_cooldown"] == 3600 assert kwargs["max_submissions"] is None @@ -97,7 +94,6 @@ def native_provider(*, host_registration_callback=None, **kwargs): monkeypatch.setattr(run, "run_agent", native_provider) with pytest.raises(RuntimeError, match="synthetic worker boundary"): run.main([*args, "--worker", profile, - *(["--complete-turn"] if complete_turn else []), *(["--validation-command-json", '["trusted-validator"]'] if profile == "turn-resume" else [])]) if custom_registration: assert events == ["prepare", "register", "bind"] @@ -109,7 +105,7 @@ def native_provider(*, host_registration_callback=None, **kwargs): assert receipt["feedback"] == "native" assert receipt["local_docker_images"] == _IMAGES assert ("validation_argv_sha256" in receipt) is (profile == "turn-resume") - assert ("complete_turn" in receipt) is complete_turn + assert "complete_turn" not in receipt assert "checkpoint_export_directory" not in receipt diff --git a/benchmark/tests/test_native_checkpoint.py b/benchmark/tests/test_native_checkpoint.py index d3a1c371a9..8d1319c2eb 100644 --- a/benchmark/tests/test_native_checkpoint.py +++ b/benchmark/tests/test_native_checkpoint.py @@ -1028,7 +1028,6 @@ def test_held_complete_guard_checkpoint_binds_original_settlement_mode(tmp_path, from benchmark.runtime.checkpoint import held_quota_decision from benchmark.runtime.checkpoint_wake import CheckpointWake - from benchmark.runtime.codex import turn_envelope_receipt from benchmark.runtime.worker import heartbeat_body from loopx.control_plane.effect_runtime import effect_runtime_result from loopx.control_plane.turn_driver.codex_agent_session import CodexAgentSession @@ -1062,14 +1061,12 @@ def test_held_complete_guard_checkpoint_binds_original_settlement_mode(tmp_path, "LOOPX_REGISTRY": str(registry), "LOOPX_RUNTIME_ROOT": str(runtime), "LOOPX_CLI": str(cli), "LOOPX_GOAL_ID": GOAL_ID, "LOOPX_AGENT_ID": AGENT_ID, "LOOPX_WAKE_LOG_DIR": str(tmp_path / "wakes"), "LOOPX_CHECKPOINT_REQUEST": str(declaration), - "LOOPX_CONTEXT_DELIVERY": "off", "LOOPX_TURN_ENVELOPE": "0", - "LOOPX_COMPLETE_TURN": "1"} + "LOOPX_CONTEXT_DELIVERY": "off"} session = CodexAgentSession(env, context="resume", sandbox="read-only", receipt={}) _store_codex_cli_session(runtime, lineage=session.lineage, session_scope="agent", session_id="fixture-session", goal_ref=session.goal_ref, session_profile_digest=session.digest) receipt = {"mode": "heartbeat", "stage": "execute", "turn_id": TURN_ID, - "session": {"session_id": "fixture-session"}, - **turn_envelope_receipt(explicit=False, complete=True)} + "session": {"session_id": "fixture-session"}} (tmp_path / "wakes" / TURN_ID).mkdir(parents=True) with CheckpointWake(env, receipt) as host: diff --git a/benchmark/tests/test_sforge_runtime.py b/benchmark/tests/test_sforge_runtime.py index 8c1668f02e..777342ae5f 100644 --- a/benchmark/tests/test_sforge_runtime.py +++ b/benchmark/tests/test_sforge_runtime.py @@ -691,9 +691,8 @@ async def installed(self, environment): assert profile["task_entry"] == entry assert profile["planning_horizon_goal"] is expected_horizon @pytest.mark.parametrize('profile', ['heartbeat-resume', 'heartbeat-explore']) -@pytest.mark.parametrize('enabled,complete', [(False, False), (True, False), (False, True)]) @pytest.mark.parametrize('cadence', [None, 2, 6]) -def test_envelope_treatment_reaches_shared_worker_and_receipts(tmp_path, monkeypatch, profile, enabled, complete, cadence): +def test_default_context_reaches_shared_worker_and_receipts(tmp_path, monkeypatch, profile, cadence): pytest.importorskip('sforge') pytest.importorskip('harbor') from sforge.harness.config import SForgeConfig @@ -703,28 +702,19 @@ async def installed(self, environment): pass # Transport only; the real renderer/guard test runs without a solver. monkeypatch.setattr(BenchmarkCodex, 'install', installed) worker = SForgeWorker(SForgeConfig(agent_model='fixture', agent_effort='xhigh'), - profile=profile, cwd='/task', turn_envelope=enabled, complete_turn=complete, + profile=profile, cwd='/task', replan_after_turns=cadence) worker.install_stop_hook(None, None, tmp_path, None) env = worker.runtime._worker_env(cwd='/task') - assert env.get('LOOPX_TURN_ENVELOPE') == ('1' if enabled else None) - assert worker.runtime.execution.turn_envelope is enabled - assert env['LOOPX_COMPLETE_TURN'] == ('1' if complete else '0') - assert worker.runtime.execution.complete_turn is complete + assert 'LOOPX_TURN_ENVELOPE' not in env and 'LOOPX_COMPLETE_TURN' not in env assert worker.runtime.replan_after_turns == (cadence or 6) receipt = json.loads((tmp_path / 'worker-profile.json').read_text()) assert receipt['outer_resume'] is False - assert receipt.get('complete_turn') is (True if complete else None) - assert receipt.get('turn_envelope') is (True if enabled else None) - if not enabled: - assert 'turn_envelope' not in receipt + assert 'complete_turn' not in receipt and 'turn_envelope' not in receipt from types import SimpleNamespace context = SimpleNamespace() worker.runtime._populate_context(context) - assert context.metadata.get('complete_turn') is (True if complete else None) - assert context.metadata.get('turn_envelope') is (True if enabled else None) - if not enabled: - assert 'turn_envelope' not in context.metadata + assert 'complete_turn' not in context.metadata and 'turn_envelope' not in context.metadata # The opt-in only changes context transport, not resume or model settings. assert env['LOOPX_ITERATION_CONTEXT'] == 'resume' assert env['REASONING_EFFORT'] == 'xhigh' @@ -776,10 +766,10 @@ async def installed(self, environment): pass # No provider login, install, native session or model is requested. monkeypatch.setattr(BenchmarkCodex, "install", installed) agent = SForgeWorker(SForgeConfig(agent_model="fixture", agent_effort="xhigh"), - profile=profile, cwd=str(project), complete_turn=True, context_delivery=delivery) + profile=profile, cwd=str(project), context_delivery=delivery) agent.install_stop_hook(None, None, tmp_path, None) env = agent.runtime._worker_env(cwd=str(project)) - assert env["LOOPX_COMPLETE_TURN"] == "1" and env["LOOPX_CONTEXT_DELIVERY"] == delivery + assert env["LOOPX_CONTEXT_DELIVERY"] == delivery source = Path(__file__).resolve().parents[2] turn = "original-complete-turn" wake = tmp_path / "wakes" / turn @@ -824,7 +814,10 @@ async def installed(self, environment): capture_output=True, text=True, check=True).stdout) assert "content" in packet else: - result = subprocess.run(["bash", "-c", block + " --todo-id " + TODO_ID], cwd=project, + suffix = ["--todo-id", TODO_ID] + if delivery == "off": + suffix += ["--decision-output-dir", str(wake / "decisions")] + result = subprocess.run(["bash", "-c", block + " " + shlex.join(suffix)], cwd=project, env=env, capture_output=True, text=True, check=True) packet = json.loads(result.stdout) original, = (wake / "decisions").rglob("decision.json") @@ -1045,7 +1038,6 @@ def test_invalid_checkpoint_declaration_rejects_before_trial_registration(tmp_pa (["--replan-after-turns", "2"], "replan_after_effective_turns", 2), (["--replan-after-todos", "3"], "replan_after_completed_todos", 3), ]) -@pytest.mark.parametrize("enabled", [False, True]) @pytest.mark.parametrize("entry", [None, "seeded-todo"]) @pytest.mark.parametrize("task,timeout_args,expected,interval", [ ("fixture", [], 64800, 0), @@ -1053,7 +1045,7 @@ def test_invalid_checkpoint_declaration_rejects_before_trial_registration(tmp_pa ("lean_analysis_proofs", [], 43200, 0), ("portfolio_risk_calibration", ["--timeout", "1800", "--eval-interval", "60"], 1800, 60), ("lean_analysis_proofs", ["--eval-interval", "0"], 43200, 0)]) -def test_edgebench_native_goal_preserves_task_with_resolved_entry_and_treatment(tmp_path, monkeypatch, enabled, task, timeout_args, expected, interval, entry, cadence_args, field, count): +def test_edgebench_native_goal_preserves_task_with_resolved_entry_and_treatment(tmp_path, monkeypatch, task, timeout_args, expected, interval, entry, cadence_args, field, count): pytest.importorskip("sforge") pytest.importorskip("harbor") from types import SimpleNamespace @@ -1098,7 +1090,7 @@ def stop_before_solver(**kwargs): if entry: args += ["--task-entry", entry] with pytest.raises(RuntimeError, match="synthetic launch failure"): - run.main(args + timeout_args + cadence_args + (["--turn-envelope"] if enabled else [])) + run.main(args + timeout_args + cadence_args) receipt = json.loads((tmp_path / f"runs/receipt/{task}/runtime-receipt.json").read_text()) assert receipt["task_entry"] == (entry or "loopx-planned") assert receipt["timeout_seconds"] == expected @@ -1110,9 +1102,7 @@ def stop_before_solver(**kwargs): other = ("replan_after_completed_todos" if field == "replan_after_effective_turns" else "replan_after_effective_turns") assert other not in receipt - assert ("turn_envelope" in receipt) is enabled - if enabled: - assert receipt["turn_envelope"] is True + assert "turn_envelope" not in receipt assert receipt["status"] == "runner_failed" diff --git a/benchmark/tests/test_sforge_turn.py b/benchmark/tests/test_sforge_turn.py index 07e5402a7b..d959e31a9c 100644 --- a/benchmark/tests/test_sforge_turn.py +++ b/benchmark/tests/test_sforge_turn.py @@ -31,8 +31,8 @@ def test_unsupported_arm_rejected_before_trial_reservation(tmp_path, args, capsy "--run-id", "fixture", "--model", "fixture", "--effort", "high", "--judge-url", "http://example.invalid", *args]) assert error.value.code == 2 - if "--complete-turn" in args: - assert "complete_turn requires heartbeat execution" in capsys.readouterr().err + for retired in {"--complete-turn", "--turn-envelope"}.intersection(args): + assert retired in capsys.readouterr().err assert not (tmp_path / "runs").exists() diff --git a/benchmark/tests/test_shared_codex_runtime.py b/benchmark/tests/test_shared_codex_runtime.py index cdca15e337..bcfd30f0bf 100644 --- a/benchmark/tests/test_shared_codex_runtime.py +++ b/benchmark/tests/test_shared_codex_runtime.py @@ -951,16 +951,10 @@ def test_default_execution_has_no_independent_turn_deadline(tmp_path): assert "--timeout-seconds" not in turn_command(env, execution, "wake-default") -@pytest.mark.parametrize("enabled,trigger,expected", [ - (False, None, None), - (True, None, "explicit"), - (False, "after_wake", None), - (False, "fresh_replan", None), - (True, "fresh_replan", "explicit"), -]) +@pytest.mark.parametrize("trigger", [None, "after_wake", "fresh_replan"]) @pytest.mark.parametrize("context_delivery", ["off", "on"]) @pytest.mark.parametrize("provider_request_admission", [False, True]) -def test_harbor_install_receipt_keeps_capture_independent_from_display(tmp_path, monkeypatch, enabled, trigger, expected, context_delivery, provider_request_admission): +def test_harbor_install_receipt_keeps_capture_independent_from_display(tmp_path, monkeypatch, trigger, context_delivery, provider_request_admission): pytest.importorskip("harbor") from benchmark.runtime.harbor import BenchmarkCodex, CodexOffline from benchmark.runtime.checkpoint_wake import CheckpointWake @@ -980,7 +974,7 @@ def test_harbor_install_receipt_keeps_capture_independent_from_display(tmp_path, "checkpoint_request": request.read_bytes()} provider_env = {"OPENAI_BASE_URL": "https://provider.invalid/v1", "OPENAI_API_KEY": "synthetic-provider-key", "CODEX_WIRE_API": "responses"} - agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture", turn_envelope=enabled, + agent = BenchmarkCodex(logs_dir=tmp_path, model_name="fixture", context_delivery=context_delivery, provider_request_admission=provider_request_admission, extra_env=provider_env, @@ -991,7 +985,6 @@ def test_harbor_install_receipt_keeps_capture_independent_from_display(tmp_path, # Real declaration parser and socket lifecycle, independent of the # metadata helper. Omitted trigger is legal after-wake capture. assert bool(wake.socket_path) is (trigger == "fresh_replan") - assert enabled is (expected is not None) commands = [] command_envs = {} async def no_op(*args, **kwargs): @@ -1025,8 +1018,7 @@ async def task_exec(**kwargs): if "install-local.sh" in command or " doctor " in command: assert command_envs[command]["LOOPX_USAGE_PING"] == "0" assert agent._worker_env(cwd="/task")["LOOPX_USAGE_PING"] == "0" - assert ("turn_envelope" in receipt) is (expected is not None) - assert receipt.get("turn_envelope_source") == expected + assert "turn_envelope" not in receipt assert receipt.get("context_delivery") == (context_delivery if context_delivery != "off" else None) assert agent._worker_env(cwd="/task")["LOOPX_CONTEXT_DELIVERY"] == context_delivery assert receipt.get("provider_request_admission") == ("on" if provider_request_admission else None) @@ -1035,90 +1027,18 @@ async def task_exec(**kwargs): assert worker_env["OPENAI_BASE_URL"] == provider_env["OPENAI_BASE_URL"] assert worker_env["OPENAI_API_KEY"] == provider_env["OPENAI_API_KEY"] assert provider_env["OPENAI_API_KEY"] not in json.dumps(receipt) - if expected: - assert receipt["turn_envelope"] is True +@pytest.mark.parametrize("setting", ["LOOPX_TURN_ENVELOPE", "LOOPX_COMPLETE_TURN"]) @pytest.mark.parametrize("stage", ["plan", "execute"]) -@pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_short_wake_rejects_c1_before_host_preparation(tmp_path, monkeypatch, stage, provider): - from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime - from tests.control_plane.test_quota_settlement_cli import ( - AGENT_ID, GOAL_ID, _heartbeat_receipt_count, _write_fixture, - ) - - isolate_sqlite_runtime(tmp_path, monkeypatch) - project, runtime, registry = _write_fixture(tmp_path, provider=provider) - state = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" - original_state = state.read_bytes() - wakes = tmp_path / "wakes" - home = tmp_path / "codex-home" - source = Path(__file__).resolve().parents[2] - env = dict( - os.environ, - PYTHONPATH=str(source), LOOPX_PYTHON=sys.executable, LOOPX_USAGE_PING="0", - LOOPX_CLI=str(Path(sys.executable).parent / "loopx"), - LOOPX_PROJECT=str(project), LOOPX_REGISTRY=str(registry), LOOPX_RUNTIME_ROOT=str(runtime), - LOOPX_GOAL_ID=GOAL_ID, LOOPX_AGENT_ID=AGENT_ID, LOOPX_WAKE_LOG_DIR=str(wakes), - LOOPX_CODEX_HOME=str(home), LOOPX_EXECUTION_MODE="heartbeat", - LOOPX_SHARED_SKILLS=str(tmp_path / "shared-skills"), - LOOPX_TASK_STAGE=stage, LOOPX_TURN_ENVELOPE="1", LOOPX_CONTEXT_DELIVERY="off", - MODEL_NAME="fixture", REASONING_EFFORT="low", - ) - - def unexpected_host_preparation(*args, **kwargs): - pytest.fail("A C1 response cannot start the Short envelope arm") +def test_retired_turn_display_rejected_before_worker_preparation(tmp_path, monkeypatch, setting, stage): + from benchmark.tests.test_resume_sessions import resume_env - monkeypatch.setattr(worker, "prepare_codex_home", unexpected_host_preparation) - with pytest.raises(ValueError, match="Short envelope requires"): + env = resume_env(tmp_path, monkeypatch) | {setting: "1", "LOOPX_TASK_STAGE": stage} + monkeypatch.setattr(worker, "prepare_codex_home", + lambda *_a, **_k: pytest.fail("Historical selection must fail before Host setup")) + with pytest.raises(ValueError, match="recorded historical product and runner revisions"): run_once(env) - receipt_path, = wakes.glob("*/receipt.json") - receipt = json.loads(receipt_path.read_text()) - assert receipt["ok"] is False and receipt["host_invoked"] is False - assert receipt["quota_input_contract"] == { - "expected_schema_version": "loopx_turn_envelope_v0", - "observed_schema_version": "loopx_turn_envelope_v1", - "eligible": False, - } - assert "turn_envelope_source" not in receipt - assert _heartbeat_receipt_count(runtime, receipt["turn_id"]) == 0 - assert state.read_bytes() == original_state - assert not home.exists() - - -@pytest.mark.parametrize("enabled", [False, True]) -def test_wake_receipt_preserves_opt_out(tmp_path, monkeypatch, enabled): - from benchmark.tests.test_resume_sessions import resume_env - env = resume_env(tmp_path, monkeypatch) - env["LOOPX_TURN_ENVELOPE"] = "1" if enabled else "0" - original_run = subprocess.run - previews = [] - - def legacy_preview(argv, **kwargs): - if argv[0] != "loopx" or "--dry-run" not in argv: - return original_run(argv, **kwargs) - previews.append(argv) - return subprocess.CompletedProcess(argv, 0, json.dumps({ - "ok": True, "schema_version": "loopx_turn_envelope_v0", - }), "") - - monkeypatch.setattr(worker.subprocess, "run", legacy_preview) - receipt = run_once(env) - assert receipt["ok"], receipt - assert ("turn_envelope" in receipt) is enabled - assert ("turn_envelope_source" in receipt) is enabled - assert ("quota_input_contract" in receipt) is enabled - assert len(previews) == int(enabled) - if enabled: - assert receipt["turn_envelope"] is True - assert receipt["turn_envelope_source"] == "explicit" - assert receipt["quota_input_contract"] == { - "expected_schema_version": "loopx_turn_envelope_v0", - "observed_schema_version": "loopx_turn_envelope_v0", - "eligible": True, - } - assert "should-run" in previews[0] and "--turn-envelope" in previews[0] - assert "--turn-instance-id" not in previews[0] and "--decision-output-root" not in previews[0] @pytest.mark.parametrize("observed", [ diff --git a/benchmark/tests/test_task_entry.py b/benchmark/tests/test_task_entry.py index 7db2a9ba09..ae31cb70de 100644 --- a/benchmark/tests/test_task_entry.py +++ b/benchmark/tests/test_task_entry.py @@ -1187,16 +1187,13 @@ def test_sforge_planning_entry_stops_retrying_after_the_attempt_limit(planning_e @pytest.mark.parametrize("context", ["fresh", "resume"]) @pytest.mark.parametrize("producer", [None, "local_probe"]) -@pytest.mark.parametrize("complete", [False, True]) @pytest.mark.parametrize("checkpoint_preflight", [False, True]) def test_execute_wake_keeps_host_clocks_out_of_fresh_and_resumed_input( - planning_env, context, producer, complete, checkpoint_preflight): + planning_env, context, producer, checkpoint_preflight): """Exercise the real worker/heartbeat CLI and capture its model transport input.""" from benchmark.runtime.research_probe import execution_observation_guidance env = planning_env | {"LOOPX_ITERATION_CONTEXT": context} - if complete: - env["LOOPX_COMPLETE_TURN"] = "1" if producer is not None: env["LOOPX_EXECUTION_OBSERVATION"] = producer if checkpoint_preflight: @@ -1238,9 +1235,9 @@ def test_execute_wake_keeps_host_clocks_out_of_fresh_and_resumed_input( assert "Research-loop execution evidence:" not in body assert receipt["session"]["action"] == ("resume" if context == "resume" else "start_new") assert "turn_envelope" not in receipt - assert receipt.get("complete_turn") is (True if complete else None) + assert "complete_turn" not in receipt assert "--complete-turn" not in body and "--turn-envelope" not in body - assert ("--decision-output-root" in body) is (complete or checkpoint_preflight) + assert ("--decision-output-root" in body) is checkpoint_preflight if checkpoint_preflight: original = Path(env["LOOPX_WAKE_LOG_DIR"]) / receipt["turn_id"] / "checkpoint-start-guard.json" assert json.loads(original.read_bytes())["schema_version"] == "loopx_turn_envelope_v1" diff --git a/benchmark/tests/test_worker_phase_budget.py b/benchmark/tests/test_worker_phase_budget.py index 2efdece8bf..a8895db90f 100644 --- a/benchmark/tests/test_worker_phase_budget.py +++ b/benchmark/tests/test_worker_phase_budget.py @@ -259,45 +259,6 @@ def setup_failure(*a, **kw): assert not (project / "native-starts").exists() -@pytest.mark.parametrize("phase_limited", [True, False], ids=["phase", "preview"]) -def test_short_preview_timeout_preserves_its_selected_limit(tmp_path, monkeypatch, phase_limited): - import subprocess - - env, project, runtime, _source, state, clock = _phase_worker( - tmp_path, monkeypatch, work_seconds=1 if phase_limited else 300) - env["LOOPX_TURN_ENVELOPE"] = "1" - before = state.read_bytes() - original_run = subprocess.run - previews = [] - - def time_out_preview(argv, **kwargs): - if argv[0] != env["LOOPX_CLI"] or "--dry-run" not in argv: - return original_run(argv, **kwargs) - assert "--turn-envelope" in argv and "--turn-instance-id" not in argv - previews.append(kwargs["timeout"]) - # The clock can pass the deadline before handling either error. - clock[0] = float(env["LOOPX_PHASE_DEADLINE_EPOCH"]) + 1 - raise subprocess.TimeoutExpired(argv, kwargs["timeout"]) - - monkeypatch.setattr(worker.subprocess, "run", time_out_preview) - if phase_limited: - receipt = worker.run_once(env) - assert receipt["ok"] and receipt["budget_exhausted"] is True - assert "host_failure" not in receipt - else: - with pytest.raises(ValueError, match="Short envelope requires a successful v0 quota preview"): - worker.run_once(env) - receipt = _receipt(env) - assert not receipt["ok"] and not receipt.get("budget_exhausted") - - assert previews == [1 if phase_limited else 120] - assert receipt["host_invoked"] is False and not receipt["quota_input_contract"]["eligible"] - assert not Path(env["LOOPX_CODEX_HOME"]).exists() - assert not (project / "native-starts").exists() - assert fixture._heartbeat_receipt_count(runtime, receipt["turn_id"]) == 0 - assert state.read_bytes() == before - - def test_checkpoint_internal_timeout_is_not_reclassified_after_deadline(tmp_path, monkeypatch): import subprocess from benchmark.runtime import checkpoint_wake diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md index d2da929760..177595edab 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.md @@ -22,19 +22,19 @@ qualification of model cost and long-horizon benefit. The ordinary CLI cutover composes every decided `quota should-run` through the existing TypeScript `composeCompleteTurnDecision` owner **before** capture. -Default calls and the compatibility aliases `--turn-envelope` / `--complete-turn` -share this source. Explicit context-delivery off returns that complete source +Current guards use one source. The `--turn-envelope` and `--complete-turn` +selectors are retired. Explicit context-delivery off returns that complete source inline; it does not choose an older format or enable progressive delivery. Full Goal material is collected independently of that presentation choice. The active CLI selection between its compactor and `buildTurnEnvelope` is -removed. Status, plan and scheduler-observation retain their separate purposes; -historical readers and other remaining callers are not retired by this slice. +removed. Status, plan and scheduler-observation retain their separate purposes. +Saved captures keep their original version, digest and recovery identity. The ordinary CLI cutover removes the JSON-only format exception from guard context collection and from composition before capture. Scheduler observation -continues to use its separate read-only projection. The public runtime artifact -still checks its qualified default independently. An archive that exposes C1 as -its default must pass the existing supported-profile and matched single-session -outcome and full-cost qualification before adoption. +continues to use its separate read-only projection. New runtime archives +independently verify C1 as the committed and installed default. Supported-profile +adoption and matched single-session outcome and full-cost acceptance remain +separate evidence requirements. The current model-behavior portfolio also composes its should-run inputs through this complete-source owner; it no longer exercises the retired CLI compactor as @@ -45,14 +45,10 @@ diagnostics stay intact. The crowded regression's pretty JSON changes from the new full carrier. Wire/page limits and the terminal actor's ten-call budget do not change. Frozen raw/v0 model comparison controls remain separate. -The benchmark worker checks an explicit historical Short request before -starting a planning or execution model. It previews the pinned CLI's quota -response without admission and records the expected and observed source versions -and eligibility in the wake receipt. A v1 or unavailable response refuses the -Short treatment. A fresh-replan checkpoint preloads a different input and cannot -qualify as direct Short. Current ordinary and Complete requests continue through -the shared C1 producer. Historical experiments retain their recorded sources -and receipts. +The benchmark worker rejects explicit historical display selections before +starting a model. Reproduce historical treatments with the recorded product +and runner revisions. Current heartbeat and checkpoint preparation use the +shared C1 producer. Todo completion, replan-successor return and blocked-completion recovery use the existing TypeScript settlement composer for their current continuation plans. diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md index 3ec0b755c1..975daaf5e1 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0/contract-and-context.zh-CN.md @@ -15,15 +15,15 @@ readiness 路径,不补造 Turn。这只是有界的 Host 交接修复,不 采用,或模型费用与长程收益已取得资格。 普通 CLI 切换让每个已形成决策的 `quota should-run` 在 capture **之前**复用既有 -TypeScript `composeCompleteTurnDecision` owner。默认调用及兼容别名 -`--turn-envelope` / `--complete-turn` 使用同一来源。显式关闭 context delivery 时, +TypeScript `composeCompleteTurnDecision` owner。当前 guard 使用同一来源, +已退役 `--turn-envelope` 和 `--complete-turn`。显式关闭 context delivery 时, 完整来源以内联形式返回,不选择旧格式,也不打开渐进交付;完整 Goal 材料的取得与 此展示选择分开。CLI 中选择 compactor 或 `buildTurnEnvelope` 的活跃分支删除。 -Status、plan 与 scheduler-observation 保留各自用途;本切片不退役历史 reader 或 -其他剩余调用方。 +Status、plan 与 scheduler-observation 保留各自用途。已保存捕获保留原版本、摘要 +与恢复身份。 普通 CLI 切换同时删除准入上下文收集和捕获前组合里仅为 JSON 调用保留的格式例外。 -调度观察继续使用独立的只读展示。公开运行时包独立核对已通过资格验收的默认契约。 -以 C1 为默认的发行包仍须通过受支持配置及匹配单会话的成果与全成本验收,才能采用。 +调度观察继续使用独立的只读展示。新运行时包独立核对提交源码和安装端默认 C1。 +受支持配置采用、匹配单会话成果及全成本仍各自需要验收证据。 当前 model-behavior portfolio 的 should-run 输入也复用该完整来源 owner,不再把 已退役 CLI compactor 当作产品默认路径。候选上下文、规划关系、任务续接与诊断事实 @@ -32,11 +32,8 @@ Status、plan 与 scheduler-observation 保留各自用途;本切片不退役 新的完整 carrier。Wire/page 上限和终态 actor 的十次调用预算不变。冻结的 raw/v0 模型对照继续独立保留。 -Benchmark worker 在启动规划或执行模型前核实显式历史 Short 请求。它从已固定 -的 CLI 只读预演 quota 响应,不准入工作,并在 wake 回执记录预期与实际版本及 -资格。v1 或无法核实的响应会拒绝 Short。Fresh-replan checkpoint 会预载另一种 -输入,不能算作直接 Short。当前普通与 Complete 请求继续复用 C1 producer。 -历史实验保留原版本与回执。 +Benchmark worker 在启动模型前拒绝显式历史交付选项。历史实验使用原记录的产品 +与 runner 版本复现;当前 heartbeat 和 checkpoint 准备共用 C1 producer。 Todo 验收完成、replan-successor 返回及 blocked-completion 恢复的当前续接计划复用 既有 TypeScript 结算 composer,保留原身份、路由与已提供的 lease 证明。JSON 与 diff --git a/docs/heartbeat-automation-prompt.md b/docs/heartbeat-automation-prompt.md index a016d66cbf..8b6f1b919d 100644 --- a/docs/heartbeat-automation-prompt.md +++ b/docs/heartbeat-automation-prompt.md @@ -548,8 +548,8 @@ native blocked/resume rules; it does not become a hosted heartbeat. Generate the normal bootstrap with `heartbeat-prompt --thin --codex-app --bootstrap`, its existing Goal/Agent/registry arguments, and -`--context-delivery on`; optionally add `--turn-envelope` or explicit private paths. The loader preserves -these options without freezing a Turn ID. Each wake loads current instructions +`--context-delivery on` and explicit private paths when needed. The loader +preserves these options and binds a fresh Turn ID on each wake. Each wake loads current instructions and binds the existing `LOOPX_TURN` before its generated guard. Selection keeps the same transport. An unset wake identity fails in the shell before admission. diff --git a/docs/product/foundations/agent-facing-trajectory-quality.md b/docs/product/foundations/agent-facing-trajectory-quality.md index 988434875f..43b18613cd 100644 --- a/docs/product/foundations/agent-facing-trajectory-quality.md +++ b/docs/product/foundations/agent-facing-trajectory-quality.md @@ -66,7 +66,7 @@ Registry、active state、todo、gate、quota decision、run history 和可选 t - validation、writeback 与 quota spend policy; - scheduler action 和必要的 cadence acknowledgement。 -TurnEnvelope 是 additive read model,目前仍为 opt-in,不改变 quota selection、todo routing 或默认完整输出。协议见 [TurnEnvelope v0](../../reference/protocols/turn-envelope-v0.md)。 +当前 quota guard 使用 Complete Turn v1。历史 v0 是已决策 quota 的精简读模型。历史读取与现用契约见 [TurnEnvelope](../../reference/protocols/turn-envelope-v0.md)。 ### 质量审计层 @@ -204,10 +204,10 @@ loopx history trajectory-hygiene \ loopx quota should-run \ --goal-id \ --agent-id \ - --turn-envelope + --context-delivery off --delta-delivery off ``` -第一条命令观察 compact history 的事件结构;第二条命令检查当前 Agent-facing envelope、byte budget 和 action signature。 +第一条命令观察 compact history 的事件结构;第二条命令检查当前 Agent-facing Complete Turn 决策。 ### 分类 diff --git a/docs/product/releases/v2.4.0.md b/docs/product/releases/v2.4.0.md index 9a7da73510..e0dd69ba1b 100644 --- a/docs/product/releases/v2.4.0.md +++ b/docs/product/releases/v2.4.0.md @@ -89,7 +89,7 @@ loopx authority-archive upgrade --all-known --require-current ## Benchmarks & Integrations -- **Antigravity, Codex & Steward executor routing:** External hosts can opt into `--complete-turn` (`loopx_turn_envelope_v1`) with digest-bound `context-read` pagination and verified original capture recovery (`#8489`, `#8940`, `#9022`, `#9048`). Steward executor routing adds Antigravity `Carbon` (`gemini-4-carbon-{high,medium,low}`) while retaining `Argon` as default, optional `endpoint_models` preferences in `steward_executor_machine_defaults_v1` (with JSON-mode authoring notes in `configuration_ui.py`), bidirectional `codex` / `antigravity` flexible failover (`loopx-codex-provider-routing 0.15.9`) with `reasoning_effort` alias capacity resolution (`#9147`), `flexible_primary_available` conversation transitions (`#9145`), and native Steward monitor/report fallback parity; legacy session model preservation (`#8977`, `#8984`), Antigravity schedule patrol and Stop hooks (`#8874`), Codex API relay untruncated streaming/payload handling and loopback relay `401` recovery (`#8713`, `#9167`), UTF-8 Codex App stdout decoding (`#8485`), quiet completion receipts (`#8454`), failed-start Session adapter retention (`#9134`), and managed chat observer lock handoff (`#9130`) complete the host layer. [#8454](https://github.com/loopx-project/loopx/pull/8454), [#8485](https://github.com/loopx-project/loopx/pull/8485), [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8713](https://github.com/loopx-project/loopx/pull/8713), [#8874](https://github.com/loopx-project/loopx/pull/8874), [#8977](https://github.com/loopx-project/loopx/pull/8977), [#8984](https://github.com/loopx-project/loopx/pull/8984), [#9130](https://github.com/loopx-project/loopx/pull/9130), [#9134](https://github.com/loopx-project/loopx/pull/9134), [#9141](https://github.com/loopx-project/loopx/pull/9141), [#9145](https://github.com/loopx-project/loopx/pull/9145), [#9147](https://github.com/loopx-project/loopx/pull/9147), [#9167](https://github.com/loopx-project/loopx/pull/9167) +- **Antigravity, Codex & Steward executor routing:** External hosts now receive `loopx_turn_envelope_v1` by default with digest-bound `context-read` pagination and verified original capture recovery (`#8489`, `#8940`, `#9022`, `#9048`). Steward executor routing adds Antigravity `Carbon` (`gemini-4-carbon-{high,medium,low}`) while retaining `Argon` as default, optional `endpoint_models` preferences in `steward_executor_machine_defaults_v1` (with JSON-mode authoring notes in `configuration_ui.py`), bidirectional `codex` / `antigravity` flexible failover (`loopx-codex-provider-routing 0.15.9`) with `reasoning_effort` alias capacity resolution (`#9147`), `flexible_primary_available` conversation transitions (`#9145`), and native Steward monitor/report fallback parity; legacy session model preservation (`#8977`, `#8984`), Antigravity schedule patrol and Stop hooks (`#8874`), Codex API relay untruncated streaming/payload handling and loopback relay `401` recovery (`#8713`, `#9167`), UTF-8 Codex App stdout decoding (`#8485`), quiet completion receipts (`#8454`), failed-start Session adapter retention (`#9134`), and managed chat observer lock handoff (`#9130`) complete the host layer. [#8454](https://github.com/loopx-project/loopx/pull/8454), [#8485](https://github.com/loopx-project/loopx/pull/8485), [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8713](https://github.com/loopx-project/loopx/pull/8713), [#8874](https://github.com/loopx-project/loopx/pull/8874), [#8977](https://github.com/loopx-project/loopx/pull/8977), [#8984](https://github.com/loopx-project/loopx/pull/8984), [#9130](https://github.com/loopx-project/loopx/pull/9130), [#9134](https://github.com/loopx-project/loopx/pull/9134), [#9141](https://github.com/loopx-project/loopx/pull/9141), [#9145](https://github.com/loopx-project/loopx/pull/9145), [#9147](https://github.com/loopx-project/loopx/pull/9147), [#9167](https://github.com/loopx-project/loopx/pull/9167) - **Lark group & private channel hardening:** Private Lark replies stay off the main blocking path, preserve queued messages on reconnect, offer read-only Steward shortcut cards, deliver Turn-scoped native images and recover legacy captured images, steer mentions into frozen original Turns, share callback dispatch across query and operation cards, escape Goal Channel operation card text in a single pass, recognize international Lark setup URLs, coalesce listener snapshots, cache recovery lookups, and reset noop recovery backoff when Turn/session inputs change. [#8270](https://github.com/loopx-project/loopx/pull/8270), [#8668](https://github.com/loopx-project/loopx/pull/8668), [#8695](https://github.com/loopx-project/loopx/pull/8695), [#8741](https://github.com/loopx-project/loopx/pull/8741), [#8858](https://github.com/loopx-project/loopx/pull/8858), [#8870](https://github.com/loopx-project/loopx/pull/8870), [#8871](https://github.com/loopx-project/loopx/pull/8871), [#8893](https://github.com/loopx-project/loopx/pull/8893), [#8903](https://github.com/loopx-project/loopx/pull/8903), [#8921](https://github.com/loopx-project/loopx/pull/8921), [#8990](https://github.com/loopx-project/loopx/pull/8990), [#8999](https://github.com/loopx-project/loopx/pull/8999), [#9041](https://github.com/loopx-project/loopx/pull/9041), [#9096](https://github.com/loopx-project/loopx/pull/9096), [#9098](https://github.com/loopx-project/loopx/pull/9098), [#9100](https://github.com/loopx-project/loopx/pull/9100), [#9114](https://github.com/loopx-project/loopx/pull/9114), [#9119](https://github.com/loopx-project/loopx/pull/9119) - **Desktop App 2.4.0 & `dsh-loopx-plugin 0.1.1-beta.7`:** Desktop App prepares updates before workspace teardown, bounds readiness probes, opens the usable workspace before optional updates, skips immutable-release frontend re-hashing (`#9089`), adds download retries to chat-bundle packaging and Desktop release/updater workflows (`#9147`), and checks signature-verified archives for supported runtime `default_contract` before preparing macOS preview updates (`#9029`). `dsh-loopx-plugin 0.1.1-beta.7` adds `DSH 0.2.2-rc.1..rc.3` compatibility, aligns integration closeout tests with `quota_settlement_plan_v2` (`#9147`), surfaces GoalBar `continuationAdmission` failures, isolates hot uninstalls from the shared Web server, fences Start/Pause with Core source fingerprints, preserves replacement cancellation/error pauses, and fixes Windows continuation paths. [#8504](https://github.com/loopx-project/loopx/pull/8504), [#8675](https://github.com/loopx-project/loopx/pull/8675), [#8723](https://github.com/loopx-project/loopx/pull/8723), [#8739](https://github.com/loopx-project/loopx/pull/8739), [#8879](https://github.com/loopx-project/loopx/pull/8879), [#8899](https://github.com/loopx-project/loopx/pull/8899), [#9029](https://github.com/loopx-project/loopx/pull/9029), [#9087](https://github.com/loopx-project/loopx/pull/9087), [#9089](https://github.com/loopx-project/loopx/pull/9089), [#9147](https://github.com/loopx-project/loopx/pull/9147) - **Windows & Benchmark tooling (no net long-horizon outcome claim):** Windows receives PowerShell settlement quoting, bounded error payloads, UTF-8 decoding, source lease clock-skew tolerance, file identity checks, and local NTFS `loopx-jev` capture (`#8599`, `#8620`, `#8641`, `#8643`, `#8761`). Benchmark adapters add `benchmark.runtime.planning_batch` initial task planning (`#9090`), idle-boundary staged CLI activation (`#8501`), governed single-worker Turn extraction (`#8499`), Codex resume restoration (`#9031`), Frontier shared task clocks (`#8875`), and restored frozen v1 archive and standalone benchmark import boundaries (`#9151`); no net long-horizon benchmark outcome or total-cost improvement is claimed in this release. [#8499](https://github.com/loopx-project/loopx/pull/8499), [#8501](https://github.com/loopx-project/loopx/pull/8501), [#8599](https://github.com/loopx-project/loopx/pull/8599), [#8620](https://github.com/loopx-project/loopx/pull/8620), [#8641](https://github.com/loopx-project/loopx/pull/8641), [#8643](https://github.com/loopx-project/loopx/pull/8643), [#8761](https://github.com/loopx-project/loopx/pull/8761), [#8875](https://github.com/loopx-project/loopx/pull/8875), [#9031](https://github.com/loopx-project/loopx/pull/9031), [#9090](https://github.com/loopx-project/loopx/pull/9090), [#9151](https://github.com/loopx-project/loopx/pull/9151) @@ -152,11 +152,11 @@ loopx --format json quota should-run --goal-id "$LOOPX_GOAL_ID" --agent-id "$LOO ### Complete Turn context for external hosts -**Activation:** Add `--complete-turn` to JSON `quota should-run` in an external host that can consume the complete v1 contract (`loopx_turn_envelope_v1`, composing runtime-owned `quota_settlement_plan_v2`). Give it an explicit fresh Turn ID and a writable capture directory. Ordinary unhosted JSON `quota should-run` without Complete Turn or host flags continues returning `quota_packet`. [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9084](https://github.com/loopx-project/loopx/pull/9084) +**Activation:** JSON `quota should-run` uses the complete v1 contract. External Hosts must read `loopx_turn_envelope_v1`. Remove the retired `--complete-turn` and `--turn-envelope` options. For a private progressive capture, supply a fresh Turn ID, an unused capture directory and `--context-delivery on --delta-delivery off`. -**Validation:** Confirm `loopx_turn_envelope_v1` and `quota_settlement_plan_v2` on the returned or saved decision. Finish its required Goal/context reads and follow the same Turn's execution and single-command settlement contract (`--settle-turn --settlement-receipt`). Follow the pinned reader supplied with a progressive response and verify the original digest and Turn identity. +**Validation:** Confirm `loopx_turn_envelope_v1` on the returned or saved decision. A progressive response can return `context_capture_navigation_v1`; follow its pinned reader and verify the original digest and Turn identity. Finish the required reads and follow the returned settlement plan for that Turn. -**Disable / rollback:** Omit `--complete-turn` from subsequent requests to return to the prior `quota_packet` context path. Keep the original digest-bound commands for existing captures. +**Disable / rollback:** Use `--context-delivery off --delta-delivery off` for inline v1. To run the earlier live contract, follow the compatible installation rollback procedure and verify that the target can read the current authority state. Preserve digest-bound commands for existing captures. **Authority boundary:** The current Goal, Agent, admission, permissions, required reads, hard-lease fence, and Stop conditions govern the Turn. @@ -165,7 +165,7 @@ loopx --format json quota should-run --goal-id "$LOOPX_GOAL_ID" --agent-id "$LOO ```bash loopx --format json quota should-run --goal-id "$LOOPX_GOAL_ID" \ --agent-id "$LOOPX_AGENT_ID" --turn-instance-id "$LOOPX_TURN_ID" \ - --complete-turn --decision-output-dir ./complete-001 + --context-delivery on --delta-delivery off --decision-output-dir ./complete-001 ``` The reader's JSON Pointer selects a field inside the captured JSON; it is not a filesystem path. Copy the returned current reader reference into `CAPTURE_READER`. Listing and selecting the current capture does not require reading an older delta baseline or creating another admission. @@ -459,7 +459,7 @@ loopx doctor ### 基准与集成 -- **Antigravity、Codex 与管家执行器路由:** 外部 Host 可显式使用 `--complete-turn` 与摘要绑定 `context-read`;管家配置新增 Antigravity `Carbon`(`gemini-4-carbon-{high,medium,low}`,默认仍为 `Argon`)、每端点 `endpoint_models` JSON 模式偏好说明、Codex 与 Antigravity 双向 `flexible` 容灾切换(配合 `loopx-codex-provider-routing 0.15.9`、`reasoning_effort` 容量别名与 `flexible_primary_available` 状态转换)及回退路径的原生监控/周报支持,同时修复 Codex API relay 请求/响应截断与回环中继 401 恢复、Codex 模型切换历史保留、UTF-8 输出解码、静默完成回执、失败重试 Session 适配器保留及受管观察锁交接(`#9167`)。 [#8454](https://github.com/loopx-project/loopx/pull/8454), [#8485](https://github.com/loopx-project/loopx/pull/8485), [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8713](https://github.com/loopx-project/loopx/pull/8713), [#8874](https://github.com/loopx-project/loopx/pull/8874), [#8977](https://github.com/loopx-project/loopx/pull/8977), [#8984](https://github.com/loopx-project/loopx/pull/8984), [#9130](https://github.com/loopx-project/loopx/pull/9130), [#9134](https://github.com/loopx-project/loopx/pull/9134), [#9141](https://github.com/loopx-project/loopx/pull/9141), [#9145](https://github.com/loopx-project/loopx/pull/9145), [#9147](https://github.com/loopx-project/loopx/pull/9147), [#9167](https://github.com/loopx-project/loopx/pull/9167) +- **Antigravity、Codex 与管家执行器路由:** 外部 Host 默认使用完整 v1 与摘要绑定 `context-read`;管家配置新增 Antigravity `Carbon`(`gemini-4-carbon-{high,medium,low}`,默认仍为 `Argon`)、每端点 `endpoint_models` JSON 模式偏好说明、Codex 与 Antigravity 双向 `flexible` 容灾切换(配合 `loopx-codex-provider-routing 0.15.9`、`reasoning_effort` 容量别名与 `flexible_primary_available` 状态转换)及回退路径的原生监控/周报支持,同时修复 Codex API relay 请求/响应截断与回环中继 401 恢复、Codex 模型切换历史保留、UTF-8 输出解码、静默完成回执、失败重试 Session 适配器保留及受管观察锁交接(`#9167`)。 [#8454](https://github.com/loopx-project/loopx/pull/8454), [#8485](https://github.com/loopx-project/loopx/pull/8485), [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8713](https://github.com/loopx-project/loopx/pull/8713), [#8874](https://github.com/loopx-project/loopx/pull/8874), [#8977](https://github.com/loopx-project/loopx/pull/8977), [#8984](https://github.com/loopx-project/loopx/pull/8984), [#9130](https://github.com/loopx-project/loopx/pull/9130), [#9134](https://github.com/loopx-project/loopx/pull/9134), [#9141](https://github.com/loopx-project/loopx/pull/9141), [#9145](https://github.com/loopx-project/loopx/pull/9145), [#9147](https://github.com/loopx-project/loopx/pull/9147), [#9167](https://github.com/loopx-project/loopx/pull/9167) - **飞书群聊与私聊加固:** 私聊反馈不阻塞主回复,重连保留排队消息,提供只读管家快捷卡片,支持 Turn 作用域原生图片与历史图片恢复、mention 定向回原冻结 Turn、查询与操作卡片共享回调分发、单趟卡片文本转义、国际版 Lark URL 识别、监听快照合并与恢复缓存,并在输入变化时重置空转退避。 [#8270](https://github.com/loopx-project/loopx/pull/8270), [#8668](https://github.com/loopx-project/loopx/pull/8668), [#8695](https://github.com/loopx-project/loopx/pull/8695), [#8741](https://github.com/loopx-project/loopx/pull/8741), [#8858](https://github.com/loopx-project/loopx/pull/8858), [#8870](https://github.com/loopx-project/loopx/pull/8870), [#8871](https://github.com/loopx-project/loopx/pull/8871), [#8893](https://github.com/loopx-project/loopx/pull/8893), [#8903](https://github.com/loopx-project/loopx/pull/8903), [#8921](https://github.com/loopx-project/loopx/pull/8921), [#8990](https://github.com/loopx-project/loopx/pull/8990), [#8999](https://github.com/loopx-project/loopx/pull/8999), [#9041](https://github.com/loopx-project/loopx/pull/9041), [#9096](https://github.com/loopx-project/loopx/pull/9096), [#9098](https://github.com/loopx-project/loopx/pull/9098), [#9100](https://github.com/loopx-project/loopx/pull/9100), [#9114](https://github.com/loopx-project/loopx/pull/9114), [#9119](https://github.com/loopx-project/loopx/pull/9119) - **Desktop App 2.4.0 与 `dsh-loopx-plugin 0.1.1-beta.7`:** Desktop App 在关闭工作区前准备更新、限制就绪探测耗时、先打开可用工作区、跳过不可变版本前端重哈希、为 `chat_bundle.py` 与桌面发布/更新工作流增加下载重试(`#9147`),并在缓存 macOS preview 更新前核验签名包里的 `default_contract`;`dsh-loopx-plugin 0.1.1-beta.7` 兼容 DSH `0.2.2-rc.1..rc.3`、对齐 `quota_settlement_plan_v2` 集成结案测试(`#9147`)、在 GoalBar 展示准入失败、隔离热卸载、保持替代后取消/错误暂停归属、用来源指纹保护 Start/Pause 并支持 Windows 原生路径。 [#8504](https://github.com/loopx-project/loopx/pull/8504), [#8675](https://github.com/loopx-project/loopx/pull/8675), [#8723](https://github.com/loopx-project/loopx/pull/8723), [#8739](https://github.com/loopx-project/loopx/pull/8739), [#8879](https://github.com/loopx-project/loopx/pull/8879), [#8899](https://github.com/loopx-project/loopx/pull/8899), [#9029](https://github.com/loopx-project/loopx/pull/9029), [#9087](https://github.com/loopx-project/loopx/pull/9087), [#9089](https://github.com/loopx-project/loopx/pull/9089), [#9147](https://github.com/loopx-project/loopx/pull/9147) - **Windows 与基准工具(不宣称长程净收益):** Windows 修复 PowerShell 引号、错误载荷上限、文件身份核对及本地 NTFS `loopx-jev` 捕获;基准工具新增初始规划批写入(`benchmark.runtime.planning_batch`)、空闲边界 staged CLI 切换预览、单 worker 回合提取、Codex 恢复、Frontier 共享时钟,并恢复冻结 v1 归档与独立 `benchmark/` 导入边界(`#9151`)。本版本不宣称可比长程任务结果或完整成本净收益。 [#8499](https://github.com/loopx-project/loopx/pull/8499), [#8501](https://github.com/loopx-project/loopx/pull/8501), [#8599](https://github.com/loopx-project/loopx/pull/8599), [#8620](https://github.com/loopx-project/loopx/pull/8620), [#8641](https://github.com/loopx-project/loopx/pull/8641), [#8643](https://github.com/loopx-project/loopx/pull/8643), [#8761](https://github.com/loopx-project/loopx/pull/8761), [#8875](https://github.com/loopx-project/loopx/pull/8875), [#9031](https://github.com/loopx-project/loopx/pull/9031), [#9090](https://github.com/loopx-project/loopx/pull/9090), [#9151](https://github.com/loopx-project/loopx/pull/9151) @@ -522,11 +522,11 @@ loopx --format json quota should-run --goal-id "$LOOPX_GOAL_ID" --agent-id "$LOO #### Complete Turn context for external hosts -**启用:** 可消费完整 v1 契约(`loopx_turn_envelope_v1` 与运行时拥有的 `quota_settlement_plan_v2`)的外部 Host 在 JSON `quota should-run` 上显式传入 `--complete-turn`,提供新的 Turn ID 和可写捕获目录。不传 Complete Turn 或宿主标志的普通 JSON `quota should-run` 继续返回 `quota_packet`。 [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9084](https://github.com/loopx-project/loopx/pull/9084) +**启用:** JSON `quota should-run` 默认组合完整 v1。外部 Host 须能读取 `loopx_turn_envelope_v1`,并移除已退役的 `--complete-turn` 与 `--turn-envelope`。需要私有渐进捕获时,提供新的 Turn ID、尚不存在的捕获目录和 `--context-delivery on --delta-delivery off`。 -**验证:** 在本次决策或保存的捕获中确认 `loopx_turn_envelope_v1` 与 `quota_settlement_plan_v2`,完成其必读 Goal/上下文,并沿同一 Turn 的执行和单命令结算契约(`--settle-turn --settlement-receipt`)推进。如返回分段导航,使用随决策返回的固定 reader,核对原摘要和 Turn 身份。 +**验证:** 在返回或保存的决策中确认 `loopx_turn_envelope_v1`。若返回 `context_capture_navigation_v1`,用固定 reader 核对原摘要与 Turn 身份。完成必读内容,并执行本轮返回的结算计划。 -**停用 / 回退:** 后续请求省略 `--complete-turn`,恢复原 `quota_packet` 上下文路径。原捕获保留原摘要绑定的读取命令。 +**停用 / 回退:** 用 `--context-delivery off --delta-delivery off` 返回内联 v1。需恢复旧实时契约时,使用兼容的安装回退流程,并先核验目标能读取当前权威状态。保留既有捕获的摘要绑定命令。 **权限边界:** 继续遵循本次 Goal、Agent、准入、权限、硬租约护栏、必读内容和 Stop 条件。 @@ -535,7 +535,7 @@ loopx --format json quota should-run --goal-id "$LOOPX_GOAL_ID" --agent-id "$LOO ```bash loopx --format json quota should-run --goal-id "$LOOPX_GOAL_ID" \ --agent-id "$LOOPX_AGENT_ID" --turn-instance-id "$LOOPX_TURN_ID" \ - --complete-turn --decision-output-dir ./complete-001 + --context-delivery on --delta-delivery off --decision-output-dir ./complete-001 ``` reader 的 JSON Pointer 指向捕获 JSON 内的字段,不是文件路径。将返回的当前 reader 引用赋给 `CAPTURE_READER` 后可目录查看或选读;读取当前捕获不要求先读旧差分基线,也不需要重新准入。 diff --git a/docs/product/runtimes/codex-cli/codex-cli-automation-driver.md b/docs/product/runtimes/codex-cli/codex-cli-automation-driver.md index 56c0d003b5..4ae4c0b990 100644 --- a/docs/product/runtimes/codex-cli/codex-cli-automation-driver.md +++ b/docs/product/runtimes/codex-cli/codex-cli-automation-driver.md @@ -143,7 +143,7 @@ the host-neutral mechanism. ```text 1. Resolve project, goal, registered agent, execution mode, and Codex capability. -2. Run live quota should-run --turn-envelope with observed capabilities. +2. Run live quota should-run with observed capabilities. 3. Route user notification, quiet wait, repair, or delivery exactly as decided. 4. Claim/preserve the selected todo and satisfy workspace guard. 5. Start or resume one Codex turn with the thin task body and TurnEnvelope. diff --git a/docs/reference/protocols/loopx-turn-v0.md b/docs/reference/protocols/loopx-turn-v0.md index 0027a3b7c2..dfae7cbcef 100644 --- a/docs/reference/protocols/loopx-turn-v0.md +++ b/docs/reference/protocols/loopx-turn-v0.md @@ -467,7 +467,7 @@ One driver tick has exactly these ordered phases: 1. **Wake**: resolve `goal_id`, registered `agent_id`, host kind, explicit execution mode, available capabilities, and an optional opaque session handle. -2. **Decide**: run live `quota should-run --turn-envelope` with the observed +2. **Decide**: run live `quota should-run` with the observed capabilities. A fixture is valid only in tests and shadow replay. 3. **Route**: obey the envelope without invoking the host when the user channel requires action, work is throttled, a monitor is unchanged, or delivery is diff --git a/docs/reference/protocols/turn-envelope-v0.md b/docs/reference/protocols/turn-envelope-v0.md index 10198cc56e..3afc22d6f7 100644 --- a/docs/reference/protocols/turn-envelope-v0.md +++ b/docs/reference/protocols/turn-envelope-v0.md @@ -33,11 +33,11 @@ loopx --format json quota should-run --goal-id --agent-id \ --turn-instance-id --decision-output-dir ./complete-001 ``` -`--turn-envelope` and `--complete-turn` remain mutually exclusive inputs -for saved commands. Both use v1 in the current CLI. With no independent -Delta request, `--context-delivery off` returns the complete inline v1 -document. Read existing captures with their original digest-bound -`quota context-read` or `context-project` recovery. +Remove `--turn-envelope` and `--complete-turn` from current guard commands. +Use `--context-delivery off --delta-delivery off` for inline v1. Read saved +captures with their original digest-bound `quota context-read` or +`context-project` recovery. To run an earlier live contract, use a compatible +runtime revision after verifying that it can read the current authority state. `quota context-project` checks a saved complete decision before presenting it as current context, including with Delta alone or with context delivery off. @@ -538,14 +538,13 @@ caller-owned checkpoint. Explicit `--context-delivery off` retains the complete inline contract when no independent Delta delivery is requested. New bootstrap, guard, selection and settlement-recovery commands use the -complete v1 source. Saved callers can still pass `--turn-envelope` or -`--complete-turn` to the current CLI under their existing input restrictions. -Saved captures and their original read commands retain the recorded version -and digest. Follow the original capture for selection, replan or required -detail. A persistent bootstrap binds each Turn on wake. - -当前生成的 bootstrap、guard、选择和结算恢复命令统一使用完整 v1 来源。原先 -保存的两个别名仍可按原输入限制使用,原捕获和读回命令保留其版本与摘要。 +complete v1 source. The saved bootstrap reader recognizes the retired +options to upgrade existing generated prompts. Saved captures and their +original read commands retain the recorded version and digest. Rebind a +selection command from the saved capture to keep the same Turn. + +当前生成的 bootstrap、guard、选择和结算恢复命令统一使用完整 v1 来源。升级 +生成的旧提示时,历史 reader 可识别旧选项。原捕获和读回命令保留其版本与摘要。 捕获与交付方式独立,显式关闭上下文交付后仍使用完整契约。 Capability planning context stays inline under the existing context owner's @@ -593,12 +592,11 @@ diagnostic remain unchanged. This is an output qualification, not a full-cost SL 中文:捕获和模型输入投影独立。`--decision-output-root` 仅保存完整决策, `--decision-handoff-socket` 仅保留检查点交接;二者均不隐式开启 TurnEnvelope。 -历史 Short 使用曾交付 v0 的产品版本,并保留原请求与捕获。当前 C1 中 -`--turn-envelope` 是完整契约的兼容别名,已有实验按其记录版本解释。 +历史 Short 使用曾交付 v0 的产品与 runner 版本,并保留原请求与捕获。 -The benchmark heartbeat worker verifies a historical `turn_envelope` request -against the pinned CLI's v0 response before launching a model. Its read-only -preview and eligibility are recorded in the wake receipt. See the [runtime +For historical Short, use the original runner and product revisions and +inspect the recorded v0 response and wake receipt. The current worker refuses +historical treatment requests before model launch. See the [runtime guide](../../../benchmark/runtime/RUNTIME.md) for supported configurations. Model cost, decision quality and long-run adoption require a separately pinned experiment. A capture carries its original read and recovery scope. diff --git a/docs/reference/required-work-context.md b/docs/reference/required-work-context.md index 94a5671895..4fa79ef1c0 100644 --- a/docs/reference/required-work-context.md +++ b/docs/reference/required-work-context.md @@ -517,9 +517,8 @@ capture,活跃会话的认领来源保持原样。恢复前先核对原 Turn After a Host claim, the ready guard uses the private `--prepared-capture-reference` route. It publishes the complete decision and returns its writer digest with the fields needed to verify the same Todo and -Turn. The default guard and the `--turn-envelope` and `--complete-turn` -compatibility spellings use the same complete v1 capture. The hook verifies -that digest when it opens the original file. If the +Turn. The guard captures the complete v1 decision. The hook verifies the +writer digest when it opens the original file. If the file changed, the receipt preserves the claim and pins recovery to the original bytes before work can continue. The private native journal reserves automatic preparation before claiming a @@ -1179,8 +1178,8 @@ Checkpoint Host 预检在显式开启 native JSON `should-run` 捕获时使用 读取。未绑定任务的分阶段重规划继续沿用 review 所属的原始 Goal 读取。 Host 领取 Todo 后,就绪检查使用内部 `--prepared-capture-reference` 路径。它保存完整决策, -只返回写入时的摘要和核对同一 Todo、Turn 所需的字段。默认 guard 和 `--turn-envelope`、 -`--complete-turn` 两个兼容别名均使用同一份完整 v1 捕获。hook 打开原文件时校验该摘要。 +只返回写入时的摘要和核对同一 Todo、Turn 所需的字段。guard 捕获完整 v1 决策。 +hook 打开原文件时校验写入摘要。 若文件已被替换,回执保留原领取记录,恢复原始内容后才能继续工作。 Goal adapter 仍完整读取文件、校验 UTF-8,并以全部字节计算修订摘要;关闭 native diff --git a/loopx/cli_commands/quota_context.py b/loopx/cli_commands/quota_context.py index 57630dc136..29327421d4 100644 --- a/loopx/cli_commands/quota_context.py +++ b/loopx/cli_commands/quota_context.py @@ -128,10 +128,6 @@ def validate_quota_command_context_request( """Validate the request before any provider read or local projection write.""" command = args.quota_command - if bool(getattr(args, "turn_envelope", False)) and command != "should-run": - raise QuotaCommandValidationError( - "--turn-envelope is only valid with `quota should-run`" - ) requested_details = set(getattr(args, "include_details", None) or ()) if requested_details and command not in QUOTA_COMMAND_DETAIL_SECTIONS: raise QuotaCommandValidationError( diff --git a/loopx/cli_commands/quota_context_reader.py b/loopx/cli_commands/quota_context_reader.py index 7d58b7f6e7..acf92805f9 100644 --- a/loopx/cli_commands/quota_context_reader.py +++ b/loopx/cli_commands/quota_context_reader.py @@ -70,7 +70,9 @@ def bind_capture_selection_transport(payload: dict[str, Any], args: argparse.Nam template = selection.get("command_args_template") if not isinstance(template, str): return - words = shlex.split(template) + # A saved capture can still carry the old boolean selectors. Rebind only + # the presented command to the current CLI; the original bytes stay intact. + words = [word for word in shlex.split(template) if word not in {"--turn-envelope", "--complete-turn"}] options: dict[str, str] = {} # A saved guard already carries its capture root. Preserve it unless this # caller explicitly selects another; otherwise use the validated cache. diff --git a/loopx/cli_commands/quota_native_context.py b/loopx/cli_commands/quota_native_context.py index 328c1ef710..b7cd940afa 100644 --- a/loopx/cli_commands/quota_native_context.py +++ b/loopx/cli_commands/quota_native_context.py @@ -139,7 +139,7 @@ def project_saved_context_capture( or payload.get("goal_id") != args.goal_id or identity.get("agent_id") != args.agent_id or receipt.get("turn_instance_id") != args.turn_instance_id): raise ValueError("context-project requires the captured quota decision's exact Goal, Agent and Turn") - if args.turn_envelope or args.decision_output_dir or args.decision_handoff_socket: + if args.decision_output_dir or args.decision_handoff_socket: raise ValueError("context-project presents the saved quota view; it does not change view or handoff") except QuotaCommandValidationError as exc: return {"ok": False, "reason": str(exc)} @@ -528,9 +528,6 @@ def handle_native_context_command(args: argparse.Namespace, *, print_payload: Ca print_payload({"ok": False, "reason": "--prepared-claim-operation-id requires quota context-project"}, args.format, str) return 1 - if getattr(args, "complete_turn", False) and (args.quota_command != "should-run" or args.format != "json"): - print_payload({"ok": False, "reason": "--complete-turn requires JSON quota should-run"}, args.format, str) - return 1 if getattr(args, "scheduler_observation", False): from .quota_request import validate_scheduler_observation_request diff --git a/loopx/cli_commands/quota_registration.py b/loopx/cli_commands/quota_registration.py index d1fec55ce8..4824de9580 100644 --- a/loopx/cli_commands/quota_registration.py +++ b/loopx/cli_commands/quota_registration.py @@ -216,18 +216,6 @@ def register_quota_command( choices=["interactive", "isolated_headless", "hosted_automation"], help="Execution mode paired with --host-surface and --scheduler-owner.", ) - turn_view = quota_parser.add_mutually_exclusive_group() - turn_view.add_argument( - "--turn-envelope", - action="store_true", - help=( - "Compatibility alias: quota should-run already returns the complete v1 work contract. " - "Context and Delta delivery remain independent." - ), - ) - turn_view.add_argument("--complete-turn", action="store_true", - help="Compatibility alias: quota should-run already returns the complete v1 work contract " - "and its shared exact-Turn settlement. Context and Delta delivery remain independent.") capture_group = quota_parser.add_mutually_exclusive_group() capture_group.add_argument( "--decision-output-dir", diff --git a/loopx/cli_commands/quota_request.py b/loopx/cli_commands/quota_request.py index fef28d6103..57003515fa 100644 --- a/loopx/cli_commands/quota_request.py +++ b/loopx/cli_commands/quota_request.py @@ -221,7 +221,7 @@ def validate_scheduler_observation_request(args: argparse.Namespace) -> None: "begin_turn", "turn_instance_id", "todo_id", "execute", "record_host_poll", "available_capabilities", "decision_output_dir", "decision_output_root", "decision_handoff_socket", "codex_context_dir", "codex_context_root", - "context_delivery", "delta_delivery", "turn_envelope", "complete_turn", "include_details", + "context_delivery", "delta_delivery", "include_details", "include_scheduler_detail", "max_page_output_bytes", "prepared_capture_reference", "defer_context_presentation", "capture_file", "decision_file", "outcome_ref", "source_hash", diff --git a/loopx/cli_commands/support_control_heartbeat.py b/loopx/cli_commands/support_control_heartbeat.py index dc1019c27a..5c07af5e02 100644 --- a/loopx/cli_commands/support_control_heartbeat.py +++ b/loopx/cli_commands/support_control_heartbeat.py @@ -214,8 +214,6 @@ def handle_heartbeat_prompt_command( codex_context_root=args.codex_context_root, context_delivery=args.context_delivery, delta_delivery=args.delta_delivery, - turn_envelope=args.turn_envelope, - complete_turn=getattr(args, "complete_turn", False), reward_memory_enabled=reward_memory_enabled, ) if args.bootstrap and payload.get("ok"): diff --git a/loopx/cli_commands/support_control_heartbeat_registration.py b/loopx/cli_commands/support_control_heartbeat_registration.py index 8102ecad32..14aae3e42c 100644 --- a/loopx/cli_commands/support_control_heartbeat_registration.py +++ b/loopx/cli_commands/support_control_heartbeat_registration.py @@ -169,17 +169,6 @@ def register_heartbeat_control_commands( "or codex-context-root with the normal per-wake LOOPX_TURN binding.", ) - turn_view = heartbeat_prompt_parser.add_mutually_exclusive_group() - turn_view.add_argument( - "--turn-envelope", - action="store_true", - help="Compatibility input for saved thin prompts with --decision-output-root. " - "Generated guards use the complete v1 work contract.", - ) - turn_view.add_argument("--complete-turn", action="store_true", - help="Compatibility input for saved thin host-owned prompts. " - "Generated guards use the complete v1 work contract.") - heartbeat_prompt_parser.add_argument( "--decision-handoff-socket", help="Retain the explicit private Host handoff on generated guards; requires --decision-output-root.", diff --git a/loopx/control_plane/heartbeat/builder.py b/loopx/control_plane/heartbeat/builder.py index 01140cd96e..186ff88cc6 100644 --- a/loopx/control_plane/heartbeat/builder.py +++ b/loopx/control_plane/heartbeat/builder.py @@ -381,8 +381,6 @@ def build_heartbeat_prompt( codex_context_root: str | None = None, context_delivery: str | None = None, delta_delivery: str | None = None, - turn_envelope: bool = False, - complete_turn: bool = False, ) -> dict[str, Any]: if not (full or compact or brief or thin): thin = True @@ -454,8 +452,6 @@ def build_heartbeat_prompt( codex_context_dir=codex_context_dir, codex_context_root=codex_context_root, context_delivery=effective_context_delivery, - turn_envelope=turn_envelope, - complete_turn=complete_turn, ) explicit_agent_scopes = normalize_agent_scopes(agent_scopes) if explicit_agent_scopes: diff --git a/loopx/control_plane/heartbeat/host.py b/loopx/control_plane/heartbeat/host.py index 63f4e40ad9..45d2a09f08 100644 --- a/loopx/control_plane/heartbeat/host.py +++ b/loopx/control_plane/heartbeat/host.py @@ -33,12 +33,8 @@ def resolve_heartbeat_capture_root( codex_context_dir: str | None = None, codex_context_root: str | None = None, context_delivery: str = "off", - turn_envelope: bool = False, - complete_turn: bool = False, ) -> Path | None: """Validate capture transport for an already resolved host-owned Turn.""" - if complete_turn and (turn_envelope or native_goal_host or not thin): - raise ValueError("--complete-turn requires a thin host-owned heartbeat without --turn-envelope") enabled = context_delivery == "on" if enabled and not (codex_context_dir or codex_context_root): raise ValueError("context-delivery requires a native context location") @@ -49,8 +45,6 @@ def resolve_heartbeat_capture_root( if root is None: if decision_handoff_socket is not None: raise ValueError("decision handoff requires an explicit decision capture root") - if turn_envelope: - raise ValueError("TurnEnvelope requires an explicit decision capture root") return None if (not thin or full or compact or brief or (native_goal_host and not enabled) or (not turn_instance_id and codex_context_root is None)): diff --git a/loopx/control_plane/testing/cli_output_budget.py b/loopx/control_plane/testing/cli_output_budget.py index fa858efa5e..b1e62e36c6 100644 --- a/loopx/control_plane/testing/cli_output_budget.py +++ b/loopx/control_plane/testing/cli_output_budget.py @@ -418,7 +418,7 @@ class CliOutputCommandClassification: CliOutputModeVariantSpec( variant_id="quota_should_run_scheduler_detail", parent_surface_id="quota_should_run", - command="quota should-run --turn-envelope --context-delivery off --include-detail scheduler", + command="quota should-run --context-delivery off --include-detail scheduler", output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", @@ -429,7 +429,7 @@ class CliOutputCommandClassification: CliOutputModeVariantSpec( variant_id="quota_should_run_todo_summary_detail", parent_surface_id="quota_should_run", - command="quota should-run --turn-envelope --context-delivery off --include-detail agent-todos", + command="quota should-run --context-delivery off --include-detail agent-todos", output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", @@ -440,7 +440,7 @@ class CliOutputCommandClassification: CliOutputModeVariantSpec( variant_id="quota_should_run_user_todo_summary_detail", parent_surface_id="quota_should_run", - command="quota should-run --turn-envelope --context-delivery off --include-detail user-todos", + command="quota should-run --context-delivery off --include-detail user-todos", output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", @@ -451,7 +451,7 @@ class CliOutputCommandClassification: CliOutputModeVariantSpec( variant_id="quota_should_run_goal_boundary_detail", parent_surface_id="quota_should_run", - command="quota should-run --turn-envelope --context-delivery off --include-detail goal-boundary", + command="quota should-run --context-delivery off --include-detail goal-boundary", output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", @@ -462,7 +462,7 @@ class CliOutputCommandClassification: CliOutputModeVariantSpec( variant_id="quota_should_run_vision_detail", parent_surface_id="quota_should_run", - command="quota should-run --turn-envelope --context-delivery off --include-detail vision", + command="quota should-run --context-delivery off --include-detail vision", output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", @@ -477,7 +477,7 @@ class CliOutputCommandClassification: CliOutputModeVariantSpec( variant_id="quota_should_run_all_detail", parent_surface_id="quota_should_run", - command="quota should-run --turn-envelope --context-delivery off --include-detail all", + command="quota should-run --context-delivery off --include-detail all", output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", @@ -488,7 +488,7 @@ class CliOutputCommandClassification: CliOutputModeVariantSpec( variant_id="quota_should_run_turn_envelope", parent_surface_id="quota_should_run", - command="quota should-run --context-delivery off --turn-envelope", + command="quota should-run --context-delivery off", output_formats=("json", "markdown"), semantic_json_keys=("schema_version", "contract_binding", "interaction_contract", "scheduler_hint", "selected_todo"), markdown_anchor="# LoopX Turn Envelope", diff --git a/loopx/hosts/codex_checkpoint.py b/loopx/hosts/codex_checkpoint.py index 20b42dd56a..1570d501ac 100644 --- a/loopx/hosts/codex_checkpoint.py +++ b/loopx/hosts/codex_checkpoint.py @@ -364,11 +364,24 @@ def _verify_interrupted_guard(turns: list[dict], guard: dict) -> None: item.get("cwd") != guard["workspace"]): raise ValueError("native checkpoint has output or work beyond its pending guard") parser = build_parser() + retired_flags = {"--turn-envelope": "turn_envelope", "--complete-turn": "complete_turn"} + def arguments(command): argv = _guard_cli_arguments(command, guard) try: + # Old sealed checkpoints attest these exact flags. The reader + # compares their historical values without invoking the old CLI. + historical = [word for word in argv if word in retired_flags] + if len(historical) > 1: + raise ValueError("native pending guard has ambiguous retired flags") + if historical: + index = argv.index(historical[0]) + if index <= argv.index("quota") or "--" in argv[:index]: + raise ValueError("native pending guard has a misplaced retired flag") + del argv[index] with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): parsed = vars(parser.parse_args(argv)) + parsed.update({field: flag in historical for flag, field in retired_flags.items()}) # A sealed command is independent of today's machine preference. # Legacy omitted transport flags mean off; explicit on stays distinct. if parsed.get("context_delivery") is None: diff --git a/tests/cli_commands/test_quota_closeout_query_failure.py b/tests/cli_commands/test_quota_closeout_query_failure.py index b3992e3af4..70f05cf345 100644 --- a/tests/cli_commands/test_quota_closeout_query_failure.py +++ b/tests/cli_commands/test_quota_closeout_query_failure.py @@ -15,10 +15,9 @@ @pytest.mark.parametrize("existing", [False, True]) -@pytest.mark.parametrize("turn_envelope", [False, True]) @pytest.mark.parametrize("failure", ["query", "write"]) def test_cli_preserves_query_failure_and_existing_receipt( - tmp_path, monkeypatch, existing, turn_envelope, failure, + tmp_path, monkeypatch, existing, failure, ): goal, agent, turn = "fixture-goal", "fixture-agent", "fixture-turn" registry = tmp_path / "registry.json" @@ -33,7 +32,7 @@ def test_cli_preserves_query_failure_and_existing_receipt( args = build_parser().parse_args([ "--format", "json", "quota", "should-run", "--goal-id", goal, "--agent-id", agent, "--turn-instance-id", turn, - ] + (["--turn-envelope"] if turn_envelope else [])) + ]) context = QuotaCommandContext( runtime_root=tmp_path, status_limit=1, status_goal_id=goal, status_payload={}, cache_metadata=None, scheduler_context=None, diff --git a/tests/control_plane/test_agent_preferences.py b/tests/control_plane/test_agent_preferences.py index 30b7cef208..3f3b37df99 100644 --- a/tests/control_plane/test_agent_preferences.py +++ b/tests/control_plane/test_agent_preferences.py @@ -216,7 +216,7 @@ def call(action, *args): 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") + rc, quota_envelope = _run_cli(registry, runtime, "quota", "should-run", *scope) assert rc == 0, quota_envelope assert quota_envelope["interaction_contract"]["agent_channel"]["work_context"]["unavailable_context"] == unavailable changed = deepcopy(failed_plan) diff --git a/tests/control_plane/test_benchmark_planning_batch.py b/tests/control_plane/test_benchmark_planning_batch.py index 1193e2b070..f95e81849c 100644 --- a/tests/control_plane/test_benchmark_planning_batch.py +++ b/tests/control_plane/test_benchmark_planning_batch.py @@ -132,7 +132,7 @@ def read(): code, admitted = fixture._run_cli( source, runtime, "quota", "should-run", "--goal-id", fixture.GOAL_ID, "--agent-id", fixture.AGENT_ID, "--todo-id", ids[0], "--runtime-profile", "generic_cli", - "--complete-turn", "--context-delivery", "off", "--delta-delivery", "off", + "--context-delivery", "off", "--delta-delivery", "off", "--turn-instance-id", "batch-fixture-execution", cwd=project, ) assert code == 0 and admitted["should_run"] and admitted["selected_todo"]["todo_id"] == ids[0] diff --git a/tests/control_plane/test_cli_output_budget.py b/tests/control_plane/test_cli_output_budget.py index 78f6b74160..ab60b13401 100644 --- a/tests/control_plane/test_cli_output_budget.py +++ b/tests/control_plane/test_cli_output_budget.py @@ -618,7 +618,7 @@ def _mode_variant_commands( "quota_should_run_goal_boundary_detail": quota + ["--include-detail", "goal-boundary"], "quota_should_run_vision_detail": quota + ["--include-detail", "vision"], "quota_should_run_all_detail": quota + ["--include-detail", "all"], - "quota_should_run_turn_envelope": quota + ["--turn-envelope"], + "quota_should_run_turn_envelope": quota, "loopx_turn_plan_transaction_detail": common + [ "turn", @@ -2248,7 +2248,7 @@ def test_turn_envelope_cli_preserves_codex_app_scheduler_binding( payload = _json_payload(text) 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. + # A fresh codex-app read preserves the same host profile. read_rc, read_text = _invoke_cli( [ "--registry", str(registry_path), "--runtime-root", str(runtime), diff --git a/tests/control_plane/test_codex_context_capture.py b/tests/control_plane/test_codex_context_capture.py index d1f31382cb..1adc1679a4 100644 --- a/tests/control_plane/test_codex_context_capture.py +++ b/tests/control_plane/test_codex_context_capture.py @@ -140,14 +140,12 @@ def test_native_cli_capture_delta_and_compact_recovery(tmp_path, monkeypatch, ho "--decision-output-root", str(root), "--context-delivery", "on", *host_args, context_option, str(lifecycle)] if handoff_socket: command += ["--decision-handoff-socket", handoff_socket] - display_args = {"turn_envelope": ["--turn-envelope"], "complete_turn": ["--complete-turn"]}.get(surface, []) - command.extend(display_args) generated_guard = None if shared_root: generated = subprocess.run([*cli, "--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", "heartbeat-prompt", "--thin", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--decision-output-root", str(root), - "--context-delivery", "on", *host_args, context_option, str(lifecycle), *display_args], + "--context-delivery", "on", *host_args, context_option, str(lifecycle)], capture_output=True, text=True, timeout=15) assert generated.returncode == 0, generated.stderr or generated.stdout prompt = json.loads(generated.stdout) @@ -554,7 +552,7 @@ def observed_response(request, number, message): project_hooks.write_text(json.dumps({"hooks": {"SessionStart": [{"hooks": [{ "type": "command", "command": shlex.join(["touch", str(unrelated)])}]}]}})) # Current benchmark delivery exercises default and explicit Complete. - env.update(LOOPX_CONTEXT_DELIVERY="on", LOOPX_COMPLETE_TURN=str(int(surface == "complete_turn")), + env.update(LOOPX_CONTEXT_DELIVERY="on", LOOPX_EXECUTION_MODE="heartbeat", LOOPX_ITERATION_CONTEXT="resume", LOOPX_TASK_ENTRY="seeded-todo", LOOPX_TASK_STAGE="execute", LOOPX_CODEX_HOME=str(home), LOOPX_PROJECT=str(project), LOOPX_SHARED_SKILLS=str(skills), diff --git a/tests/control_plane/test_context_delivery_cli.py b/tests/control_plane/test_context_delivery_cli.py index 3f0b48f21e..b9fbcb1a47 100644 --- a/tests/control_plane/test_context_delivery_cli.py +++ b/tests/control_plane/test_context_delivery_cli.py @@ -422,8 +422,7 @@ def release(): "--turn-instance-id", "host-context-delivery", "--context-delivery", setting, "--decision-output-root", str(root), "--decision-handoff-socket", str(endpoint), - *(["--codex-context-dir", str(native_directory)] if native_context else []), - *(["--turn-envelope"] if surface == "turn_envelope" else []), cwd=project) + *(["--codex-context-dir", str(native_directory)] if native_context else []), cwd=project) path, raw = future.result(timeout=30) assert code == 0, wire assert path.read_bytes() == raw diff --git a/tests/control_plane/test_context_first_read.py b/tests/control_plane/test_context_first_read.py index 5bc6202bc9..748338b721 100644 --- a/tests/control_plane/test_context_first_read.py +++ b/tests/control_plane/test_context_first_read.py @@ -97,26 +97,22 @@ def option(name): return page, selected_context_values(page["content"]) -@pytest.mark.parametrize(("flag", "option"), [ - ("--turn-envelope", "turn_envelope"), ("--complete-turn", "complete_turn"), -]) -def test_new_selection_omits_view_alias_and_saved_selection_retains_it(tmp_path, flag, option): - from loopx.cli_commands.quota_context_reader import bind_capture_selection_transport +@pytest.mark.parametrize("flag", ["--turn-envelope", "--complete-turn"]) +def test_saved_selection_projects_current_command_without_changing_capture(tmp_path, flag): + from loopx.cli_commands.quota_context_reader import _capture_selection_transport_template original = {"schema_version": "loopx_turn_envelope_v1", "interaction_contract": {"cli_channel": { "selection_command": {"command_args_template": "quota should-run --todo-id "}}}} - current = deepcopy(original) - request = Namespace(decision_output_root=str(tmp_path), **{option: True}) - bind_capture_selection_transport(current, request) - current_command = current["interaction_contract"]["cli_channel"]["selection_command"] - assert flag not in shlex.split(current_command["command_args_template"]) - - # Stored selectors keep their recorded command for same-capture recovery. - saved = deepcopy(original) - saved_command = saved["interaction_contract"]["cli_channel"]["selection_command"] + saved_command = original["interaction_contract"]["cli_channel"]["selection_command"] saved_command["command_args_template"] += " " + flag - bind_capture_selection_transport(saved, Namespace(decision_output_root=str(tmp_path))) - assert shlex.split(saved_command["command_args_template"]).count(flag) == 1 + before = deepcopy(original) + displayed = _capture_selection_transport_template( + original, Namespace(decision_output_root=str(tmp_path)), capture_root=tmp_path, + ) + assert shlex.split(displayed) == [ + "quota", "should-run", "--todo-id", "", "--decision-output-root", str(tmp_path.resolve()), + ] + assert original == before def pinned_initial_view(payload, directory): diff --git a/tests/control_plane/test_dated_vision_wait_cli.py b/tests/control_plane/test_dated_vision_wait_cli.py index 67ffe1092f..77a89f342c 100644 --- a/tests/control_plane/test_dated_vision_wait_cli.py +++ b/tests/control_plane/test_dated_vision_wait_cli.py @@ -232,8 +232,7 @@ def test_watch_only_monitor_preserves_dated_successor_wait( "--available-capability", "network", "--available-capability", "external_evidence_poll", "--turn-instance-id") details = ("--include-detail", "agent-todos") if scenario == "unproven" else () - saved_alias = ("--turn-envelope",) if details else () - rc, first = cli(registry, runtime, *args, "watch-first", *details, *saved_alias) + rc, first = cli(registry, runtime, *args, "watch-first", *details) assert rc == 0, first if scenario == "successor_due": assert first["effective_action"] == "successor_replan_required" diff --git a/tests/control_plane/test_effect_runtime_host_permission.py b/tests/control_plane/test_effect_runtime_host_permission.py index c9ca7090a8..156b6dbeb5 100644 --- a/tests/control_plane/test_effect_runtime_host_permission.py +++ b/tests/control_plane/test_effect_runtime_host_permission.py @@ -152,10 +152,9 @@ def collect(**_kwargs): assert registry.read_text() == "{}" -@pytest.mark.parametrize("turn_envelope", [False, True]) @pytest.mark.parametrize("output_format", ["json", "markdown"]) def test_failed_guard_keeps_host_recovery_without_runtime_presentation( - tmp_path: Path, monkeypatch, capsys, turn_envelope, output_format, + tmp_path: Path, monkeypatch, capsys, output_format, ) -> None: from loopx.cli_commands import quota as command from loopx.cli_runtime import print_payload @@ -164,7 +163,6 @@ def test_failed_guard_keeps_host_recovery_without_runtime_presentation( registry.write_text("{}") args = build_parser().parse_args([ "--format", output_format, "quota", "should-run", "--goal-id", "fixture-goal", - *(["--turn-envelope"] if turn_envelope else []), ]) def denied(*_args, **_kwargs): diff --git a/tests/control_plane/test_effective_turn_replan.py b/tests/control_plane/test_effective_turn_replan.py index 4422758afc..8ba86e81d2 100644 --- a/tests/control_plane/test_effective_turn_replan.py +++ b/tests/control_plane/test_effective_turn_replan.py @@ -333,7 +333,7 @@ def periodic(): assert authoring["schema_version"] == "goal_vision_replan_contract_v0" if threshold_override is None and device_count is None: rc, envelope = _run_cli( - registry, runtime, "quota", "should-run", "--codex-app", "--turn-envelope", + registry, runtime, "quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", "effective-turn-next", ) diff --git a/tests/control_plane/test_explore_settlement_attachment.py b/tests/control_plane/test_explore_settlement_attachment.py index e75bda46b0..da2edd0eb6 100644 --- a/tests/control_plane/test_explore_settlement_attachment.py +++ b/tests/control_plane/test_explore_settlement_attachment.py @@ -70,7 +70,7 @@ def test_real_cli_settlement_exposes_optional_attachment(tmp_path, monkeypatch, writeback = plan["ordered_steps"][1] assert writeback["optional_attachments"][0]["required"] is False assert "--explore-result-json" not in writeback["command_template"] - rc, compact = _run_cli(path, runtime, *command, "--turn-envelope", cwd=project) + rc, compact = _run_cli(path, runtime, *command, cwd=project) assert rc == 0, compact assert compact["interaction_contract"]["cli_channel"]["settlement_plan"] == plan rc, completed = _run_cli(path, runtime, "todo", "complete", *binding, diff --git a/tests/control_plane/test_heartbeat_cli.py b/tests/control_plane/test_heartbeat_cli.py index b83d10cd34..00e1902e0e 100644 --- a/tests/control_plane/test_heartbeat_cli.py +++ b/tests/control_plane/test_heartbeat_cli.py @@ -16,6 +16,8 @@ (["heartbeat-prompt", "--goal-id"], 2), (["heartbeat-prompt", "--goal", "fixture"], 2), (["heartbeat-prompt", "--goal-id=fixture", "--unknown"], 2), + (["heartbeat-prompt", "--goal-id=fixture", "--turn-envelope"], 2), + (["heartbeat-prompt", "--goal-id=fixture", "--complete-turn"], 2), (["heartbeat-prompt", "--goal-id=fixture", "--full", "--thin"], 2), (["heartbeat-prompt", "--goal-id=fixture", "--runtime-profile=unknown"], 2), (["heartbeat-prompt", "--goal-id=fixture", "--context-delivery=invalid"], 2), @@ -69,7 +71,6 @@ def test_heartbeat_semantic_errors_keep_recovery_and_exit_status(tmp_path): ["--agent-id=unregistered"], ["--goal-id=missing"], ["--context-delivery=on", "--trae_app"], - ["--turn-envelope"], ["--decision-handoff-socket=missing"], )] full = run_cli_batch("loopx.cli", cases) diff --git a/tests/control_plane/test_heartbeat_command_authority.py b/tests/control_plane/test_heartbeat_command_authority.py index 13bc93df74..68f0bacb95 100644 --- a/tests/control_plane/test_heartbeat_command_authority.py +++ b/tests/control_plane/test_heartbeat_command_authority.py @@ -53,8 +53,7 @@ def test_current_selection_and_settlement_override_goal_command(tmp_path, provid captures = [] settlement_identities = [] receipt_counts = [] - for name, view in (("default", ()), ("detail", ("--include-detail", "all")), - ("envelope-alias", ("--turn-envelope",)), ("complete-alias", ("--complete-turn",))): + for name, view in (("default", ()), ("detail", ("--include-detail", "all"))): capture = tmp_path / (name + "-capture") code, current = cli._run_cli(registry, runtime, *args, *binding, *view, "--decision-output-dir", str(capture), cwd=project) diff --git a/tests/control_plane/test_heartbeat_envelope_transport.py b/tests/control_plane/test_heartbeat_envelope_transport.py index b0bc6f6c42..56a7c40b76 100644 --- a/tests/control_plane/test_heartbeat_envelope_transport.py +++ b/tests/control_plane/test_heartbeat_envelope_transport.py @@ -48,7 +48,6 @@ def test_shared_native_root_keeps_dynamic_turn_binding_and_bootstrap_options(tmp args = dict(goal_id=GOAL_ID, agent_id=AGENT_ID, runtime_profile="codex_app_heartbeat", thin=True, decision_output_root=tmp_path, codex_context_root=str(tmp_path), context_delivery="on") - assert build_heartbeat_prompt(**args, **{field: True}) == build_heartbeat_prompt(**args) prompt = build_heartbeat_prompt(**args) guard = prompt["quota_guard_command"] assert '--turn-instance-id "${LOOPX_TURN:?}"' in guard @@ -62,7 +61,7 @@ def test_shared_native_root_keeps_dynamic_turn_binding_and_bootstrap_options(tmp assert list(tmp_path.iterdir()) == [] parser = build_parser() cli = ["heartbeat-prompt", "--thin", "--codex-app", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, - "--decision-output-root", str(tmp_path), "--context-delivery", "on", "--codex-context-root", str(tmp_path), alias, "--bootstrap"] + "--decision-output-root", str(tmp_path), "--context-delivery", "on", "--codex-context-root", str(tmp_path), "--bootstrap"] parsed = parser.parse_args(cli) bootstrap = goal_bootstrap(parsed, registry=tmp_path / "registry.json") command = shlex.split(bootstrap.split("```sh\n")[1].split("\n```")[0]) @@ -76,7 +75,7 @@ def test_shared_native_root_keeps_dynamic_turn_binding_and_bootstrap_options(tmp assert host_bootstrap_binding(render_heartbeat_bootstrap([*command, alias, alias])) is None -def test_capture_preserves_full_dispatcher_with_complete_source_alias(tmp_path): +def test_capture_preserves_full_dispatcher(tmp_path): args = dict(goal_id=GOAL_ID, agent_id=AGENT_ID, runtime_profile="generic_cli", turn_instance_id=TURN_ID, thin=True) assert build_heartbeat_prompt(**args) == build_heartbeat_prompt(**args, decision_output_root=None) @@ -86,11 +85,8 @@ def test_capture_preserves_full_dispatcher_with_complete_source_alias(tmp_path): assert captured['quota_guard_command'] == ordinary['quota_guard_command'] + capture_args assert captured['task_body'].replace(capture_args, '') == ordinary['task_body'] assert '--turn-envelope' not in captured['quota_guard_command'] - with pytest.raises(ValueError, match='capture root'): - build_heartbeat_prompt(**args, turn_envelope=True) - payload = build_heartbeat_prompt(**args, decision_output_root=tmp_path, turn_envelope=True) + payload = captured assert payload['interface_budget']['within_budget'], payload['interface_budget'] - assert payload == captured assert 'interaction_contract.cli_channel.settlement_plan.ordered_steps' in payload['task_body'] assert '--decision-output-root' in payload['thin_prompt_command'] # The captured allowance must neither leak into ordinary thin nor disable @@ -101,7 +97,7 @@ def test_capture_preserves_full_dispatcher_with_complete_source_alias(tmp_path): assert ordinary['interface_budget']['max_chars'] == 5_100 assert captured_only['interface_budget']['max_chars'] == 5_100 oversized = build_heartbeat_prompt( - **no_memory, decision_output_root=tmp_path, turn_envelope=True, + **no_memory, decision_output_root=tmp_path, agent_scopes=[letter * 320 for letter in 'stuvwx'], ) assert oversized['interface_budget']['max_chars'] == 5_100 @@ -126,7 +122,7 @@ def test_captured_scheduler_ack_is_inline_and_failure_detail_stays_on_original_s capture = tmp_path / 'capture' code, envelope = _run_cli(registry, runtime, 'quota', 'should-run', '--goal-id', GOAL_ID, '--agent-id', AGENT_ID, '--todo-id', TODO_ID, - '--turn-instance-id', TURN_ID, '--codex-app', '--turn-envelope', + '--turn-instance-id', TURN_ID, '--codex-app', '--decision-output-dir', str(capture), cwd=project) assert code == 0, envelope original = (capture / 'decision.json').read_bytes() @@ -160,7 +156,7 @@ def test_bound_captured_prompt_fits_budget_without_reward_memory( argv = [ sys.executable, '-m', 'loopx.entrypoint', '--format', 'json', '--registry', str(registry), '--runtime-root', str(runtime), - 'heartbeat-prompt', '--thin', '--turn-envelope', + 'heartbeat-prompt', '--thin', '--decision-output-root', str(capture), '--runtime-profile', 'generic_cli', '--goal-id', GOAL_ID, '--agent-id', AGENT_ID, '--turn-instance-id', TURN_ID, ] @@ -225,11 +221,10 @@ def release(): @pytest.mark.parametrize('provider', ['file', 'sqlite']) -@pytest.mark.parametrize('enabled', [False, True]) @pytest.mark.parametrize('private_handoff', [False, True], indirect=True) @pytest.mark.parametrize('context_delivery', [False, True]) def test_real_worker_generated_guard_selection_reentry_and_settle_once( - tmp_path, monkeypatch, provider, enabled, private_handoff, context_delivery, + tmp_path, monkeypatch, provider, private_handoff, context_delivery, ): from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime @@ -250,7 +245,7 @@ def test_real_worker_generated_guard_selection_reentry_and_settle_once( LOOPX_CLI=str(Path(sys.executable).parent / 'loopx'), LOOPX_REGISTRY=str(registry), LOOPX_RUNTIME_ROOT=str(runtime), LOOPX_PROJECT=str(project), LOOPX_GOAL_ID=GOAL_ID, LOOPX_AGENT_ID=AGENT_ID, - LOOPX_WAKE_LOG_DIR=str(logs), LOOPX_TURN_ENVELOPE='1' if enabled else '0') + LOOPX_WAKE_LOG_DIR=str(logs)) if context_delivery: # No native proof in this CLI fixture: composed capture must still # save a full baseline and preserve reentry and settlement. @@ -270,10 +265,6 @@ def test_real_worker_generated_guard_selection_reentry_and_settle_once( guard = guard.replace('${LOOPX_TURN:?}', TURN_ID) argv = shlex.split(guard) assert '--turn-envelope' not in argv - # A saved historical guard still executes. Its fresh reentry must use - # the complete contract without propagating the retired view option. - if enabled: - argv.append('--turn-envelope') result = subprocess.run(argv, env=env, cwd=project, capture_output=True, text=True) first = json.loads(result.stdout) assert result.returncode == 0, first @@ -301,23 +292,19 @@ def complete_page(value): return json.loads(body) first = complete_page(first) root = logs / TURN_ID / 'decisions' - captured = enabled or private_handoff is not None or context_delivery + captured = private_handoff is not None or context_delivery if captured: captures = list(root.glob('*/decision.json')) assert len(captures) == 1 full = json.loads(captures[0].read_text()) assert first == full and first['schema_version'] == 'loopx_turn_envelope_v1' - if enabled: - detail = shlex.split(first['detail_ref']['full_decision']) - receipts = _heartbeat_receipt_count(runtime, TURN_ID) - readback = subprocess.run(detail, env=env, cwd=project, capture_output=True, - text=True, check=True) - assert complete_page(json.loads(readback.stdout)) == full - assert _heartbeat_receipt_count(runtime, TURN_ID) == receipts - else: - assert first['interaction_contract'] == full['interaction_contract'] - assert 'action_signature' not in first and 'quota' in first - assert 'Use TurnEnvelope:' not in body + detail = shlex.split(first['detail_ref']['full_decision']) + receipts = _heartbeat_receipt_count(runtime, TURN_ID) + readback = subprocess.run(detail, env=env, cwd=project, capture_output=True, text=True, check=True) + assert complete_page(json.loads(readback.stdout)) == full + assert _heartbeat_receipt_count(runtime, TURN_ID) == receipts + assert 'action_signature' not in first and 'quota' in first + assert 'Use TurnEnvelope:' not in body else: assert not root.exists() full = first @@ -441,8 +428,7 @@ def test_native_context_prompt_keeps_capture_on_reentry(tmp_path, monkeypatch): assert argv[argv.index("--codex-context-dir") + 1] == context -@pytest.mark.parametrize("turn_envelope", [False, True]) -def test_ssh_goal_capture_keeps_native_begin_turn_and_off_boundary(tmp_path, turn_envelope): +def test_ssh_goal_capture_keeps_native_begin_turn_and_off_boundary(tmp_path): args = dict(goal_id=GOAL_ID, agent_id=AGENT_ID, runtime_profile="codex_app_ssh_goal", thin=True) original = build_heartbeat_prompt(**args) assert_explicit_off_keeps_legacy_prompt(original, build_heartbeat_prompt(**args, context_delivery="off")) @@ -450,22 +436,17 @@ def test_ssh_goal_capture_keeps_native_begin_turn_and_off_boundary(tmp_path, tur with pytest.raises(ValueError, match="host-owned"): build_heartbeat_prompt(**args, decision_output_root=tmp_path) enabled = build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=tmp_path, - codex_context_root=str(tmp_path), turn_envelope=turn_envelope) + codex_context_root=str(tmp_path)) guard = enabled["quota_guard_command"] assert "--runtime-profile codex_app_ssh_goal --begin-turn" in guard assert "--heartbeat-turn-receipt" not in guard and "${LOOPX_TURN" not in guard assert "--decision-output-root" in guard and "--codex-context-root" in guard assert "visible-goal" in enabled["quota_spend_command"] assert enabled["interface_budget"]["within_budget"] - if turn_envelope: - ordinary = build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=tmp_path, - codex_context_root=str(tmp_path)) - assert enabled == ordinary -@pytest.mark.parametrize("turn_envelope", [False, True]) @pytest.mark.parametrize("path_width,cli_width", [(160, 140), (133, 180)]) -def test_ssh_goal_capture_fits_host_with_full_command_paths(tmp_path, turn_envelope, path_width, cli_width): +def test_ssh_goal_capture_fits_host_with_full_command_paths(tmp_path, path_width, cli_width): # Fixed physical path width qualifies the shipped command workload on every # OS; the native cases also retain their actual, unshortened pytest paths. with stable_budget_fixture_root(tmp_path) as base: @@ -486,7 +467,7 @@ def test_ssh_goal_capture_fits_host_with_full_command_paths(tmp_path, turn_envel ordinary = build_heartbeat_prompt(**args) assert_explicit_off_keeps_legacy_prompt(ordinary, build_heartbeat_prompt(**args, context_delivery="off")) enabled = build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=captures, - codex_context_root=str(context), turn_envelope=turn_envelope) + codex_context_root=str(context)) body, command = enabled["task_body"], shlex.split(enabled["quota_guard_command"]) assert enabled["interface_budget"]["max_chars"] == 4000 and len(body) <= 4000 for obligation in ( @@ -513,10 +494,6 @@ def test_ssh_goal_capture_fits_host_with_full_command_paths(tmp_path, turn_envel < body.index(enabled["quota_guard_command"]) < body.index("Follow required selection_command/reentry") ) - if turn_envelope: - source = build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=captures, - codex_context_root=str(context)) - assert enabled == source with pytest.raises(ValueError, match="4000-character"): build_heartbeat_prompt(**args, context_delivery="on", decision_output_root=captures, - codex_context_root=str(context), turn_envelope=turn_envelope, agent_scopes=[c * 320 for c in "stu"]) + codex_context_root=str(context), agent_scopes=[c * 320 for c in "stu"]) diff --git a/tests/control_plane/test_open_outcome_replan.py b/tests/control_plane/test_open_outcome_replan.py index 4a7b2ec5ba..12d1d8a1cf 100644 --- a/tests/control_plane/test_open_outcome_replan.py +++ b/tests/control_plane/test_open_outcome_replan.py @@ -87,7 +87,7 @@ def guard(turn): assert "operating objective and cumulative requirements" in review assert "justified no-change" in review assert "goal-acceptance prepare-objective" in review - envelope = call("quota", "should-run", "--codex-app", "--turn-envelope", "--goal-id", GOAL, + envelope = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, "--todo-id", TODO, "--turn-instance-id", TURN, ) delivered = next( diff --git a/tests/control_plane/test_progressive_native_context.py b/tests/control_plane/test_progressive_native_context.py index 9ca205d831..9a41dde585 100644 --- a/tests/control_plane/test_progressive_native_context.py +++ b/tests/control_plane/test_progressive_native_context.py @@ -447,8 +447,7 @@ def test_numeric_type_difference_cannot_hide_a_duplicate_rows_original_value(tmp assert "context_reference_instruction" not in required -@pytest.mark.parametrize("complete", [False, True]) -def test_public_quota_cli_delivers_required_view_and_original_evidence(acceptance_goal, tmp_path, monkeypatch, complete): +def test_public_quota_cli_delivers_required_view_and_original_evidence(acceptance_goal, tmp_path, monkeypatch): workspace, document, cli, run = acceptance_goal original = {"outcome_id": "export", "owner_agent_id": "agent-a", "todo_ids": ["todo_export"], "objective": "Deliver the complete export.", "requirements": [ @@ -482,7 +481,7 @@ def test_public_quota_cli_delivers_required_view_and_original_evidence(acceptanc setup(lifecycle, monkeypatch) # Use the raw CLI response here. The acceptance fixture's policy reader # unwraps the navigation before returning the authoritative document. - code, packet = run_json_cli_result("quota", "should-run", *(["--complete-turn"] if complete else []), + code, packet = run_json_cli_result("quota", "should-run", "--goal-id", "goal-acceptance", "--agent-id", "agent-a", "--todo-id", "todo_export", "--context-delivery", "on", "--codex-app", "--codex-context-dir", str(lifecycle), "--decision-output-root", str(tmp_path / "captures"), diff --git a/tests/control_plane/test_quota_decision_capture.py b/tests/control_plane/test_quota_decision_capture.py index dfdadc24bd..4b8b7a0ec4 100644 --- a/tests/control_plane/test_quota_decision_capture.py +++ b/tests/control_plane/test_quota_decision_capture.py @@ -43,9 +43,8 @@ def test_prepared_reference_rejects_incompatible_delivery_before_guard(tmp_path, @pytest.mark.parametrize("provider", ["file", "sqlite"]) @pytest.mark.parametrize("context_delivery", ["off", "on"]) -@pytest.mark.parametrize("alias", [None, "--turn-envelope", "--complete-turn"]) -def test_prepared_capture_verifies_the_same_complete_turn_with_compatibility_aliases( - tmp_path, monkeypatch, provider, context_delivery, alias, +def test_prepared_capture_verifies_the_same_complete_turn( + tmp_path, monkeypatch, provider, context_delivery, ): from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime from tests.control_plane.test_quota_settlement_cli import _spend_run_count @@ -62,7 +61,7 @@ def test_prepared_capture_verifies_the_same_complete_turn_with_compatibility_ali code, prepared = _run_cli( registry, runtime, "quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID, "--codex-app", - "--context-delivery", context_delivery, *context_args, *([alias] if alias else []), + "--context-delivery", context_delivery, *context_args, "--decision-output-dir", str(capture_dir), "--prepared-capture-reference", ) assert code == 0, prepared @@ -284,8 +283,7 @@ def test_real_cli_fallback_reference_keeps_capture_and_turn_effects(tmp_path, mo @pytest.mark.parametrize('provider', ['file', 'sqlite']) -@pytest.mark.parametrize('alias', [None, '--turn-envelope', '--complete-turn']) -def test_real_cli_boundary_clauses_reach_shared_host_without_loss(tmp_path, monkeypatch, provider, alias): +def test_real_cli_boundary_clauses_reach_shared_host_without_loss(tmp_path, monkeypatch, provider): from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection from loopx.control_plane.turn_driver.host_candidate import extract_turn_authority, render_prompt from loopx.control_plane.turn_driver.driver import build_loopx_turn_plan @@ -319,7 +317,7 @@ def test_real_cli_boundary_clauses_reach_shared_host_without_loss(tmp_path, monk '--todo-id', TODO_ID, '--turn-instance-id', TURN_ID, '--codex-app', '--available-capability', 'shell', '--available-capability', 'filesystem_read'] capture = tmp_path / 'boundary-decision' - code, envelope = _run_cli(registry, runtime, *args, *([alias] if alias else []), + code, envelope = _run_cli(registry, runtime, *args, '--decision-output-dir', str(capture)) assert code == 0, envelope saved = capture / 'decision.json' @@ -379,7 +377,7 @@ def test_real_guard_saved_before_envelope_and_read_without_reexecution(tmp_path, args = ['quota', 'should-run', '--goal-id', GOAL_ID, '--agent-id', AGENT_ID, '--todo-id', TODO_ID, '--turn-instance-id', TURN_ID, '--codex-app', '--available-capability', 'shell', '--available-capability', 'filesystem_read'] - code, envelope = _run_cli(registry, runtime, *args, '--turn-envelope', + code, envelope = _run_cli(registry, runtime, *args, '--decision-output-dir', str(capture)) assert code == 0, envelope assert envelope['schema_version'] == 'loopx_turn_envelope_v1' @@ -439,7 +437,7 @@ def test_real_guard_saved_before_envelope_and_read_without_reexecution(tmp_path, assert json.loads(saved.read_text()) == full # A deliberate fresh invocation within the Turn has its own immutable capture. second = tmp_path / 'guard-2' - code, fresh = _run_cli(registry, runtime, *args, '--turn-envelope', '--decision-output-dir', str(second)) + code, fresh = _run_cli(registry, runtime, *args, '--decision-output-dir', str(second)) assert code == 0, fresh assert json.loads((second / 'decision.json').read_text())['heartbeat_receipt']['status'] == 'replayed' assert json.loads(saved.read_text()) == full @@ -648,7 +646,7 @@ def test_saved_selection_transport_preserves_identity_and_rebinds_once(tmp_path, selection = {"command_args_template": shlex.join(words)} payload = {"interaction_contract": {"cli_channel": {"selection_command": selection}}} args = request(None, decision_output_root=explicit if root_source == "explicit" else None, - context_delivery="on", codex_context_dir=str(native), turn_envelope=True, + context_delivery="on", codex_context_dir=str(native), max_page_output_bytes=output_limit) bind_capture_selection_transport(payload, args, capture_root=fallback) first = selection["command_args_template"] @@ -660,10 +658,10 @@ def test_saved_selection_transport_preserves_identity_and_rebinds_once(tmp_path, "goal", "agent", "{todo_id}", "original-turn") assert parsed.decision_output_root == str({"saved": saved, "explicit": explicit, "fallback": fallback}[root_source]) assert parsed.context_delivery == "on" and parsed.codex_context_dir == str(native) - assert parsed.codex_context_root is None and parsed.turn_envelope + assert parsed.codex_context_root is None and "--turn-envelope" not in argv assert parsed.max_page_output_bytes == (output_limit or 64000) assert all(argv.count(option) == 1 for option in - ("--decision-output-root", "--context-delivery", "--codex-context-dir", "--turn-envelope", + ("--decision-output-root", "--context-delivery", "--codex-context-dir", "--max-page-output-bytes")) assert not list(tmp_path.iterdir()) @@ -795,7 +793,7 @@ def serve(): thread.start() code, selected = _run_cli( registry, runtime, 'quota', 'should-run', *common, - '--todo-id', SELECTED_REPLAN_TODO_ID, '--turn-envelope', + '--todo-id', SELECTED_REPLAN_TODO_ID, '--decision-output-root', str(capture_root), '--decision-handoff-socket', str(endpoint), cwd=project) thread.join(10) @@ -936,9 +934,8 @@ def interrupt_compose(action, **kwargs): @pytest.mark.parametrize('provider', ['file', 'sqlite']) -@pytest.mark.parametrize('turn_envelope', [False, True]) def test_native_recovery_failure_keeps_original_receipt_and_capture( - tmp_path, monkeypatch, capsys, provider, turn_envelope, + tmp_path, monkeypatch, capsys, provider, ): from loopx.cli import main from loopx.control_plane.quota.error_codes import QuotaDecisionTransportError @@ -971,8 +968,6 @@ def refuse_recovery(payload, **kwargs): '--available-capability', 'shell', '--available-capability', 'filesystem_read', '--context-delivery', 'on', '--codex-context-dir', str(context), '--decision-output-root', str(captures)] - if turn_envelope: - args.append('--turn-envelope') code = main(args) failure = json.loads(capsys.readouterr().out) assert code == 1 and failure['ok'] is False diff --git a/tests/control_plane/test_quota_execution_preparation.py b/tests/control_plane/test_quota_execution_preparation.py index 201f99841c..c8c53267dc 100644 --- a/tests/control_plane/test_quota_execution_preparation.py +++ b/tests/control_plane/test_quota_execution_preparation.py @@ -649,8 +649,6 @@ def replace_capture(): def observe_guard(command, **kwargs): prepared = "--prepared-capture-reference" in command - if prepared and replace_stage == "version": - command = [*command, "--complete-turn"] result = run(command, **kwargs) if prepared: verified["writer"] = json.loads(result.stdout) diff --git a/tests/control_plane/test_quota_selection.py b/tests/control_plane/test_quota_selection.py index 3bea2ffd03..246dedb411 100644 --- a/tests/control_plane/test_quota_selection.py +++ b/tests/control_plane/test_quota_selection.py @@ -335,9 +335,8 @@ def test_quota_uses_complete_owned_commitment_count_before_display_cap(reverse): @pytest.mark.parametrize("display", ["current", "empty", "stale"]) @pytest.mark.parametrize("scope", ["global_gate=true", "blocks_agent=agent-b"]) @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("complete_turn", [False, True], ids=["ordinary", "complete-turn"]) def test_public_quota_keeps_gate_from_real_canonical_provider( - tmp_path: Path, monkeypatch, display: str, scope: str, provider: str, complete_turn: bool + tmp_path: Path, monkeypatch, display: str, scope: str, provider: str ): isolate_sqlite_runtime(tmp_path, monkeypatch) runtime, registry, state = tmp_path / "runtime", tmp_path / "registry.json", tmp_path / "state.md" @@ -362,15 +361,13 @@ def test_public_quota_keeps_gate_from_real_canonical_provider( elif display == "stale": state.write_text("# Stale projection\n## User Todo\n- [x] Old approval.\n") before = state.read_bytes() if state.exists() else None - view_args = ("--complete-turn",) if complete_turn else () code, packet = run_json_cli_result( "quota", "should-run", "--goal-id", "goal-scope", "--agent-id", "agent-b", - "--context-delivery", "off", *view_args, registry_path=registry, runtime_root=runtime, + "--context-delivery", "off", registry_path=registry, runtime_root=runtime, ) assert code == 0, packet assert packet["requires_user_action"] is True - if complete_turn: - assert_complete_turn_decision(packet) + assert_complete_turn_decision(packet) summary = packet["user_todo_summary"] if "gate_open_items_ref" in summary: assert summary["gate_open_items_ref"] == "$.user_todo_summary.first_open_items" diff --git a/tests/control_plane/test_refresh_settle_turn.py b/tests/control_plane/test_refresh_settle_turn.py index af1896b2db..650018b3db 100644 --- a/tests/control_plane/test_refresh_settle_turn.py +++ b/tests/control_plane/test_refresh_settle_turn.py @@ -29,7 +29,7 @@ def _ready_settlement_guard(tmp_path, monkeypatch, project, runtime, registry, p binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID] host = ["--codex-app"] if complete: - host = ["--runtime-profile", "generic_cli", "--complete-turn"] + host = ["--runtime-profile", "generic_cli"] monkeypatch.setenv("LOOPX_CONTEXT_DELIVERY", "on") monkeypatch.setenv("LOOPX_EXECUTION_MODE", "heartbeat") monkeypatch.setenv("LOOPX_PHASE_DEADLINE_EPOCH", "9876543210.125") @@ -424,7 +424,7 @@ def test_complete_turn_composition_failure_preserves_original_guard_and_recovers binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID] assert _run_cli(registry, runtime, "todo", "claim", *binding, "--claimed-by", AGENT_ID, cwd=project)[0] == 0 command = ["quota", "should-run", *binding, "--turn-instance-id", TURN_ID, - "--runtime-profile", "generic_cli", "--complete-turn", "--context-delivery", "off"] + "--runtime-profile", "generic_cli", "--context-delivery", "off"] directory = tmp_path / "failed-capture" def unavailable(*args, **kwargs): raise EffectRuntimeStartupError("synthetic complete-context transport unavailable", diagnostic_code="fixture_unavailable") @@ -460,16 +460,21 @@ def unavailable(*args, **kwargs): assert _heartbeat_receipt_count(runtime, TURN_ID) == 1 and _spend_run_count(runtime) == 0 -@pytest.mark.parametrize("command", ["status", "context-read", "spend-slot"]) -def test_complete_turn_rejects_other_routes_before_authority_io(tmp_path, command): +@pytest.mark.parametrize("flag", ["--turn-envelope", "--complete-turn"]) +def test_retired_display_aliases_rejected_before_admission(tmp_path, flag, capsys): + from loopx.cli import build_parser + registry, runtime = tmp_path / "absent.json", tmp_path / "absent-runtime" - rc, failed = _run_cli(registry, runtime, "quota", command, "--complete-turn") - assert rc == 1 and failed["reason"] == "--complete-turn requires JSON quota should-run" + with pytest.raises(SystemExit, match="2"): + build_parser().parse_args([ + "--registry", str(registry), "--runtime-root", str(runtime), "quota", "should-run", flag, + ]) + assert f"unrecognized arguments: {flag}" in capsys.readouterr().err assert not registry.exists() and not runtime.exists() @pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_compatibility_alias_soft_claim_reuses_the_original_default_receipt(tmp_path, provider): +def test_complete_turn_soft_claim_reuses_the_original_default_receipt(tmp_path, provider): project, runtime, registry = _write_fixture(tmp_path) _initialize_fixture_authority(project, runtime, provider=provider, handoff_mode="soft_claim") command = ["quota", "should-run", "--runtime-profile", "generic_cli", "--context-delivery", "off", @@ -478,7 +483,7 @@ def test_compatibility_alias_soft_claim_reuses_the_original_default_receipt(tmp_ assert rc == 0 and original.get("schema_version") == "loopx_turn_envelope_v1" original_cli = original["interaction_contract"]["cli_channel"] assert original_cli["settlement_plan"]["schema_version"] == "quota_settlement_plan_v2" - rc, complete = _run_cli(registry, runtime, *command, "--complete-turn", cwd=project) + rc, complete = _run_cli(registry, runtime, *command, cwd=project) assert rc == 0 and complete["schema_version"] == "loopx_turn_envelope_v1", complete cli = complete["interaction_contract"]["cli_channel"] assert "execution_preparation" not in cli # A soft claim never becomes a fabricated ready lease. diff --git a/tests/control_plane/test_replan_progress_native_cli.py b/tests/control_plane/test_replan_progress_native_cli.py index f7d0cdc046..b8cfe53cbe 100644 --- a/tests/control_plane/test_replan_progress_native_cli.py +++ b/tests/control_plane/test_replan_progress_native_cli.py @@ -336,14 +336,13 @@ def review_for(body): @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("envelope", [(), ("--complete-turn",)], ids=["quota", "complete"]) -def test_progressive_replan_stages_read_private_projection(tmp_path, monkeypatch, provider, envelope): +def test_progressive_replan_stages_read_private_projection(tmp_path, monkeypatch, provider): isolate_sqlite_runtime(tmp_path, monkeypatch) # An installed CLI can carry a long, quoted registry and runtime path. root = tmp_path / ("source with apostrophe's permission " + "x" * 110) root.mkdir() fixture = make_progress_cli_fixture(root, provider, "advanced") - scope = ("quota", "should-run", "--goal-id", GOAL, "--agent-id", AGENT, *envelope) + scope = ("quota", "should-run", "--goal-id", GOAL, "--agent-id", AGENT) def read(command, expected=0): result = subprocess.run(shlex.split(command), cwd=fixture["project"], capture_output=True, diff --git a/tests/control_plane/test_replan_staged_read.py b/tests/control_plane/test_replan_staged_read.py index 1a2851ef01..66b5bb3108 100644 --- a/tests/control_plane/test_replan_staged_read.py +++ b/tests/control_plane/test_replan_staged_read.py @@ -433,8 +433,7 @@ def test_review_retains_scoped_dependencies_and_unknown_outcomes(): @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("envelope", [False, True]) -def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, monkeypatch, provider, envelope): +def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, monkeypatch, provider): isolate_sqlite_runtime(tmp_path, monkeypatch) fixture = make_progress_cli_fixture(tmp_path, provider, "advanced") enable_explore(fixture) @@ -448,13 +447,10 @@ def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, m pinned_cli = str(Path(sys.executable).with_name("loopx")) guard = call_progress_cli(fixture, "--cli-bin", pinned_cli, "quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", TURN, - "--todo-id", TODO, "--decision-output-dir", str(capture), - *(["--turn-envelope"] if envelope else [])) + "--todo-id", TODO, "--decision-output-dir", str(capture)) guard = read_cli_policy_payload(json.dumps(guard), returncode=0) packet = guard["replan_action_packet"] - if not envelope: - assert "settlement_plan" not in guard["interaction_contract"]["cli_channel"] - assert guard["interaction_contract"]["cli_channel"]["settlement_read_ref"] == "$.replan_action_packet.writeback" + assert guard["interaction_contract"]["cli_channel"]["settlement_read_ref"] == "$.replan_action_packet.writeback" saved = (capture / "decision.json").read_bytes() source = json.loads(saved) # Unknown old/custom prose, different templates, ambiguous/missing @@ -509,9 +505,8 @@ def read(stage, expected_code=0): expected_goal = source["autonomous_replan_obligation"]["replan_context"]["core_goal"] assert review["core_goal"] == expected_goal assert review["action_portfolio"] == source.get("action_portfolio") - if not envelope: - assert "core_goal" not in guard and "planning_horizon" not in guard - assert guard.get("action_portfolio") == source.get("action_portfolio") + assert "core_goal" not in guard and "planning_horizon" not in guard + assert guard.get("action_portfolio") == source.get("action_portfolio") assert review["context_id"] == writer["context_id"] assert review["obligation_id"] == source["replan_action_packet"]["obligation_id"] assert writer["writeback_contract"] == without_example(source["replan_action_packet"]["writeback_contract"]) diff --git a/tests/control_plane/test_replan_successor_guard_reentry.py b/tests/control_plane/test_replan_successor_guard_reentry.py index 6922bccd5f..cd09d20bf9 100644 --- a/tests/control_plane/test_replan_successor_guard_reentry.py +++ b/tests/control_plane/test_replan_successor_guard_reentry.py @@ -436,7 +436,7 @@ def test_successor_guard_returns_original_settlement_not_repeated_planning( assert all("--replan-obligation-id " + obligation_id in command for command in actions) assert all("--turn-instance-id " + TURN in command for command in actions) envelope = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, - "--agent-id", AGENT, "--turn-instance-id", TURN, "--turn-envelope") + "--agent-id", AGENT, "--turn-instance-id", TURN) assert envelope["replan_action_packet"]["settlement_only"] is True assert envelope["interaction_contract"]["cli_channel"]["next_cli_actions"] == actions assert envelope["contract_binding"]["source_decision_hash"] @@ -464,7 +464,7 @@ def test_successor_guard_returns_original_settlement_not_repeated_planning( assert pending_plan["identity"] == identity assert pending_plan["ordered_steps"] == [cli["settlement_plan"]["ordered_steps"][-1]] pending_envelope = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, - "--agent-id", AGENT, "--turn-instance-id", TURN, "--turn-envelope") + "--agent-id", AGENT, "--turn-instance-id", TURN) assert pending_envelope["interaction_contract"]["cli_channel"]["next_cli_actions"] == spend_actions assert pending_envelope["interaction_contract"]["cli_channel"]["settlement_plan"] == pending_plan assert pending_envelope["contract_binding"]["source_decision_hash"] diff --git a/tests/control_plane/test_saved_context_project.py b/tests/control_plane/test_saved_context_project.py index 084caa7f56..2a24f61341 100644 --- a/tests/control_plane/test_saved_context_project.py +++ b/tests/control_plane/test_saved_context_project.py @@ -79,7 +79,7 @@ def test_saved_complete_quota_projection_rejects_invalid_source_without_legacy_f binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--turn-instance-id", TURN_ID] directory = tmp_path / "capture" code, result = _run_cli(registry, runtime, "quota", "should-run", *binding, "--todo-id", TODO_ID, - "--complete-turn", "--context-delivery", "off", "--decision-output-dir", str(directory), cwd=project) + "--context-delivery", "off", "--decision-output-dir", str(directory), cwd=project) assert code == 0, result original = directory / "decision.json" raw = original.read_bytes() diff --git a/tests/control_plane/test_selected_work_requirements.py b/tests/control_plane/test_selected_work_requirements.py index 19c34af9dd..692a61f377 100644 --- a/tests/control_plane/test_selected_work_requirements.py +++ b/tests/control_plane/test_selected_work_requirements.py @@ -146,20 +146,17 @@ def old_delivery(options): assert packet["requires_user_action"] is True 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["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. state.unlink() - for flags in ((), ("--turn-envelope",), ("--complete-turn",)): - failed = guard(*flags, expected_exit=1) - assert failed["ok"] is False - assert failed["decision"] == "skip" and failed["should_run"] is False - assert failed["diagnostic_code"] == "invalid_request" - assert failed["reason"] == "Complete Goal source is required before host dispatch" - assert "interaction_contract" not in failed - assert "reference_file" not in failed + failed = guard(expected_exit=1) + assert failed["ok"] is False + assert failed["decision"] == "skip" and failed["should_run"] is False + assert failed["diagnostic_code"] == "invalid_request" + assert failed["reason"] == "Complete Goal source is required before host dispatch" + assert "interaction_contract" not in failed + assert "reference_file" not in failed state.write_text(state_text) assert guard()["interaction_contract"]["agent_channel"]["work_context"]["complete"] is True @@ -212,7 +209,7 @@ def guard(*extra: str) -> dict: assert packet["should_run"] is True, packet.get("reason") return packet - envelope = guard("--turn-envelope") + envelope = guard() before = state.read_bytes() # Run the actual default product prompt's guard: no capture/envelope opt-in. code, generated = run_json_cli_result("heartbeat-prompt", "--goal-id", "requirements-goal", @@ -306,7 +303,7 @@ def read_detail() -> dict: assert fresh["selected_todo"]["todo_id"] == "todo_cursor_work" fresh_reads = fresh["interaction_contract"]["agent_channel"]["work_context"]["sources"] assert fresh_reads[-1]["content"]["todo"]["text"] == replacement - fresh_envelope = guard("--turn-envelope") + fresh_envelope = guard() fresh_plan = build_loopx_turn_plan(fresh_envelope, host="codex-cli", execution_mode="isolated-headless", turn_instance_id="requirements-next-turn") fresh_prompt = _prompt(build_loopx_turn_host_request(fresh_plan)) @@ -472,7 +469,7 @@ def test_short_selected_todo_deduplicates_body_but_keeps_canonical_note( assert json.dumps(context).count(note) == 1 code, turn = run_json_cli_result("quota", "should-run", "--goal-id", "requirements-goal", - "--agent-id", "agent-a", "--turn-envelope", + "--agent-id", "agent-a", registry_path=registry, runtime_root=runtime) assert code == 0 and turn["ok"], turn turn_context = turn["interaction_contract"]["agent_channel"]["work_context"] diff --git a/tests/control_plane/test_selection_replan_reentry.py b/tests/control_plane/test_selection_replan_reentry.py index ec6142289b..25c1e5414b 100644 --- a/tests/control_plane/test_selection_replan_reentry.py +++ b/tests/control_plane/test_selection_replan_reentry.py @@ -453,7 +453,7 @@ def test_first_inline_result_binds_the_complete_replan_contract(tmp_path, discov rc, first = _run_cli(registry, runtime, *guard) assert rc == 0 and first["interaction_contract"]["cli_channel"]["selection_required"] rc, decision = _run_cli(registry, runtime, *guard, - "--todo-id", SELECTED_REPLAN_TODO_ID, "--turn-envelope") + "--todo-id", SELECTED_REPLAN_TODO_ID) assert rc == 0, decision assert_complete_turn_decision(decision) contract = decision["interaction_contract"] @@ -837,7 +837,7 @@ def test_captured_direct_replan_command_composes_semantic_writeback_once(tmp_pat codex_context_hook(str(native), dict(session_id="captured-composed-replan", cwd=str(project), hook_event_name="SessionStart", source="startup")) cli = str(Path(sys.executable).with_name("loopx")) - rc, shown = _run_cli(registry, runtime, "--cli-bin", cli, "quota", "should-run", "--codex-app", "--complete-turn", + rc, shown = _run_cli(registry, runtime, "--cli-bin", cli, "quota", "should-run", "--codex-app", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--turn-instance-id", turn, "--todo-id", retained, "--context-delivery", "on", "--codex-context-dir", str(native), "--decision-output-dir", str(capture), "--max-page-output-bytes", "64000", cwd=project) diff --git a/tests/control_plane/test_settlement_input_discovery_cli.py b/tests/control_plane/test_settlement_input_discovery_cli.py index 1dd816819e..e221f1e159 100644 --- a/tests/control_plane/test_settlement_input_discovery_cli.py +++ b/tests/control_plane/test_settlement_input_discovery_cli.py @@ -186,7 +186,7 @@ def run(*args): rc, detail = run("quota", "should-run", "--codex-app", *current, "--include-detail", "vision") assert rc == 0 and detail["replan_action_packet"]["writeback_contract"] == writeback, detail assert build_turn_envelope(guard)["replan_action_packet"]["writeback_contract"] == writeback - rc, envelope = run("quota", "should-run", "--codex-app", *current, "--turn-envelope") + rc, envelope = run("quota", "should-run", "--codex-app", *current) assert rc == 0 and envelope["replan_action_packet"]["writeback_contract"] == writeback, envelope vision = deepcopy(authoring["minimal_example"]) vision["path_delta"].update( diff --git a/tests/control_plane/test_turn_envelope_capability_facts.py b/tests/control_plane/test_turn_envelope_capability_facts.py index 9cdb950aea..2d059239b0 100644 --- a/tests/control_plane/test_turn_envelope_capability_facts.py +++ b/tests/control_plane/test_turn_envelope_capability_facts.py @@ -65,7 +65,7 @@ def test_real_captured_guard_preserves_required_and_missing_capabilities( code, envelope = _run_cli(registry, runtime, "quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", "turn-capability-facts", "--codex-app", *capabilities, - "--turn-envelope", "--decision-output-dir", str(capture), cwd=project) + "--decision-output-dir", str(capture), cwd=project) assert code == (0 if network_available else 1), envelope full = json.loads((capture / "decision.json").read_text()) assert envelope == full and full["schema_version"] == "loopx_turn_envelope_v1" @@ -139,7 +139,7 @@ def test_captured_vision_contract_preserves_closeout_and_original_observation( code, envelope = _run_cli(registry, runtime, "quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", "vision-contract-turn", "--codex-app", - "--available-capability", "filesystem_read", "--turn-envelope", + "--available-capability", "filesystem_read", "--decision-output-dir", str(capture), cwd=project) assert code == 0, envelope saved = capture / "decision.json" diff --git a/tests/control_plane/test_turn_envelope_settlement.py b/tests/control_plane/test_turn_envelope_settlement.py index 8a63161612..5b8b6c97ac 100644 --- a/tests/control_plane/test_turn_envelope_settlement.py +++ b/tests/control_plane/test_turn_envelope_settlement.py @@ -103,12 +103,9 @@ def test_generated_c1_commands_settle_original_turn_once(tmp_path, profile_args) args = ("quota", "should-run", *profile_args, *binding) rc, default = _run_cli(registry, runtime, *args) assert rc == 0 and default["schema_version"] == "loopx_turn_envelope_v1", default - rc, alias = _run_cli(registry, runtime, *args, "--turn-envelope") - assert rc == 0 and alias["schema_version"] == "loopx_turn_envelope_v1", alias - plan = alias["interaction_contract"]["cli_channel"]["settlement_plan"] - assert plan == default["interaction_contract"]["cli_channel"]["settlement_plan"] + plan = default["interaction_contract"]["cli_channel"]["settlement_plan"] identity = default["heartbeat_receipt"]["settlement_identity"] - assert plan["identity"] == alias["heartbeat_receipt"]["settlement_identity"] == identity + assert plan["identity"] == identity assert plan["schema_version"] == "quota_settlement_plan_v2" assert [step["kind"] for step in plan["ordered_steps"]] == [ "validation", "durable_writeback", "quota_spend", "terminal_closeout", diff --git a/tests/control_plane/test_turn_host_context_delivery.py b/tests/control_plane/test_turn_host_context_delivery.py index 9670975ea1..a95a15aa30 100644 --- a/tests/control_plane/test_turn_host_context_delivery.py +++ b/tests/control_plane/test_turn_host_context_delivery.py @@ -72,7 +72,7 @@ def test_captured_context_reaches_actual_host_without_readmission(tmp_path, monk "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", TODO_ID, "--turn-instance-id", "host-context-turn", "--codex-app", "--available-capability", "filesystem_read", "--available-capability", "subagent_spawn", - "--turn-envelope", "--decision-output-dir", str(capture), *delivery] + "--decision-output-dir", str(capture), *delivery] produced = subprocess.run(guard, cwd=project, text=True, capture_output=True, timeout=30) assert produced.returncode == 0, produced.stdout + produced.stderr original = (capture / "decision.json").read_bytes() @@ -208,7 +208,7 @@ def test_bound_replan_reaches_actual_host_with_original_evidence(tmp_path, monke code, emitted = _run_cli(registry, runtime, "quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--todo-id", SELECTED_REPLAN_TODO_ID, "--turn-instance-id", turn, - "--codex-app", "--turn-envelope", "--decision-output-dir", str(capture), cwd=project) + "--codex-app", "--decision-output-dir", str(capture), cwd=project) assert code == 0, emitted original = (capture / "decision.json").read_bytes() source = json.loads(original) diff --git a/tests/control_plane/test_work_acceptance_context.py b/tests/control_plane/test_work_acceptance_context.py index 6eb658a732..cb29a5a945 100644 --- a/tests/control_plane/test_work_acceptance_context.py +++ b/tests/control_plane/test_work_acceptance_context.py @@ -248,7 +248,7 @@ def configure(*arguments): capture = tmp_path / "decision" guard = ("quota", "should-run", "--goal-id", goal, "--agent-id", agent, "--codex-app") first = cli(*guard, "--todo-id", selected, "--turn-instance-id", "original-delivery", - "--turn-envelope", "--decision-output-dir", str(capture)) + "--decision-output-dir", str(capture)) first = read_cli_policy_payload(json.dumps(first), returncode=0) saved = (capture / "decision.json").read_bytes() full = json.loads(saved) diff --git a/tests/control_plane/test_work_context_host_delivery.py b/tests/control_plane/test_work_context_host_delivery.py index 76d80952fe..abe81724f9 100644 --- a/tests/control_plane/test_work_context_host_delivery.py +++ b/tests/control_plane/test_work_context_host_delivery.py @@ -38,7 +38,7 @@ def test_policy_observer_reads_original_signed_capture_after_todo_references(tmp capture = tmp_path / 'signed-capture' code, view = _run_cli(registry, runtime, 'quota', 'should-run', '--goal-id', GOAL_ID, '--agent-id', AGENT_ID, '--begin-turn', - '--codex-app', '--complete-turn', '--context-delivery', 'auto', '--delta-delivery', 'off', + '--codex-app', '--context-delivery', 'auto', '--delta-delivery', 'off', '--decision-output-dir', str(capture)) assert code == 0, view saved = capture / 'decision.json' @@ -105,7 +105,7 @@ def test_authored_requirements_survive_capture_projection_and_host(tmp_path, mon '--todo-id', TODO_ID, '--turn-instance-id', TURN_ID, '--codex-app', '--available-capability', 'shell', '--available-capability', 'filesystem_read'] capture = tmp_path / 'original-context' - code, emitted = _run_cli(registry, runtime, *args, '--turn-envelope', + code, emitted = _run_cli(registry, runtime, *args, '--decision-output-dir', str(capture)) assert code == 0, emitted saved = capture / 'decision.json' diff --git a/tests/control_plane/test_work_yardstick_cli.py b/tests/control_plane/test_work_yardstick_cli.py index 00eb5fe4f2..04b5259a78 100644 --- a/tests/control_plane/test_work_yardstick_cli.py +++ b/tests/control_plane/test_work_yardstick_cli.py @@ -195,7 +195,7 @@ def record_measurement(measurement, **location): prepared = run(project, runtime, path, "quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--turn-instance-id", turn, "--runtime-profile", "generic_cli", "--available-capability", "shell", "--available-capability", "filesystem_write", - "--decision-output-dir", str(opening), "--prepared-capture-reference", "--complete-turn", + "--decision-output-dir", str(opening), "--prepared-capture-reference", "--context-delivery", "on", "--codex-context-dir", str(native), "--defer-context-presentation") original = opening / "decision.json" original_bytes = original.read_bytes() diff --git a/tests/control_plane/test_worker_observation_recovery_cli.py b/tests/control_plane/test_worker_observation_recovery_cli.py index 774aeb25c9..abb431e801 100644 --- a/tests/control_plane/test_worker_observation_recovery_cli.py +++ b/tests/control_plane/test_worker_observation_recovery_cli.py @@ -68,7 +68,7 @@ def _poll(runtime, registry, agent, *, record=False, extra=(), profile="generic_ @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("wire", ["quota", "envelope", "native"]) +@pytest.mark.parametrize("wire", ["inline", "native"]) @pytest.mark.parametrize("observation", ["recorded", "unreadable", "off"]) def test_original_capture_retains_the_emitted_poll_observation( tmp_path, monkeypatch, provider, wire, observation, @@ -85,8 +85,6 @@ def test_original_capture_retains_the_emitted_poll_observation( capture = tmp_path / "original-capture" options = ["--turn-instance-id", "capture-poll", "--decision-output-dir", str(capture), "--context-delivery", "on" if wire == "native" else "off"] - if wire == "envelope": - options.append("--turn-envelope") if wire == "native": native = tmp_path / "native-context" native.mkdir(mode=0o700) @@ -117,7 +115,7 @@ def test_original_capture_retains_the_emitted_poll_observation( if wire == "native": # Read precisely the immutable recovery view published to this caller. reader = shlex.split(emitted["recovery"]["command"]) - elif wire == "envelope": + elif wire == "inline": from loopx.control_plane.quota.turn_envelope import build_turn_envelope # Complete v1 turn envelope carriers preserve the full decision while @@ -158,7 +156,7 @@ def test_original_capture_retains_the_emitted_poll_observation( reader = [sys.executable, "-m", "loopx.cli", "--format", "json", "quota", "context-read", "--capture-file", str(capture / "decision.json"), "--capture-sha256", hashlib.sha256(original).hexdigest()] - if wire == "envelope": + if wire == "inline": def read_paged_json(page: dict) -> dict: digest = page["sha256"] raw = bytearray() diff --git a/tests/test_delegation_turn_context.py b/tests/test_delegation_turn_context.py index ab46e15a5d..eb3fce1bb0 100644 --- a/tests/test_delegation_turn_context.py +++ b/tests/test_delegation_turn_context.py @@ -442,7 +442,7 @@ def run(*arguments): for turn_id in ("agenda-turn-one", "agenda-turn-two"): # This branch consumes machine JSON; the model-facing branch below must # exercise the real capture transport even under an inline parent. - presentation = ["--turn-envelope", "--context-delivery", "off"] if delivery == "host_envelope" else [ + presentation = ["--context-delivery", "off"] if delivery == "host_envelope" else [ "--codex-app", "--context-delivery", "on", "--decision-output-root", str(tmp_path / "captures"), "--codex-context-root", str(tmp_path / "context")] code, packet = run(*prefix, "quota", "should-run", "--goal-id", "research", From c78813c0a76d5ae7f505ee9ef89f4f1875dbf07c Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:31:44 +0800 Subject: [PATCH 4/5] Exercise staged replan and acceptance through the current source Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/development/testing-and-quality.md | 13 ++++++ .../control_plane/test_replan_staged_read.py | 26 ++++++------ .../test_work_acceptance_context.py | 40 +++++++++---------- 3 files changed, 46 insertions(+), 33 deletions(-) diff --git a/docs/development/testing-and-quality.md b/docs/development/testing-and-quality.md index c9800b3d48..5b1a2167dd 100644 --- a/docs/development/testing-and-quality.md +++ b/docs/development/testing-and-quality.md @@ -1401,6 +1401,19 @@ workflow costs less. ### Budget Failure Decisions +The complete Vision fixture with 36 Todos, 12 runs and inline delivery measured +60,826 JSON characters on the explicit C1 path before the default switched. +That body exceeded both earlier fixture allowances of 55,000 and 59,000. +The current 61,100-character allowance covers this fixture while preserving +the replan authoring, settlement and continuation content. Keep the earlier +overruns in measurement history. Transport limits and total model cost are +measured independently. + +36 个 Todo、12 次 run 的 Vision 内联夹具,在默认切换前通过显式 C1 得到 +60,826 个 JSON 字符,超过当时的 55,000 和 59,000 上限。现有 61,100 字符预算 +覆盖该夹具,保留重规划编写、结算和续接内容。测量记录保留原超限结果,传输 +限制与模型完整成本另行核对。 + The thin heartbeat's 4,500-character presentation allowance did not cover the complete combination of a 320-character scope, all five runtime capability flags, Codex App transport and an explicit CLI route. The existing public CLI diff --git a/tests/control_plane/test_replan_staged_read.py b/tests/control_plane/test_replan_staged_read.py index 66b5bb3108..bc7b56d481 100644 --- a/tests/control_plane/test_replan_staged_read.py +++ b/tests/control_plane/test_replan_staged_read.py @@ -434,10 +434,11 @@ def test_review_retains_scoped_dependencies_and_unknown_outcomes(): @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, monkeypatch, provider): + from tests.control_plane.cli_output_fixture import read_pinned_cli_body + isolate_sqlite_runtime(tmp_path, monkeypatch) fixture = make_progress_cli_fixture(tmp_path, provider, "advanced") enable_explore(fixture) - capture = tmp_path / "capture" try: initial = call_progress_cli(fixture, "quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", TURN) @@ -445,18 +446,21 @@ def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, m # Exercise the emitted command verbatim even with a hostile ambient # PATH entry. The captured reader belongs to the originating checkout. pinned_cli = str(Path(sys.executable).with_name("loopx")) - guard = call_progress_cli(fixture, "--cli-bin", pinned_cli, "quota", "should-run", "--codex-app", + presented = call_progress_cli(fixture, "--cli-bin", pinned_cli, "quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", TURN, - "--todo-id", TODO, "--decision-output-dir", str(capture)) - guard = read_cli_policy_payload(json.dumps(guard), returncode=0) + "--todo-id", TODO, + "--context-delivery", "on", "--delta-delivery", "off") + body, _, _ = read_pinned_cli_body(presented["recovery"]["command"]) + guard = json.loads(body) packet = guard["replan_action_packet"] - assert guard["interaction_contract"]["cli_channel"]["settlement_read_ref"] == "$.replan_action_packet.writeback" - saved = (capture / "decision.json").read_bytes() + reader = shlex.split(packet["review"]) + capture = Path(reader[reader.index("--decision-file") + 1]) + saved = capture.read_bytes() source = json.loads(saved) # Unknown old/custom prose, different templates, ambiguous/missing # writers and missing capture must remain fully inline. for mutation in ("custom", "template", "duplicate", "missing", "capture"): - changed = copy.deepcopy(source) + changed = {**copy.deepcopy(source), "replan_read_path": str(capture)} graph = explore_source(changed)["content"]["graph"] step = next(row for row in changed["interaction_contract"]["cli_channel"]["settlement_plan"]["ordered_steps"] if row["kind"] == "durable_writeback") @@ -505,12 +509,10 @@ def read(stage, expected_code=0): expected_goal = source["autonomous_replan_obligation"]["replan_context"]["core_goal"] assert review["core_goal"] == expected_goal assert review["action_portfolio"] == source.get("action_portfolio") - assert "core_goal" not in guard and "planning_horizon" not in guard - assert guard.get("action_portfolio") == source.get("action_portfolio") assert review["context_id"] == writer["context_id"] assert review["obligation_id"] == source["replan_action_packet"]["obligation_id"] assert writer["writeback_contract"] == without_example(source["replan_action_packet"]["writeback_contract"]) - assert (capture / "decision.json").read_bytes() == saved + assert capture.read_bytes() == saved assert {key: fixture[key].read_bytes() for key in original_files} == original_files assert not reader_fixture["registry"].exists() # Changed bytes cannot masquerade as the admitted observation. @@ -526,10 +528,10 @@ def read(stage, expected_code=0): for key in carrier: target = target[key] target[field] = value - (capture / "decision.json").write_text(json.dumps(source)) + capture.write_text(json.dumps(source)) rejected = read("review", expected_code=1) assert rejected["reason"] == "capture digest mismatch; restore the original capture, do not rerun admission" - (capture / "decision.json").write_bytes(saved) + capture.write_bytes(saved) # A valid next operation still reaches the existing writer and semantic gate. result = call_progress_cli(fixture, *fixture["refresh"]) assert result["autonomous_replan_ack"]["semantic_delta"]["accepted"] is True diff --git a/tests/control_plane/test_work_acceptance_context.py b/tests/control_plane/test_work_acceptance_context.py index cb29a5a945..ec4641d913 100644 --- a/tests/control_plane/test_work_acceptance_context.py +++ b/tests/control_plane/test_work_acceptance_context.py @@ -110,7 +110,8 @@ def cli(*arguments): assert missing == {**full, "tasks": []}, "missing work must not fall back to another binding" packet = cli("quota", "should-run", "--goal-id", goal, "--agent-id", "agent-a", - ) + "--todo-id", selected, "--runtime-profile", "generic_cli", "--turn-instance-id", "export-context-turn", + "--context-delivery", "off", "--delta-delivery", "off") channel = packet["interaction_contract"]["agent_channel"] assert channel["delivery_allowed"] is True and channel["work_context"]["complete"] is True # The public canonical reader retains its full format metadata. Host context @@ -124,21 +125,16 @@ def cli(*arguments): } observed = next(row["content"] for row in channel["work_context"]["sources"] if row.get("source") == "goal_acceptance") - assert observed == exact - assert any(row.get("source") == "goal_state" for row in channel["required_reads"]) - # The normal guard's complete captured basis is the envelope input; no - # second guard may substitute a different observation for the host. - from loopx.control_plane.quota.turn_envelope import build_turn_envelope - - envelope = build_turn_envelope(packet) + scoped = inspect_goal_acceptance( + registry_path=registry, runtime_root=str(runtime), goal_id=goal, + todo_id=selected, include_work_details=False, context_agent_id="agent-a", + ) + assert observed == {**exact, "outcome_context": scoped["outcome_context"]} + goal_source = next(row for row in channel["work_context"]["sources"] if row["source"] == "goal_state") + assert "Deliver a compatible export." in goal_source["content"]["text"] + assert all(row.get("source") != "goal_state" for row in channel["required_reads"]) assert channel["work_context"]["selected_todo_text_verified"] is True - assert envelope["work_context"] == { - key: value - for key, value in channel["work_context"].items() - if key != "selected_todo_text_verified" - } - assert envelope["action"]["selected_todo"]["text_source_verified"] is True - request = build_loopx_turn_host_request(build_loopx_turn_plan(envelope, + request = build_loopx_turn_host_request(build_loopx_turn_plan(packet, host="codex-cli", execution_mode="isolated-headless", turn_instance_id="export-context-turn")) before = {p: p.read_bytes() for p in runtime.rglob("*") if p.is_file()} command = _recording_host(tmp_path) @@ -146,15 +142,16 @@ def cli(*arguments): input=json.dumps(request), capture_output=True, text=True, timeout=30) assert result.returncode == 0, result.stdout + result.stderr prompt = (tmp_path / "received.txt").read_text() - authority = json.loads(prompt.split("Turn authority JSON:\n", 1)[1].split("\n\nWhen finished", 1)[0]) - assert authority["work_context"] == envelope["work_context"] - assert authority["selected_todo"]["text_source_verified"] is True + authority = json.loads(prompt.split("Turn request:\n", 1)[1].split("\n\nWhen finished", 1)[0]) + work_context = authority["task_context"]["interaction_contract"]["agent_channel"]["work_context"] + assert work_context == channel["work_context"] changed = deepcopy(request) - acceptance = next(row["content"] for row in changed["turn_envelope"]["work_context"]["sources"] + changed_context = changed["work_contract"]["interaction_contract"]["agent_channel"]["work_context"] + acceptance = next(row["content"] for row in changed_context["sources"] if row.get("source") == "goal_acceptance") acceptance["goal_acceptance_contract"]["outcome_requirements"]["outcomes"][-1]["requirements"][-1]["description"] = "Omit recovery." rejected = subprocess.run(command, input=json.dumps(changed), capture_output=True, text=True, timeout=30) - assert rejected.returncode != 0 and "action signature" in rejected.stderr + assert rejected.returncode != 0 and "complete Turn contract rejected" in rejected.stderr assert (tmp_path / "received.txt").read_text() == prompt assert {p: p.read_bytes() for p in runtime.rglob("*") if p.is_file()} == before @@ -190,7 +187,8 @@ def observe_planner_source(method, params, **options): assert set(source) == {"selected_todo", "task_orchestration_contract", "effective_action", "interaction_contract"} assert set(source["interaction_contract"]["cli_channel"]) <= {"selection_required"} assert set(source["task_orchestration_contract"]) <= {"schema_version", "mode", "primary_todo_id"} - recovered = cli("quota", "should-run", "--goal-id", goal, "--agent-id", "agent-a", ) + recovered = cli("quota", "should-run", "--goal-id", goal, "--agent-id", "agent-a", + "--context-delivery", "off", "--delta-delivery", "off") assert recovered["interaction_contract"]["agent_channel"]["work_context"]["complete"] is True From 8dbcbbf7a05f5cea8f9ac837958cd15420fa6a11 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:34:24 +0800 Subject: [PATCH 5/5] Verify native Goal capture refusal through the handoff option Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- tests/control_plane/test_heartbeat_envelope_transport.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/control_plane/test_heartbeat_envelope_transport.py b/tests/control_plane/test_heartbeat_envelope_transport.py index 56a7c40b76..514972bf74 100644 --- a/tests/control_plane/test_heartbeat_envelope_transport.py +++ b/tests/control_plane/test_heartbeat_envelope_transport.py @@ -351,9 +351,9 @@ def test_native_worker_and_stable_bootstrap_cannot_use_capture(tmp_path): env = dict(os.environ, LOOPX_CLI='unused', LOOPX_REGISTRY=str(registry), LOOPX_RUNTIME_ROOT=str(runtime), LOOPX_PROJECT=str(project), LOOPX_GOAL_ID=GOAL_ID, LOOPX_AGENT_ID=AGENT_ID, - LOOPX_WAKE_LOG_DIR=str(tmp_path / 'absent'), LOOPX_TURN_ENVELOPE='1') + LOOPX_WAKE_LOG_DIR=str(tmp_path / 'absent')) with pytest.raises(ValueError, match='host-owned'): - heartbeat_body(env, TURN_ID, native_goal=True) + heartbeat_body(env, TURN_ID, native_goal=True, decision_handoff_socket=str(tmp_path / 'socket')) assert not (tmp_path / 'absent').exists() rc, rejected = _run_cli( registry, runtime, 'heartbeat-prompt', '--bootstrap', '--thin',