Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/apm_cli/runtime/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"""

import logging
import os
import shutil
import subprocess
import sys
Expand All @@ -16,6 +15,7 @@

from ..core.tls_trust import build_child_tls_env, ensure_child_tls_bootstrap
from ..core.token_manager import setup_runtime_environment
from ..utils.subprocess_env import external_process_env
from .registry import get_runtime_descriptor, runtime_descriptors

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -165,7 +165,9 @@ def run_embedded_script(
cmd = ["bash", str(main_script)] + script_args # noqa: RUF005

# Prepare environment with GitHub tokens for all authentication needs
env = os.environ.copy()
# Restore the caller's loader paths so a frozen binary's bundled
# libraries never leak into the setup script's python3/node children.
env = external_process_env()

# Set up comprehensive GitHub token environment for all runtimes
# New token precedence:
Expand Down Expand Up @@ -320,7 +322,12 @@ def list_runtimes(self) -> dict[str, dict[str, str]]:
try:
version_cmd = [binary_name, "--version"]
result = subprocess.run(
version_cmd, capture_output=True, text=True, encoding="utf-8", timeout=5
version_cmd,
capture_output=True,
text=True,
encoding="utf-8",
timeout=5,
env=external_process_env(),
)
if result.returncode == 0:
runtime_status["version"] = result.stdout.strip()
Expand Down Expand Up @@ -360,6 +367,7 @@ def remove_runtime(self, runtime_name: str) -> bool:
capture_output=True,
text=True,
encoding="utf-8",
env=external_process_env(),
)
if result.returncode == 0:
click.echo(
Expand Down
8 changes: 8 additions & 0 deletions tests/integration/test_architecture_owner_rule_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,14 @@ class MutationCase:
new='DEFAULT_BOOTSTRAP_PROJECT_NAME = "my-app"',
intent="Bootstrap project-name owner drifts off its pinned fallback value.",
),
MutationCase(
guard_id="registry-delegation-build-id-verification",
rule_id="registry_delegation.build_id_verification",
path="src/apm_cli/compilation/build_id.py",
old="def has_valid_build_id(content: str) -> bool:",
new="def _has_valid_build_id_removed(content: str) -> bool:",
intent="The Build ID owner loses its canonical verification entry point.",
),
MutationCase(
guard_id="registry-delegation-compiled-output-writes",
rule_id="registry_delegation.compiled_output_writes",
Expand Down
10 changes: 8 additions & 2 deletions tests/integration/test_audit_primitive_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,9 +705,15 @@ def test_preserved_nested_command_layout_is_visible_non_prompt(
payload = json.dumps({"version": 1, "hooks": {"PreToolUse": [entry]}})
path.write_text(payload, encoding="utf-8")
result = scan_project_result(project, targets=(profile,))
assert result.incomplete == ()
if target == "cursor" and nested:
# Cursor hooks are native v1 flat handlers; nested layouts are reported, not scanned.
assert [entry.diagnostic for entry in result.incomplete] == [
"native hook event requires flat handlers"
]
else:
assert result.incomplete == ()
assert [entry.status for entry in result.inventory] == ["not-applicable"]
assert result.findings_by_file == {}
assert [entry.status for entry in result.inventory] == ["not-applicable"]
assert path.read_text() == payload
assert not list(project.glob("HOOK_MUST_NOT_RUN*"))

Expand Down
7 changes: 6 additions & 1 deletion tests/integration/test_frozen_host_qualified_git_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from __future__ import annotations

import dataclasses
import os
from dataclasses import dataclass
from pathlib import Path
Expand All @@ -31,6 +32,7 @@
pytestmark = [pytest.mark.component, pytest.mark.integration, pytest.mark.requires_e2e_mode]

_COMMIT = "a" * 40
_DEPLOYED_INSTRUCTION = ".github/instructions/frozen-host.instructions.md"
_TOKEN_VARS = ("GITHUB_APM_PAT", "GITHUB_TOKEN", "GH_TOKEN", "ADO_APM_PAT")


Expand Down Expand Up @@ -102,7 +104,10 @@ def _write_project(project: Path, case: _FrozenGitCase) -> None:
encoding="utf-8",
)
lockfile = LockFile()
lockfile.add_dependency(case.locked_dep)
# A frozen install never writes the lockfile, so the committed lock must
# already record everything the install deploys.
locked_dep = dataclasses.replace(case.locked_dep, deployed_files=[_DEPLOYED_INSTRUCTION])
lockfile.add_dependency(locked_dep)
lockfile.write(project / "apm.lock.yaml")


Expand Down
42 changes: 28 additions & 14 deletions tests/integration/test_hook_root_source_drift_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def _run(apm_binary_path: Path, cwd: Path, *args: str) -> subprocess.CompletedPr
"cursor",
".cursor/hooks.json",
".cursor/apm-hooks.json",
"PreToolUse",
"preToolUse",
id="cursor",
),
pytest.param(
Expand Down Expand Up @@ -116,6 +116,31 @@ def _rewrite_source(
target.write_text(json.dumps(data), encoding="utf-8")


def _user_owned_entry(target: str) -> dict:
"""Return a user-owned hook entry in the target's native handler shape."""
if target == "cursor":
# Cursor-native v1 hooks use flat handlers.
return {"type": "command", "command": "echo user-owned", "matcher": "Shell"}
return {
"matcher": "Bash",
"hooks": [{"type": "command", "command": "echo user-owned"}],
}


def _is_user_owned(entry: object) -> bool:
if not isinstance(entry, dict):
return False
if entry.get("command") == "echo user-owned":
return True
handlers = entry.get("hooks")
return (
isinstance(handlers, list)
and bool(handlers)
and isinstance(handlers[0], dict)
and handlers[0].get("command") == "echo user-owned"
)


@pytest.mark.parametrize("target, settings_rel, sidecar_rel, event_key", _HARNESS_CASES)
def test_root_hook_source_drift_heals_on_reinstall(
tmp_path: Path,
Expand Down Expand Up @@ -179,10 +204,7 @@ def test_root_hook_source_drift_heals_on_reinstall(
settings_path = project / settings_rel
settings_data = json.loads(settings_path.read_text(encoding="utf-8"))
settings_data.setdefault("hooks", {}).setdefault(event_key, []).append(
{
"matcher": "Bash",
"hooks": [{"type": "command", "command": "echo user-owned"}],
}
_user_owned_entry(target)
)
settings_path.write_text(json.dumps(settings_data), encoding="utf-8")

Expand All @@ -197,15 +219,7 @@ def test_root_hook_source_drift_heals_on_reinstall(

settings_data = json.loads(settings_path.read_text(encoding="utf-8"))
entries = settings_data.get("hooks", {}).get(event_key, [])
user_owned = [
e
for e in entries
if isinstance(e, dict)
and isinstance(e.get("hooks"), list)
and e["hooks"]
and isinstance(e["hooks"][0], dict)
and e["hooks"][0].get("command") == "echo user-owned"
]
user_owned = [e for e in entries if _is_user_owned(e)]
assert len(user_owned) == 1, (
f"User-owned hook entry must survive healing for {target}; entries={entries}"
)
Expand Down
14 changes: 11 additions & 3 deletions tests/integration/test_install_services_orchestration.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ def make_target(
target.name = name
target.root_dir = root_dir
target.primitives = primitives or {}
target.supports = lambda primitive: primitive in target.primitives
skills_mapping = target.primitives.get("skills")
if skills_mapping is not None:
target.skills_rel_root = (
f"{getattr(skills_mapping, 'deploy_root', None) or root_dir}/"
f"{getattr(skills_mapping, 'subdir', 'skills')}"
)
target.auto_create = True
target.hooks_config_display = hooks_config_display
target.resolved_deploy_root = resolved_deploy_root
Expand Down Expand Up @@ -748,9 +755,10 @@ def test_out_of_tree_skill_paths_collapse_to_cowork(self, tmp_path: Path) -> Non
tmp_path.parent / f"{tmp_path.name}-outside" / "skills" / "demo" / "SKILL.md"
).resolve()

with patch(
"apm_cli.install.services._deployed_path_entry",
return_value="cowork://skills/demo/SKILL.md",
cowork_entry = "cowork://skills/demo/SKILL.md"
with (
patch("apm_cli.install.services._deployed_path_entry", return_value=cowork_entry),
patch("apm_cli.install.deployed_paths.deployed_path_entry", return_value=cowork_entry),
):
_, _, _, logger = invoke_integrate(
tmp_path,
Expand Down
14 changes: 11 additions & 3 deletions tests/integration/test_install_services_phase3w5.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ def make_target(
target.name = name
target.root_dir = root_dir
target.primitives = primitives or {}
target.supports = lambda primitive: primitive in target.primitives
skills_mapping = target.primitives.get("skills")
if skills_mapping is not None:
target.skills_rel_root = (
f"{getattr(skills_mapping, 'deploy_root', None) or root_dir}/"
f"{getattr(skills_mapping, 'subdir', 'skills')}"
)
target.auto_create = True
target.hooks_config_display = hooks_config_display
target.resolved_deploy_root = resolved_deploy_root
Expand Down Expand Up @@ -719,9 +726,10 @@ def test_out_of_tree_skill_paths_collapse_to_cowork(self, tmp_path: Path) -> Non
tmp_path.parent / f"{tmp_path.name}-outside" / "skills" / "demo" / "SKILL.md"
).resolve()

with patch(
"apm_cli.install.services._deployed_path_entry",
return_value="cowork://skills/demo/SKILL.md",
cowork_entry = "cowork://skills/demo/SKILL.md"
with (
patch("apm_cli.install.services._deployed_path_entry", return_value=cowork_entry),
patch("apm_cli.install.deployed_paths.deployed_path_entry", return_value=cowork_entry),
):
_, _, _, logger = invoke_integrate(
tmp_path,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ def _urlopen(request: urllib.request.Request, timeout: int) -> _Response:
outcome = builder._fetch_remote_metadata_outcome(_package())

assert outcome.status == "fetched"
expected = [None] if token is None else [None, f"token {token}"]
# A hidden repository 404s anonymously for apm.yml and then for the
# manifestless SKILL.md probe before the authenticated retry succeeds.
expected = [None] if token is None else [None, None, f"token {token}"]
assert authorization == expected


Expand Down
3 changes: 2 additions & 1 deletion tests/integration/test_wave2_adapters_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,8 @@ def test_get_config_path_project_scope(self, tmp_path: Path) -> None:
def test_get_config_path_user_scope(self) -> None:
"""User-scope returns ~/.claude.json path."""
adapter = ClaudeClientAdapter(user_scope=True)
assert adapter.get_config_path() == str(Path.home() / ".claude.json")
# The adapter resolves symlinks (macOS /var -> /private/var).
assert Path(adapter.get_config_path()) == (Path.home() / ".claude.json").resolve()

def test_get_current_config_missing_file(self, tmp_path: Path) -> None:
"""Returns empty mcpServers when config file does not exist."""
Expand Down
6 changes: 0 additions & 6 deletions tests/integration/test_wave6_deps_cli_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,12 @@
name: test-project
version: 0.1.0
description: Test project
owner:
name: test-org
""")

_APM_YML_WITH_DEPS = dedent("""\
name: test-project
version: 0.1.0
description: Test project
owner:
name: test-org
dependencies:
apm:
- test-org/test-dep
Expand All @@ -55,8 +51,6 @@
name: test-project
version: 0.1.0
description: Test project
owner:
name: test-org
dependencies:
apm:
- test-org/pkg-alpha
Expand Down
6 changes: 5 additions & 1 deletion tests/unit/cache/test_git_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,11 @@ def test_receipt_precedence_with_actual_stale_bare_reference(
dependency = DependencyReference.parse("owner/repo#main")
url = dependency.to_github_url()
bare = cache._db_root / cache_shard_key(url)
shutil.copytree(repository.origin, bare)
# Pushes can start background auto-maintenance in the origin; skip its
# transient lock and temp files so the snapshot copy cannot race them.
shutil.copytree(
repository.origin, bare, ignore=shutil.ignore_patterns("*.lock", "tmp_*", "gc.pid")
)
payload.write_text("current\n", encoding="ascii")
current_commit = repositories.commit(repository, message="Current observation")
assert L2BareRevParse._rev_parse(bare, "main") == old_commit.sha
Expand Down
17 changes: 11 additions & 6 deletions tests/unit/install/test_install_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
pytestmark = pytest.mark.windows_compat


# Generous upper bound: spawned interpreters start slowly on loaded CI runners,
# and a holder that times out releases the lock early.
_PROCESS_TIMEOUT_SECONDS = 120


def _hold_workspace_transaction(
manifest: str,
modules: str,
Expand All @@ -37,7 +42,7 @@ def _hold_workspace_transaction(
logger=None,
)
ready.set()
if not release.wait(10):
if not release.wait(_PROCESS_TIMEOUT_SECONDS):
raise TimeoutError("test did not release workspace transaction")
transaction.commit(InstallResult())

Expand Down Expand Up @@ -466,7 +471,7 @@ def test_workspace_lock_serializes_concurrent_processes(tmp_path: Path) -> None:
args=(str(manifest), str(modules), holder_ready, release_holder),
)
holder.start()
assert holder_ready.wait(10)
assert holder_ready.wait(_PROCESS_TIMEOUT_SECONDS)

contenders = []
contender_events = []
Expand All @@ -481,14 +486,14 @@ def test_workspace_lock_serializes_concurrent_processes(tmp_path: Path) -> None:
contenders.append(contender)
contender_events.append((attempting, acquired))

assert all(attempting.wait(10) for attempting, _ in contender_events)
assert all(attempting.wait(_PROCESS_TIMEOUT_SECONDS) for attempting, _ in contender_events)
assert not any(acquired.wait(0.2) for _, acquired in contender_events)

release_holder.set()
assert all(acquired.wait(10) for _, acquired in contender_events)
holder.join(10)
assert all(acquired.wait(_PROCESS_TIMEOUT_SECONDS) for _, acquired in contender_events)
holder.join(_PROCESS_TIMEOUT_SECONDS)
for contender in contenders:
contender.join(10)
contender.join(_PROCESS_TIMEOUT_SECONDS)

assert holder.exitcode == 0
assert all(contender.exitcode == 0 for contender in contenders)
Expand Down
25 changes: 23 additions & 2 deletions tests/unit/test_runtime_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

import shutil # noqa: F401
import subprocess # noqa: F401
import sys # noqa: F401
import sys
from pathlib import Path
from unittest.mock import MagicMock, Mock, call, patch # noqa: F401
from unittest.mock import ANY, MagicMock, Mock, call, patch # noqa: F401

import pytest
from click.testing import CliRunner
Expand All @@ -17,6 +17,26 @@
# ---------------------------------------------------------------------------


class TestFrozenLoaderEnvIsolation:
"""A frozen binary must not leak its bundled loader paths to setup children."""

@pytest.mark.skipif(sys.platform == "win32", reason="Bash setup scripts only")
def test_setup_script_restores_original_loader_paths(self, monkeypatch):
monkeypatch.setattr(sys, "frozen", True, raising=False)
monkeypatch.setenv("LD_LIBRARY_PATH", "/bundle/_internal")
monkeypatch.setenv("LD_LIBRARY_PATH_ORIG", "/usr/local/lib")
monkeypatch.setenv("DYLD_LIBRARY_PATH", "/bundle/_internal")
monkeypatch.delenv("DYLD_LIBRARY_PATH_ORIG", raising=False)
manager = RuntimeManager()
with patch("apm_cli.runtime.manager.subprocess.run") as mock_run:
mock_run.return_value = Mock(returncode=0)
assert manager.run_embedded_script("echo setup", "", [])
env = mock_run.call_args.kwargs["env"]
assert env["LD_LIBRARY_PATH"] == "/usr/local/lib"
assert "LD_LIBRARY_PATH_ORIG" not in env
assert "DYLD_LIBRARY_PATH" not in env


class TestRuntimeManagerInit:
def test_init_sets_runtime_dir(self):
manager = RuntimeManager()
Expand Down Expand Up @@ -229,6 +249,7 @@ def test_copilot_npm_success(self):
capture_output=True,
text=True,
encoding="utf-8",
env=ANY,
)

def test_copilot_npm_failure(self):
Expand Down
Loading