Skip to content

fix(compile): avoid duplicate global Claude instructions - #2793

Open
Josh Smith (cmyui) wants to merge 4 commits into
microsoft:mainfrom
cmyui:fix/global-claude-instruction-dedup
Open

fix(compile): avoid duplicate global Claude instructions#2793
Josh Smith (cmyui) wants to merge 4 commits into
microsoft:mainfrom
cmyui:fix/global-claude-instruction-dedup

Conversation

@cmyui

Copy link
Copy Markdown

fix(compile): avoid duplicate global Claude instructions

TL;DR

Global compilation now omits instructions already delivered by equivalent Claude user rules, while retaining uncovered instructions and other targets' output. apm compile -g --clean can remove an unchanged, fully redundant Claude root; ordinary compilation leaves it in place and explains the cleanup command.

Fixes #2792. Follows the project-mode work in #1138 / #1146 and explicit cleanup in #1729 / #1747.

Important

Cleanup is intentionally conservative: a generated marker alone is insufficient. Older, edited, partially compiled, or symlinked roots are retained when they cannot be verified against the current complete instruction set.

Problem (WHY)

  • A real install -g followed by compile -g places the same unconditional instruction in both Claude's native rules and CLAUDE.md. The regression test failed on main at c6fde641 for both default and external CLAUDE_CONFIG_DIR paths.
  • Global compilation bypasses project deduplication, and previously rejected --clean. Suppressing new output alone would leave existing duplicates active.
  • [!] Filename presence alone does not prove coverage: partial installs, stale rules, scoped rules, and same-name package instructions need distinct treatment.

The context-budget concern is the same one described in Agent Skills: “Every token in your skill competes for the agent’s attention with everything else in that window.” Here the extra text is a second delivery of the same instruction, not additional guidance.

Approach (WHAT)

  • Compare each native rule with the existing integrator's rendered output, including converted frontmatter and rewritten links.
  • Keep the compiled fallback for missing, different, unreadable, or unsafe rules. Other targets still receive their full instruction set.
  • When all Claude instructions are covered, create no new root. Retain an existing duplicate unless --clean was requested.
  • For cleanup, require a regular non-symlink root matching the expected complete generated output. Pass its independently computed expected hash through the existing shared cleanup safety gates.
  • Keep --dry-run read-only, support custom Claude roots outside home, and report retained files and actual removals.

Implementation (HOW)

Paths below are relative to the repository; runtime modules are under src/apm_cli/.

File Purpose
compilation/instruction_dedup.py Shared native coverage checks; reuse the install renderer rather than recreate native serialization.
compilation/agents_compiler.py Delegate existing project detection/naming through compatibility aliases; retain its historical any-match policy.
integration/instruction_integrator.py Extract the existing rule filename calculation for install and compile to share.
compilation/user_root_context.py Filter Claude instructions, preserve fallback, and implement explicit verified redundant-root cleanup.
integration/cleanup.py Forward the existing validator's optional prefix override; default callers and safety gates are unchanged.
commands/compile/cli.py Accept global --clean, render outcomes, and count removals in summaries.
.apm/architecture/owners/core-runtime.json Register the shared native-rule coverage owner.
scripts/architecture_linter/checks/registry_owner_guards.py Guard delegation to shared detection, naming, and rendering.
tests/integration/test_architecture_owner_rule_mutations.py Verify the new guard detects bypassing the install renderer.
tests/unit/scripts/test_architecture_runner.py Include the new guard in the frozen rule inventory.
tests/unit/compilation/test_instruction_dedup.py Cover rendered links, partial coverage, collisions, scoped/stale rules, and unsafe paths.
tests/unit/compilation/test_global_claude_dedup.py Cover fallback, cleanup, dry-run, edited files, symlinks, and removal failures.
tests/unit/integration/test_cleanup_helper.py Prove the explicit prefix override retains containment and provenance protections.
tests/integration/test_global_claude_dedup.py Exercise real install/compile commands and cleanup transitions in isolated homes.
docs/src/content/docs/reference/cli/compile.md Document native coverage and the precise global cleanup boundary.
packages/apm-guide/.apm/skills/apm-usage/commands.md Keep the shipped usage guidance aligned.
CHANGELOG.md Record the user-visible fix under Unreleased.

Diagrams

Legend: dashed nodes are the new Claude coverage and cleanup decisions; other targets retain their full output.

flowchart LR
    subgraph Source[Source]
        A["Global instructions"]
    end
    subgraph Coverage[Native coverage]
        B["uncovered_instructions: compare install-rendered content"]
        C["Uncovered instructions"]
        D["All instructions covered"]
    end
    subgraph Output[Output]
        E["CompiledOutputWriter: fallback only"]
        F["No new Claude root"]
        G["Existing root retained unless --clean and exact expected output"]
        H["remove_stale_deployed_files or read-only preview"]
        I["Other targets: full instruction set"]
    end
    A --> B
    A --> I
    B --> C --> E
    B --> D --> F
    D --> G --> H
    classDef new stroke-dasharray: 5 5;
    class B,C,D,F,G,H new;
Loading

Trade-offs

  • Conservative cleanup rather than a new ownership ledger. Global roots have no recorded deployment hash. Exact comparison to the current complete generated output proves the common existing-duplicate case, but older or partially compiled roots can require manual review.
  • Rendered equality rather than filename-only suppression. This performs bounded package discovery/rendering for existing candidate rules, avoiding loss of instructions when names collide or deployed content differs.
  • Narrow global fix. Project compilation retains its any-match policy, with shared safe-path checks. This does not redesign project deduplication, native scoped-rule placement, or cleanup after target contraction.

Benefits

  1. A fully covered native-only Claude installation stays without a generated root.
  2. Partial installs keep every uncovered instruction; Codex still receives the complete set.
  3. Existing verified duplicates have an explicit preview/removal workflow without deleting native rules or unverified user content.

Validation

uv run pytest tests/unit tests/test_console.py -x -q -n 8:

21155 passed, 4 skipped, 21 xfailed, 21 warnings, 99 subtests passed in 59.02s

uv run pytest tests/integration/test_global_claude_dedup.py -q -n 0:

5 passed in 0.70s

The original two unlinked install/compile cases failed before the fix because the duplicate CLAUDE.md existed. They now pass, along with linked-content and cleanup cases.

Ruff lint/format, pylint R0801, YAML I/O, file-length, portable-path, auth-signal, and architecture boundary checks passed. The Mermaid diagram was validated and rendered with mmdc.

Pre-existing architecture mutation-matrix failures

The matrix completeness/order checks fail identically in an untouched worktree at base c6fde64188c86ed2e6047a35e9ea4716df9eb1fc:

Extra items in the right set:
'install-deployment-lifecycle-serialization'

At index 25 diff: 'install-deployment-executable-trust-context' != 'install-deployment-bundle-native-layout'

Base command: python -m pytest tests/integration/test_architecture_owner_rule_mutations.py -q -n 0 -k 'matrix_covers or matrix_case_order':

2 failed, 232 deselected in 0.39s

Branch command: uv run pytest tests/integration/test_architecture_owner_rule_mutations.py -q -n 0 -k 'matrix_covers or matrix_case_order or instruction-deduplication':

2 failed, 3 passed, 232 deselected in 4.40s

The three checks for the new deduplication guard pass. Unrelated baseline matrix defects are left unchanged; this is not a claim that every CI job is green.

Scenario Evidence

# Scenario (user promise) Principle(s) Test(s) proving it Type
1 Install once, then compile without duplicating Claude guidance; keep Codex output Multi-harness support tests/integration/test_global_claude_dedup.py::test_installed_global_rules_are_not_compiled_again (regression-trap for #2792) integration
2 Custom Claude config roots and rewritten package links work Portability by manifest Same parametrized install/compile test above integration
3 Missing, stale, or scoped native rules do not hide global guidance Multi-harness support tests/unit/compilation/test_global_claude_dedup.py::test_only_equivalent_instructions_are_omitted unit
4 Same-named instructions from different packages keep the unmatched fallback Multi-harness support tests/unit/compilation/test_instruction_dedup.py::test_same_filename_omits_only_matching_package_content unit
5 Preview cleanup, remove only the verified duplicate, then repeat safely DevX (pragmatic as npm) tests/integration/test_global_claude_dedup.py::test_global_clean_previews_then_removes_only_redundant_claude_root integration
6 Preserve hand-written, edited, older, unreadable, or symlinked roots Secure by default tests/unit/compilation/test_global_claude_dedup.py::test_cleanup_preserves_unverifiable_content, test_cleanup_preserves_root_symlinks, test_cleanup_preserves_cyclic_root_symlink unit
7 Unsafe or cyclic native rules retain fallback instead of crashing or suppressing content Secure by default tests/unit/compilation/test_instruction_dedup.py::test_escaping_native_symlink_keeps_fallback, test_cyclic_native_symlink_keeps_fallback unit
8 Failed deletion reports an error without losing the root DevX (pragmatic as npm) tests/unit/compilation/test_global_claude_dedup.py::test_cleanup_error_is_reported_without_losing_root unit

How to test

  • uv sync --extra dev to install the development dependencies.
  • Run uv run pytest tests/integration/test_global_claude_dedup.py -q -n 0; all five synthetic CLI scenarios should pass without touching your installed global context.
  • Run uv run pytest tests/unit/compilation/test_global_claude_dedup.py tests/unit/compilation/test_instruction_dedup.py tests/unit/integration/test_cleanup_helper.py -q -n 0; fallback, ownership, and path-safety cases should pass.
  • Run bash scripts/lint-architecture-boundaries.sh; it should exit zero. The unrelated mutation-matrix failures are documented above.

apm-spec-waiver: Critical-path integration edits only extract existing rule naming and forward the existing path-validator override; current callers and registered deployment contracts are unchanged. Observable behavior changes are confined to the user-scope compiler.

@microsoft-github-policy-service

Copy link
Copy Markdown

Josh Smith (@cmyui) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

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.

🟢 Approval recommended

The changes are consistently routed through shared owners, include explicit safety gates for cleanup, and are backed by targeted unit/integration tests plus architecture guard enforcement.

Pull request overview

This PR updates global user-scope compilation to avoid duplicating Claude instructions when equivalent content is already present in Claude’s native user rules, while preserving fallback output for uncovered/mismatched/unsafe cases and adding a conservative, opt-in cleanup path for redundant generated roots.

Changes:

  • Introduces shared “native-rule coverage” logic that compares compiled instruction output against the install-rendered native rule content (including link rewriting/frontmatter effects) and uses it to filter Claude’s global compiled root.
  • Adds an explicit --clean behavior for apm compile -g to remove only a verified, unchanged, fully redundant CLAUDE.md (with dry-run preview), without affecting other targets’ outputs.
  • Registers and enforces the new shared ownership via the architecture linter guard, plus unit/integration coverage and docs/guide updates.
File summaries
File Description
src/apm_cli/compilation/instruction_dedup.py New shared dedup/coverage owner that checks installed native rules using the canonical install renderer.
src/apm_cli/compilation/user_root_context.py Filters Claude global compiled output based on native-rule equivalence and implements conservative redundant-root cleanup (clean/dry_run).
src/apm_cli/compilation/agents_compiler.py Routes prior project-mode rule detection/expected-filename logic through the new shared owner (removes local duplicates).
src/apm_cli/integration/instruction_integrator.py Extracts canonical native rule filename computation for reuse by both install and compile/dedup paths.
src/apm_cli/integration/cleanup.py Allows trusted callers to pass an explicit allowed-prefix override through to the existing path validator (without weakening other gates).
src/apm_cli/commands/compile/cli.py Wires global --clean into user-root compilation, improves per-target reporting, and updates summary counts/messages.
scripts/architecture_linter/checks/registry_owner_guards.py Adds an architecture guard ensuring dedup logic stays delegated to the shared owners and preventing local re-implementations.
.apm/architecture/owners/core-runtime.json Registers the “native instruction coverage and deployed rule filenames” decision ownership + guard.
tests/unit/compilation/test_instruction_dedup.py Unit/component coverage for equivalence checks (links, scoped rules, collisions, unreadable/unsafe paths).
tests/unit/compilation/test_global_claude_dedup.py Unit coverage for global Claude filtering and conservative cleanup outcomes (dry-run, symlinks, edited/older/unreadable roots, failures).
tests/integration/test_global_claude_dedup.py End-to-end CLI scenarios covering install→compile dedup and explicit cleanup transitions in isolated homes/config roots.
tests/unit/integration/test_cleanup_helper.py Proves the explicit-prefix override does not bypass containment/provenance/directory guards.
tests/integration/test_architecture_owner_rule_mutations.py Mutation test ensuring the new guard detects bypassing the canonical install renderer.
tests/unit/scripts/test_architecture_runner.py Updates the frozen architecture-rule inventory to include the new guard.
docs/src/content/docs/reference/cli/compile.md Documents global Claude native-rule coverage behavior and the conservative --clean boundary.
packages/apm-guide/.apm/skills/apm-usage/commands.md Updates shipped usage guidance to reflect global Claude dedup + safe cleanup workflow.
CHANGELOG.md Adds an Unreleased/Fixed entry for the user-visible global compile dedup + conservative cleanup behavior.
Review details
  • Files reviewed: 17/17 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Josh Smith (cmyui) and others added 4 commits September 4, 2026 15:30
Fixes microsoft#2792. Compare installed native rules through the existing renderer, preserve uncovered instructions, and allow explicit cleanup of an unchanged redundant global Claude root.

apm-spec-waiver: Critical-path integration edits only extract existing rule naming and forward the existing path-validator override; current callers and registered deployment contracts are unchanged. Observable behavior changes are confined to the user-scope compiler.
Run the compiled-output security gate when native Claude coverage suppresses a root write, keep --force-instructions as the global dedupe override, and surface native-rule verification warnings through CommandLogger. Addresses panel follow-ups from supply-chain, DevX, and CLI logging review.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@danielmeppiel
Daniel Meppiel (danielmeppiel) force-pushed the fix/global-claude-instruction-dedup branch from f722aeb to 34ecebf Compare September 4, 2026 19:35
@cmyui

Copy link
Copy Markdown
Author

Quick update: my employer’s legal team is reviewing the CLA and the authorization needed for me to sign it. I’ll follow up once that review is complete. Thanks for your patience!

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.

Global compile duplicates instructions already deployed to Claude user rules

3 participants