diff --git a/docs/ENTREGA_1_7.md b/docs/ENTREGA_1_7.md index 0202fe9..e76b94e 100644 --- a/docs/ENTREGA_1_7.md +++ b/docs/ENTREGA_1_7.md @@ -45,6 +45,8 @@ No chão, a zona central de 15–85% agora alcança a tela inteira. A mira à fr As funções auxiliares sem uso foram removidas. A busca de rota separa agrupamento de ameaças e cálculo de células seguras; seus testes preservam os intervalos e predicados de segurança. O modelo de perfil saiu de `persistence.py`. Fontes e ajuste de texto usam os helpers compartilhados nos caminhos alterados. +O empacotador verifica o `manifest.json` compilado pelo TSDK contra o contrato de autoria em `ttea.toml`. Confere versão, commit limpo, campos e tipos, além dos bytes de fontes e imagens; rejeita chaves duplicadas e procedência divergente. O TOML de autoria não precisa estar no cartucho distribuído. + As notas das entregas anteriores estão em [histórico](historico/README.md). O README e a descrição do repositório explicam o jogo em linguagem direta. Onze branches já mescladas foram removidas após conferência dos commits; suas alterações continuam na história da main e dos pull requests. ## Evidências e limites diff --git a/docs/validacao-v1.7/README.md b/docs/validacao-v1.7/README.md index 231f60c..15fbb6b 100644 --- a/docs/validacao-v1.7/README.md +++ b/docs/validacao-v1.7/README.md @@ -4,7 +4,7 @@ Os ensaios usam perfis sintéticos separados dos dados do jogador. Referência l ## Cobertura automatizada -- 610 testes de regras, cenas, persistência, câmera simulada e contratos portáteis em Python 3.8 e 3.12. [Execução de integração aprovada](https://github.com/lapsin-maker/dobramundo/actions/runs/40251066416); o manifesto da release identifica também a execução usada para os downloads. +- 610 testes de regras, cenas, persistência, câmera simulada e contratos portáteis em Python 3.8 e 3.12. [Execução de integração aprovada](https://github.com/lapsin-maker/dobramundo/actions/runs/40253155125). A correção final do empacotador acrescentou 18 casos de manifesto, com 31 testes focados aprovados localmente e conferência do cartucho real. O manifesto da release identifica a execução completa usada para os downloads finais. - Self-test: 14 telas, dois voos de 1.200 quadros interativos (20 segundos simulados cada) e carregamento real do detector, sem abrir a webcam. [Resultado da fonte](self-test.json). Os executáveis têm relatórios próprios no manifesto da release. - Cartucho: check/build do TSDK local e renderização do estágio isolado, sem procurar imagens no checkout: nove menus e dois voos com 900 passos, incluindo preparação. [Resultado](cartucho.json). - 35 capturas finais sem falha de geometria dos botões; quatro referências de menus com diferença de pixels igual a zero. A checagem de botões não substitui a revisão humana dos textos. [Capturas](capturas.json), [comparação](regressao-visual.json). diff --git a/tests/test_release_guards.py b/tests/test_release_guards.py index ff6e57d..4d4217e 100644 --- a/tests/test_release_guards.py +++ b/tests/test_release_guards.py @@ -9,12 +9,14 @@ from PIL import Image from dobramundo import __version__ +from dobramundo.content import texts from dobramundo.selftest import REQUIRED_SPRITES, check_report from tools.package_release import ( assert_clean_checkout, assert_tracked_inputs, github_run_id, portable_sources, + validate_cartridge_manifest, validate_cartridge_sources, validate_tar, verified_build, @@ -23,6 +25,84 @@ from tools.visual_regression import compare +def _built_cartridge_manifest(): + # TSDK compiles ttea.toml to this root JSON; authored TOML is not shipped. + return { + "id": "dobramundo", + "version": __version__, + "entrypoint": "dobramundo.cartridge:Dobramundo", + "format_version": 1, + "game_api": 1, + "builder": {"version": "0.1.0"}, + "build": {"source_commit": "a" * 40, "dirty": False}, + "requires_ttea": ">=2.0,<3", + "tracking_profile": "body", + "resolution": [1100, 650], + "assets": ["assets"], + "licenses": ["LICENSE", "CREDITOS.md"], + "name": {"pt-BR": "Dobramundo", "en": "Dobramundo"}, + "description": {"pt-BR": texts.TAGLINE, "en": "Fold the paper, fly and transform the city."}, + } + + +def test_release_accepts_tsdk_built_manifest_without_authored_toml(tmp_path): + path = tmp_path / "game.ttea" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("manifest.json", json.dumps(_built_cartridge_manifest())) + with zipfile.ZipFile(path) as archive: + assert "ttea.toml" not in archive.namelist() + assert validate_cartridge_manifest(archive, "a" * 40)["version"] == __version__ + + +@pytest.mark.parametrize( + "change", + [ + {"version": "0.0.0"}, + {"id": "other-game"}, + {"entrypoint": "other.game:Game"}, + {"format_version": 2}, + {"game_api": True}, + {"build": {"source_commit": "b" * 40, "dirty": False}}, + {"build": {"source_commit": "a" * 40, "dirty": True}}, + {"build": None}, + {"build": {"source_commit": "a" * 40, "dirty": False, "extra": True}}, + {"builder": {"version": "not a version"}}, + {"builder": {"version": "0.1.0", "extra": True}}, + {"assets": ["missing-assets"]}, + {"tracking_profile": "face"}, + {"extra": True}, + ], +) +def test_release_rejects_wrong_cartridge_identity_or_provenance(tmp_path, change): + manifest = _built_cartridge_manifest() + manifest.update(change) + path = tmp_path / "game.ttea" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("manifest.json", json.dumps(manifest)) + with zipfile.ZipFile(path) as archive, pytest.raises(ValueError): + validate_cartridge_manifest(archive, "a" * 40) + + +def test_release_rejects_duplicate_json_keys(tmp_path): + path = tmp_path / "game.ttea" + payload = json.dumps(_built_cartridge_manifest()) + payload = payload[:-1] + ', "version": "' + __version__ + '"}' + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("manifest.json", payload) + with zipfile.ZipFile(path) as archive, pytest.raises(ValueError, match="duplicada"): + validate_cartridge_manifest(archive, "a" * 40) + + +@pytest.mark.parametrize("names", [("ttea.toml",), ("manifest.json", "manifest.json")]) +def test_release_requires_unique_built_manifest(tmp_path, names): + path = tmp_path / "game.ttea" + with zipfile.ZipFile(path, "w") as archive: + for name in names: + archive.writestr(name, json.dumps(_built_cartridge_manifest())) + with zipfile.ZipFile(path) as archive, pytest.raises(ValueError, match="manifest.json"): + validate_cartridge_manifest(archive, "a" * 40) + + def test_build_guard_requires_native_detector(tmp_path): path = tmp_path / "self_test.json" path.write_text(json.dumps({"status": "ok", "camera": {"detector": "unavailable"}})) diff --git a/tools/package_release.py b/tools/package_release.py index 67960a7..da94e69 100644 --- a/tools/package_release.py +++ b/tools/package_release.py @@ -19,11 +19,18 @@ from pathlib import Path, PurePosixPath from typing import Dict, List, Optional +from packaging.version import InvalidVersion, Version + +try: + import tomllib +except ModuleNotFoundError: # Python 3.8 in the supported CI matrix + import tomli as tomllib + ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from dobramundo import __version__ # noqa: E402 -from tools.build_cartridge import DESKTOP_ONLY # noqa: E402 +from tools.build_cartridge import DESKTOP_ONLY, MANIFEST # noqa: E402 from tools.runtime_assets import runtime_assets # noqa: E402 @@ -138,6 +145,54 @@ def write_batch(path: Path, content: str) -> None: path.write_bytes(normalized.replace("\n", "\r\n").encode("ascii")) +def _unique_manifest_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("Chave duplicada no manifesto: " + key) + result[key] = value + return result + + +def validate_cartridge_manifest(archive: zipfile.ZipFile, expected_commit: str) -> dict: + """Check the built manifest emitted by TSDK, not the authored ttea.toml.""" + if archive.namelist().count("manifest.json") != 1: + raise ValueError("Cartucho precisa de um manifest.json único na raiz") + if archive.getinfo("manifest.json").file_size > 1024 * 1024: + raise ValueError("Manifesto do cartucho excede 1 MiB") + manifest = json.loads(archive.read("manifest.json"), object_pairs_hook=_unique_manifest_object) + if not isinstance(manifest, dict): + raise ValueError("Manifesto do cartucho precisa ser um objeto") + if manifest.get("version") != __version__: + raise ValueError("A versão do cartucho difere da release") + authored = tomllib.loads(MANIFEST)["game"] + if set(manifest) != set(authored) | {"format_version", "builder", "build"}: + raise ValueError("Campos do manifesto diferem do contrato de autoria") + # Compare the entire authored contract, including nested value types, without + # duplicating TSDK's general-purpose schema or our project's metadata. + actual_authored = {key: manifest[key] for key in authored} + if json.dumps(actual_authored, sort_keys=True) != json.dumps(authored, sort_keys=True): + raise ValueError("Identidade ou formato do cartucho incompatível") + if type(manifest["format_version"]) is not int or manifest["format_version"] != 1: + raise ValueError("Formato do cartucho incompatível") + builder = manifest["builder"] + if not isinstance(builder, dict) or set(builder) != {"version"} or not isinstance(builder["version"], str): + raise ValueError("Builder do cartucho inválido") + try: + Version(builder["version"]) + except InvalidVersion as exc: + raise ValueError("Versão do builder inválida") from exc + build = manifest.get("build") + if ( + not isinstance(build, dict) + or set(build) != {"source_commit", "dirty"} + or build["source_commit"] != expected_commit + or build["dirty"] is not False + ): + raise ValueError("Cartucho precisa vir do commit da release, sem alterações locais") + return manifest + + def validate_tar(path: Path) -> None: with tarfile.open(path, "r:gz") as archive: executable = archive.getmember("Dobramundo/Dobramundo") @@ -190,11 +245,9 @@ def package(args) -> dict: linux_tar = unique(args.linux, "Dobramundo-Linux.tar.gz") validate_tar(linux_tar) with zipfile.ZipFile(args.cartridge) as archive: - if archive.testzip() is not None or "ttea.toml" not in archive.namelist(): + if archive.testzip() is not None: raise ValueError("Cartucho incompleto ou corrompido") - manifest_text = archive.read("ttea.toml").decode("utf-8") - if re.search(r'^version\s*=\s*"' + re.escape(__version__) + r'"\s*$', manifest_text, re.MULTILINE) is None: - raise ValueError("A versão do cartucho difere da release") + validate_cartridge_manifest(archive, args.release_commit) validate_cartridge_sources(archive, ROOT) asset_records = list(runtime_assets(ROOT, console=True)) expected_asset_names = {"assets/" + relative.as_posix() for _source, relative in asset_records}