Skip to content
Merged
7 changes: 7 additions & 0 deletions .apm/architecture/owners/hooks-integrations.json
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@
"selectors": ["src/apm_cli/adapters/client/intellij.py"],
"guards": ["hooks-integrations-jetbrains-mcp-path"]
},
{
"id": "claude-mcp-config-paths",
"decision": "Claude user-scope MCP config path",
"owner": "adapters/client/claude.py (ClaudeClientAdapter.resolve_user_claude_json_path)",
"selectors": ["src/apm_cli/adapters/client/claude.py"],
"guards": ["hooks-integrations-claude-mcp-paths"]
},
{
"id": "copilot-cli-mcp-config-paths",
"decision": "Copilot CLI MCP config paths",
Expand Down
3 changes: 2 additions & 1 deletion CONFORMANCE.json
Original file line number Diff line number Diff line change
Expand Up @@ -1424,8 +1424,9 @@
"keyword": "MUST",
"section": "8.5",
"status": "active",
"test_count": 1,
"test_count": 2,
"tests": [
"tests/spec_conformance/test_claude_cleanup_roots.py::test_claude_cleanup_writes_only_to_selected_registered_root",
"tests/spec_conformance/test_manifest_reqs.py::test_consumer_deploys_only_under_registered_roots"
]
},
Expand Down
2 changes: 1 addition & 1 deletion CONFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ APM claims the proposed deployed-prompt-audit capability (req-pl-019, req-pl-020
| [req-sc-014](docs/src/content/docs/specs/openapm-v0.1.md#req-sc-014) | MUST | 10.15 | consumer | active | 1 | - |
| [req-sc-015](docs/src/content/docs/specs/openapm-v0.1.md#req-sc-015) | MUST | 10.16 | consumer | active | 5 | tests/fixtures/spec-conformance/source-plan/req-sc-015.json |
| [req-tg-001](docs/src/content/docs/specs/openapm-v0.1.md#req-tg-001) | MUST | 8.4 | consumer | active | 1 | - |
| [req-tg-002](docs/src/content/docs/specs/openapm-v0.1.md#req-tg-002) | MUST | 8.5 | consumer | active | 1 | - |
| [req-tg-002](docs/src/content/docs/specs/openapm-v0.1.md#req-tg-002) | MUST | 8.5 | consumer | active | 2 | - |
| [req-tg-003](docs/src/content/docs/specs/openapm-v0.1.md#req-tg-003) | MUST | 8.5 | consumer | active | 1 | - |
| [req-tg-004](docs/src/content/docs/specs/openapm-v0.1.md#req-tg-004) | MUST | 4.2.1 | consumer | active | 1 | - |
| [req-tg-005](docs/src/content/docs/specs/openapm-v0.1.md#req-tg-005) | MUST | 8.5 | consumer | active | 1 | - |
Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/docs/consumer/install-mcp-servers.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ user-scope MCP config (for example, Copilot CLI to
`$COPILOT_HOME/mcp-config.json` when `COPILOT_HOME` is set, otherwise
`~/.copilot/mcp-config.json`; Claude Code to
`$CLAUDE_CONFIG_DIR/.claude.json` when `CLAUDE_CONFIG_DIR` is set to a
non-whitespace absolute path. Unset or blank values use `~/.claude.json`;
non-whitespace absolute path (both for installation and stale server cleanup). Unset or blank values use `~/.claude.json`;
relative values are rejected. Codex CLI writes to
`$CODEX_HOME/config.toml` when `CODEX_HOME` is set to a non-whitespace value or
`~/.codex/config.toml` otherwise, Cursor to `~/.cursor/mcp.json`, OpenCode to
Expand Down
1 change: 1 addition & 0 deletions docs/src/content/docs/reference/cli/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ in `apm.yml`, then run `apm install` again.
- **Required service writes fail loudly.** If MCP or LSP work is declared but no target can be resolved, install exits non-zero before changing the manifest, package deployment, or native service config. A native MCP/LSP config write failure also exits non-zero with the failed target and a permissions/path next step. A successful direct `--mcp` add never reports `Install interrupted`.
- **Direct registry lookup fails closed.** Registry-form MCP entries (`apm install --mcp NAME` with no `--url` and no post-`--` command) resolve one unique registry identity before writing the manifest or user config. An unreachable registry, missing identity, or ambiguous bare server name exits non-zero without changing state.
- **Diff-aware.** Packages whose ref or version changed in `apm.yml` are re-downloaded automatically. MCP servers with matching config are skipped (`already configured`); changed config is re-applied (`updated`).
- **Claude Code profiles.** For user-scope MCP installs, an absolute `CLAUDE_CONFIG_DIR` selects that profile's `.claude.json` for both installation and stale-server cleanup. Removing an APM-managed server in the selected profile preserves other profiles and user-owned entries. Cleanup refuses symlinked config files or profile directories; replace the link with a regular file or directory before retrying.
- **Transactional replacement.** `--update` and `--refresh` download package
replacements to isolated staging paths and validate them before publication.
If download, validation, or activation fails, APM keeps the previous package
Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/docs/reference/environment-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ APM verifies HTTPS against the operating-system trust store by default. For the
| `APM_BROAD_FETCH_DEPTH` | Maximum commit depth used by the bare-cache broad fetch when resolving git refs. | `50` | Integer-like string; tune for very deep histories where ref resolution misses. |
| `XDG_CACHE_HOME` | Standard XDG base-directory variable APM consults when `APM_CACHE_DIR` is unset (Linux / macOS). | unset | Honoured per the XDG spec. |
| `LOCALAPPDATA` | Standard Windows variable APM consults when `APM_CACHE_DIR` is unset. | OS-provided | Used to derive the default Windows cache path. |
| `CLAUDE_CONFIG_DIR` | Override the user-scope destination Claude reads for skills, agents, and MCP config. | Claude default | For MCP config, nonblank values must be absolute. User-scope MCP servers are written to `$CLAUDE_CONFIG_DIR/.claude.json`; when unset or blank, APM uses `~/.claude.json`. |
| `CLAUDE_CONFIG_DIR` | Override the user-scope destination Claude reads for skills, agents, and MCP config. | Claude default | For MCP config, nonblank values must be absolute. User-scope MCP servers are managed in `$CLAUDE_CONFIG_DIR/.claude.json` (including installation and stale cleanup); when unset or blank, APM uses `~/.claude.json`. |

## Policy

Expand Down
6 changes: 6 additions & 0 deletions packages/apm-guide/.apm/skills/apm-usage/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,12 @@ JetBrains Copilot MCP writes use
(`XDG_CONFIG_HOME` defaults to `~/.config`). Reinstalling an older APM-managed
entry migrates only provenance-owned servers from the obsolete data path.

For user-scope Claude MCP installs, an absolute `CLAUDE_CONFIG_DIR` selects the
profile's `.claude.json` for both installation and stale-server cleanup.
Removing managed servers from the selected profile preserves other profiles and
user-owned entries. Cleanup refuses symlinked config files or profile directories;
replace the link with a regular file or directory before retrying.

`apm install` prints a one-line provenance summary before any mutation:

```
Expand Down
54 changes: 53 additions & 1 deletion scripts/architecture_linter/checks/mutation_hook_contract.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Neutral-hook-contract and hook-command-vocabulary mutation analyzers.

Ports three of the owner guards recorded in
Ports the owner guards recorded in
``.apm/architecture/owners/hooks-integrations.json``:

* ``hooks-integrations-copilot-cli-mcp-paths`` -- AC1 Copilot CLI MCP paths
owner.
* ``hooks-integrations-claude-mcp-paths`` -- Claude user MCP path owner.
* ``hooks-integrations-neutral-hook-contract`` -- AC2/AC6/AC15c/AC4 hook
grammar, per-target shape, validate-before-write ordering, drift
projection (incl. ``check_hook_file_routing_owner`` and
Expand Down Expand Up @@ -333,6 +334,50 @@ def _check_copilot_cli_mcp_paths(provider: FactsProvider) -> Iterable[Violation]
return findings


def _check_claude_mcp_paths(provider: FactsProvider) -> Iterable[Violation]:
"""Claude user cleanup must check the adapter's path before normalization."""
rule_id = "mutation_writes.claude_mcp_paths"
owner = "src/apm_cli/adapters/client/claude.py"
facts_by_path, failures = _read_required(provider, rule_id, (owner, _MCP_INTEGRATOR))
if failures:
return failures
consumer = facts_by_path[_MCP_INTEGRATOR]
calls = [call for call in consumer.calls if call.scope == "remove_stale"]
raw = [
call.line
for call in calls
if call.qualname == "ClaudeClientAdapter.resolve_user_claude_unresolved_path"
]
resolved = [
call.line
for call in calls
if call.qualname == "ClaudeClientAdapter.resolve_user_claude_json_path"
]
guarded = len(raw) == len(resolved) == 1 and any(
call.qualname == "_reject_symlink_config" and raw[0] < call.line < resolved[0]
for call in calls
)
hardcoded = any(
literal.scope == "remove_stale"
and literal.value_repr in {repr(".claude.json"), repr("CLAUDE_CONFIG_DIR")}
for literal in consumer.literals
)
return (
*_require(
_has_fixed(facts_by_path[owner], "CLAUDE_CONFIG_DIR"),
rule_id,
owner,
"Claude adapter must own the CLAUDE_CONFIG_DIR MCP config root",
),
*_require(
guarded and not hardcoded,
rule_id,
_MCP_INTEGRATOR,
"Claude user cleanup must check the adapter-selected path before normalization",
),
)


def _check_neutral_hook_contract(provider: FactsProvider) -> Iterable[Violation]:
"""Neutral hook source grammar, per-target shape, and drift projection.

Expand Down Expand Up @@ -854,6 +899,13 @@ def _check_hook_command_vocabulary(provider: FactsProvider) -> Iterable[Violatio


RULES: tuple[Rule, ...] = (
Rule(
id="mutation_writes.claude_mcp_paths",
group=GROUP,
guard_ids=("hooks-integrations-claude-mcp-paths",),
description="Claude user MCP config paths must come from the Claude adapter.",
check=_check_claude_mcp_paths,
),
Rule(
id="mutation_writes.copilot_cli_mcp_paths",
group=GROUP,
Expand Down
22 changes: 20 additions & 2 deletions src/apm_cli/adapters/client/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,12 @@ def _is_user_scope(self) -> bool:
def _project_mcp_path(self) -> Path:
return self.project_root / ".mcp.json"

def _user_claude_json_path(self) -> Path:
@classmethod
def resolve_user_claude_unresolved_path(cls) -> Path:
"""Return the un-normalized path for user-scope Claude Code config.

Used for symlink pre-checks before canonical resolution.
"""
config_dir = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()
if config_dir:
config_path = Path(config_dir).expanduser()
Expand All @@ -193,9 +198,22 @@ def _user_claude_json_path(self) -> Path:
"CLAUDE_CONFIG_DIR must be an absolute path for user-scope MCP "
"config; set an absolute path or unset it to use ~/.claude.json."
)
return config_path.resolve(strict=False) / ".claude.json"
return config_path / ".claude.json"
return Path.home() / ".claude.json"

@classmethod
def resolve_user_claude_json_path(cls, unresolved_path: Path | None = None) -> Path:
"""Resolve the selected destination, optionally reusing a checked path."""
path = (
unresolved_path
if unresolved_path is not None
else cls.resolve_user_claude_unresolved_path()
)
return path.parent.resolve(strict=False) / path.name

def _user_claude_json_path(self) -> Path:
return self.resolve_user_claude_json_path()

def _should_write_project(self) -> bool:
return (self.project_root / ".claude").is_dir()

Expand Down
45 changes: 38 additions & 7 deletions src/apm_cli/integration/mcp_integrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ def _clean_claude_config(
logger,
is_user_scope: bool = False,
fail_on_write_error: bool = False,
label: str | None = None,
) -> int:
"""Remove stale entries from a Claude Code JSON config file.

Expand All @@ -310,11 +311,14 @@ def _clean_claude_config(
logger: Command logger for progress messages.
is_user_scope: When True, validates that the top-level config is a dict
(``~/.claude.json`` guard) and uses the user-scope log label.
fail_on_write_error: When True, raise RequiredIntegrationError on write failure.
label: Optional human-readable config label used in log messages.

Returns:
Number of entries removed.
"""
label = "~/.claude.json" if is_user_scope else ".mcp.json"
if label is None:
label = str(config_path) if is_user_scope else ".mcp.json"
if (
_reject_symlink_config(
config_path,
Expand Down Expand Up @@ -758,12 +762,14 @@ def remove_stale(
target_runtimes = supported

# Claude Code: when scope is unspecified, fail safely toward the project
# config only -- never touch ~/.claude.json on the user's behalf without
# config only -- never touch user config on the user's behalf without
# an explicit USER scope, since that file is shared across all Claude
# Code projects on the host.
clean_claude_project = "claude" in target_runtimes and scope is not InstallScope.USER
clean_claude_user = "claude" in target_runtimes and scope is InstallScope.USER
if "claude" in target_runtimes and scope is None:
clean_claude_user = "claude" in target_runtimes and (
scope is InstallScope.USER or user_scope
)
clean_claude_project = "claude" in target_runtimes and not clean_claude_user
if "claude" in target_runtimes and scope is None and not user_scope:
logger.progress(
"Claude Code stale cleanup: scope unspecified -- defaulting to "
"project .mcp.json only; pass -g/--global to also clean ~/.claude.json"
Expand Down Expand Up @@ -965,14 +971,39 @@ def remove_stale(
fail_on_write_error=fail_on_write_error,
)

# Clean Claude Code user ~/.claude.json (USER scope only)
# Clean Claude Code user ~/.claude.json or $CLAUDE_CONFIG_DIR/.claude.json (USER scope only)
if clean_claude_user:
from apm_cli.adapters.client.claude import ClaudeClientAdapter

claude_label = "Claude user config"
try:
unresolved_cfg = ClaudeClientAdapter.resolve_user_claude_unresolved_path()
claude_label = str(unresolved_cfg)
if _reject_symlink_config(
unresolved_cfg,
claude_label,
logger,
fail_on_write_error=fail_on_write_error,
):
return
claude_cfg = ClaudeClientAdapter.resolve_user_claude_json_path(unresolved_cfg)
except Exception as exc:
_log.debug("Failed to resolve Claude user-scope config path", exc_info=True)
if fail_on_write_error:
from apm_cli.install.errors import RequiredIntegrationError

raise RequiredIntegrationError(
_cleanup_failure_message(claude_label, exc)
) from exc
return

_clean_claude_config(
Path.home() / ".claude.json",
claude_cfg,
expanded_stale,
logger,
is_user_scope=True,
fail_on_write_error=fail_on_write_error,
label=claude_label,
)

# ------------------------------------------------------------------
Expand Down
26 changes: 26 additions & 0 deletions tests/integration/test_architecture_owner_rule_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,14 @@ class MutationCase:
new="def _hand_authored_root_context_blocks_write_disabled(",
intent="Root context writes lose the canonical hand-authored ownership gate.",
),
MutationCase(
guard_id="hooks-integrations-claude-mcp-paths",
rule_id="mutation_writes.claude_mcp_paths",
path="src/apm_cli/integration/mcp_integrator.py",
old="claude_cfg = ClaudeClientAdapter.resolve_user_claude_json_path(unresolved_cfg)",
new='claude_cfg = Path.home() / ".claude.json"',
intent="Claude user cleanup bypasses the adapter-selected profile path.",
),
MutationCase(
guard_id="hooks-integrations-copilot-cli-mcp-paths",
rule_id="mutation_writes.copilot_cli_mcp_paths",
Expand Down Expand Up @@ -1387,6 +1395,24 @@ def test_owner_rules_report_nothing_before_mutation(
assert baseline_violated_rule_ids == frozenset()


def test_claude_cleanup_guard_preserves_unresolved_path_check() -> None:
"""The profile-path guard catches normalization before symlink inspection."""
path = "src/apm_cli/integration/mcp_integrator.py"
source = _source(path)
old = "unresolved_cfg = ClaudeClientAdapter.resolve_user_claude_unresolved_path()"
new = "unresolved_cfg = ClaudeClientAdapter.resolve_user_claude_json_path()"
assert source.count(old) == 1
report = run_selected_rules(
ROOT,
("mutation_writes.claude_mcp_paths",),
source_overrides={path: source.replace(old, new)},
)
assert report.failures == ()
assert any(
violation.rule_id == "mutation_writes.claude_mcp_paths" for violation in report.violations
)


def test_orphan_selection_guard_rejects_warning_bypass() -> None:
"""The shared-selector rule protects warnings as well as destructive pruning."""
path = "src/apm_cli/commands/_helpers.py"
Expand Down
Loading
Loading