Skip to content
Merged
1 change: 0 additions & 1 deletion changelog.d/4576.changed.md

This file was deleted.

1 change: 1 addition & 0 deletions changelog.d/5456.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `apm install` no longer adopts a stray `~/apm.yml` from a parent folder; subdirectory project-root discovery is reverted. (closes #5448, #5456)
12 changes: 0 additions & 12 deletions docs/src/content/docs/consumer/install-packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,6 @@ You can also edit the manifest and run a bare `apm install`:
+ - contoso/review-skills#v1.1.0
```

### Working from subdirectories

Running `apm install` from a subdirectory of a project automatically discovers
the nearest ancestor `apm.yml`. Sources, lockfiles, and deployed harness files
anchor to that project root, leaving the subdirectory clean:

```bash frame="terminal"
cd src/components
apm install contoso/review-skills#v1.1.0
# [i] Using apm.yml at /path/to/project/apm.yml (project root: /path/to/project)
```

## Reference formats

`apm install` and `dependencies.apm` accept these forms:
Expand Down
7 changes: 0 additions & 7 deletions docs/src/content/docs/reference/cli/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,6 @@ hash portability is not guaranteed.
|---|---|---|
| `--root DIR` | `$PWD` | Redirect every write -- `apm_modules/`, `apm.lock.yaml`, `.gitignore`, and integrated harness files -- under `DIR`, while `apm.yml`, `.apm/`, and local-path dependencies still resolve from the current working directory. Mirrors `pip install --target` / `npm install --prefix`. `DIR` is created if missing (except under `--dry-run`, which refuses to create it); an install that fails removes the directories it created if they are still empty. Not valid with `--global` (user scope), which exits `2`. |

When run from a subdirectory of a project without an `apm.yml`, project-scope
`apm install` (including `--dry-run` and positional packages) discovers the
nearest ancestor `apm.yml`. Sources, deploy paths, `apm_modules/`,
`apm.lock.yaml`, and target provenance anchor to that project root, restoring the
working directory on exit. Passing `--root DIR` keeps sources resolving from the
working directory without discovery.

`apm install --root DIR --frozen` checks `DIR/apm.lock.yaml` against the
source manifest. A source-side lockfile is not a substitute for a missing or
stale deployment lock. To create or repair it, rerun the same install command
Expand Down
107 changes: 2 additions & 105 deletions src/apm_cli/commands/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@
"""

import builtins
import contextlib
import functools
import os
import sys
from collections.abc import Iterable, Iterator
from collections.abc import Iterable
from pathlib import Path

import click
Expand Down Expand Up @@ -554,7 +553,7 @@ def _find_apm_yml(start: Path | None = None) -> Path | None:
discoverable from ``start`` upward.

An ancestor ``apm.yml`` another user owns is never adopted (git's
``safe.directory`` class, #4545): ``/tmp/work`` must not run another
``safe.directory`` class): ``/tmp/work`` must not run another
user's ``/tmp/apm.yml``. It is skipped with a warning naming it, and the
walk continues. Windows ownership (SIDs) is not checked.
"""
Expand Down Expand Up @@ -583,108 +582,6 @@ def _find_apm_yml(start: Path | None = None) -> Path | None:
return None


def resolve_cli_packages_for_project_root(
packages: tuple[str, ...],
invoking_dir: Path,
project_root: Path,
) -> tuple[str, ...]:
"""Resolve relative CLI package paths from invoking_dir relative to project_root (#4545)."""
invoking, root = invoking_dir.resolve(), project_root.resolve()
if invoking == root:
return packages
resolved: list[str] = []
for pkg in packages:
# Only an explicit relative path names the invoking directory; a bare
# name (``foo``, ``name@market``) never depends on what the subdir holds.
if not pkg.startswith(("./", "../", ".\\", "..\\")):
resolved.append(pkg)
continue
resolved.append(_rebase_relative_package(pkg, invoking, root))
return tuple(resolved)


def _rebase_relative_package(pkg: str, invoking: Path, root: Path) -> str:
"""Rebase an explicit relative *pkg* from *invoking* onto *root* (#4545).

Only the parent is resolved, so an intermediate symlink followed by
``..`` lands where the filesystem does; the final component is kept as
written, so install still refuses a selected symlink. ``.`` components
are dropped first, so ``./link/.`` cannot hide the link either. Across
Windows drives no relative path exists, so the absolute path is kept.
"""
from ..models.dependency.identity import normalise_local_path_separators

parts = [
part for part in normalise_local_path_separators(pkg).split("/") if part not in ("", ".")
]
if not parts or parts[-1] == "..":
target = os.path.realpath(os.path.join(invoking, *parts))
else:
target = os.path.join(os.path.realpath(os.path.join(invoking, *parts[:-1])), parts[-1])
try:
rel = os.path.relpath(target, root).replace("\\", "/")
except ValueError:
return Path(target).as_posix()
if rel == ".":
return "./"
if rel != ".." and not rel.startswith(("./", "../")):
return f"./{rel}"
return rel


@contextlib.contextmanager
def discover_project_root(
packages: tuple[str, ...] = (),
*,
enabled: bool = True,
) -> Iterator[tuple[Path | None, tuple[str, ...]]]:
"""Discover nearest ancestor apm.yml for project-scope install (#4545).

When *enabled*, walks parent directories from cwd looking for ``apm.yml``.
If cwd has no ``apm.yml`` and an ancestor does, prints the discovery notice,
resolves relative CLI package paths from the invoking directory against the
discovered project root, anchors sources and deploy paths by changing working
directory to that project root, and restores the original working directory on exit.
"""
if not enabled:
yield None, packages
return

manifest_path = _find_apm_yml()
if manifest_path is None:
yield None, packages
return

project_root = manifest_path.parent
original = Path.cwd()
if project_root != original.resolve():
resolved_packages = resolve_cli_packages_for_project_root(packages, original, project_root)
_rich_info(
f"Using apm.yml at {manifest_path} (project root: {project_root})",
symbol="info",
)
os.chdir(project_root)
try:
yield project_root, resolved_packages
finally:
with contextlib.suppress(OSError):
os.chdir(original)
else:
yield project_root, packages


def setup_project_root_discovery(
ctx: click.Context,
packages: tuple[str, ...],
*,
enabled: bool,
) -> tuple[str, ...]:
"""Register project root discovery with Click context if enabled (#4545)."""
if enabled:
_, packages = ctx.with_resource(discover_project_root(packages, enabled=True))
return packages


# Shared by ``apm install`` and ``apm update`` so both commands expose the same
# per-invocation consent for transitive self-defined MCP servers.
trust_transitive_mcp_option = click.option(
Expand Down
6 changes: 3 additions & 3 deletions src/apm_cli/commands/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,6 @@
_create_minimal_apm_yml,
_get_bootstrap_config,
explicit_policy_option,
setup_project_root_discovery,
trust_transitive_mcp_option,
)

Expand Down Expand Up @@ -1208,8 +1207,9 @@ def install( # noqa: PLR0913
# even if logger init itself raised.
install_started_at = time.perf_counter()
summary_rendered = False
logger = dry_run_manifest_tmp = command_result = transaction = None
packages = setup_project_root_discovery(ctx, packages, enabled=not global_ and not root)
logger = dry_run_manifest_tmp = None
command_result: InstallResult | None = None
transaction: InstallTransaction | None = None
from ..install.service import InstallService, resolve_frozen

frozen = resolve_frozen(frozen, update or refresh or packages or mcp_name, global_, root)
Expand Down
114 changes: 114 additions & 0 deletions tests/integration/test_home_manifest_discovery_lifecycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""A folder under $HOME never adopts a stray ~/apm.yml as its project (#5448).

RT-5 found subdirectory discovery (#4576) walking up to a home-directory
apm.yml, editing it and deploying into ~/.claude, a user-scope directory.
Each cell drives the installed CLI with HOME pointed at a temp home.
"""

from __future__ import annotations

import os
import subprocess
from pathlib import Path

import pytest

from apm_cli.utils.yaml_io import load_yaml

pytestmark = [
pytest.mark.integration,
pytest.mark.e2e,
pytest.mark.requires_apm_binary,
pytest.mark.promise("P-OWN-install-command-scope-selection", "P-INV-I2"),
]

# APM's own per-user state (APM home, deployment lock, deploy cache), not project data.
_APM_STATE = (".apm/", ".apm-local/", ".cache/")
_HOME_MANIFEST = "name: home\nversion: 1.0.0\ntargets: [claude]\ndependencies:\n apm: []\n"


def _home(tmp_path: Path) -> tuple[Path, dict[str, str]]:
home = tmp_path / "home"
package = home / "src" / "pkgs" / "a"
skill = package / ".apm" / "skills" / "a-skill" / "SKILL.md"
skill.parent.mkdir(parents=True)
(package / "apm.yml").write_text("name: a\nversion: 1.0.0\n", encoding="utf-8")
skill.write_text("---\nname: a-skill\ndescription: a\n---\n# a\n", encoding="utf-8")
(home / "apm.yml").write_text(_HOME_MANIFEST, encoding="utf-8")
env = {
key: value
for key, value in os.environ.items()
if key not in {"APM_HOME", "CLAUDE_CONFIG_DIR", "XDG_CONFIG_HOME"}
}
env.update({"HOME": str(home), "USERPROFILE": str(home), "NO_COLOR": "1"})
return home, env


def _tree(root: Path, *, skip: tuple[str, ...] = ()) -> dict[str, bytes]:
return {
path.relative_to(root).as_posix(): path.read_bytes()
for path in sorted(root.rglob("*"))
if path.is_file() and not path.relative_to(root).as_posix().startswith(skip)
}


def _apm(binary: Path, cwd: Path, env: dict[str, str], *args: str) -> subprocess.CompletedProcess:
return subprocess.run(
[str(binary), *args, "--no-policy"],
cwd=cwd,
env=env,
capture_output=True,
text=True,
check=False,
)


def test_a_package_install_in_a_new_folder_stays_in_that_folder(
tmp_path: Path, apm_binary_path: Path
) -> None:
home, env = _home(tmp_path)
project = home / "work" / "newproj"
(project / ".claude").mkdir(parents=True)
before = _tree(home, skip=("work/", *_APM_STATE))

result = _apm(apm_binary_path, project, env, "install", "../../src/pkgs/a")

assert result.returncode == 0, result.stdout + result.stderr
assert "../../src/pkgs/a" in str(load_yaml(project / "apm.yml")["dependencies"]["apm"])
assert (project / ".claude" / "skills" / "a-skill" / "SKILL.md").is_file()
assert _tree(home, skip=("work/", *_APM_STATE)) == before
assert not (home / ".claude").exists()


def test_a_bare_install_in_an_empty_folder_writes_nothing(
tmp_path: Path, apm_binary_path: Path
) -> None:
home, env = _home(tmp_path)
fresh = home / "work" / "fresh"
fresh.mkdir(parents=True)
before = _tree(home, skip=_APM_STATE)

result = _apm(apm_binary_path, fresh, env, "install")

assert result.returncode == 1, result.stdout + result.stderr
assert "No apm.yml found" in result.stdout + result.stderr
assert _tree(home, skip=_APM_STATE) == before
assert not (home / ".claude").exists()


def test_a_project_install_after_a_user_install_never_writes_the_home_lock(
tmp_path: Path, apm_binary_path: Path
) -> None:
home, env = _home(tmp_path)
package = home / "src" / "pkgs" / "a"
user = _apm(apm_binary_path, home, env, "install", "-g", str(package))
assert user.returncode == 0, user.stdout + user.stderr
project = home / "work" / "proj"
(project / ".claude").mkdir(parents=True)

result = _apm(apm_binary_path, project, env, "install", "../../src/pkgs/a")

assert result.returncode == 0, result.stdout + result.stderr
assert not (home / "apm.lock.yaml").exists()
assert (home / "apm.yml").read_text(encoding="utf-8") == _HOME_MANIFEST
assert (project / "apm.lock.yaml").is_file()
Loading
Loading