All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
feat(cli): wake-cli refresh and a cross-process index lock (#43)
Corey Chiub07cf5762217
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f8b1d4a..107f6b2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## [Unreleased]++- New: `wake-cli refresh` updates an existing index from the terminal, so a scheduled task (launchd, systemd timer) keeps search and session lists fresh while Wake is closed; it does nothing while Wake is running, and Wake waits for a running refresh before opening the index (#43, thanks @aka-kika)+## [0.8.0] — 2026-09-22- New: Memory page — the notes coding agents keep for themselves (Claude Code's auto-memory, Codex's memories and per-session summaries, ZCode's project memory) and the instruction files you write for them (CLAUDE.md, AGENTS.md, GEMINI.md, `.cursor/rules`, `.kiro/steering`, `copilot-instructions.md`, global and per project) in one read-only place, searchable, filtered by agent, project or user memorydiff --git a/PRODUCT.md b/PRODUCT.mdindex 3e519bc..10630eb 100644--- a/PRODUCT.md+++ b/PRODUCT.md@@ -28,7 +28,7 @@ Corey 本人(独立开发者,主力工具 Claude Code 与 Codex,中文为主)。## Capabilities and Constraints-已实现:十九家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;2026-09-03 加 Last 7 days 周对比行与 Over time 近 53 周按 agent 堆叠的每周 prompts 趋势图;口径=主线用户消息,规格见 DESIGN.md)、Updates 页与 macOS Wake 菜单手动检查 GitHub 最新正式版并打开 Release 页更新(不后台联网、不自动替换应用包)、测试套件(adapter 契约、DB 往返、scanner 回归 + CI 三平台 + pre-commit,合成 fixture)、三端桌面(macOS 主平台;Linux/Windows experimental,终端恢复/废纸篓·回收站/剪贴板按平台原生实现,发版 CI 自动出六产物)、窗口记忆(0.3.6:记住所在屏幕/屏内位置/最大化/全屏,重启与 Dock 重开都回到原处,Settings 开在主窗所在屏)、完整 macOS 菜单栏(0.3.6:标准 Edit/Window 菜单、⌘W、Window → Main Window,主窗关闭后 About/Settings/Updates 仍可用)、导出 Markdown 与保存图片走系统「另存为」并记住上次目录(0.3.6,issue #25)、远程 host(0.4.0,issue #21:Settings → Remote hosts 配 SSH 目标,rsync 白名单镜像会话数据到本地缓存后与本地会话同列同搜,`@host` 徽章标识;阶段 1 只读——不动远端文件、远程会话禁删,resume 以 Copy SSH command 形态提供;分期计划见 CLAUDE.md「远程 host」节)、**MCP 接入**(0.5.0:随应用打包的只读 `wake-mcp` stdio server,四个工具 wake_search / wake_list_sessions / wake_get_session / wake_list_projects,Claude Code / Codex / Cursor 等任何 MCP 客户端可搜历史、按项目列会话、分页读转录;Settings → Connect 展示路径与可复制配置片段,只展示不代写别家配置;零 LLM、零网络、不写库;完整参考 docs/mcp.md)、**命令行与 Skill**(0.6.0:并排打包的只读 `wake-cli`,四个子命令 search / sessions / show / projects 加 setup,给"能跑 shell 但不说 MCP"的 agent 和真人用——它不新写查询逻辑,argv 翻成 JSON 喂同一批工具,输出与 MCP 客户端看到的**逐字节相同**(仅 CLI 末尾补一个换行)并由测试卡住,所以文档只需描述一份格式;`skills/wake/SKILL.md` 是可一行安装的 skill(`npx skills add iAmCorey/Wake`),用触发条件而非名词解释写 description,让 agent 自己想得起来去翻会话历史;完整参考 docs/cli.md;0.6.3 加 `wake-cli index`——装了 Wake 却从没启动过时,agent 自己跑一条就能把索引建起来继续干活,而不是停下来问人。它**只建不存在的索引**,已有的库原样交给 GUI:扫描落在旁边的临时库、扫完才原子占位,所以被中途杀掉可重试、撞上 GUI 首扫就退让)、Connect 页四区块(0.6.1:MCP server / MCP clients / Command line / Skill,每个面的第一块挂自己的文档链接)、**记忆可见层**(2026-09-17 起,只读:把各家 agent 自己写下的记忆——Claude Code 的按项目 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的按项目记忆——按项目聚合;GUI 的 Memory 页是侧栏底部的整页目的地,侧栏在这一页换成按记忆计数的 All Memory / Agents / Projects 导航;MCP 加第五个工具 `wake_list_memories`,`wake_get_session` 认 `wake://memory/…` 引用现场读文件,`wake_search` 末尾附记忆命中;CLI 加 `memories`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。二期(2026-09-21)把用户写给 agent 的指令文件也收进来:各家 home 里的 CLAUDE.md / AGENTS.md(与 `rules/*.rules`)/ GEMINI.md,以及已索引项目根下的 CLAUDE.md / AGENTS.md / GEMINI.md / `.cursor/rules` / `.cursorrules` / `.kiro/steering` / `.github/copilot-instructions.md`,与记忆同列同搜、不另作区分;Settings 加 Memory locations 页,与 Session locations 同形制:逐来源开关、添加自定义目录或文件、Restore defaults。不编辑、不同步、不删除——写别家数据破铁律,要改一个 Reveal 就到;也不做"把会话自动写成记忆")。后续边界(2026-09-07 定):摘要层(需 LLM、opt-in、明示会把会话正文发给用户配置的端点)只在 MCP 接入有真实使用之后再做;Timeline / Profile 一类视图建立在摘要之上;不做 ChatGPT / Claude.ai 导出导入主线、不做实体本体与知识图谱、不做 Chrome 扩展注入。+已实现:十九家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;2026-09-03 加 Last 7 days 周对比行与 Over time 近 53 周按 agent 堆叠的每周 prompts 趋势图;口径=主线用户消息,规格见 DESIGN.md)、Updates 页与 macOS Wake 菜单手动检查 GitHub 最新正式版并打开 Release 页更新(不后台联网、不自动替换应用包)、测试套件(adapter 契约、DB 往返、scanner 回归 + CI 三平台 + pre-commit,合成 fixture)、三端桌面(macOS 主平台;Linux/Windows experimental,终端恢复/废纸篓·回收站/剪贴板按平台原生实现,发版 CI 自动出六产物)、窗口记忆(0.3.6:记住所在屏幕/屏内位置/最大化/全屏,重启与 Dock 重开都回到原处,Settings 开在主窗所在屏)、完整 macOS 菜单栏(0.3.6:标准 Edit/Window 菜单、⌘W、Window → Main Window,主窗关闭后 About/Settings/Updates 仍可用)、导出 Markdown 与保存图片走系统「另存为」并记住上次目录(0.3.6,issue #25)、远程 host(0.4.0,issue #21:Settings → Remote hosts 配 SSH 目标,rsync 白名单镜像会话数据到本地缓存后与本地会话同列同搜,`@host` 徽章标识;阶段 1 只读——不动远端文件、远程会话禁删,resume 以 Copy SSH command 形态提供;分期计划见 CLAUDE.md「远程 host」节)、**MCP 接入**(0.5.0:随应用打包的只读 `wake-mcp` stdio server,四个工具 wake_search / wake_list_sessions / wake_get_session / wake_list_projects,Claude Code / Codex / Cursor 等任何 MCP 客户端可搜历史、按项目列会话、分页读转录;Settings → Connect 展示路径与可复制配置片段,只展示不代写别家配置;零 LLM、零网络、不写库;完整参考 docs/mcp.md)、**命令行与 Skill**(0.6.0:并排打包的只读 `wake-cli`,四个子命令 search / sessions / show / projects 加 setup,给"能跑 shell 但不说 MCP"的 agent 和真人用——它不新写查询逻辑,argv 翻成 JSON 喂同一批工具,输出与 MCP 客户端看到的**逐字节相同**(仅 CLI 末尾补一个换行)并由测试卡住,所以文档只需描述一份格式;`skills/wake/SKILL.md` 是可一行安装的 skill(`npx skills add iAmCorey/Wake`),用触发条件而非名词解释写 description,让 agent 自己想得起来去翻会话历史;完整参考 docs/cli.md;0.6.3 加 `wake-cli index`——装了 Wake 却从没启动过时,agent 自己跑一条就能把索引建起来继续干活,而不是停下来问人。它**只建不存在的索引**,已有的库原样交给 GUI:扫描落在旁边的临时库、扫完才原子占位,所以被中途杀掉可重试、撞上 GUI 首扫就退让;2026-09-22 加 `wake-cli refresh`,issue #43:app 不开时增量刷新已有索引,给靠 MCP / CLI 用 Wake、只在浏览时开 app 的人用 launch agent / systemd timer 定时跑,Wake 在跑就退让——GUI 与两个写命令共用一把索引写锁,GUI 启动会等正在跑的 refresh 收尾)、Connect 页四区块(0.6.1:MCP server / MCP clients / Command line / Skill,每个面的第一块挂自己的文档链接)、**记忆可见层**(2026-09-17 起,只读:把各家 agent 自己写下的记忆——Claude Code 的按项目 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的按项目记忆——按项目聚合;GUI 的 Memory 页是侧栏底部的整页目的地,侧栏在这一页换成按记忆计数的 All Memory / Agents / Projects 导航;MCP 加第五个工具 `wake_list_memories`,`wake_get_session` 认 `wake://memory/…` 引用现场读文件,`wake_search` 末尾附记忆命中;CLI 加 `memories`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。二期(2026-09-21)把用户写给 agent 的指令文件也收进来:各家 home 里的 CLAUDE.md / AGENTS.md(与 `rules/*.rules`)/ GEMINI.md,以及已索引项目根下的 CLAUDE.md / AGENTS.md / GEMINI.md / `.cursor/rules` / `.cursorrules` / `.kiro/steering` / `.github/copilot-instructions.md`,与记忆同列同搜、不另作区分;Settings 加 Memory locations 页,与 Session locations 同形制:逐来源开关、添加自定义目录或文件、Restore defaults。不编辑、不同步、不删除——写别家数据破铁律,要改一个 Reveal 就到;也不做"把会话自动写成记忆")。后续边界(2026-09-07 定):摘要层(需 LLM、opt-in、明示会把会话正文发给用户配置的端点)只在 MCP 接入有真实使用之后再做;Timeline / Profile 一类视图建立在摘要之上;不做 ChatGPT / Claude.ai 导出导入主线、不做实体本体与知识图谱、不做 Chrome 扩展注入。约束:对 agent 数据目录只读;绝不写 Codex 的 SQLite;不读凭证;GPUI 无 SF Symbols(图标用 lucide SVG 自备)。已支持十九家 agent:Claude Code、Codex(0.6.6 起排除可识别的内部线程:guardian auto-review、`/review`、compaction、memory consolidation 与用户会话同树,adapter 文件边界按首行 session_meta 的 source / thread_source 认出即不枚举;老格式或读不出的首行保守放行,`codex exec --thread-source` 打了标签的自动化线程照常收录,issue #30。`spawn_agent` 子代理是其中唯一的例外,issue #42:那是用户自己派出去的活,收录后挂在派它的会话下面、以任务名为标题,fork 进来的父线程历史折成一条不入库的占位,父会话的对话不会被索引两遍)、Qoder CLI(`~/.qoder/projects` JSONL,active-leaf 分支恢复、tool result 回挂、`QODER_CONFIG_DIR`)、Copilot CLI、Cursor(CLI 转录 + 0.6.7 起 IDE Chat/Composer 历史,PR #32:`globalStorage/state.vscdb` 明文 KV 库,composerData 给顺序、bubbleId 行给正文;转录带正文的会话归转录源,库只补转录缺失或只剩 turn_ended 空壳的会话;库里多数老会话没存工作区路径,落 Unknown project)、OpenCode(含 OpenCode 2 next,stable 的 `opencode.db` 与 next 的 `opencode-next.db` 同时扫描;逐会话兼容 `message+part`、真实 `session+session_message` 及早期 `session_v2` schema;preview 会话标 opencode2 徽章)、Kiro、Gemini CLI(2026-08-17 P1 五家落地)+ Pi、Oh My Pi、Grok Build、Kimi Code、Antigravity CLI(2026-08-19 对齐 kooky 内置 roster;Antigravity 正文加密仅元数据卡片)+ DeepSeek Harness(dsh,2026-08-20,zstd 事件日志透明解压;格式由源码推断,当天用户跑出真实会话完成首验)+ Hermes Agent(2026-09-03,多档案 state.db,无 cwd 故 project 留空)、OpenClaw(2026-09-03,两代存储同扫;本机零会话,格式由源码推断未经真机验证)、CodeBuddy(2026-09-14,issue #27:`~/.codebuddy/projects` 的 Responses 形 JSONL,custom / ai / topic 三级标题,`CODEBUDDY_CONFIG_DIR`;本机零会话,格式由官方 CLI 文档与三家第三方实现交叉推断、未经真机验证)、WorkBuddy(同日,CodeBuddy 的孪生实例:同一解析核心,`~/.workbuddy/projects`、`WORKBUDDY_CONFIG_DIR`;桌面 app 无 CLI,不提供 resume;同构只有 cc-switch 一家佐证)、ZCode(2026-09-21:Z.ai 的 GLM-5.3 官方 harness,桌面 app;运行时是 OpenCode 衍生物——`~/.zcode/cli/db/db.sqlite` 的 session/message/part 与 OpenCode v1 同形、part 解码复用,但 session 表没有 model/tokens 列故另起一家;`v2/tasks-index.sqlite` 只借 deleted / migration_source 两个过滤位;按 `task_type` 白名单只列 interactive / fork / selection_side_chat(subagent_child 等运行时会话不列);`semantics.transcriptVisibility == hidden` 与用户消息 `origin != real_user` 归 Meta、compact_summary 折成一条、字段缺席放行;`ZCODE_STORAGE_DIR`;桌面 app 无 CLI、`zcode://` 没有按会话打开的深链,不提供 resume;本机 3.14.0 真会话首验通过,同日开源(Apache-2.0)后语义全部按源码核对)。做不了的:Windsurf/Trae 加密,Amp/Factory(Droid)/Warp 云端无本地数据,Reasonix 本机零会话格式未实测。diff --git a/README.md b/README.mdindex 10c4688..1de56cb 100644--- a/README.md+++ b/README.md@@ -105,7 +105,7 @@ 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 rebuilds it; there are no delete or star tools (the one thing it can write is Wake's own data directory, which resolving the default index path creates)-- 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)+- Search and lists come from Wake's index, so keep Wake running for fresh results, or schedule `wake-cli refresh` for the times it is closed — 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@@ -120,6 +120,7 @@ wake-cli sessions --project "$PWD" --limit 5 # what happened in this repowake-cli search "rate limiter" --project "$PWD" # where was this discussedwake-cli show 'claude-code:1b2c3d4e-…' # read that transcriptwake-cli setup # path, PATH setup, and a block to paste into CLAUDE.md+wake-cli refresh # update the index while Wake is closed — schedule it```It prints what the MCP tools return, asserted byte for byte in the test suite apart from a trailing newline the CLI adds, so an agent driving it through a shell sees what a connected one does. Full reference in [docs/cli.md](docs/cli.md).diff --git a/crates/wake-core/src/bin/scan.rs b/crates/wake-core/src/bin/scan.rsindex 3804130..d4eae7d 100644--- a/crates/wake-core/src/bin/scan.rs+++ b/crates/wake-core/src/bin/scan.rs@@ -3,7 +3,7 @@use anyhow::Result;use std::sync::Arc;use wake_core::adapters::create_adapters_for;-use wake_core::db::Store;+use wake_core::db::{IndexLock, Ownership, Store};use wake_core::models::SessionFilter;use wake_core::scanner::{run_scan, NullEvents, ScanEvents, ScanProgress};@@ -26,6 +26,14 @@ fn main() -> Result<()> {wake_core::db::default_db_path()};eprintln!("DB: {}", db_path.display());+ // 写真实索引的进程都得持 IndexLock(`Store::open` 的约定):GUI 在跑就别扫+ let _lock = match IndexLock::try_acquire(&db_path, "scan")? {+ Ownership::Ours(lock) => lock,+ Ownership::Held(holder) => anyhow::bail!(+ "index at {} is held by {holder}; quit Wake first, or use --tmp",+ db_path.display()+ ),+ };let store = Arc::new(Store::open(&db_path)?);// 必须带上库里的 location 配置:默认 roster 会把自定义根会话当已删清掉diff --git a/crates/wake-core/src/bin/wake_cli.rs b/crates/wake-core/src/bin/wake_cli.rsindex 324f12e..fe07dc6 100644--- a/crates/wake-core/src/bin/wake_cli.rs+++ b/crates/wake-core/src/bin/wake_cli.rs@@ -1,4 +1,4 @@-//! wake-cli:从终端查 Wake 的会话索引(只读)。+//! wake-cli:从终端查 Wake 的会话索引(查询只读;`index` / `refresh` 写它)。//!//! wake-cli search QUERY [OPTIONS] 全文搜索//! wake-cli sessions [OPTIONS] 最近的会话@@ -6,13 +6,14 @@//! wake-cli projects [OPTIONS] 有会话历史的项目//! wake-cli setup 路径、进 PATH、给 agent 的说明//! wake-cli index 库不存在时建一次(见 scanner::build_index)+//! wake-cli refresh 库已在、Wake 没开时增量刷一轮(见 scanner::refresh_index)//! wake-cli --version | --help//!//! 输出就是 MCP 工具那份文本、一字不改(tests/cli.rs 逐字节卡),所以 docs 与//! 将来的 Skill 只需描述一份格式。解析在 `wake_core::cli`,这里只做 I/O 与退-//! 出码。索引库一律只读打开(`mcp::open_index`),**绝不 open_or_rebuild**;-//! 唯一的写是 `index` 子命令——库不存在时建一次,规矩与理由在-//! `scanner::build_index`,别在这里复述或放宽。+//! 出码。查询一律只读打开索引(`mcp::open_index`),**绝不 open_or_rebuild**;+//! 写库的只有 `index` 与 `refresh` 两个子命令,都先拿 `db::IndexLock`——规矩与+//! 理由在 `scanner::build_index` / `refresh_index`,别在这里复述或放宽。//!//! **结果不许走 println!**:Rust 忽略 SIGPIPE,`wake-cli show K | head` 会让//! println! panic 成 101。所有输出统一经 cli::emit,BrokenPipe 由 write 收场。@@ -21,11 +22,9 @@ use std::path::{Path, PathBuf};use std::process::ExitCode;use wake_core::cli::{self, Action, CliError, Report, Stream};-use wake_core::db::{self, Store};+use wake_core::db::{self, LockHolder, Store};use wake_core::mcp::{self, tools};-use wake_core::models::SessionFilter;-use wake_core::scanner::{self, NullEvents, ScanEvents, ScanProgress};-use wake_core::text::plural;+use wake_core::scanner::{self, NullEvents, Outcome, ScanEvents, ScanProgress, Skip};fn main() -> ExitCode {// args()(而非 args_os)对非 UTF-8 参数是 panic,退出码 101 —— Linux 上@@ -54,7 +53,8 @@ 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(cli::report(index(&db_path(&inv.db)))),+ Action::Index => write(index(&db_path(&inv.db))),+ Action::Refresh => write(refresh(&db_path(&inv.db))),Action::Tool { tool, args } => run(&inv.db, tool, &args),}}@@ -78,13 +78,7 @@ fn run(db: &Option<PathBuf>, tool: &str, args: &serde_json::Value) -> ExitCode {// 或太老由 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,- })- }+ Err(e) => return write(refuse(e)),};let cache = tools::TranscriptCache::default();write(cli::report(tools::invoke(@@ -93,40 +87,90 @@ fn run(db: &Option<PathBuf>, tool: &str, args: &serde_json::Value) -> ExitCode {}/// 建一次索引,然后说一句人话。建不建、凭什么敢建全在 `scanner::build_index`,-/// 这里只剩措辞。场景是"装了 Wake 但从没启动过":skill 让 agent 跑这一条自救。-/// 失败一律走 `?`(anyhow → `ToolError::Internal`)交 `cli::report` 收场——-/// "跑起来了然后失败"退 1,与工具调用失败同一条出口,不另写一份映射-fn index(path: &Path) -> Result<String, tools::ToolError> {- // 进度只给终端看:全量扫描要几秒到几十秒,没有反馈像卡死;管道与 agent- // 调用时 stderr 保持安静(它是诊断通道,tests/cli.rs 也这么断言)- let events: &dyn ScanEvents = if io::stderr().is_terminal() {+/// 这里只剩措辞。场景是"装了 Wake 但从没启动过":skill 让 agent 跑这一条自救+fn index(path: &Path) -> Report {+ match scanner::build_index(path, progress_events()) {+ Ok(Outcome::Done(tally)) => cli::report(Ok(format!(+ "Indexed {tally} into {}.\n\+ Launch Wake to keep it current — it watches the agents' files while it runs. \+ With the app closed, `wake-cli refresh` brings the index up to date.",+ path.display()+ ))),+ Ok(Outcome::Skipped(skip)) => skipped(path, skip),+ Ok(Outcome::Busy(holder)) => cli::report(Ok(busy_text(&holder))),+ Err(e) => cli::report(Err(e.into())),+ }+}++/// 增量刷一轮已有的索引,然后说一句人话。刷不刷、凭什么敢刷全在 `scanner::refresh_index`+fn refresh(path: &Path) -> Report {+ match scanner::refresh_index(path, progress_events()) {+ Ok(Outcome::Done(tally)) => cli::report(Ok(format!(+ "Refreshed the index at {}: {tally}.",+ path.display()+ ))),+ Ok(Outcome::Skipped(skip)) => skipped(path, skip),+ Ok(Outcome::Busy(holder)) => cli::report(Ok(busy_text(&holder))),+ Err(e) => cli::report(Err(e.into())),+ }+}++/// 没干活的缘由翻成人话:库已在是正常收场(退 0);其余三种都是 `--db` 拿错了路径——与+/// 查询命令的缺库同款,退 2。"跑起来了然后失败"的那类(退 1)全在 `cli::report`+fn skipped(path: &Path, skip: Skip) -> Report {+ match skip {+ Skip::Exists => cli::report(Ok(format!(+ "An index already exists at {}. Launch Wake to update or rebuild it, \+ or run `wake-cli refresh` while Wake is closed.",+ path.display()+ ))),+ Skip::Missing => refuse(format!(+ "{}, or run `wake-cli index`",+ db::missing_index(path)+ )),+ Skip::NotAnIndex => refuse(format!(+ "{} is not a Wake index — pass Wake's own database (`wake-cli setup` prints its path)",+ path.display()+ )),+ Skip::MirrorsElsewhere => refuse(format!(+ "{} is not the path Wake opens this index at — its remote-host mirrors are not next \+ to it; run refresh on the path `wake-cli setup` prints",+ path.display()+ )),+ }+}++/// 拿错了库的诊断:stderr、`wake-cli: ` 前缀、退 2——与 argv 错同一条出口+/// (`CliError::report`),别在这里手拼 Report;`cli::report` 那张表里的 2 是"值不对",不走它+fn refuse(message: String) -> Report {+ CliError {+ message,+ with_usage: false,+ }+ .report()+}++/// 索引被别的进程持有时说的话:GUI 不会中途让出,直说它在跑;另一个 wake-cli+/// 几秒就完,点名让人看得出是谁+fn busy_text(holder: &LockHolder) -> String {+ if holder.app {+ "Wake is running and keeps the index current itself; nothing to do.".to_string()+ } else {+ format!("Another process is writing the index right now ({holder}); nothing to do.")+ }+}++/// 进度只给终端看:扫描要几秒到几十秒,没有反馈像卡死;管道与 agent 调用时+/// stderr 保持安静(它是诊断通道,tests/cli.rs 也这么断言)+fn progress_events() -> &'static dyn ScanEvents {+ if io::stderr().is_terminal() {&TtyProgress} else {&NullEvents- };- let Some(store) = scanner::build_index(path, events)? else {- return Ok(format!(- "An index already exists at {}. Launch Wake to update or rebuild it.",- path.display()- ));- };- let sessions = store- .list_sessions(&SessionFilter {- limit: 1,- ..Default::default()- })?- .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),- plural(agents),- path.display()- ))+ }}-/// `index` 在终端上的进度:格式在 `cli::progress_line`(有单测),这里只负责+/// `index` / `refresh` 在终端上的进度:格式在 `cli::progress_line`(有单测),这里只负责/// "写到 stderr"。写失败一律忽略——进度条不是结果;stderr 无缓冲,不需要 flushstruct TtyProgress;diff --git a/crates/wake-core/src/cli.rs b/crates/wake-core/src/cli.rsindex a333b4e..29c27ed 100644--- a/crates/wake-core/src/cli.rs+++ b/crates/wake-core/src/cli.rs@@ -109,6 +109,11 @@ const PLAIN: &[PlainSpec] = &[action: Action::Index,summary: "build the index once, when Wake has never run here",},+ PlainSpec {+ name: "refresh",+ action: Action::Refresh,+ summary: "update an existing index while Wake is closed",+ },];const F_PROJECT: FlagSpec = FlagSpec::new(@@ -259,6 +264,8 @@ pub enum Action {Setup,/// 从零建一次索引。**只在索引不存在时**——已存在的库归 GUI 管Index,+ /// 增量刷一轮已有的索引。**只在 Wake 没运行时**——它在跑就退让+ Refresh,/// 一次工具调用。`args` **恒为 JSON object**——mcp/mod.rs 那道/// `arguments` 形状检查在这条路上不可达,别再补一遍Tool {@@ -312,8 +319,8 @@ impl CliError {}}-/// 结果 → 写哪条流、什么退出码。CLI **唯一**的这份映射:工具调用与 `index`-/// 都从这里收场,别在 bin 里另写一个 `fail()`。三个变体全列、不写 `_`:+/// 结果 → 写哪条流、什么退出码。CLI **唯一**的这份映射:工具调用与 `index` /+/// `refresh` 都从这里收场,别在 bin 里另写一个 `fail()`。三个变体全列、不写 `_`:/// ToolError 加变体时这里编译不过,正是要的pub fn report(result: Result<String, tools::ToolError>) -> Report {match result {@@ -351,7 +358,7 @@ pub fn emit(text: &str, out: &mut impl Write) -> std::io::Result<()> {out.flush()}-/// `wake-cli index` 在终端上的进度行:同一行 `\r` 原地刷新,终态**只补一个换行**。+/// `wake-cli index` / `refresh` 在终端上的进度行:同一行 `\r` 原地刷新,终态**只补一个换行**。/// 不在这里宣布 "Indexed …"——那句由 bin 用库里查出来的会话数在 stdout 说,进度/// 只知道文件数(墓碑/解析失败的文件也计 done),两个数字并排只会互相打架;而且/// 扫描收尾(parent_links / backfill)出错时 done 已经等于 total,先打一行成功再@@ -598,7 +605,8 @@ Run `wake-cli --help` for every option.";const HELP_HEAD: &str = "wake-cli — query your Wake session index from the terminalWake 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.+Cursor, Gemini CLI and more). This reads that index. Only `index` and `refresh`+write to it, and only while Wake is closed.USAGE:wake-cli <command> [ARGS] [OPTIONS]@@ -642,7 +650,7 @@ EXIT CODES: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";+Everything except `index` and `refresh` is read-only. Full reference: docs/cli.md";/// 命令块与选项块的说明列起始列const CMD_COL: usize = 36;@@ -1156,8 +1164,10 @@ mod tests {assert!(message(&["sessions", "x"]).contains("takes no arguments"));assert!(message(&["setup", "x"]).contains("takes no arguments"));assert!(message(&["index", "x"]).contains("takes no arguments"));+ assert!(message(&["refresh", "x"]).contains("takes no arguments"));// PLAIN 命令不收旗标,包括全局之外的任何一个assert!(message(&["index", "--limit", "5"]).contains("takes no options"));+ assert!(message(&["refresh", "--full"]).contains("takes no options"));assert!(message(&[]).contains("needs a command"));assert!(message(&["nope"]).contains("unknown command"));}@@ -1186,6 +1196,7 @@ mod tests {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_eq!(p(&["refresh"]).unwrap().action, Action::Refresh);assert!(USAGE.lines().count() < 15, "USAGE 不该长回参考手册");assert!(!USAGE.ends_with('\n'));}diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rsindex 1418fea..70a55d7 100644--- a/crates/wake-core/src/db.rs+++ b/crates/wake-core/src/db.rs@@ -2,8 +2,10 @@ use crate::models::*;use anyhow::{Context as _, Result};use rusqlite::{params, Connection, OptionalExtension};use std::collections::HashMap;+use std::fs::{File, OpenOptions, TryLockError};use std::path::{Path, PathBuf};use std::sync::Mutex;+use std::time::{Duration, Instant};pub type LocationOverrides = (Vec<(AgentId, std::path::PathBuf)>,@@ -346,12 +348,16 @@ pub fn open_or_rebuild(path: &Path) -> Result<(Store, Option<String>)> {Ok(store) => return Ok((store, None)),Err(e) => e,};+ // 挪走的是**真实文件**:默认路径是符号链接时链接留着、新库仍沿链接建在目标处,GUI 手里+ // `IndexLock` 锁的正是目标旁那把;挪链接本身会让锁留在旧目标旁、新库无人看管+ // (Codex review 2026-09-23)。重开仍走原路径,`Store.path` 与远程镜像目录不变。// 三件套一起挪:留下 WAL 或 SHM 任何一个,新库都会接着读旧日志- let backup = std::path::PathBuf::from(format!("{}.corrupt", path.display()));+ let real = canonical(path);+ let backup = std::path::PathBuf::from(format!("{}.corrupt", real.display()));let _ = std::fs::remove_file(&backup);- let _ = std::fs::rename(path, &backup);+ let _ = std::fs::rename(&real, &backup);for suffix in ["-wal", "-shm"] {- let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));+ let _ = std::fs::remove_file(format!("{}{suffix}", real.display()));}let store = Store::open(path).with_context(|| format!("rebuild failed after: {first}"))?;Ok((@@ -364,6 +370,273 @@ pub fn open_or_rebuild(path: &Path) -> Result<(Store, Option<String>)> {))}+/// 索引库的**跨进程**写者锁。`scanner::SCAN_GATE` 只管一个进程里的两条扫描串行,+/// 这把锁管进程之间:GUI 与 `wake-cli refresh` / `wake-cli index` / scan bin 都是写者,+/// 同一时刻只能有一个——两个进程各建一份 roster,launchd 与 Dock 起的 GUI 看到的 env+/// 未必相同(CODEX_HOME / XDG_DATA_HOME / WAKE_HOME 各解各的根),删除检测会把对方收进来+/// 的会话当"磁盘已删"清掉、下一轮再由对方加回,每十分钟互删一次;靠 busy_timeout 排队+/// 解决不了这个,只能不并发。+///+/// 形态:`<db>.lock` 旁路文件上的文件锁(unix flock / Windows LockFileEx,std 的+/// `File::try_lock`),路径按库的**真实路径**派生——`--db` 给到符号链接别名也得撞上同一把。+/// **GUI 另持一把 `<db>.lock.app`**:别人拿不到主锁时探这把锁,拿不到就是有个活着的 GUI——+/// 锁随进程生死,不会残留,"持有者是不是 GUI"这条决定 GUI 等不等、CLI 怎么措辞的判据+/// 只认它。持有者自述(`"wake-cli refresh 4242"`)另写在 `<db>.lock.holder`,**只用来点名**:+/// 它写在拿到锁之后,拿到与写完之间读到的是上一任的残留,拿它做判断就会把新起的 GUI 误+/// 劝退;也不写进锁文件——Windows 的文件锁是强制锁,别的句柄读不到被锁的内容(三条都是+/// 2026-09-23 Codex review)。+/// **谁写库谁持有,且持有期必须盖住读写 `Store` 的整个生命期**:GUI 从启动持到退出+/// (watcher 与扫描随时会写),CLI 写命令只在干活那几秒持有;只读旁路(wake-mcp、+/// wake-cli 的查询)不拿。锁不长在 `Store::open` 里,因为同一进程会同时开多个 Store+/// (scanner_finale 的用例、Dock 重开)而 `open_or_rebuild` 还会把库挪走重开,锁的生命期+/// 得独立于单个 Store——写者名单是封闭的,见 `Store::open` 的约定。锁跟着文件描述符走,+/// 进程退出(含 SIGKILL)即释放,不留残骸;锁文件本身不删——删了别人接着 open 出来的+/// 是另一个 inode,两把锁互不相见+pub struct IndexLock {+ _file: File,+ /// GUI 才有的第二把(`<db>.lock.app`)+ _app: Option<File>,+}++/// 拿不到锁时的持有者:`app` 来自 `.lock.app` 那把锁(活着的 GUI 才持有),文字来自+/// 旁路自述(可能残留,只用来点名)+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct LockHolder {+ pub app: bool,+ description: String,+}++impl LockHolder {+ fn new(app: bool, note: &str) -> Self {+ let description = match note.trim() {+ "" => "another process",+ s => s,+ };+ Self {+ app,+ description: description.to_string(),+ }+ }+}++impl std::fmt::Display for LockHolder {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.description)+ }+}++/// `IndexLock::try_acquire` 的结果+pub enum Ownership {+ Ours(IndexLock),+ Held(LockHolder),+}++/// `IndexLock::acquire_or_wait` 的结果+pub enum Wait {+ Ours(IndexLock),+ /// GUI 持有:没等,它不会让+ HeldByApp(LockHolder),+ /// 等满了还是别人的+ TimedOut(LockHolder),+}++/// GUI 拿锁时报的种类名;CLI 写命令写 "wake-cli index" / "wake-cli refresh"。种类是+/// GUI 才多持 `.lock.app` 那把锁+pub const LOCK_KIND_APP: &str = "Wake";++fn open_lock_file(path: &Path) -> std::io::Result<File> {+ OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(path)+}++impl IndexLock {+ /// `<db>.lock`,按库的真实路径派生(见 `canonical`)+ pub fn path_for(db: &Path) -> PathBuf {+ PathBuf::from(format!("{}.lock", canonical(db).display()))+ }++ /// 持有者自述的旁路文件 `<db>.lock.holder`+ fn holder_path(lock: &Path) -> PathBuf {+ PathBuf::from(format!("{}.holder", lock.display()))+ }++ /// GUI 的第二把锁 `<db>.lock.app`+ fn app_path(lock: &Path) -> PathBuf {+ PathBuf::from(format!("{}.app", lock.display()))+ }++ /// 非阻塞。`kind` 是自述的前半段,pid 由这里补+ pub fn try_acquire(db: &Path, kind: &str) -> std::io::Result<Ownership> {+ let path = Self::path_for(db);+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir)?;+ }+ let file = open_lock_file(&path)?;+ match file.try_lock() {+ Ok(()) => {+ // 自述只用来点名,写不进去(权限一类)不能把刚到手的主锁放掉——放掉后 GUI 的+ // 对策是无锁启动,那就成了并发写库;尽力写,写不成别人只看到 "another process"+ // (Codex review 2026-09-23)+ let _ = std::fs::write(+ Self::holder_path(&path),+ format!("{kind} {}", std::process::id()),+ );+ // 主锁到手就算拿到了;`.lock.app` 拿不到(权限一类)只让别人认不出这是 GUI:+ // CLI 会当成别的写者退让,另一个 GUI 会等满再报——都不会并发写库+ let app = if kind == LOCK_KIND_APP {+ Self::take_app_lock(&path).ok()+ } else {+ None+ };+ Ok(Ownership::Ours(IndexLock {+ _file: file,+ _app: app,+ }))+ }+ Err(TryLockError::WouldBlock) => {+ // 主锁被占是已经确认的事实,探 `.lock.app` 失败不能把它翻成 I/O 错——GUI 对+ // 拿锁出错的对策是无锁启动,那就成了并发写库;保守按"被占、不是 GUI"报,+ // GUI 会等、CLI 会退让(Codex review 2026-09-23)+ let app = Self::app_lock_is_held(&path).unwrap_or(false);+ let note = std::fs::read_to_string(Self::holder_path(&path)).unwrap_or_default();+ Ok(Ownership::Held(LockHolder::new(app, ¬e)))+ }+ Err(TryLockError::Error(e)) => Err(e),+ }+ }++ /// 主锁在手时拿 `.lock.app`(独占)。活着的 GUI 只可能是我们自己,所以它本该是空的;+ /// 别人的共享锁探测会瞬时占住几微秒(拿到即放),撞上就隔一下再拿,别当失败+ fn take_app_lock(lock: &Path) -> std::io::Result<File> {+ let path = Self::app_path(lock);+ let mut tries = 0;+ loop {+ let file = open_lock_file(&path)?;+ match file.try_lock() {+ Ok(()) => return Ok(file),+ Err(TryLockError::WouldBlock) if tries < 50 => {+ tries += 1;+ std::thread::sleep(Duration::from_millis(2));+ }+ Err(TryLockError::WouldBlock) => {+ return Err(std::io::Error::other(+ "another Wake holds the app lock while the index lock was free",+ ))+ }+ Err(TryLockError::Error(e)) => return Err(e),+ }+ }+ }++ /// 探 `.lock.app`:以**共享锁**探,拿到即放,拿不到就是有个活着的 GUI 持着独占锁。+ /// 共享锁探测者之间不互斥——两个 CLI 或 CLI 与正在启动的 GUI 同时探,用独占锁探会把+ /// 对方的瞬时占用当成 GUI(Codex review 2026-09-23)+ fn app_lock_is_held(lock: &Path) -> std::io::Result<bool> {+ let probe = open_lock_file(&Self::app_path(lock))?;+ match probe.try_lock_shared() {+ Ok(()) => Ok(false),+ Err(TryLockError::WouldBlock) => Ok(true),+ Err(TryLockError::Error(e)) => Err(e),+ }+ }++ /// 等着拿(GUI 启动用,阻塞调用方,放在开窗之前):持有者是 CLI 写命令就隔 100ms+ /// 再试直到 `timeout`——它几秒到几十秒就完;是另一个 GUI 立刻放弃,它不会让。+ /// 用轮询不用阻塞的 `File::lock`:阻塞版认不出持有者中途从 CLI 换成了 GUI,+ /// 会无窗地挂死+ pub fn acquire_or_wait(db: &Path, kind: &str, timeout: Duration) -> std::io::Result<Wait> {+ let deadline = Instant::now() + timeout;+ loop {+ match Self::try_acquire(db, kind)? {+ Ownership::Ours(lock) => return Ok(Wait::Ours(lock)),+ Ownership::Held(holder) if holder.app => return Ok(Wait::HeldByApp(holder)),+ Ownership::Held(holder) if Instant::now() >= deadline => {+ return Ok(Wait::TimedOut(holder))+ }+ Ownership::Held(_) => std::thread::sleep(Duration::from_millis(100)),+ }+ }+ }+}++/// `Store.path` 的形态:相对路径按 cwd 补成绝对——`--db wake.db` 这种相对目录不然会以相对+/// 形态拼进远程镜像的 file_path,换个 cwd 就读不到;**不解析符号链接**:远程镜像+/// `remotes/<host>` 挂在"你打开的那个路径"旁边,把库文件链到别的盘、链接留在默认位置的+/// 用户,镜像一直在默认目录里,解析了就找不到、下一轮扫描会把远程会话全判成已删(两条都是+/// 2026-09-23 Codex review)。锁文件另按 `canonical` 落在真实文件旁+fn anchored(db: &Path) -> PathBuf {+ std::path::absolute(db).unwrap_or_else(|_| db.to_path_buf())+}++/// 库的真实绝对路径:文件在就解析它本身;还不在(`index` 建库前、清过索引再启动)就+/// 顺着符号链接走到目标、解析目标的父目录再接文件名——`Store::open` 沿链接建库建在目标+/// 处,锁得提前落在那里;都解析不了原样用。锁文件落在哪、`open_or_rebuild` 挪哪个文件按它(`Store.path` 不按,见 `anchored`)+fn canonical(db: &Path) -> PathBuf {+ if let Ok(real) = db.canonicalize() {+ return strip_verbatim(real);+ }+ let mut target = db.to_path_buf();+ for _ in 0..8 {+ let Ok(link) = std::fs::read_link(&target) else {+ break;+ };+ target = match target.parent() {+ Some(dir) => dir.join(link),+ None => link,+ };+ }+ match (target.parent(), target.file_name()) {+ (Some(dir), Some(name)) => dir+ .canonicalize()+ .map(|dir| strip_verbatim(dir).join(name))+ .unwrap_or_else(|_| target.clone()),+ _ => target,+ }+}++/// Windows 的 `canonicalize` 给的是 `\\?\C:\…` 的 verbatim 形态;它存进 `Store.path`、+/// 派生成 `remotes/<host>` 根再与库里既有的 `C:\…` 形态的 file_path 按字符串前缀比,就+/// 全对不上(Codex review 2026-09-23)。盘符与 UNC 两种各剥回普通写法;其他平台原样+fn strip_verbatim(path: PathBuf) -> PathBuf {+ #[cfg(windows)]+ {+ let text = path.to_string_lossy();+ if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {+ return PathBuf::from(format!(r"\\{rest}"));+ }+ if let Some(rest) = text.strip_prefix(r"\\?\") {+ return PathBuf::from(rest);+ }+ }+ path+}++/// 这文件是不是 Wake 自己的索引:`wake-cli refresh --db` 指错到别家 SQLite(Cursor 的+/// state.vscdb、Hermes 的 state.db)时,`Store::open` 会对它改 journal_mode、建 Wake 的表——+/// 别家数据只读是铁律(Codex review 2026-09-23)。只读开、只看三张表在不在,老版本的 Wake+/// 索引照样认(refresh 要能升级它);打不开、不是 SQLite 都算不是+pub fn is_wake_index(path: &Path) -> bool {+ let Ok(conn) = open_conn_ro(path) else {+ return false;+ };+ ["schema_meta", "sessions", "messages_fts"]+ .iter()+ .all(|table| table_exists(&conn, table).unwrap_or(false))+}++/// "没有索引"这一句的唯一出处:只读旁路(wake-mcp / wake-cli 查询)与 `wake-cli refresh`+/// 说的是同一句,docs/cli.md 的排障条目照抄它+pub fn missing_index(path: &Path) -> String {+ format!(+ "no Wake index at {} — launch Wake once to build it",+ path.display()+ )+}+/// 读写分连接(WAL 单写多读);Connection 非 Sync,各自套 Mutexpub struct Store {write: Mutex<Connection>,@@ -377,11 +650,14 @@ pub struct Store {}impl Store {+ /// 读写打开(建表、迁移)。**写真实索引的进程必须先持 `IndexLock`**,名单是封闭的:+ /// GUI(main.rs `hold_index_lock`)、`scanner::build_index` / `refresh_index`、+ /// scan bin——新写者照做。锁为什么不在这里拿,见 `IndexLock` 的注释pub fn open(path: &Path) -> Result<Self> {Ok(Self {write: Mutex::new(open_conn(path)?),read: Mutex::new(open_conn(path)?),- path: path.to_path_buf(),+ path: anchored(path),read_only: false,})}@@ -389,14 +665,12 @@ impl Store {/// 只读打开既有索引库(wake-mcp 这类旁路读者用):不建表、不迁移、不改/// journal_mode;库不存在或 schema 太老直接报错——重建权只归 GUI 的/// `open_or_rebuild`,旁路进程绝不能把正在被 GUI 写的库挪走重建- /// (唯一的例外是**库根本不存在**时建一个:`scanner::build_index`)。+ /// (例外只有两个,都先拿 `IndexLock`:库不存在时 `scanner::build_index` 建一个,+ /// Wake 没开时 `scanner::refresh_index` 增量刷一轮)。/// WAL 下读者不阻塞 GUI 写入;只读连接要能建 -shm,同用户下目录可写即可pub fn open_read_only(path: &Path) -> Result<Self> {if !path.is_file() {- anyhow::bail!(- "no Wake index at {} — launch Wake once to build it",- path.display()- );+ anyhow::bail!("{}", missing_index(path));}let read = open_conn_ro(path)?;if !table_has_column(&read, NEWEST_COLUMN.0, NEWEST_COLUMN.1)?@@ -411,7 +685,7 @@ impl Store {// Store 的形状要求有 write 连接;这里给的同样是只读句柄write: Mutex::new(open_conn_ro(path)?),read: Mutex::new(read),- path: path.to_path_buf(),+ path: anchored(path),read_only: true,})}diff --git a/crates/wake-core/src/scanner.rs b/crates/wake-core/src/scanner.rsindex 2686459..aa6f2a6 100644--- a/crates/wake-core/src/scanner.rs+++ b/crates/wake-core/src/scanner.rs@@ -1,6 +1,7 @@use crate::adapters::AgentAdapter;-use crate::db::Store;+use crate::db::{IndexLock, LockHolder, Ownership, Store};use crate::models::*;+use crate::text::plural;use anyhow::Result;use std::path::Path;use std::sync::Arc;@@ -57,52 +58,176 @@ impl Drop for ScanFinale<'_> {/// join 了,扫描没有)——不排队就是两条扫描并发改写同一个库。门放在 run_scan/// 入口而不是某个调用方:任何起扫描的入口都自动被管住。锁是进程级而非 Store/// 级,要挡的正是两个 Store 实例开同一个库文件;扫描 panic 会毒化锁,-/// into_inner 照常放行。排在后面的照常出终态事件,UI 只是多等一会儿+/// into_inner 照常放行。排在后面的照常出终态事件,UI 只是多等一会儿。进程**之间**+/// 由 `db::IndexLock` 管(GUI 整个生命周期持有、CLI 写命令干活时持有),两者不可+/// 互代:按扫描粒度拿文件锁会与 GUI 的常驻持有自锁(同进程第二个文件描述是另一把 flock)static SCAN_GATE: std::sync::Mutex<()> = std::sync::Mutex::new(());-/// 从零建一次索引:**只在索引文件不存在时**建,已经有库就原样留给 GUI-/// (`Ok(None)`)。这是"重建权只归 GUI 的 `open_or_rebuild`"(db.rs)唯一的-/// 例外,场景是"装了 Wake 但从没启动过"。+/// `build_index` / `refresh_index` 的收场;措辞由 bin 翻。退让不是失败+pub enum Outcome {+ /// 干完了,库里现在有这些+ Done(Tally),+ /// 前置条件不满足、库一个字节没动+ Skipped(Skip),+ /// 别的进程正持有这份索引(GUI 在跑,或另一个 wake-cli)+ Busy(LockHolder),+}++/// `Outcome::Skipped` 的缘由;措辞与退出码由 bin 定(`Exists` 是正常收场,其余都是+/// `--db` 拿错了路径)+pub enum Skip {+ /// `index`:库已在+ Exists,+ /// `refresh`:没有库+ Missing,+ /// `refresh`:`--db` 指到的不是 Wake 的索引(别家 SQLite)+ NotAnIndex,+ /// `refresh`:有远程会话入库,镜像目录却不在这条路径旁——给的不是 GUI 开它的那条路径+ MirrorsElsewhere,+}++/// 索引里有多少:两个写命令收尾说的同一句+pub struct Tally {+ pub sessions: i64,+ pub agents: i64,+}++impl Tally {+ pub fn of(store: &Store) -> Result<Self> {+ let sessions = store+ .list_sessions(&SessionFilter {+ limit: 1,+ ..Default::default()+ })?+ .1;+ let agents = store.agent_counts()?.len() as i64;+ Ok(Self { sessions, agents })+ }+}++impl std::fmt::Display for Tally {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "{} session{} from {} agent{}",+ self.sessions,+ plural(self.sessions),+ self.agents,+ plural(self.agents)+ )+ }+}++/// 从零建一次索引:**只在索引文件不存在时**建,已经有库就原样留给 GUI(`Skipped`)。+/// 这是"重建权只归 GUI 的 `open_or_rebuild`"(db.rs)对"建"的唯一例外,场景是+/// "装了 Wake 但从没启动过";已有的库要跟上磁盘用 `refresh_index`。///-/// 扫描落在旁边的 `<db>.build-<pid>`,扫完才用 `hard_link` 占位——**先拿到-/// 名字,再动任何东西**:+/// 先拿 `IndexLock`(拿不到即 `Busy` 退让:GUI 正在启动、下一步就是自己建库),拿到+/// 再看一次库在不在。扫描仍落在旁边的 `<db>.build-<pid>`,扫完才用 `hard_link` 占位——+/// 锁管的是"同一时刻只有一个写者",这一层管的是"中途死掉不留半截":/// ① 中途报错 / panic / 被 agent 超时杀掉,目标路径一个字节都没出现过,下次/// 还能重试(不然半截索引会被开头那道 exists 当成"已经有了"永久挡住,而/// 只读查询会把它当正常结果);-/// ② GUI 在我们扫的这几秒里首次启动并建了库,hard_link 直接 AlreadyExists,-/// 我们丢掉自己那份退让,绝不往对方的库里写、也不碰对方的日志文件;+/// ② 不认这把锁的老版本 GUI 在这几秒里首次启动建了库,hard_link 对它照样是+/// AlreadyExists——我们丢掉自己那份退让,绝不往对方的库里写;/// ③ 用 hard_link 不用 rename:rename 无条件覆盖,给不出"已存在即失败"这条-/// 语义,而它正是这里唯一的仲裁(POSIX 与 Windows 都保证)。+/// 语义(POSIX 与 Windows 都保证)。///-/// 残留:占位成功到清扫孤儿边车之间还有几十微秒窗口。真要抹平得让 GUI 与-/// CLI 共用一把跨进程锁——`SCAN_GATE` 自己那段注释就承认它只管进程内,-/// 同样的理由 **别加 --force**-pub fn build_index(path: &Path, events: &dyn ScanEvents) -> Result<Option<Arc<Store>>> {+/// 占位成功后清孤儿边车:目标刚才还不存在,躺在那儿的 -wal/-shm 只可能是孤儿(主库+/// 被手删,或 open_or_rebuild 挪库与删边车之间崩过),留着任何一个,新库都会接着读旧+/// 日志——锁在手,这几十微秒里没人会开这个库。**别加 --force**:重建已有的库归 GUI+pub fn build_index(path: &Path, events: &dyn ScanEvents) -> Result<Outcome> {+ if path.exists() {+ return Ok(Outcome::Skipped(Skip::Exists));+ }+ let _lock = match IndexLock::try_acquire(path, "wake-cli index")? {+ Ownership::Ours(lock) => lock,+ Ownership::Held(holder) => return Ok(Outcome::Busy(holder)),+ };+ // 锁外那一眼可能过时:GUI 刚建完库又退出了if path.exists() {- return Ok(None);+ return Ok(Outcome::Skipped(Skip::Exists));}let staging = Staging::new(path);- {+ let tally = {let store = Arc::new(Store::open(&staging.0)?);- // 不变量 8⑥:按库里的 location 配置建 roster(新库即内置全家)- let adapters = crate::adapters::create_adapters_for(&store);- run_scan(&adapters, &store, events, true)?;- } // 关掉最后一个连接即 checkpoint,-wal/-shm 消失,临时库自成一体+ scan_with(&store, events, true)?+ }; // 关掉最后一个连接即 checkpoint,-wal/-shm 消失,临时库自成一体match std::fs::hard_link(&staging.0, path) {Ok(()) => {}- // 有人抢先了(GUI 首扫 / 另一个 wake-cli index)。他的库归他,退让- Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => return Ok(None),+ // 有人抢先了(不认锁的老版本 GUI 首扫)。他的库归他,退让+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {+ return Ok(Outcome::Skipped(Skip::Exists))+ }// 个别文件系统不给硬链接:退回 rename,但只在目标确实还空着时Err(_) if !path.exists() => std::fs::rename(&staging.0, path)?,- Err(_) => return Ok(None),+ Err(_) => return Ok(Outcome::Skipped(Skip::Exists)),}- // 名字到手了才清孤儿边车:目标刚才还不存在,躺在那儿的 -wal/-shm 只可能- // 是孤儿(主库被手删,或 open_or_rebuild 挪库与删边车之间崩过)。留着任何- // 一个,新库都会接着读旧日志——与 open_or_rebuild 挪走三件套同一条理由for suffix in ["-wal", "-shm"] {let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));}- Ok(Some(Arc::new(Store::open_read_only(path)?)))+ Ok(Outcome::Done(tally))+}++/// 增量刷新一份**已有**的索引(`wake-cli refresh`):给"app 不开、靠 MCP / CLI 用 Wake"+/// 的人用 launch agent / systemd timer 定时跑(issue #43)。做的正是 GUI 启动与 ⌘R+/// 那一轮——增量 `run_scan`,收尾同步记忆,升级后的 FTS 回填旗子照常生效——只少远程+/// rsync(要 ssh,留给 GUI 的同步线程)。+///+/// **只在 Wake 没运行时干活**:`IndexLock` 拿不到就 `Busy` 退让。GUI 开着时它的 watcher+/// 本来就在保鲜,再跑一轮不只是多余——两个进程各建一份 roster,看到的 env 未必相同,+/// 删除检测会互删对方收进来的会话(理由在 `IndexLock` 的注释),锁把这类并发整个排除。+/// `Store::open` 会顺手迁移 schema,与 GUI 首开同一条路:刷新的目的就是让库跟上二进制;+/// 反过来(库比二进制新)认不出来,docs 让定时任务指向 app 包内那份 wake-cli+pub fn refresh_index(path: &Path, events: &dyn ScanEvents) -> Result<Outcome> {+ if !path.is_file() {+ return Ok(Outcome::Skipped(Skip::Missing));+ }+ // 开写之前先只读认一眼:`--db` 指错到别家 SQLite 时 `Store::open` 会改它的 journal_mode、+ // 建 Wake 的表,而别家数据只读是铁律(Codex review 2026-09-23)+ if !crate::db::is_wake_index(path) {+ return Ok(Outcome::Skipped(Skip::NotAnIndex));+ }+ let _lock = match IndexLock::try_acquire(path, "wake-cli refresh")? {+ Ownership::Ours(lock) => lock,+ Ownership::Held(holder) => return Ok(Outcome::Busy(holder)),+ };+ let store = Arc::new(Store::open(path)?);+ if mirrors_elsewhere(&store)? {+ return Ok(Outcome::Skipped(Skip::MirrorsElsewhere));+ }+ Ok(Outcome::Done(scan_with(&store, events, false)?))+}++/// 远程镜像按 `Store::db_dir()` 找(与 GUI 同一约定:挂在打开的那个路径旁)。给的是真库的+/// 别名、或被链接到别处的真库本身,而 GUI 开的是另一条路径时,这里的 `remotes/<host>` 不在,+/// 枚举为空,删除检测会把远程会话整批当"磁盘已删"清掉、还报成功——有远程会话入库、镜像+/// 根却不在,就是拿错了路径(Codex review 2026-09-23)。"有东西入库"要连记忆一起看:+/// 转录清掉了、Codex 记忆还在的 host 没有会话行,`sync_memories` 照样会把它的记忆当消失+/// 的来源整组删掉(同轮 review)+fn mirrors_elsewhere(store: &Store) -> Result<bool> {+ let Some(db_dir) = store.db_dir() else {+ return Ok(false);+ };+ let sessions = store.host_counts()?;+ let memories: std::collections::HashSet<String> = store+ .memory_groups()?+ .into_iter()+ .map(|(_, host)| host)+ .filter(|host| !host.is_empty())+ .collect();+ Ok(store.enabled_remote_host_names().iter().any(|host| {+ (sessions.get(host).is_some_and(|n| *n > 0) || memories.contains(host))+ && !crate::remote::host_cache_dir(&db_dir, host).is_dir()+ }))+}++/// 按库里的 location / remote host 配置建 roster(不变量 8⑥)、扫一轮、数一数。读写+/// `Store` 由调用方持有并在放锁前关掉(最后一个连接关掉即 checkpoint,-wal/-shm 消失)+fn scan_with(store: &Arc<Store>, events: &dyn ScanEvents, full: bool) -> Result<Tally> {+ let adapters = crate::adapters::create_adapters_for(store);+ run_scan(&adapters, store, events, full)?;+ Tally::of(store)}/// 临时库的清场:正常收尾、`?` 提前返回、panic unwind 三条路都要把它连同边车diff --git a/crates/wake-core/tests/cli.rs b/crates/wake-core/tests/cli.rsindex e1b1a1b..503812b 100644--- a/crates/wake-core/tests/cli.rs+++ b/crates/wake-core/tests/cli.rs@@ -16,7 +16,7 @@ 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::db::{self, Store};use wake_core::mcp::tools::{self, TranscriptCache};use wake_core::models::SessionFilter;use wake_core::scanner::{run_scan, NullEvents};@@ -565,3 +565,191 @@ fn index_builds_one_from_scratch_then_defers() {assert_eq!(code, Some(0));assert!(stdout.starts_with("An index already exists"), "{stdout}");}++/// refresh 用的库副本:主库是全文件共用的只读参照,别的用例正拿它做字节比对,+/// 刷新只能冲着自己那份拷贝跑(扫的仍是共用的 fixture home,只读)+fn db_copy(dir: &Path) -> PathBuf {+ let db = dir.join("copy.db");+ std::fs::copy(&env().db, &db).unwrap();+ db+}++/// 这个功能的主张:app 不开,`refresh` 也把索引追到磁盘的现状。抠掉一行(不留+/// 墓碑,scanner 删磁盘已删的会话用的正是这一手),文件还在,刷新该把它收回来——+/// 不往共用的 fixture home 里加文件,那会让并行的 index 用例数出别的数+#[test]+fn refresh_brings_an_existing_index_up_to_date() {+ let tmp = tempfile::tempdir().unwrap();+ let db = db_copy(tmp.path());+ let path = db.to_str().unwrap();+ Store::open(&db)+ .unwrap()+ .remove_session(CLAUDE_KEY, false)+ .unwrap();+ let (_, _, code) = cli_raw(&["--db", path, "show", CLAUDE_KEY, "--messages", "1"]);+ assert_eq!(code, Some(1), "抠掉的会话按 key 该是读不出来的");++ let (stdout, stderr, code) = cli_raw(&["--db", path, "refresh"]);+ assert_eq!(code, Some(0), "{stderr}");+ assert_eq!(stderr, "", "管道里跑,stderr 保持安静");+ assert!(stdout.starts_with("Refreshed the index at "), "{stdout}");+ assert!(stdout.contains(" sessions from "), "{stdout}");++ let (_, stderr, code) = cli_raw(&["--db", path, "show", CLAUDE_KEY, "--messages", "1"]);+ assert_eq!(code, Some(0), "刷新后该收回来:{stderr}");+}++/// 只在 Wake 没运行时干活:GUI 持锁就直说它在跑,另一个 wake-cli 持锁就点名,+/// 两种退让都退 0 且库一个字节不动;锁一放就能刷+#[test]+fn refresh_defers_while_the_index_is_held() {+ let tmp = tempfile::tempdir().unwrap();+ let db = db_copy(tmp.path());+ let path = db.to_str().unwrap();+ let before = std::fs::read(&db).unwrap();+ let refresh = || cli_raw(&["--db", path, "refresh"]);+ for (kind, expect) in [+ (db::LOCK_KIND_APP, "Wake is running"),+ (+ "wake-cli refresh",+ "Another process is writing the index right now (wake-cli refresh ",+ ),+ ] {+ let _lock = common::lock_as(&db, kind);+ let (stdout, stderr, code) = refresh();+ assert_eq!(code, Some(0), "{stderr}");+ assert!(stdout.starts_with(expect), "{stdout}");+ assert_eq!(before, std::fs::read(&db).unwrap(), "退让时一个字节不许动");+ }+ let (stdout, stderr, code) = refresh();+ assert_eq!(code, Some(0), "{stderr}");+ assert!(stdout.starts_with("Refreshed the index at "), "{stdout}");+}++/// 没索引不是 refresh 的事(`index` 或启动 Wake 才建),与查询命令缺库同退 2,+/// 而且什么都不该建——连锁文件都不留+#[test]+fn refresh_without_an_index_exits_two() {+ let tmp = tempfile::tempdir().unwrap();+ let db = tmp.path().join("none.db");+ let (stdout, stderr, code) = cli_raw(&["--db", db.to_str().unwrap(), "refresh"]);+ assert_eq!(code, Some(2));+ assert_eq!(stdout, "");+ assert!(+ stderr.starts_with("wake-cli: no Wake index at "),+ "{stderr}"+ );+ assert!(+ stderr.contains("wake-cli index"),+ "该指向建库的那条命令:{stderr}"+ );+ let left: Vec<_> = std::fs::read_dir(tmp.path())+ .unwrap()+ .map(|e| e.unwrap().file_name())+ .collect();+ assert!(+ left.is_empty(),+ "没索引就什么都不该建,连锁文件与持有者旁路都不该留:{left:?}"+ );+}++/// `index` 也认这把锁:GUI 正在启动(下一步就是自己建库)时退让,不建、退 0+#[test]+fn index_defers_while_wake_holds_the_index() {+ let tmp = tempfile::tempdir().unwrap();+ let db = tmp.path().join("fresh.db");+ let _lock = common::lock_as(&db, db::LOCK_KIND_APP);+ let (stdout, stderr, code) = cli_raw(&["--db", db.to_str().unwrap(), "index"]);+ assert_eq!(code, Some(0), "{stderr}");+ assert!(stdout.starts_with("Wake is running"), "{stdout}");+ assert!(!db.exists(), "退让就不该建库");+}++/// `--db` 指错到别家 SQLite(Cursor 的 state.vscdb 一类):一个字节不许动——别家数据只读是+/// 铁律——退 2 说清楚,连锁文件都不留(Codex review 2026-09-23)+#[test]+fn refresh_refuses_a_database_that_is_not_a_wake_index() {+ let tmp = tempfile::tempdir().unwrap();+ let foreign = tmp.path().join("state.vscdb");+ rusqlite::Connection::open(&foreign)+ .unwrap()+ .execute_batch("CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value BLOB);")+ .unwrap();+ let before = std::fs::read(&foreign).unwrap();+ let (stdout, stderr, code) = cli_raw(&["--db", foreign.to_str().unwrap(), "refresh"]);+ assert_eq!(code, Some(2), "{stderr}");+ assert_eq!(stdout, "");+ assert!(stderr.contains("is not a Wake index"), "{stderr}");+ assert_eq!(+ before,+ std::fs::read(&foreign).unwrap(),+ "别家库一个字节不许动"+ );+ let names: Vec<String> = std::fs::read_dir(tmp.path())+ .unwrap()+ .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())+ .collect();+ assert!(!names.iter().any(|n| n.contains(".lock")), "{names:?}");+}++/// 有远程会话入库、镜像目录却不在这条路径旁 = 给的不是 GUI 开它的那条路径(真库的别名,+/// 或被链接到别处的真库本身):照扫会把远程会话整批当"磁盘已删"清掉,拒掉、退 2、行还在+/// (Codex review 2026-09-23)+#[test]+fn refresh_refuses_a_path_whose_remote_mirrors_are_elsewhere() {+ let tmp = tempfile::tempdir().unwrap();+ let db = db_copy(tmp.path());+ Store::open(&db).unwrap().add_remote_host("box").unwrap();+ // 直接塞一行远程会话:这条路径旁没有 remotes/box+ rusqlite::Connection::open(&db)+ .unwrap()+ .execute(+ "INSERT INTO sessions(key, agent_id, native_id, host, file_path) \+ VALUES ('codex:box:abc', 'codex', 'abc', 'box', '/elsewhere/remotes/box/x.jsonl')",+ [],+ )+ .unwrap();+ let (stdout, stderr, code) = cli_raw(&["--db", db.to_str().unwrap(), "refresh"]);+ assert_eq!(code, Some(2), "{stderr}");+ assert_eq!(stdout, "");+ assert!(stderr.contains("mirrors are not next to it"), "{stderr}");+ let left: i64 = rusqlite::Connection::open(&db)+ .unwrap()+ .query_row(+ "SELECT COUNT(*) FROM sessions WHERE host = 'box'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(left, 1, "远程会话不许被清掉");+}++/// 同上,但这台 host 只剩远程记忆、没有会话行(转录清掉了、Codex 记忆还在):镜像不在照样+/// 拒,否则 `sync_memories` 会把它的记忆当消失的来源整组删掉(Codex review 2026-09-23)+#[test]+fn refresh_refuses_when_only_remote_memories_would_be_lost() {+ let tmp = tempfile::tempdir().unwrap();+ let db = db_copy(tmp.path());+ Store::open(&db).unwrap().add_remote_host("box").unwrap();+ rusqlite::Connection::open(&db)+ .unwrap()+ .execute(+ "INSERT INTO memories(key, agent_id, host, scope, path, title, body) \+ VALUES ('codex:box:/elsewhere/m.md', 'codex', 'box', 'user', '/elsewhere/m.md', 'm', 'x')",+ [],+ )+ .unwrap();+ let (stdout, stderr, code) = cli_raw(&["--db", db.to_str().unwrap(), "refresh"]);+ assert_eq!(code, Some(2), "{stderr}");+ assert_eq!(stdout, "");+ assert!(stderr.contains("mirrors are not next to it"), "{stderr}");+ let left: i64 = rusqlite::Connection::open(&db)+ .unwrap()+ .query_row(+ "SELECT COUNT(*) FROM memories WHERE host = 'box'",+ [],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(left, 1, "远程记忆不许被清掉");+}diff --git a/crates/wake-core/tests/common/mod.rs b/crates/wake-core/tests/common/mod.rsindex 55fcad7..1096c33 100644--- a/crates/wake-core/tests/common/mod.rs+++ b/crates/wake-core/tests/common/mod.rs@@ -7,6 +7,8 @@use std::fs;use std::path::{Path, PathBuf};+use wake_core::db::{IndexLock, Ownership};+pub fn fixture(rel: &str) -> PathBuf {Path::new(env!("CARGO_MANIFEST_DIR")).join("tests")@@ -897,3 +899,20 @@ pub fn build_zcode_tasks_db(path: &Path) {).expect("populate zcode tasks fixture db");}++/// 以某种身份持住索引锁,拿不到就 panic 点名——各测试文件里"扮演 GUI / 另一个+/// wake-cli"的同一句+pub fn lock_as(db: &Path, kind: &str) -> IndexLock {+ // 并行的别条测试正在 fork 子进程的那几微秒里,本进程所有 fd(含刚放掉的锁)会被复制一份+ // 直到 exec 关掉——锁因此晚放一瞬。真实使用没有这形态(GUI 持锁到退出),测试里等一下+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);+ loop {+ match IndexLock::try_acquire(db, kind).unwrap() {+ Ownership::Ours(lock) => return lock,+ Ownership::Held(_) if std::time::Instant::now() < deadline => {+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ Ownership::Held(who) => panic!("a fresh lock should not be held by {who}"),+ }+ }+}diff --git a/crates/wake-core/tests/db_roundtrip.rs b/crates/wake-core/tests/db_roundtrip.rsindex 782d8c4..bcc65c5 100644--- a/crates/wake-core/tests/db_roundtrip.rs+++ b/crates/wake-core/tests/db_roundtrip.rs@@ -1,9 +1,13 @@//! Store 写入/搜索/删除语义的往返测试(临时库,不碰真实索引)。//! 覆盖 CLAUDE.md 不变量 3:tombstone 防复活、user_data 独立表重建不丢。-use wake_core::db::Store;+use std::time::{Duration, Instant};++use wake_core::db::{self, IndexLock, Ownership, Store, Wait};use wake_core::models::*;+mod common;+fn temp_store() -> (tempfile::TempDir, Store) {let dir = tempfile::tempdir().expect("tempdir");let store = Store::open(&dir.path().join("test.db")).expect("open store");@@ -1751,3 +1755,251 @@ fn memories_resolve_their_project_through_the_anchor_session() {"重写后 FTS 里只剩这一份、没有旧行残留");}++/// 跨进程写锁的契约:同一路径第二把拿不到、拿不到时点得出持有者(GUI 与否)、放了+/// 就能拿;等待策略只等 CLI 持有者,遇 GUI 立刻放弃。flock 与 LockFileEx 都按打开的+/// 文件描述计,进程内第二次 open 就能演+#[test]+fn index_lock_is_exclusive_names_its_holder_and_waits_only_for_the_cli() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("test.db");+ let app = common::lock_as(&db, db::LOCK_KIND_APP);+ match IndexLock::try_acquire(&db, "wake-cli refresh").unwrap() {+ Ownership::Ours(_) => panic!("the second acquisition must fail while the first is held"),+ Ownership::Held(who) => {+ assert!(who.app, "{who}");+ assert_eq!(who.to_string(), format!("Wake {}", std::process::id()));+ }+ }+ // GUI 持有:不等,立刻报+ let t0 = Instant::now();+ assert!(matches!(+ IndexLock::acquire_or_wait(&db, "wake-cli refresh", Duration::from_secs(5)).unwrap(),+ Wait::HeldByApp(_)+ ));+ assert!(t0.elapsed() < Duration::from_secs(1), "遇 GUI 不该等");+ drop(app);++ // CLI 持有:等它放+ let cli = common::lock_as(&db, "wake-cli refresh");+ match IndexLock::try_acquire(&db, db::LOCK_KIND_APP).unwrap() {+ Ownership::Held(who) => assert!(!who.app, "{who}"),+ Ownership::Ours(_) => panic!("the CLI holder should block the app"),+ }+ let releaser = std::thread::spawn(move || {+ std::thread::sleep(Duration::from_millis(300));+ drop(cli);+ });+ match IndexLock::acquire_or_wait(&db, db::LOCK_KIND_APP, Duration::from_secs(5)).unwrap() {+ Wait::Ours(_) => {}+ Wait::HeldByApp(who) | Wait::TimedOut(who) => panic!("should have waited out {who}"),+ }+ releaser.join().unwrap();++ // 等满了还是别人的+ let _cli = common::lock_as(&db, "wake-cli index");+ assert!(matches!(+ IndexLock::acquire_or_wait(&db, db::LOCK_KIND_APP, Duration::from_millis(250)).unwrap(),+ Wait::TimedOut(_)+ ));+}++/// `--db` 给符号链接别名也得撞上同一把锁:锁文件按库的真实路径派生(Codex review+/// 2026-09-23)。Windows 建符号链接要特权,只在 unix 演+#[cfg(unix)]+#[test]+fn index_lock_follows_the_database_through_symlinks() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("wake.db");+ std::fs::write(&db, b"").unwrap();+ let alias = dir.path().join("alias.db");+ std::os::unix::fs::symlink(&db, &alias).unwrap();+ assert_eq!(IndexLock::path_for(&alias), IndexLock::path_for(&db));+ let _app = common::lock_as(&db, db::LOCK_KIND_APP);+ match IndexLock::try_acquire(&alias, "wake-cli refresh").unwrap() {+ Ownership::Held(who) => assert!(who.app, "{who}"),+ Ownership::Ours(_) => panic!("the alias must share the app's lock"),+ }+ // 库还不存在时按父目录解析:目录的别名同样撞上+ let dir_alias = dir.path().join("dir-alias");+ std::os::unix::fs::symlink(dir.path(), &dir_alias).unwrap();+ assert_eq!(+ IndexLock::path_for(&dir_alias.join("none.db")),+ IndexLock::path_for(&dir.path().join("none.db"))+ );+}++/// `db_dir()` 是"打开的那个路径"所在目录,**不解析符号链接**——远程镜像 `remotes/<host>`+/// 挂在它下面,把库链到别的盘、链接留在默认位置的用户不能因升级换镜像目录;锁文件才按真实+/// 文件落(Codex review 2026-09-23)。相对 `--db` 补成绝对那一支没法在并行测试里演+/// (cwd 是进程级状态)+#[test]+fn store_keeps_the_directory_it_was_opened_at() {+ let dir = tempfile::tempdir().unwrap();+ let store = Store::open(&dir.path().join("x.db")).unwrap();+ assert_eq!(store.db_dir().unwrap(), dir.path());+ drop(store);+ let ro = Store::open_read_only(&dir.path().join("x.db")).unwrap();+ assert_eq!(ro.db_dir().unwrap(), dir.path());+ #[cfg(unix)]+ {+ let alias = dir.path().join("alias");+ std::os::unix::fs::symlink(dir.path(), &alias).unwrap();+ let via_alias = Store::open(&alias.join("x.db")).unwrap();+ assert_eq!(+ via_alias.db_dir().unwrap(),+ alias,+ "镜像目录跟着打开的路径走"+ );+ assert_eq!(+ IndexLock::path_for(&alias.join("x.db")),+ IndexLock::path_for(&dir.path().join("x.db")),+ "锁按真实文件落"+ );+ }+}++/// 持有者自述是旁路文件、写在拿到锁之后,可能残留上一任 GUI 的 "Wake …";"是不是 GUI"+/// 只认 `.lock.app` 那把锁(随进程生死)。这里主锁被一个从不写自述、也不持 `.lock.app`+/// 的持有者拿着,残留的自述不能把新起的 GUI 劝退(Codex review 2026-09-23)+#[test]+fn a_stale_app_holder_note_does_not_turn_the_gui_away() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("test.db");+ let lock_path = IndexLock::path_for(&db);+ // 与 IndexLock 同一条命名规则:旁路文件 = 锁文件名 + ".holder"+ std::fs::write(format!("{}.holder", lock_path.display()), "Wake 1").unwrap();+ let raw = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(&lock_path)+ .unwrap();+ raw.try_lock().unwrap();+ match IndexLock::try_acquire(&db, "wake-cli refresh").unwrap() {+ Ownership::Held(who) => {+ assert!(!who.app, "残留自述不算 GUI:{who}");+ assert_eq!(who.to_string(), "Wake 1", "点名仍用自述");+ }+ Ownership::Ours(_) => panic!("the raw holder should block"),+ }+ let releaser = std::thread::spawn(move || {+ std::thread::sleep(Duration::from_millis(300));+ drop(raw);+ });+ match IndexLock::acquire_or_wait(&db, db::LOCK_KIND_APP, Duration::from_secs(5)).unwrap() {+ Wait::Ours(_) => {}+ Wait::HeldByApp(who) => panic!("turned away by a stale note: {who}"),+ Wait::TimedOut(who) => panic!("should have waited out the holder: {who}"),+ }+ releaser.join().unwrap();+}++/// 默认路径是**悬空**符号链接(目标清掉后再启动):锁要落在目标旁,`Store::open` 沿链接+/// 建库正建在那里,之后按同一路径解析出的是同一把(Codex review 2026-09-23)+#[cfg(unix)]+#[test]+fn index_lock_follows_a_dangling_symlink_to_its_target() {+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("real").join("wake.db");+ std::fs::create_dir_all(target.parent().unwrap()).unwrap();+ let link = dir.path().join("wake.db");+ std::os::unix::fs::symlink(&target, &link).unwrap();+ let before = IndexLock::path_for(&link);+ assert_eq!(before, IndexLock::path_for(&target));+ let store = Store::open(&link).unwrap();+ assert!(target.is_file(), "沿链接建库应建在目标处");+ assert_eq!(store.db_dir().unwrap(), dir.path(), "镜像目录留在链接旁");+ assert_eq!(IndexLock::path_for(&link), before, "建库前后锁的位置不能变");+}++/// 探 `.lock.app` 用共享锁:多个探测者同时探(几个 CLI、或 CLI 撞上正在启动的 GUI)+/// 不能互相当成 GUI。主锁由一个不持 `.lock.app` 的持有者拿着,四个线程各探几十次,+/// 谁都不该看到 "GUI 在"(Codex review 2026-09-23)+#[test]+fn concurrent_probes_never_mistake_each_other_for_the_gui() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("test.db");+ let raw = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(IndexLock::path_for(&db))+ .unwrap();+ raw.try_lock().unwrap();+ let probers: Vec<_> = (0..4)+ .map(|_| {+ let db = db.clone();+ std::thread::spawn(move || {+ for _ in 0..40 {+ match IndexLock::try_acquire(&db, "wake-cli refresh").unwrap() {+ Ownership::Held(who) => {+ assert!(!who.app, "a probe was taken for the GUI: {who}")+ }+ Ownership::Ours(_) => panic!("the raw holder should block"),+ }+ }+ })+ })+ .collect();+ for p in probers {+ p.join().unwrap();+ }+ drop(raw);+}++/// 主锁被占是已经确认的事实,探 `.lock.app` 出错(这里让它是个目录,open 必败)不能把+/// "被占"翻成 I/O 错——GUI 对拿锁出错的对策是无锁启动。保守按"被占、不是 GUI"报+/// (Codex review 2026-09-23)+#[test]+fn a_failing_app_probe_still_reports_the_index_as_held() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("test.db");+ let lock_path = IndexLock::path_for(&db);+ std::fs::create_dir_all(format!("{}.app", lock_path.display())).unwrap();+ let raw = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(&lock_path)+ .unwrap();+ raw.try_lock().unwrap();+ match IndexLock::try_acquire(&db, "wake-cli refresh").unwrap() {+ Ownership::Held(who) => assert!(!who.app, "{who}"),+ Ownership::Ours(_) => panic!("the raw holder should block"),+ }+ drop(raw);+ // 主锁到手、`.lock.app` 拿不到:GUI 照样算拿到,别人只是认不出它是 GUI+ match IndexLock::try_acquire(&db, db::LOCK_KIND_APP).unwrap() {+ Ownership::Ours(_) => {}+ Ownership::Held(who) => panic!("free lock reported held by {who}"),+ }+}++/// 自述文件写不进去(这里让它是个目录)不能把刚到手的主锁放掉:锁照拿,别人只是点不出名+/// (Codex review 2026-09-23)+#[test]+fn an_unwritable_holder_note_does_not_forfeit_the_lock() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("test.db");+ let lock_path = IndexLock::path_for(&db);+ std::fs::create_dir_all(format!("{}.holder", lock_path.display())).unwrap();+ let _held = match IndexLock::try_acquire(&db, db::LOCK_KIND_APP).unwrap() {+ Ownership::Ours(lock) => lock,+ Ownership::Held(who) => panic!("free lock reported held by {who}"),+ };+ match IndexLock::try_acquire(&db, "wake-cli refresh").unwrap() {+ Ownership::Held(who) => {+ assert!(who.app, "GUI 的第二把锁照拿:{who}");+ assert_eq!(+ who.to_string(),+ "another process",+ "点不出名就说 another process"+ );+ }+ Ownership::Ours(_) => panic!("the lock must still be held"),+ }+}diff --git a/crates/wake/locales/zh-Hans.json b/crates/wake/locales/zh-Hans.jsonindex 675ece3..e53a682 100644--- a/crates/wake/locales/zh-Hans.json+++ b/crates/wake/locales/zh-Hans.json@@ -319,6 +319,7 @@"View Update": "查看更新","Wake Settings": "Wake 设置","Wake couldn't open or rebuild its index at {}. {}": "Wake 无法在 {} 打开或重建索引。{}",+ "Wake couldn't open its index at {}: another process is using it ({}). Wait for it to finish or quit it, then open Wake again.": "Wake 无法打开 {} 的索引:另一个进程正在使用它({})。请等它结束或退出它,再重新打开 Wake。","Wake couldn't {} its window: {}": "Wake 无法{}窗口:{}","Wake data": "Wake 数据","Wake skill": "Wake Skill",diff --git a/crates/wake/src/i18n.rs b/crates/wake/src/i18n.rsindex 4fd847e..d140685 100644--- a/crates/wake/src/i18n.rs+++ b/crates/wake/src/i18n.rs@@ -624,6 +624,7 @@ mod tests {include_str!("workbench/memory.rs"),include_str!("settings.rs"),include_str!("main.rs"),+ include_str!("index_lock.rs"),include_str!("markdown_links.rs"),include_str!("format.rs"),];diff --git a/crates/wake/src/index_lock.rs b/crates/wake/src/index_lock.rsnew file mode 100644index 0000000..7e93b89--- /dev/null+++ b/crates/wake/src/index_lock.rs@@ -0,0 +1,57 @@+//! 索引写锁在 GUI 里的生命期:跟着 Workbench 与它派出的写线程走,**不跟进程走**。macOS 关掉+//! 主窗、app 留在 Dock 时 Workbench 已释放、watcher 随之停了;进程若还持锁,定时跑的+//! `wake-cli refresh` 会一直退让、索引就此停摆(Codex review 2026-09-23)。Workbench 持一份+//! `Arc`,每条会写库的线程 / 后台任务各持一份克隆(扫描、远程同步、记忆同步、删除、清理),+//! 最后一份放掉锁才释放;watcher 在 Workbench 的字段里排在锁前面,drop 时先 join 再放锁。+//! Dock 重开新建 Workbench 时旧扫描线程可能还在跑、那份 Arc 还活着,就在这里 upgrade 共用——+//! 否则同进程第二次 try_lock 会撞上自己的 fd,把自己当成"另一个 Wake"劝退+use std::path::Path;+use std::sync::{Arc, Mutex, Weak};+use std::time::{Duration, Instant};++use wake_core::db::{IndexLock, Wait, LOCK_KIND_APP};++static SLOT: Mutex<Weak<IndexLock>> = Mutex::new(Weak::new());++/// 拿到就 Some。持有者是另一个 Wake、或等满 60s 仍拿不到就弹窗退出——两个 GUI 写同一个库+/// 正是 wake-core SCAN_GATE 那段注释想挡而挡不住的事;拿锁本身出错(不给建议锁的文件系统)+/// 不该把 app 拦在门外,记一行、None 照常起。阻塞调用方:只在开窗之前的 Workbench::new 里调+pub fn take(db: &Path) -> Option<Arc<IndexLock>> {+ let mut slot = SLOT+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(live) = slot.upgrade() {+ return Some(live);+ }+ let me = format!("{LOCK_KIND_APP} {}", std::process::id());+ let deadline = Instant::now() + Duration::from_secs(60);+ let holder = loop {+ match IndexLock::acquire_or_wait(db, LOCK_KIND_APP, Duration::from_secs(60)) {+ Ok(Wait::Ours(lock)) => {+ let lock = Arc::new(lock);+ *slot = Arc::downgrade(&lock);+ return Some(lock);+ }+ // 上一份的最后一个持有者刚放手、fd 还没关上的那一瞬,撞见的是自己:等一下再拿+ Ok(Wait::HeldByApp(holder))+ if holder.to_string() == me && Instant::now() < deadline =>+ {+ std::thread::sleep(Duration::from_millis(10));+ }+ Ok(Wait::HeldByApp(holder) | Wait::TimedOut(holder)) => break holder,+ Err(e) => {+ eprintln!(+ "wake: index lock unavailable at {}: {e}; continuing without it",+ db.display()+ );+ return None;+ }+ }+ };+ wake_core::services::terminal::show_fatal_alert(&crate::tf!(+ "Wake couldn't open its index at {}: another process is using it ({}). Wait for it to finish or quit it, then open Wake again.",+ db.display(),+ holder+ ));+ std::process::exit(1);+}diff --git a/crates/wake/src/main.rs b/crates/wake/src/main.rsindex dc9e251..be1c1c1 100644--- a/crates/wake/src/main.rs+++ b/crates/wake/src/main.rs@@ -9,6 +9,7 @@mod assets;mod format;mod i18n;+mod index_lock;mod main_window;mod markdown_links;mod prefs;diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rsindex 12e42aa..bf34d61 100644--- a/crates/wake/src/workbench.rs+++ b/crates/wake/src/workbench.rs@@ -166,8 +166,11 @@ fn spawn_scan(store: Arc<Store>,events: Arc<dyn ScanEvents>,full: bool,+ lock: Option<Arc<wake_core::db::IndexLock>>,) {std::thread::spawn(move || {+ // 写库的线程持一份锁的克隆:Workbench 先没了(关窗)扫描还在跑,锁得跟到扫完+ let _lock = lock;let _ = run_scan(&adapters, &store, events.as_ref(), full);});}@@ -179,12 +182,15 @@ fn spawn_remote_sync_thread(store: &Arc<Store>,bg_tx: futures::channel::mpsc::UnboundedSender<BgEvent>,names: Vec<String>,+ lock: Option<Arc<wake_core::db::IndexLock>>,) {if names.is_empty() {return;}let store = store.clone();std::thread::spawn(move || {+ // sync_hosts 往 remote_hosts 表写同步结果,也算写者+ let _lock = lock;wake_core::remote::sync_hosts(&store, &names);// 同步期间被 Remove 的 host:rsync 取消不了,收工后按配置表把孤儿// 缓存目录清掉(含它刚写回的),Remove 的"缓存已删"承诺自此闭合@@ -2193,6 +2199,9 @@ pub struct Workbench {/// 可用列表内则用它——让"一直用 Ghostty"的人不用每家 agent 都选一遍last_terminal: Option<terminal::TerminalApp>,_subs: Vec<Subscription>,+ /// 索引写锁(见 index_lock.rs):**必须是最后一个字段**——drop 按声明序,watcher 先+ /// join(它的线程还在写库)再放锁;派出去的写线程各持一份克隆,锁随最后一份走+ index_lock: Option<Arc<wake_core::db::IndexLock>>,}/// Insights 分布图的维度(‹ › 循环切换)。数据三份都在 InsightsData 里,@@ -2464,6 +2473,8 @@ struct PathFormSpec {impl Workbench {pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {let db_path = wake_core::db::default_db_path();+ // 开库之前先拿索引写锁(拿不到就等 / 弹窗退出,见 index_lock.rs)+ let index_lock = crate::index_lock::take(&db_path);// 库损坏时降级重建而不是崩掉:GUI 秒退什么都不告诉用户,他们也无从知道// 删掉那个文件就能自愈。重建也失败说明是目录权限/磁盘问题,那才没救——// 但至少要用系统弹窗把话说清楚再退。@@ -2510,9 +2521,20 @@ impl Workbench {let (tx, mut rx) = futures::channel::mpsc::unbounded::<BgEvent>();let bg_tx = tx.clone();let events: Arc<dyn ScanEvents> = Arc::new(ChannelEvents(tx));- spawn_scan(adapters.clone(), store.clone(), events.clone(), false);+ spawn_scan(+ adapters.clone(),+ store.clone(),+ events.clone(),+ false,+ index_lock.clone(),+ );let syncing_hosts = store.enabled_remote_host_names();- spawn_remote_sync_thread(&store, bg_tx.clone(), syncing_hosts.clone());+ spawn_remote_sync_thread(+ &store,+ bg_tx.clone(),+ syncing_hosts.clone(),+ index_lock.clone(),+ );{let (store, bg_tx) = (store.clone(), bg_tx.clone());std::thread::spawn(move || report_remote_cache_size(&store, &bg_tx));@@ -2604,6 +2626,7 @@ impl Workbench {preferred_terminal: HashMap::new(),last_terminal: None,_subs: subs,+ index_lock,};this.load_open_in_prefs();this.load_cleanup_prefs();@@ -2837,6 +2860,7 @@ impl Workbench {self.store.clone(),self.scan_events.clone(),true,+ self.index_lock.clone(),);self.sync_all_remote_hosts(cx);}@@ -4320,7 +4344,12 @@ impl Workbench {}return;}- spawn_remote_sync_thread(&self.store, self.bg_tx.clone(), names.clone());+ spawn_remote_sync_thread(+ &self.store,+ self.bg_tx.clone(),+ names.clone(),+ self.index_lock.clone(),+ );self.syncing_hosts = names;cx.notify();}@@ -4347,6 +4376,7 @@ impl Workbench {self.store.clone(),self.scan_events.clone(),false,+ self.index_lock.clone(),);}@@ -5241,7 +5271,9 @@ impl Workbench {let store = self.store.clone();let trash_keys = keys.clone();let count = keys.len();+ let lock = self.index_lock.clone();let task = cx.background_spawn(async move {+ let _lock = lock;terminal::trash_paths(&targets)?;store.remove_sessions(&trash_keys, true)});diff --git a/crates/wake/src/workbench/cleanup.rs b/crates/wake/src/workbench/cleanup.rsindex ad81e37..1c11a64 100644--- a/crates/wake/src/workbench/cleanup.rs+++ b/crates/wake/src/workbench/cleanup.rs@@ -856,8 +856,10 @@ impl Workbench {let cancel = self.cleanup.cancel.clone();let store = self.store.clone();let adapters = self.adapters.clone();+ let lock = self.index_lock.clone();let (tx, mut rx) = futures::channel::mpsc::unbounded();std::thread::spawn(move || {+ let _lock = lock;let mut batch = CleanupBatch::new(items, chrono::Utc::now().timestamp_millis());let result = cleanup::execute(&store, &adapters, &mut batch, &cancel, |n| {let _ = tx.unbounded_send(Ok(n));@@ -943,7 +945,9 @@ impl Workbench {self.cleanup.error = None;let store = self.store.clone();let adapters = self.adapters.clone();+ let lock = self.index_lock.clone();let task = cx.background_spawn(async move {+ let _lock = lock;let result = if verify_restored_files {cleanup::restore(&store, &adapters, &mut batch)} else {diff --git a/crates/wake/src/workbench/memory.rs b/crates/wake/src/workbench/memory.rsindex 1ec3e01..d2c3470 100644--- a/crates/wake/src/workbench/memory.rs+++ b/crates/wake/src/workbench/memory.rs@@ -149,10 +149,11 @@ impl Workbench {cx.notify();let adapters = self.adapters.clone();let store = self.store.clone();- let task =- cx.background_spawn(- async move { wake_core::scanner::run_memory_sync(&adapters, &store) },- );+ let lock = self.index_lock.clone();+ let task = cx.background_spawn(async move {+ let _lock = lock;+ wake_core::scanner::run_memory_sync(&adapters, &store)+ });cx.spawn(async move |this, cx| {task.await;this.update(cx, |this, cx| {diff --git a/docs/cli.md b/docs/cli.mdindex 31fd1f8..a8b54eb 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 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.+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. Two commands write to Wake's own index, and only while the app is closed: [`wake-cli index`](#index) builds one when there is none yet, and [`wake-cli refresh`](#refresh) brings an existing one up to date. Neither ever rebuilds an index — that stays the app's job.## Where it lives@@ -35,6 +35,7 @@ wake-cli show KEY [OPTIONS]wake-cli projects [OPTIONS]wake-cli setupwake-cli index+wake-cli refreshwake-cli --help | --version```@@ -188,10 +189,104 @@ wake-cli indexIt scans the agents' files and writes Wake's index, then tells you what it found. It onlydoes 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. In a terminal it shows progress while-it scans; when piped or run by an agent, stderr stays quiet until the summary.+nothing; to bring an existing index up to date use [`refresh`](#refresh). There is+deliberately no `--force`: rebuilding an index that exists is the app's job. If Wake is+running (and about to build the index itself), `index` steps aside the same way. In a+terminal it shows progress while it scans; when piped or run by an agent, stderr stays+quiet until the summary.++### `refresh`++Brings an existing index up to date, for the case where Wake is closed most of the time —+you use it through the MCP server or this CLI and only open the app to browse:++```bash+wake-cli refresh+```++It does the pass the app does on launch and on Refresh — an incremental scan that picks up+new and changed sessions, drops the deleted ones and re-reads the memory files — and then+says what the index holds. It does not sync remote hosts; those mirrors update when the app+runs. Like `index`, it shows progress in a terminal and stays quiet when piped. Point it at+Wake's own database — the path `wake-cli setup` prints — rather than a copy or an alias: it+refuses a file that is not a Wake index, and a path whose remote-host mirrors are not next to it.++It runs only while Wake is closed. If the app is running it says so and exits `0` without+touching anything: the app is already keeping the index current, and two writers with+possibly different environments would undo each other's work. The app and the CLI share one+lock on the index for this — Wake holds it while it runs, `refresh` and `index` hold it+while they work, and Wake waits for a running `refresh` to finish before it opens the index.++#### Keeping the index fresh without the app++Point a scheduler at the copy inside the app bundle, so it updates together with Wake.++**macOS** — save this as `~/Library/LaunchAgents/dev.corey.wake.refresh.plist`:++```xml+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>Label</key>+ <string>dev.corey.wake.refresh</string>+ <key>ProgramArguments</key>+ <array>+ <string>/Applications/Wake.app/Contents/MacOS/wake-cli</string>+ <string>refresh</string>+ </array>+ <key>StartInterval</key>+ <integer>600</integer>+ <key>RunAtLoad</key>+ <true/>+</dict>+</plist>+```++then load it once:++```bash+launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/dev.corey.wake.refresh.plist+```++**Linux** — a systemd user timer. `~/.config/systemd/user/wake-refresh.service`:++```ini+[Unit]+Description=Refresh Wake's session index++[Service]+Type=oneshot+ExecStart=/usr/bin/wake-cli refresh+```++and `~/.config/systemd/user/wake-refresh.timer`:++```ini+[Unit]+Description=Refresh Wake's session index every 10 minutes++[Timer]+OnBootSec=2min+OnUnitActiveSec=10min++[Install]+WantedBy=timers.target+```++then `systemctl --user enable --now wake-refresh.timer`. Use `%h/.local/bin/wake-cli` in+`ExecStart` for a tar.gz install.++**Windows** — Task Scheduler: `schtasks /Create /SC MINUTE /MO 10 /TN "Wake refresh" /TR "\"C:\path\to\Wake\wake-cli.exe\" refresh"`.++Two things to know:++- A scheduler does not see your shell's exports. That is also the environment the app sees+ when it starts from the Dock or a launcher, so both resolve the same data directories. If+ you set `CODEX_HOME`, `XDG_DATA_HOME` or `WAKE_HOME` for the app, set them for the+ scheduled job too — an index kept by two processes with different roots would flip-flop.+- Ten minutes is a sensible interval: a refresh with nothing new takes well under a second,+ and every reply already says how fresh the index is.## When@@ -227,7 +322,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. 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`.+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 or Wake is running; a build that starts and then fails exits `1`. `refresh` exits `0` when it updates the index and when it declines because Wake is running; it exits `2` when there is no index, when `--db` is not a Wake index, or when the path is not the one Wake opens the index at (its remote-host mirrors would not be found there); a scan 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.)@@ -235,14 +330,14 @@ 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. 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.+- 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` and `refresh` opens Wake's own index without write access too, and a test asserts that the query commands never change an index by a byte — nor does `index` when one already exists, nor `refresh` while Wake is running.- 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. 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.+- **Results look stale.** Keep Wake running, or schedule [`wake-cli refresh`](#refresh) for the times it is closed; the freshness line at the end of every reply says what the index covers. Copilot / OpenCode / Antigravity / Hermes / OpenClaw databases refresh when Wake launches, when you click Refresh, or on `wake-cli 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 alsodiff --git a/docs/mcp.md b/docs/mcp.mdindex 541cec1..7de3db6 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -115,7 +115,7 @@ Everything above happens locally; Wake itself does not change and the other agen## Keeping results fresh-Search and lists come from Wake's index. Wake keeps the index current while it is running (file watching for JSONL-based agents; SQLite-based agents such as Copilot and OpenCode refresh on launch and on manual refresh). Every reply ends with a line like+Search and lists come from Wake's index. Wake keeps the index current while it is running (file watching for JSONL-based agents; SQLite-based agents such as Copilot and OpenCode refresh on launch and on manual refresh); while the app is closed, a scheduled `wake-cli refresh` does the same pass (see [docs/cli.md](cli.md#refresh)). Every reply ends with a line like```Index covers activity up to 2026-09-08 09:41:37 (local time); Wake keeps it fresh while it is running.@@ -277,6 +277,6 @@ wake-mcp --version## Troubleshooting- **The client reports the server failed to start.** Run the binary in a terminal: `no Wake index at … — launch Wake once to build it` means Wake has never run on this machine (or `--db` points to the wrong place). `… is empty or from an older version` means the index predates this Wake version; launching Wake once upgrades it.-- **Results look stale.** Keep Wake running; the freshness line at the end of every reply tells you what the index covers. Copilot / OpenCode / Antigravity / Hermes / OpenClaw databases refresh when Wake launches or when you click Refresh.+- **Results look stale.** Keep Wake running, or schedule `wake-cli refresh` for the times it is closed ([docs/cli.md](cli.md#refresh)); the freshness line at the end of every reply tells you what the index covers. Copilot / OpenCode / Antigravity / Hermes / OpenClaw databases refresh when Wake launches or when you click Refresh.- **A project path is not matched.** Pass the absolute path of the repository, or its name. `wake_list_projects` shows the paths Wake knows.- **macOS refuses to run it ("cannot be opened because the developer cannot be verified").** Wake is signed but not notarized, and a client launching `wake-mcp` hits the same first-run gate as opening Wake itself. Clear the quarantine flag for the whole bundle once: `xattr -dr com.apple.quarantine /Applications/Wake.app`, then restart the client.diff --git a/skills/wake/SKILL.md b/skills/wake/SKILL.mdindex 5076e5f..335059b 100644--- a/skills/wake/SKILL.md+++ b/skills/wake/SKILL.md@@ -32,6 +32,10 @@ Two things can be missing, and they need different answers:installed but has never run. Run `wake-cli index` once; it builds the index in afew seconds without opening the app, then retry your query.+If the freshness line at the end of a listing is well behind and Wake is not running,+`wake-cli refresh` updates the index in a few seconds; it does nothing while the app is+open. Retry the query afterwards.+## CommandsAlways scope to the current repository with `--project "$PWD"` unless the user clearly