From 1491857947f67a06df52e1a3507927e9cdfdc036 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 04:08:56 +0900 Subject: [PATCH 1/6] docs(design): 0.3.0 -- the command-line capabilities the programs built with cmdline need in common Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com> --- ...6-12-05-generic-cli-capabilities-design.md | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 .agents/docs/2026-12-05-generic-cli-capabilities-design.md diff --git a/.agents/docs/2026-12-05-generic-cli-capabilities-design.md b/.agents/docs/2026-12-05-generic-cli-capabilities-design.md new file mode 100644 index 0000000..0f9651e --- /dev/null +++ b/.agents/docs/2026-12-05-generic-cli-capabilities-design.md @@ -0,0 +1,77 @@ +# mcpplibs.cmdline 0.3.0:使用者共同需要的命令行能力 —— 子设计 + +- 日期:2026-12-05。状态:**已评审,实现于 0.3.0**(mcpplibs/cmdline 的 PR,每项一个检查点)。 +- 来源:xlings 的生态设计(openxlings/xlings `.agents/docs/2026-11-27-ecosystem-truthful-results-and-architecture-design.md` + §22)。xlings 把命令树改为只用 cmdline 声明(帮助、补全、`--agent-skill-doc` 与核对都从它派生),读它的命令行时 + 发现了库里缺的东西;mcpp(生态设计 §3.9)已用 0.2.0,同类需求它曾在自己的代码里手写。 +- 判据:**一项能力放进 cmdline,当且仅当任何一个用 cmdline 写的命令行都可能需要它,并且实现它不需要知道使用者的领域。** + 只是承载使用者的事实(例如命令的副作用)时,库提供承载的位置,不解释其含义。 +- 兼容:全部是增量。没有选用任何新项时,帮助、补全与快照的输出与 0.2.0 逐字节相同(与 0.0.7 的承诺相同)。 + +## 1. 现状(读 0.2.0 的源码) + +| 使用者需要 | 0.2.0 | 后果 | +|---|---|---| +| 命令别名(xlings:`subos list` 也叫 `ls`,`remove` 也叫 `rm`,`info` 也叫 `i`) | 没有 | 使用者只能在库外维护第二份名字表,帮助与补全看不到它 | +| 渐进显示(xlings:`--help` 只列常用的,`help --all` 再加一层,`--expert` 再加一层) | 只有 `hidden`(全有或全无) | 不常用的选项要么挤满 `--help`,要么完全看不见 | +| 给命令附加使用者的事实(xlings:每个命令的副作用 read、reversible、irreversible、external 与作用的范围,给 agent 读) | 没有 | 只能维护一张按命令路径为键的旁表,即第二份声明 | +| 原样传递的尾部参数(`xlings script <文件> [参数...]`、`exec <名字> <命令...>`) | `-h`/`--help` 在 `--` 之前的任何位置都被截走 | `xlings script x.lua --help` 打印 xlings 的帮助,脚本拿不到 `--help` | +| 未知命令的同义词提示(`uninstall` 对应 `remove`,`add` 对应 `install`) | 只有按编辑距离的相近名字 | 别的工具的动词得不到指向 | +| `help <命令...>` 入口 | 没有;mcpp 在解析前手工改写 | 每个使用者各写一遍 | +| 补全候选带说明、回调知道上下文 | `Candidates` 只返回字符串、只拿到前缀 | xlings 现有的候选带说明(主题、`current` 的含义),迁过来就丢了 | +| 补全协议是可依赖的契约 | `__complete` 与适配器已实现,但文档只写在 api.md 的用法里 | 一个包管理器想为任何用 cmdline 写的程序在安装时生成补全(不运行它),需要协议是稳定的 | + +## 2. 设计 + +1. **命令别名。** 用 `App::alias(name)` 声明,可以多个。解析接受别名,结果里的命令名是规范名 + (`ParsedArgs::subcommand_name()`、`command_path()` 都给规范名)。帮助写成 `list, ls`,补全只给规范名, + 未知命令的相近名字也比较别名。快照的 `Command` 多一个 `aliases`,`agent_skills` 的键用规范名。 + 同一级里别名与另一个名字冲突时,在建树时就报错,并有测试覆盖。 +2. **渐进显示的三级。** 命令与选项都可以设 `level(Level::common | more | expert)`,默认 common。 + - `--help` 只列 common,末尾一行说明还有多少被收起、怎样看。 + - `--help --all` 再列 more,`--help --all --expert` 列全部。只有紧跟 `--help` 时,`--all` 与 `--expert` 才是帮助的修饰; + `--help` 本来就优先于其他词,所以这不会与命令自己的 `--all` 混淆。 + - 层级只影响列出,不影响解析与补全:expert 选项照常可用,补全时排在后面。 + - 快照带上层级,使用者的参考文档可以按层输出。 +3. **注记。** 用 `App::annotate(key, value)` 声明,值是字符串,可以有多个键;选项上也可以加。注记进快照 + (`Command::annotations`),库不解释它们,也不出现在帮助里。`agent_skills::check_options` 多一个 + `required_annotations`:每个可见命令都必须带这些键,否则核对报一行,于是"每个命令都声明了副作用"也成为测试。 +4. **原样传递的尾部参数。** 用 `Arg::trailing()` 声明。落到这个参数的那个词结束选项:其后的词(包括 `--help`、 + `-v`)都是位置参数,等同于在它后面写了 `--`;在它之前,选项照常属于这个命令。两种写法由同一条规则覆盖: + - `tool script [args...]` 把 `file` 声明为 trailing,`tool script x.lua --help` 把 `--help` 交给脚本; + - `tool exec ...` 把 `command` 声明为 trailing,`tool exec box --net none -- make` 里的 + `--net` 仍是 exec 的。 + (实现时改正:初稿写的是"必须是最后一个参数",那样 `script` 的例子做不到。)补全遵守同一条规则。 +5. **未知命令的同义词。** 用 `App::synonyms({{"uninstall", "remove"}, {"agent", "--agent-skill-doc"}})` 声明, + 值是该用的写法。同义词不参与解析:它们不是命令,执行时也不会被当成命令。遇到 `unknown-command` 时, + 如果词在表里,消息写成 + `tool: 'uninstall' is not a command of 'tool'; to do that: tool remove`, + `suggestions` 的第一项是表里的写法,错误代码仍是 `unknown-command`。这只是提示,库不会替人执行。 +6. **`help` 入口。** 用 `HelpOptions::help_command = true` 开启(默认关):`tool help a b` 与 `tool a b --help` 同义, + `tool help` 打印根的帮助;`help` 出现在帮助的列表里。未知的路径按第 5 条与 0.2.0 的相近名字处理。 +7. **补全候选带说明与上下文。** 增加 `Candidates` 的一个重载: + `std::vector(std::string_view prefix, const CompletionContext&)`。`Candidate` 是 `{value, description}`; + `CompletionContext` 给出命令路径和光标前已解析的位置参数与选项。旧签名照常可用。`__complete` 的输出本来就是 + `值说明`,协议不变。 +8. **补全协议成为契约。** 在 `docs/completion-protocol.md` 写明协议版本 1:请求是 `prog <光标前的词...>`; + 回答是每行 `值说明`,最后一行是 `:<指令>`(0 无、1 由 shell 补文件、2 由 shell 补目录);四种 shell 的 + 适配器,以及 `completions::adapter(shell, program, entry)` 给出的就是它们。承诺:协议的不兼容改变使用一个新的 + 入口名,旧入口不变。这样,别的程序(例如包管理器)可以只凭"这个程序用 cmdline 的协议"就为它写出适配器, + 不需要运行它;适配器在补全时才问程序,所以它不随程序的版本变化。 + +## 3. 不放进 cmdline 的 + +- **诊断代码的查询命令(`explain`)。** 诊断代码是应用的语义,cmdline 只拥有自己的用法错误代码,0.2.0 已经让它们带上 + 代码与相近名字。一个应用如果需要按键取嵌入的文本,`agent_skills` 的构建时渲染与按键应答就是这种机制,不需要新功能。 +- **受众模式(agent 模式)、副作用的含义、退出码表。** 都是应用的。库只承载事实(第 3 条),并且已把用法错误固定为退出 2。 +- **把同义词当作别名执行。** 一个有副作用的命令按猜出的名字执行,就是替人做了决定;别名只用于应用自己定义的缩写(第 1 条)。 + +## 4. 测试与发布 + +- 每条都有 `tests/cmdline_test.cpp` 或 `tests/completions_test.cpp` 的用例:别名的解析、帮助与冲突报错;三级显示的 + `--help`、`--help --all`、`--help --all --expert` 输出快照;注记进快照,`required_annotations` 的核对报出缺的命令; + 尾部参数里的 `--help` 原样传入;同义词的消息与 `suggestions`;`help a b` 与 `a b --help` 输出相同;带说明的候选与上下文; + 协议文档中的例子由测试执行,比对输出。 +- 不选用新项时与 0.2.0 相同:现有的快照测试不改一个字节。 +- 一个 PR,每条一个 commit 作为检查点。发布 0.3.0,在 mcpp-index 加 0.2.0 与 0.3.0 的条目(xlings 设计的 M2), + 再由 xlings 使用。mcpp 可按需采用第 1、4、6 条,不需要同步。 From c517fdab3d044e99c05ae507a4665dcf1671517d Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Sat, 5 Dec 2026 04:08:56 +0900 Subject: [PATCH 2/6] feat: aliases, help levels, annotations, trailing arguments, synonyms, the help command and described candidates -- one declaration answers them all (G1-G7) Co-authored-by: speak-agent <248744407+speak-agent@users.noreply.github.com> --- fixtures/skills/src/main.cpp | 16 ++- src/agent_skills.cppm | 18 ++++ src/cmdline.cppm | 184 +++++++++++++++++++++++++++++++--- src/complete.cppm | 63 +++++++----- src/completions.cppm | 19 ++++ src/options.cppm | 67 +++++++++++++ src/parse.cppm | 3 + tests/capabilities_test.cpp | 186 +++++++++++++++++++++++++++++++++++ 8 files changed, 518 insertions(+), 38 deletions(-) create mode 100644 tests/capabilities_test.cpp diff --git a/fixtures/skills/src/main.cpp b/fixtures/skills/src/main.cpp index 41f73f6..e1abe1d 100644 --- a/fixtures/skills/src/main.cpp +++ b/fixtures/skills/src/main.cpp @@ -7,8 +7,9 @@ int main() { using namespace mcpplibs::cmdline; App app("skills-fixture"); App self("self"); - (void)self.subcommand("world").description("the nested world skill"); - (void)app.subcommand("hello").description("say hello"); + (void)self.annotate("effect", "read"); + (void)self.subcommand("world").description("the nested world skill").annotate("effect", "read"); + (void)app.subcommand("hello").description("say hello").annotate("effect", "read"); (void)app.subcommand(std::move(self)); // The table was rendered by build.mcpp; the runtime reads no file. agent_skills::install_default(app, fixture::skills::sheets, @@ -18,7 +19,8 @@ int main() { if (app.run(Argv{"skills-fixture", "--agent-skill-doc"}) != 0) return 3; // The sheets agree with the tree; a sheet that does not is reported. - if (const auto problems = agent_skills::check(app, fixture::skills::sheets, {.ascii_only = true}); + if (const auto problems = agent_skills::check(app, fixture::skills::sheets, + {.ascii_only = true, .required_annotations = {"effect"}}); !problems.empty()) { for (const auto& line : problems) std::println(std::cerr, "{}", line); return 4; @@ -33,5 +35,13 @@ int main() { for (const auto& line : problems) std::println(std::cerr, "{}", line); return 5; } + // A command without the fact every command states is reported (0.3.0). + (void)app.subcommand(App("bare").description("no facts")); + const auto unannotated = agent_skills::check(app, fixture::skills::sheets, + {.exempt = {"bare"}, .required_annotations = {"effect"}}); + if (unannotated.size() != 1 || unannotated.front().find("'skills-fixture bare' has no 'effect' annotation") == std::string::npos) { + for (const auto& line : unannotated) std::println(std::cerr, "{}", line); + return 6; + } return 0; } diff --git a/src/agent_skills.cppm b/src/agent_skills.cppm index 2654efa..c732124 100644 --- a/src/agent_skills.cppm +++ b/src/agent_skills.cppm @@ -257,6 +257,10 @@ struct check_options { bool ascii_only = false; /// 0: no limit. The build helper enforces its own limit when it renders. std::size_t max_lines = 0; + /// Annotation keys every visible command (the root and the commands the + /// library adds aside) carries (0.3.0, `App::annotate`): a fact the + /// program documents for each command cannot be forgotten for one. + std::vector required_annotations; }; namespace detail { @@ -320,7 +324,21 @@ std::vector check(const App& app, const Sheet (&sheets)[N], check_o const auto tree = snapshot(app); const auto by_key = detail::table(sheets); const std::string name(app.name()); + if (!o.required_annotations.empty()) { + const auto annotated = [&](this const auto& self, const completions::Command& command, const std::string& path) -> void { + for (const auto& sub : command.subcommands) { + if (sub.generated) continue; + const auto key = path.empty() ? sub.name : path + " " + sub.name; + for (const auto& wanted : o.required_annotations) + if (sub.annotation(wanted).empty()) + problems.push_back(std::format("command '{} {}' has no '{}' annotation", name, key, wanted)); + self(sub, key); + } + }; + annotated(tree, ""); + } for (const auto& command : tree.subcommands) { + if (command.generated) continue; if (std::ranges::find(o.exempt, command.name) != o.exempt.end()) continue; if (!by_key.contains(command.name)) problems.push_back(std::format("command '{} {}' has no sheet (docs/{}-skills/{}-{}/SKILL.md)", diff --git a/src/cmdline.cppm b/src/cmdline.cppm index cdd95bb..784a478 100644 --- a/src/cmdline.cppm +++ b/src/cmdline.cppm @@ -54,9 +54,14 @@ export struct HelpOptions { /// a group are listed under `ungrouped`, or `SUBCOMMANDS` when it is empty. /// A command's help with no groups is unchanged. bool groups_as_sections = false; + /// `tool help ...` is `tool ... --help`, and `tool help` + /// the root's help (0.3.0); `help` is listed with the subcommands. Read on + /// the root only. + bool help_command = false; }; export using detail::Arg; export using detail::Option; +export using mcpplibs::cmdline::Level; export using detail::OptionValue; export using detail::ParseError; export using detail::ParseResult; @@ -142,7 +147,8 @@ public: App(const App& other) : name_(other.name_), version_(other.version_), description_(other.description_), author_(other.author_), args_(other.args_), options_(other.options_), subcommands_(other.subcommands_), action_(other.action_), hidden_(other.hidden_), completion_(other.completion_), group_(other.group_), help_options_(other.help_options_), - epilogue_(other.epilogue_), answerers_(other.answerers_) {} + epilogue_(other.epilogue_), answerers_(other.answerers_), aliases_(other.aliases_), level_(other.level_), + annotations_(other.annotations_), synonyms_(other.synonyms_) {} App& operator=(const App& other) { if (this == &other) return *this; name_ = other.name_; @@ -159,6 +165,10 @@ public: help_options_ = other.help_options_; epilogue_ = other.epilogue_; answerers_ = other.answerers_; + aliases_ = other.aliases_; + level_ = other.level_; + annotations_ = other.annotations_; + synonyms_ = other.synonyms_; return *this; } @@ -172,6 +182,35 @@ public: hidden_ = hidden; return *this; } + /// Another name the parse takes for this command (0.3.0): the help lists it + /// beside the name (`list, ls`), the parse reports the name + /// (`subcommand_name()`), a completion offers the name only. A name or an + /// alias two subcommands of one command share is refused when the second + /// is added (`std::invalid_argument`). + [[nodiscard]] App& alias(std::string_view name) { + aliases_.emplace_back(name); + return *this; + } + /// How far into its parent's help this command is listed (0.3.0). + [[nodiscard]] App& level(Level level) { + level_ = level; + return *this; + } + /// A fact of the program's about this command (0.3.0): carried into the + /// snapshot (`Command::annotations`), not interpreted, not printed. + [[nodiscard]] App& annotate(std::string_view key, std::string_view value) { + annotations_.emplace_back(key, value); + return *this; + } + /// Words that are not commands of this one, each with what to type instead + /// (0.3.0): another tool's verb (`uninstall` -> `remove`), a retired + /// command (`agent` -> `--agent-skill-doc`). Not parsed: the word is still + /// an unknown command, and its error says what to do (`ParseError::hint`); + /// nothing runs on the strength of a guess. + [[nodiscard]] App& synonyms(std::vector> words) { + for (auto& w : words) synonyms_.push_back(std::move(w)); + return *this; + } /// Completion, built in (off unless asked for). A shell's adapter calls the /// program with `options.entry` and the words before the cursor; the /// program answers from its command tree, by the rules its parse reads it @@ -225,6 +264,7 @@ public: } [[nodiscard]] OptBuilder option(std::string_view name); [[nodiscard]] App& subcommand(App sub) { + check_names(sub.name_, sub.aliases_); subcommands_.push_back(std::move(sub)); return *this; } @@ -342,8 +382,18 @@ public: /// The same for the words of a command line, the program name first. int run(std::span args) const { return finish_run(parse_from(args)); } - void print_help(std::string_view program_name = "") const { + void print_help(std::string_view program_name = "") const { print_help(program_name, Level::common); } + + /// The help, listing the options and subcommands at `upto` and below; when + /// some are left out, the last lines say how many and how to see them. + void print_help(std::string_view program_name, Level upto) const { std::string prog = program_name.empty() ? std::string(name_) : std::string(program_name); + std::size_t more = 0, expert = 0; + const auto shown = [&](Level level) { + if (level <= upto) return true; + ++(level == Level::more ? more : expert); + return false; + }; if (!version_.empty()) std::println("{} {}", prog, version_); if (!description_.empty()) std::println("\n{}\n", description_); std::println("USAGE:"); @@ -353,6 +403,7 @@ public: if (!options_.empty()) { std::println("\nOPTIONS:"); for (const auto& opt : options_) { + if (!shown(opt.level_)) continue; std::string opt_str; if (opt.short_) opt_str += std::format("-{}, ", opt.short_); if (!opt.long_name.empty()) opt_str += "--" + opt.long_name; @@ -364,7 +415,8 @@ public: } const bool listsCompletion = completion_ && !completion_->command.empty() && (program_name.empty() || program_name == name_); - const auto commands = listed(*this, listsCompletion); + auto commands = listed(*this, listsCompletion); + std::erase_if(commands, [&](const Listed& c) { return c.sub && !shown(c.sub->level_); }); if (!commands.empty()) { const bool any_group = std::ranges::any_of(commands, [](const Listed& c) { return !c.group.empty(); }); if (!help_options_.groups_as_sections || !any_group) { @@ -376,7 +428,7 @@ public: if (!under.empty()) std::println(" {}:", under); heading = under; } - std::string padded(c.name); + std::string padded = c.label(); while (padded.size() < 12) padded += ' '; std::println(" {} {}", padded, c.description); } @@ -392,13 +444,17 @@ public: std::println("\n{}:", under); heading = under; } - std::string padded(c.name); + std::string padded = c.label(); while (padded.size() < 12) padded += ' '; std::println(" {} {}", padded, c.description); } } } if (!epilogue_.empty()) std::print("\n{}{}", epilogue_, epilogue_.ends_with('\n') ? "" : "\n"); + // What was left out, and the words that list it. Nothing when every + // option and command is listed: a tree with no levels prints as 0.2.0. + if (more) std::println("\n{} more not listed: '{} --help --all'", more, prog); + if (expert) std::println("{}{} for experts not listed: '{} --help --all --expert'", more ? "" : "\n", expert, prog); } [[nodiscard]] std::string completions(Shell shell) const; @@ -429,6 +485,17 @@ private: return std::unexpected(ParseError::make_completion()); } } + // `help ...` (HelpOptions::help_command): the command's words, + // then `--help`, then what modifies a help (`--all`, `--expert`). + std::vector rewritten; + if (help_options_.help_command && !tokens.empty() && tokens[0] == "help") { + for (const auto word : tokens.subspan(1)) + if (!word.starts_with('-')) rewritten.push_back(word); + rewritten.emplace_back("--help"); + for (const auto word : tokens.subspan(1)) + if (word.starts_with('-')) rewritten.push_back(word); + tokens = rewritten; + } global_keys_t global_keys; global_opts_t global_opts; std::vector