diff --git a/agentdescent/cli.py b/agentdescent/cli.py index 784e6383..b3e77d0b 100644 --- a/agentdescent/cli.py +++ b/agentdescent/cli.py @@ -5947,6 +5947,34 @@ def cmd_mcp(a: argparse.Namespace) -> int: # `--help`, the usage line, and unknown-verb ``choose from`` lists (#420, #886). _INTERNAL_COMMANDS = frozenset({"run"}) +#: What a first run needs, in the order the doc's Path A walks it (#1112). +#: Every other verb keeps its top-level path *and* is grouped under `lab`; the +#: grouping is additive, so this set only decides what the default `--help` +#: advertises. +DEFAULT_SURFACE = ("demo", "init", "plan", "evolve", "show", "apply", + "doctor", "status", "lab", "mcp") + + +class _CommandMount: + """Where :func:`_register_commands` places a verb (#1112). + + Every verb is declared once; the top-level parser and the ``lab`` group + are two mounts of the same declarations. Mounting must not change an + argument, only which verbs the default ``--help`` advertises: an advanced + verb mounted at the top level gets no ``help``, so argparse prints no line + for it (the trick ``run`` has used since #420) while its parser is + unchanged and still parses. ``lab`` lists everything it holds. + """ + + def __init__(self, sub: "argparse._SubParsersAction", *, listed: bool): + self._sub = sub + self._listed = listed + + def add_parser(self, name: str, **kwargs: Any) -> argparse.ArgumentParser: + if not self._listed and name not in DEFAULT_SURFACE: + kwargs.pop("help", None) + return self._sub.add_parser(name, **kwargs) + def _visible_choices(action: argparse.Action) -> List[Any]: """``action.choices`` without internal commands, in registration order.""" @@ -6046,6 +6074,23 @@ def build_parser() -> argparse.ArgumentParser: "or $AGENTDESCENT_HOME/runs)") p.add_argument("--json", action="store_true", help="machine-readable output") sub = p.add_subparsers(dest="cmd", required=True) + _register_commands(_CommandMount(sub, listed=False), with_lab=True) + # Listing order is presentation only: every verb still parses above, this + # only prints the first-run path first (#1112). + order = {name: i for i, name in enumerate(DEFAULT_SURFACE)} + sub._choices_actions.sort(key=lambda action: order.get(action.dest, len(order))) + sub.metavar = "{" + ",".join(n for n in DEFAULT_SURFACE if n in sub.choices) + "}" + _accept_json_after_verb(sub) + return p + + +def _register_commands(mount: "_CommandMount", *, with_lab: bool) -> None: + """Declare every verb once; :func:`build_parser` mounts it twice (#1112). + + ``with_lab`` adds the ``lab`` group at the top of the advanced block; the + mount inside ``lab`` passes ``False`` so the group is not recursive. + """ + sub = mount s = sub.add_parser("demo", help="build a complete example and run it, offline") s.add_argument("--dir", help="where to build it, and keep it " @@ -6141,8 +6186,8 @@ def build_parser() -> argparse.ArgumentParser: # agentdescent.cli run --run-dir `); not a user verb. argparse does # not honour help=SUPPRESS on a sub-parser (it prints "==SUPPRESS==" and # keeps the name in the {...} list), so register it with no help at all - # -- no help line -- leave it out of the metavar below (#420), and strip - # it from unknown-verb ``choose from`` lists (#886). + # -- no help line, never in the usage metavar (#420), and strip it from + # unknown-verb ``choose from`` lists (#886). s = sub.add_parser("run", description="internal: the worker `agentdescent evolve " "--detach` starts; use `evolve` instead") s.add_argument("--run-dir", required=True, dest="run_dir") @@ -6870,6 +6915,12 @@ def build_parser() -> argparse.ArgumentParser: "authentication and lists every run in the store)") s.set_defaults(fn=cmd_serve) + if with_lab: + lab = sub.add_parser("lab", help="every other verb, grouped; " + "`lab ` runs it unchanged") + _register_commands(_CommandMount(lab.add_subparsers(dest="lab_cmd", required=True), + listed=True), with_lab=False) + s = sub.add_parser("mcp", help="serve the tools over MCP (stdio by default; needs agentdescent[mcp])") s.add_argument("--transport", choices=("stdio", "streamable-http"), default="stdio", help="stdio for hosts that spawn a subprocess (default); streamable-http " @@ -6894,10 +6945,6 @@ def build_parser() -> argparse.ArgumentParser: "also AGENTDESCENT_MCP_ADVANCED=1)") s.set_defaults(fn=cmd_mcp) - sub.metavar = "{" + ",".join(n for n in sub.choices if n not in _INTERNAL_COMMANDS) + "}" - _accept_json_after_verb(sub) - return p - def _accept_json_after_verb(sub: "argparse._SubParsersAction") -> None: """Let ``--json`` follow the verb as well as precede it (#513). diff --git a/changelog.d/1112-lab-grouping.md b/changelog.d/1112-lab-grouping.md new file mode 100644 index 00000000..2cec8312 --- /dev/null +++ b/changelog.d/1112-lab-grouping.md @@ -0,0 +1,6 @@ +Changed +`agentdescent --help` now lists the first-run path (`demo`, `init`, `plan`, +`evolve`, `show`, `apply`, `doctor`, `status`) plus `mcp`, and every other verb +is grouped under a new `lab` subcommand (`agentdescent lab campaign …`); each +verb keeps its old top-level path, its arguments, its output and its exit code, +and the same declaration mounts both paths (#1112). diff --git a/tests/test_cli_help_hides_internal_run.py b/tests/test_cli_help_hides_internal_run.py index 446955c1..b59d356c 100644 --- a/tests/test_cli_help_hides_internal_run.py +++ b/tests/test_cli_help_hides_internal_run.py @@ -44,9 +44,13 @@ def test_help_and_usage_do_not_list_run(): def test_every_public_verb_is_still_listed_in_order(): + # Since #1112 the usage line lists the first-run surface only; the + # advanced verbs are hidden from it, not removed from the parser. verbs = _verbs_in_braces(cli.build_parser().format_usage()) - public = [n for n in _subparsers_action().choices if n != "run"] - assert verbs == public + assert verbs == list(cli.DEFAULT_SURFACE) + hidden = [n for n in _subparsers_action().choices + if n not in cli.DEFAULT_SURFACE and n != "run"] + assert "campaign" in hidden and "snapshot" in hidden def test_every_listed_verb_has_a_help_line(): diff --git a/tests/test_cli_lab_grouping.py b/tests/test_cli_lab_grouping.py new file mode 100644 index 00000000..bc1f59a1 --- /dev/null +++ b/tests/test_cli_lab_grouping.py @@ -0,0 +1,155 @@ +"""The default ``--help`` is one first-run path; every verb also runs under ``lab`` (#1112). + +Thirty-odd verbs are all registered at the top level, so a new user's first +screen is a wall of ``portfolio`` / ``campaign`` / ``tenant``. The fix keeps +every verb reachable under its old name and mounts the same declarations a +second time under a ``lab`` group, while the default listing shows only the +first-run surface. + +What is pinned here: + +* the verbs ``agentdescent --help`` lists, in order, and the same set in the + usage line; +* ``lab`` holding every verb but itself, so ``agentdescent lab `` is + reachable for all of them, not only the advanced ones; +* the two paths parsing to the same dispatch (``fn``) and the same namespace + for every verb -- a grouping change may not alter a single argument; +* each advanced verb still answering ``--help`` at its old path. +""" + +import argparse +import re + +import pytest + +from agentdescent import cli + + +def _subparsers(parser): + return next(a for a in parser._actions + if isinstance(a, argparse._SubParsersAction)) + + +def _top_level(): + return _subparsers(cli.build_parser()) + + +def _braced_verbs(text): + """The ``{a,b,c}`` command list argparse prints, as a list.""" + match = re.search(r"\{([a-z_,-]+)\}", text) + assert match, text + return match.group(1).split(",") + + +def _listed_verbs(text): + """The verbs under ``positional arguments:``, in the order help shows them.""" + return re.findall(r"^ ([a-z][a-z_-]*)\s{2,}\S", text, re.M) + + +#: What a first run needs, in the order argparse lists them (Path A order). +DEFAULT_SURFACE = [ + "demo", "init", "plan", "evolve", "show", "apply", "doctor", "status", + "lab", "mcp", +] + +#: Every verb mounted under ``lab``: everything registered but ``lab`` itself. +_VERBS = [n for n in _top_level().choices if n != "lab"] +_ADVANCED = [n for n in _VERBS if n not in DEFAULT_SURFACE] + + +def test_default_help_lists_only_the_first_run_surface(): + text = cli.build_parser().format_help() + assert _listed_verbs(text) == DEFAULT_SURFACE, text + + +def test_the_usage_line_names_the_same_surface(): + assert _braced_verbs(cli.build_parser().format_usage()) == DEFAULT_SURFACE + + +def test_lab_mounts_every_verb_but_itself(): + top = _top_level() + lab = _subparsers(top.choices["lab"]) + assert list(lab.choices) == _VERBS + + +def test_advanced_verbs_are_hidden_but_still_parsed(): + parser = cli.build_parser() + assert "campaign" not in _listed_verbs(parser.format_help()) + names = _subparsers(parser).choices + assert "campaign" in names and "tenant" in names and "serve" in names + + +def _value_for(action): + if action.choices: + return str(next(iter(action.choices))) + if action.type is int: + return "1" + if action.type is float: + return "1.5" + return "x" + + +def _minimal_args(parser): + """A shortest argv that satisfies one verb's required arguments.""" + argv = [] + for group in parser._mutually_exclusive_groups: + if not group.required: + continue + action = group._group_actions[0] + argv.append(action.option_strings[-1]) + if action.nargs != 0: + argv.append(_value_for(action)) + nested = None + for action in parser._actions: + if isinstance(action, argparse._SubParsersAction): + nested = action + continue + if isinstance(action, (argparse._HelpAction, argparse._VersionAction)): + continue + if action.option_strings: + if not action.required: + continue + argv.append(action.option_strings[-1]) + if action.nargs != 0: + argv.append(_value_for(action)) + elif action.nargs in (None, "+"): + argv.append(_value_for(action)) + if nested is not None: + name = next(iter(nested.choices)) + argv.append(name) + argv += _minimal_args(nested.choices[name]) + return argv + + +def _namespace(args): + # ``cmd`` is the top-level dispatch key and ``lab_cmd`` the nested one; + # both name where the verb was typed, so only they may differ. + return {k: v for k, v in vars(args).items() + if k not in ("fn", "cmd", "lab_cmd")} + + +@pytest.mark.parametrize("verb", _VERBS) +def test_lab_path_parses_like_the_top_level(verb): + parser = cli.build_parser() + argv = [verb] + _minimal_args(_subparsers(parser).choices[verb]) + at_top = parser.parse_args(argv) + at_lab = parser.parse_args(["lab"] + argv) + assert at_top.fn is not None + assert at_lab.fn is at_top.fn + assert _namespace(at_lab) == _namespace(at_top) + + +@pytest.mark.parametrize("verb", _ADVANCED) +def test_a_hidden_verb_still_answers_help(verb, capsys): + with pytest.raises(SystemExit) as exc: + cli.main([verb, "--help"]) + assert exc.value.code == 0 + assert capsys.readouterr().out.strip() + + +@pytest.mark.parametrize("verb", _ADVANCED) +def test_the_lab_path_answers_help(verb, capsys): + with pytest.raises(SystemExit) as exc: + cli.main(["lab", verb, "--help"]) + assert exc.value.code == 0 + assert capsys.readouterr().out.strip()