diff --git a/.github/workflows/desktop-updater.yml b/.github/workflows/desktop-updater.yml index e2092ffca7..1b67e421f1 100644 --- a/.github/workflows/desktop-updater.yml +++ b/.github/workflows/desktop-updater.yml @@ -6,6 +6,8 @@ on: - 'apps/desktop/**' - 'scripts/desktop_*' - 'tests/desktop/**' + - 'loopx/cli_commands/public_default_contract.json' + - 'loopx/cli_commands/update_artifact.py' - '.github/workflows/desktop-updater.yml' release: types: [published] @@ -294,13 +296,23 @@ jobs: # nullglob, Bash passes the unmatched pattern to `gh`, which exits # before the feed and channel pointer are published. shopt -s nullglob + channel_action="$(python - <<'PY' + from loopx.cli_commands.update_artifact import PUBLIC_DEFAULT_CONTRACT, public_channel_allows_default + + print("promote" if public_channel_allows_default(PUBLIC_DEFAULT_CONTRACT) else "hold") + PY + )" if [ "$EVENT_NAME" != release ]; then - gh release create "$RELEASE_TAG" --prerelease --target "$SOURCE_REF" --title "Desktop main $SOURCE_REF" --notes "Signed App and matching runtime preview." + gh release create "$RELEASE_TAG" --prerelease --latest=false --target "$SOURCE_REF" --title "Desktop main $SOURCE_REF" --notes "Signed App and matching runtime candidate for exact-revision qualification." fi for artifact in dist/updater/*.gz dist/updater/*.sig dist/updater/*.exe; do gh release upload "$RELEASE_TAG" "$artifact" done gh release upload "$RELEASE_TAG" dist/updater/desktop-updater.json --clobber + if [ "$channel_action" != promote ]; then + echo "::notice title=Desktop channel retained::The candidate's default contract is pending public channel qualification." + exit 0 + fi # Channel pointers are independent of repository Latest, which also # serves separately versioned plugin releases. Advance only after the # immutable signed assets and feed are completely uploaded. diff --git a/.github/workflows/runtime-snapshots.yml b/.github/workflows/runtime-snapshots.yml index e037b7f104..c5e5d196d4 100644 --- a/.github/workflows/runtime-snapshots.yml +++ b/.github/workflows/runtime-snapshots.yml @@ -11,6 +11,7 @@ on: - "tests/test_runtime_snapshot_publication.py" - "tests/test_update_artifact.py" - "scripts/install*.sh" + - "loopx/cli_commands/public_default_contract.json" - "loopx/cli_commands/update*.py" - "loopx/cli_commands/support_control_update*.py" - "loopx/self_update*.py" @@ -92,48 +93,36 @@ jobs: set -euo pipefail # Validate the downloaded qualification before any remote mutation. # Successful installation alone does not qualify outcome/cost claims. - revision="$(python - <<'PY' - import hashlib + publication="$(python - <<'PY' import json from pathlib import Path - import re import sys sys.path.insert(0, str(Path.cwd())) - from loopx.cli_commands.update_artifact import validate_default_contract + from loopx.cli_commands.update_artifact import ( + public_channel_allows_default, validate_published_manifest, verify_runtime_installation_qualification, + ) root = Path("runtime") manifest_bytes = (root / "loopx-runtime.json").read_bytes() - manifest = json.loads(manifest_bytes) + manifest = validate_published_manifest(json.loads(manifest_bytes)) revision = manifest["source_revision"] - if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{40}", revision): - raise SystemExit("Invalid runtime source revision") qualification = json.loads((root / f"qualification-{revision}.json").read_bytes()) - checks = ("ok", "clean_install", "upgrade", "doctor", "skills", "frontend_bundle_contract", - "frontend_http", "no_frontend_build_tools", "license_notices", "activation_failure_restored") - if any(qualification.get(check) is not True for check in checks): - raise SystemExit("Runtime installation qualification is missing or failed") - default_contract = validate_default_contract(manifest.get("default_contract")) - if qualification.get("default_contract") != default_contract: - raise SystemExit("Runtime default-contract qualification is missing or mismatched") - if manifest["channel"] != "main" or any(qualification.get(key) != manifest[key] - for key in ("source_revision", "channel", "sha256")): - raise SystemExit("Runtime qualification does not match the candidate") archive = root / f"loopx-runtime-{revision}.tar.gz" - with archive.open("rb") as stream: - digest = hashlib.file_digest(stream, "sha256").hexdigest() - if type(manifest["size"]) is not int or type(qualification.get("bytes")) is not int or ( - archive.stat().st_size != manifest["size"] or qualification["bytes"] != manifest["size"] - or digest != manifest["sha256"]): - raise SystemExit("Qualified runtime bytes differ from the candidate") + verify_runtime_installation_qualification(manifest, qualification, archive, channel="main") if (root / f"loopx-runtime-{revision}.json").read_bytes() != manifest_bytes: raise SystemExit("Immutable runtime metadata differs from the channel candidate") - print(revision) + channel_action = "promote" if public_channel_allows_default(manifest["default_contract"]) else "hold" + print(revision, channel_action) PY )" + read -r revision channel_action <<< "$publication" + # Only main revisions may be published, even when the channel is held. + relation="$(gh api "repos/${GITHUB_REPOSITORY}/compare/${revision}...main" --jq .status)" + if [[ "$relation" != ahead && "$relation" != identical ]]; then exit 1; fi # Keep each immutable snapshot below GitHub's per-release asset cap. - # The existing channel release retains its historical assets and URL. + # These candidates can be tested by exact revision before adoption. tag="runtime-main-${revision}" if ! gh release view "$tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then - gh release create "$tag" --repo "$GITHUB_REPOSITORY" --target "$revision" --prerelease --latest=false --title "Qualified main runtime ${revision}" --notes "Immutable runtime snapshot. Stable users continue with PyPI or the stable runtime." + gh release create "$tag" --repo "$GITHUB_REPOSITORY" --target "$revision" --prerelease --latest=false --title "Main runtime candidate ${revision}" --notes "Immutable runtime snapshot for exact-revision qualification." fi actual="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${tag}" --jq .sha)" if [[ "$actual" != "$revision" ]]; then exit 1; fi @@ -148,10 +137,10 @@ jobs: gh release upload "$tag" "$file" --repo "$GITHUB_REPOSITORY" fi done - # Publication is serialized. A qualified ancestor is usable while a - # newer main is still building; never publish a non-main revision. - relation="$(gh api "repos/${GITHUB_REPOSITORY}/compare/${revision}...main" --jq .status)" - if [[ "$relation" != ahead && "$relation" != identical ]]; then exit 1; fi + if [[ "$channel_action" != promote ]]; then + echo "::notice title=Runtime channel retained::The candidate's default contract is pending public channel qualification." + exit 0 + fi if ! gh release view runtime-main --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then gh release create runtime-main --repo "$GITHUB_REPOSITORY" --target "$revision" --prerelease --latest=false --title "Latest qualified main runtime" --notes "Mutable channel metadata points to immutable revision releases. Stable users continue with PyPI or the stable runtime." fi 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 5908e53541..af66a0f9b2 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 ARTIFACT_CONTRACT_POLICY: &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,8 +31,9 @@ pub(crate) fn qualify_candidate( } let invalid = "runtime_bundle_invalid"; let unavailable = "update_platform_unavailable"; - let policy: Value = serde_json::from_str(ARTIFACT_CONTRACT_POLICY).map_err(|_| invalid)?; - let supported = policy["readable_contracts"].as_array().ok_or(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; @@ -51,7 +52,7 @@ pub(crate) fn qualify_candidate( .get("default_contract") .filter(|contract| contract.is_object()) .ok_or(unavailable)?; - if !supported.contains(observed) { + if observed != current && observed != historical { return Err(unavailable.into()); } qualified = true; @@ -221,15 +222,9 @@ mod tests { assert!(qualify_candidate("stable", "2.3.0", &bytes).is_ok()); } - for (surface, schema_version) in [ - ("quota_packet", None), - ("complete_turn", Some("loopx_turn_envelope_v1")), - ] { - identity["default_contract"] = serde_json::json!({ - "surface": surface, - "schema_version": schema_version, - "interaction_schema_version": "loopx_interaction_contract_v0" - }); + 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(); 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 2d2b0e3c68..86c265be1a 100644 --- a/benchmark/runtime/RUNTIME.md +++ b/benchmark/runtime/RUNTIME.md @@ -105,30 +105,22 @@ and scoring. EdgeBench's SForge auto-resume remains a provider-specific part of its official profile. Use a fresh trial with the option omitted for a single-pass Codex baseline. -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 heartbeat formats + +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 @@ -248,12 +240,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 306c9165a9..f11cb46d57 100644 --- a/benchmark/runtime/codex.py +++ b/benchmark/runtime/codex.py @@ -45,10 +45,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 type(self.official_stop_hook) is not bool or (self.official_stop_hook and self.mode != "plain"): raise ValueError("official_stop_hook requires plain execution and a boolean opt-in") if self.mode not in MODES or self.context not in CONTEXTS: @@ -92,22 +90,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 8e4aed0100..85803bd63a 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 @@ -195,9 +195,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 {})} @@ -414,7 +413,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(), **({"official_stop_hook": True} if self.execution.official_stop_hook else {}), **({"provider_request_admission": "on"} if self.provider_request_admission else {}), @@ -695,8 +694,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, "LOOPX_OFFICIAL_STOP_HOOK": "1" if self.execution.official_stop_hook else "0", # A trial's explicit None must not inherit a container opt-in. @@ -833,7 +830,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(), **({"official_stop_hook": True} if self.execution.official_stop_hook else {}), **({"provider_request_admission": "on"} if self.provider_request_admission else {}), 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 34d417d87c..d658188567 100644 --- a/benchmark/runtime/worker.py +++ b/benchmark/runtime/worker.py @@ -17,10 +17,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 @@ -105,19 +104,15 @@ def heartbeat_body(env: dict[str, str], turn_id: str, *, native_goal: bool, command += ["--turn-instance-id", turn_id] if resume_codex_session_id: command += ["--resume-codex-session-id", resume_codex_session_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: @@ -554,64 +549,13 @@ 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") stop_hook = env.get("LOOPX_OFFICIAL_STOP_HOOK", "0") if stop_hook not in {"0", "1"}: raise ValueError("LOOPX_OFFICIAL_STOP_HOOK must be 0 or 1") - 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"), @@ -620,11 +564,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, official_stop_hook=stop_hook == "1", ) request_admission = False @@ -675,7 +617,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 {}), **({"official_stop_hook": True} if execution.official_stop_hook else {}), **({"native_child_limit": execution.native_child_limit} @@ -722,8 +663,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, @@ -817,8 +756,6 @@ def run_once(env: dict[str, str]) -> dict: if stage != "plan" and execution.mode in {"heartbeat", "loopx-goal"}: body = fresh_context_prefix + heartbeat_body(env, turn_id, native_goal=execution.native_goal, decision_handoff_socket=checkpoint_wake.socket_path, resume_codex_session_id=resumed_session_id) - if execution.turn_envelope: - receipt.update(turn_envelope_receipt(explicit=True)) if stage == "execute" and execution.mode == "heartbeat" and env.get("LOOPX_CHECKPOINT_REQUEST"): from benchmark.runtime.checkpoint import capture_before_replan 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..621635e442 100644 --- a/benchmark/tests/test_native_checkpoint.py +++ b/benchmark/tests/test_native_checkpoint.py @@ -927,6 +927,18 @@ def test_interrupted_cursor_requires_exact_unreleased_final_guard( rendered[-1]["items"][-1]["command"] = shlex.join(["/bin/bash", "-lc", "LOOPX_TURN=turn-1\n" + shlex.join(argv).replace("--turn-instance-id turn-1", '--turn-instance-id "${LOOPX_TURN:?}"')]) _verify_interrupted_guard(rendered, guard) + rendered_prequota = copy.deepcopy(turns) + prequota_argv = [guard["cli"], "--registry", guard["registry"], "--runtime-root", guard["runtime_root"], + "heartbeat-prequota", "-g", "research", "-a", "worker"] + rendered_prequota[-1]["items"][-1]["command"] = shlex.join(["/bin/bash", "-lc", + "LOOPX_TURN=turn-1\n" + shlex.join(prequota_argv) + "\n" + + shlex.join(argv).replace("--turn-instance-id turn-1", '--turn-instance-id "${LOOPX_TURN:?}"')]) + _verify_interrupted_guard(rendered_prequota, guard) + mismatched_prequota = copy.deepcopy(turns) + mismatched_prequota[-1]["items"][-1]["command"] = shlex.join(["/bin/bash", "-lc", + shlex.join([*prequota_argv[:-3], "other", "-a", "worker"]) + "\n" + shlex.join(argv)]) + with pytest.raises(ValueError, match="prequota route|invalid"): + _verify_interrupted_guard(mismatched_prequota, guard) for setting in ("off", "on"): explicit = copy.deepcopy(turns) explicit[-1]["items"][-1]["command"] = shlex.join([ @@ -1028,7 +1040,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 +1073,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..4bf424e516 100644 --- a/benchmark/tests/test_sforge_runtime.py +++ b/benchmark/tests/test_sforge_runtime.py @@ -331,13 +331,8 @@ def execute(handle, command, **kwargs): assert restored == ["workspace"] -@pytest.mark.parametrize("explicit,trigger,expected", [ - (False, None, None), - (False, "fresh_replan", None), - (True, None, "explicit"), - (True, "fresh_replan", "explicit"), -]) -def test_sforge_profile_does_not_enable_envelope_for_checkpoint(tmp_path, monkeypatch, explicit, trigger, expected): +@pytest.mark.parametrize("trigger", [None, "fresh_replan"]) +def test_sforge_checkpoint_keeps_current_worker_profile(tmp_path, monkeypatch, trigger): from types import SimpleNamespace pytest.importorskip("sforge") pytest.importorskip("harbor") @@ -354,12 +349,12 @@ async def installed(self, environment): backend = SimpleNamespace(copy_to_container=lambda *args: None, exec_run=lambda *args, **kwargs: SimpleNamespace(exit_code=0)) worker = SForgeWorker(SForgeConfig(agent_model="fixture", agent_effort="xhigh"), - profile="heartbeat-resume", cwd="/task", turn_envelope=explicit, + profile="heartbeat-resume", cwd="/task", checkpoint_request=json.dumps(declaration).encode()) worker.install_stop_hook(backend, None, tmp_path, None) profile = json.loads((tmp_path / "worker-profile.json").read_text()) - assert profile.get("turn_envelope_source") == expected - assert profile.get("turn_envelope") is (True if expected else None) + assert profile["checkpoint_capture_enabled"] is True + assert {"turn_envelope_source", "turn_envelope", "complete_turn"}.isdisjoint(profile) @pytest.mark.parametrize("enabled", [False, True]) @@ -691,9 +686,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 +697,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 +761,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 +809,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 +1033,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 +1040,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 +1085,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 +1097,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 fe2a5e5624..9ea2d107f9 100644 --- a/benchmark/tests/test_shared_codex_runtime.py +++ b/benchmark/tests/test_shared_codex_runtime.py @@ -1220,16 +1220,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 @@ -1249,7 +1243,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, @@ -1260,7 +1254,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): @@ -1294,8 +1287,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) @@ -1304,90 +1296,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 a8c1073889..3ad3175c9b 100644 --- a/benchmark/tests/test_task_entry.py +++ b/benchmark/tests/test_task_entry.py @@ -1188,25 +1188,15 @@ def test_sforge_planning_entry_stops_retrying_after_the_attempt_limit(planning_e assert len(calls) == entry.PLANNING_WAKE_ATTEMPTS -@pytest.mark.parametrize( - ("context", "producer", "complete", "checkpoint_preflight"), - [ - ("fresh", None, False, False), - ("fresh", "local_probe", True, False), - ("fresh", "local_probe", False, True), - ("resume", None, True, True), - ("resume", "local_probe", False, False), - ("resume", None, False, True), - ], -) +@pytest.mark.parametrize("context", ["fresh", "resume"]) +@pytest.mark.parametrize("producer", [None, "local_probe"]) +@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: @@ -1248,9 +1238,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.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0.md index 580b70dcff..271cc7395f 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0.md @@ -1014,11 +1014,11 @@ comparison and cannot explain away a C1 regression. ### Default adoption and retirement qualification The [context-delivery guide](../../guides/context-delivery.md#qualify-default-adoption-and-retirement) -turns this comparison into an operator plan. Documentation may ship first; -future broader default adoption needs both a declared DeepSeek model and a declared -strong model to support the claimed effectiveness and complete-cost scope. -The reference's existing Codex-scoped default remains current behavior, not proof -that these model comparisons have passed. +turns this comparison into an operator plan. The C1 source defaults to one +writer and retires the older format selectors. Public artifacts follow the +existing release qualification. Qualifying +adoption for a supported profile requires both a declared DeepSeek model and a +declared strong model to support the claimed effectiveness and complete-cost scope. Record exact model/provider/version/effort and fixed task, source, host, tools, feedback, evaluator, budget and stops. Include actual final input/output, cached/uncached tokens, requests, detail/recovery reads, wall/IO/setup costs and @@ -1028,15 +1028,13 @@ variation, failures and negative cases. Historical-best optimization keeps that native ranking, with final-retention facts separate. A Codex-scoped adapter cannot qualify a DeepSeek host. -Keep this sequence in C1/C2/C9: explanation → both-model comparison → supported -profile's reversible adoption/release → scoped default → named old-path -retirement. Mixed or regressed results retain opt-in or explicit limitations. -Retirement requires actual caller replacement, historical decoding/readback, -supported-version and rollback coverage; full snapshots, digest checks, -authority/identity/stops and recovery remain. Do not preserve two permanent -semantic owners or delete a still-supported reader based on new-path existence. -This is a qualification plan, not new experiment authority, a claim of shipped -benefit, or a gate on other independent authorized work. +For supported-profile qualification in C1/C2/C9, record the explanation, +both-model comparison, and the profile's reversible installation and adoption. +Record mixed or regressed results as explicit limitations. Retiring a writer +requires actual caller replacement, historical decoding and readback, and +supported-version and rollback coverage. Preserve full snapshots, digest +checks, authority, identity, stops, recovery and existing historical readers. +Follow the existing experiment authorization for the comparisons. The [packaged source comparison](ledger/controller-executor-unified-contract-v0/2026-10-29-packaged-source-comparison.md) pins mainline quota and the C1 candidate through real File/SQLite CLI delivery, @@ -1403,11 +1401,16 @@ Splitting delivery does not close C1 or waive §9's original quota-baseline test Public-distribution isolation now reuses the runtime artifact metadata owner: runtime qualification observes the installed ordinary writer, desktop packaging observes its archived writer, and publication requires their declared supported -contract to match. The existing quota-packet default remains supported; the -unqualified complete-contract default cannot pass on installation checks alone. -This does not qualify §9 outcomes/costs, replace an installed writer, add another -current producer or retire historical readers. Extending the supported profile -still requires the original adoption evidence. See the [release boundary](../../product/release-readiness.md). +contract to match. The immutable `v2.4.0` tag retains its quota-packet writer. +C1 source cutover and public distribution qualify separately. The publisher and +Desktop updater must support the observed contract before a C1 artifact can be +published. Engineering-qualified main builds are available for verification +through immutable prereleases. The automatic Runtime and Desktop main channels +retain their published defaults until a reviewed change to the shared +publication policy records qualification for C1. For each supported profile, +record actual installation and adoption evidence, and evaluate outcomes and +full cost under §9. See the +[release boundary](../../product/release-readiness.md). Native launch rechecks use the original `SettlementIdentity` as their sole Todo/obligation binding. Both `codex-cli` and `codex-app-server` call the existing diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0.zh-CN.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0.zh-CN.md index df7f66b9e9..73ea923e08 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0.zh-CN.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0.zh-CN.md @@ -813,19 +813,18 @@ C1 的主要对照是**同一单会话产品路径中的原 quota packet 与融 ### 默认采用与退役资格 [上下文交付指南](../../guides/context-delivery.zh-CN.md#默认化与退役的验收) 把此比较落实为 -操作方案。文档可先交付;未来扩大默认采用范围需要明确版本的 DeepSeek 与强模型分别支持 -所声明的效果和完整成本范围。reference 已有的 Codex 范围默认仍是当前行为,不证明 -这些模型对照已通过。记录精确 model/provider/version/effort,固定 task、source、host、 +操作方案。C1 源码默认使用统一 writer,旧格式选择器已退役。公开制品仍走现有发布门。 +确认受支持 profile 的采用资格时,须用明确版本的 DeepSeek 与强模型验证所声明的 +效果和完整成本范围。记录精确 model/provider/version/effort,固定 task、source、host、 tools、反馈、evaluator、预算与停止条件。除原生任务成果、约束遗漏、错误动作和 一次性恢复外,计入实际最终 input/output、cached/uncached tokens、请求、详情/恢复 补读、墙钟/IO/搭建成本与人工注意力。未知成本不记零,保留重复波动、失败与负例。 历史最佳优化保持原生排名,终态保留事实另列。仅 Codex adapter 不资格化 DeepSeek 宿主。 -顺序留在 C1/C2/C9:解释 → 双模型比较 → 受支持 profile 的可回退采用/发布 → 范围化 -默认 → 点名旧路径退役。结果混合或退步时保留 opt-in 或明确限制。退役须核实际 caller -替换、历史解码/readback、支持版本与回退覆盖;完整快照、摘要校验、权限/身份/停止 -和恢复继续保留。不长期保留两个同义决策 owner,也不因新路径存在就删除仍受支持的 -reader。这是资格方案,不授予新实验权限,不宣称已交付收益,也不阻塞其他独立获授权工作。 +C1/C2/C9 的受支持 profile 资格记录解释、双模型对照及可回退的安装和采用结果。 +结果混合或退步时记明限制。退役 writer 须核验实际 caller 替换、历史解码与读回、 +支持版本和回退覆盖。保留完整快照、摘要校验、权限、身份、停止、恢复及现有历史 +reader。模型对照遵循现有实验授权。 [打包来源对照](ledger/controller-executor-unified-contract-v0/2026-10-29-packaged-source-comparison.zh-CN.md) 固定 mainline quota 与 C1 候选版本,经真实 File/SQLite CLI 验证交付、文件差分、 @@ -1103,10 +1102,13 @@ owner。列明后续切换消费者;不能添加无人使用的基础设施或 也不豁免第 9 节相对原 quota 基线的验证。 公开分发隔离现在复用 runtime 制品元数据 owner:runtime 资格检查观察已安装的普通 -writer,桌面打包观察归档 writer,发布要求声明的支持契约与观察一致。现有 quota -packet 默认保持支持;未资格化的完整契约默认不能只凭安装检查通过。此改动不证明 -第 9 节的成果/成本,不替换已安装 writer、不增加当前 producer,也不退役历史 reader。 -扩大支持 profile 仍须原采用证据,详见[发布边界](../../product/release-readiness.md)。 +writer,桌面打包观察归档 writer,发布要求声明的支持契约与观察一致。已发布的 +`v2.4.0` 标签保留 quota-packet writer。发布器和桌面更新器都支持观测到的契约后, +C1 制品才具备发布条件。通过工程资格检查的 main 制品可从不可变预发布版本取得,供按版本 +验证。Runtime 和 Desktop 的 main 自动更新渠道继续使用已发布的默认契约,直到共享发布 +策略经评审登记 C1 资格。逐一记录受支持 profile 的安装和实际采用证据,并按第 9 节验证 +成果和完整成本。 +详见[发布边界](../../product/release-readiness.md)。 原生启动重查只从原 `SettlementIdentity` 取得 Todo/obligation 绑定。 `codex-cli` 和 `codex-app-server` 都调用既有 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 cd77c8c55a..7bfd671cbb 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,13 +22,20 @@ 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. 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 the product default. Candidate context, planning relations, task continuation and @@ -38,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 2e73976144..43b0a3eadb 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,12 +15,16 @@ 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。 +受支持配置采用、匹配单会话成果及全成本仍各自需要验收证据。 + 当前 model-behavior portfolio 的 should-run 输入也复用该完整来源 owner,不再把 已退役 CLI compactor 当作产品默认路径。候选上下文、规划关系、任务续接与诊断事实 保留。Crowded 回归的 pretty JSON 从压缩后的 86,172 字节变为完整的 121,318 字节 @@ -28,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/development/testing-and-quality.md b/docs/development/testing-and-quality.md index 1c29a0a345..a4e92fa1b3 100644 --- a/docs/development/testing-and-quality.md +++ b/docs/development/testing-and-quality.md @@ -1414,6 +1414,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/docs/guides/context-delivery.md b/docs/guides/context-delivery.md index 75b014aff5..d79adb8237 100644 --- a/docs/guides/context-delivery.md +++ b/docs/guides/context-delivery.md @@ -12,8 +12,12 @@ benchmark heartbeat callers when no machine preference is saved. Saved or explic off disables it; ordinary CLI, other hosts and unsupported platforms inherit full delivery. -The complete C1 caller migration and long-horizon cost/outcome qualification remain -open. Broad default adoption and old-path retirement need the evidence below. +C1 source uses one wire contract for both inline and staged delivery. Public +artifacts follow the [release qualification](../product/release-readiness.md). +During upgrades, saved Codex App loaders can still invoke `heartbeat-prompt` +with the historical spellings until the App reads back the refreshed loader. +Both launch the same C1 guard. +The evidence below qualifies actual Host adoption, model outcomes, and complete cost. - To understand a work session, start with [the example](#one-task-four-situations). - To operate it, see [enable, verify and roll back](#enable-verify-and-roll-back). @@ -266,13 +270,10 @@ remains first: original quota packet versus the fused contract in the same product path. Optional controller/executor separation is a later comparison. Do not explain away a single-session regression with a two-session result. -Future broader default adoption requires **both a declared DeepSeek model and a strong -model** to pass comparable effectiveness and complete-cost evaluation. Run each -model's comparison within its own fixed conditions; do not pool them to hide a -regression. This guide supplies a plan, not new experimental authority or a -claim that either model family has passed. -These criteria govern extending the current scoped default; that shipped default -does not itself prove either model comparison has passed. +Supported-profile adoption qualification requires **both a declared DeepSeek +model and a strong model** to pass comparable effectiveness and complete-cost +evaluation. Compare each model under its own fixed conditions and report +regressions per model. Follow the existing experimental authority for these comparisons. ### A minimum discriminating study diff --git a/docs/guides/context-delivery.zh-CN.md b/docs/guides/context-delivery.zh-CN.md index eb6003e190..f3a4b95fc0 100644 --- a/docs/guides/context-delivery.zh-CN.md +++ b/docs/guides/context-delivery.zh-CN.md @@ -10,8 +10,10 @@ 默认开启原生路径。保存 off 或显式关闭可禁用;普通 CLI、其他宿主与不支持的平台 继承完整交付。 -完整 C1 消费链迁移和 -长程成果/成本资格仍未完成;广泛默认化和旧路径退役须取得下文证据。 +C1 源码的内联和分阶段交付使用同一个 wire 契约。公开制品遵循 +[发布资格](../product/release-readiness.md)。升级时,已保存的 Codex App loader +可在 App 读回新 loader 前继续用旧参数调用 `heartbeat-prompt`,两种写法均启动 +同一个 C1 准入流程。下文的证据用于确认 Host 实际采用、模型成果和完整成本。 - 理解一次工作,从[四种场景](#一项任务四种场景)开始。 - 实际使用,看[开启、验证和回退](#开启验证和回退)。 @@ -207,10 +209,8 @@ journal,限制权限并拒绝不安全路径。不要把原始 capture、本 同一产品路径中的原 quota packet 与融合契约。可选 controller/executor 分离是之后 的独立比较,不能用双会话结果解释或抵消单会话回归。 -未来扩大默认采用范围必须同时有**明确版本的 DeepSeek 模型与强模型**的可比效果、完整成本 -证据。每个模型内部固定条件分别比较,不能合并结果掩盖某一个模型退步。本指南提供 -方案。 -这些标准约束现有范围化默认的扩展;已交付的默认行为本身不证明双模型对照通过。 +受支持 profile 的采用资格须有**明确版本的 DeepSeek 模型与强模型**的可比效果和 +完整成本证据。各模型在固定条件下单独比较,分别报告退步。对照遵循现有实验授权。 ### 最小判别研究 diff --git a/docs/guides/custom-agent-runner-integration.md b/docs/guides/custom-agent-runner-integration.md index e2a4a657d7..8732a40153 100644 --- a/docs/guides/custom-agent-runner-integration.md +++ b/docs/guides/custom-agent-runner-integration.md @@ -93,7 +93,7 @@ skill does not activate it; the current goal policy controls activation. If the host has no skill system, inject the equivalent `SKILL.md` instructions and keep one short re-entry instruction that tells the Agent to: -1. read a fresh JSON quota packet for the current goal and Agent; +1. read a fresh JSON Complete Turn for the current goal and Agent; 2. follow `interaction_contract`, `goal_boundary`, and the selected todo; 3. perform one bounded action and validate the real postcondition; 4. write the result through LoopX; and @@ -104,7 +104,9 @@ todo list, cadence, or project policy. ## Run One Self-Driven Tick -Use JSON for the machine path: +The current JSON entry point defaults to Complete Turn v1. The published +`v2.4.0` tag delivers the historical quota packet. Read the current work +instructions from `interaction_contract` in either version. ```bash loopx --format json \ @@ -164,8 +166,8 @@ cat ./guard-001/decision.json The parent directory must exist; LoopX creates the private capture directory. Check command success, `ok`, and Goal/Agent/Turn identity before consuming the -saved decision. Read all required hooks, admission and settlement instructions; -capture does not require `--turn-envelope` or change the displayed contract. +saved decision. Current JSON guards deliver `loopx_turn_envelope_v1` by default. +Read all required hooks, admission and settlement instructions in that decision. Selection or lease revalidation still needs a fresh guard and a new directory. After a late capture failure, inspect the existing Turn receipt before retrying. See the [capture contract](../reference/protocols/turn-envelope-v0.md). diff --git a/docs/guides/custom-agent-runner-integration.zh-CN.md b/docs/guides/custom-agent-runner-integration.zh-CN.md index 1d8289d02b..cf1294c7ca 100644 --- a/docs/guides/custom-agent-runner-integration.zh-CN.md +++ b/docs/guides/custom-agent-runner-integration.zh-CN.md @@ -84,7 +84,7 @@ OpenCode 的目录布局。 如果 host 没有 skill 系统,就注入等价的 `SKILL.md` 指令,并保留一段短 re-entry instruction,要求 Agent: -1. 为当前 goal 与 Agent 读取新鲜 JSON quota packet; +1. 为当前 goal 与 Agent 读取本轮最新的 JSON Complete Turn; 2. 遵守 `interaction_contract`、`goal_boundary` 和 selected todo; 3. 只做一次有界动作,并验证真实 postcondition; 4. 通过 LoopX 写回结果; @@ -95,7 +95,7 @@ re-entry instruction,要求 Agent: ## 跑一个自驱动 Tick -机器路径使用 JSON: +当前机器入口默认返回 Complete Turn v1。已发布的 `v2.4.0` 标签仍交付原 quota packet。两者均从 `interaction_contract` 读取当前工作指令。 ```bash loopx --format json \ @@ -148,8 +148,8 @@ cat ./guard-001/decision.json ``` 父目录必须已存在;LoopX 创建私有捕获目录。使用保存的决策前,检查命令是否成功、 -`ok` 和 Goal/Agent/Turn 身份。仍须读取所有必需的 hook、准入和结算指令;捕获不要求 -开启 `--turn-envelope`,也不改变展示的合同。选择 Todo 或重新校验 lease 时仍要运行 +`ok` 和 Goal/Agent/Turn 身份。当前 JSON guard 默认交付 `loopx_turn_envelope_v1`。 +读取其中所有必需的 hook、准入和结算指令。选择 Todo 或重新校验 lease 时仍要运行 新 guard,并使用新目录。捕获在后段失败时,应先检查已有 Turn 回执,再判断重试。 详见[捕获合同](../reference/protocols/turn-envelope-v0.md)。 diff --git a/docs/heartbeat-automation-prompt.md b/docs/heartbeat-automation-prompt.md index 6ca7804aa1..c2e642cf50 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/release-readiness.md b/docs/product/release-readiness.md index 9a15e55aa4..dd089226d2 100644 --- a/docs/product/release-readiness.md +++ b/docs/product/release-readiness.md @@ -157,18 +157,6 @@ When the qualification command itself runs from newer source code, pass a local snapshot from the older installed CLI with `--installed-doctor-json`; this option is read-only and accepted only by `update check`. -Runtime artifact readers and the macOS preview updater recognize the exact -`quota_packet` and Complete Turn v1 identities. The publisher still requires -the observed writer to match the single `publication_surface` in the same -contract declaration, currently `quota_packet`. Qualify and publish a -compatible preview on that current writer first. A later C1 release needs its -own writer qualification and supported-Host adoption evidence. - -runtime 制品读取器和 macOS 预览更新器识别 `quota_packet` 与 Complete Turn v1 的 -精确身份。发布器仍要求实际 writer 匹配同一声明中的唯一 `publication_surface`, -当前为 `quota_packet`。先用当前 writer 验证并发布兼容预览。后续 C1 发布需具备自己 -的 writer 资格与受支持 Host 的采用证据。 - ## Named Version Contract LoopX releases are tagged and built from GitHub. The release workflow @@ -293,39 +281,137 @@ The main runtime publisher verifies its downloaded installation qualification against the source revision, channel, archive digest and byte count before any remote write. Every installation/recovery check must pass, and immutable metadata must match the candidate channel metadata. Missing, failed or mismatched evidence -leaves the existing releases and channel untouched. This engineering qualification -does not establish model outcomes, complete-cost benefit or C1 default adoption. +leaves the existing releases and channel untouched. Record supported-profile +adoption, matched model outcomes and complete cost separately under RFC §9. main 运行时发布器在任何远端写入前,将下载的安装资格与源码提交、渠道、归档摘要及 字节数逐项核对。安装和恢复检查必须全部通过,不可变元数据必须与候选渠道元数据一致。 -证据缺失、失败或不匹配时,保留已有发布及渠道。此工程资格不证明模型结果、完整成本收益 -或 C1 默认采用资格。 - -New runtime descriptors carry the observed, supported `default_contract`. -The builder probes the committed runtime before writing a channel descriptor -or replacing existing output. Qualification checks the installed candidate's -ordinary quota writer in an isolated original Goal with context delivery off. -The publisher requires that observation to match the immutable descriptor. +证据缺失、失败或不匹配时,保留已有发布及渠道。按 RFC §9 单独记录受支持 profile 的 +采用、匹配的模型成果和完整成本。 + +New public runtime descriptors carry the observed C1 contract in +`qualified_default_contract`. The archive identity and qualification receipt +retain `default_contract`. Existing v1 updaters can use the same ordinary +`loopx update` flow to verify the source revision, archive digest and byte +count. Current readers normalize the attestation and verify that it matches +the archive identity. The builder probes the committed runtime before +writing a descriptor. Qualification checks the installed candidate's +ordinary quota writer in an isolated Goal with context delivery off. +The publisher requires the compatibility descriptor and exact identity match +before uploading a candidate. The main publishers offer engineering-qualified +candidates as immutable prereleases for explicit verification. Test a Runtime +candidate with `loopx update check --ref ` and the corresponding +`apply` command in a qualification installation. A signed Desktop candidate +uses the immutable release for its exact build. +The Runtime and Desktop update channels use the same reviewed `public_channel` +in `loopx/cli_commands/public_default_contract.json` for main and stable. +The named release uploader verifies the stable Runtime archive and its +qualification against the release source before uploading any package assets. +A held stable Runtime fails that upload and therefore blocks its PyPI job. +Desktop uploads the exact tagged build for verification and keeps +`desktop-stable` on its published profile until the gate passes. +Archive updaters shipped before this cutover resolve stable through GitHub +Latest. The maintainer publishes a prepared, already tagged release through +`create-named-release` after the final release body is approved. It passes +`--latest=false` to GitHub at creation, keeping old stable installs on the +previous complete release while the existing published-release workflow builds +and uploads the new bundle. + +```bash +python scripts/release_artifacts.py create-named-release --repo loopx-project/loopx \ + --title "$RELEASE_TITLE" --notes-file "$RELEASE_BODY" +``` + +From the tagged source, run +`python scripts/release_artifacts.py promote-latest --repo loopx-project/loopx --dist-dir dist` +with its validated bundle. The command reruns stable qualification and +downloads the published assets to check their bytes against that bundle. +When the maintainer authorizes the pointer move, rerun with `--execute` to +update the exact release and verify GitHub Latest. If a write response is lost, +read the release or Latest before retrying. Keep C1 candidates on their immutable +main revision while the stable gate is held. Promote C1 by reviewing the policy +change with the supported installation, adoption, matched outcome and +complete-cost evidence under RFC §9. Desktop packaging observes its actual archived source through the same probe and support validator. Runtime updates reject an unsupported declared contract before downloading or activating it, and bind the archive's contract identity to its metadata. Historical v1 descriptors remain readable. -The current supported distribution scope is the existing `quota_packet` writer; -the complete-contract default cutover stays unqualified until the original RFC §9 -matched single-session outcome/full-cost and supported-profile adoption gate is -met. Installation checks or a new boolean cannot extend that scope. Explicit -complete-contract opt-in, context-delivery configuration and historical recovery -retain their existing owners; this boundary does not switch an installed writer. - -新 runtime 描述符记录实际观测到且受支持的 `default_contract`。构建器在写入渠道描述符 -或替换已有制品之前探测已提交的 runtime。安装资格检查在隔离的原始 Goal 中关闭 -上下文传输后再次观察普通 quota writer。发布器要求安装后的观察与不可变描述符一致。 +The published `v2.4.0` tag retains `quota_packet`. New runtime and Desktop +builds qualify only the observed `complete_turn` (`loopx_turn_envelope_v1`) +default. Their update readers accept both exact profiles so an installed C1 +reader can verify a pinned historical archive during rollback. Keep historical +readback separate from publication, which requires the current default. +Record actual Host adoption and the matched single-session outcome and full-cost +comparison under [RFC §9](../architecture/rfcs/controller-executor-unified-contract-v0.md#9-validation-and-acceptance). + +新的公开 runtime 描述符将实测的 C1 契约写入 `qualified_default_contract`, +归档身份和资格回执使用 `default_contract`。已有 v1 更新器可沿原 `loopx update` +流程校验源码提交、归档摘要和字节数。当前读取端会归一化该声明,并核对归档身份。 +构建器在写入描述符前探测已提交的 runtime。安装资格检查在隔离 Goal 中关闭上下文传输后 +再次观察普通 quota writer。发布器上传候选前要求使用兼容描述符,并核对精确身份。 +通过工程资格的 main 候选可从不可变预发布版本取得,供显式验证。用 +`loopx update check --ref ` 和对应的 `apply` 命令在资格验证安装中测试 +Runtime 候选。签名 Desktop 候选使用其精确构建的不可变发布。 +Runtime 与 Desktop 的 main 和 stable 更新渠道共用 +`loopx/cli_commands/public_default_contract.json` 中通过评审的 `public_channel`。 +正式版本的上传步骤先核对 stable Runtime 归档、安装资格回执与版本来源,再上传包制品。 +stable Runtime 资格未通过时,上传失败,其 PyPI 任务也不会执行。 +Desktop 保留按具体标签验证的签名构建,`desktop-stable` 继续提供已发布的契约。 +切换前已安装的归档更新器经 GitHub Latest 解析 stable。维护者确认最终发布正文后, +使用上面的 `create-named-release` 发布已打标签的版本。创建时显式传入 +`--latest=false`,让旧客户端在现有发布工作流构建和上传制品期间继续使用上一完整版本。 + +在该标签的源码目录,用已验证的制品运行 +`python scripts/release_artifacts.py promote-latest --repo loopx-project/loopx --dist-dir dist`。命令重新核验 stable 资格, +下载已发布的资产并核对字节。维护者授权切换后,为该命令加上 `--execute`, +更新精确发布记录并读回 Latest。如果写入响应丢失,先读回发布记录或 Latest,再决定 +是否重试。stable 门禁未通过时,继续通过不可变的 main 提交验证 C1 候选。推进 C1 时, +按 RFC §9 一并评审受支持的安装、采用、匹配成果和完整成本。 桌面打包通过相同探测与支持校验器检查实际归档源码。runtime 更新在下载或激活前拒绝 未支持的声明契约,并核对归档身份与元数据中的契约;历史 v1 描述符保留读取兼容。 -当前分发范围是已有 `quota_packet` writer;完整契约默认切换在满足原 RFC §9 同单会话 -匹配成果、完整成本及支持 profile 的采用门之前保持未资格化。安装检查或新增布尔值不能 -扩大该范围。显式完整契约 opt-in、上下文传输配置及历史恢复继续由原 owner 处理,此边界 -不切换已安装 writer。 +已发布的 `v2.4.0` 标签保留 `quota_packet`。新的 runtime 和 Desktop 构建只为 +实际探测到的 `complete_turn`(`loopx_turn_envelope_v1`)默认契约签发资格。 +更新读取端接受两种精确契约,已安装 C1 的读取端可在回退时校验固定版本的历史归档。 +历史制品读取与新制品发布资格各自核验。按 +[RFC §9](../architecture/rfcs/controller-executor-unified-contract-v0.zh-CN.md#9-验证与验收) +记录受支持 Host 的实际采用,并完成同单会话匹配成果和完整成本对照。 + +#### macOS preview upgrade across the C1 cutover + +The quota-packet-only macOS updater rejects a C1 archive at the contract +check. Once a compatible signed preview is published, use this one-time manual +replacement path from the older App: + +1. Download `LoopX.app.tar.gz` and `LoopX.app.tar.gz.sig` from the same official + `desktop-main-*` [release](https://github.com/loopx-project/loopx/releases) + for a C1-capable source revision. In a scratch directory, verify the archive + against the already trusted updater key. The key is the base64 value of + `plugins.updater.pubkey` in the installed version's trusted Tauri configuration. +2. Decode the trusted key and the release signature and verify before unpacking. + With the trusted configuration saved as `trusted-tauri.conf.json`, run: + + ```bash + set -euo pipefail + jq -er '.plugins.updater.pubkey' trusted-tauri.conf.json | base64 -D > updater.pub + base64 -D -i LoopX.app.tar.gz.sig -o updater.minisig + minisign -Vm LoopX.app.tar.gz -p updater.pub -x updater.minisig + tar -xzf LoopX.app.tar.gz + codesign --verify --deep --strict LoopX.app + ``` + +3. Quit LoopX and save the existing App bundle and a compatible state backup + before replacing the App. Launch the verified replacement, then confirm the + App version, the same Goal and original receipt, and the installed runtime's + v1 default. If the checks fail, quit and restore the previous verified bundle + with the compatible backup as needed. The standalone CLI has its own update + and rollback path. + +仅支持 quota-packet 的 macOS updater 会在契约校验处拒绝 C1 归档。兼容的签名预览版 +发布后,首次跨越此边界时按上面的手动流程操作。从同一官方 `desktop-main-*` 发行版下载归档和签名, +用已信任的旧版 updater 公钥校验归档,再解包并校验 App 签名。退出 LoopX,备份旧 +App 与兼容状态后再替换。启动后读回版本、同一 Goal、原回执及已安装 runtime 的 v1 +默认值。检查失败时,退出并恢复已验证旧 App,需要时恢复兼容状态备份。独立 CLI +沿自己的更新与回退路径处理。 For a browser-fixture error discovered after an immutable tag was published, maintainers may dispatch the release workflow from reviewed tooling with diff --git a/docs/product/releases/v2.4.0.md b/docs/product/releases/v2.4.0.md index 33f5ce5a5b..a0dfd0e0db 100644 --- a/docs/product/releases/v2.4.0.md +++ b/docs/product/releases/v2.4.0.md @@ -1,6 +1,6 @@ # LoopX v2.4.0 -Keep original work, evidence, and conversations connected after interruption across Core 2.4.0, Desktop App 2.4.0, and `dsh-loopx-plugin 0.1.1-beta.7`. Core 2.4.0 adds one-confirmation Goal creation, searchable loaded conversations, isolated Steward memory, probe-gated Steward monitors and protected PR merge confirmations, bidirectional Codex/Antigravity Steward failover, and runtime-composed `quota_settlement_plan_v2` Turn envelopes while retaining `quota_packet` as the ordinary public default. Installation, data compatibility, and optional host integrations retain their own checks. +Keep original work, evidence, and conversations connected after interruption across Core 2.4.0, Desktop App 2.4.0, and `dsh-loopx-plugin 0.1.1-beta.7`. Core 2.4.0 adds one-confirmation Goal creation, searchable loaded conversations, isolated Steward memory, probe-gated Steward monitors and protected PR merge confirmations, bidirectional Codex/Antigravity Steward failover, and runtime-composed `quota_settlement_plan_v2` Turn envelopes while retaining `quota_packet` as the ordinary public default in the tagged release. Installation, data compatibility, and optional host integrations retain their own checks. ## At a Glance @@ -8,6 +8,11 @@ Create a Goal from Chat with one confirmation. Search loaded conversations back ### Upgrade +The C1 source checkout and newly qualified runtime artifacts default to Complete Turn. +The published `v2.4.0` tag keeps its original default. Once a compatible signed +preview is available, use the [manual macOS upgrade path](../release-readiness.md#macos-preview-upgrade-across-the-c1-cutover) +from an earlier preview. + After `v2.4.0` appears on your current distribution channel, check and apply the upgrade through that installation's owner. Review the migration below first if your registry still uses the legacy paused or stopped status. ```bash @@ -24,7 +29,7 @@ loopx doctor - **Create a Goal from Chat and search loaded history.** Review a draft and confirm once to create the Goal and open its conversation when runtime and permissions are ready; search loaded conversations back to original messages, keep saved Research answers intact across Desktop reopenings, recover interrupted answers or pre-dispatch requests, diagnose lost workers, and preserve readable quoted Markdown. [#8676](https://github.com/loopx-project/loopx/pull/8676), [#8780](https://github.com/loopx-project/loopx/pull/8780), [#8863](https://github.com/loopx-project/loopx/pull/8863), [#8868](https://github.com/loopx-project/loopx/pull/8868), [#8880](https://github.com/loopx-project/loopx/pull/8880), [#8892](https://github.com/loopx-project/loopx/pull/8892), [#8983](https://github.com/loopx-project/loopx/pull/8983), [#9120](https://github.com/loopx-project/loopx/pull/9120), [#9125](https://github.com/loopx-project/loopx/pull/9125) - **Steward monitors, exact-head PR review signals, and protected merge confirmations.** Generic probe-gated `continuous_monitor` Todos support `context_handoff` and bounded `steward_user_actions`, scoped GitHub PR signal monitors aggregate per-monitor findings and deliver one readable report directly into bound App or Feishu `chat_root` sessions (`#9182`), exact-head PR review screening and queue model-coverage tracking power `/confirm` `pr.merge` previews with head/review drift checks, bounded advancement evidence, inline autonomous replan settlement with isolated `native_result` sinks, and pre-host deferral retries (`#9187`, `#9188`, `#9191`) alongside report/queue/pre-dispatch recovery (including stopped/saved candidate recovery and minor JSON delimiter glitch tolerance) harden cross-endpoint Steward reliability, and opt-in `steward_memory` adds isolated OpenViking memory scoped strictly to verified owner private Steward chats. [#9014](https://github.com/loopx-project/loopx/pull/9014), [#9074](https://github.com/loopx-project/loopx/pull/9074), [#9077](https://github.com/loopx-project/loopx/pull/9077), [#9081](https://github.com/loopx-project/loopx/pull/9081), [#9083](https://github.com/loopx-project/loopx/pull/9083), [#9093](https://github.com/loopx-project/loopx/pull/9093), [#9143](https://github.com/loopx-project/loopx/pull/9143), [#9155](https://github.com/loopx-project/loopx/pull/9155), [#9157](https://github.com/loopx-project/loopx/pull/9157), [#9159](https://github.com/loopx-project/loopx/pull/9159), [#9164](https://github.com/loopx-project/loopx/pull/9164), [#9182](https://github.com/loopx-project/loopx/pull/9182), [#9187](https://github.com/loopx-project/loopx/pull/9187), [#9188](https://github.com/loopx-project/loopx/pull/9188), [#9191](https://github.com/loopx-project/loopx/pull/9191) -- **Recover original work with Complete Turn and `quota_settlement_plan_v2`.** Installed workspaces discover the Manager via the installed CLI and resume authorized Tasks on their original Turn, debit identity, and lazily rebound hard-lease fence (`#9183`); Complete Turn / native host callers compose `loopx_turn_envelope_v1` with runtime-owned `quota_settlement_plan_v2` (`--settle-turn --settlement-receipt`), while ordinary unhosted JSON `quota should-run` retains `quota_packet` as the qualified public default. [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8615](https://github.com/loopx-project/loopx/pull/8615), [#8802](https://github.com/loopx-project/loopx/pull/8802), [#8830](https://github.com/loopx-project/loopx/pull/8830), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9030](https://github.com/loopx-project/loopx/pull/9030), [#9047](https://github.com/loopx-project/loopx/pull/9047), [#9084](https://github.com/loopx-project/loopx/pull/9084), [#9097](https://github.com/loopx-project/loopx/pull/9097), [#9111](https://github.com/loopx-project/loopx/pull/9111), [#9154](https://github.com/loopx-project/loopx/pull/9154), [#9157](https://github.com/loopx-project/loopx/pull/9157), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161), [#9183](https://github.com/loopx-project/loopx/pull/9183) +- **Recover original work with Complete Turn and `quota_settlement_plan_v2`.** Installed workspaces discover the Manager via the installed CLI and resume authorized Tasks on their original Turn, debit identity, and lazily rebound hard-lease fence (`#9183`); Complete Turn / native host callers compose `loopx_turn_envelope_v1` with runtime-owned `quota_settlement_plan_v2` (`--settle-turn --settlement-receipt`), while the `v2.4.0` tag's ordinary unhosted JSON `quota should-run` uses `quota_packet`. [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8615](https://github.com/loopx-project/loopx/pull/8615), [#8802](https://github.com/loopx-project/loopx/pull/8802), [#8830](https://github.com/loopx-project/loopx/pull/8830), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9030](https://github.com/loopx-project/loopx/pull/9030), [#9047](https://github.com/loopx-project/loopx/pull/9047), [#9084](https://github.com/loopx-project/loopx/pull/9084), [#9097](https://github.com/loopx-project/loopx/pull/9097), [#9111](https://github.com/loopx-project/loopx/pull/9111), [#9154](https://github.com/loopx-project/loopx/pull/9154), [#9157](https://github.com/loopx-project/loopx/pull/9157), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161), [#9183](https://github.com/loopx-project/loopx/pull/9183) - **Antigravity Carbon, per-endpoint preferences, and bidirectional Steward failover.** Registers Antigravity `Carbon` (`gemini-4-carbon-{high,medium,low}`) while keeping `Argon` as the product default, adds `endpoint_models` preferences in `steward_executor_machine_defaults_v1` (with JSON-mode editor guidance), enables bidirectional Codex/Antigravity flexible failover (`loopx-codex-provider-routing 0.15.9`) with Antigravity reasoning-effort capacity aliases and `flexible_primary_available` transitions, recovers Codex loopback relay `401` failures and Steward active-cascade `resume_failed` states, prevents truncated Codex API relay traffic, and preserves Codex session history across model switches. [#8713](https://github.com/loopx-project/loopx/pull/8713), [#8977](https://github.com/loopx-project/loopx/pull/8977), [#8984](https://github.com/loopx-project/loopx/pull/8984), [#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), [#9170](https://github.com/loopx-project/loopx/pull/9170) - **Multi-agent collaboration and hardened Lark group/private channels.** Peers read pending results via `read_peer_returns` and `consume_peer_result` without reopening the Manager Inbox, Goal lifetime guard locks batch per Goal, and Lark gains reconnect queue recovery, read-only Steward shortcuts, Turn-scoped native images, shared card callbacks, single-pass card escaping, international setup URL recognition, and input-aware noop backoff reset. [#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), [#8871](https://github.com/loopx-project/loopx/pull/8871), [#8921](https://github.com/loopx-project/loopx/pull/8921), [#8990](https://github.com/loopx-project/loopx/pull/8990), [#9027](https://github.com/loopx-project/loopx/pull/9027), [#9085](https://github.com/loopx-project/loopx/pull/9085), [#9114](https://github.com/loopx-project/loopx/pull/9114), [#9117](https://github.com/loopx-project/loopx/pull/9117), [#9119](https://github.com/loopx-project/loopx/pull/9119) - **Desktop App 2.4.0, `dsh-loopx-plugin 0.1.1-beta.7`, LooChat workbench, and remote task gateway.** Desktop App prepares updates before workspace teardown, bounds readiness probes, skips immutable-release frontend re-hashing, adds release/chat-bundle download retries, and verifies `default_contract` before caching macOS preview updates; `dsh-loopx-plugin 0.1.1-beta.7` requires LoopX 2.4.0+, qualifies DSH `0.2.2-rc.1..rc.3` (including `quota_settlement_plan_v2` closeout tests), surfaces GoalBar admission failures, and isolates hot uninstall; `apps/workbench/` introduces the experimental LooChat conversation layer; and the remote task gateway adds scoped read ACLs and a PostgreSQL/TLS Compose self-hosting bundle. [#8508](https://github.com/loopx-project/loopx/pull/8508), [#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), [#8765](https://github.com/loopx-project/loopx/pull/8765), [#8843](https://github.com/loopx-project/loopx/pull/8843), [#8861](https://github.com/loopx-project/loopx/pull/8861), [#8879](https://github.com/loopx-project/loopx/pull/8879), [#8887](https://github.com/loopx-project/loopx/pull/8887), [#8899](https://github.com/loopx-project/loopx/pull/8899), [#9029](https://github.com/loopx-project/loopx/pull/9029), [#9089](https://github.com/loopx-project/loopx/pull/9089), [#9147](https://github.com/loopx-project/loopx/pull/9147) @@ -46,7 +51,7 @@ loopx doctor **What this release solves:** It reduces Goal creation to one confirmation, connects loaded chat search and saved Research answers to original Turns, enables probe-gated Steward monitoring and exact-head PR merge confirmation, adds isolated owner-private Steward memory and bidirectional Codex/Antigravity failover, and hardens Task/lease recovery, Desktop preview qualification, Lark delivery, and DSH 0.2.2 compatibility. -**Breaking changes:** Yes. Legacy registry `status` values `paused` and `stopped` are retired in favor of `activation.state` and Goal lifecycle commands with a backed-up migration ([#8431](https://github.com/loopx-project/loopx/pull/8431)); the unqualified compaction working memory experiment is retired with saved settings kept inert ([#8928](https://github.com/loopx-project/loopx/pull/8928)); and `dsh-loopx-plugin 0.1.1-beta.7` requires LoopX 2.4.0 or newer for the `quota receipt` reader ([#8899](https://github.com/loopx-project/loopx/pull/8899)). Ordinary unhosted JSON `quota should-run` keeps `quota_packet` as the qualified public default ([#9084](https://github.com/loopx-project/loopx/pull/9084)). +**Breaking changes:** Yes. Legacy registry `status` values `paused` and `stopped` are retired in favor of `activation.state` and Goal lifecycle commands with a backed-up migration ([#8431](https://github.com/loopx-project/loopx/pull/8431)); the unqualified compaction working memory experiment is retired with saved settings kept inert ([#8928](https://github.com/loopx-project/loopx/pull/8928)); and `dsh-loopx-plugin 0.1.1-beta.7` requires LoopX 2.4.0 or newer for the `quota receipt` reader ([#8899](https://github.com/loopx-project/loopx/pull/8899)). The `v2.4.0` tag keeps `quota_packet` as the ordinary unhosted JSON `quota should-run` default ([#9084](https://github.com/loopx-project/loopx/pull/9084)). **How to verify:** Verify `2.4.0` and the owning Python environment in `loopx doctor`, confirm an existing Goal and original Task or new Chat draft, and confirm the read-only archive check passes after any registry migration. @@ -62,7 +67,7 @@ loopx authority-archive upgrade --all-known --require-current ## State Kernel & Control Plane - Recovery retains the original Turn, debit identity, and prepared or lazily rebound hard-lease fence (`--task-lease-idempotency-key` / `--task-lease-expected-version`, plus `.validation-recovery.` / `.admission-retry` and `monitor_poll` `lease_proof` recovery) only while recovery still needs an active lease — preserving committed-Turn replay and retired-lease closeout recovery (`#9183`) — while rechecking a fresh selection's gates; first `generic-cli` Turns declared with the complete v1 adapter and an independent validator auto-prepare missing task leases (`#9047`), settled C1 Turns stay prevented from reacquiring a native Codex lease, `quota_result_delivery` retains `host_poll_receipt` on transport errors without recording premature `capture_sha256` digests, checkpoint-relocated accounting artifact reads (`readQuotaSpendEventFromRun`) resolve safely inside the active `runs` directory, and a validated Todo-less original Turn recovers its own receipt without a second spend. [#8860](https://github.com/loopx-project/loopx/pull/8860), [#8894](https://github.com/loopx-project/loopx/pull/8894), [#8900](https://github.com/loopx-project/loopx/pull/8900), [#9047](https://github.com/loopx-project/loopx/pull/9047), [#9097](https://github.com/loopx-project/loopx/pull/9097), [#9111](https://github.com/loopx-project/loopx/pull/9111), [#9157](https://github.com/loopx-project/loopx/pull/9157), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161), [#9183](https://github.com/loopx-project/loopx/pull/9183) -- Complete Turn (`loopx_turn_envelope_v1`) and native host callers compose runtime-owned `quota_settlement_plan_v2` (`--settle-turn --settlement-receipt`), keeping `quota_spend` as a runtime step in `ordered_steps`, routing stateless capture read selection through the TypeScript `context_select` owner (`#9142`), and aligning explicit `--capture-dir` settlement plan reads with progressive `context-read` references (`#9154`, `#9158`, `#9160`), while ordinary unhosted JSON `quota should-run` retains the qualified `quota_packet` public default until RFC §9 qualification; quota polling preserves explicit Monitor Todo selection (`#9099`), verifies gate scope through signed lane references (`#9101`), loads large write-scope lists on demand during Todo preparation and keeps claim overlap scopes accessible (`#9078`, `#9086`, `#9106`), preserves `rearmed_after_obligation_id` across Vision successor reconstruction and post-admission same-Agent ACKs (`#9118`), defers backup preimage directory-sync imports inside `registry_codec` for test/adapter isolation (`#9161`), and retires legacy heartbeat work prompt generation in favor of the unified contract. [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9000](https://github.com/loopx-project/loopx/pull/9000), [#9030](https://github.com/loopx-project/loopx/pull/9030), [#9054](https://github.com/loopx-project/loopx/pull/9054), [#9057](https://github.com/loopx-project/loopx/pull/9057), [#9078](https://github.com/loopx-project/loopx/pull/9078), [#9084](https://github.com/loopx-project/loopx/pull/9084), [#9086](https://github.com/loopx-project/loopx/pull/9086), [#9099](https://github.com/loopx-project/loopx/pull/9099), [#9101](https://github.com/loopx-project/loopx/pull/9101), [#9106](https://github.com/loopx-project/loopx/pull/9106), [#9118](https://github.com/loopx-project/loopx/pull/9118), [#9142](https://github.com/loopx-project/loopx/pull/9142), [#9154](https://github.com/loopx-project/loopx/pull/9154), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161) +- Complete Turn (`loopx_turn_envelope_v1`) and native host callers compose runtime-owned `quota_settlement_plan_v2` (`--settle-turn --settlement-receipt`), keeping `quota_spend` as a runtime step in `ordered_steps`, routing stateless capture read selection through the TypeScript `context_select` owner (`#9142`), and aligning explicit `--capture-dir` settlement plan reads with progressive `context-read` references (`#9154`, `#9158`, `#9160`), while the `v2.4.0` tag retains the ordinary `quota_packet` default; quota polling preserves explicit Monitor Todo selection (`#9099`), verifies gate scope through signed lane references (`#9101`), loads large write-scope lists on demand during Todo preparation and keeps claim overlap scopes accessible (`#9078`, `#9086`, `#9106`), preserves `rearmed_after_obligation_id` across Vision successor reconstruction and post-admission same-Agent ACKs (`#9118`), defers backup preimage directory-sync imports inside `registry_codec` for test/adapter isolation (`#9161`), and retires legacy heartbeat work prompt generation in favor of the unified contract. [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9000](https://github.com/loopx-project/loopx/pull/9000), [#9030](https://github.com/loopx-project/loopx/pull/9030), [#9054](https://github.com/loopx-project/loopx/pull/9054), [#9057](https://github.com/loopx-project/loopx/pull/9057), [#9078](https://github.com/loopx-project/loopx/pull/9078), [#9084](https://github.com/loopx-project/loopx/pull/9084), [#9086](https://github.com/loopx-project/loopx/pull/9086), [#9099](https://github.com/loopx-project/loopx/pull/9099), [#9101](https://github.com/loopx-project/loopx/pull/9101), [#9106](https://github.com/loopx-project/loopx/pull/9106), [#9118](https://github.com/loopx-project/loopx/pull/9118), [#9142](https://github.com/loopx-project/loopx/pull/9142), [#9154](https://github.com/loopx-project/loopx/pull/9154), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161) - Ordinary Todo edits preserve compatible stored declarations; when new fields require a newer reader, archive rollback checks the target runtime's Todo read before switching, rolls back both CLI and archive-managed `loopx-apply-rrule` launchers atomically on POSIX (`#9007`), honors custom bin and release directory overrides (`#9066`), and leaves current runtime and state untouched if the check fails. [#8902](https://github.com/loopx-project/loopx/pull/8902), [#8906](https://github.com/loopx-project/loopx/pull/8906), [#9007](https://github.com/loopx-project/loopx/pull/9007), [#9066](https://github.com/loopx-project/loopx/pull/9066) - Goal storage import follows the registered source and serializes its final source check with registry writers without substituting global discovery for that source; an already canonical Goal needs no cold import. [#8864](https://github.com/loopx-project/loopx/pull/8864) - Installed task recovery uses the original execution lease and receipt through the shared task lifecycle, `refresh-state` accepts inline JSON, `spend-slot` accepts `--delivery-workspace-path`, cross-repository binding errors explain missing bindings clearly, and standalone heartbeat settlement uses the installed route. [#8615](https://github.com/loopx-project/loopx/pull/8615), [#8707](https://github.com/loopx-project/loopx/pull/8707), [#8827](https://github.com/loopx-project/loopx/pull/8827), [#8926](https://github.com/loopx-project/loopx/pull/8926), [#8933](https://github.com/loopx-project/loopx/pull/8933) @@ -100,7 +105,7 @@ loopx authority-archive upgrade --all-known --require-current - A Japanese README joins the existing public reading entrypoints, alongside updated bilingual RFCs and Bootstrap/Control-Plane guides. [#8839](https://github.com/loopx-project/loopx/pull/8839), [#9035](https://github.com/loopx-project/loopx/pull/9035), [#9113](https://github.com/loopx-project/loopx/pull/9113) - `dsh-loopx-plugin 0.1.1-beta.7` requires LoopX `2.4.0` or newer (`loopx>=2.4.0`) for the original-Turn `quota receipt` reader and qualifies `DSH 0.2.2-rc.1..rc.3` (retaining `0.1.5..0.2.1-rc.2`). Core 2.4.0, Desktop App 2.4.0, and the DSH plugin have separate releases and support matrices; updating Core does not automatically publish or upgrade an installed DSH plugin. [#8879](https://github.com/loopx-project/loopx/pull/8879), [#8899](https://github.com/loopx-project/loopx/pull/8899) -- Ordinary unhosted JSON `quota should-run` retains `quota_packet` as the qualified public default (`public_default_contract.json`), and macOS Desktop preview updates verify that signature-verified archives declare the matching `default_contract` before caching or replacing the App. [#8952](https://github.com/loopx-project/loopx/pull/8952), [#9018](https://github.com/loopx-project/loopx/pull/9018), [#9029](https://github.com/loopx-project/loopx/pull/9029), [#9084](https://github.com/loopx-project/loopx/pull/9084) +- The `v2.4.0` tag's ordinary unhosted JSON `quota should-run` uses `quota_packet`, and macOS Desktop preview updates verify that signature-verified archives declare the matching `default_contract` before caching or replacing the App. [#8952](https://github.com/loopx-project/loopx/pull/8952), [#9018](https://github.com/loopx-project/loopx/pull/9018), [#9029](https://github.com/loopx-project/loopx/pull/9029), [#9084](https://github.com/loopx-project/loopx/pull/9084) - A backed-up upgrade converts legacy Goal pause metadata to `activation.state`. A raw pip or source install can run `loopx authority-archive upgrade --all-known --require-current` as a read-only check. For a registry you own that requires migration, run `loopx authority-archive upgrade --all-known --execute` and retain its returned backup path. Conflicting pause metadata stays stopped pending owner review. [#8431](https://github.com/loopx-project/loopx/pull/8431) - A standalone `loopx-core` wheel preparation candidate (`packages/loopx-core/`) enables workspace-free CLI and TypeScript runtime installations while keeping the ordinary `loopx` package default unchanged. [#8615](https://github.com/loopx-project/loopx/pull/8615), [#8830](https://github.com/loopx-project/loopx/pull/8830), [#8840](https://github.com/loopx-project/loopx/pull/8840) @@ -154,20 +159,20 @@ 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) +**C1 source checkout** JSON `quota should-run` delivers `loopx_turn_envelope_v1` by default, including with context and delta delivery off. Remove `--complete-turn` and `--turn-envelope`. An ordinary CLI consumer reads `cli_channel.next_cli_actions` in the full decision. A host that declares `--runtime-profile generic_cli` and binds Agent, Todo and Turn reads the returned `quota_settlement_plan_v2` when admitted. Its `--settle-turn --settlement-receipt` step uses the original identity. 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, then follow the actions or plan returned 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. -**Docs:** [Turn envelope reference](https://github.com/loopx-project/loopx/blob/v2.4.0/docs/reference/protocols/turn-envelope-v0.md) +**Docs:** [Current Turn envelope reference](../../reference/protocols/turn-envelope-v0.md) ```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. @@ -417,6 +422,8 @@ loopx extension doctor --all-enabled --execute 本页说明 LoopX Core 2.4.0、Desktop App 2.4.0 与 `dsh-loopx-plugin 0.1.1-beta.7` 的升级与可选能力用法:在对话中一次确认创建 Goal、检索已载入消息、使用独立管家长期记忆与受保护 PR 合并确认、按原任务与回执恢复工作,并支持 Codex/Antigravity 双向切换。安装、数据兼容与可选 Host 集成分别核验。 +已发布的 `v2.4.0` 标签保留 `quota_packet`。C1 源码和新通过资格校验的 runtime 制品默认使用 Complete Turn。兼容的签名预览版发布后,从 macOS 旧预览版升级时按[手动升级流程](../release-readiness.md#macos-preview-upgrade-across-the-c1-cutover)操作。 + ### 升级 现有安装渠道提供 `2.4.0` 后,依次执行 `loopx update check`、`loopx update plan`、`loopx update apply`,再运行 `loopx --version` 和 `loopx doctor`。仍使用旧暂停字段的 registry 先核对下方迁移路径。 @@ -452,7 +459,7 @@ loopx doctor **解决了什么:** 把 Goal 创建和打开会话收敛到一次确认,改善已载入会话检索、原任务/回执恢复与多 Agent 结果读取,并补齐管家探针监控、精确 Head PR 合并确认、私聊独立长期记忆、Codex/Antigravity 双向容灾、Desktop 预览校验、飞书队列与 DSH 0.2.2 兼容性。 -**是否有破坏性变更:** 有。Registry 停用旧 `status: paused/stopped`,暂停与恢复统一使用 `activation.state` 和 Goal lifecycle 命令并支持备份迁移([#8431](https://github.com/loopx-project/loopx/pull/8431));未通过验收的压缩工作记忆实验已退役([#8928](https://github.com/loopx-project/loopx/pull/8928));`dsh-loopx-plugin 0.1.1-beta.7` 要求 LoopX 2.4.0 或更新版本([#8899](https://github.com/loopx-project/loopx/pull/8899))。普通未托管 JSON `quota should-run` 继续维持 `quota_packet` 公开默认([#9084](https://github.com/loopx-project/loopx/pull/9084))。 +**是否有破坏性变更:** 有。Registry 停用旧 `status: paused/stopped`,暂停与恢复统一使用 `activation.state` 和 Goal lifecycle 命令并支持备份迁移([#8431](https://github.com/loopx-project/loopx/pull/8431));未通过验收的压缩工作记忆实验已退役([#8928](https://github.com/loopx-project/loopx/pull/8928));`dsh-loopx-plugin 0.1.1-beta.7` 要求 LoopX 2.4.0 或更新版本([#8899](https://github.com/loopx-project/loopx/pull/8899))。`v2.4.0` 标签的普通未托管 JSON `quota should-run` 默认使用 `quota_packet`([#9084](https://github.com/loopx-project/loopx/pull/9084))。 **如何验证:** 确认版本为 `2.4.0` 与 `loopx doctor` 所属环境正常,打开既有 Goal 与原任务或在 Chat 确认新草稿,并确保迁移后的只读检查命令通过。 @@ -461,7 +468,7 @@ loopx doctor ### 状态内核与控制面 - 恢复原 Turn、扣额身份和已准备或惰性重绑定的硬租约护栏(`--task-lease-idempotency-key` / `--task-lease-expected-version`,含 `.validation-recovery.` / `.admission-retry` 与 `monitor_poll` `lease_proof`)时仅在仍需有效租约时按需重绑定、保持已提交 Turn 重放与已退役租约结案恢复不被破坏(`#9183`),并继续核对新选择的门禁;已声明完整 v1 适配层与独立验证器的首次 `generic-cli` Turn 自动准备缺失租约(`#9047`),已结算的 C1 Turn 禁止再次获取原生 Codex 租约,`quota_result_delivery` 在传输失败时保留 `host_poll_receipt` 诊断而不提前写入 `capture_sha256`,检查点重定位的账务制品读取(`readQuotaSpendEventFromRun`)安全约束在当前 `runs` 目录内,已验证的无 Todo 原 Turn 可读取自身回执避免重复扣额。 [#8860](https://github.com/loopx-project/loopx/pull/8860), [#8894](https://github.com/loopx-project/loopx/pull/8894), [#8900](https://github.com/loopx-project/loopx/pull/8900), [#9047](https://github.com/loopx-project/loopx/pull/9047), [#9097](https://github.com/loopx-project/loopx/pull/9097), [#9111](https://github.com/loopx-project/loopx/pull/9111), [#9157](https://github.com/loopx-project/loopx/pull/9157), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161), [#9183](https://github.com/loopx-project/loopx/pull/9183) -- Complete Turn(`loopx_turn_envelope_v1`)与原生宿主调用方组合运行时拥有的 `quota_settlement_plan_v2`(`--settle-turn --settlement-receipt`),将 `quota_spend` 保留为 `ordered_steps` 中的 `runtime` 步骤、将无状态捕获读取选择交回 TypeScript `context_select` owner(`#9142`)并对齐显式 `--capture-dir` 与分段 `context-read` 读回(`#9154`、`#9158`、`#9160`);配额轮询保留显式 Monitor Todo 选择(`#9099`)、通过签名车道引用校验门禁作用域(`#9101`)、在 `registry_codec` 中延后备份预映像的目录同步导入以保持适配层测试隔离(`#9161`)、按需延迟加载大体积写入作用域并在重叠长认领下保留就绪控件(`#9078`、`#9086`、`#9106`)、在 Vision 后继重建与准入后同 Agent ACK 中保留 `rearmed_after_obligation_id`(`#9118`);普通未托管 JSON `quota should-run` 在 RFC §9 验收前保留 `quota_packet` 公开默认,并退役旧版心跳工作提示生成。 [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9000](https://github.com/loopx-project/loopx/pull/9000), [#9030](https://github.com/loopx-project/loopx/pull/9030), [#9054](https://github.com/loopx-project/loopx/pull/9054), [#9057](https://github.com/loopx-project/loopx/pull/9057), [#9078](https://github.com/loopx-project/loopx/pull/9078), [#9084](https://github.com/loopx-project/loopx/pull/9084), [#9086](https://github.com/loopx-project/loopx/pull/9086), [#9099](https://github.com/loopx-project/loopx/pull/9099), [#9101](https://github.com/loopx-project/loopx/pull/9101), [#9106](https://github.com/loopx-project/loopx/pull/9106), [#9118](https://github.com/loopx-project/loopx/pull/9118), [#9142](https://github.com/loopx-project/loopx/pull/9142), [#9154](https://github.com/loopx-project/loopx/pull/9154), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161) +- Complete Turn(`loopx_turn_envelope_v1`)与原生宿主调用方组合运行时拥有的 `quota_settlement_plan_v2`(`--settle-turn --settlement-receipt`),将 `quota_spend` 保留为 `ordered_steps` 中的 `runtime` 步骤、将无状态捕获读取选择交回 TypeScript `context_select` owner(`#9142`)并对齐显式 `--capture-dir` 与分段 `context-read` 读回(`#9154`、`#9158`、`#9160`);配额轮询保留显式 Monitor Todo 选择(`#9099`)、通过签名车道引用校验门禁作用域(`#9101`)、在 `registry_codec` 中延后备份预映像的目录同步导入以保持适配层测试隔离(`#9161`)、按需延迟加载大体积写入作用域并在重叠长认领下保留就绪控件(`#9078`、`#9086`、`#9106`)、在 Vision 后继重建与准入后同 Agent ACK 中保留 `rearmed_after_obligation_id`(`#9118`);`v2.4.0` 标签的普通未托管 JSON `quota should-run` 默认使用 `quota_packet`,并退役旧版心跳工作提示生成。 [#8489](https://github.com/loopx-project/loopx/pull/8489), [#8956](https://github.com/loopx-project/loopx/pull/8956), [#9000](https://github.com/loopx-project/loopx/pull/9000), [#9030](https://github.com/loopx-project/loopx/pull/9030), [#9054](https://github.com/loopx-project/loopx/pull/9054), [#9057](https://github.com/loopx-project/loopx/pull/9057), [#9078](https://github.com/loopx-project/loopx/pull/9078), [#9084](https://github.com/loopx-project/loopx/pull/9084), [#9086](https://github.com/loopx-project/loopx/pull/9086), [#9099](https://github.com/loopx-project/loopx/pull/9099), [#9101](https://github.com/loopx-project/loopx/pull/9101), [#9106](https://github.com/loopx-project/loopx/pull/9106), [#9118](https://github.com/loopx-project/loopx/pull/9118), [#9142](https://github.com/loopx-project/loopx/pull/9142), [#9154](https://github.com/loopx-project/loopx/pull/9154), [#9158](https://github.com/loopx-project/loopx/pull/9158), [#9160](https://github.com/loopx-project/loopx/pull/9160), [#9161](https://github.com/loopx-project/loopx/pull/9161) - 普通 Todo 修改保留兼容声明;新字段需要新版读取器时,归档回退先校验目标版本能否读取 Todo、在 POSIX 上原子回退 CLI 与归档托管 `loopx-apply-rrule` 两个启动器(`#9007`)、沿用自定义安装与发行目录(`#9066`),失败则保留当前运行时与数据。 [#8902](https://github.com/loopx-project/loopx/pull/8902), [#8906](https://github.com/loopx-project/loopx/pull/8906), [#9007](https://github.com/loopx-project/loopx/pull/9007), [#9066](https://github.com/loopx-project/loopx/pull/9066) - 存储导入沿已注册源执行并与 registry 写方串行核对,已采用 canonical authority 的 Goal 无需冷导入;安装环境恢复沿用原租约和回执,`refresh-state` 支持内联 JSON,`spend-slot` 新增 `--delivery-workspace-path`,跨仓库绑定错误说明更清晰。 [#8615](https://github.com/loopx-project/loopx/pull/8615), [#8707](https://github.com/loopx-project/loopx/pull/8707), [#8827](https://github.com/loopx-project/loopx/pull/8827), [#8864](https://github.com/loopx-project/loopx/pull/8864), [#8926](https://github.com/loopx-project/loopx/pull/8926), [#8933](https://github.com/loopx-project/loopx/pull/8933) - 多 Agent 协作支持通过 `read_peer_returns` 与 `consume_peer_result` 直接读回对等体结果而无需重开 Manager Inbox,交接查询按 Goal 批量加锁并缓存历史与终态扫描,阻断跨 Goal 误投递并允许单 Agent Goal 由 owner 关闭精确关联门禁。 [#8644](https://github.com/loopx-project/loopx/pull/8644), [#8779](https://github.com/loopx-project/loopx/pull/8779), [#8803](https://github.com/loopx-project/loopx/pull/8803), [#8844](https://github.com/loopx-project/loopx/pull/8844), [#8846](https://github.com/loopx-project/loopx/pull/8846), [#8853](https://github.com/loopx-project/loopx/pull/8853), [#9027](https://github.com/loopx-project/loopx/pull/9027), [#9085](https://github.com/loopx-project/loopx/pull/9085), [#9088](https://github.com/loopx-project/loopx/pull/9088), [#9117](https://github.com/loopx-project/loopx/pull/9117) @@ -492,7 +499,7 @@ loopx doctor - 新增日文 README 并接入现有公开阅读入口,同步更新多份双语 RFC 与 bootstrap/审计文档。 [#8839](https://github.com/loopx-project/loopx/pull/8839), [#9035](https://github.com/loopx-project/loopx/pull/9035), [#9113](https://github.com/loopx-project/loopx/pull/9113) - `dsh-loopx-plugin 0.1.1-beta.7` 需要 Core 2.4.0 及以上版本的原 Turn `quota receipt` 读取能力,支持 DSH `0.2.2-rc.1..rc.3`。Core、Desktop App 与插件各自发布并核对支持矩阵,升级 Core 不会自动发布或升级插件包。 [#8879](https://github.com/loopx-project/loopx/pull/8879), [#8899](https://github.com/loopx-project/loopx/pull/8899) -- 普通未托管 JSON `quota should-run` 继续保持 `quota_packet` 公开默认;macOS 桌面 preview 更新前会核对签名归档中的 `default_contract`。 [#8952](https://github.com/loopx-project/loopx/pull/8952), [#9018](https://github.com/loopx-project/loopx/pull/9018), [#9029](https://github.com/loopx-project/loopx/pull/9029), [#9084](https://github.com/loopx-project/loopx/pull/9084) +- `v2.4.0` 标签的普通未托管 JSON `quota should-run` 默认使用 `quota_packet`;macOS 桌面 preview 更新前会核对签名归档中的 `default_contract`。 [#8952](https://github.com/loopx-project/loopx/pull/8952), [#9018](https://github.com/loopx-project/loopx/pull/9018), [#9029](https://github.com/loopx-project/loopx/pull/9029), [#9084](https://github.com/loopx-project/loopx/pull/9084) - 用 `loopx authority-archive upgrade --all-known --require-current` 检查旧暂停字段;需要迁移时,获授权的 registry owner 可执行 `loopx authority-archive upgrade --all-known --execute` 并保留返回的备份路径。字段冲突时保持停止,交由 owner 核对。 [#8431](https://github.com/loopx-project/loopx/pull/8431) - 新增独立 `loopx-core` wheel 构建候选(`packages/loopx-core/`),支持无工作台环境的 CLI 与 TS 运行时安装,不改变普通 `loopx` 默认包。 [#8615](https://github.com/loopx-project/loopx/pull/8615), [#8830](https://github.com/loopx-project/loopx/pull/8830), [#8840](https://github.com/loopx-project/loopx/pull/8840) @@ -546,20 +553,20 @@ 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) +**C1 源码检出**的 JSON `quota should-run` 默认交付 `loopx_turn_envelope_v1`,关闭上下文和差分交付时也使用同一契约。移除 `--complete-turn` 和 `--turn-envelope`。普通 CLI 从完整决策读取 `cli_channel.next_cli_actions`。声明 `--runtime-profile generic_cli` 并绑定 Agent、Todo 与 Turn 的 Host 在准入后读取返回的 `quota_settlement_plan_v2`,其 `--settle-turn --settlement-receipt` 步骤沿用原身份。需要私有渐进捕获时,提供新的 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 条件。 -**文档:** [Turn envelope](https://github.com/loopx-project/loopx/blob/v2.4.0/docs/reference/protocols/turn-envelope-v0.md) +**文档:** [当前 Turn envelope](../../reference/protocols/turn-envelope-v0.md) ```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 d78e4444d9..9132cc8865 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 b026a4cbac..461a1dd264 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. @@ -544,14 +544,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 @@ -599,14 +598,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` 是完整契约的兼容别名,已有实验按其记录版本解释。 - -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 guide](https://github.com/loopx-project/loopx/blob/main/benchmark/runtime/RUNTIME.md) -for supported configurations. +历史 Short 使用曾交付 v0 的产品与 runner 版本,并保留原请求与捕获。 + +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](https://github.com/loopx-project/loopx/blob/main/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 4c092776d9..4004fae4b1 100644 --- a/docs/reference/required-work-context.md +++ b/docs/reference/required-work-context.md @@ -541,9 +541,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 @@ -1192,8 +1191,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/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/public_default_contract.json b/loopx/cli_commands/public_default_contract.json index c3b629697a..0578c709de 100644 --- a/loopx/cli_commands/public_default_contract.json +++ b/loopx/cli_commands/public_default_contract.json @@ -1,15 +1,13 @@ { - "publication_surface": "quota_packet", - "readable_contracts": [ - { - "surface": "quota_packet", - "schema_version": null, - "interaction_schema_version": "loopx_interaction_contract_v0" - }, - { - "surface": "complete_turn", - "schema_version": "loopx_turn_envelope_v1", - "interaction_schema_version": "loopx_interaction_contract_v0" - } - ] + "current": { + "surface": "complete_turn", + "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0" + }, + "public_channel": "historical", + "historical": { + "surface": "quota_packet", + "schema_version": null, + "interaction_schema_version": "loopx_interaction_contract_v0" + } } 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 6f67d1a7b9..a9bcf9c962 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 5e12999cfe..d7f771bcf8 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)} @@ -531,9 +531,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_presentation.py b/loopx/cli_commands/quota_presentation.py index daf39dadbf..2d2d95abea 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..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=( - "Select the complete v1 work contract for quota should-run. " - "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 " - "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/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 01c8519a82..f24ac07589 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -25,7 +25,6 @@ iter_rollout_events, rollout_event_log_path, ) -from .quota_presentation import is_undeclared_json_quota_caller if TYPE_CHECKING: from .quota_action_selection import RequestedQuotaActionSelection @@ -58,9 +57,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)) @@ -103,10 +100,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( @@ -443,10 +437,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/cli_commands/support_control_heartbeat.py b/loopx/cli_commands/support_control_heartbeat.py index 7997f75158..2e73a2e010 100644 --- a/loopx/cli_commands/support_control_heartbeat.py +++ b/loopx/cli_commands/support_control_heartbeat.py @@ -246,8 +246,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 7f218d3d1c..d1c3bdc485 100644 --- a/loopx/cli_commands/support_control_heartbeat_registration.py +++ b/loopx/cli_commands/support_control_heartbeat_registration.py @@ -170,16 +170,11 @@ 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.") + # Saved App loaders can run before the new prompt is written back. + # These spellings are accepted only at the loader boundary and select no writer. + legacy_loader = heartbeat_prompt_parser.add_mutually_exclusive_group() + for flag in ("--turn-envelope", "--complete-turn"): + legacy_loader.add_argument(flag, action="store_true", help=argparse.SUPPRESS) heartbeat_prompt_parser.add_argument( "--decision-handoff-socket", diff --git a/loopx/cli_commands/update_artifact.py b/loopx/cli_commands/update_artifact.py index 24fc9418fa..deec10cf80 100644 --- a/loopx/cli_commands/update_artifact.py +++ b/loopx/cli_commands/update_artifact.py @@ -31,14 +31,12 @@ from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN as REPOSITORY_PATTERN RUNTIME_ARTIFACT_SCHEMA_VERSION = "loopx_runtime_artifact_v1" -_ARTIFACT_CONTRACT_POLICY = json.loads( +QUALIFIED_DEFAULT_CONTRACT_FIELD = "qualified_default_contract" +_ARTIFACT_DEFAULT_CONTRACTS = json.loads( Path(__file__).with_name("public_default_contract.json").read_text(encoding="utf-8") ) -_READABLE_DEFAULT_CONTRACTS = _ARTIFACT_CONTRACT_POLICY["readable_contracts"] -PUBLIC_DEFAULT_CONTRACT, = ( - contract for contract in _READABLE_DEFAULT_CONTRACTS - if contract["surface"] == _ARTIFACT_CONTRACT_POLICY["publication_surface"] -) +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 @@ -69,11 +67,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("\n_ARTIFACT_CONTRACT_POLICY = ") - binding_end = source.index("\n_READABLE_DEFAULT_CONTRACTS = ", binding_start) + binding_start = source.index("\n_ARTIFACT_DEFAULT_CONTRACTS = ") + binding_end = source.index("\nPUBLIC_DEFAULT_CONTRACT = ", binding_start) return ( source[:binding_start] - + f"\n_ARTIFACT_CONTRACT_POLICY = {_ARTIFACT_CONTRACT_POLICY!r}" + + f"\n_ARTIFACT_DEFAULT_CONTRACTS = {_ARTIFACT_DEFAULT_CONTRACTS!r}" + source[binding_end:] ) @@ -113,17 +111,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) @@ -146,13 +138,58 @@ 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) - # Readers can cross a version boundary in either direction. Publication - # still checks the observed writer against the single declared default. - if "default_contract" in value: - contract = value["default_contract"] - if not isinstance(contract, dict) or contract not in _READABLE_DEFAULT_CONTRACTS: - raise ValueError("Unsupported runtime default contract in artifact metadata") - return dict(value) + manifest = dict(value) + if QUALIFIED_DEFAULT_CONTRACT_FIELD in manifest: + if "default_contract" in manifest: + raise ValueError("Runtime artifact declares two default contracts") + # The v1 manifest reserves default_contract for old readers' known + # profile. New readers normalize the publication attestation so the + # existing archive identity comparison still binds the exact contract. + manifest["default_contract"] = validate_default_contract( + manifest.pop(QUALIFIED_DEFAULT_CONTRACT_FIELD) + ) + elif "default_contract" in manifest and manifest["default_contract"] != HISTORICAL_DEFAULT_CONTRACT: + validate_default_contract(manifest["default_contract"]) + return manifest + + +def validate_published_manifest(value: dict[str, Any]) -> dict[str, Any]: + """Require the compatible, qualified descriptor before publishing a new archive.""" + if not isinstance(value, dict) or QUALIFIED_DEFAULT_CONTRACT_FIELD not in value: + raise ValueError("Runtime publication requires a qualified default contract attestation") + return validate_manifest(value) + + +def public_channel_allows_default(observed: dict[str, Any]) -> bool: + """Check the reviewed release profile independently of archive qualification.""" + approved = _ARTIFACT_DEFAULT_CONTRACTS["public_channel"] + if approved not in ("current", "historical"): + raise ValueError("Unknown public channel default contract") + return bool(observed == _ARTIFACT_DEFAULT_CONTRACTS[approved]) + + +def verify_runtime_installation_qualification( + manifest: dict[str, Any], qualification: dict[str, Any], archive: Path, *, channel: str, +) -> None: + checks = ( + "ok", "clean_install", "upgrade", "doctor", "skills", "frontend_bundle_contract", + "frontend_http", "no_frontend_build_tools", "license_notices", "activation_failure_restored", + ) + if not isinstance(qualification, dict) or any(qualification.get(check) is not True for check in checks): + raise ValueError("Runtime installation qualification is missing or failed") + if manifest.get("default_contract") is None or qualification.get("default_contract") != manifest["default_contract"]: + raise ValueError("Runtime default-contract qualification is missing or mismatched") + if manifest.get("channel") != channel or any( + qualification.get(key) != manifest[key] for key in ("source_revision", "channel", "sha256") + ): + raise ValueError("Runtime qualification does not match the candidate") + if ( + type(qualification.get("bytes")) is not int + or qualification["bytes"] != manifest["size"] + or archive.stat().st_size != manifest["size"] + or file_hash(archive) != manifest["sha256"] + ): + raise ValueError("Qualified runtime bytes differ from the candidate") def resolve_artifact(repo: str, ref: str) -> dict[str, Any]: diff --git a/loopx/control_plane/heartbeat/builder.py b/loopx/control_plane/heartbeat/builder.py index 658efa793e..e2f1e0f8cb 100644 --- a/loopx/control_plane/heartbeat/builder.py +++ b/loopx/control_plane/heartbeat/builder.py @@ -389,8 +389,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 @@ -462,8 +460,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 89ac221b86..20c3995eda 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", @@ -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,20 +462,22 @@ 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", - # 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", ), 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", @@ -486,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/control_plane/testing/cli_output_differential.py b/loopx/control_plane/testing/cli_output_differential.py index cd34e1c428..e27017ec77 100644 --- a/loopx/control_plane/testing/cli_output_differential.py +++ b/loopx/control_plane/testing/cli_output_differential.py @@ -744,8 +744,10 @@ def _complete_quota_source_migration(base: dict[str, Any], candidate: dict[str, } scenario, output_format = base.get("scenario"), base.get("format") variant = base.get("variant_id") - legacy = variant in aliases - allowed_variant = variant in variants or (legacy and output_format in aliases[variant]) + alias_variant = isinstance(variant, str) and variant in aliases and output_format in aliases[variant] + source_schema = (base.get("quota_controls") or {}).get("source_schema") + legacy = alias_variant and source_schema == "loopx_turn_envelope_v0" + allowed_variant = variant in variants or alias_variant policy = "explicit_opt_in_cold_path" if variant else "absolute_hot_path" row = (f"variant/{variant}/{scenario}/{output_format}" if variant else f"surface/quota_should_run/{scenario}/{output_format}") @@ -767,7 +769,7 @@ def _complete_quota_source_migration(base: dict[str, Any], candidate: dict[str, and candidate.get("markdown_anchor") == "# LoopX Turn Envelope" and _matching_quota_controls(base, candidate)): return False - return (base["quota_controls"].get("source_schema") == ("loopx_turn_envelope_v0" if legacy else None) + return (source_schema == ("loopx_turn_envelope_v0" if legacy else None) and candidate["quota_controls"].get("source_schema") == "loopx_turn_envelope_v1") diff --git a/loopx/control_plane/turn_driver/codex_context.py b/loopx/control_plane/turn_driver/codex_context.py index dc6007ea6e..00104f8648 100644 --- a/loopx/control_plane/turn_driver/codex_context.py +++ b/loopx/control_plane/turn_driver/codex_context.py @@ -349,11 +349,17 @@ def codex_context_configuration(directory: str, *, goal_id: str, agent_id: str, *(["--codex-app"] if scenario == "codex_app_heartbeat" else ["--runtime-profile", "codex_app_ssh_goal" if scenario == "codex_app_ssh_goal" else "generic_cli"]), option, directory]), "timeout": 10} + config_overrides = { + "tool_output_token_limit": NATIVE_CONTEXT_HISTORY_TOKENS, + "shell_environment_policy.set." + NATIVE_CONTEXT_OUTPUT_ENV: str(NATIVE_CONTEXT_LARGE_OUTPUT_BYTES), + } + # The App shell sandbox can deny even loopback TCP. Use the existing local + # pipe transport for POSIX App shell calls without opening sandbox networking. + if scenario == "codex_app_heartbeat" and os.name == "posix": + config_overrides["shell_environment_policy.set.LOOPX_EFFECT_RUNTIME_TRANSPORT"] = "stdio" # Native Interrupt handlers have a 3s ceiling. Declare the effective value # rather than letting discovery silently clamp a different configuration. - return {"config_overrides": { - "tool_output_token_limit": NATIVE_CONTEXT_HISTORY_TOKENS, - "shell_environment_policy.set." + NATIVE_CONTEXT_OUTPUT_ENV: str(NATIVE_CONTEXT_LARGE_OUTPUT_BYTES)}, + return {"config_overrides": config_overrides, "hooks": {event: [{**({"matcher": "^Bash$"} if event == "PostToolUse" else {}), "hooks": [{**handler, "timeout": 3} if event == "Interrupt" else handler]}] for event in CONTEXT_LIFECYCLE_HOOKS}, diff --git a/loopx/hosts/codex_checkpoint.py b/loopx/hosts/codex_checkpoint.py index 20b42dd56a..5b9626abb8 100644 --- a/loopx/hosts/codex_checkpoint.py +++ b/loopx/hosts/codex_checkpoint.py @@ -323,17 +323,25 @@ def request(method, params): def _guard_cli_arguments(command: str, guard: dict) -> list[str]: - """Parse the provider shell wrapper plus the renderer's optional Turn assignment.""" + """Parse the provider shell wrapper plus the renderer's optional Turn assignment and prequota.""" outer = shlex.split(command) if len(outer) != 3 or Path(outer[0]).name not in {"bash", "zsh", "sh"} or outer[1] != "-lc": raise ValueError("native pending guard is not a supported single shell command") lines = outer[2].strip().splitlines() - if len(lines) == 2 and shlex.split(lines[0]) == ["LOOPX_TURN=" + guard["turn_instance_id"]]: - script = lines[1].replace('"${LOOPX_TURN:?}"', shlex.quote(guard["turn_instance_id"])) - elif len(lines) == 1: - script = lines[0] + has_turn_var = bool(lines) and shlex.split(lines[0]) == ["LOOPX_TURN=" + guard["turn_instance_id"]] + rest = lines[1:] if has_turn_var else lines + prequota_line = None + if len(rest) == 2: + prequota_line, raw_script = rest + elif len(rest) == 1: + raw_script = rest[0] else: raise ValueError("native pending guard contains an unsupported shell program") + script = ( + raw_script.replace('"${LOOPX_TURN:?}"', shlex.quote(guard["turn_instance_id"])) + if has_turn_var + else raw_script + ) # Conservative provider syntax profile, not Goal/state classification. # Only the exact renderer assignment above is expanded; never execute shell. if not re.fullmatch(r"[A-Za-z0-9_./:=+@ '\"-]+", script): @@ -341,6 +349,28 @@ def _guard_cli_arguments(command: str, guard: dict) -> list[str]: argv = shlex.split(script) if not argv or argv[0] != guard["cli"]: raise ValueError("native pending guard executable differs") + if prequota_line is not None: + from loopx.cli import build_parser + + if not re.fullmatch(r"[A-Za-z0-9_./:=+@ '\"-]+", prequota_line): + raise ValueError("native pending guard contains unsupported shell syntax") + pre_argv = shlex.split(prequota_line) + if not pre_argv or pre_argv[0] != guard["cli"]: + raise ValueError("native pending guard executable differs") + parser = build_parser() + retired = {"--turn-envelope", "--complete-turn"} + quota_clean = [word for word in argv[1:] if word not in retired] + try: + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + pre_parsed = vars(parser.parse_args(pre_argv[1:])) + quota_parsed = vars(parser.parse_args(quota_clean)) + except SystemExit as error: + raise ValueError("native pending guard contains an unsupported shell program") from error + if pre_parsed.get("command") != "heartbeat-prequota": + raise ValueError("native pending guard contains an unsupported shell program") + for route_key in ("registry", "runtime_root", "goal_id", "agent_id", "control_cli_bin"): + if pre_parsed.get(route_key) != quota_parsed.get(route_key): + raise ValueError("native pending guard prequota route differs from held guard") return argv[1:] @@ -364,11 +394,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/scripts/qualify_runtime_artifact.py b/scripts/qualify_runtime_artifact.py index a8dc69b564..c907b7c7d3 100644 --- a/scripts/qualify_runtime_artifact.py +++ b/scripts/qualify_runtime_artifact.py @@ -13,14 +13,19 @@ import tempfile sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from loopx.cli_commands.update_artifact import extract_artifact, file_hash, validate_default_contract, validate_manifest +from loopx.cli_commands.update_artifact import ( + extract_artifact, + file_hash, + validate_default_contract, + validate_published_manifest, +) 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: @@ -63,7 +68,7 @@ def observe_default_contract(source: Path) -> dict: def qualify(directory: Path) -> dict: - manifest = validate_manifest(json.loads((directory / "loopx-runtime.json").read_text())) + manifest = validate_published_manifest(json.loads((directory / "loopx-runtime.json").read_text())) archive = directory / f"loopx-runtime-{manifest['source_revision']}.tar.gz" assert archive.stat().st_size == manifest["size"] and file_hash(archive) == manifest["sha256"] with tempfile.TemporaryDirectory(prefix="loopx-runtime-qualification-") as raw: diff --git a/scripts/release_artifacts.py b/scripts/release_artifacts.py index f328aa28e5..281e0dc7c0 100644 --- a/scripts/release_artifacts.py +++ b/scripts/release_artifacts.py @@ -199,22 +199,57 @@ def publication_files(dist_dir: Path, identity: ReleaseIdentity) -> tuple[Path, return tuple(files) -def upload_immutable(dist_dir: Path, identity: ReleaseIdentity, repo: str, - *, recover: bool = False, dry_run: bool = False) -> None: - files = publication_files(dist_dir, identity) - if recover: - commit = gh("api", f"repos/{repo}/commits/{identity.tag}", "--jq", ".sha").decode().strip() - sources = json.loads((dist_dir / "RELEASE-SOURCES.json").read_text()) - if sources["product_tag"] != identity.tag or sources["product_commit"] != commit: - raise ReleaseArtifactError("bundle product identity differs from the release tag") - for path in files: - gh("attestation", "verify", str(path), "--repo", repo, - "--signer-workflow", f"{repo}/.github/workflows/release-artifacts.yml", - "--source-digest", commit, "--source-ref", f"refs/tags/{identity.tag}", - "--deny-self-hosted-runners") - release = json.loads(gh("api", f"repos/{repo}/releases/tags/{identity.tag}")) +def require_stable_runtime_publication(dist_dir: Path, identity: ReleaseIdentity) -> None: + # Resolve the policy from the reviewed publication tooling. The selected tag + # supplies data and attested bytes, while package identity stays a static read. + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + try: + from loopx.cli_commands.update_artifact import ( + HISTORICAL_DEFAULT_CONTRACT, + public_channel_allows_default, + validate_published_manifest, + validate_manifest, + verify_runtime_installation_qualification, + ) + finally: + sys.path.pop(0) + + runtime = dist_dir / "runtime" + try: + raw = json.loads((runtime / "loopx-runtime.json").read_text(encoding="utf-8")) + if isinstance(raw, dict) and raw.get("default_contract") == HISTORICAL_DEFAULT_CONTRACT: + manifest = validate_manifest(raw) + else: + manifest = validate_published_manifest(raw) + sources = json.loads((dist_dir / "RELEASE-SOURCES.json").read_text(encoding="utf-8")) + revision = manifest["source_revision"] + if ( + not isinstance(sources, dict) + or sources.get("product_tag") != identity.tag + or sources.get("product_commit") != revision + or manifest["package_version"] != identity.version + ): + raise ValueError("Bundle product identity differs from the stable runtime") + qualification = json.loads((runtime / "qualification.json").read_text(encoding="utf-8")) + archive = runtime / f"loopx-runtime-{revision}.tar.gz" + verify_runtime_installation_qualification(manifest, qualification, archive, channel="stable") + if not public_channel_allows_default(manifest["default_contract"]): + raise ValueError("Stable runtime is pending public channel qualification") + except (OSError, ValueError) as exc: + raise ReleaseArtifactError(str(exc)) from exc + + +def require_release_commit(dist_dir: Path, identity: ReleaseIdentity, repo: str) -> str: + commit = gh("api", f"repos/{repo}/commits/{identity.tag}", "--jq", ".sha").decode().strip() + sources = json.loads((dist_dir / "RELEASE-SOURCES.json").read_text(encoding="utf-8")) + if sources["product_tag"] != identity.tag or sources["product_commit"] != commit: + raise ReleaseArtifactError("bundle product identity differs from the release tag") + return commit + + +def missing_release_assets(repo: str, release_id: int, files: tuple[Path, ...]) -> list[Path]: assets = json.loads(gh("api", "--paginate", "--slurp", - f"repos/{repo}/releases/{release['id']}/assets?per_page=100")) + f"repos/{repo}/releases/{release_id}/assets?per_page=100")) remote = {} for asset in (asset for page in assets for asset in page): key = asset["name"].casefold() @@ -238,12 +273,56 @@ def upload_immutable(dist_dir: Path, identity: ReleaseIdentity, repo: str, actual = hashlib.file_digest(downloaded, "sha256").hexdigest() if asset["size"] != path.stat().st_size or actual != sha256(path): raise ReleaseArtifactError(f"immutable release asset differs: {path.name}") + return missing + + +def upload_immutable(dist_dir: Path, identity: ReleaseIdentity, repo: str, + *, recover: bool = False, dry_run: bool = False) -> None: + files = publication_files(dist_dir, identity) + require_stable_runtime_publication(dist_dir, identity) + if recover: + commit = require_release_commit(dist_dir, identity, repo) + for path in files: + gh("attestation", "verify", str(path), "--repo", repo, + "--signer-workflow", f"{repo}/.github/workflows/release-artifacts.yml", + "--source-digest", commit, "--source-ref", f"refs/tags/{identity.tag}", + "--deny-self-hosted-runners") + release = json.loads(gh("api", f"repos/{repo}/releases/tags/{identity.tag}")) + missing = missing_release_assets(repo, release["id"], files) if missing and not dry_run: gh("release", "upload", identity.tag, *(str(path) for path in missing), "--repo", repo) print(f"verified {len(files) - len(missing)} existing assets; " f"{'would upload' if dry_run else 'uploaded'} {len(missing)} missing assets") +def create_named_release(identity: ReleaseIdentity, repo: str, notes_file: Path, title: str) -> None: + # release:published starts artifact production. Keep the old stable + # endpoint serving a complete release while the new bundle is being built. + gh("release", "create", identity.tag, "--repo", repo, "--verify-tag", + "--latest=false", "--notes-file", str(notes_file), "--title", title) + + +def promote_latest(dist_dir: Path, identity: ReleaseIdentity, repo: str, *, execute: bool) -> None: + files = publication_files(dist_dir, identity) + require_stable_runtime_publication(dist_dir, identity) + require_release_commit(dist_dir, identity, repo) + release = json.loads(gh("api", f"repos/{repo}/releases/tags/{identity.tag}")) + if (release.get("tag_name") != identity.tag + or release.get("draft") is not False or release.get("prerelease") is not False): + raise ReleaseArtifactError("Latest requires the exact published named release") + if missing := missing_release_assets(repo, release["id"], files): + names = ", ".join(path.name for path in missing) + raise ReleaseArtifactError(f"cannot promote Latest with missing assets: {names}") + if not execute: + print(f"verified {len(files)} published assets for {identity.tag}; ready for Latest") + return + gh("api", "--method", "PATCH", f"repos/{repo}/releases/{release['id']}", "-f", "make_latest=true") + latest = json.loads(gh("api", f"repos/{repo}/releases/latest")) + if latest.get("id") != release["id"] or latest.get("tag_name") != identity.tag: + raise ReleaseArtifactError("Latest readback differs from the verified release") + print(f"verified GitHub Latest points to {identity.tag}") + + def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--project-root", type=Path, default=Path.cwd()) @@ -269,11 +348,24 @@ def build_parser() -> argparse.ArgumentParser: recovery.add_argument("--repo", required=True) recovery.add_argument("--run-id", required=True) recovery.add_argument("--commit", required=True) + stable = subparsers.add_parser("check-stable-runtime", help="check the tagged bundle before making it the stable default") + stable.add_argument("--dist-dir", type=Path, required=True) + upload = subparsers.add_parser("upload-immutable", help="resume publication without replacing existing bytes") upload.add_argument("--repo", required=True) upload.add_argument("--dist-dir", type=Path, required=True) upload.add_argument("--recover", action="store_true") upload.add_argument("--dry-run", action="store_true") + + create = subparsers.add_parser("create-named-release", help="publish the existing tag without changing Latest") + create.add_argument("--repo", required=True) + create.add_argument("--notes-file", type=Path, required=True) + create.add_argument("--title", required=True) + + promote = subparsers.add_parser("promote-latest", help="verify the published bundle before moving GitHub Latest") + promote.add_argument("--repo", required=True) + promote.add_argument("--dist-dir", type=Path, required=True) + promote.add_argument("--execute", action="store_true", help="move Latest after successful asset readback") return parser @@ -298,9 +390,17 @@ def main(argv: list[str] | None = None) -> int: verify_manifest(args.dist_dir, args.checksum_file, identity) elif args.command == "verify-publication-run": verify_publication_run(args.repo, args.run_id, identity.tag, args.commit) + elif args.command == "check-stable-runtime": + publication_files(args.dist_dir, identity) + require_stable_runtime_publication(args.dist_dir, identity) + print(f"verified stable runtime publication policy for {identity.tag}") elif args.command == "upload-immutable": upload_immutable(args.dist_dir, identity, args.repo, recover=args.recover, dry_run=args.dry_run) + elif args.command == "create-named-release": + create_named_release(identity, args.repo, args.notes_file, args.title) + elif args.command == "promote-latest": + promote_latest(args.dist_dir, identity, args.repo, execute=args.execute) else: parser.error(f"unsupported command: {args.command}") except ReleaseArtifactError as exc: diff --git a/scripts/runtime_artifact.py b/scripts/runtime_artifact.py index 5097b35f88..05c964fbc3 100644 --- a/scripts/runtime_artifact.py +++ b/scripts/runtime_artifact.py @@ -25,10 +25,11 @@ sys.path.insert(0, str(ROOT)) from loopx.presentation.chat_bundle import source_digest, validate_bundle # noqa: E402 from loopx.cli_commands.update_artifact import ( # noqa: E402 + QUALIFIED_DEFAULT_CONTRACT_FIELD, RUNTIME_ARTIFACT_SCHEMA_VERSION, extract_artifact, validate_default_contract, - validate_manifest, + validate_published_manifest, ) from scripts.qualify_runtime_artifact import observe_default_contract # noqa: E402 @@ -128,14 +129,15 @@ def build(root: Path, output: Path, *, repository: str, channel: str) -> dict: raise ValueError("Git runtime archive failed") tag = f"runtime-main-{revision}" if channel == "main" else "v" + version archive = output / filename - result = validate_manifest({"schema_version": RUNTIME_ARTIFACT_SCHEMA_VERSION, "source_revision": revision, + published = {"schema_version": RUNTIME_ARTIFACT_SCHEMA_VERSION, "source_revision": revision, "package_version": version, "channel": channel, "size": archive.stat().st_size, - "default_contract": default_contract, + QUALIFIED_DEFAULT_CONTRACT_FIELD: default_contract, "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(), "urls": [f"https://github.com/{repository}/releases/download/{tag}/{filename}"], "resources": {"filename": optional_name, "size": (output / optional_name).stat().st_size, - "sha256": hashlib.sha256((output / optional_name).read_bytes()).hexdigest()}}) - (output / "loopx-runtime.json").write_text(json.dumps(result, indent=2) + "\n") + "sha256": hashlib.sha256((output / optional_name).read_bytes()).hexdigest()}} + result = validate_published_manifest(published) + (output / "loopx-runtime.json").write_text(json.dumps(published, indent=2) + "\n") (output / "runtime-inventory.json").write_text(json.dumps(inventory, indent=2) + "\n") print(json.dumps({"revision": revision, "runtime_bytes": result["size"], "optional_bytes": result["resources"]["size"], 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_automation_prompt_upgrade.py b/tests/control_plane/test_automation_prompt_upgrade.py index 7999c97f37..54f1ffbdc1 100644 --- a/tests/control_plane/test_automation_prompt_upgrade.py +++ b/tests/control_plane/test_automation_prompt_upgrade.py @@ -492,22 +492,40 @@ def fail_mirror(target, text): assert upgrade.recover_offline(home=home, automation_id="watch")["status"] == "recovered" -def test_running_app_defers_to_native_api_without_touching_cached_scheduler(tmp_path, monkeypatch): +@pytest.mark.parametrize("saved_alias", [None, "--turn-envelope", "--complete-turn"]) +def test_running_app_defers_to_native_api_without_touching_cached_scheduler(tmp_path, monkeypatch, saved_alias): from loopx.control_plane.heartbeat import installed_prompt_update as lifecycle home, path, database, registry, _ = fixture(tmp_path) prompt = upgrade.bootstrap_prompt(registry=registry, goal_id="fixture-goal", agent_id="agent-a") - legacy = prompt.replace(upgrade.BOOTSTRAP, upgrade._LEGACY_BOOTSTRAP, 1).removesuffix( - upgrade._BOOTSTRAP_INSTRUCTION) + upgrade._LEGACY_INSTRUCTION + if saved_alias is None: + legacy = prompt.replace(upgrade.BOOTSTRAP, upgrade._LEGACY_BOOTSTRAP, 1).removesuffix( + upgrade._BOOTSTRAP_INSTRUCTION) + upgrade._LEGACY_INSTRUCTION + else: + from loopx.control_plane.testing.terminal_settlement_tool_behavior import ( + TERMINAL_SETTLEMENT_FIXTURE_AGENT_ID, + TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID, + _build_fixture, + ) + + managed = _build_fixture(tmp_path / "managed-goal") + registry = managed.global_registry_path + goal_id = TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID + command = ["loopx", "--format", "json", "--registry", str(registry), + "heartbeat-prompt", "--thin", "--codex-app", "--goal-id", goal_id, + "--agent-id", TERMINAL_SETTLEMENT_FIXTURE_AGENT_ID, + "--context-delivery", "off", saved_alias] + legacy = ("LoopX managed heartbeat bootstrap v2\n每次唤醒先执行:\n```sh\n" + + shlex.join(command) + "\n```\n" + _PUBLISHED_BOOTSTRAP_INSTRUCTION) _set_fixture_prompt(path, database, legacy) before = lifecycle.snapshot(registry=registry, home=home) - monkeypatch.setattr(lifecycle.sys, "platform", "darwin") probes = [] def running(command, **kwargs): probes.append(command) return subprocess.CompletedProcess(command, 0, stdout=b"123\n") - monkeypatch.setattr(lifecycle.subprocess, "run", running) original = path.read_bytes() - with sqlite3.connect(database) as observer: + with sqlite3.connect(database) as observer, monkeypatch.context() as host: + host.setattr(lifecycle.sys, "platform", "darwin") + host.setattr(lifecycle.subprocess, "run", running) row = observer.execute("SELECT * FROM automations").fetchone() result = lifecycle.reconcile(before=before, registry=registry, home=home) assert not result["ok"] and result["results"][0]["status"] == "deferred" @@ -515,10 +533,36 @@ def running(command, **kwargs): assert path.read_bytes() == original assert probes and all(command[:2] == ["/usr/bin/pgrep", "-x"] for command in probes) request = result["api_updates"][0]["arguments"] - assert request["prompt"] == prompt assert request["id"] == "watch" and request["targetThreadId"] == "thread-a" assert request["status"] == "PAUSED" assert not (home / "loopx-automation-backups").exists() + if saved_alias is None: + assert request["prompt"] == prompt + return + + revised = shlex.split(request["prompt"].split("```sh\n", 1)[1].split("\n```", 1)[0]) + assert saved_alias not in revised + assert revised[revised.index("--context-delivery") + 1] == "off" + saved = tomllib.loads(path.read_text())["prompt"] + unchanged_loader = shlex.split(saved.split("```sh\n", 1)[1].split("\n```", 1)[0]) + assert unchanged_loader == command + monkeypatch.setenv("CODEX_HOME", str(home)) + cli = [sys.executable, "-m", "loopx.entrypoint"] + wake = subprocess.run([*cli, *unchanged_loader[1:]], capture_output=True, text=True, timeout=60) + assert wake.returncode == 0, wake.stdout + wake.stderr + payload = json.loads(wake.stdout) + assert payload["ok"] and payload["schema_version"] == "heartbeat_agent_input_v1" + body = payload["task_body"] + assert "--turn-envelope" not in body and "--complete-turn" not in body + guard = next(line for line in body.splitlines() if " quota should-run " in line) + guard = guard.replace('${LOOPX_TURN:?}', "first-wake-after-upgrade") + guarded = subprocess.run([*cli, *shlex.split(guard)[1:]], capture_output=True, text=True, timeout=60) + assert guarded.returncode == 0, guarded.stdout + guarded.stderr + decision = json.loads(guarded.stdout) + assert decision["ok"] and decision["schema_version"] == "loopx_turn_envelope_v1" + assert decision["goal_id"] == goal_id + assert decision["heartbeat_receipt"]["turn_instance_id"] == "first-wake-after-upgrade" + assert decision["heartbeat_receipt"]["status"] == "committed" def test_concurrent_manifest_change_before_write_is_not_overwritten(tmp_path, monkeypatch): 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 f59b624355..407897146e 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 hashlib import sha256 from pathlib import Path @@ -355,6 +355,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 @@ -367,10 +375,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", @@ -420,7 +425,7 @@ def _surface_commands( GOAL_ID, "--agent-id", AGENT_IDS[0], - ] + quota_view + delivery, + ] + delivery, "loopx_turn_plan": common + [ "turn", @@ -549,7 +554,6 @@ def _mode_variant_commands( registry_path: Path, state_file: Path, output_format: str, - complete_quota: bool = True, ) -> dict[str, list[str]]: common = [ "--registry", @@ -577,7 +581,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": [ @@ -927,8 +930,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"] @@ -1047,7 +1055,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: @@ -1055,22 +1063,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, ) @@ -1089,7 +1096,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, @@ -1097,7 +1103,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) @@ -1105,8 +1110,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"] @@ -1118,18 +1121,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) @@ -1196,7 +1196,7 @@ def test_complete_turn_shares_vision_audit_with_exact_native_and_stateless_reads common = ["--format", "json", "--registry", str(registry), "--runtime-root", str(runtime)] guard = common + ["quota", "should-run", "--goal-id", GOAL_ID, "--agent-id", AGENT_IDS[0]] fixed_route = ["--cli-bin", "/fixture/bin/loopx"] - code, text = _invoke_cli(fixed_route + guard + ["--complete-turn", "--context-delivery", "off"]) + code, text = _invoke_cli(fixed_route + guard + ["--context-delivery", "off"]) assert code == 0, text assert len(text) <= CLI_OUTPUT_MODE_VARIANT_BY_ID["quota_should_run_vision_detail"].max_chars["json"] payload = json.loads(text) @@ -1261,7 +1261,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, @@ -1269,7 +1268,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) @@ -1277,43 +1275,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"] @@ -1355,6 +1337,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( @@ -1544,7 +1538,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, @@ -1552,7 +1545,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) @@ -1564,22 +1556,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] @@ -1602,7 +1591,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, @@ -1610,7 +1598,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) @@ -1624,23 +1611,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] @@ -1670,7 +1648,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"], @@ -1711,7 +1688,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"): @@ -2340,7 +2316,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_cli_output_differential.py b/tests/control_plane/test_cli_output_differential.py index 8be8bb6f35..8241f83daf 100644 --- a/tests/control_plane/test_cli_output_differential.py +++ b/tests/control_plane/test_cli_output_differential.py @@ -182,7 +182,8 @@ def _receipt(*rows: dict[str, object]) -> dict[str, object]: @pytest.mark.parametrize('damage', [None, 'missing', 'changed', 'material', 'unknown', 'later', 'row', 'growth']) -def test_complete_quota_migration_requires_original_controls_and_bounded_scope(tmp_path, damage): +@pytest.mark.parametrize('variant', [None, 'quota_should_run_turn_envelope_blocking_user_gate']) +def test_complete_quota_migration_requires_original_controls_and_bounded_scope(tmp_path, damage, variant): import runpy from pathlib import Path from tests.control_plane import test_cli_output_budget as probe @@ -211,6 +212,9 @@ def test_complete_quota_migration_requires_original_controls_and_bounded_scope(t chars=1000, utf8_bytes=1000, compact_payload_chars=1000, lines=1, semantic_json_keys=['interaction_contract'], markdown_anchor='# LoopX Quota Should Run', projection_envelope_schema_versions=['loopx_projection_envelope_v0'], quota_controls=before) + if variant: + base.update(row_id=f'variant/{variant}/small/json', variant_id=variant, + qualification_policy='explicit_opt_in_cold_path') candidate = {**copy.deepcopy(base), 'chars': 2500, 'utf8_bytes': 2500, 'compact_payload_chars': 2500, 'output_contract_version': 'loopx_turn_envelope_v1', 'markdown_anchor': '# LoopX Turn Envelope', 'quota_controls': after} 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_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_codex_context_lifecycle.py b/tests/control_plane/test_codex_context_lifecycle.py index 8de4e730ec..bd4cea8725 100644 --- a/tests/control_plane/test_codex_context_lifecycle.py +++ b/tests/control_plane/test_codex_context_lifecycle.py @@ -191,9 +191,12 @@ def test_native_configuration_cli_is_read_only_and_usable_without_registry(tmp_p assert "ROLLOUT_TRACE" not in json.dumps(payload) assert "--codex-context-root" in native["developer_instructions"] assert "context-read" in native["developer_instructions"] - assert native["config_overrides"] == { + expected_overrides = { "tool_output_token_limit": 20000, "shell_environment_policy.set.LOOPX_CONTEXT_PAGE_OUTPUT_BYTES": "64000"} + if os.name == "posix": + expected_overrides["shell_environment_policy.set.LOOPX_EFFECT_RUNTIME_TRANSPORT"] = "stdio" + assert native["config_overrides"] == expected_overrides assert "--max-page-output-bytes 64000" in native["developer_instructions"] assert "max_output_tokens=22000" in native["developer_instructions"] assert "max_output_tokens=24000" in native["developer_instructions"] diff --git a/tests/control_plane/test_context_delivery_cli.py b/tests/control_plane/test_context_delivery_cli.py index 72b7a86ff2..d4d02f8c55 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 @@ -525,7 +524,7 @@ def test_c1_work_opening_carries_current_inputs_or_preserves_the_reader(tmp_path delivery = ("--context-delivery", "auto") if case == "stateless_inline" else ( "--context-delivery", "on", "--codex-context-dir", str(native)) rc, view = _run_cli(registry, runtime, "quota", "should-run", "--runtime-profile", "generic_cli", *binding, - "--turn-instance-id", turn, "--decision-output-root", str(captures), "--complete-turn", *delivery, *limit, + "--turn-instance-id", turn, "--decision-output-root", str(captures), *delivery, *limit, cwd=project) assert rc == 0 and view["ok"], view original, = captures.rglob("decision.json") diff --git a/tests/control_plane/test_context_first_read.py b/tests/control_plane/test_context_first_read.py index 7d1e670ff6..422e796db4 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 ebac6cfc95..08253982bb 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..52c991b414 100644 --- a/tests/control_plane/test_heartbeat_cli.py +++ b/tests/control_plane/test_heartbeat_cli.py @@ -16,6 +16,7 @@ (["heartbeat-prompt", "--goal-id"], 2), (["heartbeat-prompt", "--goal", "fixture"], 2), (["heartbeat-prompt", "--goal-id=fixture", "--unknown"], 2), + (["heartbeat-prompt", "--goal-id=fixture", "--turn-envelope", "--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 +70,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..514972bf74 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 @@ -364,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', @@ -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_heartbeat_notification_rule.py b/tests/control_plane/test_heartbeat_notification_rule.py index a97c336a59..183fbebe34 100644 --- a/tests/control_plane/test_heartbeat_notification_rule.py +++ b/tests/control_plane/test_heartbeat_notification_rule.py @@ -97,8 +97,7 @@ def test_rendered_task_bodies_keep_execution_obligation_authority() -> None: def test_codex_app_quiet_completion_is_host_control_not_chat(tmp_path) -> None: variants = [{mode: True} for mode in ("full", "compact", "brief", "thin")] variants.append({ - "thin": True, "turn_envelope": True, - "decision_output_root": tmp_path, "turn_instance_id": "fixture-quiet-turn", + "thin": True, "decision_output_root": tmp_path, "turn_instance_id": "fixture-quiet-turn", }) for variant in variants: body = build_heartbeat_prompt( @@ -129,10 +128,9 @@ def test_all_heartbeat_modes_scope_no_spend_to_observation() -> None: def test_todo_closeout_does_not_invent_successors_or_skip_turn_settlement(tmp_path) -> None: # A completed Todo and an external wait are distinct from Goal termination. - # Even the captured-envelope carrier must defer to the admitted current plan. + # The captured thin prompt also defers to the admitted current plan. variants = [{mode: True} for mode in ("full", "compact", "brief", "thin")] - variants.append({"thin": True, "turn_envelope": True, - "decision_output_root": tmp_path, + variants.append({"thin": True, "decision_output_root": tmp_path, "turn_instance_id": "fixture-closeout-turn"}) for variant in variants: body = build_heartbeat_prompt( diff --git a/tests/control_plane/test_heartbeat_prompt_support.py b/tests/control_plane/test_heartbeat_prompt_support.py index 72e11f8d51..1861185b65 100644 --- a/tests/control_plane/test_heartbeat_prompt_support.py +++ b/tests/control_plane/test_heartbeat_prompt_support.py @@ -456,11 +456,11 @@ def test_heartbeat_scopes_project_skill_to_material_changes(mode: str) -> None: assert obligation in body, obligation -@pytest.mark.parametrize("mode", ["full", "compact", "brief", "thin", "envelope"]) +@pytest.mark.parametrize("mode", ["full", "compact", "brief", "thin", "captured_thin"]) @pytest.mark.parametrize("profile", ["generic_cli", "codex_app_heartbeat"]) def test_timed_wait_guidance_survives_prompt_compaction(mode: str, profile: str, tmp_path: Path) -> None: - options = ({"thin": True, "turn_envelope": True, "decision_output_root": tmp_path, - "turn_instance_id": "timed-wait-turn"} if mode == "envelope" else {mode: True}) + options = ({"thin": True, "decision_output_root": tmp_path, "turn_instance_id": "timed-wait-turn"} + if mode == "captured_thin" else {mode: True}) payload = build_heartbeat_prompt(goal_id="timed-wait-fixture", agent_id="agent-wait", runtime_profile=profile, **options) body = payload["task_body"] diff --git a/tests/control_plane/test_monitor_due_requeue.py b/tests/control_plane/test_monitor_due_requeue.py index 581482b07e..4718a8c96b 100644 --- a/tests/control_plane/test_monitor_due_requeue.py +++ b/tests/control_plane/test_monitor_due_requeue.py @@ -87,12 +87,12 @@ def call(*args): assert not any(row["classification"] in {"quota_slot_spent", "state_refreshed"} for row in rows) -@pytest.mark.parametrize("mode", ["full", "compact", "brief", "thin", "envelope"]) +@pytest.mark.parametrize("mode", ["full", "compact", "brief", "thin", "captured_thin"]) def test_common_prompt_retains_settlement_and_defers_monitor_details(mode, tmp_path): from loopx.heartbeat_prompt import build_heartbeat_prompt - options = ({"thin": True, "turn_envelope": True, "decision_output_root": tmp_path} - if mode == "envelope" else {mode: True}) + options = ({"thin": True, "decision_output_root": tmp_path} + if mode == "captured_thin" else {mode: True}) prompt = build_heartbeat_prompt(goal_id=GOAL_ID, agent_id=AGENT_ID, runtime_profile="generic_cli", turn_instance_id="prompt-turn", **options) body = prompt["task_body"] 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 fef4830a55..99f42db8c9 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) @@ -955,9 +953,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 @@ -990,8 +987,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 05c219eb46..8b690951f9 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 8bac4b5104..cbd326505f 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 7e377791e9..99dd86b8ed 100644 --- a/tests/control_plane/test_replan_staged_read.py +++ b/tests/control_plane/test_replan_staged_read.py @@ -433,15 +433,14 @@ def test_review_retains_scoped_dependencies_and_unknown_outcomes(): @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("explicit_envelope", [False, True]) -def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, monkeypatch, provider, explicit_envelope): +def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, monkeypatch, provider): from loopx.control_plane.quota.turn_envelope import project_captured_replan_cli_view isolate_sqlite_runtime(tmp_path, monkeypatch) fixture = make_progress_cli_fixture(tmp_path, provider, "advanced") enable_explore(fixture) capture = tmp_path / "capture" - host = ["--codex-app", *(["--turn-envelope"] if explicit_envelope else [])] + host = ["--codex-app"] try: initial = call_progress_cli(fixture, "quota", "should-run", *host, "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", TURN) @@ -455,8 +454,7 @@ def test_real_guard_capture_read_and_writeback_without_another_guard(tmp_path, m source_path = capture / "decision.json" saved = source_path.read_bytes() source = json.loads(saved) - # Both Codex App declarations return the signed decision. Verify that - # binding before asking the existing reader owner for its staged view. + # Verify the bound Complete Turn before reading its staged view. assert guard["schema_version"] == "loopx_turn_envelope_v1" assert guard["contract_binding"] == source["contract_binding"] assert guard["interaction_contract"]["cli_channel"] == source["interaction_contract"]["cli_channel"] diff --git a/tests/control_plane/test_replan_successor_guard_reentry.py b/tests/control_plane/test_replan_successor_guard_reentry.py index 6817cc1fda..a09f36c1c9 100644 --- a/tests/control_plane/test_replan_successor_guard_reentry.py +++ b/tests/control_plane/test_replan_successor_guard_reentry.py @@ -457,7 +457,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"] @@ -486,7 +486,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_research_checkpoint_capture.py b/tests/control_plane/test_research_checkpoint_capture.py index 4aace9fa22..54435954f6 100644 --- a/tests/control_plane/test_research_checkpoint_capture.py +++ b/tests/control_plane/test_research_checkpoint_capture.py @@ -113,8 +113,7 @@ def observe_guard(argv, **kwargs): @pytest.mark.skipif(os.name != "posix", reason="benchmark uses the POSIX source launcher") @pytest.mark.parametrize("provider", ["file", "sqlite"]) -@pytest.mark.parametrize("complete", [False, True]) -def test_off_preflight_pages_the_complete_saved_view(tmp_path, monkeypatch, provider, complete): +def test_off_preflight_pages_the_complete_saved_view(tmp_path, monkeypatch, provider): import shlex import subprocess import sys @@ -133,8 +132,7 @@ def test_off_preflight_pages_the_complete_saved_view(tmp_path, monkeypatch, prov env = {**os.environ, "LOOPX_PROJECT": str(project), "LOOPX_CLI": str(cli_path), "LOOPX_PYTHON": sys.executable, "LOOPX_REGISTRY": str(registry), "LOOPX_RUNTIME_ROOT": str(runtime), "LOOPX_GOAL_ID": cli.GOAL_ID, "LOOPX_AGENT_ID": cli.AGENT_ID, "LOOPX_WAKE_LOG_DIR": str(wake.parent), - "LOOPX_CHECKPOINT_REQUEST": str(request), "LOOPX_CONTEXT_DELIVERY": "off", - "LOOPX_COMPLETE_TURN": str(int(complete))} + "LOOPX_CHECKPOINT_REQUEST": str(request), "LOOPX_CONTEXT_DELIVERY": "off"} receipt = {"turn_id": turn, "mode": "heartbeat", "stage": "execute"} def start_read(): diff --git a/tests/control_plane/test_saved_context_project.py b/tests/control_plane/test_saved_context_project.py index fd6b0f48c5..bb58bf944f 100644 --- a/tests/control_plane/test_saved_context_project.py +++ b/tests/control_plane/test_saved_context_project.py @@ -35,9 +35,10 @@ def test_stateless_saved_work_keeps_the_captured_preparation_and_readback(tmp_pa "--todo-id", TODO_ID, "--agent-id", AGENT_ID, "--claimed-by", AGENT_ID, cwd=project) assert code == 0 and claim["ok"], claim directory = tmp_path / phase - code, source = _run_cli(registry, runtime, "quota", "should-run", *binding, "--complete-turn", + code, source = _run_cli(registry, runtime, "quota", "should-run", *binding, "--context-delivery", "off", "--decision-output-dir", str(directory), cwd=project) assert code == 0, source + assert source["schema_version"] == "loopx_turn_envelope_v1" assert source["normal_delivery_allowed"] is (phase == "ready") captures.append(directory / "decision.json") @@ -141,7 +142,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 3c73c83527..692a61f377 100644 --- a/tests/control_plane/test_selected_work_requirements.py +++ b/tests/control_plane/test_selected_work_requirements.py @@ -146,18 +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() 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"]) + 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 @@ -210,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", @@ -304,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)) @@ -470,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 ea06439b52..55811bb407 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"] @@ -850,7 +850,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")) - guard = ("--cli-bin", cli, "quota", "should-run", "--codex-app", "--complete-turn", + guard = ("--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), "--max-page-output-bytes", "64000") 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..3d047ab9a3 100644 --- a/tests/control_plane/test_work_acceptance_context.py +++ b/tests/control_plane/test_work_acceptance_context.py @@ -109,8 +109,12 @@ def cli(*arguments): goal_id=goal, todo_id="todo_missing") 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", - ) + selected_guard = ( + "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", + ) + packet = cli(*selected_guard) 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 +128,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 +145,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 @@ -163,7 +163,10 @@ def cli(*arguments): from loopx.cli import main from loopx.control_plane.work_items import context_readback - def unavailable(**_kwargs): + attempted_acceptance_reads = [] + + def unavailable(**kwargs): + attempted_acceptance_reads.append(kwargs["todo_id"]) raise OSError("acceptance source unavailable") planner_sources = [] @@ -180,8 +183,10 @@ def observe_planner_source(method, params, **options): output = io.StringIO() with contextlib.redirect_stdout(output): code = main(["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", - "quota", "should-run", "--goal-id", goal, "--agent-id", "agent-a", "--context-delivery", "off"]) - failed = json.loads(output.getvalue())["interaction_contract"]["agent_channel"] + *selected_guard]) + failure = json.loads(output.getvalue()) + failed = failure["interaction_contract"]["agent_channel"] + assert attempted_acceptance_reads == [selected], failure.get("effective_action") assert code == 0 and failed["delivery_allowed"] is False assert failed["work_context"]["complete"] is False assert any(row.get("source") == "goal_acceptance" for row in failed["required_reads"]) @@ -190,8 +195,10 @@ 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", ) - assert recovered["interaction_contract"]["agent_channel"]["work_context"]["complete"] is True + recovered = cli(*selected_guard) + recovered_context = recovered["interaction_contract"]["agent_channel"]["work_context"] + assert recovered_context["complete"] is True + assert recovered_context["selected_todo_text_verified"] is True @pytest.mark.parametrize("provider", ["file", "sqlite"]) @@ -248,7 +255,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/desktop/test_update_feed.py b/tests/desktop/test_update_feed.py index dc8e572844..f7013274d5 100644 --- a/tests/desktop/test_update_feed.py +++ b/tests/desktop/test_update_feed.py @@ -4,8 +4,10 @@ import json import os from pathlib import Path +import shlex import shutil import subprocess +import sys import tempfile import unittest @@ -253,7 +255,7 @@ def _working_bash(self): return candidate self.skipTest("a working bash is required for the upload-step regression") - def _run_upload_step(self, channel, version, tag, include_windows): + def _run_upload_step(self, channel, version, tag, include_windows, *, channel_qualified=True): bash = self._working_bash() script = self._upload_step_script() case_dir = self.root / f"upload-{channel}-{int(include_windows)}" @@ -289,9 +291,20 @@ def _run_upload_step(self, channel, version, tag, include_windows): "GH_LOG": str(gh_log), "RELEASE_TAG": tag, "SOURCE_REF": "source-ref", - "EVENT_NAME": "release", + "EVENT_NAME": "workflow_dispatch" if channel == "main" else "release", "CHANNEL": channel, + "PYTHONPATH": str(WORKFLOW.parents[2]), } + interpreter = shlex.quote(sys.executable) + if channel_qualified: + qualify_channel = ( + "import sys; from loopx.cli_commands import update_artifact; " + "update_artifact._ARTIFACT_DEFAULT_CONTRACTS['public_channel'] = 'current'; " + "exec(compile(sys.stdin.read(), '', 'exec'))" + ) + script = f"python() {{ {interpreter} -c {shlex.quote(qualify_channel)}; }}\n" + script + else: + script = f"python() {{ {interpreter} \"$@\"; }}\n" + script result = subprocess.run( [bash, "-c", script], cwd=case_dir, @@ -345,6 +358,22 @@ def test_upload_step_skips_absent_windows_artifact_on_stable(self): ) self.assertLess(feed_upload, pointer_upload) + def test_unqualified_c1_desktop_candidate_does_not_advance_main_channel(self): + tag = "desktop-main-123-1" + calls = self._run_upload_step( + "main", "0.0.0-main.123.1", tag, True, channel_qualified=False + ) + self.assertTrue(any(call.startswith(f"release create {tag} --prerelease --latest=false") for call in calls)) + self.assertIn(f"release upload {tag} dist/updater/desktop-updater.json --clobber", calls) + self.assertFalse(any(call.split()[2] == "desktop-main" for call in calls)) + + def test_unqualified_c1_desktop_candidate_does_not_advance_stable_channel(self): + tag = "v1.2.4" + calls = self._run_upload_step("stable", "1.2.4", tag, False, channel_qualified=False) + self.assertIn(f"release upload {tag} dist/updater/LoopX.app.tar.gz", calls) + self.assertIn(f"release upload {tag} dist/updater/desktop-updater.json --clobber", calls) + self.assertFalse(any(call.split()[2] == "desktop-stable" for call in calls)) + def test_upload_step_rejects_main_without_windows_artifact(self): case_dir = self.root / "upload-main-missing" updater = case_dir / "dist" / "updater" diff --git a/tests/test_delegation_turn_context.py b/tests/test_delegation_turn_context.py index b331a873ee..31cb04bc1a 100644 --- a/tests/test_delegation_turn_context.py +++ b/tests/test_delegation_turn_context.py @@ -618,7 +618,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", diff --git a/tests/test_release_artifact_publication.py b/tests/test_release_artifact_publication.py index ef276debe1..24ece543dd 100644 --- a/tests/test_release_artifact_publication.py +++ b/tests/test_release_artifact_publication.py @@ -9,6 +9,13 @@ from unittest.mock import patch import pytest +from loopx.cli_commands import update_artifact +from loopx.cli_commands.update_artifact import ( + HISTORICAL_DEFAULT_CONTRACT, + PUBLIC_DEFAULT_CONTRACT, + QUALIFIED_DEFAULT_CONTRACT_FIELD, + RUNTIME_ARTIFACT_SCHEMA_VERSION, +) SPEC = importlib.util.spec_from_file_location( "publication_artifacts", Path(__file__).parents[1] / "scripts/release_artifacts.py" @@ -54,6 +61,33 @@ def test_colocated_artifact_cli_never_initializes_the_candidate(tmp_path, isolat assert "version mismatch" in result.stderr +def stable_runtime(root, identity, *, current): + revision = "a" * 40 + profile = PUBLIC_DEFAULT_CONTRACT if current else HISTORICAL_DEFAULT_CONTRACT + archive = root / "runtime" / f"loopx-runtime-{revision}.tar.gz" + archive.write_bytes(b"qualified runtime bytes") + manifest = { + "schema_version": RUNTIME_ARTIFACT_SCHEMA_VERSION, + "source_revision": revision, + "package_version": identity.version, + "channel": "stable", + "size": archive.stat().st_size, + "sha256": owner.sha256(archive), + "urls": [f"https://github.com/owner/repo/releases/download/{identity.tag}/{archive.name}"], + (QUALIFIED_DEFAULT_CONTRACT_FIELD if current else "default_contract"): profile, + } + (archive.parent / "loopx-runtime.json").write_text(json.dumps(manifest)) + qualification = dict.fromkeys(( + "ok", "clean_install", "upgrade", "doctor", "skills", "frontend_bundle_contract", + "frontend_http", "no_frontend_build_tools", "license_notices", "activation_failure_restored", + ), True) + qualification.update( + source_revision=revision, bytes=manifest["size"], sha256=manifest["sha256"], + channel="stable", default_contract=profile, + ) + (archive.parent / "qualification.json").write_text(json.dumps(qualification)) + + @pytest.fixture def bundle(tmp_path): identity = owner.ReleaseIdentity("loopx", "1.2.3") @@ -61,7 +95,7 @@ def bundle(tmp_path): (tmp_path / "runtime").mkdir() for name in ["loopx-1.2.3-py3-none-any.whl", "loopx-1.2.3.tar.gz"]: (tmp_path / "packages" / name).write_bytes(name.encode()) - (tmp_path / "runtime/qualification.json").write_bytes(b'{"ok":true}') + stable_runtime(tmp_path, identity, current=False) (tmp_path / "RELEASE-SOURCES.json").write_text(json.dumps({ "product_tag": identity.tag, "product_commit": "a" * 40, })) @@ -95,6 +129,38 @@ def download(argv, *, stdout, check): return calls, gh, download +def test_engineering_qualified_c1_cannot_reach_unqualified_stable_release(bundle): + root, identity = bundle + stable_runtime(root, identity, current=True) + calls, gh, download = transport([]) + with patch.object(owner, "gh", gh), patch.object(owner.subprocess, "run", download): + with pytest.raises(owner.ReleaseArtifactError, match="pending public channel qualification"): + owner.upload_immutable(root, identity, "owner/repo") + assert not calls + + +def test_adoption_qualified_c1_can_publish_stable_runtime(bundle, monkeypatch): + root, identity = bundle + stable_runtime(root, identity, current=True) + monkeypatch.setitem(update_artifact._ARTIFACT_DEFAULT_CONTRACTS, "public_channel", "current") + calls, gh, download = transport([]) + with patch.object(owner, "gh", gh), patch.object(owner.subprocess, "run", download): + owner.upload_immutable(root, identity, "owner/repo") + uploads = [call for call in calls if call[:2] == ("release", "upload")] + assert len(uploads) == 1 and uploads[0][2] == identity.tag + assert str(root / "runtime/loopx-runtime.json") in uploads[0] + + +def test_stable_runtime_refuses_changed_bytes_before_github(bundle): + root, identity = bundle + (root / "runtime" / ("loopx-runtime-" + "a" * 40 + ".tar.gz")).write_bytes(b"changed") + calls, gh, download = transport([]) + with patch.object(owner, "gh", gh), patch.object(owner.subprocess, "run", download): + with pytest.raises(owner.ReleaseArtifactError, match="bytes differ"): + owner.upload_immutable(root, identity, "owner/repo") + assert not calls + + @pytest.mark.parametrize("dry_run", [True, False]) def test_resume_only_uploads_missing_files(bundle, dry_run): root, identity = bundle @@ -120,6 +186,50 @@ def test_collision_or_changed_bytes_prevents_every_upload(bundle, wrong_case, mi assert not any(c[:2] == ("release", "upload") for c in calls) + +@pytest.mark.parametrize("failure", ["policy-held", "missing", "changed", "draft", None]) +def test_named_release_preserves_old_latest_until_qualified_bundle_readback(bundle, failure): + root, identity = bundle + if failure == "policy-held": + stable_runtime(root, identity, current=True) + files = owner.publication_files(root, identity) + asset_files = files[:-1] if failure == "missing" else files + old = {"id": 41, "tag_name": "v1.2.2"} + release = {"id": 42, "tag_name": identity.tag, "draft": failure == "draft", "prerelease": False} + latest = old + notes_file = root / "NOTES.md" + notes_file.write_text("Release notes", encoding="utf-8") + calls, read_remote, download = transport(asset_files, mismatch=failure == "changed") + + def github(*args): + nonlocal latest + if args[:2] == ("release", "create"): + assert args[2] == identity.tag and "--verify-tag" in args + if "--latest=false" not in args: + latest = release + return b"" + if args == ("api", f"repos/owner/repo/releases/tags/{identity.tag}"): + return json.dumps(release).encode() + if args == ("api", "repos/owner/repo/releases/latest"): + return json.dumps(latest).encode() + if args == ("api", "--method", "PATCH", "repos/owner/repo/releases/42", "-f", "make_latest=true"): + latest = release + return b"" + return read_remote(*args) + + with patch.object(owner, "gh", github), patch.object(owner.subprocess, "run", download): + owner.create_named_release(identity, "owner/repo", notes_file, "LoopX 1.2.3") + assert latest == old + if failure is not None: + with pytest.raises(owner.ReleaseArtifactError): + owner.promote_latest(root, identity, "owner/repo", execute=True) + assert latest == old + else: + owner.promote_latest(root, identity, "owner/repo", execute=False) + assert latest == old + owner.promote_latest(root, identity, "owner/repo", execute=True) + assert latest == release + def test_recovery_attestation_failure_cannot_publish(bundle): root, identity = bundle calls, gh, download = transport([], attestation_failure=True) diff --git a/tests/test_runtime_snapshot_publication.py b/tests/test_runtime_snapshot_publication.py index b4279a5063..0c64d9d1ff 100644 --- a/tests/test_runtime_snapshot_publication.py +++ b/tests/test_runtime_snapshot_publication.py @@ -13,7 +13,14 @@ 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, + QUALIFIED_DEFAULT_CONTRACT_FIELD, + RUNTIME_ARTIFACT_SCHEMA_VERSION, + validate_default_contract, + validate_published_manifest, +) ROOT = Path(__file__).resolve().parents[1] REVISION = "a" * 40 @@ -94,7 +101,10 @@ def publication(tmp_path): ("runtime-inventory", ".json")): (runtime / f"{stem}-{REVISION}{suffix}").write_bytes(f"{stem}:immutable".encode()) archive = runtime / f"loopx-runtime-{REVISION}.tar.gz" - manifest = json.dumps({"source_revision": REVISION, "channel": "main", "default_contract": dict(PUBLIC_DEFAULT_CONTRACT), + manifest = json.dumps({ + "schema_version": RUNTIME_ARTIFACT_SCHEMA_VERSION, "source_revision": REVISION, + "package_version": "1.2.3", "channel": "main", + QUALIFIED_DEFAULT_CONTRACT_FIELD: dict(PUBLIC_DEFAULT_CONTRACT), "size": archive.stat().st_size, "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(), "urls": [ f"https://github.com/example/loopx/releases/download/{SNAPSHOT}/loopx-runtime-{REVISION}.tar.gz"]}) qualification = {"ok": True, "source_revision": REVISION, "channel": "main", @@ -123,11 +133,20 @@ def write_state(root, state): (root / "github.json").write_text(json.dumps(state), encoding="utf-8") -def publish(root): +def publish(root, *, channel_qualified=True): # The production workflow uses python from setup-python. Bind the same # interpreter as pytest without requiring a particular host PATH alias. functions = f"gh() {{ {shlex.quote(sys.executable)} github.py \"$@\"; }}\n" - functions += f"python() {{ {shlex.quote(sys.executable)} \"$@\"; }}\n" + interpreter = shlex.quote(sys.executable) + if channel_qualified: + qualify_channel = ( + "import sys; from loopx.cli_commands import update_artifact; " + "update_artifact._ARTIFACT_DEFAULT_CONTRACTS['public_channel'] = 'current'; " + "exec(compile(sys.stdin.read(), '', 'exec'))" + ) + functions += f"python() {{ {interpreter} -c {shlex.quote(qualify_channel)}; }}\n" + else: + functions += f"python() {{ {interpreter} \"$@\"; }}\n" return subprocess.run(["bash", "-c", functions + PUBLISH], cwd=root, env={**os.environ, "PYTHONPATH": str(ROOT), "GITHUB_REPOSITORY": "example/loopx", "FAKE_GITHUB_STATE": str(root / "github.json")}, capture_output=True, text=True, encoding="utf-8", timeout=30, check=False) @@ -136,7 +155,8 @@ 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", + "legacy_incompatible_contract_location", "ambiguous_contract", ]) def test_unqualified_runtime_never_changes_remote_state(publication, failure): qualification = publication / "runtime" / f"qualification-{REVISION}.json" @@ -147,15 +167,20 @@ 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", + "legacy_incompatible_contract_location", "ambiguous_contract"}: path = publication / "runtime/loopx-runtime.json" data = json.loads(path.read_text(encoding="utf-8")) if failure == "missing_contract": - data.pop("default_contract") + data.pop(QUALIFIED_DEFAULT_CONTRACT_FIELD) + elif failure == "legacy_incompatible_contract_location": + data["default_contract"] = data.pop(QUALIFIED_DEFAULT_CONTRACT_FIELD) + elif failure == "ambiguous_contract": + data["default_contract"] = dict(PUBLIC_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"} - data["default_contract"] = record["default_contract"] = profile + profile = (HISTORICAL_DEFAULT_CONTRACT + if failure == "historical_default" else {"surface": "future"}) + data[QUALIFIED_DEFAULT_CONTRACT_FIELD] = record["default_contract"] = profile # All engineering checks, identities and frozen bytes still agree. for name in ["loopx-runtime.json", f"loopx-runtime-{REVISION}.json"]: (publication / "runtime" / name).write_text(json.dumps(data), encoding="utf-8") @@ -189,6 +214,21 @@ def test_unqualified_runtime_never_changes_remote_state(publication, failure): assert read_state(publication) == before +@pytest.mark.parametrize("channel_exists", [True, False]) +def test_c1_candidate_keeps_unqualified_channel_unchanged(publication, channel_exists): + before = read_state(publication) + if not channel_exists: + del before["releases"]["runtime-main"] + write_state(publication, before) + result = publish(publication, channel_qualified=False) + assert result.returncode == 0, result.stderr + state = read_state(publication) + assert state["releases"].get("runtime-main") == before["releases"].get("runtime-main") + assert len(state["releases"][SNAPSHOT]["assets"]) == 5 + assert not any(call[:2] == ["release", "upload"] and call[2] == "runtime-main" for call in state["calls"]) + assert not any("PATCH" in call for call in state["calls"]) + + def test_full_legacy_release_keeps_history_and_publishes_then_retries(publication): history = read_state(publication)["releases"]["runtime-main"]["assets"].copy() result = publish(publication) @@ -334,8 +374,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" @@ -352,7 +391,10 @@ def observe(source: Path) -> dict: descriptor = builder.build(root, output, repository="example/loopx", channel=channel) tag = f"runtime-main-{revision}" if channel == "main" else "v1.2.3" assert descriptor["urls"] == [f"https://github.com/example/loopx/releases/download/{tag}/loopx-runtime-{revision}.tar.gz"] - assert json.loads((output / "loopx-runtime.json").read_text(encoding="utf-8")) == descriptor + published = json.loads((output / "loopx-runtime.json").read_text(encoding="utf-8")) + assert "default_contract" not in published + assert published[QUALIFIED_DEFAULT_CONTRACT_FIELD] == descriptor["default_contract"] + assert validate_published_manifest(published) == descriptor runtime = output / f"loopx-runtime-{revision}.tar.gz" assert runtime.stat().st_size == descriptor["size"] assert descriptor["default_contract"] == PUBLIC_DEFAULT_CONTRACT @@ -365,6 +407,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 - # Check the actual CLI output against the supported release contract. - observed = observe_default_contract(ROOT) - assert validate_default_contract(observed) == PUBLIC_DEFAULT_CONTRACT + 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 4c2f77d41d..1dc155ba1d 100644 --- a/tests/test_update_artifact.py +++ b/tests/test_update_artifact.py @@ -28,12 +28,16 @@ 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 -c1 = {'surface':'complete_turn','schema_version':'loopx_turn_envelope_v1', - 'interaction_schema_version':'loopx_interaction_contract_v0'} -assert module['validate_manifest']({**value, 'default_contract':c1})['default_contract']==c1 -try:module['validate_default_contract'](c1) +published = {**value, module['QUALIFIED_DEFAULT_CONTRACT_FIELD']: profile} +assert module['validate_published_manifest'](published)=={**value, 'default_contract':profile} +try:module['validate_manifest']({**published, 'default_contract':profile}) except ValueError:pass -else:raise AssertionError('reader compatibility promoted the publication default') +else:raise AssertionError('ambiguous contract accepted by bootstrap') +history = module['HISTORICAL_DEFAULT_CONTRACT'] +assert module['validate_manifest']({**value, 'default_contract':history})['default_contract']==history +try:module['validate_default_contract'](history) +except ValueError:pass +else:raise AssertionError('reader compatibility promoted the historical contract as publication default') 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 @@ -111,7 +115,7 @@ def test_unqualified_default_stops_before_download_or_activation(monkeypatch, pr calls = [] monkeypatch.setattr(update, "download_artifact", lambda *_a, **_kw: calls.append("download")) monkeypatch.setattr(update, "run_installer", lambda *_a, **_kw: calls.append("activate")) - with pytest.raises(ValueError, match="Unsupported runtime default contract"): + with pytest.raises(ValueError, match="unqualified for public adoption"): update.install_artifact(descriptor, env={}, timeout_seconds=10) assert calls == [] @@ -119,28 +123,26 @@ 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 - c1 = {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", - "interaction_schema_version": "loopx_interaction_contract_v0"} - compatible = {**historical, "default_contract": c1} - assert update.validate_manifest(compatible) == compatible with pytest.raises(ValueError, match="unqualified for public adoption"): - update.validate_default_contract(c1) + update.validate_default_contract(dict(update.HISTORICAL_DEFAULT_CONTRACT)) -def test_archive_contract_mismatch_stops_before_installer(tmp_path, monkeypatch): +@pytest.mark.parametrize("contract_field", ["default_contract", update.QUALIFIED_DEFAULT_CONTRACT_FIELD]) +def test_archive_contract_mismatch_stops_before_installer(tmp_path, monkeypatch, contract_field): archive = tmp_path / "runtime.tar.gz" identity = json.dumps({"source_revision": "a" * 40, "package_version": "1.2.3", - "default_contract": {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", - "interaction_schema_version": "loopx_interaction_contract_v0"}}).encode() + "default_contract": {"surface": "complete_turn"}}).encode() with tarfile.open(archive, "w:gz") as target: for name, content in [("runtime-artifact.json", identity), ("scripts/install-local.sh", b"exit 99\n")]: member = tarfile.TarInfo(name) member.size = len(content) target.addfile(member, io.BytesIO(content)) descriptor = {**manifest(archive.read_bytes(), "https://publisher.invalid/runtime"), - "default_contract": dict(update.PUBLIC_DEFAULT_CONTRACT)} + contract_field: dict(update.PUBLIC_DEFAULT_CONTRACT)} monkeypatch.setattr(update, "download_artifact", lambda *_a, **_kw: archive) calls = [] monkeypatch.setattr(update, "run_installer", lambda *_a, **_kw: calls.append("activate"))