Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions agentdescent/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 <run_id>` 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))
Expand Down
41 changes: 34 additions & 7 deletions agentdescent/evolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
7 changes: 7 additions & 0 deletions changelog.d/1230-refusal-walk.md
Original file line number Diff line number Diff line change
@@ -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).
20 changes: 19 additions & 1 deletion tests/test_apply_noop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"})
Expand Down
194 changes: 194 additions & 0 deletions tests/test_apply_refusal_walk.py
Original file line number Diff line number Diff line change
@@ -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}: 'alpha' 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"
13 changes: 10 additions & 3 deletions tests/test_apply_symlink_dest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"))
Expand All @@ -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.
Expand Down
Loading