From a5a18df8e8e97ff0421e71e821ac43a11908eb38 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:53:05 +0800 Subject: [PATCH] fix(release): isolate unqualified default contract cutovers Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Signed-off-by: huangruiteng --- .github/workflows/runtime-snapshots.yml | 7 +++ ...controller-executor-unified-contract-v0.md | 9 ++++ ...ller-executor-unified-contract-v0.zh-CN.md | 6 +++ docs/product/release-readiness.md | 23 ++++++++ loopx/cli_commands/update_artifact.py | 25 +++++++++ scripts/desktop_runtime_bundle.py | 12 +++++ scripts/qualify_runtime_artifact.py | 52 ++++++++++++++++++- scripts/runtime_artifact.py | 5 +- tests/test_runtime_snapshot_publication.py | 44 +++++++++++++++- tests/test_update_artifact.py | 45 ++++++++++++++++ 10 files changed, 223 insertions(+), 5 deletions(-) diff --git a/.github/workflows/runtime-snapshots.yml b/.github/workflows/runtime-snapshots.yml index bcfecbf17b..e037b7f104 100644 --- a/.github/workflows/runtime-snapshots.yml +++ b/.github/workflows/runtime-snapshots.yml @@ -79,6 +79,7 @@ jobs: permissions: contents: write steps: + - uses: actions/checkout@v7 - uses: actions/download-artifact@v7 with: name: loopx-runtime @@ -96,6 +97,9 @@ jobs: 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 root = Path("runtime") manifest_bytes = (root / "loopx-runtime.json").read_bytes() manifest = json.loads(manifest_bytes) @@ -107,6 +111,9 @@ jobs: "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") diff --git a/docs/architecture/rfcs/controller-executor-unified-contract-v0.md b/docs/architecture/rfcs/controller-executor-unified-contract-v0.md index c34be4ad04..cf60956983 100644 --- a/docs/architecture/rfcs/controller-executor-unified-contract-v0.md +++ b/docs/architecture/rfcs/controller-executor-unified-contract-v0.md @@ -1373,6 +1373,15 @@ and retirement, and adoption/full-cost qualification where each boundary is independently reviewable. Record dependencies in the existing tasks and PRs. 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). + Native launch rechecks use the original `SettlementIdentity` as their sole Todo/obligation binding. Both `codex-cli` and `codex-app-server` call the existing `current_turn_host_launch_decision` owner; an observed replan packet is context, 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 37ab91d558..abc7f8769d 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 @@ -1083,6 +1083,12 @@ owner。列明后续切换消费者;不能添加无人使用的基础设施或 可按独立可审查的边界拆分,在既有任务和 PR 中记录依赖。拆分交付不代表 C1 完成, 也不豁免第 9 节相对原 quota 基线的验证。 +公开分发隔离现在复用 runtime 制品元数据 owner:runtime 资格检查观察已安装的普通 +writer,桌面打包观察归档 writer,发布要求声明的支持契约与观察一致。现有 quota +packet 默认保持支持;未资格化的完整契约默认不能只凭安装检查通过。此改动不证明 +第 9 节的成果/成本,不替换已安装 writer、不增加当前 producer,也不退役历史 reader。 +扩大支持 profile 仍须原采用证据,详见[发布边界](../../product/release-readiness.md)。 + 原生启动重查只从原 `SettlementIdentity` 取得 Todo/obligation 绑定。 `codex-cli` 和 `codex-app-server` 都调用既有 `current_turn_host_launch_decision` owner;观察到的 replan packet 是上下文, diff --git a/docs/product/release-readiness.md b/docs/product/release-readiness.md index 52575ab4cb..8f94298765 100644 --- a/docs/product/release-readiness.md +++ b/docs/product/release-readiness.md @@ -281,6 +281,29 @@ main 运行时发布器在任何远端写入前,将下载的安装资格与源 证据缺失、失败或不匹配时,保留已有发布及渠道。此工程资格不证明模型结果、完整成本收益 或 C1 默认采用资格。 +New runtime descriptors carry the supported `default_contract`. Qualification +observes 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. 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`。资格检查在隔离的原始 Goal 中,关闭 +上下文传输后观察安装候选的普通 quota writer;发布器要求该观察与不可变描述符一致。 +桌面打包通过相同探测与支持校验器检查实际归档源码。runtime 更新在下载或激活前拒绝 +未支持的声明契约,并核对归档身份与元数据中的契约;历史 v1 描述符保留读取兼容。 +当前分发范围是已有 `quota_packet` writer;完整契约默认切换在满足原 RFC §9 同单会话 +匹配成果、完整成本及支持 profile 的采用门之前保持未资格化。安装检查或新增布尔值不能 +扩大该范围。显式完整契约 opt-in、上下文传输配置及历史恢复继续由原 owner 处理,此边界 +不切换已安装 writer。 + For a browser-fixture error discovered after an immutable tag was published, maintainers may dispatch the release workflow from reviewed tooling with `tag` set to that existing release and `browser_fixture_commit` set to a full, diff --git a/loopx/cli_commands/update_artifact.py b/loopx/cli_commands/update_artifact.py index 923c400a03..d4546b50f9 100644 --- a/loopx/cli_commands/update_artifact.py +++ b/loopx/cli_commands/update_artifact.py @@ -31,6 +31,8 @@ from ..capabilities.issue_fix.repository_snapshot import _REPO_PATTERN as REPOSITORY_PATTERN RUNTIME_ARTIFACT_SCHEMA_VERSION = "loopx_runtime_artifact_v1" +PUBLIC_DEFAULT_CONTRACT = {"surface": "quota_packet", "schema_version": None, + "interaction_schema_version": "loopx_interaction_contract_v0"} SHA = re.compile(r"[0-9a-f]{40}") MAX_MANIFEST = 256 * 1024 MAX_ARCHIVE = 256 * 1024 * 1024 @@ -96,6 +98,22 @@ def read_json(url: str) -> dict[str, Any]: return result +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. + """ + 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" + ) + return dict(value) + + def validate_manifest(value: dict[str, Any], *, revision: str | None = None) -> dict[str, Any]: if value.get("schema_version") != RUNTIME_ARTIFACT_SCHEMA_VERSION: raise ValueError("Unsupported runtime artifact metadata") @@ -114,6 +132,10 @@ def validate_manifest(value: dict[str, Any], *, revision: str | None = None) -> raise ValueError("Runtime artifact has no bounded download sources") for url in urls: safe_url(url) + # Historical v1 snapshots remain readable. Newly produced artifacts and + # the publisher require the observed contract; absence is not qualification. + if "default_contract" in value: + validate_default_contract(value["default_contract"]) return dict(value) @@ -385,6 +407,7 @@ def consume(name, stream): def install_artifact(manifest: dict[str, Any], *, env: dict[str, str], timeout_seconds: int, progress=lambda _event: None): + manifest = validate_manifest(manifest) started = time.monotonic() archive = download_artifact(manifest, progress=progress, timeout=timeout_seconds) progress({"stage": "verify"}) @@ -393,6 +416,8 @@ def install_artifact(manifest: dict[str, Any], *, env: dict[str, str], timeout_s identity = json.loads((root / "runtime-artifact.json").read_text(encoding="utf-8")) if identity.get("source_revision") != manifest["source_revision"] or identity.get("package_version") != manifest["package_version"]: raise ValueError("Runtime identity disagrees with its release metadata") + if "default_contract" in manifest and identity.get("default_contract") != manifest["default_contract"]: + raise ValueError("Runtime default contract disagrees with its release metadata") selected = dict(env) selected.update({"LOOPX_RESOLVED_SOURCE_GIT_COMMIT": manifest["source_revision"], "LOOPX_ARCHIVE_SHA256": manifest["sha256"], "LOOPX_ARCHIVE_URL": manifest["urls"][0], diff --git a/scripts/desktop_runtime_bundle.py b/scripts/desktop_runtime_bundle.py index 8177e06995..bd4d18a0d4 100644 --- a/scripts/desktop_runtime_bundle.py +++ b/scripts/desktop_runtime_bundle.py @@ -16,6 +16,11 @@ import io import importlib.util import tomllib +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from loopx.cli_commands.update_artifact import extract_artifact, validate_default_contract +from scripts.qualify_runtime_artifact import observe_default_contract def build(root: Path) -> None: @@ -107,10 +112,17 @@ def build(root: Path) -> None: target.addfile(member, io.BytesIO(content)) rebuilt.replace(archive) entries = qualify_archive(archive) + # Inspect the actual archived writer, not dirty checkout files or the + # engineering-only installer result. The signed App carries these bytes. + with tempfile.TemporaryDirectory(prefix="loopx-desktop-contract-") as raw: + source_root = Path(raw).resolve() + extract_artifact(archive, source_root) + default_contract = validate_default_contract(observe_default_contract(source_root)) identity = { "schema_version": "desktop_runtime_bundle_v1", "source_revision": revision, "package_version": archive_package_version(archive), + "default_contract": default_contract, "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(), } (destination / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") diff --git a/scripts/qualify_runtime_artifact.py b/scripts/qualify_runtime_artifact.py index 9ae96c16d2..a8dc69b564 100644 --- a/scripts/qualify_runtime_artifact.py +++ b/scripts/qualify_runtime_artifact.py @@ -13,7 +13,53 @@ import tempfile sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from loopx.cli_commands.update_artifact import extract_artifact, file_hash, validate_manifest +from loopx.cli_commands.update_artifact import extract_artifact, file_hash, validate_default_contract, validate_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. + """ + source = source.resolve() + with tempfile.TemporaryDirectory(prefix="loopx-default-contract-") as raw: + scratch = Path(raw).resolve() + env = {key: value for key, value in os.environ.items() + if not key.startswith("LOOPX_") and key not in { + "CODEX_HOME", "CODEX_THREAD_ID", "CODEX_SESSION_ID", "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR"}} + env.update(PYTHONPATH=str(source), TMPDIR=str(scratch), TEMP=str(scratch), TMP=str(scratch), + CODEX_HOME=str(scratch / "home/codex")) + result = subprocess.run([sys.executable, "-c", r''' +import json, subprocess, sys +from pathlib import Path +import loopx +if Path(loopx.__file__).resolve().parents[1] != Path(sys.argv[2]): + raise ValueError("Default contract probe imported another source") +from loopx.control_plane.effect_runtime import restart_effect_runtime +from loopx.control_plane.testing.terminal_settlement_tool_behavior import ( + _build_fixture, TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID, TERMINAL_SETTLEMENT_FIXTURE_AGENT_ID) +try: + fixture = _build_fixture(Path(sys.argv[1])) + result = subprocess.run([sys.executable, "-m", "loopx.entrypoint", "--format", "json", + "--registry", str(fixture.global_registry_path), "--runtime-root", str(fixture.runtime_root), + "quota", "should-run", "--goal-id", TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID, + "--agent-id", TERMINAL_SETTLEMENT_FIXTURE_AGENT_ID, "--context-delivery", "off"], + cwd=fixture.project_root, capture_output=True, text=True, encoding="utf-8", timeout=60, check=True) + payload = json.loads(result.stdout) + if payload.get("ok") is not True or payload.get("goal_id") != TERMINAL_SETTLEMENT_FIXTURE_GOAL_ID: + raise ValueError("Default writer probe did not return its original Goal") + schema = payload.get("schema_version") + print(json.dumps({"surface": "complete_turn" if schema == "loopx_turn_envelope_v1" else "quota_packet", + "schema_version": schema, + "interaction_schema_version": payload.get("interaction_contract", {}).get("schema_version")})) +finally: + restart_effect_runtime(wait_for_exit=True) +''', str(scratch / "fixture"), str(source)], cwd=source, env=env, capture_output=True, + text=True, encoding="utf-8", timeout=120) + if result.returncode: + raise ValueError("Runtime default contract could not be qualified through its isolated CLI") + return json.loads(result.stdout) def qualify(directory: Path) -> dict: @@ -65,6 +111,9 @@ def read(*args): if not doctor.get("ok") or not skills.get("ok"): raise RuntimeError("Installed runtime/skills readback failed") release = cli.resolve().parents[1] + default_contract = validate_default_contract(observe_default_contract(release)) + if manifest.get("default_contract") != default_contract: + raise ValueError("Observed runtime default contract does not match the candidate") for name in ("LICENSE", "NOTICE", "LICENSE-MIT"): assert (release / name).read_bytes() == (source / name).read_bytes() source_record = json.loads((release / "release.json").read_text())["source"] @@ -122,6 +171,7 @@ def read(*args): env={**env, "PYTHONPATH": str(release)}, cwd=release, check=True, timeout=15, stdout=subprocess.DEVNULL) return {"ok": True, "source_revision": manifest["source_revision"], "bytes": manifest["size"], + "default_contract": default_contract, "channel": manifest["channel"], "sha256": manifest["sha256"], "clean_install": results[0] == 0, "upgrade": results[1] == 0, "doctor": True, "skills": True, "frontend_bundle_contract": True, "frontend_http": True, diff --git a/scripts/runtime_artifact.py b/scripts/runtime_artifact.py index 537cdd52c3..7735dc316d 100644 --- a/scripts/runtime_artifact.py +++ b/scripts/runtime_artifact.py @@ -23,7 +23,7 @@ ROOT = Path(__file__).resolve().parents[1] 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 RUNTIME_ARTIFACT_SCHEMA_VERSION, validate_manifest # noqa: E402 +from loopx.cli_commands.update_artifact import PUBLIC_DEFAULT_CONTRACT, RUNTIME_ARTIFACT_SCHEMA_VERSION, validate_manifest # noqa: E402 PATHS = ("loopx", "scripts", "skills", "docs", "man", "examples", "apps/presentation", ".github", "README.md", "LICENSE", "NOTICE", "LICENSE-MIT", "pyproject.toml", "setup.py", "MANIFEST.in") @@ -95,7 +95,7 @@ def build(root: Path, output: Path, *, repository: str, channel: str) -> dict: inventory["runtime"].append({"path": member.name, "bytes": len(content), "sha256": hashlib.sha256(content).hexdigest()}) identity = json.dumps({"schema_version": RUNTIME_ARTIFACT_SCHEMA_VERSION, "source_revision": revision, - "package_version": version}).encode() + "package_version": version, "default_contract": PUBLIC_DEFAULT_CONTRACT}).encode() member = tarfile.TarInfo("runtime-artifact.json") member.size, member.mode = len(identity), 0o644 runtime.addfile(member, io.BytesIO(identity)) @@ -107,6 +107,7 @@ def build(root: Path, output: Path, *, repository: str, channel: str) -> dict: archive = output / filename result = validate_manifest({"schema_version": RUNTIME_ARTIFACT_SCHEMA_VERSION, "source_revision": revision, "package_version": version, "channel": channel, "size": archive.stat().st_size, + "default_contract": dict(PUBLIC_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, diff --git a/tests/test_runtime_snapshot_publication.py b/tests/test_runtime_snapshot_publication.py index 7b40e05244..1a2d0ca969 100644 --- a/tests/test_runtime_snapshot_publication.py +++ b/tests/test_runtime_snapshot_publication.py @@ -12,6 +12,7 @@ import pytest import yaml +from loopx.cli_commands.update_artifact import PUBLIC_DEFAULT_CONTRACT, validate_default_contract ROOT = Path(__file__).resolve().parents[1] REVISION = "a" * 40 @@ -92,10 +93,11 @@ 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", + manifest = json.dumps({"source_revision": REVISION, "channel": "main", "default_contract": 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", + "default_contract": dict(PUBLIC_DEFAULT_CONTRACT), "bytes": archive.stat().st_size, "sha256": hashlib.sha256(archive.read_bytes()).hexdigest(), "clean_install": True, "upgrade": True, "doctor": True, "skills": True, "frontend_bundle_contract": True, "frontend_http": True, @@ -126,13 +128,14 @@ def publish(root): functions = f"gh() {{ {shlex.quote(sys.executable)} github.py \"$@\"; }}\n" functions += f"python() {{ {shlex.quote(sys.executable)} \"$@\"; }}\n" return subprocess.run(["bash", "-c", functions + PUBLISH], cwd=root, - env={**os.environ, "GITHUB_REPOSITORY": "example/loopx", "FAKE_GITHUB_STATE": str(root / "github.json")}, + 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) @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", ]) def test_unqualified_runtime_never_changes_remote_state(publication, failure): qualification = publication / "runtime" / f"qualification-{REVISION}.json" @@ -143,6 +146,25 @@ 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"}: + path = publication / "runtime/loopx-runtime.json" + data = json.loads(path.read_text(encoding="utf-8")) + if failure == "missing_contract": + data.pop("default_contract") + else: + profile = {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0"} if failure == "c1_default" else {"surface": "future"} + data["default_contract"] = record["default_contract"] = profile + # All engineering checks, identities and frozen bytes still agree. + for name in ["loopx-runtime.json", f"loopx-runtime-{REVISION}.json"]: + (publication / "runtime" / name).write_text(json.dumps(data), encoding="utf-8") + qualification.write_text(json.dumps(record), encoding="utf-8") + elif failure in {"mismatched_contract", "missing_observed_contract"}: + if failure == "missing_observed_contract": + record.pop("default_contract") + else: + record["default_contract"] = {"surface": "complete_turn"} + qualification.write_text(json.dumps(record), encoding="utf-8") elif failure in {"archive_changed", "manifest_changed"}: if failure == "archive_changed": (publication / "runtime" / f"loopx-runtime-{REVISION}.tar.gz").write_bytes(b"unqualified bytes") @@ -308,3 +330,21 @@ def test_builder_freezes_correct_archive_url_before_publication(tmp_path, monkey 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 assert (output / f"loopx-runtime-{revision}.tar.gz").stat().st_size == descriptor["size"] + assert descriptor["default_contract"] == PUBLIC_DEFAULT_CONTRACT + + +def test_release_probe_observes_real_default_without_model_or_active_goal(): + from scripts.qualify_runtime_artifact import observe_default_contract + + # The probe observes the real writer rather than inheriting the intended + # distribution profile. Main currently exercises C1, which remains outside + # the supported public scope until its original qualification is complete. + observed = observe_default_contract(ROOT) + assert observed == { + "surface": "complete_turn", + "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0", + } + assert observed != PUBLIC_DEFAULT_CONTRACT + with pytest.raises(ValueError, match="unqualified for public adoption"): + validate_default_contract(observed) diff --git a/tests/test_update_artifact.py b/tests/test_update_artifact.py index a6b506fd50..936072fdd6 100644 --- a/tests/test_update_artifact.py +++ b/tests/test_update_artifact.py @@ -26,6 +26,12 @@ def test_exported_bootstrap_validates_metadata_without_an_installed_package(tmp_ module=runpy.run_path(sys.argv[1]) value=json.load(sys.stdin) assert module['validate_manifest'](value)==value +profile = module['PUBLIC_DEFAULT_CONTRACT'] +assert module['validate_manifest']({**value, 'default_contract':profile})['default_contract']==profile +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 + else:raise AssertionError('unqualified contract accepted by bootstrap') for invalid in ['A'*64,'a'*63,'a'*65,'sha256:'+('a'*64),'a'*63+'g']: try:module['validate_manifest']({**value,'sha256':invalid}) except ValueError:pass @@ -91,6 +97,45 @@ def manifest(body: bytes, url: str): "package_version": "1.2.3", "channel": "main", "size": len(body), "sha256": hashlib.sha256(body).hexdigest(), "urls": [url]} +@pytest.mark.parametrize("profile", [None, {}, {"surface": "future"}, + {"surface": "complete_turn", "schema_version": "loopx_turn_envelope_v1", + "interaction_schema_version": "loopx_interaction_contract_v0"}]) +def test_unqualified_default_stops_before_download_or_activation(monkeypatch, profile): + descriptor = {**manifest(b"runtime", "https://publisher.invalid/runtime"), "default_contract": profile} + 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="unqualified for public adoption"): + update.install_artifact(descriptor, env={}, timeout_seconds=10) + assert calls == [] + + +def test_qualified_scope_and_historical_metadata_remain_readable(): + historical = manifest(b"runtime", "https://publisher.invalid/runtime") + assert update.validate_manifest(historical) == historical + current = {**historical, "default_contract": dict(update.PUBLIC_DEFAULT_CONTRACT)} + assert update.validate_manifest(current) == current + + +def test_archive_contract_mismatch_stops_before_installer(tmp_path, monkeypatch): + archive = tmp_path / "runtime.tar.gz" + identity = json.dumps({"source_revision": "a" * 40, "package_version": "1.2.3", + "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)} + monkeypatch.setattr(update, "download_artifact", lambda *_a, **_kw: archive) + calls = [] + monkeypatch.setattr(update, "run_installer", lambda *_a, **_kw: calls.append("activate")) + with pytest.raises(ValueError, match="default contract disagrees"): + update.install_artifact(descriptor, env={}, timeout_seconds=10) + assert calls == [] + + def test_redirects_cannot_weaken_source_tls(): from urllib.request import Request handler = update.UpdateRedirectHandler()