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): let wake-cli build the index when Wake never has

Corey Chiu97c647dfb9d0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c6e822..97ea04c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## Unreleased
+
+- New: `wake-cli index` builds Wake's index from the terminal, so an agent that finds Wake installed but never launched can get itself working instead of stopping to ask you — it only ever builds a missing index, never touches one the app is already keeping current
+
## [0.6.2] — 2026-09-12
- Fix: On macOS, conversation file links open in Finder instead of showing an application error. Directories open directly, files are selected, and unavailable or remote paths show an in-app notice (#28, #29).
diff --git a/crates/wake-core/src/bin/wake_cli.rs b/crates/wake-core/src/bin/wake_cli.rs
index 19beee0..fe6e233 100644
--- a/crates/wake-core/src/bin/wake_cli.rs
+++ b/crates/wake-core/src/bin/wake_cli.rs
@@ -17,14 +17,22 @@ use std::io::{self, Write as _};
use std::path::PathBuf;
use std::process::ExitCode;
+use wake_core::adapters::create_adapters_for;
use wake_core::cli::{self, Action, CliError, Report, Stream};
use wake_core::db::{self, Store};
use wake_core::mcp::{self, tools};
+use wake_core::models::SessionFilter;
+use wake_core::scanner::{run_scan, NullEvents};
+use wake_core::text::plural;
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() {
+ let argv: Vec<String> = match std::env::args_os()
+ .skip(1)
+ .map(|a| a.into_string())
+ .collect()
+ {
Ok(v) => v,
Err(bad) => {
return write(
@@ -44,6 +52,7 @@ fn main() -> ExitCode {
Action::Help => write(ok(cli::help())),
Action::Version => write(ok(format!("wake-cli {}", mcp::SERVER_VERSION))),
Action::Setup => write(ok(setup(&inv.db))),
+ Action::Index => write(index(&inv.db)),
Action::Tool { tool, args } => run(&inv.db, tool, &args),
}
}
@@ -81,6 +90,59 @@ fn run(db: &Option<PathBuf>, tool: &str, args: &serde_json::Value) -> ExitCode {
)))
}
+/// 从零建一次索引。**只在索引文件不存在时**建:已存在的库归 GUI 管。
+/// "旁路进程绝不 open_or_rebuild" 是为了不和 GUI 正在写的库打架,而
+/// `SCAN_GATE` 只是**进程级**互斥、跨进程不管用——库根本不存在的那一刻
+/// 没有任何写入方可冲突,所以这道口子只开这么宽,**别加 --force**。
+/// 场景是"装了 Wake 但从没启动过":skill 让 agent 跑这一条就能自救
+fn index(db: &Option<PathBuf>) -> Report {
+ let path = db_path(db);
+ if path.exists() {
+ return ok(format!(
+ "An index already exists at {}. Launch Wake to update or rebuild it.",
+ path.display()
+ ));
+ }
+ if let Some(dir) = path.parent() {
+ if let Err(e) = std::fs::create_dir_all(dir) {
+ return fail(format!("could not create {}: {e}", dir.display()));
+ }
+ }
+ let store = match Store::open(&path) {
+ Ok(s) => std::sync::Arc::new(s),
+ Err(e) => return fail(format!("{e:#}")),
+ };
+ // 不变量 8⑥:按库里的 location 配置建 roster(新库即内置十六家)
+ let adapters = create_adapters_for(&store);
+ if let Err(e) = run_scan(&adapters, &store, &NullEvents, true) {
+ return fail(format!("{e:#}"));
+ }
+ let sessions = store
+ .list_sessions(&SessionFilter {
+ limit: 1,
+ ..Default::default()
+ })
+ .map(|(_, total)| total)
+ .unwrap_or(0);
+ let agents = store.agent_counts().map(|c| c.len() as i64).unwrap_or(0);
+ ok(format!(
+ "Indexed {sessions} session{} from {agents} agent{} into {}.\n\
+ Launch Wake to keep it current — it watches the agents' files while it runs.",
+ plural(sessions),
+ plural(agents),
+ path.display()
+ ))
+}
+
+/// 跑起来了然后失败 → 退 1(与 `cli::report` 对 Failed/Internal 同档)
+fn fail(message: String) -> Report {
+ Report {
+ stream: Stream::Stderr,
+ text: format!("wake-cli: {message}"),
+ code: 1,
+ }
+}
+
fn setup(db: &Option<PathBuf>) -> String {
let cli_bin = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("wake-cli"));
// sibling_named 取的就是 current_exe 同级目录,从 wake-cli 调恰好对
diff --git a/crates/wake-core/src/cli.rs b/crates/wake-core/src/cli.rs
index cda6478..4f4b109 100644
--- a/crates/wake-core/src/cli.rs
+++ b/crates/wake-core/src/cli.rs
@@ -57,7 +57,14 @@ impl FlagSpec {
placeholder: &'static str,
help: &'static str,
) -> Self {
- Self { long, key, arity, placeholder, help, validate: None }
+ Self {
+ long,
+ key,
+ arity,
+ placeholder,
+ help,
+ validate: None,
+ }
}
const fn validated(mut self, v: Validator) -> Self {
@@ -77,51 +84,95 @@ pub struct CommandSpec {
pub summary: &'static str,
}
-/// 不是工具调用,单独一条路
-const SETUP: &str = "setup";
+/// 不走 `mcp::tools` 的子命令:不收位置参数、不收旗标,因此也不参与
+/// COMMANDS 与 `tools::definitions()` 的双射。加一个只在这里加一行
+const PLAIN: &[(&str, &str)] = &[
+ (
+ "setup",
+ "print this binary's path and how to point an agent at it",
+ ),
+ (
+ "index",
+ "build the index once, when Wake has never run here",
+ ),
+];
const F_PROJECT: FlagSpec = FlagSpec::new(
- "--project", "project", Arity::Value, "PATH",
+ "--project",
+ "project",
+ Arity::Value,
+ "PATH",
"one project: an absolute path (use \"$PWD\") or a project name",
-).validated(check_project);
+)
+.validated(check_project);
const F_AGENT: FlagSpec = FlagSpec::new(
- "--agent", "agents", Arity::Repeated, "ID",
+ "--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",
+ "--since",
+ "since",
+ Arity::Value,
+ "WHEN",
"only what was updated at or after WHEN",
);
const F_LIMIT: FlagSpec = FlagSpec::new(
- "--limit", "limit", Arity::Value, "N",
+ "--limit",
+ "limit",
+ Arity::Value,
+ "N",
"maximum rows to return",
);
const F_STARRED: FlagSpec = FlagSpec::new(
- "--starred", "starred", Arity::Switch, "",
+ "--starred",
+ "starred",
+ Arity::Switch,
+ "",
"only sessions starred in Wake",
);
const F_FROM: FlagSpec = FlagSpec::new(
- "--from", "from_seq", Arity::Value, "SEQ",
+ "--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",
+ "max_messages",
+ Arity::Value,
+ "N",
"messages per page",
);
const F_CHARS: FlagSpec = FlagSpec::new(
- "--chars", "max_chars", Arity::Value, "N",
+ "--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",
+ "--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, "",
+ "--tools",
+ "include_tools",
+ Arity::Switch,
+ "",
"include tool inputs and outputs",
);
const F_THINKING: FlagSpec = FlagSpec::new(
- "--thinking", "include_thinking", Arity::Switch, "",
+ "--thinking",
+ "include_thinking",
+ Arity::Switch,
+ "",
"include the assistant's thinking where the agent recorded it",
);
@@ -176,9 +227,14 @@ pub enum Action {
Help,
Version,
Setup,
+ /// 从零建一次索引。**只在索引不存在时**——已存在的库归 GUI 管
+ Index,
/// 一次工具调用。`args` **恒为 JSON object**——mcp/mod.rs 那道
/// `arguments` 形状检查在这条路上不可达,别再补一遍
- Tool { tool: &'static str, args: Value },
+ Tool {
+ tool: &'static str,
+ args: Value,
+ },
}
#[derive(Debug, Clone, PartialEq)]
@@ -275,7 +331,9 @@ fn err(message: String, with_usage: bool) -> CliError {
/// 缺值的错**不附 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))
+ it.next()
+ .cloned()
+ .ok_or_else(|| err(msg.to_string(), false))
}
/// 这个 long 归哪些命令(给 "只对 sessions 有效" / "要放在命令之后" 用)
@@ -318,7 +376,8 @@ fn check_project(v: &str) -> Result<(), String> {
#[derive(Clone, Copy)]
enum Seen {
Nothing,
- Setup,
+ /// PLAIN 表里的子命令,按名字记
+ Plain(&'static str),
Command(&'static CommandSpec),
}
@@ -346,10 +405,16 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
continue;
}
if s == "--help" || s == "-h" {
- return Ok(Invocation { db, action: Action::Help });
+ return Ok(Invocation {
+ db,
+ action: Action::Help,
+ });
}
if s == "--version" || s == "-V" {
- return Ok(Invocation { db, action: Action::Version });
+ return Ok(Invocation {
+ db,
+ action: Action::Version,
+ });
}
if s == "--" {
only_positional = true;
@@ -363,8 +428,8 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
// 2) 子命令 flag。命令还没出现 ⇒ 位置写反了,直说
let cmd = match seen {
Seen::Command(c) => c,
- Seen::Setup => {
- return Err(err(format!("setup takes no options (got {name})"), true))
+ Seen::Plain(p) => {
+ return Err(err(format!("{p} takes no options (got {name})"), true))
}
Seen::Nothing => return Err(misplaced(name, false)),
};
@@ -401,7 +466,9 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
}
// 3) 位置参数:第一个是命令名
match seen {
- Seen::Nothing if s == SETUP => seen = Seen::Setup,
+ Seen::Nothing if PLAIN.iter().any(|(n, _)| *n == s) => {
+ seen = Seen::Plain(PLAIN.iter().find(|(n, _)| *n == s).expect("just matched").0)
+ }
Seen::Nothing => {
seen = Seen::Command(
COMMANDS
@@ -410,9 +477,7 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
.ok_or_else(|| err(format!("unknown command {s}"), true))?,
)
}
- Seen::Setup => {
- return Err(err(format!("setup takes no arguments (got `{s}`)"), true))
- }
+ Seen::Plain(p) => return Err(err(format!("{p} takes no arguments (got `{s}`)"), true)),
Seen::Command(cmd) => {
let Some((_, ph)) = cmd.positional else {
return Err(err(
@@ -434,7 +499,19 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
}
}
let cmd = match seen {
- Seen::Setup => return Ok(Invocation { db, action: Action::Setup }),
+ Seen::Plain("setup") => {
+ return Ok(Invocation {
+ db,
+ action: Action::Setup,
+ })
+ }
+ Seen::Plain("index") => {
+ return Ok(Invocation {
+ db,
+ action: Action::Index,
+ })
+ }
+ Seen::Plain(other) => unreachable!("PLAIN 表加了 {other} 但没在这里给 Action"),
Seen::Nothing => return Err(err("needs a command".into(), true)),
Seen::Command(c) => c,
};
@@ -448,7 +525,10 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
}
Ok(Invocation {
db,
- action: Action::Tool { tool: cmd.tool, args: Value::Object(map) },
+ action: Action::Tool {
+ tool: cmd.tool,
+ args: Value::Object(map),
+ },
})
}
@@ -587,14 +667,19 @@ pub fn help() -> String {
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));
+ 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,
+ ));
+ }
+ for (name, summary) in PLAIN {
+ out.push_str(&row(format!(" wake-cli {name}"), 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));
@@ -623,7 +708,8 @@ pub fn help() -> String {
/// 贴进 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
+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.
@@ -790,7 +876,11 @@ mod tests {
Arity::Repeated => ty == "array",
Arity::Value => ty == "string" || ty == "integer" || ty == "number",
};
- assert!(ok, "{name}.{}: arity {:?} 配不上 schema 的 {ty}", f.key, f.arity);
+ assert!(
+ ok,
+ "{name}.{}: arity {:?} 配不上 schema 的 {ty}",
+ f.key, f.arity
+ );
}
}
for c in COMMANDS {
@@ -820,7 +910,7 @@ mod tests {
#[test]
fn no_duplicate_flag_or_command_names() {
let mut names: Vec<&str> = COMMANDS.iter().map(|c| c.name).collect();
- names.push(SETUP);
+ names.extend(PLAIN.iter().map(|(n, _)| *n));
names.sort_unstable();
let n = names.len();
names.dedup();
@@ -837,7 +927,16 @@ mod tests {
#[test]
fn argv_maps_to_the_mcp_arguments_object() {
assert_eq!(
- args_of(&["search", "qr login", "--project", "/w", "--agent", "codex", "--limit", "3"]),
+ args_of(&[
+ "search",
+ "qr login",
+ "--project",
+ "/w",
+ "--agent",
+ "codex",
+ "--limit",
+ "3"
+ ]),
json!({"query":"qr login","project":"/w","agents":"codex","limit":"3"})
);
assert_eq!(
@@ -848,11 +947,17 @@ mod tests {
// mcp/mod.rs 那道 `arguments` 形状检查在这条路上不可达,别再补一遍
assert_eq!(
p(&["projects"]).unwrap().action,
- Action::Tool { tool: tools::LIST_PROJECTS, args: json!({}) }
+ Action::Tool {
+ tool: tools::LIST_PROJECTS,
+ args: json!({})
+ }
);
assert_eq!(
p(&["sessions"]).unwrap().action,
- Action::Tool { tool: tools::LIST_SESSIONS, args: json!({}) }
+ Action::Tool {
+ tool: tools::LIST_SESSIONS,
+ args: json!({})
+ }
);
}
@@ -868,7 +973,12 @@ mod tests {
argv.push(f.long);
argv.push("7");
let v = args_of(&argv);
- assert!(v[f.key].is_string(), "{} {} 应当原样传字符串", c.name, f.long);
+ assert!(
+ v[f.key].is_string(),
+ "{} {} 应当原样传字符串",
+ c.name,
+ f.long
+ );
}
}
}
@@ -876,7 +986,10 @@ mod tests {
#[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));
+ assert_eq!(
+ args_of(&["show", "k", "--thinking"])["include_thinking"],
+ json!(true)
+ );
}
#[test]
@@ -931,6 +1044,9 @@ mod tests {
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(&["index", "x"]).contains("takes no arguments"));
+ // PLAIN 命令不收旗标,包括全局之外的任何一个
+ assert!(message(&["index", "--limit", "5"]).contains("takes no options"));
assert!(message(&[]).contains("needs a command"));
assert!(message(&["nope"]).contains("unknown command"));
}
@@ -958,6 +1074,7 @@ mod tests {
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_eq!(p(&["index"]).unwrap().action, Action::Index);
assert!(USAGE.lines().count() < 15, "USAGE 不该长回参考手册");
assert!(!USAGE.ends_with('\n'));
}
@@ -972,17 +1089,29 @@ mod tests {
assert!(h.contains(f.long), "help 缺旗标 {}", f.long);
}
}
- assert!(h.contains(SETUP));
+ for (name, summary) in PLAIN {
+ assert!(h.contains(name), "help 缺命令 {name}");
+ assert!(h.contains(summary), "help 缺 {name} 的说明");
+ }
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 的区间没渲染出来");
+ 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 的下界没渲染出来");
+ assert!(
+ h.contains("default 20000, 200–100000"),
+ "show --chars 的下界没渲染出来"
+ );
// AGENT IDS 必须落在 WHEN 与 KEYS 之间,不能被甩到文末
let (when, ids, keys) = (
h.find("\nWHEN:").expect("WHEN"),
@@ -996,14 +1125,28 @@ mod tests {
#[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"));
+ 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"));
+ 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);
+ assert_eq!(
+ CliError {
+ message: "m".into(),
+ with_usage: false
+ }
+ .report()
+ .code,
+ 2
+ );
}
#[test]
@@ -1073,8 +1216,13 @@ mod tests {
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"));
+ assert!(
+ !t.contains("claude mcp add"),
+ "没有 wake-mcp 就不该给 MCP 片段"
+ );
+ assert!(t
+ .trim_end()
+ .ends_with("Note: no Wake index at /tmp/wake.db"));
}
#[test]
diff --git a/crates/wake-core/tests/cli.rs b/crates/wake-core/tests/cli.rs
index 7acf97c..dffbb4f 100644
--- a/crates/wake-core/tests/cli.rs
+++ b/crates/wake-core/tests/cli.rs
@@ -58,7 +58,10 @@ fn env() -> &'static TestEnv {
..Default::default()
})
.unwrap();
- assert!(total > 10, "fixture home should index many sessions ({total})");
+ assert!(
+ total > 10,
+ "fixture home should index many sessions ({total})"
+ );
} // 块尾关写连接:最后一个连接 checkpoint,-wal/-shm 消失,之后
// open_read_only 与字节快照才稳定
TestEnv { db, _home: tmp }
@@ -137,8 +140,18 @@ fn cases() -> Vec<(Vec<String>, &'static str, Value)> {
json!({"query":"二维码","limit":3}),
),
(
- argv(&["search", "二维码", "--project", CLAUDE_PROJECT, "--agent", "claude",
- "--since", ALWAYS, "--limit", "2"]),
+ argv(&[
+ "search",
+ "二维码",
+ "--project",
+ CLAUDE_PROJECT,
+ "--agent",
+ "claude",
+ "--since",
+ ALWAYS,
+ "--limit",
+ "2",
+ ]),
tools::SEARCH,
json!({"query":"二维码","project":CLAUDE_PROJECT,"agents":["claude"],"since":ALWAYS,"limit":2}),
),
@@ -148,15 +161,37 @@ fn cases() -> Vec<(Vec<String>, &'static str, Value)> {
json!({"limit":5}),
),
(
- argv(&["sessions", "--project", CLAUDE_PROJECT, "--agent", "claude,codex",
- "--starred", "--since", ALWAYS, "--limit", "3"]),
+ 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"]),
+ 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}),
@@ -210,7 +245,10 @@ fn every_command_and_flag_is_exercised_end_to_end() {
#[test]
fn bad_arguments_exit_two_and_name_the_problem() {
for (argv, needle) in [
- (vec!["sessions", "--since", "yesterday"], "`since` not understood"),
+ (
+ 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"),
@@ -218,7 +256,10 @@ fn bad_arguments_exit_two_and_name_the_problem() {
(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!["search", "x", "--starred"],
+ "only valid for `sessions`",
+ ),
(vec!["sessions", "--project", "."], "$PWD"),
(vec!["sessions", "myproj"], "takes no arguments"),
] {
@@ -241,7 +282,12 @@ fn bad_arguments_exit_two_and_name_the_problem() {
#[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"})) {
+ 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:?}"),
};
@@ -256,7 +302,10 @@ fn unreadable_session_exits_one() {
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", "--project", "/nope/nope"],
+ "No indexed project matches",
+ ),
(vec!["sessions", "--since", NEVER], "No sessions"),
(vec!["projects", "--since", NEVER], "No projects"),
] {
@@ -266,16 +315,28 @@ fn no_results_is_success() {
}
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}");
+ 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}));
+ 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 根本不开库,
@@ -313,7 +374,10 @@ fn setup_reports_the_binary_and_never_fails() {
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}");
+ assert!(
+ stdout.trim_end().ends_with("launch Wake once to build it"),
+ "{stdout}"
+ );
}
/// Linux 上目录名可以不是 UTF-8,而 `--project "$PWD"` 正是主用法:
@@ -332,7 +396,10 @@ fn non_utf8_arguments_exit_two_instead_of_panicking() {
.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}");
+ assert!(
+ stderr.starts_with("wake-cli: argument is not valid UTF-8"),
+ "{stderr}"
+ );
}
/// SKILL.md 是 CLI 的第二张脸:CLI 改了而它没跟上,agent 就会照着过时的说明
@@ -350,7 +417,11 @@ fn the_skill_stays_in_sync_with_the_cli() {
// Windows CI 按 core.autocrlf=true 检出的 SKILL.md 是 CRLF,硬比 "---\n"
// 会让这条测试在三平台里只红一个
let mut lines = md.lines();
- assert_eq!(lines.next(), Some("---"), "SKILL.md 要以 YAML frontmatter 开头");
+ 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");
@@ -359,7 +430,10 @@ fn the_skill_stays_in_sync_with_the_cli() {
.find_map(|l| l.strip_prefix("description: "))
.expect("frontmatter 缺单行的 `description: …`");
// description 是触发条件,不是名词解释——没有 "Use when" 就等于没有触发器
- assert!(desc.contains("Use when"), "description 要写成触发条件: {desc}");
+ assert!(
+ desc.contains("Use when"),
+ "description 要写成触发条件: {desc}"
+ );
for c in cli::COMMANDS {
assert!(
@@ -369,7 +443,10 @@ fn the_skill_stays_in_sync_with_the_cli() {
);
}
// 最容易被误读的两条约定
- assert!(md.contains("--project \"$PWD\""), "SKILL.md 要交代 --project 的约定");
+ assert!(
+ md.contains("--project \"$PWD\""),
+ "SKILL.md 要交代 --project 的约定"
+ );
assert!(md.contains("wake://session/"), "SKILL.md 要交代引用格式");
assert!(md.contains("read-only"), "SKILL.md 要声明只读");
}
@@ -384,12 +461,39 @@ fn the_cli_never_writes_the_index() {
vec!["search", "二维码"],
vec!["show", CLAUDE_KEY],
vec!["projects"],
+ // index 对**已存在**的库同样不许动一个字节——那道口子只开给"库不存在"
+ vec!["index"],
] {
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"
+ "wake-cli must never write an index that already exists"
);
}
+
+/// 这条口子存在的唯一理由:装了 Wake 但从没启动过。库不存在时建一次,
+/// 建完立刻可查;库已存在就退让给 GUI(上面那条测试卡字节不变)
+#[test]
+fn index_builds_one_from_scratch_then_defers() {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = tmp.path().join("fresh.db");
+
+ let (stdout, stderr, code) = cli_raw(&["--db", db.to_str().unwrap(), "index"]);
+ assert_eq!(code, Some(0), "{stderr}");
+ assert!(db.is_file(), "应当真的建出库来");
+ assert!(stdout.starts_with("Indexed "), "{stdout}");
+
+ // 建完就能查,不必先启动 GUI
+ let (stdout, _, code) = cli_raw(&["--db", db.to_str().unwrap(), "projects"]);
+ assert_eq!(code, Some(0));
+ assert!(stdout.contains("project"), "{stdout}");
+
+ // 第二次是退让,不是重建
+ let bytes = std::fs::read(&db).unwrap();
+ let (stdout, _, code) = cli_raw(&["--db", db.to_str().unwrap(), "index"]);
+ assert_eq!(code, Some(0));
+ assert!(stdout.starts_with("An index already exists"), "{stdout}");
+ assert_eq!(bytes, std::fs::read(&db).unwrap(), "退让时不得改动库");
+}
diff --git a/docs/cli.md b/docs/cli.md
index c447509..e2122a8 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -34,6 +34,7 @@ wake-cli sessions [OPTIONS]
wake-cli show KEY [OPTIONS]
wake-cli projects [OPTIONS]
wake-cli setup
+wake-cli index
wake-cli --help | --version
```
@@ -123,6 +124,20 @@ install anything, or want the guidance to live in the repository.
Neither writes to another tool's configuration; Wake only ever prints.
+### `index`
+
+Builds the index once, for the case where Wake is installed but has never been launched:
+
+```bash
+wake-cli index
+```
+
+It scans the agents' files and writes Wake's index, then tells you what it found. It only
+does this when there is **no index yet** — if one already exists it says so and changes
+nothing, because keeping the index current is the app's job (it watches the files while it
+runs, and Refresh forces a pass). There is deliberately no `--force`: a second full scan
+from outside the app would race the one inside it.
+
## 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.
diff --git a/skills/wake/SKILL.md b/skills/wake/SKILL.md
index 6585d62..fee0936 100644
--- a/skills/wake/SKILL.md
+++ b/skills/wake/SKILL.md
@@ -22,9 +22,15 @@ 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.
+`~/.local/bin/wake-cli` from the tarball; on Windows it sits next to `Wake.exe`.
+
+Two things can be missing, and they need different answers:
+
+- **No binary.** Say so — the user needs [Wake](https://github.com/iAmCorey/Wake).
+ Do not try to install it yourself.
+- **No index** (`no Wake index at … — launch Wake once to build it`). Wake is
+ installed but has never run. Run `wake-cli index` once; it builds the index in a
+ few seconds without opening the app, then retry your query.
## Commands