Skip to content
Merged
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
57 changes: 50 additions & 7 deletions agentdescent/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2427,20 +2427,60 @@ def _plan_agent_line(spec: Dict[str, Any]) -> Optional[str]:



def _declared_cap(spec: Any) -> Tuple[bool, Optional[int]]:
"""The call cap a spec already declares, for the advice (#1219).

An explicit ``--max-calls`` in ``next:`` wins over the spec's own knobs
(``runstore.py``: "an explicit run option is the sharper instruction"), so
naming the structural bound there silently raised a cap the user had
written down. ``(True, n)`` is ``evolve.max_calls``; ``(True, None)`` is a
priced dollar cap the advice cannot express in calls -- and it wins when a
spec declares both, because an explicit flag replaces the whole
``CallLimit``. ``(False, None)`` means the spec declares neither and the
bound is still the advice.
"""
evolve = getattr(spec, "evolve", None)
knobs = evolve if isinstance(evolve, dict) else {}
# The dollar pair is checked first: an explicit `--max-calls` replaces the
# spec's whole `CallLimit` (`overrides["call_limit"]`, `runstore.py`), so
# advising one for a spec that also declares `max_usd` + `usd_per_call`
# would drop that dollar cap. The spec governs; no flag is advised.
if knobs.get("max_usd") is not None and knobs.get("usd_per_call") is not None:
return True, None
calls = knobs.get("max_calls")
if isinstance(calls, (int, float)) and not isinstance(calls, bool):
return True, int(calls)
return False, None


def _capped_evolve_next(spec_path: str, calls: Any, *,
already_probed: bool = False,
extra_flags: str = "") -> str:
extra_flags: str = "",
declared: Optional[Tuple[bool, Optional[int]]] = None) -> str:
"""The first-run ``next:`` line: preflight, then evolve with a per-call cap.

#1201 / #1217: a new user or host following ``next`` must see
``plan --probe`` (unless this invocation already probed) and
``evolve --max-calls N``, with N from the plan's own
``agent_calls_upper_bound``. ``<N>`` is the placeholder when no
bound is known yet (the default demo footer has no user estimate).

#1219: when the spec declares its own cap, the advice may not raise it --
``min(bound, declared)``, or no flag at all for a dollar cap the command
line cannot express in calls.
"""
cap = (f" --max-calls {int(calls)}"
if isinstance(calls, (int, float)) and calls > 0
else " --max-calls <N>")
declared_flag, declared_calls = declared or (False, None)
if not declared_flag:
cap = (f" --max-calls {int(calls)}"
if isinstance(calls, (int, float)) and calls > 0
else " --max-calls <N>")
elif declared_calls is None:
cap = ""
else:
number = declared_calls
if isinstance(calls, (int, float)) and calls > 0:
number = min(int(calls), declared_calls)
cap = f" --max-calls {number}"
evolve = f"agentdescent evolve {spec_path}{extra_flags}{cap}"
if already_probed:
return evolve
Expand Down Expand Up @@ -2611,7 +2651,8 @@ def cmd_plan(a: argparse.Namespace) -> int:
extra_flags += f" --param {param}"
calls = (payload.get("estimate") or {}).get("agent_calls_upper_bound")
next_line = _capped_evolve_next(
a.spec, calls, already_probed=False, extra_flags=extra_flags)
a.spec, calls, already_probed=False, extra_flags=extra_flags,
declared=_declared_cap(spec))
then_line = None
probe_refused = False
if probe is not None:
Expand All @@ -2633,7 +2674,8 @@ def cmd_plan(a: argparse.Namespace) -> int:
# This invocation already probed; `next:` is the capped evolve
# only (#1217). A refusal keeps the repair + `then:` above.
next_line = _capped_evolve_next(
a.spec, calls, already_probed=True, extra_flags=extra_flags)
a.spec, calls, already_probed=True, extra_flags=extra_flags,
declared=_declared_cap(spec))
# `--baseline-sample` spends real calls, so it runs last: a broken spec or a
# refused probe must not first pay for N rollouts (#1113). The sample's own
# call count is printed before the first one; it is opt-in, and plain `plan`
Expand Down Expand Up @@ -4920,7 +4962,8 @@ def algorithms_run_payload(
# cap `docs/start.md` documents, at the plan's own upper bound -- the
# bare `evolve <spec>` was the one path that named neither.
calls = (payload.get("estimate") or {}).get("agent_calls_upper_bound")
obj["next"] = _capped_evolve_next(out, calls)
obj["next"] = _capped_evolve_next(
out, calls, declared=_declared_cap(spec))
else:
obj["next"] = retry_line
obj["_stage"] = "done"
Expand Down
7 changes: 7 additions & 0 deletions changelog.d/1219-plan-next-spec-cap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Fixed
`plan`'s `next:` line no longer raises a call cap the spec already declares: a
spec with `evolve.max_calls` is advised at `min(bound, declared)`, a spec with
`max_usd` + `usd_per_call` gets no `--max-calls` at all (also when it declares
both, since a flag would replace that dollar cap), and `--json.next` is the
same string. The `estimate.agent_calls_upper_bound` reading is unchanged
(#1219).
115 changes: 115 additions & 0 deletions tests/test_plan_next_respects_spec_cap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""``plan``'s ``next:`` must not raise a cap the spec already declares (#1219).

``runstore.py:1021-1024`` states the rule the advice broke: an explicit run
option "wins over a spec's own knobs". ``next:`` printed ``--max-calls`` at the
structural bound, so a spec declaring ``evolve.max_calls: 5`` was advised to run
with 11 -- following the advice silently raised the user's own cap. The same
declaration also has to agree on both surfaces: ``next:`` and ``--json.next``
are one string, so a host reading the payload sees the same command a person
does.

The bound itself is the engine's structural number, not the CLI's advice, and
``--json.estimate.agent_calls_upper_bound`` stays exactly what it was (#1219
acceptance 4).
"""

import io
import json
from contextlib import redirect_stdout

from agentdescent import cli


def _spec(tmp_path, n=8, **evolve):
rows = [{"prompt": f"q{i}", "gold": f"a{i}"} for i in range(n)]
prompt = tmp_path / "prompt.md"
prompt.write_text("Answer.\n", encoding="utf-8")
cases = tmp_path / "cases.jsonl"
cases.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
path = tmp_path / "spec.json"
path.write_text(json.dumps({
"kind": "text", "target": str(prompt),
"data": {"path": str(cases)}, "score": "contains",
"agent": "echo", "reflect": "echo",
"evolve": {"rounds": 1, "n_workers": 1, "seed": 0, **evolve},
}), encoding="utf-8")
return str(path)


def _run(argv):
buf = io.StringIO()
with redirect_stdout(buf):
code = cli.main(argv)
return code, buf.getvalue()


def _plan(tmp_path, *extra, **evolve):
"""Run ``plan`` in both forms; return (path, text next, json doc)."""
path = _spec(tmp_path, **evolve)
code, out = _run(["plan", path, *extra])
assert code == 0, out
text_next = next(
line[len("next: "):] for line in out.splitlines() if line.startswith("next: "))
code, out = _run(["plan", path, *extra, "--json"])
assert code == 0, out
return path, text_next, json.loads(out)


def test_a_declared_max_calls_is_not_raised_by_the_advice(tmp_path):
path, text_next, doc = _plan(tmp_path, max_calls=5)
# The bound is untouched: it is the engine's number, not the advice's.
assert doc["estimate"]["agent_calls_upper_bound"] == 11
assert text_next == (
f"agentdescent plan {path} --probe, then "
f"agentdescent evolve {path} --max-calls 5"), text_next
assert doc["next"] == text_next


def test_a_declared_cap_above_the_bound_uses_the_bound(tmp_path):
# min(bound, declared): a larger declaration does tighten nothing, and the
# advice must not print a number the plan itself does not support.
path, text_next, doc = _plan(tmp_path, max_calls=50)
assert text_next == (
f"agentdescent plan {path} --probe, then "
f"agentdescent evolve {path} --max-calls 11"), text_next
assert doc["next"] == text_next


def test_a_declared_dollar_cap_suppresses_the_call_cap(tmp_path):
# `max_usd` + `usd_per_call` is a cap the advice cannot express as calls:
# print no `--max-calls` at all, so the spec's dollar cap governs.
path, text_next, doc = _plan(tmp_path, max_usd=0.05, usd_per_call=0.01)
assert "--max-calls" not in text_next, text_next
assert text_next == (
f"agentdescent plan {path} --probe, then "
f"agentdescent evolve {path}"), text_next
assert doc["next"] == text_next



def test_a_spec_declaring_both_caps_keeps_the_dollar_cap(tmp_path):
# An explicit `--max-calls` builds its own CallLimit and the CLI's
# `overrides["call_limit"]` replaces the spec's (`runstore.py:1017-1021`),
# so advising one here would drop the declared *dollar* cap. When a spec
# names both, the dollar pair governs and the advice adds no flag.
path, text_next, doc = _plan(
tmp_path, max_calls=5, max_usd=0.05, usd_per_call=0.01)
assert "--max-calls" not in text_next, text_next
assert text_next == (
f"agentdescent plan {path} --probe, then "
f"agentdescent evolve {path}"), text_next
assert doc["next"] == text_next

def test_without_a_declared_cap_the_bound_is_still_named(tmp_path):
# The #1201 / #1217 contract, unchanged.
path, text_next, doc = _plan(tmp_path)
assert text_next == (
f"agentdescent plan {path} --probe, then "
f"agentdescent evolve {path} --max-calls 11"), text_next
assert doc["next"] == text_next


def test_a_plan_that_already_probed_keeps_the_declared_cap(tmp_path):
path, text_next, doc = _plan(tmp_path, "--probe", max_calls=5)
assert text_next == f"agentdescent evolve {path} --max-calls 5", text_next
assert doc["next"] == text_next
Loading