Repository navigation
fix: preserve hand-authored root context files (closes #2767) - #2779
Conversation
Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
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
New issues introduced by this change (4)
| Severity | Finding |
|---|---|
src/apm_cli/compilation/agents_compiler.py — The overwrite-eligibility check treats a file as APM-generated if the marker appears anywhere in… |
|
scripts/architecture_linter/checks/registry_semantic_rules.py — The duplicate-owner detector regex requires the entire function signature (including ) and :)… |
|
src/apm_cli/compilation/agents_compiler.py — The warning for an unreadable/undecodable root context file interpolates the raw exception string… |
|
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.mdwrite. - 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.
| if marker in prefix: | ||
| return False |
| _ROOT_CONTEXT_DUPLICATE_PATTERN = ( | ||
| r"^\s*def\s+\w*(?:hand_authored.*root_context|root_context.*hand_authored)" | ||
| r"\w*\([^)]*\)\s*(?:->[^:]+)?:" | ||
| ) |
| self.warnings.append( | ||
| f"Skipped {rel_path}: could not verify the APM-generated marker; " | ||
| f"file will not be overwritten ({exc!s})." | ||
| ) |
| if agents_write_blocked: | ||
| logger.progress( | ||
| "AGENTS.md not generated -- protected hand-authored root file retained", | ||
| symbol="info", | ||
| ) |
APM Review Panel:
|
| 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
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
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-- deletedAgentsCompiler._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]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
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]>



fix(compile): preserve hand-authored root context files
TL;DR
Project-scope
apm compilenow checks existing rootAGENTS.mdandCLAUDE.mdfiles for the APM-generated marker before writing. Files withoutthat 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)
AGENTS.mdandCLAUDE.mdcontent and exited successfully.
apm compile --root ...could redirect that destructive write into auser-level tool configuration directory.
"Hand-authored files (files that do not carry the APM-generated marker) are never overwritten."
This fix brings project compilation in line with that marker-gated contract.
Approach (WHAT)
AgentsCompilerhelper.--rootprotection in both user reference surfaces.Implementation (HOW)
src/apm_cli/compilation/agents_compiler.py- Adds the marker-gatedeligibility 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-writeresult before the CLI performs its constitution-aware final AGENTS write.
.apm/architecture/owners/core-runtime.json- Extends the existing agentoutput preparation owner with root overwrite eligibility.
scripts/architecture_linter/checks/registry_semantic_rules.py- Requiresevery 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 amutation that introduces a second CLI owner and proves the static rule catches
it.
tests/unit/compilation/test_project_root_context_protection.py- Coversdistributed, single-file, dry-run, live, and redirected-root behavior.
docs/src/content/docs/reference/cli/compile.md- Documents project rootoverwrite protection.
packages/apm-guide/.apm/skills/apm-usage/commands.md- Mirrors thecommand 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;Trade-offs
automatic content merging would invent ownership boundaries that do not exist.
file before compiling; this keeps the fix bounded and avoids adding CLI
surface in a data-loss repair.
behavior; the reported destructive contract concerns root context files.
Benefits
--rootdestinations receive the same marker check.Validation
Focused regression suites on the final implementation:
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
tests/unit/compilation/test_project_root_context_protection.py::test_compile_preserves_hand_authored_project_root_context(regression-trap for #2767)tests/unit/compilation/test_project_root_context_protection.py::test_compile_root_preserves_hand_authored_context(regression-trap for #2767)tests/integration/test_architecture_owner_rule_mutations.pytests/unit/compilation/test_project_root_context_protection.py::test_managed_section_rejects_external_agents_symlinkHow to test
AGENTS.mdandCLAUDE.mdfiles.apm compileand confirm both files are unchanged with skip warnings.apm compile --dry-runand confirm the same warnings without writes.apm compile --target claude --root <dir>against an unmarked<dir>/CLAUDE.mdand confirm it remains unchanged.created with APM markers.
AGENTS.mdat 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]