Skip to content

fix: preserve hand-authored root context files (closes #2767) - #2779

Merged
Daniel Meppiel (danielmeppiel) merged 15 commits into
mainfrom
fix/protect-hand-authored-context
Sep 3, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 15 commits into
mainfrom
fix/protect-hand-authored-context

Conversation

@danielmeppiel

@danielmeppiel Daniel Meppiel (danielmeppiel) commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator

fix(compile): preserve hand-authored root context files

TL;DR

Project-scope apm compile now checks existing root AGENTS.md and
CLAUDE.md files for the APM-generated marker before writing. Files without
that marker are retained with a warning, including files under an explicit
--root, closing the data-loss path reported in #2767.

Important

Generated root files remain writable; only unmarked, hand-authored root files
are protected.

Problem (WHY)

This fix brings project compilation in line with that marker-gated contract.

Approach (WHAT)

# Fix
1 Route root write eligibility through one AgentsCompiler helper.
2 Remove protected Claude and distributed AGENTS outputs before batch writes.
3 Carry the single-file decision to the CLI's constitution-aware final write.
4 Register and mutation-test the canonical architecture owner.
5 Document project and --root protection in both user reference surfaces.

Implementation (HOW)

  • src/apm_cli/compilation/agents_compiler.py - Adds the marker-gated
    eligibility owner and applies it to Claude, distributed AGENTS, and legacy
    single-file output paths.
  • src/apm_cli/commands/compile/cli.py - Honors the compiler's blocked-write
    result before the CLI performs its constitution-aware final AGENTS write.
  • .apm/architecture/owners/core-runtime.json - Extends the existing agent
    output preparation owner with root overwrite eligibility.
  • scripts/architecture_linter/checks/registry_semantic_rules.py - Requires
    every affected call path to route through the compiler owner and rejects a
    second similarly named owner.
  • tests/integration/test_architecture_owner_rule_mutations.py - Adds a
    mutation that introduces a second CLI owner and proves the static rule catches
    it.
  • tests/unit/compilation/test_project_root_context_protection.py - Covers
    distributed, single-file, dry-run, live, and redirected-root behavior.
  • docs/src/content/docs/reference/cli/compile.md - Documents project root
    overwrite protection.
  • packages/apm-guide/.apm/skills/apm-usage/commands.md - Mirrors the
    command contract in the packaged usage guide.

Diagrams

Legend: the dashed nodes are the new eligibility decision and protected outcome.

flowchart LR
    E[existing root context] --> O[root overwrite eligibility]
    O -->|APM marker found| W[write generated output]
    O -->|APM marker absent| S[retain file and warn]
    classDef new stroke-dasharray: 5 5;
    class O,S new;
Loading

Trade-offs

  • Skip rather than merge. Full-file root outputs are retained unchanged;
    automatic content merging would invent ownership boundaries that do not exist.
  • No force flag. Users can explicitly delete or rename the hand-authored
    file before compiling; this keeps the fix bounded and avoids adding CLI
    surface in a data-loss repair.
  • Root-only protection. Nested distributed files retain their existing
    behavior; the reported destructive contract concerns root context files.

Benefits

  1. Live project compiles retain both tested hand-authored root file types.
  2. Dry runs report the same two protected outcomes without touching either file.
  3. Explicit --root destinations receive the same marker check.
  4. A static mutation test prevents a second overwrite authority from landing.

Validation

Focused regression suites on the final implementation:

15 root-protection tests passed
30 user/global-root tests passed
116 cleanup/distributed tests passed
163 compiler/marker tests passed
282 architecture-owner tests passed

Mutation-break probes removed the containment guard, exact-header check,
protected-file stats, blocked-preview condition, and partial-result reporting.
Every affected regression test failed, confirming all five traps kill their
production mutation.

The complete CI lint mirror, source-safety guards, and architecture boundary
entrypoint passed locally.

Scenario Evidence

# Scenario (user promise) Principle(s) Test(s) proving it Type
1 Project compile retains hand-authored root AGENTS.md and CLAUDE.md files in live and preview modes Multi-harness support, DevX tests/unit/compilation/test_project_root_context_protection.py::test_compile_preserves_hand_authored_project_root_context (regression-trap for #2767) integration
2 Compile with an explicit output root retains an existing hand-authored CLAUDE.md Multi-harness support, DevX tests/unit/compilation/test_project_root_context_protection.py::test_compile_root_preserves_hand_authored_context (regression-trap for #2767) integration
3 A second root overwrite decision owner is rejected Governed by policy tests/integration/test_architecture_owner_rule_mutations.py integration
4 Managed-section compilation rejects a root AGENTS.md symlink that escapes the project and leaves its external target unchanged Secure by default, DevX tests/unit/compilation/test_project_root_context_protection.py::test_managed_section_rejects_external_agents_symlink integration

How to test

  • Create a project with unmarked root AGENTS.md and CLAUDE.md files.
  • Run apm compile and confirm both files are unchanged with skip warnings.
  • Run apm compile --dry-run and confirm the same warnings without writes.
  • Run apm compile --target claude --root <dir> against an unmarked
    <dir>/CLAUDE.md and confirm it remains unchanged.
  • Delete the root files, compile again, and confirm generated files are
    created with APM markers.
  • Point root AGENTS.md at an external file with a symlink in managed-section mode and confirm compilation exits non-zero without changing the external file.

Closes #2767

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.

Copilot review overview

🟡 Changes recommended

There are a few correctness/guarding issues (marker detection robustness, noisy/non-ASCII-prone warning content, and a bypassable duplicate-owner regex) that should be addressed before approval.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review tier: Lite
Findings: 1 High severity · 2 Medium severity · 1 Low severity

New issues introduced by this change (4)
Severity Finding
High severity src/​apm_cli/​compilation/​agents_compiler.py — The overwrite-eligibility check treats a file as APM-generated if the marker appears anywhere in…
Medium severity scripts/​architecture_linter/​checks/​registry_semantic_rules.py — The duplicate-owner detector regex requires the entire function signature (including ) and :)…
Medium severity src/​apm_cli/​compilation/​agents_compiler.py — The warning for an unreadable/undecodable root context file interpolates the raw exception string…
Low severity src/​apm_cli/​commands/​compile/​cli.py — When agents_write_blocked is true in a dry run, the current top-level message doesn't indicate…
What changed in this PR

Aligns project-scope apm compile with the existing marker-gated overwrite contract by preventing destructive writes to hand-authored root AGENTS.md / CLAUDE.md (including when --root redirects outputs), and adds an architecture guard + tests to keep the decision centralized.

Changes:

  • Add a canonical compiler-owned helper to block writes to unmarked root context files and thread that decision through single-file, Claude, and distributed output paths.
  • Teach the compile CLI to honor the compiler’s blocked-write result for the final constitution-aware AGENTS.md write.
  • Add static architecture enforcement + mutation coverage, plus unit/component regression tests and docs updates describing the contract.
File Description
src/​apm_cli/​compilation/​agents_compiler.py Implements root overwrite eligibility helper and applies it across output paths; emits warnings and stats for blocked writes.
src/​apm_cli/​commands/​compile/​cli.py Skips final AGENTS.md write when compiler blocks overwrite; reports the blocked outcome.
scripts/​architecture_linter/​checks/​registry_semantic_rules.py Adds a semantic rule to enforce the single canonical owner and detect duplicate implementations.
.apm/​architecture/​owners/​core-runtime.json Extends the registered owner/guards to include root context write eligibility.
tests/​unit/​compilation/​test_project_root_context_protection.py Regression coverage for preserving hand-authored root AGENTS.md/CLAUDE.md in live/dry-run and redirected-root scenarios.
tests/​integration/​test_architecture_owner_rule_mutations.py Mutation that introduces a second owner in the CLI to prove the static rule catches it.
docs/​src/​content/​docs/​reference/​cli/​compile.md Documents project/root overwrite protection in the CLI reference.
packages/​apm-guide/​.apm/​skills/​apm-usage/​commands.md Mirrors the updated compile contract in the packaged usage guide.

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

Comment on lines +1811 to +1812
if marker in prefix:
return False
Comment on lines +185 to +188
_ROOT_CONTEXT_DUPLICATE_PATTERN = (
r"^\s*def\s+\w*(?:hand_authored.*root_context|root_context.*hand_authored)"
r"\w*\([^)]*\)\s*(?:->[^:]+)?:"
)
Comment on lines +1806 to +1809
self.warnings.append(
f"Skipped {rel_path}: could not verify the APM-generated marker; "
f"file will not be overwritten ({exc!s})."
)
Comment on lines +890 to +894
if agents_write_blocked:
logger.progress(
"AGENTS.md not generated -- protected hand-authored root file retained",
symbol="info",
)
@danielmeppiel

Daniel Meppiel (danielmeppiel) commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

APM Review Panel: ship_now

APM compile now preserves hand-authored root AGENTS.md and CLAUDE.md, strengthening first-run trust without adding architecture, auth, performance, or docs risk.

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

The panel converges: the retained-file behavior is now routed through the compiler-owned write-eligibility gate, CLI and watch output give actionable warnings, docs and changelog explain the safer contract, and the security posture fails closed for unowned or unverifiable root context files. The only remaining finding is a python-architect nit that affirms the current design as the simplest correct shape for this scope.

The highest-signal validation supports shipping: targeted pytest is green at 360 passed and 1 skipped, the mutation-break for redirected root AGENTS coverage failed when the guard was removed and passed when restored, and the full PR check suite is green. This is a trust fix, not a scope expansion: it closes the clobbering failure mode while preserving normal generated-output behavior for APM-owned files.

Aligned with: secure by default: unmarked or unverifiable root AGENTS.md and CLAUDE.md now fail closed by being retained instead of overwritten; governed by policy: APM-generated markers define compiler ownership before root context files are rewritten; OSS community driven: the PR resolves a user-trust issue by protecting existing hand-authored project context; pragmatic as npm: users get clear warnings and recovery guidance without needing a new policy surface.

Growth signal. This is worth a release-note beat: apm compile will not clobber hand-authored root AGENTS.md or CLAUDE.md, including --root scratch outputs.

Panel summary

Persona B R N Takeaway
Python Architect 0 0 1 Root context protection routes through the compiler-owned write-eligibility gate with behavioral and static guardrails; no architecture changes requested.
CLI Logging Expert 0 0 0 CLI output reports retained hand-authored root context files with actionable warnings; no logging issues found.
DevX UX Expert 0 0 0 Root-context protection is documented and reports clear retain/recovery guidance; no DevX UX concerns.
Supply Chain Security Expert 0 0 0 Root AGENTS/CLAUDE protection now fails closed on unowned or unverifiable files; no supply-chain security concerns from this diff.
OSS Growth Hacker 0 0 0 Ship from the growth lens: this strengthens first-run trust and the docs/changelog explain the safer behavior clearly.
Doc Writer 0 0 0 Docs now reflect root context protection and link to the canonical manifest schema; no doc-writer concerns.
Test Coverage Expert 0 0 0 Root context preservation surfaces have regression traps; no remaining test-coverage gaps.
Performance Expert 0 0 0 No performance concerns: added compile protection is O(1) per root output with bounded 4096-byte marker reads.

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

Architecture

classDiagram
    direction LR
    class CompileCommand {
      <<IOBoundary>>
      +compile(ctx, output, target, root, global_) None
      +_report_protected_no_write(...) None
    }
    class CompilationConfig {
      <<ValueObject>>
      +target CompileTargetType
      +strategy str
      +agents_md_mode str
      +dry_run bool
    }
    class CompilationResult {
      <<ValueObject>>
      +success bool
      +warnings list
      +errors list
      +stats dict
    }
    class AgentsCompiler {
      <<CanonicalOwner>>
      +compile(config, logger) CompilationResult
      +_prepare_distributed_file(path, content, config) str
      +_hand_authored_root_context_blocks_write(path) bool
    }
    class CompiledOutputWriter {
      <<CanonicalWriter>>
      +write(path, content)
      +write_many(outputs)
    }
    CompileCommand ..> CompilationConfig : builds
    CompileCommand ..> AgentsCompiler : invokes
    CompileCommand ..> CompilationResult : renders
    AgentsCompiler ..> CompiledOutputWriter : writes eligible outputs
Loading
flowchart TD
    A[apm compile] --> B[CompilationConfig]
    B --> C[AgentsCompiler.compile]
    C --> D{root context output?}
    D -->|AGENTS.md or CLAUDE.md| E[_hand_authored_root_context_blocks_write]
    E -->|APM marker found| F[write generated output]
    E -->|marker absent or unverifiable| G[retain file and warn]
    D -->|non-root or custom output| H[normal compiler output]
    G --> I[CLI and watch reporters show retained output]
    F --> J[CompilationResult stats]
    H --> J
    I --> J
Loading

Recommendation

Ship now. The panel found no blocking or recommended follow-ups, prior stale needs_rework items were folded, and the remaining design note supports the current implementation rather than asking for more work.

Folded in this run

  • (panel) Restore managed-section updates, canonicalize aliases, recognize both generated markers, scope explicit outputs, and fix protected-output reporting -- resolved in b5cf24a.
  • (panel) Fix the broken compile-reference link so the docs build link checker passes -- resolved in 254209a.
  • (panel) Add direct redirected-root AGENTS.md preservation regression coverage -- resolved in c9a4292.

Copilot signals reviewed

  • review:5097190825 -- LEGIT: the review identified real in-scope correctness, reporting, and guard gaps; branch commits now cover them (resolved in c9a4292).

Regression-trap evidence (mutation-break gate)

  • tests/unit/compilation/test_project_root_context_protection.py::test_compile_root_preserves_hand_authored_agents_context -- deleted AgentsCompiler._prepare_distributed_file call to _hand_authored_root_context_blocks_write(agents_path); test FAILED as expected; guard restored.

Lint contract

uv run --extra dev ruff check src/ tests/ scripts/lint_architecture_boundaries.py scripts/architecture_linter/ and uv run --extra dev ruff format --check src/ tests/ scripts/lint_architecture_boundaries.py scripts/architecture_linter/ both silent after merging origin/main. Pylint R0801, scripts/lint-auth-signals.sh, and scripts/lint-architecture-boundaries.sh also passed.

CI

All PR checks are green at c9a4292. Docs build passed: https://github.com/microsoft/apm/actions/runs/33745656598/job/100617398790. CI suite passed: https://github.com/microsoft/apm/actions/runs/33745656671.

Mergeability status

Captured from gh pr view 2779 --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
#2779 c9a4292 ship_now 2 3 0 2 green MERGEABLE BLOCKED pending required review

Convergence

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

Ready for maintainer review.


Full per-persona findings

Python Architect

  • [nit] Architecture note: the current shape is the simplest correct design for this scope.
    AgentsCompiler._hand_authored_root_context_blocks_write centralizes project-root AGENTS.md and CLAUDE.md write eligibility before any CompiledOutputWriter call; keeping this as a compiler-owned helper plus CLI/watch render helpers is lower-risk than a new policy class.

CLI Logging Expert

No findings.

DevX UX Expert

No findings.

Supply Chain Security Expert

No findings.

OSS Growth Hacker

No findings.

Auth Expert -- inactive

Touched files are compile CLI/watcher/compiler, architecture linter, docs, package guide, and tests, with no AuthResolver, token manager, credential, downloader, marketplace, or host-auth behavior affected.

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.

Address panel follow-ups by preserving managed sections, recognizing both APM markers, canonicalizing root aliases, retaining custom outputs, improving reporting, documenting the contract, and using lexical architecture scans.

Co-authored-by: Copilot <[email protected]>
Record the new root-context ownership rule in the frozen inventory and fix the compile reference link surfaced by CI.

Co-authored-by: Copilot <[email protected]>
Address Copilot review by requiring generated markers on header lines, keeping unreadable-file warnings ASCII-stable, catching multiline duplicate owners, and clarifying dry-run retention.

Co-authored-by: Copilot <[email protected]>
Fix the relative link to the manifest schema so the docs build link checker resolves the page from the nested compile reference route.

Co-authored-by: Copilot <[email protected]>
Add direct regression coverage for preserving hand-authored AGENTS.md when compile writes through an explicit root, addressing the final test-coverage panel follow-up.

Co-authored-by: Copilot <[email protected]>
@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit c919ba3 into main Sep 3, 2026
18 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the fix/protect-hand-authored-context branch September 3, 2026 14:30
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 compile silently overwrites hand-authored root CLAUDE.md / AGENTS.md (data loss)

2 participants