From df940ab61e5c9276a47b8860faa91093ddec23d8 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 09:56:23 +0000 Subject: [PATCH 1/4] test(cli): one refusal row per leaf apply can write (#1230) The preview and the tree writer read different rules for a link planted inside the destination: `_refuse_blocked_parent` follows a link to a directory, `_refuse_blocked_leaf` skips one, so `show --diff` and `apply --dry-run` advertise `written: ["alpha"]` while the real apply raises an uncaught `TreeError` traceback instead of the exit-2 refusal. Red at 761eb4cb with only this file added: 2 failed, 4 passed. The two are the new link leaves (at the leaf, on the way to it); the four passers are the earlier shapes as locks plus a legal sibling. --- tests/test_apply_refusal_walk.py | 194 +++++++++++++++++++++++++++++++ 1 file changed, 194 insertions(+) create mode 100644 tests/test_apply_refusal_walk.py diff --git a/tests/test_apply_refusal_walk.py b/tests/test_apply_refusal_walk.py new file mode 100644 index 00000000..63546712 --- /dev/null +++ b/tests/test_apply_refusal_walk.py @@ -0,0 +1,194 @@ +"""One refusal walk for every leaf ``apply`` can write (#1230). + +``#1215`` (destination blocked by a file), ``#1222`` (tree child blocked by a +file) and ``#1224`` (tree leaf already a directory) each fixed the leaf its +report named. The rules they added all live in ``_check_apply_paths``, the +funnel ``show``, ``apply``, ``--from`` and ``--install-to`` share -- except the +fourth: a *link* planted inside the destination. ``_refuse_blocked_parent`` +follows a link to a directory and ``_refuse_blocked_leaf`` deliberately skips +one, so the preview advertised ``written: ["alpha"]`` while the tree writer +raised an uncaught ``TreeError`` traceback out of ``main``. + +The rows below are the enumeration, one per leaf: the two link shapes (at the +leaf, on the way to it), then the three earlier shapes as locks, then a legal +sibling as the control that nothing here refuses a destination that works. +""" + +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 _tree_run(tmp_path, dest, state): + store = str(tmp_path / "runs-tree") + 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 _show_plan(store, rid, capsys): + code, out = _run_cli( + ["--store", store, "show", rid, "--diff", "--json"], capsys) + assert code == 0, out.err or out.out + return json.loads(out.out)["apply_plan"] + + +def _apply_error(argv, capsys): + code, out = _run_cli(argv, capsys) + assert code == 2, out.out or out.err + doc = json.loads(out.out) + assert doc["ok"] is False + return doc["error"] + + +def _same_refusal_on_every_surface(tmp_path, capsys, dest, state, expected): + """show, dry run and the real write name the same thing; nothing is written.""" + store, rid = _tree_run(tmp_path, dest, state=state) + before = sorted(os.listdir(dest)) + + plan = _show_plan(store, rid, capsys) + assert plan.get("error") == expected, ( + "show advertised a write the real apply refuses: " + json.dumps(plan)) + assert "written" not in plan + + code, out = _run_cli(["--store", store, "show", rid, "--diff"], capsys) + assert code == 0, out.err + assert expected in out.out + + assert _apply_error( + ["--store", store, "apply", rid, "--dry-run", "--json"], capsys + ) == expected + assert _apply_error( + ["--store", store, "apply", rid, "--json"], capsys + ) == expected + assert sorted(os.listdir(dest)) == before + return store, rid + + +def _from_error(tmp_path, capsys, dest, files, flag="--to"): + src = tmp_path / "artifact" + for rel, text in files.items(): + path = src / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return _apply_error( + ["apply", "--from", str(src), flag, str(dest), "--json"], capsys) + + +def test_a_symlinked_leaf_is_named_on_every_surface(tmp_path, capsys): + dest = tmp_path / "lib" + dest.mkdir() + victim = tmp_path / "victim.md" + victim.write_text("SECRET\n", encoding="utf-8") + leaf = dest / "alpha" + os.symlink(str(victim), str(leaf)) + + expected = f"cannot write {leaf}: {str(leaf)!r} is a symlink" + _same_refusal_on_every_surface( + tmp_path, capsys, dest, {"alpha": "evolved\n"}, expected) + assert os.path.islink(str(leaf)) + assert victim.read_text(encoding="utf-8") == "SECRET\n" + + # `--from` and `--install-to` walk the same set. + assert _from_error(tmp_path, capsys, dest, {"alpha": "evolved\n"}) == expected + assert _from_error( + tmp_path, capsys, dest, {"alpha": "evolved\n"}, flag="--install-to" + ) == expected + assert victim.read_text(encoding="utf-8") == "SECRET\n" + + +def test_a_symlinked_intermediate_directory_is_named_on_every_surface( + tmp_path, capsys): + dest = tmp_path / "lib" + dest.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + os.symlink(str(outside), str(dest / "sub")) + + leaf = dest / "sub" / "leaf.md" + expected = f"cannot write {leaf}: 'sub/leaf.md' is a symlink" + _same_refusal_on_every_surface( + tmp_path, capsys, dest, {"sub/leaf.md": "evolved\n"}, expected) + assert os.path.islink(str(dest / "sub")) + assert list(outside.iterdir()) == [] + + assert _from_error( + tmp_path, capsys, dest, {"sub/leaf.md": "evolved\n"}) == expected + + +def test_a_tree_child_blocked_by_a_file_is_named_the_same_way(tmp_path, capsys): + dest = tmp_path / "lib" + dest.mkdir() + child = dest / "alpha" + child.write_text("file\n", encoding="utf-8") + leaf = child / "SKILL.md" + expected = f"cannot write {leaf}: {str(child)!r} is a file, not a directory" + _same_refusal_on_every_surface( + tmp_path, capsys, dest, {"alpha/SKILL.md": "evolved\n"}, expected) + assert child.read_text(encoding="utf-8") == "file\n" + + +def test_a_tree_leaf_blocked_by_a_directory_is_named_the_same_way( + tmp_path, capsys): + dest = tmp_path / "lib" + dest.mkdir() + leaf = dest / "beta" + leaf.mkdir() + expected = f"cannot write {leaf}: {str(leaf)!r} is a directory, not a file" + _same_refusal_on_every_surface( + tmp_path, capsys, dest, {"beta": "evolved\n"}, expected) + assert leaf.is_dir() + + +def test_a_destination_blocked_by_a_file_still_refuses(tmp_path, capsys): + blocker = tmp_path / "blocked" + blocker.write_text("file\n", encoding="utf-8") + dest = blocker / "lib" + expected = f"cannot write {dest}: {str(blocker)!r} is a file, not a directory" + store, rid = _tree_run(tmp_path, dest, state={"alpha": "evolved\n"}) + assert _show_plan(store, rid, capsys).get("error") == expected + assert _apply_error( + ["--store", store, "apply", rid, "--json"], capsys) == expected + assert not dest.exists() + + +def test_a_legal_sibling_survives_the_walk(tmp_path, capsys): + dest = tmp_path / "lib" + dest.mkdir() + keep = dest / "keep.txt" + keep.write_text("stay\n", encoding="utf-8") + store, rid = _tree_run(tmp_path, dest, state={"alpha": "evolved\n"}) + + code, out = _run_cli(["--store", store, "apply", rid, "--json"], capsys) + assert code == 0, out.out or out.err + assert (dest / "alpha").read_text(encoding="utf-8") == "evolved\n" + assert keep.read_text(encoding="utf-8") == "stay\n" From a16500e218327f478081e7495938d1a94d6dd269 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 10:04:34 +0000 Subject: [PATCH 2/4] fix(cli): refuse a link in the destination from the same walk (#1230) `_refuse_blocked_parent` treats a link to a directory as a directory and `_refuse_blocked_leaf` skips links, so a link planted inside the tree was the one leaf of this walk the preview did not see: `show --diff` and `apply --dry-run` returned `written` while `materialize` refused at write time with a `TreeError` -- an uncaught traceback out of `main`. `_check_apply_paths` now runs `filetree.dest_problem(dest, path)` for every produced path, the same rule `materialize` enforces, so preview and write cannot drift; the refusal is the funnel's `RunStoreError`, which the CLI already turns into the exit-2 JSON refusal. `apply --from`'s per-leaf `_refuse_dest_link` loop is subsumed by it, so the two surfaces name one block with one sentence. A text artifact's `written` is `[dest]` and is skipped here; its link refusals run before the funnel. `tests/test_apply_symlink_dest.py` asserted the old `TreeError` from `materialize` for the run-id path; the refusal now arrives earlier and as the type every other blocked leaf uses. Rule and sentence unchanged. --- agentdescent/cli.py | 6 ++--- agentdescent/evolution.py | 41 ++++++++++++++++++++++++++------ changelog.d/1230-refusal-walk.md | 7 ++++++ tests/test_apply_symlink_dest.py | 13 +++++++--- 4 files changed, 54 insertions(+), 13 deletions(-) create mode 100644 changelog.d/1230-refusal-walk.md diff --git a/agentdescent/cli.py b/agentdescent/cli.py index c82566b4..1f9830be 100644 --- a/agentdescent/cli.py +++ b/agentdescent/cli.py @@ -3890,9 +3890,9 @@ def _same(a_path: str, b_path: str) -> bool: "source": src, "dest": dest} # Every leaf, before the backup is taken: a link planted in --to must not # redirect the `.bak-N` copy either, or the backup holds the target's - # bytes inside a directory host scanners read (#977). - for rel in changed: - _refuse_dest_link(dest, os.path.join(dest, rel.replace("/", os.sep))) + # bytes inside a directory host scanners read (#977). The funnel below owns + # that rule now (`_refuse_link_in_dest`, #1230), so this surface and + # `apply ` name the same block with the same sentence. slot = (_file_tree_backup_path(dest) if backup and not plan["noop"] and os.path.isdir(dest) else None) _check_apply_paths(dest, [os.path.join(dest, rel.replace("/", os.sep)) diff --git a/agentdescent/evolution.py b/agentdescent/evolution.py index a3adf095..3ae3e5f4 100644 --- a/agentdescent/evolution.py +++ b/agentdescent/evolution.py @@ -1634,8 +1634,7 @@ def _refuse_blocked_leaf(path: str) -> None: Called from ``_check_apply_paths`` on every path in ``written`` (not on ``dest`` itself: a tree root *is* a directory). A symlink at the leaf is - left to ``_refuse_dest_link`` / ``dest_problem``; this helper names only a - real directory. + ``_refuse_link_in_dest``'s job; this helper names only a real directory. """ if os.path.lexists(path) and not os.path.islink(path) and os.path.isdir(path): from . import runstore # runstore imports this module at import time @@ -1644,23 +1643,51 @@ def _refuse_blocked_leaf(path: str) -> None: f"cannot write {path}: {path!r} is a directory, not a file") +def _refuse_link_in_dest(dest: str, path: str) -> None: + """Refuse a produced path a link in the destination would redirect (#1230). + + ``_refuse_blocked_parent`` treats a link to a directory as a directory and + ``_refuse_blocked_leaf`` deliberately skips links, so a link planted inside + the tree was the one leaf of this walk the preview did not see: ``show + --diff`` and ``apply --dry-run`` advertised ``written`` while + ``materialize`` refused at write time with a ``TreeError`` -- an uncaught + traceback, not the exit-2 JSON refusal the other leaves return. + + The rule is ``filetree.dest_problem``, the one ``materialize`` enforces, so + the two cannot drift. A text artifact passes ``[dest]`` here and its link + refusals run before this funnel; ``path == dest`` is therefore skipped. + """ + if os.path.abspath(path) == os.path.abspath(dest): + return + from .filetree import dest_problem + + problem = dest_problem(dest, path) + if problem is not None: + from . import runstore # runstore imports this module at import time + + raise runstore.RunStoreError(f"cannot write {path}: {problem}") + + def _check_apply_paths(dest: str, written: Sequence[str], backup: Optional[str], check_write: Optional[Callable[[str, str], Any]]) -> None: """Check the selected write set before any artifact or backup is changed. - The blocked-parent and blocked-leaf refusals run before the operator - allowlist guard: they are a property of the filesystem, not of who is - writing, so ``show`` and ``--dry-run`` see them even when + The blocked-parent, blocked-leaf and destination-link refusals run before + the operator allowlist guard: they are a property of the filesystem, not of + who is writing, so ``show`` and ``--dry-run`` see them even when ``AGENTDESCENT_SURFACE_WRITE_DIRS`` is unset. The helper covers ``dest`` and every path in ``written`` (tree children included): a regular file sitting at an intermediate path blocks a leaf the same way a file sitting - at the destination's parent does (#1221, #1208), and a directory already - sitting at a written leaf is refused the other way around (#1223). + at the destination's parent does (#1221, #1208), a directory already + sitting at a written leaf is refused the other way around (#1223), and a + link at a leaf or on the way to one is refused by the writer's own rule + (#1230). """ _refuse_blocked_parent(dest) for path in written: _refuse_blocked_parent(path) _refuse_blocked_leaf(path) + _refuse_link_in_dest(dest, path) if check_write is not None: check_write(dest, "to") for path in written: diff --git a/changelog.d/1230-refusal-walk.md b/changelog.d/1230-refusal-walk.md new file mode 100644 index 00000000..9d3919b9 --- /dev/null +++ b/changelog.d/1230-refusal-walk.md @@ -0,0 +1,7 @@ +Fixed +`apply` and its previews now refuse a link planted inside the destination — at +a tree leaf or on the way to one — with the writer's own rule instead of +advertising the write and then exiting on an uncaught `TreeError`: `show +--diff`, `apply --dry-run`, `apply`, `apply --from` and `apply --install-to` +name the same block. The rule is `filetree.dest_problem`, the one +`materialize` enforces, so the preview cannot drift from the write (#1230). diff --git a/tests/test_apply_symlink_dest.py b/tests/test_apply_symlink_dest.py index aced0c2e..7994523f 100644 --- a/tests/test_apply_symlink_dest.py +++ b/tests/test_apply_symlink_dest.py @@ -17,7 +17,7 @@ import pytest -from agentdescent import cli +from agentdescent import cli, runstore from agentdescent.evolution import EvolutionResult from agentdescent.filetree import TreeError, canonical @@ -145,7 +145,14 @@ def test_a_dangling_link_in_the_backup_dir_is_skipped(tmp_path, capsys, def test_apply_of_a_run_refuses_a_planted_destination_link(tmp_path, monkeypatch): - """The run-id path writes through `filetree.materialize`; same refusal.""" + """The run-id path refuses the link in the funnel, before `materialize`. + + The sentence and the rule stay `materialize`'s (`dest_problem`), but the + exception is the funnel's: every other blocked leaf there (a file on the + way, a directory at the leaf) is refused with ``RunStoreError``, and the + CLI turns that into the exit-2 JSON refusal instead of a traceback + (#1230). + """ real_home = os.path.join(os.path.expanduser("~"), ".agentdescent") home_before = sorted(os.listdir(real_home)) if os.path.isdir(real_home) else None monkeypatch.setenv("AGENTDESCENT_HOME", str(tmp_path / "ad-home")) @@ -157,7 +164,7 @@ def test_apply_of_a_run_refuses_a_planted_destination_link(tmp_path, monkeypatch result = EvolutionResult(state={"SKILL.md": "evolved\n"}, rendered=canonical({"SKILL.md": "evolved\n"}), final_reward=0.0, history=[], ledger_log=[]) - with pytest.raises(TreeError, match="symlink"): + with pytest.raises(runstore.RunStoreError, match="symlink"): result.write_to(str(dest)) assert outside.read_text(encoding="utf-8") == "PRIVATE KEY\n" # The run-id path must not fall back to the developer's own home. From ef336178ce199e8a552f25cda27f7138ebd856d0 Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:05:53 +0800 Subject: [PATCH 3/4] test(cli): the leaf refusal names the relative leaf, as issue #1230 specifies `dest_problem` returns `'' is a symlink` (filetree.py:359) and `_refuse_linked_dest` prefixes the absolute destination path (cli.py:1328), so the sentence is `cannot write : 'alpha' is a symlink`. The row asserted the absolute path inside the reason and was red at a16500e2. Test-only: no production file changes. --- tests/test_apply_refusal_walk.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_apply_refusal_walk.py b/tests/test_apply_refusal_walk.py index 63546712..e0391c52 100644 --- a/tests/test_apply_refusal_walk.py +++ b/tests/test_apply_refusal_walk.py @@ -112,7 +112,7 @@ def test_a_symlinked_leaf_is_named_on_every_surface(tmp_path, capsys): leaf = dest / "alpha" os.symlink(str(victim), str(leaf)) - expected = f"cannot write {leaf}: {str(leaf)!r} is a symlink" + expected = f"cannot write {leaf}: 'alpha' is a symlink" _same_refusal_on_every_surface( tmp_path, capsys, dest, {"alpha": "evolved\n"}, expected) assert os.path.islink(str(leaf)) From 10c957318fd898bbb2aa649b266864512b0135e5 Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 12:01:19 +0000 Subject: [PATCH 4/4] test(apply): pin prune=True refusing to delete a symlink it did not evolve `prune=True` no longer removes a stray link inside the destination: `_check_apply_paths` now runs over `plan["deleted"]` too, so the link is refused with the same `cannot write : '' is a symlink` sentence the write leaves use (#1230). Base deleted it silently, which is why this row fails at 761eb4cb. --- tests/test_apply_noop.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/test_apply_noop.py b/tests/test_apply_noop.py index 7c327941..a6f986b6 100644 --- a/tests/test_apply_noop.py +++ b/tests/test_apply_noop.py @@ -6,7 +6,7 @@ import pytest -from agentdescent import cli +from agentdescent import cli, runstore from agentdescent.evolution import EvolutionResult from agentdescent.filetree import canonical, load_tree @@ -70,6 +70,24 @@ def test_extra_files_alone_do_not_make_an_apply_worth_doing(tmp_path): assert plan["noop"] is False and plan["deleted"] == ["notes.md"] and plan["backup"] +def test_prune_refuses_to_delete_a_symlink_it_did_not_evolve(tmp_path): + # `prune=True` deletes what the run did not evolve, but a link is refused + # before anything is removed (#1230): deleting it would have been a silent + # success over a leaf the rest of the walk refuses to write. + outside = tmp_path / "outside.md" + outside.write_text("keep me\n", encoding="utf-8") + dest = _tree(tmp_path, {"rules.md": "x\n"}) + stray = os.path.join(dest, "stray") + os.symlink(str(outside), stray) + + with pytest.raises(runstore.RunStoreError) as exc: + _result({"rules.md": "x\n"}).write_to(dest, prune=True) + assert str(exc.value) == f"cannot write {stray}: 'stray' is a symlink" + assert os.path.islink(stray) and os.readlink(stray) == str(outside) + assert outside.read_text(encoding="utf-8") == "keep me\n" + assert _baks(dest) == [] + + @pytest.mark.skipif(os.name == "nt", reason="POSIX exec bit") def test_a_script_that_lost_its_exec_bit_is_still_a_change(tmp_path): dest = _tree(tmp_path, {"scripts/run.sh": "echo hi\n"})