diff --git a/changelog.d/5877.changed.md b/changelog.d/5877.changed.md new file mode 100644 index 0000000000..134cafad35 --- /dev/null +++ b/changelog.d/5877.changed.md @@ -0,0 +1 @@ +- Local plugin re-passes no longer walk and hash each cached copy a second time; a package changed while install was running now stops install instead of re-copying. (#5877) diff --git a/src/apm_cli/install/deployable_source_plan.py b/src/apm_cli/install/deployable_source_plan.py index b5bfe228c1..a7c0d8a833 100644 --- a/src/apm_cli/install/deployable_source_plan.py +++ b/src/apm_cli/install/deployable_source_plan.py @@ -336,7 +336,9 @@ def add_direct_matching_files( ): continue skill_source_roots.add(portable_relpath(skill_dir, source_root)) - for path in tree_files(skill_dir): + skill_files = list(tree_files(skill_dir)) + _require_sealed_members(skill_dir, skill_files) + for path in skill_files: relative = path.relative_to(skill_dir) if skip_bin and relative.parts[0] == "bin": continue @@ -396,3 +398,21 @@ def copy_ignore(self, directory: str, contents: list[str]) -> list[str]: continue ignored.append(name) return ignored + + +def _require_sealed_members(skill_dir: Path, files: list[Path]) -> None: + """Refuse a sealed skill directory whose files are not exactly its verified members (#5838). + + A re-pass integrates a sealed image without walking it again; this walk is + the one that would see a member deleted or added after the seal. + """ + import sys + + registry = sys.modules.get("apm_cli.utils.sealed_files") + expected = None if registry is None else registry.members_under(skill_dir) + if expected is None: + return + walked = frozenset(portable_relpaths(files, skill_dir)) + if walked != expected: + changed = sorted(walked ^ expected)[0] + raise registry.changed_error(skill_dir / changed) diff --git a/src/apm_cli/install/local_plugin_image.py b/src/apm_cli/install/local_plugin_image.py index 7765d444e4..7bf45d609a 100644 --- a/src/apm_cli/install/local_plugin_image.py +++ b/src/apm_cli/install/local_plugin_image.py @@ -30,6 +30,8 @@ class ResolvedLocalPlugin: destination: Path # The name the image was normalized under, when it differs from the destination's. staged_name: str | None = None + # The token of the seal a re-pass verified this image under (#5838 slice 5b). + seal: object | None = None def _plain_legacy_plugin(dep_ref: Any, image: Path) -> tuple[bool, Path | None]: @@ -123,12 +125,14 @@ def reuse_resolved_local_plugin( every raw file resolve hashed, with the same bytes, and may add only what normalization writes (the synthesized manifest and ``.apm/``). Anything else, including a file turned into a link, takes the copy-and-validate path. + An image a re-pass sealed this command, still under that same seal, is taken + without a second walk: a member changed after the seal is refused where it is + planned, scanned or copied. """ from apm_cli.core.scope import manifest_file - from apm_cli.install.source_helpers import package_digests from apm_cli.models.apm_package import APMPackage from apm_cli.models.validation import PackageType - from apm_cli.utils.content_hash import package_payload_paths + from apm_cli.utils import sealed_files record = ctx.resolved_local_plugins.pop(dep_key, None) if record is None or install_path.is_symlink() or not install_path.is_dir(): @@ -137,24 +141,36 @@ def reuse_resolved_local_plugin( return None if not _validated_at(ctx, dep_key, install_path, record.destination): return None + # An image verified this command and still under that seal is the record's: + # every later reader takes its sealed or verified bytes (#5838 slice 5b). + sealed = record.seal is not None and sealed_files.seal_of(install_path, dep_key) is record.seal + if not sealed and not _still_recorded(ctx, record, install_path): + return None + package = APMPackage.from_apm_yml(manifest_file(install_path), source_path=source_path) + return record.digests, package, PackageType.MARKETPLACE_PLUGIN + + +def _still_recorded(ctx: Any, record: ResolvedLocalPlugin, install_path: Path) -> bool: + """Whether *install_path* still holds the raw files and digest *record* hashed.""" + from apm_cli.core.scope import manifest_file + from apm_cli.install.source_helpers import package_digests + from apm_cli.utils.content_hash import package_payload_paths + apm_yml = manifest_file(install_path) if not apm_yml.is_file(): - return None + return False current = package_payload_paths(install_path) added = current - record.files synthesized = {apm_yml.name} if not record.files <= current or any( path not in synthesized and not path.startswith(".apm/") for path in added ): - return None + return False if record.staged_name is not None and _names_staging( install_path, added, apm_yml, record.staged_name ): - return None - if package_digests(ctx, install_path, exclude=added) != record.digests: - return None - package = APMPackage.from_apm_yml(apm_yml, source_path=source_path) - return record.digests, package, PackageType.MARKETPLACE_PLUGIN + return False + return package_digests(ctx, install_path, exclude=added) == record.digests # -- Re-pass of an unchanged local plugin (#5838 slice 8) ---------------------- @@ -432,7 +448,7 @@ def reuse_unchanged_local_plugin( "reinstalled from source" ) return False - sealed_files.seal_image( + token = sealed_files.seal_image( install_path, { manifest_file(install_path).name: seal.manifest, @@ -440,9 +456,10 @@ def reuse_unchanged_local_plugin( }, seal.members, owner=dep_ref.get_display_name(), + key=dep_key, ) ctx.resolved_local_plugins[dep_key] = ResolvedLocalPlugin( - seal.digests, seal.files, install_path.resolve() + seal.digests, seal.files, install_path.resolve(), seal=token ) ctx.sealed_local_plugins[dep_key] = seal return True diff --git a/src/apm_cli/install/primitive_classification.py b/src/apm_cli/install/primitive_classification.py index 7603e61c29..35cbad7a76 100644 --- a/src/apm_cli/install/primitive_classification.py +++ b/src/apm_cli/install/primitive_classification.py @@ -117,14 +117,23 @@ def warn_unrecognized_plugin_schema(diagnostics, package_key: str, install_path: """Surface non-fatal plugin schema identification misses.""" if diagnostics is None: return - from apm_cli.agent_plugins.io import read_json_document + import sys + + from apm_cli.agent_plugins.io import decode_json_document, read_json_document from apm_cli.utils.helpers import find_plugin_json plugin_json_path = find_plugin_json(install_path) if plugin_json_path is None or not plugin_json_path.is_file(): return + registry = sys.modules.get("apm_cli.utils.sealed_files") # loaded only by install + # A sealed image's manifest is judged in its verified bytes (#5838). + verified = None if registry is None else registry.read_sealed(plugin_json_path) try: - document = read_json_document(plugin_json_path) + document = ( + read_json_document(plugin_json_path) + if verified is None + else decode_json_document(verified, path=plugin_json_path) + ) except (OSError, ValueError): return if not isinstance(document, dict): diff --git a/src/apm_cli/integration/write_seam.py b/src/apm_cli/integration/write_seam.py index c0e3b29e58..28f96d7a96 100644 --- a/src/apm_cli/integration/write_seam.py +++ b/src/apm_cli/integration/write_seam.py @@ -260,14 +260,11 @@ def copy2(source: Path, destination: Path) -> Path: A member of a sealed image (#5838) is copied only from its verified bytes. """ - from apm_cli.utils.sealed_files import member_digest, sealed - - digest = member_digest(source) - if digest is not None: - synthesized = sealed(source) - if synthesized is not None: # a verified synthesized file: its sealed bytes - return _copy2_bytes(source, destination, synthesized) - return _copy2_verified(source, destination, digest) + from apm_cli.utils.sealed_files import read_sealed + + verified = read_sealed(source) + if verified is not None: # deploy only the bytes that were verified + return _copy2_bytes(source, destination, verified) record_before_write( destination, follow=True, @@ -280,31 +277,6 @@ def copy2(source: Path, destination: Path) -> Path: return copied -def _copy2_verified(source: Path, destination: Path, digest: str) -> Path: - """``copy2`` of a sealed image member: deploy only the bytes that were verified (#5838). - - The member is read once; those bytes are hashed against *digest* and are - the bytes written, so a swap after verification is either refused here or - never read. The destination is never hashed. Raises - :class:`~apm_cli.utils.sealed_files.SealedImageChangedError` on a mismatch, - before anything is written. - """ - import hashlib - - from apm_cli.core.remediation import SEALED_IMAGE_CHANGED - from apm_cli.utils.sealed_files import SealedImageChangedError, sealed_owner - - owner = sealed_owner(source) - - data = Path(source).read_bytes() - if hashlib.sha256(data).hexdigest() != digest: - raise SealedImageChangedError( - f"The cached copy of {owner} changed while it was being installed; " - f"nothing was recorded. {SEALED_IMAGE_CHANGED.sentence()}" - ) - return _copy2_bytes(source, destination, data) - - def _copy2_bytes(source: Path, destination: Path, data: bytes) -> Path: """``copy2`` that writes *data* (*source*'s verified content) with *source*'s metadata.""" from apm_cli.utils.content_hash import exact_hash_of_bytes diff --git a/src/apm_cli/security/content_scanner.py b/src/apm_cli/security/content_scanner.py index 92d599beb7..7becd2a9b3 100644 --- a/src/apm_cli/security/content_scanner.py +++ b/src/apm_cli/security/content_scanner.py @@ -10,6 +10,7 @@ """ import re +import sys import unicodedata from dataclasses import dataclass from pathlib import Path @@ -274,8 +275,14 @@ def scan_file(path: Path) -> list[ScanFinding]: Handles encoding errors gracefully — returns an empty list if the file cannot be decoded as UTF-8 (binary files, etc.). """ + registry = sys.modules.get("apm_cli.utils.sealed_files") # loaded only by install + # A sealed image member is scanned in the bytes it will be deployed with (#5838). + verified = None if registry is None else registry.read_sealed(path) try: - content = path.read_text(encoding="utf-8") + if verified is not None: + content = verified.decode("utf-8") + else: + content = path.read_text(encoding="utf-8") except (UnicodeDecodeError, OSError): return [] return ContentScanner.scan_text(content, filename=str(path)) diff --git a/src/apm_cli/utils/sealed_files.py b/src/apm_cli/utils/sealed_files.py index ac6ee5e61a..efce72703f 100644 --- a/src/apm_cli/utils/sealed_files.py +++ b/src/apm_cli/utils/sealed_files.py @@ -23,12 +23,35 @@ _FILES: dict[str, bytes] = {} _MEMBERS: dict[str, str] = {} _ROOTS: dict[str, str] = {} +# Root -> (dependency key, the token its seal returned): integrate binds to that object. +_SEALS: dict[str, tuple[str, object]] = {} class SealedImageChangedError(RuntimeError): """A sealed image member changed between its verification and its deployment.""" +def changed_error(path: str | Path) -> SealedImageChangedError: + """The one refusal for sealed member *path*: changed, deleted or added after its seal. + + It names the plugin and the member path relative to its image. + """ + from apm_cli.core.remediation import SEALED_IMAGE_CHANGED + from apm_cli.utils.diagnostics import printable_ascii_text + + key = _key(path) + with _LOCK: + roots = [root for root in _ROOTS if key.startswith(root + os.sep)] + root = max(roots, key=len) if roots else "" + owner = _ROOTS.get(root, "") + member = key[len(root) + 1 :].replace(os.sep, "/") if root else os.fspath(path) + return SealedImageChangedError( + f"The cached copy of {owner} changed while it was being installed " + f"({printable_ascii_text(member)}); nothing was recorded. " + f"{SEALED_IMAGE_CHANGED.sentence()}" + ) + + def _key(path: str | Path) -> str: return os.path.normcase(os.path.normpath(os.path.abspath(os.fspath(path)))) @@ -43,22 +66,32 @@ def reset() -> None: _FILES.clear() _MEMBERS.clear() _ROOTS.clear() + _SEALS.clear() def seal_image( - root: str | Path, files: dict[str, bytes], members: dict[str, str], *, owner: str = "" -) -> None: + root: str | Path, + files: dict[str, bytes], + members: dict[str, str], + *, + owner: str = "", + key: str = "", +) -> object: """Serve *files* (relative path -> bytes) and bind *members* (relative path -> sha256). - *owner* names the plugin in a refusal. + *owner* names the plugin in a refusal. Returns this seal's token: :func:`seal_of` + answers it for (*root*, *key*) until the image is unsealed or sealed again. """ + token = object() with _LOCK: for base in _forms(root): _ROOTS[base] = owner or Path(root).name + _SEALS[base] = (key, token) for relative, data in files.items(): _FILES[_key(os.path.join(base, relative))] = data for relative, digest in members.items(): _MEMBERS[_key(os.path.join(base, relative))] = digest + return token def unseal_image(root: str | Path) -> None: @@ -66,6 +99,7 @@ def unseal_image(root: str | Path) -> None: with _LOCK: for base in _forms(root): _ROOTS.pop(base, None) + _SEALS.pop(base, None) prefix = base + os.sep for table in (_FILES, _MEMBERS): for key in [key for key in table if key.startswith(prefix)]: @@ -101,3 +135,48 @@ def member_digest(path: str | Path) -> str | None: if any(key.startswith(root + os.sep) for root in _ROOTS): return "" return None + + +def seal_of(root: str | Path, key: str) -> object | None: + """The token of the seal on *root* made for *key*, or None.""" + with _LOCK: + entry = _SEALS.get(_key(root)) + return entry[1] if entry is not None and entry[0] == key else None + + +def members_under(directory: str | Path) -> frozenset[str] | None: + """The bound members below *directory*, relative to it, or None when it is not sealed.""" + base = _key(directory) + os.sep + with _LOCK: + if not any(base.startswith(root + os.sep) for root in _ROOTS): + return None + return frozenset( + key[len(base) :].replace(os.sep, "/") for key in _MEMBERS if key.startswith(base) + ) + + +def read_sealed(path: str | Path) -> bytes | None: + """The single reader of a sealed image member: the bytes to scan, parse or copy. + + None when *path* is in no sealed image. A synthesized file is served from its + seal; any other member is read once and that buffer is returned only when it + hashes to the member's bound digest. A member changed, deleted or added after + the seal raises :func:`changed_error`; it is never skipped. + """ + import hashlib + + digest = member_digest(path) + if digest is None: + return None + synthesized = sealed(path) + if synthesized is not None: + return synthesized + if not digest: # under a sealed image, but no member was verified there + raise changed_error(path) + try: + data = Path(path).read_bytes() + except OSError as exc: + raise changed_error(path) from exc + if hashlib.sha256(data).hexdigest() != digest: + raise changed_error(path) + return data diff --git a/tests/benchmarks/spawn_counter/sitecustomize.py b/tests/benchmarks/spawn_counter/sitecustomize.py index 026a88897b..524ada8dc0 100644 --- a/tests/benchmarks/spawn_counter/sitecustomize.py +++ b/tests/benchmarks/spawn_counter/sitecustomize.py @@ -15,7 +15,7 @@ ``APM_PERF_COUNT_CALLS=1`` also counts top-level ``shutil.copytree`` calls and ``normalize_plugin_directory``, ``discover_primitives`` (every primitive discovery) -and ``planned_skill_files`` calls, the install hint's instruction walks +``planned_skill_files``, ``package_payload_paths`` and ``package_digests`` calls, the install hint's instruction walks (``_parsed_instructions``) and listed directories (``_hint_listing``) and ``Path.home()`` lookups (the ``calls`` table, #5838). They are engine invariants, not budget rows. @@ -158,6 +158,8 @@ def _copytree(*a, **k): "apm_cli.primitives.discovery": ("discover_primitives",), "apm_cli.compilation.user_root_context": ("_parsed_instructions", "_hint_listing"), "apm_cli.integration.skill_preflight": ("planned_skill_files",), + "apm_cli.utils.content_hash": ("package_payload_paths",), + "apm_cli.install.source_helpers": ("package_digests",), } class _CallCounter(importlib.abc.MetaPathFinder): diff --git a/tests/integration/test_local_plugin_repass_cost.py b/tests/integration/test_local_plugin_repass_cost.py index 7e5ef1fe2a..964da4b7bf 100644 --- a/tests/integration/test_local_plugin_repass_cost.py +++ b/tests/integration/test_local_plugin_repass_cost.py @@ -171,6 +171,14 @@ def test_repass_normalizes_only_what_cannot_prove_itself(mutation: str, repasses assert run["calls"].get("copytree", 0) <= _EXPECTED_NORMALIZE[mutation], run["calls"] +def test_an_unchanged_repass_never_walks_a_sealed_image_again(repasses) -> None: + """5b-a: integrate takes the payload and digests of the 23 sealed images from + their seals; the walks were 23 each before.""" + calls = repasses["unchanged"]["calls"] + assert calls.get("package_payload_paths", 0) == 0, calls + assert calls.get("package_digests", 0) == 0, calls + + @pytest.mark.parametrize("mutation", list(_MUTATIONS)) def test_repass_plans_only_what_cannot_replay(mutation: str, repasses) -> None: """A verified unchanged plugin replays its deploy: no discovery, no planning (#5838 8b).""" @@ -201,14 +209,29 @@ def test_repass_deploys_the_source_bytes(mutation: str, repasses) -> None: _SWAP = """ +import json + import apm_cli.install.local_plugin_image as image _SKILL = ("skills", "np00-s0", "SKILL.md") def _swap(install_path): + action = "{action}" member = install_path.joinpath(*_SKILL) - member.write_bytes(member.read_bytes() + b"\\nswapped\\n") + if action == "append": + member.write_bytes(member.read_bytes() + b"\\nswapped-5838\\n") + elif action == "hidden": + member.write_bytes(member.read_bytes() + "\\nswapped-5838 \\u202e\\n".encode()) + elif action == "delete": + install_path.joinpath("skills", "np00-s0", "references", "ref0.md").unlink() + elif action == "add": + install_path.joinpath("skills", "np00-s0", "added.md").write_bytes(b"# swapped-5838\\n") + elif action == "schema": + manifest = install_path / ".claude-plugin" / "plugin.json" + data = json.loads(manifest.read_text(encoding="utf-8")) + data["$schema"] = "https://swapped-5838.invalid/plugin.json" + manifest.write_text(json.dumps(data), encoding="utf-8") _seal = image.reuse_unchanged_local_plugin @@ -244,7 +267,7 @@ def _state(home: Path, config_root: Path) -> dict[str, bytes]: return state -def _swap_run(apm: list[str], tmp_path: Path, point: str) -> dict: +def _swap_run(apm: list[str], tmp_path: Path, point: str, action: str = "append") -> dict: import os import subprocess @@ -262,34 +285,78 @@ def _swap_run(apm: list[str], tmp_path: Path, point: str) -> dict: before = _state(isolated.home, isolated.config_root) inject = tmp_path / "inject" inject.mkdir() - (inject / "sitecustomize.py").write_text(_SWAP.replace("{point}", point), encoding="ascii") + (inject / "sitecustomize.py").write_text( + _SWAP.replace("{point}", point).replace("{action}", action), encoding="ascii" + ) path = os.pathsep.join(p for p in (str(inject), env.get("PYTHONPATH", "")) if p) run = subprocess.run( argv, cwd=isolated.home, env={**env, "PYTHONPATH": path}, capture_output=True, text=True ) image = isolated.config_root / "apm_modules" / "_local" / _EDITED / "skills" / _SKILL + after = _state(isolated.home, isolated.config_root) + was_deployed = deployed.read_bytes() if deployed.exists() else None + # The printed hint, run as a new command with no injection. + hint = subprocess.run(argv, cwd=isolated.home, env=env, capture_output=True, text=True) return { "run": run, "before": before, - "after": _state(isolated.home, isolated.config_root), - "deployed": deployed.read_bytes() if deployed.exists() else None, + "after": after, + "deployed": was_deployed, + "hint": hint, + "healed": _state(isolated.home, isolated.config_root), + "healed_deployed": deployed.read_bytes() if deployed.exists() else None, "image": (image / "SKILL.md").read_bytes(), "source": (plugins.new[0] / "skills" / _SKILL / "SKILL.md").read_bytes(), } -def test_a_member_swapped_after_the_resolve_seal_is_restored_from_source( +def _assert_fails_closed(out: dict) -> None: + """The install stops with the sealed-image refusal before it writes or records anything.""" + run = out["run"] + output = run.stdout + run.stderr + assert run.returncode != 0, output[-3000:] + assert "The cached copy of" in output and "changed while it was being installed" in output + assert "Run 'apm install' to reinstall the plugin from its source." in output + assert f"{_EDITED} changed while it was being installed (" in output, output[-3000:] + assert out["after"] == out["before"] + assert out["deployed"] is None + # The hint heals it: a new install re-verifies, reinstalls from source, exits 0. + hint = out["hint"] + assert hint.returncode == 0, hint.stdout[-3000:] + hint.stderr[-3000:] + assert out["healed_deployed"] == out["source"] + assert not [path for path, data in out["healed"].items() if b"swapped-5838" in data] + assert not any(path.endswith("added.md") for path in out["healed"]) + + +@pytest.mark.parametrize("action", ["append", "delete", "add"]) +def test_an_image_changed_after_the_resolve_seal_fails_closed( + apm_engine_command, tmp_path: Path, action: str +) -> None: + """5b-a (S1, S2): integrate takes the seal resolve made this command (no second + walk), so an edited, deleted or added member after it is refused at the plan or + the copy: nothing is deployed or recorded, and the next install restores it.""" + _assert_fails_closed(_swap_run(list(apm_engine_command), tmp_path, "resolve", action)) + + +def test_a_parsed_manifest_changed_after_the_seal_never_takes_effect( apm_engine_command, tmp_path: Path ) -> None: - """C4, restore branch: integrate re-hashes the image (#5839), sees the swap, and - re-materializes the image from the local SOURCE; the deployment is copied from - that fresh copy. The swapped bytes are never deployed or recorded.""" - out = _swap_run(list(apm_engine_command), tmp_path, "resolve") - run = out["run"] - assert run.returncode == 0, run.stdout[-3000:] + run.stderr[-3000:] - assert out["image"] == out["source"] # re-copied from source, the swap is gone - assert out["deployed"] == out["source"] - assert not any(b"\nswapped\n" in data for data in out["after"].values()) + """5b-a (S4): plugin.json is parsed, never copied: integrate reads it only through + the sealed reader, which refuses it; the swapped declaration never takes effect.""" + out = _swap_run(list(apm_engine_command), tmp_path, "resolve", "schema") + output = out["run"].stdout + out["run"].stderr + assert "swapped-5838" not in output, output[-3000:] + _assert_fails_closed(out) + assert "(.claude-plugin/plugin.json)" in output, output[-3000:] + + +def test_the_scanner_reads_the_sealed_bytes(apm_engine_command, tmp_path: Path) -> None: + """5b-a (S5): the pre-deploy scan of a sealed image judges the verified bytes: a + member swapped after the seal is refused, never scanned in their place.""" + out = _swap_run(list(apm_engine_command), tmp_path, "integrate", "hidden") + output = out["run"].stdout + out["run"].stderr + assert "hidden character" not in output, output[-3000:] + _assert_fails_closed(out) def test_a_member_swapped_after_integrate_trusted_the_image_fails_closed( @@ -298,14 +365,7 @@ def test_a_member_swapped_after_integrate_trusted_the_image_fails_closed( """C4, refusal branch: integrate already reuses the sealed image, so neither the image (swapped) nor the source (not re-read) may serve the copy; the copy reads the member once, its digest differs, and the install stops before recording.""" - out = _swap_run(list(apm_engine_command), tmp_path, "integrate") - run = out["run"] - output = run.stdout + run.stderr - assert run.returncode != 0, output[-3000:] - assert "The cached copy of" in output and "changed while it was being installed" in output - assert "Run 'apm install' to reinstall the plugin from its source." in output - assert out["after"] == out["before"] - assert out["deployed"] is None + _assert_fails_closed(_swap_run(list(apm_engine_command), tmp_path, "integrate")) _THREE_RUNS = """ diff --git a/tests/unit/install/test_local_plugin_image.py b/tests/unit/install/test_local_plugin_image.py index 33bcfcdc20..b66533a27e 100644 --- a/tests/unit/install/test_local_plugin_image.py +++ b/tests/unit/install/test_local_plugin_image.py @@ -905,3 +905,68 @@ def test_the_commit_gate_sees_every_replayed_plan() -> None: ) gated = gate_plans(planned, {"pkg-b": replay}) assert gated == {"pkg-a": planned["pkg-a"], "pkg-b": plan} + + +# -- slice 5b-a: integrate takes a seal made this command, never a second walk + + +def _sealed_this_command(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """Resolve's re-pass half: the image is sealed and validated in this command.""" + from apm_cli.install import source_helpers + from apm_cli.install.local_plugin_image import reuse_unchanged_local_plugin + from apm_cli.utils import content_hash + + source, image, modules, locked = _sealed_world(tmp_path) + ctx = _ctx() + ctx.sealed_local_plugins = {} + ctx.existing_lockfile = SimpleNamespace( + framed_content_hashes=True, + get_dependency=lambda key: SimpleNamespace(content_hash=locked), + ) + dep_ref = SimpleNamespace(get_unique_key=lambda: "probe", get_display_name=lambda: "probe") + assert reuse_unchanged_local_plugin(ctx, dep_ref, source, image, modules, None) + _validate(ctx, {"probe": SimpleNamespace(package=SimpleNamespace(package_path=image))}) + walks: list[str] = [] + for module, name in ( + (content_hash, "package_payload_paths"), + (source_helpers, "package_digests"), + ): + real = getattr(module, name) + + def spy(*args, _real=real, _name=name, **kwargs): + walks.append(_name) + return _real(*args, **kwargs) + + monkeypatch.setattr(module, name, spy) + return ctx, source, image, walks + + +def test_an_image_sealed_this_command_is_reused_without_a_second_walk( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from apm_cli.core.invocation_memo import invocation_scope + + with invocation_scope(): + ctx, source, image, walks = _sealed_this_command(tmp_path, monkeypatch) + seal = ctx.sealed_local_plugins["probe"] + reused = reuse_resolved_local_plugin(ctx, "probe", image, source) + assert reused is not None + assert reused[0] == seal.digests + assert walks == [] + + +@pytest.mark.parametrize("rewrite", ["unsealed", "resealed"]) +def test_an_image_rewritten_after_its_seal_never_takes_the_record( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rewrite: str +) -> None: + """S3: a re-copy drops (or replaces) the seal, so integrate walks the image again.""" + from apm_cli.core.invocation_memo import invocation_scope + from apm_cli.utils import sealed_files + + with invocation_scope(): + ctx, source, image, walks = _sealed_this_command(tmp_path, monkeypatch) + sealed_files.unseal_image(image) + if rewrite == "resealed": + sealed_files.seal_image(image, {}, {}, owner="probe") + reuse_resolved_local_plugin(ctx, "probe", image, source) + assert "package_payload_paths" in walks