Skip to content

fix(yaml): preserve apm.yml comments on manifest update (closes #2000) - #2012

Merged
Daniel Meppiel (danielmeppiel) merged 4 commits into
mainfrom
bbs/fix-2000
Jul 4, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 4 commits into
mainfrom
bbs/fix-2000

Conversation

@danielmeppiel

Copy link
Copy Markdown
Collaborator

Why: apm install and apm uninstall rewrote apm.yml through PyYAML, which dropped user comments during dependency updates. What: route apm.yml manifest update reads and writes through the existing ruamel.yaml dependency in bounded round-trip helpers, preserving comments while keeping the existing YAML safety pre-parse. How to test: uv run --extra dev pytest tests/unit/commands/test_install_context_and_resolution.py::TestValidateAndAddPackagesToApmYml::test_manifest_update_preserves_comments tests/unit/test_uninstall_dev_dependencies.py::TestUninstallDevDependencies::test_uninstall_preserves_manifest_comments -q; uv run --extra dev pytest tests/unit -k "yaml or install or uninstall or manifest" -q; uv run --extra dev ruff check src/ tests/ --quiet; uv run --extra dev ruff format --check src/ tests/ --quiet; uv run --extra dev python -m pylint --disable=all --enable=R0801 --min-similarity-lines=10 --fail-on=R0801 src/apm_cli/. Closes #2000.

Use ruamel round-trip YAML helpers for apm.yml manifest update paths so install and uninstall keep existing comments when rewriting dependencies.

Co-authored-by: Copilot <[email protected]>

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.

Pull request overview

Routes apm.yml manifest reads/writes for apm install and apm uninstall through ruamel.yaml round-trip helpers to preserve user comments during dependency updates, while retaining the existing bounded PyYAML pre-parse safety check.

Changes:

  • Add load_yaml_roundtrip() / dump_yaml_roundtrip() helpers in apm_cli.utils.yaml_io and switch manifest-update call sites to use them.
  • Update install/uninstall manifest mutation paths to use round-trip load/dump.
  • Add/adjust unit tests to assert that apm.yml comments survive install/uninstall manifest updates.
Show a summary per file
File Description
src/apm_cli/utils/yaml_io.py Introduces round-trip YAML load/dump helpers (ruamel.yaml) with bounded PyYAML pre-parse validation.
src/apm_cli/commands/install.py Switches manifest load/dump to round-trip helpers so dependency updates preserve comments.
src/apm_cli/install/package_resolution.py Uses dump_yaml_roundtrip when persisting dependency list changes.
src/apm_cli/commands/uninstall/cli.py Switches manifest load/dump to round-trip helpers so uninstall preserves comments.
tests/unit/commands/test_install_context_and_resolution.py Adds a regression test asserting install manifest updates preserve comments.
tests/unit/test_uninstall_dev_dependencies.py Adds a regression test asserting uninstall preserves existing manifest comments.
tests/unit/commands/test_install_phase3.py Updates mocks to patch dump_yaml_roundtrip instead of dump_yaml.
tests/unit/commands/test_install_phase3w4.py Updates mocks to patch dump_yaml_roundtrip instead of dump_yaml.
tests/unit/commands/test_install_error_handling.py Updates mocks to patch dump_yaml_roundtrip instead of dump_yaml.
tests/unit/install/test_package_resolution_persistence.py Updates persistence test to patch/assert dump_yaml_roundtrip.

Review details

  • Files reviewed: 10/10 changed files
  • Comments generated: 1
  • Review effort level: Low

Comment on lines +329 to +333
stream = StringIO()
_roundtrip_yaml().dump(data, stream)
text = stream.getvalue()
with open(path, "w", encoding="utf-8") as fh:
fh.write(text)
Add round-trip YAML regression traps for comment preservation, alias expansion bombs, and unsafe Python tags while polishing the normalized parse error text. This folds the panel follow-ups for PR #2012 before CI watch.

Co-authored-by: Copilot <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator Author

APM Review Panel: ship_now

PR #2012 makes apm install and apm uninstall preserve user comments in apm.yml, closing a user-visible config-integrity gap while keeping the bounded YAML safety gate intact.

cc Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

Panel signals converge cleanly. The round-trip comment-preservation approach is structurally sound, the bounded YAML safety gate remains enforced before ruamel parses the document, and the shepherd-folded regression tests now cover comment preservation, alias-expansion fail-closed behavior, and unsafe Python tag rejection. DevX UX sees this as table-stakes package-manager behavior: user annotations in a manifest should survive tool mutations.

No substantive disagreements surfaced. The PR folded the prior follow-ups during the shepherd cycle: tests, CHANGELOG entry, error-text polish, NoReturn annotation, and ruamel tag hardening. CI is green on the latest pushed SHA.

Aligned with: portable by manifest: comments survive manifest updates; secure by default: bounded YAML safety gate remains in front of round-trip parsing; pragmatic as npm: package operations do not silently destroy user annotations.

Panel summary

Persona B R N Takeaway
Python Architect 0 0 1 Layered security-first round-trip architecture is correct; no structural concerns after shepherd folds.
CLI Logging Expert 0 0 1 Error normalization is clean; all output routes through CommandLogger; no new anti-patterns.
DevX UX Expert 0 0 0 Comment-preserving round-trip aligns apm install and apm uninstall with package-manager expectations.
Supply Chain Security Expert 0 0 0 Dual-parse YAML architecture is defense-in-depth correct; alias-bomb and Python-tag rejection are tested.
OSS Growth Hacker 0 0 0 CHANGELOG is user-facing and release-note-ready.
Doc Writer 0 0 0 Changelog entry accurately describes the apm.yml comment-preservation fix.
Test Coverage Expert 0 0 0 Critical surfaces have regression traps; shepherd-folded tests pass and mutation-break gates hold.
Performance Expert 0 0 0 Double-parse adds tiny one-time manifest I/O overhead outside the dominant fetch path.

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

Architecture

flowchart TD
    A["CLI: apm install / apm uninstall"] --> B["load_yaml_roundtrip(apm_yml_path)"]
    B --> C["Path.read_text(encoding=utf-8)"]
    C --> D["_bounded_load(text) -- security pre-pass"]
    D -->|"yaml.YAMLError"| E["Fail closed: expansion or merge bomb"]
    D -->|"OK"| F["_roundtrip_yaml().load(text) -- ruamel parse"]
    F -->|"RuamelYAMLError"| G["_raise_as_pyyaml_error"]
    F -->|"OK"| H["CommentedMap with comments preserved"]
    H --> I["Mutate dependency entries"]
    I --> J["dump_yaml_roundtrip(data, apm_yml_path)"]
    J --> K["Write UTF-8 apm.yml with comments intact"]
Loading

Recommendation

Merge as-is. CI is green, all substantive panel findings were folded, and no remaining follow-up changes the ship decision.

Folded in this run

  • (panel) Added YAML-bomb regression-trap coverage for load_yaml_roundtrip -- resolved in 0727da8.
  • (panel) Added explicit ruamel Python-tag rejection coverage and guard -- resolved in 0727da8.
  • (panel) Added CHANGELOG entry for the community-reported comment-preservation fix -- resolved in 0727da8.
  • (panel) Removed round-trip implementation jargon from normalized YAML parse errors -- resolved in 0727da8.
  • (panel) Annotated the always-raising YAML error adapter with NoReturn -- resolved in 0727da8.

Regression-trap evidence (mutation-break gate)

  • tests/unit/test_yaml_io.py::TestLoadYamlRoundtrip::test_alias_expansion_bomb_fails_closed -- deleted _bounded_load(text); test FAILED as expected; guard restored.
  • tests/unit/test_yaml_io.py::TestLoadYamlRoundtrip::test_roundtrip_parser_rejects_python_tags -- deleted rt.Constructor.add_multi_constructor(...); test FAILED as expected; guard restored.

Lint contract

uv run --extra dev ruff check src/ tests/ and
uv run --extra dev ruff format --check src/ tests/ both silent. The full local lint gate also passed pylint R0801 and scripts/lint-auth-signals.sh.

CI

gh pr checks 2012 --repo microsoft/apm --watch observed all checks green on 0727da8a7e7d9f2bdc1554936b8871f3ea5fbc4b (CI run https://github.com/microsoft/apm/actions/runs/28681844091) after 0 CI fix iteration(s).

Mergeability status

Captured from gh pr view 2012 --json mergeable,mergeStateStatus,statusCheckRollup immediately after the last push of this run.

PR head SHA CEO stance iters folds defers Copilot rounds CI mergeable mergeStateStatus notes
#2012 0727da8 ship_now 1 5 0 2 green MERGEABLE BLOCKED awaiting required review

Convergence

1 outer iteration(s); 2 Copilot round(s). Final panel verdict: ship_now.

Ready for maintainer review.


Full per-persona findings

Python Architect

  • [nit] persist_dependency_list_if_changed type annotation says dict but receives a ruamel CommentedMap at src/apm_cli/install/package_resolution.py:360.
    Runtime behavior is fine because CommentedMap behaves like a mapping; consider tightening only if the type surface is made strict later.

CLI Logging Expert

  • [nit] Nested error message may read as Failed to read apm.yml: YAML parse failed: ....
    The two-layer design is correct because the outer layer names the file and the inner layer names the cause.

DevX UX Expert

No findings.

Supply Chain Security Expert

No findings.

OSS Growth Hacker

No findings.

Auth Expert -- inactive

No auth, token, credential, host-classification, or AuthResolver behavior touched.

Doc Writer

No findings.

Test Coverage Expert

No findings.

Performance Expert

No findings.

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

Add a hermetic integration test that drives the real apm install command through an apm.yml rewrite and asserts comments plus formatting survive. Also marks existing network-dependent integration smoke/live files so the non-network suite gate can run hermetically.

Co-authored-by: Copilot <[email protected]>
Normalize round-trip dump failures through the YAML error path, document the intentional ruamel constructor registration, and make the changelog entry name the user-visible comment preservation benefit.

Co-authored-by: Copilot <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator Author

APM review panel recommendation

Recommendation: ship_now.

Summary: PR #2012 closes the apm.yml trust gap from issue #2000 by preserving comments and formatting during dependency install/uninstall manifest rewrites. The round-trip YAML layer keeps the bounded PyYAML safety pre-parse, then uses ruamel only for comment-preserving serialization.

Folded in this shepherd pass:

  • Added hermetic e2e coverage at tests/integration/test_manifest_comments_e2e.py for real apm install rewriting an annotated manifest.
  • Marked live/network integration tests so the non-network e2e suite stays hermetic.
  • Normalized dump-side round-trip YAML exceptions through the existing YAML error path.
  • Documented intentional ruamel constructor registration.
  • Strengthened the changelog entry for user-facing comment and formatting preservation.

Validation:

  • APM_E2E_TESTS=1 uv run pytest tests/integration/test_manifest_comments_e2e.py -v -> passed.
  • Old PyYAML safe_load/safe_dump behavior makes the new e2e fail by stripping comments/formatting.
  • APM_E2E_TESTS=1 uv run pytest tests/integration -m "not requires_network_integration" -p no:cacheprovider -q -> 10158 passed, 154 skipped, 37 deselected, 2 xfailed.
  • Local lint mirror passed.
  • Latest PR checks passed on 47542666dbf5f391e1efc26a7d6eb15fb0cdc5ea.

Deferred follow-up: migrate remaining non-dependency apm.yml writers, such as MCP writer paths, to the same round-trip helpers in a separate bounded PR.

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 4724c0d into main Jul 4, 2026
13 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the bbs/fix-2000 branch July 4, 2026 09:20
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 13, 2026
…3649)

#2000/#2012 made `apm install PKG` / `apm uninstall PKG` rewrite apm.yml
through the ruamel round-trip pair so comments and layout survive. Two
sibling writers of the same consumer manifest still used the lossy
`load_yaml` / `dump_yaml` pair: `apm approve` / `apm deny`
(security/executables.write_project_executables) and `apm install --mcp`
(install/mcp/writer.add_mcp_to_apm_yml). Each run stripped every comment,
expanded anchors/aliases and reflowed flow-style lists.

Route both through `load_yaml_roundtrip` / `dump_yaml_roundtrip`, the
existing comment-preserving owner. The executable-trust architecture
guard now requires the round-trip read in write_project_executables.

apm-spec-waiver: manifest write formatting only, no OpenAPM contract change

Co-authored-by: Copilot App <[email protected]>
Daniel Meppiel (danielmeppiel) added a commit that referenced this pull request Nov 13, 2026
…, graph reconciliation, approvals, manifest corner cases) (#3709)

* fix(lifecycle): reap command scripts when the APM command is interrupted (#3649)

Lifecycle command scripts run in their own session so a timeout can
killpg the tree, but Ctrl+C reaches only the foreground group. An
interrupted apm compile/install exited and released its lifecycle lock
while the pre-compile/pre-install script kept running and writing into
.apm/. _execute_command now reaps the group on any BaseException before
propagating it.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): route JSON MCP config writes through the shared adapter owner (#3649)

Copilot (.github/mcp.json and the Copilot CLI user config), VS Code
(.vscode/mcp.json), Gemini and Kiro read their config with a parser that
returned {} on any JSON error and then rewrote the file, so a user
mcp.json with a JSONC comment or a trailing comma lost every user server
on apm install, with exit 0 and no warning. They now parse through the
base MCPClientAdapter owner (_parse_json_config_for_update, split out of
_read_json_config_for_update) and write through _write_json_config, so an
unparsable file is kept byte-identical and the server is reported failed,
as Cursor and OpenCode already do.

Claude's project .mcp.json now uses the same shared atomic, symlink-safe
writer; its recorded tolerate-and-rewrite parse policy is unchanged.
_write_json_config gains shared=True for committed project config files so
they keep their umask mode instead of 0600.

Static boundary: the MCPClientAdapter owner record gains the
hooks-integrations-mcp-json-config-write guard
(mutation_writes.mcp_json_config_write) with a mutation case: adapters
other than base.py may not serialize JSON straight into a config file.

Co-authored-by: Copilot App <[email protected]>

* test(integration): fault-injection atomicity and fix-guard lifecycle scenarios (#3649)

Installed-CLI scenarios that inject one fault mid-pipeline (read-only
module store, target root replaced by a file, deployed path replaced by a
directory or a symlink, unwritable nested compile output, Ctrl+C during a
fresh install) and assert a failing exit, unchanged apm.lock.yaml and user
bytes, no staging leftovers, and convergence with apm audit --ci.
Fix guards cover MCP config merges that keep unparsable user configs and
interrupted pre-compile scripts.

Co-authored-by: Copilot App <[email protected]>

* test(integration): user-authored same-name collision lifecycle (#3649)

Co-authored-by: Copilot App <[email protected]>

* fix(integration): skip unmanaged same-name native rules instead of overwriting (#3649)

Rule-dir formats (.claude/rules, .cursor/rules, .windsurf/rules,
.kiro/steering) treated any existing file at the derived path as
APM-owned and silently rewrote it, then recorded it so uninstall
deleted it. Route them through the shared BaseIntegrator
_check_adopt_or_skip decision like every other primitive: adopt when
the rendered output already matches, rewrite managed paths, and skip
unmanaged user-authored files unless --force (docs: enterprise/security
Collision detection).

Co-authored-by: Copilot App <[email protected]>

* fix(uninstall): never glob-delete native instruction files without a lockfile (#3649)

Without apm.lock.yaml, uninstall fell back to broad legacy globs and
deleted every .cursor/rules/*.mdc and .github/instructions/*.instructions.md,
including user-authored files. Uninstall only removes lockfile-tracked
paths (docs: reference/cli/uninstall), so drop the instruction legacy
glob like the Claude, Windsurf, Kiro and Copilot user-scope precedents.

Co-authored-by: Copilot App <[email protected]>

* test(integration): JSONC MCP configs survive install across adapters (#3649)

Co-authored-by: Copilot App <[email protected]>

* fix(view): report user-scope provenance for every target in view -g --file (#3649)

apm install -g persists deployment rows whose scope DeploymentLedgerCodec
infers from the path, so only ~/.copilot/ rows say 'user'. view -g --file
skipped every other row and reported 'No recorded provenance' (exit 1)
for ~/.claude, ~/.cursor, ~/.agents and other user-scope files.

Add DeploymentLedgerCodec.locator_in_scope: a path-inferred scope is not
scope evidence; only a recorded scope that differs from the inference
excludes a row. Route file provenance through it and extend the
install-deployment-provenance-state guard to reject raw locator.scope
comparisons outside the codec.

Co-authored-by: Copilot App <[email protected]>

* fix(install): keep files renamed only by case on case-insensitive filesystems (#3649)

When a package renamed a primitive only by letter case (Guide.md ->
guide.md), apm update / install on macOS or Windows treated the existing
APM-owned entry as a user collision (agents, prompts, instructions were
skipped), then stale cleanup deleted the old spelling -- the same entry
the run had just written -- so the package's new files vanished and left
the lockfile, while rules were kept as 'user-edited'.

Add apm_cli.utils.paths.physical_alias, the single owner for 'another
spelling of the same directory entry' (case/NFC only, confirmed with
os.path.samefile). BaseIntegrator.check_collision treats such an alias
of a managed path as managed, and remove_stale_deployed_files renames
the aliased entry to the live spelling instead of deleting it. Extend the
install-deployment-base-integrator guard to keep both routes.

Co-authored-by: Copilot App <[email protected]>

* fix(export-patch): disambiguate patch names that differ only by case (#3649)

patch_filenames disambiguated sanitizer collisions by exact name, so two
packages whose patch names differ only by case (skills/PDF vs skills/pdf)
kept distinct names that macOS and Windows fold into one file; the
second write silently replaced the first patch. Group by casefolded name.

Co-authored-by: Copilot App <[email protected]>

* test(lifecycle): guard spaced and non-ASCII project, HOME and package paths (#3649)

Co-authored-by: Copilot App <[email protected]>

* test(lifecycle): keep the unicode path chain independent of subdirectory patch roots (#3649)

Co-authored-by: Copilot App <[email protected]>

* fix(security): apm approve unlocks github.com dependencies (#3649)

With the executable gate on, `apm approve owner/repo` recorded the grant
under the lockfile identity (`owner/repo#<version>`), but the install gate
looked a package up by `str(dependency_ref)`, which is host-qualified
(`github.com/owner/repo#ref`): the gate called a non-existent
`canonical_string()` and fell back to it. Every dependency on the default
host therefore stayed parked after approval while `apm policy explain`
said "allowed". Non-default hosts and local paths were unaffected.

- security/executables.py owns `dependency_approval_key()`: the lockfile
  identity domain `apm approve` writes, bound to the selected source so a
  replacement still never inherits upstream approval.
- install/exec_gate.py routes `resolve_package_key` through it, and only
  parks a package when one of its DECLARED exec types stays unapproved
  (an approved hooks-only package no longer prints "parked pending
  approval").
- `apm approve --pending` resolves through the same deny-wins ladder as
  install (project, user, org layers) instead of an exact-key lookup in
  one store, so a `--user` grant no longer shows as pending.
- Architecture guard install-deployment-executable-trust-context now
  requires the gate and `--pending` to route through the owner.

apm-spec-waiver: executable trust key routing fix, no OpenAPM contract change

Co-authored-by: Copilot App <[email protected]>

* fix(manifest): approve, deny and install --mcp keep apm.yml comments (#3649)

#2000/#2012 made `apm install PKG` / `apm uninstall PKG` rewrite apm.yml
through the ruamel round-trip pair so comments and layout survive. Two
sibling writers of the same consumer manifest still used the lossy
`load_yaml` / `dump_yaml` pair: `apm approve` / `apm deny`
(security/executables.write_project_executables) and `apm install --mcp`
(install/mcp/writer.add_mcp_to_apm_yml). Each run stripped every comment,
expanded anchors/aliases and reflowed flow-style lists.

Route both through `load_yaml_roundtrip` / `dump_yaml_roundtrip`, the
existing comment-preserving owner. The executable-trust architecture
guard now requires the round-trip read in write_project_executables.

apm-spec-waiver: manifest write formatting only, no OpenAPM contract change

Co-authored-by: Copilot App <[email protected]>

* test(install): racing install and uninstall converge under the lifecycle lock (#3649)

Co-authored-by: Copilot App <[email protected]>

* chore(architecture): register the consumer apm.yml rewrite owner (#3649)

Folds the python-architect review of the approve/deny and install --mcp
round-trip fix: the MCP writer had no static guard. Register owner
`consumer-manifest-rewrite` (utils/yaml_io round-trip pair) with guard
install-deployment-consumer-manifest-rewrite, requiring install,
uninstall, approve/deny and install --mcp to rewrite apm.yml through
load_yaml_roundtrip / dump_yaml_roundtrip, plus its mutation case.

Co-authored-by: Copilot App <[email protected]>

* fix(install): targeted install and update re-read only the selected local packages (#3649)

Since #3571 the shared ref-recheck gate re-staged every local dependency,
so apm install PKG, apm install --update PKG and apm update PKG re-read the
current apm.yml of unselected local packages too. An unrelated sibling with
invalid YAML or an unpublished dependency failed the targeted command, and a
valid edit fetched the sibling's new dependencies into apm_modules without
locking them. Pass the selected-key set for every targeted run and let the
gate recheck a local package only inside that selection; full installs
still re-read every local package.

Co-authored-by: Copilot App <[email protected]>

* fix(lockfile): record a mixed-case parent by its canonical identity (#3649)

A parent declared as Owner/Repo on a case-insensitive host was written as
resolved_by: Owner/Repo while its lock entry is owner/repo, so deps tree
could not place the transitive, deps why lost the chain and changing the
declared casing churned the lockfile. lockfile_parent_identity now returns
the canonical repository identity for legacy locks.

Co-authored-by: Copilot App <[email protected]>

* test(lifecycle): one lock entry across dependency spellings; diamonds fail closed (#3649)

Co-authored-by: Copilot App <[email protected]>

* fix(view): match decomposed (NFD) paths in view --file (#3687)

macOS tools such as Finder drag and drop pass NFD paths for NFC-named
files. view --file compared the query exactly, so an absolute NFD path
exited 2 ('outside the project deploy root') and a relative one exited 1
('origin is unknown') for a recorded file.

When the exact query matches nothing, retry once with its NFC spelling,
but only when utils.paths.physical_alias confirms through the filesystem
that both spellings name the same file; case variants and
normalization-sensitive filesystems keep exact-path semantics. The
install-deployment-base-integrator guard now also requires this route.

Co-authored-by: Copilot App <[email protected]>

* fix(audit): fail audit --ci when the current directory has no apm.yml (#3688)

APM resolves the project from the working directory and does not search
parent directories. From a project subdirectory or a wrong checkout path,
apm audit --ci reported 'All checks passed' and exited 0 although it
audited nothing, a false green for a CI gate.

In --ci mode, run_baseline_checks now always emits a failing
manifest-missing check when apm.yml is absent, naming the fix (run from
the project root that contains apm.yml). Bare audit keeps the advisory
warning only when APM artifacts suggest a deleted manifest.

Co-authored-by: Copilot App <[email protected]>

* fix(install): name obstructed deployment paths with a remedy (#3678)

A directory where APM deploys a file, or a file where it needs a
directory, surfaced as raw '[Errno 21] Is a directory: <abs path>'. A
target root replaced by a regular file was reported as 'Failed to resolve
APM dependencies: [Errno 17] File exists'. Compile printed the same
distributed-batch write error once per target.

utils/file_ops gains the single wording owner (obstructed_path_message,
describe_path_obstruction). The shared integration template formats
integrate failures through it into the existing DiagnosticCollector
entry; skill copies raise a real EISDIR so they share the wording.
materialize_project_target_profiles refuses an obstructed target root
with TargetRootObstructedError, in the PathTraversalError family that the
pipeline already surfaces verbatim (no 'resolve' label); mcp install keeps
its RequiredIntegrationError mapping. AgentsCompiler._merge_results
dedupes errors like warnings.

Co-authored-by: Copilot App <[email protected]>

* fix(cli): route SIGTERM through the Ctrl+C rollback path (#3676)

SIGTERM (a cancelled CI job, docker stop, a timeout) killed apm without
running any finally block: install left apm_modules/.apm-resolution-staging
and modules behind with no report, and lifecycle scripts kept running.
cli.main now installs one handler that raises KeyboardInterrupt, so the
install transaction rollback, failure-residue reporting and lifecycle
script reaping run exactly as for Ctrl+C. The handler restores default
handling first, so a second SIGTERM still terminates.

Static boundary: new owner record process-interrupt-signals (cli.py) with
guard registry-delegation-process-interrupt-signals: main must install the
handler and no other module installs a SIGTERM handler.

Co-authored-by: Copilot App <[email protected]>

* fix(install): release a removed dependency's skill dir that holds only user files (#3677)

When a removed dependency's skill directory also held a user's file,
stale cleanup deleted APM's members but filed the directory as
skipped_unmanaged. That retained the dependency's lockfile row and
pinned its apm_modules copy, so install exited 0 while audit --ci
reported every former file as unintegrated drift and suggested an
install that could never converge; deps list still showed the package.

_safe_remove_skill_directory now files such a directory (every
remaining entry untracked user content) under CleanupResult.released,
which retained never includes: the user's directory and file stay, the
row is dropped, and deps list, prune and audit --ci agree exactly as for
a plain removal. Edited or failed APM members still retain ownership.

Static boundary: the file-level deploy/cleanup owner record now selects
integration/cleanup.py and carries guard
install-deployment-cleanup-ownership-release with a mutation case.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): refuse symlinked project MCP configs and invalid Claude configs

Project MCP configs that are symbolic links, or are reached through one,
are now refused like user-scope ones: MCPClientAdapter applies the policy
in _parse_json_config_for_update (so every adapter entry point gets it)
and in _write_json_config, leaves the link untouched and reports the
target as failed.

Claude Code's .mcp.json and ~/.claude.json now parse through the same
owner, so an invalid file is kept byte-identical and the server is
reported failed, as for Cursor, instead of being rewritten from scratch.

The hooks-integrations-mcp-json-config-write guard now also requires both
owner methods to apply the project symlink policy and rejects a
rewrite-from-scratch path in any adapter.

Co-authored-by: Copilot App <[email protected]>

* fix(lockfile): read an unquoted integer lockfile_version (#3692)

`lockfile_version: 1` (quotes dropped by a hand edit or a YAML tool)
failed every command with the self-contradicting "Unsupported lockfile
version 1; supported versions: 1, 2, 3". The lockfile owner
(require_supported_lockfile_version) now treats an integer as its string
form, and the validated container carries the normalized value so every
reader agrees, including the local-bundle lockfile reader. Booleans, floats and unknown versions still fail closed.

apm-spec-waiver: lockfile version parsing leniency, no OpenAPM contract change

Co-authored-by: Copilot App <[email protected]>

* fix(config): unknown keys are a plain user error with the full key list (#3694)

`apm config get/set <typo>` printed "This error may indicate a bug in
command routing. Please report this issue." for an ordinary typo, and the
valid-key hint was a hand-maintained list per message site (unset also
offered `auto-integrate`, which it rejects).

One registry, `_CONFIG_KEYS` (name, experimental flag, unsettable), now
feeds `_valid_config_keys()`; get/set/unset reject unknown keys through a
single `_reject_unknown_key()` helper. A unit test drives every registered
key through get/set/unset to pin the registry to the dispatch.

Co-authored-by: Copilot App <[email protected]>

* fix(deps): deps list, deps tree and prune name a conflicted lockfile (#3695)

With git merge conflict markers in apm.lock.yaml, `apm deps list` and
`apm deps tree` swallowed the lockfile owner's LockfileConflictError and
exited 0 from an apm_modules scan, and `apm prune` reported "Failed to
parse apm.yml" for the lockfile. All three now surface the same
actionable conflicted-lockfile error as install, audit, outdated and
update (exit 1, path named, lockfile bytes untouched).

Co-authored-by: Copilot App <[email protected]>

* fix(manifest): refuse duplicate top-level keys in apm.yml before any write (#3691)

A merge that left two `dependencies:` blocks made bare `apm install`
(PyYAML last-wins) drop the first block's packages and clean their files
as stale, while `apm install PKG` / `apm uninstall` printed a raw ruamel
DuplicateKeyError.

New read owner models/manifest_io.py: `reject_duplicate_manifest_keys`
composes the top-level mapping (no alias/merge expansion) and raises
DuplicateManifestKeyError naming the file, key and both lines;
`load_manifest` / `load_manifest_roundtrip` read once and route every
acting apm.yml read through it -- APMPackage.from_apm_yml, project
executable trust (approve/deny, install gate), `apm run` config, and the
install PKG, uninstall, install --mcp, approve/deny and adopt rewrites.
`apm deps list` re-raises it instead of showing partial data. The shared
YAML loader is unchanged apart from a text-input round-trip twin
(load_yaml_roundtrip_str).

The consumer-manifest-rewrite owner record and its guard now require the
read routing. Docs: manifest schema and apm-usage troubleshooting.

Co-authored-by: Copilot App <[email protected]>

* fix(install): local bundle install honours apm.yml targets (#3649)

apm install <bundle> resolved targets with an explicit --target or
directory auto-detection only, so a project declaring
targets: [claude, cursor] received .github/ output and nothing for the
declared targets. Route the bundle handler through the canonical
resolve_manifest_target_decision owner (the same one apm install --mcp
uses): --target > apm.yml targets > apm config target > auto-detect.
The install-target-selection guard now requires this route.

Co-authored-by: Copilot App <[email protected]>

* fix(lockfile): link legacy mixed-case parents when reading a lockfile (#3698)

Recording parents canonically left locks written before that change with
children whose resolved_by keeps the declared casing (Acme/Parent) while the
parent entry is acme/parent, so uninstall and targeted installs on an existing
lock missed those descendants until a full install rewrote it. On read, a
legacy resolved_by that names no locked entry is mapped onto the locked entry
with the same case-insensitive identity; case-sensitive hosts are untouched.

Co-authored-by: Copilot App <[email protected]>

* fix(uninstall): remove every declaration of a package; install --dev moves it (#3693)

A package declared twice (in dependencies and devDependencies, or under two
spellings) made apm uninstall exit 'ambiguous' for every spelling, and
apm install --dev X with X in dependencies silently added a duplicate.
Uninstall now removes every declaration of the selected identity through the
selection owner (manifest_declarations_of); distinct local packages behind one
_local alias stay ambiguous. Install follows npm: --dev moves a production
declaration to devDependencies, and a plain install keeps a dev-declared
package where it is, updating that entry in place.

Co-authored-by: Copilot App <[email protected]>

* fix(resolve): reject a repository declared with its own subdirectory package (#3699)

The subdirectory package is installed inside the repository package's
apm_modules directory, so uninstalling the repository deleted it and deps
list hid it. Install and update now fail before fetching anything when root
declarations would nest (nested_materialization_pairs in the materialization
owner); a repository whose own manifest depends on its subdirectory package
still installs.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): report same-name MCP conflicts on every JSON adapter (#3681)

VS Code, Copilot CLI, Cursor, Gemini, Kiro, OpenCode, Windsurf and
Antigravity treated an existing connection with the requested name as
"already configured" and exited 0 even when its definition differed,
so the package server was never written. Route every runtime through
the #3239 native content comparison via one owner,
install.mcp.ownership.native_comparison_clients, driven by the adapter
capability MCPClientAdapter.compares_native_connections (JetBrains and
Hermes opt out). A differing user entry is preserved, named and exits 1
without an ownership claim; an identical one stays unclaimed.

To keep APM's own entries managed on those targets, every successful
write now records a native fingerprint (written_native_hash, read back
through the same detector view), and the base adapter accepts a matching
fingerprint as proof of an earlier write (e.g. a Gemini env value that
resolved differently). VS Code now owns its full-reference config key and
OpenCode's renderer accepts registry env/runtime overrides.

Co-authored-by: Copilot App <[email protected]>

* fix(audit): classify skipped same-name user files as unmanaged conflicts (#3682)

When install skipped a user-authored prompt, agent, command or rule that
shares a package primitive's name, apm audit --ci reported it as managed
'modified' drift with the 'apm export-patch' local-edit hint, which then
had nothing to export; a case-only variant on a case-insensitive
filesystem showed as 'unintegrated'. diff_scratch_against_project now
classifies any differing file no lockfile entry claims (and a case-only
variant occupying the destination) as the existing unmanaged-conflict
kind, so the export-patch hint only counts managed edits, and the
guidance names rename/--force for files as well as skills.

Co-authored-by: Copilot App <[email protected]>

* fix(view): strip the path anchor without the raw relative_to string form (#3687)

Co-authored-by: Copilot App <[email protected]>

* refactor(security): write allowExecutables through the round-trip manifest owner (#3690)

Co-authored-by: Copilot App <[email protected]>

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

apm-spec-waiver: round-2 red-team bug fixes restore existing documented behavior; no OpenAPM spec requirement changes.

Co-authored-by: Copilot App <[email protected]>

* test(lifecycle): promote small round-2 fix guards to lifecycle smoke (#3649)

Co-authored-by: Copilot App <[email protected]>

* docs(changelog): link round-2 entries to #3709

Co-authored-by: Copilot App <[email protected]>

* test(lifecycle): guard frozen replay of an unquoted lockfile_version (#3692)

Co-authored-by: Copilot App <[email protected]>

* test(output-mode): audit a real manifest in the machine-output notice test (#3688)

audit --ci now fails without apm.yml (#3688), so the parametrized
machine-output cases hit SystemExit(1) before checking stdout. The update
notice already stays on stderr; give those cases a minimal apm.yml so
they keep testing a passing gate, and add a failing-gate case proving
stdout stays one JSON document when the gate exits 1.

Co-authored-by: Copilot App <[email protected]>

* test(prune): reach the released-root trim through a valid declaration switch (#3699)

The direct and dev cases declared a repository together with its own
subdirectory package, which #3699 now rejects before resolution. They now
install the repository first and then switch the declaration to the
subdirectory package (in dependencies or devDependencies), the #2926 switch
the trim exists for; the transitive case is unchanged. #3677's released
skill directories were not involved.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): keep Claude Code's trailing newline in shared JSON config writes (#3649)

Claude's project .mcp.json moved to the shared MCPClientAdapter writer,
which writes JSON without a trailing newline (the historical bytes of the
other JSON adapters), so committed .mcp.json files churned. The writer now
honours an adapter-declared json_config_trailing_newline (alongside
mcp_servers_key); Claude Code sets it, every other adapter keeps its bytes.

Co-authored-by: Copilot App <[email protected]>

* fix(security): key replacement consent by the declared with: source (#3689)

#3689 keyed executable approval by `source_reference.get_unique_key()`.
For a local replacement (`replace: [{for: ..., with: {path: ../local}}]`)
the bound reference carries an absolute materialization anchor, so the
key became `local:/abs/path` and a grant for the declared `../local`
never matched: the replacement's hooks stayed parked
(test_replacement_hook_consent_stays_with_selected_source).

dependency_approval_key now drops that anchor for replacements, keying
consent by the `with:` source as the consumer declared it. An upstream
grant still never unlocks the replacement, and default-host approval
keys are unchanged.

apm-spec-waiver: executable trust key for local replacements, no OpenAPM contract change

Co-authored-by: Copilot App <[email protected]>

* test(pack): stop appending a duplicate dependencies key after apm init (#3691)

apm init already writes an empty dependencies block; appending a second
one is now rejected as a duplicate top-level key.

Co-authored-by: Copilot App <[email protected]>

* fix(install): release user-content skill dirs only for departing owners (#3677)

#3677 released a skill directory kept only for user content in every
cleanup pass, so narrowing a still-declared dependency's targets dropped
its directory claim from the lockfile. Release now applies only to orphan
cleanup (failed_path_retained=False, the owner is leaving the lockfile);
intra-package stale cleanup retains the claim as before, so a later
install still removes the directory once the user's file is gone. The
static guard and mutation case follow the scoped condition.

Co-authored-by: Copilot App <[email protected]>

* test(mcp): align adapter tests with the shared JSON config owner (#3649)

VS Code update_config writes through MCPClientAdapter._write_json_config
(atomic temp file + os.replace), so patching builtins.open no longer
injects a write error; the write-error tests now fail the owner's
atomic_write_text and still assert False plus the logged/printed error.
The Claude corrupted-.mcp.json test now asserts the approved fail-closed
contract: the file is kept as-is and update_config returns False.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): compare native MCP entries by JSON type, not Python equality (#3681)

Native comparison used Python equality, where True == 1, so an OpenCode
enabled: true entry matched a declaration that changed it to enabled: 1
and the managed entry was never rewritten. MCPClientAdapter.json_identical
compares sorted JSON text; the base matches_managed_server_config and
the registry-request comparison in compare_native_mcp_connection use it.

Co-authored-by: Copilot App <[email protected]>

* test(lifecycle): expect unmanaged-conflict for the skipped Kiro prompt collision (#3682)

The user-authored .kiro/prompts/collision.md is never recorded by
install, so audit now reports it as unmanaged-conflict instead of a
managed local edit, per the approved #3682 contract.

Co-authored-by: Copilot App <[email protected]>

* refactor(audit): give drift claim membership its own owner and register its guards (#3682)

Moves replay claim membership (claimed_prefixes and the unclaimed
predicate behind the #3682 unmanaged-conflict classification) from
install/drift.py into install/drift_claims.py (ReplayClaims), bringing
drift.py back under its LOC budget without raising it.

Registers the #3681/#3682 static checks as canonical owner guards
instead of guard-less registry_delegation rules:
install-deployment-mcp-native-comparison on the MCP ownership owner and
install-deployment-drift-claim-classification on the new
drift-claim-membership owner, each with a MutationCase and an entry in
the frozen rule inventory.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): keep APM-written entries until their declaration changes (#3681)

Native comparison rewrote an unchanged, APM-written entry on VS Code,
Copilot, Cursor, Gemini, Kiro and OpenCode whenever its render changed
only through the install environment (GitHub auto-auth credential source
precedence, resolved env values), churning native files the previous
name-only behavior kept stable. compare_native_mcp_connection now takes
declaration_changed and returns MATCHING_MANAGED for an unchanged
declaration unless the adapter opts into refreshes_environment_renders
(Claude and Codex, which already reconcile such renders). Registry
declaration drift is now detected for every compared server, so a real
declaration change (e.g. OpenCode enabled true -> 1) still rewrites.

Co-authored-by: Copilot App <[email protected]>

* test(mcp): align MCP and drift tests with the #3681/#3682 contracts (#3681)

Tests that encoded the pre-#3681 name-only behavior now expect a
differing same-name user connection on Cursor/OpenCode to be preserved
and reported (exit 1); scenarios meant to exercise unowned names use an
identical foreign entry instead. Name-only 'already configured'
characterisations patch native_comparison_clients to the opt-out set.
The deps-model drift test tracks its path so it stays a managed edit
(#3682). Frozen rule inventory kept in sorted order.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): retain the receipt of a managed MCP entry that already matches (#3681)

A managed self-defined connection that already matches is not rewritten,
so a lockfile rebuilt without its deployment rows lost the native
fingerprint on the next install and the repaired lock differed from the
original. retain_native_receipt records the existing entry's fingerprint
when none is held.

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): compare VS Code entries against the render that keeps optional fields (#3681)

VS Code's write path keeps optional registry fields the existing entry
already carries, but native comparison rendered without them, so an
entry identical to what APM would write compared as a conflict.
render_server_config now passes the existing entry like
configure_mcp_server does. The reinstall test now expects that identical,
unowned entry to be left alone (no rewrite, no conflict).

Co-authored-by: Copilot App <[email protected]>

* docs(lockfile-spec): wrap the MCP receipt paragraph (#3681)

Co-authored-by: Copilot App <[email protected]>

* test(e2e): declare sibling subdirectory packages in the private fallback scenario (#3699)

The branch case declared fixture-private/private-package together with its
own subdirectory package, which install now rejects. Declare two sibling
subdirectory packages of the same private repository instead: the scenario
still proves the scoped credential fallback, locale normalization and the
subdirectory (partial clone) path; the semver case keeps the whole-repository
clone.

Co-authored-by: Copilot App <[email protected]>

* fix(manifest): refuse duplicate top-level keys on the same line (#3691)

Folds Copilot review 4558274750 on #3709. reject_duplicate_manifest_keys
compared line numbers, so two `dependencies:` entries in one flow-style
mapping (same line) reached the last-wins loader and install could remove
the first entry's deployments. Duplicates are now detected by key
identity; a same-line duplicate reports "twice on line N" and asks to
merge both entries.

Co-authored-by: Copilot App <[email protected]>

* perf(install): index spelling aliases once per inventory (#3684)

physical_alias rescanned and NFC/casefold-normalized the whole candidate
inventory on every lookup, so stale cleanup cost O(stale x live) and every
existing unmanaged collision destination cost O(managed), even when no
alias existed.

The utils.paths spelling owner now offers SpellingAliasIndex (built once
per inventory; lookups hash the queried spelling and samefile only its
bucket) and stored_alias (looks up the filesystem's stored spelling of an
existing entry, plus its NFC/NFD forms for HFS+, in the inventory: a few
set lookups). Stale cleanup builds one index per call; check_collision
uses stored_alias. physical_alias stays as the one-shot wrapper. The
install-deployment-base-integrator guard and owner record follow.

Co-authored-by: Copilot App <[email protected]>

* fix(view): keep the root spelling when retrying a decomposed --file path (#3687)

The NFD retry normalized the whole absolute path, including the deploy
root. When the project (or target) root itself is stored decomposed, the
NFC path no longer matched _roots(deploy_root), so an NFD query for an
NFC-recorded member still had no provenance.

Compare query and each deploy/target root in NFC, then rebuild the
candidate as <root as spelled>/<NFC member>; physical_alias still
confirms the filesystem names one file.

Co-authored-by: Copilot App <[email protected]>

* fix(install): keep a declaration's fields when install moves or keeps it across sections (#3693)

Cross-section reconciliation ran after validation against only the
destination section, so a bare apm install X dropped the ref of X's
devDependencies declaration, and apm install --dev X moved a bare copy that
lost the production entry's ref, skills restriction or registry source.
Expose the existing declaration to validation first (borrow), so its
explicit-change rules decide what the CLI changes, then return a kept
declaration to its position (settle).

Co-authored-by: Copilot App <[email protected]>

* fix(mcp): keep the VS Code full-reference config key on the public determine_config_key (#3681)

#3672 promoted MCPClientAdapter.determine_config_key to public; the VS Code
override still named the old private method, so its full-reference keys were
bypassed after the rebase.

Co-authored-by: Copilot App <[email protected]>

* test(cleanup): give round-2 cleanup tests the recorded hashes #3663 requires

Since #3672 stale cleanup deletes only files whose recorded hash still
matches, so the alias-index and released-directory tests now pass the
recorded hash of each APM-deployed member.

Co-authored-by: Copilot App <[email protected]>

---------

Co-authored-by: danielmeppiel <[email protected]>
Co-authored-by: Copilot App <[email protected]>
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.

[BUG] apm install removes all comments from apm.yml

2 participants