diff --git a/changelog.d/5447.fixed.md b/changelog.d/5447.fixed.md new file mode 100644 index 0000000000..8d4e415f37 --- /dev/null +++ b/changelog.d/5447.fixed.md @@ -0,0 +1 @@ +- `apm install` no longer replays "up to date" after an `AGENTS.md` or `CLAUDE.md` that decides Claude rules changes (#5447) diff --git a/src/apm_cli/compilation/claude_agents_md.py b/src/apm_cli/compilation/claude_agents_md.py index 100df2b66b..b70621965d 100644 --- a/src/apm_cli/compilation/claude_agents_md.py +++ b/src/apm_cli/compilation/claude_agents_md.py @@ -667,14 +667,39 @@ def compiled_agents_md_may_carry(project_root: Path) -> bool: defer to the full run when APM home records a compile for this root or a root ``AGENTS.md`` or ``CLAUDE.md`` exists. """ - from ..core.agents_md_compile_record import read_record + from ..core.agents_md_compile_record import may_carry - if read_record(project_root): - return True - return any( - (project_root / name).is_symlink() or (project_root / name).exists() - for name in ("AGENTS.md", "CLAUDE.md") - ) + return may_carry(project_root) + + +def lock_ships_routable_instruction(project_root: Path, lock: object) -> bool: + """Whether a locked package ships an instruction Claude may load from AGENTS.md (#5434). + + Routing reads carriers anywhere under the project, and a directory + instruction routes once its directory and carrier exist, so this is the + static form (:func:`routes_to_agents_md` without a root). A fast path that + replays the lock declines for any such instruction; an unreadable one, or a + missing package copy the engine would restore, counts. + """ + from ..constants import APM_MODULES_DIR + from ..integration.instruction_integrator import InstructionIntegrator + + modules = project_root / APM_MODULES_DIR + integrator = InstructionIntegrator() + for key, dependency in getattr(lock, "dependencies", {}).items(): + if key == ".": + continue + try: + package = dependency.to_dependency_ref().get_install_path(modules) + if package.is_symlink() or not package.is_dir(): + return True # a copy the engine would restore: unknown content counts + for source in integrator.find_instruction_files(package): + metadata = integrator._parse_frontmatter(source.read_text(encoding="utf-8"))[0] + if routes_to_agents_md(metadata.get("applyTo")): + return True + except Exception: # unreadable: the full run decides + return True + return False def compiled_agents_md_has(project_root: Path, apply_to: object, body: str) -> bool: diff --git a/src/apm_cli/core/agents_md_compile_record.py b/src/apm_cli/core/agents_md_compile_record.py index 08e4032df4..a90c23d0b8 100644 --- a/src/apm_cli/core/agents_md_compile_record.py +++ b/src/apm_cli/core/agents_md_compile_record.py @@ -31,6 +31,22 @@ def read_record(root: Path) -> dict: return files if isinstance(files, dict) else {} +ROOT_CARRIERS = ("AGENTS.md", "CLAUDE.md") + + +def may_carry(root: Path) -> bool: + """Whether a compiled ``AGENTS.md`` may stand in for a Claude rule at *root* (#5343). + + The one decision behind ``compiled_agents_md_may_carry`` (the engine fast + path's decline) and the no-op replay's (#5434): this record exists, or a + root carrier does. Kept here, light, so a replay asks it without importing + the compiler: two lstat and one read of the record. + """ + if read_record(root): + return True + return any(os.path.lexists(root / name) for name in ROOT_CARRIERS) + + def write_record(root: Path, files: dict) -> None: """Replace the record for *root*; a failed write only costs a reminder.""" from apm_cli.integration.write_seam import atomic_write_text, mkdir diff --git a/src/apm_cli/install/diff_apply.py b/src/apm_cli/install/diff_apply.py index 32404ef031..859449b4ae 100644 --- a/src/apm_cli/install/diff_apply.py +++ b/src/apm_cli/install/diff_apply.py @@ -214,17 +214,24 @@ def _plan_files( return writes -def _refuse_claude_carried_rules(project_root: Path, targets: Any) -> None: - """Decline when a Claude rule may be left to a compiled AGENTS.md (#5343). +def _refuse_claude_carried_rules(project_root: Path, targets: Any, lock: Any = None) -> None: + """Decline when a Claude rule may be left to a compiled AGENTS.md (#5343, #5434). The lock records only the rules install wrote, so a deleted carrier would - otherwise leave Claude with no copy; the full run restores the rule. + otherwise leave Claude with no copy; the full run restores the rule. A + locked package's routable instruction can be carried by a directory's + AGENTS.md anywhere, so it declines too. """ - from apm_cli.compilation.claude_agents_md import compiled_agents_md_may_carry + from apm_cli.compilation.claude_agents_md import ( + compiled_agents_md_may_carry, + lock_ships_routable_instruction, + ) - if any( - getattr(t, "compile_family", None) == "claude" for t in targets - ) and compiled_agents_md_may_carry(project_root): + if not any(getattr(t, "compile_family", None) == "claude" for t in targets): + return + if compiled_agents_md_may_carry(project_root) or ( + lock is not None and lock_ships_routable_instruction(project_root, lock) + ): raise Decline("claude rules may depend on a compiled AGENTS.md") @@ -777,7 +784,7 @@ def try_apply( _root, user_scope, targets = resolve_audit_scope(project_root, lock) if user_scope or not targets: raise Decline("scope") - _refuse_claude_carried_rules(project_root, targets) + _refuse_claude_carried_rules(project_root, targets, lock) from apm_cli.cache.deploy_store import DeployStore session = DeploymentMaterializationSession(project_root, InstallScope.PROJECT, lock) diff --git a/src/apm_cli/install/verdict_record.py b/src/apm_cli/install/verdict_record.py index 836d431355..d07f096124 100644 --- a/src/apm_cli/install/verdict_record.py +++ b/src/apm_cli/install/verdict_record.py @@ -749,6 +749,11 @@ def _verified_stdout(argv: list[str], root: Path, *, attested: bool = False) -> raw = _read_nofollow(_record_path(root)) if raw is None or not _location_trusted(root): raise _Miss("") + from apm_cli.core.agents_md_compile_record import may_carry + + if not attested and may_carry(root): + # The full run decides Claude rules from it; a replay never does (#5434). + raise _Miss("a compiled AGENTS.md may carry a Claude rule") key = _key(create=False) if key is None: raise _Miss("no key") diff --git a/src/apm_cli/install/verdict_write.py b/src/apm_cli/install/verdict_write.py index 21cdadde9d..9758e56c22 100644 --- a/src/apm_cli/install/verdict_write.py +++ b/src/apm_cli/install/verdict_write.py @@ -86,6 +86,11 @@ def _record_after( if attested: _write_at_entry(entry, argv, "", "", deployed, kind=ATTESTED, provenance=ATTESTED) return + from apm_cli.core.agents_md_compile_record import may_carry + + if may_carry(Path.cwd()): + vr._trace("no record (a compiled AGENTS.md may carry a Claude rule)") # #5434 + return provenance = ATTESTED if ATTESTED in vr._VERIFIED_NOOP else PROVEN out_text, err_text = "".join(out.parts), "".join(err.parts) _write_at_entry(entry, argv, out_text, err_text, deployed, provenance=provenance) diff --git a/src/apm_cli/integration/instruction_integrator.py b/src/apm_cli/integration/instruction_integrator.py index a2305fd2be..e2a6a66b3d 100644 --- a/src/apm_cli/integration/instruction_integrator.py +++ b/src/apm_cli/integration/instruction_integrator.py @@ -734,14 +734,20 @@ def _claude_rule_sources( ) if live_root.resolve() == get_deploy_root(InstallScope.USER).resolve(): return instruction_files + apply_tos = { + source: self._parse_frontmatter(prepared_instructions[source].content)[0].get("applyTo") + for source in instruction_files + } + if any(routes_to_agents_md(apply_to) for apply_to in apply_tos.values()): + # Routing reads carriers anywhere (a directory routes once it and its + # carrier exist); a no-op replay never re-decides it, so record none (#5434). + from apm_cli.install import verdict_record + + verdict_record.unknown("claude routing") routed = { source for source in instruction_files - if routes_to_agents_md( - self._parse_frontmatter(prepared_instructions[source].content)[0].get("applyTo"), - live_root, - cache=self._routing_cache, - ) + if routes_to_agents_md(apply_tos[source], live_root, cache=self._routing_cache) } if not routed: return instruction_files diff --git a/tests/fixtures/lifecycle_bug_ledger/bugs/5434.json b/tests/fixtures/lifecycle_bug_ledger/bugs/5434.json new file mode 100644 index 0000000000..6392a7c083 --- /dev/null +++ b/tests/fixtures/lifecycle_bug_ledger/bugs/5434.json @@ -0,0 +1,18 @@ +{ + "issue": 5434, + "fixed_in": "Unreleased", + "summary": "The install no-op replay printed 'up to date' after a root AGENTS.md / CLAUDE.md, the compile record or a directory AGENTS.md carrier changed, while the full run would write or retire a .claude/rules file; the replay now declines while a carrier may stand in, a run that decided Claude routing records nothing, and the engine fast path declines for a routable instruction.", + "failure_modes": [ + "cache", + "outcome" + ], + "properties": [ + "outcome.status_matches_state" + ], + "regression_tests": [ + "tests/integration/test_verdict_record.py::test_a_root_carrier_appearing_after_the_record_misses", + "tests/integration/test_verdict_record.py::test_a_run_that_decided_claude_routing_records_nothing", + "tests/integration/test_verdict_record.py::test_the_engine_fast_path_declines_for_a_routable_instruction", + "tests/integration/test_verdict_record_attested_world.py::test_a_root_agents_md_after_a_replay_record_misses_and_the_full_run_decides" + ] +} diff --git a/tests/integration/test_verdict_record.py b/tests/integration/test_verdict_record.py index 3c51e857de..a9d1a77a93 100644 --- a/tests/integration/test_verdict_record.py +++ b/tests/integration/test_verdict_record.py @@ -1540,3 +1540,162 @@ def test_terminal_styling_never_hides_a_deferral_warning( def _assert_replays(expected: bool) -> None: assert verdict_record.replay(["install"]) is expected + + +# #5434 (RT1, W3d): the full run decides Claude rules from carriers -- the root +# AGENTS.md / CLAUDE.md, the compile record, and a directory's AGENTS.md for a +# routable instruction. The replay never re-decides them: it declines while a root +# carrier or record may stand in (compiled_agents_md_may_carry's owner), a run that +# decided routing records nothing, and the engine declines for a routable instruction. +_CARRIER = "## Global Instructions\n\nAlways run the linter.\n" + + +def _nested_carrier(project: Path) -> None: + nested = project / "src" / "test" + nested.mkdir(parents=True, exist_ok=True) + (nested / "AGENTS.md").write_text(_CARRIER, encoding="utf-8") + (nested / "CLAUDE.md").write_text("@AGENTS.md\n", encoding="utf-8") + + +@pytest.mark.parametrize("name", ["AGENTS.md", "CLAUDE.md"]) +def test_a_root_carrier_appearing_after_the_record_misses(project: Path, capsys, name: str) -> None: + _record() + (project / name).write_text(_CARRIER, encoding="utf-8") + capsys.readouterr() + + _assert_replays(False) + + +def test_a_compile_record_appearing_after_the_record_misses(project: Path, capsys) -> None: + from apm_cli.core.agents_md_compile_record import write_record + + _record() + write_record(project, {"AGENTS.md": {"sha256": "sha256:0", "instructions": []}}) + capsys.readouterr() + + _assert_replays(False) + + +def test_a_root_carrier_removed_after_the_record_misses(project: Path, capsys) -> None: + """A run with a root carrier writes no replayable record, so removing it cannot hit.""" + (project / "AGENTS.md").write_text(_CARRIER, encoding="utf-8") + (project / "CLAUDE.md").write_text("@AGENTS.md\n", encoding="utf-8") + _record() + assert not verdict_record._record_path(project).exists() + (project / "AGENTS.md").unlink() + capsys.readouterr() + + _assert_replays(False) + + +def test_control_with_no_carrier_the_record_still_replays(project: Path, capsys) -> None: + _record() + capsys.readouterr() + + _assert_replays(True) + + +def _decide_claude_routing(project: Path, apply_to: str) -> None: + """The instruction integrator's Claude routing step for one instruction.""" + from types import SimpleNamespace + + from apm_cli.core.scope import InstallScope + from apm_cli.integration.instruction_integrator import InstructionIntegrator + from apm_cli.integration.targets import KNOWN_TARGETS + + source = project / "apm_modules" / "o" / "p" / ".apm" / "instructions" / "t.instructions.md" + content = f"---\napplyTo: '{apply_to}'\n---\nRun the tests.\n" + prepared = {source: SimpleNamespace(content=content, body="Run the tests.\n")} + InstructionIntegrator()._claude_rule_sources( + KNOWN_TARGETS["claude"], + [source], + prepared, + SimpleNamespace(), + project, + InstallScope.PROJECT, + None, + ) + + +@pytest.mark.parametrize( + ("apply_to", "replays"), + [("**", False), ("src/test/**", False), ("**/*.py", True)], +) +def test_a_run_that_decided_claude_routing_records_nothing( + project: Path, capsys, apply_to: str, replays: bool +) -> None: + """A routable instruction (always-on or one literal directory, even while that + directory is absent) means the run decided routing: nothing is recorded, so a + carrier created later (src/test/AGENTS.md importing CLAUDE.md) cannot be skipped. + A path-scoped instruction never routes: its no-op still records and replays.""" + with verdict_record.recording(["install"]): + sys.stdout.write(_OUTPUT) + _decide_claude_routing(project, apply_to) + verdict_record.note_verified_noop() + _nested_carrier(project) + capsys.readouterr() + + _assert_replays(replays) + + +def _ship_instruction(project: Path, apply_to: str) -> None: + instructions = project / "apm_modules" / "o" / "p" / ".apm" / "instructions" + instructions.mkdir(parents=True) + (instructions / "t.instructions.md").write_text( + f"---\napplyTo: '{apply_to}'\n---\nRun the tests.\n", encoding="utf-8" + ) + + +@pytest.mark.parametrize( + ("apply_to", "carrier", "declines"), + [ + ("src/test/**", True, True), + ("src/test/**", False, True), # the directory does not exist yet: still routable + ("**", False, True), + ("**/*.py", True, False), + (None, True, False), # no instruction: a nested carrier decides nothing + ("missing-copy", False, True), # a copy the engine would restore: unknown counts + ], +) +def test_the_engine_fast_path_declines_for_a_routable_instruction( + project: Path, apply_to: str | None, carrier: bool, declines: bool +) -> None: + from types import SimpleNamespace + + from apm_cli.deps.lockfile import LockFile + from apm_cli.install import diff_apply + + if apply_to == "missing-copy": + shutil.rmtree(project / "apm_modules" / "o" / "p") + elif apply_to is not None: + _ship_instruction(project, apply_to) + if carrier: + _nested_carrier(project) + lock = LockFile.read(project / "apm.lock.yaml") + claude = [SimpleNamespace(compile_family="claude")] + + if declines: + with pytest.raises(diff_apply.Decline): + diff_apply._refuse_claude_carried_rules(project, claude, lock) + else: + diff_apply._refuse_claude_carried_rules(project, claude, lock) + # Another target family never declines here. + diff_apply._refuse_claude_carried_rules(project, [SimpleNamespace(compile_family="x")], lock) + + +def test_the_replay_and_the_engine_share_one_carrier_owner(project: Path, capsys) -> None: + """Every root carrier the engine's predicate names also stops the record and the replay.""" + from apm_cli.compilation.claude_agents_md import compiled_agents_md_may_carry + from apm_cli.core.agents_md_compile_record import ROOT_CARRIERS + + for name in ROOT_CARRIERS: + (project / name).write_text(_CARRIER, encoding="utf-8") + assert compiled_agents_md_may_carry(project) + _record() + capsys.readouterr() + _assert_replays(False) + (project / name).unlink() + assert not compiled_agents_md_may_carry(project) + _record() + capsys.readouterr() + _assert_replays(True) diff --git a/tests/integration/test_verdict_record_attested_world.py b/tests/integration/test_verdict_record_attested_world.py index 873a18aca5..783137534e 100644 --- a/tests/integration/test_verdict_record_attested_world.py +++ b/tests/integration/test_verdict_record_attested_world.py @@ -127,6 +127,29 @@ def test_a_valid_attestation_never_skips_the_claude_carried_rules_refusal(world_ _assert_full_pipeline_ran(second) +@pytest.mark.parametrize("world_install", ["tree-10-claude"], indirect=True) +def test_a_root_agents_md_after_a_replay_record_misses_and_the_full_run_decides( + world_install, +) -> None: + """#5434: the replayed no-op was recorded with no carrier; a root AGENTS.md that + appears later can decide Claude rules, so the next install is not a replay and + prints what the full pipeline prints for that state.""" + install, project, _world = world_install + _assert_attested(install()) + _assert_attested_hit(install()) + (project / "AGENTS.md").write_text("# Project notes\n", encoding="utf-8") + before = _tree_bytes(project) + + after, full = install(), install(fast="0") + + assert after[0] == 0, after[1] + after[2] + assert "hit" not in _traces(after[2]), after[2] + assert "attested hit" not in _traces(after[2]), after[2] + assert full[0] == 0 and not _traces(full[2]), full[1] + full[2] + assert _normalized(after[1]) == _normalized(full[1]) + assert _tree_bytes(project) == before + + def _assert_full_pipeline_ran(result: tuple[int, str, str]) -> None: """The record matched ("attested hit" is the check, not the outcome), yet the fast path declined: the full pipeline re-attested and no attested commit recorded output."""