Skip to content
Open
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
4 changes: 3 additions & 1 deletion agentdescent/integrations/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ after `doctor`. Do not invent a keyless path for those cards.
`agentdescent algorithms list` / `show`. To build the spec for one,
call `algorithm_spec` (name, absolute `path`, absolute `cases`, optional
`params` object, `rounds`/`workers` 1/1 for a quick trial): it writes the
starter spec beside the target, plans it, and returns `spec` to pass to
starter spec under `$AGENTDESCENT_HOME` (`agentdescent.<name>.spec.json`,
inside the operator's write allowlist; pass `out` for another allowed root,
never inside a directory target), plans it, and returns `spec` to pass to
`start` after the user's yes -- the MCP form of `agentdescent algorithms
run`. Hosts that expose slash
commands also ship `/algorithms` (Claude `/agentdescent:algorithms`,
Expand Down
35 changes: 27 additions & 8 deletions agentdescent/mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,11 @@ def advanced_from_env(environ: Optional[Dict[str, str]] = None) -> bool:
"algorithm `name` (from list_algorithms), the absolute target `path`, and the "
"absolute `cases` JSONL; `params` is the algorithm's params as an object "
"(check describe_algorithm first), and `rounds`/`workers` = 1/1 is a quick "
"trial. It writes the spec file (default beside the target, never inside it) "
"and returns the plan estimate plus `spec`, the dict to pass to start. It "
"trial. It writes the spec file under `$AGENTDESCENT_HOME` "
"(`agentdescent.<name>.spec.json`, inside the operator's write allowlist) "
"unless `out` names another path under one of those roots -- never inside "
"a directory target -- and returns the plan estimate plus `spec`, the dict "
"to pass to start. It "
"starts nothing: show the user the estimate and get a yes before start. "
"`model`/`base_url` come from the user, never guess them."),
"plan": (
Expand Down Expand Up @@ -538,21 +541,28 @@ def algorithm_spec(self, name: str, path: str, cases: Optional[str] = None,
return {"ok": False, "error": f"params key {pname!r} was given "
"more than once"}
clean[pname] = value
# The server's cwd is not the host's, so paths are made absolute here
# and the default spec goes beside the target -- never inside a
# directory target, where it would become part of the artifact.
# The server's cwd is not the host's, so paths are made absolute here.
# The default spec goes under the write allowlist, not beside the
# target: the user's file is usually outside the default roots (the
# server's cwd and $AGENTDESCENT_HOME), so a beside-the-target default
# was refused on an untouched install (#1108).
abs_path = os.path.abspath(os.path.expanduser(path))
abs_cases = (os.path.abspath(os.path.expanduser(cases))
if cases is not None else None)
registered = name
if out is None:
from . import algorithms
from .surface_common import SurfaceError, default_write_root

try:
registered = algorithms.get(name, where="algorithm_spec").name
except algorithms.AlgorithmError as e:
return {"ok": False, "error": str(e)}
out = os.path.join(os.path.dirname(abs_path.rstrip(os.sep)) or os.sep,
f"agentdescent.{registered}.spec.json")
try:
root = default_write_root(self.surface_write_dirs)
except SurfaceError as e:
return {"ok": False, "error": str(e)}
out = os.path.join(root, f"agentdescent.{registered}.spec.json")
else:
out = os.path.abspath(os.path.expanduser(out))
# Every other tool that writes a file routes its destination through
Expand All @@ -564,7 +574,16 @@ def algorithm_spec(self, name: str, path: str, cases: Optional[str] = None,
try:
self._check_write(out, "out")
except SurfaceError as e:
return {"ok": False, "error": str(e)}
# Actionable, not just the variable name: name a path that works
# (#1108). The allowed roots come from _check_write's own message.
hint = ""
if self.surface_write_dirs:
example = os.path.join(
os.path.abspath(os.path.expanduser(
str(self.surface_write_dirs[0]))),
f"agentdescent.{registered}.spec.json")
hint = f"; pass `out` under one of those roots, e.g. {example!r}"
return {"ok": False, "error": f"{e}{hint}"}
try:
obj = algorithms_run_payload(
name, abs_path, kind=kind, cases=abs_cases, agent=agent,
Expand Down
49 changes: 46 additions & 3 deletions agentdescent/surface_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
"resolve_ref",
"surface_allow_from_env",
"surface_write_dirs_from_env",
"surface_home",
"default_write_root",
"scrub_host_env",
"SESSION_MARKERS",
"DETACHED_KEEP_VARS",
Expand Down Expand Up @@ -200,11 +202,51 @@ def surface_write_dirs_from_env(environ: Optional[Mapping[str, str]] = None
env = environ if environ is not None else os.environ
raw = env.get("AGENTDESCENT_SURFACE_WRITE_DIRS")
if raw is None:
home = env.get("AGENTDESCENT_HOME") or "~/.agentdescent"
return (os.getcwd(), os.path.abspath(os.path.expanduser(home)))
return (os.getcwd(), surface_home(env))
return tuple(part.strip() for part in raw.split(",") if part.strip())


def surface_home(environ: Optional[Mapping[str, str]] = None) -> str:
"""``$AGENTDESCENT_HOME``, expanded and absolute (else ``~/.agentdescent``).

The same normalisation the run store applies (#402): a host config's ``env``
is not shell-expanded, so ``~/x`` arrives with a literal ``~``.
"""
env = environ if environ is not None else os.environ
return os.path.abspath(os.path.expanduser(
env.get("AGENTDESCENT_HOME") or "~/.agentdescent"))


def _inside(root: str, path: str) -> bool:
target = os.path.normcase(os.path.realpath(path))
base = os.path.normcase(os.path.realpath(os.path.expanduser(str(root))))
return target == base or target.startswith(base.rstrip(os.sep) + os.sep)


def default_write_root(allow: Optional[Sequence[str]],
environ: Optional[Mapping[str, str]] = None) -> str:
"""The root a surface writes under when its own argument names no path.

``$AGENTDESCENT_HOME`` while the operator allows it -- unset, the default
allowlist is the server's cwd plus that home -- otherwise the first allowed
root. Its whole point is that the default is inside the allowlist: the old
"beside the target" default was outside it for every user file outside those
two roots, so the shortest documented path failed on an untouched install
(#1108).
"""
roots = [os.path.abspath(os.path.expanduser(str(root)))
for root in (allow or ()) if str(root).strip()]
if not roots:
raise SurfaceError(
"no write directory is allowed (AGENTDESCENT_SURFACE_WRITE_DIRS is "
"empty), so there is no default output path; pass an explicit path "
"and name its root in AGENTDESCENT_SURFACE_WRITE_DIRS")
home = surface_home(environ)
if any(_inside(root, home) for root in roots):
return home
return roots[0]


#: Environment variables a host agent sets in its own session and its children
#: inherit. A worker that sees them believes it is *inside* that session: Claude
#: Code refuses to start, DSH loads the parent's profile, and a worker whose
Expand Down Expand Up @@ -318,7 +360,8 @@ def ensure_write_path(path: Any, *, name: str,
for root in roots):
raise SurfaceError(
f"{name} {path!r} is outside the operator's write allowlist "
f"(AGENTDESCENT_SURFACE_WRITE_DIRS)")
f"(AGENTDESCENT_SURFACE_WRITE_DIRS); allowed roots: "
+ ", ".join(repr(root) for root in allow))
return resolved


Expand Down
7 changes: 7 additions & 0 deletions changelog.d/1108-algorithm-spec-default-out.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Fixed
`algorithm_spec` no longer defaults its starter spec to a path beside the
user's target, which the default write allowlist refused: an omitted `out` now
writes `agentdescent.<name>.spec.json` under `$AGENTDESCENT_HOME` (or the first
explicitly allowed root), so the shortest documented path plans on an untouched
install. The tool description and the shared `SKILL.md` say so, and a refused
explicit `out` names the allowed roots and an `out` that works (#1108).
4 changes: 3 additions & 1 deletion integrations/claude-code/skills/agentdescent/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ after `doctor`. Do not invent a keyless path for those cards.
`agentdescent algorithms list` / `show`. To build the spec for one,
call `algorithm_spec` (name, absolute `path`, absolute `cases`, optional
`params` object, `rounds`/`workers` 1/1 for a quick trial): it writes the
starter spec beside the target, plans it, and returns `spec` to pass to
starter spec under `$AGENTDESCENT_HOME` (`agentdescent.<name>.spec.json`,
inside the operator's write allowlist; pass `out` for another allowed root,
never inside a directory target), plans it, and returns `spec` to pass to
`start` after the user's yes -- the MCP form of `agentdescent algorithms
run`. Hosts that expose slash
commands also ship `/algorithms` (Claude `/agentdescent:algorithms`,
Expand Down
2 changes: 1 addition & 1 deletion integrations/dsh-agentdescent/lib/index.js

Large diffs are not rendered by default.

9 changes: 6 additions & 3 deletions tests/test_mcp_algorithm_spec_allowlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,19 @@ def test_an_out_outside_the_write_allowlist_is_refused(tmp_path):
assert not outside.exists()


def test_the_default_out_beside_an_outside_target_is_refused_too(tmp_path):
def test_the_default_out_goes_to_the_allowed_root_not_the_target_directory(
tmp_path):
"""A default that lands outside the allowlist is refused before it is
written, so it must not be "beside the target" any more (#1108)."""
prompt, cases = _prompt_and_cases(tmp_path)
allowed = tmp_path / "allowed"
allowed.mkdir()

result = Tools(None, surface_write_dirs=(str(allowed),)).algorithm_spec(
"rrsi", str(prompt), str(cases), **_FLAGS)

assert result["ok"] is False
assert "write allowlist" in result["error"]
assert result["ok"] is True, result
assert result["spec_path"] == str(allowed / "agentdescent.rrsi.spec.json")
assert not (tmp_path / "agentdescent.rrsi.spec.json").exists()


Expand Down
118 changes: 118 additions & 0 deletions tests/test_mcp_algorithm_spec_default_out.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""An omitted ``out`` must land inside the write allowlist (#1108).

The tool description and the shared ``SKILL.md`` taught hosts to call
``algorithm_spec`` without ``out`` and get the starter spec *beside the target*.
That default is inside no default write root whenever the user's file sits
outside the server's cwd and ``$AGENTDESCENT_HOME``, so the shortest documented
path failed with ``ok=false`` on an untouched install (#1108). The default now
lands under ``$AGENTDESCENT_HOME`` (or the first explicit root), and the refusal
for an explicit ``out`` names the roots it can use.
"""

import json

from agentdescent.mcp import TOOL_DESCRIPTIONS, Tools

_FLAGS = dict(model="deepseek-v4-flash",
base_url="https://ark.cn-beijing.volces.com/api/coding/v3")


def _prompt_and_cases(tmp_path, n=8):
prompt = tmp_path / "prompt.md"
prompt.write_text("be terse\n")
cases = tmp_path / "cases.jsonl"
cases.write_text("".join(
json.dumps({"prompt": f"q{i}", "gold": f"a{i}"}) + "\n" for i in range(n)))
return prompt, cases


def _scratch(tmp_path, monkeypatch):
"""A server cwd and a user directory that are neither the home."""
server = tmp_path / "server"
user = tmp_path / "user-project"
home = tmp_path / "home"
server.mkdir()
user.mkdir()
monkeypatch.chdir(server)
monkeypatch.delenv("AGENTDESCENT_SURFACE_WRITE_DIRS", raising=False)
monkeypatch.setenv("AGENTDESCENT_HOME", str(home))
return server, user, home


def test_an_omitted_out_lands_under_the_home_root(tmp_path, monkeypatch):
_, user, home = _scratch(tmp_path, monkeypatch)
prompt, cases = _prompt_and_cases(user)

result = Tools(None).algorithm_spec(
"rrsi", str(prompt), str(cases), **_FLAGS)

assert result["ok"] is True, result
expected = home / "agentdescent.rrsi.spec.json"
assert result["spec_path"] == str(expected)
assert json.loads(expected.read_text())["algorithm"] == "rrsi"
# The documented default never touches the user's directory.
assert not (user / "agentdescent.rrsi.spec.json").exists()


def test_an_omitted_out_honours_an_explicit_allowlist(tmp_path, monkeypatch):
_, user, _ = _scratch(tmp_path, monkeypatch)
prompt, cases = _prompt_and_cases(user)
allowed = tmp_path / "allowed"
allowed.mkdir()

result = Tools(None, surface_write_dirs=(str(allowed),)).algorithm_spec(
"rrsi", str(prompt), str(cases), **_FLAGS)

assert result["ok"] is True, result
expected = allowed / "agentdescent.rrsi.spec.json"
assert result["spec_path"] == str(expected)
assert expected.exists()


def test_an_explicit_out_outside_the_allowlist_names_where_it_may_write(
tmp_path, monkeypatch):
_, user, _ = _scratch(tmp_path, monkeypatch)
prompt, cases = _prompt_and_cases(user)
allowed = tmp_path / "allowed"
allowed.mkdir()
outside = tmp_path / "outside" / "spec.json"

result = Tools(None, surface_write_dirs=(str(allowed),)).algorithm_spec(
"rrsi", str(prompt), str(cases), out=str(outside), **_FLAGS)

assert result["ok"] is False
error = result["error"]
assert "write allowlist" in error
# Actionable: the roots it may use and an example path under one of them.
assert str(allowed) in error
assert "pass `out`" in error
assert not outside.exists()


def test_an_empty_allowlist_says_so_instead_of_naming_a_target_directory(
tmp_path, monkeypatch):
_, user, _ = _scratch(tmp_path, monkeypatch)
prompt, cases = _prompt_and_cases(user)

result = Tools(None, surface_write_dirs=()).algorithm_spec(
"rrsi", str(prompt), str(cases), **_FLAGS)

assert result["ok"] is False
assert "AGENTDESCENT_SURFACE_WRITE_DIRS" in result["error"]
assert "no write" in result["error"].lower()


def test_the_description_no_longer_documents_a_beside_the_target_default():
text = TOOL_DESCRIPTIONS["algorithm_spec"]

assert "beside the target" not in text
assert "AGENTDESCENT_HOME" in text


def test_the_shared_skill_writes_the_default_spec_under_the_home():
from agentdescent.integrations import _skill_body

body = _skill_body()

assert "beside the target" not in body
assert "AGENTDESCENT_HOME" in body
Loading