Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -199,20 +199,40 @@ def check_approval_outcome_routing(provider: FactsProvider) -> tuple[Violation,


_DISCOVER_POLICY_CALL = re.compile(r"discover_policy\(")
_CHAIN_DISCOVERY_CALL = re.compile(r"\bdiscover_policy_with_chain\(")
_AUDIT_CI_GATE_DEF = re.compile(r"^def _audit_ci_gate\(")
_TOP_LEVEL_DEF = re.compile(r"^def ")


def check_audit_policy_discovery(provider: FactsProvider) -> tuple[Violation, ...]:
"""Audit policy sources must use chain-aware discovery, not discover_policy()."""
return tuple(
_banned(
provider,
rule_id=RULE_AUDIT_POLICY_DISCOVERY,
paths=(_AUDIT_ADAPTER,),
pattern=_DISCOVER_POLICY_CALL,
message="Audit policy sources must use chain-aware discovery, not discover_policy(",
respect_exempt=True,
)
rule_id = RULE_AUDIT_POLICY_DISCOVERY
adapter, failures = _configured(provider, _AUDIT_ADAPTER, rule_id)
if failures:
return failures
findings = _banned(
provider,
rule_id=rule_id,
paths=(_AUDIT_ADAPTER,),
pattern=_DISCOVER_POLICY_CALL,
message="Audit policy sources must use chain-aware discovery, not discover_policy(",
respect_exempt=True,
)
gate_body: list[tuple[int, str]] = []
for number, text in adapter:
if gate_body and _TOP_LEVEL_DEF.search(text):
break
if gate_body or _AUDIT_CI_GATE_DEF.search(text):
gate_body.append((number, text))
if not _has_re(gate_body, _CHAIN_DISCOVERY_CALL):
findings.append(
_report(
rule_id,
_AUDIT_ADAPTER,
"_audit_ci_gate must discover policy through discover_policy_with_chain(",
)
)
return tuple(findings)


_POLICY_INHERITANCE = "src/apm_cli/policy/inheritance.py"
Expand Down
8 changes: 7 additions & 1 deletion src/apm_cli/deps/lockfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1799,7 +1799,13 @@ def write(
self.generated_at = datetime.now(UTC).isoformat()
else:
self.generated_at = None
if not unchanged and not _keeps_untranslated_mcp_stamp(self, existing):
if unchanged:
# A no-op keeps the recorded generator when this lock carries none
# (a freshly built one); an explicit stamp, such as the MCP phase
# recording that it translated pre-0.37 claims, is written.
if self.apm_version is None:
self.apm_version = existing.apm_version
elif not _keeps_untranslated_mcp_stamp(self, existing):
# The generator gate's only signal: whoever changes it owns it (#3962).
self.apm_version = installed_apm_version()
serialized = self.to_yaml()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -756,14 +756,8 @@ def _replace(old: str, new: str) -> tuple[tuple[str, str], ...]:
AUDIT_RULE,
"src/apm_cli/policy/ci_checks.py",
_replace(
" prepared_replay.modules_root\n"
" if prepared_replay is not None\n"
" else project_root / APM_MODULES_DIR,\n"
" # Consent is re-evaluated from apm.yml and org policy, never from the\n",
" prepared_replay.project_root\n"
" if prepared_replay is not None\n"
" else project_root / APM_MODULES_DIR,\n"
" # Consent is re-evaluated from apm.yml and org policy, never from the\n",
" modules_root=prepared_replay.modules_root if prepared_replay is not None else None,\n",
" modules_root=prepared_replay.project_root if prepared_replay is not None else None,\n",
),
),
CompoundMutation(
Expand All @@ -780,8 +774,8 @@ def _replace(old: str, new: str) -> tuple[tuple[str, str], ...]:
AUDIT_RULE,
"src/apm_cli/policy/ci_checks.py",
_replace(
" else project_root / APM_MODULES_DIR,\n",
' else project_root / "apm_modules",\n',
"modules_root if modules_root is not None else project_root / APM_MODULES_DIR,\n",
'modules_root if modules_root is not None else project_root / "apm_modules",\n',
),
),
CompoundMutation(
Expand Down
12 changes: 6 additions & 6 deletions tests/integration/test_architecture_semantic_rule_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ class MutationCase:
MutationCase(
rule_id="install-deployment-audit-policy-discovery",
path="src/apm_cli/commands/audit.py",
old="fetch_result = discover_policy_with_chain(\n cfg.project_root,",
new="fetch_result = discover_policy(\n cfg.project_root,",
old="lambda: discover_policy_with_chain(\n cfg.project_root,",
new="lambda: discover_policy(\n cfg.project_root,",
intent="Audit resolves policy without the chain-aware discovery entry point.",
),
MutationCase(
Expand Down Expand Up @@ -160,8 +160,8 @@ class MutationCase:
MutationCase(
rule_id="install-deployment-local-bundle-policy-preflight",
path="src/apm_cli/install/local_bundle_handler.py",
old="effective_target_source=deployment_decision.source,\n )",
new="effective_target_source=deployment_decision.source,\n cache_only=True,\n )",
old="effective_target_source=deployment_decision.source,\n",
new="effective_target_source=deployment_decision.source,\n cache_only=True,\n",
intent="Local bundle policy preflight reads a cold policy cache as no policy.",
),
MutationCase(
Expand Down Expand Up @@ -371,9 +371,9 @@ class MutationCase:
MutationCase(
rule_id="registry_delegation.lockfile_version_authority",
path="src/apm_cli/bundle/local_bundle.py",
old="from ..deps.lockfile import require_supported_lockfile_version",
old="from ..deps.lockfile import recorded_generator, require_supported_lockfile_version",
new=(
"from ..deps.lockfile import SUPPORTED_LOCKFILE_VERSIONS,"
"from ..deps.lockfile import SUPPORTED_LOCKFILE_VERSIONS, recorded_generator,"
" require_supported_lockfile_version"
),
intent="Local bundles import the supported-version vocabulary instead of the check.",
Expand Down
6 changes: 3 additions & 3 deletions tests/integration/test_commands_config_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -1094,11 +1094,11 @@ def test_publish_no_apm_dir_exits_error(self, runner: CliRunner) -> None:
class TestConfigModuleHelpers:
"""Additional unit tests for uncovered paths in ``apm_cli.config``."""

def test_get_default_client_returns_vscode(self, isolated_config: Path) -> None:
"""get_default_client() returns 'vscode' from default config."""
def test_get_default_client_returns_copilot(self, isolated_config: Path) -> None:
"""get_default_client() returns 'copilot' (vscode is its deprecated alias)."""
import apm_cli.config as _conf

assert _conf.get_default_client() == "vscode"
assert _conf.get_default_client() == "copilot"

def test_set_default_client(self, isolated_config: Path) -> None:
"""set_default_client() persists to disk."""
Expand Down
5 changes: 3 additions & 2 deletions tests/integration/test_default_port_normalisation_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ def test_lockfile_yaml_roundtrip_preserves_non_default_port(self, tmp_path):

loaded = LockFile.read(lock_path)
assert loaded is not None
# Non-default host (#773): lockfile dedup key is host-qualified.
reloaded_dep = loaded.dependencies.get("bitbucket.corp.com/team/repo")
# Non-default host (#773) and port (#3932) are both part of the identity key.
assert locked.get_unique_key() == "bitbucket.corp.com:7990/team/repo"
reloaded_dep = loaded.dependencies.get(locked.get_unique_key())
assert reloaded_dep is not None
assert reloaded_dep.port == 7990

Expand Down
5 changes: 4 additions & 1 deletion tests/integration/test_marketplace_e2e_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -673,7 +673,10 @@ def test_update_all_with_source_exception_verbose(self):
),
):
result = runner.invoke(marketplace, ["update", "--verbose"])
assert result.exit_code == 0
# A failed revalidation fails closed and names the marketplace (#3910).
assert result.exit_code == 1
assert "failed: failing-market" in result.output
assert "Traceback" in result.output


# ---------------------------------------------------------------------------
Expand Down
2 changes: 2 additions & 0 deletions tests/integration/test_marketplace_ref_install_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@ def _run_install(
patch(_PATCH_UPDATES, return_value=None),
patch(_PATCH_VALIDATE_EXISTS, return_value=True),
patch("apm_cli.marketplace.resolver.get_marketplace_by_name", return_value=source),
# The reinstall's #3959 origin check reads the same registration.
patch("apm_cli.marketplace.catalog_origin.get_marketplace_by_name", return_value=source),
patch("apm_cli.marketplace.resolver.fetch_or_cache", return_value=_manifest()),
):
return runner.invoke(
Expand Down
13 changes: 7 additions & 6 deletions tests/integration/test_wave2_adapters_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -786,16 +786,17 @@ def test_normalize_mcp_entry_non_dict_passthrough(self) -> None:
result = ClaudeClientAdapter._normalize_mcp_entry_for_claude_code("not-a-dict")
assert result == "not-a-dict"

def test_rewrite_self_defined_skill_command_converged(self) -> None:
def test_rewrite_self_defined_skill_command_converged(self, tmp_path: Path) -> None:
"""Converged skill prefix is rewritten to Claude-specific path."""
result = ClaudeClientAdapter._rewrite_self_defined_skill_command(
".agents/skills/my-skill/run.sh"
)
(tmp_path / ".claude" / "skills" / "my-skill").mkdir(parents=True)
adapter = ClaudeClientAdapter(project_root=tmp_path)
result = adapter._rewrite_self_defined_skill_command(".agents/skills/my-skill/run.sh")
assert result == ".claude/skills/my-skill/run.sh"

def test_rewrite_self_defined_skill_command_other(self) -> None:
def test_rewrite_self_defined_skill_command_other(self, tmp_path: Path) -> None:
"""Non-converged commands pass through unchanged."""
result = ClaudeClientAdapter._rewrite_self_defined_skill_command("npx")
adapter = ClaudeClientAdapter(project_root=tmp_path)
result = adapter._rewrite_self_defined_skill_command("npx")
assert result == "npx"

def test_merge_mcp_server_dicts_shallow_merge(self) -> None:
Expand Down
10 changes: 6 additions & 4 deletions tests/integration/test_wave7_marketplace_install_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ def test_update_no_marketplaces_registered(self, runner: CliRunner, tmp_path: Pa
assert "No marketplaces" in result.output or "registered" in result.output

def test_update_partial_failure(self, runner: CliRunner, tmp_path: Path) -> None:
"""One marketplace failing during update doesn't abort the whole run."""
"""One failing marketplace does not stop the others, but the run exits 1."""
sources = [_fake_source("good"), _fake_source("bad")]
good_manifest = _fake_manifest("good")

Expand All @@ -443,9 +443,11 @@ def _fetch_side_effect(source, **_kwargs):
),
):
result = runner.invoke(cli, ["marketplace", "update"])
# Should complete (exit 0) but warn about the bad marketplace
assert result.exit_code == 0
assert "bad" in result.output or "network" in result.output
# The good catalog still refreshes; the failure is named and fails closed (#3910).
assert result.exit_code == 1
assert "good (" in result.output
assert "bad: network error" in result.output
assert "Refreshed 1 of 2 marketplace(s); failed: bad" in result.output


# ===========================================================================
Expand Down
18 changes: 18 additions & 0 deletions tests/unit/deps/test_lockfile_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,3 +317,21 @@ def test_packed_bundle_lock_names_the_packer(tmp_path, stamping):
enriched = yaml.safe_load(enrich_lockfile_for_pack(source, "plugin", "all"))
assert enriched["apm_version"] == "0.40.0"
assert source.apm_version == "0.35.0"


def test_noop_write_from_a_fresh_lock_keeps_the_recorded_stamp(tmp_path, stamping):
"""A rebuilt but unchanged lock keeps its bytes and generator, never dropping the stamp."""
path = _older_lock(tmp_path, LockFile(apm_version="0.1.0", mcp_servers=["same"]))
before = path.read_bytes()
LockFile(mcp_servers=["same"]).write(path)
assert path.read_bytes() == before
assert stamping(path) == "0.1.0"


def test_noop_write_records_an_explicit_stamp(tmp_path, stamping):
"""A caller that stamps a semantically unchanged lock (the MCP translation) is written."""
path = _older_lock(tmp_path, LockFile(apm_version="0.35.0", mcp_servers=["same"]))
lock = LockFile.read(path)
lock.apm_version = "0.40.0"
lock.write(path, existing_lockfile=LockFile.read(path))
assert stamping(path) == "0.40.0"