diff --git a/scripts/desktop_runtime_bundle.py b/scripts/desktop_runtime_bundle.py index bd4d18a0d4..8a88d37e4f 100644 --- a/scripts/desktop_runtime_bundle.py +++ b/scripts/desktop_runtime_bundle.py @@ -6,7 +6,6 @@ from __future__ import annotations -import hashlib import json from pathlib import Path import gzip @@ -19,7 +18,8 @@ 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 loopx.cli_commands.update_artifact import extract_artifact, file_hash, validate_default_contract +from loopx.file_lock import exclusive_file_lock from scripts.qualify_runtime_artifact import observe_default_contract @@ -39,7 +39,33 @@ def build(root: Path) -> None: cwd=root, check=True, ) - archive = destination / "runtime-source.tar.gz" + with tempfile.TemporaryDirectory(prefix=".runtime-candidate-", dir=destination) as raw: + staging = Path(raw) + archive = _build_archive(root, revision, staging) + entries = qualify_archive(archive) + # Probe the same archived writer the signed App will install before + # replacing either part of the previous Desktop bundle. + with tempfile.TemporaryDirectory(prefix="loopx-desktop-contract-") as raw_source: + source = extract_artifact(archive, Path(raw_source).resolve()) + default_contract = validate_default_contract(observe_default_contract(source)) + identity = { + "schema_version": "desktop_runtime_bundle_v1", + "source_revision": revision, + "package_version": archive_package_version(archive), + "default_contract": default_contract, + "sha256": file_hash(archive), + } + identity_file = staging / "identity.json" + identity_file.write_text(json.dumps(identity, indent=2) + "\n", encoding="utf-8") + with exclusive_file_lock(root / ".local/desktop-runtime-bundle", operation="desktop-runtime-publish"): + _publish_bundle(destination, archive, identity_file) + print( + f"Prepared exact desktop runtime: {revision[:12]} ({entries} installable entries)" + ) + + +def _build_archive(root: Path, revision: str, staging: Path) -> Path: + archive = staging / "runtime-source.tar.gz" subprocess.run( [ "git", @@ -91,7 +117,7 @@ def build(root: Path) -> None: raise RuntimeError( f"desktop build input differs from committed source: {name}" ) - rebuilt = destination / "runtime-source.staged.tar.gz" + rebuilt = staging / "runtime-source.staged.tar.gz" with ( tarfile.open(archive, "r:gz") as source, tarfile.open(rebuilt, "w:gz", format=tarfile.PAX_FORMAT) as target, @@ -111,24 +137,25 @@ def build(root: Path) -> None: member.mode = 0o644 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") - print( - f"Prepared exact desktop runtime: {revision[:12]} ({entries} installable entries)" - ) + return archive + + +def _publish_bundle(destination: Path, archive: Path, identity: Path) -> None: + # The old identity stays in place until the candidate archive is ready. + target_archive = destination / archive.name + previous_archive = archive.with_name("previous-runtime-source.tar.gz") + had_previous = target_archive.is_file() or target_archive.is_symlink() + if had_previous: + target_archive.rename(previous_archive) + try: + archive.replace(target_archive) + identity.replace(destination / identity.name) + except OSError: + if had_previous: + previous_archive.replace(target_archive) + elif not archive.exists(): + target_archive.unlink() + raise def archive_package_version(archive: Path) -> str: diff --git a/tests/desktop/test_runtime_bundle.py b/tests/desktop/test_runtime_bundle.py index e494c84e8e..838779f0ef 100644 --- a/tests/desktop/test_runtime_bundle.py +++ b/tests/desktop/test_runtime_bundle.py @@ -1,10 +1,15 @@ """Reject runtime snapshots the App-side installer could never unpack.""" import gzip +import hashlib import io import importlib.util +import json +import os from pathlib import Path +import subprocess import tempfile import unittest +from unittest.mock import patch import tarfile spec = importlib.util.spec_from_file_location( @@ -26,6 +31,112 @@ def tar_header(name: bytes, typeflag: bytes, size: int = 0) -> bytes: return bytes(header) +class RuntimeBundleBuildTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + fixture_files = { + "loopx/presentation/chat_bundle.py": "# Synthetic frontend contract\n", + "scripts/chat_bundle.py": "# Synthetic frontend preparation\n", + "scripts/install-local.sh": "#!/bin/sh\n", + "skills/synthetic.txt": "skills\n", + "docs/synthetic.txt": "docs\n", + "man/synthetic.txt": "man\n", + "examples/synthetic.txt": "examples\n", + "apps/presentation/synthetic.txt": "presentation\n", + ".github/synthetic.txt": "workflows\n", + "README.md": "Synthetic runtime\n", + "LICENSE": "license\n", + "pyproject.toml": '[project]\nversion = "1.2.3"\n', + "setup.py": "# Synthetic setup\n", + "MANIFEST.in": "# Synthetic manifest\n", + } + for name, content in fixture_files.items(): + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + env = { + **os.environ, + "GIT_AUTHOR_NAME": "Fixture Author", + "GIT_COMMITTER_NAME": "Fixture Author", + "GIT_AUTHOR_EMAIL": "fixture@example.invalid", + "GIT_COMMITTER_EMAIL": "fixture@example.invalid", + } + for args in (("init", "--quiet"), ("add", "--", *fixture_files), + ("-c", "commit.gpgSign=false", "commit", "--quiet", "-m", "Synthetic runtime")): + subprocess.run(["git", *args], cwd=self.root, env=env, check=True, capture_output=True) + self.revision = subprocess.check_output( + ["git", "rev-parse", "HEAD"], cwd=self.root, text=True + ).strip() + chat = self.root / "loopx/web/chat" + chat.mkdir(parents=True) + (chat / "bundle-manifest.json").write_text( + json.dumps({"source_revision": self.revision, "source_files": {}}), + encoding="utf-8", + ) + + def previous_outputs(self): + destination = self.root / "apps/desktop/loopx-control-plane/runtime" + destination.mkdir(parents=True) + archive = destination / "runtime-source.tar.gz" + identity = destination / "identity.json" + archive.write_bytes(b"previous archive") + identity.write_bytes(b"previous identity") + return archive, identity + + def test_unqualified_default_keeps_previous_archive_and_identity(self): + archive, identity = self.previous_outputs() + with patch.object(bundle, "observe_default_contract", return_value={"surface": "unsupported"}): + with self.assertRaisesRegex(ValueError, "unqualified for public adoption"): + bundle.build(self.root) + + self.assertEqual(archive.read_bytes(), b"previous archive") + self.assertEqual(identity.read_bytes(), b"previous identity") + self.assertEqual(set(archive.parent.iterdir()), {archive, identity}) + + def test_supported_default_publishes_identity_for_exact_archive(self): + from loopx.cli_commands.update_artifact import PUBLIC_DEFAULT_CONTRACT + + archive, identity_file = self.previous_outputs() + (self.root / "README.md").write_text("Uncommitted source\n", encoding="utf-8") + + def observe(source: Path): + self.assertEqual((source / "README.md").read_text(), "Synthetic runtime\n") + return PUBLIC_DEFAULT_CONTRACT + + with patch.object(bundle, "observe_default_contract", side_effect=observe): + bundle.build(self.root) + + identity = json.loads(identity_file.read_text()) + self.assertEqual(identity["source_revision"], self.revision) + self.assertEqual(identity["package_version"], "1.2.3") + self.assertEqual(identity["default_contract"], PUBLIC_DEFAULT_CONTRACT) + self.assertEqual(identity["sha256"], hashlib.sha256(archive.read_bytes()).hexdigest()) + + def test_identity_replacement_failure_restores_previous_archive(self): + from loopx.cli_commands.update_artifact import PUBLIC_DEFAULT_CONTRACT + + archive, identity = self.previous_outputs() + real_replace = Path.replace + + def replace(path: Path, target: Path): + if target == identity: + raise OSError("synthetic identity replacement failure") + return real_replace(path, target) + + with ( + patch.object(bundle, "observe_default_contract", return_value=PUBLIC_DEFAULT_CONTRACT), + patch.object(Path, "replace", replace), + self.assertRaisesRegex(OSError, "synthetic identity replacement failure"), + ): + bundle.build(self.root) + + self.assertEqual(archive.read_bytes(), b"previous archive") + self.assertEqual(identity.read_bytes(), b"previous identity") + self.assertEqual(set(archive.parent.iterdir()), {archive, identity}) + + class ArchiveQualificationTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory()