Skip to content

armgit / Wake

Public Imported from GitHub
0

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

Rust

refactor(cli): move the index-building rule into wake-core

Corey Chiub91b41d2f744
diff --git a/crates/wake-core/src/bin/wake_cli.rs b/crates/wake-core/src/bin/wake_cli.rs
index fe6e233..5a9f775 100644
--- a/crates/wake-core/src/bin/wake_cli.rs
+++ b/crates/wake-core/src/bin/wake_cli.rs
@@ -5,24 +5,26 @@
//! wake-cli show KEY [OPTIONS] 读一份转录
//! wake-cli projects [OPTIONS] 有会话历史的项目
//! wake-cli setup 路径、进 PATH、给 agent 的说明
+//! wake-cli index 库不存在时建一次(见 scanner::build_index)
//! wake-cli --version | --help
//!
//! 输出就是 MCP 工具那份文本、一字不改(tests/cli.rs 逐字节卡),所以 docs 与
//! 将来的 Skill 只需描述一份格式。解析在 `wake_core::cli`,这里只做 I/O 与退
-//! 出码。索引库只读打开,绝不 open_or_rebuild、不扫描、不写。
+//! 出码。索引库一律只读打开(`mcp::open_index`),**绝不 open_or_rebuild**;
+//! 唯一的写是 `index` 子命令——库不存在时建一次,规矩与理由在
+//! `scanner::build_index`,别在这里复述或放宽。
//!
//! **结果不许走 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::path::{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::scanner::{self, NullEvents};
use wake_core::text::plural;
fn main() -> ExitCode {
@@ -52,7 +54,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::Index => write(cli::report(index(&db_path(&inv.db)))),
Action::Tool { tool, args } => run(&inv.db, tool, &args),
}
}
@@ -90,42 +92,25 @@ 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!(
+/// 建一次索引,然后说一句人话。建不建、凭什么敢建全在 `scanner::build_index`,
+/// 这里只剩措辞。场景是"装了 Wake 但从没启动过":skill 让 agent 跑这一条自救。
+/// 失败一律走 `?`(anyhow → `ToolError::Internal`)交 `cli::report` 收场——
+/// "跑起来了然后失败"退 1,与工具调用失败同一条出口,不另写一份映射
+fn index(path: &Path) -> Result<String, tools::ToolError> {
+ let Some(store) = scanner::build_index(path, &NullEvents)? else {
+ 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!(
+ })?
+ .1;
+ let agents = store.agent_counts()?.len() as i64;
+ 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),
@@ -134,15 +119,6 @@ fn index(db: &Option<PathBuf>) -> Report {
))
}
-/// 跑起来了然后失败 → 退 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 4f4b109..acce2f0 100644
--- a/crates/wake-core/src/cli.rs
+++ b/crates/wake-core/src/cli.rs
@@ -85,16 +85,29 @@ pub struct CommandSpec {
}
/// 不走 `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",
- ),
+/// COMMANDS 与 `tools::definitions()` 的双射
+#[derive(Debug)]
+struct PlainSpec {
+ name: &'static str,
+ /// **`Action` 就在表里**——所以 parse 不必在末尾按名字再认一遍,加一行
+ /// 忘了配 match 这种事从此不存在(那是运行时 panic、退 101,而这个 bin
+ /// 的两处显眼设计 args_os 与 cli::emit 都是为了永不退 101)
+ action: Action,
+ summary: &'static str,
+}
+
+/// 加一个子命令只在这里加一行
+const PLAIN: &[PlainSpec] = &[
+ PlainSpec {
+ name: "setup",
+ action: Action::Setup,
+ summary: "print this binary's path and how to point an agent at it",
+ },
+ PlainSpec {
+ name: "index",
+ action: Action::Index,
+ summary: "build the index once, when Wake has never run here",
+ },
];
const F_PROJECT: FlagSpec = FlagSpec::new(
@@ -282,8 +295,9 @@ impl CliError {
}
}
-/// 工具结果 → 写哪条流、什么退出码。三个变体全列、不写 `_`:ToolError 加变体
-/// 时这里编译不过,正是要的
+/// 结果 → 写哪条流、什么退出码。CLI **唯一**的这份映射:工具调用与 `index`
+/// 都从这里收场,别在 bin 里另写一个 `fail()`。三个变体全列、不写 `_`:
+/// ToolError 加变体时这里编译不过,正是要的
pub fn report(result: Result<String, tools::ToolError>) -> Report {
match result {
Ok(text) => Report {
@@ -376,8 +390,9 @@ fn check_project(v: &str) -> Result<(), String> {
#[derive(Clone, Copy)]
enum Seen {
Nothing,
- /// PLAIN 表里的子命令,按名字记
- Plain(&'static str),
+ /// PLAIN 表里的子命令。与下面一行同形:**存表行、不存名字**,下游就不必
+ /// 再认一遍(`&'static` 引用恒 Copy,`Action` 不 Copy 不碍事)
+ Plain(&'static PlainSpec),
Command(&'static CommandSpec),
}
@@ -429,7 +444,10 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
let cmd = match seen {
Seen::Command(c) => c,
Seen::Plain(p) => {
- return Err(err(format!("{p} takes no options (got {name})"), true))
+ return Err(err(
+ format!("{} takes no options (got {name})", p.name),
+ true,
+ ))
}
Seen::Nothing => return Err(misplaced(name, false)),
};
@@ -466,18 +484,23 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
}
// 3) 位置参数:第一个是命令名
match seen {
- 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
- .iter()
- .find(|c| c.name == s)
- .ok_or_else(|| err(format!("unknown command {s}"), true))?,
- )
+ seen = match PLAIN.iter().find(|p| p.name == s) {
+ Some(p) => Seen::Plain(p),
+ None => Seen::Command(
+ COMMANDS
+ .iter()
+ .find(|c| c.name == s)
+ .ok_or_else(|| err(format!("unknown command {s}"), true))?,
+ ),
+ }
+ }
+ Seen::Plain(p) => {
+ return Err(err(
+ format!("{} takes no arguments (got `{s}`)", p.name),
+ 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(
@@ -499,19 +522,12 @@ pub fn parse(argv: &[String]) -> Result<Invocation, CliError> {
}
}
let cmd = match seen {
- Seen::Plain("setup") => {
- return Ok(Invocation {
- db,
- action: Action::Setup,
- })
- }
- Seen::Plain("index") => {
+ Seen::Plain(p) => {
return Ok(Invocation {
db,
- action: Action::Index,
+ action: p.action.clone(),
})
}
- Seen::Plain(other) => unreachable!("PLAIN 表加了 {other} 但没在这里给 Action"),
Seen::Nothing => return Err(err("needs a command".into(), true)),
Seen::Command(c) => c,
};
@@ -677,8 +693,8 @@ pub fn help() -> String {
CMD_COL,
));
}
- for (name, summary) in PLAIN {
- out.push_str(&row(format!(" wake-cli {name}"), summary, CMD_COL));
+ for p in PLAIN {
+ out.push_str(&row(format!(" wake-cli {}", p.name), p.summary, CMD_COL));
}
out.push_str(HELP_GLOBALS);
for c in COMMANDS {
@@ -910,7 +926,7 @@ mod tests {
#[test]
fn no_duplicate_flag_or_command_names() {
let mut names: Vec<&str> = COMMANDS.iter().map(|c| c.name).collect();
- names.extend(PLAIN.iter().map(|(n, _)| *n));
+ names.extend(PLAIN.iter().map(|p| p.name));
names.sort_unstable();
let n = names.len();
names.dedup();
@@ -1089,9 +1105,9 @@ mod tests {
assert!(h.contains(f.long), "help 缺旗标 {}", f.long);
}
}
- for (name, summary) in PLAIN {
- assert!(h.contains(name), "help 缺命令 {name}");
- assert!(h.contains(summary), "help 缺 {name} 的说明");
+ for p in PLAIN {
+ assert!(h.contains(p.name), "help 缺命令 {}", p.name);
+ assert!(h.contains(p.summary), "help 缺 {} 的说明", p.name);
}
for a in AgentId::ALL {
assert!(h.contains(a.as_str()), "help 缺 agent {}", a.as_str());
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index 95ed3c8..467e883 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -254,7 +254,8 @@ impl Store {
/// 只读打开既有索引库(wake-mcp 这类旁路读者用):不建表、不迁移、不改
/// journal_mode;库不存在或 schema 太老直接报错——重建权只归 GUI 的
- /// `open_or_rebuild`,旁路进程绝不能把正在被 GUI 写的库挪走重建。
+ /// `open_or_rebuild`,旁路进程绝不能把正在被 GUI 写的库挪走重建
+ /// (唯一的例外是**库根本不存在**时建一个:`scanner::build_index`)。
/// WAL 下读者不阻塞 GUI 写入;只读连接要能建 -shm,同用户下目录可写即可
pub fn open_read_only(path: &Path) -> Result<Self> {
if !path.is_file() {
diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rs
index f979e37..d867c31 100644
--- a/crates/wake-core/src/scanner.rs
+++ b/crates/wake-core/src/scanner.rs
@@ -59,6 +59,30 @@ impl Drop for ScanFinale<'_> {
/// into_inner 照常放行。排在后面的照常出终态事件,UI 只是多等一会儿
static SCAN_GATE: std::sync::Mutex<()> = std::sync::Mutex::new(());
+/// 从零建一次索引:**只在索引文件不存在时**建,已经有库就原样留给 GUI
+/// (`Ok(None)`)。这是 "重建权只归 GUI 的 `open_or_rebuild`"(db.rs)唯一的
+/// 例外,场景是"装了 Wake 但从没启动过"——此时库根本不存在,没有任何写入方
+/// 可冲突,这就是全部的安全论证。**别据此加 --force**:上面那把 `SCAN_GATE`
+/// 只是**进程级**互斥,对"GUI 正在写这个库"毫无办法。
+/// 放在 scanner 而不是某个 bin 里:这条规矩是扫描侧的,`wake-mcp` 与
+/// `wake-cli` 的只读那一半仍归 `mcp::open_index`
+pub fn build_index(path: &std::path::Path, events: &dyn ScanEvents) -> Result<Option<Arc<Store>>> {
+ if path.exists() {
+ return Ok(None);
+ }
+ // 主库不在、WAL/SHM 还躺着:留下任何一个,新库都会接着读旧日志
+ // (与 `open_or_rebuild` 挪走三件套同一条理由)
+ for suffix in ["-wal", "-shm"] {
+ let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
+ }
+ // Store::open 会 create_dir_all 父目录并跑迁移,不必在调用方先建一遍
+ let store = Arc::new(Store::open(path)?);
+ // 不变量 8⑥:按库里的 location 配置建 roster(新库即内置全家)
+ let adapters = crate::adapters::create_adapters_for(&store);
+ run_scan(&adapters, &store, events, true)?;
+ Ok(Some(store))
+}
+
/// 全量/增量扫描。quickMeta 先行秒出列表,然后按 mtime 降序逐文件解析。
/// 阻塞执行——调用方放后台线程。进度与终态一律经 `events` 上报,终态由
/// `ScanFinale` 保证送达;返回的 `Result` 只用于调用方自己记日志。
diff --git a/crates/wake-core/tests/cli.rs b/crates/wake-core/tests/cli.rs
index dffbb4f..1bc184a 100644
--- a/crates/wake-core/tests/cli.rs
+++ b/crates/wake-core/tests/cli.rs
@@ -451,9 +451,10 @@ fn the_skill_stays_in_sync_with_the_cli() {
assert!(md.contains("read-only"), "SKILL.md 要声明只读");
}
-/// 一旦有人把 Store::open / open_or_rebuild 摸进来,这条就红
+/// 一旦有人把 open_or_rebuild 摸进来,或者把 `index` 那道口子放宽到已存在的
+/// 库上,这条就红
#[test]
-fn the_cli_never_writes_the_index() {
+fn the_cli_never_writes_an_index_that_exists() {
let db = &env().db;
let before = std::fs::read(db).unwrap();
for argv in [
@@ -473,27 +474,42 @@ fn the_cli_never_writes_the_index() {
);
}
-/// 这条口子存在的唯一理由:装了 Wake 但从没启动过。库不存在时建一次,
-/// 建完立刻可查;库已存在就退让给 GUI(上面那条测试卡字节不变)
+/// 这条口子存在的唯一理由:装了 Wake 但从没启动过。库不存在时建一次、建完
+/// 立刻可查;库已存在就退让(字节不变那一半由上面那条卡)。
+///
+/// **先 `env()` 再 spawn**:它建 fixture home 并钉住 WAKE_HOME/HOME 给子进程
+/// 继承。不走这一步,子进程扫的就是维护者真实的家目录——本机十秒、还把真实
+/// 索引整个拷进 tempdir,而 CI 上家目录是空的,`starts_with("Indexed ")` 对
+/// "Indexed 0 sessions" 照样为真,整条用例空过
#[test]
fn index_builds_one_from_scratch_then_defers() {
+ let want = Store::open_read_only(&env().db)
+ .unwrap()
+ .list_sessions(&SessionFilter {
+ limit: 1,
+ ..Default::default()
+ })
+ .unwrap()
+ .1;
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}");
+ // 这个功能的主张就是这一句:CLI 自己建的索引 == GUI 从同一棵树建的那个
+ assert!(
+ stdout.starts_with(&format!("Indexed {want} session")),
+ "应当与 fixture 库同样收录 {want} 条:{stdout}"
+ );
// 建完就能查,不必先启动 GUI
let (stdout, _, code) = cli_raw(&["--db", db.to_str().unwrap(), "projects"]);
assert_eq!(code, Some(0));
- assert!(stdout.contains("project"), "{stdout}");
+ assert!(stdout.contains(CLAUDE_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 e2122a8..d3ed4c4 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -4,7 +4,7 @@
It prints what an MCP client is given: the two surfaces call the same code, and the test suite asserts their output byte for byte apart from a trailing newline the CLI adds (see [Output](#output)). 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.
+Nothing here can modify a session. The CLI opens Wake's index without write access and never touches the agents' own files except to read a transcript. It has exactly one way to write: [`wake-cli index`](#index) builds an index when there is none yet. It never rebuilds one that exists — that stays the app's job.
## Where it lives
@@ -172,7 +172,7 @@ Exactly one trailing newline is added when the text does not already end with on
| `1` | it ran and failed — unknown or ambiguous key, a transcript that would not parse, a query that errored, or a failed write to stdout |
| `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 go to stderr, prefixed `wake-cli: `, so `wake-cli show <key> > out.md` cannot capture one. `setup` is the exception in both directions: it always exits `0`, even with no index, and reports a missing one as a `Note:` line on stdout — "not set up yet" is the normal state for someone running it.
+Empty results are never an error, so `wake-cli search x || fallback` does not fire just because nothing was ever discussed about `x`. Diagnostics go to stderr, prefixed `wake-cli: `, so `wake-cli show <key> > out.md` cannot capture one. Two commands treat a missing index as normal rather than as the `2` above. `setup` always exits `0`, even with no index, and reports a missing one as a `Note:` line on stdout — "not set up yet" is the normal state for someone running it. `index` exits `0` both when it builds one and when it declines because one already exists; a build that starts and then fails exits `1`.
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 exits `1` for anything the tool layer rejects — its JSON-RPC envelope already carries the classification, so the exit code never had to. (`wake-mcp` still uses `2` for its own argv problems: a missing tool name, unparsable JSON, or an index it cannot open.)
@@ -180,12 +180,12 @@ Both a mistyped option (`--sinse 7d`) and a value the tools reject (`--since 7dd
- 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.
+- Wake's read-only rules apply: other agents' directories and databases are opened read-only and credential files are never read. Every command except `index` opens Wake's own index without write access too, and a test asserts that an index which already exists never changes by a byte — including when `index` itself is the command.
- 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 Wake index at … — launch Wake once to build it`.** Wake has never run on this machine, or `--db` points at the wrong file. If Wake is installed but has never been launched, `wake-cli index` builds the index from a terminal instead. `… 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`.