From f907ebea3c5b942596eb6e8be7f445a48e10cebf Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 12:14:42 +0100 Subject: [PATCH 01/11] fix(deps): one local parent reached by two relative spellings is not ambiguous (#4731) install --frozen refused a lockfile where ./packages/lib-05 (root) and ../lib-05 (sibling) both carry _local/lib-05. Resolve every parent candidate and refuse only when they anchor to different directories. Adds a failing-before installed-CLI lifecycle test and an owner unit case. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/deps/path_anchoring.py | 52 ++++++------ ..._local_monorepo_frozen_replay_lifecycle.py | 80 +++++++++++++++++++ tests/unit/deps/test_path_anchoring.py | 17 +++- 3 files changed, 124 insertions(+), 25 deletions(-) create mode 100644 tests/integration/test_local_monorepo_frozen_replay_lifecycle.py diff --git a/src/apm_cli/deps/path_anchoring.py b/src/apm_cli/deps/path_anchoring.py index 4d402d4ef3..9a196ac59d 100644 --- a/src/apm_cli/deps/path_anchoring.py +++ b/src/apm_cli/deps/path_anchoring.py @@ -218,35 +218,47 @@ def _resolve_dep_dir( ) seen.add(key) - parent = _find_parent(lockfile, dep, parent_index=parent_index) - parent_dir = _resolve_dep_dir( - parent, - lockfile, - project_root, - parent_index=parent_index, - resolved_cache=resolved_cache, - seen=seen, - ) - resolved = _join(parent_dir, dep.local_path) + parents = _find_parents(lockfile, dep, parent_index=parent_index) + parent_dirs = { + _resolve_dep_dir( + parent, + lockfile, + project_root, + parent_index=parent_index, + resolved_cache=resolved_cache, + seen=seen, + ) + for parent in parents + } + if len(parent_dirs) > 1: + raise LocalResolutionError( + f"ambiguous resolved_by parent {dep.resolved_by!r} of {dep.repo_url!r}: " + f"{len(parents)} local dependencies share that repo_url " + f"({sorted(p.local_path for p in parents if p.local_path)}) and anchor to " + f"different directories" + ) + resolved = _join(parent_dirs.pop(), dep.local_path) resolved_cache[key] = resolved seen.remove(key) return resolved -def _find_parent( +def _find_parents( lockfile: LockFile | None, dep: LockedDependency, *, parent_index: dict[str, tuple[LockedDependency, ...]], -) -> LockedDependency: - """Find the unique local parent of *dep* by ``repo_url == resolved_by``. +) -> tuple[LockedDependency, ...]: + """Find the local parent candidates of *dep* by ``repo_url == resolved_by``. ``resolved_by`` carries the parent's ``repo_url`` (e.g. ``_local/foo``), NOT its ``local_path``; and the lockfile dict is keyed by ``get_unique_key()`` (``local_path`` for locals), so the parent cannot be looked up by key -- we scan by ``repo_url``. Because ``_local/`` - is basename-derived it is NOT guaranteed unique, so a duplicate match is - a hard error rather than a silent first-wins pick. + is basename-derived it is NOT guaranteed unique: one directory reached + through two relative spellings (``./packages/lib`` from the root and + ``../lib`` from a sibling) yields several candidates, and the caller + refuses only when they anchor to different directories. """ if lockfile is None: raise LocalResolutionError( @@ -259,17 +271,11 @@ def _find_parent( raise LocalResolutionError( f"resolved_by parent {dep.resolved_by!r} of {dep.repo_url!r} is not a locked local source" ) - return parent + return (parent,) matches = parent_index.get(dep.resolved_by, ()) if not matches: raise LocalResolutionError( f"resolved_by parent {dep.resolved_by!r} of {dep.repo_url!r} " f"(local_path={dep.local_path!r}) is not a local dependency in the lockfile" ) - if len(matches) > 1: - raise LocalResolutionError( - f"ambiguous resolved_by parent {dep.resolved_by!r} of {dep.repo_url!r}: " - f"{len(matches)} local dependencies share that repo_url " - f"({sorted(m.local_path for m in matches if m.local_path)})" - ) - return matches[0] + return matches diff --git a/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py new file mode 100644 index 0000000000..639a97e513 --- /dev/null +++ b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py @@ -0,0 +1,80 @@ +"""A monorepo lib reached through two relative spellings replays with --frozen (#4731). + +PROMISE: lockfile.frozen_preserves_bytes -- ``apm install --frozen`` replays the +lockfile ``apm install`` just wrote, without changing the lockfile or the deployed +files (source: issue #4731 scope record). +CELL: OP=install FROZEN=on SRC=local(transitive, two spellings) PRIM=skill SCOPE=project +""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +from tests.utils.apm_lifecycle_runner import ApmLifecycleRunner, CommandResult +from tests.utils.artifact_snapshot import ArtifactSnapshot, assert_unchanged +from tests.utils.isolated_apm_environment import IsolatedApmEnvironment + +pytestmark = [ + pytest.mark.integration, + pytest.mark.e2e, + pytest.mark.promise("P-INV-I2", "P-INV-I3"), + pytest.mark.requires_apm_binary, +] + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="ascii") + + +def _package(root: Path, name: str, deps: tuple[str, ...] = ()) -> None: + manifest = f"name: {name}\nversion: 1.0.0\n" + if deps: + manifest += "dependencies:\n apm:\n" + "".join(f" - {dep}\n" for dep in deps) + _write(root / "apm.yml", manifest) + _write( + root / ".apm" / "skills" / f"{name}-skill" / "SKILL.md", + f"---\nname: {name}-skill\ndescription: {name} skill\n---\n{name} body\n", + ) + + +def _evidence(result: CommandResult) -> str: + return f"exit={result.returncode}\nstdout={result.stdout}\nstderr={result.stderr}" + + +def test_frozen_replays_a_lib_reached_by_two_relative_spellings( + tmp_path: Path, apm_binary_path: Path +) -> None: + isolated = IsolatedApmEnvironment.create(tmp_path / "world", base_env=dict(os.environ)) + env = isolated.subprocess_env() + runner = ApmLifecycleRunner((str(apm_binary_path),), timeout_seconds=240) + root = isolated.work_root / "monorepo" + packages = root / "packages" + _package(packages / "lib-06", "lib-06") + _package(packages / "lib-05", "lib-05", ("../lib-06",)) + _package(packages / "lib-04", "lib-04", ("../lib-05",)) + _write( + root / "apm.yml", + "name: monorepo\nversion: 1.0.0\ntargets: [claude]\n" + "dependencies:\n apm:\n - ./packages/lib-04\n - ./packages/lib-05\n", + ) + (root / ".claude").mkdir() + + installed = runner.run(("install",), cwd=root, env=env) + assert installed.returncode == 0, _evidence(installed) + lock = (root / "apm.lock.yaml").read_bytes() + deployed = ArtifactSnapshot.capture(root / ".claude") + for name in ("lib-04", "lib-05", "lib-06"): + assert (root / ".claude" / "skills" / f"{name}-skill" / "SKILL.md").is_file() + + frozen = runner.run(("install", "--frozen"), cwd=root, env=env) + + assert frozen.returncode == 0, _evidence(frozen) + assert "ambiguous resolved_by parent" not in frozen.stdout + frozen.stderr + assert (root / "apm.lock.yaml").read_bytes() == lock + assert_unchanged(deployed, ArtifactSnapshot.capture(root / ".claude")) + audit = runner.run(("audit", "--ci"), cwd=root, env=env) + assert audit.returncode == 0, _evidence(audit) diff --git a/tests/unit/deps/test_path_anchoring.py b/tests/unit/deps/test_path_anchoring.py index bc3260e6f1..adbce48638 100644 --- a/tests/unit/deps/test_path_anchoring.py +++ b/tests/unit/deps/test_path_anchoring.py @@ -102,8 +102,8 @@ def test_shared_index_and_cache_resolve_chain_linearly(self, tmp_path: Path) -> lockfile = _lockfile(*dependencies) with patch.object( path_anchoring, - "_find_parent", - wraps=path_anchoring._find_parent, + "_find_parents", + wraps=path_anchoring._find_parents, ) as find_parent: resolved = resolve_local_dep_dirs(lockfile, tmp_path) @@ -133,6 +133,19 @@ def test_ambiguous_parent_raises(self, tmp_path: Path) -> None: with pytest.raises(LocalResolutionError, match="ambiguous"): resolve_local_dep_dir(child, _lockfile(dup_a, dup_b, child), tmp_path) + def test_parents_anchoring_to_one_directory_are_one_parent(self, tmp_path: Path) -> None: + """#4731: ./packages/lib from the root and ../lib from a sibling are one parent.""" + sibling = _local("_local/lib-04", "./packages/lib-04") + from_root = _local("_local/lib-05", "./packages/lib-05") + from_sibling = _local("_local/lib-05", "../lib-05", resolved_by="_local/lib-04") + child = _local("_local/lib-06", "../lib-06", resolved_by="_local/lib-05") + lock = _lockfile(sibling, from_root, from_sibling, child) + + assert ( + resolve_local_dep_dir(child, lock, tmp_path) + == (tmp_path / "packages" / "lib-06").resolve() + ) + def test_cycle_raises(self, tmp_path: Path) -> None: a = _local("_local/a", "../a", resolved_by="_local/b") b = _local("_local/b", "../b", resolved_by="_local/a") From 5069b583ce39a6d8a46425605da3d077fc32e69f Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 12:33:54 +0100 Subject: [PATCH 02/11] test(deps): different-directory parents stay ambiguous; changelog (#4731) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- changelog.d/4739.fixed.md | 1 + tests/unit/deps/test_path_anchoring.py | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 changelog.d/4739.fixed.md diff --git a/changelog.d/4739.fixed.md b/changelog.d/4739.fixed.md new file mode 100644 index 0000000000..f6cf0c5e30 --- /dev/null +++ b/changelog.d/4739.fixed.md @@ -0,0 +1 @@ +- `apm install --frozen` replays a monorepo lockfile where one local library is referenced through two relative paths, instead of failing on an ambiguous parent. (#4739) diff --git a/tests/unit/deps/test_path_anchoring.py b/tests/unit/deps/test_path_anchoring.py index adbce48638..7a62353919 100644 --- a/tests/unit/deps/test_path_anchoring.py +++ b/tests/unit/deps/test_path_anchoring.py @@ -146,6 +146,18 @@ def test_parents_anchoring_to_one_directory_are_one_parent(self, tmp_path: Path) == (tmp_path / "packages" / "lib-06").resolve() ) + def test_parents_anchoring_to_different_directories_stay_ambiguous( + self, tmp_path: Path + ) -> None: + """#4731: two same-named libraries in different directories still fail.""" + sibling = _local("_local/lib-04", "./packages/lib-04") + from_root = _local("_local/lib-05", "./packages/lib-05") + elsewhere = _local("_local/lib-05", "../vendor/lib-05", resolved_by="_local/lib-04") + child = _local("_local/lib-06", "../lib-06", resolved_by="_local/lib-05") + + with pytest.raises(LocalResolutionError, match="ambiguous resolved_by parent"): + resolve_local_dep_dir(child, _lockfile(sibling, from_root, elsewhere, child), tmp_path) + def test_cycle_raises(self, tmp_path: Path) -> None: a = _local("_local/a", "../a", resolved_by="_local/b") b = _local("_local/b", "../b", resolved_by="_local/a") From 6fbef8ea824e3ff158bd1dcd109e698092fa3872 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 13:02:03 +0100 Subject: [PATCH 03/11] test(lifecycle): scope the #4731 audit check to the ambiguous-parent replay Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../test_local_monorepo_frozen_replay_lifecycle.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py index 639a97e513..f0cd00b4b3 100644 --- a/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py +++ b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py @@ -76,5 +76,7 @@ def test_frozen_replays_a_lib_reached_by_two_relative_spellings( assert "ambiguous resolved_by parent" not in frozen.stdout + frozen.stderr assert (root / "apm.lock.yaml").read_bytes() == lock assert_unchanged(deployed, ArtifactSnapshot.capture(root / ".claude")) + # Audit's drift replay resolves the same parents; the duplicate lock row's + # skill-subset verdict is tracked separately (not this fix's owner). audit = runner.run(("audit", "--ci"), cwd=root, env=env) - assert audit.returncode == 0, _evidence(audit) + assert "ambiguous resolved_by parent" not in audit.stdout + audit.stderr, _evidence(audit) From 6ad79c0a18c75e9352515431c55320f468911efc Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 13:05:56 +0100 Subject: [PATCH 04/11] chore(spec): waive Mode B for #4731 apm-spec-waiver: bug fix restores replay of a lockfile apm install already wrote; no normative requirement changes (anchoring and containment rules unchanged) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> From c4c603b8e7938a30e8690ec62058573a5e9a5a5e Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 13:21:11 +0100 Subject: [PATCH 05/11] test(deps): the #4731 anchoring case observes the resolved package on disk Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/unit/deps/test_path_anchoring.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/unit/deps/test_path_anchoring.py b/tests/unit/deps/test_path_anchoring.py index 7a62353919..bc525981a6 100644 --- a/tests/unit/deps/test_path_anchoring.py +++ b/tests/unit/deps/test_path_anchoring.py @@ -140,11 +140,14 @@ def test_parents_anchoring_to_one_directory_are_one_parent(self, tmp_path: Path) from_sibling = _local("_local/lib-05", "../lib-05", resolved_by="_local/lib-04") child = _local("_local/lib-06", "../lib-06", resolved_by="_local/lib-05") lock = _lockfile(sibling, from_root, from_sibling, child) + for name in ("lib-04", "lib-05", "lib-06"): + (tmp_path / "packages" / name).mkdir(parents=True) + (tmp_path / "packages" / name / "apm.yml").write_text(f"name: {name}\n") - assert ( - resolve_local_dep_dir(child, lock, tmp_path) - == (tmp_path / "packages" / "lib-06").resolve() - ) + resolved = resolve_local_dep_dir(child, lock, tmp_path) + + assert resolved == (tmp_path / "packages" / "lib-06").resolve() + assert (resolved / "apm.yml").exists() def test_parents_anchoring_to_different_directories_stay_ambiguous( self, tmp_path: Path From 526e0fbffe2535a4e995b9e1a728ae8bde5b7340 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 13:38:05 +0100 Subject: [PATCH 06/11] Revert "chore(spec): waive Mode B for #4731" This reverts commit 6ad79c0a18c. The fix now cites req-mf-016 through a conformance marker, so Mode B passes without a waiver. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> From 58d5ca6452f697ccacc390d186b7e8f775a775e9 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 12:57:32 +0100 Subject: [PATCH 07/11] fix(deps): one anchored local directory is one dependency (#4731) A sibling's ../lib edge to a directory the root manifest declares as ./packages/lib now takes the root declaration's identity, so install writes one lock row. The resolver owns the rule (transitive_local_identity); the --frozen local-content verdict and the reachability walk behind audit --ci route through it. Cites req-mf-016. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- changelog.d/4739.fixed.md | 2 +- src/apm_cli/deps/apm_resolver.py | 51 +++++++++++++-- src/apm_cli/deps/reachability.py | 9 +-- src/apm_cli/install/local_content_verdict.py | 9 +-- .../lifecycle_bug_ledger/bugs/4731.json | 18 +++++ ..._local_monorepo_frozen_replay_lifecycle.py | 7 +- tests/spec_conformance/test_manifest_reqs.py | 21 ++++++ tests/unit/deps/test_apm_resolver_helpers.py | 65 +++++++++++++++++++ tests/unit/deps/test_path_anchoring.py | 28 -------- 9 files changed, 168 insertions(+), 42 deletions(-) create mode 100644 tests/fixtures/lifecycle_bug_ledger/bugs/4731.json diff --git a/changelog.d/4739.fixed.md b/changelog.d/4739.fixed.md index f6cf0c5e30..52e95bd638 100644 --- a/changelog.d/4739.fixed.md +++ b/changelog.d/4739.fixed.md @@ -1 +1 @@ -- `apm install --frozen` replays a monorepo lockfile where one local library is referenced through two relative paths, instead of failing on an ambiguous parent. (#4739) +- `apm install --frozen` and `apm audit --ci` accept a monorepo library referenced as `./packages/lib` from the root and `../lib` from a sibling. (closes #4731, #4739) diff --git a/src/apm_cli/deps/apm_resolver.py b/src/apm_cli/deps/apm_resolver.py index e730a5c3b2..a29ef27b31 100644 --- a/src/apm_cli/deps/apm_resolver.py +++ b/src/apm_cli/deps/apm_resolver.py @@ -522,6 +522,46 @@ def _portable_anchor_identity(anchored: Path, base: Path | None) -> str: return anchored.resolve().as_posix() return portable_relpath(anchored, base) + @staticmethod + def root_local_dirs( + root_refs: Iterable[DependencyReference], consumer_root: Path + ) -> dict[Path, DependencyReference]: + """Map each root-declared local package's resolved directory to its ref.""" + dirs: dict[Path, DependencyReference] = {} + for ref in root_refs: + if ref.is_local and ref.local_path and ref.replacement is None: + raw = Path(ref.local_path).expanduser() + anchored = raw.resolve() if raw.is_absolute() else (consumer_root / raw).resolve() + dirs.setdefault(anchored, ref) + return dirs + + @classmethod + def transitive_local_identity( + cls, + sub_dep: DependencyReference, + *, + declaring_parent: str, + anchored: Path, + root: Path | None, + root_local_dirs: dict[Path, DependencyReference], + ) -> DependencyReference: + """Return the node identity of a local edge a package declares. + + One anchored directory is one dependency (#4731): when the root + manifest also declares that directory, the edge takes the root + declaration's identity and spelling, however the declaring package + spells its relative path (``../lib`` vs ``./packages/lib``). + Otherwise the edge is keyed by its anchored directory. + """ + root_ref = root_local_dirs.get(anchored) + if root_ref is not None: + return replace(sub_dep, repo_url=root_ref.repo_url, local_path=root_ref.local_path) + return replace( + sub_dep, + declaring_parent=declaring_parent, + anchored_local_path=cls._portable_anchor_identity(anchored, root), + ) + def _remote_source_paths_for_parent( self, parent_dep: DependencyReference, @@ -965,6 +1005,9 @@ def build_dependency_tree( queued_keys.add(key) # If already queued as prod, prod wins — skip + root_local_dirs = self.root_local_dirs( + [item[0] for item in processing_queue], consumer_root + ) if self._reject_nested_root_declarations( tree, [item[0] for item in processing_queue], modules_dir ): @@ -1179,12 +1222,12 @@ def build_dependency_tree( if local_path.is_absolute() else (node.package.source_path / local_path).resolve() ) - sub_dep = replace( + sub_dep = self.transitive_local_identity( sub_dep, declaring_parent=node.get_id(), - anchored_local_path=self._portable_anchor_identity( - anchored, root_package.source_path - ), + anchored=anchored, + root=root_package.source_path, + root_local_dirs=root_local_dirs, ) ancestor: DependencyNode | None = node while ancestor is not None: diff --git a/src/apm_cli/deps/reachability.py b/src/apm_cli/deps/reachability.py index 7aace5ed0c..f45f031470 100644 --- a/src/apm_cli/deps/reachability.py +++ b/src/apm_cli/deps/reachability.py @@ -310,6 +310,7 @@ def compute_forward_reachable_keys( expander = APMDependencyResolver(read_only=True, apm_modules_dir=apm_modules_dir) marketplace_index = lockfile.marketplace_index() + root_local_dirs = APMDependencyResolver.root_local_dirs((*direct_refs, *dev_refs), project_root) while queue or dev_queue: ref, anchor, parent_repo_url, is_dev, chain = (queue or dev_queue).popleft() @@ -334,12 +335,12 @@ def compute_forward_reachable_keys( if real_dir is None: continue if ref.replacement is None and parent_repo_url is not None: - ref = replace( + ref = APMDependencyResolver.transitive_local_identity( ref, declaring_parent=parent_repo_url, - anchored_local_path=APMDependencyResolver._portable_anchor_identity( - real_dir, project_root - ), + anchored=real_dir, + root=project_root, + root_local_dirs=root_local_dirs, ) visit_key = ref.get_unique_key() if ref.replacement is not None else str(real_dir) matched_key = ( diff --git a/src/apm_cli/install/local_content_verdict.py b/src/apm_cli/install/local_content_verdict.py index 57f83f9c56..b1e7ef4fac 100644 --- a/src/apm_cli/install/local_content_verdict.py +++ b/src/apm_cli/install/local_content_verdict.py @@ -105,6 +105,7 @@ def local_content_reasons( package_root = Path(apm_package.package_path).resolve() consumer_root = apm_package.source_path or package_root rules = build_replacement_index(apm_package.replace_rules or []) + root_local_dirs = APMDependencyResolver.root_local_dirs(manifest_deps, consumer_root) parent_index = build_local_parent_index(lockfile) resolved_cache: dict[str, Path] = {} seen: set[str] = set() @@ -176,12 +177,12 @@ def local_content_reasons( anchored = APMDependencyResolver._compute_dep_source_path( child, package, source ) - child = replace( + child = APMDependencyResolver.transitive_local_identity( child, declaring_parent=key, - anchored_local_path=APMDependencyResolver._portable_anchor_identity( - anchored, apm_package.source_path or package_root - ), + anchored=anchored, + root=apm_package.source_path or package_root, + root_local_dirs=root_local_dirs, ) queue.append(child) except (LocalResolutionError, OSError, ValueError) as exc: diff --git a/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json b/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json new file mode 100644 index 0000000000..c3cc1ab9a8 --- /dev/null +++ b/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json @@ -0,0 +1,18 @@ +{ + "issue": 4731, + "fixed_in": "Unreleased", + "summary": "apm install --frozen refused a monorepo whose root declares ./packages/lib while a sibling declares ../lib ('ambiguous resolved_by parent'); one anchored directory is now one lock row, and parents anchoring to the same directory are not ambiguous.", + "failure_modes": [ + "outcome", + "reference" + ], + "properties": [ + "lockfile.frozen_preserves_bytes", + "outcome.status_matches_state" + ], + "regression_tests": [ + "tests/integration/test_local_monorepo_frozen_replay_lifecycle.py::test_frozen_replays_a_lib_reached_by_two_relative_spellings", + "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_root_declared_directory_wins_its_spelling", + "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_lockfile_parents_anchoring_to_one_directory_are_one_parent" + ] +} diff --git a/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py index f0cd00b4b3..87723cf46c 100644 --- a/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py +++ b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py @@ -1,6 +1,6 @@ """A monorepo lib reached through two relative spellings replays with --frozen (#4731). -PROMISE: lockfile.frozen_preserves_bytes -- ``apm install --frozen`` replays the +PROMISE: P-INV-I3 -- ``apm install --frozen`` and ``apm audit --ci`` accept the lockfile ``apm install`` just wrote, without changing the lockfile or the deployed files (source: issue #4731 scope record). CELL: OP=install FROZEN=on SRC=local(transitive, two spellings) PRIM=skill SCOPE=project @@ -12,6 +12,7 @@ from pathlib import Path import pytest +import yaml from tests.utils.apm_lifecycle_runner import ApmLifecycleRunner, CommandResult from tests.utils.artifact_snapshot import ArtifactSnapshot, assert_unchanged @@ -66,6 +67,10 @@ def test_frozen_replays_a_lib_reached_by_two_relative_spellings( installed = runner.run(("install",), cwd=root, env=env) assert installed.returncode == 0, _evidence(installed) lock = (root / "apm.lock.yaml").read_bytes() + rows = yaml.safe_load(lock)["dependencies"] + assert [row["local_path"] for row in rows if row["repo_url"] == "_local/lib-05"] == [ + "./packages/lib-05" + ] deployed = ArtifactSnapshot.capture(root / ".claude") for name in ("lib-04", "lib-05", "lib-06"): assert (root / ".claude" / "skills" / f"{name}-skill" / "SKILL.md").is_file() diff --git a/tests/spec_conformance/test_manifest_reqs.py b/tests/spec_conformance/test_manifest_reqs.py index f10321ee91..809934a8fe 100644 --- a/tests/spec_conformance/test_manifest_reqs.py +++ b/tests/spec_conformance/test_manifest_reqs.py @@ -210,6 +210,27 @@ def test_consumer_rejects_absolute_paths_in_apm_source(): ) +@pytest.mark.req("req-mf-016") +def test_consumer_recognises_two_relative_spellings_of_one_local_path(tmp_path): + """#4731: ``./packages/lib`` (root) and ``../lib`` (sibling) are one local-path entry.""" + from apm_cli.deps.apm_resolver import APMDependencyResolver + from apm_cli.models.dependency.reference import DependencyReference + + root_entry = DependencyReference.parse("./packages/lib") + sibling_entry = DependencyReference.parse("../lib") + assert root_entry.is_local and sibling_entry.is_local + + edge = APMDependencyResolver.transitive_local_identity( + sibling_entry, + declaring_parent="_local/sib", + anchored=(tmp_path / "packages" / "sib" / "../lib").resolve(), + root=tmp_path, + root_local_dirs=APMDependencyResolver.root_local_dirs([root_entry], tmp_path), + ) + + assert edge.get_unique_key() == root_entry.get_unique_key() + + @pytest.mark.req("req-mf-017") def test_producer_publishes_apm_yml_at_repo_root(): assert_spec_contains("apm.yml") diff --git a/tests/unit/deps/test_apm_resolver_helpers.py b/tests/unit/deps/test_apm_resolver_helpers.py index b647c6cb46..5d4fb181c6 100644 --- a/tests/unit/deps/test_apm_resolver_helpers.py +++ b/tests/unit/deps/test_apm_resolver_helpers.py @@ -2,12 +2,14 @@ from __future__ import annotations +from pathlib import Path from unittest.mock import MagicMock, patch import pytest from apm_cli.deps.apm_resolver import APMDependencyResolver from apm_cli.deps.lockfile import LockedDependency, LockFile +from apm_cli.deps.path_anchoring import LocalResolutionError, resolve_local_dep_dir from apm_cli.models.apm_package import DependencyReference pytestmark = [ @@ -412,3 +414,66 @@ def test_false_for_unchanged_literal_ref_on_plain_install(self) -> None: # --------------------------------------------------------------------------- # Anchored-local-path portability (committable, cross-machine lockfile) # --------------------------------------------------------------------------- + + +class TestOneAnchoredDirectoryIsOneDependency: + """#4731: a library reached as ``./packages/lib`` and ``../lib`` is one package.""" + + @pytest.mark.parametrize( + ("declared", "expected_key"), + [("../lib", "./packages/lib"), ("../other", "local:packages/other")], + ) + def test_root_declared_directory_wins_its_spelling( + self, tmp_path: Path, declared: str, expected_key: str + ) -> None: + root_ref = DependencyReference.parse("./packages/lib") + dirs = APMDependencyResolver.root_local_dirs([root_ref], tmp_path) + + edge = APMDependencyResolver.transitive_local_identity( + DependencyReference.parse(declared), + declaring_parent="_local/sib", + anchored=(tmp_path / "packages" / "sib" / declared).resolve(), + root=tmp_path, + root_local_dirs=dirs, + ) + + assert edge.get_unique_key() == expected_key + + @staticmethod + def _lockfile(*rows: tuple[str, str, str | None]) -> LockFile: + lockfile = LockFile() + for repo_url, local_path, resolved_by in rows: + lockfile.add_dependency( + LockedDependency( + repo_url=repo_url, + source="local", + local_path=local_path, + resolved_by=resolved_by, + ) + ) + return lockfile + + def test_lockfile_parents_anchoring_to_one_directory_are_one_parent( + self, tmp_path: Path + ) -> None: + lockfile = self._lockfile( + ("_local/sib", "./packages/sib", None), + ("_local/lib", "./packages/lib", None), + ("_local/lib", "../lib", "_local/sib"), + ("_local/leaf", "../leaf", "_local/lib"), + ) + leaf = lockfile.get_dependency("../leaf") + + resolved = resolve_local_dep_dir(leaf, lockfile, tmp_path) + + assert resolved == (tmp_path / "packages" / "leaf").resolve() + + def test_lockfile_parents_in_different_directories_still_refuse(self, tmp_path: Path) -> None: + lockfile = self._lockfile( + ("_local/lib", "./packages/lib", None), + ("_local/lib", "./vendor/lib", None), + ("_local/leaf", "../leaf", "_local/lib"), + ) + + with pytest.raises(LocalResolutionError, match="different directories"): + resolve_local_dep_dir(lockfile.get_dependency("../leaf"), lockfile, tmp_path) diff --git a/tests/unit/deps/test_path_anchoring.py b/tests/unit/deps/test_path_anchoring.py index bc525981a6..d23ceb86a9 100644 --- a/tests/unit/deps/test_path_anchoring.py +++ b/tests/unit/deps/test_path_anchoring.py @@ -133,34 +133,6 @@ def test_ambiguous_parent_raises(self, tmp_path: Path) -> None: with pytest.raises(LocalResolutionError, match="ambiguous"): resolve_local_dep_dir(child, _lockfile(dup_a, dup_b, child), tmp_path) - def test_parents_anchoring_to_one_directory_are_one_parent(self, tmp_path: Path) -> None: - """#4731: ./packages/lib from the root and ../lib from a sibling are one parent.""" - sibling = _local("_local/lib-04", "./packages/lib-04") - from_root = _local("_local/lib-05", "./packages/lib-05") - from_sibling = _local("_local/lib-05", "../lib-05", resolved_by="_local/lib-04") - child = _local("_local/lib-06", "../lib-06", resolved_by="_local/lib-05") - lock = _lockfile(sibling, from_root, from_sibling, child) - for name in ("lib-04", "lib-05", "lib-06"): - (tmp_path / "packages" / name).mkdir(parents=True) - (tmp_path / "packages" / name / "apm.yml").write_text(f"name: {name}\n") - - resolved = resolve_local_dep_dir(child, lock, tmp_path) - - assert resolved == (tmp_path / "packages" / "lib-06").resolve() - assert (resolved / "apm.yml").exists() - - def test_parents_anchoring_to_different_directories_stay_ambiguous( - self, tmp_path: Path - ) -> None: - """#4731: two same-named libraries in different directories still fail.""" - sibling = _local("_local/lib-04", "./packages/lib-04") - from_root = _local("_local/lib-05", "./packages/lib-05") - elsewhere = _local("_local/lib-05", "../vendor/lib-05", resolved_by="_local/lib-04") - child = _local("_local/lib-06", "../lib-06", resolved_by="_local/lib-05") - - with pytest.raises(LocalResolutionError, match="ambiguous resolved_by parent"): - resolve_local_dep_dir(child, _lockfile(sibling, from_root, elsewhere, child), tmp_path) - def test_cycle_raises(self, tmp_path: Path) -> None: a = _local("_local/a", "../a", resolved_by="_local/b") b = _local("_local/b", "../b", resolved_by="_local/a") From ee0131bf307d79dcecb059b57e07a42017c89645 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 13:19:52 +0100 Subject: [PATCH 08/11] test(spec): cite req-mf-016 for #4731; regenerate CONFORMANCE Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CONFORMANCE.json | 13 +++++---- CONFORMANCE.md | 4 +-- .../test_local_path_identity_reqs.py | 28 +++++++++++++++++++ tests/spec_conformance/test_manifest_reqs.py | 21 -------------- 4 files changed, 38 insertions(+), 28 deletions(-) create mode 100644 tests/spec_conformance/test_local_path_identity_reqs.py diff --git a/CONFORMANCE.json b/CONFORMANCE.json index fdf96b4e40..1f831533ae 100644 --- a/CONFORMANCE.json +++ b/CONFORMANCE.json @@ -1012,14 +1012,17 @@ ] }, { - "behavioral_tests": [], + "behavioral_tests": [ + "tests/spec_conformance/test_local_path_identity_reqs.py::test_consumer_recognises_two_relative_spellings_of_one_local_path" + ], "conformance_class": "consumer", "id": "req-mf-016", "keyword": "MUST", "section": "4.3.5", - "status": "skipped", - "test_count": 1, + "status": "active", + "test_count": 2, "tests": [ + "tests/spec_conformance/test_local_path_identity_reqs.py::test_consumer_recognises_two_relative_spellings_of_one_local_path", "tests/spec_conformance/test_manifest_reqs.py::test_consumer_rejects_absolute_paths_in_apm_source" ], "waivers": [ @@ -3350,9 +3353,9 @@ "spec_version": "v0.1.1", "summary_by_class": { "consumer": { - "active": 110, + "active": 111, "partial": 1, - "skipped": 3, + "skipped": 2, "text-only": 3, "unbound": 0, "xfail": 0 diff --git a/CONFORMANCE.md b/CONFORMANCE.md index 3ce9f86fd4..321600035e 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -45,7 +45,7 @@ APM implements the proposed staged-replacement recovery capability (req-lk-023). | Class | Active | Partial | Skipped | Xfail | Text-only | Unbound | |-------|-------:|--------:|--------:|------:|----------:|--------:| | Producer | 9 | 0 | 0 | 0 | 3 | 0 | -| Consumer | 110 | 1 | 3 | 0 | 3 | 0 | +| Consumer | 111 | 1 | 2 | 0 | 3 | 0 | | Registry | 0 | 0 | 0 | 0 | 1 | 0 | | Governance | 22 | 0 | 0 | 0 | 0 | 0 | @@ -97,7 +97,7 @@ APM implements the proposed staged-replacement recovery capability (req-lk-023). | [req-mf-013](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-013) | MUST | 4.5 | consumer | active | 2 / 3 | - | | [req-mf-014](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-014) | MUST | 4.2.3 | producer | active | 1 / 2 | - | | [req-mf-015](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-015) | MUST | 4.2.3 | producer | active | 2 / 3 | - | -| [req-mf-016](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-016) | MUST | 4.3.5 | consumer | skipped | 0 / 1 | - | +| [req-mf-016](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-016) | MUST | 4.3.5 | consumer | active | 1 / 2 | - | | [req-mf-017](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-017) | MUST | 4.7 | producer | active | 11 / 12 | - | | [req-mf-018](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-018) | MUST | 4.6.1 | consumer | active | 5 / 6 | - | | [req-mf-019](docs/src/content/docs/specs/openapm-v0.1.md#req-mf-019) | MUST | 4.2.4 | consumer | active | 1 / 2 | - | diff --git a/tests/spec_conformance/test_local_path_identity_reqs.py b/tests/spec_conformance/test_local_path_identity_reqs.py new file mode 100644 index 0000000000..bc7668bec7 --- /dev/null +++ b/tests/spec_conformance/test_local_path_identity_reqs.py @@ -0,0 +1,28 @@ +"""OpenAPM req-mf-016: one local path spelled two ways is one local-path entry (#4731).""" + +from __future__ import annotations + +import pytest + +from apm_cli.deps.apm_resolver import APMDependencyResolver +from apm_cli.models.dependency.reference import DependencyReference + +pytestmark = [pytest.mark.unit, pytest.mark.promise("req-mf-016")] + + +@pytest.mark.req("req-mf-016") +def test_consumer_recognises_two_relative_spellings_of_one_local_path(tmp_path): + """#4731: ``./packages/lib`` (root) and ``../lib`` (sibling) are one local-path entry.""" + root_entry = DependencyReference.parse("./packages/lib") + sibling_entry = DependencyReference.parse("../lib") + assert root_entry.is_local and sibling_entry.is_local + + edge = APMDependencyResolver.transitive_local_identity( + sibling_entry, + declaring_parent="_local/sib", + anchored=(tmp_path / "packages" / "sib" / "../lib").resolve(), + root=tmp_path, + root_local_dirs=APMDependencyResolver.root_local_dirs([root_entry], tmp_path), + ) + + assert edge.get_unique_key() == root_entry.get_unique_key() diff --git a/tests/spec_conformance/test_manifest_reqs.py b/tests/spec_conformance/test_manifest_reqs.py index 809934a8fe..f10321ee91 100644 --- a/tests/spec_conformance/test_manifest_reqs.py +++ b/tests/spec_conformance/test_manifest_reqs.py @@ -210,27 +210,6 @@ def test_consumer_rejects_absolute_paths_in_apm_source(): ) -@pytest.mark.req("req-mf-016") -def test_consumer_recognises_two_relative_spellings_of_one_local_path(tmp_path): - """#4731: ``./packages/lib`` (root) and ``../lib`` (sibling) are one local-path entry.""" - from apm_cli.deps.apm_resolver import APMDependencyResolver - from apm_cli.models.dependency.reference import DependencyReference - - root_entry = DependencyReference.parse("./packages/lib") - sibling_entry = DependencyReference.parse("../lib") - assert root_entry.is_local and sibling_entry.is_local - - edge = APMDependencyResolver.transitive_local_identity( - sibling_entry, - declaring_parent="_local/sib", - anchored=(tmp_path / "packages" / "sib" / "../lib").resolve(), - root=tmp_path, - root_local_dirs=APMDependencyResolver.root_local_dirs([root_entry], tmp_path), - ) - - assert edge.get_unique_key() == root_entry.get_unique_key() - - @pytest.mark.req("req-mf-017") def test_producer_publishes_apm_yml_at_repo_root(): assert_spec_contains("apm.yml") From 26cbdec84e14c1c66279be52c65e48746202359e Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 13:38:42 +0100 Subject: [PATCH 09/11] test(lifecycle): #4731 audit --ci must exit 0 after the frozen replay Restores the strict audit oracle relaxed in 6fbef8ea: with one lock row per anchored directory the skill-subset check passes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../test_local_monorepo_frozen_replay_lifecycle.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py index 87723cf46c..561af8233a 100644 --- a/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py +++ b/tests/integration/test_local_monorepo_frozen_replay_lifecycle.py @@ -81,7 +81,5 @@ def test_frozen_replays_a_lib_reached_by_two_relative_spellings( assert "ambiguous resolved_by parent" not in frozen.stdout + frozen.stderr assert (root / "apm.lock.yaml").read_bytes() == lock assert_unchanged(deployed, ArtifactSnapshot.capture(root / ".claude")) - # Audit's drift replay resolves the same parents; the duplicate lock row's - # skill-subset verdict is tracked separately (not this fix's owner). audit = runner.run(("audit", "--ci"), cwd=root, env=env) - assert "ambiguous resolved_by parent" not in audit.stdout + audit.stderr, _evidence(audit) + assert audit.returncode == 0, _evidence(audit) From cd99d2ef76ce29af91c4a0fae94436b4f2b2dcdb Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 15:42:46 +0100 Subject: [PATCH 10/11] fix(deps): collapsed local node keeps dev and recheck semantics; guard its owner (#4731) - Production status now reaches every descendant of a production node, so a root devDependency that a production sibling also needs ships its subtree. - A targeted update rechecks an existing node at its own reference and parent, not at the incoming edge's anchor. - deps/local_identity.py owns the local node identity; the resolver, the --frozen verdict and the reachability walk call it, and the new contracts-tooling-local-identity guard (with a mutation case) refuses bypasses. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../owners/contracts-tooling.json | 7 +- .../checks/contracts_local_path_anchor.py | 79 ++++++++++++++- src/apm_cli/deps/apm_resolver.py | 97 ++++++------------- src/apm_cli/deps/local_identity.py | 80 +++++++++++++++ src/apm_cli/deps/reachability.py | 6 +- src/apm_cli/install/local_content_verdict.py | 6 +- .../lifecycle_bug_ledger/bugs/4731.json | 4 +- .../test_architecture_owner_rule_mutations.py | 8 ++ .../test_local_path_identity_reqs.py | 6 +- tests/unit/deps/test_apm_resolver_helpers.py | 84 +++++++++++++++- .../unit/scripts/test_architecture_runner.py | 1 + 11 files changed, 298 insertions(+), 80 deletions(-) create mode 100644 src/apm_cli/deps/local_identity.py diff --git a/.apm/architecture/owners/contracts-tooling.json b/.apm/architecture/owners/contracts-tooling.json index 90bc06c1e9..8499d6a12f 100644 --- a/.apm/architecture/owners/contracts-tooling.json +++ b/.apm/architecture/owners/contracts-tooling.json @@ -48,7 +48,7 @@ { "id": "dependency-identity-materialization", "decision": "Dependency comparison identity and policy casing vs display-cased materialization path; host-bound exact policy require identity (required_package_policy_hosts), resolved once by policy/matcher.py DependencyPolicyIndex.find for the manifest and, via the matched dependency's unique key, the lockfile; distinct remote packages never share one materialization directory (MaterializationSlots, before fetch); root-owned exact source replacement and original ownership; embedded git URL subpath validation; the anchor a relative local_path resolves against (the declaring package at every scope; a root-declared relative path at user scope is refused)", - "owner": "models/dependency/identity.py + materialization.py + replacement.py (typed root binding and clean selected-source projection) + object_fields.py (alias validation) + deps/apm_resolver.py (remote source-coordinate anchoring) + DependencyReference (_check_no_embedded_subpath consumes core/host_providers.py) + install/plan.py (root intent comparison; update plans compare the ref the lockfile records) + install/phases/lockfile.py (including empty-graph root intent persistence) + deps/path_anchoring.py local_dep_base_dir (local_path anchor: it decides which directory a relative dependency path names, so it is the local half of materialization identity)", + "owner": "models/dependency/identity.py + materialization.py + replacement.py (typed root binding and clean selected-source projection) + object_fields.py (alias validation) + deps/apm_resolver.py (remote source-coordinate anchoring) + DependencyReference (_check_no_embedded_subpath consumes core/host_providers.py) + install/plan.py (root intent comparison; update plans compare the ref the lockfile records) + install/phases/lockfile.py (including empty-graph root intent persistence) + deps/path_anchoring.py local_dep_base_dir (local_path anchor: it decides which directory a relative dependency path names, so it is the local half of materialization identity) + deps/local_identity.py transitive_local_identity (one anchored directory is one dependency: the node key of a declared local edge for install, the --frozen verdict and the reachability walk, #4731)", "selectors": [ "src/apm_cli/models/dependency/identity.py", "src/apm_cli/models/dependency/materialization.py", @@ -64,9 +64,10 @@ "src/apm_cli/install/presentation/resolution.py", "src/apm_cli/install/helpers/no_work.py", "src/apm_cli/install/plan.py", - "src/apm_cli/deps/path_anchoring.py" + "src/apm_cli/deps/path_anchoring.py", + "src/apm_cli/deps/local_identity.py" ], - "guards": ["contracts-tooling-dependency-identity", "contracts-tooling-local-path-anchor", "contracts-tooling-policy-identity", "contracts-tooling-source-replacements", "contracts-tooling-update-plan-recorded-ref"] + "guards": ["contracts-tooling-dependency-identity", "contracts-tooling-local-identity", "contracts-tooling-local-path-anchor", "contracts-tooling-policy-identity", "contracts-tooling-source-replacements", "contracts-tooling-update-plan-recorded-ref"] }, { "id": "native-lifecycle-evidence", diff --git a/scripts/architecture_linter/checks/contracts_local_path_anchor.py b/scripts/architecture_linter/checks/contracts_local_path_anchor.py index 9e6dbb87d6..c75a72ee50 100644 --- a/scripts/architecture_linter/checks/contracts_local_path_anchor.py +++ b/scripts/architecture_linter/checks/contracts_local_path_anchor.py @@ -5,7 +5,8 @@ root, or nothing (a root-declared relative path at user scope). The guard is closed-world: no other function may combine a user-scope test with an ``is_absolute()`` test on a ``local_path``, nor restate the refusal text, and the three install -consumers must call the owner. +consumers must call the owner. ``deps/local_identity.transitive_local_identity`` +likewise owns the node key of a declared local edge (#4731). """ from __future__ import annotations @@ -111,6 +112,75 @@ def check_local_path_anchor(provider: FactsProvider) -> tuple[Violation, ...]: return tuple(findings) +IDENTITY_RULE = "contracts-tooling-local-identity" +IDENTITY_OWNER = "src/apm_cli/deps/local_identity.py" +IDENTITY_SYMBOL = "transitive_local_identity" +_ANCHOR_HELPERS = frozenset({"portable_anchor_identity", "_portable_anchor_identity"}) +_ANCHOR_DELEGATE = ("src/apm_cli/deps/apm_resolver.py", "_portable_anchor_identity") +IDENTITY_CONSUMERS = { + "src/apm_cli/deps/apm_resolver.py": "APMDependencyResolver.build_dependency_tree", + "src/apm_cli/install/local_content_verdict.py": "local_content_reasons", + "src/apm_cli/deps/reachability.py": "compute_forward_reachable_keys", +} + + +def _called_name(call: ast.Call) -> str | None: + if isinstance(call.func, ast.Name): + return call.func.id + if isinstance(call.func, ast.Attribute): + return call.func.attr + return None + + +def _calls(node: ast.AST, names: frozenset[str]) -> bool: + return any( + isinstance(item, ast.Call) and _called_name(item) in names for item in ast.walk(node) + ) + + +def _anchor_bypasses(provider: FactsProvider) -> list[Violation]: + """Only the identity owner may turn an anchored directory into a node key.""" + findings: list[Violation] = [] + for path in _python_paths(provider, _SRC_PREFIX): + if path == IDENTITY_OWNER: + continue + index = provider.tree_index(path) + if index is None or index.root is None: + continue + for node in index.functions(): + if (path, getattr(node, "name", "")) == _ANCHOR_DELEGATE: + continue + body = ast.Module(body=node.body, type_ignores=[]) + if _calls(body, _ANCHOR_HELPERS): + findings.append( + _summary( + IDENTITY_RULE, + path, + f"{node.name} derives a local anchored identity; " + f"call {IDENTITY_SYMBOL} ({IDENTITY_OWNER})", + ) + ) + return findings + + +def check_local_identity(provider: FactsProvider) -> tuple[Violation, ...]: + """One anchored directory is one dependency, keyed only by the identity owner.""" + findings = _anchor_bypasses(provider) + for path, symbol in IDENTITY_CONSUMERS.items(): + facts, failures = checked_facts(provider, path, IDENTITY_RULE, require_python=True) + findings.extend(failures) + if facts is None or facts.tree_index is None: + continue + function = facts.tree_index.function(symbol) + if function is None or not _calls(function, frozenset({IDENTITY_SYMBOL})): + findings.append( + _summary( + IDENTITY_RULE, path, f"{symbol} must key local edges via {IDENTITY_SYMBOL}" + ) + ) + return tuple(findings) + + RULES = ( Rule( id=RULE, @@ -119,4 +189,11 @@ def check_local_path_anchor(provider: FactsProvider) -> tuple[Violation, ...]: description="Relative local paths anchor on the declaring package via one owner.", check=check_local_path_anchor, ), + Rule( + id=IDENTITY_RULE, + group="contracts_tests", + guard_ids=(IDENTITY_RULE,), + description="One anchored local directory is one dependency, keyed by one owner.", + check=check_local_identity, + ), ) diff --git a/src/apm_cli/deps/apm_resolver.py b/src/apm_cli/deps/apm_resolver.py index a29ef27b31..cb3a2c627a 100644 --- a/src/apm_cli/deps/apm_resolver.py +++ b/src/apm_cli/deps/apm_resolver.py @@ -26,7 +26,6 @@ from ..models.dependency.subsets import EdgeSelection, merge_edge_selections from ..models.validation import PackageType, detect_package_type, validate_apm_package from ..utils.path_security import PathTraversalError, ensure_path_within, validate_path_segments -from ..utils.paths import portable_relpath from ._shared import MarketplaceManifestMaterializationError, materialize_marketplace_manifest from .dependency_graph import ( CircularRef, @@ -40,6 +39,8 @@ ImmutableRequirements, ReferenceResolver, ) +from .local_identity import portable_anchor_identity, transitive_local_identity +from .local_identity import root_local_dirs as collect_root_local_dirs if TYPE_CHECKING: from .lockfile import LockFile @@ -499,68 +500,8 @@ def _is_absolute_local_path(local_path: str) -> bool: @staticmethod def _portable_anchor_identity(anchored: Path, base: Path | None) -> str: - """Return a machine-independent identity string for a resolved local dep. - - ``anchored`` is the absolute, resolved on-disk location of a local - package. The returned value is the package's stable identity only -- - it feeds the ``local:`` cycle key, the lockfile - ``dependencies[].anchored_local_path`` field, and (via that same owner - identity) the deployment-ledger owner rows. It is never re-opened as a - filesystem path. - - A lockfile is a committed, cross-machine artifact, so this identity - MUST NOT carry a developer's home directory or any absolute prefix. - Packages inside ``base`` (the project root) are recorded relative to - it in forward-slash POSIX form -- matching how directly-declared local - owners already serialize -- which keeps a regenerated lockfile - deterministic across machines and CI. Packages outside ``base`` (or - when ``base`` is unknown) fall back to the resolved absolute POSIX - path: such out-of-project local deps are inherently non-committable, - and the fallback preserves a unique identity without inventing one. - """ - if base is None: - return anchored.resolve().as_posix() - return portable_relpath(anchored, base) - - @staticmethod - def root_local_dirs( - root_refs: Iterable[DependencyReference], consumer_root: Path - ) -> dict[Path, DependencyReference]: - """Map each root-declared local package's resolved directory to its ref.""" - dirs: dict[Path, DependencyReference] = {} - for ref in root_refs: - if ref.is_local and ref.local_path and ref.replacement is None: - raw = Path(ref.local_path).expanduser() - anchored = raw.resolve() if raw.is_absolute() else (consumer_root / raw).resolve() - dirs.setdefault(anchored, ref) - return dirs - - @classmethod - def transitive_local_identity( - cls, - sub_dep: DependencyReference, - *, - declaring_parent: str, - anchored: Path, - root: Path | None, - root_local_dirs: dict[Path, DependencyReference], - ) -> DependencyReference: - """Return the node identity of a local edge a package declares. - - One anchored directory is one dependency (#4731): when the root - manifest also declares that directory, the edge takes the root - declaration's identity and spelling, however the declaring package - spells its relative path (``../lib`` vs ``./packages/lib``). - Otherwise the edge is keyed by its anchored directory. - """ - root_ref = root_local_dirs.get(anchored) - if root_ref is not None: - return replace(sub_dep, repo_url=root_ref.repo_url, local_path=root_ref.local_path) - return replace( - sub_dep, - declaring_parent=declaring_parent, - anchored_local_path=cls._portable_anchor_identity(anchored, root), - ) + """Delegate to :func:`apm_cli.deps.local_identity.portable_anchor_identity`.""" + return portable_anchor_identity(anchored, base) def _remote_source_paths_for_parent( self, @@ -1005,7 +946,7 @@ def build_dependency_tree( queued_keys.add(key) # If already queued as prod, prod wins — skip - root_local_dirs = self.root_local_dirs( + root_local_dirs = collect_root_local_dirs( [item[0] for item in processing_queue], consumer_root ) if self._reject_nested_root_declarations( @@ -1080,7 +1021,15 @@ def build_dependency_tree( and dep_ref.get_unique_key() not in self._scoped_rechecked and existing_node.get_id() not in scheduled_nodes ): - work_items.append((existing_node, dep_ref, parent_node, is_dev)) + # Recheck the node at its own anchor, not this edge's (#4731). + work_items.append( + ( + existing_node, + existing_node.dependency_ref, + existing_node.parent, + is_dev, + ) + ) scheduled_nodes.add(existing_node.get_id()) continue @@ -1222,7 +1171,7 @@ def build_dependency_tree( if local_path.is_absolute() else (node.package.source_path / local_path).resolve() ) - sub_dep = self.transitive_local_identity( + sub_dep = transitive_local_identity( sub_dep, declaring_parent=node.get_id(), anchored=anchored, @@ -1274,9 +1223,25 @@ def build_dependency_tree( processing_queue.append((sub_dep, node.depth + 1, node, is_dev)) queued_keys.add(queue_key) + self._propagate_production(tree) self._apply_edge_selections(tree) return tree + @staticmethod + def _propagate_production(tree: DependencyTree) -> None: + """Mark every descendant of a production node production (prod wins over dev). + + A production edge can reach a node first loaded as dev (a root + devDependency a production sibling also declares); promoting only that + node would leave its already-queued descendants dev (#4731). + """ + pending = [node for node in tree.nodes.values() if not node.is_dev] + while pending: + for child in pending.pop().children: + if child.is_dev: + child.is_dev = False + pending.append(child) + @staticmethod def _reject_nested_root_declarations( tree: DependencyTree, diff --git a/src/apm_cli/deps/local_identity.py b/src/apm_cli/deps/local_identity.py new file mode 100644 index 0000000000..0a5f76fd30 --- /dev/null +++ b/src/apm_cli/deps/local_identity.py @@ -0,0 +1,80 @@ +"""The one owner of a local dependency's node identity (#4731). + +A relative ``local_path`` names a directory; one directory is one dependency. +The install resolver, the ``--frozen`` local-content verdict and the +reachability walk behind ``audit --ci``, ``uninstall`` and ``prune`` all key a +declared local edge through :func:`transitive_local_identity`, so they agree +on one lockfile row per anchored directory. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from dataclasses import replace +from pathlib import Path + +from ..models.dependency.reference import DependencyReference +from ..utils.paths import portable_relpath + + +def portable_anchor_identity(anchored: Path, base: Path | None) -> str: + """Return a machine-independent identity string for a resolved local dep. + + ``anchored`` is the absolute, resolved on-disk location of a local + package. The returned value is the package's stable identity only -- + it feeds the ``local:`` cycle key, the lockfile + ``dependencies[].anchored_local_path`` field, and (via that same owner + identity) the deployment-ledger owner rows. It is never re-opened as a + filesystem path. + + A lockfile is a committed, cross-machine artifact, so this identity + MUST NOT carry a developer's home directory or any absolute prefix. + Packages inside ``base`` (the project root) are recorded relative to + it in forward-slash POSIX form -- matching how directly-declared local + owners already serialize -- which keeps a regenerated lockfile + deterministic across machines and CI. Packages outside ``base`` (or + when ``base`` is unknown) fall back to the resolved absolute POSIX + path: such out-of-project local deps are inherently non-committable, + and the fallback preserves a unique identity without inventing one. + """ + if base is None: + return anchored.resolve().as_posix() + return portable_relpath(anchored, base) + + +def root_local_dirs( + root_refs: Iterable[DependencyReference], consumer_root: Path +) -> dict[Path, DependencyReference]: + """Map each root-declared local package's resolved directory to its ref.""" + dirs: dict[Path, DependencyReference] = {} + for ref in root_refs: + if ref.is_local and ref.local_path and ref.replacement is None: + raw = Path(ref.local_path).expanduser() + anchored = raw.resolve() if raw.is_absolute() else (consumer_root / raw).resolve() + dirs.setdefault(anchored, ref) + return dirs + + +def transitive_local_identity( + sub_dep: DependencyReference, + *, + declaring_parent: str, + anchored: Path, + root: Path | None, + root_local_dirs: dict[Path, DependencyReference], +) -> DependencyReference: + """Return the node identity of a local edge a package declares. + + When the root manifest also declares the anchored directory, the edge + takes the root declaration's identity and spelling, however the declaring + package spells its relative path (``../lib`` vs ``./packages/lib``). + Otherwise the edge is keyed by its anchored directory. + """ + root_ref = root_local_dirs.get(anchored) + if root_ref is not None: + return replace(sub_dep, repo_url=root_ref.repo_url, local_path=root_ref.local_path) + return replace( + sub_dep, + declaring_parent=declaring_parent, + anchored_local_path=portable_anchor_identity(anchored, root), + ) diff --git a/src/apm_cli/deps/reachability.py b/src/apm_cli/deps/reachability.py index f45f031470..18f3a6774e 100644 --- a/src/apm_cli/deps/reachability.py +++ b/src/apm_cli/deps/reachability.py @@ -286,6 +286,8 @@ def compute_forward_reachable_keys( """ unverifiable: list[tuple[str, str]] = [] from apm_cli.deps.apm_resolver import APMDependencyResolver + from apm_cli.deps.local_identity import root_local_dirs as collect_root_local_dirs + from apm_cli.deps.local_identity import transitive_local_identity from apm_cli.deps.lockfile import lockfile_parent_identity replacement_index = build_replacement_index(parse_replace_block(lockfile.replacements)) @@ -310,7 +312,7 @@ def compute_forward_reachable_keys( expander = APMDependencyResolver(read_only=True, apm_modules_dir=apm_modules_dir) marketplace_index = lockfile.marketplace_index() - root_local_dirs = APMDependencyResolver.root_local_dirs((*direct_refs, *dev_refs), project_root) + root_local_dirs = collect_root_local_dirs((*direct_refs, *dev_refs), project_root) while queue or dev_queue: ref, anchor, parent_repo_url, is_dev, chain = (queue or dev_queue).popleft() @@ -335,7 +337,7 @@ def compute_forward_reachable_keys( if real_dir is None: continue if ref.replacement is None and parent_repo_url is not None: - ref = APMDependencyResolver.transitive_local_identity( + ref = transitive_local_identity( ref, declaring_parent=parent_repo_url, anchored=real_dir, diff --git a/src/apm_cli/install/local_content_verdict.py b/src/apm_cli/install/local_content_verdict.py index b1e7ef4fac..546ad7963e 100644 --- a/src/apm_cli/install/local_content_verdict.py +++ b/src/apm_cli/install/local_content_verdict.py @@ -86,6 +86,8 @@ def local_content_reasons( from dataclasses import replace from apm_cli.deps.apm_resolver import APMDependencyResolver + from apm_cli.deps.local_identity import root_local_dirs as collect_root_local_dirs + from apm_cli.deps.local_identity import transitive_local_identity from apm_cli.deps.path_anchoring import ( LocalResolutionError, build_local_parent_index, @@ -105,7 +107,7 @@ def local_content_reasons( package_root = Path(apm_package.package_path).resolve() consumer_root = apm_package.source_path or package_root rules = build_replacement_index(apm_package.replace_rules or []) - root_local_dirs = APMDependencyResolver.root_local_dirs(manifest_deps, consumer_root) + root_local_dirs = collect_root_local_dirs(manifest_deps, consumer_root) parent_index = build_local_parent_index(lockfile) resolved_cache: dict[str, Path] = {} seen: set[str] = set() @@ -177,7 +179,7 @@ def local_content_reasons( anchored = APMDependencyResolver._compute_dep_source_path( child, package, source ) - child = APMDependencyResolver.transitive_local_identity( + child = transitive_local_identity( child, declaring_parent=key, anchored=anchored, diff --git a/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json b/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json index c3cc1ab9a8..25f42a82ca 100644 --- a/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json +++ b/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json @@ -12,7 +12,9 @@ ], "regression_tests": [ "tests/integration/test_local_monorepo_frozen_replay_lifecycle.py::test_frozen_replays_a_lib_reached_by_two_relative_spellings", + "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_lockfile_parents_anchoring_to_one_directory_are_one_parent", "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_root_declared_directory_wins_its_spelling", - "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_lockfile_parents_anchoring_to_one_directory_are_one_parent" + "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryNode::test_production_sibling_promotes_a_dev_library_and_its_descendants", + "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryNode::test_targeted_sibling_update_rechecks_the_library_at_its_own_anchor" ] } diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index 56e780d562..c4a366d563 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -1901,6 +1901,14 @@ class MutationCase: new="reused = None", intent="The facts provider skips the session and re-parses content it already built.", ), + MutationCase( + guard_id="contracts-tooling-local-identity", + rule_id="contracts-tooling-local-identity", + path="src/apm_cli/deps/reachability.py", + old=" ref = transitive_local_identity(", + new=" ref = replace(", + intent="The reachability walk re-keys a local edge itself instead of calling the owner.", + ), MutationCase( guard_id="contracts-tooling-local-path-anchor", rule_id="contracts-tooling-local-path-anchor", diff --git a/tests/spec_conformance/test_local_path_identity_reqs.py b/tests/spec_conformance/test_local_path_identity_reqs.py index bc7668bec7..ec1bbc0d42 100644 --- a/tests/spec_conformance/test_local_path_identity_reqs.py +++ b/tests/spec_conformance/test_local_path_identity_reqs.py @@ -4,7 +4,7 @@ import pytest -from apm_cli.deps.apm_resolver import APMDependencyResolver +from apm_cli.deps.local_identity import root_local_dirs, transitive_local_identity from apm_cli.models.dependency.reference import DependencyReference pytestmark = [pytest.mark.unit, pytest.mark.promise("req-mf-016")] @@ -17,12 +17,12 @@ def test_consumer_recognises_two_relative_spellings_of_one_local_path(tmp_path): sibling_entry = DependencyReference.parse("../lib") assert root_entry.is_local and sibling_entry.is_local - edge = APMDependencyResolver.transitive_local_identity( + edge = transitive_local_identity( sibling_entry, declaring_parent="_local/sib", anchored=(tmp_path / "packages" / "sib" / "../lib").resolve(), root=tmp_path, - root_local_dirs=APMDependencyResolver.root_local_dirs([root_entry], tmp_path), + root_local_dirs=root_local_dirs([root_entry], tmp_path), ) assert edge.get_unique_key() == root_entry.get_unique_key() diff --git a/tests/unit/deps/test_apm_resolver_helpers.py b/tests/unit/deps/test_apm_resolver_helpers.py index 5d4fb181c6..eaeafed4f8 100644 --- a/tests/unit/deps/test_apm_resolver_helpers.py +++ b/tests/unit/deps/test_apm_resolver_helpers.py @@ -8,6 +8,7 @@ import pytest from apm_cli.deps.apm_resolver import APMDependencyResolver +from apm_cli.deps.local_identity import root_local_dirs, transitive_local_identity from apm_cli.deps.lockfile import LockedDependency, LockFile from apm_cli.deps.path_anchoring import LocalResolutionError, resolve_local_dep_dir from apm_cli.models.apm_package import DependencyReference @@ -427,9 +428,9 @@ def test_root_declared_directory_wins_its_spelling( self, tmp_path: Path, declared: str, expected_key: str ) -> None: root_ref = DependencyReference.parse("./packages/lib") - dirs = APMDependencyResolver.root_local_dirs([root_ref], tmp_path) + dirs = root_local_dirs([root_ref], tmp_path) - edge = APMDependencyResolver.transitive_local_identity( + edge = transitive_local_identity( DependencyReference.parse(declared), declaring_parent="_local/sib", anchored=(tmp_path / "packages" / "sib" / declared).resolve(), @@ -477,3 +478,82 @@ def test_lockfile_parents_in_different_directories_still_refuse(self, tmp_path: with pytest.raises(LocalResolutionError, match="different directories"): resolve_local_dep_dir(lockfile.get_dependency("../leaf"), lockfile, tmp_path) + + +def _monorepo(root: Path, *, dev_lib: bool) -> Path: + """root -> ./packages/sib (-> ../lib -> ../leaf), and ./packages/lib directly.""" + for name, deps in (("sib", ["../lib"]), ("lib", ["../leaf"]), ("leaf", [])): + package = root / "packages" / name + package.mkdir(parents=True) + listed = "".join(f" - {dep}\n" for dep in deps) + apm = f"dependencies:\n apm:\n{listed}" if deps else "" + (package / "apm.yml").write_text(f"name: {name}\nversion: 1.0.0\n{apm}", encoding="utf-8") + lib_section = "devDependencies" if dev_lib else "dependencies" + sib = "dependencies:\n apm:\n - ./packages/sib\n" + lib = f"{lib_section}:\n apm:\n - ./packages/lib\n" + body = ( + sib + lib + if dev_lib + else "dependencies:\n apm:\n - ./packages/sib\n - ./packages/lib\n" + ) + (root / "apm.yml").write_text(f"name: mono\nversion: 1.0.0\n{body}", encoding="utf-8") + return root / "apm.yml" + + +def _copy_local(calls: list[Path]): + """Download callback that materializes a local package like install does.""" + import shutil + + def download(dep_ref, modules_dir, parent_chain, parent_pkg=None): + base = APMDependencyResolver._effective_base_dir(parent_pkg, modules_dir.parent) + source = (base / dep_ref.local_path).resolve() + calls.append(source) + destination = dep_ref.get_install_path(modules_dir) + shutil.copytree(source, destination, dirs_exist_ok=True) + return destination + + return download + + +class TestOneAnchoredDirectoryNode: + """#4731: the collapsed node keeps install semantics for dev status and rechecks.""" + + def test_production_sibling_promotes_a_dev_library_and_its_descendants( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.chdir(tmp_path) + manifest = _monorepo(tmp_path, dev_lib=True) + calls: list[Path] = [] + resolver = APMDependencyResolver( + apm_modules_dir=tmp_path / "apm_modules", download_callback=_copy_local(calls) + ) + resolver._project_root = tmp_path + + tree = resolver.build_dependency_tree(manifest) + + assert not tree.resolution_errors, tree.resolution_errors + dev = {node.dependency_ref.get_unique_key(): node.is_dev for node in tree.nodes.values()} + assert dev == { + "./packages/sib": False, + "./packages/lib": False, + "local:packages/leaf": False, + } + + def test_targeted_sibling_update_rechecks_the_library_at_its_own_anchor( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.chdir(tmp_path) + manifest = _monorepo(tmp_path, dev_lib=False) + calls: list[Path] = [] + resolver = APMDependencyResolver( + apm_modules_dir=tmp_path / "apm_modules", + download_callback=_copy_local(calls), + update_keys={"./packages/sib"}, + ) + resolver._project_root = tmp_path + + tree = resolver.build_dependency_tree(manifest) + + assert not tree.resolution_errors, tree.resolution_errors + assert (tmp_path / "packages" / "sib" / "packages" / "lib") not in calls, calls + assert (tmp_path / "packages" / "lib").resolve() in calls, calls diff --git a/tests/unit/scripts/test_architecture_runner.py b/tests/unit/scripts/test_architecture_runner.py index 15155bd8c2..e16d34fcf9 100644 --- a/tests/unit/scripts/test_architecture_runner.py +++ b/tests/unit/scripts/test_architecture_runner.py @@ -617,6 +617,7 @@ def exiting_import( contracts-tooling-lifecycle-policy-errors contracts-tooling-linter-cache-content-key contracts-tooling-linter-cache-parse-once +contracts-tooling-local-identity contracts-tooling-local-path-anchor contracts-tooling-lockfile-generator-gate contracts-tooling-lockfile-generator-stamp From 2f2cca07057cc620ace1fa51b40685bccccccb81 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 16:28:29 +0100 Subject: [PATCH 11/11] fix(deps): production status follows every declaring edge (#4731) Propagation now also walks edges the queue dedup dropped (recorded in _edge_parents), so a leaf shared by two dev roots is production once a production edge reaches one of them, in either declaration order. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/deps/apm_resolver.py | 25 ++++++++++---- .../lifecycle_bug_ledger/bugs/4731.json | 3 +- tests/unit/deps/test_apm_resolver_helpers.py | 33 +++++++++++++++++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/apm_cli/deps/apm_resolver.py b/src/apm_cli/deps/apm_resolver.py index cb3a2c627a..e26ff25517 100644 --- a/src/apm_cli/deps/apm_resolver.py +++ b/src/apm_cli/deps/apm_resolver.py @@ -1227,17 +1227,28 @@ def build_dependency_tree( self._apply_edge_selections(tree) return tree - @staticmethod - def _propagate_production(tree: DependencyTree) -> None: - """Mark every descendant of a production node production (prod wins over dev). + def _propagate_production(self, tree: DependencyTree) -> None: + """Mark every node a production node declares production (prod wins over dev). - A production edge can reach a node first loaded as dev (a root - devDependency a production sibling also declares); promoting only that - node would leave its already-queued descendants dev (#4731). + Follows materialized children and every recorded declaring edge, so a + node first loaded as dev (a root devDependency a production sibling also + declares) promotes its whole subtree, including children whose edges the + queue dedup dropped, independent of declaration order (#4731). """ + declared: dict[int, list[str]] = {} + for key, parents in self._edge_parents.items(): + for parent in parents: + declared.setdefault(id(parent), []).append(key) + by_key: dict[str, list[DependencyNode]] = {} + for node in tree.nodes.values(): + by_key.setdefault(node.dependency_ref.get_unique_key(), []).append(node) pending = [node for node in tree.nodes.values() if not node.is_dev] while pending: - for child in pending.pop().children: + node = pending.pop() + declared_children = ( + c for key in declared.get(id(node), ()) for c in by_key.get(key, ()) + ) + for child in [*node.children, *declared_children]: if child.is_dev: child.is_dev = False pending.append(child) diff --git a/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json b/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json index 25f42a82ca..b0afdf4a1e 100644 --- a/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json +++ b/tests/fixtures/lifecycle_bug_ledger/bugs/4731.json @@ -15,6 +15,7 @@ "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_lockfile_parents_anchoring_to_one_directory_are_one_parent", "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryIsOneDependency::test_root_declared_directory_wins_its_spelling", "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryNode::test_production_sibling_promotes_a_dev_library_and_its_descendants", - "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryNode::test_targeted_sibling_update_rechecks_the_library_at_its_own_anchor" + "tests/unit/deps/test_apm_resolver_helpers.py::TestOneAnchoredDirectoryNode::test_targeted_sibling_update_rechecks_the_library_at_its_own_anchor", + "tests/unit/deps/test_apm_resolver_helpers.py::test_production_reaches_a_shared_leaf_in_either_dev_order" ] } diff --git a/tests/unit/deps/test_apm_resolver_helpers.py b/tests/unit/deps/test_apm_resolver_helpers.py index eaeafed4f8..532aa3cc06 100644 --- a/tests/unit/deps/test_apm_resolver_helpers.py +++ b/tests/unit/deps/test_apm_resolver_helpers.py @@ -557,3 +557,36 @@ def test_targeted_sibling_update_rechecks_the_library_at_its_own_anchor( assert not tree.resolution_errors, tree.resolution_errors assert (tmp_path / "packages" / "sib" / "packages" / "lib") not in calls, calls assert (tmp_path / "packages" / "lib").resolve() in calls, calls + + +@pytest.mark.parametrize("dev_order", [("a", "lib"), ("lib", "a")], ids=["a-first", "lib-first"]) +def test_production_reaches_a_shared_leaf_in_either_dev_order( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, dev_order: tuple[str, str] +) -> None: + """A leaf both dev roots declare is production once a production edge reaches lib.""" + monkeypatch.chdir(tmp_path) + graph = {"sib": ["../lib"], "a": ["../leaf"], "lib": ["../leaf"], "leaf": []} + for name, deps in graph.items(): + package = tmp_path / "packages" / name + package.mkdir(parents=True) + listed = "".join(f" - {dep}\n" for dep in deps) + apm = f"dependencies:\n apm:\n{listed}" if deps else "" + (package / "apm.yml").write_text(f"name: {name}\nversion: 1.0.0\n{apm}", encoding="utf-8") + dev = "".join(f" - ./packages/{name}\n" for name in dev_order) + (tmp_path / "apm.yml").write_text( + "name: mono\nversion: 1.0.0\ndependencies:\n apm:\n - ./packages/sib\n" + f"devDependencies:\n apm:\n{dev}", + encoding="utf-8", + ) + resolver = APMDependencyResolver( + apm_modules_dir=tmp_path / "apm_modules", download_callback=_copy_local([]) + ) + resolver._project_root = tmp_path + + tree = resolver.build_dependency_tree(tmp_path / "apm.yml") + + assert not tree.resolution_errors, tree.resolution_errors + dev_flags = {node.dependency_ref.get_unique_key(): node.is_dev for node in tree.nodes.values()} + assert dev_flags["./packages/lib"] is False, dev_flags + assert dev_flags["local:packages/leaf"] is False, dev_flags + assert dev_flags["./packages/a"] is True, dev_flags