Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

feat(cli): ship wake-cli and a Wake skill

Corey Chiu7d9a6fe7b6b2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ab9f8ec..ad0e4b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## Unreleased
+- New: `wake-cli` — search your session history, list what you worked on in a project and read a transcript straight from the terminal, so any agent that can run a shell command gets the same answers a connected MCP client does; run `wake-cli setup` for the path and how to point an agent at it (see docs/cli.md)
+- New: a Wake skill, so agents reach for your session history on their own — `npx skills add iAmCorey/Wake` teaches Claude Code, Codex and anything else that reads skills when to look back at earlier conversations, decisions and errors instead of guessing from git
+
## [0.5.2] — 2026-09-10
- New: Wake speaks your language — Simplified Chinese included, and the UI follows your system language on first launch; pick a fixed language under Settings → General
diff --git a/README.md b/README.md
index 4b2088f..4bf314a 100644
--- a/README.md
+++ b/README.md
@@ -23,6 +23,7 @@ Your agent history is scattered across `~/.claude`, `~/.codex`, and a dozen othe
- **Insights** — a stats page for your whole library: GitHub-style activity heatmap with streaks, hour / weekday / month breakdowns, and Agents / Projects / Models leaderboards switchable between sessions, tokens, and prompts
- **Remote hosts** — mirror the sessions on your other machines over SSH (Settings → Remote hosts); they show up next to local ones with an `@host` badge, searchable like everything else, and resume through a copied `ssh -t` command
- **Connect your agents (MCP)** — a bundled read-only MCP server, `wake-mcp`, lets Claude Code, Codex, Cursor or any MCP client search your whole history, list recent sessions per project and read transcripts page by page, so a new agent can pick up where another one left off; Settings → Connect has copy-paste setup snippets
+- **Command line** — `wake-cli` gives the same four answers to anything that can run a shell command: `wake-cli sessions --project "$PWD"`, `wake-cli search "…"`, `wake-cli show <key>`; its output is byte-identical to what an MCP client sees; `npx skills add iAmCorey/Wake` installs a skill so agents reach for it on their own
![Full-text search across every agent's sessions](imgs/screenshot-2.webp)
@@ -94,12 +95,27 @@ command = "/Applications/Wake.app/Contents/MacOS/wake-mcp"
A few things worth knowing:
- Everything is read-only: the server opens Wake's index without write access and never scans or modifies anything; there are no delete or star tools
-- Search and lists come from Wake's index, so keep Wake running for fresh results — every reply says how recent the index is. Reading a transcript parses the agent's files live, so it is always current
+- Search and lists come from Wake's index, so keep Wake running for fresh results — every reply says how recent the index is. Reading a transcript parses the agent's files rather than the index, so it does not depend on the last scan (remote-host sessions are read from their local mirror)
- Agents see the same session files Wake indexes, on this machine only (remote-host mirrors included); nothing leaves the machine
- `wake-mcp call wake_search '{"query":"useEffect("}'` runs a single tool from the terminal, handy for checking what an agent would see
The full reference — every parameter, output formats, key and reference formats, error semantics, troubleshooting — is in [docs/mcp.md](docs/mcp.md).
+### From a shell
+
+Not every agent speaks MCP, and sometimes you just want the answer in a terminal. `wake-cli` sits next to `wake-mcp` and covers the same ground:
+
+```bash
+wake-cli sessions --project "$PWD" --limit 5 # what happened in this repo
+wake-cli search "rate limiter" --project "$PWD" # where was this discussed
+wake-cli show 'claude-code:1b2c3d4e-…' # read that transcript
+wake-cli setup # path, PATH setup, and a block to paste into CLAUDE.md
+```
+
+It prints exactly what the MCP tools return — the two are asserted byte for byte — so an agent driving it through a shell sees what a connected one does. Full reference in [docs/cli.md](docs/cli.md).
+
+To make an agent reach for it without being told, install the bundled skill with `npx skills add iAmCorey/Wake` (or copy `skills/wake/` into `~/.claude/skills/wake/`).
+
## Language
Wake's interface follows your system language on first launch and falls back to
@@ -173,6 +189,7 @@ cargo run -p wake-core --bin scan # data-layer smoke test: scan and print s
cargo run -p wake-core --bin scan -- --search "useEffect(" # search smoke test
cargo run -p wake-core --bin wake-mcp -- setup # print MCP setup snippets for the dev build
cargo run -p wake-core --bin wake-mcp -- call wake_search '{"query":"useEffect("}' # run one MCP tool against your index
+cargo run -p wake-core --bin wake-cli -- sessions --project "$PWD" # the CLI against your index
WAKE_THEME=dark cargo run -p wake # force dark/light (defaults to system)
WAKE_HOME=/path cargo run -p wake # point all agent adapters at a different home dir (portable installs, testing)
WAKE_LIVE_REMOTE_HOST=<host> cargo test -p wake-core --test remote_sync live -- --ignored # run the remote-host pipeline against a real SSH host
@@ -196,6 +213,7 @@ crates/
│ ├── watcher.rs # notify-based file watching → per-file incremental updates
│ ├── db.rs # rusqlite (WAL): sessions / messages / messages_fts / user_data / tombstones (+ location, remote_hosts & schema meta tables)
│ ├── mcp/ # wake-mcp: read-only MCP server over stdio (hand-written JSON-RPC, four tools)
+│ ├── cli.rs # wake-cli: argv → the same four tools, output byte-identical to MCP
│ └── services/ # terminal resume (per-platform: AppleScript / argv / Win32) / export / trash / agent context helpers
└── wake # GPUI app (three-pane workbench + ⌘K / Ctrl+K palette)
```
diff --git a/crates/wake-core/Cargo.toml b/crates/wake-core/Cargo.toml
index 244e679..881e103 100644
--- a/crates/wake-core/Cargo.toml
+++ b/crates/wake-core/Cargo.toml
@@ -50,3 +50,8 @@ path = "src/bin/scan.rs"
[[bin]]
name = "wake-mcp"
path = "src/bin/wake_mcp.rs"
+
+# 会话查询 CLI(只读),随 Wake 一起打包、与主程序并排;解析层见 src/cli.rs
+[[bin]]
+name = "wake-cli"
+path = "src/bin/wake_cli.rs"
diff --git a/crates/wake-core/src/bin/wake_cli.rs b/crates/wake-core/src/bin/wake_cli.rs
new file mode 100644
index 0000000..5a377fd
--- /dev/null
+++ b/crates/wake-core/src/bin/wake_cli.rs
@@ -0,0 +1,114 @@
+//! wake-cli:从终端查 Wake 的会话索引(只读)。
+//!
+//! wake-cli search QUERY [OPTIONS] 全文搜索
+//! wake-cli sessions [OPTIONS] 最近的会话
+//! wake-cli show KEY [OPTIONS] 读一份转录
+//! wake-cli projects [OPTIONS] 有会话历史的项目
+//! wake-cli setup 路径、进 PATH、给 agent 的说明
+//! wake-cli --version | --help
+//!
+//! 输出就是 MCP 工具那份文本、一字不改(tests/cli.rs 逐字节卡),所以 docs 与
+//! 将来的 Skill 只需描述一份格式。解析在 `wake_core::cli`,这里只做 I/O 与退
+//! 出码。索引库只读打开,绝不 open_or_rebuild、不扫描、不写。
+//!
+//! **结果不许走 println!**:Rust 忽略 SIGPIPE,`wake-cli show K | head` 会让
+//! println! panic 成 101。所有输出统一经 cli::emit,BrokenPipe 由 write 收场。
+use std::io::{self, Write as _};
+use std::path::PathBuf;
+use std::process::ExitCode;
+
+use wake_core::cli::{self, Action, CliError, Report, Stream};
+use wake_core::db::{self, Store};
+use wake_core::mcp::{self, tools};
+
+fn main() -> ExitCode {
+ // args()(而非 args_os)对非 UTF-8 参数是 panic,退出码 101 —— Linux 上
+ // 目录名可以不是 UTF-8,而 `--project "$PWD"` 正是主用法,不能崩
+ let argv: Vec<String> = match std::env::args_os().skip(1).map(|a| a.into_string()).collect() {
+ Ok(v) => v,
+ Err(bad) => {
+ return write(
+ CliError {
+ message: format!("argument is not valid UTF-8: {}", bad.to_string_lossy()),
+ with_usage: false,
+ }
+ .report(),
+ )
+ }
+ };
+ let inv = match cli::parse(&argv) {
+ Ok(i) => i,
+ Err(e) => return write(e.report()),
+ };
+ match inv.action {
+ Action::Help => write(ok(cli::help())),
+ Action::Version => write(ok(format!("wake-cli {}", mcp::SERVER_VERSION))),
+ Action::Setup => write(ok(setup(&inv.db))),
+ Action::Tool { tool, args } => run(&inv.db, tool, &args),
+ }
+}
+
+fn ok(text: String) -> Report {
+ Report {
+ stream: Stream::Stdout,
+ text,
+ code: 0,
+ }
+}
+
+/// db 路径只在真要用库时求值:`path_or_default` 落到 default_db_path 时有副
+/// 作用(首次会把旧 vibex 库拷过来),--help / --version 不该碰用户的文件系统
+fn db_path(db: &Option<PathBuf>) -> PathBuf {
+ db::path_or_default(db.as_deref())
+}
+
+fn run(db: &Option<PathBuf>, tool: &str, args: &serde_json::Value) -> ExitCode {
+ // 只读打开 + 按库配置建 roster,与 wake-mcp 同一条(不变量 8⑥);库不存在
+ // 或太老由 open_read_only 给出 "launch Wake once"
+ let (store, adapters) = match mcp::open_index(&db_path(db)) {
+ Ok(x) => x,
+ Err(e) => {
+ return write(Report {
+ stream: Stream::Stderr,
+ text: format!("wake-cli: {e}"),
+ code: 2,
+ })
+ }
+ };
+ let cache = tools::TranscriptCache::default();
+ write(cli::report(tools::invoke(
+ &store, &adapters, &cache, tool, args,
+ )))
+}
+
+fn setup(db: &Option<PathBuf>) -> String {
+ let cli_bin = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("wake-cli"));
+ // sibling_binary 取的就是 current_exe 同级目录,从 wake-cli 调恰好对
+ let mcp_bin = mcp::sibling_binary().filter(|p| p.exists());
+ let path = db_path(db);
+ // 只探库,不必为一行提示把十六家 roster 建起来
+ let db_error = Store::open_read_only(&path).err().map(|e| format!("{e:#}"));
+ cli::setup_text(&cli::SetupFacts {
+ cli_bin: &cli_bin,
+ mcp_bin: mcp_bin.as_deref(),
+ db: &path,
+ db_error,
+ })
+}
+
+/// 唯一的输出出口。下游关掉管道(`wake-cli search x | head`)是正常收场,保持
+/// 原本的退出码;stderr 也可能被关,同理别 panic
+fn write(r: Report) -> ExitCode {
+ let res = match r.stream {
+ Stream::Stdout => cli::emit(&r.text, &mut io::stdout().lock()),
+ Stream::Stderr => cli::emit(&r.text, &mut io::stderr().lock()),
+ };
+ match res {
+ Ok(()) => ExitCode::from(r.code),
+ Err(e) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::from(r.code),
+ Err(e) => {
+ let _ = writeln!(io::stderr(), "wake-cli: {e}");
+ ExitCode::from(1)
+ }
+ }
+}
diff --git a/crates/wake-core/src/bin/wake_mcp.rs b/crates/wake-core/src/bin/wake_mcp.rs
index 7147c34..dba224a 100644
--- a/crates/wake-core/src/bin/wake_mcp.rs
+++ b/crates/wake-core/src/bin/wake_mcp.rs
@@ -10,9 +10,7 @@
use std::io::{self, Write as _};
use std::path::PathBuf;
use std::process::ExitCode;
-use std::sync::Arc;
-use wake_core::adapters::create_adapters_for;
use wake_core::db::Store;
use wake_core::mcp::{self, McpServer};
@@ -60,15 +58,11 @@ fn parse_args() -> Result<Args, String> {
}
fn db_path(db: &Option<PathBuf>) -> PathBuf {
- db.clone().unwrap_or_else(wake_core::db::default_db_path)
+ wake_core::db::path_or_default(db.as_deref())
}
fn open(db: &Option<PathBuf>) -> Result<McpServer, String> {
- let store = Store::open_read_only(&db_path(db)).map_err(|e| format!("{e:#}"))?;
- let store = Arc::new(store);
- // 必须带上库里的 location / remote host 配置(不变量 8⑥),否则自定义根
- // 与远程缓存里的会话找不到能读它的 adapter
- let adapters = create_adapters_for(&store);
+ let (store, adapters) = mcp::open_index(&db_path(db))?;
Ok(McpServer::new(store, adapters))
}
diff --git a/crates/wake-core/src/cli.rs b/crates/wake-core/src/cli.rs
new file mode 100644
index 0000000..57a2812
--- /dev/null
+++ b/crates/wake-core/src/cli.rs
@@ -0,0 +1,1086 @@
+//! wake-cli 的解析层:argv → 一次 MCP 工具调用。bin 只做 I/O 与退出码,有
+//! 判断的东西全在这里、可单测。文案恒英文(wake-core 不参与 i18n,别包 t())。
+//!
+//! **值一律原样当字符串塞进 JSON**:数字不解析、范围不裁剪、agent 名不认、
+//! since 文法不懂——`mcp::tools` 的 int_arg 认字符串、agents_arg 认逗号串,
+//! 校验与裁剪只此一家。同一个坏参数在 CLI 与 MCP 两条路上才会给出同一句话,
+//! 两条路的输出也才可能逐字节相同(tests/cli.rs 卡着)。
+//!
+//! COMMANDS 表与 `tools::definitions()` 必须双射,单测卡死:工具新增参数、
+//! 改名、改类型、加第五个工具,这个文件都会红。
+
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+use serde_json::{Map, Value};
+
+use crate::mcp::tools;
+use crate::models::AgentId;
+use crate::services::terminal::sh_quote;
+
+// ---------------------------------------------------------------- 命令表
+
+/// 取值检查函数:出错时返回给用户看的整句
+pub type Validator = fn(&str) -> Result<(), String>;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Arity {
+ /// 取一个值,重复出现后来者覆盖
+ Value,
+ /// 可重复;最后以逗号串一次性写入(agents_arg 自己切分/trim/去重/校验)
+ Repeated,
+ /// 出现即 JSON true;**不出现就不写这个键**,让工具的默认值生效
+ Switch,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct FlagSpec {
+ /// 含前导 `--`
+ pub long: &'static str,
+ /// MCP 工具的参数名,必须与 inputSchema 的 property 同名(单测卡)
+ pub key: &'static str,
+ pub arity: Arity,
+ /// 帮助里的值占位符;Switch 用 ""
+ pub placeholder: &'static str,
+ /// 帮助里的说明。**不写默认值/取值区间的数字**——那些由 definitions() 现渲染
+ pub help: &'static str,
+ /// 取值检查。**CLI 仅有的值语义只能长在这里**:别在 parse 里按 key 名写
+ /// `if`,那样这张表就不再是 CLI 表面的完整描述,加第二条时没有东西会红
+ pub validate: Option<Validator>,
+}
+
+impl FlagSpec {
+ const fn new(
+ long: &'static str,
+ key: &'static str,
+ arity: Arity,
+ placeholder: &'static str,
+ help: &'static str,
+ ) -> Self {
+ Self { long, key, arity, placeholder, help, validate: None }
+ }
+
+ const fn validated(mut self, v: Validator) -> Self {
+ self.validate = Some(v);
+ self
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct CommandSpec {
+ pub name: &'static str,
+ /// 恒取 tools 的常量、不写字面量——常量改名即编译错
+ pub tool: &'static str,
+ /// 位置参数的 (JSON 键, 占位符);None = 不收位置参数
+ pub positional: Option<(&'static str, &'static str)>,
+ pub flags: &'static [FlagSpec],
+ pub summary: &'static str,
+}
+
+/// 不是工具调用,单独一条路
+const SETUP: &str = "setup";
+
+const F_PROJECT: FlagSpec = FlagSpec::new(
+ "--project", "project", Arity::Value, "PATH",
+ "one project: an absolute path (use \"$PWD\") or a project name",
+).validated(check_project);
+const F_AGENT: FlagSpec = FlagSpec::new(
+ "--agent", "agents", Arity::Repeated, "ID",
+ "only this agent; repeat the flag or comma-separate",
+);
+const F_SINCE: FlagSpec = FlagSpec::new(
+ "--since", "since", Arity::Value, "WHEN",
+ "only what was updated at or after WHEN",
+);
+const F_LIMIT: FlagSpec = FlagSpec::new(
+ "--limit", "limit", Arity::Value, "N",
+ "maximum rows to return",
+);
+const F_STARRED: FlagSpec = FlagSpec::new(
+ "--starred", "starred", Arity::Switch, "",
+ "only sessions starred in Wake",
+);
+const F_FROM: FlagSpec = FlagSpec::new(
+ "--from", "from_seq", Arity::Value, "SEQ",
+ "start at this message seq (a wake://…#N reference sets it too)",
+);
+const F_MESSAGES: FlagSpec = FlagSpec::new(
+ "--messages", "max_messages", Arity::Value, "N",
+ "messages per page",
+);
+const F_CHARS: FlagSpec = FlagSpec::new(
+ "--chars", "max_chars", Arity::Value, "N",
+ "character budget for the page",
+);
+const F_MESSAGE_CHARS: FlagSpec = FlagSpec::new(
+ "--message-chars", "max_message_chars", Arity::Value, "N",
+ "truncate each message to this many characters",
+);
+const F_TOOLS: FlagSpec = FlagSpec::new(
+ "--tools", "include_tools", Arity::Switch, "",
+ "include tool inputs and outputs",
+);
+const F_THINKING: FlagSpec = FlagSpec::new(
+ "--thinking", "include_thinking", Arity::Switch, "",
+ "include the assistant's thinking where the agent recorded it",
+);
+
+const SEARCH_FLAGS: &[FlagSpec] = &[F_PROJECT, F_AGENT, F_SINCE, F_LIMIT];
+const SESSIONS_FLAGS: &[FlagSpec] = &[F_PROJECT, F_AGENT, F_SINCE, F_LIMIT, F_STARRED];
+const SHOW_FLAGS: &[FlagSpec] = &[
+ F_FROM,
+ F_MESSAGES,
+ F_CHARS,
+ F_MESSAGE_CHARS,
+ F_TOOLS,
+ F_THINKING,
+];
+const PROJECTS_FLAGS: &[FlagSpec] = &[F_SINCE, F_LIMIT];
+
+/// 子命令与 MCP 工具一一对应。加一家工具就在这里加一行,否则单测红
+pub const COMMANDS: &[CommandSpec] = &[
+ CommandSpec {
+ name: "search",
+ tool: tools::SEARCH,
+ positional: Some(("query", "QUERY")),
+ flags: SEARCH_FLAGS,
+ summary: "search transcripts across every indexed session",
+ },
+ CommandSpec {
+ name: "sessions",
+ tool: tools::LIST_SESSIONS,
+ positional: None,
+ flags: SESSIONS_FLAGS,
+ summary: "list the most recently updated sessions",
+ },
+ CommandSpec {
+ name: "show",
+ tool: tools::GET_SESSION,
+ positional: Some(("key", "KEY")),
+ flags: SHOW_FLAGS,
+ summary: "print one transcript as compact Markdown",
+ },
+ CommandSpec {
+ name: "projects",
+ tool: tools::LIST_PROJECTS,
+ positional: None,
+ flags: PROJECTS_FLAGS,
+ summary: "list projects that have session history",
+ },
+];
+
+// ---------------------------------------------------------------- 类型
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Action {
+ Help,
+ Version,
+ Setup,
+ /// 一次工具调用。`args` **恒为 JSON object**——mcp/mod.rs 那道
+ /// `arguments` 形状检查在这条路上不可达,别再补一遍
+ Tool { tool: &'static str, args: Value },
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Invocation {
+ /// `--db`;None = `db::default_db_path()`(由 bin 惰性求值)
+ pub db: Option<PathBuf>,
+ pub action: Action,
+}
+
+/// 已经是给人看的整句(小写开头、不带 `wake-cli: ` 前缀)
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CliError {
+ pub message: String,
+ /// 命令级的错(没给命令 / 命令不认识 / 选项不认识 / 位置参数缺或多)附短
+ /// USAGE;"这个选项缺值"一类本身已完整,不附——wake_mcp.rs 的这处不对称
+ /// 是有意的,别顺手抹平
+ pub with_usage: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Stream {
+ Stdout,
+ Stderr,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Report {
+ pub stream: Stream,
+ pub text: String,
+ pub code: u8,
+}
+
+impl CliError {
+ pub fn report(&self) -> Report {
+ let mut text = format!("wake-cli: {}", self.message);
+ if self.with_usage {
+ text.push_str("\n\n");
+ text.push_str(USAGE);
+ }
+ Report {
+ stream: Stream::Stderr,
+ text,
+ code: 2,
+ }
+ }
+}
+
+/// 工具结果 → 写哪条流、什么退出码。三个变体全列、不写 `_`:ToolError 加变体
+/// 时这里编译不过,正是要的
+pub fn report(result: Result<String, tools::ToolError>) -> Report {
+ match result {
+ Ok(text) => Report {
+ stream: Stream::Stdout,
+ text,
+ code: 0,
+ },
+ // 值不对就是命令行敲错了(--since/--limit/--agent 的值全交给 tools.rs
+ // 校验),与 "unknown option" 同一类,退 2。`wake-mcp call` 把它压成 1
+ // 是因为那条路过 JSON-RPC 信封、分类由 payload 携带,退出码不是通道
+ Err(tools::ToolError::InvalidParams(m)) => Report {
+ stream: Stream::Stderr,
+ text: format!("wake-cli: {m}"),
+ code: 2,
+ },
+ // Failed = 这份会话读不出来;Internal = 库在但查询炸了(索引损坏 /
+ // schema 漂移)。对用户是同一件事:跑起来了,然后失败
+ Err(tools::ToolError::Failed(m) | tools::ToolError::Internal(m)) => Report {
+ stream: Stream::Stderr,
+ text: format!("wake-cli: {m}"),
+ code: 1,
+ },
+ }
+}
+
+/// 文本写出去:末尾没换行就补一个(search/sessions/projects 收在 index_note
+/// 上、无换行,get_session 自带),除此之外一个字节不加不减。**必须 flush**:
+/// BrokenPipe 常常只在 flush 时才浮出来,而 Stdout 的析构会把错误吞掉
+pub fn emit(text: &str, out: &mut impl Write) -> std::io::Result<()> {
+ out.write_all(text.as_bytes())?;
+ if !text.ends_with('\n') {
+ out.write_all(b"\n")?;
+ }
+ out.flush()
+}
+
+// ---------------------------------------------------------------- 解析
+
+fn err(message: String, with_usage: bool) -> CliError {
+ CliError {
+ message,
+ with_usage,
+ }
+}
+
+/// 缺值的错**不附 USAGE**(与 wake_mcp.rs 的 `--db needs a path` 同款)
+fn next_value(it: &mut std::slice::Iter<'_, String>, msg: &str) -> Result<String, CliError> {
+ it.next().cloned().ok_or_else(|| err(msg.to_string(), false))
+}
+
+/// 这个 long 归哪些命令(给 "只对 sessions 有效" / "要放在命令之后" 用)
+fn flag_owners(long: &str) -> Vec<&'static str> {
+ COMMANDS
+ .iter()
+ .filter(|c| c.flags.iter().any(|f| f.long == long))
+ .map(|c| c.name)
+ .collect()
+}
+
+/// 旗标放错地方或根本不认识——三句话一个出口,免得两处各写一遍 "unknown
+/// option" 然后各自漂
+fn misplaced(name: &str, in_command: bool) -> CliError {
+ let owners = flag_owners(name);
+ let msg = match (owners.is_empty(), in_command) {
+ (true, _) => format!("unknown option {name}"),
+ (false, false) => format!("{name} must come after the command"),
+ (false, true) => format!("{name} is only valid for `{}`", owners.join("` and `")),
+ };
+ err(msg, true)
+}
+
+/// CLI 仅有的取值检查(挂在 F_PROJECT 上,不是按 key 名的 if):`--project .`
+/// 在 tools 那边不算路径(见 context.rs 的 looks_like_path),会静默降级成项目
+/// 名匹配、报 "No indexed project matches `.`"。相对路径这边也解不对(符号链
+/// 接下 getcwd 与 $PWD 不是一回事),干脆直说,别猜
+fn check_project(v: &str) -> Result<(), String> {
+ let head = v.trim().split(std::path::is_separator).next().unwrap_or("");
+ if head == "." || head == ".." {
+ return Err("--project needs an absolute path or a project name; \
+ pass --project \"$PWD\" for the current directory"
+ .into());
+ }
+ Ok(())
+}
+
+/// 解析途中已经认出的东西。三态一个枚举——`Option<&CommandSpec>` 加一个
+/// `setup: bool` 能拼出第四种不该存在的状态,于是每个分支都要自证不可达
+#[derive(Clone, Copy)]
+enum Seen {
+ Nothing,
+ Setup,
+ Command(&'static CommandSpec),
+}
+
+/// argv(**不含** argv[0])→ 一次调用。纯函数:不读环境、不碰文件系统、不
+/// exit。wake_mcp.rs 在 parse_args 里直接 process::exit(0) 处理 --help /
+/// --version,那样这两条路没法单测,这里改成返回 Action
+pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
+ let mut db: Option<PathBuf> = None;
+ let mut seen = Seen::Nothing;
+ let mut map = Map::new();
+ let mut positional: Option<String> = None;
+ let mut only_positional = false; // `--` 之后
+ let mut it = argv.iter();
+ while let Some(a) = it.next() {
+ let s = a.as_str();
+ if !only_positional {
+ // 1) 全局:位置无关,与 wake_mcp.rs 同形。--db 后面那个词恒被吃掉
+ // (`--db --help` 把 --help 当路径),行为与 wake-mcp 一致
+ if s == "--db" {
+ db = Some(PathBuf::from(next_value(&mut it, "--db needs a path")?));
+ continue;
+ }
+ if let Some(v) = s.strip_prefix("--db=") {
+ db = Some(PathBuf::from(v));
+ continue;
+ }
+ if s == "--help" || s == "-h" {
+ return Ok(Invocation { db, action: Action::Help });
+ }
+ if s == "--version" || s == "-V" {
+ return Ok(Invocation { db, action: Action::Version });
+ }
+ if s == "--" {
+ only_positional = true;
+ continue;
+ }
+ if s.starts_with('-') && s != "-" {
+ let (name, inline) = match s.split_once('=') {
+ Some((f, v)) if f.starts_with("--") => (f, Some(v.to_string())),
+ _ => (s, None),
+ };
+ // 2) 子命令 flag。命令还没出现 ⇒ 位置写反了,直说
+ let cmd = match seen {
+ Seen::Command(c) => c,
+ Seen::Setup => {
+ return Err(err(format!("setup takes no options (got {name})"), true))
+ }
+ Seen::Nothing => return Err(misplaced(name, false)),
+ };
+ let Some(f) = cmd.flags.iter().find(|f| f.long == name) else {
+ return Err(misplaced(name, true));
+ };
+ let v = match (f.arity, inline) {
+ (Arity::Switch, Some(_)) => {
+ return Err(err(format!("{name} takes no value"), true))
+ }
+ (Arity::Switch, None) => {
+ map.insert(f.key.to_string(), Value::Bool(true));
+ continue;
+ }
+ (_, Some(v)) => v,
+ (_, None) => next_value(&mut it, &format!("{name} needs a value"))?,
+ };
+ if let Some(check) = f.validate {
+ check(&v).map_err(|m| err(m, false))?;
+ }
+ if f.arity == Arity::Repeated {
+ // 就地拼成逗号串:agents_arg 自己切分/trim/去重/校验,
+ // `--agent a --agent b` 与 `--agent a,b` 于是同义
+ if let Some(Value::String(prev)) = map.get_mut(f.key) {
+ prev.push(',');
+ prev.push_str(&v);
+ continue;
+ }
+ }
+ // 原样当字符串传,校验与裁剪交给 mcp::tools
+ map.insert(f.key.to_string(), Value::String(v));
+ continue;
+ }
+ }
+ // 3) 位置参数:第一个是命令名
+ match seen {
+ Seen::Nothing if s == SETUP => seen = Seen::Setup,
+ Seen::Nothing => {
+ seen = Seen::Command(
+ COMMANDS
+ .iter()
+ .find(|c| c.name == s)
+ .ok_or_else(|| err(format!("unknown command {s}"), true))?,
+ )
+ }
+ Seen::Setup => {
+ return Err(err(format!("setup takes no arguments (got `{s}`)"), true))
+ }
+ Seen::Command(cmd) => {
+ let Some((_, ph)) = cmd.positional else {
+ return Err(err(
+ format!("{} takes no arguments (got `{s}`)", cmd.name),
+ true,
+ ));
+ };
+ if positional.is_some() {
+ return Err(err(
+ format!(
+ "{} takes one {ph} — quote it: wake-cli {} \"…\"",
+ cmd.name, cmd.name
+ ),
+ true,
+ ));
+ }
+ positional = Some(a.clone());
+ }
+ }
+ }
+ let cmd = match seen {
+ Seen::Setup => return Ok(Invocation { db, action: Action::Setup }),
+ Seen::Nothing => return Err(err("needs a command".into(), true)),
+ Seen::Command(c) => c,
+ };
+ if let Some((key, ph)) = cmd.positional {
+ match positional {
+ Some(v) => {
+ map.insert(key.to_string(), Value::String(v));
+ }
+ None => return Err(err(format!("{} needs a {ph}", cmd.name), true)),
+ }
+ }
+ Ok(Invocation {
+ db,
+ action: Action::Tool { tool: cmd.tool, args: Value::Object(map) },
+ })
+}
+
+// ---------------------------------------------------------------- 帮助
+
+/// 短用法:命令级错误后附在 stderr。全文另有 `help()`——把 50 行参考手册贴在
+/// "`--limit` needs a value" 后面是骚扰,所以拆成两份(单测卡这份的行数)
+const USAGE: &str = "wake-cli — query your Wake session index from the terminal
+
+USAGE:
+ wake-cli search QUERY [OPTIONS]
+ wake-cli sessions [OPTIONS]
+ wake-cli show KEY [OPTIONS]
+ wake-cli projects [OPTIONS]
+ wake-cli setup
+ wake-cli --help | --version
+
+Run `wake-cli --help` for every option.";
+
+const HELP_HEAD: &str = "wake-cli — query your Wake session index from the terminal
+
+Wake indexes every coding-agent session on this machine (Claude Code, Codex,
+Cursor, Gemini CLI and more). This reads that index; it never writes to it.
+
+USAGE:
+ wake-cli <command> [ARGS] [OPTIONS]
+
+COMMANDS:";
+
+const HELP_GLOBALS: &str = "
+GLOBAL OPTIONS:
+ --db PATH index database (default: Wake's own, e.g. ~/Library/Application Support/wake/wake.db)
+ --help, -h print this help
+ --version, -V print the version
+ -- treat everything after it as arguments, not options
+";
+
+const HELP_WHEN: &str = "
+WHEN:
+ Relative: 30m, 24h, 7d, 2w. Absolute: 2026-09-01, \"2026-09-01 09:30\",
+ 2026-09-01T09:30:00Z. Date-times without a zone are read in local time.
+ Values outside a flag's range are clamped, not rejected.
+";
+
+const HELP_TAIL: &str = "
+KEYS AND REFERENCES:
+ A session key is <agent>:<id>, or <agent>:<host>:<id> for a session mirrored
+ from a remote host. `sessions` and `search` print the key of every session
+ they list; `search` also prints a reference under each snippet:
+
+ ref: wake://session/claude-code:1b2c…#42
+
+ Pass a reference to `show` and the page starts at that message.
+
+EXAMPLES:
+ wake-cli sessions --project \"$PWD\" --limit 5
+ wake-cli search \"useEffect(\" --project \"$PWD\" --since 7d
+ wake-cli search \"rate limiter\" --agent codex --agent claude-code
+ wake-cli show 'wake://session/claude-code:1b2c…#42' --tools
+ wake-cli search -- --dry-run # a query that starts with a dash
+
+EXIT CODES:
+ 0 it ran — including \"no matches\" and \"no such project\"
+ 1 a session could not be read (unknown key, or a transcript that would not parse)
+ 2 the command line was wrong, or the index is missing / unreadable / too old
+
+Everything is read-only. Full reference: docs/cli.md";
+
+/// 命令块与选项块的说明列起始列
+const CMD_COL: usize = 36;
+const OPT_COL: usize = 22;
+
+/// 左列补空格到 width,左列过长时至少留两格
+fn row(left: String, right: &str, width: usize) -> String {
+ let pad = width.saturating_sub(left.chars().count()).max(2);
+ format!("{left}{}{right}\n", " ".repeat(pad))
+}
+
+/// 某个工具参数的默认值与取值区间,现从 `tools::definitions()` 的 schema 取。
+/// 帮助文本里最容易烂掉的就是这些数字,渲染出来它们至少不会与 schema 各说各
+/// 话(schema 与 int_arg 调用点仍是两份,那是 tools.rs 自己的事)
+fn limits_of(defs: &[Value], tool: &str, key: &str) -> String {
+ let Some(p) = defs
+ .iter()
+ .find(|d| d["name"] == tool)
+ .and_then(|d| d["inputSchema"]["properties"].get(key))
+ else {
+ return String::new();
+ };
+ let mut bits = Vec::new();
+ if let Some(v) = p.get("default").filter(|v| v.is_number()) {
+ bits.push(format!("default {v}"));
+ }
+ // 上下界成对才写:from_seq 只有 minimum 0,"at least 0" 是废话
+ if let (Some(lo), Some(hi)) = (p.get("minimum"), p.get("maximum")) {
+ bits.push(format!("{lo}–{hi}"));
+ }
+ if bits.is_empty() {
+ String::new()
+ } else {
+ format!(" ({})", bits.join(", "))
+ }
+}
+
+/// 逗号分隔、缩进两格、贪心折到 76 列
+fn wrapped(items: &[&str], width: usize) -> String {
+ let mut out = String::new();
+ let mut line = String::from(" ");
+ for (i, it) in items.iter().enumerate() {
+ let piece = if i + 1 == items.len() {
+ it.to_string()
+ } else {
+ format!("{it},")
+ };
+ let len = line.chars().count();
+ if len > 2 {
+ if len + 1 + piece.chars().count() > width {
+ out.push_str(&line);
+ out.push('\n');
+ line = String::from(" ");
+ } else {
+ line.push(' ');
+ }
+ }
+ line.push_str(&piece);
+ }
+ out.push_str(&line);
+ out
+}
+
+/// `--help` 的全文。命令块、各命令的选项块、默认值上限与 agent 名全部由
+/// COMMANDS 表与 `tools::definitions()` / `AgentId::ALL` 渲染,静态散文只剩
+/// 不含事实的那几段
+pub fn help() -> String {
+ let defs = tools::definitions();
+ let mut out = String::from(HELP_HEAD);
+ out.push('\n');
+ for c in COMMANDS {
+ let arg = c.positional.map(|(_, ph)| format!(" {ph}")).unwrap_or_default();
+ out.push_str(&row(format!(" wake-cli {}{arg}", c.name), c.summary, CMD_COL));
+ }
+ out.push_str(&row(
+ format!(" wake-cli {SETUP}"),
+ "print this binary's path and how to point an agent at it",
+ CMD_COL,
+ ));
+ out.push_str(HELP_GLOBALS);
+ for c in COMMANDS {
+ out.push_str(&format!("\n{} OPTIONS:\n", c.name));
+ for f in c.flags {
+ let left = if f.placeholder.is_empty() {
+ format!(" {}", f.long)
+ } else {
+ format!(" {} {}", f.long, f.placeholder)
+ };
+ let help = format!("{}{}", f.help, limits_of(&defs, c.tool, f.key));
+ out.push_str(&row(left, &help, OPT_COL));
+ }
+ }
+ out.push_str(HELP_WHEN);
+ let ids: Vec<&str> = AgentId::ALL.iter().map(|a| a.as_str()).collect();
+ out.push_str(&format!(
+ "\nAGENT IDS:\n{}\n Display names (\"Claude Code\") and a few aliases work too.\n",
+ wrapped(&ids, 76)
+ ));
+ out.push_str(HELP_TAIL);
+ out
+}
+
+// ---------------------------------------------------------------- setup
+
+/// 贴进 CLAUDE.md / AGENTS.md 的那段——给不想装 skill、只想在一个项目里用的
+/// 人。与 skills/wake/SKILL.md 说的是同一件事,那份更全(找二进制、翻页、
+/// 退出码);这里只留最短的一版
+const AGENT_MEMO: &str = "Earlier sessions with every coding agent on this machine are searchable with
+wake-cli. Reach for it when the user asks about an earlier conversation, a past
+decision, why something was done a certain way, where previous work stopped, or
+whether an error has been seen before — git history does not hold that.
+
+ wake-cli sessions --project \"$PWD\" --limit 10
+ wake-cli search \"<terms>\" --project \"$PWD\"
+ wake-cli show <key>
+
+`sessions` and `search` print a key for every session; `search` also prints a
+`wake://session/<key>#<seq>` reference that `show` accepts. Always pass
+--project \"$PWD\" — without it every project on the machine is in scope.
+Everything is read-only.";
+
+/// 一行装好 skill。`owner/repo` 形式由 vercel-labs 的 skills CLI 认,仓库里
+/// 有 `skills/` 目录即可被发现
+const SKILL_INSTALL: &str = "npx skills add iAmCorey/Wake";
+
+/// `wake-cli setup` 要说的事实(由 bin 查好传进来,函数本身仍是纯的)
+pub struct SetupFacts<'a> {
+ pub cli_bin: &'a Path,
+ /// 同目录的 wake-mcp(存在才给)
+ pub mcp_bin: Option<&'a Path>,
+ pub db: &'a Path,
+ /// 库打不开的原因(`{e:#}`);能打开是 None
+ pub db_error: Option<String>,
+}
+
+/// 已经在 `…/bin` 里的(deb / tar 装法)不必再叫人 symlink,那是噪音;
+/// current_exe 失败时只剩个裸文件名,parent 为空,更不该打印自指的 ln
+fn path_hint(bin: &Path) -> Option<String> {
+ let dir = bin.parent().filter(|d| !d.as_os_str().is_empty())?;
+ if dir.file_name().is_some_and(|n| n == "bin") {
+ return None;
+ }
+ if cfg!(target_os = "windows") {
+ return Some(format!("Add this folder to PATH:\n\n{}", dir.display()));
+ }
+ let quoted = sh_quote(&bin.to_string_lossy());
+ Some(if cfg!(target_os = "macos") {
+ // 出厂 macOS 的 /usr/local/bin 是 root:wheel,而且可能压根不存在——
+ // 不带 sudo 的 ln 在干净机器上必然 Permission denied
+ format!("sudo mkdir -p /usr/local/bin && sudo ln -sf {quoted} /usr/local/bin/wake-cli")
+ } else {
+ format!("mkdir -p ~/.local/bin && ln -sf {quoted} ~/.local/bin/wake-cli")
+ })
+}
+
+/// `## {标题} — {怎么用这段}` 与 `wake-mcp setup` 同形,两个 bin 的输出读起来
+/// 才是一家人
+pub fn setup_text(f: &SetupFacts<'_>) -> String {
+ let mut out = format!(
+ "wake-cli binary: {}\nIndex database: {}\n",
+ f.cli_bin.display(),
+ f.db.display()
+ );
+ if let Some(hint) = path_hint(f.cli_bin) {
+ out.push_str(&format!(
+ "\n## Put it on your PATH — Run in a terminal\n\n{hint}\n"
+ ));
+ }
+ out.push_str(&format!(
+ "\n## Teach an agent to use it — Paste into the project's CLAUDE.md or AGENTS.md\n\n{AGENT_MEMO}\n"
+ ));
+ out.push_str(&format!(
+ "\n## Install it once for every project — Run in a terminal\n\n{SKILL_INSTALL}\n\n\
+ That adds the same guidance as a skill, so you do not have to paste it per\n\
+ project. Manual install: copy `skills/wake/` from the repository into\n\
+ `~/.claude/skills/wake/`.\n"
+ ));
+ // 片段按 agent 认,不按下标——那个顺序是 Connect 页的事;hint 也用它自己
+ // 带的,两个 bin 的 setup 输出才真的同形
+ if let Some(snippet) = f.mcp_bin.and_then(|mcp| {
+ crate::mcp::setup_snippets(mcp)
+ .into_iter()
+ .find(|s| s.agent == AgentId::ClaudeCode)
+ }) {
+ out.push_str(&format!(
+ "\n## Tool-calling clients: prefer MCP — {}\n\n{}\n\n\
+ `wake-mcp setup` prints the same for Codex and Cursor.\n",
+ snippet.hint, snippet.text
+ ));
+ }
+ out.push_str("\nFull reference: docs/cli.md\n");
+ if let Some(e) = &f.db_error {
+ out.push_str(&format!("\nNote: {e}\n"));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ /// 故意不给 CLI 子命令的工具(现在没有)。加工具时要么进 COMMANDS,要么
+ /// 在这里写明白为什么不进
+ const NOT_IN_CLI: &[&str] = &[];
+
+ fn p(a: &[&str]) -> Result<Invocation, CliError> {
+ parse(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>())
+ }
+
+ fn args_of(a: &[&str]) -> Value {
+ match p(a).expect("parses").action {
+ Action::Tool { args, .. } => args,
+ other => panic!("expected a tool call, got {other:?}"),
+ }
+ }
+
+ fn message(a: &[&str]) -> String {
+ p(a).expect_err("should not parse").message
+ }
+
+ /// 这个文件的看家测试:CLI 的旗标表与 MCP 工具的 inputSchema 必须双射。
+ /// 工具加参数、改名、改类型、加第五家,这里就红
+ #[test]
+ fn every_tool_parameter_has_exactly_one_flag() {
+ let defs = tools::definitions();
+ for d in &defs {
+ let name = d["name"].as_str().expect("tool has a name");
+ if NOT_IN_CLI.contains(&name) {
+ continue;
+ }
+ let cmd = COMMANDS.iter().find(|c| c.tool == name).unwrap_or_else(|| {
+ panic!("{name} has no wake-cli subcommand; add one to COMMANDS or list it in NOT_IN_CLI")
+ });
+ let props = d["inputSchema"]["properties"]
+ .as_object()
+ .expect("inputSchema has properties");
+ let mut mine: Vec<&str> = cmd.flags.iter().map(|f| f.key).collect();
+ if let Some((key, _)) = cmd.positional {
+ mine.push(key);
+ }
+ mine.sort_unstable();
+ let mut theirs: Vec<&str> = props.keys().map(String::as_str).collect();
+ theirs.sort_unstable();
+ assert_eq!(mine, theirs, "{name}: CLI 旗标与工具参数对不上");
+
+ // required 只能是位置参数——旗标是可选的
+ for r in d["inputSchema"]["required"].as_array().unwrap_or(&vec![]) {
+ let r = r.as_str().expect("required entries are strings");
+ assert_eq!(
+ Some(r),
+ cmd.positional.map(|(k, _)| k),
+ "{name}: 必填参数 {r} 在 CLI 里不是位置参数"
+ );
+ }
+ for f in cmd.flags {
+ let ty = props[f.key]["type"].as_str().unwrap_or_default();
+ let ok = match f.arity {
+ Arity::Switch => ty == "boolean",
+ Arity::Repeated => ty == "array",
+ Arity::Value => ty == "string" || ty == "integer" || ty == "number",
+ };
+ assert!(ok, "{name}.{}: arity {:?} 配不上 schema 的 {ty}", f.key, f.arity);
+ }
+ }
+ for c in COMMANDS {
+ assert!(
+ defs.iter().any(|d| d["name"] == c.tool),
+ "COMMANDS 里的 {} 在 tools::definitions() 中不存在",
+ c.tool
+ );
+ }
+ }
+
+ #[test]
+ fn flag_specs_are_consistent_across_commands() {
+ for c in COMMANDS {
+ for f in c.flags {
+ for other in COMMANDS.iter().flat_map(|c| c.flags) {
+ if other.long == f.long {
+ assert_eq!(other.key, f.key, "{} 在两处映到不同的键", f.long);
+ assert_eq!(other.arity, f.arity, "{} 在两处 arity 不同", f.long);
+ assert_eq!(other.help, f.help, "{} 在两处说明不同", f.long);
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn no_duplicate_flag_or_command_names() {
+ let mut names: Vec<&str> = COMMANDS.iter().map(|c| c.name).collect();
+ names.push(SETUP);
+ names.sort_unstable();
+ let n = names.len();
+ names.dedup();
+ assert_eq!(n, names.len(), "命令重名");
+ for c in COMMANDS {
+ let mut longs: Vec<&str> = c.flags.iter().map(|f| f.long).collect();
+ longs.sort_unstable();
+ let n = longs.len();
+ longs.dedup();
+ assert_eq!(n, longs.len(), "{} 的旗标重名", c.name);
+ }
+ }
+
+ #[test]
+ fn argv_maps_to_the_mcp_arguments_object() {
+ assert_eq!(
+ args_of(&["search", "qr login", "--project", "/w", "--agent", "codex", "--limit", "3"]),
+ json!({"query":"qr login","project":"/w","agents":"codex","limit":"3"})
+ );
+ assert_eq!(
+ args_of(&["show", "k", "--tools", "--from", "7"]),
+ json!({"key":"k","include_tools":true,"from_seq":"7"})
+ );
+ // 路由 + args 内容 + "args 恒为 object" 一次比完。后者意味着
+ // mcp/mod.rs 那道 `arguments` 形状检查在这条路上不可达,别再补一遍
+ assert_eq!(
+ p(&["projects"]).unwrap().action,
+ Action::Tool { tool: tools::LIST_PROJECTS, args: json!({}) }
+ );
+ assert_eq!(
+ p(&["sessions"]).unwrap().action,
+ Action::Tool { tool: tools::LIST_SESSIONS, args: json!({}) }
+ );
+ }
+
+ /// 整个设计压在这条上:数字不解析,交给 int_arg 去认字符串并裁剪
+ #[test]
+ fn numeric_values_stay_strings() {
+ for c in COMMANDS {
+ for f in c.flags.iter().filter(|f| f.arity == Arity::Value) {
+ let mut argv = vec![c.name];
+ if c.positional.is_some() {
+ argv.push("x");
+ }
+ argv.push(f.long);
+ argv.push("7");
+ let v = args_of(&argv);
+ assert!(v[f.key].is_string(), "{} {} 应当原样传字符串", c.name, f.long);
+ }
+ }
+ }
+
+ #[test]
+ fn switches_are_json_booleans() {
+ assert_eq!(args_of(&["sessions", "--starred"])["starred"], json!(true));
+ assert_eq!(args_of(&["show", "k", "--thinking"])["include_thinking"], json!(true));
+ }
+
+ #[test]
+ fn repeated_and_comma_separated_agents_become_one_string() {
+ let a = args_of(&["search", "x", "--agent", "codex", "--agent", "claude"]);
+ let b = args_of(&["search", "x", "--agent", "codex,claude"]);
+ assert_eq!(a["agents"], json!("codex,claude"));
+ assert_eq!(a, b);
+ }
+
+ #[test]
+ fn equals_form_and_global_flags_anywhere() {
+ assert_eq!(
+ args_of(&["sessions", "--limit=5"]),
+ args_of(&["sessions", "--limit", "5"])
+ );
+ for a in [vec!["--db=/x", "sessions"], vec!["sessions", "--db", "/x"]] {
+ assert_eq!(p(&a).unwrap().db, Some(PathBuf::from("/x")));
+ }
+ }
+
+ #[test]
+ fn double_dash_ends_option_parsing() {
+ assert_eq!(
+ args_of(&["search", "--", "--dry-run"])["query"],
+ json!("--dry-run")
+ );
+ }
+
+ #[test]
+ fn flags_are_rejected_by_name_when_they_belong_elsewhere() {
+ let m = message(&["search", "x", "--starred"]);
+ assert!(m.contains("only valid for `sessions`"), "{m}");
+ assert!(message(&["--limit", "5", "sessions"]).contains("must come after the command"));
+ assert!(message(&["projects", "--starred"]).contains("only valid for"));
+ }
+
+ /// 缺值的错不附 USAGE、形状错附——wake_mcp.rs 的这处不对称是有意的
+ #[test]
+ fn missing_values_and_unknown_options_are_parse_errors() {
+ assert!(!p(&["--db"]).unwrap_err().with_usage);
+ assert!(!p(&["sessions", "--limit"]).unwrap_err().with_usage);
+ assert!(p(&["sessions", "--nope"]).unwrap_err().with_usage);
+ assert!(message(&["sessions", "--nope"]).contains("unknown option"));
+ assert!(message(&["sessions", "--starred=false"]).contains("takes no value"));
+ }
+
+ #[test]
+ fn positional_count_errors() {
+ assert!(message(&["search"]).contains("needs a QUERY"));
+ assert!(message(&["search", "a", "b"]).contains("quote it"));
+ assert!(message(&["show"]).contains("needs a KEY"));
+ assert!(message(&["sessions", "x"]).contains("takes no arguments"));
+ assert!(message(&["setup", "x"]).contains("takes no arguments"));
+ assert!(message(&[]).contains("needs a command"));
+ assert!(message(&["nope"]).contains("unknown command"));
+ }
+
+ #[test]
+ fn relative_project_paths_are_refused_with_advice() {
+ for v in [".", "./x", "..", "../x"] {
+ assert!(
+ message(&["sessions", "--project", v]).contains("$PWD"),
+ "{v} 应当被拒并给出 $PWD 的写法"
+ );
+ }
+ for v in ["/abs", "~/x", "myname", ".hidden"] {
+ assert_eq!(
+ args_of(&["sessions", "--project", v])["project"],
+ json!(v),
+ "{v} 应当原样传下去"
+ );
+ }
+ }
+
+ #[test]
+ fn help_and_version_short_circuit() {
+ assert_eq!(p(&["--help", "--nonsense"]).unwrap().action, Action::Help);
+ assert_eq!(p(&["sessions", "-h"]).unwrap().action, Action::Help);
+ assert_eq!(p(&["-V"]).unwrap().action, Action::Version);
+ assert_eq!(p(&["setup"]).unwrap().action, Action::Setup);
+ assert!(USAGE.lines().count() < 15, "USAGE 不该长回参考手册");
+ assert!(!USAGE.ends_with('\n'));
+ }
+
+ #[test]
+ fn help_lists_every_command_flag_and_agent() {
+ let h = help();
+ for c in COMMANDS {
+ assert!(h.contains(c.name), "help 缺命令 {}", c.name);
+ assert!(h.contains(c.summary));
+ for f in c.flags {
+ assert!(h.contains(f.long), "help 缺旗标 {}", f.long);
+ }
+ }
+ assert!(h.contains(SETUP));
+ for a in AgentId::ALL {
+ assert!(h.contains(a.as_str()), "help 缺 agent {}", a.as_str());
+ }
+ assert!(h.contains("wake://session/"));
+ assert!(h.contains("EXIT CODES:"));
+ // 默认值与取值区间现渲染,不是手写进散文里的
+ assert!(h.contains("default 10, 1–30"), "search --limit 的区间没渲染出来");
+ assert!(h.contains("default 60, 1–200"), "show --messages 的区间没渲染出来");
+ // 下界曾经不渲染,于是 `--chars 5` 被悄悄裁到 200 而 help 里一个字都没有
+ assert!(h.contains("default 20000, 200–100000"), "show --chars 的下界没渲染出来");
+ // AGENT IDS 必须落在 WHEN 与 KEYS 之间,不能被甩到文末
+ let (when, ids, keys) = (
+ h.find("\nWHEN:").expect("WHEN"),
+ h.find("\nAGENT IDS:").expect("AGENT IDS"),
+ h.find("\nKEYS AND REFERENCES:").expect("KEYS"),
+ );
+ assert!(when < ids && ids < keys, "help 的段落顺序错了");
+ assert!(!h.ends_with('\n'), "emit 负责补最后那个换行");
+ }
+
+ #[test]
+ fn report_splits_argument_errors_from_read_failures() {
+ let r = report(Ok("body".into()));
+ assert_eq!((r.stream, r.code, r.text.as_str()), (Stream::Stdout, 0, "body"));
+ let r = report(Err(tools::ToolError::InvalidParams("x".into())));
+ assert_eq!((r.stream, r.code, r.text.as_str()), (Stream::Stderr, 2, "wake-cli: x"));
+ let r = report(Err(tools::ToolError::Failed("x".into())));
+ assert_eq!((r.stream, r.code), (Stream::Stderr, 1));
+ let r = report(Err(tools::ToolError::Internal("x".into())));
+ assert_eq!((r.stream, r.code), (Stream::Stderr, 1));
+ assert_eq!(CliError { message: "m".into(), with_usage: false }.report().code, 2);
+ }
+
+ #[test]
+ fn emit_adds_at_most_one_trailing_newline() {
+ for (input, want) in [("a", "a\n"), ("a\n", "a\n"), ("a\n\n", "a\n\n"), ("", "\n")] {
+ let mut buf: Vec<u8> = Vec::new();
+ emit(input, &mut buf).unwrap();
+ assert_eq!(String::from_utf8(buf).unwrap(), want, "input {input:?}");
+ }
+ }
+
+ /// 下游关掉管道要浮成 Err 让 bin 去分类,不能 panic。真管道不好测(fixture
+ /// 转录塞得进 64K 管道缓冲,子进程往往先写完),这里用假 writer 卡行为
+ #[test]
+ fn a_closed_pipe_surfaces_as_an_error_not_a_panic() {
+ struct FailWrite;
+ impl Write for FailWrite {
+ fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
+ Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "gone"))
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+ struct FailFlush;
+ impl Write for FailFlush {
+ fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
+ Ok(b.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "gone"))
+ }
+ }
+ assert_eq!(
+ emit("x", &mut FailWrite).unwrap_err().kind(),
+ std::io::ErrorKind::BrokenPipe
+ );
+ assert_eq!(
+ emit("x\n", &mut FailFlush).unwrap_err().kind(),
+ std::io::ErrorKind::BrokenPipe
+ );
+ }
+
+ #[test]
+ fn setup_text_names_the_binary_and_the_gap() {
+ let cli_bin = PathBuf::from("/Apps/Wake.app/Contents/MacOS/wake-cli");
+ let mcp_bin = PathBuf::from("/Apps/Wake.app/Contents/MacOS/wake-mcp");
+ let db = PathBuf::from("/tmp/wake.db");
+ let t = setup_text(&SetupFacts {
+ cli_bin: &cli_bin,
+ mcp_bin: Some(&mcp_bin),
+ db: &db,
+ db_error: None,
+ });
+ assert!(t.contains(&cli_bin.display().to_string()));
+ assert!(t.contains("/tmp/wake.db"));
+ assert!(t.contains("docs/cli.md"));
+ assert!(t.contains("--project \"$PWD\""));
+ // setup 必须给出真正能跑的安装方式(阶段 1 那句"还没有 skill 包"的棘轮)
+ assert!(t.contains(SKILL_INSTALL), "{t}");
+ assert!(t.contains("~/.claude/skills/wake/"), "{t}");
+ assert!(t.contains("claude mcp add"));
+
+ let t = setup_text(&SetupFacts {
+ cli_bin: &cli_bin,
+ mcp_bin: None,
+ db: &db,
+ db_error: Some("no Wake index at /tmp/wake.db".into()),
+ });
+ assert!(!t.contains("claude mcp add"), "没有 wake-mcp 就不该给 MCP 片段");
+ assert!(t.trim_end().ends_with("Note: no Wake index at /tmp/wake.db"));
+ }
+
+ #[test]
+ fn path_hint_quotes_spaces_and_skips_bin_dirs() {
+ assert_eq!(path_hint(Path::new("/usr/bin/wake-cli")), None);
+ assert_eq!(path_hint(Path::new("/home/me/.local/bin/wake-cli")), None);
+ // current_exe 失败时的兜底裸名:没有目录可说,别给自指的 ln
+ assert_eq!(path_hint(Path::new("wake-cli")), None);
+ let hint = path_hint(Path::new("/Apps/My Wake.app/Contents/MacOS/wake-cli"))
+ .expect("bundle 里要给提示");
+ if cfg!(target_os = "windows") {
+ // Windows 没有 ln -s,给的是"把这个目录加进 PATH"
+ assert!(hint.contains("MacOS"), "{hint}");
+ } else {
+ assert!(
+ hint.contains("'/Apps/My Wake.app/Contents/MacOS/wake-cli'"),
+ "{hint}"
+ );
+ }
+ }
+}
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index 9293d01..95ed3c8 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -2,7 +2,7 @@ use crate::models::*;
use anyhow::{Context as _, Result};
use rusqlite::{params, Connection, OptionalExtension};
use std::collections::HashMap;
-use std::path::Path;
+use std::path::{Path, PathBuf};
use std::sync::Mutex;
pub type LocationOverrides = (
@@ -1877,6 +1877,12 @@ pub fn now_ms() -> i64 {
chrono::Utc::now().timestamp_millis()
}
+/// `--db` 给了就用它,否则取 GUI 那份。调用点一律**惰性**求值:
+/// `default_db_path` 首次调用会把旧 vibex 库拷过来,`--help` 不该触发它
+pub fn path_or_default(db: Option<&Path>) -> PathBuf {
+ db.map(Path::to_path_buf).unwrap_or_else(default_db_path)
+}
+
/// 索引库路径:macOS 为 ~/Library/Application Support/wake,Linux 为
/// ~/.local/share/wake,Windows 为 %LOCALAPPDATA%\wake
/// (从旧 vibex 路径一次性迁移,保留收藏等 user_data)。
diff --git a/crates/wake-core/src/lib.rs b/crates/wake-core/src/lib.rs
index 4c5598e..e09a58a 100644
--- a/crates/wake-core/src/lib.rs
+++ b/crates/wake-core/src/lib.rs
@@ -1,4 +1,5 @@
pub mod adapters;
+pub mod cli;
pub mod db;
pub mod mcp;
pub mod models;
diff --git a/crates/wake-core/src/mcp/mod.rs b/crates/wake-core/src/mcp/mod.rs
index 3ee3cc0..8bd730f 100644
--- a/crates/wake-core/src/mcp/mod.rs
+++ b/crates/wake-core/src/mcp/mod.rs
@@ -196,13 +196,7 @@ impl McpServer {
"`arguments` must be an object".to_string(),
));
}
- let ctx = tools::ToolContext {
- store: &self.store,
- adapters: &self.adapters,
- now_ms: crate::db::now_ms(),
- cache: &self.transcripts,
- };
- match tools::call(&ctx, name, args) {
+ match tools::invoke(&self.store, &self.adapters, &self.transcripts, name, args) {
Ok(text) => Ok(tool_result(text, false)),
// 参数形状错(含未知工具名)是协议错误;执行失败(坏 key、解析失败)
// 是给 LLM 看的结果
@@ -226,6 +220,16 @@ fn error_response(id: Value, code: i64, message: &str) -> Value {
// ---------------------------------------------------------------- 安装辅助
+/// 只读打开索引,并按库里的 location / remote host 配置建 roster(不变量
+/// 8⑥:否则自定义根与远程缓存里的会话找不到能读它的 adapter)。旁路进程
+/// (wake-mcp / wake-cli)共用这一条——**绝不 open_or_rebuild**,那会把 GUI
+/// 正在写的库挪走重建
+pub fn open_index(db: &Path) -> Result<(Arc<Store>, Vec<Box<dyn AgentAdapter>>), String> {
+ let store = Arc::new(Store::open_read_only(db).map_err(|e| format!("{e:#}"))?);
+ let adapters = crate::adapters::create_adapters_for(&store);
+ Ok((store, adapters))
+}
+
/// 与本进程同目录的 wake-mcp 可执行文件(GUI 的 Settings → Connect 展示用;
/// 打包时 bin 与 Wake 主程序并排:macOS 在 Contents/MacOS,Linux/Windows 同目录)。
/// current_exe 进程内不变,算一次缓存住——调用方可能在 render 里问
diff --git a/crates/wake-core/src/mcp/tools.rs b/crates/wake-core/src/mcp/tools.rs
index 89c6449..721f815 100644
--- a/crates/wake-core/src/mcp/tools.rs
+++ b/crates/wake-core/src/mcp/tools.rs
@@ -17,11 +17,11 @@ use crate::services::context::{parse_since, resolve_project_paths};
use crate::services::exporter::{fmt_time, render_compact, CompactOptions};
use crate::text::{one_line, plural};
-pub struct ToolContext<'a> {
- pub store: &'a Store,
- pub adapters: &'a [Box<dyn AgentAdapter>],
- pub now_ms: i64,
- pub cache: &'a TranscriptCache,
+struct ToolContext<'a> {
+ store: &'a Store,
+ adapters: &'a [Box<dyn AgentAdapter>],
+ now_ms: i64,
+ cache: &'a TranscriptCache,
}
/// 单槽转录缓存:分页读同一会话时不必每页整文件重解析(默认 20k 字符一页,
@@ -184,7 +184,7 @@ pub fn definitions() -> Vec<Value> {
]
}
-pub fn call(ctx: &ToolContext, name: &str, args: &Value) -> ToolResult {
+fn call(ctx: &ToolContext, name: &str, args: &Value) -> ToolResult {
match name {
SEARCH => search(ctx, args),
LIST_SESSIONS => list_sessions(ctx, args),
@@ -194,6 +194,25 @@ pub fn call(ctx: &ToolContext, name: &str, args: &Value) -> ToolResult {
}
}
+/// 用当前时刻构造 ToolContext 并跑一次工具。**MCP server 与 wake-cli 共用这
+/// 一条**——now_ms 是两条路唯一可能各算各的东西(它只喂 parse_since),只留一
+/// 个构造点就没有漂移的余地
+pub fn invoke(
+ store: &Store,
+ adapters: &[Box<dyn AgentAdapter>],
+ cache: &TranscriptCache,
+ name: &str,
+ args: &Value,
+) -> ToolResult {
+ let ctx = ToolContext {
+ store,
+ adapters,
+ now_ms: crate::db::now_ms(),
+ cache,
+ };
+ call(&ctx, name, args)
+}
+
// ---------------------------------------------------------------- 参数读取
fn str_arg<'a>(args: &'a Value, name: &str) -> Result<Option<&'a str>, ToolError> {
diff --git a/crates/wake-core/tests/cli.rs b/crates/wake-core/tests/cli.rs
new file mode 100644
index 0000000..7acf97c
--- /dev/null
+++ b/crates/wake-core/tests/cli.rs
@@ -0,0 +1,395 @@
+//! wake-cli 的端到端契约:合成 fixtures 建临时库 → 起真实 bin → 与进程内
+//! `mcp::tools::invoke` 同参数的输出**逐字节**比对(MCP server 跑的正是这个
+//! 入口)。docs 与将来的 Skill 因此只需描述一份格式。
+//!
+//! 参照那一侧故意喂**自然形态**的 JSON(`5` / `true` / `["claude"]`),CLI 那
+//! 侧喂字符串与逗号串——同一条断言于是顺带卡住 int_arg 认字符串、agents_arg
+//! 认逗号串这两处宽容:谁把它们收紧了,当天就红,而不是 CLI 悄悄开始拒数字。
+//!
+//! WAKE_HOME/HOME 是进程级环境且子进程继承它:fixture home 只建一次
+//! (OnceLock)、全文件共用;不碰 home 的用例(缺库 / --help)照常并行。
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::{Arc, OnceLock};
+
+use serde_json::{json, Value};
+use wake_core::adapters::{create_adapter_roster_for, create_adapters_for, AgentAdapter};
+use wake_core::cli;
+use wake_core::db::Store;
+use wake_core::mcp::tools::{self, TranscriptCache};
+use wake_core::models::SessionFilter;
+use wake_core::scanner::{run_scan, NullEvents};
+
+mod common;
+
+const CLAUDE_KEY: &str = "claude-code:11111111-aaaa-bbbb-cccc-000000000001";
+const CLAUDE_PROJECT: &str = "/Users/tester/Github/wakefx";
+/// 绝对日期,不用 7d 这类相对量:fs::copy 在 Linux 上不保留 mtime,fixture 在
+/// 那边全是"刚刚",相对窗口两平台结果不同(2026-09-08 让 CI 红过一次)
+const ALWAYS: &str = "2000-01-01";
+const NEVER: &str = "2999-01-01";
+
+struct TestEnv {
+ db: PathBuf,
+ _home: tempfile::TempDir, // TempDir 必须被持有,否则整进程期间被清掉
+}
+
+static ENV: OnceLock<TestEnv> = OnceLock::new();
+
+fn env() -> &'static TestEnv {
+ ENV.get_or_init(|| {
+ let tmp = tempfile::Builder::new()
+ .prefix("wake-cli-e2e-")
+ .tempdir()
+ .unwrap();
+ let home = tmp.path().join("home");
+ common::stage_dir_fixtures(&home);
+ common::stage_sidecars(&home);
+ common::isolate_home(&home); // 必须在任何 adapter 构造之前
+ let db = tmp.path().join("wake.db");
+ {
+ let store = Arc::new(Store::open(&db).unwrap());
+ let roster = create_adapter_roster_for(&store);
+ run_scan(&roster.active, &store, &NullEvents, true).expect("scan ok");
+ let (_, total) = store
+ .list_sessions(&SessionFilter {
+ limit: 1,
+ ..Default::default()
+ })
+ .unwrap();
+ assert!(total > 10, "fixture home should index many sessions ({total})");
+ } // 块尾关写连接:最后一个连接 checkpoint,-wal/-shm 消失,之后
+ // open_read_only 与字节快照才稳定
+ TestEnv { db, _home: tmp }
+ })
+}
+
+/// 参照侧:与 bin 同一条打开路径、同一份 roster
+fn store_and_roster() -> (Store, Vec<Box<dyn AgentAdapter>>) {
+ let store = Store::open_read_only(&env().db).expect("read-only open");
+ let adapters = create_adapters_for(&store);
+ (store, adapters)
+}
+
+fn call(
+ store: &Store,
+ adapters: &[Box<dyn AgentAdapter>],
+ tool: &str,
+ args: &Value,
+) -> Result<String, tools::ToolError> {
+ tools::invoke(store, adapters, &TranscriptCache::default(), tool, args)
+}
+
+/// 唯一的 spawn 实现。不要 .env_clear():子进程的 roster 全靠继承
+/// WAKE_HOME/HOME
+fn cli_raw(args: &[&str]) -> (String, String, Option<i32>) {
+ let out = Command::new(env!("CARGO_BIN_EXE_wake-cli"))
+ .args(args)
+ .output()
+ .expect("spawn wake-cli");
+ (
+ String::from_utf8(out.stdout).expect("stdout is utf-8"),
+ String::from_utf8(out.stderr).expect("stderr is utf-8"),
+ out.status.code(),
+ )
+}
+
+/// 冲着 fixture 库跑
+fn cli_run(args: &[&str]) -> (String, String, Option<i32>) {
+ let db = env().db.to_str().expect("tmp path is utf-8");
+ cli_raw(&[&["--db", db], args].concat())
+}
+
+/// argv 跑出来的东西必须与同参数的工具文本逐字节相同
+fn same(
+ (store, adapters): &(Store, Vec<Box<dyn AgentAdapter>>),
+ argv: &[&str],
+ tool: &str,
+ natural: Value,
+) {
+ let text = call(store, adapters, tool, &natural).expect("tool ok");
+ // CLI 最多补一个换行:search/sessions/projects 收在 index_note 上、无换行,
+ // get_session 自带。用算出来的期望值精确相等,不要 trim_end——那会把工具
+ // 文本自带的尾换行一起吃掉、把差异藏起来
+ let want = if text.ends_with('\n') {
+ text
+ } else {
+ format!("{text}\n")
+ };
+ let (stdout, stderr, code) = cli_run(argv);
+ assert_eq!(code, Some(0), "argv {argv:?} 应当成功: {stderr}");
+ assert_eq!(stderr, "", "argv {argv:?} 跑通时 stderr 必须一个字节都没有");
+ assert_eq!(stdout, want, "argv {argv:?} 必须原样吐工具文本");
+}
+
+/// 每条 argv 与它对应的自然形态参数。测试 2 会走这张表核对旗标覆盖率
+fn argv(a: &[&str]) -> Vec<String> {
+ a.iter().map(|s| s.to_string()).collect()
+}
+
+fn cases() -> Vec<(Vec<String>, &'static str, Value)> {
+ let reference = format!("wake://session/{CLAUDE_KEY}#3");
+ vec![
+ (
+ argv(&["search", "二维码", "--limit", "3"]),
+ tools::SEARCH,
+ json!({"query":"二维码","limit":3}),
+ ),
+ (
+ argv(&["search", "二维码", "--project", CLAUDE_PROJECT, "--agent", "claude",
+ "--since", ALWAYS, "--limit", "2"]),
+ tools::SEARCH,
+ json!({"query":"二维码","project":CLAUDE_PROJECT,"agents":["claude"],"since":ALWAYS,"limit":2}),
+ ),
+ (
+ argv(&["sessions", "--limit", "5"]),
+ tools::LIST_SESSIONS,
+ json!({"limit":5}),
+ ),
+ (
+ argv(&["sessions", "--project", CLAUDE_PROJECT, "--agent", "claude,codex",
+ "--starred", "--since", ALWAYS, "--limit", "3"]),
+ tools::LIST_SESSIONS,
+ json!({"project":CLAUDE_PROJECT,"agents":["claude","codex"],"starred":true,
+ "since":ALWAYS,"limit":3}),
+ ),
+ (
+ argv(&["show", CLAUDE_KEY, "--from", "1", "--messages", "2", "--chars", "5000",
+ "--message-chars", "500", "--tools", "--thinking"]),
+ tools::GET_SESSION,
+ json!({"key":CLAUDE_KEY,"from_seq":1,"max_messages":2,"max_chars":5000,
+ "max_message_chars":500,"include_tools":true,"include_thinking":true}),
+ ),
+ (
+ argv(&["show", &reference]),
+ tools::GET_SESSION,
+ json!({ "key": reference }),
+ ),
+ (
+ argv(&["projects", "--since", ALWAYS, "--limit", "10"]),
+ tools::LIST_PROJECTS,
+ json!({"since":ALWAYS,"limit":10}),
+ ),
+ ]
+}
+
+#[test]
+fn every_command_prints_the_tool_text_verbatim() {
+ let reference = store_and_roster();
+ for (args, tool, natural) in cases() {
+ let args: Vec<&str> = args.iter().map(String::as_str).collect();
+ same(&reference, &args, tool, natural);
+ }
+}
+
+/// 每个命令、每个旗标都被上面那张表真正跑过一次。与 cli.rs 里的双射单测合起
+/// 来,"工具新增参数不可能未经测试地发版"才是真的,不是口号
+#[test]
+fn every_command_and_flag_is_exercised_end_to_end() {
+ let cases = cases();
+ for c in cli::COMMANDS {
+ let used: Vec<&Vec<String>> = cases
+ .iter()
+ .filter(|(argv, _, _)| argv.first().map(String::as_str) == Some(c.name))
+ .map(|(argv, _, _)| argv)
+ .collect();
+ assert!(!used.is_empty(), "命令 {} 没有端到端用例", c.name);
+ for f in c.flags {
+ assert!(
+ used.iter().any(|argv| argv.iter().any(|a| a == f.long)),
+ "{} 的 {} 没有端到端用例",
+ c.name,
+ f.long
+ );
+ }
+ }
+}
+
+/// 退出码那道决定的全部:argv 敲错与工具认为值不对,对用户是同一件事,都退 2
+#[test]
+fn bad_arguments_exit_two_and_name_the_problem() {
+ for (argv, needle) in [
+ (vec!["sessions", "--since", "yesterday"], "`since` not understood"),
+ (vec!["sessions", "--agent", "chatgpt"], "unknown agent"),
+ (vec!["sessions", "--limit", "abc"], "must be an integer"),
+ (vec!["nope"], "unknown command"),
+ (vec!["sessions", "--nope"], "unknown option"),
+ (vec!["sessions", "--starred=false"], "takes no value"),
+ (vec!["search"], "needs a QUERY"),
+ (vec!["show"], "needs a KEY"),
+ (vec!["search", "x", "--starred"], "only valid for `sessions`"),
+ (vec!["sessions", "--project", "."], "$PWD"),
+ (vec!["sessions", "myproj"], "takes no arguments"),
+ ] {
+ let (stdout, stderr, code) = cli_run(&argv);
+ assert_eq!(code, Some(2), "argv {argv:?} 应当退 2: {stderr}");
+ assert!(stdout.is_empty(), "argv {argv:?} 出错时 stdout 必须为空");
+ assert!(
+ stderr.contains(needle),
+ "argv {argv:?} 的 stderr 应当提到 {needle:?},实际是 {stderr}"
+ );
+ assert!(stderr.starts_with("wake-cli: "), "{stderr}");
+ }
+ // 缺命令走的是另一条:parse 直接给 "needs a command"
+ let (_, stderr, code) = cli_run(&[]);
+ assert_eq!(code, Some(2));
+ assert!(stderr.contains("needs a command"), "{stderr}");
+}
+
+/// 读不出来的会话是"跑起来了然后失败",退 1,且文本与 MCP 那侧同源
+#[test]
+fn unreadable_session_exits_one() {
+ let (store, adapters) = store_and_roster();
+ let want = match call(&store, &adapters, tools::GET_SESSION, &json!({"key":"claude-code:nope"})) {
+ Err(tools::ToolError::Failed(m)) => m,
+ other => panic!("坏 key 应当是 ToolError::Failed,实际 {other:?}"),
+ };
+ let (stdout, stderr, code) = cli_run(&["show", "claude-code:nope"]);
+ assert_eq!(code, Some(1));
+ assert!(stdout.is_empty());
+ assert_eq!(stderr, format!("wake-cli: {want}\n"));
+}
+
+/// 空结果不是错误:`wake-cli search x || fallback` 不能因为"这事没讨论过"就触发
+#[test]
+fn no_results_is_success() {
+ for (argv, prefix) in [
+ (vec!["search", "zzqqxx-no-such-term"], "No matches for"),
+ (vec!["sessions", "--project", "/nope/nope"], "No indexed project matches"),
+ (vec!["sessions", "--since", NEVER], "No sessions"),
+ (vec!["projects", "--since", NEVER], "No projects"),
+ ] {
+ let (stdout, stderr, code) = cli_run(&argv);
+ assert_eq!(code, Some(0), "argv {argv:?}: {stderr}");
+ assert!(stdout.starts_with(prefix), "argv {argv:?} 输出是 {stdout}");
+ }
+ let (stdout, _, code) = cli_run(&["show", CLAUDE_KEY, "--from", "9999"]);
+ assert_eq!(code, Some(0));
+ assert!(stdout.contains("No messages at or after seq 9999"), "{stdout}");
+}
+
+/// 超范围的数字由 int_arg 裁剪,不是 CLI 拒绝——CLI 若自己校验就会与 MCP 分家
+#[test]
+fn out_of_range_limits_are_clamped_not_rejected() {
+ let reference = store_and_roster();
+ same(&reference, &["sessions", "--limit", "999"], tools::LIST_SESSIONS, json!({"limit":100}));
+ same(&reference, &["search", "二维码", "--limit", "0"], tools::SEARCH,
+ json!({"query":"二维码","limit":1}));
+}
+
+/// 这三条不碰 fixture home,与别的用例并行也安全:--help/--version 根本不开库,
+/// 缺库那条在建 roster 之前就退了,而且都显式带 --db,不会触发
+/// default_db_path() 的首次迁移副作用
+#[test]
+fn missing_index_and_help_need_no_fixture_home() {
+ let tmp = tempfile::tempdir().unwrap();
+ let missing = tmp.path().join("nope.db");
+ let (stdout, stderr, code) = cli_raw(&["--db", missing.to_str().unwrap(), "sessions"]);
+ assert_eq!(code, Some(2));
+ assert!(stdout.is_empty());
+ assert!(stderr.contains("launch Wake once"), "{stderr}");
+
+ let (stdout, stderr, code) = cli_raw(&["--help"]);
+ assert_eq!(code, Some(0));
+ assert_eq!(stderr, "");
+ assert_eq!(stdout, format!("{}\n", cli::help()));
+
+ let (stdout, _, code) = cli_raw(&["--version"]);
+ assert_eq!(code, Some(0));
+ assert_eq!(stdout, format!("wake-cli {}\n", env!("CARGO_PKG_VERSION")));
+}
+
+/// setup 不是工具调用,上面那张 cases 表结构上覆盖不到它
+#[test]
+fn setup_reports_the_binary_and_never_fails() {
+ let (stdout, stderr, code) = cli_run(&["setup"]);
+ assert_eq!(code, Some(0), "{stderr}");
+ assert!(stdout.contains("wake-cli binary: "), "{stdout}");
+ assert!(stdout.contains(env!("CARGO_BIN_EXE_wake-cli")), "{stdout}");
+ assert!(stdout.contains("--project \"$PWD\""), "{stdout}");
+ // 库缺失也照样退 0:"还没装好"正是跑 setup 的人的处境
+ let tmp = tempfile::tempdir().unwrap();
+ let missing = tmp.path().join("nope.db");
+ let (stdout, _, code) = cli_raw(&["--db", missing.to_str().unwrap(), "setup"]);
+ assert_eq!(code, Some(0));
+ assert!(stdout.trim_end().ends_with("launch Wake once to build it"), "{stdout}");
+}
+
+/// Linux 上目录名可以不是 UTF-8,而 `--project "$PWD"` 正是主用法:
+/// std::env::args() 会 panic 成 101,args_os 才能给出契约内的退出码
+#[cfg(unix)]
+#[test]
+fn non_utf8_arguments_exit_two_instead_of_panicking() {
+ use std::ffi::OsStr;
+ use std::os::unix::ffi::OsStrExt;
+
+ let out = Command::new(env!("CARGO_BIN_EXE_wake-cli"))
+ .arg("sessions")
+ .arg("--project")
+ .arg(OsStr::from_bytes(b"/tmp/caf\xe9"))
+ .output()
+ .expect("spawn wake-cli");
+ assert_eq!(out.status.code(), Some(2));
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert!(stderr.starts_with("wake-cli: argument is not valid UTF-8"), "{stderr}");
+}
+
+/// SKILL.md 是 CLI 的第二张脸:CLI 改了而它没跟上,agent 就会照着过时的说明
+/// 去敲命令。frontmatter 齐、四个子命令全提到、退出码那条约定在,少一样就红
+#[test]
+fn the_skill_stays_in_sync_with_the_cli() {
+ let path = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../skills/wake/SKILL.md")
+ .canonicalize()
+ .expect("skills/wake/SKILL.md 必须存在——它是 `npx skills add` 装的东西");
+ let md = std::fs::read_to_string(&path).expect("read SKILL.md");
+
+ // frontmatter:name 与 description 是懒加载时常驻上下文的那两行。
+ // **一律按 `lines()` 切**(它同时吃 \n 与 \r\n):仓库没有 .gitattributes,
+ // Windows CI 按 core.autocrlf=true 检出的 SKILL.md 是 CRLF,硬比 "---\n"
+ // 会让这条测试在三平台里只红一个
+ let mut lines = md.lines();
+ assert_eq!(lines.next(), Some("---"), "SKILL.md 要以 YAML frontmatter 开头");
+ let front: Vec<&str> = lines.by_ref().take_while(|l| *l != "---").collect();
+ assert!(lines.next().is_some(), "frontmatter 要闭合,后面还要有正文");
+ assert!(front.contains(&"name: wake"), "frontmatter 缺 name");
+ let desc = front
+ .iter()
+ .find_map(|l| l.strip_prefix("description: "))
+ .expect("frontmatter 缺单行的 `description: …`");
+ // description 是触发条件,不是名词解释——没有 "Use when" 就等于没有触发器
+ assert!(desc.contains("Use when"), "description 要写成触发条件: {desc}");
+
+ for c in cli::COMMANDS {
+ assert!(
+ md.contains(&format!("wake-cli {}", c.name)),
+ "SKILL.md 没有 `wake-cli {}` 的例子",
+ c.name
+ );
+ }
+ // 最容易被误读的两条约定
+ assert!(md.contains("--project \"$PWD\""), "SKILL.md 要交代 --project 的约定");
+ assert!(md.contains("wake://session/"), "SKILL.md 要交代引用格式");
+ assert!(md.contains("read-only"), "SKILL.md 要声明只读");
+}
+
+/// 一旦有人把 Store::open / open_or_rebuild 摸进来,这条就红
+#[test]
+fn the_cli_never_writes_the_index() {
+ let db = &env().db;
+ let before = std::fs::read(db).unwrap();
+ for argv in [
+ vec!["sessions", "--limit", "3"],
+ vec!["search", "二维码"],
+ vec!["show", CLAUDE_KEY],
+ vec!["projects"],
+ ] {
+ let (_, stderr, code) = cli_run(&argv);
+ assert_eq!(code, Some(0), "{stderr}");
+ }
+ assert!(
+ before == std::fs::read(db).unwrap(),
+ "wake-cli must never write the index"
+ );
+}
diff --git a/docs/cli.md b/docs/cli.md
new file mode 100644
index 0000000..ae7e726
--- /dev/null
+++ b/docs/cli.md
@@ -0,0 +1,178 @@
+# Wake CLI (`wake-cli`)
+
+`wake-cli` is a small, read-only command-line tool that ships with Wake. It answers the same three questions the [MCP server](mcp.md) answers — what did I discuss, what did I work on here, what happened in that session — from a terminal, a script, or any agent that can run a shell command.
+
+It prints exactly what an MCP client is given: the two surfaces call the same code and their output is asserted byte for byte in the test suite. So a `wake-cli show …` transcript and a `wake_get_session` reply are the same text, and this page and [docs/mcp.md](mcp.md) describe one format, not two.
+
+Nothing here can modify a session. The CLI opens Wake's index without write access, never scans or rebuilds it, and never touches the agents' own files except to read a transcript.
+
+## Where it lives
+
+| Platform | Path |
+|---|---|
+| macOS | `/Applications/Wake.app/Contents/MacOS/wake-cli` |
+| Linux | next to `wake`: `~/.local/bin/wake-cli` (tar.gz install) or `/usr/bin/wake-cli` (deb) |
+| Windows | next to `Wake.exe` in the unpacked zip |
+
+On Linux the deb puts it in `/usr/bin`; the tar.gz installer puts it in `~/.local/bin`, which you may need to add to your `PATH`. On macOS it lives inside the app bundle, so link it once:
+
+```bash
+sudo mkdir -p /usr/local/bin && sudo ln -sf '/Applications/Wake.app/Contents/MacOS/wake-cli' /usr/local/bin/wake-cli
+```
+
+`/usr/local/bin` is root-owned on a stock macOS, hence the `sudo`. If you would rather not, skip the link entirely — the full path works anywhere, and `wake-cli setup` prints it.
+
+`wake-cli setup` prints the path for your install, the right link command, and a block you can paste into a project's `CLAUDE.md` / `AGENTS.md` to teach an agent to use it. Updating Wake keeps the path, so there is nothing to redo after an update.
+
+The binary is not named `wake`: that name already belongs to the GUI. Symlink it to whatever short name you like.
+
+## Commands
+
+```bash
+wake-cli search QUERY [OPTIONS]
+wake-cli sessions [OPTIONS]
+wake-cli show KEY [OPTIONS]
+wake-cli projects [OPTIONS]
+wake-cli setup
+wake-cli --help | --version
+```
+
+Global options, valid anywhere on the line: `--db PATH` (another index database), `--help` / `-h`, `--version` / `-V`, and `--` to end option parsing. Command options must come after their command. Every option that takes a value also accepts the `--flag=value` form, which is how you pass a value that starts with a dash. The switches (`--starred`, `--tools`, `--thinking`) take no value at all.
+
+There is no default project scope. Pass `--project "$PWD"` when you mean "here" — otherwise every project on the machine is in scope. A relative path (`.`, `../x`) is refused rather than guessed at, because inside a symlinked checkout the shell's `$PWD` and the process's working directory disagree.
+
+### `search`
+
+Full-text search across every indexed session — user prompts, assistant replies, tool names and inputs. Terms are ANDed; CJK text and code substrings like `useEffect(` work. Returns matching sessions with up to three snippets each, and a `wake://session/<key>#<seq>` reference per snippet.
+
+| Option | Value | Notes |
+|---|---|---|
+| `--project` | path or name | absolute path, or a project name |
+| `--agent` | agent id | repeatable, or comma-separated |
+| `--since` | when | see [When](#when) |
+| `--limit` | N | default 10, max 30 |
+
+```bash
+wake-cli search "rate limiter" --project "$PWD" --since 7d
+wake-cli search "useEffect(" --agent codex --agent claude-code
+wake-cli search -- --dry-run # a query that starts with a dash
+```
+
+### `sessions`
+
+The most recently updated sessions. Subagent sessions are folded into their parents; archived sessions are excluded. This is what to run when you want the key of "the session from yesterday".
+
+Same options as `search`, plus `--starred` (only sessions you starred in Wake). `--limit` defaults to 20, max 100.
+
+```bash
+wake-cli sessions --project "$PWD" --limit 5
+wake-cli sessions --agent codex --since 24h
+```
+
+### `show`
+
+One session's transcript, parsed live from the agent's own files, as compact Markdown: user and assistant messages with `[seq N]` markers, tool calls folded to one line each, injected context omitted. Because it reads the file rather than the index, it does not depend on when Wake last scanned. One exception: a session mirrored from a remote host is read from the local mirror, so it reflects Wake's last successful sync rather than the remote machine right now.
+
+| Option | Value | Notes |
+|---|---|---|
+| `--from` | SEQ | start at this message; a `wake://…#N` reference sets it too |
+| `--messages` | N | messages per page, default 60, max 200 |
+| `--chars` | N | character budget per page, default 20000, max 100000 |
+| `--message-chars` | N | truncate each message, default 4000, max 50000 |
+| `--tools` | — | include tool inputs and outputs (verbose) |
+| `--thinking` | — | include the assistant's thinking where the agent recorded it |
+
+Long transcripts are paginated: when the reply ends with a `from_seq` hint, run it again with `--from <that number>`.
+
+```bash
+wake-cli show 'claude-code:1b2c3d4e-…'
+wake-cli show 'wake://session/claude-code:1b2c3d4e-…#42' --tools
+wake-cli show 'codex:0195c2a1-…' --from 120 --messages 40
+```
+
+### `projects`
+
+Working directories that have session history, most recently active first, with session counts. Use it to find the right `--project` value. Options: `--since`, `--limit` (default 50, max 200).
+
+### `setup`
+
+Prints this binary's path, the index path, how to put it on your `PATH`, a paste-able block that tells an agent when and how to use it, and — when `wake-mcp` sits next to it — the one-line MCP setup for Claude Code. It writes nothing and installs nothing — Wake never edits another tool's config files.
+
+To make this automatic instead of per-project, install the skill (next section).
+
+## Teaching an agent to use it
+
+Two ways, same content.
+
+**A skill, once, for every project** — the repository ships one at `skills/wake/`:
+
+```bash
+npx skills add iAmCorey/Wake
+```
+
+That works for Claude Code, Codex and anything else that reads the skills format. To do
+it by hand, copy `skills/wake/` into `~/.claude/skills/wake/`. The skill tells the agent
+*when* to look back — earlier conversations, past decisions, where work stopped, whether
+an error has been seen before — and how to read keys, references and pages.
+
+**A paste block, for one project** — `wake-cli setup` prints a short version you can drop
+into that project's `CLAUDE.md` or `AGENTS.md`. Use this when you would rather not
+install anything, or want the guidance to live in the repository.
+
+Neither writes to another tool's configuration; Wake only ever prints.
+
+## When
+
+`--since` accepts a relative window — `30m`, `24h`, `7d`, `2w` — or an absolute date/time: `2026-09-01`, `"2026-09-01 09:30"`, `2026-09-01T09:30:00Z`. Date-times without a zone are read in local time.
+
+Numeric options outside their range are clamped, not rejected: `--limit 999` on `sessions` gives you 100.
+
+## Agent ids
+
+`claude-code`, `codex`, `grok`, `dsh`, `cursor`, `opencode`, `pi`, `omp`, `kiro`, `kimi`, `gemini`, `copilot`, `antigravity`, `qoder`, `hermes`, `openclaw`. Display names (`"Claude Code"`) and a few aliases (`claude`, `deepseek`) work too.
+
+## Session keys and references
+
+- Local sessions: `<agent>:<native id>`, for example `codex:0195c2a1-…`.
+- Sessions mirrored from a remote host: `<agent>:<host>:<native id>`.
+- References: `wake://session/<key>#<seq>` point at one message; `show` accepts them and starts the page there.
+
+The native id is the one the agent's own `--resume` flag expects.
+
+## Output
+
+The text is Markdown, written for an agent to read, and identical to what the MCP tools return. One consequence is visible: the closing hint in a listing names the MCP tool (`wake_get_session`) rather than `wake-cli show`, because the same string serves both surfaces. Read it as "the command that reads a session".
+
+`search`, `sessions` and `projects` end with a line saying how fresh the index is (`Index covers activity up to …`); keep Wake running and it stays current. `show` has no such line because it reads the agent's file rather than the index. For a session mirrored from a remote host that file is the local mirror, current as of the last successful sync — Settings → Remote hosts shows whether the last one succeeded.
+
+Exactly one trailing newline is added when the text does not already end with one — nothing else is added or removed. Piping is safe: `wake-cli show <key> --tools | head -3` prints three lines and exits 0.
+
+## Exit codes
+
+| Code | Meaning |
+|---|---|
+| `0` | it ran — **including** "no matches", "no such project" and "no sessions" |
+| `1` | a session could not be read — unknown key, or a transcript that would not parse |
+| `2` | the command line was wrong, or the index is missing / unreadable / too old |
+
+Empty results are never an error, so `wake-cli search x \|\| fallback` does not fire just because nothing was ever discussed about `x`. Diagnostics always go to stderr, prefixed `wake-cli: `, so `wake-cli show <key> > out.md` cannot capture one.
+
+Both a mistyped option (`--sinse 7d`) and a value the tools reject (`--since 7dd`) exit `2` — from a user's seat they are the same mistake, and the layer that caught it is not visible. This is a deliberate difference from `wake-mcp call`, which collapses every failure to `1` because its JSON-RPC envelope already carries the classification.
+
+## Privacy and scope
+
+- Everything runs on this machine. The CLI makes no network requests.
+- It reads the same session files Wake indexes — local agents' data directories plus the local mirrors of any remote hosts you configured in Wake. Nothing leaves the machine.
+- Wake's read-only rules apply: other agents' directories and databases are opened read-only and credential files are never read. The index itself is opened without write access; a test asserts its bytes never change.
+- On its first run against the default database path, Wake's shared path helper migrates an index left by the old `vibex` builds. `wake-mcp` does the same; `--db` skips it entirely.
+
+## Troubleshooting
+
+- **`no Wake index at … — launch Wake once to build it`.** Wake has never run on this machine, or `--db` points at the wrong file. `… is empty or from an older version` means the index predates this Wake version; launching Wake once upgrades it.
+- **`No indexed project matches …`.** Pass the absolute path of the repository, or its name. `wake-cli projects` shows the paths Wake knows.
+- **Results look stale.** Keep Wake running; the freshness line at the end of every reply says what the index covers. Copilot / OpenCode / Antigravity / Hermes / OpenClaw databases refresh when Wake launches or when you click Refresh.
+- **macOS refuses to run it ("cannot be opened because the developer cannot be verified").** Wake is signed but not notarized. Clear the quarantine flag for the whole bundle once: `xattr -dr com.apple.quarantine /Applications/Wake.app`.
+
+## See also
+
+[docs/mcp.md](mcp.md) — the same index over MCP, for clients that call tools rather than run commands.
diff --git a/docs/mcp.md b/docs/mcp.md
index 6ab1020..a8ef189 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -116,7 +116,7 @@ Search and lists come from Wake's index. Wake keeps the index current while it i
Index covers activity up to 2026-09-08 09:41:37 (local time); Wake keeps it fresh while it is running.
```
-so an agent can tell how recent the data is. Reading a transcript with `wake_get_session` parses the agent's own files live, so it is always current regardless of the index.
+so an agent can tell how recent the data is. Reading a transcript with `wake_get_session` parses the agent's own files rather than the index, so it does not depend on when Wake last scanned. Sessions mirrored from a remote host are read from their local mirror, so they are current as of the last successful sync.
## Tools
diff --git a/scripts/make-app.sh b/scripts/make-app.sh
index b04011f..a725fa5 100755
--- a/scripts/make-app.sh
+++ b/scripts/make-app.sh
@@ -36,13 +36,14 @@ iconutil -c icns "$ICONSET" -o dist/wake.icns
# 2. release 构建。Universal 模式在同一 macOS SDK 上交叉编译两个 Rust
# target,再用 lipo 合并;目标标准库由调用方预先通过 rustup 安装。
# 发行二进制清单:主程序 Wake + 并排的辅助可执行文件(只读 MCP server
-# wake-mcp,Settings → Connect 按同目录找它)。两者 cargo 包不同,构建各写一行;
-# lipo / 拷贝 / 签名 / 架构核对按清单循环,再加一个辅助 bin 只改 SIDE_BINS
-SIDE_BINS=(wake-mcp)
+# wake-mcp,Settings → Connect 按同目录找它;会话查询 CLI wake-cli)。辅助 bin
+# 与主程序 cargo 包不同,构建各写一行;lipo / 拷贝 / 签名 / 架构核对、以及
+# cargo 的 --bin 清单全部由 SIDE_BINS 派生,再加一个辅助 bin 只改这一个数组
+SIDE_BINS=(wake-mcp wake-cli)
BINS=(Wake "${SIDE_BINS[@]}")
build_bins() {
cargo build --release -p wake "$@"
- cargo build --release -p wake-core --bin wake-mcp "$@"
+ cargo build --release -p wake-core "${SIDE_BINS[@]/#/--bin=}" "$@"
}
if $UNIVERSAL; then
ARM_TARGET=aarch64-apple-darwin
@@ -96,7 +97,7 @@ PLIST
# 4. ad-hoc 签名(本机运行足够;分发需开发者证书 + notarize)。--deep 只递归
# 标准嵌套位置(Frameworks/PlugIns/XPCServices…),MacOS/ 里并排的辅助可执行
-# 文件不算,先单独签它们,否则 Gatekeeper 会拦 MCP 客户端起的 wake-mcp
+# 文件不算,先单独签它们,否则 Gatekeeper 会拦下别人起的 wake-mcp / wake-cli
for bin in "${SIDE_BINS[@]}"; do
codesign --force -s - "$APP/Contents/MacOS/$bin"
done
diff --git a/scripts/make-linux.sh b/scripts/make-linux.sh
index 326e475..a52ebef 100755
--- a/scripts/make-linux.sh
+++ b/scripts/make-linux.sh
@@ -14,13 +14,15 @@ ARCH=$(dpkg --print-architecture 2>/dev/null || uname -m)
# 1. release 构建(二进制名 Wake 来自 [[bin]],macOS 菜单栏需要;
# Linux 装成小写 wake,CLI 惯例)
cargo build --release -p wake
-cargo build --release -p wake-core --bin wake-mcp
+cargo build --release -p wake-core --bin wake-mcp --bin wake-cli
STAGE=$(mktemp -d)/wake-${VERSION}-linux-${ARCH}
mkdir -p "$STAGE"
cp "$TARGET_DIR/release/Wake" "$STAGE/wake"
# 只读 MCP server,装在主程序旁边(Settings → Connect 按同目录找它)
cp "$TARGET_DIR/release/wake-mcp" "$STAGE/wake-mcp"
+# 会话查询 CLI,同样并排
+cp "$TARGET_DIR/release/wake-cli" "$STAGE/wake-cli"
cp "$ASSETS/icon.svg" "$STAGE/wake.svg"
# 2. .desktop(StartupWMClass 对齐 main.rs 的 app_id = "wake")
@@ -43,13 +45,14 @@ set -euo pipefail
cd "$(dirname "$0")"
install -Dm755 wake "$HOME/.local/bin/wake"
install -Dm755 wake-mcp "$HOME/.local/bin/wake-mcp"
+install -Dm755 wake-cli "$HOME/.local/bin/wake-cli"
# 桌面项写绝对路径:~/.local/bin 若是本次新建的,图形会话的 PATH 里还没有它,
# Exec=wake 会找不到程序直到重新登录(deb 装 /usr/bin 不受此累,保持裸名)
sed "s|^Exec=wake$|Exec=\"$HOME/.local/bin/wake\"|" wake.desktop \
| install -Dm644 /dev/stdin "$HOME/.local/share/applications/wake.desktop"
install -Dm644 wake.svg "$HOME/.local/share/icons/hicolor/scalable/apps/wake.svg"
command -v update-desktop-database >/dev/null && update-desktop-database "$HOME/.local/share/applications" || true
-echo "Installed. Make sure ~/.local/bin is on your PATH, then run: wake"
+echo "Installed. Make sure ~/.local/bin is on your PATH, then run: wake (or wake-cli --help)"
INSTALL
chmod +x "$STAGE/install.sh"
@@ -64,6 +67,7 @@ if command -v dpkg-deb >/dev/null; then
mkdir -p "$DEB/DEBIAN"
install -Dm755 "$STAGE/wake" "$DEB/usr/bin/wake"
install -Dm755 "$STAGE/wake-mcp" "$DEB/usr/bin/wake-mcp"
+ install -Dm755 "$STAGE/wake-cli" "$DEB/usr/bin/wake-cli"
install -Dm644 "$STAGE/wake.desktop" "$DEB/usr/share/applications/wake.desktop"
install -Dm644 "$STAGE/wake.svg" "$DEB/usr/share/icons/hicolor/scalable/apps/wake.svg"
cat > "$DEB/DEBIAN/control" <<CONTROL
diff --git a/scripts/make-windows.ps1 b/scripts/make-windows.ps1
index d3420e1..4c9e987 100644
--- a/scripts/make-windows.ps1
+++ b/scripts/make-windows.ps1
@@ -20,7 +20,7 @@ $targetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { "target
cargo build --release -p wake
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
-cargo build --release -p wake-core --bin wake-mcp
+cargo build --release -p wake-core --bin wake-mcp --bin wake-cli
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# 二进制名 Wake.exe 来自 [[bin]](macOS 菜单栏取进程名所需);Windows 惯例
@@ -31,6 +31,8 @@ New-Item -ItemType Directory -Path $stage -Force | Out-Null
Copy-Item (Join-Path $targetDir "release/Wake.exe") (Join-Path $stage "Wake.exe")
# 只读 MCP server,与主程序并排(Settings → Connect 按同目录找它)
Copy-Item (Join-Path $targetDir "release/wake-mcp.exe") (Join-Path $stage "wake-mcp.exe")
+# 会话查询 CLI,同样并排
+Copy-Item (Join-Path $targetDir "release/wake-cli.exe") (Join-Path $stage "wake-cli.exe")
New-Item -ItemType Directory -Path dist -Force | Out-Null
$zip = "dist/wake-$version-windows-$arch.zip"
diff --git a/skills/wake/SKILL.md b/skills/wake/SKILL.md
new file mode 100644
index 0000000..c1ea636
--- /dev/null
+++ b/skills/wake/SKILL.md
@@ -0,0 +1,96 @@
+---
+name: wake
+description: Search and read past coding-agent sessions on this machine. Use when the user refers to earlier conversations, decisions, why something was done, where work stopped, or whether an error was seen before.
+---
+
+# Wake — past coding-agent sessions
+
+Wake indexes every coding-agent session on this machine — Claude Code, Codex, Cursor,
+Gemini CLI, OpenCode and a dozen more — and `wake-cli` reads that index from a shell.
+
+Reach for it whenever the answer lives in an earlier conversation rather than in the
+code: what was discussed, what was decided and why, where previous work stopped, which
+approaches were already tried and rejected, whether an error has been seen before. Git
+history and the working tree do not hold any of that.
+
+Everything below is read-only. Nothing here can modify or delete a session.
+
+## Finding the binary
+
+```bash
+command -v wake-cli || ls /Applications/Wake.app/Contents/MacOS/wake-cli
+```
+
+Use whichever resolves. On Linux it is on `PATH` after a deb install, or at
+`~/.local/bin/wake-cli` from the tarball; on Windows it sits next to `Wake.exe`. If
+neither exists, say so — the user needs [Wake](https://github.com/iAmCorey/Wake), and it
+has to have run once to build the index. Do not try to install it yourself.
+
+## Commands
+
+Always scope to the current repository with `--project "$PWD"` unless the user clearly
+means "everywhere". Without it, every project on the machine is in scope.
+
+**What happened in this project recently**
+
+```bash
+wake-cli sessions --project "$PWD" --limit 10
+```
+
+Add `--agent codex` (repeatable), `--since 7d`, or `--starred` to narrow it.
+
+**Where was this discussed**
+
+```bash
+wake-cli search "rate limiter" --project "$PWD"
+```
+
+Terms are ANDed. CJK text and code substrings like `useEffect(` work. Drop `--project`
+when the user asks about something they might have worked on elsewhere.
+
+**Read a session**
+
+```bash
+wake-cli show 'claude-code:1b2c3d4e-…'
+```
+
+Add `--tools` for tool inputs and outputs, `--thinking` for recorded reasoning. Both are
+verbose — start without them.
+
+**Which projects have history**
+
+```bash
+wake-cli projects --limit 20
+```
+
+## Keys, references and paging
+
+`sessions` and `search` print a key for every session — `<agent>:<id>`, or
+`<agent>:<host>:<id>` for a session mirrored from a remote machine. Pass a key to `show`.
+
+`search` also prints `ref: wake://session/<key>#<seq>` under each snippet. Pass the whole
+reference (quoted) to `show` and the transcript starts at that message — that is the fast
+path from "this term was mentioned" to "here is the surrounding conversation".
+
+Long transcripts are paginated. When the output ends with a `from_seq` hint, run again
+with `--from <that number>` to continue.
+
+## Reading the results
+
+- Exit code `0` means it ran — **including "no matches" and "no such project"**. Do not
+ treat an empty result as a failure; report that nothing was found.
+- Exit `1` means a session could not be read; exit `2` means the command line was wrong
+ or there is no index yet. Both print an explanation to stderr.
+- Every listing ends with the index freshness (`Index covers activity up to …`). If it
+ looks stale, Wake has not been running. `show` does not depend on that line — it reads
+ the agent's own file rather than the index. The exception is a session from a remote
+ host (`<agent>:<host>:<id>`): that file is a local mirror, current as of Wake's last
+ successful sync. Say so rather than reporting it as the other machine's latest state.
+- Values out of range are clamped, not rejected: `--limit 999` returns the maximum.
+
+## Sensible defaults
+
+- Start with `sessions --project "$PWD"` when the user says "last time" or "yesterday",
+ and with `search` when they name a topic, an error or a decision.
+- Read one or two transcripts, not ten — `show` output is large.
+- Quote keys and `wake://` references: they contain characters the shell will eat.