From 2088f9ecc423e24db3ebcdfbcb439698b6a623e8 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 17:05:37 +0100 Subject: [PATCH 1/6] fix(uninstall): keep a direct dependency another package still needs apm uninstall of a remote direct dependency that another installed package still needs transitively dropped the shared lock row, so the next apm install --frozen failed. The orphan owner now walks the removal roots too: a root still reachable from a survivor is removed from apm.yml only, stays installed, and its lock row is re-parented to the dependent package. Dry run and real run say which package still needs it. Fixes #4749 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../content/docs/reference/cli/uninstall.md | 4 + .../.apm/skills/apm-usage/commands.md | 2 +- src/apm_cli/commands/uninstall/cli.py | 136 +++++++++++++++- src/apm_cli/install/orphans.py | 49 ++++-- .../lifecycle_bug_ledger/bugs/4749.json | 17 ++ ...tall_shared_direct_dependency_lifecycle.py | 149 ++++++++++++++++++ 6 files changed, 336 insertions(+), 21 deletions(-) create mode 100644 tests/fixtures/lifecycle_bug_ledger/bugs/4749.json create mode 100644 tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py diff --git a/docs/src/content/docs/reference/cli/uninstall.md b/docs/src/content/docs/reference/cli/uninstall.md index 77c9795a26..0f46a5a623 100644 --- a/docs/src/content/docs/reference/cli/uninstall.md +++ b/docs/src/content/docs/reference/cli/uninstall.md @@ -96,6 +96,10 @@ What gets removed, in order: shared diamond dependencies. If a surviving package's manifest cannot be read, APM keeps every remaining candidate rather than guessing. Run again with `--verbose`, fix or restore the reported manifest, then retry. + A requested direct dependency that another installed package still + needs is removed from `apm.yml` only: it stays installed, its lockfile + entry now names that package as its parent, and `apm install --frozen` + keeps passing. The output says which package still needs it. Now-empty `apm_modules/` parent directories are cleaned at this step. 2. Target-scoped files owned only by the removed packages, while lockfile ownership is still available for safe cleanup. diff --git a/packages/apm-guide/.apm/skills/apm-usage/commands.md b/packages/apm-guide/.apm/skills/apm-usage/commands.md index cd08911b61..6eef864387 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/commands.md +++ b/packages/apm-guide/.apm/skills/apm-usage/commands.md @@ -65,7 +65,7 @@ scope. It reads only the selected store; it does not substitute another store. | `apm install [PKGS...]` | Install APM, MCP, and LSP dependencies (supports APM packages, Claude skills (SKILL.md), and plugin collections (plugin.json)); one effective target decision drives package, MCP, and LSP phases; dependency aliases materialize at the canonical install path, not duplicate noncanonical paths; plain/frozen installs replay matching dependency and provider lock entries, and a mutable ref without a matching lock entry resolves upstream instead of stale bare-cache refs, including with unrelated or sibling lock entries; a successful non-dry-run install also reconciles deployed artifacts, lockfile ownership, and merge-hook config/sidecar entries for any target dropped from `targets:`; project-local `.apm/` cleanup requires recorded concrete target ownership (including after whole-tree deletion), preserves ambiguous legacy output, user edits, and surviving package/target claims, including declared targets skipped by `--target`; a run narrowed by `--target` keeps a skipped runtime's MCP entry while the server stays declared and admitted there and the manifest still selects that runtime (undeclared or `targets:`-excluded servers are still removed); `apm install PKG` (project or `-g`) also installs declared local-path dependencies the lockfile does not record yet, keeps unrelated packages' lock entries but removes dependencies PKG no longer declares and nothing else retained needs from the lockfile, `apm_modules/` and deployed files | `--update` (deprecated; prefer `apm update`) refresh refs without accepting stale bare-cache answers, `--refresh` re-fetch all deps from upstream and re-resolve all ref pins, `--force` overwrite collisions and permit deployment after critical built-in scan findings (does NOT refresh refs by itself; `apm update --force` still requires upstream truth), `--frozen` requires the lockfile (unless `apm.yml` declares no APM, MCP or LSP dependency, a converged no-op that `apm audit --ci` also accepts) and checks manifest refs, pins, providers, transport, local-source content and available MCP declarations before the pipeline; unavailable package MCP evidence is verified after hydration, before deployment (see [MCP-only lock and frozen behavior](#mcp-only-lock-and-frozen-behavior); not network freshness; mutually exclusive with `--update`, package additions, and `--mcp`; before deployment it also fails when any deployed file (instruction, agent, command or skill) differs from its locked hash -- restore by deleting the listed files, rerunning `apm install`, and committing (`--force` also restores but overwrites every edit and skips the critical-findings block); normal install creates or repairs lock state; packages the lock lists but `apm.yml` no longer declares keep their deployed files, `apm_modules/` checkout and lock rows, with an info line naming them -- run `apm install` to remove them), `--dry-run` (runs the install pipeline up to its first write: contacts sources and applies the same policy and MCP checks; no package/deployment writes; positional packages and ref changes are previewed without changing an existing `apm.yml`; project bootstrap keeps its new manifest and explicit targets, while absent global `-g` bootstrap uses temporary preview state and does not create `~/.apm`; stale-file cleanup is not previewed), `--verbose`, `--only [apm\|mcp]` (APM packages or MCP/LSP service dependencies), `--target` (comma-separated, e.g. `--target claude,cursor`; resolution chain `--target` > apm.yml `targets:` > `apm config set target ...` > auto-detect; this decision is reused by package, MCP, and LSP phases; unresolved required service work fails non-zero before manifest or package writes, and native MCP/LSP write failures also fail non-zero; `intellij` is MCP-only and writes JetBrains Copilot's user-scope config; explicit lists are exact, so `intellij,claude` writes those two MCP configs and `all,intellij` adds JetBrains to `all`; on auto-bootstrap when no `apm.yml` exists, recognized manifest target(s) are persisted to the new manifest's `targets:` field so a later bare `apm update` reuses them (`intellij` is an IDE, not a target: every bootstrap, project or global `--mcp`, refuses it before any write; use `copilot`, or create `apm.yml` first to deploy JetBrains MCP config), except absent global dry-runs only preview targets in temporary state; the bootstrapped manifest omits `author` instead of recording the local Git identity; `--target all` deprecated, see `apm compile --all`; use `kiro` for Kiro IDE; use `grok-build` for stable Grok Build rules, agents, commands, skills, and `AGENTS.md`; use `copilot-cowork` with `--global` after `apm experimental enable copilot-cowork`; use `grok-cloud` after `apm experimental enable grok-cloud` to deploy skills only to `.grok/skills/`; use explicit target `hermes` to deploy skills and home-scoped MCP servers to `$HERMES_HOME/config.yaml` (or `~/.hermes/config.yaml` when unset or blank); run `apm compile` separately for `AGENTS.md`), use explicit target `grok-bot` to deploy skills only to `agent-data/workflows/` (project) or `~/agent-data/workflows/` (`--global`), `--dev` (moves a package already in `dependencies`; without `--dev`, a package already in `devDependencies` stays there), `-g` global (MCP deploys only to user-scope runtimes: Copilot CLI, Claude Code, Cursor, OpenCode, Codex CLI, Gemini CLI, Antigravity CLI, Kiro, Windsurf, JetBrains Copilot, and Hermes when selected explicitly), `--trust-transitive-mcp` (unapproved transitive MCP for this run only; never saved; keep one with `apm approve `), `--parallel-downloads N`, `--trust-bin` / `--no-trust-bin` (per-invocation consent for marketplace-plugin bin/ deployment: `--trust-bin` suppresses the trust-posture warning, `--no-trust-bin` skips bin/ even if policy allows; default deploys with a warning), `--allow-insecure`, `--allow-insecure-host HOSTNAME`, `--skill NAME` install named skills from a dependency that exposes selectable skills (repeatable; plugin manifests accept a leaf name or source-relative path under skills/; a CLI name or path that matches no declared skill fails before manifest or lockfile commit with available names; a non-empty persisted `skills:` selection matching no available skill fails nonzero with the dependency, requested names, and available names (or none) before any of that dependency's primitives are written, preserving its previously deployed bytes and ownership/hash records across repeated failures; correct `skills:` in apm.yml to restore normal reconciliation, including valid narrowing and dependency removal; persisted in apm.yml only on a successful CLI match; additive across separate installs -- a later `--skill X` adds to the existing pin (union) rather than replacing it, so previously deployed skills are never silently removed; `'*'` resets to the full bundle; drop a single skill by editing the `skills:` list in apm.yml then re-running install), `--legacy-skill-paths` restore per-client skill dirs, `--mcp NAME` add MCP entry using that same effective target decision (the shared decision applies, so `apm install --mcp NAME --target intellij` writes only JetBrains Copilot's MCP config; compilation target policy applies to every explicitly selected target; `apm install -g --mcp NAME` writes user-scope and bypasses the project-scope gate by design), `--transport`, `--url`, `--env KEY=VAL`, `--header KEY=VAL`, `--mcp-version`, `--registry URL` custom MCP registry, `--root DIR` redirect writes (`apm_modules/`, lockfile, `.gitignore`, integrated harness files) under DIR while `apm.yml`/`.apm/`/local deps resolve from `$PWD` (mirrors `pip install --target`; created if missing; not valid with `-g`/`--global`, which exits 2). Explicit plugin component paths must resolve inside the plugin root; missing declarations fail before deployment and lockfile commit. | | `apm install [PKGS...]` | Install APM, MCP, and LSP dependencies (supports APM packages, Claude skills (SKILL.md), and plugin collections (plugin.json)); one effective target decision drives package, MCP, and LSP phases; dependency aliases materialize at the canonical install path, not duplicate noncanonical paths; plain/frozen installs replay matching dependency and provider lock entries, and a mutable ref without a matching lock entry resolves upstream instead of stale bare-cache refs, including with unrelated or sibling lock entries; a successful non-dry-run install also reconciles deployed artifacts, lockfile ownership, and merge-hook config/sidecar entries for any target dropped from `targets:`; project-local `.apm/` cleanup requires recorded concrete target ownership (including after whole-tree deletion), preserves ambiguous legacy output, user edits, and surviving package/target claims, including declared targets skipped by `--target`; a run narrowed by `--target` keeps a skipped runtime's MCP entry while the server stays declared and admitted there and the manifest still selects that runtime (undeclared or `targets:`-excluded servers are still removed); `apm install PKG` (project or `-g`) also installs declared local-path dependencies the lockfile does not record yet, keeps unrelated packages' lock entries but removes dependencies PKG no longer declares and nothing else retained needs from the lockfile, `apm_modules/` and deployed files | `--update` (deprecated; prefer `apm update`) refresh refs without accepting stale bare-cache answers, `--refresh` re-fetch all deps from upstream and re-resolve all ref pins, `--force` overwrite collisions and permit deployment after critical built-in scan findings (does NOT refresh refs by itself; `apm update --force` still requires upstream truth), `--frozen` (default when `CI` is set and not empty, `0` or `false` and `apm.lock.yaml` exists; without a lockfile install resolves and writes one; `--no-frozen`, `--update`, `--refresh`, positional packages and `--mcp` opt out) requires the lockfile and checks manifest refs, pins, providers, transport, local-source content and available MCP declarations before the pipeline; unavailable package MCP evidence is verified after hydration, before deployment (see [MCP-only lock and frozen behavior](#mcp-only-lock-and-frozen-behavior); not network freshness; mutually exclusive with `--update`, package additions, and `--mcp`; before deployment it also fails when any deployed file (instruction, agent, command or skill) differs from its locked hash -- restore by deleting the listed files, rerunning `apm install`, and committing (`--force` also restores but overwrites every edit and skips the critical-findings block); normal install creates or repairs lock state; packages the lock lists but `apm.yml` no longer declares keep their deployed files, `apm_modules/` checkout and lock rows, with an info line naming them -- run `apm install` to remove them), `--dry-run` (no package/deployment writes; positional packages and ref changes are previewed without changing an existing `apm.yml`; project bootstrap keeps its new manifest and explicit targets, while absent global `-g` bootstrap uses temporary preview state and does not create `~/.apm`; stale-file cleanup is not previewed), `--verbose`, `--only [apm\|mcp]` (APM packages or MCP/LSP service dependencies), `--target` (comma-separated, e.g. `--target claude,cursor`; resolution chain `--target` > apm.yml `targets:` > `apm config set target ...` > auto-detect; this decision is reused by package, MCP, and LSP phases; unresolved required service work fails non-zero before manifest or package writes, and native MCP/LSP write failures also fail non-zero; `intellij` is MCP-only and writes JetBrains Copilot's user-scope config; explicit lists are exact, so `intellij,claude` writes those two MCP configs and `all,intellij` adds JetBrains to `all`; on auto-bootstrap when no `apm.yml` exists, recognized manifest target(s) are persisted to the new manifest's `targets:` field so a later bare `apm update` reuses them (`intellij` is an IDE, not a target: every bootstrap, project or global `--mcp`, refuses it before any write; use `copilot`, or create `apm.yml` first to deploy JetBrains MCP config), except absent global dry-runs only preview targets in temporary state; the bootstrapped manifest omits `author` instead of recording the local Git identity; `--target all` deprecated, see `apm compile --all`; use `kiro` for Kiro IDE; use `grok-build` for stable Grok Build rules, agents, commands, skills, and `AGENTS.md`; use `copilot-cowork` with `--global` after `apm experimental enable copilot-cowork`; use `grok-cloud` after `apm experimental enable grok-cloud` to deploy skills only to `.grok/skills/`; use explicit target `hermes` to deploy skills and home-scoped MCP servers to `$HERMES_HOME/config.yaml` (or `~/.hermes/config.yaml` when unset or blank); run `apm compile` separately for `AGENTS.md`), use explicit target `grok-bot` to deploy skills only to `agent-data/workflows/` (project) or `~/agent-data/workflows/` (`--global`), `--dev` (moves a package already in `dependencies`; without `--dev`, a package already in `devDependencies` stays there), `-g` global (MCP deploys only to user-scope runtimes: Copilot CLI, Claude Code, Cursor, OpenCode, Codex CLI, Gemini CLI, Antigravity CLI, Kiro, Windsurf, JetBrains Copilot, and Hermes when selected explicitly), `--trust-transitive-mcp` (unapproved transitive MCP for this run only; never saved; keep one with `apm approve `), `--parallel-downloads N`, `--trust-bin` / `--no-trust-bin` (per-invocation consent for marketplace-plugin bin/ deployment: `--trust-bin` suppresses the trust-posture warning, `--no-trust-bin` skips bin/ even if policy allows; default deploys with a warning), `--allow-insecure`, `--allow-insecure-host HOSTNAME`, `--skill NAME` install named skills from a dependency that exposes selectable skills (repeatable; plugin manifests accept a leaf name or source-relative path under skills/; a CLI name or path that matches no declared skill fails before manifest or lockfile commit with available names; a non-empty persisted `skills:` selection matching no available skill fails nonzero with the dependency, requested names, and available names (or none) before any of that dependency's primitives are written, preserving its previously deployed bytes and ownership/hash records across repeated failures; correct `skills:` in apm.yml to restore normal reconciliation, including valid narrowing and dependency removal; persisted in apm.yml only on a successful CLI match; additive across separate installs -- a later `--skill X` adds to the existing pin (union) rather than replacing it, so previously deployed skills are never silently removed; `'*'` resets to the full bundle; drop a single skill by editing the `skills:` list in apm.yml then re-running install), `--legacy-skill-paths` restore per-client skill dirs, `--mcp NAME` add MCP entry using that same effective target decision (the shared decision applies, so `apm install --mcp NAME --target intellij` writes only JetBrains Copilot's MCP config; compilation target policy applies to every explicitly selected target; `apm install -g --mcp NAME` writes user-scope and bypasses the project-scope gate by design), `--transport`, `--url`, `--env KEY=VAL`, `--header KEY=VAL`, `--mcp-version`, `--registry URL` custom MCP registry, `--root DIR` redirect writes (`apm_modules/`, lockfile, `.gitignore`, integrated harness files) under DIR while `apm.yml`/`.apm/`/local deps resolve from `$PWD` (mirrors `pip install --target`; created if missing; not valid with `-g`/`--global`, which exits 2). Explicit plugin component paths must resolve inside the plugin root; missing declarations fail before deployment and lockfile commit. | | `apm targets` | Show resolved deployment targets for the current project (Click group; reads filesystem signals; works with or without `apm.yml`) | `--all` also include the stable explicit-only targets (`agent-skills`, `antigravity`, `grok-bot`, `hermes`; only meaningful with `--json`), `--json` machine-readable output. No provenance line is printed (the table is the provenance). | -| `apm uninstall PKGS...` | Remove packages; reconcile tracked files, hooks, MCP, and LSP. Accepts `owner/repo`, `name@marketplace` (also for object-form `{name, marketplace}` entries, offline), exact declared local paths, or portable `_local/` keys with lock metadata. A local bundle path (`apm install `) is refused with a message that bundles cannot be uninstalled; an MCP server name is refused with its removal route (delete it under `dependencies.mcp` and run `apm install`, uninstall the package that brings it in, or, for a local-bundle server, a note that bundles cannot be uninstalled yet, #3887). A package declared more than once (both sections or several spellings) loses every declaration. Selection is atomic: missing or ambiguous identifiers exit before scripts or APM writes. Direct and orphan materialized directories are deleted before target cleanup or manifest and lockfile writes. Deletion failure exits 1 without `Uninstall complete` and retains declarations, the on-disk lockfile, and deployed ownership; earlier deletions are not rolled back. Fix permission or file-lock errors, or the unsafe path after a containment refusal, then retry the same command. Restore with `apm install` (`apm install --global` for user scope). An edited or unproven tracked file (no receipt or locked render) refuses before any change, naming each file and two remedies: move aside files holding your edits, run `apm install` with the source reachable, then uninstall; or move the files aside. A later undeletable tracked file keeps `apm.yml`, drops already-removed files from `apm.lock.yaml` so it claims only what is still on disk, and may leave removed directories; resolve the listed files and retry. Remaining packages are rebuilt only into targets apm.lock.yaml records; a target apm.yml declares since the last install is left to `apm install` (#4636). MCP cleanup uses recorded target ownership, attempts every owning runtime, and exits nonzero if any target fails. Safe LSP or managed hook cleanup failure (including a hook changed after the initial check or beneath a symlinked parent) preserves the conflicting configuration and exits nonzero after package removal; repair it, then run the scope-appropriate install command. Without a lockfile, no skill directories are removed. | `--dry-run`, `-g` global | +| `apm uninstall PKGS...` | Remove packages; reconcile tracked files, hooks, MCP, and LSP. Accepts `owner/repo`, `name@marketplace` (also for object-form `{name, marketplace}` entries, offline), exact declared local paths, or portable `_local/` keys with lock metadata. A local bundle path (`apm install `) is refused with a message that bundles cannot be uninstalled; an MCP server name is refused with its removal route (delete it under `dependencies.mcp` and run `apm install`, uninstall the package that brings it in, or, for a local-bundle server, a note that bundles cannot be uninstalled yet, #3887). A package declared more than once (both sections or several spellings) loses every declaration. A requested package that another installed package still needs is removed from `apm.yml` only; it stays installed and its lock row is re-parented, so `apm install --frozen` keeps passing (#4749). Selection is atomic: missing or ambiguous identifiers exit before scripts or APM writes. Direct and orphan materialized directories are deleted before target cleanup or manifest and lockfile writes. Deletion failure exits 1 without `Uninstall complete` and retains declarations, the on-disk lockfile, and deployed ownership; earlier deletions are not rolled back. Fix permission or file-lock errors, or the unsafe path after a containment refusal, then retry the same command. Restore with `apm install` (`apm install --global` for user scope). An edited or unproven tracked file (no receipt or locked render) refuses before any change, naming each file and two remedies: move aside files holding your edits, run `apm install` with the source reachable, then uninstall; or move the files aside. A later undeletable tracked file keeps `apm.yml`, drops already-removed files from `apm.lock.yaml` so it claims only what is still on disk, and may leave removed directories; resolve the listed files and retry. Remaining packages are rebuilt only into targets apm.lock.yaml records; a target apm.yml declares since the last install is left to `apm install` (#4636). MCP cleanup uses recorded target ownership, attempts every owning runtime, and exits nonzero if any target fails. Safe LSP or managed hook cleanup failure (including a hook changed after the initial check or beneath a symlinked parent) preserves the conflicting configuration and exits nonzero after package removal; repair it, then run the scope-appropriate install command. Without a lockfile, no skill directories are removed. | `--dry-run`, `-g` global | | `apm prune` | Remove unneeded recognized roots under `apm_modules/`, including manifestless `SKILL.md` packages after their lock entries disappear. No receipt or `.apm-pin` is required; personal content inside removable roots is also removed. Preserve declared direct/dev and retained transitive packages, packages a retained package still declares (even after a hand edit removed them from `apm.yml`; kept when a manifest is unreadable), bundles, and entire ancestors containing needed children. Switching `owner/repo` to `path:` dependencies on that repository needs no prune: the next install or update trims the old checkout to the requested subdirectories. GitHub owner/repository casing changes do not orphan packages or rename their directories; aliases, local paths, case-sensitive hosts, and in-repository paths retain their casing rules. Distinct repositories can share case-variant owner prefixes. Multiple case-equivalent paths for the same package exit 1 before cleanup: inspect the conflicting paths under `apm_modules/`, keep the intended package, and rerun `apm install`. Outside deployments retain ownership-based protections; stale records never authorize deleting untrusted or shared bytes. Deletion failures exit 1 with removed/failed counts; resolve the errors and rerun to converge. | `--dry-run` previews removal, retention, and ownership repair without mutation | | `apm export-patch` | Export local edits to APM-managed files as `git apply`-ready patches against their source packages (one `patches/@.patch` per package, locked base in the header; verbatim-deployed files only -- transformed deployments are listed as skipped with the reason). Read-only: never writes `apm.yml` or the lockfile. `apm audit` drift output and `apm install` point here when managed files carry local edits | `-o/--out DIR` output dir (default `patches`; must not point inside `apm_modules/`), `--dry-run` preview, `-v` verbose | | `apm deps list` | List manifest- and lockfile-resolved packages; ignore parent-owned embedded manifests. Orphan status uses `apm prune`'s selection: skills bundled inside a declared package are not orphans; a real package above a declared subdirectory is still reported. Direct locked local packages use actionable `_local/` keys without absolute paths; transitives are removed through their parent. Non-default hosts list the host-qualified key `apm uninstall` accepts; Source follows the declared or locked host type. | `-g` global, `--all` both scopes, `--insecure` | diff --git a/src/apm_cli/commands/uninstall/cli.py b/src/apm_cli/commands/uninstall/cli.py index 53fac068f1..5ba5eead22 100644 --- a/src/apm_cli/commands/uninstall/cli.py +++ b/src/apm_cli/commands/uninstall/cli.py @@ -56,6 +56,7 @@ _removed_lock_key, _stage_shared_local_survivors, _sync_integrations_after_uninstall, + _uninstall_orphan_decision, _validate_uninstall_packages, gate_retired_hook_survivors, manifest_dependency_entries, @@ -68,7 +69,9 @@ ) -def _uninstall_summary(removed_count: int, retained_count: int, orphan_count: int) -> str: +def _uninstall_summary( + removed_count: int, retained_count: int, orphan_count: int, still_needed_count: int = 0 +) -> str: """Return the final summary, counting each package once.""" summary = f"removed {_count_noun(removed_count, 'package')}" if orphan_count: @@ -81,9 +84,105 @@ def _uninstall_summary(removed_count: int, retained_count: int, orphan_count: in if retained_count: retained = _count_noun(retained_count, "package") summary += f"; removed {retained} from the selected profile only" + if still_needed_count: + kept = _count_noun(still_needed_count, "declaration") + summary += f"; removed {kept} whose package another dependency still needs" return summary +def _manifest_declarations_to_drop(declarations: list, packages_to_remove: list) -> list: + """Return every apm.yml declaration of *packages_to_remove* (#3693, #4749). + + Still-needed packages are dropped from the manifest too, so the caller + passes them alongside the packages that are uninstalled for real. + """ + return list(manifest_declarations_of(declarations, packages_to_remove)) + + +def _split_still_needed_packages( + lockfile, packages_to_remove: list, modules_dir, apm_yml_path, logger +) -> tuple[list, list, dict]: + """Split removals into full removals and declarations a survivor still needs. + + A removed direct dependency that a surviving package still declares keeps + its lock row, ``apm_modules`` copy and deployed files; only its manifest + declaration goes, and the orphan owner's repair re-parents the row + (#4749). Returns ``(removed, still_needed, repairs)``. + """ + if not lockfile or not packages_to_remove or not modules_dir.exists(): + return packages_to_remove, [], {} + decision = _uninstall_orphan_decision( + lockfile, packages_to_remove, modules_dir, apm_yml_path, logger, warn_on_incomplete=False + ) + if not decision.rescued_roots: + return packages_to_remove, [], {} + still_needed = [ + package + for package in packages_to_remove + if _removed_lock_key(package, lockfile) in decision.rescued_roots + ] + removed = [package for package in packages_to_remove if package not in still_needed] + repairs = { + key: repair for key, repair in decision.repairs.items() if key in decision.rescued_roots + } + return removed, still_needed, repairs + + +def _split_removals( + packages_to_remove: list, lockfile, paths: tuple, logger, *, user_scope: bool +) -> tuple[list, list, list, dict]: + """Split the selection into full, selected-profile and declaration-only removals.""" + removed, retained = _split_selected_profile_packages( + packages_to_remove, lockfile, user_scope=user_scope + ) + modules_dir, apm_yml_path = paths + removed, still_needed, repairs = _split_still_needed_packages( + lockfile, removed, modules_dir, apm_yml_path, logger + ) + return removed, retained, still_needed, repairs + + +def _reparent_still_needed(lockfile, repairs: dict) -> bool: + """Re-parent each still-needed row to the survivor that reaches it.""" + updated = False + for key, (parent, local_path, dev_only) in repairs.items(): + kept = lockfile.get_dependency(key) + if kept is None: + continue + kept.resolved_by = parent + kept.is_dev = dev_only + if local_path is not None: + kept.local_path = local_path + updated = True + return updated + + +def _still_needed_summary( + selections: tuple[list, list, list], orphan_removed: int, repairs: dict, lockfile, logger +) -> str: + """Report still-needed packages and return the final uninstall summary.""" + removed, retained, still_needed = selections + _report_still_needed_packages(still_needed, repairs, lockfile, logger, dry_run=False) + return _uninstall_summary(len(removed), len(retained), orphan_removed, len(still_needed)) + + +def _report_still_needed_packages( + still_needed: list, repairs: dict, lockfile, logger: CommandLogger, *, dry_run: bool +) -> None: + """Explain why a removed declaration's package stays installed.""" + for package in still_needed: + label = _dependency_public_label(package) + parent = repairs.get(_removed_lock_key(package, lockfile), (None,))[0] + needed_by = f"{parent} still depends on it" if parent else "another dependency needs it" + if dry_run: + logger.progress( + f"Dry run: Would remove {label} from apm.yml only; it stays installed " + f"because {needed_by}" + ) + else: + logger.progress(f"Kept {label} installed because {needed_by}") + + def _report_uninstall_outcome( logger: CommandLogger, summary: str, @@ -754,8 +853,9 @@ def _dry_run_with_selected_profile( *, surviving_dependencies: list, lockfile=None, + still_needed: tuple[list, dict] = ((), {}), ) -> None: - """Preview full removals and selected-profile-only removals.""" + """Preview full, selected-profile-only and declaration-only removals.""" if packages_to_remove: _dry_run_uninstall( packages_to_remove, @@ -766,6 +866,9 @@ def _dry_run_with_selected_profile( lockfile=lockfile, ) _report_selected_profile_packages(retained_packages, logger, dry_run=True) + _report_still_needed_packages( + list(still_needed[0]), still_needed[1], lockfile, logger, dry_run=True + ) def _retire_selected_profile_packages( @@ -1046,8 +1149,17 @@ def uninstall(ctx, packages, dry_run, verbose, global_): selected_package_labels = tuple( _dependency_lifecycle_label(package) for package in packages_to_remove ) - packages_to_remove, retained_packages = _split_selected_profile_packages( - packages_to_remove, lockfile, user_scope=scope is InstallScope.USER + ( + packages_to_remove, + retained_packages, + still_needed_packages, + still_needed_repairs, + ) = _split_removals( + packages_to_remove, + lockfile, + (modules_dir, apm_yml_path), + logger, + user_scope=scope is InstallScope.USER, ) surviving_deps = list(current_deps) for declaration in manifest_declarations_of(current_deps, packages_to_remove): @@ -1108,6 +1220,7 @@ def uninstall(ctx, packages, dry_run, verbose, global_): apm_yml_path, surviving_dependencies=surviving_deps, lockfile=lockfile, + still_needed=(still_needed_packages, still_needed_repairs), ) return @@ -1201,7 +1314,7 @@ def uninstall(ctx, packages, dry_run, verbose, global_): profile_lock_updated = _retire_selected_profile_packages( lockfile, profile_keys, profile_survivors, retained_packages, logger ) - if not packages_to_remove: + if not packages_to_remove and not still_needed_packages: _finish_selected_profile_uninstall( lockfile=lockfile, lockfile_path=lockfile_path, @@ -1222,7 +1335,9 @@ def uninstall(ctx, packages, dry_run, verbose, global_): ("dependencies.apm", prod_deps), ("devDependencies.apm", dev_deps), ): - for declaration in manifest_declarations_of(declarations, packages_to_remove): + for declaration in _manifest_declarations_to_drop( + declarations, [*packages_to_remove, *still_needed_packages] + ): declarations.remove(declaration) package_label = _dependency_public_label(declaration) _progress_once( @@ -1282,6 +1397,7 @@ def uninstall(ctx, packages, dry_run, verbose, global_): if orphan_key in lockfile.dependencies: del lockfile.dependencies[orphan_key] lockfile_updated = True + lockfile_updated |= _reparent_still_needed(lockfile, still_needed_repairs) # Step 10: Sync integrations cleaned = { @@ -1428,8 +1544,12 @@ def uninstall(ctx, packages, dry_run, verbose, global_): ) # Final summary: count each package once, whichever stores it left. - summary = _uninstall_summary( - len(packages_to_remove), len(retained_packages), orphan_removed + summary = _still_needed_summary( + (packages_to_remove, retained_packages, still_needed_packages), + orphan_removed, + still_needed_repairs, + lockfile, + logger, ) if compile_inputs is not None: hint_compile_after_removal(compile_inputs, modules_dir, logger) diff --git a/src/apm_cli/install/orphans.py b/src/apm_cli/install/orphans.py index 84cec6a0dc..884df52874 100644 --- a/src/apm_cli/install/orphans.py +++ b/src/apm_cli/install/orphans.py @@ -113,13 +113,16 @@ class OrphanRemovalDecision: ``retained_paths`` installed roots kept as required package content, and ``stale_keys`` lock rows without removable package content. ``superseded_roots`` pairs each released root with the retained package - subtrees it still hosts. + subtrees it still hosts. ``rescued_roots`` are an uninstall's own removal + roots that a surviving package still reaches: only their declaration goes, + their lock row stays (re-parented through ``repairs``) with its content. """ operation: OrphanOperation candidate_keys: frozenset[str] = frozenset() removed_keys: frozenset[str] = frozenset() rescued_keys: frozenset[str] = frozenset() + rescued_roots: frozenset[str] = frozenset() retained_keys: frozenset[str] = frozenset() removed_files: Mapping[str, tuple[str, ...]] = field( default_factory=lambda: MappingProxyType({}) @@ -542,34 +545,37 @@ def _lock_keys_by_install_path( def _decide_uninstall( lockfile: LockFile, roots: Sequence[object], probe: ReachabilityProbe ) -> OrphanRemovalDecision: - """Decide which removed roots' descendants are truly unreachable. + """Decide which removed roots and descendants are truly unreachable. Subtracts the surviving direct dependencies and every still-declared lockfile entry from the backward-scan candidates, then asks :mod:`apm_cli.deps.reachability` whether a remaining candidate is still forward-reachable from a surviving package's own manifest (the - shared/diamond-dependency rescue). An incomplete walk keeps every - candidate this run; with replacement evidence it refuses instead. - ``repairs`` maps each rescued key to the ``(parent_repo_url, - local_path, dev_only)`` of the surviving node that reached it; only the - real run may persist them. + shared/diamond-dependency rescue). The removal roots themselves are + asked too: a root a surviving package still declares is a + ``rescued_root`` whose declaration alone goes (#4749). An incomplete walk + keeps every descendant candidate and rescues no root this run; with + replacement evidence it refuses instead. ``repairs`` maps each rescued + key to the ``(parent_repo_url, local_path, dev_only)`` of the surviving + node that reached it; only the real run may persist them. """ operation = OrphanOperation.UNINSTALL if not probe.apm_modules_dir.exists(): return OrphanRemovalDecision(operation=operation) orphans, removed_parents = _collect_orphan_candidates(lockfile, list(roots)) - if not orphans: - return OrphanRemovalDecision(operation=operation) + root_keys = _locked_root_keys(lockfile, roots) remaining = {ref.get_unique_key() for ref in (*probe.direct_refs, *probe.dev_refs)} for dep in lockfile.get_package_dependencies(): key = dep.get_unique_key() if ( key not in orphans + and key not in root_keys and lockfile_parent_identity(dep, lockfile.replacements) not in removed_parents ): remaining.add(key) candidate_orphans = frozenset(orphans) - remaining - if not candidate_orphans: + candidate_roots = root_keys - remaining + if not candidate_orphans and not candidate_roots: return OrphanRemovalDecision(operation=operation) from ..deps.reachability import compute_forward_reachable_keys @@ -579,10 +585,14 @@ def _decide_uninstall( probe.project_root, probe.apm_modules_dir, list(probe.direct_refs), - candidate_orphans, + candidate_orphans | candidate_roots, dev_refs=probe.dev_refs, ) if not walk.complete: + if not candidate_orphans: + # Only roots were asked: an unverifiable survivor rescues none, + # so the removal proceeds exactly as before (no descendant to keep). + return OrphanRemovalDecision(operation=operation) if lockfile.replacements is not None: unverifiable = sorted({key for key, _reason in walk.unverifiable}) details = ", ".join(unverifiable[:3]) @@ -600,9 +610,10 @@ def _decide_uninstall( reachability=walk, ) rescued = candidate_orphans & walk.reachable + rescued_roots = candidate_roots & walk.reachable repairs = { key: (*walk.reachable_via[key], key in walk.dev_only) - for key in rescued + for key in rescued | rescued_roots if key in walk.reachable_via } return OrphanRemovalDecision( @@ -610,11 +621,25 @@ def _decide_uninstall( candidate_keys=candidate_orphans, removed_keys=candidate_orphans - walk.reachable, rescued_keys=rescued, + rescued_roots=rescued_roots, repairs=MappingProxyType(repairs), reachability=walk, ) +def _locked_root_keys(lockfile: LockFile, roots: Sequence[object]) -> frozenset[str]: + """Lock keys of the removal roots that hold a package row.""" + keys: set[str] = set() + for root in roots: + try: + key = parse_dependency_entry(root).get_unique_key() + except (ValueError, TypeError, AttributeError, KeyError): + continue + if key in lockfile.dependencies and key != _SELF_KEY: + keys.add(key) + return frozenset(keys) + + def _build_expected_install_paths( declared_deps, lockfile, diff --git a/tests/fixtures/lifecycle_bug_ledger/bugs/4749.json b/tests/fixtures/lifecycle_bug_ledger/bugs/4749.json new file mode 100644 index 0000000000..e0bb5a1f6e --- /dev/null +++ b/tests/fixtures/lifecycle_bug_ledger/bugs/4749.json @@ -0,0 +1,17 @@ +{ + "issue": 4749, + "fixed_in": "Unreleased", + "summary": "apm uninstall of a remote direct dependency that another installed package still needs transitively dropped its shared apm.lock.yaml row, so the next apm install --frozen failed; uninstall now removes only the apm.yml declaration, keeps the package installed and re-parents the lock row to the dependent package.", + "failure_modes": [ + "cleanup", + "outcome" + ], + "properties": [ + "lockfile.frozen_preserves_bytes", + "outcome.status_matches_state" + ], + "regression_tests": [ + "tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py::test_uninstall_keeps_a_direct_dependency_another_package_still_needs", + "tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py::test_uninstall_still_removes_a_dependency_nothing_else_needs" + ] +} diff --git a/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py b/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py new file mode 100644 index 0000000000..655cc52e76 --- /dev/null +++ b/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py @@ -0,0 +1,149 @@ +"""Uninstalling a direct dependency another package still needs keeps its lock row (#4749). + +PROMISE: P-INV-I3 -- after ``apm uninstall e``, where a remaining direct +dependency ``d`` also depends on ``e``, ``apm install --frozen`` and +``apm audit --ci`` still agree the project is current, because ``e``'s lock +row and deployed files stay, re-attributed to ``d`` +(source: #4749 scope record). +CELL: OP=uninstall SRC=git PRIM=skill SCOPE=project LOCK=consistent +GRAPH=direct-also-transitive | control: GRAPH=direct-unreachable + +A dependency no other package reaches is still removed in full. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from apm_cli.utils.yaml_io import dump_yaml, load_yaml +from tests.integration._install_audit_replay_kit import ( + ReplayWorld, + deployed_files, + lock_bytes, + tree_digest, + write, +) + +pytestmark = [ + pytest.mark.integration, + pytest.mark.e2e, + pytest.mark.requires_apm_binary, + pytest.mark.promise("P-INV-I3", "P-INV-I1"), +] + + +def _skill_package(root: Path, name: str, deps: tuple[str, ...] = ()) -> None: + """One skill named after the package, so packages never share a deployed path.""" + 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 / f".apm/skills/{name}-skill/SKILL.md", + f"---\nname: {name}-skill\ndescription: Skill of {name}\n---\n# {name}\n", + ) + + +def _parent_of(child: str): + """Author a package that declares ``test/`` as its own dependency.""" + + def _author(root: Path, name: str) -> None: + _skill_package(root, name, (f"test/{child}",)) + + return _author + + +def _world(tmp_path: Path, apm_binary_path: Path) -> ReplayWorld: + world = ReplayWorld.create(tmp_path, apm_binary_path) + world.publish("e", _skill_package) + world.publish("d", _parent_of("e")) + world.publish("f", _skill_package) + dump_yaml( + { + "name": "proj", + "version": "1.0.0", + "targets": ["claude"], + "dependencies": {"apm": ["test/d", "test/e", "test/f"]}, + }, + world.project / "apm.yml", + ) + world.apm("install") + world.apm("install", "--frozen") + return world + + +def _rows(world: ReplayWorld) -> dict[str, dict]: + lock = load_yaml(world.project / "apm.lock.yaml") + return {row["repo_url"]: row for row in lock["dependencies"]} + + +def _row_files(world: ReplayWorld, repo_url: str) -> set[str]: + return set(_rows(world)[repo_url].get("deployed_files") or []) + + +def test_uninstall_keeps_a_direct_dependency_another_package_still_needs( + tmp_path: Path, apm_binary_path: Path +) -> None: + world = _world(tmp_path, apm_binary_path) + before = _rows(world) + assert before["test/e"].get("resolved_by") is None + e_files = _row_files(world, "test/e") + assert e_files + tree_before = tree_digest(world.project) + + # The preview names the declaration-only removal and writes nothing. + preview = world.apm("uninstall", "test/e", "--dry-run") + assert ( + "Would remove test/e from apm.yml only; it stays installed because " + "test/d still depends on it" + ) in " ".join(preview.stdout.split()) + assert tree_digest(world.project) == tree_before + + result = world.apm("uninstall", "test/e") + assert "Kept test/e installed because test/d still depends on it" in " ".join( + result.stdout.split() + ) + + manifest = load_yaml(world.project / "apm.yml") + assert manifest["dependencies"]["apm"] == ["test/d", "test/f"] + after = _rows(world) + # e stays locked, now attributed to the package that still needs it. + assert set(after) == {"test/d", "test/e", "test/f"} + assert after["test/e"]["resolved_by"] == "test/d" + assert after["test/e"]["resolved_commit"] == before["test/e"]["resolved_commit"] + assert set(after["test/e"].get("deployed_files") or []) == e_files + assert (world.project / "apm_modules" / "test" / "e" / "apm.yml").is_file() + # Only apm.yml and the lockfile changed; every deployed file is intact. + tree_after = tree_digest(world.project) + changed = { + path + for path in set(tree_before) | set(tree_after) + if tree_before.get(path) != tree_after.get(path) + } + assert changed == {"apm.yml", "apm.lock.yaml"} + + # I3: both readers agree the uninstalled-but-still-needed state is current. + lock_after = lock_bytes(world.project) + world.apm("install", "--frozen") + world.apm("audit", "--ci") + assert lock_bytes(world.project) == lock_after + assert tree_digest(world.project) == tree_after + + +def test_uninstall_still_removes_a_dependency_nothing_else_needs( + tmp_path: Path, apm_binary_path: Path +) -> None: + world = _world(tmp_path, apm_binary_path) + f_files = _row_files(world, "test/f") + assert f_files + + world.apm("uninstall", "test/f") + + assert load_yaml(world.project / "apm.yml")["dependencies"]["apm"] == ["test/d", "test/e"] + assert set(_rows(world)) == {"test/d", "test/e"} + assert not (world.project / "apm_modules" / "test" / "f").exists() + assert not any((world.project / path).exists() for path in f_files) + assert not (f_files & deployed_files(world.project)) + world.apm("install", "--frozen") From cd352dcffc0f3a38bd0573bad79336443120f691 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 17:07:06 +0100 Subject: [PATCH 2/6] docs(changelog): fragment for #4765 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- changelog.d/4765.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/4765.fixed.md diff --git a/changelog.d/4765.fixed.md b/changelog.d/4765.fixed.md new file mode 100644 index 0000000000..f7c0cb973d --- /dev/null +++ b/changelog.d/4765.fixed.md @@ -0,0 +1 @@ +- `apm uninstall` keeps a dependency another installed package still needs, so `apm install --frozen` keeps passing. (#4765) From bebe04c2dc08f566219565154efe41dcd0e28d38 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 17:21:30 +0100 Subject: [PATCH 3/6] fix(uninstall): word the still-needed line outside the Kept vocabulary Kept lines belong to core/remediation (files left in place); a package that stays installed now reads ' stays installed because still depends on it'. Re-anchor the lifecycle generator rule evidence for the uninstall options that moved. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/commands/uninstall/cli.py | 2 +- .../test_uninstall_shared_direct_dependency_lifecycle.py | 2 +- tests/lifecycle/generator/rules.py | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/apm_cli/commands/uninstall/cli.py b/src/apm_cli/commands/uninstall/cli.py index 5ba5eead22..4e6aa4dbe4 100644 --- a/src/apm_cli/commands/uninstall/cli.py +++ b/src/apm_cli/commands/uninstall/cli.py @@ -180,7 +180,7 @@ def _report_still_needed_packages( f"because {needed_by}" ) else: - logger.progress(f"Kept {label} installed because {needed_by}") + logger.progress(f"{label} stays installed because {needed_by}") def _report_uninstall_outcome( diff --git a/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py b/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py index 655cc52e76..a57316d02d 100644 --- a/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py +++ b/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py @@ -102,7 +102,7 @@ def test_uninstall_keeps_a_direct_dependency_another_package_still_needs( assert tree_digest(world.project) == tree_before result = world.apm("uninstall", "test/e") - assert "Kept test/e installed because test/d still depends on it" in " ".join( + assert "test/e stays installed because test/d still depends on it" in " ".join( result.stdout.split() ) diff --git a/tests/lifecycle/generator/rules.py b/tests/lifecycle/generator/rules.py index 5cef6abab7..3f3ab04bbc 100644 --- a/tests/lifecycle/generator/rules.py +++ b/tests/lifecycle/generator/rules.py @@ -85,8 +85,8 @@ def __str__(self) -> str: Ev("src/apm_cli/commands/update.py", 710, '"--target"'), ), "uninstall": ( - Ev("src/apm_cli/commands/uninstall/cli.py", 853, 'argument("packages"'), - Ev("src/apm_cli/commands/uninstall/cli.py", 855, '"--dry-run"'), + Ev("src/apm_cli/commands/uninstall/cli.py", 963, 'argument("packages"'), + Ev("src/apm_cli/commands/uninstall/cli.py", 965, '"--dry-run"'), ), "prune": ( Ev("src/apm_cli/commands/prune.py", 85, '"--dry-run"'), @@ -154,7 +154,7 @@ def __str__(self) -> str: USER_SCOPE_EVIDENCE: Mapping[str, Ev] = { "install": Ev(_INSTALL, 933, '"--global"'), "update": Ev("src/apm_cli/commands/update.py", 675, '"--global"'), - "uninstall": Ev("src/apm_cli/commands/uninstall/cli.py", 861, '"--global"'), + "uninstall": Ev("src/apm_cli/commands/uninstall/cli.py", 971, '"--global"'), "compile": Ev(_COMPILE, 1396, '"--global"'), "lock": Ev("src/apm_cli/commands/lock.py", 107, '"--global"'), "approve-deny": Ev(_APPROVE, 239, '"--user"'), From 1baf0b364d59c0cd88f5c9e84b24e070a59521ab Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 18:32:16 +0100 Subject: [PATCH 4/6] fix(uninstall): still-needed declarations leave survivor intent; re-derive depth; rescue reached roots Review follow-ups on #4765: - Survivor intent, the deletion-evidence projection and the selection shrink now drop the still-needed declarations too, so the direct edge leaves the skill/target union and the row narrows to what the dependent package still selects. - The orphan owner returns rescued_depths: a rescued root sits one level below its new parent and its recorded subtree follows, so trust and tree consumers stop treating it as direct and a later install writes the same lockfile. - An incomplete walk still rescues every root it reached, and replacement evidence refuses whenever an orphan or an unreached root cannot be verified, instead of returning early. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/commands/uninstall/cli.py | 78 ++++++++++++++----- src/apm_cli/install/orphans.py | 74 ++++++++++++++---- .../test_skill_selection_merge_lifecycle.py | 28 +++++++ ...tall_shared_direct_dependency_lifecycle.py | 6 ++ 4 files changed, 151 insertions(+), 35 deletions(-) diff --git a/src/apm_cli/commands/uninstall/cli.py b/src/apm_cli/commands/uninstall/cli.py index 4e6aa4dbe4..d716193572 100644 --- a/src/apm_cli/commands/uninstall/cli.py +++ b/src/apm_cli/commands/uninstall/cli.py @@ -5,7 +5,7 @@ import sys import traceback from dataclasses import dataclass -from typing import Any +from typing import Any, NamedTuple import click @@ -99,38 +99,48 @@ def _manifest_declarations_to_drop(declarations: list, packages_to_remove: list) return list(manifest_declarations_of(declarations, packages_to_remove)) +class _StillNeededRepair(NamedTuple): + """Orphan-owner repair for still-needed rows: new parents and subtree depths.""" + + parents: dict + depths: dict + + +_NO_STILL_NEEDED_REPAIR = _StillNeededRepair({}, {}) + + def _split_still_needed_packages( lockfile, packages_to_remove: list, modules_dir, apm_yml_path, logger -) -> tuple[list, list, dict]: +) -> tuple[list, list, _StillNeededRepair]: """Split removals into full removals and declarations a survivor still needs. A removed direct dependency that a surviving package still declares keeps its lock row, ``apm_modules`` copy and deployed files; only its manifest declaration goes, and the orphan owner's repair re-parents the row - (#4749). Returns ``(removed, still_needed, repairs)``. + (#4749). Returns ``(removed, still_needed, repair)``. """ if not lockfile or not packages_to_remove or not modules_dir.exists(): - return packages_to_remove, [], {} + return packages_to_remove, [], _NO_STILL_NEEDED_REPAIR decision = _uninstall_orphan_decision( lockfile, packages_to_remove, modules_dir, apm_yml_path, logger, warn_on_incomplete=False ) if not decision.rescued_roots: - return packages_to_remove, [], {} + return packages_to_remove, [], _NO_STILL_NEEDED_REPAIR still_needed = [ package for package in packages_to_remove if _removed_lock_key(package, lockfile) in decision.rescued_roots ] removed = [package for package in packages_to_remove if package not in still_needed] - repairs = { + parents = { key: repair for key, repair in decision.repairs.items() if key in decision.rescued_roots } - return removed, still_needed, repairs + return removed, still_needed, _StillNeededRepair(parents, dict(decision.rescued_depths)) def _split_removals( packages_to_remove: list, lockfile, paths: tuple, logger, *, user_scope: bool -) -> tuple[list, list, list, dict]: +) -> tuple[list, list, list, _StillNeededRepair]: """Split the selection into full, selected-profile and declaration-only removals.""" removed, retained = _split_selected_profile_packages( packages_to_remove, lockfile, user_scope=user_scope @@ -142,10 +152,10 @@ def _split_removals( return removed, retained, still_needed, repairs -def _reparent_still_needed(lockfile, repairs: dict) -> bool: - """Re-parent each still-needed row to the survivor that reaches it.""" +def _reparent_still_needed(lockfile, repair: _StillNeededRepair) -> bool: + """Re-parent each still-needed row and move its subtree one level down.""" updated = False - for key, (parent, local_path, dev_only) in repairs.items(): + for key, (parent, local_path, dev_only) in repair.parents.items(): kept = lockfile.get_dependency(key) if kept is None: continue @@ -154,25 +164,47 @@ def _reparent_still_needed(lockfile, repairs: dict) -> bool: if local_path is not None: kept.local_path = local_path updated = True + for key, depth in repair.depths.items(): + kept = lockfile.get_dependency(key) + if kept is not None and kept.depth != depth: + kept.depth = depth + updated = True return updated +def _surviving_declarations(current_deps: list, packages_to_remove: list) -> list: + """Declarations apm.yml keeps once every removed declaration goes.""" + surviving = list(current_deps) + for declaration in manifest_declarations_of(current_deps, packages_to_remove): + surviving.remove(declaration) + return surviving + + def _still_needed_summary( - selections: tuple[list, list, list], orphan_removed: int, repairs: dict, lockfile, logger + selections: tuple[list, list, list], + orphan_removed: int, + repair: _StillNeededRepair, + lockfile, + logger, ) -> str: """Report still-needed packages and return the final uninstall summary.""" removed, retained, still_needed = selections - _report_still_needed_packages(still_needed, repairs, lockfile, logger, dry_run=False) + _report_still_needed_packages(still_needed, repair, lockfile, logger, dry_run=False) return _uninstall_summary(len(removed), len(retained), orphan_removed, len(still_needed)) def _report_still_needed_packages( - still_needed: list, repairs: dict, lockfile, logger: CommandLogger, *, dry_run: bool + still_needed: list, + repair: _StillNeededRepair, + lockfile, + logger: CommandLogger, + *, + dry_run: bool, ) -> None: """Explain why a removed declaration's package stays installed.""" for package in still_needed: label = _dependency_public_label(package) - parent = repairs.get(_removed_lock_key(package, lockfile), (None,))[0] + parent = repair.parents.get(_removed_lock_key(package, lockfile), (None,))[0] needed_by = f"{parent} still depends on it" if parent else "another dependency needs it" if dry_run: logger.progress( @@ -853,7 +885,7 @@ def _dry_run_with_selected_profile( *, surviving_dependencies: list, lockfile=None, - still_needed: tuple[list, dict] = ((), {}), + still_needed: tuple[list, _StillNeededRepair] = ((), _NO_STILL_NEEDED_REPAIR), ) -> None: """Preview full, selected-profile-only and declaration-only removals.""" if packages_to_remove: @@ -1161,9 +1193,9 @@ def uninstall(ctx, packages, dry_run, verbose, global_): logger, user_scope=scope is InstallScope.USER, ) - surviving_deps = list(current_deps) - for declaration in manifest_declarations_of(current_deps, packages_to_remove): - surviving_deps.remove(declaration) + surviving_deps = _surviving_declarations( + current_deps, [*packages_to_remove, *still_needed_packages] + ) removed_keys = builtins.set() for package in packages_to_remove: removed_keys.add(_removed_lock_key(package, lockfile)) @@ -1233,7 +1265,7 @@ def uninstall(ctx, packages, dry_run, verbose, global_): removed_keys | builtins.set(projected_orphans) | profile_keys, profile_survivors, staged_local_refreshes, - (packages_to_remove, modules_dir, apm_yml_path), + ([*packages_to_remove, *still_needed_packages], modules_dir, apm_yml_path), logger, user_scope=scope is InstallScope.USER, ) @@ -1265,7 +1297,11 @@ def uninstall(ctx, packages, dry_run, verbose, global_): ) # Survivors whose selection shrinks are redeployed in full below. refreshed_survivor_keys |= _shrink_surviving_selections( - lockfile, packages_to_remove, modules_dir, apm_yml_path, logger + lockfile, + [*packages_to_remove, *still_needed_packages], + modules_dir, + apm_yml_path, + logger, ) except (OSError, PathTraversalError, LocalSurvivorRefreshError, CodexNativeError) as exc: _report_package_removal_failure(logger, exc, user_scope=scope is InstallScope.USER) diff --git a/src/apm_cli/install/orphans.py b/src/apm_cli/install/orphans.py index 884df52874..69b55c53f8 100644 --- a/src/apm_cli/install/orphans.py +++ b/src/apm_cli/install/orphans.py @@ -115,7 +115,9 @@ class OrphanRemovalDecision: ``superseded_roots`` pairs each released root with the retained package subtrees it still hosts. ``rescued_roots`` are an uninstall's own removal roots that a surviving package still reaches: only their declaration goes, - their lock row stays (re-parented through ``repairs``) with its content. + their lock row stays (re-parented through ``repairs``) with its content, + and ``rescued_depths`` gives the depth it and its subtree take below the + new parent. """ operation: OrphanOperation @@ -139,6 +141,7 @@ class OrphanRemovalDecision: repairs: Mapping[str, tuple[str, str | None, bool]] = field( default_factory=lambda: MappingProxyType({}) ) + rescued_depths: Mapping[str, int] = field(default_factory=lambda: MappingProxyType({})) reachability: ReachabilityResult | None = None @property @@ -554,8 +557,8 @@ def _decide_uninstall( shared/diamond-dependency rescue). The removal roots themselves are asked too: a root a surviving package still declares is a ``rescued_root`` whose declaration alone goes (#4749). An incomplete walk - keeps every descendant candidate and rescues no root this run; with - replacement evidence it refuses instead. ``repairs`` maps each rescued + keeps every descendant candidate and rescues only the roots it already + reached; with replacement evidence it refuses instead. ``repairs`` maps each rescued key to the ``(parent_repo_url, local_path, dev_only)`` of the surviving node that reached it; only the real run may persist them. """ @@ -589,11 +592,8 @@ def _decide_uninstall( dev_refs=probe.dev_refs, ) if not walk.complete: - if not candidate_orphans: - # Only roots were asked: an unverifiable survivor rescues none, - # so the removal proceeds exactly as before (no descendant to keep). - return OrphanRemovalDecision(operation=operation) - if lockfile.replacements is not None: + unreached_roots = candidate_roots - walk.reachable + if lockfile.replacements is not None and (candidate_orphans or unreached_roots): unverifiable = sorted({key for key, _reason in walk.unverifiable}) details = ", ".join(unverifiable[:3]) if len(unverifiable) > 3: @@ -603,19 +603,23 @@ def _decide_uninstall( f"({len(unverifiable)} manifest(s): {details}). Restore missing or " "invalid package manifests before uninstalling." ) + # A root the partial walk already reached is still needed: reaching + # it is proof. Unreached roots go as before, and every descendant + # candidate is kept because the walk cannot prove it unused. + rescued_roots = candidate_roots & walk.reachable + repairs = _rescue_repairs(walk, rescued_roots) return OrphanRemovalDecision( operation=operation, candidate_keys=candidate_orphans, retained_keys=candidate_orphans, - reachability=walk, + rescued_roots=rescued_roots, + repairs=MappingProxyType(repairs), + rescued_depths=MappingProxyType(_rescued_root_depths(lockfile, rescued_roots, repairs)), + reachability=walk if candidate_orphans else None, ) rescued = candidate_orphans & walk.reachable rescued_roots = candidate_roots & walk.reachable - repairs = { - key: (*walk.reachable_via[key], key in walk.dev_only) - for key in rescued | rescued_roots - if key in walk.reachable_via - } + repairs = _rescue_repairs(walk, rescued | rescued_roots) return OrphanRemovalDecision( operation=operation, candidate_keys=candidate_orphans, @@ -623,10 +627,52 @@ def _decide_uninstall( rescued_keys=rescued, rescued_roots=rescued_roots, repairs=MappingProxyType(repairs), + rescued_depths=MappingProxyType(_rescued_root_depths(lockfile, rescued_roots, repairs)), reachability=walk, ) +def _rescue_repairs(walk, keys: frozenset[str]) -> dict: + """Map each rescued key to the surviving parent that reached it.""" + return { + key: (*walk.reachable_via[key], key in walk.dev_only) + for key in keys + if key in walk.reachable_via + } + + +def _rescued_root_depths( + lockfile: LockFile, rescued_roots: frozenset[str], repairs: Mapping +) -> dict[str, int]: + """Depth each re-parented root and its locked subtree take (#4749). + + A rescued root is no longer direct. As install records it, its depth is + its new parent's depth plus one, and each entry recorded under it follows. + """ + replacements = lockfile.replacements + dependencies = lockfile.get_package_dependencies() + by_identity = {lockfile_parent_identity(dep, replacements): dep for dep in dependencies} + children = _build_children_index(lockfile) + depths: dict[str, int] = {} + queue = [] + for key in sorted(rescued_roots): + dep = lockfile.get_dependency(key) + if dep is None or key not in repairs: + continue + parent = by_identity.get(repairs[key][0]) + depths[key] = max(parent.depth if parent is not None else 1, 1) + 1 + queue.append(dep) + while queue: + dep = queue.pop() + depth = depths[dep.get_unique_key()] + 1 + for child in children.get(lockfile_parent_identity(dep, replacements), ()): + child_key = child.get_unique_key() + if child_key not in depths: + depths[child_key] = depth + queue.append(child) + return depths + + def _locked_root_keys(lockfile: LockFile, roots: Sequence[object]) -> frozenset[str]: """Lock keys of the removal roots that hold a package row.""" keys: set[str] = set() diff --git a/tests/integration/test_skill_selection_merge_lifecycle.py b/tests/integration/test_skill_selection_merge_lifecycle.py index 02804af54a..7f8e9786f7 100644 --- a/tests/integration/test_skill_selection_merge_lifecycle.py +++ b/tests/integration/test_skill_selection_merge_lifecycle.py @@ -330,6 +330,34 @@ def test_uninstalling_one_diamond_parent_shrinks_to_the_survivor_selection_then_ assert locked(project, bundle) is None +def test_uninstalling_a_direct_dependency_a_parent_still_selects_shrinks_to_that_edge( + tmp_path: Path, apm_binary_path: Path +) -> None: + """#4749: the direct edge leaves the union; the bundle stays with pkg-a's skills.""" + world = _world(tmp_path, apm_binary_path) + bundle = world.publish("bundle", skills=_SKILLS).slug + a = world.publish("pkg-a", dependencies=[_edge(bundle, skills=["alpha"])]).slug + project = world.project("consumer", dependencies=[a, bundle]) + skills_root = project / _PROJECT_SKILLS + with world.serve() as env: + world.run(INSTALL, cwd=project, env=env, scenario_id="4749-install") + assert skill_dirs(skills_root) == sorted(_SKILLS) + assert locked(project, bundle).get("depth", 1) == 1 + + world.run(("uninstall", bundle), cwd=project, env=env, scenario_id="4749-uninstall") + assert skill_dirs(skills_root) == ["alpha"] + entry = locked(project, bundle) + assert entry["skill_subset"] == ["alpha"] + assert entry["depth"] == 2 + recorded = deployment_values(project) + for gone in ("beta", "gamma", "delta"): + assert not any(f"/skills/{gone}" in value for value in recorded), recorded + _assert_audit_green(world, project, env, "4749-audit") + lock_after = lock_path(project).read_bytes() + world.run((*INSTALL, "--frozen"), cwd=project, env=env, scenario_id="4749-frozen") + assert lock_path(project).read_bytes() == lock_after + + def _tree_bytes(*roots: Path) -> dict[str, bytes]: found: dict[str, bytes] = {} for root in roots: diff --git a/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py b/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py index a57316d02d..0156de80a2 100644 --- a/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py +++ b/tests/integration/test_uninstall_shared_direct_dependency_lifecycle.py @@ -112,6 +112,9 @@ def test_uninstall_keeps_a_direct_dependency_another_package_still_needs( # e stays locked, now attributed to the package that still needs it. assert set(after) == {"test/d", "test/e", "test/f"} assert after["test/e"]["resolved_by"] == "test/d" + # No longer direct: one level below its new parent, as install records it. + assert before["test/e"].get("depth", 1) == 1 + assert after["test/e"]["depth"] == 2 assert after["test/e"]["resolved_commit"] == before["test/e"]["resolved_commit"] assert set(after["test/e"].get("deployed_files") or []) == e_files assert (world.project / "apm_modules" / "test" / "e" / "apm.yml").is_file() @@ -130,6 +133,9 @@ def test_uninstall_keeps_a_direct_dependency_another_package_still_needs( world.apm("audit", "--ci") assert lock_bytes(world.project) == lock_after assert tree_digest(world.project) == tree_after + # I2: a full install re-resolves the graph and writes the same lockfile. + world.apm("install") + assert lock_bytes(world.project) == lock_after def test_uninstall_still_removes_a_dependency_nothing_else_needs( From 6bfd87da7f865104ddb2a4582f4f69eb4337d514 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 20:47:06 +0100 Subject: [PATCH 5/6] fix(uninstall): declaration-only removal keeps the evidence refusal and drops the replacement root request Review follow-ups on #4765 (blocking under the time-box): - The deletion-evidence refusal no longer returns early when only a survivor-selection shrink retires files, so an edited skill the shrink would remove still refuses before apm.yml changes. - A still-needed replacement-backed row drops the removed declaration's root request through the replacement owner, keeping requests from surviving parents. Red-first lifecycle cells for both. Metadata follow-ups: #4804. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/commands/uninstall/cli.py | 5 +- src/apm_cli/models/dependency/replacement.py | 17 +++++-- .../test_dependency_replacement_lifecycle.py | 46 +++++++++++++++++++ .../test_skill_selection_merge_lifecycle.py | 29 ++++++++++++ 4 files changed, 91 insertions(+), 6 deletions(-) diff --git a/src/apm_cli/commands/uninstall/cli.py b/src/apm_cli/commands/uninstall/cli.py index d716193572..2ad2aebd60 100644 --- a/src/apm_cli/commands/uninstall/cli.py +++ b/src/apm_cli/commands/uninstall/cli.py @@ -163,6 +163,9 @@ def _reparent_still_needed(lockfile, repair: _StillNeededRepair) -> bool: kept.is_dev = dev_only if local_path is not None: kept.local_path = local_path + if kept.replacement is not None: + # The removed declaration's own request goes; surviving parents' stay. + kept.replacement.drop_root_requests() updated = True for key, depth in repair.depths.items(): kept = lockfile.get_dependency(key) @@ -722,7 +725,7 @@ def _refuse_uninstall_without_evidence( from ...integration.base_integrator import BaseIntegrator from ...integration.cleanup import refusal_reason, uninstall_evidence_remedies - if not lockfile or not cleanup_keys: + if not lockfile or (not cleanup_keys and not shrunk): return # Hash-tracked skill members count too: directory cleanup deletes them. selected, selected_hashes = _collect_deployed_cleanup_state(lockfile, cleanup_keys) diff --git a/src/apm_cli/models/dependency/replacement.py b/src/apm_cli/models/dependency/replacement.py index fc4195edce..e6613c7b29 100644 --- a/src/apm_cli/models/dependency/replacement.py +++ b/src/apm_cli/models/dependency/replacement.py @@ -196,11 +196,18 @@ def to_dict(self) -> dict: def retain_parents(self, parent_keys: set[str]) -> bool: """Prune removed dependency requests without changing chosen ownership.""" - retained = { - request: None - for request in self.requests - if request.parent is None or request.parent in parent_keys - } + return self._retain(lambda parent: parent is None or parent in parent_keys) + + def drop_root_requests(self) -> bool: + """Forget the project's own requests once its declaration is gone (#4749). + + Requests from surviving parents stay, so the binding keeps the edges + that still need the selected source. + """ + return self._retain(lambda parent: parent is not None) + + def _retain(self, keep) -> bool: + retained = {request: None for request in self.requests if keep(request.parent)} if not retained: raise ReplacementConfigError( f"Replacement {self.original.get_unique_key()} has no surviving original request" diff --git a/tests/integration/test_dependency_replacement_lifecycle.py b/tests/integration/test_dependency_replacement_lifecycle.py index 813e9567d7..cbb8d82454 100644 --- a/tests/integration/test_dependency_replacement_lifecycle.py +++ b/tests/integration/test_dependency_replacement_lifecycle.py @@ -1377,3 +1377,49 @@ def test_existing_local_replacement_reloads_changed_child_manifest( entries = load_yaml(fixture.consumer.root / "apm.lock.yaml")["dependencies"] assert len(entries) == 1 assert entries[0]["repo_url"] == "apm-replacement-fixture/base" + + +def test_declaration_only_uninstall_drops_the_replacement_root_request( + tmp_path: Path, + apm_binary_path: Path, +) -> None: + """#4749: uninstalling a replaced direct dependency a parent still needs keeps + only the surviving parent's request, so the lock no longer records the + removed declaration.""" + fixture = _replacement_fixture(tmp_path, apm_binary_path) + factory = LocalPackageFactory(fixture.consumer.root.parent) + parent = factory.create("left", dependencies=({"git": _UPSTREAM, "ref": fixture.upstream_sha},)) + repository = fixture.repositories.create("left", source_tree=parent.root) + sha = fixture.repositories.commit(repository, message="Parent of base").sha + remote = "https://github.com/apm-replacement-fixture/left" + fixture.environment.update( + fixture.repositories.url_rewrite_subprocess_env_many( + ((fixture.upstream, _UPSTREAM), (fixture.fork, _FORK), (repository, remote)) + ) + ) + manifest = load_yaml(fixture.consumer.manifest_path) + manifest["dependencies"]["apm"] = [ + {"git": remote, "ref": sha}, + {"git": _UPSTREAM, "ref": fixture.upstream_sha}, + ] + dump_yaml(manifest, fixture.consumer.manifest_path) + fixture.replace({"path": "../local-base"}) + fixture.install() + + def base_entry() -> dict: + entries = load_yaml(fixture.consumer.root / "apm.lock.yaml")["dependencies"] + return next(d for d in entries if d["repo_url"] == "apm-replacement-fixture/base") + + parents = {r["parent"] for r in base_entry()["replacement"]["requests"]} + assert parents == {None, "apm-replacement-fixture/left"} + + result = fixture.run("uninstall", "apm-replacement-fixture/base") + assert result.returncode == 0, result.stdout + result.stderr + entry = base_entry() + assert entry["resolved_by"] == "apm-replacement-fixture/left" + assert [r["parent"] for r in entry["replacement"]["requests"]] == [ + "apm-replacement-fixture/left" + ] + fixture.assert_bytes("LOCAL") + frozen = fixture.run(*_INSTALL, "--frozen") + assert frozen.returncode == 0, frozen.stdout + frozen.stderr diff --git a/tests/integration/test_skill_selection_merge_lifecycle.py b/tests/integration/test_skill_selection_merge_lifecycle.py index 7f8e9786f7..d44c54d589 100644 --- a/tests/integration/test_skill_selection_merge_lifecycle.py +++ b/tests/integration/test_skill_selection_merge_lifecycle.py @@ -804,3 +804,32 @@ def test_uninstall_of_an_unrelated_local_package_keeps_a_local_bundle_skill_pin( assert skill_dirs(skills_root) == ["alpha"] world.run(("uninstall", "../local-c"), cwd=project, env=env, scenario_id="u1l-uninstall") assert skill_dirs(skills_root) == ["alpha"] + + +def test_declaration_only_uninstall_refuses_when_its_shrink_would_remove_an_edited_skill( + tmp_path: Path, apm_binary_path: Path +) -> None: + """#4749: a declaration-only removal still checks the files its shrink retires.""" + world = _world(tmp_path, apm_binary_path) + bundle = world.publish("bundle", skills=_SKILLS).slug + a = world.publish("pkg-a", dependencies=[_edge(bundle, skills=["alpha"])]).slug + project = world.project("consumer", dependencies=[a, bundle]) + skills_root = project / _PROJECT_SKILLS + with world.serve() as env: + world.run(INSTALL, cwd=project, env=env, scenario_id="4749-edit-install") + assert skill_dirs(skills_root) == sorted(_SKILLS) + edited = skills_root / "beta" / "SKILL.md" + edited.write_text(edited.read_text(encoding="utf-8") + "\nlocal edit\n", encoding="utf-8") + watched = ( + project / "apm.yml", + lock_path(project), + project / "apm_modules", + skills_root, + project / _CLAUDE_SKILLS, + ) + before = _tree_bytes(*watched) + result = world.run( + ("uninstall", bundle), cwd=project, env=env, expect=None, scenario_id="4749-edit" + ) + _assert_shrink_refused(result, edited) + assert _tree_bytes(*watched) == before From fc8d2c881a351844b1a4e8ba7444c3b4d7fef151 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Sun, 22 Nov 2026 22:04:30 +0100 Subject: [PATCH 6/6] fix(uninstall): a replaced still-needed row takes its surviving parents' selection Dropping the removed declaration's root request left replacement.original carrying that declaration's skill/target selection, so survivor reintegration redeployed skills uninstall had just removed. The replacement owner now re-derives the node selection from the retained requests, as from_dict does. The replacement lifecycle cell selects a narrower skill set on the surviving parent and asserts the extra skill stays removed (red before the fix). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/apm_cli/models/dependency/replacement.py | 33 +++++++++++++------ .../test_dependency_replacement_lifecycle.py | 21 ++++++++++-- 2 files changed, 41 insertions(+), 13 deletions(-) diff --git a/src/apm_cli/models/dependency/replacement.py b/src/apm_cli/models/dependency/replacement.py index e6613c7b29..a0b7e3f140 100644 --- a/src/apm_cli/models/dependency/replacement.py +++ b/src/apm_cli/models/dependency/replacement.py @@ -202,9 +202,29 @@ def drop_root_requests(self) -> bool: """Forget the project's own requests once its declaration is gone (#4749). Requests from surviving parents stay, so the binding keeps the edges - that still need the selected source. + that still need the selected source, and the node's selection becomes + what those edges select, as :meth:`from_dict` derives it. """ - return self._retain(lambda parent: parent is not None) + changed = self._retain(lambda parent: parent is not None) + if changed: + self._select_from_requests() + return changed + + def _select_from_requests(self) -> None: + """Give the node the merged selection of its recorded requests (#3735).""" + if len(self.requests) == 1: + (request,) = self.requests + skills, targets = request.skills, request.targets + else: + merged = merge_edge_selections( + EdgeSelection((), request.skills, request.targets) for request in self.requests + ) + skills, targets = merged.skill_subset, merged.target_subset + self.original = replace( + self.original, + skill_subset=None if skills is None else list(skills), + target_subset=None if targets is None else list(targets), + ) def _retain(self, keep) -> bool: retained = {request: None for request in self.requests if keep(request.parent)} @@ -268,14 +288,7 @@ def from_dict(cls, raw: object, original: DependencyReference) -> ReplacementBin binding.record(edge, request["parent"], request["dev"]) if len(binding.requests) > 1: # The node carries the merged selection of every incoming edge (#3735). - merged = merge_edge_selections( - EdgeSelection((), request.skills, request.targets) for request in binding.requests - ) - binding.original = replace( - binding.original, - skill_subset=None if merged.skill_subset is None else list(merged.skill_subset), - target_subset=None if merged.target_subset is None else list(merged.target_subset), - ) + binding._select_from_requests() return binding def local_source_path(self, consumer_root: Path | None = None) -> Path: diff --git a/tests/integration/test_dependency_replacement_lifecycle.py b/tests/integration/test_dependency_replacement_lifecycle.py index cbb8d82454..4efe17857c 100644 --- a/tests/integration/test_dependency_replacement_lifecycle.py +++ b/tests/integration/test_dependency_replacement_lifecycle.py @@ -1384,11 +1384,20 @@ def test_declaration_only_uninstall_drops_the_replacement_root_request( apm_binary_path: Path, ) -> None: """#4749: uninstalling a replaced direct dependency a parent still needs keeps - only the surviving parent's request, so the lock no longer records the - removed declaration.""" + only the surviving parent's request and selection, so the lock no longer + records the removed declaration and its extra skill is not redeployed.""" fixture = _replacement_fixture(tmp_path, apm_binary_path) + for skill in ("alpha", "beta"): + skill_file = fixture.local.root / ".apm" / "skills" / skill / "SKILL.md" + skill_file.parent.mkdir(parents=True) + skill_file.write_text( + f"---\nname: {skill}\ndescription: {skill} skill\n---\n# {skill}\n", encoding="utf-8" + ) factory = LocalPackageFactory(fixture.consumer.root.parent) - parent = factory.create("left", dependencies=({"git": _UPSTREAM, "ref": fixture.upstream_sha},)) + parent = factory.create( + "left", + dependencies=({"git": _UPSTREAM, "ref": fixture.upstream_sha, "skills": ["alpha"]},), + ) repository = fixture.repositories.create("left", source_tree=parent.root) sha = fixture.repositories.commit(repository, message="Parent of base").sha remote = "https://github.com/apm-replacement-fixture/left" @@ -1412,6 +1421,8 @@ def base_entry() -> dict: parents = {r["parent"] for r in base_entry()["replacement"]["requests"]} assert parents == {None, "apm-replacement-fixture/left"} + skills = fixture.consumer.root / ".agents" / "skills" + assert (skills / "beta" / "SKILL.md").is_file() result = fixture.run("uninstall", "apm-replacement-fixture/base") assert result.returncode == 0, result.stdout + result.stderr @@ -1420,6 +1431,10 @@ def base_entry() -> dict: assert [r["parent"] for r in entry["replacement"]["requests"]] == [ "apm-replacement-fixture/left" ] + # Only the surviving parent's selection stays deployed. + assert entry["skill_subset"] == ["alpha"] + assert (skills / "alpha" / "SKILL.md").is_file() + assert not (skills / "beta").exists() fixture.assert_bytes("LOCAL") frozen = fixture.run(*_INSTALL, "--frozen") assert frozen.returncode == 0, frozen.stdout + frozen.stderr