Skip to content

fix(mcp): preserve declared self-defined server names containing slashes - #3493

Merged
Daniel Meppiel (danielmeppiel) merged 9 commits into
microsoft:mainfrom
bodapatisaikrishna:fix/preserve-self-defined-mcp-server-names
Nov 11, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 9 commits into
microsoft:mainfrom
bodapatisaikrishna:fix/preserve-self-defined-mcp-server-names

Conversation

@bodapatisaikrishna

@bodapatisaikrishna Sai krishna Bodapati (bodapatisaikrishna) commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Description

Self-defined MCP servers whose names contain slashes (such as reverse-DNS names like com.azure.dev/mcp-remote-azure-devops) were getting truncated to their final segment when materializing client harness configurations, colliding with other entries and failing private registry policy checks. This marks self-defined entries so their declared names are preserved across client adapters while keeping the historical owner/repo -> repo basename fallback for registry dependencies.

Issue and approved scope

Issue: #3456

Scope record (apm-scope:v1, approved by Daniel Meppiel (@danielmeppiel)): #3456 (comment)

Does this PR complete the issue, or what remains?
Completes #3456.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor

Testing

  • Tested locally
  • All existing tests pass
  • Added tests for new functionality (if applicable)

Spec conformance (OpenAPM v0.1)

  • Spec edit: docs/src/content/docs/specs/openapm-v0.1.md updated
    (new/changed <a id="req-XXX"></a> anchor + prose + Appendix C
    row).
  • Manifest edit: docs/src/content/docs/specs/manifests/openapm-v0.1.requirements.yml
    updated.
  • Test edit: a @pytest.mark.req("req-XXX") test under
    tests/spec_conformance/ added or extended.
  • CONFORMANCE.{md,json} regenerated via
    uv run --extra dev python -m tests.spec_conformance.gen_statement
    and committed.
  • N/A -- this PR does not change OpenAPM-observable behaviour.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The change leaves config_key uninitialized when registry lookup fails, causing UnboundLocalError, and duplicates centralized naming logic in the installer, bypassing the adapter’s declared-name selection.

2 open issues
What changed in this PR

This PR addresses #3456 by preserving slash-containing names for self-defined MCP servers in client configurations, while retaining the historical owner/repo -> repo fallback for registry dependencies.

Changes:

  • Marks self-defined server metadata and extends shared configuration-key selection.
  • Passes server metadata through eight client adapters and updates installer name handling.
  • Adds regression coverage for reverse-DNS names and names sharing the same final segment.
File Description
tests/​unit/​test_scoped_mcp_server_names.py Tests name preservation, collision avoidance, and installer forwarding.
tests/​integration/​test_wave2_adapters_coverage.py Tests shared key selection for self-defined servers.
src/​apm_cli/​integration/​mcp_integrator.py Marks synthetic metadata as self-defined.
src/​apm_cli/​core/​safe_installer.py Forwards explicit names for self-defined servers.
src/​apm_cli/​adapters/​client/​opencode.py Supplies metadata to shared key selection.
src/​apm_cli/​adapters/​client/​kiro.py Moves key selection after metadata lookup.
src/​apm_cli/​adapters/​client/​hermes.py Supplies metadata to shared key selection.
src/​apm_cli/​adapters/​client/​gemini.py Replaces inline key selection with the shared helper.
src/​apm_cli/​adapters/​client/​cursor.py Supplies metadata to shared key selection.
src/​apm_cli/​adapters/​client/​copilot.py Supplies metadata to shared key selection.
src/​apm_cli/​adapters/​client/​codex.py Supplies metadata to shared key selection.
src/​apm_cli/​adapters/​client/​claude.py Supplies metadata to shared key selection.
src/​apm_cli/​adapters/​client/​base.py Preserves declared self-defined names in the shared helper.

Review effort: Balanced


config_key = self._determine_config_key(server_url, server_name)

try:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, initialized config_key before the try block and added a regression test.

Comment thread src/apm_cli/core/safe_installer.py Outdated
Comment on lines +128 to +132
is_self_defined = bool(
cached_info
and (cached_info.get("is_self_defined") or "_raw_stdio" in cached_info)
)
if is_self_defined or (server_ref.startswith("@") and server_ref.count("/") == 1):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, removed the redundant installer check so key determination stays centralized in the adapter, and added a static AST guard.

Older APM releases wrote self-defined servers such as com.example/srv under
their final segment. With the declared name now used as the key, an upgrade
would leave that truncated entry behind. Remove it only when the per-target
ownership ledger proves APM wrote that server to the runtime; otherwise leave
it and print names-only guidance. Keys claimed by other current dependencies
are never touched.

Adds end-to-end tests through run_mcp_install, SafeMCPInstaller and every
runtime adapter (http and stdio): exact declared key, no collision for a
shared final segment, unchanged @scope/plain/registry keys, ownership ledger
equals the written key, registry lookup failure does not raise, and the
ownership-gated legacy replacement. Addresses scope record on microsoft#3456.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ined-mcp-server-names

# Conflicts:
#	src/apm_cli/integration/mcp_integrator_install.py
Main's native-ownership checks for Claude and Codex derived the config key
without server context, so a self-defined com.example/srv entry was compared
and removed under the truncated key: reinstall raised a false conflict and
uninstall missed the declared-key entry. Route both through the adapter
naming owner with self-defined context from the request or stored lockfile
config. Legacy truncated-key removal now passes the stored baseline so those
runtimes also require unchanged content, falling back to names-only guidance.
Align the PR's unit-test update_config stubs with main's managed_fields kwarg.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Adds the CHANGELOG entry crediting the contributor and documents that
self-defined servers keep their declared name as the config key, plus the
ownership-gated handling of older truncated entries.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Return the caller's reference instead of server_info["name"] for
self-defined markers so a registry response cannot pick an arbitrary
config key (supply-chain). Include the config path in legacy-entry
guidance and use user terms in the rename message (devx, cli-logging).
Add a direct _native_config_key contract test and a registry-marker
hardening test (architect, test-coverage); comment the Kiro fallback key.
Docs: real registry example, unchanged-content condition for Claude Code
and Codex, and OpenCode caveat (doc-writer).

apm-spec-waiver: Target-native MCP config key naming is adapter output outside OpenAPM v0.1 normative scope; manifest, lockfile schema and recorded server names are unchanged.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_now

Self-defined MCP servers with a slash in their name (e.g. com.example/server) now keep their declared name as the native config key in all 12 targets, with ownership-gated cleanup of older truncated entries; every in-scope panel and Copilot item is folded and CI is green at 2436a47.

panel-mode=delta; personas=python-architect,test-coverage-expert,doc-writer,supply-chain-security-expert,cli-logging-expert,devx-ux-expert,apm-ceo (iteration 1 ran full with the same roster)

cc Sai krishna Bodapati (@bodapatisaikrishna) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

Reviewed against the approved scope record on #3456: #3456 (comment)

The merge worker folded every recommended follow-up from the first full pass: registry-supplied server_info can no longer choose an arbitrary config key, legacy-entry warnings name the config file, docs no longer over-claim (OpenCode caveat, unchanged-content condition for Claude Code and Codex), and a direct contract test locks _native_config_key to the naming owner. All six delta panelists returned zero findings. The canonical-owner gate verified six touched owners with exact-head functional tests.

After merging current main, main's new native-ownership checks for Claude Code and Codex derived keys without server context; they now route through MCPClientAdapter._determine_config_key with self-defined context, so reinstall no longer raises a false conflict and uninstall removes the declared-key entry. Two pre-existing issues stay out of scope (see Deferred).

Aligned with: secure by default (registry markers cannot steer keys; deletion needs ownership proof); multi-harness (one naming owner across all 12 adapters); pragmatic as npm (honest CHANGELOG, actionable guidance with config path).

Panel summary (terminal delta)

Persona B R N Takeaway
Python Architect 0 0 0 Naming decision remains single-owner in _determine_config_key; hardening correct.
Test Coverage Expert 0 0 0 All Done-when items have regression traps; new contract and hardening tests close the prior nit.
Doc Writer 0 0 0 Docs and CHANGELOG match the code at head.
Supply Chain Security Expert 0 0 0 Registry-marker trust gap closed; messages carry no config values.
CLI Logging Expert 0 0 0 Outcome-first wording, config path in warnings, exception detail in verbose.
DevX UX Expert 0 0 0 Upgrade path conservative and idempotent; guidance actionable.

B = blocking-severity findings, R = recommended, N = nits. Counts are signal strength, not gates. The maintainer ships.

Top 2 follow-ups

  1. [Python Architect] OpenCode adapter declares mcp_servers_key = "mcpServers" but writes under mcp, so conflict and legacy-entry detection cannot see OpenCode entries. -- Pre-existing; affects OpenCode users beyond key naming.
  2. [Python Architect] MCPIntegrator.remove_stale still expands stale names to their final segment on non-baseline runtimes. -- Pre-existing cleanup semantics that could remove a same-named unrelated entry.

Recommendation

All five prior advisory findings are resolved with test and docs evidence. CI is green across all checks. File the two deferred items as follow-up issues after merge.

Folded in this run

  • (panel) Scope-record gaps: all-runtime http/stdio declared-key, collision, unchanged-key, ownership-ledger and lookup-failure tests; ownership-gated legacy truncated-key replacement with names-only guidance -- resolved in 7a7b5e4.
  • (panel) Main's Claude/Codex native comparison and removal keys use the declared name for self-defined servers; legacy removal there also requires unchanged content -- resolved in c50e094.
  • (panel) Registry info markers cannot choose an arbitrary key (supply-chain), config path in guidance (devx), docs caveats (doc-writer), _native_config_key contract test and Kiro comment (architect), wording and verbose detail (cli-logging) -- resolved in 82fec26.
  • (copilot) Kiro UnboundLocalError on registry lookup failure -- resolved in 0a71750, regression-trapped below.
  • (copilot) Keep self-defined naming out of SafeMCPInstaller -- resolved in 0a71750.

Copilot signals reviewed

  • src/apm_cli/adapters/client/kiro.py:213 -- LEGIT: real crash path; config_key initialised before try; mutation-verified tests (resolved in 0a71750).
  • src/apm_cli/core/safe_installer.py -- LEGIT: single-owner rule; installer override dropped, AST static guard added (resolved in 0a71750).

Deferred (out-of-scope follow-ups)

  • (panel) OpenCode mcp_servers_key mismatch hides OpenCode entries from conflict and legacy detection -- scope boundary: pre-existing OpenCode detection bug; fixing it changes skip/overwrite behavior beyond key naming.
  • (panel) remove_stale final-segment expansion on non-baseline runtimes -- scope boundary: pre-existing cleanup semantics; the scope excludes forced deletion or migration changes.

Regression-trap evidence (mutation-break gate)

  • Kiro fetch-raises tests -- deleted the pre-try config_key initialisation; tests FAILED with UnboundLocalError; guard restored.
  • Owned/unowned legacy-entry tests -- deleted the _reconcile_legacy_truncated_key call; 20 tests FAILED; guard restored.
  • Unowned legacy-entry tests -- deleted the ownership-ledger check; 10 tests FAILED; guard restored.
  • test_truncated_key_claimed_by_current_dependency_is_kept -- deleted the claimed-key check; test FAILED; guard restored.
  • Claude/Codex reinstall, uninstall and legacy tests -- removed self-defined context from _native_config_key; 8 tests FAILED; guard restored.
  • test_owned_but_edited_truncated_entry_is_left_on_baseline_runtimes -- removed the conflict fallback; 2 tests FAILED; guard restored.
  • test_registry_info_markers_cannot_choose_an_arbitrary_key -- restored server_info["name"] return; 2 tests FAILED; guard restored.
  • 54 of the new end-to-end tests fail on main before this PR.

Lint contract

ruff check and ruff format --check (src/, tests/, architecture linter) silent; pylint R0801 10.00/10; lint-auth-signals.sh and lint-architecture-boundaries.sh clean.

CI

All checks green on 2436a47 (24 pass, 3 skipped): https://github.com/microsoft/apm/actions/runs/42879018030 (after 1 CI fix iteration: Spec conformance Mode B, resolved with an apm-spec-waiver because native MCP key naming is adapter output outside OpenAPM v0.1; manifest, lockfile schema and recorded names are unchanged). license/cla passed.

Mergeability status

PR head SHA CEO stance iters folds defers Copilot rounds CI mergeable mergeStateStatus notes
#3493 2436a47 ship_now 2 9 2 2 green MERGEABLE BLOCKED pending required review

Convergence

2 outer iterations; 2 Copilot rounds. Final panel stance: ship_now. The PR body's scope link now points to the approved record above. Ready for maintainer review.

Full per-persona findings (iteration 1, all folded)

Python Architect

  • [recommended] Guard the _native_config_key -> _determine_config_key synthetic-marker coupling. Folded: test_native_config_key_follows_stored_self_defined_config.
  • [nit] Comment Kiro's pre-try fallback key. Folded.

Test Coverage Expert

  • [nit] No slash-name unit case for _native_config_key. Folded.

Doc Writer

  • [recommended] Docs/CHANGELOG over-claimed removal-or-warning on every target; OpenCode gets neither. Folded.
  • [nit] Mention the unchanged-content condition on Claude Code and Codex. Folded.
  • [nit] Use a real reverse-DNS registry example. Folded.

Supply Chain Security Expert

  • [recommended] Registry server_info with is_self_defined/_raw_stdio and a crafted name could choose an arbitrary key. Folded: return the caller's reference.
  • [nit] Document the trust boundary. Folded.

CLI Logging Expert

  • [nit] "truncated MCP key" jargon at default verbosity. Folded.
  • [nit] Include the exception message in verbose detail. Folded.

DevX UX Expert

  • [recommended] Include the config path in "Remove it manually" warnings. Folded.
  • [nit] Same jargon point. Folded.

This panel is advisory. It does not block merge. Re-apply the panel-review label after addressing feedback to re-run.


Generated by autopilot-pr-merge-worker. This comment is AI-generated and may contain errors.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 5753b7e into microsoft:main Nov 11, 2026
2 checks passed
Daniel Meppiel (danielmeppiel) added a commit to Aaryan-Dadu/apm that referenced this pull request Nov 12, 2026
After merging main (microsoft#3493), self-defined servers keep their declared name
(slashes included) as the native key. The security-upgrade snapshot and
the conflict guidance looked entries up by the truncated key, so a
slash-named server lost its upgrade notice and reconciliation guidance.
Both now use the declared key.

Panel follow-ups folded: the conflict guidance names which ${VAR} belongs
in each field (names only, never values or defaults); the --force caveat
sits on its own line; Claude's upgrade notice reads "the project
.mcp.json"; the opaque _begin_env_tracking/_record_env_diagnostics
snapshot contract is documented; a test guards that Claude redeclares
every mutable Copilot aggregation bucket; a symmetric project-scope
assertion; a comment documents the empty-value expansion choice.

Addresses review-panel follow-ups (python-architect, devx-ux-expert,
cli-logging-expert, test-coverage-expert, supply-chain-security-expert).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 12, 2026
* fix(claude): keep ${VAR} references in project .mcp.json

Claude Code expands ${VAR} and ${VAR:-default} in the project .mcp.json,
so apm install keeps the references there instead of prompting for and
writing the real values. Reinstall replaces values an earlier release
wrote when APM can confirm it wrote them; otherwise it keeps the entry
and names the fields to fix. User scope is unchanged.

Adds an MCP variable compatibility page covering every harness.

Closes #3252

* docs(spec): add req-mf-026 for Claude project MCP references

Adds the spec citation for this PR's install and ownership change:
req-mf-026 in Section 4.5, the Appendix C and manifest rows, three
conformance tests, and the regenerated CONFORMANCE files.

* fix(claude): key MCP upgrade checks by declared name; clearer guidance

After merging main (#3493), self-defined servers keep their declared name
(slashes included) as the native key. The security-upgrade snapshot and
the conflict guidance looked entries up by the truncated key, so a
slash-named server lost its upgrade notice and reconciliation guidance.
Both now use the declared key.

Panel follow-ups folded: the conflict guidance names which ${VAR} belongs
in each field (names only, never values or defaults); the --force caveat
sits on its own line; Claude's upgrade notice reads "the project
.mcp.json"; the opaque _begin_env_tracking/_record_env_diagnostics
snapshot contract is documented; a test guards that Claude redeclares
every mutable Copilot aggregation bucket; a symmetric project-scope
assertion; a comment documents the empty-value expansion choice.

Addresses review-panel follow-ups (python-architect, devx-ux-expert,
cli-logging-expert, test-coverage-expert, supply-chain-security-expert).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(mcp): record Codex env_vars after #3406; name exit on conflict

The MCP variable compatibility inventory was written before #3406 landed
on main and still said Codex project scope writes resolved env values.
Codex project and user scope are now separate rows, and the known-gap
lists name Codex user scope. The producer page no longer uses Codex
project env as the example of a harness needing literal values. The
consumer page says a preserved Claude entry ends the install with an
error naming each field and its reference. The CHANGELOG entry is
trimmed to one line ending in (#3377).

Addresses review-panel follow-ups (doc-writer, devx-ux-expert).

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: danielmeppiel <danielmeppiel@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 12, 2026
…ed (#3649)

Stale MCP cleanup expanded every stale name to its last path segment, so
removing self-defined com.example/server deleted a user-authored or
still-declared 'server' entry from VS Code, Cursor, Copilot and OpenCode.
Self-defined servers keep their declared key (#3493) and older truncated
keys are reconciled only under ownership proof at install time, so derive
the alias from the adapter key owner with self-defined context.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 12, 2026
…ed (#3649)

Stale MCP cleanup expanded every stale name to its last path segment, so
removing self-defined com.example/server deleted a user-authored or
still-declared 'server' entry from VS Code, Cursor, Copilot and OpenCode.
Self-defined servers keep their declared key (#3493) and older truncated
keys are reconciled only under ownership proof at install time, so derive
the alias from the adapter key owner with self-defined context.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 13, 2026
…kfile symlink, audit replay, targeted install, MCP cleanup) (#3672)

* fix(export-patch): make subdirectory package patches apply from the repo root (#3649)

A git: + path: (or marketplace git-subdir) dependency is cached as just
its subdirectory, so exported diff paths were relative to that
subdirectory while the patch header says to apply from the package
repository root; git apply failed with 'No such file or directory'.
Prefix the locked virtual_path for subdirectory packages.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(export-patch): export edits to Claude plugin packages (#3649)

Install normalizes a Claude plugin (no apm.yml) by mirroring skills/,
agents/ and commands/ into .apm/ inside the cache. export-patch indexed
both copies, so every skill or agent edit in a marketplace plugin was
skipped as 'ambiguous source'. When the cache carries the parser-owned
normalization receipt, prefer the upstream candidate over the .apm/
mirror.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(view): accept logical absolute paths in view --file (#3649)

apm view --file "$PWD/<file>" exited 2 ('outside the project deploy
root') whenever the working directory was reached through a symlink
(macOS /tmp and /var, symlinked workspaces): the deploy root comes from
the physical getcwd() while the query kept its logical parents. When
the lexical query is not under the deploy root, resolve only its parent
directory so the queried leaf stays exact.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(redteam): C5 marketplace, pack, export-patch and view --file chains (#3649)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(lockfile): refuse a symlinked lockfile before update or uninstall writes (#3649)

apm update, apm install --update and apm uninstall detected a symlinked
apm.lock.yaml (#3532) only when writing the lockfile, after deploying new
files, cleaning stale ones and editing apm.yml. The command then exited 1
with the lockfile still describing the old state, and update reported that
no transaction changes were committed. ensure_lockfile_writable() is now
the single owner of the rule; LockFile.write uses it, and update (when the
plan changes the graph) and uninstall (when it removes a locked package)
call it before any other write, so the transaction rolls back cleanly.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(audit): replay local apm.yml packages with plugin.json as apm_package (#3649)

apm install DIR (routed by #3604) and manifest-declared local deps classify
a directory with apm.yml and a root plugin.json as apm_package and deploy
only its .apm/ primitives. The audit --ci replay normalized any local dir
with a plugin.json as a legacy plugin, integrating root agents/ and failing
drift on a fresh install. Route the replay through detect_package_type,
the same classifier install uses.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(install): keep a targeted package's dropped deps an unreached entry may need (#3649)

apm install PKG drops the selected package's former descendants that this
run's graph no longer contains (#3528). With #3571 the graph is rebuilt from
the current apm.yml of every local package, so an unselected sibling edited
since it was locked makes the graph omit retained entries it still locks.
A shared dependency of such an entry was then removed while the entry stayed
locked, leaving apm.lock.yaml without that entry's dependency while audit
and prune passed. When the graph omits any retained entry it cannot prove the
candidate unneeded, so drop nothing; the next full install reconciles.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(mcp): keep user short-name entries when a slashed server is removed (#3649)

Stale MCP cleanup expanded every stale name to its last path segment, so
removing self-defined com.example/server deleted a user-authored or
still-declared 'server' entry from VS Code, Cursor, Copilot and OpenCode.
Self-defined servers keep their declared key (#3493) and older truncated
keys are reconciled only under ownership proof at install time, so derive
the alias from the adapter key owner with self-defined context.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(lifecycle): guard 0.36.0 release flows with lifecycle chains (#3649)

Permanent APMLifecycle scenarios from the 0.36.0 pre-release sweep.
They drive the real apm binary over hermetic local Git fixtures across
install, install --frozen, update, audit --ci, prune, uninstall, pack,
marketplace, export-patch, view --file, policy and user scope. They
assert disk, lockfile, receipts and exit code after every step.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): record 0.36.0 red-team regression fixes (#3649)

apm-spec-waiver: restores promised behavior of features merged since v0.35.0; no OpenAPM requirement changes

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* refactor(owners): route export-patch mirror, lockfile preflight, and MCP config-key through canonical owners (#3649)

Fix 2: export_patch now routes .apm/ mirror classification through
plugin_parser.is_install_generated_mirror() instead of hard-coding
.apm/ prefix knowledge. The normalization owner decides what is a
mirror.

Fix 4: lockfile symlink write-guard consolidated into
refuse_lockfile_before_mutation() in deps/lockfile.py (single owner).
Both pipeline.py and uninstall/cli.py now call this owner API.
Added owner registry guard contracts-tooling-lockfile-symlink-write-guard
with a MutationCase proving its teeth.

Fix 7: MCPClientAdapter._determine_config_key promoted to public
determine_config_key(). All 17 call sites (adapters, integrators,
ownership, cleanup) updated. No cross-module private access.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): cite #3672 for the red-team regression fixes (#3649)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(compile): never overwrite hand-authored nested context files (#3655)

Distributed compile replaced a hand-authored subdirectory AGENTS.md or
CLAUDE.md that carries no APM marker, then treated the replaced file as
generated output and reported it as orphaned. The canonical owner
hand_authored_root_context_blocks_write now applies its marker rule to
catalog context filenames at any depth, the AGENTS.md and CLAUDE.md call
sites route every placement through it, and nested Git repository skips
are decided before protection so their accounting is unchanged. The
static guard pins the any-depth rule, with mutation cases.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(uninstall): keep apm.lock.yaml truthful when uninstall refuses (#3656)

When apm uninstall stopped because a tracked target file was edited or a
user file sat in a managed skill directory, it had already removed the
package's other target files but left apm.lock.yaml claiming all of them.
The target-contraction owner (reconcile_target_deployed_files) now reports
what each selected dependency still owns through SelectedCleanupOutcome,
and the refusal applies it via DeploymentLedgerCodec.replace_legacy_owners
and writes the lockfile, so it claims only files still on disk while
apm.yml keeps the package for the retry. Preserved profile rows stay
claimed. The retained-edit warning now carries its [!] symbol.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(uninstall): keep the other runtime's default root on selected-profile uninstall (#3661)

A global uninstall retained for another Claude/Hermes profile removed rows
under every USER_ROOT_ENV_VARS target's selected root, so a HERMES_HOME
profile uninstall also deleted ~/.claude files (and vice versa).
profile_scope now shares one other-profile record walk and removes only the
selected roots of the runtimes whose profiles split the package.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(deps): replay proxy-routed lock rows under --frozen (#3657)

A transparent registry proxy records the proxy host and registry_prefix
instead of the upstream host, so drift classified every such row as a
provider change and --frozen refused the lock the proxy had just written.
ArtifactoryRouter now owns the proxy routing target (promoted from the
resolver's private copy) and answers whether a dep routes to a locked proxy
row; drift, download-ref replay and the cached-commit owner reuse it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(audit): honor --no-cache for auto-discovered policy (#3659)

The explicit --policy and auto-discovery branches now share one discovery
call that always forwards no_cache, so 'apm audit --ci --no-cache' fetches
the org policy fresh as documented.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(policy): guard audit --ci agreeing with install on denied transitives (#3658)

main's source-dependency owner (#3606) already runs the allow and deny
checks over effective direct deps plus locked transitives. This keeps
the installed-CLI guard that install and audit --ci agree.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(marketplace): real recovery hint, verified package refs, packed relative hook scripts (#3670)

- apm pack on a branch-ref marketplace package no longer suggests the
  nonexistent --allow-head flag; it names the real recovery command
  (apm marketplace package set <pkg> --ref <tag-or-sha>).
- marketplace package add/set --ref verify the ref on the entry's own host
  through the explicit-ref owner shared with marketplace check
  (ref_resolver.explicit_ref_error, package_entry_coordinates): a missing
  tag or unreachable remote exits 2 without changing apm.yml; --no-verify
  keeps the opt-out. Previously a non-default host looked 'network
  unavailable' and any missing tag was stored with exit 0.
- apm pack carries hook scripts referenced as ./scripts/x from .apm/hooks
  the way install resolves them (resolve_relative_hook_script, promoted to
  public) and repoints the packed command.
- Owner record marketplace-entry-ref-verification + AC10 guard + MutationCase.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(bundle): name skipped source symlinks in pack; skip plugin hooks in bundle installs (#3670)

- apm pack keeps not following own-source symlinks (matching own-project
  install), but now names each dropped link in a pack warning instead of
  dropping it silently. The existing exporter walkers record the skipped
  links; both bundle exporters warn through _emit_pack_warning.
- apm install <bundle> no longer copies a Claude plugin bundle's hooks.json
  raw into the target root or lowers hooks/ scripts through the hook
  descriptor extension (fmt.sh -> fmt.sh.json). The local-bundle routing
  owner (install/local_bundle_paths.py) skips plugin-native hook paths and
  reports one bundle_deploy_skip_warning per file; deployed-layout bundles
  keep routing their target hook files. Merging bundle hooks through the
  hook integrator is a follow-up.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(mcp): clean recorded servers after their runtime opt-in dir is pruned (#3664)

Removing a dependency prunes an emptied .claude/ or .opencode/ before MCP
stale cleanup runs, and remove_stale reused those write opt-in directories
as cleanup gates, so the recorded server stayed in .mcp.json or
opencode.json while its ledger ownership was dropped (apm uninstall and
apm install after removing the dependency).

install/mcp/ownership.py, the safe-removal owner, gains
project_mcp_cleanup_reachable: ledger-scoped cleanup (an explicit runtime
from the ownership ledger) stays reachable, otherwise the opt-in dir still
gates. remove_stale routes both gates through it; Claude removal stays
content-verified by require_removable_mcp_connections. The
install-deployment-mcp-ownership-migration guard requires that route and
rejects a raw .claude/.opencode is_dir gate in mcp_integrator.py, with a
mutation case.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(hooks): retire merged events a hook source no longer declares (#3665)

Merged hook targets cleared a source's earlier entries only for the
events its current hook files declare. Deleting one hook file from a
package or the root .apm/hooks while another remained left the old event
entry in .claude/settings.json and apm-hooks.json, pointing at a deleted
script, and apm audit --ci then reported drift.

hook_ownership.py gains drop_source_entries, extracted from Cursor's
inline whole-source clear. HookIntegrator now uses it for that clear and,
after merging, to drop the source's entries from every event it did not
re-declare, so hook_integrator.py shrinks. The neutral-hook-contract
guard requires both calls and forbids a second definition, with a
mutation case.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(mcp): exit apm mcp install through the install outcome (#3666)

apm mcp install forwarded to apm install --mcp with
cli.main(standalone_mode=False), which returns ctx.exit codes instead of
raising them, so a failed forwarded install (for example an org policy
block) exited 0. Run the forwarded command in standalone mode so its exit
comes from install/outcome.py and Click's error handling exactly as for
apm install. The install-deployment-outcome guard rejects
standalone_mode=False under commands/, with a mutation case.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(deps): list the dependency key apm uninstall accepts (#3671)

apm deps list showed a self-hosted GitLab dependency (type: gitlab) by its
host-blind org/repo key with Source github, while apm deps tree showed
the host-qualified key and apm uninstall only accepts that identity.
deps list now shows the key deps tree derives (_dep_display_key, extracted
from _dep_display_name) for remote locked dependencies, keeping
host-blind keys for orphan detection, and labels Source through the
canonical classify_host_provider with the declared or locked host_type.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(cleanup): never delete a deployed file without a matching recorded hash (#3663)

Stale, orphan, contraction, prune and uninstall cleanup all route through
integration/cleanup.py::remove_stale_deployed_files. Its provenance gate
deleted any lockfile-claimed file without a recorded hash (legacy
fall-through), so a hand-edited lockfile could make a receipt-less install
delete user files. Gate 3 now keeps such files with a warning and reports
them as retained, matching the documented rule that stale files are removed
only when recorded hashes match. cowork:// rows stay exempt because install
records no hashes for them yet. enterprise/security.md now states that a
committed apm.lock.yaml is reviewed input with cleanup authority.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(audit): replay local packages through the install package image (#3667)

apm install copies a local package with materialize_local_package, which
dereferences in-package links and materializes single files. The audit
--ci replay integrated straight from the source tree, where integrators
skip links, so a clean install of a package with a contained link reported
its deployed file as orphaned drift.

materialize_local_package is now the one raising owner of the local
package image: install (_copy_local_package), the uninstall survivor
refresh and audit replay (materialize_local_package_for_replay) all copy
through it. path_anchoring.resolve_local_dep_base owns the admission
anchor for a locked local dep. The replay's raw-directory branch, the
file-only replay materializer and the legacy-plugin normalizer's extra
copy are gone. The single-file owner guard, registry record and mutation
cases now pin the shared routes.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(prune): keep a hand-removed direct dependency another package still needs (#3668)

prune and deps list retained lock entries recorded with depth > 1 only, so
a dependency hand-removed from apm.yml that another installed package
still declares looked orphaned and prune deleted its checkout, deployed
files and lock entry.

deps/reachability.py, the forward-reachability owner uninstall already
uses, now answers which lock entries are retained (retained_lock_keys):
recorded transitives plus stale direct entries still reachable from a
declared package's manifest, failing closed when the walk is incomplete.
_build_expected_install_paths (prune, deps list, orphan warning) and
prune's lock-key selection route through it instead of re-deriving
depth > 1. The walk treats a manifestless skill, skill bundle or hook
package as a leaf (classified by detect_package_type) instead of an
unverifiable node. The reachability guard rejects a parallel depth rule
in prune or the selector; docs describe the kept package.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(uninstall): keep is_dev as install writes it and never report a withheld lock write (#3669)

The forward-reachability walk that rescues a shared dependency after
uninstall treated every survivor as production, so a dependency left
reachable only through devDependencies was rewritten without is_dev and
the next install rewrote apm.lock.yaml.

compute_forward_reachable_keys now takes the surviving devDependencies
separately and drains production paths first, reporting dev_only keys
with the install resolver's rule (a production path wins); uninstall
persists it with the resolved_by repair. LockFile.write/save return
whether the file was persisted, so install --frozen no longer prints
'Updated apm.lock.yaml' for a write it withheld.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* refactor(install): gate update plans through one plan_inputs owner (#3649)

The update-plan confirmation and the symlinked-lockfile refusal now
live in install/helpers/plan_inputs.confirm_update_plan, next to
build_resolved_update_plan. The pipeline makes one call and drops its
local helper, so pipeline.py stays under the install LOC budget. The
plan is still built lazily, only when an unwritable lockfile needs it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* refactor(install): keep install modules within their LOC budgets (#3649)

Moves SelectedCleanupOutcome (#3656) into install/selected_cleanup.py;
the target-contraction owner re-exports it for its callers. Compacts
the cached-commit tail in sources.py (#3657) with no behavior change.
The dependency-replacement guard and its mutation case now pin the plan
through plan_inputs.confirm_update_plan.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): record the #3649 fix wave (#3672)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(policy): state that org policy does not govern user-scope installs (#3660)

Org policy discovery starts from the project's git remote, so apm install -g
(user scope) is not governed by org policy today. Docs only; no behavior
change. A user-scope policy source is tracked separately.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(architecture): keep one matrix case per guard for sweep sub-rules (#3649)

The #3664, #3665 and #3666 guard extensions now prove their teeth in a
parametrized standalone test, so the owner-rule matrix keeps exactly one
mutation case per registry guard.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(install): keep packages apm.yml no longer declares during --frozen (#3662)

apm install --frozen tolerated lockfile entries that apm.yml no longer
declares but still ran orphan cleanup, deleting their deployed files while
the never-rewritten lockfile kept claiming them. The cleanup phase now
retains every orphan under --frozen through the existing
orphan_cleanup_retained map, so files, the apm_modules checkout and the
lock rows stay in place, and prints one info line naming the kept packages
with the remedy to run apm install. Retained orphans now carry their
source rows' concrete targets, so the frozen build stays equivalent to the
committed lockfile and no rewrite is withheld.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): record frozen orphan retention (#3662)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(lifecycle): install vs audit --ci replay matrix across package shapes (#3649)

Sixteen package shapes (APM package via Git/local/alias/target subset,
monorepo subdirectory, contained links in Git and local packages, hooks via
Git alias/local alias/symlinked path, Claude skill local alias and Git,
skill bundle subset, Claude plugin Git and local alias, MCP-only, single
file) driven through install, re-install, install --frozen, compile, cold
clone without receipts or cache, and uninstall, asserting audit --ci agrees
at every step. Guards the #3667 local package image replay for aliased and
symlinked local paths.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(audit): keep local replay images out of the live apm_modules (#3667)

The #3667 replay wrote each local package image at
apm_modules_dir/<slot>. A cache-only replay (bare 'apm audit') passes the
live project apm_modules there, so auditing silently rewrote the installed
copy with unaudited source bytes and normalized legacy plugins in place;
in --ci mode the image landed on the native plugin replay path and
verify_native_plugin_cache then copied the source onto itself
(SameFileError). Materialize local images under the scratch deployment
root and let native verification hash that image instead of re-copying.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(deps): find case-equivalent installs in the reachability walk; keep sweep guards green (#3649)

- models/dependency/materialization.installed_package_path is the one
  read-only lookup for where a dependency is materialized. It recognizes a
  case-equivalent directory. Prune's expected-path builder and the forward
  reachability walk both use it, so prune and uninstall no longer treat a
  casing-equivalent install as unverifiable on case-sensitive file systems
  (#3668).
- integration/cleanup.py: a managed final symlink needs no content hash
  to be unlinked, because unlinking removes no file content (#3663).
- Hook sync tests pass the recorded hashes that uninstall passes. The
  Claude MCP broadcast test pins the opt-in gate (#3664). The frozen rule
  inventory lists the lockfile symlink guard.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): drop the #3658 entry delivered by #3606 (#3649)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): remove stale placeholder bullets left by the rebase (#3649)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* style(tests): format owner-rule mutations after rebase (#3649)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(install)!: fail --frozen when deployed bytes differ from locked hashes (#3654)

BREAKING CHANGE: apm install --frozen now exits 1 when a deployed file's
on-disk bytes differ from its deployed_file_hashes entry (OpenAPM
req-lk-017), naming each path with its expected and observed envelope.
Before, frozen exited 0 on a dirty tree and the next apm audit --ci
failed with hash drift. This covers a kept local edit (e.g. a user-edited
skill) and an APM upgrade that renders an already-locked file
differently. Repair: run apm install without --frozen and commit.

The per-record hash loop of audit content-integrity is extracted into
policy/ci_checks.py verify_deployed_file_hashes, and audit scope/target
resolution into resolve_audit_scope; audit and the existing post-deploy
frozen owner (InstallService._enforce_frozen_no_rewrite) both call them.
The install success line now reads 'Deployed files verified against
apm.lock.yaml.'. Audit drift text no longer offers export-patch for a
modified file whose bytes still match the lock; local_edits owns the new
rendering-change hint. check_frozen pins both verifier call sites; docs,
apm-usage skill, a req-lk-017 CLI conformance test and lifecycle guards
are updated.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): record the frozen hash verification break (#3654)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(spec): give the cleanup conformance context its frozen default (#3662)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(audit): keep user-scope local replay images out of the governed tree (#3667)

At user scope the scratch modules root sits under the governed .apm
directory, so local package images read as deployed drift. Replay now
materializes local images in an ungoverned scratch apm_modules. At project
scope that is the same directory as before.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(lifecycle): parse git URLs in the SSH transport guard (#3640)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(deps): guard the case-equivalent install lookup directly (#3668)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* refactor(architecture): register MCP config-key derivation owner (#3649)

Add guard hooks-integrations-mcp-config-key-derivation to the existing
mcp-package-launcher owner in hooks-integrations.json, with a static
check in mutation_mcp_target_and_scope.py that verifies:
  - determine_config_key exists as a definition in MCPClientAdapter
  - MCP consumers (mcp_integrator, mcp_integrator_install, mcp/ownership)
    route through determine_config_key() and do not re-derive config keys
    by splitting on "/"

MutationCase proves the guard fires when the definition is renamed.
Frozen rule inventory updated in test_architecture_runner.py.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* test(install): guard frozen hash verification at user scope (#3654)

Parametrize the warm kept-edit frozen guard over project and user scope:
apm install -g, tamper with a deployed skill under the isolated HOME,
then apm install --frozen -g must exit 1 naming the path with expected
and observed hashes and leave $APM_HOME/apm.lock.yaml byte-identical;
after the user resolves the edit and runs apm install -g, --frozen -g
exits 0.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(uninstall): scope selected-profile removal per package in batched uninstalls (#3649)

selected_profile_survivors combined the split runtimes of every requested
package, so uninstalling two packages at once could delete files that two
separate uninstalls keep (one package split across Hermes homes, the other
across Claude profiles). The removable selected-profile prefixes are now
computed per package before survivor rows are combined.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(install): refuse a symlinked lockfile before any update side effect (#3649)

confirm_update_plan only refused a symlinked apm.lock.yaml when the
resolved dependency plan had changes. A target-only change under
apm install --update leaves the plan unchanged but still rewrites the
deployment ledger, so files were deployed before the lockfile write
failed. An update exists to rewrite the lockfile, so it now refuses
unconditionally through refuse_lockfile_before_mutation(would_mutate=True),
after the apm update plan callback and before any download, deploy or
cleanup. Plain install, --frozen, apm lock and dry runs are unchanged.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(export-patch): classify plugin mirrors from path-specific receipt evidence (#3649)

A normalization receipt does not prove every .apm/ file was generated:
plugins can declare authored .apm/skills or .apm/agents sources. When such
a source shared bytes with an unrelated repository file, export-patch
dropped the real source and patched the unrelated file. The normalization
owner now maps only .apm/skills/<name>/<tail> to the source directory its
receipt records (install_generated_mirror_source), and export-patch drops a
candidate only when that proven source is itself another candidate;
otherwise the ambiguity skip is kept.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(pack): reject symlinked relative hook scripts before packing (#3649)

resolve_relative_hook_script() resolved symlinks before pack validated the
resource, so a contained ./scripts/alias.sh -> fmt.sh (or a linked scripts/
directory) was packed instead of rejected. The owner gains a lexical mode,
like resolve_plugin_root_hook_script, so pack validates the unresolved path
and its ancestors through the existing hook-resource symlink rule; install
keeps resolving as before.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(pack): anchor packed relative hook scripts on the plugin root (#3649)

A packed ./scripts/fmt.sh reference became ./hooks/scripts/fmt.sh, which
resolves from the consumer's working directory rather than the installed
plugin, so it could not find the bundled file. The plugin-root vocabulary
owner gains plugin_root_script_reference, which anchors the packed path on
${CLAUDE_PLUGIN_ROOT} while keeping the authored quoting (unquoted,
double- or single-quoted); pack uses it for relative script references.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* fix(hooks): retire dropped events under safe legacy source markers (#3649)

The #3665 retirement pass dropped a source's entries from events it no
longer declares only under the canonical marker. An upgraded install
whose sidecar still carries a leaf marker such as 'hooks' kept the
dropped event pointing at a deleted script. HookIntegrator now computes
the owned marker set once from _get_hook_source_markers (keeping its
ambiguity rules) and passes it to both drop_source_entries passes. The
neutral-hook-contract guard requires both passes to use it, with a
mutation case.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

* docs(changelog): match export-patch and pack entries to the review folds (#3672)

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: danielmeppiel <danielmeppiel@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants