diff --git a/agentdescent/cli.py b/agentdescent/cli.py index 3c9e9e5d..d7dcc377 100644 --- a/agentdescent/cli.py +++ b/agentdescent/cli.py @@ -3199,6 +3199,13 @@ def show_payload(run_id: str, *, store: Optional[str] = None, diff: bool = True, dest = os.path.expanduser(spec.target) plan = _text_plan(dest, result.rendered) payload["apply_plan"] = plan + # Directory and symlink refusals apply makes first (#1204, #755, #977). + # Catch them so the preview stays read-only and exits 0. + try: + _refuse_text_dest(run_id, dest) + except runstore.RunStoreError as e: + payload["apply_plan"] = {"error": str(e)} + return payload _refuse_plan_outside_write_dirs( payload, dest, plan["written"], _backup_slot(dest) if not plan["noop"] and os.path.exists(dest) else None) @@ -3214,9 +3221,14 @@ def show_payload(run_id: str, *, store: Optional[str] = None, diff: bool = True, # The call `apply` makes for a tree, with only `dry_run` differing: # `_write_to` checks the destination, every written leaf and the # directory backup slot before it returns the plan (#1188). + dest = os.path.expanduser(spec.target) try: + # Same refusal apply makes before `_write_to` (#1204): a symlink + # root is never dereferenced. `_write_to` abspaths and would not + # see it. + _refuse_dest_link(dest, dest) payload["apply_plan"] = result._write_to( - os.path.expanduser(spec.target), dry_run=True, + dest, dry_run=True, check_write=_operator_write_guard()) except Exception as e: # noqa: BLE001 payload["apply_plan"] = {"error": str(e)} @@ -3514,6 +3526,23 @@ def apply_with_target(run_id: Optional[str] = None, *, to: Optional[str] = None, notes, f"run {run_id}") +def _refuse_text_dest(run_id: str, dest: str) -> None: + """Refuse a text destination ``apply`` would also refuse (#1204, #755, #977). + + A directory cannot receive a single text artifact (the dry run used to + report it would write the directory, then apply traced back on + ``IsADirectoryError``), and a destination link is never dereferenced. + ``show_payload`` calls the same helper so the preview cannot drift from + the write; the message bytes are unchanged. + """ + if os.path.isdir(dest): + raise runstore.RunStoreError( + f"{run_id} evolved a single text artifact and {dest!r} is a " + "directory; pass --to FILE to write it to a file, or read it " + "with `show`") + _refuse_dest_link(os.path.dirname(os.path.abspath(dest)) or os.sep, dest) + + def _refuse_dest_link(top: str, path: str) -> None: """Refuse a link planted in the destination, before any backup or write (#977). @@ -3557,15 +3586,7 @@ def apply_payload(run_id: str, *, to: Optional[str] = None, store: Optional[str] "pass --to PATH to write the rule, or read it with `show`") dest = os.path.expanduser(to or spec.target) if spec.kind in ("text", "policy_slot"): - if os.path.isdir(dest): - # Same refusal for --dry-run and the real write: the dry run used to - # report it would write the directory, then apply traced back on - # IsADirectoryError (#755). - raise runstore.RunStoreError( - f"{run_id} evolved a single text artifact and {dest!r} is a " - "directory; pass --to FILE to write it to a file, or read it " - "with `show`") - _refuse_dest_link(os.path.dirname(os.path.abspath(dest)) or os.sep, dest) + _refuse_text_dest(run_id, dest) plan = _text_plan(dest, result.rendered) slot = (_backup_slot(dest) if backup and not plan["noop"] and os.path.exists(dest) else None) diff --git a/changelog.d/1204-show-dest-refusals.md b/changelog.d/1204-show-dest-refusals.md new file mode 100644 index 00000000..0f8efbe3 --- /dev/null +++ b/changelog.d/1204-show-dest-refusals.md @@ -0,0 +1,6 @@ +Fixed +`agentdescent show --diff` previews every destination `apply` refuses, not +only the write-dir boundary: a text artifact whose target is a directory or +a symlink, and a tree whose root is a symlink, now appear as +`apply_plan.error` with `apply`'s own message, and `show` stays read-only +(#1204). diff --git a/docs/plugins.md b/docs/plugins.md index 743b1f02..3dd7c0d7 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -281,7 +281,9 @@ all ~39 tools as the primary path. there -- the destination, every file its plan names, and the backup slot (a directory artifact backs up under `$AGENTDESCENT_HOME/backups/...`) -- so its `apply_plan` reports that refusal instead of a write `apply` would not - perform (#1188). + perform (#1188). The same preview also reports the destination refusals + `apply` raises before that check: a text artifact whose target is a + directory or a symlink, and a tree whose root is a symlink (#1204). * **Questions about an archive are read-only tools.** `safety` (safe to keep seeding from?), `portfolio` (layer ranking and a suggested budget split) and `audit_trace` (one adoption's evidence rings) return the same JSON as the diff --git a/tests/test_show_dest_refusals.py b/tests/test_show_dest_refusals.py new file mode 100644 index 00000000..c38e65ec --- /dev/null +++ b/tests/test_show_dest_refusals.py @@ -0,0 +1,141 @@ +"""``show --diff`` must preview every destination ``apply`` refuses (#1204). + +``#1200`` taught the preview about the operator write-dir boundary. The other +half of ``apply``'s destination refusals was still missing: a text artifact +whose target is a directory or a symlink, and a tree whose root is a symlink. +``show`` advertised those writes (``written``, no ``error``) while ``apply`` +exited 2. The preview must carry ``apply``'s own message, stay read-only, and +exit 0. +""" + +from __future__ import annotations + +import json +import os + +import pytest + +from agentdescent import runstore +from agentdescent.cli import main +from agentdescent.evolution import EvolutionResult +from agentdescent.filetree import canonical + + +@pytest.fixture(autouse=True) +def isolated_home(tmp_path, monkeypatch): + monkeypatch.setenv("AGENTDESCENT_HOME", str(tmp_path / "ad-home")) + monkeypatch.delenv("AGENTDESCENT_SURFACE_WRITE_DIRS", raising=False) + + +def _run_cli(argv, capsys): + code = main(argv) + return code, capsys.readouterr() + + +def _text_run(tmp_path, dest, rendered="hello\n"): + store = str(tmp_path / "runs") + rd = runstore.create({ + "kind": "text", "target": str(dest), + "data": {"inline": [{"prompt": "p", "gold": "g"}], + "prompt": "prompt", "gold": "gold"}, + "score": "exact", "agent": {"ref": "echo"}, "reflect": {"ref": "echo"}, + }, store=store) + EvolutionResult(state={}, rendered=rendered, final_reward=1.0, + history=[], ledger_log=[]).save(rd.result_path) + rd.update_status(state="done") + return store, str(rd.run_id) + + +def _tree_run(tmp_path, dest, state=None): + store = str(tmp_path / "runs") + if state is None: + state = {"alpha/SKILL.md": "evolved\n"} + rd = runstore.create({ + "kind": "skill_library", + "target": str(dest), + "data": {"inline": [{"prompt": "p", "gold": "g"}], + "prompt": "prompt", "gold": "gold"}, + "score": "exact", + "agent": {"ref": "claude_code"}, + "reflect": {"ref": "echo"}, + }, store=store) + EvolutionResult(state=state, rendered=canonical(state), final_reward=1.0, + history=[], ledger_log=[]).save(rd.result_path) + rd.update_status(state="done") + return store, str(rd.run_id) + + +def _assert_show_matches_apply(store, rid, capsys): + """``show --diff --json`` reports ``apply``'s own refusal and exits 0.""" + code, out = _run_cli( + ["--store", store, "show", rid, "--diff", "--json"], capsys) + assert code == 0, out.err or out.out + plan = json.loads(out.out)["apply_plan"] + show_error = plan.get("error") + assert show_error, "show advertised a write apply would refuse: " + json.dumps(plan) + + code, out = _run_cli(["--store", store, "apply", rid, "--json"], capsys) + assert code == 2, out.out or out.err + apply_payload = json.loads(out.out) + assert apply_payload.get("ok") is False + assert show_error == apply_payload["error"] + return show_error + + +def test_show_previews_the_directory_refusal_for_a_text_artifact(tmp_path, capsys): + dest = tmp_path / "outdir" + dest.mkdir() + marker = dest / "keep.txt" + marker.write_text("stay\n", encoding="utf-8") + store, rid = _text_run(tmp_path, dest) + + _assert_show_matches_apply(store, rid, capsys) + + assert dest.is_dir() + assert marker.read_text(encoding="utf-8") == "stay\n" + assert sorted(p.name for p in dest.iterdir()) == ["keep.txt"] + + +def test_show_previews_the_symlink_refusal_for_a_text_artifact(tmp_path, capsys): + real = tmp_path / "real.txt" + real.write_text("secret\n", encoding="utf-8") + dest = tmp_path / "link.txt" + os.symlink(str(real), str(dest)) + store, rid = _text_run(tmp_path, dest) + + error = _assert_show_matches_apply(store, rid, capsys) + + assert "destination link is never dereferenced" in error + assert os.path.islink(str(dest)) + assert real.read_text(encoding="utf-8") == "secret\n" + + +def test_show_previews_the_symlink_root_refusal_for_a_tree_artifact(tmp_path, capsys): + real = tmp_path / "real-root" + real.mkdir() + (real / "SKILL.md").write_text("original\n", encoding="utf-8") + dest = tmp_path / "link-root" + os.symlink(str(real), str(dest)) + store, rid = _tree_run(tmp_path, dest) + + error = _assert_show_matches_apply(store, rid, capsys) + + assert "destination link is never dereferenced" in error + assert os.path.islink(str(dest)) + assert (real / "SKILL.md").read_text(encoding="utf-8") == "original\n" + assert list(real.iterdir()) == [real / "SKILL.md"] + + +def test_show_still_reports_a_regular_file_text_plan(tmp_path, capsys): + dest = tmp_path / "prompt.txt" + dest.write_text("old\n", encoding="utf-8") + store, rid = _text_run(tmp_path, dest, rendered="new text\n") + + code, out = _run_cli( + ["--store", store, "show", rid, "--diff", "--json"], capsys) + assert code == 0, out.err or out.out + plan = json.loads(out.out)["apply_plan"] + assert plan.get("error") is None + assert plan["written"] == [str(dest)] + assert plan["noop"] is False + assert dest.read_text(encoding="utf-8") == "old\n"