From 005f3694e83230f9db5942d84af867336e071aa4 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 16:44:12 +0100 Subject: [PATCH 01/10] fix(policy): judge compilation-target on the canonical target set apm audit read only the singular `target:` key, so a manifest using plural `targets:` passed compilation-target policy whatever it listed (#3732). Audit and every install seam now hand the check the EffectiveTargetDecision.canonical_targets projection, and the policy parser canonicalizes compilation.target.allow/enforce through the same owner: - plural `targets:` is judged in audit, matching the install gate; - CSV `target: "claude,copilot"` is split instead of failing as one token; - aliases compare as the profile they deploy (vscode/agents -> copilot, agy -> antigravity, intellij -> copilot) on both sides; - `target: all` is judged as its install expansion; `targets: [all]` stays omitted; `all` in an allow list means unrestricted; - inherited alias allow lists no longer intersect to "allow nothing". normalize_policy_targets is folded into EffectiveTargetDecision and a new registry-delegation-policy-target-projection guard keeps every compilation-target seam on that projection. Fixes #3732. Supersedes #3739 and reuses its plural-key tests. apm-spec-waiver: compilation-target policy evaluation is APM policy behavior; OpenAPM v0.1 does not specify it Co-authored-by: Mohammed Alkindi Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .apm/architecture/owners/core-runtime.json | 7 +- .../docs/enterprise/governance-guide.md | 4 +- .../docs/enterprise/policy-reference.md | 14 +- .../content/docs/reference/policy-schema.md | 4 +- .../.apm/skills/apm-usage/governance.md | 2 +- .../checks/registry_owner_guards.py | 114 ++++++++++ src/apm_cli/core/target_detection.py | 92 ++++---- src/apm_cli/install/local_bundle_handler.py | 11 +- src/apm_cli/install/mcp/command.py | 4 +- .../install/phases/policy_target_check.py | 26 +-- src/apm_cli/policy/install_preflight.py | 9 +- src/apm_cli/policy/parser.py | 9 +- src/apm_cli/policy/policy_checks.py | 90 +++++--- .../policy/golden/parsed-policies.json | 8 +- .../test_compilation_target_policy_e2e.py | 203 ++++++++++++++++++ .../test_architecture_owner_rule_mutations.py | 46 ++++ .../test_wave7_policy_registry_coverage.py | 20 +- tests/unit/core/test_target_detection.py | 76 +++++-- .../unit/install/test_mcp_preflight_policy.py | 2 +- .../install/test_policy_target_check_phase.py | 33 ++- tests/unit/policy/test_inheritance.py | 11 + .../test_integration_pinned_constraint.py | 2 +- tests/unit/policy/test_parser.py | 4 +- tests/unit/policy/test_policy_checks.py | 174 ++++++++++++--- .../test_run_dependency_policy_checks.py | 4 +- 25 files changed, 794 insertions(+), 175 deletions(-) create mode 100644 tests/integration/policy/test_compilation_target_policy_e2e.py diff --git a/.apm/architecture/owners/core-runtime.json b/.apm/architecture/owners/core-runtime.json index bbdebfeee6..0b27011035 100644 --- a/.apm/architecture/owners/core-runtime.json +++ b/.apm/architecture/owners/core-runtime.json @@ -10,12 +10,13 @@ }, { "id": "effective-install-target-selection", - "decision": "Effective install target selection", - "owner": "core/target_detection.py (EffectiveTargetDecision)", + "decision": "Effective target selection and its compilation-target policy projection", + "owner": "core/target_detection.py (EffectiveTargetDecision.canonical_targets, canonical_policy_target_names)", "selectors": ["src/apm_cli/core/target_detection.py"], "guards": [ "registry-delegation-install-target-selection", - "registry-delegation-audit-target-selection" + "registry-delegation-audit-target-selection", + "registry-delegation-policy-target-projection" ] }, { diff --git a/docs/src/content/docs/enterprise/governance-guide.md b/docs/src/content/docs/enterprise/governance-guide.md index 2eb91b3bd4..20ee03a816 100644 --- a/docs/src/content/docs/enterprise/governance-guide.md +++ b/docs/src/content/docs/enterprise/governance-guide.md @@ -80,7 +80,7 @@ The scope matrix below is the contract. Every row maps a security or operational | MCP server denylist | `mcp.deny` | `mcp-denylist` | Yes (direct + transitive) | Yes | | MCP transport allowlist | `mcp.transport.allow` | `mcp-transport` | Yes | Yes | | Self-defined MCP control | `mcp.self_defined` | `mcp-self-defined` | Yes | Yes | -| Compilation target allowlist | `compilation.target.allow` (with `enforce: true`) | `compilation-target` | Yes (post-targets phase) | Yes | +| Compilation target allowlist | `compilation.target.allow` / `.enforce` | `compilation-target` | Yes (post-targets phase, effective selection) | Yes (targets declared in `apm.yml`) | | Compilation strategy | `compilation.strategy.enforce` | `compilation-strategy` | `[i] audit-only` | Yes | | Source attribution | `compilation.source_attribution` | `source-attribution` | `[i] audit-only` | Yes | | Required manifest fields | `manifest.required_fields` | `required-manifest-fields` | `[i] audit-only` | Yes | @@ -308,7 +308,7 @@ When `apm install` returns exit code 0 and the effective org policy is in `enfor - Every package in `dependencies.require` is present and at the required version (with one nuance: `require_resolution: project-wins` downgrades version mismatches to warnings, by design). - Every direct MCP server matches `mcp.allow`, is not matched by `mcp.deny`, uses an allowed transport, and respects the `mcp.self_defined` rule. - Every transitive MCP server discovered from APM packages was re-checked against the same `mcp.*` rules in a second pass (unless `--trust-transitive-mcp` was passed). -- Compilation targets that would be written match `compilation.target.allow` (when `enforce: true` on that field). +- The effective target selection (`--target`, `apm.yml`, `apm config target`, or auto-detection) matches `compilation.target.allow` and `compilation.target.enforce`, compared after aliases resolve (`vscode` is `copilot`). - The fetched policy file matched any `policy.hash` pin in `apm.yml`. If the hash did not match, install failed closed regardless of `fetch_failure_default` -- hash-mismatch is unconditionally fail-closed in non-dry-run install paths. (`apm install --dry-run` logs the mismatch but does not exit non-zero -- see section 14 gap.) - The lockfile (`apm.lock.yaml`) was regenerated from the resolved, gated set. - Any cached policy used was current within the effective `cache.ttl` (default `3600` seconds), or -- if a refresh failed -- was within the 7-day stale ceiling (`MAX_STALE_TTL`) and a warning was logged naming the cache age. diff --git a/docs/src/content/docs/enterprise/policy-reference.md b/docs/src/content/docs/enterprise/policy-reference.md index fbb6ad74e0..5ab90e9ae3 100644 --- a/docs/src/content/docs/enterprise/policy-reference.md +++ b/docs/src/content/docs/enterprise/policy-reference.md @@ -254,10 +254,18 @@ Whether to trust MCP servers declared by transitive dependencies. Default: `fals ### `target.allow` / `target.enforce` -Control which compilation targets are permitted. With multi-target support, these policies apply to every item in the target list: +Control which compilation targets are permitted. These policies apply to every target in the selection: -- **`enforce`**: The enforced target must be present in the target list. Fails if missing (e.g., `enforce: copilot` requires `copilot` to appear in `target: [claude, copilot]`). -- **`allow`**: Every target in the list must be in the allowed set. Rejects any target not listed. +- **`enforce`**: The enforced target must be present in the target list. Fails if missing (e.g., `enforce: copilot` requires `copilot` to appear in `targets: [claude, copilot]`). +- **`allow`**: Every target in the list must be in the allowed set. Rejects any target not listed. `all` in the list allows every target. + +Both sides are compared as the target each spelling deploys: + +- `targets:`, `target:`, CSV (`target: "claude,copilot"`), and list forms are the same declaration. +- Aliases resolve before comparison: `vscode` and `agents` are `copilot`, `agy` is `antigravity`, and `intellij` (MCP-only) is judged as `copilot`. +- `target: all` is judged as every target it installs. `targets: [all]` is treated as omitted, so it has nothing to judge. + +`apm install` judges its effective target selection (`--target`, then `apm.yml`, then `apm config target`, then auto-detection). `apm audit` judges the targets `apm.yml` declares; a manifest without a target declaration passes this check. ```yaml compilation: diff --git a/docs/src/content/docs/reference/policy-schema.md b/docs/src/content/docs/reference/policy-schema.md index cc7a58710f..7cb3b6603e 100644 --- a/docs/src/content/docs/reference/policy-schema.md +++ b/docs/src/content/docs/reference/policy-schema.md @@ -166,8 +166,8 @@ Rules over MCP server references, including transitive ones declared by deep dep | Field | Type | Default | Notes | |------------------------|-----------------------|---------|--------------------------------------------------------------------------------| -| `target.allow` | list or null | `null` | Allowed `apm compile` targets, e.g. `vscode`, `claude`, `all`. | -| `target.enforce` | string or null | `null` | If set, `apm compile` must select this target. | +| `target.allow` | list or null | `null` | Allowed targets, e.g. `copilot`, `claude`. Aliases resolve (`vscode` is `copilot`); `all` allows every target. | +| `target.enforce` | string or null | `null` | If set, the target selection must include this target. | | `strategy.enforce` | enum or null | `null` | `distributed` / `single-file`. Pins the compilation strategy. | | `source_attribution` | boolean | `false` | Require source-attribution headers in compiled outputs. | diff --git a/packages/apm-guide/.apm/skills/apm-usage/governance.md b/packages/apm-guide/.apm/skills/apm-usage/governance.md index 62eecd5cb1..5f433f70e2 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/governance.md +++ b/packages/apm-guide/.apm/skills/apm-usage/governance.md @@ -503,7 +503,7 @@ relax an ancestor that requires an explicit `includes:` list. - **Dependencies:** allow, deny, require (presence + optional version pin), max_depth - **MCP:** allow, deny, transport.allow, self_defined, trust_transitive -- **Compilation:** target.allow / target.enforce (target-aware) +- **Compilation:** target.allow / target.enforce (target-aware). `target:`, `targets:`, and CSV forms are one declaration; aliases resolve before comparison (`vscode`/`agents` are `copilot`); `all` in `allow` allows everything. Install judges its effective selection; audit judges the targets `apm.yml` declares. - **Manifest:** required_fields, scripts, content_types.allow - **Unmanaged files:** action against configured directories diff --git a/scripts/architecture_linter/checks/registry_owner_guards.py b/scripts/architecture_linter/checks/registry_owner_guards.py index 464ebcc50e..bb12e92189 100644 --- a/scripts/architecture_linter/checks/registry_owner_guards.py +++ b/scripts/architecture_linter/checks/registry_owner_guards.py @@ -14,6 +14,8 @@ use canonical_targets" registry-delegation-install-target- AC1 "Package, MCP, and LSP phases selection must share EffectiveTargetDecision" +registry-delegation-policy-target- Compilation-target policy judges +projection EffectiveTargetDecision.canonical_targets registry-delegation-output-diagnostics AC12 doctor-status STATUS_SYMBOLS owner check registry-delegation-compiled-output- AC2 "Compiled output writes must use @@ -294,6 +296,109 @@ def _check_target_vocabulary(provider: FactsProvider) -> Iterable[Violation]: ) +_POLICY_TARGET_SEAMS: frozenset[str] = frozenset( + {"run_dependency_policy_checks", "run_policy_preflight"} +) +_POLICY_TARGET_CHECK = "_check_compilation_target" +_POLICY_TARGET_SEAM_PARAMETER = "effective_target" + + +def _call_name(node: ast.Call) -> str | None: + func = node.func + if isinstance(func, ast.Name): + return func.id + if isinstance(func, ast.Attribute): + return func.attr + return None + + +def _is_canonical_targets(node: ast.AST | None) -> bool: + return isinstance(node, ast.Attribute) and node.attr == "canonical_targets" + + +def _check_policy_target_projection(provider: FactsProvider) -> Iterable[Violation]: + """Compilation-target policy judges only the canonical decision projection. + + Every target selection handed to the policy seams must be an + ``EffectiveTargetDecision.canonical_targets`` expression, the check itself + must never read the raw manifest, and no sibling normalizer may exist. + """ + rule_id = "registry_delegation.policy_target_projection" + findings: list[Violation] = [] + for path in _python_paths(provider, under=_SRC): + _facts, read_failures = checked_facts(provider, path, rule_id, require_python=True) + if read_failures: + findings.extend(read_failures) + continue + index = provider.tree_index(path) + if index is None: + continue + for node in index.nodes: + line = getattr(node, "lineno", 1) + if isinstance(node, FUNCTION_NODES) and node.name == "normalize_policy_targets": + findings.append( + violation( + rule_id, + path, + "policy target normalization belongs to " + "EffectiveTargetDecision.canonical_targets", + line=line, + ) + ) + elif isinstance(node, FUNCTION_NODES) and node.name == _POLICY_TARGET_CHECK: + first = node.args.args[0].arg if node.args.args else None + if first != "targets": + findings.append( + violation( + rule_id, + path, + f"{_POLICY_TARGET_CHECK} must take canonical targets, not {first}", + line=line, + ) + ) + if not isinstance(node, ast.Call): + continue + name = _call_name(node) + anchor = index.definition_anchor(node) + # A seam may forward its own already-projected parameter. + passthrough = isinstance(anchor, FUNCTION_NODES) and anchor.name in _POLICY_TARGET_SEAMS + if name in _POLICY_TARGET_SEAMS: + for keyword in node.keywords: + if keyword.arg != _POLICY_TARGET_SEAM_PARAMETER: + continue + value = keyword.value + if isinstance(value, ast.Constant) and value.value is None: + continue + if passthrough and _is_name(value, _POLICY_TARGET_SEAM_PARAMETER): + continue + if not _is_canonical_targets(value): + findings.append( + violation( + rule_id, + path, + f"{name} effective_target must be an " + "EffectiveTargetDecision.canonical_targets projection", + line=line, + ) + ) + elif name == _POLICY_TARGET_CHECK: + first_arg = node.args[0] if node.args else None + if not ( + _is_canonical_targets(first_arg) + or (passthrough and _is_name(first_arg, _POLICY_TARGET_SEAM_PARAMETER)) + ): + findings.append( + violation( + rule_id, + path, + f"{_POLICY_TARGET_CHECK} must receive " + "EffectiveTargetDecision.canonical_targets", + line=line, + ) + ) + return findings + + def _check_audit_target_selection(provider: FactsProvider) -> Iterable[Violation]: """Audit consumers must share target intent and recorded identity owners.""" rule_id = "registry_delegation.audit_target_selection" @@ -1125,6 +1230,15 @@ def _check_version_rendering(provider: FactsProvider) -> Iterable[Violation]: description="Manifest target consumers must use core/target_catalog canonical targets.", check=_check_target_vocabulary, ), + Rule( + id="registry_delegation.policy_target_projection", + group=GROUP, + guard_ids=("registry-delegation-policy-target-projection",), + description=( + "Compilation-target policy judges EffectiveTargetDecision.canonical_targets only." + ), + check=_check_policy_target_projection, + ), Rule( id="registry_delegation.install_target_selection", group=GROUP, diff --git a/src/apm_cli/core/target_detection.py b/src/apm_cli/core/target_detection.py index eb1a1183f6..b4c89fe01e 100644 --- a/src/apm_cli/core/target_detection.py +++ b/src/apm_cli/core/target_detection.py @@ -22,7 +22,7 @@ """ import warnings -from collections.abc import Iterator +from collections.abc import Iterable, Iterator from functools import cached_property from pathlib import Path from typing import Literal, Union @@ -551,36 +551,6 @@ def normalize_target_list( return result -def normalize_policy_targets(value: str | list[str] | None) -> str | list[str] | None: - """Normalize MCP-only selectors for compilation-target policy checks. - - The return shape matches the input shape so scalar callers remain - backward-compatible while plural target sets are evaluated together. - """ - if value is None: - return None - - values = [value] if isinstance(value, str) else list(value) - normalized: list[str] = [] - for target in values: - if target == "all": - if target not in normalized: - normalized.append(target) - continue - if target in MCP_ONLY_TARGETS: - try: - canonical = get_target_capability(target).primitive_profile - except KeyError: - canonical = None - if canonical is None: - raise RuntimeError(f"MCP-only target '{target}' has no canonical policy mapping") - target = canonical - if target not in normalized: - normalized.append(target) - - return normalized[0] if isinstance(value, str) else normalized - - # --------------------------------------------------------------------------- # Click parameter type for --target (comma-separated multi-target support) # --------------------------------------------------------------------------- @@ -833,6 +803,60 @@ def _target_capabilities( yield target, get_target_capability(target) +def _canonical_profile(target: str, capability: TargetCapability) -> str: + """Return the native profile a target spelling selects. + + Aliases resolve to their capability name and MCP-only targets map to the + primitive profile they configure; an MCP-only target without one fails + closed instead of escaping policy under its own name. + """ + if not capability.mcp_only: + return normalize_target_name(target) + if capability.primitive_profile is None: + raise RuntimeError(f"MCP-only target '{target}' has no canonical policy mapping") + return capability.primitive_profile + + +def canonical_policy_target_names( + values: str | Iterable[str] | None, +) -> tuple[str, ...] | None: + """Canonicalize a policy target list so it compares against decisions. + + ``all`` means unrestricted and yields ``None``. Known spellings resolve + through the same profile mapping as + :attr:`EffectiveTargetDecision.canonical_targets`; unknown spellings are kept + verbatim so they can never match a real target. + """ + if values is None: + return None + spellings = [values] if isinstance(values, str) else list(values) + names: list[str] = [] + for raw in spellings: + spelling = str(raw).strip().lower() + if not spelling: + continue + if spelling == "all": + return None + try: + name = _canonical_profile(spelling, get_target_capability(spelling)) + except KeyError: + name = spelling + if name not in names: + names.append(name) + return tuple(names) + + +def canonical_policy_target_name(value: str | None) -> str | None: + """Canonicalize one policy target (``enforce``); ``all`` stays ``all``.""" + if value is None: + return None + spelling = str(value).strip().lower() + if spelling == "all": + return spelling + names = canonical_policy_target_names(spelling) + return names[0] if names else None + + @dataclass(frozen=True) class EffectiveTargetDecision: """One install-time target decision shared by package, MCP, and LSP phases.""" @@ -849,11 +873,7 @@ def canonical_targets(self) -> tuple[str, ...] | None: canonical: list[str] = [] seen: set[str] = set() for target, capability in _target_capabilities(self.value): - name = ( - capability.primitive_profile - if capability.mcp_only and capability.primitive_profile is not None - else normalize_target_name(target) - ) + name = _canonical_profile(target, capability) if name not in seen: seen.add(name) canonical.append(name) diff --git a/src/apm_cli/install/local_bundle_handler.py b/src/apm_cli/install/local_bundle_handler.py index 66d3a5a3ff..7690d22214 100644 --- a/src/apm_cli/install/local_bundle_handler.py +++ b/src/apm_cli/install/local_bundle_handler.py @@ -61,7 +61,10 @@ def install_local_bundle( verify_bundle_integrity, ) from ..core.scope import InstallScope, get_manifest_path, get_source_root - from ..core.target_detection import resolve_manifest_target_decision + from ..core.target_detection import ( + EffectiveTargetDecision, + resolve_manifest_target_decision, + ) from ..deps.lockfile import LockFile, get_lockfile_path from ..install.services import ( enforce_agent_plugin_deployment_boundary, @@ -200,6 +203,9 @@ def install_local_bundle( ) from ..policy.install_preflight import run_policy_preflight + deployment_decision = EffectiveTargetDecision( + [resolved.name for resolved in targets], "bundle deployment targets" + ) policy_fetch, _enforcement_active = run_policy_preflight( project_root=source_root, apm_deps=(), @@ -207,7 +213,8 @@ def install_local_bundle( no_policy=no_policy, logger=logger, dry_run=dry_run, - effective_target=[resolved.name for resolved in targets], + effective_target=deployment_decision.canonical_targets, + effective_target_source=deployment_decision.source, cache_only=True, ) policy = policy_fetch.policy if policy_fetch is not None else None diff --git a/src/apm_cli/install/mcp/command.py b/src/apm_cli/install/mcp/command.py index 81680dc3fe..0e983756c7 100644 --- a/src/apm_cli/install/mcp/command.py +++ b/src/apm_cli/install/mcp/command.py @@ -59,7 +59,6 @@ def run_mcp_policy_preflight( target_decision: EffectiveTargetDecision, ) -> None: """Run policy checks for a direct MCP install before any persistent write.""" - from ...core.target_detection import normalize_policy_targets from ...models.dependency.mcp import MCPDependency from ...policy.install_preflight import PolicyBlockError, run_policy_preflight @@ -82,7 +81,8 @@ def run_mcp_policy_preflight( no_policy=no_policy, logger=logger, dry_run=logger.dry_run, - effective_target=normalize_policy_targets(target_decision.value), + effective_target=target_decision.canonical_targets, + effective_target_source=target_decision.source, ) except PolicyBlockError: logger.render_summary() diff --git a/src/apm_cli/install/phases/policy_target_check.py b/src/apm_cli/install/phases/policy_target_check.py index 17de95d33c..85342aa237 100644 --- a/src/apm_cli/install/phases/policy_target_check.py +++ b/src/apm_cli/install/phases/policy_target_check.py @@ -35,8 +35,7 @@ def run(ctx: InstallContext) -> None: decided no enforcement -- no policy, fail-open, escape-hatched, enforcement=off, etc.) - no policy was fetched (``policy_fetch is None``) - - no effective target is resolved (neither ``--target`` CLI override - nor manifest ``target:`` field) + - the shared target decision is unrestricted (nothing selected) """ # ------------------------------------------------------------------ # 1. Skip if gate phase already determined no enforcement @@ -51,25 +50,13 @@ def run(ctx: InstallContext) -> None: return # ------------------------------------------------------------------ - # 3. Resolve effective target: CLI --target wins, then manifest target - # (mirrors targets.py:38-39 logic exactly) + # 3. Judge the shared EffectiveTargetDecision (--target, apm.yml, + # apm config target, or auto-detect) through its canonical projection. # ------------------------------------------------------------------ - config_target = getattr(ctx.apm_package, "target", None) if ctx.apm_package else None - effective_target = ctx.target_override or config_target or None - - if effective_target is None: + target_decision = ctx.target_decision + if target_decision is None or target_decision.canonical_targets is None: return # no target to check -- trivially passes - # ------------------------------------------------------------------ - # 3b. Normalize scalar or plural MCP-only pseudo-targets to their - # canonical policy form (e.g. intellij -> copilot). - # ------------------------------------------------------------------ - # Keep these lazy: target_detection and integration.targets reference each - # other at runtime, so module-level imports would create an import cycle. - from apm_cli.core.target_detection import normalize_policy_targets - - effective_target = normalize_policy_targets(effective_target) - # ------------------------------------------------------------------ # 4. Run policy checks with effective_target populated # ------------------------------------------------------------------ @@ -83,7 +70,8 @@ def run(ctx: InstallContext) -> None: ctx.deps_to_install, lockfile=ctx.existing_lockfile, policy=policy, - effective_target=effective_target, + effective_target=target_decision.canonical_targets, + effective_target_source=target_decision.source, fetch_outcome=ctx.policy_fetch.outcome, fail_fast=False, # ensure target check runs even if dep checks re-pass registries=registries_map, diff --git a/src/apm_cli/policy/install_preflight.py b/src/apm_cli/policy/install_preflight.py index 005b5be83e..5bfce99067 100644 --- a/src/apm_cli/policy/install_preflight.py +++ b/src/apm_cli/policy/install_preflight.py @@ -68,7 +68,8 @@ def run_policy_preflight( logger, dry_run: bool = False, registries: dict[str, str] | None = None, - effective_target: str | list[str] | None = None, + effective_target: tuple[str, ...] | None = None, + effective_target_source: str = "effective target", cache_only: bool = False, ) -> tuple[PolicyFetchResult | None, bool]: """Discover + enforce policy for a non-pipeline command site. @@ -83,7 +84,10 @@ def run_policy_preflight( mcp_deps: Iterable of ``MCPDependency``, or ``None`` to skip MCP checks. effective_target: - Resolved scalar or plural target selection for compilation policy. + ``EffectiveTargetDecision.canonical_targets`` of the resolved target + selection, for compilation-target policy. + effective_target_source: + Where that selection came from, named in violation details. cache_only: Resolve policy from persisted cache or local-file sources without remote transport. Used by offline local-bundle installs. @@ -160,6 +164,7 @@ def run_policy_preflight( policy=policy, mcp_deps=mcp_deps, effective_target=effective_target, + effective_target_source=effective_target_source, fail_fast=(enforcement == "block"), registries=registries, direct_dep_keys={d.get_unique_key() for d in apm_deps_list}, diff --git a/src/apm_cli/policy/parser.py b/src/apm_cli/policy/parser.py index 37c2d1dd58..08faa8c7be 100644 --- a/src/apm_cli/policy/parser.py +++ b/src/apm_cli/policy/parser.py @@ -273,6 +273,11 @@ def _build_policy(data: dict) -> ApmPolicy: if not data: return ApmPolicy() + from ..core.target_detection import ( + canonical_policy_target_name, + canonical_policy_target_names, + ) + cache_data = data.get("cache") or {} cache = PolicyCache( ttl=cache_data.get("ttl", PolicyCache.ttl), @@ -313,8 +318,8 @@ def _build_policy(data: dict) -> ApmPolicy: strategy_data = comp_data.get("strategy") or {} compilation = CompilationPolicy( target=CompilationTargetPolicy( - allow=_parse_allow(target_data.get("allow")), - enforce=target_data.get("enforce"), + allow=canonical_policy_target_names(_parse_allow(target_data.get("allow"))), + enforce=canonical_policy_target_name(target_data.get("enforce")), ), strategy=CompilationStrategyPolicy( enforce=strategy_data.get("enforce"), diff --git a/src/apm_cli/policy/policy_checks.py b/src/apm_cli/policy/policy_checks.py index b4f4b2c51b..2cc373341d 100644 --- a/src/apm_cli/policy/policy_checks.py +++ b/src/apm_cli/policy/policy_checks.py @@ -537,12 +537,25 @@ def _check_mcp_self_defined( def _check_compilation_target( - raw_yml: dict | None, + targets: tuple[str, ...] | None, policy: CompilationPolicy, + *, + source: str = "apm.yml", ) -> CheckResult: - """Check 11: compilation target matches policy.""" - enforce = policy.target.enforce - allow = policy.target.allow + """Check 11: the selected target profiles match compilation-target policy. + + *targets* must be an :attr:`EffectiveTargetDecision.canonical_targets` + projection: aliases resolved, ``all`` expanded, MCP-only targets mapped to + their primitive profile. ``None`` or empty means nothing is selected. + """ + from ..core.target_detection import ( + EffectiveTargetDecision, + canonical_policy_target_name, + canonical_policy_target_names, + ) + + enforce = canonical_policy_target_name(policy.target.enforce) + allow = canonical_policy_target_names(policy.target.allow) if not enforce and allow is None: return CheckResult( @@ -551,34 +564,36 @@ def _check_compilation_target( message="No compilation target restrictions configured", ) - target = (raw_yml or {}).get("target") - if not target: + if not targets: return CheckResult( name="compilation-target", passed=True, message="No compilation target set in manifest", ) - # Normalize target to a list for uniform checking - target_list = target if isinstance(target, list) else [target] - + target_list = list(targets) if enforce: - if enforce not in target_list: + required = ( + EffectiveTargetDecision("all", "policy").canonical_targets or () + if enforce == "all" + else (enforce,) + ) + missing = [name for name in required if name not in target_list] + if missing: return CheckResult( name="compilation-target", passed=False, message=f"Enforced target '{enforce}' not present in {target_list}", - details=[f"target: {target}, enforced: {enforce}"], + details=[f"targets: {target_list} (source: {source}), enforced: {enforce}"], ) elif allow is not None: - allow_set = set(allow) if isinstance(allow, (list, tuple)) else {allow} - disallowed = [t for t in target_list if t not in allow_set] + disallowed = [name for name in target_list if name not in allow] if disallowed: return CheckResult( name="compilation-target", passed=False, - message=f"Target(s) {disallowed} not in allowed list {sorted(allow_set)}", - details=[f"target: {target}, allowed: {sorted(allow_set)}"], + message=f"Target(s) {disallowed} not in allowed list {sorted(allow)}", + details=[f"targets: {target_list} (source: {source}), allowed: {sorted(allow)}"], ) return CheckResult( @@ -1197,7 +1212,8 @@ def run_dependency_policy_checks( lockfile=None, policy: ApmPolicy, mcp_deps=None, - effective_target: str | list[str] | None = None, + effective_target: tuple[str, ...] | None = None, + effective_target_source: str = "effective target", fetch_outcome: str | None = None, fail_fast: bool = True, manifest_includes=_INCLUDES_NOT_PROVIDED, @@ -1228,9 +1244,13 @@ def run_dependency_policy_checks( resolved set includes MCP entries they are checked against ``policy.mcp``. effective_target: - The post-targets-phase compilation target string, or ``None``. - When ``None`` target/compilation checks are **skipped** (they - belong to the separate W2-target-aware call). + The ``EffectiveTargetDecision.canonical_targets`` projection of the + resolved target selection, or ``None``. When ``None`` + target/compilation checks are **skipped** (they belong to the + separate W2-target-aware call). + effective_target_source: + Where the target selection came from (``apm.yml``, ``--target flag``, + ...), named in compilation-target violation details. fetch_outcome: Human-readable label for diagnostic context (e.g. ``"cached"``, ``"fetched"``). Currently informational only. @@ -1351,8 +1371,13 @@ def _run(check: CheckResult) -> bool: ] # Target / compilation + manifest tail checks. if effective_target is not None: - synthetic_yml = {"target": effective_target} - remaining_checks.append(_check_compilation_target(synthetic_yml, policy.compilation)) + remaining_checks.append( + _check_compilation_target( + effective_target, + policy.compilation, + source=effective_target_source, + ) + ) if manifest_includes is not _INCLUDES_NOT_PROVIDED: remaining_checks.append(_check_includes_explicit(manifest_includes, policy.manifest)) for check in remaining_checks: @@ -1437,12 +1462,6 @@ def run_policy_checks( apm_deps = manifest.get_apm_dependencies() mcp_deps = manifest.get_mcp_dependencies() - # Read effective target from raw manifest for the full-project path - # NOTE: the wrapper does NOT pass effective_target to the dep seam. - # Target checks run as disk-level checks below (reading raw_yml), - # because the wrapper has the on-disk manifest. The install pipeline - # will pass effective_target directly (W2-target-aware). - try: source_deps = _audit_source_dependencies(manifest, lock) except ValueError as exc: @@ -1463,7 +1482,7 @@ def run_policy_checks( lockfile=lock, policy=policy, mcp_deps=mcp_deps, - # effective_target=None: target checks handled below from raw_yml + # effective_target=None: the manifest target check runs below. fail_fast=fail_fast, manifest_includes=manifest.includes, registries=getattr(manifest, "registries", None), @@ -1492,8 +1511,19 @@ def _run(check: CheckResult) -> bool: # -- Disk-level checks that only apply to full-project audits -- - # Compilation checks (11-13) -- all run from raw_yml in wrapper - if _run(_check_compilation_target(raw_yml, policy.compilation)): + # Compilation checks (11-13). Audit judges the targets the manifest + # declares, through the same projection the install gate uses. + from ..core.target_detection import EffectiveTargetDecision + from ..models.apm_package import package_target_selection + + manifest_decision = EffectiveTargetDecision(package_target_selection(manifest), "apm.yml") + if _run( + _check_compilation_target( + manifest_decision.canonical_targets, + policy.compilation, + source=manifest_decision.source, + ) + ): return result if _run(_check_compilation_strategy(raw_yml, policy.compilation)): return result diff --git a/tests/fixtures/policy/golden/parsed-policies.json b/tests/fixtures/policy/golden/parsed-policies.json index 54c57c1081..7fa4e9c143 100644 --- a/tests/fixtures/policy/golden/parsed-policies.json +++ b/tests/fixtures/policy/golden/parsed-policies.json @@ -1219,7 +1219,7 @@ }, "target": { "allow": [ - "vscode" + "copilot" ], "enforce": null } @@ -1525,11 +1525,7 @@ "enforce": "distributed" }, "target": { - "allow": [ - "vscode", - "claude", - "all" - ], + "allow": null, "enforce": null } }, diff --git a/tests/integration/policy/test_compilation_target_policy_e2e.py b/tests/integration/policy/test_compilation_target_policy_e2e.py new file mode 100644 index 0000000000..51d55f6771 --- /dev/null +++ b/tests/integration/policy/test_compilation_target_policy_e2e.py @@ -0,0 +1,203 @@ +"""Real-binary contract for #3732: compilation-target policy judges the +canonical target set in ``apm audit`` and ``apm install``. + +Every manifest spelling (plural ``targets:``, CSV ``target:``, the ``vscode`` +alias, legacy ``targets: [all]``) is projected to the profiles install +deploys before it meets ``compilation.target.allow``. Audit therefore agrees +with the install gate instead of reading only the singular key. + +Policy reaches ``install`` the way the Govern contract does: an ADO-shaped +origin, a leaf that ``extends`` a strict local policy, and ``apm policy +status`` warming the cache. Audit reads the same strict file with +``--policy``. No network is used. +""" + +from __future__ import annotations + +import json +import os +import subprocess +from pathlib import Path, PurePosixPath + +import pytest + +from apm_cli.utils.yaml_io import dump_yaml +from tests.utils.apm_lifecycle_runner import ApmLifecycleRunner, CommandResult +from tests.utils.isolated_apm_environment import IsolatedApmEnvironment + +pytestmark = [ + pytest.mark.e2e, + pytest.mark.requires_e2e_mode, + pytest.mark.requires_apm_binary, +] + +_POLICY_SOURCE = "dev.azure.com/contoso/apm/apm-policy" +_POLICY_REMOTE = "https://dev.azure.com/contoso/project/_git/compilation-target" +_POLICY_DIAGNOSTIC = f"Policy: org:{_POLICY_SOURCE} (cached" +_STRICT = PurePosixPath(".apm-policy") / "strict.yml" +_AUDIT = ( + "audit", + "--ci", + "--no-fail-fast", + "--no-drift", + "--format", + "json", + "--policy", + _STRICT.as_posix(), +) +_INSTRUCTION = "---\napplyTo: '**'\ndescription: compilation-target contract\n---\n# rule\n" +_ECHO_MCP = { + "name": "local-echo", + "registry": False, + "transport": "stdio", + "command": "echo", + "args": ["hi"], +} + + +def _git(args: tuple[str, ...], *, cwd: Path, env: dict[str, str]) -> None: + subprocess.run(args, cwd=cwd, env=env, capture_output=True, text=True, check=True, timeout=30) + + +def _project(root: Path, name: str, declaration: dict, env: dict[str, str], **extra) -> Path: + project = root / name + (project / ".apm" / "instructions").mkdir(parents=True) + (project / ".apm" / "instructions" / "rule.instructions.md").write_text(_INSTRUCTION) + dump_yaml({"name": name, "version": "1.0.0", **declaration, **extra}, project / "apm.yml") + _git(("git", "init", "--initial-branch=main"), cwd=project, env=env) + _git(("git", "remote", "add", "origin", _POLICY_REMOTE), cwd=project, env=env) + strict = project.joinpath(*_STRICT.parts) + strict.parent.mkdir() + dump_yaml( + { + "name": "compilation-target-contract", + "version": "1", + "enforcement": "block", + "fetch_failure": "block", + "compilation": {"target": {"allow": ["claude", "copilot"]}}, + }, + strict, + ) + leaf = project.joinpath(*PurePosixPath(_POLICY_SOURCE).parts) + leaf.parent.mkdir(parents=True) + dump_yaml({"name": "compilation-target-leaf", "extends": _STRICT.as_posix()}, leaf) + return project + + +def _run( + runner: ApmLifecycleRunner, + args: tuple[str, ...], + *, + cwd: Path, + env: dict[str, str], + scenario_id: str, + expected: int, +) -> CommandResult: + result = runner.run(args, scenario_id=scenario_id, cwd=cwd, env=env) + assert result.returncode == expected, ( + f"{scenario_id}: expected exit {expected}, got {result.returncode}\n" + f"stdout={result.stdout!r}\nstderr={result.stderr!r}" + ) + return result + + +def _compilation_target(runner, project: Path, env, tag: str, expected: int) -> dict: + manifest_before = (project / "apm.yml").read_bytes() + audit = _run( + runner, _AUDIT, cwd=project, env=env, scenario_id=f"{tag}-audit", expected=expected + ) + payload = json.loads(audit.stdout) + assert payload["policy"]["enforced"] is True, payload["policy"] + assert (project / "apm.yml").read_bytes() == manifest_before + checks = {check["name"]: check for check in payload["checks"]} + return checks["compilation-target"] + + +def _install(runner, project: Path, env, tag: str, expected: int) -> CommandResult: + _run( + runner, + ("policy", "status", "--policy-source", _POLICY_SOURCE, "--json", "--check", "--no-cache"), + cwd=project, + env=env, + scenario_id=f"{tag}-warm-policy", + expected=0, + ) + result = _run( + runner, + ("install", "--parallel-downloads", "0"), + cwd=project, + env=env, + scenario_id=f"{tag}-install", + expected=expected, + ) + assert _POLICY_DIAGNOSTIC in result.stdout + result.stderr + return result + + +@pytest.fixture(scope="module") +def harness(tmp_path_factory): + root = tmp_path_factory.mktemp("compilation-target") + isolated = IsolatedApmEnvironment.create(root / "isolated", base_env=dict(os.environ)) + return isolated, isolated.subprocess_env() + + +def _runner(apm_binary_path: Path) -> ApmLifecycleRunner: + return ApmLifecycleRunner( + (str(apm_binary_path),), timeout_seconds=120, scenario_timeout_seconds=600 + ) + + +@pytest.mark.parametrize( + ("tag", "declaration", "passed"), + [ + pytest.param("plural-violation", {"targets": ["claude", "cursor"]}, False, id="L1"), + pytest.param("csv-compliant", {"target": "claude,copilot"}, True, id="L2"), + pytest.param("alias-compliant", {"target": "vscode"}, True, id="L3"), + pytest.param("legacy-all", {"targets": ["all"]}, True, id="L4"), + ], +) +def test_audit_judges_the_canonical_declared_targets( + harness, apm_binary_path, tag, declaration, passed +): + isolated, env = harness + runner = _runner(apm_binary_path) + project = _project(isolated.work_root, tag, declaration, env) + + check = _compilation_target(runner, project, env, tag, expected=0 if passed else 1) + + assert check["passed"] is passed, check + if not passed: + assert "cursor" in check["message"], check + assert not (project / "apm.lock.yaml").exists() + + +def test_install_blocks_a_noncompliant_plural_declaration_before_writing(harness, apm_binary_path): + isolated, env = harness + runner = _runner(apm_binary_path) + project = _project(isolated.work_root, "plural-install", {"targets": ["claude", "cursor"]}, env) + + result = _install(runner, project, env, "L5", expected=1) + + assert "compilation target" in (result.stdout + result.stderr).lower() + assert not (project / "apm.lock.yaml").exists() + for root in (".claude", ".cursor", ".github"): + written = [p for p in (project / root).rglob("*") if p.is_file()] + assert written == [], written + + +def test_vscode_alias_complies_and_keeps_its_mcp_destination(harness, apm_binary_path): + isolated, env = harness + runner = _runner(apm_binary_path) + project = _project( + isolated.work_root, + "alias-install", + {"targets": ["vscode"]}, + env, + dependencies={"mcp": [_ECHO_MCP]}, + ) + + _install(runner, project, env, "L3-install", expected=0) + + assert (project / ".vscode" / "mcp.json").is_file() + assert not (project / ".github" / "mcp.json").exists() + assert _compilation_target(runner, project, env, "L3-after", expected=0)["passed"] is True diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index 1f6cc2ff4a..541fd64a70 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -1351,6 +1351,14 @@ class MutationCase: ), intent="Doctor status icons hard-code glyphs instead of console STATUS_SYMBOLS.", ), + MutationCase( + guard_id="registry-delegation-policy-target-projection", + rule_id="registry_delegation.policy_target_projection", + path="src/apm_cli/policy/policy_checks.py", + old=" manifest_decision.canonical_targets,\n", + new=" raw_yml,\n", + intent="Audit judges compilation-target policy from the raw manifest dict.", + ), MutationCase( guard_id="registry-delegation-process-interrupt-signals", rule_id="registry_delegation.process_interrupt_signals", @@ -2936,3 +2944,41 @@ def test_host_credential_guard_rejects_proxy_route_bypass(path: str, old: str, n report = run_selected_rules(ROOT, (_HOST_CRED_RULE,), source_overrides={path: mutated}) assert report.failures == () assert any(v.rule_id == _HOST_CRED_RULE for v in report.violations) + + +@pytest.mark.parametrize( + ("path", "old", "new"), + [ + pytest.param( + "src/apm_cli/install/phases/policy_target_check.py", + "effective_target=target_decision.canonical_targets,", + 'effective_target=getattr(ctx.apm_package, "target", None),', + id="install-gate-raw-manifest", + ), + pytest.param( + "src/apm_cli/install/mcp/command.py", + "effective_target=target_decision.canonical_targets,", + "effective_target=target_decision.value,", + id="mcp-install-raw-selection", + ), + pytest.param( + "src/apm_cli/core/target_detection.py", + "def canonical_policy_target_name(value: str | None) -> str | None:", + "def normalize_policy_targets(value):\n return value\n\n\n" + "def canonical_policy_target_name(value: str | None) -> str | None:", + id="sibling-normalizer", + ), + ], +) +def test_policy_target_projection_guard_rejects_raw_selections( + path: str, old: str, new: str +) -> None: + """Every compilation-target policy seam judges the canonical projection (#3732).""" + source = _source(path) + assert source.count(old) == 1 + mutated = source.replace(old, new, 1) + ast.parse(mutated, filename=path) + rule_id = "registry_delegation.policy_target_projection" + report = run_selected_rules(ROOT, (rule_id,), source_overrides={path: mutated}) + assert report.failures == () + assert any(violation.rule_id == rule_id for violation in report.violations) diff --git a/tests/integration/test_wave7_policy_registry_coverage.py b/tests/integration/test_wave7_policy_registry_coverage.py index f9d2b784c5..bbbeb8539b 100644 --- a/tests/integration/test_wave7_policy_registry_coverage.py +++ b/tests/integration/test_wave7_policy_registry_coverage.py @@ -479,46 +479,46 @@ def test_warn_policy_passes_with_details(self): class TestCheckCompilationTarget: def test_no_restrictions_configured(self): policy = CompilationPolicy(target=CompilationTargetPolicy(enforce=None, allow=None)) - result = _check_compilation_target({"target": "vscode"}, policy) + result = _check_compilation_target(("copilot",), policy) assert result.passed assert "No compilation target restrictions" in result.message def test_no_target_in_manifest(self): policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) - result = _check_compilation_target({}, policy) + result = _check_compilation_target((), policy) assert result.passed assert "No compilation target set" in result.message - def test_raw_yml_none_with_enforce(self): + def test_no_selection_with_enforce(self): policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) result = _check_compilation_target(None, policy) assert result.passed def test_enforce_matches(self): policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) - result = _check_compilation_target({"target": "vscode"}, policy) + result = _check_compilation_target(("copilot",), policy) assert result.passed assert "Compilation target compliant" in result.message def test_enforce_mismatch(self): policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) - result = _check_compilation_target({"target": "claude"}, policy) + result = _check_compilation_target(("claude",), policy) assert not result.passed assert "not present" in result.message def test_allow_list_matches(self): policy = CompilationPolicy(target=CompilationTargetPolicy(allow=("vscode", "claude"))) - result = _check_compilation_target({"target": "vscode"}, policy) + result = _check_compilation_target(("copilot",), policy) assert result.passed def test_allow_list_rejects(self): policy = CompilationPolicy(target=CompilationTargetPolicy(allow=("vscode",))) - result = _check_compilation_target({"target": "claude"}, policy) + result = _check_compilation_target(("claude",), policy) assert not result.passed def test_target_as_list(self): policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) - result = _check_compilation_target({"target": ["vscode", "claude"]}, policy) + result = _check_compilation_target(("copilot", "claude"), policy) assert result.passed @@ -781,7 +781,7 @@ def test_effective_target_runs_compilation_check(self): policy = ApmPolicy( compilation=CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) ) - result = run_dependency_policy_checks([], policy=policy, effective_target="claude") + result = run_dependency_policy_checks([], policy=policy, effective_target=("claude",)) assert not result.passed names = [c.name for c in result.checks] assert "compilation-target" in names @@ -829,7 +829,7 @@ def test_consolidated_tail_checks_cover_all_categories(self): [], policy=policy, fail_fast=False, - effective_target="claude", + effective_target=("claude",), manifest_includes=None, mcp_deps=[mcp], ) diff --git a/tests/unit/core/test_target_detection.py b/tests/unit/core/test_target_detection.py index 53d5b9cb38..dcb93a5784 100644 --- a/tests/unit/core/test_target_detection.py +++ b/tests/unit/core/test_target_detection.py @@ -11,12 +11,14 @@ EXPERIMENTAL_TARGETS, MCP_ONLY_TARGETS, VALID_TARGET_VALUES, + EffectiveTargetDecision, TargetParamType, can_dedup_agents_md_instructions, + canonical_policy_target_name, + canonical_policy_target_names, detect_target, get_dedup_rules_dir, get_target_description, - normalize_policy_targets, normalize_target_list, should_compile_agents_md, should_compile_claude_md, @@ -958,36 +960,84 @@ def test_all_expansion_excludes_intellij(self): assert t in result -class TestNormalizePolicyTargets: - """Direct contract tests for MCP-only policy target normalization.""" +class TestPolicyTargetProjection: + """Contract tests for the compilation-target policy projection (#3732).""" @pytest.mark.parametrize( ("value", "expected"), [ (None, None), - ("intellij", "copilot"), - (["intellij", "claude"], ["copilot", "claude"]), - (["intellij", "copilot"], ["copilot"]), + ("intellij", ("copilot",)), + (["intellij", "claude"], ("copilot", "claude")), + (["intellij", "copilot"], ("copilot",)), + ("vscode", ("copilot",)), + ("agents", ("copilot",)), + ("agy", ("antigravity",)), + (["claude", "vscode"], ("claude", "copilot")), ], ) - def test_normalizes_shape_and_deduplicates( + def test_decision_projects_aliases_and_mcp_only_targets( self, value: str | list[str] | None, - expected: str | list[str] | None, + expected: tuple[str, ...] | None, ) -> None: - """Normalize MCP-only values while preserving scalar/list shape.""" - assert normalize_policy_targets(value) == expected + """The decision projection resolves aliases and MCP-only targets.""" + assert EffectiveTargetDecision(value, "apm.yml").canonical_targets == expected + + def test_decision_expands_all(self) -> None: + """``all`` projects to every target an install deploys.""" + projected = EffectiveTargetDecision("all", "apm.yml").canonical_targets + assert projected is not None + assert "all" not in projected + assert {"claude", "copilot"} <= set(projected) + + def test_runtime_targets_keep_vscode_distinct(self) -> None: + """Policy canonicalization must not move the VS Code MCP destination.""" + decision = EffectiveTargetDecision(["claude", "vscode"], "apm.yml") + assert decision.canonical_targets == ("claude", "copilot") + assert "vscode" in (decision.runtime_targets or ()) def test_unmapped_mcp_only_target_fails_closed(self, monkeypatch: pytest.MonkeyPatch) -> None: """Reject an MCP-only target without a canonical policy mapping.""" + from dataclasses import replace + + real = target_detection.get_target_capability monkeypatch.setattr( target_detection, - "MCP_ONLY_TARGETS", - frozenset({*MCP_ONLY_TARGETS, "unmapped-mcp"}), + "get_target_capability", + lambda name: replace(real(name), primitive_profile=None), ) with pytest.raises(RuntimeError, match="has no canonical policy mapping"): - normalize_policy_targets("unmapped-mcp") + _ = EffectiveTargetDecision("intellij", "apm.yml").canonical_targets + + @pytest.mark.parametrize( + ("values", "expected"), + [ + (None, None), + ((), ()), + (("vscode", "claude"), ("copilot", "claude")), + (("Copilot", "agents"), ("copilot",)), + (("all",), None), + (("claude", "all"), None), + (("agy", "unknown-tool"), ("antigravity", "unknown-tool")), + ], + ) + def test_policy_names_canonicalize( + self, + values: tuple[str, ...] | None, + expected: tuple[str, ...] | None, + ) -> None: + """Policy allow lists compare on profiles; ``all`` means unrestricted.""" + assert canonical_policy_target_names(values) == expected + + @pytest.mark.parametrize( + ("value", "expected"), + [(None, None), ("vscode", "copilot"), ("all", "all"), ("claude", "claude")], + ) + def test_policy_enforce_canonicalizes(self, value: str | None, expected: str | None) -> None: + """A single enforced target resolves its alias; ``all`` is kept.""" + assert canonical_policy_target_name(value) == expected # --------------------------------------------------------------------------- diff --git a/tests/unit/install/test_mcp_preflight_policy.py b/tests/unit/install/test_mcp_preflight_policy.py index 1212f7f8d9..b8f207741a 100644 --- a/tests/unit/install/test_mcp_preflight_policy.py +++ b/tests/unit/install/test_mcp_preflight_policy.py @@ -182,7 +182,7 @@ def test_direct_mcp_plural_targets_are_policy_checked(self): run_policy_preflight( project_root=Path("/tmp/fake"), mcp_deps=[_make_mcp_dep("test-server", transport="http")], - effective_target=["copilot", "claude"], + effective_target=("copilot", "claude"), logger=_make_logger(), ) diff --git a/tests/unit/install/test_policy_target_check_phase.py b/tests/unit/install/test_policy_target_check_phase.py index 9e9654b2b2..f745001de3 100644 --- a/tests/unit/install/test_policy_target_check_phase.py +++ b/tests/unit/install/test_policy_target_check_phase.py @@ -23,6 +23,7 @@ import pytest import yaml +from apm_cli.core.target_detection import EffectiveTargetDecision from apm_cli.install.phases.policy_gate import PolicyViolationError from apm_cli.install.phases.policy_target_check import TARGET_CHECK_IDS, run from apm_cli.policy.models import CheckResult, CIAuditResult @@ -74,6 +75,7 @@ class _FakeContext: # From caller / CLI apm_package: Any = None target_override: str | list[str] | None = None + target_decision: EffectiveTargetDecision | None = None # From policy_gate policy_fetch: Any = None @@ -89,13 +91,19 @@ def _make_ctx( manifest_target=None, deps=None, ): - """Build a _FakeContext with defaults.""" + """Build a _FakeContext whose target decision mirrors the pipeline.""" pkg = _FakePackage(target=manifest_target) + decision = ( + EffectiveTargetDecision(target_override, "--target flag") + if target_override is not None + else EffectiveTargetDecision(manifest_target, "apm.yml") + ) return _FakeContext( logger=logger or MagicMock(), deps_to_install=deps or [], apm_package=pkg, - target_override=target_override, + target_override=decision.value, + target_decision=decision, policy_fetch=policy_fetch, policy_enforcement_active=enforcement_active, ) @@ -216,6 +224,16 @@ def test_skip_when_no_effective_target(self): run(ctx) # should not raise + def test_raw_manifest_target_is_not_a_second_source(self): + """Only the shared decision is judged, never ``apm_package.target``.""" + ctx = _make_ctx( + enforcement_active=True, + policy_fetch=_make_policy_fetch(enforcement="block", allow=("copilot",)), + ) + ctx.apm_package = _FakePackage(target="claude") + + run(ctx) # decision is unrestricted -> nothing to judge + # ===================================================================== # Test: block mode @@ -311,7 +329,8 @@ def test_cli_override_disallowed_raises_in_block_mode(self, mock_checks): # Verify effective_target passed to checks is the CLI override mock_checks.assert_called_once() call_kwargs = mock_checks.call_args - assert call_kwargs[1]["effective_target"] == "claude" + assert call_kwargs[1]["effective_target"] == ("claude",) + assert call_kwargs[1]["effective_target_source"] == "--target flag" @patch(_PATCH_CHECKS) def test_cli_override_fixes_disallowed_manifest_target(self, mock_checks): @@ -333,7 +352,7 @@ def test_cli_override_fixes_disallowed_manifest_target(self, mock_checks): # Verify effective_target passed to checks is the CLI override mock_checks.assert_called_once() call_kwargs = mock_checks.call_args - assert call_kwargs[1]["effective_target"] == "vscode" + assert call_kwargs[1]["effective_target"] == ("copilot",) ctx.logger.policy_violation.assert_not_called() @@ -350,7 +369,7 @@ def test_intellij_override_is_normalized_to_copilot(self, mock_checks): run(ctx) mock_checks.assert_called_once() - assert mock_checks.call_args.kwargs["effective_target"] == "copilot" + assert mock_checks.call_args.kwargs["effective_target"] == ("copilot",) ctx.logger.policy_violation.assert_not_called() @patch(_PATCH_CHECKS) @@ -369,7 +388,7 @@ def test_plural_override_is_normalized_as_one_target_set(self, mock_checks): run(ctx) mock_checks.assert_called_once() - assert mock_checks.call_args.kwargs["effective_target"] == ["copilot", "claude"] + assert mock_checks.call_args.kwargs["effective_target"] == ("copilot", "claude") def test_plural_override_blocks_when_any_target_is_disallowed(self): """A plural target set cannot bypass compilation.target.allow.""" @@ -501,7 +520,7 @@ def test_fixture_cli_override_fixes_mismatch(self, mock_checks): # Verify the override was passed through call_kwargs = mock_checks.call_args - assert call_kwargs[1]["effective_target"] == "vscode" + assert call_kwargs[1]["effective_target"] == ("copilot",) # ===================================================================== diff --git a/tests/unit/policy/test_inheritance.py b/tests/unit/policy/test_inheritance.py index 8c090abd94..39a5aee21c 100644 --- a/tests/unit/policy/test_inheritance.py +++ b/tests/unit/policy/test_inheritance.py @@ -377,6 +377,17 @@ def test_target_allow_intersection(self): ) self.assertEqual(result.compilation.target.allow, ("vscode",)) + def test_parsed_alias_allow_lists_intersect_on_profiles(self): + """Parent ``[vscode, claude]`` and child ``[copilot]`` keep copilot (#3732).""" + from apm_cli.policy.parser import load_policy + + def _policy(allow: str): + text = f"name: p\nversion: '1'\ncompilation:\n target:\n allow: {allow}\n" + return load_policy(text)[0] + + result = merge_policies(_policy("[vscode, claude]"), _policy("[copilot]")) + self.assertEqual(result.compilation.target.allow, ("copilot",)) + def test_strategy_enforce_parent_wins(self): result = merge_policies( ApmPolicy( diff --git a/tests/unit/policy/test_integration_pinned_constraint.py b/tests/unit/policy/test_integration_pinned_constraint.py index 671876dd4c..49c8f3b0b1 100644 --- a/tests/unit/policy/test_integration_pinned_constraint.py +++ b/tests/unit/policy/test_integration_pinned_constraint.py @@ -134,7 +134,7 @@ def _run_via_target_check_seam(deps, policy): deps, lockfile=None, policy=policy, - effective_target="vscode", + effective_target=("copilot",), fetch_outcome="cached", fail_fast=False, ) diff --git a/tests/unit/policy/test_parser.py b/tests/unit/policy/test_parser.py index 0b55f16b0d..26c972e4e6 100644 --- a/tests/unit/policy/test_parser.py +++ b/tests/unit/policy/test_parser.py @@ -306,8 +306,8 @@ def test_valid_complete_policy(self): self.assertEqual(policy.mcp.transport.allow, ("stdio", "sse")) self.assertEqual(policy.mcp.self_defined, "deny") self.assertTrue(policy.mcp.trust_transitive) - self.assertEqual(policy.compilation.target.allow, ("vscode", "claude")) - self.assertEqual(policy.compilation.target.enforce, "vscode") + self.assertEqual(policy.compilation.target.allow, ("copilot", "claude")) + self.assertEqual(policy.compilation.target.enforce, "copilot") self.assertEqual(policy.compilation.strategy.enforce, "distributed") self.assertTrue(policy.compilation.source_attribution) self.assertEqual(policy.manifest.required_fields, ("description", "version")) diff --git a/tests/unit/policy/test_policy_checks.py b/tests/unit/policy/test_policy_checks.py index 654cd9bdff..038db13c7c 100644 --- a/tests/unit/policy/test_policy_checks.py +++ b/tests/unit/policy/test_policy_checks.py @@ -497,79 +497,195 @@ def test_pass_no_self_defined_servers(self): # -- Check 11: compilation-target ----------------------------------- +def _decision_targets(value): + """Project a target selection the way every caller of the check must.""" + from apm_cli.core.target_detection import EffectiveTargetDecision + + return EffectiveTargetDecision(value, "apm.yml").canonical_targets + + +def _target_policy(*, allow=None, enforce=None) -> CompilationPolicy: + return CompilationPolicy(target=CompilationTargetPolicy(allow=allow, enforce=enforce)) + + class TestCompilationTarget: def test_pass_no_restrictions(self): - result = _check_compilation_target({"target": "vscode"}, CompilationPolicy()) + result = _check_compilation_target(_decision_targets("vscode"), CompilationPolicy()) assert result.passed def test_pass_enforce_match(self): - policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) - result = _check_compilation_target({"target": "vscode"}, policy) + policy = _target_policy(enforce="vscode") + result = _check_compilation_target(_decision_targets("vscode"), policy) assert result.passed def test_fail_enforce_mismatch(self): - policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) - result = _check_compilation_target({"target": "claude"}, policy) + policy = _target_policy(enforce="vscode") + result = _check_compilation_target(_decision_targets("claude"), policy) assert not result.passed assert "enforced" in result.details[0] def test_pass_in_allow_list(self): - policy = CompilationPolicy(target=CompilationTargetPolicy(allow=["vscode", "claude"])) - result = _check_compilation_target({"target": "claude"}, policy) + policy = _target_policy(allow=["vscode", "claude"]) + result = _check_compilation_target(_decision_targets("claude"), policy) assert result.passed def test_fail_not_in_allow_list(self): - policy = CompilationPolicy(target=CompilationTargetPolicy(allow=["vscode"])) - result = _check_compilation_target({"target": "claude"}, policy) + policy = _target_policy(allow=["vscode"]) + result = _check_compilation_target(_decision_targets("claude"), policy) assert not result.passed def test_pass_no_target_in_manifest(self): - policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="vscode")) - result = _check_compilation_target({}, policy) + policy = _target_policy(enforce="vscode") + result = _check_compilation_target(None, policy) assert result.passed # -- Multi-target (list) tests ---------------------------------- def test_target_list_enforce_present(self): """List target containing the enforced value passes.""" - policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="claude")) - result = _check_compilation_target({"target": ["claude", "copilot"]}, policy) + policy = _target_policy(enforce="claude") + result = _check_compilation_target(_decision_targets(["claude", "copilot"]), policy) assert result.passed def test_target_list_enforce_missing(self): """List target missing the enforced value fails.""" - policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="claude")) - result = _check_compilation_target({"target": ["cursor", "copilot"]}, policy) + policy = _target_policy(enforce="claude") + result = _check_compilation_target(_decision_targets(["cursor", "copilot"]), policy) assert not result.passed assert "enforced" in result.details[0] def test_target_list_allow_all_in(self): """All items in list target within allow set passes.""" - policy = CompilationPolicy( - target=CompilationTargetPolicy(allow=["claude", "copilot", "cursor"]) - ) - result = _check_compilation_target({"target": ["claude", "copilot"]}, policy) + policy = _target_policy(allow=["claude", "copilot", "cursor"]) + result = _check_compilation_target(_decision_targets(["claude", "copilot"]), policy) assert result.passed def test_target_list_allow_some_disallowed(self): """List target with items outside allow set fails.""" - policy = CompilationPolicy(target=CompilationTargetPolicy(allow=["claude"])) - result = _check_compilation_target({"target": ["claude", "copilot"]}, policy) + policy = _target_policy(allow=["claude"]) + result = _check_compilation_target(_decision_targets(["claude", "copilot"]), policy) assert not result.passed assert "copilot" in result.message - def test_target_string_still_works(self): - """Backward compat: single string target with enforce.""" - policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="copilot")) - result = _check_compilation_target({"target": "copilot"}, policy) - assert result.passed - def test_target_list_single_item(self): """Single-element list target with matching enforce passes.""" - policy = CompilationPolicy(target=CompilationTargetPolicy(enforce="copilot")) - result = _check_compilation_target({"target": ["copilot"]}, policy) + policy = _target_policy(enforce="copilot") + result = _check_compilation_target(_decision_targets(["copilot"]), policy) assert result.passed + # -- Canonical comparison (#3732) ------------------------------- + + @pytest.mark.parametrize("spelling", ["vscode", "agents", "copilot", ["vscode"]]) + def test_alias_matches_canonical_allow(self, spelling): + """Aliases compare as the profile they deploy, on the manifest side.""" + policy = _target_policy(allow=["claude", "copilot"]) + assert _check_compilation_target(_decision_targets(spelling), policy).passed + + def test_policy_alias_matches_canonical_target(self): + """Aliases also compare as profiles on the policy side.""" + policy = _target_policy(allow=["vscode"], enforce=None) + assert _check_compilation_target(_decision_targets("copilot"), policy).passed + policy = _target_policy(enforce="vscode") + assert _check_compilation_target(_decision_targets(["claude", "copilot"]), policy).passed + + def test_mcp_only_target_judged_as_its_profile(self): + """intellij configures Copilot, so policy judges it as copilot.""" + policy = _target_policy(allow=["copilot"]) + assert _check_compilation_target(_decision_targets("intellij"), policy).passed + + def test_all_in_allow_is_unrestricted(self): + """``allow: [all]`` permits every target.""" + policy = _target_policy(allow=["all"]) + assert _check_compilation_target(_decision_targets(["claude", "cursor"]), policy).passed + + def test_singular_all_judges_the_install_expansion(self): + """``target: all`` deploys everywhere, so a narrow allow list fails.""" + policy = _target_policy(allow=["claude", "copilot"]) + result = _check_compilation_target(_decision_targets("all"), policy) + assert not result.passed + assert "'all'" not in result.message + assert "cursor" in result.message + + def test_enforce_all_requires_the_full_expansion(self): + policy = _target_policy(enforce="all") + assert _check_compilation_target(_decision_targets("all"), policy).passed + assert not _check_compilation_target(_decision_targets("claude"), policy).passed + + def test_violation_names_the_selection_source(self): + policy = _target_policy(allow=["claude"]) + result = _check_compilation_target( + _decision_targets(["claude", "cursor"]), policy, source="--target flag" + ) + assert "--target flag" in result.details[0] + + +class TestAuditCompilationTargetFromManifest: + """``apm audit`` judges the targets apm.yml declares (#3732). + + The plural ``targets:`` cases are ported from #3739 by @MohammedAlkindi. + """ + + @staticmethod + def _audit(tmp_path: Path, manifest_targets: dict, policy: CompilationPolicy) -> CheckResult: + _write_apm_yml(tmp_path, {"name": "test", "version": "1.0.0", **manifest_targets}) + result = run_policy_checks(tmp_path, ApmPolicy(compilation=policy), fail_fast=False) + return next(check for check in result.checks if check.name == "compilation-target") + + def test_targets_plural_enforce_match(self, tmp_path): + """Plural targets list containing the enforced value passes.""" + check = self._audit( + tmp_path, {"targets": ["claude", "copilot"]}, _target_policy(enforce="claude") + ) + assert check.passed + + def test_targets_plural_enforce_mismatch(self, tmp_path): + """Plural targets list missing the enforced value fails.""" + check = self._audit( + tmp_path, {"targets": ["cursor", "copilot"]}, _target_policy(enforce="claude") + ) + assert not check.passed + assert "enforced" in check.details[0] + + def test_targets_plural_allow_match(self, tmp_path): + """Plural targets list with all items allowed passes.""" + check = self._audit( + tmp_path, + {"targets": ["claude", "copilot"]}, + _target_policy(allow=["claude", "copilot", "cursor"]), + ) + assert check.passed + + def test_targets_plural_allow_disallowed(self, tmp_path): + """Plural targets list with disallowed target fails (the #3732 bypass).""" + check = self._audit( + tmp_path, {"targets": ["claude", "cursor"]}, _target_policy(allow=["claude", "copilot"]) + ) + assert not check.passed + assert "cursor" in check.message + assert "apm.yml" in check.details[0] + + def test_no_targets_declared_passes(self, tmp_path): + """A manifest without a target declaration has nothing to judge.""" + check = self._audit(tmp_path, {}, _target_policy(enforce="vscode")) + assert check.passed + + def test_csv_target_is_split(self, tmp_path): + """A compliant CSV value no longer fails as one literal token.""" + check = self._audit( + tmp_path, {"target": "claude,copilot"}, _target_policy(allow=["claude", "copilot"]) + ) + assert check.passed + + @pytest.mark.parametrize("declaration", [{"target": "vscode"}, {"targets": ["vscode"]}]) + def test_vscode_alias_is_compliant(self, tmp_path, declaration): + check = self._audit(tmp_path, declaration, _target_policy(allow=["claude", "copilot"])) + assert check.passed + + def test_plural_legacy_all_stays_compliant(self, tmp_path): + """``targets: [all]`` folds to omitted, so it must not fail as literal 'all'.""" + check = self._audit(tmp_path, {"targets": ["all"]}, _target_policy(allow=["claude"])) + assert check.passed + # -- Check 12: compilation-strategy --------------------------------- diff --git a/tests/unit/policy/test_run_dependency_policy_checks.py b/tests/unit/policy/test_run_dependency_policy_checks.py index 40a823b650..fe6d0ff041 100644 --- a/tests/unit/policy/test_run_dependency_policy_checks.py +++ b/tests/unit/policy/test_run_dependency_policy_checks.py @@ -477,7 +477,7 @@ def test_target_enforced_when_provided(self): policy = ApmPolicy( compilation=CompilationPolicy(target=CompilationTargetPolicy(allow=("vscode",))) ) - result = run_dependency_policy_checks(deps, policy=policy, effective_target="claude") + result = run_dependency_policy_checks(deps, policy=policy, effective_target=("claude",)) assert not result.passed assert "compilation-target" in _failed_names(result) @@ -487,7 +487,7 @@ def test_target_pass_when_allowed(self): policy = ApmPolicy( compilation=CompilationPolicy(target=CompilationTargetPolicy(allow=("vscode",))) ) - result = run_dependency_policy_checks(deps, policy=policy, effective_target="vscode") + result = run_dependency_policy_checks(deps, policy=policy, effective_target=("copilot",)) assert result.passed assert "compilation-target" in _check_names(result) From fe385f43b0e814bb50f7d4095cdefb402e376179 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 16:45:32 +0100 Subject: [PATCH 02/10] docs(changelog): compilation-target policy fix (#3774) Co-authored-by: Mohammed Alkindi Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6e2505d5a..2ab7bea54d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- `compilation.target` policy now judges the targets a project actually selects: `apm audit` reads plural `targets:` (non-compliant manifests that `apm install` already blocked now also fail audit), CSV values such as `target: "claude,copilot"` are split, aliases compare as the target they deploy (`vscode` and `agents` are `copilot`) on both the manifest and policy side, `allow: [all]` allows every target, and inherited alias allow lists no longer merge to "allow nothing". Plural-key tests ported from #3739 -- by @MohammedAlkindi (#3774) + ## [0.36.0] - 2026-11-17 **Upgrade notes:** APM now requires Python 3.11 or newer for `pip`, `pipx` and `uv` installs; the standalone installers and prebuilt binaries are unaffected. After upgrading, run `apm install` once and commit the re-rendered files and `apm.lock.yaml` (export local edits with `apm export-patch` first), because `apm install --frozen` now fails closed when a deployed file differs from its locked hash (#3654). Packages that relied on `*--hooks.json` or `hooks-.json` filenames to route hooks must declare the target in a package `apm.yml` instead, or consumers can narrow the dependency with `targets:`; see "Migrating from filename routing" in the hooks guide (#3613). Hostless policy patterns whose first segment contains a dot, such as `my.group/**`, are now read as hosts; rewrite them with their host, for example `gitlab.com/my.group/**` (#3606). Transitive MCP servers that set their own registry, env, headers, args or URL now need `--trust-transitive-mcp` on each `apm install` or `apm update`, because consent is no longer carried in the lockfile; and `ARTIFACTORY_APM_TOKEN` is only sent when `PROXY_REGISTRY_URL` is set, so set `PROXY_REGISTRY_URL` and `PROXY_REGISTRY_TOKEN` (#3716). From f4bdfdc607c7d751b96dd7e0968ef5f5b5d2d95a Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 17:23:18 +0100 Subject: [PATCH 03/10] test(arch): register policy-target-projection rule and pin local bundle Add registry_delegation.policy_target_projection to the frozen rule inventory so test_registered_rule_inventory_matches_frozen_semantic_contract matches the registered rules (Build & Test Shard 2 was red). Add the local-bundle install seam to the policy-target projection mutation test, and scope each case's assertion to a violation in the mutated file so an unrelated violation elsewhere cannot satisfy it. Mutation-break: dropping run_policy_preflight from the guard's seams fails the new case. Addresses panel follow-ups 1 and 3 on #3774. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../test_architecture_owner_rule_mutations.py | 10 +++++++++- tests/unit/scripts/test_architecture_runner.py | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index 541fd64a70..6625d81f02 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -2961,6 +2961,12 @@ def test_host_credential_guard_rejects_proxy_route_bypass(path: str, old: str, n "effective_target=target_decision.value,", id="mcp-install-raw-selection", ), + pytest.param( + "src/apm_cli/install/local_bundle_handler.py", + "effective_target=deployment_decision.canonical_targets,", + "effective_target=[resolved.name for resolved in targets],", + id="local-bundle-raw-names", + ), pytest.param( "src/apm_cli/core/target_detection.py", "def canonical_policy_target_name(value: str | None) -> str | None:", @@ -2981,4 +2987,6 @@ def test_policy_target_projection_guard_rejects_raw_selections( rule_id = "registry_delegation.policy_target_projection" report = run_selected_rules(ROOT, (rule_id,), source_overrides={path: mutated}) assert report.failures == () - assert any(violation.rule_id == rule_id for violation in report.violations) + assert any( + violation.rule_id == rule_id and violation.path == path for violation in report.violations + ) diff --git a/tests/unit/scripts/test_architecture_runner.py b/tests/unit/scripts/test_architecture_runner.py index 63ccd5305f..981e1047ea 100644 --- a/tests/unit/scripts/test_architecture_runner.py +++ b/tests/unit/scripts/test_architecture_runner.py @@ -741,6 +741,7 @@ def exiting_import( registry_delegation.native_locator_target_names registry_delegation.output_diagnostics registry_delegation.policy_ref_redaction +registry_delegation.policy_target_projection registry_delegation.process_interrupt_signals registry_delegation.root_cli_output_mode registry_delegation.runtime_descriptors From 0a9af04b741bebdeb6ececc34e41ef720f6cdbb6 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 17:23:18 +0100 Subject: [PATCH 04/10] docs(governance): state that target enforce takes precedence over allow The install guarantees said the selection matches both compilation.target.allow and compilation.target.enforce, but the check evaluates enforce first and skips allow when enforce is set, as the policy reference already documents. Addresses Copilot inline review on governance-guide.md:311 and panel follow-up 2 on #3774. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/src/content/docs/enterprise/governance-guide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/src/content/docs/enterprise/governance-guide.md b/docs/src/content/docs/enterprise/governance-guide.md index 20ee03a816..cfd12ef6d3 100644 --- a/docs/src/content/docs/enterprise/governance-guide.md +++ b/docs/src/content/docs/enterprise/governance-guide.md @@ -308,7 +308,7 @@ When `apm install` returns exit code 0 and the effective org policy is in `enfor - Every package in `dependencies.require` is present and at the required version (with one nuance: `require_resolution: project-wins` downgrades version mismatches to warnings, by design). - Every direct MCP server matches `mcp.allow`, is not matched by `mcp.deny`, uses an allowed transport, and respects the `mcp.self_defined` rule. - Every transitive MCP server discovered from APM packages was re-checked against the same `mcp.*` rules in a second pass (unless `--trust-transitive-mcp` was passed). -- The effective target selection (`--target`, `apm.yml`, `apm config target`, or auto-detection) matches `compilation.target.allow` and `compilation.target.enforce`, compared after aliases resolve (`vscode` is `copilot`). +- The effective target selection (`--target`, `apm.yml`, `apm config target`, or auto-detection) includes `compilation.target.enforce` when it is set; otherwise every selected target is in `compilation.target.allow`. `enforce` takes precedence, so `allow` is not checked when both are set. Targets compare after aliases resolve (`vscode` is `copilot`). - The fetched policy file matched any `policy.hash` pin in `apm.yml`. If the hash did not match, install failed closed regardless of `fetch_failure_default` -- hash-mismatch is unconditionally fail-closed in non-dry-run install paths. (`apm install --dry-run` logs the mismatch but does not exit non-zero -- see section 14 gap.) - The lockfile (`apm.lock.yaml`) was regenerated from the resolved, gated set. - Any cached policy used was current within the effective `cache.ttl` (default `3600` seconds), or -- if a refresh failed -- was within the 7-day stale ceiling (`MAX_STALE_TTL`) and a warning was logged naming the cache age. From 6499c3ef3605f38d17db548741df3db8b4eeb9d5 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 18:14:17 +0100 Subject: [PATCH 05/10] refactor(targets): route every manifest target reader through one owner Package-level `target:` / `targets:` is now read only through ManifestTargetDeclaration (models/manifest_targets.py), exposed as APMPackage.target_declaration, package_target_declaration(), read_manifest_target_declaration() and manifest_target_restriction(). Compile, the install targets phase, MCP/LSP integration, lockfile reconciliation, the build orchestrator, the audit target hint, the package-target filter and init re-init no longer re-read or re-parse the raw keys. - `apm install` rejects `target: intellij` / `copilot-app` before writing anything (it used to deploy files and a lockfile, then exit 2). - singular `target: all` no longer prints "treating the field as omitted" while install expands it; `apm init` re-init writes its expansion instead of narrowing it to `targets: [all]`. - docs: `compilation.target` is documented as ignored by `apm compile`. The registry-delegation-target-vocabulary rule is widened to deny-by-default over src/apm_cli with concept-named exemptions, and a new manifest-target-declaration owner record registers its guard. Refs #3732 apm-spec-waiver: routes existing manifest target readers through one owner; OpenAPM-observable acceptance is unchanged Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .apm/architecture/owners/core-runtime.json | 7 + .../docs/enterprise/policy-reference.md | 2 +- .../content/docs/reference/manifest-schema.md | 9 +- .../.apm/skills/apm-usage/governance.md | 2 +- .../checks/mutation_mcp_target_and_scope.py | 10 +- .../checks/registry_owner_guards.py | 170 +++++++++++++-- src/apm_cli/bundle/local_bundle.py | 2 +- src/apm_cli/commands/_helpers.py | 2 + src/apm_cli/commands/compile/cli.py | 21 +- src/apm_cli/commands/init.py | 22 +- src/apm_cli/commands/pack.py | 2 +- src/apm_cli/commands/targets.py | 3 +- src/apm_cli/compilation/agents_compiler.py | 1 + src/apm_cli/core/build_orchestrator.py | 8 +- src/apm_cli/core/deployment_ledger.py | 4 +- src/apm_cli/core/target_detection.py | 4 +- src/apm_cli/install/manifest_reconcile.py | 4 +- src/apm_cli/install/mcp/integration.py | 16 +- src/apm_cli/install/phases/targets.py | 54 +---- src/apm_cli/install/pipeline.py | 12 ++ src/apm_cli/install/target_filter.py | 9 - src/apm_cli/integration/mcp_integrator.py | 6 +- .../integration/mcp_integrator_install.py | 7 +- src/apm_cli/models/apm_package.py | 113 ++++++---- .../models/dependency/object_fields.py | 2 +- .../models/dependency/registry_entry.py | 2 +- src/apm_cli/models/manifest_targets.py | 198 ++++++++++++++++++ src/apm_cli/policy/parser.py | 2 +- tests/integration/_target_policy_kit.py | 186 ++++++++++++++++ .../test_architecture_owner_rule_mutations.py | 61 +++++- ...declaration_adjacent_commands_lifecycle.py | 137 ++++++++++++ ...st_target_declaration_install_lifecycle.py | 164 +++++++++++++++ tests/unit/core/test_build_orchestrator.py | 10 +- .../test_read_yaml_targets_list_form.py | 13 +- tests/unit/models/test_manifest_targets.py | 146 +++++++++++++ 35 files changed, 1204 insertions(+), 207 deletions(-) create mode 100644 src/apm_cli/models/manifest_targets.py create mode 100644 tests/integration/_target_policy_kit.py create mode 100644 tests/integration/test_target_declaration_adjacent_commands_lifecycle.py create mode 100644 tests/integration/test_target_declaration_install_lifecycle.py create mode 100644 tests/unit/models/test_manifest_targets.py diff --git a/.apm/architecture/owners/core-runtime.json b/.apm/architecture/owners/core-runtime.json index 0b27011035..4b06044766 100644 --- a/.apm/architecture/owners/core-runtime.json +++ b/.apm/architecture/owners/core-runtime.json @@ -8,6 +8,13 @@ "selectors": ["src/apm_cli/core/target_catalog.py"], "guards": ["registry-delegation-target-vocabulary"] }, + { + "id": "manifest-target-declaration", + "decision": "Package manifest target declaration: target:/targets: spelling, token validation, legacy all, and the views readers consume", + "owner": "models/manifest_targets.py (ManifestTargetDeclaration, read_manifest_target_declaration) via models/apm_package.py (APMPackage.target_declaration, package_target_declaration)", + "selectors": ["src/apm_cli/models/manifest_targets.py"], + "guards": ["registry-delegation-manifest-target-declaration"] + }, { "id": "effective-install-target-selection", "decision": "Effective target selection and its compilation-target policy projection", diff --git a/docs/src/content/docs/enterprise/policy-reference.md b/docs/src/content/docs/enterprise/policy-reference.md index 5ab90e9ae3..d3103005ec 100644 --- a/docs/src/content/docs/enterprise/policy-reference.md +++ b/docs/src/content/docs/enterprise/policy-reference.md @@ -993,7 +993,7 @@ When `enforcement=block`, any of the following exit `1` and abort before integra | `allowlist` | Dep not in non-empty `dependencies.allow` | `Policy violation: -- not in dependencies.allow` | Add the dep to the org allowlist or switch to an approved package. | | `required` | Missing `dependencies.require` entry, or pin mismatch | `Policy violation: -- required by org policy but not declared in apm.yml` (or `... required >=X but apm.yml pins `) | Add the required dep to `apm.yml` (and pin the required version). Pin mismatches downgrade to warn under `require_resolution: project-wins`; missing required deps still block. | | `transport` | MCP transport not in `mcp.transport.allow` | `Policy violation: -- transport not in mcp.transport.allow=[]` | Switch the server to an allowed transport, or request `mcp.transport.allow` updates. | -| `target` | Resolved target not in `compilation.target.allow` (or violates `target.enforce`) | `Policy violation: target -- not in compilation.target.allow=[]` | Re-run with `--target `, or update `compilation.target` in `apm.yml`. Evaluated post-`targets` phase, so CLI overrides are honoured. | +| `target` | Resolved target not in `compilation.target.allow` (or violates `target.enforce`) | `Policy violation: target -- not in compilation.target.allow=[]` | Re-run with `--target `, or update `targets:` in `apm.yml`. Evaluated post-`targets` phase, so CLI overrides are honoured. | | `pinned-constraint` | `require_pinned_constraint: true` and a dep declares an unbounded ref | `Policy violation: N dependency(ies) use unbounded constraints (hint: pin to a semver range, literal tag, or SHA)` plus per-dep `: ` | Pin each listed dep to a semver range with an upper bound (`^1.2.3`, `>=1.0,<2.0`), a literal tag (`v1.5.3`), or a 40-char SHA. Roll out under `enforcement: warn` first to size the fleet impact. | | `transitive_mcp` | MCP server pulled in by a transitive dep, blocked by `mcp.deny`/`transport`/`self_defined` | `Transitive MCP server(s) blocked by org policy. APM packages remain installed; MCP configs were NOT written.` plus per-server `Policy violation: ...` | Remove the offending dep, request an org policy update, or pass `--trust-transitive-mcp` only as a reviewed break-glass CLI choice. | diff --git a/docs/src/content/docs/reference/manifest-schema.md b/docs/src/content/docs/reference/manifest-schema.md index a50fa423a3..1f9683abb4 100644 --- a/docs/src/content/docs/reference/manifest-schema.md +++ b/docs/src/content/docs/reference/manifest-schema.md @@ -170,6 +170,8 @@ Controls which output targets are generated during compilation, installation, an **Deprecated: `all`.** Manifests published before the canonical target catalog could declare `all`, meaning "no restriction". The value is deprecated: parsers treat a field containing `all` as if the field were omitted (auto-detect / `--target` decide; any sibling targets listed alongside `all` are ignored, though they are still validated) and emit a deprecation warning once per run. Remove the field to keep this behavior permanently; `all` will become a hard parse error in a future release. +The exception is `target: all` on its own: `apm install` and `apm compile` select every supported target, and `compilation.target` policy judges that full set. + For project-scope commands, when both fields are omitted, APM auto-detects from the [documented filesystem signals](../cli/targets/#detection-signals). Once set, the field is authoritative. @@ -194,6 +196,9 @@ A scalar remains accepted as a one-item compatibility input. Declaring both fields is a parse error. Prefer `targets:` in new manifests; `target:` remains supported for backward compatibility. The `vscode` alias is accepted in either form and normalized to `copilot`; `agents` remains a CLI-only alias. +MCP-only and experimental `--target` values such as `intellij` and +`copilot-app` are not manifest targets: `apm install` rejects them in +`apm.yml` before writing any file. | Value | Effect | |---|---| @@ -947,7 +952,7 @@ The `compilation` key is OPTIONAL. It controls [`apm compile`](../cli/compile/) | Field | Type | Default | Constraint | Description | |---|---|---|---|---| -| `target` | `enum` | `all` | Same values as Section 3.6 | Output target. Defaults to `all` when set explicitly in compilation config. | +| `target` | `enum` | unset | Same values as Section 3.6 | Ignored by `apm compile`, which uses `--target`, then the top-level `targets:` (Section 3.6), then auto-detection. Declare outputs with `targets:` instead. | | `strategy` | `enum` | `distributed` | `distributed`, `single-file` | `distributed` generates per-directory target files (e.g. `AGENTS.md`, `CLAUDE.md`). `single-file` generates one monolithic file at `output`. | | `single_file` | `bool` | `false` | | Legacy alias. When `true`, overrides `strategy` to `single-file`. | | `output` | `string` | `AGENTS.md` | File path | Custom output path for the compiled file. | @@ -966,7 +971,6 @@ The `compilation` key is OPTIONAL. It controls [`apm compile`](../cli/compile/) ```yaml compilation: - target: all strategy: distributed source_attribution: true exclude: @@ -1220,7 +1224,6 @@ devDependencies: - owner/test-helpers compilation: - target: all strategy: distributed exclude: - "apm_modules/**" diff --git a/packages/apm-guide/.apm/skills/apm-usage/governance.md b/packages/apm-guide/.apm/skills/apm-usage/governance.md index 5f433f70e2..1212dbdb5a 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/governance.md +++ b/packages/apm-guide/.apm/skills/apm-usage/governance.md @@ -715,7 +715,7 @@ Violation classes: | `required` | Missing `dependencies.require` entry, or version-pin mismatch | Add the dep (and pin) to `apm.yml`. Pin mismatches downgrade to warn under `require_resolution: project-wins`; missing required deps still block | | `pinned-constraint` | `dependencies.require_pinned_constraint: true` + a direct dep with no ref, a wildcard, a bare branch, or a bare `>=X.Y` | Pin the dep to an exact version (`1.2.3` or npm/cargo-style `=1.2.3`; pip-style `==1.2.3` is not supported), caret/tilde/bounded semver range, literal tag (`vX.Y.Z`, or `{name}-vX.Y.Z` / `{name}--vX.Y.Z` for the dep's own package name), or a full SHA. The constraint is judged as declared in `apm.yml` (a `replace:` rule by the ref it selects), not the tag a range resolved to. Roll out enforcement with `warn` before `block`. | | `transport` | MCP transport not in `mcp.transport.allow` | Switch transport, or request `mcp.transport.allow` update | -| `target` | Resolved target not in `compilation.target.allow` (or violates `target.enforce`) | Re-run with `--target `, or adjust `compilation.target` in `apm.yml` | +| `target` | Resolved target not in `compilation.target.allow` (or violates `target.enforce`) | Re-run with `--target `, or adjust `targets:` in `apm.yml` | | `transitive_mcp` | MCP server pulled in by a transitive dep, blocked by `mcp.deny` / `transport` / `self_defined` | Remove offending dep, request policy update, or set `mcp.trust_transitive: true` | Full message text per outcome and per class lives in diff --git a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py index c099123657..d4806e7d05 100644 --- a/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py +++ b/scripts/architecture_linter/checks/mutation_mcp_target_and_scope.py @@ -188,7 +188,7 @@ def _check_mcp_target_selection(provider: FactsProvider) -> Iterable[Violation]: return () findings: list[Violation] = [] - if not _span_has_fixed(install_facts, adapter_span, "parse_targets_field(apm_config)"): + if not _span_has_fixed(install_facts, adapter_span, "manifest_target_restriction(apm_config)"): findings.append( violation( rule_id, _MCP_INSTALL, "manifest adapter must parse targets from the manifest" @@ -215,12 +215,16 @@ def _check_mcp_target_selection(provider: FactsProvider) -> Iterable[Violation]: "resolver must consult the manifest adapter before runtime discovery", ) ) - if _span_has_fixed(install_facts, resolver_span, "parse_targets_field("): + if _span_has_fixed(install_facts, resolver_span, "parse_targets_field(") or _span_has_fixed( + install_facts, resolver_span, "manifest_target_restriction(" + ): findings.append( violation(rule_id, _MCP_INSTALL, "resolver must not parse manifest targets itself") ) validation_line = _first_span_line( - integration_facts, integration_span, "parse_targets_field(mcp_apm_config)" + integration_facts, + integration_span, + "package_target_declaration(apm_package).validate_for_install()", ) install_line = _first_span_line(integration_facts, integration_span, "MCPIntegrator.install(") if validation_line is None or install_line is None or validation_line >= install_line: diff --git a/scripts/architecture_linter/checks/registry_owner_guards.py b/scripts/architecture_linter/checks/registry_owner_guards.py index bb12e92189..117def497f 100644 --- a/scripts/architecture_linter/checks/registry_owner_guards.py +++ b/scripts/architecture_linter/checks/registry_owner_guards.py @@ -11,7 +11,8 @@ registry-delegation-runtime-descriptors AC1 "Runtime names must come from runtime/registry.py" registry-delegation-target-vocabulary AC1 "Manifest target consumers must - use canonical_targets" + use canonical_targets", widened to + deny-by-default over src/apm_cli registry-delegation-install-target- AC1 "Package, MCP, and LSP phases selection must share EffectiveTargetDecision" registry-delegation-policy-target- Compilation-target policy judges @@ -81,14 +82,34 @@ ) -_TARGET_VOCAB_CONSUMERS: tuple[str, ...] = ( - "src/apm_cli/bundle/packer.py", - "src/apm_cli/install/mcp/integration.py", - "src/apm_cli/commands/uninstall/engine.py", +_TARGET_DECLARATION_OWNERS: frozenset[str] = frozenset( + { + "src/apm_cli/models/manifest_targets.py", + "src/apm_cli/models/apm_package.py", + "src/apm_cli/core/apm_yml.py", + "src/apm_cli/core/target_detection.py", + } +) +# The user default (``apm config target``) is parsed with the --target rules. +_TARGET_FIELD_PARSER_USERS: frozenset[str] = frozenset({"src/apm_cli/config.py"}) +_TARGET_FIELD_PARSERS: frozenset[str] = frozenset({"parse_targets_field", "parse_target_field"}) +_TARGET_KEYS: frozenset[str] = frozenset({"target", "targets"}) +_PACKAGE_RECEIVERS: frozenset[str] = frozenset( + {"package", "apm_package", "pkg", "apm_pkg", "manifest", "root_package"} +) +# Reads of a ``target``/``targets`` key that are a different decision than the +# package-level manifest declaration. Each must say which one it is. +_TARGET_EXEMPT_CONCEPTS: frozenset[str] = frozenset( + { + "dependency-target-subset", + "policy-schema", + "bundle-pack-metadata", + "ledger-row", + "display-row", + "bootstrap-writer", + "compilation-target-field", + } ) - - -_TARGET_VOCAB_PATTERN = r"(package|apm_package)\.(target|targets)\b" _EFFECTIVE_TARGET_OWNER = "src/apm_cli/core/target_detection.py" @@ -278,22 +299,124 @@ def _check_runtime_descriptors(provider: FactsProvider) -> Iterable[Violation]: ) +def _is_package_receiver(node: ast.AST) -> bool: + if isinstance(node, ast.Name): + return node.id in _PACKAGE_RECEIVERS + return isinstance(node, ast.Attribute) and node.attr in _PACKAGE_RECEIVERS + + +def _is_target_key(node: ast.AST | None) -> bool: + return isinstance(node, ast.Constant) and node.value in _TARGET_KEYS + + +def _raw_target_read(node: ast.AST, path: str) -> str | None: + """Describe a raw package-target read outside the declaration owner.""" + if ( + isinstance(node, ast.Attribute) + and isinstance(node.ctx, ast.Load) + and node.attr in _TARGET_KEYS + and _is_package_receiver(node.value) + ): + return f"raw package .{node.attr} read" + if isinstance(node, ast.Subscript) and isinstance(node.ctx, ast.Load): + if _is_target_key(node.slice): + return f"raw [{node.slice.value!r}] read" + return None + if isinstance(node, ast.Compare): + if _is_target_key(node.left) and any( + isinstance(op, (ast.In, ast.NotIn)) for op in node.ops + ): + return f"raw {node.left.value!r} key test" + return None + if not isinstance(node, ast.Call): + return None + name = _call_name(node) + if name in _TARGET_FIELD_PARSERS and path not in _TARGET_FIELD_PARSER_USERS: + return f"{name} outside the declaration owner" + if name == "_package_field": + return "_package_field stand-in read" + if name == "get" and node.args and _is_target_key(node.args[0]): + return f"raw .get({node.args[0].value!r}) read" + if ( + name == "getattr" + and len(node.args) >= 2 + and _is_target_key(node.args[1]) + and _is_package_receiver(node.args[0]) + ): + return f"raw getattr(..., {node.args[1].value!r}) read" + return None + + +def _target_exemption(index: TreeIndex, node: ast.AST, lines: tuple[str, ...]) -> str | None: + """Return the exemption concept declared for *node*, if any. + + The marker may sit on the flagged lines, on a header line of an enclosing + statement, or on the line directly above one, up to the enclosing def. + """ + candidates = set(range(node.lineno, (getattr(node, "end_lineno", None) or node.lineno) + 1)) + current: ast.AST | None = node + while current is not None and not isinstance(current, (*FUNCTION_NODES, ast.ClassDef)): + if isinstance(current, ast.stmt): + body = getattr(current, "body", None) + header_end = ( + body[0].lineno - 1 + if isinstance(body, list) and body + else (current.end_lineno or current.lineno) + ) + candidates.update(range(current.lineno - 1, header_end + 1)) + current = index.parent(current) + for line in sorted(candidates): + if 0 < line <= len(lines): + marker = lines[line - 1].partition(EXEMPT_MARKER)[2].strip() + if marker: + return marker.split()[0] + return None + + def _check_target_vocabulary(provider: FactsProvider) -> Iterable[Violation]: - """Manifest target consumers must route through ``canonical_targets``. + """Package manifest targets are read only through the declaration owner. - Ports the AC1 ``check_pattern`` forbidding raw ``package.target`` / - ``apm_package.targets`` attribute reads in the three manifest-target - consumer modules. + Deny-by-default over ``src/apm_cli``: outside ``models/apm_package.py`` + (``ManifestTargetDeclaration``) and its parsers, no module may read a + package's ``target``/``targets`` attributes or keys, or call the target + field parsers. Reads of a different decision carry + ``# architecture-authority-exempt: `` naming it. """ rule_id = "registry_delegation.target_vocabulary" - return line_pattern_violations( - provider, - rule_id=rule_id, - paths=_TARGET_VOCAB_CONSUMERS, - pattern=_TARGET_VOCAB_PATTERN, - message="manifest target consumers must use canonical_targets", - exempt_marker=EXEMPT_MARKER, - ) + findings: list[Violation] = [] + for path in _python_paths(provider, under=_SRC): + if path in _TARGET_DECLARATION_OWNERS: + continue + facts, read_failures = checked_facts(provider, path, rule_id, require_python=True) + if read_failures: + findings.extend(read_failures) + continue + index = provider.tree_index(path) + if index is None: + continue + for node in index.nodes: + reason = _raw_target_read(node, path) + if reason is None: + continue + line = getattr(node, "lineno", 1) + concept = _target_exemption(index, node, facts.lines) + if concept in _TARGET_EXEMPT_CONCEPTS: + continue + message = ( + f"{reason}: route package targets through ManifestTargetDeclaration" + if concept is None + else f"{reason}: unknown exemption concept {concept!r}" + ) + findings.append( + violation( + rule_id, + path, + message, + line=line, + column=getattr(node, "col_offset", 0) + 1, + ) + ) + return findings _POLICY_TARGET_SEAMS: frozenset[str] = frozenset( @@ -1226,8 +1349,11 @@ def _check_version_rendering(provider: FactsProvider) -> Iterable[Violation]: Rule( id="registry_delegation.target_vocabulary", group=GROUP, - guard_ids=("registry-delegation-target-vocabulary",), - description="Manifest target consumers must use core/target_catalog canonical targets.", + guard_ids=( + "registry-delegation-target-vocabulary", + "registry-delegation-manifest-target-declaration", + ), + description=("Package manifest targets are read only through ManifestTargetDeclaration."), check=_check_target_vocabulary, ), Rule( diff --git a/src/apm_cli/bundle/local_bundle.py b/src/apm_cli/bundle/local_bundle.py index b3f1ef888f..107c328788 100644 --- a/src/apm_cli/bundle/local_bundle.py +++ b/src/apm_cli/bundle/local_bundle.py @@ -190,7 +190,7 @@ def _extract_pack_targets(lockfile: dict[str, Any] | None) -> list[str]: if not lockfile: return [] pack = lockfile.get("pack") or {} - target = pack.get("target") + target = pack.get("target") # architecture-authority-exempt: bundle-pack-metadata if target is None: return [] if isinstance(target, list): diff --git a/src/apm_cli/commands/_helpers.py b/src/apm_cli/commands/_helpers.py index 6ba0bd00cc..be4a7edf75 100644 --- a/src/apm_cli/commands/_helpers.py +++ b/src/apm_cli/commands/_helpers.py @@ -692,6 +692,7 @@ def _create_minimal_apm_yml(config, plugin=False, target_path=None): # Add targets field if present in config (plural list form -- canonical). # Older callers may still pass a singular CSV "target" string; honor that # for backwards compatibility but normalise on disk to plural list form. + # architecture-authority-exempt: bootstrap-writer if config.get("targets"): apm_yml_data["targets"] = list(config["targets"]) elif config.get("target"): @@ -724,6 +725,7 @@ def _create_minimal_apm_yml(config, plugin=False, target_path=None): out_file = Path(out_path) content = out_file.read_text(encoding="utf-8") + # architecture-authority-exempt: bootstrap-writer if "targets" in apm_yml_data: from apm_cli.core.target_catalog import manifest_target_names diff --git a/src/apm_cli/commands/compile/cli.py b/src/apm_cli/commands/compile/cli.py index 4fe31bf6ad..f0c98db0b9 100644 --- a/src/apm_cli/commands/compile/cli.py +++ b/src/apm_cli/commands/compile/cli.py @@ -337,28 +337,15 @@ def _resolve_effective_target( (str | list | None) for user-facing label rendering. """ from ...core.target_detection import detect_target - from ...models.apm_package import APMPackage + from ...models.apm_package import APMPackage, package_target_selection _root = source_root or Path(".") config_target = None apm_yml_path = _root / APM_YML_FILENAME if apm_yml_path.exists(): - apm_pkg = APMPackage.from_apm_yml(apm_yml_path) - config_target = apm_pkg.target - if config_target is None: - try: - from ...core.apm_yml import parse_targets_field - from ...utils.yaml_io import load_yaml - - _raw = load_yaml(apm_yml_path) - if isinstance(_raw, dict): - _yaml_targets = parse_targets_field(_raw) - if _yaml_targets: - config_target = ( - _yaml_targets[0] if len(_yaml_targets) == 1 else _yaml_targets - ) - except Exception: - pass + config_target = package_target_selection(APMPackage.from_apm_yml(apm_yml_path)) + if isinstance(config_target, list) and len(config_target) == 1: + config_target = config_target[0] compile_target = _resolve_compile_target(target) compile_config_target = _resolve_compile_target(config_target) diff --git a/src/apm_cli/commands/init.py b/src/apm_cli/commands/init.py index 335607b495..d44a74bdc2 100644 --- a/src/apm_cli/commands/init.py +++ b/src/apm_cli/commands/init.py @@ -693,7 +693,7 @@ def _confirm_setup_summary(config: dict, logger) -> None: Aborts via ``sys.exit(0)`` if the user declines. """ - targets = config.get("targets") + targets = config.get("targets") # architecture-authority-exempt: bootstrap-writer targets_line = ", ".join(targets) if targets else "(none -- auto-detect at compile time)" try: @@ -793,7 +793,7 @@ def _resolve_init_targets( ) if prechecked: targets = sorted(prechecked) - sources = ", ".join(signal_hints.get(t, "") for t in targets) + sources = ", ".join(dict.fromkeys(signal_hints.get(t, "") for t in targets)) logger.progress( f"Auto-detected targets: {', '.join(targets)} {sources}".rstrip(), symbol="info", @@ -819,24 +819,10 @@ def _read_existing_targets(project_root: Path) -> list[str]: try: # Bounded loader so a hostile apm.yml cannot wedge target parsing with a # merge/alias expansion bomb (fails closed -> empty target list). + from apm_cli.models.manifest_targets import ManifestTargetDeclaration from apm_cli.utils.yaml_io import load_yaml - data = load_yaml(apm_yml_path) - if not isinstance(data, dict): - return [] - # Canonical plural form - raw = data.get("targets") - if raw is not None: - if isinstance(raw, list): - return [str(t).strip() for t in raw if str(t).strip()] - return [t.strip() for t in str(raw).split(",") if t.strip()] - # Legacy singular form - raw = data.get("target") - if raw is None: - return [] - if isinstance(raw, list): - return [str(t).strip() for t in raw if str(t).strip()] - return [t.strip() for t in str(raw).split(",") if t.strip()] + return ManifestTargetDeclaration.from_mapping(load_yaml(apm_yml_path)).prefill_names() except Exception: return [] diff --git a/src/apm_cli/commands/pack.py b/src/apm_cli/commands/pack.py index 8ebf782910..f6a1dcceb7 100644 --- a/src/apm_cli/commands/pack.py +++ b/src/apm_cli/commands/pack.py @@ -1012,7 +1012,7 @@ def _log_bundle_meta(result, output_dir, logger): if not meta: return - bundle_target = meta.get("target", "") + bundle_target = meta.get("target", "") # architecture-authority-exempt: bundle-pack-metadata dep_count = len(result.dependency_files) if result.dependency_files else 0 file_count = len(result.files) if result.files else 0 diff --git a/src/apm_cli/commands/targets.py b/src/apm_cli/commands/targets.py index 5897ed42f8..8637ca71c4 100644 --- a/src/apm_cli/commands/targets.py +++ b/src/apm_cli/commands/targets.py @@ -102,7 +102,7 @@ def _row(name: str) -> dict: from apm_cli.core.target_catalog import TARGET_CAPABILITIES from apm_cli.integration.targets import KNOWN_TARGETS - shown = {row["target"] for row in rows} + shown = {row["target"] for row in rows} # architecture-authority-exempt: display-row for name, capability in TARGET_CAPABILITIES.items(): profile = KNOWN_TARGETS.get(name) if ( @@ -135,6 +135,7 @@ def _row(name: str) -> dict: source_col = row["source"] or "" else: source_col = f"needs {row['needs']}" if row["needs"] else "" + # architecture-authority-exempt: display-row click.echo( f" {row['target']:<12} {row['status']:<10} {source_col:<40} {row['deploy_dir']}" ) diff --git a/src/apm_cli/compilation/agents_compiler.py b/src/apm_cli/compilation/agents_compiler.py index 6fbf063ea8..28d4d972ca 100644 --- a/src/apm_cli/compilation/agents_compiler.py +++ b/src/apm_cli/compilation/agents_compiler.py @@ -203,6 +203,7 @@ def from_apm_yml(cls, **overrides) -> "CompilationConfig": config.chatmode = compilation_config["chatmode"] if "resolve_links" in compilation_config: config.resolve_links = compilation_config["resolve_links"] + # architecture-authority-exempt: compilation-target-field if "target" in compilation_config: config.target = compilation_config["target"] diff --git a/src/apm_cli/core/build_orchestrator.py b/src/apm_cli/core/build_orchestrator.py index a385eaa7bb..440bc75316 100644 --- a/src/apm_cli/core/build_orchestrator.py +++ b/src/apm_cli/core/build_orchestrator.py @@ -338,7 +338,7 @@ class PluginManifestProducer: def produce(self, options: BuildOptions, logger: Any) -> ProducerResult: from ..bundle.formats import BundleFormat, coerce_bundle_format - from .apm_yml import parse_targets_field + from ..models.manifest_targets import manifest_target_restriction from .errors import ( ConflictingTargetsError, EmptyTargetsListError, @@ -362,7 +362,7 @@ def produce(self, options: BuildOptions, logger: Any) -> ProducerResult: pass try: - targets = parse_targets_field(data) + targets = manifest_target_restriction(data) except ( ConflictingTargetsError, EmptyTargetsListError, @@ -475,7 +475,7 @@ def detect_outputs(apm_yml_path: Path) -> set[OutputKind]: # Check target: field for 'claude' or 'copilot' (plugin-manifest ecosystems). if data: - from .apm_yml import parse_targets_field + from ..models.manifest_targets import manifest_target_restriction from .errors import ( ConflictingTargetsError, EmptyTargetsListError, @@ -484,7 +484,7 @@ def detect_outputs(apm_yml_path: Path) -> set[OutputKind]: from .plugin_manifest import PLUGIN_MANIFEST_ECOSYSTEMS try: - targets = parse_targets_field(data) + targets = manifest_target_restriction(data) except ( ConflictingTargetsError, EmptyTargetsListError, diff --git a/src/apm_cli/core/deployment_ledger.py b/src/apm_cli/core/deployment_ledger.py index 10ba552deb..f6fbe0db1f 100644 --- a/src/apm_cli/core/deployment_ledger.py +++ b/src/apm_cli/core/deployment_ledger.py @@ -1327,7 +1327,7 @@ def from_rows(rows: Any) -> DeploymentLedger: active_owner = str(row.get("active_owner") or "") locator = DeploymentLocator( kind=LocatorKind(str(row["kind"])), - target=str(row["target"]), + target=str(row["target"]), # architecture-authority-exempt: ledger-row value=str(row["value"]), runtime=str(row["runtime"]) if row.get("runtime") is not None else None, scope=str(row["scope"]), @@ -1352,7 +1352,7 @@ def validate_rows(rows: Any) -> None: raise ValueError(f"Lockfile deployment row {index} must be a mapping") try: LocatorKind(str(row["kind"])) - target = row["target"] + target = row["target"] # architecture-authority-exempt: ledger-row value = row["value"] scope = row["scope"] except (KeyError, TypeError, ValueError) as exc: diff --git a/src/apm_cli/core/target_detection.py b/src/apm_cli/core/target_detection.py index b4c89fe01e..7ec4679bfd 100644 --- a/src/apm_cli/core/target_detection.py +++ b/src/apm_cli/core/target_detection.py @@ -1028,7 +1028,7 @@ def read_manifest_target(project_root: Path) -> list[str] | None: """Read audit's manifest target hint; manifest checks own parse failures.""" import yaml - from apm_cli.core.apm_yml import parse_targets_field + from apm_cli.models.manifest_targets import manifest_target_restriction from apm_cli.utils.yaml_io import load_yaml apm_yml = project_root / "apm.yml" @@ -1036,7 +1036,7 @@ def read_manifest_target(project_root: Path) -> list[str] | None: return None try: data = load_yaml(apm_yml) or {} - tokens = parse_targets_field(data) + tokens = manifest_target_restriction(data) return tokens if tokens else None except (OSError, ValueError, TypeError, yaml.YAMLError, click.UsageError): return None diff --git a/src/apm_cli/install/manifest_reconcile.py b/src/apm_cli/install/manifest_reconcile.py index f4bcaf2dae..50c210b785 100644 --- a/src/apm_cli/install/manifest_reconcile.py +++ b/src/apm_cli/install/manifest_reconcile.py @@ -396,10 +396,10 @@ def declared_target_profiles( diagnostics: DiagnosticCollector | None = None, ) -> list[TargetProfile] | None: """Resolve the target universe declared by a project manifest.""" - from apm_cli.core.apm_yml import parse_targets_field from apm_cli.core.errors import TargetResolutionError from apm_cli.core.target_catalog import normalize_target_name from apm_cli.integration.targets import KNOWN_TARGETS, scoped_profile_or_none + from apm_cli.models.manifest_targets import manifest_target_restriction from apm_cli.utils.yaml_io import load_yaml try: @@ -409,7 +409,7 @@ def declared_target_profiles( if not isinstance(data, dict): return None try: - names = parse_targets_field(data) + names = manifest_target_restriction(data) except TargetResolutionError: return None active_by_name = _profiles_by_name(active_targets) diff --git a/src/apm_cli/install/mcp/integration.py b/src/apm_cli/install/mcp/integration.py index 2fedb62730..ce83a00119 100644 --- a/src/apm_cli/install/mcp/integration.py +++ b/src/apm_cli/install/mcp/integration.py @@ -323,18 +323,16 @@ def run_mcp_integration( # noqa: PLR0913 mcp_count = 0 new_mcp_servers: builtins.set = builtins.set() mcp_apm_config: dict = {"scripts": apm_package.scripts or {}} - from apm_cli.core.apm_yml import ( - ConflictingTargetsError, - EmptyTargetsListError, - UnknownTargetError, - parse_targets_field, + from apm_cli.core.errors import TargetResolutionError + from apm_cli.models.apm_package import ( + canonical_package_target_config, + package_target_declaration, ) - from apm_cli.models.apm_package import canonical_package_target_config - mcp_apm_config.update(canonical_package_target_config(apm_package)) try: - parse_targets_field(mcp_apm_config) - except (ConflictingTargetsError, EmptyTargetsListError, UnknownTargetError) as exc: + mcp_apm_config.update(canonical_package_target_config(apm_package)) + package_target_declaration(apm_package).validate_for_install() + except TargetResolutionError as exc: logger.error(str(exc), symbol="") logger.render_summary() raise SystemExit(2) from exc diff --git a/src/apm_cli/install/phases/targets.py b/src/apm_cli/install/phases/targets.py index d4495f4ea2..9bbbab81b4 100644 --- a/src/apm_cli/install/phases/targets.py +++ b/src/apm_cli/install/phases/targets.py @@ -19,34 +19,11 @@ from apm_cli.integration.targets import TargetProfile -def _package_field(apm_package: Any, name: str) -> Any: - """Return a real APMPackage field without treating MagicMock attrs as set.""" - if apm_package is None: - return None - try: - attrs = vars(apm_package) - except TypeError: - attrs = {} - if name in attrs: - return attrs[name] - value = getattr(apm_package, name, None) - if type(value).__module__ == "unittest.mock": - return None - return value - - def _package_target_value(apm_package: Any) -> str | list[str] | None: - """Read singular target or plural targets from the parsed package model.""" - from apm_cli.core.apm_yml import parse_targets_field + """Return the package's declared target selection from the declaration owner.""" + from apm_cli.models.apm_package import package_target_selection - target = _package_field(apm_package, "target") - targets = _package_field(apm_package, "targets") - if target is not None and targets is not None: - parse_targets_field({"target": target, "targets": targets}) - if targets is not None: - parsed = parse_targets_field({"targets": targets}) - return parsed if parsed else None - return target + return package_target_selection(apm_package) def _raise_target_usage_error(ctx: Any, exc: Exception) -> None: @@ -86,31 +63,16 @@ def _normalize_runtime_target_aliases(tokens: Iterable[str]) -> list[str]: def _read_yaml_targets(ctx) -> list[str] | None: - """Read targets/target from raw apm.yml using v2 parser. + """Return the names the package manifest restricts deployment to. - Returns a list of canonical target names, or None if neither key - is present. Raises ConflictingTargetsError if both keys appear. + ``None`` when nothing restricting is declared (including legacy ``all``). + Raises ConflictingTargetsError if both keys appear. """ if ctx.apm_package is None: return None - apm_yml_path = getattr(ctx.apm_package, "package_path", None) - if apm_yml_path is None: - return _as_yaml_targets(_package_target_value(ctx.apm_package)) - manifest = apm_yml_path / "apm.yml" - if not manifest.exists(): - return _as_yaml_targets(_package_target_value(ctx.apm_package)) - try: - from apm_cli.utils.yaml_io import load_yaml - - data = load_yaml(manifest) - except Exception: - return None - if not isinstance(data, dict): - return None - from apm_cli.core.apm_yml import parse_targets_field + from apm_cli.models.apm_package import package_target_declaration - result = parse_targets_field(data) - return result if result else None + return package_target_declaration(ctx.apm_package).restriction() def declared_target_profiles(ctx: InstallContext) -> list[TargetProfile] | None: diff --git a/src/apm_cli/install/pipeline.py b/src/apm_cli/install/pipeline.py index 04d7c7e2e4..8a2fd0b367 100644 --- a/src/apm_cli/install/pipeline.py +++ b/src/apm_cli/install/pipeline.py @@ -435,6 +435,18 @@ def run_install_pipeline( # noqa: C901, PLR0913, PLR0915, RUF100 if scope is None: scope = InstallScope.PROJECT + # Reject manifest targets install cannot deploy before anything is written. + from ..core.errors import TargetResolutionError + from ..models.apm_package import package_target_declaration + + try: + package_target_declaration(apm_package).validate_for_install() + except TargetResolutionError as exc: + if logger: + logger.error(str(exc), symbol="") + logger.render_summary() + raise SystemExit(2) from exc + apm_deps = apm_package.get_apm_dependencies() dev_apm_deps = apm_package.get_dev_apm_dependencies() all_apm_deps = apm_deps + dev_apm_deps diff --git a/src/apm_cli/install/target_filter.py b/src/apm_cli/install/target_filter.py index b525d86c92..e7716b38a7 100644 --- a/src/apm_cli/install/target_filter.py +++ b/src/apm_cli/install/target_filter.py @@ -5,7 +5,6 @@ from dataclasses import dataclass from typing import TYPE_CHECKING -from apm_cli.core.apm_yml import parse_targets_field from apm_cli.models.apm_package import canonical_package_targets if TYPE_CHECKING: @@ -135,14 +134,6 @@ def resolve_effective_package_targets( consumer_targets = tuple(filtered) package = getattr(package_source, "package", package_source) - try: - package_fields = vars(package) - except TypeError: - package_fields = {} - raw_target = package_fields.get("target") - raw_targets = package_fields.get("targets") - if raw_target is not None and raw_targets is not None: - parse_targets_field({"target": raw_target, "targets": raw_targets}) declared_targets = canonical_package_targets(package) package_restriction_active = bool(declared_targets) and "all" not in declared_targets package_allowed = frozenset(declared_targets) if package_restriction_active else frozenset() diff --git a/src/apm_cli/integration/mcp_integrator.py b/src/apm_cli/integration/mcp_integrator.py index d9cc37659a..b6d6ffc4f1 100644 --- a/src/apm_cli/integration/mcp_integrator.py +++ b/src/apm_cli/integration/mcp_integrator.py @@ -1451,9 +1451,9 @@ def _gate_project_scoped_runtimes( ConflictingTargetsError, EmptyTargetsListError, UnknownTargetError, - parse_targets_field, ) from apm_cli.integration.targets import RUNTIME_TO_CANONICAL_TARGET + from apm_cli.models.manifest_targets import manifest_target_restriction if target_decision is not None and target_decision.canonical_targets is not None: active = set(target_decision.canonical_targets) @@ -1477,7 +1477,7 @@ def _gate_project_scoped_runtimes( yaml_targets: list[str] | None = None if apm_config: try: - parsed = parse_targets_field(apm_config) + parsed = manifest_target_restriction(apm_config) yaml_targets = parsed if parsed else None except ( ConflictingTargetsError, @@ -1490,7 +1490,7 @@ def _gate_project_scoped_runtimes( ) _rich_error(str(exc), symbol="") _log.debug( - "parse_targets_field failed; failing closed (no MCP writes)", + "manifest target declaration invalid; failing closed (no MCP writes)", exc_info=True, ) return [] diff --git a/src/apm_cli/integration/mcp_integrator_install.py b/src/apm_cli/integration/mcp_integrator_install.py index 578f997e48..1502ab4fc9 100644 --- a/src/apm_cli/integration/mcp_integrator_install.py +++ b/src/apm_cli/integration/mcp_integrator_install.py @@ -19,7 +19,6 @@ ConflictingTargetsError, EmptyTargetsListError, UnknownTargetError, - parse_targets_field, ) from apm_cli.core.null_logger import NullCommandLogger from apm_cli.core.target_catalog import accepted_target_values @@ -896,7 +895,7 @@ def _declared_manifest_target_runtimes( ) -> tuple[list[str] | None, bool]: """Return canonical manifest targets and whether the declaration is valid. - Delegates to :func:`apm_cli.core.apm_yml.parse_targets_field`, the same + Delegates to the manifest target declaration owner, the same parser the v2 file-deployment target resolver and :meth:`MCPIntegrator._gate_project_scoped_runtimes` both use, so a manifest-declared target list is interpreted identically everywhere @@ -913,7 +912,9 @@ def _declared_manifest_target_runtimes( return None, True try: - parsed = parse_targets_field(apm_config) + from apm_cli.models.manifest_targets import manifest_target_restriction + + parsed = manifest_target_restriction(apm_config) except (ConflictingTargetsError, EmptyTargetsListError, UnknownTargetError): return None, False if not parsed: diff --git a/src/apm_cli/models/apm_package.py b/src/apm_cli/models/apm_package.py index cfb1dcf070..22f04604da 100644 --- a/src/apm_cli/models/apm_package.py +++ b/src/apm_cli/models/apm_package.py @@ -16,9 +16,7 @@ import yaml -from ..core.apm_yml import parse_targets_field from ..core.target_catalog import normalize_target_name -from ..core.target_detection import parse_target_field from .dependency import ( DependencyReference, GitReferenceType, @@ -28,6 +26,11 @@ ResolvedReference, parse_git_reference, ) +from .manifest_targets import ( + _LEGACY_ALL_TARGET, + _MANIFEST_TARGET_KEYS, + ManifestTargetDeclaration, +) from .validation import ( InvalidVirtualPackageExtensionError, PackageContentType, @@ -505,8 +508,22 @@ class APMPackage: # ``None`` means the key was absent; ``[]`` means it was present but empty. replace_rules: "list[ReplacementRule] | None" = None + target_declaration: ManifestTargetDeclaration | None = field( + default=None, repr=False, compare=False + ) + """Owner of the authored ``target:`` / ``targets:`` declaration.""" + def __post_init__(self) -> None: - """Derive the canonical target projection for compatibility callers.""" + """Derive the target declaration and canonical projection for direct constructions.""" + if self.target_declaration is None: + self.target_declaration = ManifestTargetDeclaration( + tuple( + (key, value) + for key, value in (("target", self.target), ("targets", self.targets)) + if value is not None + ), + self.source_path, + ) if self.canonical_targets: return raw_targets: list[str] = [] @@ -732,35 +749,14 @@ def from_mapping( else: raise ValueError("'includes' must be 'auto' or a list of strings") - # Parse target field through the same validator as --target so a CSV - # string like ``target: "claude,copilot"`` resolves identically to - # ``--target claude,copilot`` and unknown tokens fail at parse time - # (see apm_cli.core.target_detection.parse_target_field). - target_value = None - targets_value: list[str] | None = None - if "targets" in data and "target" in data: - parse_targets_field(data) - raise AssertionError("unreachable: conflicting target keys were accepted") - elif "targets" in data: - parsed_targets = parse_targets_field(data) - targets_value = parsed_targets or None - canonical_targets = tuple(parsed_targets) - else: - target_value = parse_target_field( - data.get("target"), - source_path=source_manifest, - ) - parsed_target_values = ( - target_value - if isinstance(target_value, list) - else [target_value] - if isinstance(target_value, str) - else [] - ) - canonical_targets = tuple( - name if name == "all" else normalize_target_name(name) - for name in parsed_target_values - ) + # The declaration owner validates ``target:`` with the --target + # vocabulary and ``targets:`` with the manifest vocabulary, and rejects + # a manifest that declares both. + target_declaration = ManifestTargetDeclaration.from_mapping(data, source_manifest) + selection = target_declaration.selection + target_value = selection if target_declaration.spelling == "target" else None + targets_value = selection if target_declaration.spelling == "targets" else None + canonical_targets = target_declaration.canonical extensions = _collect_manifest_extensions(data, source_manifest, warning_handler) @@ -816,6 +812,7 @@ def from_mapping( target=target_value, targets=targets_value, canonical_targets=canonical_targets, + target_declaration=target_declaration, type=pkg_type, includes=includes, registries=registries, @@ -951,7 +948,14 @@ def get_dev_lsp_dependencies(self) -> list["LSPDependency"]: def canonical_package_targets(package: object) -> tuple[str, ...]: - """Return canonical targets for packages and compatibility stand-ins.""" + """Return canonical targets for packages and compatibility stand-ins. + + A package declaring both ``target`` and ``targets`` raises + ConflictingTargetsError instead of degrading to either key. + """ + declaration = package_target_declaration(package) + if len(declaration.fields) > 1: + _ = declaration.selection canonical = getattr(package, "canonical_targets", ()) if isinstance(canonical, (tuple, list)) and canonical: return tuple(canonical) @@ -981,6 +985,10 @@ def canonical_package_target_config(package: object) -> dict[str, object]: if not canonical: return {} if isinstance(package, APMPackage): + if package_target_declaration(package).selection == _LEGACY_ALL_TARGET: + # Singular ``all`` leaves MCP/LSP runtime selection unrestricted; + # projecting it as ``targets: [all]`` would claim it was omitted. + return {} return {"targets": list(canonical)} if isinstance(plural, list): return {"targets": list(canonical)} @@ -989,13 +997,38 @@ def canonical_package_target_config(package: object) -> dict[str, object]: return {"targets": list(canonical)} -def package_target_selection(package: APMPackage) -> str | list[str] | None: - """Return pack-compatible selection from the canonical package owner.""" - if package.targets is not None: - return list(package.canonical_targets) - if package.target is not None: - return package.target - return list(package.canonical_targets) or None +def _declared_package_field(package: object, name: str) -> Any: + """Read a stand-in package field without treating MagicMock attrs as set.""" + try: + attrs = vars(package) + except TypeError: + attrs = {} + if name in attrs: + return attrs[name] + value = getattr(package, name, None) + if type(value).__module__ == "unittest.mock": + return None + return value + + +def package_target_declaration(package: object) -> ManifestTargetDeclaration: + """Return the target declaration of a parsed package or a stand-in.""" + if package is None: + return ManifestTargetDeclaration() + if isinstance(package, APMPackage) and package.target_declaration is not None: + return package.target_declaration + return ManifestTargetDeclaration( + tuple( + (key, value) + for key in _MANIFEST_TARGET_KEYS + if (value := _declared_package_field(package, key)) is not None + ) + ) + + +def package_target_selection(package: object) -> str | list[str] | None: + """Return the declared target selection handed to target decisions.""" + return package_target_declaration(package).selection @dataclass diff --git a/src/apm_cli/models/dependency/object_fields.py b/src/apm_cli/models/dependency/object_fields.py index fb1816341f..dbf88338e9 100644 --- a/src/apm_cli/models/dependency/object_fields.py +++ b/src/apm_cli/models/dependency/object_fields.py @@ -79,7 +79,7 @@ def apply_optional_dependency_fields(dep: Any, entry: dict) -> None: skills_raw = entry.get("skills") if skills_raw is not None: dep.skill_subset = parse_skill_subset(skills_raw) - targets_raw = entry.get("targets") + targets_raw = entry.get("targets") # architecture-authority-exempt: dependency-target-subset if targets_raw is not None: dep.target_subset = parse_target_subset(targets_raw) diff --git a/src/apm_cli/models/dependency/registry_entry.py b/src/apm_cli/models/dependency/registry_entry.py index e9088040b9..a19c318150 100644 --- a/src/apm_cli/models/dependency/registry_entry.py +++ b/src/apm_cli/models/dependency/registry_entry.py @@ -78,7 +78,7 @@ def parse_registry_object_entry(dependency_reference_cls: Any, entry: dict) -> A skills_raw = entry.get("skills") skill_subset = parse_skill_subset(skills_raw) if skills_raw is not None else None - targets_raw = entry.get("targets") + targets_raw = entry.get("targets") # architecture-authority-exempt: dependency-target-subset target_subset = parse_target_subset(targets_raw) if targets_raw is not None else None # Reject any unknown keys to catch typos early. diff --git a/src/apm_cli/models/manifest_targets.py b/src/apm_cli/models/manifest_targets.py new file mode 100644 index 0000000000..dab4cf07e4 --- /dev/null +++ b/src/apm_cli/models/manifest_targets.py @@ -0,0 +1,198 @@ +"""Package-level manifest target declaration (``target:`` / ``targets:``). + +Canonical owner of how an apm.yml's package targets are read. Dependency +``targets:`` subsets, ``compilation.target``, and policy targets are separate +decisions owned elsewhere. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from functools import cached_property +from pathlib import Path +from typing import Any + +import yaml + +from ..core.apm_yml import parse_targets_field +from ..core.target_catalog import normalize_target_name +from ..core.target_detection import parse_target_field + +_MANIFEST_TARGET_KEYS: tuple[str, ...] = ("target", "targets") +_LEGACY_ALL_TARGET = "all" + + +def _authored_target_tokens(value: Any) -> list[str]: + if isinstance(value, str): + return [token.strip().lower() for token in value.split(",") if token.strip()] + if isinstance(value, list): + return [str(token).strip().lower() for token in value if str(token).strip()] + return [] + + +@dataclass(frozen=True) +class ManifestTargetDeclaration: + """The package-level ``target:`` / ``targets:`` declaration of one apm.yml. + + Canonical owner of how a manifest's target fields are read: which spelling + was used, per-spelling token validation, legacy ``all``, and the views each + consumer needs. Readers go through this type (``APMPackage.target_declaration``, + :func:`package_target_declaration`, :func:`read_manifest_target_declaration`) + instead of re-reading the raw keys. Dependency ``targets:`` subsets, the + ``compilation.target`` field, and policy targets are different decisions. + """ + + fields: tuple[tuple[str, Any], ...] = () + source_path: Path | None = None + + @classmethod + def from_mapping( + cls, + data: Mapping[str, Any] | None, + source_path: Path | None = None, + ) -> ManifestTargetDeclaration: + """Capture the authored target fields of a manifest mapping.""" + if not isinstance(data, Mapping): + return cls(source_path=source_path) + return cls( + tuple((key, data[key]) for key in _MANIFEST_TARGET_KEYS if key in data), + source_path, + ) + + @property + def spelling(self) -> str | None: + """``"target"``, ``"targets"``, or ``None`` when nothing is declared.""" + keys = [key for key, _value in self.fields] + return keys[-1] if keys else None + + @cached_property + def _validated(self) -> tuple[str | list[str] | None, tuple[str, ...]]: + data = dict(self.fields) + if "targets" in data: + # Also rejects a manifest that declares both keys. + parsed = parse_targets_field(data) + return (list(parsed) or None), tuple(parsed) + value = parse_target_field(data.get("target"), source_path=self.source_path) + values = value if isinstance(value, list) else [value] if isinstance(value, str) else [] + return value, tuple( + name if name == _LEGACY_ALL_TARGET else normalize_target_name(name) for name in values + ) + + @property + def selection(self) -> str | list[str] | None: + """Validated selection handed to target decisions (spelling-preserving). + + Singular ``target: all`` stays ``"all"`` (expanded by the decision); + plural ``targets: [all]`` folds to ``None`` (unrestricted). + """ + return self._validated[0] + + @property + def canonical(self) -> tuple[str, ...]: + """Validated target names with aliases resolved; singular ``all`` kept.""" + return self._validated[1] + + @property + def legacy_all(self) -> bool: + """Whether the manifest declares the legacy ``all`` token.""" + return any( + _LEGACY_ALL_TARGET in _authored_target_tokens(value) for _key, value in self.fields + ) + + @property + def explicit(self) -> bool: + """A valid, nonempty declaration that does not rely on legacy ``all``.""" + return bool(self.selection) and not self.legacy_all + + def restriction(self) -> list[str] | None: + """Declared names that restrict deployment, with legacy ``all`` folded. + + Validates with the plural vocabulary, so MCP-only and experimental + tokens raise. Singular ``all`` folds without the plural deprecation + warning because install expands it rather than treating it as omitted. + """ + data = dict(self.fields) + if self.spelling == "target" and "targets" not in data and self.legacy_all: + remaining = [ + token + for token in _authored_target_tokens(data["target"]) + if token != _LEGACY_ALL_TARGET + ] + if remaining: + parse_targets_field({"target": remaining}) + return None + names = parse_targets_field(data) + return names or None + + def authored_names(self) -> list[str]: + """Unvalidated names as written, ``targets:`` first (for prompts only).""" + data = dict(self.fields) + value = data.get("targets") + if value is None: + value = data.get("target") + if isinstance(value, list): + return [str(name).strip() for name in value if str(name).strip()] + if value is None: + return [] + return [name.strip() for name in str(value).split(",") if name.strip()] + + def prefill_names(self) -> list[str]: + """Names a re-init writes as ``targets:`` without changing what deploys. + + Singular ``target: all`` expands at install, so it is written as that + explicit set; plural ``targets: [all]`` already means omitted. + """ + if self.spelling == "target" and self.legacy_all: + from ..core.errors import TargetResolutionError + from ..core.target_detection import EffectiveTargetDecision + + try: + selection = self.selection + except (ValueError, TargetResolutionError): + return self.authored_names() + if selection is not None: + return list(EffectiveTargetDecision(selection, "apm.yml").canonical_targets or ()) + return self.authored_names() + + def validate_for_install(self) -> None: + """Reject declared targets ``apm install`` cannot deploy. + + Install calls this before writing anything, so a singular token the + manifest parser accepts but install cannot deploy (``intellij``, + ``copilot-app``) fails without leaving partial output behind. + """ + if self.selection == _LEGACY_ALL_TARGET or not self.canonical: + return + parse_targets_field({"targets": list(self.canonical)}) + + +def read_manifest_target_declaration( + manifest_path: Path, + *, + lenient: bool = False, +) -> ManifestTargetDeclaration | None: + """Read and validate the target declaration of the apm.yml at *manifest_path*. + + Returns ``None`` when the file is absent. With *lenient*, unreadable or + invalid manifests also return ``None`` instead of raising. + """ + from ..core.errors import TargetResolutionError + from ..utils.yaml_io import load_yaml + + if not manifest_path.is_file(): + return None + try: + data = load_yaml(manifest_path) + declaration = ManifestTargetDeclaration.from_mapping(data, manifest_path) + _ = declaration.selection + except (OSError, ValueError, TypeError, yaml.YAMLError, TargetResolutionError): + if lenient: + return None + raise + return declaration + + +def manifest_target_restriction(data: Mapping[str, Any] | None) -> list[str]: + """Return the restricting target names of a manifest mapping (empty if none).""" + return ManifestTargetDeclaration.from_mapping(data).restriction() or [] diff --git a/src/apm_cli/policy/parser.py b/src/apm_cli/policy/parser.py index 08faa8c7be..4d50720c56 100644 --- a/src/apm_cli/policy/parser.py +++ b/src/apm_cli/policy/parser.py @@ -314,7 +314,7 @@ def _build_policy(data: dict) -> ApmPolicy: ) comp_data = data.get("compilation") or {} - target_data = comp_data.get("target") or {} + target_data = comp_data.get("target") or {} # architecture-authority-exempt: policy-schema strategy_data = comp_data.get("strategy") or {} compilation = CompilationPolicy( target=CompilationTargetPolicy( diff --git a/tests/integration/_target_policy_kit.py b/tests/integration/_target_policy_kit.py new file mode 100644 index 0000000000..d64d36f36d --- /dev/null +++ b/tests/integration/_target_policy_kit.py @@ -0,0 +1,186 @@ +"""Shared plumbing for manifest-target and compilation-target policy chains (#3732). + +Builds on :mod:`tests.integration._policy_scope_kit`: an org policy served from +``contoso/.github`` over the loopback GitHub HTTPS fixture, ``contoso/pkg-*`` +packages from local bare repositories, and consumer projects whose ``origin`` +points at ``contoso`` so policy auto-discovery needs no real network. +""" + +from __future__ import annotations + +import json +import os +import re +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path + +from apm_cli.utils.yaml_io import dump_yaml, load_yaml +from tests.integration._policy_scope_kit import ( + PolicyScopeWorld, + output, + run_step, + tree_snapshot, +) +from tests.utils.apm_lifecycle_runner import ApmLifecycleRunner, CommandResult +from tests.utils.local_github_https_fixture import local_github_https_fixture + +SELF_DEFINED_MCP = { + "name": "srv", + "registry": False, + "transport": "http", + "url": "https://mcp.example.com/mcp", +} + +# The legacy deprecation text the MCP phase prints for ``all``. Under decision +# D1 a singular ``target: all`` expands for deployment, so this claim must not +# be printed for it. +TREATED_AS_OMITTED = "treating the field as omitted" + + +def block_policy(target_policy: Mapping[str, object] | None = None, **extra: object) -> dict: + """Return a block-mode org policy with an optional ``compilation.target`` block.""" + policy: dict[str, object] = { + "name": "contoso-policy", + "version": "1.0.0", + "enforcement": "block", + } + if target_policy is not None: + policy["compilation"] = {"target": dict(target_policy)} + policy.update(extra) + return policy + + +def write_manifest(project: Path, declaration: Mapping[str, object], **extra: object) -> None: + """Replace the consumer manifest's target declaration, keeping dependencies.""" + manifest = load_yaml(project / "apm.yml") or {} + manifest.pop("targets", None) + manifest.pop("target", None) + manifest.update(declaration) + manifest.update(extra) + dump_yaml(manifest, project / "apm.yml") + + +def compilation_target_check(result: CommandResult) -> dict: + """Return the ``compilation-target`` row from ``audit --ci -f json`` output.""" + try: + report = json.loads(result.stdout) + except json.JSONDecodeError as exc: # pragma: no cover - diagnostic path + raise AssertionError(f"audit did not emit JSON:\n{output(result)}") from exc + for check in report.get("checks") or []: + if check.get("name") == "compilation-target": + return check + raise AssertionError(f"no compilation-target check in audit report:\n{result.stdout}") + + +def check_text(check: Mapping[str, object]) -> str: + return " ".join([str(check.get("message", "")), *map(str, check.get("details") or [])]) + + +def quoted_tokens(text: str) -> set[str]: + """Return every single-quoted token in a policy message.""" + return set(re.findall(r"'([^']*)'", text)) + + +def names_word(text: str, name: str) -> bool: + return re.search(rf"(? str: + """Return the whitespace-normalized install violation for ``check``.""" + flat = " ".join(output(result).split()) + match = re.search(rf"Policy violation: {re.escape(check)} -- (.*?)(?: Blocked by |$)", flat) + return match.group(1) if match else "" + + +def changed_paths(before: Mapping[str, str], after: Mapping[str, str]) -> list[str]: + keys = set(before) | set(after) + return sorted(key for key in keys if before.get(key) != after.get(key)) + + +def file_bytes(path: Path) -> bytes | None: + return path.read_bytes() if path.exists() else None + + +@dataclass +class TargetPolicyWorld: + """One policy world plus a runner and child environment inside the HTTPS fixture.""" + + world: PolicyScopeWorld + runner: ApmLifecycleRunner + env: dict[str, str] + + def consumer( + self, + name: str, + declaration: Mapping[str, object], + *, + dependencies: Sequence[object] | None = None, + mcp: Sequence[Mapping[str, object]] = (), + dirs: Sequence[str] = (), + ) -> Path: + deps = ( + [f"{pkg.slug}#v1.0.0" for pkg in self.world.packages.values()] + if dependencies is None + else list(dependencies) + ) + project = self.world.consumer(name, dependencies=deps) + extra: dict[str, object] = {} + if mcp: + extra["dependencies"] = {"apm": deps, "mcp": [dict(entry) for entry in mcp]} + write_manifest(project, declaration, **extra) + for directory in dirs: + (project / directory).mkdir(parents=True, exist_ok=True) + return project + + def run( + self, + project: Path, + *args: str, + step: str, + expected: int | tuple[int, ...] = 0, + env: Mapping[str, str] | None = None, + ) -> CommandResult: + return run_step( + self.runner, args, cwd=project, env=env or self.env, step=step, expected=expected + ) + + def audit_read_only(self, project: Path, *, step: str) -> tuple[CommandResult, dict]: + """Run ``audit --ci -f json`` and assert it changed nothing in the project.""" + before = tree_snapshot(project) + result = self.run(project, "audit", "--ci", "-f", "json", step=step, expected=(0, 1)) + after = tree_snapshot(project) + assert after == before, ( + f"[{step}] audit --ci changed project files: {changed_paths(before, after)}" + ) + return result, compilation_target_check(result) + + +@contextmanager +def target_policy_world( + tmp_path: Path, + apm_binary_path: Path, + policy: Mapping[str, object], + *, + packages: Sequence[str] = ("pkg-a",), + extra_policy_repos: Mapping[str, Mapping[str, object]] | None = None, +) -> Iterator[TargetPolicyWorld]: + """Yield a served policy world. ``extra_policy_repos`` adds ``contoso/`` repos.""" + world = PolicyScopeWorld(tmp_path, dict(os.environ)) + for name in packages: + world.publish_package(name) + world.publish_policy(policy) + served = world.served_repositories() + for name, content in (extra_policy_repos or {}).items(): + source = world.isolated.package_root / name + source.mkdir(parents=True) + dump_yaml(dict(content), source / "apm-policy.yml") + repository = world.repositories.create(name, source_tree=source) + world.repositories.commit(repository, message=f"{name} policy") + served[f"contoso/{name}"] = repository + runner = ApmLifecycleRunner((str(apm_binary_path),), scenario_timeout_seconds=900) + with local_github_https_fixture(tmp_path / "certs", served) as fixture: + env = fixture.child_environment(world.git_env()) + env.pop("CLAUDE_CONFIG_DIR", None) + yield TargetPolicyWorld(world=world, runner=runner, env=env) diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index 541fd64a70..bcec2fd0e0 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -753,8 +753,8 @@ class MutationCase: guard_id="hooks-integrations-mcp-target-selection", rule_id="mutation_writes.mcp_target_selection", path="src/apm_cli/integration/mcp_integrator_install.py", - old="parse_targets_field(apm_config)", - new="parse_target_fields(apm_config)", + old="manifest_target_restriction(apm_config)", + new="manifest_target_restrictions(apm_config)", intent="MCP install adapter stops parsing targets through the manifest owner.", ), MutationCase( @@ -1335,6 +1335,17 @@ class MutationCase: intent="Install pipeline stops resolving the shared EffectiveTargetDecision.", replace_all=True, ), + MutationCase( + guard_id="registry-delegation-manifest-target-declaration", + rule_id="registry_delegation.target_vocabulary", + path="src/apm_cli/install/target_filter.py", + old=' package = getattr(package_source, "package", package_source)\n', + new=( + ' package = getattr(package_source, "package", package_source)\n' + ' raw_targets = vars(package).get("targets")\n' + ), + intent="Package-target authorization re-reads the raw manifest targets field.", + ), MutationCase( guard_id="registry-delegation-output-diagnostics", rule_id="registry_delegation.output_diagnostics", @@ -2982,3 +2993,49 @@ def test_policy_target_projection_guard_rejects_raw_selections( report = run_selected_rules(ROOT, (rule_id,), source_overrides={path: mutated}) assert report.failures == () assert any(violation.rule_id == rule_id for violation in report.violations) + + +@pytest.mark.parametrize( + ("path", "old", "new"), + [ + pytest.param( + "src/apm_cli/policy/policy_checks.py", + " manifest_decision = EffectiveTargetDecision(", + ' raw_target = (raw_yml or {}).get("target")\n' + " manifest_decision = EffectiveTargetDecision(", + id="audit-raw-get", + ), + pytest.param( + "src/apm_cli/install/phases/policy_target_check.py", + " target_decision = ctx.target_decision\n", + " target_decision = ctx.target_decision\n" + ' config_target = getattr(ctx.apm_package, "target", None)\n', + id="install-gate-getattr", + ), + pytest.param( + "src/apm_cli/commands/compile/cli.py", + " if isinstance(config_target, list) and len(config_target) == 1:\n", + " config_target = parse_targets_field({})\n" + " if isinstance(config_target, list) and len(config_target) == 1:\n", + id="compile-reparse", + ), + pytest.param( + "src/apm_cli/policy/parser.py", + "# architecture-authority-exempt: policy-schema", + "# architecture-authority-exempt: anything-goes", + id="unknown-exemption-concept", + ), + ], +) +def test_manifest_target_declaration_guard_rejects_raw_readers( + path: str, old: str, new: str +) -> None: + """Every package-target reader routes through ManifestTargetDeclaration (#3732).""" + source = _source(path) + assert source.count(old) == 1 + mutated = source.replace(old, new, 1) + ast.parse(mutated, filename=path) + rule_id = "registry_delegation.target_vocabulary" + report = run_selected_rules(ROOT, (rule_id,), source_overrides={path: mutated}) + assert report.failures == () + assert any(violation.rule_id == rule_id for violation in report.violations) diff --git a/tests/integration/test_target_declaration_adjacent_commands_lifecycle.py b/tests/integration/test_target_declaration_adjacent_commands_lifecycle.py new file mode 100644 index 0000000000..5a1d11477e --- /dev/null +++ b/tests/integration/test_target_declaration_adjacent_commands_lifecycle.py @@ -0,0 +1,137 @@ +"""Adjacent commands keep package targets and dependency target subsets apart (#3732). + +Promise under test (0.36.1 T2 brief, section 4 "L" rows and section 5.4 risk): +the declaration owner and the widened guard touch every reader of the +package-level ``target:`` / ``targets:`` field, but a per-dependency +``targets:`` subset is a different concept and must keep working. + +* Read-only commands (``compile --dry-run``, ``deps list/tree/why``, ``view``, + ``audit --ci``, ``export-patch --dry-run``) never rewrite ``apm.yml`` or the + lockfile, whatever the package target spelling. +* ``uninstall`` and ``prune`` keep the package target declaration verbatim and + keep the remaining dependency's ``targets:`` subset. +* A dependency subset narrows deployment and is never judged by + compilation-target policy. +* Re-initialising a project with ``init --yes`` keeps the deployment set a + singular ``target: all`` selects (decision D1). +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from apm_cli.utils.yaml_io import load_yaml +from tests.integration._policy_scope_kit import output +from tests.integration._target_policy_kit import block_policy, target_policy_world +from tests.utils.local_github_https_fixture import openssl_executable + +pytestmark = [ + pytest.mark.integration, + pytest.mark.requires_apm_binary, + pytest.mark.skipif(openssl_executable() is None, reason="openssl CLI not available"), +] + +CLAUDE_COPILOT = {"allow": ["claude", "copilot"]} + + +def _dep(name: str, *subset: str) -> dict: + return {"git": f"https://github.com/contoso/{name}", "ref": "v1.0.0", "targets": list(subset)} + + +def _declaration(project: Path) -> dict: + """The package-level ``target:`` / ``targets:`` keys as parsed YAML.""" + manifest = load_yaml(project / "apm.yml") or {} + return {key: manifest[key] for key in ("target", "targets") if key in manifest} + + +@pytest.mark.parametrize( + "declaration", + [{"targets": ["claude", "copilot"]}, {"target": "claude,copilot"}], + ids=["plural", "singular-csv"], +) +def test_adjacent_commands_keep_package_targets_and_dependency_subsets( + declaration: dict, tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world( + tmp_path, apm_binary_path, block_policy(CLAUDE_COPILOT), packages=("pkg-a", "pkg-b") + ) as tw: + project = tw.consumer( + "consumer", + declaration, + dependencies=[_dep("pkg-a", "claude"), _dep("pkg-b", "cursor")], + ) + tw.run(project, "install", step="1-install") + assert (project / ".claude/skills/pkg-a-skill/SKILL.md").is_file() + assert not (project / ".agents/skills/pkg-a-skill").exists(), "subset ignored" + assert not list(project.glob(".*/skills/pkg-b-skill")), "cursor-only dep deployed" + + manifest = (project / "apm.yml").read_bytes() + lock = (project / "apm.lock.yaml").read_bytes() + for step, args in ( + ("2-compile-dry-run", ("compile", "--dry-run")), + ("3-deps-list", ("deps", "list")), + ("4-deps-tree", ("deps", "tree")), + ("5-deps-why", ("deps", "why", "contoso/pkg-a")), + ("6-view", ("view", "contoso/pkg-a")), + ("7-install-frozen", ("install", "--frozen")), + ("8-update", ("update", "--yes")), + ("9-export-patch", ("export-patch", "--dry-run")), + ): + tw.run(project, *args, step=step) + assert (project / "apm.yml").read_bytes() == manifest, f"[{step}] rewrote apm.yml" + assert (project / "apm.lock.yaml").read_bytes() == lock, f"[{step}] lockfile churn" + + _result, check = tw.audit_read_only(project, step="10-audit") + assert check["passed"] is True, check + assert "cursor" not in str(check), check + + tw.run(project, "uninstall", "contoso/pkg-b", step="11-uninstall") + assert _declaration(project) == declaration, (project / "apm.yml").read_text() + remaining = load_yaml(project / "apm.yml")["dependencies"]["apm"] + assert remaining == [_dep("pkg-a", "claude")], remaining + + tw.run(project, "prune", step="12-prune") + tw.run(project, "install", step="13-reinstall") + assert _declaration(project) == declaration + assert (project / ".claude/skills/pkg-a-skill/SKILL.md").is_file() + assert not (project / ".agents/skills/pkg-a-skill").exists() + + +@pytest.mark.parametrize( + "declaration", + [{"targets": ["claude", "copilot"]}, {"target": "claude,copilot"}, {"target": "all"}], + ids=["plural", "singular-csv", "singular-all"], +) +def test_export_patch_finds_local_edits_for_every_spelling( + declaration: dict, tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + project = tw.consumer("consumer", declaration) + tw.run(project, "install", step="1-install") + skill = project / ".claude/skills/pkg-a-skill/SKILL.md" + skill.write_text(skill.read_text(encoding="utf-8") + "local edit\n", encoding="utf-8") + manifest = (project / "apm.yml").read_bytes() + result = tw.run(project, "export-patch", "--dry-run", step="2-export-patch") + assert "pkg-a" in output(result), output(result) + assert "No local edits" not in output(result), output(result) + assert (project / "apm.yml").read_bytes() == manifest + + +def test_reinit_keeps_the_singular_all_deployment_set( + tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + project = tw.consumer("consumer", {"target": "all"}, dirs=(".claude",)) + tw.run(project, "install", step="1-install") + expanded = sorted(p.parent.parent.parent.name for p in project.glob(".*/skills/*/SKILL.md")) + assert len(expanded) > 1, expanded + + tw.run(project, "init", "--yes", step="2-reinit") + tw.run(project, "install", "contoso/pkg-a#v1.0.0", step="3-readd") + after = sorted(p.parent.parent.parent.name for p in project.glob(".*/skills/*/SKILL.md")) + assert after == expanded, ( + f"re-init narrowed target: all from {expanded} to {after}:\n" + f"{(project / 'apm.yml').read_text(encoding='utf-8')}" + ) diff --git a/tests/integration/test_target_declaration_install_lifecycle.py b/tests/integration/test_target_declaration_install_lifecycle.py new file mode 100644 index 0000000000..b61f6e8c0c --- /dev/null +++ b/tests/integration/test_target_declaration_install_lifecycle.py @@ -0,0 +1,164 @@ +"""Manifest target declarations install consistently across spellings and scopes (#3732). + +Promise under test (0.36.1 T2 brief, decisions C and D1, fact F12): + +* A singular ``target:`` naming a harness that install cannot deploy + (``intellij``, ``copilot-app``) is rejected before any write: no lockfile, + no deployed primitives, no ``.gitignore`` edit. +* A singular ``target: all`` keeps expanding to the install set (D1), and the + MCP phase no longer claims the field is "treated as omitted" in the same + run (F10). A plural ``targets: [all]`` still folds, with the warning. +* The MCP destination depends on the runtime spelling, identically for + ``target:`` and ``targets:``: ``vscode`` writes ``.vscode/mcp.json`` and + ``copilot`` writes ``.github/mcp.json`` (F12, regression lock). +* ``apm install -g`` reads ``~/.apm/apm.yml`` through the same declaration + owner, so every spelling of the same set deploys the same files (L7). +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from apm_cli.utils.yaml_io import dump_yaml, load_yaml +from tests.integration._policy_scope_kit import output, tree_snapshot +from tests.integration._target_policy_kit import ( + SELF_DEFINED_MCP, + TREATED_AS_OMITTED, + block_policy, + changed_paths, + target_policy_world, +) +from tests.utils.local_github_https_fixture import openssl_executable + +pytestmark = [ + pytest.mark.integration, + pytest.mark.requires_apm_binary, + pytest.mark.skipif(openssl_executable() is None, reason="openssl CLI not available"), +] + + +@pytest.mark.parametrize("token", ["intellij", "copilot-app"]) +def test_undeployable_singular_target_is_rejected_before_any_write( + token: str, tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + project = tw.consumer("consumer", {"target": token}) + before = tree_snapshot(project) + result = tw.run(project, "install", step="1-install", expected=(1, 2)) + assert result.returncode == 2, output(result) + assert token in output(result), output(result) + after = tree_snapshot(project) + assert after == before, f"rejected install wrote: {changed_paths(before, after)}" + assert not (project / "apm.lock.yaml").exists() + assert not (project / ".github").exists() + assert not (project / ".agents").exists() + + +def test_singular_all_expands_without_claiming_it_was_omitted( + tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + project = tw.consumer("consumer", {"target": "all"}, mcp=[SELF_DEFINED_MCP]) + result = tw.run(project, "install", step="1-install") + text = " ".join(output(result).split()) + assert TREATED_AS_OMITTED not in text, text + # D1: the expansion still deploys primitives and MCP to many harnesses. + for deployed in ( + ".claude/skills/pkg-a-skill/SKILL.md", + ".agents/skills/pkg-a-skill/SKILL.md", + ".kiro/skills/pkg-a-skill/SKILL.md", + ".vscode/mcp.json", + ".cursor/mcp.json", + ".mcp.json", + ): + assert (project / deployed).is_file(), f"target: all no longer deploys {deployed}" + manifest = (project / "apm.yml").read_bytes() + result = tw.run(project, "install", step="2-reinstall") + assert TREATED_AS_OMITTED not in " ".join(output(result).split()) + assert (project / "apm.yml").read_bytes() == manifest + + +def test_plural_all_still_folds_to_auto_detect_with_warning( + tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + project = tw.consumer( + "consumer", {"targets": ["all"]}, mcp=[SELF_DEFINED_MCP], dirs=(".claude",) + ) + result = tw.run(project, "install", step="1-install") + text = " ".join(output(result).split()) + assert "deprecated" in text, text + assert (project / ".claude/skills/pkg-a-skill/SKILL.md").is_file() + assert not (project / ".cursor").exists(), "targets: [all] expanded beyond auto-detect" + assert not (project / ".agents").exists() + + +@pytest.mark.parametrize( + ("declaration", "destination", "absent"), + [ + ({"target": "vscode"}, ".vscode/mcp.json", ".github/mcp.json"), + ({"targets": ["vscode"]}, ".vscode/mcp.json", ".github/mcp.json"), + ({"target": "copilot"}, ".github/mcp.json", ".vscode/mcp.json"), + ({"targets": ["copilot"]}, ".github/mcp.json", ".vscode/mcp.json"), + ], + ids=["singular-vscode", "plural-vscode", "singular-copilot", "plural-copilot"], +) +def test_mcp_destination_follows_runtime_spelling( + declaration: dict, destination: str, absent: str, tmp_path: Path, apm_binary_path: Path +) -> None: + policy = block_policy({"allow": ["claude", "copilot"]}) + with target_policy_world(tmp_path, apm_binary_path, policy) as tw: + project = tw.consumer("consumer", declaration, dependencies=[], mcp=[SELF_DEFINED_MCP]) + tw.run(project, "install", step="1-install") + assert (project / destination).is_file(), f"{declaration} did not write {destination}" + assert not (project / absent).exists(), f"{declaration} also wrote {absent}" + lock = load_yaml(project / "apm.lock.yaml") or {} + runtime = "vscode" if destination.startswith(".vscode") else "copilot" + assert list((lock.get("mcp_target_servers") or {}).keys()) == [runtime], lock + + +@pytest.mark.parametrize( + "declaration", + [ + {"targets": ["claude", "cursor"]}, + {"target": "claude,cursor"}, + {"target": ["claude", "cursor"]}, + ], + ids=["plural", "singular-csv", "singular-list"], +) +def test_user_scope_reads_declared_targets_for_every_spelling( + declaration: dict, tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + isolated = tw.world.isolated + manifest = {"name": "user", "version": "0.1.0", **declaration} + manifest["dependencies"] = {"apm": ["contoso/pkg-a#v1.0.0"]} + dump_yaml(manifest, isolated.config_root / "apm.yml") + cwd = isolated.work_root + tw.run(cwd, "install", "-g", step="1-install-g") + home = isolated.home + assert (home / ".claude/skills/pkg-a-skill/SKILL.md").is_file() + assert (home / ".agents/skills/pkg-a-skill/SKILL.md").is_file() + assert not (home / ".copilot").exists(), "undeclared copilot received files" + lock = load_yaml(isolated.config_root / "apm.lock.yaml") or {} + targets = sorted({row.get("target") for row in lock.get("deployments") or []}) + assert targets == ["claude", "cursor"], lock.get("deployments") + before = (isolated.config_root / "apm.yml").read_bytes() + tw.run(cwd, "compile", "-g", step="2-compile-g") + assert (isolated.config_root / "apm.yml").read_bytes() == before + + +def test_user_scope_singular_all_expands_without_claiming_it_was_omitted( + tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + isolated = tw.world.isolated + manifest = {"name": "user", "version": "0.1.0", "target": "all"} + manifest["dependencies"] = {"apm": ["contoso/pkg-a#v1.0.0"]} + dump_yaml(manifest, isolated.config_root / "apm.yml") + result = tw.run(isolated.work_root, "install", "-g", step="1-install-g") + assert TREATED_AS_OMITTED not in " ".join(output(result).split()), output(result) + assert (isolated.home / ".claude/skills/pkg-a-skill/SKILL.md").is_file() + assert (isolated.home / ".config/opencode/skills/pkg-a-skill/SKILL.md").is_file() diff --git a/tests/unit/core/test_build_orchestrator.py b/tests/unit/core/test_build_orchestrator.py index 4ff2a75431..0aac8a9313 100644 --- a/tests/unit/core/test_build_orchestrator.py +++ b/tests/unit/core/test_build_orchestrator.py @@ -598,15 +598,9 @@ def test_force_overwrites_existing_file(self, tmp_path: Path) -> None: def test_conflicting_targets_raises_build_error( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - from apm_cli.core.errors import ConflictingTargetsError - apm = self._apm_yml(tmp_path, "claude") + apm.write_text(apm.read_text() + "targets: [cursor]\n") opts = BuildOptions(project_root=tmp_path, apm_yml_path=apm) - def _raise(data: dict) -> list[str]: - raise ConflictingTargetsError("both target and targets set") - - monkeypatch.setattr("apm_cli.core.apm_yml.parse_targets_field", _raise) - - with pytest.raises(BuildError, match=r"both target and targets set"): + with pytest.raises(BuildError, match=r"target"): PluginManifestProducer().produce(opts, logger=None) diff --git a/tests/unit/install/phases/test_read_yaml_targets_list_form.py b/tests/unit/install/phases/test_read_yaml_targets_list_form.py index 1cecd51b1d..d81241a639 100644 --- a/tests/unit/install/phases/test_read_yaml_targets_list_form.py +++ b/tests/unit/install/phases/test_read_yaml_targets_list_form.py @@ -20,14 +20,15 @@ import pytest +from apm_cli.models.apm_package import APMPackage + def _ctx_with_apm_yml(tmp_path: Path, body: str) -> MagicMock: project = tmp_path / "proj" project.mkdir() (project / "apm.yml").write_text(body, encoding="utf-8") ctx = MagicMock() - ctx.apm_package = MagicMock() - ctx.apm_package.package_path = project + ctx.apm_package = APMPackage.from_apm_yml(project / "apm.yml") return ctx @@ -108,13 +109,13 @@ def test_read_yaml_targets_unknown_token_in_list_raises_clean_error(tmp_path): """Unknown token inside a YAML list must surface a readable headline, not a Python list-repr fragment like '['copilot''. """ + from types import SimpleNamespace + from apm_cli.core.errors import UnknownTargetError from apm_cli.install.phases.targets import _read_yaml_targets - ctx = _ctx_with_apm_yml( - tmp_path, - "name: demo\nversion: 0.1.0\ntarget: [bogus]\n", - ) + ctx = MagicMock() + ctx.apm_package = SimpleNamespace(target=["bogus"]) with pytest.raises(UnknownTargetError) as exc_info: _read_yaml_targets(ctx) headline = str(exc_info.value).splitlines()[0] diff --git a/tests/unit/models/test_manifest_targets.py b/tests/unit/models/test_manifest_targets.py new file mode 100644 index 0000000000..7540d443d7 --- /dev/null +++ b/tests/unit/models/test_manifest_targets.py @@ -0,0 +1,146 @@ +"""Contract tests for the package manifest target declaration owner (#3732).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from apm_cli.core import apm_yml +from apm_cli.core.errors import ConflictingTargetsError, UnknownTargetError +from apm_cli.core.target_detection import EffectiveTargetDecision +from apm_cli.models.apm_package import ( + APMPackage, + canonical_package_target_config, + package_target_declaration, + package_target_selection, +) +from apm_cli.models.manifest_targets import ( + ManifestTargetDeclaration, + manifest_target_restriction, + read_manifest_target_declaration, +) +from apm_cli.utils.yaml_io import dump_yaml + + +def _declaration(**fields) -> ManifestTargetDeclaration: + return ManifestTargetDeclaration.from_mapping(fields) + + +@pytest.fixture(autouse=True) +def _rearm_legacy_all_warning(): + apm_yml._reset_legacy_all_warning() + yield + apm_yml._reset_legacy_all_warning() + + +@pytest.mark.parametrize( + ("singular", "plural"), + [ + ("claude,vscode", ["claude", "vscode"]), + (["claude", "vscode"], ["claude", "vscode"]), + ("agy", ["antigravity"]), + ("agents", ["copilot"]), + ], +) +def test_spellings_project_to_the_same_policy_targets(singular, plural): + """``target:`` CSV/list and ``targets:`` are one declaration for policy.""" + singular_decl = _declaration(target=singular) + plural_decl = _declaration(targets=plural) + + assert singular_decl.spelling == "target" + assert plural_decl.spelling == "targets" + assert ( + EffectiveTargetDecision(singular_decl.selection, "apm.yml").canonical_targets + == EffectiveTargetDecision(plural_decl.selection, "apm.yml").canonical_targets + ) + + +def test_vscode_spelling_keeps_its_mcp_runtime(): + decision = EffectiveTargetDecision(_declaration(targets=["vscode"]).selection, "apm.yml") + assert decision.canonical_targets == ("copilot",) + assert decision.runtime_targets == ("vscode",) + + +@pytest.mark.parametrize( + ("fields", "selection", "legacy_all", "explicit"), + [ + ({}, None, False, False), + ({"target": None}, None, False, False), + ({"target": "all"}, "all", True, False), + ({"targets": ["all"]}, None, True, False), + ({"targets": ["claude"]}, ["claude"], False, True), + ], +) +def test_declaration_views(fields, selection, legacy_all, explicit): + declaration = ManifestTargetDeclaration.from_mapping(fields) + assert declaration.selection == selection + assert declaration.legacy_all is legacy_all + assert declaration.explicit is explicit + + +def test_conflicting_keys_are_rejected(): + with pytest.raises(ConflictingTargetsError): + _ = _declaration(target="claude", targets=["cursor"]).selection + + +def test_singular_all_restriction_folds_without_the_omitted_warning(capsys): + """Install expands ``target: all``; it must not be reported as omitted.""" + declaration = _declaration(target="all") + + assert declaration.restriction() is None + declaration.validate_for_install() + assert canonical_package_target_config(APMPackage("p", "1", target="all")) == {} + + assert "treating the field as omitted" not in capsys.readouterr().out + + +def test_plural_all_still_warns_that_it_is_omitted(capsys): + assert _declaration(targets=["all"]).restriction() is None + assert "treating the field as omitted" in capsys.readouterr().out + + +@pytest.mark.parametrize("token", ["intellij", "copilot-app"]) +def test_install_rejects_tokens_it_cannot_deploy(token): + """The manifest parser accepts these singular tokens; install must not.""" + declaration = _declaration(target=token) + assert declaration.selection == token + + with pytest.raises(UnknownTargetError): + declaration.validate_for_install() + + +def test_install_accepts_deployable_declarations(): + for fields in ({"target": "claude,copilot"}, {"targets": ["vscode"]}, {}): + ManifestTargetDeclaration.from_mapping(fields).validate_for_install() + + +def test_parsed_package_exposes_its_declaration(tmp_path: Path): + manifest = tmp_path / "apm.yml" + dump_yaml({"name": "p", "version": "1.0.0", "targets": ["claude", "vscode"]}, manifest) + + package = APMPackage.from_apm_yml(manifest) + + assert package.target_declaration is not None + assert package_target_declaration(package) is package.target_declaration + assert package_target_selection(package) == ["claude", "vscode"] + assert read_manifest_target_declaration(manifest).restriction() == ["claude", "vscode"] + + +def test_path_reader_is_lenient_only_on_request(tmp_path: Path): + manifest = tmp_path / "apm.yml" + dump_yaml({"name": "p", "version": "1.0.0", "targets": ["nope"]}, manifest) + + assert read_manifest_target_declaration(tmp_path / "missing.yml") is None + assert read_manifest_target_declaration(manifest, lenient=True) is None + with pytest.raises(UnknownTargetError): + read_manifest_target_declaration(manifest) + + +def test_stand_in_packages_route_through_the_owner(): + class _StandIn: + target = "claude,cursor" + + assert package_target_selection(_StandIn()) == ["claude", "cursor"] + assert manifest_target_restriction({"target": "claude,cursor"}) == ["claude", "cursor"] + assert manifest_target_restriction(None) == [] From 456a637dbc8e50bbabba00e5c744e05139c2b5b0 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 18:20:58 +0100 Subject: [PATCH 06/10] docs(changelog): manifest target declaration owner (#3791) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a78c416b13..f9c4bba7d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - `compilation.target` policy now judges the targets a project actually selects: `apm audit` reads plural `targets:` (non-compliant manifests that `apm install` already blocked now also fail audit), CSV values such as `target: "claude,copilot"` are split, aliases compare as the target they deploy (`vscode` and `agents` are `copilot`) on both the manifest and policy side, `allow: [all]` allows every target, and inherited alias allow lists no longer merge to "allow nothing". Plural-key tests ported from #3739 -- by @MohammedAlkindi (#3774) +- `apm install` rejects `target: intellij` or `target: copilot-app` in `apm.yml` before writing any file (it used to deploy files and a lockfile, then fail); `target: all` no longer prints a contradictory "treating the field as omitted" warning while installing everywhere; re-running `apm init` keeps the targets `target: all` deploys to; and the docs now say the ignored `compilation.target` field has no effect, so use `targets:`. (#3791) ## [0.36.0] - 2026-11-17 From 5f1190b81a8af37203b5f483d74d0b6affac4ae8 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 19:27:27 +0100 Subject: [PATCH 07/10] fix(architecture): scope target exemptions to the marked statement The deny-by-default target guard let an exemption marker cover a whole block (marker above an if/for/try exempted its body) and the line after a trailing marker, so a raw package.targets read placed inside an exempted block went unflagged. A marker now covers only the innermost statement holding the read (its header for compound statements) or sits alone on the line directly above it. The guard also flags .pop/.setdefault on the target keys. Existing init and compilation.target exemptions are marked per statement. Mutation cases cover a read leaking out of an exempt block, a trailing-marker leak, and the subscript, key-test and pop shapes. Addresses panel follow-up 2 (test-coverage-expert, python-architect) on #3791. apm-spec-waiver: architecture guard and exemption markers only; no OpenAPM-observable behavior change Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../checks/registry_owner_guards.py | 35 ++++++++++--------- src/apm_cli/commands/_helpers.py | 4 +++ src/apm_cli/compilation/agents_compiler.py | 1 + .../test_architecture_owner_rule_mutations.py | 35 +++++++++++++++++++ 4 files changed, 58 insertions(+), 17 deletions(-) diff --git a/scripts/architecture_linter/checks/registry_owner_guards.py b/scripts/architecture_linter/checks/registry_owner_guards.py index 117def497f..fb1760c72f 100644 --- a/scripts/architecture_linter/checks/registry_owner_guards.py +++ b/scripts/architecture_linter/checks/registry_owner_guards.py @@ -335,8 +335,8 @@ def _raw_target_read(node: ast.AST, path: str) -> str | None: return f"{name} outside the declaration owner" if name == "_package_field": return "_package_field stand-in read" - if name == "get" and node.args and _is_target_key(node.args[0]): - return f"raw .get({node.args[0].value!r}) read" + if name in {"get", "pop", "setdefault"} and node.args and _is_target_key(node.args[0]): + return f"raw .{name}({node.args[0].value!r}) read" if ( name == "getattr" and len(node.args) >= 2 @@ -350,22 +350,23 @@ def _raw_target_read(node: ast.AST, path: str) -> str | None: def _target_exemption(index: TreeIndex, node: ast.AST, lines: tuple[str, ...]) -> str | None: """Return the exemption concept declared for *node*, if any. - The marker may sit on the flagged lines, on a header line of an enclosing - statement, or on the line directly above one, up to the enclosing def. + The marker must sit on a line of the innermost statement holding *node* + (only its header, for a compound statement) or alone on the line directly + above that statement. It never covers a sibling or nested statement. """ - candidates = set(range(node.lineno, (getattr(node, "end_lineno", None) or node.lineno) + 1)) - current: ast.AST | None = node - while current is not None and not isinstance(current, (*FUNCTION_NODES, ast.ClassDef)): - if isinstance(current, ast.stmt): - body = getattr(current, "body", None) - header_end = ( - body[0].lineno - 1 - if isinstance(body, list) and body - else (current.end_lineno or current.lineno) - ) - candidates.update(range(current.lineno - 1, header_end + 1)) - current = index.parent(current) - for line in sorted(candidates): + statement: ast.AST | None = node + while statement is not None and not isinstance(statement, ast.stmt): + statement = index.parent(statement) + anchor = statement if statement is not None else node + first = anchor.lineno + last = getattr(anchor, "end_lineno", None) or first + body = getattr(anchor, "body", None) + if isinstance(anchor, ast.stmt) and isinstance(body, list) and body: + last = max(first, body[0].lineno - 1) + candidates = list(range(first, last + 1)) + if 1 < first <= len(lines) + 1 and lines[first - 2].lstrip().startswith("#"): + candidates.append(first - 1) + for line in candidates: if 0 < line <= len(lines): marker = lines[line - 1].partition(EXEMPT_MARKER)[2].strip() if marker: diff --git a/src/apm_cli/commands/_helpers.py b/src/apm_cli/commands/_helpers.py index be4a7edf75..0203eb3630 100644 --- a/src/apm_cli/commands/_helpers.py +++ b/src/apm_cli/commands/_helpers.py @@ -692,10 +692,14 @@ def _create_minimal_apm_yml(config, plugin=False, target_path=None): # Add targets field if present in config (plural list form -- canonical). # Older callers may still pass a singular CSV "target" string; honor that # for backwards compatibility but normalise on disk to plural list form. + # These read the init config, not a manifest. # architecture-authority-exempt: bootstrap-writer if config.get("targets"): + # architecture-authority-exempt: bootstrap-writer apm_yml_data["targets"] = list(config["targets"]) + # architecture-authority-exempt: bootstrap-writer elif config.get("target"): + # architecture-authority-exempt: bootstrap-writer raw = config["target"] if isinstance(raw, list): apm_yml_data["targets"] = list(raw) diff --git a/src/apm_cli/compilation/agents_compiler.py b/src/apm_cli/compilation/agents_compiler.py index 28d4d972ca..999b7428c9 100644 --- a/src/apm_cli/compilation/agents_compiler.py +++ b/src/apm_cli/compilation/agents_compiler.py @@ -205,6 +205,7 @@ def from_apm_yml(cls, **overrides) -> "CompilationConfig": config.resolve_links = compilation_config["resolve_links"] # architecture-authority-exempt: compilation-target-field if "target" in compilation_config: + # architecture-authority-exempt: compilation-target-field config.target = compilation_config["target"] # Distributed compilation settings (Task 7) diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index 0b69a09d29..d6725374b3 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -3060,6 +3060,41 @@ def test_policy_target_projection_guard_rejects_raw_selections( "# architecture-authority-exempt: anything-goes", id="unknown-exemption-concept", ), + pytest.param( + "src/apm_cli/commands/_helpers.py", + ' apm_yml_data["targets"] = list(config["targets"])\n', + ' apm_yml_data["targets"] = list(config["targets"])\n' + " leaked = package.targets\n", + id="exempt-block-does-not-cover-nested-read", + ), + pytest.param( + "src/apm_cli/bundle/local_bundle.py", + ' target = pack.get("target") # architecture-authority-exempt: bundle-pack-metadata\n', + ' target = pack.get("target") # architecture-authority-exempt: bundle-pack-metadata\n' + ' leaked = lockfile.get("targets")\n', + id="trailing-marker-does-not-cover-next-line", + ), + pytest.param( + "src/apm_cli/install/target_filter.py", + ' package = getattr(package_source, "package", package_source)\n', + ' package = getattr(package_source, "package", package_source)\n' + ' raw_targets = package_source["targets"]\n', + id="raw-subscript", + ), + pytest.param( + "src/apm_cli/install/target_filter.py", + ' package = getattr(package_source, "package", package_source)\n', + ' package = getattr(package_source, "package", package_source)\n' + ' declared = "targets" in vars(package)\n', + id="raw-key-test", + ), + pytest.param( + "src/apm_cli/install/target_filter.py", + ' package = getattr(package_source, "package", package_source)\n', + ' package = getattr(package_source, "package", package_source)\n' + ' raw_targets = dict(vars(package)).pop("targets", None)\n', + id="raw-pop", + ), ], ) def test_manifest_target_declaration_guard_rejects_raw_readers( From 19488ec4a9e3d9c688da8a3d290504efaaa102ce Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 19:27:28 +0100 Subject: [PATCH 08/10] fix(targets): route compile -g and disk readers through the declaration owner apm compile -g still re-read ~/.apm/apm.yml with its own parser and, for target: all, printed the "treating the field as omitted" warning that install no longer prints. read_manifest_target_declaration is now the one disk reader (strict: refuses symlinks, empty and non-mapping documents; lenient: returns None), and compile -g, audit's read_manifest_target and install's declared_target_profiles go through it. read_declared_target_names is removed; restriction() gains allow_empty_singular for strict readers. The pre-write rejection moves into reject_undeployable_manifest_targets (keeps install/pipeline.py under its LOC budget) and also runs before the CLI renames a legacy apm.lock, so a rejected install writes nothing. Re-init expands singular target: all with the install spellings, so vscode keeps its .vscode/mcp.json destination instead of becoming copilot (.github/mcp.json). Tests: e2e for compile -g without the warning, -g pre-write rejection, legacy lockfile untouched on rejection, and the MCP destination after re-init; unit tests for the strict/lenient reader; drift tests patch the owner's parser. Addresses panel follow-ups 1 and 3 and Copilot inline comments on src/apm_cli/install/pipeline.py:443 and src/apm_cli/models/manifest_targets.py:155. apm-spec-waiver: routes existing manifest target readers through one owner; OpenAPM-observable acceptance is unchanged Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- src/apm_cli/commands/compile/cli.py | 13 ++++- src/apm_cli/commands/install.py | 3 + src/apm_cli/core/apm_yml.py | 49 ---------------- src/apm_cli/core/target_detection.py | 15 ++--- src/apm_cli/install/manifest_reconcile.py | 12 ++-- src/apm_cli/install/phases/targets.py | 14 +++++ src/apm_cli/install/pipeline.py | 12 +--- src/apm_cli/models/manifest_targets.py | 56 ++++++++++++------- ...declaration_adjacent_commands_lifecycle.py | 15 ++++- ...st_target_declaration_install_lifecycle.py | 32 ++++++++++- tests/unit/install/test_drift_detection.py | 2 +- tests/unit/install/test_drift_phase3.py | 2 +- tests/unit/models/test_manifest_targets.py | 50 ++++++++++++++++- 14 files changed, 168 insertions(+), 109 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f9c4bba7d6..c236324fbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - `compilation.target` policy now judges the targets a project actually selects: `apm audit` reads plural `targets:` (non-compliant manifests that `apm install` already blocked now also fail audit), CSV values such as `target: "claude,copilot"` are split, aliases compare as the target they deploy (`vscode` and `agents` are `copilot`) on both the manifest and policy side, `allow: [all]` allows every target, and inherited alias allow lists no longer merge to "allow nothing". Plural-key tests ported from #3739 -- by @MohammedAlkindi (#3774) -- `apm install` rejects `target: intellij` or `target: copilot-app` in `apm.yml` before writing any file (it used to deploy files and a lockfile, then fail); `target: all` no longer prints a contradictory "treating the field as omitted" warning while installing everywhere; re-running `apm init` keeps the targets `target: all` deploys to; and the docs now say the ignored `compilation.target` field has no effect, so use `targets:`. (#3791) +- `apm install` rejects `target: intellij` or `target: copilot-app` in `apm.yml` before writing any file (it used to deploy files and a lockfile, then fail); `target: all` no longer prints a contradictory "treating the field as omitted" warning in `apm install` or `apm compile -g` while deploying everywhere; re-running `apm init` keeps the targets `target: all` deploys to; and the docs now say the ignored `compilation.target` field has no effect, so use `targets:`. (#3791) ## [0.36.0] - 2026-11-17 diff --git a/src/apm_cli/commands/compile/cli.py b/src/apm_cli/commands/compile/cli.py index f0c98db0b9..1b38e016f5 100644 --- a/src/apm_cli/commands/compile/cli.py +++ b/src/apm_cli/commands/compile/cli.py @@ -377,13 +377,20 @@ def _global_compile_targets(source_root: Path) -> tuple[list[TargetProfile], lis Declared names are normalized before lookup because ``apm.yml`` accepts the ``vscode`` alias, which is not a ``KNOWN_TARGETS`` key; matching raw tokens would drop it and silently compile nothing. + + The manifest is read strictly through the declaration owner: a broken user + manifest fails closed instead of widening to every harness, and singular + ``target: all`` expands to every target like ``apm install -g`` does. """ - from ...core.apm_yml import read_declared_target_names from ...core.target_catalog import normalize_target_name from ...integration.targets import KNOWN_TARGETS + from ...models.manifest_targets import read_manifest_target_declaration - declared = read_declared_target_names(source_root) - if declared is None or not declared: + declaration = read_manifest_target_declaration(source_root / APM_YML_FILENAME) + if declaration is None or declaration.spelling is None: + return list(KNOWN_TARGETS.values()), None + declared = declaration.restriction(allow_empty_singular=False) + if not declared: return list(KNOWN_TARGETS.values()), None canonical = dict.fromkeys(normalize_target_name(name) for name in declared) profiles = (KNOWN_TARGETS.get(name) for name in canonical) diff --git a/src/apm_cli/commands/install.py b/src/apm_cli/commands/install.py index da6740a978..5fab638e55 100644 --- a/src/apm_cli/commands/install.py +++ b/src/apm_cli/commands/install.py @@ -1866,6 +1866,9 @@ def _local_cleanup_pending(lockfile: "LockFile | None") -> bool: apm_count = 0 + from apm_cli.install.phases.targets import reject_undeployable_manifest_targets + + reject_undeployable_manifest_targets(apm_package, logger) # before the lockfile rename migrate_lockfile_if_needed(ctx.apm_dir) # Preserve MCP fields across APM lockfile regeneration, even with --only=apm. diff --git a/src/apm_cli/core/apm_yml.py b/src/apm_cli/core/apm_yml.py index 8e54a84e4a..d4c7c1a27e 100644 --- a/src/apm_cli/core/apm_yml.py +++ b/src/apm_cli/core/apm_yml.py @@ -13,8 +13,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from apm_cli.core.errors import ( ConflictingTargetsError, EmptyTargetsListError, @@ -24,9 +22,6 @@ ) from apm_cli.core.target_catalog import get_target_capability, manifest_target_names -if TYPE_CHECKING: - from pathlib import Path - # Canonical target names accepted by APM. CANONICAL_TARGETS: frozenset[str] = manifest_target_names() @@ -186,47 +181,3 @@ def parse_targets_field( # Neither key present return [] - - -def read_declared_target_names(root: Path) -> list[str] | None: - """Return target names declared by ``root/apm.yml``, else ``None``. - - Returns ``None`` only when the manifest is absent or its mapping contains - no target declaration, so callers can distinguish that fallback from a - present declaration. - - A manifest that exists is otherwise authoritative and its failures - propagate, because reporting "nothing declared" for a broken manifest would - silently widen a caller's target set on a typo, which is the failure mode - callers use this to avoid. Malformed YAML (including undecodable bytes) - arrives as ``yaml.YAMLError`` from :func:`~apm_cli.utils.yaml_io.load_yaml`, - an invalid ``targets:`` value raises out of :func:`parse_targets_field`, and - a document that is not a mapping is rejected the same way - :meth:`~apm_cli.models.apm_package.APMPackage.from_apm_yml` rejects it. - - Names are returned as written, so ``vscode`` comes back as ``vscode``. - Callers mapping them onto target profiles must first normalize through - :func:`~apm_cli.core.target_catalog.normalize_target_name`. - """ - import yaml - - from apm_cli.utils.yaml_io import load_yaml - - manifest_path = root / "apm.yml" - if manifest_path.is_symlink(): - raise OSError("apm.yml must be a regular, non-symlink file") - if not manifest_path.exists(): - return None - if not manifest_path.is_file(): - raise OSError("apm.yml must be a regular, non-symlink file") - data = load_yaml(manifest_path) - if data is None: - raise yaml.YAMLError("apm.yml must contain a YAML object, got an empty document") - if not isinstance(data, dict): - # Raised as YAMLError, not ValueError, so callers keep the single - # fail-closed ``except yaml.YAMLError`` that _bounded_load already - # normalizes its own non-parse failures into. - raise yaml.YAMLError(f"apm.yml must contain a YAML object, got {type(data)}") - if "target" not in data and "targets" not in data: - return None - return parse_targets_field(data, allow_empty_singular=False) diff --git a/src/apm_cli/core/target_detection.py b/src/apm_cli/core/target_detection.py index 7ec4679bfd..3201332386 100644 --- a/src/apm_cli/core/target_detection.py +++ b/src/apm_cli/core/target_detection.py @@ -1026,19 +1026,14 @@ def resolve_audit_target_decision( def read_manifest_target(project_root: Path) -> list[str] | None: """Read audit's manifest target hint; manifest checks own parse failures.""" - import yaml + from apm_cli.models.manifest_targets import read_manifest_target_declaration - from apm_cli.models.manifest_targets import manifest_target_restriction - from apm_cli.utils.yaml_io import load_yaml - - apm_yml = project_root / "apm.yml" - if not apm_yml.exists(): + declaration = read_manifest_target_declaration(project_root / "apm.yml", lenient=True) + if declaration is None: return None try: - data = load_yaml(apm_yml) or {} - tokens = manifest_target_restriction(data) - return tokens if tokens else None - except (OSError, ValueError, TypeError, yaml.YAMLError, click.UsageError): + return declaration.restriction() + except (ValueError, TypeError, click.UsageError): return None diff --git a/src/apm_cli/install/manifest_reconcile.py b/src/apm_cli/install/manifest_reconcile.py index 50c210b785..46ccb007fa 100644 --- a/src/apm_cli/install/manifest_reconcile.py +++ b/src/apm_cli/install/manifest_reconcile.py @@ -399,17 +399,13 @@ def declared_target_profiles( from apm_cli.core.errors import TargetResolutionError from apm_cli.core.target_catalog import normalize_target_name from apm_cli.integration.targets import KNOWN_TARGETS, scoped_profile_or_none - from apm_cli.models.manifest_targets import manifest_target_restriction - from apm_cli.utils.yaml_io import load_yaml + from apm_cli.models.manifest_targets import read_manifest_target_declaration - try: - data = load_yaml(project_root / "apm.yml") - except (AttributeError, KeyError, OSError, TypeError, ValueError): - return None - if not isinstance(data, dict): + declaration = read_manifest_target_declaration(project_root / "apm.yml", lenient=True) + if declaration is None: return None try: - names = manifest_target_restriction(data) + names = declaration.restriction() or [] except TargetResolutionError: return None active_by_name = _profiles_by_name(active_targets) diff --git a/src/apm_cli/install/phases/targets.py b/src/apm_cli/install/phases/targets.py index 9bbbab81b4..cf59e7194e 100644 --- a/src/apm_cli/install/phases/targets.py +++ b/src/apm_cli/install/phases/targets.py @@ -33,6 +33,20 @@ def _raise_target_usage_error(ctx: Any, exc: Exception) -> None: raise SystemExit(2) from exc +def reject_undeployable_manifest_targets(apm_package: Any, logger: Any) -> None: + """Exit 2 before any write when the manifest declares a target install cannot deploy.""" + from apm_cli.core.errors import TargetResolutionError + from apm_cli.models.apm_package import package_target_declaration + + try: + package_target_declaration(apm_package).validate_for_install() + except TargetResolutionError as exc: + if logger: + logger.error(str(exc), symbol="") + logger.render_summary() + raise SystemExit(2) from exc + + def _as_yaml_targets(value: str | list[str] | None) -> list[str] | None: """Normalize a package target value to the v2 yaml_targets shape.""" if value is None: diff --git a/src/apm_cli/install/pipeline.py b/src/apm_cli/install/pipeline.py index 8a2fd0b367..b793f8e4d5 100644 --- a/src/apm_cli/install/pipeline.py +++ b/src/apm_cli/install/pipeline.py @@ -435,17 +435,9 @@ def run_install_pipeline( # noqa: C901, PLR0913, PLR0915, RUF100 if scope is None: scope = InstallScope.PROJECT - # Reject manifest targets install cannot deploy before anything is written. - from ..core.errors import TargetResolutionError - from ..models.apm_package import package_target_declaration + from .phases.targets import reject_undeployable_manifest_targets - try: - package_target_declaration(apm_package).validate_for_install() - except TargetResolutionError as exc: - if logger: - logger.error(str(exc), symbol="") - logger.render_summary() - raise SystemExit(2) from exc + reject_undeployable_manifest_targets(apm_package, logger) # before any write apm_deps = apm_package.get_apm_dependencies() dev_apm_deps = apm_package.get_dev_apm_dependencies() diff --git a/src/apm_cli/models/manifest_targets.py b/src/apm_cli/models/manifest_targets.py index dab4cf07e4..ef55134b6c 100644 --- a/src/apm_cli/models/manifest_targets.py +++ b/src/apm_cli/models/manifest_targets.py @@ -105,12 +105,14 @@ def explicit(self) -> bool: """A valid, nonempty declaration that does not rely on legacy ``all``.""" return bool(self.selection) and not self.legacy_all - def restriction(self) -> list[str] | None: + def restriction(self, *, allow_empty_singular: bool = True) -> list[str] | None: """Declared names that restrict deployment, with legacy ``all`` folded. Validates with the plural vocabulary, so MCP-only and experimental tokens raise. Singular ``all`` folds without the plural deprecation warning because install expands it rather than treating it as omitted. + Authoritative readers pass ``allow_empty_singular=False`` so an empty + singular ``target:`` raises instead of meaning "nothing declared". """ data = dict(self.fields) if self.spelling == "target" and "targets" not in data and self.legacy_all: @@ -122,7 +124,7 @@ def restriction(self) -> list[str] | None: if remaining: parse_targets_field({"target": remaining}) return None - names = parse_targets_field(data) + names = parse_targets_field(data, allow_empty_singular=allow_empty_singular) return names or None def authored_names(self) -> list[str]: @@ -145,14 +147,15 @@ def prefill_names(self) -> list[str]: """ if self.spelling == "target" and self.legacy_all: from ..core.errors import TargetResolutionError - from ..core.target_detection import EffectiveTargetDecision + from ..core.target_catalog import expand_all try: selection = self.selection except (ValueError, TargetResolutionError): return self.authored_names() - if selection is not None: - return list(EffectiveTargetDecision(selection, "apm.yml").canonical_targets or ()) + if selection == _LEGACY_ALL_TARGET: + # Spelling-preserving, so ``vscode`` keeps its MCP destination. + return list(expand_all("install")) return self.authored_names() def validate_for_install(self) -> None: @@ -172,25 +175,38 @@ def read_manifest_target_declaration( *, lenient: bool = False, ) -> ManifestTargetDeclaration | None: - """Read and validate the target declaration of the apm.yml at *manifest_path*. - - Returns ``None`` when the file is absent. With *lenient*, unreadable or - invalid manifests also return ``None`` instead of raising. + """Load the target declaration of the apm.yml at *manifest_path*. + + Returns ``None`` when the file is absent. A strict read is authoritative: + a symlink, a non-file, or a document that is not a YAML mapping raises + (``OSError`` / ``yaml.YAMLError``), so a broken manifest never reads as + "nothing declared" and silently widens the caller's target set. With + *lenient*, unreadable or malformed manifests return ``None`` instead. + Tokens are validated when a view (``selection``, ``restriction()``) is read. """ - from ..core.errors import TargetResolutionError from ..utils.yaml_io import load_yaml - if not manifest_path.is_file(): - return None - try: - data = load_yaml(manifest_path) - declaration = ManifestTargetDeclaration.from_mapping(data, manifest_path) - _ = declaration.selection - except (OSError, ValueError, TypeError, yaml.YAMLError, TargetResolutionError): - if lenient: + if lenient: + try: + if not manifest_path.is_file(): + return None + data = load_yaml(manifest_path) + except (OSError, ValueError, TypeError, yaml.YAMLError): return None - raise - return declaration + if not isinstance(data, Mapping): + return None + return ManifestTargetDeclaration.from_mapping(data, manifest_path) + if manifest_path.is_symlink(): + raise OSError(f"{manifest_path.name} must be a regular, non-symlink file") + if not manifest_path.exists(): + return None + if not manifest_path.is_file(): + raise OSError(f"{manifest_path.name} must be a regular, non-symlink file") + data = load_yaml(manifest_path) + if not isinstance(data, Mapping): + got = "an empty document" if data is None else str(type(data)) + raise yaml.YAMLError(f"{manifest_path.name} must contain a YAML object, got {got}") + return ManifestTargetDeclaration.from_mapping(data, manifest_path) def manifest_target_restriction(data: Mapping[str, Any] | None) -> list[str]: diff --git a/tests/integration/test_target_declaration_adjacent_commands_lifecycle.py b/tests/integration/test_target_declaration_adjacent_commands_lifecycle.py index 5a1d11477e..b3636e9877 100644 --- a/tests/integration/test_target_declaration_adjacent_commands_lifecycle.py +++ b/tests/integration/test_target_declaration_adjacent_commands_lifecycle.py @@ -22,9 +22,13 @@ import pytest -from apm_cli.utils.yaml_io import load_yaml +from apm_cli.utils.yaml_io import dump_yaml, load_yaml from tests.integration._policy_scope_kit import output -from tests.integration._target_policy_kit import block_policy, target_policy_world +from tests.integration._target_policy_kit import ( + SELF_DEFINED_MCP, + block_policy, + target_policy_world, +) from tests.utils.local_github_https_fixture import openssl_executable pytestmark = [ @@ -135,3 +139,10 @@ def test_reinit_keeps_the_singular_all_deployment_set( f"re-init narrowed target: all from {expanded} to {after}:\n" f"{(project / 'apm.yml').read_text(encoding='utf-8')}" ) + # The rewritten spellings keep the MCP destination target: all had. + manifest = load_yaml(project / "apm.yml") or {} + manifest.setdefault("dependencies", {})["mcp"] = [dict(SELF_DEFINED_MCP)] + dump_yaml(manifest, project / "apm.yml") + tw.run(project, "install", step="4-mcp") + assert (project / ".vscode/mcp.json").is_file(), "re-init moved MCP off .vscode/mcp.json" + assert not (project / ".github/mcp.json").exists(), "re-init redirected MCP to .github" diff --git a/tests/integration/test_target_declaration_install_lifecycle.py b/tests/integration/test_target_declaration_install_lifecycle.py index b61f6e8c0c..ed6e810bf5 100644 --- a/tests/integration/test_target_declaration_install_lifecycle.py +++ b/tests/integration/test_target_declaration_install_lifecycle.py @@ -4,10 +4,11 @@ * A singular ``target:`` naming a harness that install cannot deploy (``intellij``, ``copilot-app``) is rejected before any write: no lockfile, - no deployed primitives, no ``.gitignore`` edit. + no deployed primitives, no ``.gitignore`` edit, in project and user scope. * A singular ``target: all`` keeps expanding to the install set (D1), and the MCP phase no longer claims the field is "treated as omitted" in the same - run (F10). A plural ``targets: [all]`` still folds, with the warning. + run (F10); neither does ``apm compile -g``. A plural ``targets: [all]`` + still folds, with the warning. * The MCP destination depends on the runtime spelling, identically for ``target:`` and ``targets:``: ``vscode`` writes ``.vscode/mcp.json`` and ``copilot`` writes ``.github/mcp.json`` (F12, regression lock). @@ -45,6 +46,10 @@ def test_undeployable_singular_target_is_rejected_before_any_write( ) -> None: with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: project = tw.consumer("consumer", {"target": token}) + # A legacy lockfile must not be migrated by a rejected install either. + (project / "apm.lock").write_text( + 'lockfile_version: "1"\ndependencies: []\n', encoding="utf-8" + ) before = tree_snapshot(project) result = tw.run(project, "install", step="1-install", expected=(1, 2)) assert result.returncode == 2, output(result) @@ -56,6 +61,26 @@ def test_undeployable_singular_target_is_rejected_before_any_write( assert not (project / ".agents").exists() +@pytest.mark.parametrize("token", ["intellij", "copilot-app"]) +def test_user_scope_undeployable_singular_target_is_rejected_before_any_write( + token: str, tmp_path: Path, apm_binary_path: Path +) -> None: + with target_policy_world(tmp_path, apm_binary_path, block_policy()) as tw: + isolated = tw.world.isolated + manifest = {"name": "user", "version": "0.1.0", "target": token} + manifest["dependencies"] = {"apm": ["contoso/pkg-a#v1.0.0"]} + dump_yaml(manifest, isolated.config_root / "apm.yml") + before = tree_snapshot(isolated.home) + result = tw.run(isolated.work_root, "install", "-g", step="1-install-g", expected=(1, 2)) + assert result.returncode == 2, output(result) + assert token in output(result), output(result) + changed = changed_paths(before, tree_snapshot(isolated.home)) + # CLI bookkeeping (its config and lifecycle locks) is not deployment output. + infra = ("config.json", ".apm-lifecycle.lock") + assert [path for path in changed if not path.endswith(infra)] == [], changed + assert not (isolated.config_root / "apm.lock.yaml").exists() + + def test_singular_all_expands_without_claiming_it_was_omitted( tmp_path: Path, apm_binary_path: Path ) -> None: @@ -162,3 +187,6 @@ def test_user_scope_singular_all_expands_without_claiming_it_was_omitted( assert TREATED_AS_OMITTED not in " ".join(output(result).split()), output(result) assert (isolated.home / ".claude/skills/pkg-a-skill/SKILL.md").is_file() assert (isolated.home / ".config/opencode/skills/pkg-a-skill/SKILL.md").is_file() + # compile -g reads the same declaration through the owner (#3791 F10). + result = tw.run(isolated.work_root, "compile", "-g", step="2-compile-g") + assert TREATED_AS_OMITTED not in " ".join(output(result).split()), output(result) diff --git a/tests/unit/install/test_drift_detection.py b/tests/unit/install/test_drift_detection.py index 964781c1cf..02bc315d2e 100644 --- a/tests/unit/install/test_drift_detection.py +++ b/tests/unit/install/test_drift_detection.py @@ -356,7 +356,7 @@ def test_apm_yml_with_targets_list_returns_list(self, tmp_path: Path) -> None: def test_parse_targets_field_exception_returns_none(self, tmp_path: Path) -> None: (tmp_path / "apm.yml").write_text("name: pkg\ntarget: copilot\n", encoding="utf-8") with patch( - "apm_cli.core.apm_yml.parse_targets_field", + "apm_cli.models.manifest_targets.parse_targets_field", side_effect=ValueError("bad"), ): result = _read_apm_yml_target(tmp_path) diff --git a/tests/unit/install/test_drift_phase3.py b/tests/unit/install/test_drift_phase3.py index def24297cd..cf23523aaf 100644 --- a/tests/unit/install/test_drift_phase3.py +++ b/tests/unit/install/test_drift_phase3.py @@ -376,7 +376,7 @@ def test_apm_yml_with_singular_target_returns_list(self, tmp_path: Path) -> None def test_parse_targets_field_exception_returns_none(self, tmp_path: Path) -> None: (tmp_path / "apm.yml").write_text("name: pkg\ntarget: copilot\n", encoding="utf-8") with patch( - "apm_cli.core.apm_yml.parse_targets_field", + "apm_cli.models.manifest_targets.parse_targets_field", side_effect=ValueError("bad"), ): result = _read_apm_yml_target(tmp_path) diff --git a/tests/unit/models/test_manifest_targets.py b/tests/unit/models/test_manifest_targets.py index 7540d443d7..2e0fb037e1 100644 --- a/tests/unit/models/test_manifest_targets.py +++ b/tests/unit/models/test_manifest_targets.py @@ -5,9 +5,14 @@ from pathlib import Path import pytest +import yaml from apm_cli.core import apm_yml -from apm_cli.core.errors import ConflictingTargetsError, UnknownTargetError +from apm_cli.core.errors import ( + ConflictingTargetsError, + EmptyTargetsListError, + UnknownTargetError, +) from apm_cli.core.target_detection import EffectiveTargetDecision from apm_cli.models.apm_package import ( APMPackage, @@ -132,10 +137,42 @@ def test_path_reader_is_lenient_only_on_request(tmp_path: Path): dump_yaml({"name": "p", "version": "1.0.0", "targets": ["nope"]}, manifest) assert read_manifest_target_declaration(tmp_path / "missing.yml") is None - assert read_manifest_target_declaration(manifest, lenient=True) is None + # Tokens are validated when a view is read, not when the file is loaded. + declaration = read_manifest_target_declaration(manifest) with pytest.raises(UnknownTargetError): + declaration.restriction() + + manifest.write_text("- not\n- a mapping\n", encoding="utf-8") + assert read_manifest_target_declaration(manifest, lenient=True) is None + with pytest.raises(yaml.YAMLError, match="must contain a YAML object"): read_manifest_target_declaration(manifest) + manifest.write_text("targets: [claude\n", encoding="utf-8") + assert read_manifest_target_declaration(manifest, lenient=True) is None + with pytest.raises(yaml.YAMLError): + read_manifest_target_declaration(manifest) + + +def test_strict_path_reader_refuses_symlinked_manifest(tmp_path: Path): + real = tmp_path / "real.yml" + dump_yaml({"name": "p", "version": "1.0.0", "targets": ["claude"]}, real) + link = tmp_path / "apm.yml" + try: + link.symlink_to(real) + except OSError: + pytest.skip("symlinks unavailable") + + with pytest.raises(OSError, match="non-symlink"): + read_manifest_target_declaration(link) + assert read_manifest_target_declaration(link, lenient=True).restriction() == ["claude"] + + +def test_strict_restriction_rejects_an_empty_singular_target(): + declaration = _declaration(target=None) + assert declaration.restriction() is None + with pytest.raises(EmptyTargetsListError): + declaration.restriction(allow_empty_singular=False) + def test_stand_in_packages_route_through_the_owner(): class _StandIn: @@ -144,3 +181,12 @@ class _StandIn: assert package_target_selection(_StandIn()) == ["claude", "cursor"] assert manifest_target_restriction({"target": "claude,cursor"}) == ["claude", "cursor"] assert manifest_target_restriction(None) == [] + + +def test_reinit_prefill_expands_singular_all_with_install_spellings(): + """Re-init writes the spellings install deploys, so MCP keeps .vscode/mcp.json.""" + names = _declaration(target="all").prefill_names() + assert len(names) > 1 + assert "vscode" in names + assert "copilot" not in names + assert _declaration(targets=["all"]).prefill_names() == ["all"] From 80f6976e7c99358aa2596c0ea87dba7f7e91ee52 Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 20:32:27 +0100 Subject: [PATCH 09/10] fix(targets): close delta-panel gaps in exemption scope and strict reads A marker on a block's first body line still exempted raw reads in the enclosing if/for/with header, because comment lines between a header and its body counted as header lines. Those lines now belong to the body, and match blocks end their header at the first case. compile -g silently compiled every harness for singular target: all,, which install -g rejects; restriction(strict=True) (renamed from allow_empty_singular) now raises the same "all cannot be combined" error. A direct run_install_pipeline test pins the pipeline's own pre-write gate, which the CLI's earlier call otherwise hides. Addresses delta panel findings (python-architect, test-coverage-expert) on #3791. apm-spec-waiver: routes existing manifest target readers through one owner; OpenAPM-observable acceptance is unchanged Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../checks/registry_owner_guards.py | 5 +++++ src/apm_cli/commands/compile/cli.py | 2 +- src/apm_cli/models/manifest_targets.py | 19 ++++++++++++---- .../test_architecture_owner_rule_mutations.py | 9 ++++++++ tests/unit/install/test_pipeline_preflight.py | 22 +++++++++++++++++++ tests/unit/models/test_manifest_targets.py | 12 +++++++++- 6 files changed, 63 insertions(+), 6 deletions(-) diff --git a/scripts/architecture_linter/checks/registry_owner_guards.py b/scripts/architecture_linter/checks/registry_owner_guards.py index fb1760c72f..2997b0fa08 100644 --- a/scripts/architecture_linter/checks/registry_owner_guards.py +++ b/scripts/architecture_linter/checks/registry_owner_guards.py @@ -361,8 +361,13 @@ def _target_exemption(index: TreeIndex, node: ast.AST, lines: tuple[str, ...]) - first = anchor.lineno last = getattr(anchor, "end_lineno", None) or first body = getattr(anchor, "body", None) + if isinstance(anchor, ast.Match) and anchor.cases: + body = [anchor.cases[0].pattern] if isinstance(anchor, ast.stmt) and isinstance(body, list) and body: last = max(first, body[0].lineno - 1) + # Comments between a header and its body belong to the body. + while last > first and lines[last - 1].lstrip()[:1] in {"", "#"}: + last -= 1 candidates = list(range(first, last + 1)) if 1 < first <= len(lines) + 1 and lines[first - 2].lstrip().startswith("#"): candidates.append(first - 1) diff --git a/src/apm_cli/commands/compile/cli.py b/src/apm_cli/commands/compile/cli.py index 1b38e016f5..0de6f50127 100644 --- a/src/apm_cli/commands/compile/cli.py +++ b/src/apm_cli/commands/compile/cli.py @@ -389,7 +389,7 @@ def _global_compile_targets(source_root: Path) -> tuple[list[TargetProfile], lis declaration = read_manifest_target_declaration(source_root / APM_YML_FILENAME) if declaration is None or declaration.spelling is None: return list(KNOWN_TARGETS.values()), None - declared = declaration.restriction(allow_empty_singular=False) + declared = declaration.restriction(strict=True) if not declared: return list(KNOWN_TARGETS.values()), None canonical = dict.fromkeys(normalize_target_name(name) for name in declared) diff --git a/src/apm_cli/models/manifest_targets.py b/src/apm_cli/models/manifest_targets.py index ef55134b6c..ef50b90f0f 100644 --- a/src/apm_cli/models/manifest_targets.py +++ b/src/apm_cli/models/manifest_targets.py @@ -105,14 +105,15 @@ def explicit(self) -> bool: """A valid, nonempty declaration that does not rely on legacy ``all``.""" return bool(self.selection) and not self.legacy_all - def restriction(self, *, allow_empty_singular: bool = True) -> list[str] | None: + def restriction(self, *, strict: bool = False) -> list[str] | None: """Declared names that restrict deployment, with legacy ``all`` folded. Validates with the plural vocabulary, so MCP-only and experimental tokens raise. Singular ``all`` folds without the plural deprecation warning because install expands it rather than treating it as omitted. - Authoritative readers pass ``allow_empty_singular=False`` so an empty - singular ``target:`` raises instead of meaning "nothing declared". + Authoritative readers pass ``strict=True``: an empty singular + ``target:`` and a singular ``all`` combined with other targets raise, + as they do for install, instead of meaning "nothing declared". """ data = dict(self.fields) if self.spelling == "target" and "targets" not in data and self.legacy_all: @@ -123,10 +124,20 @@ def restriction(self, *, allow_empty_singular: bool = True) -> list[str] | None: ] if remaining: parse_targets_field({"target": remaining}) + if strict: + self._raise_invalid_selection() return None - names = parse_targets_field(data, allow_empty_singular=allow_empty_singular) + names = parse_targets_field(data, allow_empty_singular=not strict) return names or None + def _raise_invalid_selection(self) -> None: + from ..core.errors import TargetResolutionError + + try: + _ = self.selection + except ValueError as exc: + raise TargetResolutionError(str(exc)) from exc + def authored_names(self) -> list[str]: """Unvalidated names as written, ``targets:`` first (for prompts only).""" data = dict(self.fields) diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index d6725374b3..56c8104bd1 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -3074,6 +3074,15 @@ def test_policy_target_projection_guard_rejects_raw_selections( ' leaked = lockfile.get("targets")\n', id="trailing-marker-does-not-cover-next-line", ), + pytest.param( + "src/apm_cli/install/target_filter.py", + ' package = getattr(package_source, "package", package_source)\n', + ' package = getattr(package_source, "package", package_source)\n' + " if package.targets:\n" + " # architecture-authority-exempt: bootstrap-writer\n" + " pass\n", + id="body-marker-does-not-cover-header", + ), pytest.param( "src/apm_cli/install/target_filter.py", ' package = getattr(package_source, "package", package_source)\n', diff --git a/tests/unit/install/test_pipeline_preflight.py b/tests/unit/install/test_pipeline_preflight.py index c0e85a77dc..eea0a9bbfb 100644 --- a/tests/unit/install/test_pipeline_preflight.py +++ b/tests/unit/install/test_pipeline_preflight.py @@ -456,3 +456,25 @@ def test_materialization_collision_is_not_double_wrapped( with pytest.raises(error_type) as raised: run_install_pipeline(pkg, target="claude") assert raised.value is collision + + +@pytest.mark.parametrize("token", ["intellij", "copilot-app"]) +def test_pipeline_rejects_undeployable_manifest_target_before_any_write( + token: str, tmp_path, monkeypatch +) -> None: + """Direct pipeline callers get the CLI promise: exit 2 before writing anything.""" + from apm_cli.install.pipeline import run_install_pipeline + from apm_cli.models.apm_package import APMPackage + from apm_cli.utils.yaml_io import dump_yaml + + manifest = tmp_path / "apm.yml" + dump_yaml({"name": "p", "version": "1.0.0", "target": token}, manifest) + pkg = APMPackage.from_apm_yml(manifest) + monkeypatch.chdir(tmp_path) + before = sorted(p.relative_to(tmp_path).as_posix() for p in tmp_path.rglob("*")) + + with pytest.raises(SystemExit) as excinfo: + run_install_pipeline(pkg) + + assert excinfo.value.code == 2 + assert sorted(p.relative_to(tmp_path).as_posix() for p in tmp_path.rglob("*")) == before diff --git a/tests/unit/models/test_manifest_targets.py b/tests/unit/models/test_manifest_targets.py index 2e0fb037e1..d736e58b28 100644 --- a/tests/unit/models/test_manifest_targets.py +++ b/tests/unit/models/test_manifest_targets.py @@ -11,6 +11,7 @@ from apm_cli.core.errors import ( ConflictingTargetsError, EmptyTargetsListError, + TargetResolutionError, UnknownTargetError, ) from apm_cli.core.target_detection import EffectiveTargetDecision @@ -171,7 +172,16 @@ def test_strict_restriction_rejects_an_empty_singular_target(): declaration = _declaration(target=None) assert declaration.restriction() is None with pytest.raises(EmptyTargetsListError): - declaration.restriction(allow_empty_singular=False) + declaration.restriction(strict=True) + + +def test_strict_restriction_rejects_singular_all_combined_with_targets(): + """compile -g agrees with install: ``all`` cannot be combined with other targets.""" + declaration = _declaration(target="all,claude") + assert declaration.restriction() is None + with pytest.raises(TargetResolutionError, match="all"): + declaration.restriction(strict=True) + assert _declaration(target="all").restriction(strict=True) is None def test_stand_in_packages_route_through_the_owner(): From 0d20c6c5f66f264c79ed84f10936653839d74e1f Mon Sep 17 00:00:00 2001 From: danielmeppiel Date: Tue, 17 Nov 2026 20:37:18 +0100 Subject: [PATCH 10/10] chore(changelog): place #3774 entry away from the section head Avoids landing-order conflicts with other queued PRs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7933a7fb5b..17f570466f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- `compilation.target` policy now judges the targets a project actually selects: `apm audit` reads plural `targets:` (non-compliant manifests that `apm install` already blocked now also fail audit), CSV values such as `target: "claude,copilot"` are split, aliases compare as the target they deploy (`vscode` and `agents` are `copilot`) on both the manifest and policy side, `allow: [all]` allows every target, and inherited alias allow lists no longer merge to "allow nothing". Plural-key tests ported from #3739 -- by @MohammedAlkindi (#3774) - After `apm install --legacy-skill-paths`, `apm audit --ci` no longer reports the per-client skills (`.github/skills/`, `~/.copilot/skills/`) as drift, and `apm uninstall` keeps surviving skills in that layout instead of copying them into `.agents/skills/` and removes an uninstalled package's legacy-layout skills; both reuse the layout recorded in `apm.lock.yaml`. (#3793) +- `compilation.target` policy now judges the targets a project actually selects: `apm audit` reads plural `targets:` (non-compliant manifests that `apm install` already blocked now also fail audit), CSV values such as `target: "claude,copilot"` are split, aliases compare as the target they deploy (`vscode` and `agents` are `copilot`) on both the manifest and policy side, `allow: [all]` allows every target, and inherited alias allow lists no longer merge to "allow nothing". Plural-key tests ported from #3739 -- by @MohammedAlkindi (#3774) ## [0.36.0] - 2026-11-17